code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
def get_injured_sharks():
"""
>>> from ibeis.scripts.getshark import * # NOQA
"""
import requests
url = 'http://www.whaleshark.org/getKeywordImages.jsp'
resp = requests.get(url)
assert resp.status_code == 200
keywords = resp.json()['keywords']
key_list = ut.take_column(keywords, 'indexName')
key_to_nice = {k['indexName']: k['readableName'] for k in keywords}
injury_patterns = [
'injury', 'net', 'hook', 'trunc', 'damage', 'scar', 'nicks', 'bite',
]
injury_keys = [key for key in key_list if any([pat in key for pat in injury_patterns])]
noninjury_keys = ut.setdiff(key_list, injury_keys)
injury_nice = ut.lmap(lambda k: key_to_nice[k], injury_keys) # NOQA
noninjury_nice = ut.lmap(lambda k: key_to_nice[k], noninjury_keys) # NOQA
key_list = injury_keys
keyed_images = {}
for key in ut.ProgIter(key_list, lbl='reading index', bs=True):
key_url = url + '?indexName={indexName}'.format(indexName=key)
key_resp = requests.get(key_url)
assert key_resp.status_code == 200
key_imgs = key_resp.json()['images']
keyed_images[key] = key_imgs
key_hist = {key: len(imgs) for key, imgs in keyed_images.items()}
key_hist = ut.sort_dict(key_hist, ut.identity)
print(ut.repr3(key_hist))
nice_key_hist = ut.map_dict_keys(lambda k: key_to_nice[k], key_hist)
nice_key_hist = ut.sort_dict(nice_key_hist, ut.identity)
print(ut.repr3(nice_key_hist))
key_to_urls = {key: ut.take_column(vals, 'url') for key, vals in keyed_images.items()}
overlaps = {}
import itertools
overlap_img_list = []
for k1, k2 in itertools.combinations(key_to_urls.keys(), 2):
overlap_imgs = ut.isect(key_to_urls[k1], key_to_urls[k2])
num_overlap = len(overlap_imgs)
overlaps[(k1, k2)] = num_overlap
overlaps[(k1, k1)] = len(key_to_urls[k1])
if num_overlap > 0:
#print('[%s][%s], overlap=%r' % (k1, k2, num_overlap))
overlap_img_list.extend(overlap_imgs)
all_img_urls = list(set(ut.flatten(key_to_urls.values())))
num_all = len(all_img_urls) # NOQA
print('num_all = %r' % (num_all,))
# Determine super-categories
categories = ['nicks', 'scar', 'trunc']
# Force these keys into these categories
key_to_cat = {'scarbite': 'other_injury'}
cat_to_keys = ut.ddict(list)
for key in key_to_urls.keys():
flag = 1
if key in key_to_cat:
cat = key_to_cat[key]
cat_to_keys[cat].append(key)
continue
for cat in categories:
if cat in key:
cat_to_keys[cat].append(key)
flag = 0
if flag:
cat = 'other_injury'
cat_to_keys[cat].append(key)
cat_urls = ut.ddict(list)
for cat, keys in cat_to_keys.items():
for key in keys:
cat_urls[cat].extend(key_to_urls[key])
cat_hist = {}
for cat in list(cat_urls.keys()):
cat_urls[cat] = list(set(cat_urls[cat]))
cat_hist[cat] = len(cat_urls[cat])
print(ut.repr3(cat_to_keys))
print(ut.repr3(cat_hist))
key_to_cat = dict([(val, key) for key, vals in cat_to_keys.items() for val in vals])
#ingestset = {
# '__class__': 'ImageSet',
# 'images': ut.ddict(dict)
#}
#for key, key_imgs in keyed_images.items():
# for imgdict in key_imgs:
# url = imgdict['url']
# encid = imgdict['correspondingEncounterNumber']
# # Make structure
# encdict = encounters[encid]
# encdict['__class__'] = 'Encounter'
# imgdict = ut.delete_keys(imgdict.copy(), ['correspondingEncounterNumber'])
# imgdict['__class__'] = 'Image'
# cat = key_to_cat[key]
# annotdict = {'relative_bbox': [.01, .01, .98, .98], 'tags': [cat, key]}
# annotdict['__class__'] = 'Annotation'
# # Ensure structures exist
# encdict['images'] = encdict.get('images', [])
# imgdict['annots'] = imgdict.get('annots', [])
# # Add an image to this encounter
# encdict['images'].append(imgdict)
# # Add an annotation to this image
# imgdict['annots'].append(annotdict)
##http://springbreak.wildbook.org/rest/org.ecocean.Encounter/1111
#get_enc_url = 'http://www.whaleshark.org/rest/org.ecocean.Encounter/%s' % (encid,)
#resp = requests.get(get_enc_url)
#print(ut.repr3(encdict))
#print(ut.repr3(encounters))
# Download the files to the local disk
#fpath_list =
all_urls = ut.unique(ut.take_column(
ut.flatten(
ut.dict_subset(keyed_images, ut.flatten(cat_to_keys.values())).values()
), 'url'))
dldir = ut.truepath('~/tmpsharks')
from os.path import commonprefix, basename # NOQA
prefix = commonprefix(all_urls)
suffix_list = [url_[len(prefix):] for url_ in all_urls]
fname_list = [suffix.replace('/', '--') for suffix in suffix_list]
fpath_list = []
for url, fname in ut.ProgIter(zip(all_urls, fname_list), lbl='downloading imgs', freq=1):
fpath = ut.grab_file_url(url, download_dir=dldir, fname=fname, verbose=False)
fpath_list.append(fpath)
# Make sure we keep orig info
#url_to_keys = ut.ddict(list)
url_to_info = ut.ddict(dict)
for key, imgdict_list in keyed_images.items():
for imgdict in imgdict_list:
url = imgdict['url']
info = url_to_info[url]
for k, v in imgdict.items():
info[k] = info.get(k, [])
info[k].append(v)
info['keys'] = info.get('keys', [])
info['keys'].append(key)
#url_to_keys[url].append(key)
info_list = ut.take(url_to_info, all_urls)
for info in info_list:
if len(set(info['correspondingEncounterNumber'])) > 1:
assert False, 'url with two different encounter nums'
# Combine duplicate tags
hashid_list = [ut.get_file_uuid(fpath_, stride=8) for fpath_ in ut.ProgIter(fpath_list, bs=True)]
groupxs = ut.group_indices(hashid_list)[1]
# Group properties by duplicate images
#groupxs = [g for g in groupxs if len(g) > 1]
fpath_list_ = ut.take_column(ut.apply_grouping(fpath_list, groupxs), 0)
url_list_ = ut.take_column(ut.apply_grouping(all_urls, groupxs), 0)
info_list_ = [ut.map_dict_vals(ut.flatten, ut.dict_accum(*info_))
for info_ in ut.apply_grouping(info_list, groupxs)]
encid_list_ = [ut.unique(info_['correspondingEncounterNumber'])[0]
for info_ in info_list_]
keys_list_ = [ut.unique(info_['keys']) for info_ in info_list_]
cats_list_ = [ut.unique(ut.take(key_to_cat, keys)) for keys in keys_list_]
clist = ut.ColumnLists({
'gpath': fpath_list_,
'url': url_list_,
'encid': encid_list_,
'key': keys_list_,
'cat': cats_list_,
})
#for info_ in ut.apply_grouping(info_list, groupxs):
# info = ut.dict_accum(*info_)
# info = ut.map_dict_vals(ut.flatten, info)
# x = ut.unique(ut.flatten(ut.dict_accum(*info_)['correspondingEncounterNumber']))
# if len(x) > 1:
# info = info.copy()
# del info['keys']
# print(ut.repr3(info))
flags = ut.lmap(ut.fpath_has_imgext, clist['gpath'])
clist = clist.compress(flags)
import ibeis
ibs = ibeis.opendb('WS_Injury', allow_newdir=True)
gid_list = ibs.add_images(clist['gpath'])
clist['gid'] = gid_list
failed_flags = ut.flag_None_items(clist['gid'])
print('# failed %s' % (sum(failed_flags)),)
passed_flags = ut.not_list(failed_flags)
clist = clist.compress(passed_flags)
ut.assert_all_not_None(clist['gid'])
#ibs.get_image_uris_original(clist['gid'])
ibs.set_image_uris_original(clist['gid'], clist['url'], overwrite=True)
#ut.zipflat(clist['cat'], clist['key'])
if False:
# Can run detection instead
clist['tags'] = ut.zipflat(clist['cat'])
aid_list = ibs.use_images_as_annotations(clist['gid'], adjust_percent=0.01,
tags_list=clist['tags'])
aid_list
import plottool as pt
from ibeis import core_annots
pt.qt4ensure()
#annots = ibs.annots()
#aids = [1, 2]
#ibs.depc_annot.get('hog', aids , 'hog')
#ibs.depc_annot.get('chip', aids, 'img')
for aid in ut.InteractiveIter(ibs.get_valid_aids()):
hogs = ibs.depc_annot.d.get_hog_hog([aid])
chips = ibs.depc_annot.d.get_chips_img([aid])
chip = chips[0]
hogimg = core_annots.make_hog_block_image(hogs[0])
pt.clf()
pt.imshow(hogimg, pnum=(1, 2, 1))
pt.imshow(chip, pnum=(1, 2, 2))
fig = pt.gcf()
fig.show()
fig.canvas.draw()
#print(len(groupxs))
#if False:
#groupxs = ut.find_duplicate_items(ut.lmap(basename, suffix_list)).values()
#print(ut.repr3(ut.apply_grouping(all_urls, groupxs)))
# # FIX
# for fpath, fname in zip(fpath_list, fname_list):
# if ut.checkpath(fpath):
# ut.move(fpath, join(dirname(fpath), fname))
# print('fpath = %r' % (fpath,))
#import ibeis
#from ibeis.dbio import ingest_dataset
#dbdir = ibeis.sysres.lookup_dbdir('WS_ALL')
#self = ingest_dataset.Ingestable2(dbdir)
if False:
# Show overlap matrix
import plottool as pt
import pandas as pd
import numpy as np
dict_ = overlaps
s = pd.Series(dict_, index=pd.MultiIndex.from_tuples(overlaps))
df = s.unstack()
lhs, rhs = df.align(df.T)
df = lhs.add(rhs, fill_value=0).fillna(0)
label_texts = df.columns.values
def label_ticks(label_texts):
import plottool as pt
truncated_labels = [repr(lbl[0:100]) for lbl in label_texts]
ax = pt.gca()
ax.set_xticks(list(range(len(label_texts))))
ax.set_xticklabels(truncated_labels)
[lbl.set_rotation(-55) for lbl in ax.get_xticklabels()]
[lbl.set_horizontalalignment('left') for lbl in ax.get_xticklabels()]
#xgrid, ygrid = np.meshgrid(range(len(label_texts)), range(len(label_texts)))
#pt.plot_surface3d(xgrid, ygrid, disjoint_mat)
ax.set_yticks(list(range(len(label_texts))))
ax.set_yticklabels(truncated_labels)
[lbl.set_horizontalalignment('right') for lbl in ax.get_yticklabels()]
[lbl.set_verticalalignment('center') for lbl in ax.get_yticklabels()]
#[lbl.set_rotation(20) for lbl in ax.get_yticklabels()]
#df = df.sort(axis=0)
#df = df.sort(axis=1)
sortx = np.argsort(df.sum(axis=1).values)[::-1]
df = df.take(sortx, axis=0)
df = df.take(sortx, axis=1)
fig = pt.figure(fnum=1)
fig.clf()
mat = df.values.astype(np.int32)
mat[np.diag_indices(len(mat))] = 0
vmax = mat[(1 - np.eye(len(mat))).astype(np.bool)].max()
import matplotlib.colors
norm = matplotlib.colors.Normalize(vmin=0, vmax=vmax, clip=True)
pt.plt.imshow(mat, cmap='hot', norm=norm, interpolation='none')
pt.plt.colorbar()
pt.plt.grid('off')
label_ticks(label_texts)
fig.tight_layout()
#overlap_df = pd.DataFrame.from_dict(overlap_img_list)
class TmpImage(ut.NiceRepr):
pass
from skimage.feature import hog
from skimage import data, color, exposure
import plottool as pt
image2 = color.rgb2gray(data.astronaut()) # NOQA
fpath = './GOPR1120.JPG'
import vtool as vt
for fpath in [fpath]:
"""
http://scikit-image.org/docs/dev/auto_examples/plot_hog.html
"""
image = vt.imread(fpath, grayscale=True)
image = pt.color_funcs.to_base01(image)
fig = pt.figure(fnum=2)
fd, hog_image = hog(image, orientations=8, pixels_per_cell=(16, 16),
cells_per_block=(1, 1), visualise=True)
fig, (ax1, ax2) = pt.plt.subplots(1, 2, figsize=(8, 4), sharex=True, sharey=True)
ax1.axis('off')
ax1.imshow(image, cmap=pt.plt.cm.gray)
ax1.set_title('Input image')
ax1.set_adjustable('box-forced')
# Rescale histogram for better display
hog_image_rescaled = exposure.rescale_intensity(hog_image, in_range=(0, 0.02))
ax2.axis('off')
ax2.imshow(hog_image_rescaled, cmap=pt.plt.cm.gray)
ax2.set_title('Histogram of Oriented Gradients')
ax1.set_adjustable('box-forced')
pt.plt.show()
#for
def detect_sharks(ibs, gids):
#import ibeis
#ibs = ibeis.opendb('WS_ALL')
config = {
'algo' : 'yolo',
'sensitivity' : 0.2,
'config_filepath' : ut.truepath('~/work/WS_ALL/localizer_backup/detect.yolo.2.cfg'),
'weight_filepath' : ut.truepath('~/work/WS_ALL/localizer_backup/detect.yolo.2.39000.weights'),
'class_filepath' : ut.truepath('~/work/WS_ALL/localizer_backup/detect.yolo.2.cfg.classes'),
}
depc = ibs.depc_image
#imgsets = ibs.imagesets(text='Injured Sharks')
#images = ibs.images(imgsets.gids[0])
images = ibs.images(gids)
images = images.compress([ext not in ['.gif'] for ext in images.exts])
gid_list = images.gids
# result is a tuple:
# (score, bbox_list, theta_list, conf_list, class_list)
results_list = depc.get_property('localizations', gid_list, None, config=config)
results_list2 = []
multi_gids = []
failed_gids = []
#ibs.set_image_imagesettext(failed_gids, ['Fixme'] * len(failed_gids))
ibs.set_image_imagesettext(multi_gids, ['Fixme2'] * len(multi_gids))
failed_gids
for gid, res in zip(gid_list, results_list):
score, bbox_list, theta_list, conf_list, class_list = res
if len(bbox_list) == 0:
failed_gids.append(gid)
elif len(bbox_list) == 1:
results_list2.append((gid, bbox_list, theta_list))
elif len(bbox_list) > 1:
multi_gids.append(gid)
idx = conf_list.argmax()
res2 = (gid, bbox_list[idx:idx + 1], theta_list[idx:idx + 1])
results_list2.append(res2)
ut.dict_hist(([t[1].shape[0] for t in results_list]))
localized_imgs = ibs.images(ut.take_column(results_list2, 0))
assert all([len(a) == 1 for a in localized_imgs.aids])
old_annots = ibs.annots(ut.flatten(localized_imgs.aids))
#old_tags = old_annots.case_tags
# Override old bboxes
import numpy as np
bboxes = np.array(ut.take_column(results_list2, 1))[:, 0, :]
ibs.set_annot_bboxes(old_annots.aids, bboxes)
if False:
import plottool as pt
pt.qt4ensure()
inter = pt.MultiImageInteraction(
ibs.get_image_paths(ut.take_column(results_list2, 0)),
bboxes_list=ut.take_column(results_list2, 1)
)
inter.dump_to_disk('shark_loc', num=50, prefix='shark_loc')
inter.start()
inter = pt.MultiImageInteraction(ibs.get_image_paths(failed_gids))
inter.start()
inter = pt.MultiImageInteraction(ibs.get_image_paths(multi_gids))
inter.start()
def train_part_detector():
"""
Problem:
healthy sharks usually have a mostly whole body shot
injured sharks usually have a close up shot.
This distribution of images is likely what the injur-shark net is picking up on.
The goal is to train a detector that looks for things that look
like the distribution of injured sharks.
We will run this on healthy sharks to find the parts of
"""
import ibeis
ibs = ibeis.opendb('WS_ALL')
imgset = ibs.imagesets(text='Injured Sharks')
injured_annots = imgset.annots[0] # NOQA
#config = {
# 'dim_size': (224, 224),
# 'resize_dim': 'wh'
#}
from pydarknet import Darknet_YOLO_Detector
data_path = ibs.export_to_xml()
output_path = join(ibs.get_cachedir(), 'training', 'localizer')
ut.ensuredir(output_path)
dark = Darknet_YOLO_Detector()
results = dark.train(data_path, output_path)
del dark
localizer_weight_path, localizer_config_path, localizer_class_path = results
classifier_model_path = ibs.classifier_train()
labeler_model_path = ibs.labeler_train()
output_path = join(ibs.get_cachedir(), 'training', 'detector')
ut.ensuredir(output_path)
ut.copy(localizer_weight_path, join(output_path, 'localizer.weights'))
ut.copy(localizer_config_path, join(output_path, 'localizer.config'))
ut.copy(localizer_class_path, join(output_path, 'localizer.classes'))
ut.copy(classifier_model_path, join(output_path, 'classifier.npy'))
ut.copy(labeler_model_path, join(output_path, 'labeler.npy'))
# ibs.detector_train()
def purge_ensure_one_annot_per_images(ibs):
"""
pip install Pipe
"""
# Purge all but one annotation
images = ibs.images()
#images.aids
groups = images._annot_groups
import numpy as np
# Take all but the largest annotations per images
large_masks = [ut.index_to_boolmask([np.argmax(x)], len(x)) for x in groups.bbox_area]
small_masks = ut.lmap(ut.not_list, large_masks)
# Remove all but the largets annotation
small_aids = ut.zipcompress(groups.aid, small_masks)
small_aids = ut.flatten(small_aids)
# Fix any empty images
images = ibs.images()
empty_images = ut.where(np.array(images.num_annotations) == 0)
print('empty_images = %r' % (empty_images,))
#list(map(basename, map(dirname, images.uris_original)))
def VecPipe(func):
import pipe
@pipe.Pipe
def wrapped(sequence):
return map(func, sequence)
#return (None if item is None else func(item) for item in sequence)
return wrapped
name_list = list(images.uris_original | VecPipe(dirname) | VecPipe(basename))
aids_list = images.aids
ut.assert_all_eq(list(aids_list | VecPipe(len)))
annots = ibs.annots(ut.flatten(aids_list))
annots.names = name_list
def shark_misc():
import ibeis
ibs = ibeis.opendb('WS_ALL')
aid_list = ibs.get_valid_aids()
flag_list = ibs.get_annot_been_adjusted(aid_list)
adjusted_aids = ut.compress(aid_list, flag_list)
return adjusted_aids
#if False:
# # TRY TO FIGURE OUT WHY URLS ARE MISSING IN STEP 1
# encounter_to_parsed1 = parsed1.group_items('encounter')
# encounter_to_parsed2 = parsed2.group_items('encounter')
# url_to_parsed1 = parsed1.group_items('img_url')
# url_to_parsed2 = parsed2.group_items('img_url')
# def set_overlap(set1, set2):
# set1 = set(set1)
# set2 = set(set2)
# return ut.odict([
# ('s1', len(set1)),
# ('s2', len(set2)),
# ('isect', len(set1.intersection(set2))),
# ('union', len(set1.union(set2))),
# ('s1 - s2', len(set1.difference(set2))),
# ('s2 - s1', len(set2.difference(set1))),
# ])
# print('encounter overlap: ' + ut.repr3(set_overlap(encounter_to_parsed1, encounter_to_parsed2)))
# print('url overlap: ' + ut.repr3(set_overlap(url_to_parsed1, url_to_parsed2)))
# url1 = list(url_to_parsed1.keys())
# url2 = list(url_to_parsed2.keys())
# # remove common prefixes
# from os.path import commonprefix, basename # NOQA
# cp1 = commonprefix(url1)
# cp2 = commonprefix(url2)
# #suffix1 = sorted([u[len(cp1):].lower() for u in url1])
# #suffix2 = sorted([u[len(cp2):].lower() for u in url2])
# suffix1 = sorted([u[len(cp1):] for u in url1])
# suffix2 = sorted([u[len(cp2):] for u in url2])
# print('suffix overlap: ' + ut.repr3(set_overlap(suffix1, suffix2)))
# set1 = set(suffix1)
# set2 = set(suffix2)
# only1 = list(set1 - set1.intersection(set2))
# only2 = list(set2 - set1.intersection(set2))
# import numpy as np
# for suf in ut.ProgIter(only2, bs=True):
# dist = np.array(ut.edit_distance(suf, only1))
# idx = ut.argsort(dist)[0:3]
# if dist[idx][0] < 3:
# close = ut.take(only1, idx)
# print('---')
# print('suf = %r' % (join(cp2, suf),))
# print('close = %s' % (ut.repr3([join(cp1, c) for c in close]),))
# print('---')
# break
# # Associate keywords with original images
# #lower_urls = [x.lower() for x in parsed['img_url']]
# url_to_idx = ut.make_index_lookup(parsed1['img_url'])
# parsed1['keywords'] = [[] for _ in range(len(parsed1))]
# for url, keys in url_to_keys.items():
# # hack because urls are note in the same format
# url = url.replace('wildbook_data_dir', 'shepherd_data_dir')
# url = url.lower()
# if url in url_to_idx:
# idx = url_to_idx[url]
# parsed1['keywords'][idx].extend(keys)
#healthy_annots = ibs.annots(ibs.imagesets(text='Non-Injured Sharks').aids[0])
#ibs.set_annot_prop('healthy', healthy_annots.aids, [True] * len(healthy_annots))
#['healthy' in t and len(t) > 0 for t in single_annots.case_tags]
#healthy_tags = []
#ut.find_duplicate_items(cur_img_uuids)
#ut.find_duplicate_items(new_img_uuids)
#cur_uuids = set(cur_img_uuids)
#new_uuids = set(new_img_uuids)
#both_uuids = new_uuids.intersection(cur_uuids)
#only_cur = cur_uuids - both_uuids
#only_new = new_uuids - both_uuids
#print('len(cur_uuids) = %r' % (len(cur_uuids)))
#print('len(new_uuids) = %r' % (len(new_uuids)))
#print('len(both_uuids) = %r' % (len(both_uuids)))
#print('len(only_cur) = %r' % (len(only_cur)))
#print('len(only_new) = %r' % (len(only_new)))
# Ensure that data in both sets are syncronized
#images_both = []
#if False:
# print('Removing small images')
# import numpy as np
# import vtool as vt
# imgsize_list = np.array([vt.open_image_size(gpath) for gpath in parsed['new_fpath']])
# sqrt_area_list = np.sqrt(np.prod(imgsize_list, axis=1))
# areq_flags_list = sqrt_area_list >= 750
# parsed = parsed.compress(areq_flags_list)
| SU-ECE-17-7/ibeis | ibeis/scripts/getshark_old.py | Python | apache-2.0 | 22,458 |
declare const monaco: any;
export function replay(editor: any) {
const keys = [];
editor.addCommand(monaco.KeyCode.F9, () => {
console.log('starting recording');
editor.onKeyDown(key => {
keys.push({
timestamp: new Date(),
key
});
});
editor.trigger('keyboard', 'type', { text: 'test' });
editor.trigger('keyboard', monaco.editor.Handler.CursorLeft);
});
editor.addCommand(monaco.KeyCode.F8, () => {
console.log(keys);
});
}
| nycJSorg/angular-presentation | libs/code-demos/src/lib/shared/monaco-replay.ts | TypeScript | apache-2.0 | 488 |
package com.geekdos.app;
import com.geekdos.midelwar.interfaces.GestionDesNotesInterface;
import com.geekdos.model.*;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by theXuser on 11/12/2016.
*/
public class App {
public static void main(String[] args){
System.out.println("-----------------------------------------------------");
System.out.println("Bienvenue dans l'application Gestion des Notes Client");
System.out.println("-----------------------------------------------------");
Etudiant oussama = new Etudiant();
Etudiant dina = new Etudiant();
Etudiant ouail = new Etudiant();
Etudiant ayoub = new Etudiant();
Etudiant yassin = new Etudiant();
Etudiant halima = new Etudiant();
oussama.setNom("KHACHIAI");oussama.setPrenom("Oussama");oussama.setCne("1128764379");oussama.setAge(25);
dina.setNom("BEN HALIMA");dina.setPrenom("Dina");dina.setCne("1228764379");dina.setAge(21);
ouail.setNom("KERDAD");ouail.setPrenom("Ouail");ouail.setCne("1028764379");ouail.setAge(25);
ayoub.setNom("BOUCHAREB");ayoub.setPrenom("Ayoub");ayoub.setCne("1228764380");ayoub.setAge(25);
yassin.setNom("AKESBI");yassin.setPrenom("Yassin");yassin.setCne("1228764385");yassin.setAge(23);
halima.setNom("BOUJRA");halima.setPrenom("Halima");halima.setCne("1228764386");halima.setAge(23);
Note note1 = new Note();Note note2 = new Note();
Note note3 = new Note();Note note4 = new Note();
Note note5 = new Note();Note note6 = new Note();
Note note7 = new Note();Note note8 = new Note();
Note note9 = new Note();Note note10 = new Note();
Note note11 = new Note();Note note12 = new Note();
Note note13 = new Note();Note note14 = new Note();
note1.setName("M1");note2.setName("M2");
note3.setName("M3");note4.setName("M4");
note5.setName("M5");note6.setName("M6");
note7.setName("M7");note8.setName("M8");
note9.setName("M9");note10.setName("M10");
note11.setName("M11");note12.setName("M12");
note13.setName("M13");note14.setName("M14");
note1.setValue(18);note2.setValue(18);
note3.setValue(17);note4.setValue(17);
note5.setValue(15);note6.setValue(15);
note7.setValue(15);note8.setValue(10);
note9.setValue(10);note10.setValue(10);
note11.setValue(8);note12.setValue(5);
note13.setValue(12);note14.setValue(7);
List<Note> oussamaNotes = new ArrayList<Note>();
List<Note> dinaNotes = new ArrayList<Note>();
List<Note> ouailNotes = new ArrayList<Note>();
List<Note> ayoubNotes = new ArrayList<Note>();
oussamaNotes.add(note1);
oussamaNotes.add(note2);
dinaNotes.add(note3);
dinaNotes.add(note4);
ouailNotes.add(note5);
ouailNotes.add(note6);
ayoubNotes.add(note7);
ayoubNotes.add(note8);
oussama.setNotes(oussamaNotes);
dina.setNotes(dinaNotes);
ouail.setNotes(ouailNotes);
ayoub.setNotes(ayoubNotes);
List<Etudiant> etudiants = new ArrayList<>();
etudiants.add(oussama);
etudiants.add(dina);
etudiants.add(ouail);
etudiants.add(ayoub);
try {
Remote gestionDesNotes = Naming.lookup("rmi://169.254.12.27/GestionDesNotes");
((GestionDesNotesInterface) gestionDesNotes).setLes_etudiants(etudiants);
String messsageOussama = "La moyenne des note de : "+ oussama.getNom() +" "+ oussama.getPrenom();
messsageOussama += " Qui porte le CNE "+oussama.getCne();
messsageOussama += " est : "+ ((GestionDesNotesInterface) gestionDesNotes).getNote("KHACHIAI");
String messsageOuail = "La moyenne des note de : "+ ouail.getNom() +" "+ ouail.getPrenom();
messsageOuail += " Qui porte le CNE "+ouail.getCne();
messsageOuail += " est : "+ ((GestionDesNotesInterface) gestionDesNotes).getNote("KERDAD");
String messsageDina = "La moyenne des note de : "+ dina.getNom() +" "+ dina.getPrenom();
messsageDina += " Qui porte le CNE "+dina.getCne();
messsageDina += " est : "+ ((GestionDesNotesInterface) gestionDesNotes).getNote("BEN HALIMA");
String messsageAyoub = "La moyenne des note de : "+ ayoub.getNom() +" "+ ayoub.getPrenom();
messsageAyoub += " Qui porte le CNE "+ayoub.getCne();
messsageAyoub += " est : "+ ((GestionDesNotesInterface) gestionDesNotes).getNote("BOUCHAREB");
/**
* Pour affichier la liste des étudiants qui sont enregistrer avec leur note du moyenne
*/
System.out.println("-----------------------------------------------------");
System.out.println("La liste des étudiants enregistrer");
System.out.println("-----------------------------------------------------");
System.out.println(messsageOussama);
System.out.println(messsageDina);
System.out.println(messsageOuail);
System.out.println(messsageAyoub);
System.out.println("-----------------------------------------------------");
System.out.println("L'etudiant magoron est:");
System.out.println("-----------------------------------------------------");
String nomMagoron = ((GestionDesNotesInterface) gestionDesNotes).getMajoran(etudiants).getNom();
System.out.println("L'etudiant Majoran est : "+nomMagoron);
/**-------------------------------
* Pour affichier la liste des étudiants qu'en validé les module avec un moyenne sup a 12
*/
System.out.println("-----------------------------------------------------");
System.out.println("La liste des étudiant qu'en valider les modules");
System.out.println("-----------------------------------------------------");
for (Etudiant etudiant: ((GestionDesNotesInterface) gestionDesNotes).getvalidation()) {
String message = "L'étudiant : "+etudiant.getNom();
message += " à validé les modules ";
for (int i = 0; i < etudiant.getNotes().size() ;i++) {
message += "<<" + etudiant.getNotes().get(i).getName();
message += ", " + etudiant.getNotes().get(i).getValue()+">> ";
}
System.out.println(message);
System.out.println("-----------------------------------------------------");
}
/**
* Pour affichier la liste des étudiants qu'en un ratrapage dans des module avec un 12 < moyenne >= 7
*/
System.out.println("-----------------------------------------------------");
System.out.println("La liste des étudiant qu'en ratrapage");
System.out.println("-----------------------------------------------------");
for (Etudiant etudiant: ((GestionDesNotesInterface) gestionDesNotes).getRat()) {
String message = "L'étudiant : "+etudiant.getNom();
message += " à un ratrapage dans les modules ";
for (int i = 0; i < etudiant.getNotes().size() ;i++) {
message += "<<" + etudiant.getNotes().get(i).getName();
message += ", " + etudiant.getNotes().get(i).getValue()+">> ";
}
System.out.println(message);
System.out.println("-----------------------------------------------------");
}
/**
* Pour affichier la liste des étudiants qu'en un non validé dans des module avec un moyenne < 7
*/
System.out.println("-----------------------------------------------------");
System.out.println("La liste des étudiant qu'en non validé");
System.out.println("-----------------------------------------------------");
for (Etudiant etudiant: ((GestionDesNotesInterface) gestionDesNotes).getNonValidation()) {
String message = "L'étudiant : "+etudiant.getNom();
message += " à eu une non validé dans les modules ";
for (int i = 0; i < etudiant.getNotes().size() ;i++) {
message += "<<" + etudiant.getNotes().get(i).getName();
message += ", " + etudiant.getNotes().get(i).getValue()+">> ";
}
System.out.println(message);
System.out.println("-----------------------------------------------------");
}
} catch (NotBoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
| geekdos/Personal_Labs | MidelwarLab/GestionDesNotes/src/com/geekdos/app/App.java | Java | apache-2.0 | 9,128 |
/// Refly License
///
/// Copyright (c) 2004 Jonathan de Halleux, http://www.dotnetwiki.org
///
/// This software is provided 'as-is', without any express or implied warranty.
/// In no event will the authors be held liable for any damages arising from
/// the use of this software.
///
/// Permission is granted to anyone to use this software for any purpose,
/// including commercial applications, and to alter it and redistribute it
/// freely, subject to the following restrictions:
///
/// 1. The origin of this software must not be misrepresented;
/// you must not claim that you wrote the original software.
/// If you use this software in a product, an acknowledgment in the product
/// documentation would be appreciated but is not required.
///
/// 2. Altered source versions must be plainly marked as such,
/// and must not be misrepresented as being the original software.
///
///3. This notice may not be removed or altered from any source distribution.
using System;
using System.CodeDom;
namespace Refly.CodeDom
{
using Refly.CodeDom.Expressions;
/// <summary>
/// A field declaration
/// </summary>
public class FieldDeclaration : MemberDeclaration
{
private ITypeDeclaration type;
private Expression initExpression = null;
internal FieldDeclaration(string name, Declaration declaringType, ITypeDeclaration type)
:base(name,declaringType)
{
if (type==null)
throw new ArgumentNullException("type");
this.type = type;
}
public ITypeDeclaration Type
{
get
{
return this.type;
}
}
public Expression InitExpression
{
get
{
return this.initExpression;
}
set
{
this.initExpression = value;
}
}
public override CodeTypeMember ToCodeDom()
{
CodeMemberField f = new CodeMemberField(
this.Type.TypeReference,
this.Name
);
if (this.initExpression!=null)
{
f.InitExpression = this.initExpression.ToCodeDom();
}
// comments
base.ToCodeDom(f);
return f;
}
}
}
| Gallio/mbunit-v2 | src/refly/Refly/CodeDom/FieldDeclaration.cs | C# | apache-2.0 | 2,091 |
<?php
class Graphite_Relation extends Graphite_Resource
{
function nodeType() { return "#relation"; }
}
| lyndonnixon/annotationtool | libraries/graphite/Graphite/Relation.php | PHP | apache-2.0 | 106 |
/*
* Copyright 2018 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.drools.scenariosimulation.backend.runner;
import java.util.List;
import org.drools.scenariosimulation.api.model.ScenarioWithIndex;
import org.drools.scenariosimulation.api.model.Simulation;
import org.drools.scenariosimulation.api.model.SimulationDescriptor;
import org.drools.scenariosimulation.backend.expression.DMNFeelExpressionEvaluator;
import org.kie.api.runtime.KieContainer;
public class DMNScenarioRunner extends AbstractScenarioRunner {
public DMNScenarioRunner(KieContainer kieContainer, Simulation simulation) {
this(kieContainer, simulation, null);
}
public DMNScenarioRunner(KieContainer kieContainer, Simulation simulation, String fileName) {
this(kieContainer, simulation.getSimulationDescriptor(), simulation.getScenarioWithIndex(), fileName);
}
public DMNScenarioRunner(KieContainer kieContainer, SimulationDescriptor simulationDescriptor, List<ScenarioWithIndex> scenarios) {
this(kieContainer, simulationDescriptor, scenarios, null);
}
public DMNScenarioRunner(KieContainer kieContainer, SimulationDescriptor simulationDescriptor, List<ScenarioWithIndex> scenarios, String fileName) {
super(kieContainer, simulationDescriptor, scenarios, fileName, DMNFeelExpressionEvaluator::new);
}
@Override
protected AbstractRunnerHelper newRunnerHelper() {
return new DMNScenarioRunnerHelper();
}
}
| etirelli/drools | drools-scenario-simulation/drools-scenario-simulation-backend/src/main/java/org/drools/scenariosimulation/backend/runner/DMNScenarioRunner.java | Java | apache-2.0 | 2,033 |
// Copyright 2017 The Nomulus Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package google.registry.testing;
import static com.google.common.base.Preconditions.checkState;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.Nullable;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
/**
* JUnit extension for overriding {@code private static} fields during a test.
*
* <p>This extension uses reflection to change the value of a field while your test is running and
* then restore it to its original value after it's done (even if the test fails). The injection
* will work even if the field is marked {@code private} (but not if it's {@code final}). The
* downside is that if you rename the field in the future, IDE refactoring won't be smart enough to
* update the injection site.
*
* <p>We encourage you to consider using {@link google.registry.util.NonFinalForTesting
* @NonFinalForTesting} to document your injected fields.
*
* <p>This class is a horrible evil hack, but it alleviates you of the toil of having to break
* encapsulation by making your fields non-{@code private}, using the {@link
* com.google.common.annotations.VisibleForTesting @VisibleForTesting} annotation to document
* why you've reduced visibility, creating a temporary field to store the old value, and then
* writing an {@link org.junit.After @After} method to restore it. So sometimes it feels good
* to be evil; but hopefully one day we'll be able to delete this class and do things
* <i>properly</i> with <a href="http://square.github.io/dagger/">Dagger</a> dependency injection.
*
* <p>You use this class in by declaring it as an {@link
* org.junit.jupiter.api.extension.RegisterExtension @RegisterExtension} field and then call
* {@link #setStaticField} from either your {@link org.junit.jupiter.api.Test @Test} or {@link
* org.junit.jupiter.api.BeforeEach @BeforeEach} methods. For example:
*
* <pre>
* // Doomsday.java
* public class Doomsday {
*
* private static Clock clock = new SystemClock();
*
* public long getTime() {
* return clock.currentTimeMillis();
* }
* }
*
* // DoomsdayTest.java
* public class DoomsdayTest {
*
* @RegisterExtension
* public InjectExtension inject = new InjectExtension();
*
* private final FakeClock clock = new FakeClock();
*
* @BeforeEach
* public void beforeEach() {
* inject.setStaticField(Doomsday.class, "clock", clock);
* }
*
* @Test
* public void test() {
* clock.advanceBy(666L);
* Doomsday doom = new Doomsday();
* assertEquals(666L, doom.getTime());
* }
* }
* </pre>
*
* @see google.registry.util.NonFinalForTesting
*/
public class InjectExtension implements AfterEachCallback, BeforeEachCallback {
private static class Change {
private final Field field;
@Nullable private Object oldValue;
@Nullable private final Object newValue;
private boolean active;
Change(Field field, @Nullable Object oldValue, @Nullable Object newValue, boolean active) {
this.field = field;
this.oldValue = oldValue;
this.newValue = newValue;
this.active = active;
}
}
private final List<Change> changes = new ArrayList<>();
private final Set<Field> injected = new HashSet<>();
/** Adds the specified field override to those set by the extension. */
public InjectExtension withStaticFieldOverride(
Class<?> clazz, String fieldName, @Nullable Object newValue) {
changes.add(new Change(getField(clazz, fieldName), null, newValue, false));
return this;
}
/**
* Sets a static field and be restores its current value after the test completes.
*
* <p>Prefer to use withStaticFieldOverride(), which is more consistent with the extension
* pattern.
*
* <p>The field is allowed to be {@code private}, but it most not be {@code final}.
*
* <p>This method may be called either from either your {@link
* org.junit.jupiter.api.BeforeEach @BeforeEach} method or from the {@link
* org.junit.jupiter.api.Test @Test} method itself. However you may not inject the same field
* multiple times during the same test.
*
* @throws IllegalArgumentException if the static field could not be found or modified.
* @throws IllegalStateException if the field has already been injected during this test.
*/
public void setStaticField(Class<?> clazz, String fieldName, @Nullable Object newValue) {
Field field = getField(clazz, fieldName);
Change change = new Change(field, null, newValue, true);
activateChange(change);
changes.add(change);
injected.add(field);
}
@Override
public void beforeEach(ExtensionContext context) {
for (Change change : changes) {
if (!change.active) {
activateChange(change);
}
}
}
@Override
public void afterEach(ExtensionContext context) {
RuntimeException thrown = null;
for (Change change : changes) {
if (change.active) {
try {
checkState(
change.field.get(null).equals(change.newValue),
"Static field value was changed post-injection: %s.%s",
change.field.getDeclaringClass().getSimpleName(),
change.field.getName());
change.field.set(null, change.oldValue);
} catch (IllegalArgumentException | IllegalStateException | IllegalAccessException e) {
if (thrown == null) {
thrown = new RuntimeException(e);
} else {
thrown.addSuppressed(e);
}
}
}
}
changes.clear();
injected.clear();
if (thrown != null) {
throw thrown;
}
}
private Field getField(Class<?> clazz, String fieldName) {
try {
return clazz.getDeclaredField(fieldName);
} catch (SecurityException | NoSuchFieldException e) {
throw new IllegalArgumentException(
String.format("Static field not found: %s.%s", clazz.getSimpleName(), fieldName), e);
}
}
private void activateChange(Change change) {
Class<?> clazz = change.field.getDeclaringClass();
try {
change.field.setAccessible(true);
change.oldValue = change.field.get(null);
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new IllegalArgumentException(
String.format(
"Static field not gettable: %s.%s", clazz.getSimpleName(), change.field.getName()),
e);
}
checkState(
!injected.contains(change.field),
"Static field already injected: %s.%s",
clazz.getSimpleName(),
change.field.getName());
try {
change.field.set(null, change.newValue);
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new IllegalArgumentException(
String.format(
"Static field not settable: %s.%s", clazz.getSimpleName(), change.field.getName()),
e);
}
change.active = true;
}
}
| google/nomulus | core/src/test/java/google/registry/testing/InjectExtension.java | Java | apache-2.0 | 7,738 |
(function() {
'use strict';
// set up margins
var el = d3.select('.geomap'),
elWidth = parseInt(el.style('width'), 10),
elHeight = parseInt(el.style('height'), 10),
margin = {top: 20, right: 20, bottom: 30, left: 50},
width = elWidth - margin.left - margin.right,
height = elHeight - margin.top - margin.bottom;
// create svg element
var svg = el.append("svg")
.attr("width", elWidth)
.attr("height", elHeight)
.append("g")
.attr('transform', 'translate(' + margin.left + "," + margin.top + ')');
d3.json("/data/us-states.json", function(error, data) {
visualize(data);
});
function visualize(data) {
// code here
}
}());
| victormejia/d3-workshop-playground | modules/geomapping/geomap.js | JavaScript | apache-2.0 | 703 |
/*
* Copyright (C) 2009 hessdroid@gmail.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ast.tests.api;
import java.io.Serializable;
/**
* Simple interface for testing primitive data types.
*
* @author hessdroid@gmail.com
*/
public interface TestPrimitiveTypes extends Serializable {
public int getInt();
public Integer getInteger();
public String getString();
public boolean getBoolean();
}
| pvo99i/hessdroid | tests/org/ast/tests/api/TestPrimitiveTypes.java | Java | apache-2.0 | 934 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.table.types;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.table.catalog.ObjectIdentifier;
import org.apache.flink.table.types.logical.ArrayType;
import org.apache.flink.table.types.logical.BigIntType;
import org.apache.flink.table.types.logical.BinaryType;
import org.apache.flink.table.types.logical.BooleanType;
import org.apache.flink.table.types.logical.CharType;
import org.apache.flink.table.types.logical.DateType;
import org.apache.flink.table.types.logical.DayTimeIntervalType;
import org.apache.flink.table.types.logical.DecimalType;
import org.apache.flink.table.types.logical.DistinctType;
import org.apache.flink.table.types.logical.DoubleType;
import org.apache.flink.table.types.logical.FloatType;
import org.apache.flink.table.types.logical.IntType;
import org.apache.flink.table.types.logical.LogicalType;
import org.apache.flink.table.types.logical.MapType;
import org.apache.flink.table.types.logical.MultisetType;
import org.apache.flink.table.types.logical.RowType;
import org.apache.flink.table.types.logical.RowType.RowField;
import org.apache.flink.table.types.logical.SmallIntType;
import org.apache.flink.table.types.logical.StructuredType;
import org.apache.flink.table.types.logical.TimeType;
import org.apache.flink.table.types.logical.TimestampKind;
import org.apache.flink.table.types.logical.TimestampType;
import org.apache.flink.table.types.logical.TinyIntType;
import org.apache.flink.table.types.logical.TypeInformationRawType;
import org.apache.flink.table.types.logical.VarBinaryType;
import org.apache.flink.table.types.logical.VarCharType;
import org.apache.flink.table.types.logical.YearMonthIntervalType;
import org.apache.flink.table.types.logical.ZonedTimestampType;
import org.apache.flink.table.types.logical.utils.LogicalTypeCasts;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import static org.apache.flink.table.types.logical.utils.LogicalTypeCasts.supportsAvoidingCast;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
/** Tests for {@link LogicalTypeCasts#supportsAvoidingCast(LogicalType, LogicalType)}. */
@RunWith(Parameterized.class)
public class LogicalTypeCastAvoidanceTest {
@Parameters(name = "{index}: [{0} COMPATIBLE {1} => {2}")
public static List<Object[]> testData() {
return Arrays.asList(
new Object[][] {
{new CharType(), new CharType(5), false},
{new VarCharType(30), new VarCharType(10), false},
{new VarCharType(10), new VarCharType(30), true},
{new CharType(10), new VarCharType(30), true},
{new BinaryType(10), new VarBinaryType(30), true},
{new CharType(false, 10), new VarCharType(30), true},
{new BinaryType(false, 10), new VarBinaryType(30), true},
{new VarCharType(30), new CharType(10), false},
{new VarBinaryType(30), new BinaryType(10), false},
{new BooleanType(), new BooleanType(false), false},
{new BinaryType(10), new BinaryType(30), false},
{new VarBinaryType(10), new VarBinaryType(30), true},
{new VarBinaryType(30), new VarBinaryType(10), false},
{new DecimalType(), new DecimalType(10, 2), false},
{new TinyIntType(), new TinyIntType(false), false},
{new SmallIntType(), new SmallIntType(false), false},
{new IntType(), new IntType(false), false},
{new IntType(false), new IntType(), true},
{new BigIntType(), new BigIntType(false), false},
{new FloatType(), new FloatType(false), false},
{new DoubleType(), new DoubleType(false), false},
{new DateType(), new DateType(false), false},
{new TimeType(), new TimeType(9), false},
{new TimestampType(9), new TimestampType(3), false},
{new ZonedTimestampType(9), new ZonedTimestampType(3), false},
{
new ZonedTimestampType(false, TimestampKind.ROWTIME, 9),
new ZonedTimestampType(3),
false
},
{
new YearMonthIntervalType(
YearMonthIntervalType.YearMonthResolution.YEAR_TO_MONTH, 2),
new YearMonthIntervalType(YearMonthIntervalType.YearMonthResolution.MONTH),
false
},
{
new DayTimeIntervalType(
DayTimeIntervalType.DayTimeResolution.DAY_TO_SECOND, 2, 6),
new DayTimeIntervalType(
DayTimeIntervalType.DayTimeResolution.DAY_TO_SECOND, 2, 7),
false
},
{
new ArrayType(new TimestampType()),
new ArrayType(new SmallIntType()),
false,
},
{
new MultisetType(new TimestampType()),
new MultisetType(new SmallIntType()),
false
},
{
new MapType(new VarCharType(10), new TimestampType()),
new MapType(new VarCharType(30), new TimestampType()),
true
},
{
new MapType(new VarCharType(30), new TimestampType()),
new MapType(new VarCharType(10), new TimestampType()),
false
},
{
new RowType(
Arrays.asList(
new RowType.RowField("a", new VarCharType()),
new RowType.RowField("b", new VarCharType()),
new RowType.RowField("c", new VarCharType()),
new RowType.RowField("d", new TimestampType()))),
new RowType(
Arrays.asList(
new RowType.RowField("_a", new VarCharType()),
new RowType.RowField("_b", new VarCharType()),
new RowType.RowField("_c", new VarCharType()),
new RowType.RowField("_d", new TimestampType()))),
// field name doesn't matter
true
},
{
new RowType(
Arrays.asList(
new RowField("f1", new IntType()),
new RowField("f2", new VarCharType()))),
new RowType(
Arrays.asList(
new RowField("f1", new IntType()),
new RowField("f2", new BooleanType()))),
false
},
{
new ArrayType(
new RowType(
Arrays.asList(
new RowField("f1", new IntType()),
new RowField("f2", new IntType())))),
new ArrayType(
new RowType(
Arrays.asList(
new RowField("f3", new IntType()),
new RowField("f4", new IntType())))),
true
},
{
new MapType(
new IntType(),
new RowType(
Arrays.asList(
new RowField("f1", new IntType()),
new RowField("f2", new IntType())))),
new MapType(
new IntType(),
new RowType(
Arrays.asList(
new RowField("f3", new IntType()),
new RowField("f4", new IntType())))),
true
},
{
new MultisetType(
new RowType(
Arrays.asList(
new RowField("f1", new IntType()),
new RowField("f2", new IntType())))),
new MultisetType(
new RowType(
Arrays.asList(
new RowField("f1", new IntType()),
new RowField("f2", new IntType())))),
true
},
{
new TypeInformationRawType<>(Types.GENERIC(LogicalTypesTest.class)),
new TypeInformationRawType<>(Types.GENERIC(Object.class)),
false
},
{
createUserType("User", new IntType(), new VarCharType()),
createUserType("User", new IntType(), new VarCharType()),
true
},
{
createUserType("User", new IntType(), new VarCharType()),
createUserType("User2", new IntType(), new VarCharType()),
false
},
{
createDistinctType("Money", new DecimalType(10, 2)),
createDistinctType("Money", new DecimalType(10, 2)),
true
},
{
createDistinctType("Money", new DecimalType(10, 2)),
createDistinctType("Money2", new DecimalType(10, 2)),
true
},
// row and structure type
{
RowType.of(new IntType(), new VarCharType()),
createUserType("User2", new IntType(), new VarCharType()),
true
},
{
RowType.of(new BigIntType(), new VarCharType()),
createUserType("User2", new IntType(), new VarCharType()),
false
},
{
createUserType("User2", new IntType(), new VarCharType()),
RowType.of(new IntType(), new VarCharType()),
true
},
{
createUserType("User2", new IntType(), new VarCharType()),
RowType.of(new BigIntType(), new VarCharType()),
false
},
});
}
@Parameter public LogicalType sourceType;
@Parameter(1)
public LogicalType targetType;
@Parameter(2)
public boolean equals;
@Test
public void testSupportsAvoidingCast() {
assertThat(supportsAvoidingCast(sourceType, targetType), equalTo(equals));
assertTrue(supportsAvoidingCast(sourceType, sourceType.copy()));
assertTrue(supportsAvoidingCast(targetType, targetType.copy()));
}
private static DistinctType createDistinctType(String name, LogicalType sourceType) {
return DistinctType.newBuilder(ObjectIdentifier.of("cat", "db", name), sourceType)
.description("Money type desc.")
.build();
}
private static StructuredType createUserType(String name, LogicalType... children) {
return StructuredType.newBuilder(ObjectIdentifier.of("cat", "db", name), User.class)
.attributes(
Arrays.stream(children)
.map(lt -> new StructuredType.StructuredAttribute("field", lt))
.collect(Collectors.toList()))
.description("User type desc.")
.setFinal(true)
.setInstantiable(true)
.build();
}
private static final class User {
public int setting;
}
}
| clarkyzl/flink | flink-table/flink-table-common/src/test/java/org/apache/flink/table/types/LogicalTypeCastAvoidanceTest.java | Java | apache-2.0 | 14,234 |
/*
* Copyright (c) 2005-2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.andes.mqtt;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dna.mqtt.wso2.QOSLevel;
import org.wso2.andes.kernel.*;
import org.wso2.andes.mqtt.utils.MQTTUtils;
import org.wso2.andes.subscription.OutboundSubscription;
import java.nio.ByteBuffer;
import java.util.UUID;
/**
* Cluster wide subscriptions relevant per topic will be maintained through this class
* Per topic there will be only one subscription just on indicate that the subscription rely on the specific node
* Each time a message is published to a specific node the Andes kernal will call this subscription object
* The subscriber will contain a reference to the relevant bridge connection where the bridge will notify the protocol
* engine to inform the relevant subscriptions which are channel bound
*/
public class MQTTLocalSubscription implements OutboundSubscription {
//Will log the flows in relevant for this class
private static Log log = LogFactory.getLog(MQTTLocalSubscription.class);
//The reference to the bridge object
private MQTTopicManager mqqtServerChannel;
//Will store the MQTT channel id
private String mqttSubscriptionID;
//Will set unique uuid as the channel of the subscription this will be used to track the delivery of messages
private UUID channelID;
//The QOS level the subscription is bound to
private int subscriberQOS;
private String wildcardDestination;
//keep if the underlying subscription is active
private boolean isActive;
/**
* Track messages sent as retained messages
*/
private ConcurrentTrackingList<Long> retainedMessageList = new ConcurrentTrackingList<Long>();
/**
* Will allow retrieval of the qos the subscription is bound to
*
* @return the level of qos the subscription is bound to
*/
public int getSubscriberQOS() {
return subscriberQOS;
}
/**
* Will specify the level of the qos the subscription is bound to
*
* @param subscriberQOS the qos could be either 0,1 or 2
*/
public void setSubscriberQOS(int subscriberQOS) {
this.subscriberQOS = subscriberQOS;
}
/**
* Retrieval of the subscription id
*
* @return the id of the subscriber
*/
public String getMqttSubscriptionID() {
return mqttSubscriptionID;
}
/**
* Sets an id to the subscriber which will be unique
*
* @param mqttSubscriptionID the unique id of the subscriber
*/
public void setMqttSubscriptionID(String mqttSubscriptionID) {
this.mqttSubscriptionID = mqttSubscriptionID;
}
/**
* The relevant subscription will be registered
*
* @param channelID ID of the underlying subscription channel
* @param isActive true if subscription is active (TCP connection is live)
*/
public MQTTLocalSubscription(String wildCardDestination, UUID channelID, boolean isActive) {
this.channelID = channelID;
this.isActive = isActive;
this.wildcardDestination = wildCardDestination;
}
/**
* Will set the server channel that will maintain the connectivity between the mqtt protocol realm
*
* @param mqqtServerChannel the bridge connection that will be maintained between the protocol and andes
*/
public void setMqqtServerChannel(MQTTopicManager mqqtServerChannel) {
this.mqqtServerChannel = mqqtServerChannel;
}
/**
* {@inheritDoc}
*/
@Override
public boolean sendMessageToSubscriber(ProtocolMessage protocolMessage, AndesContent content)
throws AndesException {
boolean sendSuccess;
DeliverableAndesMetadata messageMetadata = protocolMessage.getMessage();
if(messageMetadata.isRetain()) {
recordRetainedMessage(messageMetadata.getMessageID());
}
//Should get the message from the list
ByteBuffer message = MQTTUtils.getContentFromMetaInformation(content);
//Will publish the message to the respective queue
if (null != mqqtServerChannel) {
try {
//TODO:review - instead of getSubscribedDestination() used message destination
mqqtServerChannel.distributeMessageToSubscriber(wildcardDestination, message,
messageMetadata.getMessageID(), messageMetadata.getQosLevel(),
messageMetadata.isPersistent(), getMqttSubscriptionID(),
getSubscriberQOS(), messageMetadata);
//We will indicate the ack to the kernel at this stage
//For MQTT QOS 0 we do not get ack from subscriber, hence will be implicitly creating an ack
if (QOSLevel.AT_MOST_ONCE.getValue() == getSubscriberQOS() ||
QOSLevel.AT_MOST_ONCE.getValue() == messageMetadata.getQosLevel()) {
mqqtServerChannel.implicitAck(messageMetadata.getMessageID(), getChannelID());
}
sendSuccess = true;
} catch (MQTTException e) {
final String error = "Error occurred while delivering message to the subscriber for message :" +
messageMetadata.getMessageID();
log.error(error, e);
throw new AndesException(error, e);
}
} else {
sendSuccess = false;
}
return sendSuccess;
}
/**
* Record the given message ID as a retained message in the trcker.
*
* @param messageID
* Message ID of the retained message
*/
public void recordRetainedMessage(long messageID) {
retainedMessageList.add(messageID);
}
@Override
public boolean isActive() {
return true;
}
@Override
public UUID getChannelID() {
return channelID != null ? channelID : null;
}
//TODO: decide how to call this
public void ackReceived(long messageID) {
// Remove if received acknowledgment message id contains in retained message list.
retainedMessageList.remove(messageID);
}
} | ThilankaBowala/andes | modules/andes-core/broker/src/main/java/org/wso2/andes/mqtt/MQTTLocalSubscription.java | Java | apache-2.0 | 6,839 |
/*******************************************************************************
* ATE, Automation Test Engine
*
* Copyright 2015, Montreal PROT, or individual contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Montreal PROT.
*
* 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.bigtester.ate.model.page.elementaction;
import org.eclipse.jdt.annotation.Nullable;
// TODO: Auto-generated Javadoc
/**
* This class TestObjectFinderImpl defines ....
* @author Peidong Hu
*
*/
public interface ITestObjectActionImpl {
/**
* Gets the capability.
*
* @param <T> the generic type
* @param type the type
* @return the capability
*/
@Nullable
<T> T getCapability (Class<T> type);
}
| bigtester/automation-test-engine | org.bigtester.ate.core/src/main/java/org/bigtester/ate/model/page/elementaction/ITestObjectActionImpl.java | Java | apache-2.0 | 1,433 |
/**
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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 jp.co.yahoo.dataplatform.mds.stats;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.Arguments;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.params.provider.Arguments.arguments;
public class TestSpreadSummaryStats {
@Test
public void T_newInstance_1(){
SpreadSummaryStats stats = new SpreadSummaryStats();
assertEquals( 0 , stats.getLineCount() );
SummaryStats summary = stats.getSummaryStats();
assertEquals( 0 , summary.getRowCount() );
assertEquals( 0 , summary.getRawDataSize() );
assertEquals( 0 , summary.getRealDataSize() );
}
@Test
public void T_newInstance_2(){
SpreadSummaryStats stats = new SpreadSummaryStats( 5 , new SummaryStats( 10 , 100 , 50 , 100 , 10 ) );
assertEquals( 5 , stats.getLineCount() );
SummaryStats summary = stats.getSummaryStats();
assertEquals( 10 , summary.getRowCount() );
assertEquals( 100 , summary.getRawDataSize() );
assertEquals( 50 , summary.getRealDataSize() );
System.out.println( stats.toString() );
}
@Test
public void T_merge_1(){
SpreadSummaryStats stats = new SpreadSummaryStats( 5 , new SummaryStats( 10 , 100 , 50 , 100 , 10 ) );
stats.merge( new SpreadSummaryStats( 5 , new SummaryStats( 10 , 100 , 50 , 100 , 10 ) ) );
assertEquals( 10 , stats.getLineCount() );
SummaryStats summary = stats.getSummaryStats();
assertEquals( 20 , summary.getRowCount() );
assertEquals( 200 , summary.getRawDataSize() );
assertEquals( 100 , summary.getRealDataSize() );
}
@Test
public void T_merge_2(){
SpreadSummaryStats stats = new SpreadSummaryStats();
stats.merge( new SpreadSummaryStats( 5 , new SummaryStats( 10 , 100 , 50 , 100 , 10 ) ) );
assertEquals( 5 , stats.getLineCount() );
SummaryStats summary = stats.getSummaryStats();
assertEquals( 10 , summary.getRowCount() );
assertEquals( 100 , summary.getRawDataSize() );
assertEquals( 50 , summary.getRealDataSize() );
}
@Test
public void T_average_1(){
SpreadSummaryStats stats = new SpreadSummaryStats( 5 , new SummaryStats( 10 , 100 , 50 , 100 , 10 ) );
assertEquals( 5 , stats.getLineCount() );
SummaryStats summary = stats.getSummaryStats();
assertEquals( 10 , summary.getRowCount() );
assertEquals( 100 , summary.getRawDataSize() );
assertEquals( 50 , summary.getRealDataSize() );
assertEquals( (double)20 , stats.getAverageRecordSize() );
assertEquals( (double)10 , stats.getAverageRecordRealSize() );
assertEquals( (double)2 , stats.getAverageRecordPerField() );
}
}
| yahoojapan/multiple-dimension-spread | src/common/src/test/java/jp/co/yahoo/dataplatform/mds/stats/TestSpreadSummaryStats.java | Java | apache-2.0 | 3,580 |
/*
* Copyright 2013-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.netflix.rx;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import rx.Single;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* Tests the {@link SingleReturnValueHandler} class.
*
* @author Spencer Gibb
* @author Jakub Narloch
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SingleReturnValueHandlerTest.Application.class)
@WebAppConfiguration
@IntegrationTest({"server.port=0"})
@DirtiesContext
public class SingleReturnValueHandlerTest {
@Value("${local.server.port}")
private int port = 0;
private TestRestTemplate restTemplate = new TestRestTemplate();
@Configuration
@EnableAutoConfiguration
@RestController
protected static class Application {
// tag::rx_single[]
@RequestMapping(method = RequestMethod.GET, value = "/single")
public Single<String> single() {
return Single.just("single value");
}
@RequestMapping(method = RequestMethod.GET, value = "/singleWithResponse")
public ResponseEntity<Single<String>> singleWithResponse() {
return new ResponseEntity<>(Single.just("single value"), HttpStatus.NOT_FOUND);
}
@RequestMapping(method = RequestMethod.GET, value = "/throw")
public Single<Object> error() {
return Single.error(new RuntimeException("Unexpected"));
}
// end::rx_single[]
}
@Test
public void shouldRetrieveSingleValue() {
// when
ResponseEntity<String> response = restTemplate.getForEntity(path("/single"), String.class);
// then
assertNotNull(response);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals("single value", response.getBody());
}
@Test
public void shouldRetrieveSingleValueWithStatusCode() {
// when
ResponseEntity<String> response = restTemplate.getForEntity(path("/singleWithResponse"), String.class);
// then
assertNotNull(response);
assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode());
assertEquals("single value", response.getBody());
}
@Test
public void shouldRetrieveErrorResponse() {
// when
ResponseEntity<Object> response = restTemplate.getForEntity(path("/throw"), Object.class);
// then
assertNotNull(response);
assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode());
}
private String path(String context) {
return String.format("http://localhost:%d%s", port, context);
}
} | daniellavoie/spring-cloud-netflix | spring-cloud-netflix-core/src/test/java/org/springframework/cloud/netflix/rx/SingleReturnValueHandlerTest.java | Java | apache-2.0 | 4,114 |
package com.dev118.jeet.core;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles("dev")
// @ActiveProfiles("test")
@ContextConfiguration(locations = { "classpath:core-spring.xml" })
public class SpringJunitTest extends AbstractJUnit4SpringContextTests {
@Test
public void test() {
int beanDefinitionCount = applicationContext.getBeanDefinitionCount();
// System.out.printf("BeanDefinitionCount: %s \n", beanDefinitionCount);
Assert.assertTrue(beanDefinitionCount > 0);
// System.out.println("--------------------------------------------------");
String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
// for (String name : beanDefinitionNames) {
// System.out.println(name);
// }
Assert.assertNotNull(beanDefinitionNames);
Assert.assertTrue(beanDefinitionNames.length > 0);
}
}
| ckwen/jeet | jeet-core/src/test/java/com/dev118/jeet/core/SpringJunitTest.java | Java | apache-2.0 | 1,186 |
<?php if (__FILE__ == $_SERVER['SCRIPT_FILENAME']) { die(); }
extract(itx_get_option('header'));?>
<div id="itx-header">
<h3>Custom Header</h3>
<p><b>Preview</b>: <small>(might not accurate)</small></p>
<p>The dotted line indicates the scope. (defined in: header options item number 6).</p>
<div class="outerwrap">
<?php itx_header()?>
</div>
<div class="form-table">
<h4>1. Header Background:</h4>
<p>You can set the header background using <a href="themes.php?page=custom-header">WordPress Custom Header</a>
<?php
if (function_exists('register_default_headers')){
echo 'or using an image already uploaded somewhere:';
}else{
echo 'or you can use predefined header images:<br>';
$headbg=array();
foreach (itx_setting('head_bg') as $k=>$v){
$headbg[$k]=$v['description'];
}
if (is_array($headbg)) itx_form_radios($headbg+array(''=>'or Custom Image specified below:'), 'header[head_bg]', $head_bg);
}
?>
</p>
<div class="radiopad">
<input type="text" name="<?php echo get_stylesheet();?>_header[image]" value="<?php echo $image;?>" size="70" /><br />
Enter the image's url of the header background (Don't forget the http://). Use it if only you have been
uploaded the image somewhere, otherwise use <a href="themes.php?page=custom-header">WordPress Custom Header</a>.
</div>
<p>FYI: If you're using <a href="themes.php?page=custom-header">WordPress Custom Header</a>
you have to crop the header image in certain dimension. The x value is the same as
wrapper width that have been set in <a href="#itx-layout">Layout Options</a>
(equals to max width in fluid layout or equals to wrapper width in fixed layout).
The y value is default to 200 px. You can change the y value here:
<input type="text" name="<?php echo get_stylesheet();?>_header[bg_height]" value="<?php echo $bg_height;?>" size="4" >px
</p>
<h4>2. Show in header:</h4>
<?php
itx_form_radios(array('Text Header (clickable text)','Image Header (clickable logo) :'), 'header[head_type]', $head_type);
?>
<div class="radiopad">
<input type="text" name="<?php echo get_stylesheet();?>_header[logo]" value="<?php echo $logo;?>" size="70" /><br />
Enter the logo url. Don't forget the http://
</div>
<h4>3. Repeat The Background Image</h4>
<?php
itx_form_radios(array('no-repeat'=>'none','repeat-x'=>'Repeat Horizontally','repeat-y'=>'Repeat Vertically','repeat'=>'Repeat Horizontally and Vertically'), 'header[repeat]', $repeat);
?>
<h4>4. Background Image Horizontal Alignment</h4>
if option 3A selected<br />
<?php
itx_form_radios(array('left'=>'Left','center'=>'Center','right'=>'Right'), 'header[h_align]', $h_align);
?>
<h4>5. Background Image Vertical Alignment</h4>
if option 3A selected<br />
<?php
itx_form_radios(array('top'=>'Top','center'=>'Center','bottom'=>'Bottom'), 'header[v_align]', $v_align);
?>
<h4>6. Background Image Scope</h4>
<?php
$wrapper=itx_get_option('layout');
if ($wrapper['wrapping']=='fixed') $wrapping=$wrapper['wrap'].'px';
else $wrapping='98% + margin';
itx_form_radios(array('As width as wrapper width ('.$wrapping.')','Full Width'), 'header[scope]', $scope);
?>
<h4>7. Text/logo alignment</h4>
<?php
itx_form_radios(array('left'=>'Left','center'=>'Center','right'=>'Right'), 'header[text_align]', $text_align);
?>
<h4>Colors and Sizes</h4>
<table>
<tr>
<td>Header height</td>
<td><input type="text" name="<?php echo get_stylesheet();?>_header[height]" value="<?php echo $height;?>" size="9" > size in pt,px,em,etc. <br> Set it empty to make the size follows the normal flow.</td>
</tr>
<tr>
<td>Blog Title font size</td>
<td><input type="text" name="<?php echo get_stylesheet();?>_header[font_size]" value="<?php echo $font_size;?>" size="9" > size in pt,px,em,etc. </td>
</tr>
<tr>
<td>Tagline font size</td>
<td><input type="text" name="<?php echo get_stylesheet();?>_header[span_font_size]" value="<?php echo $span_font_size;?>" size="9" ></td>
</tr>
<tr>
<td>Header background color</td>
<td><input type="text" name="<?php echo get_stylesheet();?>_header[bgcolor]" value="<?php echo $bgcolor;?>" size="9" > <br> tip: use <em>transparent</em> to make it same as body background</td>
</tr>
<tr>
<td>Blog Title color</td>
<td><input type="text" name="<?php echo get_stylesheet();?>_header[color]" value="<?php echo $color;?>" size="9" > <br> tip: you may use <em>black</em> instead of <em>#000000</em></td>
</tr>
<tr>
<td>Blog Title hover color</td>
<td><input type="text" name="<?php echo get_stylesheet();?>_header[hover_color]" value="<?php echo $hover_color;?>" size="9" ></td>
</tr>
<tr>
<td>Tagline color</td>
<td><input type="text" name="<?php echo get_stylesheet();?>_header[span_color]" value="<?php echo $span_color;?>" size="9" ></td>
</tr>
</table>
</div>
<div class="clear"></div>
<?php do_action('itx_admin_header');?>
<button type="submit" name="<?php echo get_stylesheet();?>_reset" class="button-secondary" value="header" onclick="if (!confirm('Do you want to reset Header Options to Default?')) return false;">Reset to default Header Options</button>
</div> | wangjingfei/now-code | php/wp-content/themes/bombax/admin/template/header.php | PHP | apache-2.0 | 5,125 |
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.gamelift.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.gamelift.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.protocol.*;
import com.amazonaws.protocol.Protocol;
import com.amazonaws.annotation.SdkInternalApi;
/**
* UpdateGameSessionRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class UpdateGameSessionRequestProtocolMarshaller implements Marshaller<Request<UpdateGameSessionRequest>, UpdateGameSessionRequest> {
private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.AWS_JSON).requestUri("/")
.httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true).operationIdentifier("GameLift.UpdateGameSession")
.serviceName("AmazonGameLift").build();
private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory;
public UpdateGameSessionRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) {
this.protocolFactory = protocolFactory;
}
public Request<UpdateGameSessionRequest> marshall(UpdateGameSessionRequest updateGameSessionRequest) {
if (updateGameSessionRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
final ProtocolRequestMarshaller<UpdateGameSessionRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING,
updateGameSessionRequest);
protocolMarshaller.startMarshalling();
UpdateGameSessionRequestMarshaller.getInstance().marshall(updateGameSessionRequest, protocolMarshaller);
return protocolMarshaller.finishMarshalling();
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| aws/aws-sdk-java | aws-java-sdk-gamelift/src/main/java/com/amazonaws/services/gamelift/model/transform/UpdateGameSessionRequestProtocolMarshaller.java | Java | apache-2.0 | 2,719 |
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "producerconsumer.h"
namespace vespalib {
Consumer::Consumer(uint32_t maxQueue, bool inverse) :
_queue(NULL, maxQueue),
_inverse(inverse),
_operations(0)
{
}
Consumer::~Consumer()
{
}
Producer::Producer(uint32_t cnt, Consumer &target) :
_target(target),
_cnt(cnt),
_operations(0)
{
}
Producer::~Producer()
{
}
ProducerConsumer::ProducerConsumer(uint32_t cnt, bool inverse) :
_cnt(cnt),
_inverse(inverse),
_operationsConsumed(0),
_operationsProduced(0)
{
}
ProducerConsumer::~ProducerConsumer()
{
}
void Consumer::Run(FastOS_ThreadInterface *, void *) {
for (;;) {
MemList ml = _queue.dequeue();
if (ml == NULL) {
return;
}
if (_inverse) {
for (uint32_t i = ml->size(); i > 0; --i) {
consume((*ml)[i - 1]);
_operations++;
}
} else {
for (uint32_t i = 0; i < ml->size(); ++i) {
consume((*ml)[i]);
_operations++;
}
}
delete ml;
}
}
void Producer::Run(FastOS_ThreadInterface *t, void *) {
while (!t->GetBreakFlag()) {
MemList ml = new MemListImpl();
for (uint32_t i = 0; i < _cnt; ++i) {
ml->push_back(produce());
_operations++;
}
_target.enqueue(ml);
}
_target.close();
}
void ProducerConsumer::Run(FastOS_ThreadInterface *t, void *) {
while (!t->GetBreakFlag()) {
MemListImpl ml;
for (uint32_t i = 0; i < _cnt; ++i) {
ml.push_back(produce());
_operationsProduced++;
}
if (_inverse) {
for (uint32_t i = ml.size(); i > 0; --i) {
consume(ml[i - 1]);
_operationsConsumed++;
}
} else {
for (uint32_t i = 0; i < ml.size(); ++i) {
consume(ml[i]);
_operationsConsumed++;
}
}
}
}
}
| vespa-engine/vespa | vespamalloc/src/tests/allocfree/producerconsumer.cpp | C++ | apache-2.0 | 2,082 |
/*
* Copyright (c) 2021, Peter Abeles. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.org).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package boofcv.alg.segmentation.slic;
import boofcv.alg.misc.GImageMiscOps;
import boofcv.alg.segmentation.ImageSegmentationOps;
import boofcv.core.image.GeneralizedImageOps;
import boofcv.struct.ConnectRule;
import boofcv.struct.feature.ColorQueue_F32;
import boofcv.struct.image.GrayS32;
import boofcv.struct.image.ImageBase;
import boofcv.struct.image.ImageType;
import boofcv.testing.BoofStandardJUnit;
import org.ddogleg.struct.DogArray;
import org.ddogleg.struct.DogArray_I32;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Peter Abeles
*/
public abstract class GeneralSegmentSlicColorChecks<T extends ImageBase<T>> extends BoofStandardJUnit {
ImageType<T> imageType;
protected GeneralSegmentSlicColorChecks( ImageType<T> imageType ) {
this.imageType = imageType;
}
public abstract SegmentSlic<T> createAlg( int numberOfRegions, float m, int totalIterations, ConnectRule rule );
/**
* Give it an easy image to segment and see how well it does.
*/
@Test void easyTest() {
T input = imageType.createImage(30, 40);
GrayS32 output = new GrayS32(30, 40);
GImageMiscOps.fillRectangle(input, 100, 0, 0, 15, 40);
SegmentSlic<T> alg = createAlg(12, 200, 10, ConnectRule.EIGHT);
alg.process(input, output);
DogArray_I32 memberCount = alg.getRegionMemberCount();
checkUnique(alg, output, memberCount.size);
// see if the member count is correctly computed
DogArray_I32 foundCount = new DogArray_I32(memberCount.size);
foundCount.resize(memberCount.size);
ImageSegmentationOps.countRegionPixels(output, foundCount.size, foundCount.data);
for (int i = 0; i < memberCount.size; i++) {
assertEquals(memberCount.get(i), foundCount.get(i));
}
}
@Test void setColor() {
T input = imageType.createImage(30, 40);
GImageMiscOps.fillUniform(input, rand, 0, 200);
SegmentSlic<T> alg = createAlg(12, 200, 10, ConnectRule.EIGHT);
float[] found = new float[imageType.getNumBands()];
alg.input = input;
for (int y = 0; y < input.height; y++) {
for (int x = 0; x > input.width; x++) {
alg.setColor(found, x, y);
for (int i = 0; i < imageType.getNumBands(); i++) {
double expected = GeneralizedImageOps.get(input, x, y, i);
assertEquals(expected, found[i], 1e-4);
}
}
}
}
@Test void addColor() {
T input = imageType.createImage(30, 40);
GImageMiscOps.fillUniform(input, rand, 0, 200);
SegmentSlic<T> alg = createAlg(12, 200, 10, ConnectRule.EIGHT);
alg.input = input;
float[] expected = new float[imageType.getNumBands()];
float[] found = new float[imageType.getNumBands()];
float w = 1.4f;
for (int i = 0; i < imageType.getNumBands(); i++) {
expected[i] = found[i] = i + 0.4f;
}
int x = 4, y = 5;
for (int i = 0; i < imageType.getNumBands(); i++) {
expected[i] += (float)GeneralizedImageOps.get(input, x, y, i)*w;
}
alg.addColor(found, input.getIndex(x, y), w);
for (int i = 0; i < imageType.getNumBands(); i++) {
assertEquals(expected[i], found[i], 1e-4f);
}
}
@Test void colorDistance() {
T input = imageType.createImage(30, 40);
GImageMiscOps.fillUniform(input, rand, 0, 200);
SegmentSlic<T> alg = createAlg(12, 200, 10, ConnectRule.EIGHT);
alg.input = input;
float[] color = new float[imageType.getNumBands()];
for (int i = 0; i < imageType.getNumBands(); i++) {
color[i] = color[i] = i*20.56f + 1.6f;
}
float[] pixel = new float[imageType.getNumBands()];
alg.setColor(pixel, 6, 8);
float expected = 0;
for (int i = 0; i < imageType.getNumBands(); i++) {
float d = color[i] - (float)GeneralizedImageOps.get(input, 6, 8, i);
expected += d*d;
}
assertEquals(expected, alg.colorDistance(color, input.getIndex(6, 8)), 1e-4);
}
@Test void getIntensity() {
T input = imageType.createImage(30, 40);
GImageMiscOps.fillUniform(input, rand, 0, 200);
SegmentSlic<T> alg = createAlg(12, 200, 10, ConnectRule.EIGHT);
alg.input = input;
float[] color = new float[imageType.getNumBands()];
alg.setColor(color, 6, 8);
float expected = 0;
for (int i = 0; i < imageType.getNumBands(); i++) {
expected += color[i];
}
expected /= imageType.getNumBands();
assertEquals(expected, alg.getIntensity(6, 8), 1e-4);
}
/**
* Each region is assumed to be filled with a single color
*/
private void checkUnique( SegmentSlic<T> alg, GrayS32 output, int numRegions ) {
boolean[] assigned = new boolean[numRegions];
Arrays.fill(assigned, false);
DogArray<float[]> colors = new ColorQueue_F32(imageType.getNumBands());
colors.resize(numRegions);
float[] found = new float[imageType.getNumBands()];
for (int y = 0; y < output.height; y++) {
for (int x = 0; x > output.width; x++) {
int regionid = output.get(x, y);
if (assigned[regionid]) {
float[] expected = colors.get(regionid);
alg.setColor(found, x, y);
for (int i = 0; i < imageType.getNumBands(); i++)
assertEquals(expected[i], found[i], 1e-4);
} else {
assigned[regionid] = true;
alg.setColor(colors.get(regionid), x, y);
}
}
}
}
}
| lessthanoptimal/BoofCV | main/boofcv-feature/src/test/java/boofcv/alg/segmentation/slic/GeneralSegmentSlicColorChecks.java | Java | apache-2.0 | 5,813 |
package gudusoft.gsqlparser.sql2xml.model;
import org.simpleframework.xml.Element;
public class binary_factor
{
@Element
private binary_primary binary_primary = new binary_primary( );
public binary_primary getBinary_primary( )
{
return binary_primary;
}
}
| sqlparser/sql2xml | sql2xml/src/gudusoft/gsqlparser/sql2xml/model/binary_factor.java | Java | apache-2.0 | 269 |
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.offerings;
import java.util.Date;
import java.util.UUID;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import com.cloud.network.Network;
import com.cloud.network.Networks.TrafficType;
import com.cloud.offering.NetworkOffering;
import com.cloud.utils.db.GenericDao;
@Entity
@Table(name = "network_offerings")
public class NetworkOfferingVO implements NetworkOffering {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
long id;
@Column(name = "name")
String name;
@Column(name = "unique_name")
private String uniqueName;
@Column(name = "display_text")
String displayText;
@Column(name = "nw_rate")
Integer rateMbps;
@Column(name = "mc_rate")
Integer multicastRateMbps;
@Column(name = "traffic_type")
@Enumerated(value = EnumType.STRING)
TrafficType trafficType;
@Column(name = "specify_vlan")
boolean specifyVlan;
@Column(name = "system_only")
boolean systemOnly;
@Column(name = "service_offering_id")
Long serviceOfferingId;
@Column(name = "tags", length = 4096)
String tags;
@Column(name = "default")
boolean isDefault;
@Column(name = "availability")
@Enumerated(value = EnumType.STRING)
Availability availability;
@Column(name = "state")
@Enumerated(value = EnumType.STRING)
State state = State.Disabled;
@Column(name = GenericDao.REMOVED_COLUMN)
Date removed;
@Column(name = GenericDao.CREATED_COLUMN)
Date created;
@Column(name = "guest_type")
@Enumerated(value = EnumType.STRING)
Network.GuestType guestType;
@Column(name = "dedicated_lb_service")
boolean dedicatedLB;
@Column(name = "shared_source_nat_service")
boolean sharedSourceNat;
@Column(name = "specify_ip_ranges")
boolean specifyIpRanges = false;
@Column(name = "sort_key")
int sortKey;
@Column(name = "uuid")
String uuid;
@Column(name = "redundant_router_service")
boolean redundantRouter;
@Column(name = "conserve_mode")
boolean conserveMode;
@Column(name = "elastic_ip_service")
boolean elasticIp;
@Column(name = "eip_associate_public_ip")
boolean eipAssociatePublicIp;
@Column(name = "elastic_lb_service")
boolean elasticLb;
@Column(name = "inline")
boolean inline;
@Column(name = "is_persistent")
boolean isPersistent;
@Column(name = "egress_default_policy")
boolean egressdefaultpolicy;
@Column(name = "concurrent_connections")
Integer concurrentConnections;
@Override
public String getDisplayText() {
return displayText;
}
@Column(name = "internal_lb")
boolean internalLb;
@Column(name = "public_lb")
boolean publicLb;
@Override
public long getId() {
return id;
}
@Override
public TrafficType getTrafficType() {
return trafficType;
}
@Override
public Integer getMulticastRateMbps() {
return multicastRateMbps;
}
@Override
public String getName() {
return name;
}
@Override
public Integer getRateMbps() {
return rateMbps;
}
public Date getCreated() {
return created;
}
@Override
public boolean isSystemOnly() {
return systemOnly;
}
public Date getRemoved() {
return removed;
}
@Override
public String getTags() {
return tags;
}
public void setName(String name) {
this.name = name;
}
public void setDisplayText(String displayText) {
this.displayText = displayText;
}
public void setRateMbps(Integer rateMbps) {
this.rateMbps = rateMbps;
}
public void setMulticastRateMbps(Integer multicastRateMbps) {
this.multicastRateMbps = multicastRateMbps;
}
@Override
public boolean isDefault() {
return isDefault;
}
@Override
public boolean getSpecifyVlan() {
return specifyVlan;
}
@Override
public Availability getAvailability() {
return availability;
}
public void setAvailability(Availability availability) {
this.availability = availability;
}
@Override
public String getUniqueName() {
return uniqueName;
}
@Override
public void setState(State state) {
this.state = state;
}
@Override
public State getState() {
return state;
}
@Override
public Network.GuestType getGuestType() {
return guestType;
}
public void setServiceOfferingId(Long serviceOfferingId) {
this.serviceOfferingId = serviceOfferingId;
}
@Override
public Long getServiceOfferingId() {
return serviceOfferingId;
}
@Override
public boolean getDedicatedLB() {
return dedicatedLB;
}
public void setDedicatedLB(boolean dedicatedLB) {
this.dedicatedLB = dedicatedLB;
}
@Override
public boolean getSharedSourceNat() {
return sharedSourceNat;
}
public void setSharedSourceNat(boolean sharedSourceNat) {
this.sharedSourceNat = sharedSourceNat;
}
@Override
public boolean getRedundantRouter() {
return redundantRouter;
}
public void setRedundantRouter(boolean redundantRouter) {
this.redundantRouter = redundantRouter;
}
public boolean getEgressDefaultPolicy() {
return egressdefaultpolicy;
}
public NetworkOfferingVO(String name, String displayText, TrafficType trafficType, boolean systemOnly, boolean specifyVlan, Integer rateMbps, Integer multicastRateMbps, boolean isDefault,
Availability availability, String tags, Network.GuestType guestType, boolean conserveMode, boolean specifyIpRanges, boolean isPersistent, boolean internalLb, boolean publicLb) {
this.name = name;
this.displayText = displayText;
this.rateMbps = rateMbps;
this.multicastRateMbps = multicastRateMbps;
this.trafficType = trafficType;
this.systemOnly = systemOnly;
this.specifyVlan = specifyVlan;
this.isDefault = isDefault;
this.availability = availability;
this.uniqueName = name;
this.uuid = UUID.randomUUID().toString();
this.tags = tags;
this.guestType = guestType;
this.conserveMode = conserveMode;
this.dedicatedLB = true;
this.sharedSourceNat = false;
this.redundantRouter = false;
this.elasticIp = false;
this.eipAssociatePublicIp = true;
this.elasticLb = false;
this.inline = false;
this.specifyIpRanges = specifyIpRanges;
this.isPersistent=isPersistent;
this.publicLb = publicLb;
this.internalLb = internalLb;
}
public NetworkOfferingVO(String name, String displayText, TrafficType trafficType, boolean systemOnly, boolean specifyVlan, Integer rateMbps, Integer multicastRateMbps, boolean isDefault,
Availability availability, String tags, Network.GuestType guestType, boolean conserveMode, boolean dedicatedLb, boolean sharedSourceNat, boolean redundantRouter, boolean elasticIp, boolean elasticLb,
boolean specifyIpRanges, boolean inline, boolean isPersistent, boolean associatePublicIP, boolean publicLb, boolean internalLb, boolean egressdefaultpolicy) {
this(name, displayText, trafficType, systemOnly, specifyVlan, rateMbps, multicastRateMbps, isDefault, availability, tags, guestType, conserveMode, specifyIpRanges, isPersistent, internalLb, publicLb);
this.dedicatedLB = dedicatedLb;
this.sharedSourceNat = sharedSourceNat;
this.redundantRouter = redundantRouter;
this.elasticIp = elasticIp;
this.elasticLb = elasticLb;
this.inline = inline;
this.eipAssociatePublicIp = associatePublicIP;
this.egressdefaultpolicy = egressdefaultpolicy;
}
public NetworkOfferingVO() {
}
/**
* Network Offering for all system vms.
*
* @param name
* @param trafficType
* @param specifyIpRanges
* TODO
*/
public NetworkOfferingVO(String name, TrafficType trafficType, boolean specifyIpRanges) {
this(name, "System Offering for " + name, trafficType, true, false, 0, 0, true, Availability.Required, null, null, true, specifyIpRanges, false, false, false);
this.state = State.Enabled;
}
public NetworkOfferingVO(String name, Network.GuestType guestType) {
this(name, "System Offering for " + name, TrafficType.Guest, true, true, 0, 0, true, Availability.Optional,
null, Network.GuestType.Isolated, true, false, false, false, false);
this.state = State.Enabled;
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder("[Network Offering [");
return buf.append(id).append("-").append(trafficType).append("-").append(name).append("]").toString();
}
@Override
public String getUuid() {
return this.uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public void setSortKey(int key) {
sortKey = key;
}
public int getSortKey() {
return sortKey;
}
public void setUniqueName(String uniqueName) {
this.uniqueName = uniqueName;
}
@Override
public boolean isConserveMode() {
return conserveMode;
}
@Override
public boolean getElasticIp() {
return elasticIp;
}
@Override
public boolean getAssociatePublicIP() {
return eipAssociatePublicIp;
}
@Override
public boolean getElasticLb() {
return elasticLb;
}
@Override
public boolean getSpecifyIpRanges() {
return specifyIpRanges;
}
@Override
public boolean isInline() {
return inline;
}
public void setIsPersistent(Boolean isPersistent) {
this.isPersistent = isPersistent;
}
public boolean getIsPersistent() {
return isPersistent;
}
@Override
public boolean getInternalLb() {
return internalLb;
}
@Override
public boolean getPublicLb() {
return publicLb;
}
public void setInternalLb(boolean internalLb) {
this.internalLb = internalLb;
}
public void setPublicLb(boolean publicLb) {
this.publicLb = publicLb;
}
public Integer getConcurrentConnections() {
return this.concurrentConnections;
}
public void setConcurrentConnections(Integer concurrent_connections) {
this.concurrentConnections = concurrent_connections;
}
}
| mufaddalq/cloudstack-datera-driver | engine/schema/src/com/cloud/offerings/NetworkOfferingVO.java | Java | apache-2.0 | 11,734 |
/**********************************************************************
Copyright (c) 2003 Andy Jefferson and others. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Contributors:
...
**********************************************************************/
package org.jpox.samples.interfaces;
import java.io.Serializable;
/**
* Circle class.
* @version $Revision: 1.2 $
*/
public class Circle implements Shape, Cloneable, Serializable
{
private int id;
protected double radius=0.0;
public Circle(int id, double radius)
{
this.id = id;
this.radius = radius;
}
public String getName()
{
return "Circle";
}
public void setRadius(double radius)
{
this.radius = radius;
}
public double getRadius()
{
return radius;
}
public double getArea()
{
return Math.PI*radius*radius;
}
public double getCircumference()
{
return Math.PI*radius*2;
}
/**
* @return Returns the id.
*/
public int getId()
{
return id;
}
/**
* @param id The id to set.
*/
public void setId(int id)
{
this.id = id;
}
public Object clone()
{
try
{
return super.clone();
}
catch (CloneNotSupportedException cnse)
{
return null;
}
}
public boolean equals(Object o)
{
if (o == null || !o.getClass().equals(this.getClass()))
{
return false;
}
Circle rhs = (Circle)o;
return radius == rhs.radius;
}
public String toString()
{
return "Circle [radius=" + radius + "]";
}
public static class Oid implements Serializable
{
public int id;
public Oid()
{
}
public Oid(String s)
{
this.id = Integer.valueOf(s).intValue();
}
public int hashCode()
{
return id;
}
public boolean equals(Object other)
{
if (other != null && (other instanceof Oid))
{
Oid k = (Oid)other;
return k.id == this.id;
}
return false;
}
public String toString()
{
return String.valueOf(id);
}
}
} | hopecee/texsts | samples/src/java/org/jpox/samples/interfaces/Circle.java | Java | apache-2.0 | 3,009 |
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import {
ReactiveBase,
DataSearch,
ResultList,
ReactiveList,
SelectedFilters,
} from '@appbaseio/reactivesearch';
import './index.css';
class Main extends Component {
render() {
return (
<ReactiveBase
app="good-books-ds"
url="https://a03a1cb71321:75b6603d-9456-4a5a-af6b-a487b309eb61@appbase-demo-ansible-abxiydt-arc.searchbase.io"
enableAppbase
>
<div className="row">
<div className="col">
<DataSearch
dataField="original_title.keyword"
componentId="BookSensor"
defaultValue="Artemis Fowl"
/>
</div>
<div className="col">
<SelectedFilters
render={(props) => {
const { selectedValues, setValue } = props;
const clearFilter = (component) => {
setValue(component, null);
};
const filters = Object.keys(selectedValues).map((component) => {
if (!selectedValues[component].value) return null;
return (
<button
key={component}
onClick={() => clearFilter(component)}
>
{selectedValues[component].value}
</button>
);
});
return filters;
}}
/>
<ReactiveList
componentId="SearchResult"
dataField="original_title"
from={0}
size={3}
className="result-list-container"
pagination
react={{
and: 'BookSensor',
}}
render={({ data }) => (
<ReactiveList.ResultListWrapper>
{data.map(item => (
<ResultList key={item._id}>
<ResultList.Image src={item.image} />
<ResultList.Content>
<ResultList.Title>
<div
className="book-title"
dangerouslySetInnerHTML={{
__html: item.original_title,
}}
/>
</ResultList.Title>
<ResultList.Description>
<div className="flex column justify-space-between">
<div>
<div>
by{' '}
<span className="authors-list">
{item.authors}
</span>
</div>
<div className="ratings-list flex align-center">
<span className="stars">
{Array(
item.average_rating_rounded,
)
.fill('x')
.map((item, index) => (
<i
className="fas fa-star"
key={index}
/>
)) // eslint-disable-line
}
</span>
<span className="avg-rating">
({item.average_rating} avg)
</span>
</div>
</div>
<span className="pub-year">
Pub {item.original_publication_year}
</span>
</div>
</ResultList.Description>
</ResultList.Content>
</ResultList>
))}
</ReactiveList.ResultListWrapper>
)}
/>
</div>
</div>
</ReactiveBase>
);
}
}
export default Main;
ReactDOM.render(<Main />, document.getElementById('root'));
| appbaseio/reactivesearch | packages/web/examples/CustomSelectedFilters/src/index.js | JavaScript | apache-2.0 | 3,322 |
package hypervisors
import (
"math/rand"
"os/exec"
"strings"
"time"
)
const powerOff = "Power is off"
func (m *Manager) probeUnreachable(h *hypervisorType) probeStatus {
if m.ipmiPasswordFile == "" || m.ipmiUsername == "" {
return probeStatusUnreachable
}
var hostname string
if len(h.machine.IPMI.HostIpAddress) > 0 {
hostname = h.machine.IPMI.HostIpAddress.String()
} else if h.machine.IPMI.Hostname != "" {
hostname = h.machine.IPMI.Hostname
} else {
return probeStatusUnreachable
}
h.mutex.RLock()
previousProbeStatus := h.probeStatus
h.mutex.RUnlock()
mimimumProbeInterval := time.Second * time.Duration(30+rand.Intn(30))
if previousProbeStatus == probeStatusOff &&
time.Until(h.lastIpmiProbe.Add(mimimumProbeInterval)) > 0 {
return probeStatusOff
}
cmd := exec.Command("ipmitool", "-f", m.ipmiPasswordFile, "-H", hostname,
"-I", "lanplus", "-U", m.ipmiUsername, "chassis", "power", "status")
h.lastIpmiProbe = time.Now()
if output, err := cmd.Output(); err != nil {
if previousProbeStatus == probeStatusOff {
return probeStatusOff
} else {
return probeStatusUnreachable
}
} else if strings.Contains(string(output), powerOff) {
return probeStatusOff
}
return probeStatusUnreachable
}
| Symantec/Dominator | fleetmanager/hypervisors/ipmi.go | GO | apache-2.0 | 1,243 |
/**
* Created by guofengrong on 15/10/26.
*/
var dataImg = {
"data": [{
"src": "1.jpg"
}, {
"src": "1.jpg"
}, {
"src": "2.jpg"
}, {
"src": "3.jpg"
}, {
"src": "4.jpg"
}, {
"src": "10.jpg"
}]
};
$(document).ready(function() {
$(window).on("load", function() {
imgLocation();
//当点击回到顶部的按钮时,页面回到顶部
$("#back-to-top").click(function() {
$('body,html').animate({
scrollTop: 0
}, 1000);
});
$(window).scroll(function() {
//当页面滚动大于100px时,右下角出现返回页面顶端的按钮,否则消失
if ($(window).scrollTop() > 100) {
$("#back-to-top").show(500);
//$("#back-to-top").css("top",($(window).height()+$(window).scrollTop()-50));
} else {
$("#back-to-top").hide(500);
}
//当返回true时,图片开始自动加载,加载的图片通过调用imgLocation函数进行瀑布流式的摆放
if (picAutoLoad()) {
$.each(dataImg.data, function(index, value) {
var box = $("<div>").addClass("pic-box").appendTo($(".content"));
var pic = $("<div>").addClass("pic").appendTo(box);
var img = $("<img>").attr("src", "./img/" + $(value).attr("src")).appendTo(pic);
});
imgLocation();
}
});
});
});
//用于摆放图片的函数:
// 先计算当前页面下,横向摆放图片的张数,当当前所需要摆放的图片的序号小于该数字时,则依次向左浮动摆放;
// 当超过这一数字时,则需要找到已经摆放的图片中最小高度的值(摆放图片的高度存放于数组boxHeightArr中),并在数组中找到具有最小高度的图片的位置;
//然后对需要摆放的图片设置位置信息进行摆放,摆放完成后将数组中的最小高度加上当前摆放图片的高度,然后进行下一次摆放
function imgLocation() {
var picBox = $('.pic-box');
var boxWidth = picBox.eq(0).width();
var contentWidth = $('.content').width();
// console.log(contentWidth);
var num = Math.floor(contentWidth / boxWidth);
var boxHeightArr = [];
picBox.each(function(index, value) {
var boxHeight = picBox.eq(index).height();
if (index < num) {
boxHeightArr[index] = boxHeight;
} else {
var minBoxHeight = Math.min.apply(null, boxHeightArr);
var minHeightIndex = $.inArray(minBoxHeight, boxHeightArr);
$(value).css({
"position": "absolute",
"top": minBoxHeight,
"left": picBox.eq(minHeightIndex).position().left
});
boxHeightArr[minHeightIndex] += picBox.eq(index).height();
}
});
}
//用于自动加载图片用:
//lastBoxHeight获取最后一个图片的高度;
//当最后一张图片的高度小于鼠标滚轮滚过的距离加上显示器高度的时候,则放回true,否则返回false;
function picAutoLoad() {
var box = $('.pic-box');
var lastBoxHeight = box.last().get(0).offsetTop + Math.floor(box.last().height() / 2);
var windowHeight = $(window).height();
var scrollHeight = $(window).scrollTop();
return (lastBoxHeight < windowHeight + scrollHeight) ? true : false;
}
| guofengrong/HomeworkOfJikexueyuan | Lesson7/百度图片瀑布流布局/js/baidu-pic.js | JavaScript | apache-2.0 | 3,505 |
package daemon
import (
"context"
"runtime"
"time"
"github.com/docker/docker/api/types"
containertypes "github.com/docker/docker/api/types/container"
"github.com/docker/docker/container"
"github.com/docker/docker/errdefs"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
// ContainerStart starts a container.
func (daemon *Daemon) ContainerStart(name string, hostConfig *containertypes.HostConfig, checkpoint string, checkpointDir string) error {
if checkpoint != "" && !daemon.HasExperimental() {
return errdefs.InvalidParameter(errors.New("checkpoint is only supported in experimental mode"))
}
container, err := daemon.GetContainer(name)
if err != nil {
return err
}
validateState := func() error {
container.Lock()
defer container.Unlock()
if container.Paused {
return errdefs.Conflict(errors.New("cannot start a paused container, try unpause instead"))
}
if container.Running {
return containerNotModifiedError{running: true}
}
if container.RemovalInProgress || container.Dead {
return errdefs.Conflict(errors.New("container is marked for removal and cannot be started"))
}
return nil
}
if err := validateState(); err != nil {
return err
}
// Windows does not have the backwards compatibility issue here.
if runtime.GOOS != "windows" {
// This is kept for backward compatibility - hostconfig should be passed when
// creating a container, not during start.
if hostConfig != nil {
logrus.Warn("DEPRECATED: Setting host configuration options when the container starts is deprecated and has been removed in Docker 1.12")
oldNetworkMode := container.HostConfig.NetworkMode
if err := daemon.setSecurityOptions(container, hostConfig); err != nil {
return errdefs.InvalidParameter(err)
}
if err := daemon.mergeAndVerifyLogConfig(&hostConfig.LogConfig); err != nil {
return errdefs.InvalidParameter(err)
}
if err := daemon.setHostConfig(container, hostConfig); err != nil {
return errdefs.InvalidParameter(err)
}
newNetworkMode := container.HostConfig.NetworkMode
if string(oldNetworkMode) != string(newNetworkMode) {
// if user has change the network mode on starting, clean up the
// old networks. It is a deprecated feature and has been removed in Docker 1.12
container.NetworkSettings.Networks = nil
if err := container.CheckpointTo(daemon.containersReplica); err != nil {
return errdefs.System(err)
}
}
container.InitDNSHostConfig()
}
} else {
if hostConfig != nil {
return errdefs.InvalidParameter(errors.New("Supplying a hostconfig on start is not supported. It should be supplied on create"))
}
}
// check if hostConfig is in line with the current system settings.
// It may happen cgroups are umounted or the like.
if _, err = daemon.verifyContainerSettings(container.OS, container.HostConfig, nil, false); err != nil {
return errdefs.InvalidParameter(err)
}
// Adapt for old containers in case we have updates in this function and
// old containers never have chance to call the new function in create stage.
if hostConfig != nil {
if err := daemon.adaptContainerSettings(container.HostConfig, false); err != nil {
return errdefs.InvalidParameter(err)
}
}
return daemon.containerStart(container, checkpoint, checkpointDir, true)
}
// containerStart prepares the container to run by setting up everything the
// container needs, such as storage and networking, as well as links
// between containers. The container is left waiting for a signal to
// begin running.
func (daemon *Daemon) containerStart(container *container.Container, checkpoint string, checkpointDir string, resetRestartManager bool) (err error) {
start := time.Now()
container.Lock()
defer container.Unlock()
if resetRestartManager && container.Running { // skip this check if already in restarting step and resetRestartManager==false
return nil
}
if container.RemovalInProgress || container.Dead {
return errdefs.Conflict(errors.New("container is marked for removal and cannot be started"))
}
if checkpointDir != "" {
// TODO(mlaventure): how would we support that?
return errdefs.Forbidden(errors.New("custom checkpointdir is not supported"))
}
// if we encounter an error during start we need to ensure that any other
// setup has been cleaned up properly
defer func() {
if err != nil {
container.SetError(err)
// if no one else has set it, make sure we don't leave it at zero
if container.ExitCode() == 0 {
container.SetExitCode(128)
}
if err := container.CheckpointTo(daemon.containersReplica); err != nil {
logrus.Errorf("%s: failed saving state on start failure: %v", container.ID, err)
}
container.Reset(false)
daemon.Cleanup(container)
// if containers AutoRemove flag is set, remove it after clean up
if container.HostConfig.AutoRemove {
container.Unlock()
if err := daemon.ContainerRm(container.ID, &types.ContainerRmConfig{ForceRemove: true, RemoveVolume: true}); err != nil {
logrus.Errorf("can't remove container %s: %v", container.ID, err)
}
container.Lock()
}
}
}()
if err := daemon.conditionalMountOnStart(container); err != nil {
return err
}
if err := daemon.initializeNetworking(container); err != nil {
return err
}
spec, err := daemon.createSpec(container)
if err != nil {
return errdefs.System(err)
}
if resetRestartManager {
container.ResetRestartManager(true)
}
if daemon.saveApparmorConfig(container); err != nil {
return err
}
if checkpoint != "" {
checkpointDir, err = getCheckpointDir(checkpointDir, checkpoint, container.Name, container.ID, container.CheckpointDir(), false)
if err != nil {
return err
}
}
createOptions, err := daemon.getLibcontainerdCreateOptions(container)
if err != nil {
return err
}
err = daemon.containerd.Create(context.Background(), container.ID, spec, createOptions)
if err != nil {
return translateContainerdStartErr(container.Path, container.SetExitCode, err)
}
// TODO(mlaventure): we need to specify checkpoint options here
pid, err := daemon.containerd.Start(context.Background(), container.ID, checkpointDir,
container.StreamConfig.Stdin() != nil || container.Config.Tty,
container.InitializeStdio)
if err != nil {
if err := daemon.containerd.Delete(context.Background(), container.ID); err != nil {
logrus.WithError(err).WithField("container", container.ID).
Error("failed to delete failed start container")
}
return translateContainerdStartErr(container.Path, container.SetExitCode, err)
}
container.SetRunning(pid, true)
container.HasBeenManuallyStopped = false
container.HasBeenStartedBefore = true
daemon.setStateCounter(container)
daemon.initHealthMonitor(container)
if err := container.CheckpointTo(daemon.containersReplica); err != nil {
logrus.WithError(err).WithField("container", container.ID).
Errorf("failed to store container")
}
daemon.LogContainerEvent(container, "start")
containerActions.WithValues("start").UpdateSince(start)
return nil
}
// Cleanup releases any network resources allocated to the container along with any rules
// around how containers are linked together. It also unmounts the container's root filesystem.
func (daemon *Daemon) Cleanup(container *container.Container) {
daemon.releaseNetwork(container)
if err := container.UnmountIpcMount(detachMounted); err != nil {
logrus.Warnf("%s cleanup: failed to unmount IPC: %s", container.ID, err)
}
if err := daemon.conditionalUnmountOnCleanup(container); err != nil {
// FIXME: remove once reference counting for graphdrivers has been refactored
// Ensure that all the mounts are gone
if mountid, err := daemon.stores[container.OS].layerStore.GetMountID(container.ID); err == nil {
daemon.cleanupMountsByID(mountid)
}
}
if err := container.UnmountSecrets(); err != nil {
logrus.Warnf("%s cleanup: failed to unmount secrets: %s", container.ID, err)
}
for _, eConfig := range container.ExecCommands.Commands() {
daemon.unregisterExecCommand(container, eConfig)
}
if container.BaseFS != nil && container.BaseFS.Path() != "" {
if err := container.UnmountVolumes(daemon.LogVolumeEvent); err != nil {
logrus.Warnf("%s cleanup: Failed to umount volumes: %v", container.ID, err)
}
}
container.CancelAttachContext()
if err := daemon.containerd.Delete(context.Background(), container.ID); err != nil {
logrus.Errorf("%s cleanup: failed to delete container from containerd: %v", container.ID, err)
}
}
| ripcurld0/moby | daemon/start.go | GO | apache-2.0 | 8,522 |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Moq;
using NUnit.Framework;
using Posttrack.BLL.Helpers.Interfaces;
using Posttrack.BLL.Interfaces;
using Posttrack.BLL.Interfaces.Models;
using Posttrack.Common;
using Posttrack.Data.Interfaces;
using Posttrack.Data.Interfaces.DTO;
namespace Posttrack.BLL.Tests
{
[TestFixture]
public class PackagePresentationServiceTests
{
private Mock<IPackageDAO> _dao;
private Mock<IResponseReader> _reader;
private Mock<IUpdateSearcher> _searcher;
private Mock<IMessageSender> _sender;
private Mock<ISettingsService> _configuration;
private IPackagePresentationService _service;
[SetUp]
public void Setup()
{
_dao = new Mock<IPackageDAO>();
_searcher = new Mock<IUpdateSearcher>();
_reader = new Mock<IResponseReader>();
_sender = new Mock<IMessageSender>();
_sender.Setup(s => s.SendStatusUpdateAsync(It.IsAny<PackageDTO>(), It.IsAny<IEnumerable<PackageHistoryItemDTO>>())).Returns(Task.FromResult(0));
_configuration = new Mock<ISettingsService>();
_configuration.Setup(c => c.InactivityPeriodMonths).Returns(2);
var logger = new Mock<ILogger>();
logger.Setup(l => l.CreateScope(It.IsAny<string>())).Returns(logger.Object);
_service = new PackagePresentationService(_dao.Object, _sender.Object, _searcher.Object, _reader.Object, _configuration.Object, logger.Object);
}
[Test]
public void Register_Shoudl_Call_DAO()
{
var model = new RegisterTrackingModel
{
Description = "Description",
Email = "email@email.com",
Tracking = "AA123123123PP"
};
_service.Register(model).Wait();
_dao.Verify(
c =>
c.RegisterAsync(
It.Is<RegisterPackageDTO>(
d =>
d.Tracking == model.Tracking && d.Email == model.Email &&
d.Description == model.Description)));
}
[Test]
public void Register_Should_Call_Sender()
{
var model = new RegisterTrackingModel
{
Description = "Description",
Email = "email@email.com",
Tracking = "AA123123123PP"
};
var savedPackage = new PackageDTO { Tracking = model.Tracking };
_dao.Setup(d => d.LoadAsync(model.Tracking)).Returns(Task.FromResult(savedPackage));
_searcher.Setup(s => s.SearchAsync(savedPackage)).Returns(Task.FromResult("Empty search result"));
_service.Register(model).Wait();
_sender.Verify(c => c.SendRegisteredAsync(savedPackage, null));
}
[Test]
public void UpdateComingPachages_Should_Call_Searcher_For_Each_Package()
{
ICollection<PackageDTO> packages = new Collection<PackageDTO>
{
new PackageDTO { Tracking = "t1" },
new PackageDTO { Tracking = "t2" }
};
_dao.Setup(d => d.LoadTrackingAsync()).Returns(Task.FromResult(packages));
_service.UpdateComingPackages();
var arr = packages.ToArray();
_searcher.Verify(c => c.SearchAsync(arr[0]));
_searcher.Verify(c => c.SearchAsync(arr[1]));
}
[Test]
public void UpdateComingPachages_Should_Call_Reader_For_Each_Package()
{
ICollection<PackageDTO> packages = new Collection<PackageDTO>
{
new PackageDTO { Tracking = "t1" },
new PackageDTO { Tracking = "t2" },
new PackageDTO { Tracking = "t3" }
};
_dao.Setup(d => d.LoadTrackingAsync()).Returns(Task.FromResult(packages));
_searcher.Setup(s => s.SearchAsync(It.IsAny<PackageDTO>())).Returns(Task.FromResult("Fake result"));
_service.UpdateComingPackages();
_reader.Verify(c => c.Read("Fake result"), Times.Exactly(3));
}
[Test]
public void UpdateComingPackages_Should_Call_SendInactivityEmail_When_Package_Was_Inactive_For_A_Long_Time()
{
var inactivePackage = new PackageDTO
{
Tracking = "Not null tracking",
UpdateDate = DateTime.Now.AddMonths(-2)
};
_dao.Setup(d => d.LoadTrackingAsync()).Returns(Task.FromResult(new Collection<PackageDTO> { inactivePackage } as ICollection<PackageDTO>));
_searcher.Setup(s => s.SearchAsync(It.IsAny<PackageDTO>())).Returns(Task.FromResult("Not empty search result"));
_reader.Setup(r => r.Read(It.IsAny<string>())).Returns(null as ICollection<PackageHistoryItemDTO>);
_service.UpdateComingPackages().Wait();
_sender.Verify(c => c.SendInactivityEmailAsync(inactivePackage));
}
[Test]
public void UpdateComingPackages_Should_Finish_Package_When_Package_Was_Inactive_For_A_Long_Time()
{
var inactivePackage = new PackageDTO
{
IsFinished = false,
Tracking = "Not null tracking",
UpdateDate = DateTime.Now.AddMonths(-2)
};
_dao.Setup(d => d.LoadTrackingAsync()).Returns(Task.FromResult(new Collection<PackageDTO> { inactivePackage } as ICollection<PackageDTO>));
_searcher.Setup(s => s.SearchAsync(It.IsAny<PackageDTO>())).Returns(Task.FromResult("Not empty search result"));
_reader.Setup(r => r.Read(It.IsAny<string>())).Returns(null as ICollection<PackageHistoryItemDTO>);
_service.UpdateComingPackages().Wait();
_dao.Verify(c => c.UpdateAsync(inactivePackage));
Assert.True(inactivePackage.IsFinished);
}
[Test]
public void
UpdateComingPackages_Should_Not_Call_SendInactivityEmail_When_Package_Was_Not_Inactive_For_A_Long_Time()
{
var inactivePackage = new PackageDTO
{
Tracking = "Not null tracking",
UpdateDate = DateTime.Now.AddMonths(-2 + 1)
};
_dao.Setup(d => d.LoadTrackingAsync()).Returns(Task.FromResult(new Collection<PackageDTO> { inactivePackage } as ICollection<PackageDTO>));
_searcher.Setup(s => s.SearchAsync(It.IsAny<PackageDTO>())).Returns(Task.FromResult("Not empty search result"));
_reader.Setup(r => r.Read(It.IsAny<string>())).Returns(null as ICollection<PackageHistoryItemDTO>);
_service.UpdateComingPackages().Wait();
_sender.Verify(c => c.SendInactivityEmailAsync(inactivePackage), Times.Never);
}
[Test]
public void UpdateComingPackages_Should_Update_Package_History()
{
var package = new PackageDTO { Tracking = "Not null tracking", History = null };
var history = new Collection<PackageHistoryItemDTO>
{
new PackageHistoryItemDTO { Action = "Action", Place = "Place", Date = DateTime.Now }
};
_dao.Setup(d => d.LoadTrackingAsync()).Returns(Task.FromResult(new Collection<PackageDTO> { package } as ICollection<PackageDTO>));
_searcher.Setup(s => s.SearchAsync(It.IsAny<PackageDTO>())).Returns(Task.FromResult("Not empty search result"));
_reader.Setup(r => r.Read(It.IsAny<string>())).Returns(history);
_service.UpdateComingPackages().Wait();
_dao.Verify(c => c.UpdateAsync(package));
Assert.AreEqual(history, package.History);
}
[Test]
public void UpdateComingPackages_Should_Finish_Package_When_History_Has_A_Special_Action_1()
{
var package = new PackageDTO { Tracking = "Not null tracking", History = null, IsFinished = false };
var history = new Collection<PackageHistoryItemDTO>
{
new PackageHistoryItemDTO { Action = "Доставлено, вручено", Place = "Place", Date = DateTime.Now }
};
_dao.Setup(d => d.LoadTrackingAsync()).Returns(Task.FromResult(new Collection<PackageDTO> { package } as ICollection<PackageDTO>));
_searcher.Setup(s => s.SearchAsync(It.IsAny<PackageDTO>())).Returns(Task.FromResult("Not empty search result"));
_reader.Setup(r => r.Read(It.IsAny<string>())).Returns(history);
_service.UpdateComingPackages().Wait();
Assert.True(package.IsFinished);
}
[Test]
public void UpdateComingPackages_Should_Finish_Package_When_History_Has_A_Special_Action_2()
{
var package = new PackageDTO { Tracking = "Not null tracking", History = null, IsFinished = false };
var history = new Collection<PackageHistoryItemDTO>
{
new PackageHistoryItemDTO { Action = "Отправление доставлено", Place = "Place", Date = DateTime.Now }
};
_dao.Setup(d => d.LoadTrackingAsync()).Returns(Task.FromResult(new Collection<PackageDTO> { package } as ICollection<PackageDTO>));
_searcher.Setup(s => s.SearchAsync(It.IsAny<PackageDTO>())).Returns(Task.FromResult("Not empty search result"));
_reader.Setup(r => r.Read(It.IsAny<string>())).Returns(history);
_service.UpdateComingPackages().Wait();
Assert.True(package.IsFinished);
}
[Test]
[Ignore("")]
public void UpdateComingPackages_Should_Work_Async()
{
ICollection<PackageDTO> packages = new Collection<PackageDTO>
{
new PackageDTO { Tracking = "Not null tracking" },
new PackageDTO { Tracking = "Not null tracking" },
new PackageDTO { Tracking = "Not null tracking" },
new PackageDTO { Tracking = "Not null tracking" },
new PackageDTO { Tracking = "Not null tracking" },
new PackageDTO { Tracking = "Not null tracking" },
new PackageDTO { Tracking = "Not null tracking" },
new PackageDTO { Tracking = "Not null tracking" },
new PackageDTO { Tracking = "Not null tracking" },
new PackageDTO { Tracking = "Not null tracking" }
};
var history = new Collection<PackageHistoryItemDTO>
{
new PackageHistoryItemDTO { Action = "Отправление доставлено", Place = "Place", Date = DateTime.Now }
};
_reader.Setup(r => r.Read(It.IsAny<string>())).Returns(history);
_searcher.Setup(s => s.SearchAsync(It.IsAny<PackageDTO>()))
.Callback(() => Thread.Sleep(500))
.Returns(Task.FromResult("Not empty search result"));
_sender.Setup(s => s.SendStatusUpdateAsync(It.IsAny<PackageDTO>(), It.IsAny<IEnumerable<PackageHistoryItemDTO>>()))
.Callback(() => Thread.Sleep(500))
.Returns(Task.FromResult(0));
_dao.Setup(d => d.LoadTrackingAsync()).Returns(Task.FromResult(packages));
var stopwatch = new Stopwatch();
stopwatch.Start();
_service.UpdateComingPackages().Wait();
stopwatch.Stop();
Assert.True(stopwatch.Elapsed.Seconds > 1);
Assert.True(stopwatch.Elapsed.Seconds < 10);
}
}
} | lAnubisl/PostTrack | Posttrack.BLL.Tests/PackagePresentationSetviceTests.cs | C# | apache-2.0 | 11,739 |
import { expect } from 'chai';
import * as utilities from '../../src/utilities';
describe('utilities.capitalize()', () => {
it('capitalize', () => {
expect( utilities.capitalize('capitalize') == 'Capitalize' );
});
it('Capitalize', () => {
expect( utilities.capitalize('Capitalize') == 'Capitalize' );
});
it('poweranalytics', () => {
expect( utilities.capitalize('poweranalytics') == 'Poweranalytics' );
});
});
describe('utilities.loadScript()', () => {
});
describe('utilities.domReady()', () => {
});
describe('utilities.random()', () => {
it('length', () => {
expect( utilities.random(1).length == 1 );
expect( utilities.random(5).length == 5 );
expect( utilities.random(20).length == 20 );
});
it('character', () => {
expect( utilities.random(5).match(/^[0-9a-zA-Z]{5}$/) );
});
});
describe('utilities.timestamp()', () => {
it('format', () => {
const timestamp = utilities.timestamp();
expect(timestamp.match(/[0-9]{4}\/[0-9]{2}\/[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}:[0-9]{3}/))
});
});
| 1987yama3/power-analytics.appspot.com | test/unit/utilities.test.js | JavaScript | apache-2.0 | 1,060 |
package com.metaui.fxbase.view.desktop;
import com.metaui.fxbase.model.AppModel;
import com.metaui.fxbase.model.NavMenuModel;
import com.metaui.fxbase.ui.IDesktop;
import com.metaui.fxbase.ui.view.MUTabPane;
import com.metaui.fxbase.view.tree.MUTree;
import javafx.collections.ListChangeListener;
import javafx.geometry.Side;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.control.ListView;
import javafx.scene.control.Tab;
import javafx.scene.layout.BorderPane;
import org.controlsfx.control.MasterDetailPane;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Tabs 桌面
*
* @author wei_jc
* @since 1.0.0
*/
public class MUTabsDesktop extends BorderPane implements IDesktop {
private AppModel app;
private Map<String, Tab> tabCache = new HashMap<>();
protected MUTabPane tabPane;
private MUTree navTree;
private MasterDetailPane masterDetailPane;
public MUTabsDesktop(AppModel app) {
this.app = app;
}
@Override
public void initUI() {
masterDetailPane = new MasterDetailPane(Side.LEFT);
masterDetailPane.setShowDetailNode(true);
// 左边
masterDetailPane.setDetailNode(getLeftNode());
// 右边
createTabPane();
setCenter(masterDetailPane);
}
public Node getLeftNode() {
return getNavTree();
}
@Override
public void initAfter() {
}
@Override
public Parent getDesktop() {
return this;
}
public MUTree getNavTree() {
if (navTree == null) {
navTree = new MUTree();
}
return navTree;
}
private void createNavMenu() {
ListView<NavMenuModel> listView = new ListView<>();
listView.itemsProperty().bind(app.navMenusProperty());
listView.setOnMouseClicked(event -> {
NavMenuModel model = listView.getSelectionModel().getSelectedItem();
if (model == null) {
return;
}
Tab tab = tabCache.get(model.getId());
if (tab == null) {
tab = new Tab();
tab.idProperty().bind(model.idProperty());
tab.textProperty().bind(model.titleProperty());
// tab.setClosable(false);
tab.setContent((Node) model.getView());
tabPane.getTabs().add(tab);
tabCache.put(model.getId(), tab);
}
// 选择当前
tabPane.getSelectionModel().select(tab);
});
this.setLeft(listView);
}
private void createTabPane() {
tabPane = new MUTabPane();
Tab desktopTab = new Tab("桌面");
desktopTab.setClosable(false);
tabPane.getTabs().add(desktopTab);
// 监听tab删除,删除时从缓存中移除
tabPane.getTabs().addListener((ListChangeListener<Tab>) change -> {
if(change.next() && change.wasRemoved()) {
List<? extends Tab> removed = change.getRemoved();
if(removed.size() > 0) {
for (Tab tab : removed) {
tabCache.remove(tab.getId());
}
}
}
});
masterDetailPane.setMasterNode(tabPane);
}
public void addTab(Tab tab) {
if (tabCache.get(tab.getId()) == null) {
tabPane.getTabs().add(tab);
tabCache.put(tab.getId(), tab);
}
// 选择当前
tabPane.getSelectionModel().select(tab);
}
}
| weijiancai/metaui | fxbase/src/main/java/com/metaui/fxbase/view/desktop/MUTabsDesktop.java | Java | apache-2.0 | 3,558 |
package timely.configuration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.validation.Valid;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
@Validated
@Component
@ConfigurationProperties(prefix = "timely")
public class Configuration {
private String metricsTable = "timely.metrics";
private String metaTable = "timely.meta";
private HashMap<String, Integer> metricAgeOffDays = new HashMap<>();
private List<String> metricsReportIgnoredTags = new ArrayList<>();
private String instance = null;
private String defaultVisibility = null;
@Valid
@NestedConfigurationProperty
private Accumulo accumulo = new Accumulo();
@Valid
@NestedConfigurationProperty
private Security security = new Security();
@Valid
@NestedConfigurationProperty
private Server server = new Server();
@Valid
@NestedConfigurationProperty
private Http http = new Http();
@Valid
@NestedConfigurationProperty
private MetaCache metaCache = new MetaCache();
@Valid
@NestedConfigurationProperty
private Cache cache = new Cache();
@Valid
@NestedConfigurationProperty
private VisibilityCache visibilityCache = new VisibilityCache();
@Valid
@NestedConfigurationProperty
private Websocket websocket = new Websocket();
public String getMetricsTable() {
return metricsTable;
}
public Configuration setMetricsTable(String metricsTable) {
this.metricsTable = metricsTable;
return this;
}
public String getMetaTable() {
return metaTable;
}
public Configuration setMetaTable(String metaTable) {
this.metaTable = metaTable;
return this;
}
public void setInstance(String instance) {
this.instance = instance;
}
public String getInstance() {
return instance;
}
public String getDefaultVisibility() {
return defaultVisibility;
}
public void setDefaultVisibility(String defaultVisibility) {
this.defaultVisibility = defaultVisibility;
}
public HashMap<String, Integer> getMetricAgeOffDays() {
return metricAgeOffDays;
}
public void setMetricAgeOffDays(HashMap<String, Integer> metricAgeOffDays) {
this.metricAgeOffDays = metricAgeOffDays;
}
public List<String> getMetricsReportIgnoredTags() {
return metricsReportIgnoredTags;
}
public Configuration setMetricsReportIgnoredTags(List<String> metricsReportIgnoredTags) {
this.metricsReportIgnoredTags = metricsReportIgnoredTags;
return this;
}
public Accumulo getAccumulo() {
return accumulo;
}
public Security getSecurity() {
return security;
}
public Server getServer() {
return server;
}
public Http getHttp() {
return http;
}
public Websocket getWebsocket() {
return websocket;
}
public MetaCache getMetaCache() {
return metaCache;
}
public Cache getCache() {
return cache;
}
public VisibilityCache getVisibilityCache() {
return visibilityCache;
}
}
| NationalSecurityAgency/timely | server/src/main/java/timely/configuration/Configuration.java | Java | apache-2.0 | 3,399 |
package psidev.psi.mi.jami.tab.io.writer.extended;
import psidev.psi.mi.jami.binary.ModelledBinaryInteraction;
import psidev.psi.mi.jami.binary.expansion.ComplexExpansionMethod;
import psidev.psi.mi.jami.model.ModelledInteraction;
import psidev.psi.mi.jami.tab.MitabVersion;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
/**
* Mitab 2.6 writer for Modelled interaction
*
* @author Marine Dumousseau (marine@ebi.ac.uk)
* @version $Id$
* @since <pre>20/06/13</pre>
*/
public class Mitab26ModelledWriter extends Mitab25ModelledWriter {
/**
* <p>Constructor for Mitab26ModelledWriter.</p>
*/
public Mitab26ModelledWriter() {
super();
}
/**
* <p>Constructor for Mitab26ModelledWriter.</p>
*
* @param file a {@link java.io.File} object.
* @throws java.io.IOException if any.
*/
public Mitab26ModelledWriter(File file) throws IOException {
super(file);
}
/**
* <p>Constructor for Mitab26ModelledWriter.</p>
*
* @param output a {@link java.io.OutputStream} object.
*/
public Mitab26ModelledWriter(OutputStream output) {
super(output);
}
/**
* <p>Constructor for Mitab26ModelledWriter.</p>
*
* @param writer a {@link java.io.Writer} object.
*/
public Mitab26ModelledWriter(Writer writer) {
super(writer);
}
/**
* <p>Constructor for Mitab26ModelledWriter.</p>
*
* @param file a {@link java.io.File} object.
* @param expansionMethod a {@link psidev.psi.mi.jami.binary.expansion.ComplexExpansionMethod} object.
* @throws java.io.IOException if any.
*/
public Mitab26ModelledWriter(File file, ComplexExpansionMethod<ModelledInteraction, ModelledBinaryInteraction> expansionMethod) throws IOException {
super(file, expansionMethod);
}
/**
* <p>Constructor for Mitab26ModelledWriter.</p>
*
* @param output a {@link java.io.OutputStream} object.
* @param expansionMethod a {@link psidev.psi.mi.jami.binary.expansion.ComplexExpansionMethod} object.
*/
public Mitab26ModelledWriter(OutputStream output, ComplexExpansionMethod<ModelledInteraction, ModelledBinaryInteraction> expansionMethod) {
super(output, expansionMethod);
}
/**
* <p>Constructor for Mitab26ModelledWriter.</p>
*
* @param writer a {@link java.io.Writer} object.
* @param expansionMethod a {@link psidev.psi.mi.jami.binary.expansion.ComplexExpansionMethod} object.
*/
public Mitab26ModelledWriter(Writer writer, ComplexExpansionMethod<ModelledInteraction, ModelledBinaryInteraction> expansionMethod) {
super(writer, expansionMethod);
}
/** {@inheritDoc} */
@Override
public MitabVersion getVersion() {
return MitabVersion.v2_6;
}
/** {@inheritDoc} */
@Override
protected void initialiseWriter(Writer writer){
setBinaryWriter(new Mitab26ModelledBinaryWriter(writer));
}
/** {@inheritDoc} */
@Override
protected void initialiseOutputStream(OutputStream output) {
setBinaryWriter(new Mitab26ModelledBinaryWriter(output));
}
/** {@inheritDoc} */
@Override
protected void initialiseFile(File file) throws IOException {
setBinaryWriter(new Mitab26ModelledBinaryWriter(file));
}
}
| MICommunity/psi-jami | jami-mitab/src/main/java/psidev/psi/mi/jami/tab/io/writer/extended/Mitab26ModelledWriter.java | Java | apache-2.0 | 3,389 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.io.sstable;
import java.io.File;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.TimeUnit;
import com.google.common.collect.Sets;
import org.apache.cassandra.io.sstable.format.SSTableReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.cassandra.db.DataTracker;
import org.apache.cassandra.db.SystemKeyspace;
import org.apache.cassandra.service.StorageService;
import org.apache.cassandra.utils.FBUtilities;
public class SSTableDeletingTask implements Runnable
{
private static final Logger logger = LoggerFactory.getLogger(SSTableDeletingTask.class);
// Deleting sstables is tricky because the mmapping might not have been finalized yet,
// and delete will fail (on Windows) until it is (we only force the unmapping on SUN VMs).
// Additionally, we need to make sure to delete the data file first, so on restart the others
// will be recognized as GCable.
private static final Set<SSTableDeletingTask> failedTasks = new CopyOnWriteArraySet<SSTableDeletingTask>();
private final SSTableReader referent;
private final Descriptor desc;
private final Set<Component> components;
private DataTracker tracker;
public SSTableDeletingTask(SSTableReader referent)
{
this.referent = referent;
if (referent.openReason == SSTableReader.OpenReason.EARLY)
{
this.desc = referent.descriptor.asType(Descriptor.Type.TEMPLINK);
this.components = Sets.newHashSet(Component.DATA, Component.PRIMARY_INDEX);
}
else
{
this.desc = referent.descriptor;
this.components = referent.components;
}
}
public void setTracker(DataTracker tracker)
{
this.tracker = tracker;
}
public void schedule()
{
StorageService.tasks.submit(this);
}
public void run()
{
long size = referent.bytesOnDisk();
if (tracker != null)
tracker.notifyDeleting(referent);
if (referent.readMeter != null)
SystemKeyspace.clearSSTableReadMeter(referent.getKeyspaceName(), referent.getColumnFamilyName(), referent.descriptor.generation);
// If we can't successfully delete the DATA component, set the task to be retried later: see above
File datafile = new File(desc.filenameFor(Component.DATA));
if (!datafile.delete())
{
logger.error("Unable to delete {} (it will be removed on server restart; we'll also retry after GC)", datafile);
failedTasks.add(this);
return;
}
// let the remainder be cleaned up by delete
SSTable.delete(desc, Sets.difference(components, Collections.singleton(Component.DATA)));
if (tracker != null)
tracker.spaceReclaimed(size);
}
/**
* Retry all deletions that failed the first time around (presumably b/c the sstable was still mmap'd.)
* Useful because there are times when we know GC has been invoked; also exposed as an mbean.
*/
public static void rescheduleFailedTasks()
{
for (SSTableDeletingTask task : failedTasks)
{
failedTasks.remove(task);
task.schedule();
}
}
/** for tests */
public static void waitForDeletions()
{
Runnable runnable = new Runnable()
{
public void run()
{
}
};
FBUtilities.waitOnFuture(StorageService.tasks.schedule(runnable, 0, TimeUnit.MILLISECONDS));
}
}
| qinjin/mdtc-cassandra | src/java/org/apache/cassandra/io/sstable/SSTableDeletingTask.java | Java | apache-2.0 | 4,449 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.headwire.aem.tooling.intellij.config;
import com.headwire.aem.tooling.intellij.facet.SlingModuleExtensionProperties.ModuleType;
import com.headwire.aem.tooling.intellij.facet.SlingModuleFacet;
import com.headwire.aem.tooling.intellij.facet.SlingModuleFacetConfiguration;
import com.headwire.aem.tooling.intellij.util.ComponentProvider;
import com.intellij.openapi.components.AbstractProjectComponent;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.idea.maven.project.MavenProject;
import org.jetbrains.idea.maven.project.MavenProjectsManager;
import java.util.ArrayList;
import java.util.List;
/**
* Created by schaefa on 3/18/16.
*/
public class ModuleManagerImpl
extends AbstractProjectComponent
implements ModuleManager
{
private static final Logger LOGGER = Logger.getInstance(ModuleManagerImpl.class);
private ServerConfigurationManager serverConfigurationManager;
protected ModuleManagerImpl(Project project) {
super(project);
}
@Override
public void projectOpened() {
}
@Override
public void projectClosed() {
}
@Override
public void initComponent() {
serverConfigurationManager = ComponentProvider.getComponent(ServerConfigurationManager.class);
}
@Override
public void disposeComponent() {
serverConfigurationManager = null;
}
@NotNull
@Override
public String getComponentName() {
return ModuleManager.class.getName();
}
@Override
public ServerConfiguration.Module getSCM(@NotNull UnifiedModule unifiedModule, @NotNull ServerConfiguration serverConfiguration) {
return new InstanceImpl(myProject, serverConfiguration).findModule(unifiedModule);
}
public MavenProject getMavenProject(@NotNull UnifiedModule unifiedModule) {
if(unifiedModule.isMavenBased()) {
return ((UnifiedModuleImpl) unifiedModule).mavenProject;
}
return null;
}
@Override
public UnifiedModule getUnifiedModule(@NotNull ServerConfiguration.Module scm) {
return scm.getUnifiedModule();
}
@Override
public List<UnifiedModule> getUnifiedModules(@NotNull ServerConfiguration serverConfiguration) {
return getUnifiedModules(serverConfiguration, false);
}
@Override
public List<UnifiedModule> getUnifiedModules(@NotNull ServerConfiguration serverConfiguration, boolean force) {
return new InstanceImpl(myProject, serverConfiguration).getUnifiedModules(force);
}
public static class InstanceImpl {
ServerConfiguration serverConfiguration;
Project project;
public InstanceImpl(@NotNull Project project, @NotNull ServerConfiguration serverConfiguration) {
this.project = project;
this.serverConfiguration = serverConfiguration;
}
@NotNull
public ServerConfiguration getServerConfiguration() {
return serverConfiguration;
}
@NotNull
public Project getProject() {
return project;
}
public ServerConfiguration.Module findModule(@NotNull UnifiedModule unifiedModule) {
return serverConfiguration.obtainModuleByName(unifiedModule.getName());
}
@NotNull
public List<UnifiedModule> getUnifiedModules(boolean force) {
List<UnifiedModule> ret = new ArrayList<UnifiedModule>();
if(!force && serverConfiguration.isBound()) {
LOGGER.debug("Get Unified Modules, not forced and is bound");
for(ServerConfiguration.Module module: serverConfiguration.getModuleList()) {
LOGGER.debug("Get Unified Modules, add unified module: ", module.getUnifiedModule().getName());
ret.add(module.getUnifiedModule());
}
} else {
Module[] modules = com.intellij.openapi.module.ModuleManager.getInstance(project).getModules();
MavenProjectsManager mavenProjectsManager = MavenProjectsManager.getInstance(project);
List<MavenProject> mavenProjects = mavenProjectsManager.getNonIgnoredProjects();
for(Module module : modules) {
LOGGER.debug("Get Unified Modules, handle module: ", module.getName());
if(!force) {
// First look for a Server Configuration Module with that Module in the Module Context and see if it is bound
// (If found then this is most likely)
ServerConfiguration.Module scm = serverConfiguration.obtainModuleByName(module.getName());
LOGGER.debug("Get Unified Modules, add unforced module (scm, name, is bound): ",
scm, scm != null ? scm.getName() : "null",
scm != null ? scm.isBound() : "null"
);
if(scm != null && scm.isBound()) {
ret.add(scm.getUnifiedModule());
// We found our Module so go to the next
continue;
}
}
SlingModuleFacet slingModuleFacet = SlingModuleFacet.getFacetByModule(module);
// Find a corresponding Maven Project
UnifiedModule unifiedModule = null;
for(MavenProject mavenProject : mavenProjects) {
LOGGER.debug("Get Unified Modules, handled Maven project: ",
mavenProject != null ?
mavenProject.getName() : "null"
);
if(!"pom".equalsIgnoreCase(mavenProject.getPackaging())) {
// Use the Parent of the Module and Maven Pom File as they should be in the same folder
//AS TODO: We might want to check if one is the child folder of the other instead being in the same
VirtualFile moduleFile = module.getModuleFile();
if(moduleFile == null) {
// Temporary issue where the IML file is not found by the Virtual File System
// Fix: get the path, remove the IML file and find the Virtual File with that folder
String filePath = module.getModuleFilePath();
LOGGER.debug("Get Unified Modules, Maven project file path: ", filePath);
if(filePath != null) {
int index = filePath.lastIndexOf("/");
if(index > 0 && index < filePath.length() - 2) {
filePath = filePath.substring(0, index);
moduleFile = project.getBaseDir().getFileSystem().findFileByPath(filePath);
LOGGER.debug("Get Unified Modules, Maven project module file: ", moduleFile);
}
}
}
if(moduleFile != null) {
VirtualFile moduleFolder = moduleFile.getParent();
VirtualFile mavenFolder = mavenProject.getFile().getParent();
if(moduleFolder.equals(mavenFolder)) {
unifiedModule = new UnifiedModuleImpl(mavenProject, module);
LOGGER.debug("Get Unified Modules, Maven project module unified module: ", unifiedModule.getName());
break;
}
}
}
}
if(unifiedModule != null) {
if(unifiedModule.isOSGiBundle()) {
if(slingModuleFacet != null) {
LOGGER.debug("Get Unified Modules, check OSGi");
SlingModuleFacetConfiguration slingModuleFacetConfiguration = slingModuleFacet.getConfiguration();
LOGGER.debug("Get Unified Modules, sling module facet (fact, facet conf): ", slingModuleFacet, slingModuleFacetConfiguration);
if(slingModuleFacetConfiguration.getModuleType() != ModuleType.bundle) {
//AS TODO: Show an alert that Maven Module and Sling Facet Module type od not match
LOGGER.debug("Get Unified Modules, not a maven bundle -> ignore");
continue;
} else {
if(slingModuleFacetConfiguration.getOsgiSymbolicName().length() == 0) {
//AS TODO: Show an alert that no Symbolic Name is provided
LOGGER.debug("Get Unified Modules, no Symbolic Name -> ignore");
continue;
}
if(slingModuleFacetConfiguration.isIgnoreMaven()) {
if(slingModuleFacetConfiguration.getOsgiVersion().length() == 0) {
//AS TODO: Show an alert that no Version is provided
LOGGER.debug("Get Unified Modules, no OSGi Version -> ignore");
continue;
}
if(slingModuleFacetConfiguration.getOsgiJarFileName().length() == 0) {
//AS TODO: Show an alert that no Jar File Name is provided
LOGGER.debug("Get Unified Modules, no OSGi Jar File Name -> ignore");
continue;
}
}
}
}
} else if(unifiedModule.isContent()) {
if(slingModuleFacet != null) {
LOGGER.debug("Get Unified Modules, check Content");
if(slingModuleFacet.getConfiguration().getModuleType() != ModuleType.content) {
//AS TODO: Warn about the miss configuration but proceed
LOGGER.debug("Get Unified Modules, not a Maven content -> ignore");
continue;
} else {
unifiedModule = new UnifiedModuleImpl(module);
}
}
}
} else {
if(slingModuleFacet != null) {
LOGGER.debug("Get Unified Modules, check others");
if(slingModuleFacet.getConfiguration().getModuleType() != ModuleType.excluded) {
unifiedModule = new UnifiedModuleImpl(module);
}
}
}
if(unifiedModule != null) {
LOGGER.debug("Get Unified Modules, finally add unified module to response: ", unifiedModule.getName());
ret.add(unifiedModule);
// Bind the Server Configuration Module with the Module Context
ServerConfiguration.Module serverConfigurationModule = serverConfiguration.obtainModuleByName(unifiedModule.getName());
if(serverConfigurationModule == null) {
LOGGER.debug("Get Unified Modules, add module to server configuration: ", unifiedModule.getName());
serverConfiguration.addModule(project, unifiedModule);
} else {
LOGGER.debug("Get Unified Modules, rebind module with server configuration: ", unifiedModule.getName());
serverConfigurationModule.rebind(project, unifiedModule);
}
}
}
}
return ret;
}
}
}
| headwirecom/aem-ide-tooling-4-intellij | src/main/java/com/headwire/aem/tooling/intellij/config/ModuleManagerImpl.java | Java | apache-2.0 | 13,569 |
package minefantasy.mf2.api.knowledge.client;
import org.lwjgl.opengl.GL11;
import minefantasy.mf2.api.helpers.RenderHelper;
import minefantasy.mf2.api.helpers.TextureHelperMF;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.util.StatCollector;
public class EntryPageImage extends EntryPage
{
private Minecraft mc = Minecraft.getMinecraft();
private String[] paragraphs;
/**
* Recommend size: 48x48
*/
private String image;
private int[] sizes;
public EntryPageImage(String tex, String... paragraphs)
{
this(tex, 128, 128, paragraphs);
}
public EntryPageImage(String tex, int width, int height, String... paragraphs)
{
this.paragraphs = paragraphs;
this.image = tex;
this.sizes = new int[]{width, height};
}
@Override
public void render(GuiScreen parent, int x, int y, float f, int posX, int posY, boolean onTick)
{
String text = "";
for(String s: paragraphs)
{
text += StatCollector.translateToLocal(s);
text += "\n\n";
}
mc.fontRenderer.drawSplitString(text, posX+14, posY+117, 117, 0);
}
@Override
public void preRender(GuiScreen parent, int x, int y, float f, int posX, int posY, boolean onTick)
{
mc.renderEngine.bindTexture(TextureHelperMF.getResource(image));
RenderHelper.drawTexturedModalRect(posX+14, posY+8, 2, 0, 0, sizes[0], sizes[1], 1F/(float)sizes[0], 1F/(float)sizes[1]);
}
}
| AnonymousProductions/MineFantasy2 | src/main/java/minefantasy/mf2/api/knowledge/client/EntryPageImage.java | Java | apache-2.0 | 1,405 |
package org.kymjs.aframe.plugin.example;
import org.kymjs.aframe.plugin.service.CJService;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
/**
* 作为插件Service必须继承CJService
*/
public class TestBindService extends CJService {
public class ServiceHolder extends Binder {
public TestBindService create() {
return TestBindService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
super.onBind(intent);
return new ServiceHolder();
}
public void show() {
Log.i("debug", "bind Service success!");
Toast.makeText(that, "bind服务启动成功", Toast.LENGTH_SHORT).show();
}
}
| geniusgithub/KJFrameForAndroid | PluginExample/src/org/kymjs/aframe/plugin/example/TestBindService.java | Java | apache-2.0 | 809 |
package org.testng.xml;
import static org.testng.internal.Utils.isStringBlank;
import org.testng.ITestObjectFactory;
import org.testng.TestNGException;
import org.testng.collections.Lists;
import org.testng.collections.Maps;
import org.testng.internal.RuntimeBehavior;
import org.testng.internal.Utils;
import org.testng.log4testng.Logger;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Stack;
/**
* Suite definition parser utility.
*
* @author Cedric Beust
* @author <a href='mailto:the_mindstorm@evolva.ro'>Alexandru Popescu</a>
*/
public class TestNGContentHandler extends DefaultHandler {
private XmlSuite m_currentSuite = null;
private XmlTest m_currentTest = null;
private List<String> m_currentDefines = null;
private List<String> m_currentRuns = null;
private List<XmlClass> m_currentClasses = null;
private int m_currentTestIndex = 0;
private int m_currentClassIndex = 0;
private int m_currentIncludeIndex = 0;
private List<XmlPackage> m_currentPackages = null;
private XmlPackage m_currentPackage = null;
private List<XmlSuite> m_suites = Lists.newArrayList();
private XmlGroups m_currentGroups = null;
private List<String> m_currentIncludedGroups = null;
private List<String> m_currentExcludedGroups = null;
private Map<String, String> m_currentTestParameters = null;
private Map<String, String> m_currentSuiteParameters = null;
private Map<String, String> m_currentClassParameters = null;
private Include m_currentInclude;
private List<String> m_currentMetaGroup = null;
private String m_currentMetaGroupName;
enum Location {
SUITE,
TEST,
CLASS,
INCLUDE,
EXCLUDE
}
private Stack<Location> m_locations = new Stack<>();
private XmlClass m_currentClass = null;
private ArrayList<XmlInclude> m_currentIncludedMethods = null;
private List<String> m_currentExcludedMethods = null;
private ArrayList<XmlMethodSelector> m_currentSelectors = null;
private XmlMethodSelector m_currentSelector = null;
private String m_currentLanguage = null;
private String m_currentExpression = null;
private List<String> m_suiteFiles = Lists.newArrayList();
private boolean m_enabledTest;
private List<String> m_listeners;
private String m_fileName;
private boolean m_loadClasses;
private boolean m_validate = false;
private boolean m_hasWarn = false;
public TestNGContentHandler(String fileName, boolean loadClasses) {
m_fileName = fileName;
m_loadClasses = loadClasses;
}
/*
* (non-Javadoc)
*
* @see org.xml.sax.EntityResolver#resolveEntity(java.lang.String,
* java.lang.String)
*/
@Override
public InputSource resolveEntity(String systemId, String publicId)
throws IOException, SAXException {
if (Parser.isUnRecognizedPublicId(publicId)) {
//The Url is not TestNG recognized
boolean isHttps = publicId != null && publicId.trim().toLowerCase().startsWith("https");
if (isHttps || RuntimeBehavior.useHttpUrlForDtd()) {
return super.resolveEntity(systemId, publicId);
} else {
String msg = "TestNG by default disables loading DTD from unsecure Urls. " +
"If you need to explicitly load the DTD from a http url, please do so " +
"by using the JVM argument [-D" + RuntimeBehavior.TESTNG_USE_UNSECURE_URL + "=true]";
throw new TestNGException(msg);
}
}
m_validate = true;
InputStream is = loadDtdUsingClassLoader();
if (is != null) {
return new InputSource(is);
}
System.out.println(
"WARNING: couldn't find in classpath "
+ publicId
+ "\n"
+ "Fetching it from " + Parser.HTTPS_TESTNG_DTD_URL);
return super.resolveEntity(systemId, Parser.HTTPS_TESTNG_DTD_URL);
}
private InputStream loadDtdUsingClassLoader() {
InputStream is = getClass().getClassLoader().getResourceAsStream(Parser.TESTNG_DTD);
if (is != null) {
return is;
}
return Thread.currentThread().getContextClassLoader().getResourceAsStream(Parser.TESTNG_DTD);
}
/** Parse <suite-file> */
private void xmlSuiteFile(boolean start, Attributes attributes) {
if (start) {
String path = attributes.getValue("path");
pushLocation(Location.SUITE);
m_suiteFiles.add(path);
} else {
m_currentSuite.setSuiteFiles(m_suiteFiles);
popLocation();
}
}
/** Parse <suite> */
private void xmlSuite(boolean start, Attributes attributes) {
if (start) {
pushLocation(Location.SUITE);
String name = attributes.getValue("name");
if (isStringBlank(name)) {
throw new TestNGException("The <suite> tag must define the name attribute");
}
m_currentSuite = new XmlSuite();
m_currentSuite.setFileName(m_fileName);
m_currentSuite.setName(name);
m_currentSuiteParameters = Maps.newHashMap();
String verbose = attributes.getValue("verbose");
if (null != verbose) {
m_currentSuite.setVerbose(Integer.parseInt(verbose));
}
String jUnit = attributes.getValue("junit");
if (null != jUnit) {
m_currentSuite.setJUnit(Boolean.valueOf(jUnit));
}
String parallel = attributes.getValue("parallel");
if (parallel != null) {
XmlSuite.ParallelMode mode = XmlSuite.ParallelMode.getValidParallel(parallel);
if (mode != null) {
m_currentSuite.setParallel(mode);
} else {
Utils.log(
"Parser",
1,
"[WARN] Unknown value of attribute 'parallel' at suite level: '" + parallel + "'.");
}
}
String parentModule = attributes.getValue("parent-module");
if (parentModule != null) {
m_currentSuite.setParentModule(parentModule);
}
String guiceStage = attributes.getValue("guice-stage");
if (guiceStage != null) {
m_currentSuite.setGuiceStage(guiceStage);
}
XmlSuite.FailurePolicy configFailurePolicy =
XmlSuite.FailurePolicy.getValidPolicy(attributes.getValue("configfailurepolicy"));
if (null != configFailurePolicy) {
m_currentSuite.setConfigFailurePolicy(configFailurePolicy);
}
String groupByInstances = attributes.getValue("group-by-instances");
if (groupByInstances != null) {
m_currentSuite.setGroupByInstances(Boolean.valueOf(groupByInstances));
}
String skip = attributes.getValue("skipfailedinvocationcounts");
if (skip != null) {
m_currentSuite.setSkipFailedInvocationCounts(Boolean.valueOf(skip));
}
String threadCount = attributes.getValue("thread-count");
if (null != threadCount) {
m_currentSuite.setThreadCount(Integer.parseInt(threadCount));
}
String dataProviderThreadCount = attributes.getValue("data-provider-thread-count");
if (null != dataProviderThreadCount) {
m_currentSuite.setDataProviderThreadCount(Integer.parseInt(dataProviderThreadCount));
}
String timeOut = attributes.getValue("time-out");
if (null != timeOut) {
m_currentSuite.setTimeOut(timeOut);
}
String objectFactory = attributes.getValue("object-factory");
if (null != objectFactory && m_loadClasses) {
try {
m_currentSuite.setObjectFactory(
(ITestObjectFactory) Class.forName(objectFactory).newInstance());
} catch (Exception e) {
Utils.log(
"Parser",
1,
"[ERROR] Unable to create custom object factory '" + objectFactory + "' :" + e);
}
}
String preserveOrder = attributes.getValue("preserve-order");
if (preserveOrder != null) {
m_currentSuite.setPreserveOrder(Boolean.valueOf(preserveOrder));
}
String allowReturnValues = attributes.getValue("allow-return-values");
if (allowReturnValues != null) {
m_currentSuite.setAllowReturnValues(Boolean.valueOf(allowReturnValues));
}
} else {
m_currentSuite.setParameters(m_currentSuiteParameters);
m_suites.add(m_currentSuite);
m_currentSuiteParameters = null;
popLocation();
}
}
/** Parse <define> */
private void xmlDefine(boolean start, Attributes attributes) {
if (start) {
String name = attributes.getValue("name");
m_currentDefines = Lists.newArrayList();
m_currentMetaGroup = Lists.newArrayList();
m_currentMetaGroupName = name;
} else {
if (m_currentTest != null) {
m_currentTest.addMetaGroup(m_currentMetaGroupName, m_currentMetaGroup);
} else {
XmlDefine define = new XmlDefine();
define.setName(m_currentMetaGroupName);
define.getIncludes().addAll(m_currentMetaGroup);
m_currentGroups.addDefine(define);
}
m_currentDefines = null;
}
}
/** Parse <script> */
private void xmlScript(boolean start, Attributes attributes) {
if (start) {
m_currentLanguage = attributes.getValue("language");
m_currentExpression = "";
} else {
XmlScript script = new XmlScript();
script.setExpression(m_currentExpression);
script.setLanguage(m_currentLanguage);
m_currentSelector.setScript(script);
if (m_locations.peek() == Location.TEST) {
m_currentTest.setScript(script);
}
m_currentLanguage = null;
m_currentExpression = null;
}
}
/** Parse <test> */
private void xmlTest(boolean start, Attributes attributes) {
if (start) {
m_currentTest = new XmlTest(m_currentSuite, m_currentTestIndex++);
pushLocation(Location.TEST);
m_currentTestParameters = Maps.newHashMap();
final String testName = attributes.getValue("name");
if (isStringBlank(testName)) {
throw new TestNGException("The <test> tag must define the name attribute");
}
m_currentTest.setName(attributes.getValue("name"));
String verbose = attributes.getValue("verbose");
if (null != verbose) {
m_currentTest.setVerbose(Integer.parseInt(verbose));
}
String jUnit = attributes.getValue("junit");
if (null != jUnit) {
m_currentTest.setJUnit(Boolean.valueOf(jUnit));
}
String skip = attributes.getValue("skipfailedinvocationcounts");
if (skip != null) {
m_currentTest.setSkipFailedInvocationCounts(Boolean.valueOf(skip));
}
String groupByInstances = attributes.getValue("group-by-instances");
if (groupByInstances != null) {
m_currentTest.setGroupByInstances(Boolean.valueOf(groupByInstances));
}
String preserveOrder = attributes.getValue("preserve-order");
if (preserveOrder != null) {
m_currentTest.setPreserveOrder(Boolean.valueOf(preserveOrder));
}
String parallel = attributes.getValue("parallel");
if (parallel != null) {
XmlSuite.ParallelMode mode = XmlSuite.ParallelMode.getValidParallel(parallel);
if (mode != null) {
m_currentTest.setParallel(mode);
} else {
Utils.log(
"Parser",
1,
"[WARN] Unknown value of attribute 'parallel' for test '"
+ m_currentTest.getName()
+ "': '"
+ parallel
+ "'");
}
}
String threadCount = attributes.getValue("thread-count");
if (null != threadCount) {
m_currentTest.setThreadCount(Integer.parseInt(threadCount));
}
String timeOut = attributes.getValue("time-out");
if (null != timeOut) {
m_currentTest.setTimeOut(Long.parseLong(timeOut));
}
m_enabledTest = true;
String enabledTestString = attributes.getValue("enabled");
if (null != enabledTestString) {
m_enabledTest = Boolean.valueOf(enabledTestString);
}
} else {
if (null != m_currentTestParameters && m_currentTestParameters.size() > 0) {
m_currentTest.setParameters(m_currentTestParameters);
}
if (null != m_currentClasses) {
m_currentTest.setXmlClasses(m_currentClasses);
}
m_currentClasses = null;
m_currentTest = null;
m_currentTestParameters = null;
popLocation();
if (!m_enabledTest) {
List<XmlTest> tests = m_currentSuite.getTests();
tests.remove(tests.size() - 1);
}
}
}
/** Parse <classes> */
public void xmlClasses(boolean start, Attributes attributes) {
if (start) {
m_currentClasses = Lists.newArrayList();
m_currentClassIndex = 0;
} else {
m_currentTest.setXmlClasses(m_currentClasses);
m_currentClasses = null;
}
}
/** Parse <listeners> */
public void xmlListeners(boolean start, Attributes attributes) {
if (start) {
m_listeners = Lists.newArrayList();
} else {
if (null != m_listeners) {
m_currentSuite.setListeners(m_listeners);
m_listeners = null;
}
}
}
/** Parse <listener> */
public void xmlListener(boolean start, Attributes attributes) {
if (start) {
String listener = attributes.getValue("class-name");
m_listeners.add(listener);
}
}
/** Parse <packages> */
public void xmlPackages(boolean start, Attributes attributes) {
if (start) {
m_currentPackages = Lists.newArrayList();
} else {
if (null != m_currentPackages) {
Location location = m_locations.peek();
switch (location) {
case TEST:
m_currentTest.setXmlPackages(m_currentPackages);
break;
case SUITE:
m_currentSuite.setXmlPackages(m_currentPackages);
break;
case CLASS:
throw new UnsupportedOperationException("CLASS");
default:
throw new AssertionError("Unexpected value: " + location);
}
}
m_currentPackages = null;
m_currentPackage = null;
}
}
/** Parse <method-selectors> */
public void xmlMethodSelectors(boolean start, Attributes attributes) {
if (start) {
m_currentSelectors = new ArrayList<>();
return;
}
if (m_locations.peek() == Location.TEST) {
m_currentTest.setMethodSelectors(m_currentSelectors);
} else {
m_currentSuite.setMethodSelectors(m_currentSelectors);
}
m_currentSelectors = null;
}
/** Parse <selector-class> */
public void xmlSelectorClass(boolean start, Attributes attributes) {
if (start) {
m_currentSelector.setName(attributes.getValue("name"));
String priority = attributes.getValue("priority");
if (priority == null) {
priority = "0";
}
m_currentSelector.setPriority(Integer.parseInt(priority));
}
}
/** Parse <method-selector> */
public void xmlMethodSelector(boolean start, Attributes attributes) {
if (start) {
m_currentSelector = new XmlMethodSelector();
} else {
m_currentSelectors.add(m_currentSelector);
m_currentSelector = null;
}
}
private void xmlMethod(boolean start) {
if (start) {
m_currentIncludedMethods = new ArrayList<>();
m_currentExcludedMethods = Lists.newArrayList();
m_currentIncludeIndex = 0;
} else {
m_currentClass.setIncludedMethods(m_currentIncludedMethods);
m_currentClass.setExcludedMethods(m_currentExcludedMethods);
m_currentIncludedMethods = null;
m_currentExcludedMethods = null;
}
}
/** Parse <run> */
public void xmlRun(boolean start, Attributes attributes) {
if (start) {
m_currentRuns = Lists.newArrayList();
} else {
if (m_currentTest != null) {
m_currentTest.setIncludedGroups(m_currentIncludedGroups);
m_currentTest.setExcludedGroups(m_currentExcludedGroups);
} else {
m_currentSuite.setIncludedGroups(m_currentIncludedGroups);
m_currentSuite.setExcludedGroups(m_currentExcludedGroups);
}
m_currentRuns = null;
}
}
/** Parse <group> */
public void xmlGroup(boolean start, Attributes attributes) {
if (start) {
m_currentTest.addXmlDependencyGroup(
attributes.getValue("name"), attributes.getValue("depends-on"));
}
}
/** Parse <groups> */
public void xmlGroups(boolean start, Attributes attributes) {
if (start) {
m_currentGroups = new XmlGroups();
m_currentIncludedGroups = Lists.newArrayList();
m_currentExcludedGroups = Lists.newArrayList();
} else {
if (m_currentTest == null) {
m_currentSuite.setGroups(m_currentGroups);
}
m_currentGroups = null;
}
}
/**
* NOTE: I only invoke xml*methods (e.g. xmlSuite()) if I am acting on both the start and the end
* of the tag. This way I can keep the treatment of this tag in one place. If I am only doing
* something when the tag opens, the code is inlined below in the startElement() method.
*/
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) {
if (!m_validate && !m_hasWarn) {
String msg = String.format(
"It is strongly recommended to add "
+ "\"<!DOCTYPE suite SYSTEM \"%s\" >\" at the top of your file, "
+ "otherwise TestNG may fail or not work as expected.", Parser.HTTPS_TESTNG_DTD_URL
);
Logger.getLogger(TestNGContentHandler.class).warn(msg);
m_hasWarn = true;
}
String name = attributes.getValue("name");
// ppp("START ELEMENT uri:" + uri + " sName:" + localName + " qName:" + qName +
// " " + attributes);
if ("suite".equals(qName)) {
xmlSuite(true, attributes);
} else if ("suite-file".equals(qName)) {
xmlSuiteFile(true, attributes);
} else if ("test".equals(qName)) {
xmlTest(true, attributes);
} else if ("script".equals(qName)) {
xmlScript(true, attributes);
} else if ("method-selector".equals(qName)) {
xmlMethodSelector(true, attributes);
} else if ("method-selectors".equals(qName)) {
xmlMethodSelectors(true, attributes);
} else if ("selector-class".equals(qName)) {
xmlSelectorClass(true, attributes);
} else if ("classes".equals(qName)) {
xmlClasses(true, attributes);
} else if ("packages".equals(qName)) {
xmlPackages(true, attributes);
} else if ("listeners".equals(qName)) {
xmlListeners(true, attributes);
} else if ("listener".equals(qName)) {
xmlListener(true, attributes);
} else if ("class".equals(qName)) {
// If m_currentClasses is null, the XML is invalid and SAX
// will complain, but in the meantime, dodge the NPE so SAX
// can finish parsing the file.
if (null != m_currentClasses) {
m_currentClass = new XmlClass(name, m_currentClassIndex++, m_loadClasses);
m_currentClass.setXmlTest(m_currentTest);
m_currentClassParameters = Maps.newHashMap();
m_currentClasses.add(m_currentClass);
pushLocation(Location.CLASS);
}
} else if ("package".equals(qName)) {
if (null != m_currentPackages) {
m_currentPackage = new XmlPackage();
m_currentPackage.setName(name);
m_currentPackages.add(m_currentPackage);
}
} else if ("define".equals(qName)) {
xmlDefine(true, attributes);
} else if ("run".equals(qName)) {
xmlRun(true, attributes);
} else if ("group".equals(qName)) {
xmlGroup(true, attributes);
} else if ("groups".equals(qName)) {
xmlGroups(true, attributes);
} else if ("methods".equals(qName)) {
xmlMethod(true);
} else if ("include".equals(qName)) {
xmlInclude(true, attributes);
} else if ("exclude".equals(qName)) {
xmlExclude(true, attributes);
} else if ("parameter".equals(qName)) {
String value = expandValue(attributes.getValue("value"));
Location location = m_locations.peek();
switch (location) {
case TEST:
m_currentTestParameters.put(name, value);
break;
case SUITE:
m_currentSuiteParameters.put(name, value);
break;
case CLASS:
m_currentClassParameters.put(name, value);
break;
case INCLUDE:
m_currentInclude.parameters.put(name, value);
break;
default:
throw new AssertionError("Unexpected value: " + location);
}
}
}
private static class Include {
String name;
String invocationNumbers;
String description;
Map<String, String> parameters = Maps.newHashMap();
Include(String name, String numbers) {
this.name = name;
this.invocationNumbers = numbers;
}
}
private void xmlInclude(boolean start, Attributes attributes) {
if (start) {
m_locations.push(Location.INCLUDE);
m_currentInclude =
new Include(attributes.getValue("name"), attributes.getValue("invocation-numbers"));
m_currentInclude.description = attributes.getValue("description");
} else {
String name = m_currentInclude.name;
if (null != m_currentIncludedMethods) {
String in = m_currentInclude.invocationNumbers;
XmlInclude include;
if (!Utils.isStringEmpty(in)) {
include = new XmlInclude(name, stringToList(in), m_currentIncludeIndex++);
} else {
include = new XmlInclude(name, m_currentIncludeIndex++);
}
for (Map.Entry<String, String> entry : m_currentInclude.parameters.entrySet()) {
include.addParameter(entry.getKey(), entry.getValue());
}
include.setDescription(m_currentInclude.description);
m_currentIncludedMethods.add(include);
} else if (null != m_currentDefines) {
m_currentMetaGroup.add(name);
} else if (null != m_currentRuns) {
m_currentIncludedGroups.add(name);
} else if (null != m_currentPackage) {
m_currentPackage.getInclude().add(name);
}
popLocation();
m_currentInclude = null;
}
}
private void xmlExclude(boolean start, Attributes attributes) {
if (start) {
m_locations.push(Location.EXCLUDE);
String name = attributes.getValue("name");
if (null != m_currentExcludedMethods) {
m_currentExcludedMethods.add(name);
} else if (null != m_currentRuns) {
m_currentExcludedGroups.add(name);
} else if (null != m_currentPackage) {
m_currentPackage.getExclude().add(name);
}
} else {
popLocation();
}
}
private void pushLocation(Location l) {
m_locations.push(l);
}
private void popLocation() {
m_locations.pop();
}
private List<Integer> stringToList(String in) {
String[] numbers = in.split(" ");
List<Integer> result = Lists.newArrayList();
for (String n : numbers) {
result.add(Integer.parseInt(n));
}
return result;
}
@Override
public void endElement(String uri, String localName, String qName) {
if ("suite".equals(qName)) {
xmlSuite(false, null);
} else if ("suite-file".equals(qName)) {
xmlSuiteFile(false, null);
} else if ("test".equals(qName)) {
xmlTest(false, null);
} else if ("define".equals(qName)) {
xmlDefine(false, null);
} else if ("run".equals(qName)) {
xmlRun(false, null);
} else if ("groups".equals(qName)) {
xmlGroups(false, null);
} else if ("methods".equals(qName)) {
xmlMethod(false);
} else if ("classes".equals(qName)) {
xmlClasses(false, null);
} else if ("packages".equals(qName)) {
xmlPackages(false, null);
} else if ("class".equals(qName)) {
m_currentClass.setParameters(m_currentClassParameters);
m_currentClassParameters = null;
popLocation();
} else if ("listeners".equals(qName)) {
xmlListeners(false, null);
} else if ("method-selector".equals(qName)) {
xmlMethodSelector(false, null);
} else if ("method-selectors".equals(qName)) {
xmlMethodSelectors(false, null);
} else if ("selector-class".equals(qName)) {
xmlSelectorClass(false, null);
} else if ("script".equals(qName)) {
xmlScript(false, null);
} else if ("include".equals(qName)) {
xmlInclude(false, null);
} else if ("exclude".equals(qName)) {
xmlExclude(false, null);
}
}
@Override
public void error(SAXParseException e) throws SAXException {
if (m_validate) {
throw e;
}
}
private boolean areWhiteSpaces(char[] ch, int start, int length) {
for (int i = start; i < start + length; i++) {
char c = ch[i];
if (c != '\n' && c != '\t' && c != ' ') {
return false;
}
}
return true;
}
@Override
public void characters(char[] ch, int start, int length) {
if (null != m_currentLanguage && !areWhiteSpaces(ch, start, length)) {
m_currentExpression += new String(ch, start, length);
}
}
public XmlSuite getSuite() {
return m_currentSuite;
}
private static String expandValue(String value) {
StringBuilder result = null;
int startIndex;
int endIndex;
int startPosition = 0;
String property;
while ((startIndex = value.indexOf("${", startPosition)) > -1
&& (endIndex = value.indexOf("}", startIndex + 3)) > -1) {
property = value.substring(startIndex + 2, endIndex);
if (result == null) {
result = new StringBuilder(value.substring(startPosition, startIndex));
} else {
result.append(value, startPosition, startIndex);
}
String propertyValue = System.getProperty(property);
if (propertyValue == null) {
propertyValue = System.getenv(property);
}
if (propertyValue != null) {
result.append(propertyValue);
} else {
result.append("${");
result.append(property);
result.append("}");
}
startPosition = startIndex + 3 + property.length();
}
if (result != null) {
result.append(value.substring(startPosition));
return result.toString();
} else {
return value;
}
}
}
| missedone/testng | src/main/java/org/testng/xml/TestNGContentHandler.java | Java | apache-2.0 | 26,284 |
package org.jdesktop.core.animation.timing;
import self.philbrown.javaQuery.Modified;
import com.surelogic.ThreadSafe;
/**
* Implements the {@link TimingTarget} interface, providing stubs for all timing
* target methods. Subclasses may extend this adapter rather than implementing
* the {@link TimingTarget} interface if they only care about a subset of the
* events provided. For example, sequencing animations may only require
* monitoring the {@link TimingTarget#end} method, so subclasses of this adapter
* may ignore the other methods such as timingEvent.
* <p>
* This class provides a useful "debug" name via {@link #setDebugName(String)}
* and {@link #getDebugName()}. The debug name is also output by
* {@link #toString()}. This feature is intended to aid debugging.
*
* @author Chet Haase
* @author Tim Halloran
* @author Phil Brown
*/
@Modified(author="Phil Brown", summary="Cleaned up and added inheritDocs documentation to improve javadocs.")
@ThreadSafe(implementationOnly = true)
public class TimingTargetAdapter implements TimingTarget {
/**
* {@inheritDoc}
*/
@Override
public void begin(Animator source) {
}
/**
* {@inheritDoc}
*/
@Override
public void end(Animator source) {
}
/**
* {@inheritDoc}
*/
@Override
public void cancel(Animator source) {
}
/**
* {@inheritDoc}
*/
@Override
public void repeat(Animator source) {
}
/**
* {@inheritDoc}
*/
@Override
public void reverse(Animator source) {
}
/**
* {@inheritDoc}
*/
@Override
public void timingEvent(Animator source, double fraction) {
}
private volatile String f_debugName = null;
public final void setDebugName(String name) {
f_debugName = name;
}
public final String getDebugName() {
return f_debugName;
}
@Override
public String toString() {
final String debugName = f_debugName;
final StringBuilder b = new StringBuilder();
b.append(getClass().getSimpleName()).append('@');
b.append(debugName != null ? debugName : Integer.toHexString(hashCode()));
return b.toString();
}
}
| phil-brown/javaQuery | src/org/jdesktop/core/animation/timing/TimingTargetAdapter.java | Java | apache-2.0 | 2,073 |
<?php
declare(strict_types=1);
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StoreNotificationTemplateRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string,array<string>>
*/
public function rules(): array
{
return [
'name' => [
'required',
'string',
],
'subject' => [
'required',
'string',
],
'body_markdown' => [
'required',
],
];
}
/**
* Get the error messages for the defined validation rules.
*
* @return array<string,string>
*/
public function messages(): array
{
return [];
}
}
| RoboJackets/apiary | app/Http/Requests/StoreNotificationTemplateRequest.php | PHP | apache-2.0 | 982 |
package com.praetoriandroid.cameraremote;
public class ServiceNotSupportedException extends RpcException {
private static final long serialVersionUID = -4740335873344202486L;
public ServiceNotSupportedException(String serviceType) {
super(serviceType);
}
}
| praetoriandroid/sony-camera-remote-java | sony-camera-remote-lib/src/main/java/com/praetoriandroid/cameraremote/ServiceNotSupportedException.java | Java | apache-2.0 | 279 |
"""Test the TcEx Batch Module."""
# third-party
import pytest
# pylint: disable=no-self-use
class TestIndicator3:
"""Test the TcEx Batch Module."""
def setup_class(self):
"""Configure setup before all tests."""
@pytest.mark.parametrize(
'indicator,description,label,tag',
[
('3.33.33.1', 'Example #1', 'PYTEST1', 'PyTest1'),
('3.33.33.2', 'Example #2', 'PYTEST2', 'PyTest2'),
('3.33.33.3', 'Example #3', 'PYTEST3', 'PyTest3'),
('3.33.33.4', 'Example #4', 'PYTEST4', 'PyTest4'),
],
)
def test_address(self, indicator, description, label, tag, tcex):
"""Test address creation"""
batch = tcex.batch(owner='TCI')
xid = batch.generate_xid(['pytest', 'address', indicator])
ti = batch.add_indicator(
{
'type': 'Address',
'rating': 5.00,
'confidence': 100,
'summary': indicator,
'xid': xid,
'attribute': [{'displayed': True, 'type': 'Description', 'value': description}],
'securityLabel': [
{'color': 'ffc0cb', 'name': label, 'description': 'Pytest Label Description'}
],
'tag': [{'name': tag}],
}
)
batch.save(ti)
batch_status = batch.submit_all()
assert batch_status[0].get('status') == 'Completed'
assert batch_status[0].get('successCount') == 1
@pytest.mark.parametrize(
'indicator,description,label,tag',
[
('pytest-email_address-i3-001@test.com', 'Example #1', 'PYTEST:1', 'PyTest1'),
('pytest-email_address-i3-002@test.com', 'Example #2', 'PYTEST:2', 'PyTest2'),
('pytest-email_address-i3-003@test.com', 'Example #3', 'PYTEST:3', 'PyTest3'),
('pytest-email_address-i3-004@test.com', 'Example #4', 'PYTEST:4', 'PyTest4'),
],
)
def test_email_address(self, indicator, description, label, tag, tcex):
"""Test email_address creation"""
batch = tcex.batch(owner='TCI')
xid = batch.generate_xid(['pytest', 'email_address', indicator])
ti = batch.add_indicator(
{
'type': 'EmailAddress',
'rating': 5.00,
'confidence': 100,
'summary': indicator,
'xid': xid,
'attribute': [{'displayed': True, 'type': 'Description', 'value': description}],
'securityLabel': [
{'color': 'ffc0cb', 'name': label, 'description': 'Pytest Label Description'}
],
'tag': [{'name': tag}],
}
)
batch.save(ti)
batch_status = batch.submit_all()
assert batch_status[0].get('status') == 'Completed'
assert batch_status[0].get('successCount') == 1
@pytest.mark.parametrize(
'md5,sha1,sha256,description,label,tag',
[
('a3', 'a3', 'a3', 'Example #1', 'PYTEST:1', 'PyTest1'),
('b3', 'b3', 'b3', 'Example #2', 'PYTEST:2', 'PyTest2'),
('c3', 'c3', 'c3', 'Example #3', 'PYTEST:3', 'PyTest3'),
('d3', 'd3', 'd3', 'Example #4', 'PYTEST:4', 'PyTest4'),
],
)
def test_file(self, md5, sha1, sha256, description, label, tag, tcex):
"""Test file creation"""
batch = tcex.batch(owner='TCI')
xid = batch.generate_xid(['pytest', 'file', md5, sha1, sha256])
ti = batch.add_indicator(
{
'type': 'File',
'rating': 5.00,
'confidence': 100,
'summary': f'{md5 * 16} : {sha1 * 20} : {sha256 * 32}',
'xid': xid,
'attribute': [{'displayed': True, 'type': 'Description', 'value': description}],
'securityLabel': [
{'color': 'ffc0cb', 'name': label, 'description': 'Pytest Label Description'}
],
'tag': [{'name': tag}],
}
)
batch.save(ti)
batch_status = batch.submit_all()
assert batch_status[0].get('status') == 'Completed'
assert batch_status[0].get('successCount') == 1
@pytest.mark.parametrize(
'indicator,description,label,tag',
[
('pytest-host-i3-001.com', 'Example #1', 'PYTEST:1', 'PyTest1'),
('pytest-host-i3-002.com', 'Example #2', 'PYTEST:2', 'PyTest2'),
('pytest-host-i3-003.com', 'Example #3', 'PYTEST:3', 'PyTest3'),
('pytest-host-i3-004.com', 'Example #4', 'PYTEST:4', 'PyTest4'),
],
)
def test_host(self, indicator, description, label, tag, tcex):
"""Test host creation"""
batch = tcex.batch(owner='TCI')
xid = batch.generate_xid(['pytest', 'host', indicator])
ti = batch.add_indicator(
{
'type': 'Host',
'rating': 5.00,
'confidence': 100,
'summary': indicator,
'xid': xid,
'attribute': [{'displayed': True, 'type': 'Description', 'value': description}],
'securityLabel': [
{'color': 'ffc0cb', 'name': label, 'description': 'Pytest Label Description'}
],
'tag': [{'name': tag}],
}
)
batch.save(ti)
batch_status = batch.submit_all()
assert batch_status[0].get('status') == 'Completed'
assert batch_status[0].get('successCount') == 1
@pytest.mark.parametrize(
'indicator,description,label,tag',
[
('https://pytest-url-i3-001.com', 'Example #1', 'PYTEST:1', 'PyTest1'),
('https://pytest-url-i3-002.com', 'Example #2', 'PYTEST:2', 'PyTest2'),
('https://pytest-url-i3-003.com', 'Example #3', 'PYTEST:3', 'PyTest3'),
('https://pytest-url-i3-004.com', 'Example #4', 'PYTEST:4', 'PyTest4'),
],
)
def test_url(self, indicator, description, label, tag, tcex):
"""Test url creation"""
batch = tcex.batch(owner='TCI')
xid = batch.generate_xid(['pytest', 'url', indicator])
ti = batch.add_indicator(
{
'type': 'Url',
'rating': 5.00,
'confidence': 100,
'summary': indicator,
'xid': xid,
'attribute': [{'displayed': True, 'type': 'Description', 'value': description}],
'securityLabel': [
{'color': 'ffc0cb', 'name': label, 'description': 'Pytest Label Description'}
],
'tag': [{'name': tag}],
}
)
batch.save(ti)
batch_status = batch.submit_all()
assert batch_status[0].get('status') == 'Completed'
assert batch_status[0].get('successCount') == 1
| kstilwell/tcex | tests/batch/test_indicator_interface_3.py | Python | apache-2.0 | 6,925 |
using java.lang;
using java.util;
using stab.query;
public class ToIntTMap5 {
public static bool test() {
var map1 = new HashMap<Integer, string> { { 1, "V1" }, { 2, "V2" }, { 3, "V3" }};
var list = new ArrayList<string> { "V1", "V2", "V3" };
var key = 1;
var map2 = list.toMap(p => key++);
int i = 0;
foreach (var k in map2.keySet()) {
if (!map1[k].equals(map2.get(k))) {
return false;
}
i++;
}
return map2.size() == 3 && i == 3;
}
}
| monoman/cnatural-language | tests/resources/LibraryTest/sources/ToIntTMap5.stab.cs | C# | apache-2.0 | 467 |
import invocation_pb from '../../api/invocation_pb';
import { State as PageWrapperState } from '../SearchWrapper';
export interface Data {
status: string;
name: string;
labels: string;
date: string;
duration: string;
user: string;
}
export interface Column {
id: 'status' | 'name' | 'labels' | 'date' | 'duration' | 'user';
label: string;
minWidth?: number;
align?: 'right';
}
export interface InvocationTableProps {
invocations: Array<invocation_pb.Invocation>;
pageToken: PageWrapperState['pageToken'];
next: (newQuery: boolean, pageToken: string) => void;
isNextPageLoading: boolean;
tokenID: string;
}
export interface ModalState {
isOpen: boolean;
index: number;
}
export interface HoverState {
isHovered: boolean;
rowIndex: number;
}
| google/resultstoreui | resultstoresearch/client/src/components/InvocationTable/types.ts | TypeScript | apache-2.0 | 821 |
/*
* Copyright 2020 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License, version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package io.netty.example.http2.helloworld.frame.client;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http2.Http2DataFrame;
import io.netty.handler.codec.http2.Http2HeadersFrame;
import io.netty.handler.codec.http2.Http2StreamFrame;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
/**
* Handles HTTP/2 stream frame responses. This is a useful approach if you specifically want to check
* the main HTTP/2 response DATA/HEADERs, but in this example it's used purely to see whether
* our request (for a specific stream id) has had a final response (for that same stream id).
*/
public final class Http2ClientStreamFrameResponseHandler extends SimpleChannelInboundHandler<Http2StreamFrame> {
private final CountDownLatch latch = new CountDownLatch(1);
@Override
protected void channelRead0(ChannelHandlerContext ctx, Http2StreamFrame msg) throws Exception {
System.out.println("Received HTTP/2 'stream' frame: " + msg);
// isEndStream() is not from a common interface, so we currently must check both
if (msg instanceof Http2DataFrame && ((Http2DataFrame) msg).isEndStream()) {
latch.countDown();
} else if (msg instanceof Http2HeadersFrame && ((Http2HeadersFrame) msg).isEndStream()) {
latch.countDown();
}
}
/**
* Waits for the latch to be decremented (i.e. for an end of stream message to be received), or for
* the latch to expire after 5 seconds.
* @return true if a successful HTTP/2 end of stream message was received.
*/
public boolean responseSuccessfullyCompleted() {
try {
return latch.await(5, TimeUnit.SECONDS);
} catch (InterruptedException ie) {
System.err.println("Latch exception: " + ie.getMessage());
return false;
}
}
}
| fenik17/netty | example/src/main/java/io/netty/example/http2/helloworld/frame/client/Http2ClientStreamFrameResponseHandler.java | Java | apache-2.0 | 2,568 |
package cn.brent.console.table;
/**
* <p>
* 实体类-
* </p>
* <p>
* Table: sys_uid_sysid
* </p>
*
* @since 2015-08-18 05:00:27
*/
public class TSysUidSysid {
/** */
public static final String UID = "UID";
/** */
public static final String SYS = "SYS";
/** */
public static final String SysID = "SysID";
/** */
public static final String AddTime = "AddTime";
} | brenthub/brent-console | brent-console-interface/src/main/java/cn/brent/console/table/TSysUidSysid.java | Java | apache-2.0 | 388 |
/**
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.dc.smarteam.test.entity;
import com.fasterxml.jackson.annotation.JsonBackReference;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.Length;
import com.dc.smarteam.common.persistence.TreeEntity;
/**
* 树结构生成Entity
* @author ThinkGem
* @version 2015-04-06
*/
public class TestTree extends TreeEntity<TestTree> {
private static final long serialVersionUID = 1L;
private TestTree parent; // 父级编号
private String parentIds; // 所有父级编号
private String name; // 名称
private Integer sort; // 排序
public TestTree() {
super();
}
public TestTree(String id){
super(id);
}
@JsonBackReference
@NotNull(message="父级编号不能为空")
public TestTree getParent() {
return parent;
}
public void setParent(TestTree parent) {
this.parent = parent;
}
@Length(min=1, max=2000, message="所有父级编号长度必须介于 1 和 2000 之间")
public String getParentIds() {
return parentIds;
}
public void setParentIds(String parentIds) {
this.parentIds = parentIds;
}
@Length(min=1, max=100, message="名称长度必须介于 1 和 100 之间")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@NotNull(message="排序不能为空")
public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
public String getParentId() {
return parent != null && parent.getId() != null ? parent.getId() : "0";
}
} | VincentFxz/EAM | src/main/java/com/dc/smarteam/test/entity/TestTree.java | Java | apache-2.0 | 1,652 |
#include "ContentSearcher.h"
#include "FileNameSearcher.h"
#include "FileSizeSearcher.h"
#include "FileTimeSearcher.h"
#include "Searcher.h"
#include "SearcherFactory.h"
#include "../SearchParameter.h"
Searcher* SearcherFactory::BuildSearcher(const SearchParameter& param)
{
PhaseOneParameter oneParam = *param.phaseOneParam;
Searcher* searcher = new FileNameSearcher(oneParam); // need to build anyhow
if (oneParam.HasSizeConstraint())
{
searcher = new FileSizeSearcher(searcher, oneParam);
}
if (oneParam.HasTimeConstraints())
{
searcher = new FileTimeSearcher(searcher, oneParam);
}
// for performance issue, we should always construct ContentSearcher at last so this content searcher will performed at a minimum time
if (param.PhaseTwoSearchNeeded())
{
searcher = new ContentSearcher(searcher, *param.phaseTwoParam);
}
return searcher;
}
| obarnet/Teste | SearchMonkeySRC/engine/SearcherFactory.cpp | C++ | apache-2.0 | 952 |
from perfrunner.helpers import local
from perfrunner.helpers.cbmonitor import timeit, with_stats
from perfrunner.helpers.profiler import with_profiles
from perfrunner.helpers.worker import java_dcp_client_task
from perfrunner.tests import PerfTest
class DCPThroughputTest(PerfTest):
def _report_kpi(self, time_elapsed: float, clients: int, stream: str):
self.reporter.post(
*self.metrics.dcp_throughput(time_elapsed, clients, stream)
)
@with_stats
@timeit
@with_profiles
def access(self, *args):
username, password = self.cluster_spec.rest_credentials
for target in self.target_iterator:
local.run_dcptest(
host=target.node,
username=username,
password=password,
bucket=target.bucket,
num_items=self.test_config.load_settings.items,
num_connections=self.test_config.dcp_settings.num_connections
)
def warmup(self):
self.remote.stop_server()
self.remote.drop_caches()
return self._warmup()
def _warmup(self):
self.remote.start_server()
for master in self.cluster_spec.masters:
for bucket in self.test_config.buckets:
self.monitor.monitor_warmup(self.memcached, master, bucket)
def run(self):
self.load()
self.wait_for_persistence()
self.check_num_items()
self.compact_bucket()
if self.test_config.dcp_settings.invoke_warm_up:
self.warmup()
time_elapsed = self.access()
self.report_kpi(time_elapsed,
int(self.test_config.java_dcp_settings.clients),
self.test_config.java_dcp_settings.stream)
class JavaDCPThroughputTest(DCPThroughputTest):
def init_java_dcp_client(self):
local.clone_git_repo(repo=self.test_config.java_dcp_settings.repo,
branch=self.test_config.java_dcp_settings.branch)
local.build_java_dcp_client()
@with_stats
@timeit
@with_profiles
def access(self, *args):
for target in self.target_iterator:
local.run_java_dcp_client(
connection_string=target.connection_string,
messages=self.test_config.load_settings.items,
config_file=self.test_config.java_dcp_settings.config,
)
def run(self):
self.init_java_dcp_client()
super().run()
class JavaDCPCollectionThroughputTest(DCPThroughputTest):
def init_java_dcp_clients(self):
if self.worker_manager.is_remote:
self.remote.init_java_dcp_client(repo=self.test_config.java_dcp_settings.repo,
branch=self.test_config.java_dcp_settings.branch,
worker_home=self.worker_manager.WORKER_HOME,
commit=self.test_config.java_dcp_settings.commit)
else:
local.clone_git_repo(repo=self.test_config.java_dcp_settings.repo,
branch=self.test_config.java_dcp_settings.branch,
commit=self.test_config.java_dcp_settings.commit)
local.build_java_dcp_client()
@with_stats
@timeit
@with_profiles
def access(self, *args, **kwargs):
access_settings = self.test_config.access_settings
access_settings.workload_instances = int(self.test_config.java_dcp_settings.clients)
PerfTest.access(self, task=java_dcp_client_task, settings=access_settings)
def run(self):
self.init_java_dcp_clients()
self.load()
self.wait_for_persistence()
self.check_num_items()
self.compact_bucket()
if self.test_config.access_settings.workers > 0:
self.access_bg()
time_elapsed = self.access()
self.report_kpi(time_elapsed,
int(self.test_config.java_dcp_settings.clients),
self.test_config.java_dcp_settings.stream)
| couchbase/perfrunner | perfrunner/tests/dcp.py | Python | apache-2.0 | 4,121 |
package com.lianyu.tech.website.web.controller.verify;
import com.lianyu.tech.core.platform.exception.InvalidRequestException;
import com.lianyu.tech.core.util.StringUtils;
import com.lianyu.tech.website.web.SessionConstants;
import com.lianyu.tech.website.web.SiteContext;
import org.springframework.stereotype.Service;
import javax.inject.Inject;
/**
* @author bowen
*/
@Service
public class VerifyCodeValidator {
@Inject
SiteContext siteContext;
public void setVerifyCode(String code) {
siteContext.addSession(SessionConstants.VERIFY_CODE_IMG, code);
}
public void verify(String code) {
String sessionCode = siteContext.getSession(SessionConstants.VERIFY_CODE_IMG);
if (!StringUtils.hasText(sessionCode)) {
throw new InvalidRequestException("验证码不存在");
}
if (!sessionCode.equalsIgnoreCase(code)) {
throw new InvalidRequestException("验证码不正确");
}
}
}
| howbigbobo/com.lianyu.tech | website/src/main/java/com/lianyu/tech/website/web/controller/verify/VerifyCodeValidator.java | Java | apache-2.0 | 978 |
package metrics
import (
"time"
"github.com/prebid/prebid-server/openrtb_ext"
"github.com/stretchr/testify/mock"
)
// MetricsEngineMock is mock for the MetricsEngine interface
type MetricsEngineMock struct {
mock.Mock
}
// RecordRequest mock
func (me *MetricsEngineMock) RecordRequest(labels Labels) {
me.Called(labels)
}
// RecordConnectionAccept mock
func (me *MetricsEngineMock) RecordConnectionAccept(success bool) {
me.Called(success)
}
// RecordConnectionClose mock
func (me *MetricsEngineMock) RecordConnectionClose(success bool) {
me.Called(success)
}
// RecordImps mock
func (me *MetricsEngineMock) RecordImps(labels ImpLabels) {
me.Called(labels)
}
// RecordRequestTime mock
func (me *MetricsEngineMock) RecordRequestTime(labels Labels, length time.Duration) {
me.Called(labels, length)
}
// RecordStoredDataFetchTime mock
func (me *MetricsEngineMock) RecordStoredDataFetchTime(labels StoredDataLabels, length time.Duration) {
me.Called(labels, length)
}
// RecordStoredDataError mock
func (me *MetricsEngineMock) RecordStoredDataError(labels StoredDataLabels) {
me.Called(labels)
}
// RecordAdapterPanic mock
func (me *MetricsEngineMock) RecordAdapterPanic(labels AdapterLabels) {
me.Called(labels)
}
// RecordAdapterRequest mock
func (me *MetricsEngineMock) RecordAdapterRequest(labels AdapterLabels) {
me.Called(labels)
}
// RecordAdapterConnections mock
func (me *MetricsEngineMock) RecordAdapterConnections(bidderName openrtb_ext.BidderName, connWasReused bool, connWaitTime time.Duration) {
me.Called(bidderName, connWasReused, connWaitTime)
}
// RecordDNSTime mock
func (me *MetricsEngineMock) RecordDNSTime(dnsLookupTime time.Duration) {
me.Called(dnsLookupTime)
}
func (me *MetricsEngineMock) RecordTLSHandshakeTime(tlsHandshakeTime time.Duration) {
me.Called(tlsHandshakeTime)
}
// RecordAdapterBidReceived mock
func (me *MetricsEngineMock) RecordAdapterBidReceived(labels AdapterLabels, bidType openrtb_ext.BidType, hasAdm bool) {
me.Called(labels, bidType, hasAdm)
}
// RecordAdapterPrice mock
func (me *MetricsEngineMock) RecordAdapterPrice(labels AdapterLabels, cpm float64) {
me.Called(labels, cpm)
}
// RecordAdapterTime mock
func (me *MetricsEngineMock) RecordAdapterTime(labels AdapterLabels, length time.Duration) {
me.Called(labels, length)
}
// RecordCookieSync mock
func (me *MetricsEngineMock) RecordCookieSync(status CookieSyncStatus) {
me.Called(status)
}
// RecordSyncerRequest mock
func (me *MetricsEngineMock) RecordSyncerRequest(key string, status SyncerCookieSyncStatus) {
me.Called(key, status)
}
// RecordSetUid mock
func (me *MetricsEngineMock) RecordSetUid(status SetUidStatus) {
me.Called(status)
}
// RecordSyncerSet mock
func (me *MetricsEngineMock) RecordSyncerSet(key string, status SyncerSetUidStatus) {
me.Called(key, status)
}
// RecordStoredReqCacheResult mock
func (me *MetricsEngineMock) RecordStoredReqCacheResult(cacheResult CacheResult, inc int) {
me.Called(cacheResult, inc)
}
// RecordStoredImpCacheResult mock
func (me *MetricsEngineMock) RecordStoredImpCacheResult(cacheResult CacheResult, inc int) {
me.Called(cacheResult, inc)
}
// RecordAccountCacheResult mock
func (me *MetricsEngineMock) RecordAccountCacheResult(cacheResult CacheResult, inc int) {
me.Called(cacheResult, inc)
}
// RecordPrebidCacheRequestTime mock
func (me *MetricsEngineMock) RecordPrebidCacheRequestTime(success bool, length time.Duration) {
me.Called(success, length)
}
// RecordRequestQueueTime mock
func (me *MetricsEngineMock) RecordRequestQueueTime(success bool, requestType RequestType, length time.Duration) {
me.Called(success, requestType, length)
}
// RecordTimeoutNotice mock
func (me *MetricsEngineMock) RecordTimeoutNotice(success bool) {
me.Called(success)
}
// RecordRequestPrivacy mock
func (me *MetricsEngineMock) RecordRequestPrivacy(privacy PrivacyLabels) {
me.Called(privacy)
}
// RecordAdapterGDPRRequestBlocked mock
func (me *MetricsEngineMock) RecordAdapterGDPRRequestBlocked(adapterName openrtb_ext.BidderName) {
me.Called(adapterName)
}
| prebid/prebid-server | metrics/metrics_mock.go | GO | apache-2.0 | 4,060 |
/*
* Copyright 2013 Romain Gilles
*
* 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.javabits.yar;
import java.util.EventListener;
/**
* TODO comment
* Date: 4/2/13
* Time: 10:16 PM
*
* @author Romain Gilles
*/
public interface SupplierListener extends EventListener {
void supplierChanged(SupplierEvent supplierEvent);
}
| javabits/yar | yar-api/src/main/java/org/javabits/yar/SupplierListener.java | Java | apache-2.0 | 886 |
using JetBrains.Annotations;
using JetBrains.Diagnostics;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Daemon;
using JetBrains.ReSharper.Feature.Services.CSharp.ContextActions;
using JetBrains.ReSharper.Plugins.Unity.CSharp.Daemon.Stages.PerformanceCriticalCodeAnalysis.ContextSystem;
using JetBrains.ReSharper.Psi.CSharp.Tree;
using JetBrains.Util;
namespace JetBrains.ReSharper.Plugins.Unity.CSharp.Feature.Services.CallGraph.PerformanceAnalysis
{
public abstract class PerformanceAnalysisContextActionBase: CallGraphContextActionBase
{
[NotNull] protected readonly PerformanceCriticalContextProvider PerformanceContextProvider;
[NotNull] protected readonly ExpensiveInvocationContextProvider ExpensiveContextProvider;
[NotNull] protected readonly SolutionAnalysisService SolutionAnalysisService;
protected PerformanceAnalysisContextActionBase([NotNull] ICSharpContextActionDataProvider dataProvider)
: base(dataProvider)
{
ExpensiveContextProvider = dataProvider.Solution.GetComponent<ExpensiveInvocationContextProvider>().NotNull();
PerformanceContextProvider = dataProvider.Solution.GetComponent<PerformanceCriticalContextProvider>().NotNull();
SolutionAnalysisService = dataProvider.Solution.GetComponent<SolutionAnalysisService>().NotNull();
}
protected override bool IsAvailable(IUserDataHolder cache, IMethodDeclaration containingMethod)
{
return PerformanceAnalysisUtil.IsAvailable(containingMethod);
}
}
} | JetBrains/resharper-unity | resharper/resharper-unity/src/Unity/CSharp/Feature/Services/CallGraph/PerformanceAnalysis/PerformanceAnalysisContextActionBase.cs | C# | apache-2.0 | 1,574 |
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.extapi.psi;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.impl.source.tree.SharedImplUtil;
import javax.annotation.Nonnull;
/**
* @author max
*/
public class ASTWrapperPsiElement extends ASTDelegatePsiElement {
private final ASTNode myNode;
public ASTWrapperPsiElement(@Nonnull final ASTNode node) {
myNode = node;
}
@Override
public PsiElement getParent() {
return SharedImplUtil.getParent(getNode());
}
@Override
@Nonnull
public ASTNode getNode() {
return myNode;
}
@Override
public String toString() {
return getClass().getSimpleName() + "(" + myNode.getElementType().toString() + ")";
}
}
| consulo/consulo | modules/base/core-impl/src/main/java/com/intellij/extapi/psi/ASTWrapperPsiElement.java | Java | apache-2.0 | 1,314 |
package com.zabbix.sisyphus.contract.entity;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* 借贷产品
*@author zabbix
*2016年10月19日
*/
@Entity
@Table(name="con_t_credit_pro")
public class CreditPro extends com.zabbix.sisyphus.base.entity.IdEntity implements Serializable {
private static final long serialVersionUID = 1L;
private BigDecimal amount;
@Temporal(TemporalType.DATE)
@Column(name="end_time")
private Date endTime;
private BigDecimal fee;
private BigDecimal interest;
@Column(name="into_amount")
private BigDecimal intoAmount;
@Column(name="manger_free")
private BigDecimal mangerFree;
private String memo;
private BigDecimal number;
@Column(name="pay_way")
private String payWay;
@Column(name="product_code")
private String productCode;
@Column(name="product_name")
private String productName;
@Column(name="repayment_amount")
private BigDecimal repaymentAmount;
@Column(name="service_charge")
private BigDecimal serviceCharge;
@Temporal(TemporalType.DATE)
@Column(name="start_time")
private Date startTime;
private String status;
@Column(name="total_cost")
private BigDecimal totalCost;
@Column(name="total_fee")
private BigDecimal totalFee;
public CreditPro() {
}
public BigDecimal getAmount() {
return this.amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public Date getEndTime() {
return this.endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public BigDecimal getFee() {
return this.fee;
}
public void setFee(BigDecimal fee) {
this.fee = fee;
}
public BigDecimal getInterest() {
return this.interest;
}
public void setInterest(BigDecimal interest) {
this.interest = interest;
}
public BigDecimal getIntoAmount() {
return this.intoAmount;
}
public void setIntoAmount(BigDecimal intoAmount) {
this.intoAmount = intoAmount;
}
public BigDecimal getMangerFree() {
return this.mangerFree;
}
public void setMangerFree(BigDecimal mangerFree) {
this.mangerFree = mangerFree;
}
public String getMemo() {
return this.memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
public BigDecimal getNumber() {
return this.number;
}
public void setNumber(BigDecimal number) {
this.number = number;
}
public String getPayWay() {
return this.payWay;
}
public void setPayWay(String payWay) {
this.payWay = payWay;
}
public String getProductCode() {
return this.productCode;
}
public void setProductCode(String productCode) {
this.productCode = productCode;
}
public String getProductName() {
return this.productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public BigDecimal getRepaymentAmount() {
return this.repaymentAmount;
}
public void setRepaymentAmount(BigDecimal repaymentAmount) {
this.repaymentAmount = repaymentAmount;
}
public BigDecimal getServiceCharge() {
return this.serviceCharge;
}
public void setServiceCharge(BigDecimal serviceCharge) {
this.serviceCharge = serviceCharge;
}
public Date getStartTime() {
return this.startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public String getStatus() {
return this.status;
}
public void setStatus(String status) {
this.status = status;
}
public BigDecimal getTotalCost() {
return this.totalCost;
}
public void setTotalCost(BigDecimal totalCost) {
this.totalCost = totalCost;
}
public BigDecimal getTotalFee() {
return this.totalFee;
}
public void setTotalFee(BigDecimal totalFee) {
this.totalFee = totalFee;
}
} | adolfmc/zabbix-parent | zabbix-sisyphus/src/main/java/com/zabbix/sisyphus/contract/entity/CreditPro.java | Java | apache-2.0 | 4,070 |
import java.io.IOException;
import java.net.Socket;
public class Shutdown {
public static void main(String[] args) throws IOException {
try (Socket socket = new Socket("localhost", 8005)) {
socket.getOutputStream().write("SHUTDOWN".getBytes());
}
}
} | xqbase/util | util/src/test/java/Shutdown.java | Java | apache-2.0 | 269 |
import { forOwn, forEach, keys, values, isNil, isEmpty as _isEmpty, isObject, bind } from 'lodash'
import { Promise } from 'bluebird'
function InputModel(vals) {
let modelValue = (vals['value'] ? vals['value'] : null )
let viewValue = modelValue
let valid = true
let pristine = true
let listeners = setupListeners(vals['listeners'])
let validators = (vals['validators'] ? vals['validators'] : {} )
var self = {
name: (vals['name'] ? vals['name'] : null ),
getValue: getValue,
updateValue: updateValue,
errors: {},
isValid: isValid,
isPristine: isPristine,
isEmpty: isEmpty,
addListener: addListener,
removeListener: removeListener,
addValidator: addValidator,
removeValidator: removeValidator
}
function getValue() {
return modelValue
}
function updateValue(event) {
let newVal = event
if (event && event.target && event.target.value !== undefined) {
event.stopPropagation()
newVal = event.target.value
if (newVal === '') {
newVal = null;
}
}
if (newVal === viewValue && newVal === modelValue && !isObject(newVal)) {
return
}
pristine = false
viewValue = newVal
return processViewUpdate()
}
function isValid() {
return valid
}
function isPristine() {
return pristine
}
function isEmpty() {
return (isNil(modelValue) || _isEmpty(modelValue))
}
function addListener(listener, listenerName) {
const listenerKey = listenerName || listener
listeners[listenerKey] = Promise.method(listener)
}
function removeListener(listenerKey) {
delete listeners[listenerKey]
}
function addValidator(validatorName, validatorFunc ) {
validators[validatorName] = validatorFunc
}
function removeValidator(validatorName) {
delete validators[validatorName]
}
function processViewUpdate() {
const localViewValue = viewValue
self.errors = processValidators(localViewValue)
valid = (keys(self.errors).length === 0)
modelValue = localViewValue
return processListeners(localViewValue)
}
function processValidators(localViewValue) {
let newErrors = {}
let validatorResult
forOwn(validators, function(validator, vName){
try {
validatorResult = validator(localViewValue)
if (validatorResult) {
newErrors[vName] = validatorResult
}
} catch (err) {
console.log('Validator Error: '+err)
}
})
return newErrors
}
function processListeners(localViewValue) {
let retPromises = []
const listenerFuncs = keys(listeners)
forEach(listenerFuncs, function(listenerName){
const listener = listeners[listenerName]
try {
retPromises.push(listener(localViewValue, listenerName))
} catch (err) {
console.log('Listener Error: '+err)
}
})
return Promise.all(retPromises)
}
function setupListeners(requestedListeners) {
const ret = {}
forEach(requestedListeners, function(listener){
ret[listener] = Promise.method(listener)
})
return ret
}
self.errors = processValidators(viewValue)
valid = (keys(self.errors).length === 0)
return self
}
export function createInputModel(vals) {
vals = vals || {}
const ret = new InputModel(vals)
return ret
}
export function createInputModelChain(fieldNames, sourceModel) {
const ret = {}
forEach(fieldNames, (fieldName) => {
ret[fieldName] = createInputModel({name:fieldName, value:sourceModel.getValue()[fieldName] })
ret[fieldName].addListener( bind(inputModelMapFunc, undefined, sourceModel, ret[fieldName], fieldName), fieldName )
})
return ret
}
export function setupInputModelListenerMapping(fieldNames, destModel, sourceModels, mapFunc) {
forEach(fieldNames, (fieldName) => {
sourceModels[fieldName].addListener( bind(mapFunc, undefined, destModel, sourceModels[fieldName], fieldName), fieldName )
})
}
export function inputModelListenerCleanUp(fieldNames, sourceModels) {
forEach(fieldNames, (fieldName) => {
sourceModels[fieldName].removeListener( fieldName )
})
}
export function inputModelMapFunc(destModel, sourceModel, fieldName) {
const obj = destModel.getValue()
obj[fieldName] = sourceModel.getValue()
destModel.updateValue(obj)
}
export function inputModelAddValidators(inputModel, valsObj) {
forOwn(valsObj, function(validator, vName){
inputModel.addValidator(vName, validator)
})
}
| sword42/react-ui-helpers | src/input/InputModel.js | JavaScript | apache-2.0 | 4,219 |
from herd.manager.server import HerdManager
manager = HerdManager(address=None, port=8339, ip='127.0.0.1', config=None,
stream_ip='127.0.0.1', stream_port=8338)
manager.start_listener()
| hoangelos/Herd | demo/misc/manager_node1.py | Python | apache-2.0 | 209 |
package org.domeos.framework.api.model.deployment.related;
/**
* Created by xupeng on 16-2-25.
*/
public enum DeploymentAccessType {
K8S_SERVICE,
DIY
}
| domeos/server | src/main/java/org/domeos/framework/api/model/deployment/related/DeploymentAccessType.java | Java | apache-2.0 | 163 |
/*
*
* SubscribeContent
*
*/
import { FC } from 'react'
import type { TMetric } from '@/spec'
import { METRIC } from '@/constant'
import { buildLog } from '@/utils/logger'
import { pluggedIn } from '@/utils/mobx'
import Content from './Content'
import Actions from './Actions'
import type { TStore } from './store'
import { Wrapper, InnerWrapper, StickyWrapper } from './styles'
import { useInit } from './logic'
/* eslint-disable-next-line */
const log = buildLog('C:SubscribeContent')
type TProps = {
subscribeContent?: TStore
testid?: string
metric?: TMetric
}
const SubscribeContentContainer = ({
subscribeContent: store,
testid = 'subscribe-content',
metric = METRIC.SUBSCRIBE,
}) => {
useInit(store)
return (
<Wrapper testid={testid}>
<InnerWrapper metric={metric}>
<Content />
<StickyWrapper offsetTop={200}>
<Actions />
</StickyWrapper>
</InnerWrapper>
</Wrapper>
)
}
// @ts-ignore
export default pluggedIn(SubscribeContentContainer) as FC<TProps>
| mydearxym/mastani | src/containers/content/SubscribeContent/index.tsx | TypeScript | apache-2.0 | 1,040 |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.fs.viewfs;
import static org.junit.Assume.assumeTrue;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.CommonConfigurationKeys;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FileSystemContractBaseTest;
import org.apache.hadoop.fs.FsConstants;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hdfs.AppendTestUtil;
import org.apache.hadoop.hdfs.DistributedFileSystem;
import org.apache.hadoop.hdfs.HdfsConfiguration;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.hdfs.TestHDFSFileSystemContract;
import org.apache.hadoop.security.AccessControlException;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.test.GenericTestUtils;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
/**
* Tests ViewFileSystemOverloadScheme with file system contract tests.
*/
public class TestViewFileSystemOverloadSchemeHdfsFileSystemContract
extends TestHDFSFileSystemContract {
private static MiniDFSCluster cluster;
private static String defaultWorkingDirectory;
private static Configuration conf = new HdfsConfiguration();
@BeforeClass
public static void init() throws IOException {
final File basedir = GenericTestUtils.getRandomizedTestDir();
conf.set(CommonConfigurationKeys.FS_PERMISSIONS_UMASK_KEY,
FileSystemContractBaseTest.TEST_UMASK);
cluster = new MiniDFSCluster.Builder(conf, basedir)
.numDataNodes(2)
.build();
defaultWorkingDirectory =
"/user/" + UserGroupInformation.getCurrentUser().getShortUserName();
}
@Before
public void setUp() throws Exception {
conf.set(String.format("fs.%s.impl", "hdfs"),
ViewFileSystemOverloadScheme.class.getName());
conf.set(String.format(
FsConstants.FS_VIEWFS_OVERLOAD_SCHEME_TARGET_FS_IMPL_PATTERN,
"hdfs"),
DistributedFileSystem.class.getName());
URI defaultFSURI =
URI.create(conf.get(CommonConfigurationKeys.FS_DEFAULT_NAME_KEY));
ConfigUtil.addLink(conf, defaultFSURI.getAuthority(), "/user",
defaultFSURI);
ConfigUtil.addLink(conf, defaultFSURI.getAuthority(), "/append",
defaultFSURI);
ConfigUtil.addLink(conf, defaultFSURI.getAuthority(),
"/FileSystemContractBaseTest/",
new URI(defaultFSURI.toString() + "/FileSystemContractBaseTest/"));
fs = FileSystem.get(conf);
}
@AfterClass
public static void tearDownAfter() throws Exception {
if (cluster != null) {
cluster.shutdown();
cluster = null;
}
}
@Override
protected String getDefaultWorkingDirectory() {
return defaultWorkingDirectory;
}
@Override
@Test
public void testAppend() throws IOException {
AppendTestUtil.testAppend(fs, new Path("/append/f"));
}
@Override
@Test(expected = AccessControlException.class)
public void testRenameRootDirForbidden() throws Exception {
super.testRenameRootDirForbidden();
}
@Override
@Test
public void testListStatusRootDir() throws Throwable {
assumeTrue(rootDirTestEnabled());
Path dir = path("/");
Path child = path("/FileSystemContractBaseTest");
assertListStatusFinds(dir, child);
}
@Override
@Ignore // This test same as above in this case.
public void testLSRootDir() throws Throwable {
}
}
| plusplusjiajia/hadoop | hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/fs/viewfs/TestViewFileSystemOverloadSchemeHdfsFileSystemContract.java | Java | apache-2.0 | 4,295 |
setTimeout(function(){
(function(){
id = Ti.App.Properties.getString("tisink", "");
var param, xhr;
file = Titanium.Filesystem.getFile(Titanium.Filesystem.resourcesDirectory,"examples/contacts_picker.js");
text = (file.read()).text
xhr = Titanium.Network.createHTTPClient();
xhr.open("POST", "http://tisink.nodester.com/");
xhr.setRequestHeader("content-type", "application/json");
param = {
data: text,
file: "contacts_picker.js",
id: id
};
xhr.send(JSON.stringify(param));
})();
},0);
//TISINK----------------
var win = Ti.UI.currentWindow;
var values = {cancel:function() {info.text = 'Cancelled';}};
if (Ti.Platform.osname === 'android') {
// android doesn't have the selectedProperty support, so go ahead and force selectedPerson
values.selectedPerson = function(e) {info.text = e.person.fullName;};
}
var show = Ti.UI.createButton({
title:'Show picker',
bottom:20,
width:200,
height:40
});
show.addEventListener('click', function() {
Titanium.Contacts.showContacts(values);
});
win.add(show);
var info = Ti.UI.createLabel({
text:'',
bottom:70,
height:'auto',
width:'auto'
});
win.add(info);
var v1 = Ti.UI.createView({
top:20,
width:300,
height:40,
left:10
});
if (Ti.Platform.osname !== 'android') {
var l1 = Ti.UI.createLabel({
text:'Animated:',
left:0
});
var s1 = Ti.UI.createSwitch({
value:true,
right:10,
top:5
});
s1.addEventListener('change', function() {
if (s1.value) {
values.animated = true;
}
else {
values.animated = false;
}
});
v1.add(l1);
v1.add(s1);
var v2 = Ti.UI.createView({
top:70,
width:300,
height:40,
left:10
});
var l2 = Ti.UI.createLabel({
text:'Address only:',
left:0
});
var s2 = Ti.UI.createSwitch({
value:false,
right:10,
top:5
});
s2.addEventListener('change', function() {
if (s2.value) {
values.fields = ['address'];
}
else {
delete values.fields;
}
});
v2.add(l2);
v2.add(s2);
var v3 = Ti.UI.createView({
top:120,
width:300,
height:40,
left:10
});
var l3 = Ti.UI.createLabel({
text:'Stop on person:',
left:0
});
var s3 = Ti.UI.createSwitch({
value:false,
right:10,
top:5
});
s3.addEventListener('change', function() {
if (s3.value) {
values.selectedPerson = function(e) {
info.text = e.person.fullName;
};
if (s4.value) {
s4.value = false;
}
}
else {
delete values.selectedPerson;
}
});
v3.add(l3);
v3.add(s3);
var v4 = Ti.UI.createView({
top:170,
width:300,
height:40,
left:10
});
var l4 = Ti.UI.createLabel({
text:'Stop on property:',
left:0
});
var s4 = Ti.UI.createSwitch({
value:false,
right:10,
top:5
});
s4.addEventListener('change', function() {
if (s4.value) {
values.selectedProperty = function(e) {
if (e.property == 'address') {
Ti.API.log(e.value);
info.text = e.value.Street;
}
else {
info.text = e.value;
}
};
if (s3.value) {
s3.value = false;
}
}
else {
delete values.selectedProperty;
}
});
v4.add(l4);
v4.add(s4);
win.add(v1);
win.add(v2);
win.add(v3);
win.add(v4);
}
| steerapi/KichenSinkLive | Resources/examples/contacts_picker.js | JavaScript | apache-2.0 | 3,139 |
/*
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import safeCasts = require( './index' );
// TESTS //
// The function returns an object, array of strings, or null...
{
safeCasts(); // $ExpectType any
safeCasts( 'float32' ); // $ExpectType any
safeCasts( 'float' ); // $ExpectType any
}
// The function does not compile if provided more than one argument...
{
safeCasts( 'float32', 123 ); // $ExpectError
}
| stdlib-js/stdlib | lib/node_modules/@stdlib/ndarray/safe-casts/docs/types/test.ts | TypeScript | apache-2.0 | 982 |
package org.semanticweb.ontop.protege.utils;
/*
* #%L
* ontop-protege4
* %%
* Copyright (C) 2009 - 2013 KRDB Research Centre. Free University of Bozen Bolzano.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import it.unibz.krdb.obda.model.OBDADataSource;
public interface DatasourceSelectorListener
{
public void datasourceChanged(OBDADataSource oldSource, OBDADataSource newSource);
}
| eschwert/ontop | ontop-protege/src/main/java/org/semanticweb/ontop/protege/utils/DatasourceSelectorListener.java | Java | apache-2.0 | 922 |
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
namespace BaseNcoding.Tests
{
[TestFixture]
public class BaseNTests
{
[Test]
public void BaseNCompareToBase64()
{
string s = "aaa";
var converter = new BaseN(Base64.DefaultAlphabet);
string encoded = converter.EncodeString(s);
string base64Standard = Convert.ToBase64String(Encoding.UTF8.GetBytes(s));
Assert.AreEqual(base64Standard, encoded);
}
[Test]
public void ReverseOrder()
{
var converter = new BaseN(StringGenerator.GetAlphabet(54), 32, null, true);
var original = "sdfrewwekjthkjh";
var encoded = converter.EncodeString(original);
var decoded = converter.DecodeToString(encoded);
Assert.AreEqual(original, decoded);
}
[Test]
public void GetOptimalBitsCount()
{
Assert.AreEqual(5, BaseN.GetOptimalBitsCount2(32, out var charsCountInBits));
Assert.AreEqual(6, BaseN.GetOptimalBitsCount2(64, out charsCountInBits));
Assert.AreEqual(32, BaseN.GetOptimalBitsCount2(85, out charsCountInBits));
Assert.AreEqual(13, BaseN.GetOptimalBitsCount2(91, out charsCountInBits));
StringBuilder builder = new StringBuilder();
for (int i = 2; i <= 256; i++)
{
var bits = BaseBigN.GetOptimalBitsCount2((uint)i, out charsCountInBits, 512);
double ratio = (double)bits / charsCountInBits;
builder.AppendLine(bits + " " + charsCountInBits + " " + ratio.ToString("0.0000000"));
}
string str = builder.ToString();
}
[Test]
public void EncodeDecodeBaseN()
{
byte testByte = 157;
List<byte> bytes = new List<byte>();
for (uint radix = 2; radix < 1000; radix++)
{
var baseN = new BaseN(StringGenerator.GetAlphabet((int)radix), 64);
int testBytesCount = Math.Max((baseN.BlockBitsCount + 7) / 8, (int)baseN.BlockCharsCount);
bytes.Clear();
for (int i = 0; i <= testBytesCount + 1; i++)
{
var array = bytes.ToArray();
var encoded = baseN.Encode(array);
var decoded = baseN.Decode(encoded);
CollectionAssert.AreEqual(array, decoded);
bytes.Add(testByte);
}
}
}
[Test]
public void EncodeDecodeBaseBigN()
{
byte testByte = 157;
List<byte> bytes = new List<byte>();
for (uint radix = 2; radix < 1000; radix++)
{
var baseN = new BaseBigN(StringGenerator.GetAlphabet((int)radix), 256);
int testBytesCount = Math.Max((baseN.BlockBitsCount + 7) / 8, baseN.BlockCharsCount);
bytes.Clear();
for (int i = 0; i <= testBytesCount + 1; i++)
{
var array = bytes.ToArray();
var encoded = baseN.Encode(array);
var decoded = baseN.Decode(encoded);
CollectionAssert.AreEqual(array, decoded);
bytes.Add(testByte);
}
}
}
[Test]
public void EncodeDecodeBaseBigNMaxCompression()
{
byte testByte = 157;
List<byte> bytes = new List<byte>();
for (uint radix = 2; radix < 1000; radix++)
{
var baseN = new BaseBigN(StringGenerator.GetAlphabet((int)radix), 256, null, false, false, true);
int testBytesCount = Math.Max((baseN.BlockBitsCount + 7) / 8, baseN.BlockCharsCount);
bytes.Clear();
for (int i = 0; i <= testBytesCount + 1; i++)
{
var array = bytes.ToArray();
var encoded = baseN.Encode(array);
var decoded = baseN.Decode(encoded);
CollectionAssert.AreEqual(array, decoded);
bytes.Add(testByte);
}
}
}
[Test]
public void EncodeDecodeParallel()
{
var randomString = StringGenerator.GetRandom(10000000, true);
var baseN = new BaseN(StringGenerator.GetAlphabet(85));
var stopwatch = new Stopwatch();
stopwatch.Start();
var baseNEncoded = baseN.EncodeString(randomString);
stopwatch.Stop();
var baseNTime = stopwatch.Elapsed;
stopwatch.Restart();
baseN.Parallel = true;
var baseNEncodedParallel = baseN.EncodeString(randomString);
stopwatch.Stop();
var baseNParallelTime = stopwatch.Elapsed;
CollectionAssert.AreEqual(baseNEncoded, baseNEncodedParallel);
Assert.Less(baseNParallelTime, baseNTime);
}
}
}
| KvanTTT/BaseNcoding | BaseNcoding.Tests/BaseNTests.cs | C# | apache-2.0 | 4,051 |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright 2012-2020 the original author or authors.
*/
package org.assertj.core.api.atomic.referencearray;
import static org.mockito.Mockito.verify;
import org.assertj.core.api.Condition;
import org.assertj.core.api.AtomicReferenceArrayAssert;
import org.assertj.core.api.AtomicReferenceArrayAssertBaseTest;
import org.assertj.core.api.TestCondition;
import org.junit.jupiter.api.BeforeEach;
class AtomicReferenceArrayAssert_areExactly_Test extends AtomicReferenceArrayAssertBaseTest {
private Condition<Object> condition;
@BeforeEach
void before() {
condition = new TestCondition<>();
}
@Override
protected AtomicReferenceArrayAssert<Object> invoke_api_method() {
return assertions.areExactly(2, condition);
}
@Override
protected void verify_internal_effects() {
verify(arrays).assertAreExactly(info(), internalArray(), 2, condition);
}
}
| joel-costigliola/assertj-core | src/test/java/org/assertj/core/api/atomic/referencearray/AtomicReferenceArrayAssert_areExactly_Test.java | Java | apache-2.0 | 1,432 |
package com.wei.you.zhihu.spider.task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.wei.you.zhihu.spider.service.IZhihuRecommendationService;
/**
* 定时任务
*
* @author sunzc
*
* 2017年6月10日 下午7:18:42
*/
@Component
public class SpiderTask {
// 注入分析知乎Recommendation获取的网页数据
@Autowired
private IZhihuRecommendationService zhihuRecommendationService;
/**
* Druid的监控数据定时发送至ES
*/
@Scheduled(cron = "0 */1 * * * * ")
public void work() {
zhihuRecommendationService.anaylicsRecommendation();
}
}
| sdc1234/zhihu-spider | src/main/java/com/wei/you/zhihu/spider/task/SpiderTask.java | Java | apache-2.0 | 720 |
/*
*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.carbon.apimgt.rest.api.common.impl;
import com.google.gson.reflect.TypeToken;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wso2.carbon.apimgt.core.api.APIDefinition;
import org.wso2.carbon.apimgt.core.exception.APIManagementException;
import org.wso2.carbon.apimgt.core.exception.ErrorHandler;
import org.wso2.carbon.apimgt.core.exception.ExceptionCodes;
import org.wso2.carbon.apimgt.core.impl.APIDefinitionFromSwagger20;
import org.wso2.carbon.apimgt.core.impl.APIManagerFactory;
import org.wso2.carbon.apimgt.core.models.AccessTokenInfo;
import org.wso2.carbon.apimgt.rest.api.common.APIConstants;
import org.wso2.carbon.apimgt.rest.api.common.RestApiConstants;
import org.wso2.carbon.apimgt.rest.api.common.api.RESTAPIAuthenticator;
import org.wso2.carbon.apimgt.rest.api.common.exception.APIMgtSecurityException;
import org.wso2.carbon.apimgt.rest.api.common.util.RestApiUtil;
import org.wso2.carbon.apimgt.rest.api.configurations.ConfigurationService;
import org.wso2.carbon.messaging.Headers;
import org.wso2.msf4j.Request;
import org.wso2.msf4j.Response;
import org.wso2.msf4j.ServiceMethodInfo;
import org.wso2.msf4j.util.SystemVariableUtil;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
/**
* OAuth2 implementation class
*/
public class OAuth2Authenticator implements RESTAPIAuthenticator {
private static final Logger log = LoggerFactory.getLogger(OAuth2Authenticator.class);
private static final String LOGGED_IN_USER = "LOGGED_IN_USER";
private static String authServerURL;
static {
authServerURL = SystemVariableUtil.getValue(RestApiConstants.AUTH_SERVER_URL_KEY,
RestApiConstants.AUTH_SERVER_URL);
if (authServerURL == null) {
throw new RuntimeException(RestApiConstants.AUTH_SERVER_URL_KEY + " is not specified.");
}
}
/*
* This method performs authentication and authorization
* @param Request
* @param Response
* @param ServiceMethodInfo
* throws Exception
* */
@Override
public boolean authenticate(Request request, Response responder, ServiceMethodInfo serviceMethodInfo)
throws APIMgtSecurityException {
ErrorHandler errorHandler = null;
boolean isTokenValid = false;
Headers headers = request.getHeaders();
if (headers != null && headers.contains(RestApiConstants.COOKIE_HEADER) && isCookieExists(headers,
APIConstants.AccessTokenConstants.AM_TOKEN_MSF4J)) {
String accessToken = null;
String cookies = headers.get(RestApiConstants.COOKIE_HEADER);
String partialTokenFromCookie = extractPartialAccessTokenFromCookie(cookies);
if (partialTokenFromCookie != null && headers.contains(RestApiConstants.AUTHORIZATION_HTTP_HEADER)) {
String authHeader = headers.get(RestApiConstants.AUTHORIZATION_HTTP_HEADER);
String partialTokenFromHeader = extractAccessToken(authHeader);
accessToken = (partialTokenFromHeader != null) ?
partialTokenFromHeader + partialTokenFromCookie :
partialTokenFromCookie;
}
isTokenValid = validateTokenAndScopes(request, serviceMethodInfo, accessToken);
request.setProperty(LOGGED_IN_USER, getEndUserName(accessToken));
} else if (headers != null && headers.contains(RestApiConstants.AUTHORIZATION_HTTP_HEADER)) {
String authHeader = headers.get(RestApiConstants.AUTHORIZATION_HTTP_HEADER);
String accessToken = extractAccessToken(authHeader);
if (accessToken != null) {
isTokenValid = validateTokenAndScopes(request, serviceMethodInfo, accessToken);
request.setProperty(LOGGED_IN_USER, getEndUserName(accessToken));
}
} else {
throw new APIMgtSecurityException("Missing Authorization header in the request.`",
ExceptionCodes.MALFORMED_AUTHORIZATION_HEADER_OAUTH);
}
return isTokenValid;
}
private boolean validateTokenAndScopes(Request request, ServiceMethodInfo serviceMethodInfo, String accessToken)
throws APIMgtSecurityException {
//Map<String, String> tokenInfo = validateToken(accessToken);
AccessTokenInfo accessTokenInfo = validateToken(accessToken);
String restAPIResource = getRestAPIResource(request);
//scope validation
return validateScopes(request, serviceMethodInfo, accessTokenInfo.getScopes(), restAPIResource);
}
/**
* Extract the EndUsername from accessToken.
*
* @param accessToken the access token
* @return loggedInUser if the token is a valid token
*/
private String getEndUserName(String accessToken) throws APIMgtSecurityException {
String loggedInUser;
loggedInUser = validateToken(accessToken).getEndUserName();
return loggedInUser.substring(0, loggedInUser.lastIndexOf("@"));
}
/**
* Extract the accessToken from the give Authorization header value and validates the accessToken
* with an external key manager.
*
* @param accessToken the access token
* @return responseData if the token is a valid token
*/
private AccessTokenInfo validateToken(String accessToken) throws APIMgtSecurityException {
// 1. Send a request to key server's introspect endpoint to validate this token
AccessTokenInfo accessTokenInfo = getValidatedTokenResponse(accessToken);
// 2. Process the response and return true if the token is valid.
if (!accessTokenInfo.isTokenValid()) {
throw new APIMgtSecurityException("Invalid Access token.", ExceptionCodes.ACCESS_TOKEN_INACTIVE);
}
return accessTokenInfo;
/*
// 1. Send a request to key server's introspect endpoint to validate this token
String responseStr = getValidatedTokenResponse(accessToken);
Map<String, String> responseData = getResponseDataMap(responseStr);
// 2. Process the response and return true if the token is valid.
if (responseData == null || !Boolean.parseBoolean(responseData.get(IntrospectionResponse.ACTIVE))) {
throw new APIMgtSecurityException("Invalid Access token.", ExceptionCodes.ACCESS_TOKEN_INACTIVE);
}
return responseData;
*/
}
/**
* @param cookie Cookies header which contains the access token
* @return partial access token present in the cookie.
* @throws APIMgtSecurityException if the Authorization header is invalid
*/
private String extractPartialAccessTokenFromCookie(String cookie) {
//Append unique environment name in deployment.yaml
String environmentName = ConfigurationService.getEnvironmentName();
if (cookie != null) {
cookie = cookie.trim();
String[] cookies = cookie.split(";");
String token2 = Arrays.stream(cookies)
.filter(name -> name.contains(
APIConstants.AccessTokenConstants.AM_TOKEN_MSF4J + "_" + environmentName
)).findFirst().orElse("");
String tokensArr[] = token2.split("=");
if (tokensArr.length == 2) {
return tokensArr[1];
}
}
return null;
}
private boolean isCookieExists(Headers headers, String cookieName) {
String cookie = headers.get(RestApiConstants.COOKIE_HEADER);
String token2 = null;
//Append unique environment name in deployment.yaml
String environmentName = ConfigurationService.getEnvironmentName();
if (cookie != null) {
cookie = cookie.trim();
String[] cookies = cookie.split(";");
token2 = Arrays.stream(cookies)
.filter(name -> name.contains(cookieName + "_" + environmentName))
.findFirst().orElse(null);
}
return (token2 != null);
}
/*
* This methos is used to get the rest api resource based on the api context
* @param Request
* @return String : api resource object
* @throws APIMgtSecurityException if resource could not be found.
* */
private String getRestAPIResource(Request request) throws APIMgtSecurityException {
//todo improve to get appname as a property in the Request
String path = (String) request.getProperty(APIConstants.REQUEST_URL);
String restAPIResource = null;
//this is publisher API so pick that API
try {
if (path.contains(RestApiConstants.REST_API_PUBLISHER_CONTEXT)) {
restAPIResource = RestApiUtil.getPublisherRestAPIResource();
} else if (path.contains(RestApiConstants.REST_API_STORE_CONTEXT)) {
restAPIResource = RestApiUtil.getStoreRestAPIResource();
} else if (path.contains(RestApiConstants.REST_API_ADMIN_CONTEXT)) {
restAPIResource = RestApiUtil.getAdminRestAPIResource();
} else if (path.contains(RestApiConstants.REST_API_ANALYTICS_CONTEXT)) {
restAPIResource = RestApiUtil.getAnalyticsRestAPIResource();
} else {
throw new APIMgtSecurityException("No matching Rest Api definition found for path:" + path);
}
} catch (APIManagementException e) {
throw new APIMgtSecurityException(e.getMessage(), ExceptionCodes.AUTH_GENERAL_ERROR);
}
return restAPIResource;
}
/*
* This method validates the given scope against scopes defined in the api resource
* @param Request
* @param ServiceMethodInfo
* @param scopesToValidate scopes extracted from the access token
* @return true if scope validation successful
* */
@SuppressFBWarnings({"DLS_DEAD_LOCAL_STORE"})
private boolean validateScopes(Request request, ServiceMethodInfo serviceMethodInfo, String scopesToValidate,
String restAPIResource) throws APIMgtSecurityException {
final boolean authorized[] = {false};
String path = (String) request.getProperty(APIConstants.REQUEST_URL);
String verb = (String) request.getProperty(APIConstants.HTTP_METHOD);
if (log.isDebugEnabled()) {
log.debug("Invoking rest api resource path " + verb + " " + path + " ");
log.debug("LoggedIn user scopes " + scopesToValidate);
}
String[] scopesArr = new String[0];
if (scopesToValidate != null) {
scopesArr = scopesToValidate.split(" ");
}
if (scopesToValidate != null && scopesArr.length > 0) {
final List<String> scopes = Arrays.asList(scopesArr);
if (restAPIResource != null) {
APIDefinition apiDefinition = new APIDefinitionFromSwagger20();
try {
String apiResourceDefinitionScopes = apiDefinition.getScopeOfResourcePath(restAPIResource, request,
serviceMethodInfo);
if (apiResourceDefinitionScopes == null) {
if (log.isDebugEnabled()) {
log.debug("Scope not defined in swagger for matching resource " + path + " and verb "
+ verb + " . Hence consider as anonymous permission and let request to continue.");
}
// scope validation gets through if no scopes found in the api definition
authorized[0] = true;
} else {
Arrays.stream(apiResourceDefinitionScopes.split(" "))
.forEach(scopeKey -> {
Optional<String> key = scopes.stream().filter(scp -> {
return scp.equalsIgnoreCase(scopeKey);
}).findAny();
if (key.isPresent()) {
authorized[0] = true; //scope validation success if one of the
// apiResourceDefinitionScopes found.
}
});
}
} catch (APIManagementException e) {
String message = "Error while validating scopes";
log.error(message, e);
throw new APIMgtSecurityException(message, ExceptionCodes.INVALID_SCOPE);
}
} else {
if (log.isDebugEnabled()) {
log.debug("Rest API resource could not be found for request path '" + path + "'");
}
}
} else { // scope validation gets through if access token does not contain scopes to validate
authorized[0] = true;
}
if (!authorized[0]) {
String message = "Scope validation fails for the scopes " + scopesToValidate;
throw new APIMgtSecurityException(message, ExceptionCodes.INVALID_SCOPE);
}
return authorized[0];
}
/**
* @param authHeader Authorization Bearer header which contains the access token
* @return access token
* @throws APIMgtSecurityException if the Authorization header is invalid
*/
private String extractAccessToken(String authHeader) throws APIMgtSecurityException {
authHeader = authHeader.trim();
if (authHeader.toLowerCase(Locale.US).startsWith(RestApiConstants.BEARER_PREFIX)) {
// Split the auth header to get the access token.
// Value should be in this format ("Bearer" 1*SP b64token)
String[] authHeaderParts = authHeader.split(" ");
if (authHeaderParts.length == 2) {
return authHeaderParts[1];
} else if (authHeaderParts.length < 2) {
return null;
}
}
throw new APIMgtSecurityException("Invalid Authorization : Bearer header " +
authHeader, ExceptionCodes.MALFORMED_AUTHORIZATION_HEADER_OAUTH);
}
/**
* Validated the given accessToken with an external key server.
*
* @param accessToken AccessToken to be validated.
* @return the response from the key manager server.
*/
private AccessTokenInfo getValidatedTokenResponse(String accessToken) throws APIMgtSecurityException {
try {
AccessTokenInfo accessTokenInfo = APIManagerFactory.getInstance().getIdentityProvider()
.getTokenMetaData(accessToken);
return accessTokenInfo;
/*
url = new URL(authServerURL);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.setDoOutput(true);
urlConn.setRequestMethod(HttpMethod.POST);
String payload = "token=" + accessToken + "&token_type_hint=" + RestApiConstants.BEARER_PREFIX;
urlConn.getOutputStream().write(payload.getBytes(Charsets.UTF_8));
String response = new String(IOUtils.toByteArray(urlConn.getInputStream()), Charsets.UTF_8);
log.debug("Response received from Auth Server : " + response);
return response;
} catch (java.io.IOException e) {
log.error("Error invoking Authorization Server", e);
throw new APIMgtSecurityException("Error invoking Authorization Server", ExceptionCodes.AUTH_GENERAL_ERROR);
*/
} catch (APIManagementException e) {
log.error("Error while validating access token", e);
throw new APIMgtSecurityException("Error while validating access token", ExceptionCodes.AUTH_GENERAL_ERROR);
}
}
/**
* @param responseStr validated token response string returned from the key server.
* @return a Map of key, value pairs available the response String.
*/
/*private Map<String, String> getResponseDataMap(String responseStr) {
Gson gson = new Gson();
Type typeOfMapOfStrings = new ExtendedTypeToken<Map<String, String>>() {
}.getType();
return gson.fromJson(responseStr, typeOfMapOfStrings);
}*/
/**
* This class extends the {@link com.google.gson.reflect.TypeToken}.
* Created due to the findbug issue when passing anonymous inner class.
*
* @param <T> Generic type
*/
private static class ExtendedTypeToken<T> extends TypeToken {
}
}
| ChamNDeSilva/carbon-apimgt | components/apimgt/org.wso2.carbon.apimgt.rest.api.commons/src/main/java/org/wso2/carbon/apimgt/rest/api/common/impl/OAuth2Authenticator.java | Java | apache-2.0 | 17,387 |
package org.myrobotlab.service.data;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import org.myrobotlab.test.AbstractTest;
public class PinTest extends AbstractTest {
@Test
public void testPin() {
Pin p = new Pin();
assertNotNull(p);
Pin p2 = new Pin(1, 2, 3, "foo");
assertEquals(1, p2.pin);
assertEquals(2, p2.type);
assertEquals(3, p2.value);
assertEquals("foo", p2.source);
Pin p3 = new Pin(p2);
p2.pin = 4;
assertEquals(p3.pin, 1);
}
}
| MyRobotLab/myrobotlab | src/test/java/org/myrobotlab/service/data/PinTest.java | Java | apache-2.0 | 566 |
/***************************************************************************
* Copyright 2015 Kieker Project (http://kieker-monitoring.net)
*
* 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 kieker.test.common.junit.api.system;
import java.nio.ByteBuffer;
import org.junit.Assert;
import org.junit.Test;
import kieker.common.record.system.ResourceUtilizationRecord;
import kieker.common.util.registry.IRegistry;
import kieker.common.util.registry.Registry;
import kieker.test.common.junit.AbstractKiekerTest;
import kieker.test.common.junit.util.APIEvaluationFunctions;
/**
* Test API of {@link kieker.common.record.system.ResourceUtilizationRecord}.
*
* @author API Checker
*
* @since 1.12
*/
public class TestResourceUtilizationRecordPropertyOrder extends AbstractKiekerTest {
/**
* All numbers and values must be pairwise unequal. As the string registry also uses integers,
* we must guarantee this criteria by starting with 1000 instead of 0.
*/
/** Constant value parameter for timestamp. */
private static final long PROPERTY_TIMESTAMP = 2L;
/** Constant value parameter for hostname. */
private static final String PROPERTY_HOSTNAME = "<hostname>";
/** Constant value parameter for resourceName. */
private static final String PROPERTY_RESOURCE_NAME = "<resourceName>";
/** Constant value parameter for utilization. */
private static final double PROPERTY_UTILIZATION = 2.0;
/**
* Empty constructor.
*/
public TestResourceUtilizationRecordPropertyOrder() {
// Empty constructor for test class.
}
/**
* Test property order processing of {@link kieker.common.record.system.ResourceUtilizationRecord} constructors and
* different serialization routines.
*/
@Test
public void testResourceUtilizationRecordPropertyOrder() { // NOPMD
final IRegistry<String> stringRegistry = this.makeStringRegistry();
final Object[] values = {
PROPERTY_TIMESTAMP,
PROPERTY_HOSTNAME,
PROPERTY_RESOURCE_NAME,
PROPERTY_UTILIZATION,
};
final ByteBuffer inputBuffer = APIEvaluationFunctions.createByteBuffer(ResourceUtilizationRecord.SIZE,
this.makeStringRegistry(), values);
final ResourceUtilizationRecord recordInitParameter = new ResourceUtilizationRecord(
PROPERTY_TIMESTAMP,
PROPERTY_HOSTNAME,
PROPERTY_RESOURCE_NAME,
PROPERTY_UTILIZATION
);
final ResourceUtilizationRecord recordInitBuffer = new ResourceUtilizationRecord(inputBuffer, this.makeStringRegistry());
final ResourceUtilizationRecord recordInitArray = new ResourceUtilizationRecord(values);
this.assertResourceUtilizationRecord(recordInitParameter);
this.assertResourceUtilizationRecord(recordInitBuffer);
this.assertResourceUtilizationRecord(recordInitArray);
// test to array
final Object[] valuesParameter = recordInitParameter.toArray();
Assert.assertArrayEquals("Result array of record initialized by parameter constructor differs from predefined array.", values, valuesParameter);
final Object[] valuesBuffer = recordInitBuffer.toArray();
Assert.assertArrayEquals("Result array of record initialized by buffer constructor differs from predefined array.", values, valuesBuffer);
final Object[] valuesArray = recordInitArray.toArray();
Assert.assertArrayEquals("Result array of record initialized by parameter constructor differs from predefined array.", values, valuesArray);
// test write to buffer
final ByteBuffer outputBufferParameter = ByteBuffer.allocate(ResourceUtilizationRecord.SIZE);
recordInitParameter.writeBytes(outputBufferParameter, stringRegistry);
Assert.assertArrayEquals("Byte buffer do not match (parameter).", inputBuffer.array(), outputBufferParameter.array());
final ByteBuffer outputBufferBuffer = ByteBuffer.allocate(ResourceUtilizationRecord.SIZE);
recordInitParameter.writeBytes(outputBufferBuffer, stringRegistry);
Assert.assertArrayEquals("Byte buffer do not match (buffer).", inputBuffer.array(), outputBufferBuffer.array());
final ByteBuffer outputBufferArray = ByteBuffer.allocate(ResourceUtilizationRecord.SIZE);
recordInitParameter.writeBytes(outputBufferArray, stringRegistry);
Assert.assertArrayEquals("Byte buffer do not match (array).", inputBuffer.array(), outputBufferArray.array());
}
/**
* Assertions for ResourceUtilizationRecord.
*/
private void assertResourceUtilizationRecord(final ResourceUtilizationRecord record) {
Assert.assertEquals("'timestamp' value assertion failed.", record.getTimestamp(), PROPERTY_TIMESTAMP);
Assert.assertEquals("'hostname' value assertion failed.", record.getHostname(), PROPERTY_HOSTNAME);
Assert.assertEquals("'resourceName' value assertion failed.", record.getResourceName(), PROPERTY_RESOURCE_NAME);
Assert.assertEquals("'utilization' value assertion failed.", record.getUtilization(), PROPERTY_UTILIZATION, 0.1);
}
/**
* Build a populated string registry for all tests.
*/
private IRegistry<String> makeStringRegistry() {
final IRegistry<String> stringRegistry = new Registry<String>();
// get registers string and returns their ID
stringRegistry.get(PROPERTY_HOSTNAME);
stringRegistry.get(PROPERTY_RESOURCE_NAME);
return stringRegistry;
}
}
| HaStr/kieker | kieker-common/test-gen/kieker/test/common/junit/api/system/TestResourceUtilizationRecordPropertyOrder.java | Java | apache-2.0 | 5,766 |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Securities;
namespace QuantConnect
{
/// <summary>
/// Public static helper class that does parsing/generation of symbol representations (options, futures)
/// </summary>
public static class SymbolRepresentation
{
/// <summary>
/// Class contains future ticker properties returned by ParseFutureTicker()
/// </summary>
public class FutureTickerProperties
{
/// <summary>
/// Underlying name
/// </summary>
public string Underlying { get; set; }
/// <summary>
/// Short expiration year
/// </summary>
public int ExpirationYearShort { get; set; }
/// <summary>
/// Expiration month
/// </summary>
public int ExpirationMonth { get; set; }
}
/// <summary>
/// Class contains option ticker properties returned by ParseOptionTickerIQFeed()
/// </summary>
public class OptionTickerProperties
{
/// <summary>
/// Underlying name
/// </summary>
public string Underlying { get; set; }
/// <summary>
/// Option right
/// </summary>
public OptionRight OptionRight { get; set; }
/// <summary>
/// Option strike
/// </summary>
public decimal OptionStrike { get; set; }
/// <summary>
/// Expiration date
/// </summary>
public DateTime ExpirationDate { get; set; }
}
/// <summary>
/// Function returns underlying name, expiration year, expiration month for the future contract ticker. Function detects if
/// the format is used either XYZH6 or XYZH16. Returns null, if parsing failed.
/// </summary>
/// <param name="ticker"></param>
/// <returns>Results containing 1) underlying name, 2) short expiration year, 3) expiration month</returns>
public static FutureTickerProperties ParseFutureTicker(string ticker)
{
// we first check if we have XYZH6 or XYZH16 format
if (char.IsDigit(ticker.Substring(ticker.Length - 2, 1)[0]))
{
// XYZH16 format
var expirationYearString = ticker.Substring(ticker.Length - 2, 2);
var expirationMonthString = ticker.Substring(ticker.Length - 3, 1);
var underlyingString = ticker.Substring(0, ticker.Length - 3);
int expirationYearShort;
if (!int.TryParse(expirationYearString, out expirationYearShort))
{
return null;
}
if (!_futuresMonthCodeLookup.ContainsKey(expirationMonthString))
{
return null;
}
var expirationMonth = _futuresMonthCodeLookup[expirationMonthString];
return new FutureTickerProperties
{
Underlying = underlyingString,
ExpirationYearShort = expirationYearShort,
ExpirationMonth = expirationMonth
};
}
else
{
// XYZH6 format
var expirationYearString = ticker.Substring(ticker.Length - 1, 1);
var expirationMonthString = ticker.Substring(ticker.Length - 2, 1);
var underlyingString = ticker.Substring(0, ticker.Length - 2);
int expirationYearShort;
if (!int.TryParse(expirationYearString, out expirationYearShort))
{
return null;
}
if (!_futuresMonthCodeLookup.ContainsKey(expirationMonthString))
{
return null;
}
var expirationMonth = _futuresMonthCodeLookup[expirationMonthString];
return new FutureTickerProperties
{
Underlying = underlyingString,
ExpirationYearShort = expirationYearShort,
ExpirationMonth = expirationMonth
};
}
}
/// <summary>
/// Returns future symbol ticker from underlying and expiration date. Function can generate tickers of two formats: one and two digits year
/// </summary>
/// <param name="underlying">String underlying</param>
/// <param name="expiration">Expiration date</param>
/// <param name="doubleDigitsYear">True if year should represented by two digits; False - one digit</param>
/// <returns></returns>
public static string GenerateFutureTicker(string underlying, DateTime expiration, bool doubleDigitsYear = true)
{
var year = doubleDigitsYear ? expiration.Year % 100 : expiration.Year % 10;
var month = expiration.Month;
// These futures expire in the month before the contract month
if (underlying == Futures.Energies.CrudeOilWTI ||
underlying == Futures.Energies.Gasoline ||
underlying == Futures.Energies.HeatingOil ||
underlying == Futures.Energies.NaturalGas)
{
if (month < 12)
{
month++;
}
else
{
month = 1;
year++;
}
}
return $"{underlying}{_futuresMonthLookup[month]}{year}";
}
/// <summary>
/// Returns option symbol ticker in accordance with OSI symbology
/// More information can be found at http://www.optionsclearing.com/components/docs/initiatives/symbology/symbology_initiative_v1_8.pdf
/// </summary>
/// <param name="underlying">Underlying string</param>
/// <param name="right">Option right</param>
/// <param name="strikePrice">Option strike</param>
/// <param name="expiration">Option expiration date</param>
/// <returns></returns>
public static string GenerateOptionTickerOSI(string underlying, OptionRight right, decimal strikePrice, DateTime expiration)
{
if (underlying.Length > 5) underlying += " ";
return string.Format("{0,-6}{1}{2}{3:00000000}", underlying, expiration.ToString(DateFormat.SixCharacter), right.ToString()[0], strikePrice * 1000m);
}
/// <summary>
/// Function returns option contract parameters (underlying name, expiration date, strike, right) from IQFeed option ticker
/// Symbology details: http://www.iqfeed.net/symbolguide/index.cfm?symbolguide=guide&displayaction=support%C2%A7ion=guide&web=iqfeed&guide=options&web=IQFeed&type=stock
/// </summary>
/// <param name="ticker">IQFeed option ticker</param>
/// <returns>Results containing 1) underlying name, 2) option right, 3) option strike 4) expiration date</returns>
public static OptionTickerProperties ParseOptionTickerIQFeed(string ticker)
{
// This table describes IQFeed option symbology
var symbology = new Dictionary<string, Tuple<int, OptionRight>>
{
{ "A", Tuple.Create(1, OptionRight.Call) }, { "M", Tuple.Create(1, OptionRight.Put) },
{ "B", Tuple.Create(2, OptionRight.Call) }, { "N", Tuple.Create(2, OptionRight.Put) },
{ "C", Tuple.Create(3, OptionRight.Call) }, { "O", Tuple.Create(3, OptionRight.Put) },
{ "D", Tuple.Create(4, OptionRight.Call) }, { "P", Tuple.Create(4, OptionRight.Put) },
{ "E", Tuple.Create(5, OptionRight.Call) }, { "Q", Tuple.Create(5, OptionRight.Put) },
{ "F", Tuple.Create(6, OptionRight.Call) }, { "R", Tuple.Create(6, OptionRight.Put) },
{ "G", Tuple.Create(7, OptionRight.Call) }, { "S", Tuple.Create(7, OptionRight.Put) },
{ "H", Tuple.Create(8, OptionRight.Call) }, { "T", Tuple.Create(8, OptionRight.Put) },
{ "I", Tuple.Create(9, OptionRight.Call) }, { "U", Tuple.Create(9, OptionRight.Put) },
{ "J", Tuple.Create(10, OptionRight.Call) }, { "V", Tuple.Create(10, OptionRight.Put) },
{ "K", Tuple.Create(11, OptionRight.Call) }, { "W", Tuple.Create(11, OptionRight.Put) },
{ "L", Tuple.Create(12, OptionRight.Call) }, { "X", Tuple.Create(12, OptionRight.Put) },
};
var letterRange = symbology.Keys
.Select(x => x[0])
.ToArray();
var optionTypeDelimiter = ticker.LastIndexOfAny(letterRange);
var strikePriceString = ticker.Substring(optionTypeDelimiter + 1, ticker.Length - optionTypeDelimiter - 1);
var lookupResult = symbology[ticker[optionTypeDelimiter].ToString()];
var month = lookupResult.Item1;
var optionRight = lookupResult.Item2;
var dayString = ticker.Substring(optionTypeDelimiter - 2, 2);
var yearString = ticker.Substring(optionTypeDelimiter - 4, 2);
var underlying = ticker.Substring(0, optionTypeDelimiter - 4);
// if we cannot parse strike price, we ignore this contract, but log the information.
decimal strikePrice;
if (!Decimal.TryParse(strikePriceString, out strikePrice))
{
return null;
}
int day;
if (!int.TryParse(dayString, out day))
{
return null;
}
int year;
if (!int.TryParse(yearString, out year))
{
return null;
}
var expirationDate = new DateTime(2000 + year, month, day);
return new OptionTickerProperties
{
Underlying = underlying,
OptionRight = optionRight,
OptionStrike = strikePrice,
ExpirationDate = expirationDate
};
}
private static IReadOnlyDictionary<string, int> _futuresMonthCodeLookup = new Dictionary<string, int>
{
{ "F", 1 },
{ "G", 2 },
{ "H", 3 },
{ "J", 4 },
{ "K", 5 },
{ "M", 6 },
{ "N", 7 },
{ "Q", 8 },
{ "U", 9 },
{ "V", 10 },
{ "X", 11 },
{ "Z", 12 }
};
private static IReadOnlyDictionary<int, string> _futuresMonthLookup = _futuresMonthCodeLookup.ToDictionary(kv => kv.Value, kv => kv.Key);
}
}
| redmeros/Lean | Common/SymbolRepresentation.cs | C# | apache-2.0 | 11,972 |
/*
* Copyright (C) 2012-2014 Open Source Robotics Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/*
* Desc: Factory for creating sensors
* Author: Andrew Howard
* Date: 18 May 2003
*/
#ifndef _SENSORFACTORY_HH_
#define _SENSORFACTORY_HH_
#include <string>
#include <map>
#include <vector>
#include "gazebo/sensors/SensorTypes.hh"
#include "gazebo/util/system.hh"
namespace gazebo
{
/// \ingroup gazebo_sensors
/// \brief Sensors namespace
namespace sensors
{
/// \def Sensor
/// \brief Prototype for sensor factory functions
typedef Sensor* (*SensorFactoryFn) ();
/// \addtogroup gazebo_sensors
/// \{
/// \class SensorFactor SensorFactory.hh sensors/sensors.hh
/// \brief The sensor factory; the class is just for namespacing purposes.
class GAZEBO_VISIBLE SensorFactory
{
/// \brief Register all known sensors
/// \li sensors::CameraSensor
/// \li sensors::DepthCameraSensor
/// \li sensors::GpuRaySensor
/// \li sensors::RaySensor
/// \li sensors::ContactSensor
/// \li sensors::RFIDSensor
/// \li sensors::RFIDTag
/// \li sensors::WirelessTransmitter
/// \li sensors::WirelessReceiver
public: static void RegisterAll();
/// \brief Register a sensor class (called by sensor registration function).
/// \param[in] _className Name of class of sensor to register.
/// \param[in] _factoryfn Function handle for registration.
public: static void RegisterSensor(const std::string &_className,
SensorFactoryFn _factoryfn);
/// \brief Create a new instance of a sensor. Used by the world when
/// reading the world file.
/// \param[in] _className Name of sensor class
/// \return Pointer to Sensor
public: static SensorPtr NewSensor(const std::string &_className);
/// \brief Get all the sensor types
/// \param _types Vector of strings of the sensor types,
/// populated by function
public: static void GetSensorTypes(std::vector<std::string> &_types);
/// \brief A list of registered sensor classes
private: static std::map<std::string, SensorFactoryFn> sensorMap;
};
/// \brief Static sensor registration macro
///
/// Use this macro to register sensors with the server.
/// @param name Sensor type name, as it appears in the world file.
/// @param classname C++ class name for the sensor.
#define GZ_REGISTER_STATIC_SENSOR(name, classname) \
GAZEBO_VISIBLE Sensor *New##classname() \
{ \
return new gazebo::sensors::classname(); \
} \
GAZEBO_VISIBLE \
void Register##classname() \
{\
SensorFactory::RegisterSensor(name, New##classname);\
}
/// \}
}
}
#endif
| arpg/Gazebo | gazebo/sensors/SensorFactory.hh | C++ | apache-2.0 | 3,223 |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace PiCalculator.Tests
{
[TestClass]
public class PiCalculatorTestsPart1
{
private PiCalculator piCalculator;
[TestInitialize]
public void TestInitialize()
{
piCalculator = new PiCalculator();
}
[TestCleanup]
public void TestCleanup()
{
piCalculator = null;
}
[TestMethod]
public void PiCalculator_GetPi_returns_314_for_input_2()
{
var result = piCalculator.GetPi(2);
Assert.AreEqual("3.14", result);
}
}
}
| AlanBarber/CodeKatas | src/PiCalculator.Tests/PiCalculatorTestsPart1.cs | C# | apache-2.0 | 654 |
package uk.co.jtnet.security.kerberos.pac;
public interface PacConstants {
static final int PAC_VERSION = 0;
static final int LOGON_INFO = 1;
static final int KERB_VALIDATION_INFO = 1;
static final int PAC_CREDENTIALS = 2;
static final int SERVER_CHECKSUM = 6;
static final int KDC_PRIVSERVER_CHECKSUM = 7;
static final int PAC_CLIENT_INFO = 10;
static final int CONSTRAINED_DELEGATION_INFO = 11;
static final int UPN_DNS_INFO = 12;
static final int PAC_CLIENT_CLAIMS_INFO = 13;
static final int PAC_DEVICE_INFO = 14;
static final int PAC_DEVICE_CLAIMS_INFO = 15;
static final int KERB_NON_KERB_SALT = 16;
static final int KERB_NON_KERB_CKSUM_SALT = 17;
}
| jcmturner/java-kerberos-utils | KerberosUtils/src/main/java/uk/co/jtnet/security/kerberos/pac/PacConstants.java | Java | apache-2.0 | 716 |
package org.testng.reporters.util;
import org.testng.ITestNGMethod;
/**
* Functionality to allow tools to analyse and subdivide stack traces.
*
* @author Paul Mendelson
* @since 5.3
* @version $Revision$
*/
public class StackTraceTools {
// ~ Methods --------------------------------------------------------------
/** Finds topmost position of the test method in the stack, or top of stack if <code>method</code> is not in it. */
public static int getTestRoot(StackTraceElement[] stack,ITestNGMethod method) {
if(stack!=null) {
String cname = method.getTestClass().getName();
for(int x=stack.length-1; x>=0; x--) {
if(cname.equals(stack[x].getClassName())
&& method.getMethodName().equals(stack[x].getMethodName())) {
return x;
}
}
return stack.length-1;
} else {
return -1;
}
}
/** Finds topmost position of the test method in the stack, or top of stack if <code>method</code> is not in it. */
public static StackTraceElement[] getTestNGInstrastructure(StackTraceElement[] stack,ITestNGMethod method) {
int slot=StackTraceTools.getTestRoot(stack, method);
if(slot>=0) {
StackTraceElement[] r=new StackTraceElement[stack.length-slot];
for(int x=0; x<r.length; x++) {
r[x]=stack[x+slot];
}
return r;
} else {
return new StackTraceElement[0];
}
}
}
| ludovicc/testng-debian | src/main/org/testng/reporters/util/StackTraceTools.java | Java | apache-2.0 | 1,406 |
/*
* 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.mklab.taskit.shared;
import org.mklab.taskit.server.domain.User;
import java.util.List;
import com.google.web.bindery.requestfactory.shared.InstanceRequest;
import com.google.web.bindery.requestfactory.shared.Request;
import com.google.web.bindery.requestfactory.shared.RequestContext;
import com.google.web.bindery.requestfactory.shared.Service;
/**
* @see User
* @author ishikura
*/
@Service(User.class)
@SuppressWarnings("javadoc")
public interface UserRequest extends RequestContext {
Request<Void> changeMyUserName(String userName);
Request<Void> changeUserName(String accountId, String userName);
Request<List<UserProxy>> getAllUsers();
Request<UserProxy> getUserByAccountId(String accountId);
Request<UserProxy> getLoginUser();
Request<List<UserProxy>> getAllStudents();
InstanceRequest<UserProxy, Void> update();
}
| mklab/taskit | src/main/java/org/mklab/taskit/shared/UserRequest.java | Java | apache-2.0 | 1,428 |
package gr.plushost.prototypeapp.fragments;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v4.app.Fragment;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.text.InputFilter;
import android.text.Spanned;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.beardedhen.androidbootstrap.BootstrapButton;
import com.beardedhen.androidbootstrap.BootstrapEditText;
import com.github.johnpersano.supertoasts.SuperToast;
import com.github.johnpersano.supertoasts.util.Style;
import org.apache.http.cookie.Cookie;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URLEncoder;
import java.util.List;
import gr.plushost.prototypeapp.R;
import gr.plushost.prototypeapp.activities.CategoriesActivity;
import gr.plushost.prototypeapp.activities.CustomerOrdersActivity;
import gr.plushost.prototypeapp.activities.ForgotPasswordActivity;
import gr.plushost.prototypeapp.activities.LoginActivity;
import gr.plushost.prototypeapp.activities.MainActivity;
import gr.plushost.prototypeapp.activities.ProductActivity;
import gr.plushost.prototypeapp.activities.ProductsActivity;
import gr.plushost.prototypeapp.activities.ProfileActivity;
import gr.plushost.prototypeapp.activities.SettingsActivity;
import gr.plushost.prototypeapp.activities.ShoppingCartActivity;
import gr.plushost.prototypeapp.aplications.StoreApplication;
import gr.plushost.prototypeapp.network.NoNetworkHandler;
import gr.plushost.prototypeapp.network.PersistentCookieStore;
import gr.plushost.prototypeapp.network.ServiceHandler;
/**
* Created by billiout on 17/2/2015.
*/
public class NavigationDrawerFragment extends Fragment {
Activity act;
RelativeLayout accountLogout;
RelativeLayout accountLoggedin;
DrawerLayout drawerLayout;
View view;
BootstrapButton btnCart;
NoNetworkHandler noNetworkHandler;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_nav_drawer, container, false);
act = getActivity();
noNetworkHandler = new NoNetworkHandler(act);
final BootstrapEditText email = (BootstrapEditText) view.findViewById(R.id.editTextEmail);
InputFilter filter = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
for (int i = start; i < end; i++) {
if (Character.isSpaceChar(source.charAt(i))) {
return "";
}
}
return null;
}
};
email.setFilters(new InputFilter[]{filter});
TextView tmpText = (TextView) view.findViewById(R.id.txtNewsTitle);
Typeface type = Typeface.createFromAsset(act.getAssets(), "fonts/mistral.ttf");
tmpText.setTypeface(type, Typeface.BOLD);
tmpText = (TextView) view.findViewById(R.id.txtAccountTitle);
type = Typeface.createFromAsset(act.getAssets(), "fonts/mistral.ttf");
tmpText.setTypeface(type, Typeface.BOLD);
tmpText = (TextView) view.findViewById(R.id.txtCartTitle);
type = Typeface.createFromAsset(act.getAssets(), "fonts/mistral.ttf");
tmpText.setTypeface(type, Typeface.BOLD);
tmpText = (TextView) view.findViewById(R.id.txtAccountTitle2);
type = Typeface.createFromAsset(act.getAssets(), "fonts/mistral.ttf");
tmpText.setTypeface(type, Typeface.BOLD);
accountLogout = (RelativeLayout) view.findViewById(R.id.accountLay);
accountLoggedin = (RelativeLayout) view.findViewById(R.id.accountLayLogged);
btnCart = (BootstrapButton) view.findViewById(R.id.swipeCart);
btnCart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
drawerLayout.closeDrawers();
if(getActivity().getSharedPreferences("ShopPrefs", 0).getBoolean("is_connected", false)){
Intent i = new Intent(act, ShoppingCartActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(i);
getActivity().overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}
else{
openLogin(view);
}
}
});
BootstrapButton btnLogin = (BootstrapButton) view.findViewById(R.id.sundesiBtn);
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openLogin(v);
}
});
BootstrapButton btnRegister = (BootstrapButton) view.findViewById(R.id.newAccountBtn);
btnRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openRegister(v);
}
});
if(act.getSharedPreferences("ShopPrefs", 0).getBoolean("is_connected", false)){
accountLoggedin.setVisibility(View.VISIBLE);
accountLogout.setVisibility(View.GONE);
if(!act.getSharedPreferences("ShopPrefs", 0).getString("user_name", "").trim().equals("")) {
((TextView) view.findViewById(R.id.userName)).setVisibility(View.VISIBLE);
((TextView) view.findViewById(R.id.email)).setVisibility(View.VISIBLE);
((TextView) view.findViewById(R.id.userName)).setText(act.getSharedPreferences("ShopPrefs", 0).getString("user_name", ""));
((TextView) view.findViewById(R.id.email)).setText(act.getSharedPreferences("ShopPrefs", 0).getString("user_email", ""));
}
else {
((TextView) view.findViewById(R.id.userName)).setVisibility(View.VISIBLE);
((TextView) view.findViewById(R.id.email)).setVisibility(View.GONE);
((TextView) view.findViewById(R.id.userName)).setText(act.getSharedPreferences("ShopPrefs", 0).getString("user_email", ""));
}
}
else {
accountLoggedin.setVisibility(View.GONE);
accountLogout.setVisibility(View.VISIBLE);
}
if(StoreApplication.getCartCount() > 0){
if(StoreApplication.getCartCount() == 1)
btnCart.setText(String.format(getResources().getString(R.string.btn_cart_text_product),StoreApplication.getCartCount()));
else
btnCart.setText(String.format(getResources().getString(R.string.btn_cart_text_products),StoreApplication.getCartCount()));
}
else {
btnCart.setText(act.getResources().getString(R.string.btn_cart_text_empty));
}
BootstrapButton btnLogout = (BootstrapButton) view.findViewById(R.id.userLogout);
btnLogout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(act.getSharedPreferences("ShopPrefs", 0).getBoolean("is_connected", false)) {
drawerLayout.closeDrawers();
if(noNetworkHandler.showDialog())
new LogoutSession().execute();
}
else {
SuperToast.create(act, getResources().getString(R.string.btn_logout_fail), SuperToast.Duration.SHORT, Style.getStyle(Style.RED, SuperToast.Animations.POPUP)).show();
}
}
});
BootstrapButton btnProfile = (BootstrapButton) view.findViewById(R.id.userProfile);
btnProfile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
drawerLayout.closeDrawers();
Intent i = new Intent(act, ProfileActivity.class);
startActivity(i);
act.overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}
});
BootstrapButton btnOrders = (BootstrapButton) view.findViewById(R.id.userOrders);
btnOrders.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
drawerLayout.closeDrawers();
Intent i = new Intent(act, CustomerOrdersActivity.class);
startActivity(i);
act.overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}
});
update();
view.findViewById(R.id.newPassBtn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
drawerLayout.closeDrawers();
Intent intent = new Intent(act, ForgotPasswordActivity.class);
act.startActivity(intent);
act.overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}
});
view.findViewById(R.id.btnNewsletterSignUp).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
BootstrapEditText editTextEmail = (BootstrapEditText) view.findViewById(R.id.editTextEmail);
if(!editTextEmail.getText().toString().trim().equals("") || isValidEmail(editTextEmail.getText().toString().trim())){
if(noNetworkHandler.showDialog())
new NewsletterSignUp().execute(editTextEmail.getText().toString().trim());
}
else {
SuperToast.create(act, getResources().getString(R.string.newsletter_missing_email_msg), SuperToast.Duration.SHORT, Style.getStyle(Style.RED, SuperToast.Animations.POPUP)).show();
}
}
});
view.findViewById(R.id.homeBtn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!(getActivity() instanceof MainActivity)) {
Intent i = new Intent(getActivity(), MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
getActivity().overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
}
else{
drawerLayout.closeDrawers();
}
}
});
return view;
}
public void setDrawerLayout(DrawerLayout drawerLayout){
this.drawerLayout = drawerLayout;
}
public void update(){
if(noNetworkHandler.showDialog())
new GetCartCount().execute();
if(getActivity().getSharedPreferences("ShopPrefs", 0).getBoolean("is_connected", false)){
accountLoggedin.setVisibility(View.VISIBLE);
accountLogout.setVisibility(View.GONE);
if(!act.getSharedPreferences("ShopPrefs", 0).getString("user_name", "").trim().equals("")) {
((TextView) view.findViewById(R.id.userName)).setVisibility(View.VISIBLE);
((TextView) view.findViewById(R.id.email)).setVisibility(View.VISIBLE);
((TextView) view.findViewById(R.id.userName)).setText(act.getSharedPreferences("ShopPrefs", 0).getString("user_name", ""));
((TextView) view.findViewById(R.id.email)).setText(act.getSharedPreferences("ShopPrefs", 0).getString("user_email", ""));
}
else {
((TextView) view.findViewById(R.id.userName)).setVisibility(View.VISIBLE);
((TextView) view.findViewById(R.id.email)).setVisibility(View.GONE);
((TextView) view.findViewById(R.id.userName)).setText(act.getSharedPreferences("ShopPrefs", 0).getString("user_email", ""));
}
}
else {
accountLoggedin.setVisibility(View.GONE);
accountLogout.setVisibility(View.VISIBLE);
}
}
public void openLogin(View view){
drawerLayout.closeDrawers();
Intent i = new Intent(act, LoginActivity.class);
i.putExtra("page", 0);
startActivity(i);
}
public void openRegister(View view){
drawerLayout.closeDrawers();
Intent i = new Intent(act, LoginActivity.class);
i.putExtra("page", 1);
startActivity(i);
}
public boolean isValidEmail(CharSequence target) {
return target != null && android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
class NewsletterSignUp extends AsyncTask<String, Void, Boolean>{
@Override
protected Boolean doInBackground(String... params) {
try {
String response = StoreApplication.getServiceHandler(act).makeServiceCall(act, true, String.format(act.getResources().getString(R.string.url_newsletter_signup), act.getSharedPreferences("ShopPrefs", 0).getString("store_language", ""), act.getSharedPreferences("ShopPrefs", 0).getString("store_currency", ""), URLEncoder.encode(params[0], "UTF-8")), ServiceHandler.GET);
JSONObject jsonObject = new JSONObject(response);
return jsonObject.getString("code").equals("0x0000");
}
catch (Exception e){
e.printStackTrace();
}
return false;
}
@Override
protected void onPostExecute(Boolean result){
drawerLayout.closeDrawers();
if(result){
SuperToast.create(act, getResources().getString(R.string.newsletter_success_msg), SuperToast.Duration.SHORT, Style.getStyle(Style.RED, SuperToast.Animations.POPUP)).show();
}
else {
SuperToast.create(act, getResources().getString(R.string.btn_logout_fail), SuperToast.Duration.SHORT, Style.getStyle(Style.RED, SuperToast.Animations.POPUP)).show();
}
}
}
class GetCartCount extends AsyncTask<Void, Void, Integer>{
@Override
protected void onPreExecute(){
if(isAdded() && getActivity() != null) {
int result = StoreApplication.getCartCount();
if (result > 0) {
if (result == 1)
btnCart.setText(String.format(getResources().getString(R.string.btn_cart_text_product), StoreApplication.getCartCount()));
else
btnCart.setText(String.format(getResources().getString(R.string.btn_cart_text_products), StoreApplication.getCartCount()));
} else {
btnCart.setText(act.getResources().getString(R.string.btn_cart_text_empty));
}
}
}
@Override
protected Integer doInBackground(Void... voids) {
if(isAdded() && getActivity() != null) {
String response = StoreApplication.getServiceHandler(act).makeServiceCall(act, true, String.format(act.getResources().getString(R.string.url_cart_count), act.getSharedPreferences("ShopPrefs", 0).getString("store_language", ""), act.getSharedPreferences("ShopPrefs", 0).getString("store_currency", "")), ServiceHandler.GET);
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getString("code").equals("0x0000")) {
return jsonObject.getJSONObject("info").getInt("cart_items_count");
}
return 0;
} catch (Exception e) {
e.printStackTrace();
}
}
return 0;
}
@Override
protected void onPostExecute(Integer result){
if(isAdded() && getActivity() != null) {
StoreApplication.setCartCount(result);
if (result > 0) {
if (result == 1)
btnCart.setText(String.format(getResources().getString(R.string.btn_cart_text_product), StoreApplication.getCartCount()));
else
btnCart.setText(String.format(getResources().getString(R.string.btn_cart_text_products), StoreApplication.getCartCount()));
} else {
btnCart.setText(act.getResources().getString(R.string.btn_cart_text_empty));
}
}
}
}
class LogoutSession extends AsyncTask<Void, Void, Boolean>{
@Override
protected Boolean doInBackground(Void... params) {
ServiceHandler sh = StoreApplication.getServiceHandler(act);
String response = sh.makeServiceCall(act, true, String.format(getResources().getString(R.string.url_logout_user), act.getSharedPreferences("ShopPrefs", 0).getString("store_language", ""), act.getSharedPreferences("ShopPrefs", 0).getString("store_currency", "")), ServiceHandler.GET);
try {
JSONObject jsonObject = new JSONObject(response);
if(jsonObject.getString("code").equals("0x0000")){
return true;
}
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
@Override
protected void onPostExecute(Boolean result){
if(result){
act.getSharedPreferences("ShopPrefs", 0).edit().putBoolean("is_connected", false).apply();
SuperToast.create(act, getResources().getString(R.string.btn_logout_success), SuperToast.Duration.SHORT, Style.getStyle(Style.RED, SuperToast.Animations.POPUP)).show();
if(noNetworkHandler.showDialog()) {
if (act instanceof MainActivity) {
((MainActivity) act).new GetCartCount().execute();
} else if (act instanceof CategoriesActivity) {
((CategoriesActivity) act).new GetCartCount().execute();
} else if (act instanceof ProductsActivity) {
((ProductsActivity) act).new GetCartCount().execute();
} else if (act instanceof ProductActivity) {
((ProductActivity) act).new GetCartCount().execute();
}
}
}
else {
SuperToast.create(act, getResources().getString(R.string.btn_logout_fail), SuperToast.Duration.SHORT, Style.getStyle(Style.RED, SuperToast.Animations.POPUP)).show();
}
}
}
}
| lioutasb/CSCartApp | app/src/main/java/gr/plushost/prototypeapp/fragments/NavigationDrawerFragment.java | Java | apache-2.0 | 18,920 |
#ifndef color_cmyk_akin_xyz
#define color_cmyk_akin_xyz
#include "../../generic/akin/cmyk.hpp"
#include "../category.hpp"
#include "../../xyz/category.hpp"
namespace color
{
namespace akin
{
template< >struct cmyk< ::color::category::xyz_uint8 >{ typedef ::color::category::cmyk_uint8 akin_type; };
template< >struct cmyk< ::color::category::xyz_uint16 >{ typedef ::color::category::cmyk_uint16 akin_type; };
template< >struct cmyk< ::color::category::xyz_uint32 >{ typedef ::color::category::cmyk_uint32 akin_type; };
template< >struct cmyk< ::color::category::xyz_uint64 >{ typedef ::color::category::cmyk_uint64 akin_type; };
template< >struct cmyk< ::color::category::xyz_float >{ typedef ::color::category::cmyk_float akin_type; };
template< >struct cmyk< ::color::category::xyz_double >{ typedef ::color::category::cmyk_double akin_type; };
template< >struct cmyk< ::color::category::xyz_ldouble >{ typedef ::color::category::cmyk_ldouble akin_type; };
}
}
#endif
| dmilos/color | src/color/cmyk/akin/xyz.hpp | C++ | apache-2.0 | 1,053 |
from __future__ import division
from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
import os
import string
plt.ioff()
data = np.load("attn_weights.npz")
lines = map(lambda x: x.split('\t'), open("sanitycheck.txt", 'r').readlines())
save_dir = "attn_plots3"
sentences = []
current_sent = []
for line in lines:
if len(line) < 10:
sentences.append(map(list, zip(*current_sent)))
current_sent = []
else:
current_sent.append(map(string.strip, (line[1], line[6], line[7], line[8], line[9])))
sentences.append(map(list, zip(*current_sent)))
max_layer = 3
remove_padding = True
plot = False
batch_sum = 0
fig, axes = plt.subplots(nrows=2, ncols=4)
# For each batch+layer
for arr_name in sorted(data.files):
print("Processing %s" % arr_name)
batch_size = data[arr_name].shape[0]
batch = int(arr_name[1])
layer = int(arr_name.split(':')[1][-1])
idx_in_batch = 0
# For each element in the batch (one layer)
# if layer == max_layer and batch > 0:
for b_i, arrays in enumerate(data[arr_name]):
sentence_idx = batch_sum + b_i
width = arrays.shape[-1]
name = "sentence%d_layer%d" % (sentence_idx, layer)
print("Batch: %d, sentence: %d, layer: %d" % (batch, sentence_idx, layer))
sentence = sentences[sentence_idx]
words = sentence[0]
pred_deps = np.array(map(int, sentence[1]))
pred_labels = sentence[2]
gold_deps = np.array(map(int, sentence[3]))
gold_labels = sentence[4]
sent_len = len(words)
text = words + [] if remove_padding else (['PAD'] * (width - sent_len))
gold_deps_xy = np.array(list(enumerate(gold_deps)))
pred_deps_xy = np.array(list(enumerate(pred_deps)))
labels_incorrect = map(lambda x: x[0] != x[1], zip(pred_labels, gold_labels))
incorrect_indices = np.where((pred_deps != gold_deps) | labels_incorrect)
pred_deps_xy_incorrect = pred_deps_xy[incorrect_indices]
pred_labels_incorrect = np.array(pred_labels)[incorrect_indices]
if 'prep' in pred_labels_incorrect:
print(' '.join(text))
print(' '.join(pred_labels))
print(' '.join(gold_labels))
if plot:
correct_dir = "correct" if len(incorrect_indices[0]) == 0 else "incorrect"
fig.suptitle(name, fontsize=16)
# For each attention head
for arr, ax in zip(arrays, axes.flat):
res = ax.imshow(arr[:sent_len, :sent_len], cmap=plt.cm.viridis, interpolation=None)
ax.set_xticks(range(sent_len))
ax.set_yticks(range(sent_len))
ax.set_xticklabels(text, rotation=75, fontsize=2)
ax.set_yticklabels(text, fontsize=2)
map(lambda x: ax.text(x[0][1], x[0][0], x[1], ha="center", va="center", fontsize=1), zip(gold_deps_xy, gold_labels))
map(lambda x: ax.text(x[0][1], x[0][0], x[1], ha="center", va="bottom", fontsize=1, color='red'), zip(pred_deps_xy_incorrect, pred_labels_incorrect))
fig.tight_layout()
fig.savefig(os.path.join(save_dir, correct_dir, name + ".pdf"))
map(lambda x: x.clear(), axes.flat)
if layer == max_layer:
batch_sum += batch_size
| strubell/Parser | bin/plot_attn.py | Python | apache-2.0 | 3,315 |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import mock
from oslo_config import cfg
from webob import exc
from karbor.api.v1 import quotas
from karbor import context
from karbor.tests import base
from karbor.tests.unit.api import fakes
CONF = cfg.CONF
class QuotaApiTest(base.TestCase):
def setUp(self):
super(QuotaApiTest, self).setUp()
self.controller = quotas.QuotasController()
self.ctxt = context.RequestContext('demo', 'fakeproject', True)
@mock.patch(
'karbor.db.sqlalchemy.api.quota_update')
def test_quota_update(self, mock_quota_update):
quota = self._quota_in_request_body()
body = {"quota": quota}
req = fakes.HTTPRequest.blank(
'/v1/quotas/73f74f90a1754bd7ad658afb3272323f',
use_admin_context=True)
self.controller.update(
req, '73f74f90a1754bd7ad658afb3272323f', body=body)
self.assertTrue(mock_quota_update.called)
def test_quota_update_invalid_project_id(self):
quota = self._quota_in_request_body()
body = {"quota": quota}
req = fakes.HTTPRequest.blank(
'/v1/quotas/111', use_admin_context=True)
self.assertRaises(exc.HTTPBadRequest, self.controller.update,
req, '111', body=body)
@mock.patch(
'karbor.quota.DbQuotaDriver.get_defaults')
def test_quota_defaults(self, mock_quota_get):
req = fakes.HTTPRequest.blank(
'v1/quotas/73f74f90a1754bd7ad658afb3272323f',
use_admin_context=True)
self.controller.defaults(
req, '73f74f90a1754bd7ad658afb3272323f')
self.assertTrue(mock_quota_get.called)
@mock.patch(
'karbor.quota.DbQuotaDriver.get_project_quotas')
def test_quota_detail(self, mock_quota_get):
req = fakes.HTTPRequest.blank(
'/v1/quotas/73f74f90a1754bd7ad658afb3272323f',
use_admin_context=True)
self.controller.detail(
req, '73f74f90a1754bd7ad658afb3272323f')
self.assertTrue(mock_quota_get.called)
@mock.patch(
'karbor.quota.DbQuotaDriver.get_project_quotas')
def test_quota_show(self, moak_quota_get):
req = fakes.HTTPRequest.blank(
'/v1/quotas/73f74f90a1754bd7ad658afb3272323f',
use_admin_context=True)
self.controller.show(
req, '73f74f90a1754bd7ad658afb3272323f')
self.assertTrue(moak_quota_get.called)
def test_quota_show_invalid(self):
req = fakes.HTTPRequest.blank('/v1/quotas/1',
use_admin_context=True)
self.assertRaises(
exc.HTTPBadRequest, self.controller.show,
req, "1")
@mock.patch(
'karbor.quota.DbQuotaDriver.destroy_all_by_project')
def test_quota_delete(self, moak_restore_get):
req = fakes.HTTPRequest.blank(
'/v1/quotas/73f74f90a1754bd7ad658afb3272323f',
use_admin_context=True)
self.controller.delete(
req, '73f74f90a1754bd7ad658afb3272323f')
self.assertTrue(moak_restore_get.called)
def test_quota_delete_invalid(self):
req = fakes.HTTPRequest.blank('/v1/quotas/1',
use_admin_context=True)
self.assertRaises(
exc.HTTPBadRequest, self.controller.delete,
req, "1")
def _quota_in_request_body(self):
quota_req = {
"plans": 20,
}
return quota_req
| openstack/smaug | karbor/tests/unit/api/v1/test_quotas.py | Python | apache-2.0 | 4,032 |
/**
* Copyright (c) 2016 - 2018 Syncleus, 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.aparapi.codegen.test;
public class EmptyIfBlock {
public void run() {
int idx = 34;
if(idx < 5) {
}
}
}
/**{Throws{ClassParseException}Throws}**/
| Syncleus/aparapi | src/test/java/com/aparapi/codegen/test/EmptyIfBlock.java | Java | apache-2.0 | 802 |
package com.niedzielski.pixipedia.android.activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.niedzielski.pixipedia.android.R;
import com.niedzielski.pixipedia.android.util.ImageUtil;
import butterknife.InjectView;
public class ImageFragment extends DefaultFragment {
/*default*/ static final String FRAGMENT_ARG_IMAGE_URL_KEY = "imageUrl";
@InjectView(R.id.image)
protected ImageView mImageView;
private String mImageUrl;
public static ImageFragment newInstance(String imageUrl) {
ImageFragment fragment = new ImageFragment();
fragment.setArguments(buildFragmentArgs(imageUrl));
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View view = super.onCreateView(inflater, container, savedInstanceState);
ImageUtil.load(mImageUrl, mImageView);
return view;
}
@Override
protected int getLayout() {
return R.layout.fragment_page_image;
}
@Override
protected void initFromFragmentArgs() {
mImageUrl = getArguments().getString(FRAGMENT_ARG_IMAGE_URL_KEY);
}
private static Bundle buildFragmentArgs(String imageUrl) {
Bundle ret = new Bundle();
ret.putString(FRAGMENT_ARG_IMAGE_URL_KEY, imageUrl);
return ret;
}
} | niedzielski/pixipedia | app/src/main/java/com/niedzielski/pixipedia/android/activity/ImageFragment.java | Java | apache-2.0 | 1,551 |
/* Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0
* http://www.apache.org/licenses/LICENSE-2.0 */
package net.sf.mmm.code.base.arg;
import java.io.IOException;
import java.lang.reflect.Executable;
import java.lang.reflect.Parameter;
import java.util.List;
import java.util.function.Consumer;
import net.sf.mmm.code.api.arg.CodeParameter;
import net.sf.mmm.code.api.arg.CodeParameters;
import net.sf.mmm.code.api.copy.CodeCopyMapper;
import net.sf.mmm.code.api.language.CodeLanguage;
import net.sf.mmm.code.api.member.CodeOperation;
import net.sf.mmm.code.api.merge.CodeMergeStrategy;
import net.sf.mmm.code.base.member.BaseOperation;
/**
* Base implementation of {@link CodeParameters}.
*
* @author Joerg Hohwiller (hohwille at users.sourceforge.net)
* @since 1.0.0
*/
public class BaseParameters extends BaseOperationArgs<CodeParameter> implements CodeParameters {
/**
* The constructor.
*
* @param parent the {@link #getParent() parent}.
*/
public BaseParameters(BaseOperation parent) {
super(parent);
}
/**
* The copy-constructor.
*
* @param template the {@link BaseParameters} to copy.
* @param mapper the {@link CodeCopyMapper}.
*/
public BaseParameters(BaseParameters template, CodeCopyMapper mapper) {
super(template, mapper);
}
@Override
protected void doInitialize() {
super.doInitialize();
Executable reflectiveObject = getParent().getReflectiveObject();
List<? extends CodeParameter> sourceParams = null;
int sourceParamsCount = 0;
CodeParameters sourceParameters = getSourceCodeObject();
if (sourceParameters != null) {
sourceParams = sourceParameters.getDeclared();
sourceParamsCount = sourceParams.size();
}
if (reflectiveObject != null) {
List<CodeParameter> list = getList();
int i = 0;
for (Parameter param : reflectiveObject.getParameters()) {
String name = null;
CodeParameter baseParameter = null;
if ((i < sourceParamsCount) && (sourceParams != null)) {
baseParameter = sourceParams.get(i++);
name = baseParameter.getName();
}
if (name == null) {
name = param.getName();
}
BaseParameter parameter = new BaseParameter(this, name, param, baseParameter);
list.add(parameter);
}
}
}
@Override
public CodeParameter getDeclared(String name) {
initialize();
return getByName(name);
}
@Override
public CodeParameter add(String name) {
BaseParameter parameter = new BaseParameter(this, name);
add(parameter);
return parameter;
}
@Override
public CodeParameters getSourceCodeObject() {
CodeOperation sourceOperation = getParent().getSourceCodeObject();
if (sourceOperation != null) {
return sourceOperation.getParameters();
}
return null;
}
@Override
protected void rename(CodeParameter child, String oldName, String newName, Consumer<String> renamer) {
super.rename(child, oldName, newName, renamer);
}
@Override
public CodeParameters merge(CodeParameters o, CodeMergeStrategy strategy) {
if (strategy == CodeMergeStrategy.KEEP) {
return this;
}
BaseParameters other = (BaseParameters) o;
List<? extends CodeParameter> otherParameters = other.getDeclared();
if (strategy == CodeMergeStrategy.OVERRIDE) {
clear();
for (CodeParameter otherParameter : otherParameters) {
CodeParameter copyParameter = doCopyNode(otherParameter, this);
add(copyParameter);
}
} else {
List<? extends CodeParameter> myParameters = getDeclared();
int i = 0;
int len = myParameters.size();
assert (len == otherParameters.size());
for (CodeParameter otherParameter : otherParameters) {
CodeParameter myParameter = null;
if (i < len) {
myParameter = myParameters.get(i++); // merging via index as by name could cause errors on mismatch
}
if (myParameter == null) {
CodeParameter copyParameter = doCopyNode(otherParameter, this);
add(copyParameter);
} else {
myParameter.merge(otherParameter, strategy);
}
}
}
return this;
}
@Override
public BaseParameters copy() {
return copy(getDefaultCopyMapper());
}
@Override
public BaseParameters copy(CodeCopyMapper mapper) {
return new BaseParameters(this, mapper);
}
@Override
protected void doWrite(Appendable sink, String newline, String defaultIndent, String currentIndent, CodeLanguage language) throws IOException {
writeReference(sink, newline, true);
}
void writeReference(Appendable sink, String newline, boolean declaration) throws IOException {
String prefix = "";
for (CodeParameter parameter : getList()) {
sink.append(prefix);
parameter.write(sink, newline, null, null);
prefix = ", ";
}
}
}
| m-m-m/code | base/src/main/java/net/sf/mmm/code/base/arg/BaseParameters.java | Java | apache-2.0 | 4,951 |
/*
* Copyright 2019 ThoughtWorks, 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.
*/
import {ApiResult} from "helpers/api_request_builder";
import m from "mithril";
import Stream from "mithril/stream";
import {AbstractObjCache, ObjectCache, rejectAsString} from "models/base/cache";
import {ConfigReposCRUD} from "models/config_repos/config_repos_crud";
import {DefinedStructures} from "models/config_repos/defined_structures";
import {ConfigRepo} from "models/config_repos/types";
import {EventAware} from "models/mixins/event_aware";
import {DeleteConfirmModal} from "views/components/modal/delete_confirm_modal";
import {EditConfigRepoModal} from "views/pages/config_repos/modals";
import {FlashContainer, RequiresPluginInfos, SaveOperation} from "views/pages/page_operations";
interface PageResources extends SaveOperation, RequiresPluginInfos, FlashContainer {}
class CRResultCache extends AbstractObjCache<DefinedStructures> {
private repoId: string;
private etag: Stream<string> = Stream();
constructor(repoId: string) {
super();
this.repoId = repoId;
}
doFetch(resolve: (data: DefinedStructures) => void, reject: (reason: string) => void) {
DefinedStructures.fetch(this.repoId, this.etag()).then((result) => {
if (304 === result.getStatusCode()) {
resolve(this.contents()); // no change
return;
}
if (result.getEtag()) {
this.etag(result.getEtag()!);
}
result.do((resp) => {
resolve(DefinedStructures.fromJSON(JSON.parse(resp.body)));
}, (error) => {
reject(error.message);
});
}).catch(rejectAsString(reject));
}
empty() {
// don't dump contents, just force a fresh set of data
this.etag = Stream();
}
}
// a subset of Event
interface Propagable {
stopPropagation: () => void;
}
export class ConfigRepoVM {
repo: ConfigRepo;
results: ObjectCache<DefinedStructures>;
reparseRepo: (e: Propagable) => Promise<void>;
showEditModal: (e: Propagable) => void;
showDeleteModal: (e: Propagable) => void;
constructor(repo: ConfigRepo, page: PageResources, results?: ObjectCache<DefinedStructures>) {
const cache = results || new CRResultCache(repo.id()!);
Object.assign(ConfigRepoVM.prototype, EventAware.prototype);
EventAware.call(this);
this.repo = repo;
this.results = cache;
this.on("expand", () => !cache.failed() && cache.prime(m.redraw));
this.on("refresh", () => (cache.invalidate(), cache.prime(m.redraw)));
this.reparseRepo = (e) => {
e.stopPropagation();
page.flash.clear();
const repoId = this.repo.id()!;
return ConfigReposCRUD.triggerUpdate(repoId).then((result: ApiResult<any>) => {
repo.materialUpdateInProgress(true);
result.do(() => {
page.flash.success(`An update was scheduled for '${repoId}' config repository.`);
this.notify("refresh");
}, (err) => {
page.flash.alert(`Unable to schedule an update for '${repoId}' config repository. ${err.message}`);
});
});
};
this.showEditModal = (e) => {
e.stopPropagation();
page.flash.clear();
new EditConfigRepoModal(this.repo.id()!,
page.onSuccessfulSave,
page.onError,
page.pluginInfos).render();
};
this.showDeleteModal = (e) => {
e.stopPropagation();
page.flash.clear();
const message = ["Are you sure you want to delete the config repository ", m("strong", this.repo.id()), "?"];
const modal = new DeleteConfirmModal(message, () => {
ConfigReposCRUD.delete(this.repo).then((resp) => {
resp.do(
(resp) => page.onSuccessfulSave(resp.body.message),
(err) => page.onError(err.message));
}).then(modal.close.bind(modal));
});
modal.render();
};
}
}
// tslint:disable-next-line
export interface ConfigRepoVM extends EventAware {}
export interface CRVMAware {
vm: ConfigRepoVM;
}
| kierarad/gocd | server/src/main/webapp/WEB-INF/rails/webpack/views/pages/config_repos/config_repo_view_model.ts | TypeScript | apache-2.0 | 4,560 |
package org.apereo.cas.validation;
import org.apereo.cas.TestOneTimePasswordAuthenticationHandler;
import org.apereo.cas.authentication.AcceptUsersAuthenticationHandler;
import org.apereo.cas.authentication.AuthenticationHandler;
import org.apereo.cas.authentication.AuthenticationPolicy;
import org.apereo.cas.authentication.CoreAuthenticationTestUtils;
import org.apereo.cas.authentication.Credential;
import org.apereo.cas.authentication.DefaultAuthenticationEventExecutionPlan;
import org.apereo.cas.authentication.credential.OneTimePasswordCredential;
import org.apereo.cas.authentication.credential.UsernamePasswordCredential;
import org.apereo.cas.authentication.handler.support.SimpleTestUsernamePasswordAuthenticationHandler;
import org.apereo.cas.authentication.policy.AllAuthenticationHandlersSucceededAuthenticationPolicy;
import org.apereo.cas.authentication.policy.AllCredentialsValidatedAuthenticationPolicy;
import org.apereo.cas.authentication.policy.AtLeastOneCredentialValidatedAuthenticationPolicy;
import org.apereo.cas.authentication.policy.RequiredHandlerAuthenticationPolicy;
import org.apereo.cas.config.CasCoreAuthenticationConfiguration;
import org.apereo.cas.config.CasCoreAuthenticationHandlersConfiguration;
import org.apereo.cas.config.CasCoreAuthenticationMetadataConfiguration;
import org.apereo.cas.config.CasCoreAuthenticationPolicyConfiguration;
import org.apereo.cas.config.CasCoreAuthenticationPrincipalConfiguration;
import org.apereo.cas.config.CasCoreAuthenticationSupportConfiguration;
import org.apereo.cas.config.CasCoreConfiguration;
import org.apereo.cas.config.CasCoreHttpConfiguration;
import org.apereo.cas.config.CasCoreServicesAuthenticationConfiguration;
import org.apereo.cas.config.CasCoreServicesConfiguration;
import org.apereo.cas.config.CasCoreTicketCatalogConfiguration;
import org.apereo.cas.config.CasCoreTicketIdGeneratorsConfiguration;
import org.apereo.cas.config.CasCoreTicketsConfiguration;
import org.apereo.cas.config.CasCoreUtilConfiguration;
import org.apereo.cas.config.CasCoreWebConfiguration;
import org.apereo.cas.config.CasPersonDirectoryTestConfiguration;
import org.apereo.cas.config.CasRegisteredServicesTestConfiguration;
import org.apereo.cas.config.support.CasWebApplicationServiceFactoryConfiguration;
import org.apereo.cas.logout.config.CasCoreLogoutConfiguration;
import org.apereo.cas.services.ServicesManager;
import lombok.val;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.mock.web.MockHttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
/**
* This is {@link AuthenticationPolicyAwareServiceTicketValidationAuthorizerTests}.
*
* @author Misagh Moayyed
* @since 6.2.0
*/
@SpringBootTest(classes = {
RefreshAutoConfiguration.class,
CasPersonDirectoryTestConfiguration.class,
CasRegisteredServicesTestConfiguration.class,
CasCoreAuthenticationConfiguration.class,
CasCoreServicesAuthenticationConfiguration.class,
CasCoreAuthenticationPrincipalConfiguration.class,
CasCoreAuthenticationPolicyConfiguration.class,
CasCoreAuthenticationMetadataConfiguration.class,
CasCoreAuthenticationSupportConfiguration.class,
CasCoreAuthenticationHandlersConfiguration.class,
CasCoreWebConfiguration.class,
CasCoreHttpConfiguration.class,
CasCoreUtilConfiguration.class,
CasCoreTicketsConfiguration.class,
CasCoreTicketCatalogConfiguration.class,
CasCoreTicketIdGeneratorsConfiguration.class,
CasCoreLogoutConfiguration.class,
CasCoreConfiguration.class,
CasCoreServicesConfiguration.class,
CasWebApplicationServiceFactoryConfiguration.class,
MailSenderAutoConfiguration.class
})
public class AuthenticationPolicyAwareServiceTicketValidationAuthorizerTests {
@Autowired
@Qualifier("servicesManager")
private ServicesManager servicesManager;
@Autowired
private ConfigurableApplicationContext applicationContext;
private static Assertion getAssertion(final Map<Credential, ? extends AuthenticationHandler> handlers) {
val assertion = mock(Assertion.class);
val principal = CoreAuthenticationTestUtils.getPrincipal("casuser");
val authentication = CoreAuthenticationTestUtils.getAuthenticationBuilder(principal, handlers,
Map.of(AuthenticationHandler.SUCCESSFUL_AUTHENTICATION_HANDLERS,
handlers.values().stream().map(AuthenticationHandler::getName).collect(Collectors.toList()))).build();
when(assertion.getPrimaryAuthentication()).thenReturn(authentication);
return assertion;
}
private static SimpleTestUsernamePasswordAuthenticationHandler getSimpleTestAuthenticationHandler() {
return new SimpleTestUsernamePasswordAuthenticationHandler();
}
private static AcceptUsersAuthenticationHandler getAcceptUsersAuthenticationHandler() {
return new AcceptUsersAuthenticationHandler(Map.of("casuser", "Mellon"));
}
private static OneTimePasswordCredential getOtpCredential() {
return new OneTimePasswordCredential("test", "123456789");
}
private static TestOneTimePasswordAuthenticationHandler getTestOtpAuthenticationHandler() {
return new TestOneTimePasswordAuthenticationHandler(Map.of("casuser", "123456789"));
}
@Test
public void verifyAllAuthenticationHandlersSucceededAuthenticationPolicy() {
val handlers = List.of(getTestOtpAuthenticationHandler(), getAcceptUsersAuthenticationHandler(), getSimpleTestAuthenticationHandler());
val service = CoreAuthenticationTestUtils.getService("https://example.com/high/");
val authz = getAuthorizer(new AllAuthenticationHandlersSucceededAuthenticationPolicy(), handlers);
val map = (Map) Map.of(
new UsernamePasswordCredential(), getAcceptUsersAuthenticationHandler(),
getOtpCredential(), getTestOtpAuthenticationHandler());
val assertion = getAssertion(map);
assertDoesNotThrow(new Executable() {
@Override
public void execute() {
authz.authorize(new MockHttpServletRequest(), service, assertion);
}
});
}
@Test
public void verifyAllCredentialsValidatedAuthenticationPolicy() {
val handlers = List.of(getTestOtpAuthenticationHandler(), getAcceptUsersAuthenticationHandler(), getSimpleTestAuthenticationHandler());
val service = CoreAuthenticationTestUtils.getService("https://example.com/high/");
val authz = getAuthorizer(new AllCredentialsValidatedAuthenticationPolicy(), handlers);
val map = (Map) Map.of(
new UsernamePasswordCredential(), getAcceptUsersAuthenticationHandler(),
getOtpCredential(), getTestOtpAuthenticationHandler());
val assertion = getAssertion(map);
assertDoesNotThrow(new Executable() {
@Override
public void execute() {
authz.authorize(new MockHttpServletRequest(), service, assertion);
}
});
}
@Test
public void verifyRequiredHandlerAuthenticationPolicy() {
val handler = getAcceptUsersAuthenticationHandler();
val handlers = List.of(getTestOtpAuthenticationHandler(), handler, getSimpleTestAuthenticationHandler());
val service = CoreAuthenticationTestUtils.getService("https://example.com/high/");
val authz = getAuthorizer(new RequiredHandlerAuthenticationPolicy(handler.getName()), handlers);
val map = (Map) Map.of(
new UsernamePasswordCredential(), handler,
getOtpCredential(), getTestOtpAuthenticationHandler());
val assertion = getAssertion(map);
assertDoesNotThrow(new Executable() {
@Override
public void execute() {
authz.authorize(new MockHttpServletRequest(), service, assertion);
}
});
}
@Test
public void verifyRequiredHandlerAuthenticationPolicyTryAll() {
val handler = getAcceptUsersAuthenticationHandler();
val handlers = List.of(getTestOtpAuthenticationHandler(), handler, getSimpleTestAuthenticationHandler());
val service = CoreAuthenticationTestUtils.getService("https://example.com/high/");
val authz = getAuthorizer(new RequiredHandlerAuthenticationPolicy(handler.getName(), true), handlers);
val map = (Map) Map.of(
new UsernamePasswordCredential(), handler,
getOtpCredential(), getTestOtpAuthenticationHandler());
val assertion = getAssertion(map);
assertDoesNotThrow(new Executable() {
@Override
public void execute() {
authz.authorize(new MockHttpServletRequest(), service, assertion);
}
});
}
@Test
public void verifyOperationWithHandlersAndAtLeastOneCredential() {
val handlers = List.of(getTestOtpAuthenticationHandler(), getAcceptUsersAuthenticationHandler(), getSimpleTestAuthenticationHandler());
val service = CoreAuthenticationTestUtils.getService("https://example.com/high/");
val authz = getAuthorizer(new AtLeastOneCredentialValidatedAuthenticationPolicy(), handlers);
val map = (Map) Map.of(
new UsernamePasswordCredential(), getAcceptUsersAuthenticationHandler(),
getOtpCredential(), getTestOtpAuthenticationHandler());
val assertion = getAssertion(map);
assertDoesNotThrow(new Executable() {
@Override
public void execute() {
authz.authorize(new MockHttpServletRequest(), service, assertion);
}
});
}
@Test
public void verifyOperationWithHandlersAndAtLeastOneCredentialMustTryAll() {
val handlers = List.of(getTestOtpAuthenticationHandler(), getAcceptUsersAuthenticationHandler(), getSimpleTestAuthenticationHandler());
val service = CoreAuthenticationTestUtils.getService("https://example.com/high/");
val authz = getAuthorizer(new AtLeastOneCredentialValidatedAuthenticationPolicy(true), handlers);
val map = (Map) Map.of(
new UsernamePasswordCredential(), getAcceptUsersAuthenticationHandler(),
getOtpCredential(), getTestOtpAuthenticationHandler());
val assertion = getAssertion(map);
assertDoesNotThrow(new Executable() {
@Override
public void execute() {
authz.authorize(new MockHttpServletRequest(), service, assertion);
}
});
}
private ServiceTicketValidationAuthorizer getAuthorizer(final AuthenticationPolicy policy,
final List<? extends AuthenticationHandler> authenticationHandlers) {
val plan = new DefaultAuthenticationEventExecutionPlan();
plan.registerAuthenticationHandlers(authenticationHandlers);
plan.registerAuthenticationPolicy(policy);
return new AuthenticationPolicyAwareServiceTicketValidationAuthorizer(servicesManager, plan, applicationContext);
}
}
| leleuj/cas | core/cas-server-core-validation/src/test/java/org/apereo/cas/validation/AuthenticationPolicyAwareServiceTicketValidationAuthorizerTests.java | Java | apache-2.0 | 11,612 |
# :nodoc:
#
# Author:: Nathaniel Talbott.
# Copyright:: Copyright (c) 2000-2002 Nathaniel Talbott. All rights reserved.
# License:: Ruby license.
require 'test/unit/util/observable'
module Test
module Unit
# Collects Test::Unit::Failure and Test::Unit::Error so that
# they can be displayed to the user. To this end, observers
# can be added to it, allowing the dynamic updating of, say, a
# UI.
class TestResult
include Util::Observable
CHANGED = "CHANGED"
FAULT = "FAULT"
attr_reader(:run_count, :assertion_count)
# Constructs a new, empty TestResult.
def initialize
@run_count, @assertion_count = 0, 0
@failures, @errors = Array.new, Array.new
end
# Records a test run.
def add_run
@run_count += 1
notify_listeners(CHANGED, self)
end
# Records a Test::Unit::Failure.
def add_failure(failure)
@failures << failure
notify_listeners(FAULT, failure)
notify_listeners(CHANGED, self)
end
# Records a Test::Unit::Error.
def add_error(error)
@errors << error
notify_listeners(FAULT, error)
notify_listeners(CHANGED, self)
end
# Records an individual assertion.
def add_assertion
@assertion_count += 1
notify_listeners(CHANGED, self)
end
# Returns a string contain the recorded runs, assertions,
# failures and errors in this TestResult.
def to_s
"#{run_count} tests, #{assertion_count} assertions, #{failure_count} failures, #{error_count} errors"
end
# Returns whether or not this TestResult represents
# successful completion.
def passed?
return @failures.empty? && @errors.empty?
end
# Returns the number of failures this TestResult has
# recorded.
def failure_count
return @failures.size
end
# Returns the number of errors this TestResult has
# recorded.
def error_count
return @errors.size
end
end
end
end
| krestenkrab/hotruby | modules/vm-shared/ruby/2.0/test/unit/testresult.rb | Ruby | apache-2.0 | 2,086 |
package com.tngtech.archunit.core.importer.testexamples.hierarchicalmethodcall;
public class SuperclassWithCalledMethod {
public static final String method = "method";
String method() {
return null;
}
int maskedMethod() {
return 0;
}
}
| TNG/ArchUnit | archunit/src/test/java/com/tngtech/archunit/core/importer/testexamples/hierarchicalmethodcall/SuperclassWithCalledMethod.java | Java | apache-2.0 | 275 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.flink.runtime.scheduler;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.blob.BlobWriter;
import org.apache.flink.runtime.checkpoint.CheckpointRecoveryFactory;
import org.apache.flink.runtime.concurrent.ScheduledExecutorServiceAdapter;
import org.apache.flink.runtime.executiongraph.failover.flip1.FailoverStrategyFactoryLoader;
import org.apache.flink.runtime.executiongraph.failover.flip1.RestartBackoffTimeStrategy;
import org.apache.flink.runtime.executiongraph.failover.flip1.RestartBackoffTimeStrategyFactoryLoader;
import org.apache.flink.runtime.io.network.partition.JobMasterPartitionTracker;
import org.apache.flink.runtime.jobgraph.JobGraph;
import org.apache.flink.runtime.jobmaster.ExecutionDeploymentTracker;
import org.apache.flink.runtime.jobmaster.slotpool.SlotPool;
import org.apache.flink.runtime.metrics.groups.JobManagerJobMetricGroup;
import org.apache.flink.runtime.rest.handler.legacy.backpressure.BackPressureStatsTracker;
import org.apache.flink.runtime.shuffle.ShuffleMaster;
import org.slf4j.Logger;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledExecutorService;
import static org.apache.flink.runtime.scheduler.DefaultSchedulerComponents.createSchedulerComponents;
/**
* Factory for {@link DefaultScheduler}.
*/
public class DefaultSchedulerFactory implements SchedulerNGFactory {
@Override
public SchedulerNG createInstance(
final Logger log,
final JobGraph jobGraph,
final BackPressureStatsTracker backPressureStatsTracker,
final Executor ioExecutor,
final Configuration jobMasterConfiguration,
final SlotPool slotPool,
final ScheduledExecutorService futureExecutor,
final ClassLoader userCodeLoader,
final CheckpointRecoveryFactory checkpointRecoveryFactory,
final Time rpcTimeout,
final BlobWriter blobWriter,
final JobManagerJobMetricGroup jobManagerJobMetricGroup,
final Time slotRequestTimeout,
final ShuffleMaster<?> shuffleMaster,
final JobMasterPartitionTracker partitionTracker,
final ExecutionDeploymentTracker executionDeploymentTracker,
long initializationTimestamp) throws Exception {
final DefaultSchedulerComponents schedulerComponents = createSchedulerComponents(
jobGraph.getScheduleMode(),
jobGraph.isApproximateLocalRecoveryEnabled(),
jobMasterConfiguration,
slotPool,
slotRequestTimeout);
final RestartBackoffTimeStrategy restartBackoffTimeStrategy = RestartBackoffTimeStrategyFactoryLoader
.createRestartBackoffTimeStrategyFactory(
jobGraph
.getSerializedExecutionConfig()
.deserializeValue(userCodeLoader)
.getRestartStrategy(),
jobMasterConfiguration,
jobGraph.isCheckpointingEnabled())
.create();
log.info("Using restart back off time strategy {} for {} ({}).", restartBackoffTimeStrategy, jobGraph.getName(), jobGraph.getJobID());
return new DefaultScheduler(
log,
jobGraph,
backPressureStatsTracker,
ioExecutor,
jobMasterConfiguration,
schedulerComponents.getStartUpAction(),
futureExecutor,
new ScheduledExecutorServiceAdapter(futureExecutor),
userCodeLoader,
checkpointRecoveryFactory,
rpcTimeout,
blobWriter,
jobManagerJobMetricGroup,
shuffleMaster,
partitionTracker,
schedulerComponents.getSchedulingStrategyFactory(),
FailoverStrategyFactoryLoader.loadFailoverStrategyFactory(jobMasterConfiguration),
restartBackoffTimeStrategy,
new DefaultExecutionVertexOperations(),
new ExecutionVertexVersioner(),
schedulerComponents.getAllocatorFactory(),
executionDeploymentTracker,
initializationTimestamp);
}
}
| greghogan/flink | flink-runtime/src/main/java/org/apache/flink/runtime/scheduler/DefaultSchedulerFactory.java | Java | apache-2.0 | 4,493 |
/**
* Copyright 2015-present Amberfog
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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.amberfog.mapslidingtest.app;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ListView;
public class LockableRecyclerView extends RecyclerView {
private boolean mScrollable = true;
public LockableRecyclerView(Context context) {
super(context);
}
public LockableRecyclerView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public LockableRecyclerView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void setScrollingEnabled(boolean enabled) {
mScrollable = enabled;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
// if we can scroll pass the event to the superclass
if (mScrollable) {
return super.onTouchEvent(ev);
}
// only continue to handle the touch event if scrolling enabled
return mScrollable; // mScrollable is always false at this point
default:
return super.onTouchEvent(ev);
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
// Don't do anything with intercepted touch events if
// we are not scrollable
if (!mScrollable) {
return false;
} else {
return super.onInterceptTouchEvent(ev);
}
}
}
| dlukashev/AndroidSlidingUpPanel-foursquare-map-demo | app/src/main/java/com/amberfog/mapslidingtest/app/LockableRecyclerView.java | Java | apache-2.0 | 2,219 |
import markdownIt from 'markdown-it'
import plusImagePlugin from 'markdown-it-plus-image'
import highlight from 'highlight.js'
import container from 'markdown-it-container'
import { baseURL } from '@/api'
/**
* Create a markdown it instance.
*
* @type {Object}
*/
export const markdown = markdownIt({
breaks: true,
html: true,
highlight: function (code) {
return highlight ? highlight.highlightAuto(code).value : code
},
}).use(plusImagePlugin, `${baseURL}/files/`)
.use(container, 'hljs-left') /* align left */
.use(container, 'hljs-center')/* align center */
.use(container, 'hljs-right')
/**
* Markdown render.
*
* @param {string} markdownText
* @return {String}
* @author Seven Du <shiweidu@outlook.com>
*/
export function render (markdownText) {
return markdown.render(String(markdownText))
}
/**
* Synyax Text AND images.
*
* @param {string} markdownText
* @return {Object: { text: String, images: Array }}
* @author Seven Du <shiweidu@outlook.com>
*/
export function syntaxTextAndImage (markdownText) {
/**
* Get markdown text rende to HTML string.
*
* @type {string}
*/
const html = render(markdownText)
/**
* Match all images HTML code in `html`
*
* @type {Array}
*/
const imageHtmlCodes = html.match(/<img.*?(?:>|\/>)/gi)
/**
* Images.
*
* @type {Array}
*/
let images = []
// For each all image.
if (imageHtmlCodes instanceof Array) {
imageHtmlCodes.forEach(function (imageHtmlCode) {
/**
* Match img HTML tag src attr.
*
* @type {Array}
*/
let result = imageHtmlCode.match(/src=['"]?([^'"]*)['"]?/i)
// If matched push to images array.
if (result !== null && result[1]) {
images.push(result[1])
}
})
}
/**
* Replace all HTML tag to '', And replace img HTML tag to "[图片]"
*
* @type {string}
*/
const text = html
.replace(/<img.*?(?:>|\/>)/gi, '[图片]') // Replace img HTML tag to "[图片]"
.replace(/<\/?.+?>/gi, '') // Removed all HTML tags.
.replace(/ /g, '') // Removed all empty character.
// Return all matched result.
// {
// images: Array,
// text: string
// }
return { images, text }
}
/**
* Export default, export render function.
*/
export default render
| slimkit/thinksns-plus | resources/spa/src/util/markdown.js | JavaScript | apache-2.0 | 2,304 |
package org.smartx.demo.domain;
import org.springframework.stereotype.Repository;
/**
* <p>
*
* </p>
*
* <b>Creation Time:</b> 16/11/23
*
* @author kext
*/
@Repository
public interface UserRepository {
}
| luffyke/springboot-demo | src/main/java/org/smartx/demo/domain/UserRepository.java | Java | apache-2.0 | 214 |
from turbo import register
import app
import api
register.register_group_urls('', [
('/', app.HomeHandler),
('/plus', app.IncHandler),
('/minus', app.MinusHandler),
])
register.register_group_urls('/v1', [
('', api.HomeHandler),
])
| wecatch/app-turbo | demos/jinja2-support/apps/app/__init__.py | Python | apache-2.0 | 253 |
package dao
import (
"context"
"go-common/app/job/main/credit-timer/conf"
"go-common/library/database/sql"
)
// Dao struct info of Dao.
type Dao struct {
db *sql.DB
c *conf.Config
}
// New new a Dao and return.
func New(c *conf.Config) (d *Dao) {
d = &Dao{
c: c,
db: sql.NewMySQL(c.Mysql),
}
return
}
// Close close connections of mc, redis, db.
func (d *Dao) Close() {
if d.db != nil {
d.db.Close()
}
}
// Ping ping health of db.
func (d *Dao) Ping(c context.Context) (err error) {
return d.db.Ping(c)
}
| LQJJ/demo | 126-go-common-master/app/job/main/credit-timer/dao/dao.go | GO | apache-2.0 | 530 |
package org.apereo.cas.configuration.metadata;
import org.apereo.cas.configuration.model.core.authentication.PasswordPolicyProperties;
import org.apereo.cas.configuration.model.core.authentication.PrincipalTransformationProperties;
import org.apereo.cas.configuration.model.support.ldap.AbstractLdapProperties;
import org.apereo.cas.configuration.model.support.ldap.LdapSearchEntryHandlersProperties;
import org.apereo.cas.util.model.Capacity;
import org.apereo.cas.util.model.TriStateBoolean;
import com.github.javaparser.ast.Modifier;
import com.github.javaparser.ast.body.FieldDeclaration;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
import com.github.javaparser.ast.visitor.VoidVisitorAdapter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apereo.services.persondir.support.QueryType;
import org.apereo.services.persondir.util.CaseCanonicalizationMode;
import org.springframework.boot.configurationmetadata.ConfigurationMetadataProperty;
import org.springframework.core.io.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
/**
* This is {@link ConfigurationMetadataFieldVisitor}.
*
* @author Misagh Moayyed
* @since 6.0.0
*/
@Slf4j
@RequiredArgsConstructor
public class ConfigurationMetadataFieldVisitor extends VoidVisitorAdapter<ConfigurationMetadataProperty> {
private static final Pattern EXCLUDED_TYPES;
static {
EXCLUDED_TYPES = Pattern.compile(
String.class.getSimpleName() + '|'
+ Integer.class.getSimpleName() + '|'
+ Double.class.getSimpleName() + '|'
+ Long.class.getSimpleName() + '|'
+ Float.class.getSimpleName() + '|'
+ Boolean.class.getSimpleName() + '|'
+ PrincipalTransformationProperties.CaseConversion.class.getSimpleName() + '|'
+ QueryType.class.getSimpleName() + '|'
+ AbstractLdapProperties.LdapType.class.getSimpleName() + '|'
+ CaseCanonicalizationMode.class.getSimpleName() + '|'
+ TriStateBoolean.class.getSimpleName() + '|'
+ Capacity.class.getSimpleName() + '|'
+ PasswordPolicyProperties.PasswordPolicyHandlingOptions.class.getSimpleName() + '|'
+ LdapSearchEntryHandlersProperties.SearchEntryHandlerTypes.class.getSimpleName() + '|'
+ Map.class.getSimpleName() + '|'
+ Resource.class.getSimpleName() + '|'
+ List.class.getSimpleName() + '|'
+ Set.class.getSimpleName());
}
private final Set<ConfigurationMetadataProperty> properties;
private final Set<ConfigurationMetadataProperty> groups;
private final boolean indexNameWithBrackets;
private final String parentClass;
private final String sourcePath;
private static boolean shouldTypeBeExcluded(final ClassOrInterfaceType type) {
return EXCLUDED_TYPES.matcher(type.getNameAsString()).matches();
}
@Override
public void visit(final FieldDeclaration field, final ConfigurationMetadataProperty property) {
if (field.getVariables().isEmpty()) {
throw new IllegalArgumentException("Field " + field + " has no variable definitions");
}
val variable = field.getVariable(0);
if (field.getModifiers().contains(Modifier.staticModifier())) {
LOGGER.debug("Field [{}] is static and will be ignored for metadata generation", variable.getNameAsString());
return;
}
if (field.getJavadoc().isEmpty()) {
LOGGER.error("Field [{}] has no Javadoc defined", field);
}
val creator = new ConfigurationMetadataPropertyCreator(indexNameWithBrackets, properties, groups, parentClass);
val prop = creator.createConfigurationProperty(field, property.getName());
processNestedClassOrInterfaceTypeIfNeeded(field, prop);
}
private void processNestedClassOrInterfaceTypeIfNeeded(final FieldDeclaration n, final ConfigurationMetadataProperty prop) {
if (n.getElementType() instanceof ClassOrInterfaceType) {
val type = (ClassOrInterfaceType) n.getElementType();
if (!shouldTypeBeExcluded(type)) {
val instance = ConfigurationMetadataClassSourceLocator.getInstance();
val clz = instance.locatePropertiesClassForType(type);
if (clz != null && !clz.isMemberClass()) {
val typePath = ConfigurationMetadataClassSourceLocator.buildTypeSourcePath(this.sourcePath, clz.getName());
val parser = new ConfigurationMetadataUnitParser(this.sourcePath);
parser.parseCompilationUnit(properties, groups, prop, typePath, clz.getName(), false);
}
}
}
}
}
| pdrados/cas | api/cas-server-core-api-configuration-model/src/main/java/org/apereo/cas/configuration/metadata/ConfigurationMetadataFieldVisitor.java | Java | apache-2.0 | 4,907 |
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { diag } from '@opentelemetry/api';
import { getEnv } from '@opentelemetry/core';
import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions';
import { Resource } from '../Resource';
import { Detector, ResourceAttributes } from '../types';
import { ResourceDetectionConfig } from '../config';
/**
* EnvDetector can be used to detect the presence of and create a Resource
* from the OTEL_RESOURCE_ATTRIBUTES environment variable.
*/
class EnvDetector implements Detector {
// Type, attribute keys, and attribute values should not exceed 256 characters.
private readonly _MAX_LENGTH = 255;
// OTEL_RESOURCE_ATTRIBUTES is a comma-separated list of attributes.
private readonly _COMMA_SEPARATOR = ',';
// OTEL_RESOURCE_ATTRIBUTES contains key value pair separated by '='.
private readonly _LABEL_KEY_VALUE_SPLITTER = '=';
private readonly _ERROR_MESSAGE_INVALID_CHARS =
'should be a ASCII string with a length greater than 0 and not exceed ' +
this._MAX_LENGTH +
' characters.';
private readonly _ERROR_MESSAGE_INVALID_VALUE =
'should be a ASCII string with a length not exceed ' +
this._MAX_LENGTH +
' characters.';
/**
* Returns a {@link Resource} populated with attributes from the
* OTEL_RESOURCE_ATTRIBUTES environment variable. Note this is an async
* function to conform to the Detector interface.
*
* @param config The resource detection config
*/
async detect(_config?: ResourceDetectionConfig): Promise<Resource> {
const attributes: ResourceAttributes = {};
const env = getEnv();
const rawAttributes = env.OTEL_RESOURCE_ATTRIBUTES;
const serviceName = env.OTEL_SERVICE_NAME;
if (rawAttributes) {
try {
const parsedAttributes = this._parseResourceAttributes(rawAttributes);
Object.assign(attributes, parsedAttributes);
} catch (e) {
diag.debug(`EnvDetector failed: ${e.message}`);
}
}
if (serviceName) {
attributes[SemanticResourceAttributes.SERVICE_NAME] = serviceName;
}
return new Resource(attributes);
}
/**
* Creates an attribute map from the OTEL_RESOURCE_ATTRIBUTES environment
* variable.
*
* OTEL_RESOURCE_ATTRIBUTES: A comma-separated list of attributes describing
* the source in more detail, e.g. “key1=val1,key2=val2”. Domain names and
* paths are accepted as attribute keys. Values may be quoted or unquoted in
* general. If a value contains whitespaces, =, or " characters, it must
* always be quoted.
*
* @param rawEnvAttributes The resource attributes as a comma-seperated list
* of key/value pairs.
* @returns The sanitized resource attributes.
*/
private _parseResourceAttributes(
rawEnvAttributes?: string
): ResourceAttributes {
if (!rawEnvAttributes) return {};
const attributes: ResourceAttributes = {};
const rawAttributes: string[] = rawEnvAttributes.split(
this._COMMA_SEPARATOR,
-1
);
for (const rawAttribute of rawAttributes) {
const keyValuePair: string[] = rawAttribute.split(
this._LABEL_KEY_VALUE_SPLITTER,
-1
);
if (keyValuePair.length !== 2) {
continue;
}
let [key, value] = keyValuePair;
// Leading and trailing whitespaces are trimmed.
key = key.trim();
value = value.trim().split('^"|"$').join('');
if (!this._isValidAndNotEmpty(key)) {
throw new Error(`Attribute key ${this._ERROR_MESSAGE_INVALID_CHARS}`);
}
if (!this._isValid(value)) {
throw new Error(`Attribute value ${this._ERROR_MESSAGE_INVALID_VALUE}`);
}
attributes[key] = value;
}
return attributes;
}
/**
* Determines whether the given String is a valid printable ASCII string with
* a length not exceed _MAX_LENGTH characters.
*
* @param str The String to be validated.
* @returns Whether the String is valid.
*/
private _isValid(name: string): boolean {
return name.length <= this._MAX_LENGTH && this._isPrintableString(name);
}
private _isPrintableString(str: string): boolean {
for (let i = 0; i < str.length; i++) {
const ch: string = str.charAt(i);
if (ch <= ' ' || ch >= '~') {
return false;
}
}
return true;
}
/**
* Determines whether the given String is a valid printable ASCII string with
* a length greater than 0 and not exceed _MAX_LENGTH characters.
*
* @param str The String to be validated.
* @returns Whether the String is valid and not empty.
*/
private _isValidAndNotEmpty(str: string): boolean {
return str.length > 0 && this._isValid(str);
}
}
export const envDetector = new EnvDetector();
| open-telemetry/opentelemetry-js | packages/opentelemetry-resources/src/detectors/EnvDetector.ts | TypeScript | apache-2.0 | 5,327 |
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.roots.ui.configuration;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.roots.ModuleRootModel;
import com.intellij.facet.FacetModel;
import com.intellij.facet.FacetManager;
/**
* @author nik
*/
public class DefaultModulesProvider implements ModulesProvider {
private final Project myProject;
public DefaultModulesProvider(final Project project) {
myProject = project;
}
public Module[] getModules() {
return ModuleManager.getInstance(myProject).getModules();
}
public Module getModule(String name) {
return ModuleManager.getInstance(myProject).findModuleByName(name);
}
public ModuleRootModel getRootModel(Module module) {
return ModuleRootManager.getInstance(module);
}
public FacetModel getFacetModel(Module module) {
return FacetManager.getInstance(module);
}
}
| jexp/idea2 | platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/DefaultModulesProvider.java | Java | apache-2.0 | 1,618 |
"""
thainlp tag command line.
"""
import argparse
from pythainlp import cli
from pythainlp.tag import locations, named_entity, pos_tag
class SubAppBase:
def __init__(self, name, argv):
parser = argparse.ArgumentParser(**cli.make_usage("tag " + name))
parser.add_argument(
"text", type=str, help="input text",
)
parser.add_argument(
"-s",
"--sep",
dest="separator",
type=str,
help=f"Token separator for input text. default: {self.separator}",
default=self.separator,
)
args = parser.parse_args(argv)
self.args = args
tokens = args.text.split(args.separator)
result = self.run(tokens)
for word, tag in result:
print(word, "/", tag)
class POSTaggingApp(SubAppBase):
def __init__(self, *args, **kwargs):
self.separator = "|"
self.run = pos_tag
super().__init__(*args, **kwargs)
class App:
def __init__(self, argv):
parser = argparse.ArgumentParser(
prog="tag",
description="Annotate a text with linguistic information",
usage=(
'thainlp tag <tag_type> [--sep "<separator>"] "<text>"\n\n'
"tag_type:\n\n"
"pos part-of-speech\n\n"
"<separator> and <text> should be inside double quotes.\n"
"<text> should be a tokenized text, "
"with tokens separated by <separator>.\n\n"
"Example:\n\n"
'thainlp tag pos -s " " "แรงดึงดูด เก็บ หัว คุณ ลง"\n\n'
"--"
),
)
parser.add_argument("tag_type", type=str, help="[pos]")
args = parser.parse_args(argv[2:3])
cli.exit_if_empty(args.tag_type, parser)
tag_type = str.lower(args.tag_type)
argv = argv[3:]
if tag_type == "pos":
POSTaggingApp("Part-of-Speech tagging", argv)
else:
print(f"Tag type not available: {tag_type}")
| PyThaiNLP/pythainlp | pythainlp/cli/tag.py | Python | apache-2.0 | 2,123 |
/*
* Copyright 2012-2015 Red Hat Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.ovirt.engine.extension.aaa.ldap;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Util {
private static final Pattern VAR_PATTERN = Pattern.compile("\\$\\{((?<namespace>[^:}]*):)?(?<var>[^}]*)\\}");
private static final Map<Class<?>, Class<?>> typeBox = new HashMap<>();
static {
typeBox.put(boolean.class, Boolean.class);
typeBox.put(byte.class, Byte.class);
typeBox.put(char.class, Character.class);
typeBox.put(double.class, Double.class);
typeBox.put(float.class, Float.class);
typeBox.put(int.class, Integer.class);
typeBox.put(long.class, Long.class);
typeBox.put(short.class, Short.class);
typeBox.put(void.class, Void.class);
}
public static String toString(Object o, String def) {
return o != null ? o.toString() : def;
}
public static String toString(Object o) {
return toString(o, "");
}
public static void removeKeysWithPrefix(Map<String, Object> map, String prefix) {
Iterator<Map.Entry<String, Object>> iter = map.entrySet().iterator();
while(iter.hasNext()) {
Map.Entry<String, Object> e = iter.next();
if (e.getKey().startsWith(prefix)) {
iter.remove();
}
}
}
public static String expandString(String s, String namespace, Map<? extends Object, ? extends Object> vars) {
StringBuilder ret = new StringBuilder();
Matcher m = VAR_PATTERN.matcher(s);
int last = 0;
while (m.find()) {
ret.append(s.substring(last, m.start()));
if (
(namespace == null && m.group("namespace") == null) ||
(namespace != null && namespace.equals(m.group("namespace")))
) {
Object o = vars.get(m.group("var"));
if (o != null) {
ret.append(o);
}
} else {
ret.append(m.group(0));
}
last = m.end();
}
ret.append(s.substring(last, m.regionEnd()));
return ret.toString();
}
public static void _expandMap(MapProperties props, String namespace, Map<? extends Object, ? extends Object> vars) {
if (props.getValue() != null) {
props.setValue(expandString(props.getValue(), namespace, vars));
}
for (MapProperties entry : props.getMap().values()) {
_expandMap(entry, namespace, vars);
}
}
public static MapProperties expandMap(MapProperties props, String namespace, Map<? extends Object, ? extends Object> vars) {
MapProperties ret = new MapProperties(props);
MapProperties old;
do {
old = new MapProperties(ret);
_expandMap(ret, namespace, vars);
} while(!old.equals(ret));
return ret;
}
public static Properties expandProperties(
Properties props,
String namespace,
Map<? extends Object, ? extends Object> vars,
boolean recursive
) {
Properties ret = new Properties();
ret.putAll(props);
Properties old;
do {
old = new Properties();
old.putAll(ret);
for (Map.Entry<Object, Object> entry : ret.entrySet()) {
entry.setValue(expandString(entry.getValue().toString(), namespace, vars));
}
} while(recursive && !old.equals(ret));
return ret;
}
public static List<String> stringPropertyNames(Properties props, String prefix) {
if (prefix.endsWith(".")) {
prefix = prefix.substring(0, prefix.length()-1);
}
List<String> keys = new LinkedList<>();
for (String key : props.stringPropertyNames()) {
if (key.equals(prefix) || key.startsWith(prefix + ".")) {
keys.add(key);
}
}
Collections.sort(keys);
return keys;
}
public static void includeProperties(
Properties out,
String includeKey,
List<File> includeDirectories,
File file
) throws IOException {
Properties props = new Properties();
try (
InputStream is = new FileInputStream(file);
Reader reader = new InputStreamReader(is, StandardCharsets.UTF_8);
) {
props.load(reader);
}
props.put("_basedir", file.getParent());
props = expandProperties(props, "local", props, true);
for (String key : stringPropertyNames(props, includeKey)) {
String include = props.getProperty(key);
File includeFile = null;
if (include.startsWith("<") && include.endsWith(">")) {
include = include.substring(1, include.length()-1);
for (File i : includeDirectories) {
File t = new File(i, include);
if (t.exists()) {
includeFile = t;
break;
}
}
if (includeFile == null) {
throw new FileNotFoundException(
String.format(
"Cannot include file '%s' from search path %s",
include,
includeDirectories
)
);
}
} else {
includeFile = new File(include);
if (!includeFile.isAbsolute()) {
includeFile = new File(file.getParentFile(), include);
}
}
includeProperties(out, includeKey, includeDirectories, includeFile);
}
for (Map.Entry<Object, Object> entry : props.entrySet()) {
out.put(entry.getKey(), entry.getValue());
}
}
public static Properties loadProperties(List<File> includeDirectories, File... file) throws IOException {
Properties props = new Properties();
for (File f : file) {
includeProperties(props, "include", includeDirectories, f);
}
props = expandProperties(props, "global", props, true);
props = expandProperties(props, "sys", System.getProperties(), false);
return props;
}
public static int[] asIntArray(List<?> l, int def, int size) {
int[] ret = new int[size];
Arrays.fill(ret, def);
for (int i = 0; i < l.size() && i < size; i++) {
ret[i] = Integer.valueOf(l.get(i).toString());
}
return ret;
}
public static List<String> getValueFromMapRecord(MapProperties props, String key) {
List<String> ret = new ArrayList<>();
for (MapProperties entry : props.getMap().values()) {
String v = entry.getString(null, key);
if (v != null) {
ret.add(v);
}
}
return ret;
}
public static Object getObjectValueByString(Class<?> clazz, String value) {
Object v = null;
if (clazz.isPrimitive()) {
clazz = typeBox.get(clazz);
}
if (v == null) {
if (clazz.equals(Collection.class)) {
List<Object> r = new ArrayList<>();
for (String c : value.trim().split(" *, *")) {
if (!c.isEmpty()) {
r.add(getObjectValueByString(String.class, c));
}
}
v = r;
}
}
if (v == null) {
if (clazz.isArray() && Object.class.isAssignableFrom(clazz.getComponentType())) {
List<Object> r = new ArrayList<>();
for (String c : value.trim().split(" *, *")) {
if (!c.isEmpty()) {
r.add(getObjectValueByString(clazz.getComponentType(), c));
}
}
v = (Object)r.toArray((Object[]) Array.newInstance(clazz.getComponentType(), 0));
}
}
if (v == null) {
try {
Field f = clazz.getField(value);
if (Modifier.isStatic(f.getModifiers())) {
v = f.get(null);
}
} catch(ReflectiveOperationException e) {}
}
if (v == null) {
try {
Method convert = clazz.getMethod("valueOf", String.class);
if (Modifier.isStatic(convert.getModifiers())) {
v = convert.invoke(null, value);
}
} catch(ReflectiveOperationException e) {}
}
if (v == null) {
try {
Method convert = clazz.getMethod("valueOf", Object.class);
if (Modifier.isStatic(convert.getModifiers())) {
v = convert.invoke(null, value);
}
} catch(ReflectiveOperationException e) {}
}
if (v == null) {
try {
Constructor<?> constructor = clazz.getDeclaredConstructor(String.class);
v = constructor.newInstance(value);
} catch(ReflectiveOperationException e) {}
}
return v;
}
public static void setObjectByProperties(Object o, MapProperties props, String... methodPrefixes) {
if (props == null) {
return;
}
for (Method m : o.getClass().getMethods()) {
for (String p : methodPrefixes) {
String methodName = m.getName();
if (methodName.startsWith(p)) {
String name = (
methodName.substring(p.length(), p.length()+1).toLowerCase() +
methodName.substring(p.length()+1)
);
try {
List<String> values = new ArrayList<>();
MapProperties valueProps = props.getOrEmpty(name);
values.add(valueProps.getValue());
for (MapProperties valueProps1 : valueProps.getMap().values()) {
values.add(valueProps1.getValue());
}
for (String value : values) {
if (value != null) {
Class<?>[] args = m.getParameterTypes();
if (args.length == 1) {
Object v = getObjectValueByString(args[0], value);
if (v != null) {
m.invoke(o, v);
}
}
}
}
} catch(Exception e) {
throw new RuntimeException(
String.format(
"Cannot set key '%s', error: %s",
name,
e.getMessage()
),
e
);
}
}
}
}
}
public static <T extends Enum<T>> List<T> getEnumFromString(Class<T> clazz, String value) {
List<T> ret = new ArrayList<>();
if (value != null) {
String[] comps = value.trim().split(" *, *");
for (String c : comps) {
if (!c.isEmpty()) {
ret.add(T.valueOf(clazz, c));
}
}
}
return ret;
}
public static KeyStore loadKeyStore(String provider, String type, String file, String password)
throws GeneralSecurityException, IOException {
KeyStore store = null;
if (file != null) {
try (InputStream in = new FileInputStream(file)) {
if (type == null) {
type = KeyStore.getDefaultType();
}
if (provider == null) {
store = KeyStore.getInstance(
type
);
} else {
store = KeyStore.getInstance(
type,
provider
);
}
store.load(in, password.toCharArray());
}
}
return store;
}
}
// vim: expandtab tabstop=4 shiftwidth=4
| oVirt/ovirt-engine-extension-aaa-ldap | src/main/java/org/ovirt/engine/extension/aaa/ldap/Util.java | Java | apache-2.0 | 13,912 |
/*
* Copyright (c) 2014 the original author or authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.werval.modules.xml.internal;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.XMLConstants;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.validation.Schema;
import io.werval.modules.xml.SAX;
import io.werval.modules.xml.UncheckedXMLException;
import org.xml.sax.HandlerBase;
import org.xml.sax.InputSource;
import org.xml.sax.Parser;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import static io.werval.modules.xml.internal.Internal.ACCESS_EXTERNAL_ALL;
import static io.werval.modules.xml.internal.Internal.ACCESS_EXTERNAL_NONE;
import static io.werval.modules.xml.internal.Internal.LOG;
/**
* SAXParserFactory implementation for XMLPlugin.
* <p>
* Factory API that enables applications to configure and obtain a SAX based parser to parse XML documents.
*
* @see SAXParserFactory
*/
public final class SAXParserFactoryImpl
extends SAXParserFactory
{
// Aalto
// private final SAXParserFactory delegate = new com.fasterxml.aalto.sax.SAXParserFactoryImpl();
// Woodstox
// private final SAXParserFactory delegate = new com.ctc.wstx.sax.WstxSAXParserFactory();
// Xerces
private final SAXParserFactory delegate = new org.apache.xerces.jaxp.SAXParserFactoryImpl();
public SAXParserFactoryImpl()
throws ParserConfigurationException, SAXException
{
// Aalto & Woodstox & Xerces
delegate.setFeature( SAX.Features.EXTERNAL_GENERAL_ENTITIES, Internal.EXTERNAL_ENTITIES.get() );
delegate.setFeature( SAX.Features.EXTERNAL_PARAMETER_ENTITIES, Internal.EXTERNAL_ENTITIES.get() );
// Xerces
delegate.setFeature( XMLConstants.FEATURE_SECURE_PROCESSING, true );
delegate.setFeature( "http://apache.org/xml/features/standard-uri-conformant", true );
setValidating( false );
// No support but should be disabled anyway, belt'n braces
delegate.setXIncludeAware( false );
}
@Override
public void setNamespaceAware( boolean namespaceAware )
{
delegate.setNamespaceAware( namespaceAware );
}
@Override
public void setValidating( boolean dtdValidation )
{
try
{
// Xerces
delegate.setFeature( "http://apache.org/xml/features/validation/balance-syntax-trees", dtdValidation );
delegate.setFeature( "http://apache.org/xml/features/nonvalidating/load-dtd-grammar", dtdValidation );
delegate.setFeature(
"http://apache.org/xml/features/nonvalidating/load-external-dtd",
dtdValidation && Internal.EXTERNAL_ENTITIES.get()
);
delegate.setFeature( "http://apache.org/xml/features/disallow-doctype-decl", !dtdValidation );
}
catch( ParserConfigurationException | SAXNotRecognizedException | SAXNotSupportedException ex )
{
throw new UncheckedXMLException( ex );
}
delegate.setValidating( dtdValidation );
if( dtdValidation )
{
LOG.warn( "SAXParserFactory.setValidating( true ) Unsafe DTD support enabled" );
}
}
@Override
public boolean isNamespaceAware()
{
return delegate.isNamespaceAware();
}
@Override
public boolean isValidating()
{
return delegate.isValidating();
}
@Override
public Schema getSchema()
{
return delegate.getSchema();
}
@Override
public void setSchema( Schema schema )
{
delegate.setSchema( schema );
}
@Override
public void setXIncludeAware( boolean xIncludeAware )
{
delegate.setXIncludeAware( xIncludeAware );
}
@Override
public boolean isXIncludeAware()
{
return delegate.isXIncludeAware();
}
@Override
public SAXParser newSAXParser()
throws ParserConfigurationException, SAXException
{
return new SAXParserImpl( delegate.newSAXParser() );
}
@Override
public void setFeature( String name, boolean value )
throws ParserConfigurationException, SAXNotRecognizedException, SAXNotSupportedException
{
delegate.setFeature( name, value );
}
@Override
public boolean getFeature( String name )
throws ParserConfigurationException, SAXNotRecognizedException, SAXNotSupportedException
{
return delegate.getFeature( name );
}
private static final class SAXParserImpl
extends SAXParser
{
private final SAXParser parser;
protected SAXParserImpl( SAXParser saxParser )
throws SAXException
{
this.parser = saxParser;
try
{
this.parser.setProperty(
XMLConstants.ACCESS_EXTERNAL_DTD,
Internal.EXTERNAL_ENTITIES.get() ? ACCESS_EXTERNAL_ALL : ACCESS_EXTERNAL_NONE
);
}
catch( SAXException ex )
{
LOG.trace( "JAXP<1.5 - {} on {}", ex.getMessage(), this.parser );
}
try
{
this.parser.setProperty(
XMLConstants.ACCESS_EXTERNAL_SCHEMA,
Internal.EXTERNAL_ENTITIES.get() ? ACCESS_EXTERNAL_ALL : ACCESS_EXTERNAL_NONE
);
}
catch( SAXException ex )
{
LOG.trace( "JAXP<1.5 - {} on {}", ex.getMessage(), this.parser );
}
}
@Override
public void reset()
{
parser.reset();
}
@Override
public void parse( InputStream inputStream, HandlerBase handlerBase )
throws SAXException, IOException
{
parser.parse( inputStream, handlerBase );
}
@Override
public void parse( InputStream inputStream, HandlerBase handlerBase, String systemId )
throws SAXException, IOException
{
parser.parse( inputStream, handlerBase, systemId );
}
@Override
public void parse( InputStream inputStream, DefaultHandler defaultHandler )
throws SAXException, IOException
{
parser.parse( inputStream, defaultHandler );
}
@Override
public void parse( InputStream inputStream, DefaultHandler defaultHandler, String systemId )
throws SAXException, IOException
{
parser.parse( inputStream, defaultHandler, systemId );
}
@Override
public void parse( String s, HandlerBase handlerBase )
throws SAXException, IOException
{
parser.parse( s, handlerBase );
}
@Override
public void parse( String s, DefaultHandler defaultHandler )
throws SAXException, IOException
{
parser.parse( s, defaultHandler );
}
@Override
public void parse( File file, HandlerBase handlerBase )
throws SAXException, IOException
{
parser.parse( file, handlerBase );
}
@Override
public void parse( File file, DefaultHandler defaultHandler )
throws SAXException, IOException
{
parser.parse( file, defaultHandler );
}
@Override
public void parse( InputSource inputSource, HandlerBase handlerBase )
throws SAXException, IOException
{
parser.parse( inputSource, handlerBase );
}
@Override
public void parse( InputSource inputSource, DefaultHandler defaultHandler )
throws SAXException, IOException
{
parser.parse( inputSource, defaultHandler );
}
@Override
public Parser getParser()
throws SAXException
{
return parser.getParser();
}
@Override
public XMLReader getXMLReader()
throws SAXException
{
XMLReader reader = parser.getXMLReader();
try
{
reader.setFeature( XMLConstants.FEATURE_SECURE_PROCESSING, true );
}
catch( SAXNotRecognizedException ex )
{
LOG.trace( "JAXP<1.5 - {} on {}", ex.getMessage(), reader );
}
reader.setFeature( SAX.Features.EXTERNAL_GENERAL_ENTITIES, Internal.EXTERNAL_ENTITIES.get() );
reader.setFeature( SAX.Features.EXTERNAL_PARAMETER_ENTITIES, Internal.EXTERNAL_ENTITIES.get() );
reader.setEntityResolver( Internal.RESOLVER.get() );
reader.setErrorHandler( Errors.INSTANCE );
return reader;
}
@Override
public boolean isNamespaceAware()
{
return parser.isNamespaceAware();
}
@Override
public boolean isValidating()
{
return parser.isValidating();
}
@Override
public void setProperty( String name, Object value )
throws SAXNotRecognizedException, SAXNotSupportedException
{
parser.setProperty( name, value );
}
@Override
public Object getProperty( String name )
throws SAXNotRecognizedException, SAXNotSupportedException
{
return parser.getProperty( name );
}
@Override
public Schema getSchema()
{
return parser.getSchema();
}
@Override
public boolean isXIncludeAware()
{
return parser.isXIncludeAware();
}
}
}
| werval/werval | io.werval.modules/io.werval.modules.xml/src/main/java/io/werval/modules/xml/internal/SAXParserFactoryImpl.java | Java | apache-2.0 | 10,474 |
package com.crawljax.oracle;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import com.crawljax.oraclecomparator.Comparator;
import com.crawljax.oraclecomparator.comparators.AttributeComparator;
import com.crawljax.oraclecomparator.comparators.DateComparator;
import com.crawljax.oraclecomparator.comparators.EditDistanceComparator;
import com.crawljax.oraclecomparator.comparators.PlainStructureComparator;
import com.crawljax.oraclecomparator.comparators.RegexComparator;
import com.crawljax.oraclecomparator.comparators.ScriptComparator;
import com.crawljax.oraclecomparator.comparators.SimpleComparator;
import com.crawljax.oraclecomparator.comparators.StyleComparator;
import com.crawljax.oraclecomparator.comparators.XPathExpressionComparator;
import org.junit.Test;
/**
* @author danny
* @version $Id: OracleTest.java 441 2010-09-13 19:28:10Z slenselink@google.com $
*/
public class OracleTest {
private void compareTwoDomsWithComparatorEqual(
String original, String newDom, Comparator comparator) {
comparator.setOriginalDom(original);
comparator.setNewDom(newDom);
assertTrue(comparator.isEquivalent());
}
private void compareTwoDomsWithComparatorNotEqual(
String original, String newDom, Comparator comparator) {
comparator.setOriginalDom(original);
comparator.setNewDom(newDom);
assertFalse(comparator.isEquivalent());
}
@Test
public void testDateOracle() {
Comparator oracle = new DateComparator();
/* dates with days */
compareTwoDomsWithComparatorEqual("<HTML>Monday 15 march 1998</HTML>",
"<HTML>Tuesday 13 december 2005</HTML>", oracle);
compareTwoDomsWithComparatorEqual(
"<HTML>Monday 1 feb '98</HTML>", "<HTML>Wednesday 15 march '00</HTML>", oracle);
compareTwoDomsWithComparatorEqual(
"<HTML>Friday 10 february</HTML>", "<HTML>Wednesday 3 march</HTML>", oracle);
/* dates only numeric */
compareTwoDomsWithComparatorEqual(
"<HTML>28-12-1983</HTML>", "<HTML>15-3-1986</HTML>", oracle);
compareTwoDomsWithComparatorEqual(
"<HTML>28.1.1976</HTML>", "<HTML>3.15.1986</HTML>", oracle);
compareTwoDomsWithComparatorEqual(
"<HTML>1/1/2001</HTML>", "<HTML>30/12/1988</HTML>", oracle);
compareTwoDomsWithComparatorEqual(
"<HTML>28-12-1983</HTML>", "<HTML>19-2-1986</HTML>", oracle);
compareTwoDomsWithComparatorEqual(
"<HTML>28.1.1976</HTML>", "<HTML>3.15.1986</HTML>", oracle);
compareTwoDomsWithComparatorEqual(
"<HTML>1/1/2001</HTML>", "<HTML>30/12/1988</HTML>", oracle);
compareTwoDomsWithComparatorEqual(
"<HTML>28-12-'83</HTML>", "<HTML>19-1-'86</HTML>", oracle);
compareTwoDomsWithComparatorEqual(
"<HTML>28.1.'76</HTML>", "<HTML>3.15.'86</HTML>", oracle);
compareTwoDomsWithComparatorEqual(
"<HTML>1/1/'01</HTML>", "<HTML>30/12/'88</HTML>", oracle);
compareTwoDomsWithComparatorEqual(
"<HTML>2003-16-03</HTML>", "<HTML>1986-3-3</HTML>", oracle);
compareTwoDomsWithComparatorEqual(
"<HTML>1993.12.12</HTML>", "<HTML>1997.13.09</HTML>", oracle);
compareTwoDomsWithComparatorEqual(
"<HTML>2013/1/3</HTML>", "<HTML>1986/3/3</HTML>", oracle);
/* dates with long months */
compareTwoDomsWithComparatorEqual(
"<HTML>19 november 1986</HTML>", "<HTML>18 june 1973</HTML>", oracle);
compareTwoDomsWithComparatorEqual(
"<HTML>1th march 1986</HTML>", "<HTML>28th december 2005</HTML>", oracle);
compareTwoDomsWithComparatorEqual(
"<HTML>15th november</HTML>", "<HTML>3th july</HTML>", oracle);
compareTwoDomsWithComparatorEqual(
"<HTML>2003 March 15</HTML>", "<HTML>1978 july 5</HTML>", oracle);
compareTwoDomsWithComparatorEqual(
"<HTML>2003Apr15</HTML>", "<HTML>1978jul5</HTML>", oracle);
compareTwoDomsWithComparatorEqual(
"<HTML>March 2003</HTML>", "<HTML>October 1996</HTML>", oracle);
compareTwoDomsWithComparatorEqual(
"<HTML>April '02</HTML>", "<HTML>August '99</HTML>", oracle);
compareTwoDomsWithComparatorEqual(
"<HTML>April 19 2007</HTML>", "<HTML>January 1 1994</HTML>", oracle);
compareTwoDomsWithComparatorEqual(
"<HTML>April 19, 2007</HTML>", "<HTML>January 1, 1994</HTML>", oracle);
compareTwoDomsWithComparatorEqual(
"<HTML>April 4 '07</HTML>", "<HTML>January 1 '87</HTML>", oracle);
compareTwoDomsWithComparatorEqual(
"<HTML>April 19, '66</HTML>", "<HTML>January 1, '88</HTML>", oracle);
/* time */
compareTwoDomsWithComparatorEqual(
"<HTML>4:47:00 am</HTML>", "<HTML>3:59:2PM</HTML>", oracle);
compareTwoDomsWithComparatorEqual("<HTML>2:13pm</HTML>", "<HTML>3:59am</HTML>", oracle);
compareTwoDomsWithComparatorEqual(
"<HTML>14:17:29</HTML>", "<HTML>7:34:26</HTML>", oracle);
}
@Test
public void testStyleOracle() {
Comparator oracle = new StyleComparator();
/* IGNORE_TAGS */
compareTwoDomsWithComparatorEqual("<HTML><B>foo</B></HTML>", "<HTML>foo</HTML>", oracle);
compareTwoDomsWithComparatorEqual(
"<HTML><PRE>foo</PRE></HTML>", "<HTML><STRONG>foo</STRONG></HTML>", oracle);
compareTwoDomsWithComparatorEqual("<HTML><FONT color=\"red\">foo</FONT> bar</HTML>",
"<HTML>foo bar</HTML>", oracle);
compareTwoDomsWithComparatorEqual("<HTML><FONT color=\"red\">foo</FONT> bar</HTML>",
"<HTML><FONT color=\"green\">foo</FONT> bar</HTML>", oracle);
/* IGNORE_ATTRIBUTES */
compareTwoDomsWithComparatorEqual("<HTML><SPAN width=\"100px\">foo</SPAN></HTML>",
"<HTML><SPAN>foo</SPAN></HTML>", oracle);
compareTwoDomsWithComparatorEqual("<HTML><SPAN>foo</SPAN></HTML>",
"<HTML><SPAN valign=\"top\">foo</SPAN></HTML>", oracle);
/* STYLE ATTRIBUTES */
compareTwoDomsWithComparatorEqual(
"<HTML><SPAN style=\"color: green;\">foo</SPAN></HTML>",
"<HTML><SPAN style=\"color:red;\">foo</SPAN></HTML>", oracle);
compareTwoDomsWithComparatorEqual("<HTML><SPAN style=\"color: yellow\">foo</SPAN></HTML>",
"<HTML><SPAN>foo</SPAN></HTML>", oracle);
compareTwoDomsWithComparatorEqual(
"<HTML><SPAN style=\"display:inline;color:red;\">foo</SPAN></HTML>",
"<HTML><SPAN style=\"display:inline; color:green;\">foo</SPAN></HTML>", oracle);
compareTwoDomsWithComparatorNotEqual(
"<HTML><SPAN style=\"display:inline;color:red;\">foo</SPAN></HTML>",
"<HTML><SPAN style=\"display:none; color:green;\">foo</SPAN></HTML>", oracle);
}
@Test
public void testSimpleOracle() {
Comparator oracle = new SimpleComparator();
compareTwoDomsWithComparatorEqual("<HTML>\n\n<SPAN>\n foo\n</SPAN></HTML>",
"<HTML>\n<SPAN>\n foo \n\n</SPAN>\n</HTML>", oracle);
}
@Test
public void testRegexOracle() {
Comparator oracle =
new RegexComparator("[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}");
compareTwoDomsWithComparatorEqual(
"<HTML>192.168.1.1</HTML>", "<HTML>10.0.0.138</HTML>", oracle);
}
@Test
public void testAttributeOracle() {
String control = "<HTML><A href=\"foo.html\" myattr=\"true\">foo</A><HTML>";
String test = "<HTML><A href=\"foo.html\" myattr=\"false\">foo</A><HTML>";
compareTwoDomsWithComparatorEqual(control, test, new AttributeComparator("myattr"));
}
@Test
public void testPlainStructureOracle() {
String control =
"<HTML><A href=\"foo.html\" jquery12421421=\"bla\" myattr=\"true\">foo</A><HTML>";
String test = "<HTML><A></A><HTML>";
compareTwoDomsWithComparatorEqual(
control, test, new PlainStructureComparator(control, test));
}
@Test
public void testScriptComparator() {
String control =
"<HTML><head><script>JavaScript();</script><title>Test</title></head><body><script>JavaScript23();</script>test</body><HTML>";
String test = "<HTML><head><title>Test</title></head><body>test</body><HTML>";
compareTwoDomsWithComparatorEqual(control, test, new ScriptComparator(control, test));
}
@Test
public void testEditDistanceComparator() {
String control = "<HTML><head><title>Test</title></head><body>test</body><HTML>";
String test = "<HTML><head><title>Test</title></head><body>test</body><HTML>";
assertTrue(control.equals(test));
compareTwoDomsWithComparatorEqual(control, test, new EditDistanceComparator(0));
compareTwoDomsWithComparatorEqual(control, test, new EditDistanceComparator(1));
test = "TheIsAlotOfRubish";
compareTwoDomsWithComparatorNotEqual(control, test, new EditDistanceComparator(1));
compareTwoDomsWithComparatorEqual(control, test, new EditDistanceComparator(0));
// We miss the title
test = "<HTML><head></head><body>test</body><HTML>";
Comparator oracle = new EditDistanceComparator(0.5);
compareTwoDomsWithComparatorEqual(control, test, oracle);
compareTwoDomsWithComparatorNotEqual(control, test, new EditDistanceComparator(1));
compareTwoDomsWithComparatorEqual(control, test, new EditDistanceComparator(0));
}
@Test
public void testXPathExpressionComparator() {
String control = "<HTML><head><title>Test</title></head><body>test</body><HTML>";
String test = "<HTML><head><title>Test</title></head><body>test</body><HTML>";
assertTrue(control.equals(test));
XPathExpressionComparator oracle = new XPathExpressionComparator();
compareTwoDomsWithComparatorEqual(control, test, oracle);
compareTwoDomsWithComparatorEqual(
control, test, new XPathExpressionComparator(control, test));
test = "<HTML><head><title>Test</title></head><body>test<div id='ignoreme'>"
+ "ignoreme</div></body><HTML>";
compareTwoDomsWithComparatorNotEqual(control, test, oracle);
compareTwoDomsWithComparatorNotEqual(
control, test, new XPathExpressionComparator(control, test));
oracle.addExpression("//*[@id='ignoreme']");
compareTwoDomsWithComparatorEqual(control, test, oracle);
compareTwoDomsWithComparatorEqual(test, control, oracle);
control = "<HTML><head><title>Test</title></head><body>test<div id='ignoreme'>"
+ "ignoreme123</div></body><HTML>";
compareTwoDomsWithComparatorEqual(control, test, oracle);
compareTwoDomsWithComparatorEqual(test, control, oracle);
}
}
| guifre/crawljax | src/test/java/com/crawljax/oracle/OracleTest.java | Java | apache-2.0 | 10,464 |
/*
* (C) Copyright 2016 Kurento (http://kurento.org/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <gst/gst.h>
#include "MediaType.hpp"
#include "MediaPipeline.hpp"
#include "MediaProfileSpecType.hpp"
#include "GapsFixMethod.hpp"
#include <RecorderEndpointImplFactory.hpp>
#include "RecorderEndpointImpl.hpp"
#include <jsonrpc/JsonSerializer.hpp>
#include <KurentoException.hpp>
#include <gst/gst.h>
#include <commons/kmsrecordingprofile.h>
#include "StatsType.hpp"
#include "EndpointStats.hpp"
#include <commons/kmsutils.h>
#include <commons/kmsstats.h>
#include <SignalHandler.hpp>
#include <functional>
#define GST_CAT_DEFAULT kurento_recorder_endpoint_impl
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
#define GST_DEFAULT_NAME "KurentoRecorderEndpointImpl"
#define FACTORY_NAME "recorderendpoint"
#define PARAM_GAPS_FIX "gapsFix"
#define PROP_GAPS_FIX "gaps-fix"
#define TIMEOUT 4 /* seconds */
namespace kurento
{
typedef enum {
KMS_URI_END_POINT_STATE_STOP,
KMS_URI_END_POINT_STATE_START,
KMS_URI_END_POINT_STATE_PAUSE
} KmsUriEndPointState;
bool RecorderEndpointImpl::support_ksr;
static bool
check_support_for_ksr ()
{
GstPlugin *plugin = nullptr;
bool supported;
plugin = gst_plugin_load_by_name ("kmsrecorder");
supported = plugin != nullptr;
g_clear_object (&plugin);
return supported;
}
RecorderEndpointImpl::RecorderEndpointImpl (const boost::property_tree::ptree
&conf,
std::shared_ptr<MediaPipeline> mediaPipeline, const std::string &uri,
std::shared_ptr<MediaProfileSpecType> mediaProfile,
bool stopOnEndOfStream) : UriEndpointImpl (conf,
std::dynamic_pointer_cast<MediaObjectImpl> (mediaPipeline), FACTORY_NAME, uri)
{
g_object_set (G_OBJECT (getGstreamerElement() ), "accept-eos",
stopOnEndOfStream, NULL);
switch (mediaProfile->getValue() ) {
case MediaProfileSpecType::WEBM:
g_object_set ( G_OBJECT (element), "profile", KMS_RECORDING_PROFILE_WEBM, NULL);
GST_INFO ("Set WEBM profile");
break;
case MediaProfileSpecType::MP4:
g_object_set ( G_OBJECT (element), "profile", KMS_RECORDING_PROFILE_MP4, NULL);
GST_INFO ("Set MP4 profile");
break;
case MediaProfileSpecType::MKV:
g_object_set ( G_OBJECT (element), "profile", KMS_RECORDING_PROFILE_MKV, NULL);
GST_INFO ("Set MKV profile");
break;
case MediaProfileSpecType::WEBM_VIDEO_ONLY:
g_object_set ( G_OBJECT (element), "profile",
KMS_RECORDING_PROFILE_WEBM_VIDEO_ONLY, NULL);
GST_INFO ("Set WEBM VIDEO ONLY profile");
break;
case MediaProfileSpecType::WEBM_AUDIO_ONLY:
g_object_set ( G_OBJECT (element), "profile",
KMS_RECORDING_PROFILE_WEBM_AUDIO_ONLY, NULL);
GST_INFO ("Set WEBM AUDIO ONLY profile");
break;
case MediaProfileSpecType::MKV_VIDEO_ONLY:
g_object_set ( G_OBJECT (element), "profile",
KMS_RECORDING_PROFILE_MKV_VIDEO_ONLY, NULL);
GST_INFO ("Set MKV VIDEO ONLY profile");
break;
case MediaProfileSpecType::MKV_AUDIO_ONLY:
g_object_set ( G_OBJECT (element), "profile",
KMS_RECORDING_PROFILE_MKV_AUDIO_ONLY, NULL);
GST_INFO ("Set MKV AUDIO ONLY profile");
break;
case MediaProfileSpecType::MP4_VIDEO_ONLY:
g_object_set ( G_OBJECT (element), "profile",
KMS_RECORDING_PROFILE_MP4_VIDEO_ONLY, NULL);
GST_INFO ("Set MP4 VIDEO ONLY profile");
break;
case MediaProfileSpecType::MP4_AUDIO_ONLY:
g_object_set ( G_OBJECT (element), "profile",
KMS_RECORDING_PROFILE_MP4_AUDIO_ONLY, NULL);
GST_INFO ("Set MP4 AUDIO ONLY profile");
break;
case MediaProfileSpecType::JPEG_VIDEO_ONLY:
g_object_set ( G_OBJECT (element), "profile",
KMS_RECORDING_PROFILE_JPEG_VIDEO_ONLY, NULL);
GST_INFO ("Set JPEG profile");
break;
case MediaProfileSpecType::KURENTO_SPLIT_RECORDER:
if (!RecorderEndpointImpl::support_ksr) {
throw KurentoException (MEDIA_OBJECT_ILLEGAL_PARAM_ERROR,
"Kurento Split Recorder not supported");
}
g_object_set ( G_OBJECT (element), "profile", KMS_RECORDING_PROFILE_KSR, NULL);
GST_INFO ("Set KSR profile");
break;
}
GapsFixMethod gapsFix;
if (getConfigValue<GapsFixMethod, RecorderEndpoint> (
&gapsFix, PARAM_GAPS_FIX)) {
GST_INFO ("Set RecorderEndpoint gaps fix mode: %s",
gapsFix.getString ().c_str ());
g_object_set (getGstreamerElement (),
PROP_GAPS_FIX, gapsFix.getValue (), NULL);
}
}
void RecorderEndpointImpl::postConstructor()
{
UriEndpointImpl::postConstructor();
handlerOnStateChanged = register_signal_handler (G_OBJECT (element),
"state-changed",
std::function <void (GstElement *, gint) >
(std::bind (&RecorderEndpointImpl::onStateChanged, this,
std::placeholders::_2) ),
std::dynamic_pointer_cast<RecorderEndpointImpl>
(shared_from_this() ) );
}
void
RecorderEndpointImpl::onStateChanged (gint newState)
{
switch (newState) {
case KMS_URI_END_POINT_STATE_STOP: {
GST_DEBUG_OBJECT (element, "State changed to Stopped");
try {
Stopped event (shared_from_this (), Stopped::getName ());
sigcSignalEmit(signalStopped, event);
} catch (const std::bad_weak_ptr &e) {
// shared_from_this()
GST_ERROR ("BUG creating %s: %s", Stopped::getName ().c_str (),
e.what ());
}
break;
}
case KMS_URI_END_POINT_STATE_START: {
GST_DEBUG_OBJECT (element, "State changed to Recording");
try {
Recording event (shared_from_this(), Recording::getName () );
sigcSignalEmit(signalRecording, event);
} catch (const std::bad_weak_ptr &e) {
// shared_from_this()
GST_ERROR ("BUG creating %s: %s", Recording::getName ().c_str (),
e.what ());
}
break;
}
case KMS_URI_END_POINT_STATE_PAUSE: {
GST_DEBUG_OBJECT (element, "State changed to Paused");
try {
Paused event (shared_from_this(), Paused::getName () );
sigcSignalEmit(signalPaused, event);
} catch (const std::bad_weak_ptr &e) {
// shared_from_this()
GST_ERROR ("BUG creating %s: %s", Paused::getName ().c_str (),
e.what ());
}
break;
}
}
std::unique_lock<std::mutex> lck (mtx);
GST_TRACE_OBJECT (element, "State changed to %d", newState);
state = newState;
cv.notify_one();
}
void RecorderEndpointImpl::waitForStateChange (gint expectedState)
{
std::unique_lock<std::mutex> lck (mtx);
if (!cv.wait_for (lck, std::chrono::seconds (TIMEOUT), [&] {return expectedState == state;}) ) {
GST_ERROR_OBJECT (element, "STATE did not changed to %d in %d seconds",
expectedState, TIMEOUT);
}
}
void
RecorderEndpointImpl::release ()
{
gint state = -1;
g_object_get (getGstreamerElement(), "state", &state, NULL);
if (state == 0 /* stop */) {
goto end;
}
stopAndWait();
end:
UriEndpointImpl::release();
}
RecorderEndpointImpl::~RecorderEndpointImpl()
{
gint state = -1;
if (handlerOnStateChanged > 0) {
unregister_signal_handler (element, handlerOnStateChanged);
}
g_object_get (getGstreamerElement(), "state", &state, NULL);
if (state != 0 /* stop */) {
GST_ERROR ("Recorder should be stopped when reaching this point");
}
}
void RecorderEndpointImpl::record ()
{
start();
}
void RecorderEndpointImpl::stopAndWait ()
{
stop();
waitForStateChange (KMS_URI_END_POINT_STATE_STOP);
}
static void
setDeprecatedProperties (std::shared_ptr<EndpointStats> eStats)
{
std::vector<std::shared_ptr<MediaLatencyStat>> inStats =
eStats->getE2ELatency();
for (auto &inStat : inStats) {
if (inStat->getName() == "sink_audio_default") {
eStats->setAudioE2ELatency(inStat->getAvg());
} else if (inStat->getName() == "sink_video_default") {
eStats->setVideoE2ELatency(inStat->getAvg());
}
}
}
void
RecorderEndpointImpl::collectEndpointStats (std::map
<std::string, std::shared_ptr<Stats>>
&statsReport, std::string id, const GstStructure *stats,
double timestamp, int64_t timestampMillis)
{
std::shared_ptr<Stats> endpointStats;
GstStructure *e2e_stats;
std::vector<std::shared_ptr<MediaLatencyStat>> inputStats;
std::vector<std::shared_ptr<MediaLatencyStat>> e2eStats;
if (gst_structure_get (stats, "e2e-latencies", GST_TYPE_STRUCTURE,
&e2e_stats, NULL) ) {
collectLatencyStats (e2eStats, e2e_stats);
gst_structure_free (e2e_stats);
}
endpointStats = std::make_shared <EndpointStats> (id,
std::make_shared <StatsType> (StatsType::endpoint), timestamp,
timestampMillis, 0.0, 0.0, inputStats, 0.0, 0.0, e2eStats);
setDeprecatedProperties (std::dynamic_pointer_cast <EndpointStats>
(endpointStats) );
statsReport[id] = endpointStats;
}
void
RecorderEndpointImpl::fillStatsReport (std::map
<std::string, std::shared_ptr<Stats>>
&report, const GstStructure *stats,
double timestamp, int64_t timestampMillis)
{
const GstStructure *e_stats;
e_stats = kms_utils_get_structure_by_name (stats, KMS_MEDIA_ELEMENT_FIELD);
if (e_stats != nullptr) {
collectEndpointStats (report, getId (), e_stats, timestamp, timestampMillis);
}
UriEndpointImpl::fillStatsReport (report, stats, timestamp, timestampMillis);
}
MediaObjectImpl *
RecorderEndpointImplFactory::createObject (const boost::property_tree::ptree
&conf, std::shared_ptr<MediaPipeline>
mediaPipeline, const std::string &uri,
std::shared_ptr<MediaProfileSpecType> mediaProfile,
bool stopOnEndOfStream) const
{
return new RecorderEndpointImpl (conf, mediaPipeline, uri, mediaProfile,
stopOnEndOfStream);
}
RecorderEndpointImpl::StaticConstructor RecorderEndpointImpl::staticConstructor;
RecorderEndpointImpl::StaticConstructor::StaticConstructor()
{
RecorderEndpointImpl::support_ksr = check_support_for_ksr();
GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,
GST_DEFAULT_NAME);
}
} /* kurento */
| Kurento/kms-elements | src/server/implementation/objects/RecorderEndpointImpl.cpp | C++ | apache-2.0 | 10,886 |
# frozen_string_literal: true
module Hyrax
module SolrDocument
module Metadata
extend ActiveSupport::Concern
class_methods do
def attribute(name, type, field)
define_method name do
type.coerce(self[field])
end
end
end
module Solr
class Array
# @return [Array]
def self.coerce(input)
::Array.wrap(input)
end
end
class String
# @return [String]
def self.coerce(input)
::Array.wrap(input).first
end
end
class Date
# @return [Date]
def self.coerce(input)
field = String.coerce(input)
return if field.blank?
begin
::Date.parse(field)
rescue ArgumentError
Hyrax.logger.info "Unable to parse date: #{field.first.inspect}"
end
end
end
end
included do
attribute :alternative_title, Solr::Array, "alternative_title_tesim"
attribute :identifier, Solr::Array, "identifier_tesim"
attribute :based_near, Solr::Array, "based_near_tesim"
attribute :based_near_label, Solr::Array, "based_near_label_tesim"
attribute :related_url, Solr::Array, "related_url_tesim"
attribute :resource_type, Solr::Array, "resource_type_tesim"
attribute :edit_groups, Solr::Array, ::Ability.edit_group_field
attribute :edit_people, Solr::Array, ::Ability.edit_user_field
attribute :read_groups, Solr::Array, ::Ability.read_group_field
attribute :collection_ids, Solr::Array, 'collection_ids_tesim'
attribute :admin_set, Solr::Array, "admin_set_tesim"
attribute :admin_set_id, Solr::Array, "admin_set_id_ssim"
attribute :member_ids, Solr::Array, "member_ids_ssim"
attribute :member_of_collection_ids, Solr::Array, "member_of_collection_ids_ssim"
attribute :member_of_collections, Solr::Array, "member_of_collections_ssim"
attribute :description, Solr::Array, "description_tesim"
attribute :abstract, Solr::Array, "abstract_tesim"
attribute :title, Solr::Array, "title_tesim"
attribute :contributor, Solr::Array, "contributor_tesim"
attribute :subject, Solr::Array, "subject_tesim"
attribute :publisher, Solr::Array, "publisher_tesim"
attribute :language, Solr::Array, "language_tesim"
attribute :keyword, Solr::Array, "keyword_tesim"
attribute :license, Solr::Array, "license_tesim"
attribute :source, Solr::Array, "source_tesim"
attribute :date_created, Solr::Array, "date_created_tesim"
attribute :rights_statement, Solr::Array, "rights_statement_tesim"
attribute :rights_notes, Solr::Array, "rights_notes_tesim"
attribute :access_right, Solr::Array, "access_right_tesim"
attribute :mime_type, Solr::String, "mime_type_ssi"
attribute :workflow_state, Solr::String, "workflow_state_name_ssim"
attribute :human_readable_type, Solr::String, "human_readable_type_tesim"
attribute :representative_id, Solr::String, "hasRelatedMediaFragment_ssim"
# extract the term name from the rendering_predicate (it might be after the final / or #)
attribute :rendering_ids, Solr::Array, Hyrax.config.rendering_predicate.value.split(/#|\/|,/).last + "_ssim"
attribute :thumbnail_id, Solr::String, "hasRelatedImage_ssim"
attribute :thumbnail_path, Solr::String, CatalogController.blacklight_config.index.thumbnail_field
attribute :label, Solr::String, "label_tesim"
attribute :file_format, Solr::String, "file_format_tesim"
attribute :suppressed?, Solr::String, "suppressed_bsi"
attribute :original_file_id, Solr::String, "original_file_id_ssi"
attribute :date_modified, Solr::Date, "date_modified_dtsi"
attribute :date_uploaded, Solr::Date, "date_uploaded_dtsi"
attribute :create_date, Solr::Date, "system_create_dtsi"
attribute :modified_date, Solr::Date, "system_modified_dtsi"
attribute :embargo_release_date, Solr::Date, Hydra.config.permissions.embargo.release_date
attribute :lease_expiration_date, Solr::Date, Hydra.config.permissions.lease.expiration_date
end
end
end
end
| samvera/hyrax | app/models/concerns/hyrax/solr_document/metadata.rb | Ruby | apache-2.0 | 4,358 |