repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
crosscompile/refined-github
source/features/set-default-repositories-type-to-sources.js
<filename>source/features/set-default-repositories-type-to-sources.js import select from 'select-dom'; import features from '../libs/features'; function init() { // Get repositories link from user profile navigation const link = select('.user-profile-nav a[href*="tab=repositories"]'); if (!link) { return false; } link.search += '&type=source'; } features.add({ id: 'set-default-repositories-type-to-sources', include: [ features.isUserProfile ], load: features.onAjaxedPages, init });
gotoprosperity/algorithm
binary_search/Search_a_2D_Matrix/answer_test.go
package Search_a_2D_Matrix import "testing" func TestIdxToPos(t *testing.T) { var ( i, j int ) if i, j = idxToPos(0, 10); i != 0 && j != 0 { t.Errorf("wrong ret with i=%d, j=%d", i, j) } } func TestSearchMatrix(t *testing.T) { var ( matrix [][]int target int ) matrix, target = [][]int{{1, 3, 5, 7}, {10, 11, 16, 20}, {23, 30, 34, 60}}, 3 if !searchMatrix(matrix, target) { t.Errorf("should be true") } matrix, target = [][]int{{1, 3, 5, 7}, {10, 11, 16, 20}, {23, 30, 34, 60}}, 13 if searchMatrix(matrix, target) { t.Errorf("should be false") } matrix, target = [][]int{{1}}, 1 if !searchMatrix(matrix, target) { t.Errorf("should be true") } matrix, target = [][]int{{1, 3}}, 3 if !searchMatrix(matrix, target) { t.Errorf("should be true") } }
kubemq-hub/builder
cluster/status.go
package cluster type Status struct { Replicas int32 `json:"replicas"` Version string `json:"version"` Ready int32 `json:"ready"` Grpc string `json:"grpc"` Rest string `json:"rest"` Api string `json:"api"` Selector string `json:"selector"` LicenseType string `json:"license_type"` LicenseTo string `json:"license_to"` LicenseExpire string `json:"license_expire"` Status string `json:"status"` }
sanblch/hunter
examples/nanosvg/main.cpp
#include <cstdio> #define NANOSVG_IMPLEMENTATION #include <nanosvg/nanosvg.h> // See https://github.com/memononen/nanosvg/tree/master/example // for further examples. int main() { NSVGimage image; (void)image; }
BrunoCersozimo/Fundamentos-Javascript
fundamentos/usandoVAr1.js
{ { { var sera = "Será???"; } } } console.log(sera)// Exibindo variável de escopo de nível global, isso pode gerar um problema no programa porque todos podem sobrescrever essa variável. A variável tem dos níveis escopo global onde a varíável fica visivel na aplicação inteira function teste(){ var local = 123 console.log(local)// O resultado aqui ficará visível apenas dentro do escopo da função }// Um outro exemplo de var é em escopo de nível de função teste() console.log(local)
assembla/amp
lib/amp/encoding/difflib.rb
################################################################## # Licensing Information # # # # The following code is licensed, as standalone code, under # # the Ruby License, unless otherwise directed within the code. # # # # For information on the license of this code when distributed # # with and used in conjunction with the other modules in the # # Amp project, please see the root-level LICENSE file. # # # # © <NAME> and <NAME>, 2009-2010 # # # ################################################################## # # Special Licensing Note: # This code is a derivative work from Python's standard library, namely, the # difflib module. The PSF allows us to license this code as we like. module Amp ## # = Difflib # Port of the Python Difflib. Only ports what is necessary. The cool part is that # this works for anything that has []! So it'll find matches in an array of lines # or just strings. module Diffs ## # Port of the Python SequenceMatcher, leaving out parts that Mercurial doesn't use. class SequenceMatcher ## # Initializes the sequence matcher. # # @param [String] seq1 The source data # @param [String] seq2 The "destination" data def initialize(seq1='', seq2='') @a = @b = nil set_seqs(seq1,seq2) end ## # Initializes the 2 sequences and prepares the rest of the matcher # # @param [#each] seq1 The source input sequence. Can be anything responding to #each. # @param [#each] seq2 The destination sequence - what we transform seq1 into. def set_seqs(seq1,seq2); set_seq1(seq1); set_seq2(seq2); end ## # Initializes the source sequence and resets the matching blocks. # # @param [#each] seq1 The source input sequence. def set_seq1(seq1) return if @a == seq1 @a = seq1 @matching_blocks = nil end ## # Initializes the destination sequence and resets the matching blocks. It also prepares # some optimization data. # # @param [#each] seq2 The destination input sequence. def set_seq2(seq2) return if @b == seq2 @b = seq2 @matching_blocks = nil build_b2j end ## # Sets up some optimization stuff. internal use only. I fucking hate python but ok here's what it # does... it goes through the destination sequence, setting the indices into the destination where # you can find each line. So it'll save the fact that "return nil" appears on lines 3, 14, and 20. # at the same time it's looking for "popular" entries, that are ignored to save runtime later. They # get removed from the list. # The original source respected a "junk" parameter, which was also removed from the list. But # Mercurial doesn't use the junk parameter, so I stripped that code. def build_b2j n = @b.size @b2j = {} populardict = {} n.times do |i| elt = @b[i,1] if @b2j[elt] indices = @b2j[elt] if n >= 2000 && (indices.size * 100 > n) populardict[elt] = true indices.clear else indices << i end else @b2j[elt] = [i] end end populardict.each do |k,v| @b2j.delete k end end ## # Finds the longest match in the 2 sequences between the 2 ranges provided. # # @param alo don't look at any part of the source before this # @param ahi don't look at any part of the source after this # @param blo don't look at any part of the destination before this # @param bhi don't look at any part of the destination after this # @return [[Integer,Integer,Integer]] The return is of the form # [start_source, start_destination, length_of_common_sequence]. # source[start_source + i] == destination[start_destination + i] for all 0 <= i < length_of_common_sequence def find_longest_match(alo, ahi, blo, bhi) j2len = {} besti, bestj, bestsize = alo, blo, 0 alo.upto(ahi-1) do |i| newj2len = {} @b2j[@a[i,1]] && @b2j[@a[i,1]].each do |j| next if j < blo break if j >= bhi k = newj2len[j] = j2len[j-1].to_i + 1 besti, bestj, bestsize = i-k+1, j-k+1, k if k > bestsize end j2len = newj2len end # we ignored popular elements before. they're being added here. while besti > alo && bestj > blo && @a[besti-1,1] == @b[bestj-1,1] besti, bestj, bestsize = besti-1, bestj-1, bestsize + 1 end # we ignored popular elements before. they're being added here. while besti+bestsize < ahi && bestj+bestsize < bhi && @a[besti+bestsize,1] == @b[bestj+bestsize,1] bestsize += 1 end return [besti, bestj, bestsize] end ## # This will go through and find all the matching blocks in the # 2 sequences, picking out the best sequences using find_longest_match. # # @return [[Hash]] A list of hashes, each of which represents 1 matching block. def get_matching_blocks return @matching_blocks if @matching_blocks la, lb = @a.size, @b.size # This is best done recursively, but if you have a large file it can blow # the stack. We ignore popular lines here to speed things up. I guess. queue = [[0, la, 0, lb]] @matching_blocks = [] while queue.any? alo, ahi, blo, bhi = queue.shift i, j, k = x = find_longest_match(alo, ahi, blo, bhi) if k > 0 @matching_blocks << x if alo < i && blo < j queue << [alo, i, blo, j] end if i+k < ahi && j+k < bhi queue << [i+k, ahi, j+k, bhi] end end end # Sort 'em from beginning of the sequences to the end @matching_blocks.sort! i1 = j1 = k1 = 0 non_adjacent = [] # If any "popular" entries were ignored, let's add them to the sequence now. @matching_blocks.each do |i2, j2, k2| if i1 + k1 == i2 && j1 + k1 == j2 k1 += k2 else non_adjacent << [i1, j1, k1] if k1 > 0 i1, j1, k1 = i2, j2, k2 end end # Add the last found sequence if there is one non_adjacent << [i1, j1, k1] if k1 > 0 # Add the terminator sequence non_adjacent << [la, lb, 0] # Make the output ruby-like, we don't need fucking tuples @matching_blocks = non_adjacent.map do |i, j, k| {:start_a => i, :start_b => j, :length => k} end @matching_blocks end end end end
rajatenzyme/Coding-Journey-
Algo_Ds_Notes-master/Algo_Ds_Notes-master/Sum_Of_Cubes/Sum_Of_Cubes.java
/* The sum of cubes of first N natural numbers is given by the equation (N * (N + 1) / 2) ^ 2 i.e. 1^3 + 2^3 + 3^3 + 4^3 + 5^3.........N^3 sums upto (N * (N + 1) / 2) ^ 2 */ import java.util.Scanner; import java.lang.Math; class Sum_Of_Cubes { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter the value of N: "); int N = sc.nextInt(); double ans = Math.pow(N * (N + 1) / 2, 2); System.out.println(ans); } } /* Input: N = 5 Output: ans = 225 Verification: 1^3 + 2^3 + 3^3 + 4^3 + 5^3 = 1 + 8 + 27 + 64 + 125 = 225 */
0xsan-z/AFLplusplus
frida_mode/include/lib.h
#ifndef _LIB_H #define _LIB_H #include "frida-gumjs.h" void lib_config(void); void lib_init(void); guint64 lib_get_text_base(void); guint64 lib_get_text_limit(void); #endif
kautMaks/validator
buildin/string_is_ip_iface_local_multicast_dive_test.go
package buildin import ( "fmt" "testing" "github.com/s3rj1k/validator" "github.com/stretchr/testify/require" ) func Test_StringIsIPIfaceLocalMulticastDive(t *testing.T) { r := require.New(t) var tests = []struct { field []string valid bool invalidIndexes []int }{ {[]string{"fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b", "fdf8:f53e:61e4::18", "fc00:e968:6179::de52:7100", "fc00:e968:6179::de52:7100"}, true, []int{}}, {[]string{"::1", "0.0.0.0", "feb0::0"}, false, []int{0, 1, 2}}, {[]string{"127.0.0.1", "192.168.127.12", "8.8.8.8"}, false, []int{0, 1, 2}}, {[]string{" ", ""}, false, []int{0, 1}}, {nil, false, []int{0}}, } for index, test := range tests { v := &StringSliceDive{ Validator: &StringIsIPIfaceLocalMulticast{Name: "IPIface"}, Field: test.field, } e := validator.NewErrors() v.Validate(e) r.Equalf(!test.valid, e.HasAny(), "tc %d expecting error=%v got=%v", index, !test.valid, e.HasAny()) if !test.valid { r.Equalf(len(test.invalidIndexes), e.Count(), "tc %d wrong number of errors", index) errnames := []string{} for _, i := range test.invalidIndexes { errnames = append(errnames, fmt.Sprintf("IPIface[%d]", i)) } for _, en := range errnames { r.Containsf(e.JSON(), en, "tc %d", index) } } } }
robin-gdwl/examples_topop-desc
examples/mesh-smoothing/mesh-smoothing-centroid.py
from random import choice from numpy import array import compas from compas.datastructures import Mesh from compas.datastructures import mesh_smooth_centroid from compas.geometry import add_vectors from compas_plotters import MeshPlotter mesh = Mesh.from_obj(compas.get('faces.obj')) key = choice(list(set(mesh.vertices()) - set(mesh.vertices_on_boundary()))) mesh.vertex[key]['x'] += 0.3 mesh.vertex[key]['y'] += 0.3 mesh_smooth_centroid(mesh, fixed=list(mesh.vertices_on_boundary())) plotter = MeshPlotter(mesh, figsize=(8, 5), tight=True) plotter.draw_vertices() plotter.draw_edges() plotter.draw_faces() plotter.show()
somprasongd/boilerplate-node-express-api
src/helpers/errorControllerHandler.js
import { InvalidExceptions } from './exceptions'; import logger from '../logger'; // Mongoose bad ObjectId const handleCastErrorDB = err => { const message = `Invalid ${err.path}: ${err.value}.`; return new InvalidExceptions(message); }; const handleDuplicateFieldsDB = err => { const value = err.errmsg.match(/(["'])(\\?.)*?\1/)[0]; console.log(value); const message = `Duplicate field value: ${value}. Please use another value!`; return new InvalidExceptions(message); }; const handleValidationErrorDB = err => { const errors = Object.values(err.errors).map(el => el.message); const message = `Invalid input data. ${errors.join('. ')}`; return new InvalidExceptions(message); }; const sendErrorDev = (err, res) => { // Log to console for dev console.log(err.stack); res.status(err.statusCode).json({ status: err.status, error: err, message: err.message, stack: err.stack, }); }; const sendErrorProd = (err, res) => { // Operational, trusted error: send message to client if (err.isOperational) { res.status(err.statusCode).json({ status: err.status, message: err.message, }); // Programming or other unknown error: don't leak error details } else { // 1) Log error logger.error(err); // 2) Send generic message res.status(500).json({ status: 'error', message: 'Server Error', }); } }; export default (err, req, res, next) => { const error = { ...err }; error.statusCode = error.statusCode || 500; error.status = error.status || 'error'; error.message = error.message || 'Server Error'; const env = process.env.NODE_ENV || 'development'; if (env === 'development') { sendErrorDev(error, res); } else if (env === 'production') { // handle mongoose error // if (error.name === 'CastError') error = handleCastErrorDB(error); // if (error.code === 11000) error = handleDuplicateFieldsDB(error); // if (error.name === 'ValidationError') // error = handleValidationErrorDB(error); sendErrorProd(error, res); } };
poanchen/azure-sdk-for-ruby
management/azure_mgmt_monitor/lib/2018-06-01-preview/generated/azure_mgmt_monitor/models/guest_diagnostic_settings_association_list.rb
<reponame>poanchen/azure-sdk-for-ruby # encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::Monitor::Mgmt::V2018_06_01_preview module Models # # A list of guest diagnostic settings association. # class GuestDiagnosticSettingsAssociationList include MsRestAzure # @return [Array<GuestDiagnosticSettingsAssociationResource>] The list of # guest diagnostic settings association. attr_accessor :value # @return [String] Provides the link to retrieve the next set of # elements. attr_accessor :next_link # # Mapper for GuestDiagnosticSettingsAssociationList class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'GuestDiagnosticSettingsAssociationList', type: { name: 'Composite', class_name: 'GuestDiagnosticSettingsAssociationList', model_properties: { value: { client_side_validation: true, required: false, serialized_name: 'value', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'GuestDiagnosticSettingsAssociationResourceElementType', type: { name: 'Composite', class_name: 'GuestDiagnosticSettingsAssociationResource' } } } }, next_link: { client_side_validation: true, required: false, serialized_name: 'nextLink', type: { name: 'String' } } } } } end end end end
ChocolateLoverRaj/dev-react
__mocks__/display-task.js
<filename>__mocks__/display-task.js export { default as DisplayTask } from '../test-lib/mock-display-task/display-task.js' export { default } from '../test-lib/mock-display-task/display-task.js' export { Addon, Addons, AutoStateAddon, ColorAddon, ConcatAddon, ConcatTask, CustomTask, HideTask, MapTask, MaxLengthAddon, NameTask, SetAddon, SetTask, SortSetTask, StateAddon, Task, Tasks, TextAddon } from 'display-task'
princeton-vl/MetaGen
src/train_pred_lm.py
<reponame>princeton-vl/MetaGen import os,sys import numpy as np import math import time import random import multiprocessing as mp import torch import torch.utils.data as data from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence import torch_models import params import log import data_loader_forward from data_utils import * def embed(tokens, trees, emb, gru, args): def _init_hidden(): hidden_layers = args.gru_depth * 2 if args.bidirectional else args.gru_depth return torch.zeros(hidden_layers, len(tokens), args.nFeats).to(args.device) padded_tokens, padded_trees, perm_idx, lengths = pad_list(tokens, trees, args.device) padded_feats = emb(padded_tokens, padded_trees) packed_feats = pack_padded_sequence(padded_feats, lengths.cpu().numpy()) packed_output, h = gru(packed_feats, _init_hidden()) output = torch.cat((h[-2], h[-1]), 1) if args.bidirectional else h[-1] _, unperm_idx = perm_idx.sort(0) output = output[unperm_idx] return output def step(batch, models, args): g_tokens, g_trees, p_tokens, p_trees = batch g_vec = embed(g_tokens, g_trees, models['emb'], models['g_gru'], args) p_vec = embed(p_tokens, p_trees, models['emb'], models['p_gru'], args) score = models['biln'](g_vec, p_vec).view(-1, args.negative_samples+1) return score # batch_size * (1+neg) no softmax def step_hardneg(batch, models, args): g_tokens, g_trees, p_tokens, p_trees, prop_idx, true_prop = batch p_tokens_hard_neg = [] p_trees_hard_neg = [] with torch.no_grad(): g_vec = embed(g_tokens, g_trees, models['emb'], models['g_gru'], args) cnt = 0 for g, p_idx, true_pos in zip(g_vec, prop_idx, true_prop): l = len(p_idx) if type(p_idx) == list else p_idx p_emb = embed(p_tokens[cnt:cnt+l], p_trees[cnt:cnt+l], models['emb'], models['p_gru'], args) score = models['biln'](g.view(1,-1), p_emb).view(-1) score[true_pos] = -100 hard_neg_idx = (-score).sort()[1][:args.negative_samples] p_tokens_hard_neg.append(p_tokens[cnt+true_pos]) p_trees_hard_neg.append(p_trees[cnt+true_pos]) for idx in hard_neg_idx: p_tokens_hard_neg.append(p_tokens[cnt+idx]) p_trees_hard_neg.append(p_trees[cnt+idx]) cnt += l return step([g_tokens, g_trees, p_tokens_hard_neg, p_trees_hard_neg], models, args) def step_allneg(batch, models, args): g_tokens, g_trees, p_tokens, p_trees, prop_idx, true_prop = batch g_vec = embed(g_tokens, g_trees, models['emb'], models['g_gru'], args) p_vec = embed(p_tokens, p_trees, models['emb'], models['p_gru'], args) loss = [] acc = 0 cnt = 0 for g, p_idx, true_pos in zip(g_vec, prop_idx, true_prop): l = len(p_idx) if type(p_idx) == list else p_idx p_emb = p_vec[cnt:cnt+l] cnt += l score = models['biln'](g.view(1,-1), p_emb).view(-1) #print (score[true_pos], score) idx = score[true_pos]<=score _pos = idx.sum().item() if _pos == 1: acc += 1 if args.train_neg_only: loss.append(-score[true_pos] + score[idx].exp().sum().log()) else: loss.append(-score[true_pos] + score.exp().sum().log()) return sum(loss)/len(loss), acc def train(models, queue, opt, args, _logger, epoch, _train=True): batch_time = AverageMeter() data_time = AverageMeter() losses = AverageMeter() acces = AverageMeter() acces_cons = AverageMeter() ppls = AverageMeter() # switch to train mode for k,v in models.items(): if _train: v.train() else: v.eval() end = time.time() i = 0 if args.cur_iter != 0: i = args.cur_iter args.cur_iter = 0 while i < args.samples: batch = queue.get() if batch is None: _logger.warning('An epoch end') if _train==False: break batch = queue.get() b0 = [torch.Tensor(d).long().to(args.device) for d in batch[0]] b1 = [torch.Tensor(d).to(args.device) for d in batch[1]] b2 = [torch.Tensor(d).long().to(args.device) for d in batch[2]] b3 = [torch.Tensor(d).to(args.device) for d in batch[3]] data_time.update(time.time() - end) if args.allneg: loss, acc = step_allneg((b0,b1,b2,b3, batch[4], batch[5]), models, args) print (loss, acc) else: if args.hardneg: score = step_hardneg((b0,b1,b2,b3, batch[4], batch[5]), models, args) else: score = step((b0,b1,b2,b3), models, args) acc = (score.max(dim=1)[1]==0).sum().item() prob = torch.nn.functional.softmax(score, dim=1)[:,0] ppl = prob.sum().item() score[:, 1:] = -score[:, 1:] score = torch.nn.functional.logsigmoid(score) loss = -score.sum(dim=1).mean() # backward if _train: opt.zero_grad() loss.backward() opt.step() # update ppls.update(ppl, args.batch_size) acces.update(acc, args.batch_size) losses.update(loss.item(), args.batch_size) batch_time.update(time.time() - end) end = time.time() print_info = 'Epoch: %d (%d/%d) Data: %.4f Batch: %.4f Loss: %.4f Acc: %.4f ppl: %.4f' % ( epoch, i + 1, args.samples, data_time.val, batch_time.val, losses.avg*100, acces.avg*100, ppls.avg ) _logger.info(print_info) if ((i+1) % args.save == 0 or (i+1) % args.samples == 0) and _train: aux = {'epoch':epoch, 'cur_iter':i} save_model(aux, args, models, opt) _logger.warning('save models') i += 1 return losses.avg, acces.avg def evaluate(models, loader, args, _logger): batch_time = AverageMeter() data_time = AverageMeter() acces_1 = AverageMeter() acces_5 = AverageMeter() acces_20 = AverageMeter() rank = [] for k,v in models.items(): v.eval() prop_embs = torch.zeros(len(loader.dataset.lm_inputs), args.nFeats*2 if args.bidirectional else args.nFeats).to(args.device) l = 0 while l < len(loader.dataset.lm_inputs): r = min(len(loader.dataset.lm_inputs), l+args.batch_size*10) tokens = [torch.LongTensor(loader.dataset.lm_inputs[i][0]).to(args.device) for i in range(l, r)] trees = [torch.Tensor(loader.dataset.lm_inputs[i][1]).to(args.device) for i in range(l, r)] prop_embs[l:r] = embed(tokens, trees, models['emb'], models['p_gru'], args) l = r _logger.info('Embed %d/%d props', l, len(loader.dataset.lm_inputs)) end = time.time() i=0 while loader.dataset.cur_epoch == 0: batch = next(iter(loader)) data_time.update(time.time() - end) g_emb = embed(batch[0], batch[1], models['emb'], models['g_gru'], args) prop_idx = batch[-2] true_prop = batch[-1] for g, p_idx, true_pos in zip(g_emb, prop_idx, true_prop): #print (p_idx) p_emb = prop_embs[torch.Tensor(p_idx).to(device).long()] score = models['biln'](g.view(1,-1), p_emb) #print (score[true_pos], score) _pos = (score[true_pos]<score).sum().item() rank.append(_pos) if _pos==0: acces_1.update(1,1) else: acces_1.update(0,1) if _pos<5: acces_5.update(1,1) else: acces_5.update(0,1) if _pos<20: acces_20.update(1,1) else: acces_20.update(0,1) end = time.time() print_info = '(%d/%d) Data: %.4f | \ Batch: %.4f | top1: %.4f | top5: %4f |\ top20: %.4f' % ( i + 1, len(loader), data_time.val, batch_time.val, acces_1.avg*100, acces_5.avg*100, acces_20.avg*100 ) _logger.info(print_info) print (sum(rank)/len(rank)) i += 1 _logger.warning('top1: %.4f top5: %.4f top20: %.4f', acces_1.avg*100, acces_5.avg*100, acces_20.avg*100) def start_loader(args, task): args.device = None q1 = mp.Queue(50) proc = mp.Process( target=data_loader_forward.worker, args=(args, 0, task, q1) ) proc.daemon=True proc.start() args.device = torch.device("cuda:0" if (not args.cpu) and torch.cuda.is_available() else "cpu") return proc, q1 def close_loader(proc, q1): proc.terminate() q1.close() proc.join() if __name__ == "__main__": args = params.get_args() _logger = log.get_logger(__name__, args) _logger.info(print_args(args)) args.valid_split = 'test' if args.evaluate else 'valid' proc, q1 = start_loader(args, 'pred') if args.partial_lm: lm = build_language_model(args.num_props, new=args.gen_lm, _all=False) else: lm = load_language_model(new=args.gen_lm, iset=args.iset) config = get_config(lm) args.vocab_size = len(config.encode)+1 models = {} models['emb'] = torch_models.Emb(args, config).to(args.device) in_dim = args.nFeats if not args.no_use_tree: in_dim += 4 models['g_gru'] = torch.nn.GRU(in_dim, args.nFeats, args.gru_depth, dropout=args.dropout, bidirectional=args.bidirectional).to(args.device) models['p_gru'] = torch.nn.GRU(in_dim, args.nFeats, args.gru_depth, dropout=args.dropout, bidirectional=args.bidirectional).to(args.device) models['biln'] = torch_models.Dot(args).to(args.device) opt = get_opt(models, args) start_epoch = 0 args.cur_iter = 0 if args.pretrained != "": loaddata = torch.load(args.pretrained) start_epoch = loaddata['aux']['epoch'] args.cur_iter = loaddata['aux']['cur_iter'] for k,v in models.items(): v.load_state_dict(loaddata['models'][k]) opt.load_state_dict(loaddata['opt']) _logger.warning('load data from %s\n', args.pretrained) for param_group in opt.param_groups: param_group['lr'] = args.learning_rate if args.evaluate != 'none': _logger.warning('Evaluation begins') with torch.no_grad(): evaluate(models, validloader, args, _logger) exit(0) valid_losses = [] valid_acces = [] for e in range(start_epoch, args.epoch): _logger.warning("Training Epoch %d begins.", e) loss, acc = train(models, q1, opt, args, _logger, e) if e in args.schedule: adjust_lr(opt, args) _logger.warning('Learning rate decreases') close_loader(proc, q1)
golint-fixer/untappd
brewery_info_test.go
<filename>brewery_info_test.go package untappd import ( "net/http" "net/url" "strconv" "strings" "testing" ) // TestClientBreweryInfoBadBrewery verifies that Client.Brewery.Info returns an error when // an invalid brewery is queried. func TestClientBreweryInfoBadBrewery(t *testing.T) { breweryID := -1 sBreweryID := strconv.Itoa(breweryID) c, done := breweryInfoTestClient(t, func(t *testing.T, w http.ResponseWriter, r *http.Request) { path := "/v4/brewery/info/" + sBreweryID + "/" if p := r.URL.Path; p != path { t.Fatalf("unexpected URL path: %q != %q", p, path) } w.WriteHeader(http.StatusInternalServerError) w.Write(invalidBreweryErrJSON) }) defer done() _, _, err := c.Brewery.Info(breweryID, false) assertInvalidBreweryErr(t, err) } // TestClientBreweryInfoCompactOK verifies that Client.Brewery.Info properly requests compact // brewery output. func TestClientBreweryInfoCompactOK(t *testing.T) { c, done := breweryInfoTestClient(t, func(t *testing.T, w http.ResponseWriter, r *http.Request) { assertParameters(t, r, url.Values{ "compact": []string{"true"}, }) // In the future, we may return compact canned brewery data here. // For now, write a mostly empty JSON object is enough to get // test coverage. w.Write([]byte(`{"response":{"brewery":{"brewery_id":1}}}`)) }) defer done() if _, _, err := c.Brewery.Info(1, true); err != nil { t.Fatal(err) } } // TestClientBreweryInfoOK verifies that Client.Brewery.Info returns a valid brewery when // provided with correct input parameters. func TestClientBreweryInfoOK(t *testing.T) { breweryID := 1 sBreweryID := strconv.Itoa(breweryID) c, done := breweryInfoTestClient(t, func(t *testing.T, w http.ResponseWriter, r *http.Request) { path := "/v4/brewery/info/" + sBreweryID + "/" if p := r.URL.Path; p != path { t.Fatalf("unexpected URL path: %q != %q", p, path) } w.Write(bellsBreweryJSON) }) defer done() b, _, err := c.Brewery.Info(breweryID, false) if err != nil { t.Fatal(err) } if id := b.ID; id != breweryID { t.Fatalf("unexpected ID: %d != %d", id, 1) } breweryName := "<NAME>, Inc." if n := b.Name; n != breweryName { t.Fatalf("unexpected Brewery.Name: %q != %q", n, breweryName) } brewerySlug := "bells-brewery-inc" if n := b.Slug; n != brewerySlug { t.Fatalf("unexpected Brewery.Slug: %q != %q", n, brewerySlug) } breweryType := "Micro Brewery" if n := b.Type; n != breweryType { t.Fatalf("unexpected Brewery.Type: %q != %q", n, breweryType) } breweryTypeID := 2 if n := b.TypeID; n != breweryTypeID { t.Fatalf("unexpected Brewery.TypeID: %q != %q", n, breweryTypeID) } breweryContactTwitter := "BellsBrewery" if n := b.Contact.Twitter; n != breweryContactTwitter { t.Fatalf("unexpected Brewery.TypeID: %q != %q", n, breweryContactTwitter) } } // breweryInfoTestClient builds upon testClient, and adds additional sanity checks // for tests which target the brewery info API. func breweryInfoTestClient(t *testing.T, fn func(t *testing.T, w http.ResponseWriter, r *http.Request)) (*Client, func()) { return testClient(t, func(t *testing.T, w http.ResponseWriter, r *http.Request) { // Always GET request method := "GET" if m := r.Method; m != method { t.Fatalf("unexpected HTTP method: %q != %q", m, method) } // Always uses specific path prefix prefix := "/v4/brewery/info/" if p := r.URL.Path; !strings.HasPrefix(p, prefix) { t.Fatalf("unexpected HTTP path prefix: %q != %q", p, prefix) } // Guard against panics if fn != nil { fn(t, w, r) } }) } // Canned JSON used in tests var bellsBreweryJSON = []byte(` { "meta": { "code": 200, "response_time": { "time": 0, "measure": "seconds" } }, "notifications": {}, "response": { "brewery": { "brewery_id": 1, "brewery_name": "Bell's Brewery, Inc.", "brewery_slug": "bells-brewery-inc", "brewery_type": "Micro Brewery", "brewery_type_id": 2, "contact": { "twitter": "BellsBrewery", "facebook": "", "url": "" } } } }`)
stevenlin5520/dynamic-datasource
dynamic-datasource/src/main/java/com/steven/datasource/system/core/DynamicDataSourceContextHolder.java
<filename>dynamic-datasource/src/main/java/com/steven/datasource/system/core/DynamicDataSourceContextHolder.java package com.steven.datasource.system.core; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @desc 数据源切换进程 * @author steven * @date 2021/6/25 11:35 */ public class DynamicDataSourceContextHolder { public static final Logger log = LoggerFactory.getLogger(DynamicDataSourceContextHolder.class); /** *此类提供线程局部变量。这些变量不同于它们的正常对应关系是每个线程访问一个线程(通过get、set方法),有自己的独立初始化变量的副本。 */ private static final ThreadLocal<String> contextHolder = new ThreadLocal<>(); /** * 设置当前线程的数据源变量 */ public static void setDataSourceType(String dataSourceType) { log.info("已切换到{}数据源", dataSourceType); contextHolder.set(dataSourceType); } /** * 获取当前线程的数据源变量 */ public static String getDataSourceType() { return contextHolder.get(); } /** * 删除与当前线程绑定的数据源变量 */ public static void removeDataSourceType() { contextHolder.remove(); } }
rhuan080/dls-repository-stack
shared-source/src/edu/ucar/dls/schemedit/autoform/LarEditorRenderer.java
<gh_stars>1-10 /* Copyright 2017 Digital Learning Sciences (DLS) at the University Corporation for Atmospheric Research (UCAR), P.O. Box 3000, Boulder, CO 80307 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 edu.ucar.dls.schemedit.autoform; import edu.ucar.dls.schemedit.autoform.mde.*; import edu.ucar.dls.schemedit.standards.StandardsManager; import edu.ucar.dls.xml.*; import edu.ucar.dls.xml.schema.*; import java.util.*; import java.util.regex.*; import org.dom4j.Node; import org.dom4j.Attribute; import org.dom4j.Element; import org.dom4j.DocumentHelper; /** * Includes lar-specific kludges, most notably the /record/general/subjects * field, which requires an editing approach OTHER than than implied by the * schema ...<p> * * Elements created by the LarEditorRenderer starting with "lar__" (e.g., * "lar__subjects") are rendered tag calls (e.g., "msg:subjects") which are * handled by tag files (e.g., "subjects.tag") in the tags/lar directory. * * @author ostwald */ public class LarEditorRenderer extends DleseEditorRenderer { /** Description of the Field */ private static boolean debug = false; String asnStandardPath = "/record/standard"; /** * Intercept renderNode calls for certain paths and use jsp tags instead of * autoform */ public void renderNode() { if (asnStandardPath.equals(xpath)) { prtln("LarEditorRenderer got STANDARDS node"); renderStandardNode(); } else { super.renderNode(); } } /** Custom renderer for the Subjects node using a tag file. */ protected void renderStandardNode() { prtln("renderStandardNode()"); parent.add(DocumentHelper.createElement("lar__asn-standards")); parent.add(DocumentHelper.createElement("lar__other-standards")); } /** * Sets the debug attribute of the LarEditorRenderer class * * @param bool The new debug value */ public static void setDebug(boolean bool) { debug = bool; } /** * Description of the Method * * @param s Description of the Parameter */ private static void prtln(String s) { if (debug) { while (s.length() > 0 && s.charAt(0) == '\n') { System.out.println(""); s = s.substring(1); } System.out.println("LarEditorRenderer: " + s); } } /** * NOT YET DOCUMENTED * * @param s NOT YET DOCUMENTED */ private final void prtlnErr(String s) { System.err.println("LarEditorRenderer: " + s); } }
arturo32/PODE
PODE-backend/src/main/java/br/ufrn/imd/pode/model/Usuario.java
<gh_stars>0 package br.ufrn.imd.pode.model; import javax.persistence.Column; import javax.persistence.MappedSuperclass; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; @MappedSuperclass public abstract class Usuario extends AbstractModel<Long> { @NotNull @NotBlank @Column(unique = true) protected String nome; @NotNull @NotBlank @Column(unique = true) protected String email; @NotNull @NotBlank protected String senha; public Usuario() { } public Usuario(String nome, String email, String senha) { this.nome = nome; this.email = email; this.senha = senha; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getSenha() { return senha; } public void setSenha(String senha) { this.senha = senha; } }
MrWilhelm/WikiEduDashboard
app/controllers/training_controller.rb
<gh_stars>1-10 # frozen_string_literal: true require "#{Rails.root}/lib/training_progress_manager" require "#{Rails.root}/lib/training_library" require "#{Rails.root}/lib/training_module" class TrainingController < ApplicationController layout 'training' def index @libraries = TrainingLibrary.all.sort_by(&:name) end def show add_training_root_breadcrumb add_library_breadcrumb fail_if_entity_not_found(TrainingLibrary, params[:library_id]) @library = TrainingLibrary.find_by(slug: params[:library_id]) end def training_module add_training_root_breadcrumb add_library_breadcrumb add_module_breadcrumb fail_if_entity_not_found(TrainingModule, params[:module_id]) @pres = TrainingModulePresenter.new(current_user, params) end def slide_view add_training_root_breadcrumb if current_user @tmu = TrainingModulesUsers.find_or_create_by( user_id: current_user.id, training_module_id: TrainingModule.find_by(slug: params[:module_id]).id ) end add_module_breadcrumb end private def add_training_root_breadcrumb add_breadcrumb 'Training Library', :training_path end def add_library_breadcrumb add_breadcrumb params[:library_id].titleize, :training_library_path end def add_module_breadcrumb add_breadcrumb params[:module_id].titleize, :training_module_path end def fail_if_entity_not_found(entity, finder) raise ActiveRecord::RecordNotFound unless entity.find_by(slug: finder).present? end end
mbeckem/msc
code/geodb/null_set.hpp
<reponame>mbeckem/msc<filename>code/geodb/null_set.hpp #ifndef GEODB_NULL_SET_HPP #define GEODB_NULL_SET_HPP #include "geodb/common.hpp" #include <initializer_list> /// \file /// Implements a "set" that does nothing. namespace geodb { /// The null set is a trivial probabilistic data structure /// that uses zero space and "contains" every element. /// Its interface is compatible with the \ref interval_set /// and the \ref bloom_filter. /// /// It is used by the quickload algorithm which does not /// need to store trajectory ids. template<typename T> class null_set { public: using value_type = T; public: template<typename NullSets> static null_set set_union(const NullSets&) { return {}; } template<typename NullSets> static null_set set_intersection(const NullSets&) { return {}; } public: null_set() = default; null_set(std::initializer_list<value_type>) {} template<typename Iter> null_set(Iter, Iter) {} void add(const value_type&) {} template<typename Iter> void assign(Iter, Iter) {} void clear() {} bool empty() const { return false; } bool contains(value_type&) const { return true; } null_set intersection_with(const null_set&) const { return {}; } null_set union_with(const null_set&) const { return {}; } }; } // namespace geodb #endif // GEODB_NULL_SET_HPP
manuelgentile/pxlab
pxlab/src/main/java/de/pxlab/pxl/MediaPlayerElement.java
package de.pxlab.pxl; import java.awt.*; import java.net.*; import de.pxlab.util.*; /** * Plays audiovisual media which are supported by the <a * href="http://java.sun.com/products/java-media/jmf/">Java Media Framework * (JMF)</a> package. This creates a player for a given media file and then * plays the file on request. Media playing runs in its own thread and uses a * END_OF_MEDIA_TIMER to signal the PresentationManager that the media is * finished. * * <p> * It is a strict rule that the object which starts the media player also has to * close it and free the player's resources by calling the dispose() method! * * @version 0.1.2 */ /* * * 2005/05/09 * * 2005/10/19 removed the ControllerListener interface in order to make sure * that this file can be used without the JMF being installed. */ public class MediaPlayerElement extends DisplayElement { protected javax.media.Player player; protected Component visualComponent; protected int referenceCode; protected MediaEventListener mediaEventListener; protected MediaPlayerListener mediaPlayerListener; protected Container container; protected Panel panel; protected Color bgc; protected MediaMonitor monitor; protected boolean fastStart = false; protected boolean cycle = false; protected long showTime; protected long startTime; private static final int PREP_OPEN_MEDIA = 1; private static final int PREP_START_MEDIA = 2; private static final int PREP_CLOSE_MEDIA = 3; public MediaPlayerElement() { type = DisplayElement.PICTURE; monitor = new MediaMonitor(); } /** * Prepare the media player for the given media file and cache initial media * data in order to get the fastest possible start time. For fastStart * players this method also attaches the player's visual component to the * display device. This may be undesirable since it ovelays the display * screen at the movie display frame. The method returns after the media * data prefetch is complete. */ public void setProperties(DisplayDevice displayDevice, int x, int y, int w, int h, int ref, String dir, String fn, boolean fst, boolean cyc, MediaEventListener listener) { container = ((ExperimentalDisplayDevice) displayDevice).getWindow(); setLocation(x, y); setSize(w, h); referenceCode = ref; fastStart = fst; cycle = cyc; mediaEventListener = listener; bgc = ExPar.ScreenBackgroundColor.getPxlColor().dev(); URL url = FileBase.url(dir, fn); if (url != null) { panel = new Panel(); panel.setLayout(null); javax.media.MediaLocator mrl = new javax.media.MediaLocator(url); try { player = javax.media.Manager.createPlayer(mrl); Debug.showTime(Debug.MEDIA_TIMING, this, "Player created for " + mrl); player.addControllerListener(new MediaPlayerListener(this)); monitor.prepare(PREP_OPEN_MEDIA); player.prefetch(); monitor.waitForPlayer(3000); showTime = 0L; startTime = 0L; } catch (javax.media.NoPlayerException npe) { new FileError( "MediaPlayerElement.setProperties(): Could not create player for " + mrl); player = null; } catch (java.io.IOException iox) { new FileError( "MediaPlayerElement.setProperties(): Could not find " + mrl); player = null; } } } /** Synonym to start(). */ public void show() { start(); } /** * Start the player. The player should be in the 'Prefetched' state when it * is started. For non-fastStart players starting the player includes * attaching the player's visual component to the display device. */ public void start() { showTime = HiresClock.getTimeNanos(); Debug.showTime(Debug.MEDIA_TIMING, this, "MediaPlayerElement.start()"); if (player != null) { if (!fastStart && visualComponent == null) { visualComponent = setVisual(); } monitor.prepare(PREP_START_MEDIA); player.start(); monitor.waitForPlayer(3000); } } /** * Stop the player and free all resources associated with the player. The * player can not be continued after this method has been called. */ public void stop() { Debug.showTime(Debug.MEDIA_TIMING, this, "MediaPlayerElement.stop()"); if (player != null) { monitor.prepare(PREP_CLOSE_MEDIA); player.stop(); player.close(); monitor.waitForPlayer(3000); } } /** * Add a synchronization task to the player. The task will send a * synchronization event of type ResponseCodes.SYNC_MEDIA to the * MediaEventListener when the given media time has been reached. */ public void setSyncAt(long mediaTimeNanos) { new MediaSync(mediaTimeNanos).start(); } private class MediaSync extends Thread { long syncMediaTimeNanos; public MediaSync(long t) { syncMediaTimeNanos = t; } private WaitLock waitLock = new WaitLock(); public void run() { if (player.getState() == javax.media.Controller.Started) { long cmt = player.getMediaNanoseconds(); if (cmt > 0L) { long dt = syncMediaTimeNanos - cmt; if (dt > 0L) { waitLock.waitForNanos(dt); long mt = player.getMediaNanoseconds(); if (mediaEventListener != null) { mediaEventListener .mediaActionPerformed(new MediaEvent( MediaPlayerElement.this, ResponseCodes.SYNC_MEDIA, mt, HiresClock.getTimeNanos())); } Debug.showTime(Debug.MEDIA_TIMING, this, "Controller sync [MT=" + mt + "]."); } else { System.out .println("MediaPlayerElement.MediaSync.run(): Negative synchronization delay."); } } else { System.out .println("MediaPlayerElement.MediaSync.run(): Player not running."); } } else { System.out .println("MediaPlayerElement.MediaSync.run(): Player not started."); } } } /* * public void dispose() { Debug.showTime(Debug.MEDIA_TIMING, this, * "MediaPlayerElement.dispose()"); if (player != null) { // * monitor.prepare(ResponseCodes.CLOSE_MEDIA); // player.deallocate(); * player.close(); // monitor.waitForPlayer(3000); player = null; } } */ private Component setVisual() { Component visualComponent = null; if ((visualComponent = player.getVisualComponent()) != null) { container.add(panel); // This makes the movie frame area identical to the // background AFTER the visual component has been removed. container.setBackground(bgc); // visualComponent.setBackground(bgc); // visualComponent.setForeground(bgc); panel.setBackground(bgc); // panel.setForeground(bgc); panel.add(visualComponent); Dimension videoSize = visualComponent.getPreferredSize(); int videoWidth = videoSize.width; int videoHeight = videoSize.height; int maxWidth = container.getWidth(); int maxHeight = container.getHeight(); if (size.width > 0 && size.height > 0) { if (size.width < maxWidth && size.height < maxHeight) { // Set movie component to requested size visualComponent.setBounds(0, 0, size.width, size.height); panel.setBounds( locX(referenceCode, location.x + maxWidth / 2, size.width), rectLocY(referenceCode, location.y + maxHeight / 2, size.height), size.width, size.height); } else { // Set movie component to maximum size visualComponent.setBounds(0, 0, maxWidth, maxHeight); panel.setBounds(0, 0, maxWidth, maxHeight); } } else { // No size requested, set movie component to its preferred size visualComponent.setBounds(0, 0, videoWidth, videoHeight); panel.setBounds( locX(referenceCode, location.x + container.getWidth() / 2, videoWidth), rectLocY(referenceCode, location.y + container.getHeight() / 2, videoHeight), videoWidth, videoHeight); } } else { // System.out.println("MediaPlayerElement.controllerUpdate(): no visual component."); } return visualComponent; } /** * Get the delay period between the call to the show()/start() method and * the actual start of the media player as signaled by the 'Started' event. * * @return the delay period in nanoseconds. If either the show()/start() * time or the actual start time have not yet beeen set then -1 is * returned. */ public long getStartDelay() { long t = -1L; if (showTime != 0L && startTime != 0) { t = startTime - showTime; } return t; } // ------------------------------------------------------------------------------- // Media event handler // ------------------------------------------------------------------------------- protected void realizeCompleteEvent() { // Debug.showTime(Debug.MEDIA_TIMING, this, // "Controller realize complete."); if (fastStart && visualComponent == null) { visualComponent = setVisual(); } } protected void cachingControlEvent() { Debug.showTime(Debug.MEDIA_TIMING, this, "Controller caching control."); /* * if (player.getState() > javax.media.Controller.Realizing) return; */ } protected void prefetchCompleteEvent() { long mt = player.getMediaNanoseconds(); /* * if (mediaEventListener != null) { * mediaEventListener.mediaActionPerformed(new * MediaEvent(MediaPlayerElement.this, ResponseCodes.OPEN_MEDIA, mt, * HiresClock.getTimeNanos())); } */ Debug.showTime(Debug.MEDIA_TIMING, this, "Controller prefetch complete [MT=" + mt + "]."); monitor.playerReady(PREP_OPEN_MEDIA); } protected void startEvent() { startTime = HiresClock.getTimeNanos(); long mt = player.getMediaNanoseconds(); /* * if (mediaEventListener != null) { * mediaEventListener.mediaActionPerformed(new * MediaEvent(MediaPlayerElement.this, ResponseCodes.START_MEDIA, mt, * startTime)); } */ Debug.showTime(Debug.MEDIA_TIMING, this, "Controller started [MT=" + mt + "]."); monitor.playerReady(PREP_START_MEDIA); } protected void stopByRequestEvent() { long mt = player.getMediaNanoseconds(); /* * if (mediaEventListener != null) { * mediaEventListener.mediaActionPerformed(new * MediaEvent(MediaPlayerElement.this, ResponseCodes.STOP_MEDIA, mt, * HiresClock.getTimeNanos())); } */ Debug.showTime(Debug.MEDIA_TIMING, this, "Controller stopped by request [MT=" + mt + "]."); } protected void endOfMediaEvent() { if (cycle) { player.setMediaTime(new javax.media.Time(0L)); player.start(); } else { long mt = player.getMediaNanoseconds(); player.close(); /* * if (mediaEventListener != null) { * mediaEventListener.mediaActionPerformed(new * MediaEvent(MediaPlayerElement.this, ResponseCodes.STOP_MEDIA, mt, * HiresClock.getTimeNanos())); } */ Debug.showTime(Debug.MEDIA_TIMING, this, "Controller found end of media [MT=" + mt + "]."); } } protected void controllerClosedEvent() { monitor.playerReady(PREP_CLOSE_MEDIA); long mt = (player != null) ? player.getMediaNanoseconds() : 0L; if (mediaEventListener != null) { mediaEventListener.mediaActionPerformed(new MediaEvent( MediaPlayerElement.this, ResponseCodes.CLOSE_MEDIA, mt, HiresClock.getTimeNanos())); } if (visualComponent != null) { panel.removeAll(); container.remove(panel); visualComponent = null; } Debug.showTime(Debug.MEDIA_TIMING, this, "Controller closed."); // player = null; } protected void resourceUnavailableEvent(String s) { player = null; new FileError(s); } protected void controllerErrorEvent(String s) { player = null; new FileError(s); } // ------------------------------------------------------------------------------- // End of media event handler // ------------------------------------------------------------------------------- private class MediaMonitor { private int eventCode; private int lastEventCode; private boolean tmOut; public void prepare(int e) { eventCode = e; lastEventCode = 0; Debug.showTime(Debug.MEDIA_TIMING, this, "Prepare for event " + eventCode + " [" + HiresClock.getTime() + "]"); } public synchronized void waitForPlayer(int timeOut) { if (eventCode != 0) { tmOut = true; try { Debug.showTime(Debug.MEDIA_TIMING, this, "Waiting until player signals event " + eventCode + " [" + HiresClock.getTime() + "]"); wait(timeOut); if (tmOut) { Debug.showTime(Debug.MEDIA_TIMING, this, "Player timeout. [" + HiresClock.getTime() + "]"); } else { Debug.showTime(Debug.MEDIA_TIMING, this, "Player ready by event " + lastEventCode + ". [" + HiresClock.getTime() + "]"); } eventCode = 0; } catch (InterruptedException iex) { } } else { Debug.showTime(Debug.MEDIA_TIMING, this, "No waiting necessary. Already found event " + lastEventCode); } } public synchronized void playerReady(int e) { if (e == eventCode) { lastEventCode = e; eventCode = 0; tmOut = false; notify(); } } } }
leopardoooo/cambodia
boss-job/src/main/java/com/yaochen/boss/job/OrderExpChangeStatusJob.java
package com.yaochen.boss.job; import java.util.List; import org.quartz.JobExecutionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.yaochen.boss.job.component.AuthComponent; import com.yaochen.boss.job.component.JobComponent; import com.yaochen.myquartz.Job2; import com.yaochen.myquartz.Job2ExecutionContext; import com.ycsoft.beans.core.prod.CProdOrder; /** * 订单失效修改状态为到期停 * 每天凌晨1点执行 * @author new * */ @Service public class OrderExpChangeStatusJob implements Job2 { private final Logger logger = LoggerFactory.getLogger(getClass()); @Autowired private JobComponent jobComponent; @Autowired private AuthComponent authComponent; @Override public void execute(Job2ExecutionContext arg0) throws JobExecutionException { logger.info("启动处理订单失效修改状态为到期停"); try{ Integer doneCode=-7; List<CProdOrder> orders=jobComponent.changeHasExpOrderStatusToForStop(doneCode); //宽带所有订单到期日后,对宽带补发清除授权指令,因为宽带在汇聚系统发的长授权 authComponent.clearBandAuth(orders,doneCode); logger.info("结束处理订单失效修改状态为到期停"); }catch(Exception e){ logger.error("处理订单失效修改状态为到期停失败",e); } } }
leusonmario/2022PhDThesis
retrofit/2b6c719c6645f8e48dca6d0047c752069d321bc4/randoop_18/ErrorTest0.java
import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class ErrorTest0 { public static boolean debug = false; @Test public void test1() throws Throwable { if (debug) System.out.format("%n%s%n", "ErrorTest0.test1"); retrofit.RestAdapter restAdapter0 = new retrofit.RestAdapter(); retrofit.ErrorHandler errorHandler1 = restAdapter0.errorHandler; retrofit.RestAdapter.RestHandler restHandler2 = restAdapter0.new RestHandler(); retrofit.RestAdapter.Builder builder3 = new retrofit.RestAdapter.Builder(); java.util.concurrent.Executor executor4 = builder3.callbackExecutor; retrofit.RestAdapter.LogLevel logLevel5 = retrofit.RestAdapter.LogLevel.HEADERS; retrofit.RestAdapter.Builder builder6 = builder3.setLogLevel(logLevel5); boolean boolean7 = logLevel5.log(); // during test generation this statement threw an exception of type java.lang.NullPointerException in error restAdapter0.setLogLevel(logLevel5); } @Test public void test2() throws Throwable { if (debug) System.out.format("%n%s%n", "ErrorTest0.test2"); retrofit.RestAdapter.Builder builder0 = new retrofit.RestAdapter.Builder(); java.util.concurrent.Executor executor1 = builder0.callbackExecutor; retrofit.Profiler profiler2 = builder0.profiler; java.util.concurrent.Executor executor3 = builder0.callbackExecutor; // during test generation this statement threw an exception of type java.lang.NullPointerException in error retrofit.RestAdapter.Builder builder5 = builder0.setServer(""); } @Test public void test3() throws Throwable { if (debug) System.out.format("%n%s%n", "ErrorTest0.test3"); retrofit.RestAdapter.Builder builder0 = new retrofit.RestAdapter.Builder(); builder0.ensureSaneDefaults(); retrofit.client.Client.Provider provider2 = builder0.clientProvider; retrofit.ErrorHandler errorHandler3 = builder0.errorHandler; retrofit.RestAdapter.Builder builder4 = new retrofit.RestAdapter.Builder(); builder4.ensureSaneDefaults(); retrofit.client.Client.Provider provider6 = builder4.clientProvider; retrofit.ErrorHandler errorHandler7 = builder4.errorHandler; retrofit.RestAdapter.Builder builder8 = builder0.setErrorHandler(errorHandler7); retrofit.converter.Converter converter9 = builder0.converter; java.util.concurrent.Executor executor10 = builder0.callbackExecutor; // during test generation this statement threw an exception of type java.lang.NullPointerException in error retrofit.RestAdapter.Builder builder12 = builder0.setServer(""); } @Test public void test4() throws Throwable { if (debug) System.out.format("%n%s%n", "ErrorTest0.test4"); retrofit.RestAdapter.Builder builder0 = new retrofit.RestAdapter.Builder(); java.util.concurrent.Executor executor1 = builder0.callbackExecutor; retrofit.Profiler profiler2 = builder0.profiler; java.util.concurrent.Executor executor3 = builder0.callbackExecutor; retrofit.ErrorHandler errorHandler4 = builder0.errorHandler; retrofit.RestAdapter.Log log5 = builder0.log; // during test generation this statement threw an exception of type java.lang.NullPointerException in error retrofit.RestAdapter.Builder builder7 = builder0.setServer(""); } @Test public void test5() throws Throwable { if (debug) System.out.format("%n%s%n", "ErrorTest0.test5"); retrofit.RestAdapter.Builder builder0 = new retrofit.RestAdapter.Builder(); builder0.ensureSaneDefaults(); retrofit.client.Client.Provider provider2 = builder0.clientProvider; retrofit.RestAdapter.LogLevel logLevel3 = builder0.logLevel; // during test generation this statement threw an exception of type java.lang.NullPointerException in error retrofit.RestAdapter.Builder builder5 = builder0.setServer(""); } @Test public void test6() throws Throwable { if (debug) System.out.format("%n%s%n", "ErrorTest0.test6"); retrofit.RestAdapter.Builder builder0 = new retrofit.RestAdapter.Builder(); builder0.ensureSaneDefaults(); retrofit.converter.Converter converter2 = builder0.converter; retrofit.Profiler profiler3 = builder0.profiler; retrofit.converter.Converter converter4 = builder0.converter; // during test generation this statement threw an exception of type java.lang.NullPointerException in error retrofit.RestAdapter.Builder builder6 = builder0.setServer(""); } @Test public void test7() throws Throwable { if (debug) System.out.format("%n%s%n", "ErrorTest0.test7"); retrofit.RestAdapter.Builder builder0 = new retrofit.RestAdapter.Builder(); java.util.concurrent.Executor executor1 = builder0.callbackExecutor; retrofit.Profiler profiler2 = builder0.profiler; java.util.concurrent.Executor executor3 = builder0.callbackExecutor; retrofit.RequestInterceptor requestInterceptor4 = builder0.requestInterceptor; retrofit.RequestInterceptor requestInterceptor5 = builder0.requestInterceptor; java.util.concurrent.Executor executor6 = builder0.httpExecutor; // during test generation this statement threw an exception of type java.lang.NullPointerException in error retrofit.RestAdapter.Builder builder8 = builder0.setServer(""); } @Test public void test8() throws Throwable { if (debug) System.out.format("%n%s%n", "ErrorTest0.test8"); retrofit.RestAdapter.Builder builder0 = new retrofit.RestAdapter.Builder(); builder0.ensureSaneDefaults(); retrofit.client.Client.Provider provider2 = builder0.clientProvider; retrofit.RestAdapter.LogLevel logLevel3 = builder0.logLevel; retrofit.converter.Converter converter4 = builder0.converter; retrofit.Server server5 = builder0.server; builder0.ensureSaneDefaults(); java.util.concurrent.Executor executor7 = builder0.callbackExecutor; // during test generation this statement threw an exception of type java.lang.NullPointerException in error retrofit.RestAdapter.Builder builder9 = builder0.setServer(""); } @Test public void test9() throws Throwable { if (debug) System.out.format("%n%s%n", "ErrorTest0.test9"); retrofit.RestAdapter.Builder builder0 = new retrofit.RestAdapter.Builder(); retrofit.Server server1 = builder0.server; retrofit.RestAdapter.LogLevel logLevel2 = builder0.logLevel; // during test generation this statement threw an exception of type java.lang.NullPointerException in error retrofit.RestAdapter.Builder builder4 = builder0.setServer(""); } }
nmldiegues/jvm-stm
classpath-0.98/org/omg/CosNaming/NamingContextHelper.java
<reponame>nmldiegues/jvm-stm /* NamingContextHelper.java -- Copyright (C) 2005, 2006 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU Classpath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package org.omg.CosNaming; import gnu.CORBA.Minor; import gnu.CORBA.OrbRestricted; import org.omg.CORBA.Any; import org.omg.CORBA.BAD_OPERATION; import org.omg.CORBA.BAD_PARAM; import org.omg.CORBA.TypeCode; import org.omg.CORBA.portable.Delegate; import org.omg.CORBA.portable.InputStream; import org.omg.CORBA.portable.ObjectImpl; import org.omg.CORBA.portable.OutputStream; /** * The helper operations for the naming context. * * @author <NAME>, Lithuania (<EMAIL>) */ public abstract class NamingContextHelper { /** * The naming context repository id. */ private static String _id = "IDL:omg.org/CosNaming/NamingContext:1.0"; /** * Extract the naming context from the given {@link Any}. */ public static NamingContext extract(Any a) { try { return ((NamingContextHolder) a.extract_Streamable()).value; } catch (ClassCastException ex) { BAD_OPERATION bad = new BAD_OPERATION("Naming context expected"); bad.initCause(ex); bad.minor = Minor.Any; throw bad; } } /** * Get the {@link NamingContext} repository id. */ public static String id() { return _id; } /** * Insert the naming context into the given {@link Any} */ public static void insert(Any a, NamingContext that) { a.insert_Streamable(new NamingContextHolder(that)); } /** * Cast the passed object into the NamingContext. If the * object has a different java type, create an instance * of the NamingContext, using the same delegate, as for * the passed parameter. * * If the object repository Id indicates that it is an instance of * {@link NamingContextExt} that is a subclass of the NamingContext, * the functionality is delegated to {@link NamingContextHelper#narrow}. * * @param obj the object to cast. * @return casted instance. * * @throws BAD_PARAM if the passed object is not an instance of * {@link NamingContext} or {@link NamingContextExt}. */ public static NamingContext narrow(org.omg.CORBA.Object obj) { if (obj == null) return null; else if (obj instanceof NamingContext) return (NamingContext) obj; else if (obj._is_a(id())) { Delegate delegate = ((ObjectImpl) obj)._get_delegate(); return new _NamingContextStub(delegate); } else if (obj._is_a(NamingContextExtHelper.id())) return NamingContextExtHelper.narrow(obj); else throw new BAD_PARAM(); } /** * Narrow the given object to the NamingContext. No type-checking is performed * to verify that the object actually supports the requested type. The * {@link BAD_OPERATION} will be thrown if unsupported operations are invoked * on the new returned reference, but no failure is expected at the time of * the unchecked_narrow. See OMG issue 4158. * * @param obj the object to cast. * * @return the casted NamingContext. */ public static NamingContext unchecked_narrow(org.omg.CORBA.Object obj) { if (obj == null) return null; else if (obj instanceof NamingContext) return (NamingContext) obj; else { // Do not call the _is_a(..). Delegate delegate = ((ObjectImpl) obj)._get_delegate(); return new _NamingContextStub(delegate); } } /** * Read the naming context from the given CDR input stream. */ public static NamingContext read(InputStream istream) { return narrow(istream.read_Object(_NamingContextStub.class)); } /** * Get the type code of the {@link NamingContext}. */ public static TypeCode type() { return OrbRestricted.Singleton.create_interface_tc(id(), "NamingContext"); } /** * Write the given naming context into the given CDR output stream. */ public static void write(OutputStream ostream, NamingContext value) { ostream.write_Object(value); } }
QuantiModo/quantimodo-sdk-javascript
ts/qm.shell.js
"use strict"; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; Object.defineProperty(exports, "__esModule", { value: true }); var qmLog = __importStar(require("./qm.log")); function executeSynchronously(cmd, catchExceptions) { var execSync = require("child_process").execSync; console.info(cmd); try { var res = execSync(cmd); qmLog.info(res); } catch (error) { if (catchExceptions) { console.error(error); } else { throw error; } } } exports.executeSynchronously = executeSynchronously; //# sourceMappingURL=qm.shell.js.map
Intern426/azure-sdk-for-java
eventhubs/client/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/PartitionProperties.java
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.messaging.eventhubs; import java.time.Instant; /** * Contains runtime information about an Event Hub partition. */ public final class PartitionProperties { private final String eventHubPath; private final String id; private final long beginningSequenceNumber; private final long lastEnqueuedSequenceNumber; private final String lastEnqueuedOffset; private final Instant lastEnqueuedTime; private final boolean isEmpty; PartitionProperties( final String eventHubPath, final String id, final long beginningSequenceNumber, final long lastEnqueuedSequenceNumber, final String lastEnqueuedOffset, final Instant lastEnqueuedTime, final boolean isEmpty) { this.eventHubPath = eventHubPath; this.id = id; this.beginningSequenceNumber = beginningSequenceNumber; this.lastEnqueuedSequenceNumber = lastEnqueuedSequenceNumber; this.lastEnqueuedOffset = lastEnqueuedOffset; this.lastEnqueuedTime = lastEnqueuedTime; this.isEmpty = isEmpty; } /** * Gets the Event Hub path for this partition. * * @return The Event Hub path for this partition. */ public String eventHubPath() { return this.eventHubPath; } /** * Gets the identifier of the partition within the Event Hub. * * @return The identifier of the partition within the Event Hub. */ public String id() { return this.id; } /** * Gets the starting sequence number of the partition's message stream. * * @return The starting sequence number of the partition's message stream. */ public long beginningSequenceNumber() { return this.beginningSequenceNumber; } /** * Gets the last sequence number of the partition's message stream. * * @return the last sequence number of the partition's message stream. */ public long lastEnqueuedSequenceNumber() { return this.lastEnqueuedSequenceNumber; } /** * Gets the offset of the last enqueued message in the partition's stream. * * @return the offset of the last enqueued message in the partition's stream. */ public String lastEnqueuedOffset() { return this.lastEnqueuedOffset; } /** * Gets the instant, in UTC, of the last enqueued message in the partition's stream. * * @return the instant, in UTC, of the last enqueued message in the partition's stream. */ public Instant lastEnqueuedTime() { return this.lastEnqueuedTime; } /** * Indicates whether or not there are events in the partition. * * @return true if there are no events, and false otherwise. */ public boolean isEmpty() { return this.isEmpty; } }
assembla/amp
lib/amp/extensions/stats.rb
################################################################## # Licensing Information # # # # The following code is licensed, as standalone code, under # # the Ruby License, unless otherwise directed within the code. # # # # For information on the license of this code when distributed # # with and used in conjunction with the other modules in the # # Amp project, please see the root-level LICENSE file. # # # # © <NAME> and <NAME>, 2009-2010 # # # ################################################################## # temporary hack to make sure helper functions don't leak into the global # namespace. Module.new do ## # Creates the stats command and injects it into the runtime. # Relatively similar to the HG churn command though it shares no # actual lineage - I (<NAME>) started this as a simple demonstration # command long before I knew about the official churn extension. I'm adding # some churn features along the way, but this code has nothing to do with churn. command "stats" do |c| c.workflow :hg c.opt :template, "A template string to compute the grouping key. Defaults to <%= user %>.", :type => :string, :default => "<%= user %>", :short => "-t" c.opt :dateformat, "Use formatted date of commit as the grouping key", :type => :string, :short => "-f" c.opt :sort, "Sorts by the grouping key instead of commit/change amount" c.desc "Prints how many commits each user has contributed" c.on_run do |opts, args| repo = opts[:repository] results = Hash.new {|h, k| h[k] = 0} # We need a proc that extracts the key to use from the changeset keyproc = build_key_proc opts # Iterate over each changeset, counting changesets based on the key repo.each do |changeset| results[keyproc[changeset]] += 1 # end pairs = results.to_a # Sort based on options given sort_pairs! pairs, opts # Print our output as a histogram puts Amp::Statistics.histogram(pairs, Amp::Support.terminal_size[0]) end ## # Prepares a proc that, when run on a changeset, extracts a grouping key # from the changeset. This is highly customizable by the user as it is # the backbone behind providing useful output. # # @param [Hash<Symbol => Object>] opts the opts provided by the user # @return [Proc] a proc that takes a changeset as a parameter and # returns a string key to be used for grouping def build_key_proc(opts) if opts[:dateformat] then keyproc = proc {|changeset| changeset.easy_date.strftime(opts[:dateformat])} else keyproc = proc {|changeset| changeset.to_templated_s(:"template-raw" => opts[:template]) } end end ## # Sorts the results based on the options provided to the command by # the user. # # @param [Array<String, Integer>] pairs the pairs of key-value churned results. # will be sorted in-place. # @param [Hash<Symbol => Object>] opts the options provided by the user def sort_pairs!(pairs, opts) if opts[:sort] then pairs.sort! {|a, b| a[0] <=> b[0]} # sort keys ascending else pairs.sort! {|a, b| b[1] <=> a[1]} # sort values descending end end end end
Mavr1/goit-fe-course
JavaScript/goit-js-hw-07/js/task-5.js
"use strict"; const input = document.querySelector("#name-input"); const output = document.querySelector("#name-output"); const onInput = () => input.value !== "" ? (output.textContent = input.value) : (output.textContent = "незнакомец"); input.addEventListener("input", onInput);
oguzhankaymak/Haber-Gunlukleri
app/screens/detail/styles/DetailScreenStyle.js
<reponame>oguzhankaymak/Haber-Gunlukleri import {StyleSheet} from 'react-native'; import Colors from '../../../theme/Colors'; import {deviceHeight, deviceWidth} from '../../../utils/Metrics'; export default StyleSheet.create({ container: { flex: 1, }, webView: { width: deviceWidth, height: deviceHeight, }, loaderView: { position: 'absolute', alignItems: 'center', justifyContent: 'center', width: deviceWidth, height: deviceHeight, }, loader: { color: Colors.purplishPink, }, });
psanyal/geoportal-server
geoportal/src/com/esri/gpt/control/view/ThumbnailServlet.java
<gh_stars>100-1000 /* See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * Esri 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 com.esri.gpt.control.view; import com.esri.gpt.framework.context.BaseServlet; import com.esri.gpt.framework.context.RequestContext; import com.esri.gpt.framework.security.identity.NotAuthorizedException; import com.esri.gpt.framework.security.metadata.MetadataAcl; import com.esri.gpt.framework.util.UuidUtil; import java.io.IOException; import java.io.InputStream; import java.sql.Blob; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.logging.Logger; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Handles the display of local metadata thumbnail images. * <p> * Most thumbnails are remote urls and are accessed through standard HTTP. <br/> * The images for some metadata thumbnails are stored within the DBMS. These * typically come from metadata that is being created/edited through ArcCatalog. * These images are retrieved by the browser through this Servlet. A sample url * to access this servlet:<br/> &lt;img * src="/GPT9/thumbnail?uuid={6153A394-70A9-4311-A6DC-582F2F9758FF}"/&gt; */ public class ThumbnailServlet extends BaseServlet { /** class variables ========================================================= */ /** The Logger. */ private static Logger LOGGER = Logger.getLogger(ThumbnailServlet.class.getName()); /** methods ================================================================= */ /** * Executes the request. * @param request the HTTP request * @param response the HTTP response * @throws Exception if an exception occurs */ protected void execute(HttpServletRequest request, HttpServletResponse response, RequestContext context) throws Exception { // determine the guid for the thumbnail String uuid = UuidUtil.addCurlies(request.getParameter("uuid")); Connection con = null; PreparedStatement st = null; InputStream bis = null; ServletOutputStream sos = null; try { // open the binary input stream for the thumbnail image (blob) if (uuid.length() > 0) { // ensure access to the document boolean bCheckAccess = true; if (bCheckAccess) { MetadataAcl acl = new MetadataAcl(context); boolean bHasAccess = acl.hasReadAccess(context.getUser(),uuid); if (!bHasAccess) { throw new NotAuthorizedException("Access denied"); } } con = context.getConnectionBroker().returnConnection("").getJdbcConnection(); String sTbl = context.getCatalogConfiguration().getResourceDataTableName(); String sSql = "SELECT THUMBNAIL FROM " + sTbl + " WHERE DOCUUID=?"; st = con.prepareStatement(sSql); st.setString(1,uuid); ResultSet rs = st.executeQuery(); if (rs.next()) { String database = con.getMetaData().getDatabaseProductName().toLowerCase(); if (database.contains("postgresql")){ bis = rs.getBinaryStream("thumbnail"); } else{ Blob blob = rs.getBlob(1); if (blob != null) { bis = blob.getBinaryStream(); } } } } // write the image to the response output stream if (bis != null) { response.setHeader("Content-Disposition:","attachment;filename=thumbnail"); byte[] aBuffer = new byte[4096]; sos = response.getOutputStream(); while (true) { int nBytes = bis.read(aBuffer, 0, aBuffer.length); if (nBytes <= 0) break; sos.write(aBuffer, 0, nBytes); } } else { response.sendError(HttpServletResponse.SC_NOT_FOUND); } } finally { try {if (st != null) st.close();} catch (Exception ef) {} try {if (con != null) con.close();} catch (Exception ef) {} try {if (bis != null) bis.close();} catch (Exception ef) {} try {if (sos != null) sos.flush();} catch (Exception ef) {LOGGER.severe(ef.getMessage());} } } }
figassis/iso20022
PaymentCard7.go
package iso20022 // Payment card performing the transaction. type PaymentCard7 struct { // Replacement of the message element PlainCardData by a digital envelope using a cryptographic key. ProtectedCardData *ContentInformationType7 `xml:"PrtctdCardData,omitempty"` // Sensitive data associated with the card performing the transaction. PlainCardData *PlainCardData4 `xml:"PlainCardData,omitempty"` // Country code assigned to the card by the card issuer. CardCountryCode *Max3Text `xml:"CardCtryCd,omitempty"` // Currency code of the card issuer (ISO 4217 numeric code). CardCurrencyCode *Exact3NumericText `xml:"CardCcyCd,omitempty"` // Defines a category of cards related to the acceptance processing rules defined by the acquirer. CardProductProfile *Exact4NumericText `xml:"CardPdctPrfl,omitempty"` // Brand name of the card. CardBrand *Max35Text `xml:"CardBrnd,omitempty"` // Additional card issuer specific data. AdditionalCardData *Max70Text `xml:"AddtlCardData,omitempty"` } func (p *PaymentCard7) AddProtectedCardData() *ContentInformationType7 { p.ProtectedCardData = new(ContentInformationType7) return p.ProtectedCardData } func (p *PaymentCard7) AddPlainCardData() *PlainCardData4 { p.PlainCardData = new(PlainCardData4) return p.PlainCardData } func (p *PaymentCard7) SetCardCountryCode(value string) { p.CardCountryCode = (*Max3Text)(&value) } func (p *PaymentCard7) SetCardCurrencyCode(value string) { p.CardCurrencyCode = (*Exact3NumericText)(&value) } func (p *PaymentCard7) SetCardProductProfile(value string) { p.CardProductProfile = (*Exact4NumericText)(&value) } func (p *PaymentCard7) SetCardBrand(value string) { p.CardBrand = (*Max35Text)(&value) } func (p *PaymentCard7) SetAdditionalCardData(value string) { p.AdditionalCardData = (*Max70Text)(&value) }
hmrc/property-business-api
test/v1/models/response/retrieveForeignPropertyAnnualSubmission/RetrieveForeignPropertyAnnualSubmissionResponseSpec.scala
/* * Copyright 2021 HM Revenue & Customs * * 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 v1.models.response.retrieveForeignPropertyAnnualSubmission import mocks.MockAppConfig import play.api.libs.json.Json import support.UnitSpec import v1.models.hateoas.{Link, Method} import v1.models.response.retrieveForeignPropertyAnnualSubmission.foreignFhlEea.{ForeignFhlEeaAdjustments, ForeignFhlEeaAllowances, ForeignFhlEeaEntry} import v1.models.response.retrieveForeignPropertyAnnualSubmission.foreignProperty.{ForeignPropertyAdjustments, ForeignPropertyAllowances, ForeignPropertyEntry} class RetrieveForeignPropertyAnnualSubmissionResponseSpec extends UnitSpec with MockAppConfig { private val retrieveForeignPropertyAnnualSubmissionRequestBody = RetrieveForeignPropertyAnnualSubmissionResponse( Some(ForeignFhlEeaEntry( Some(ForeignFhlEeaAdjustments( Some(100.25), Some(100.25), Some(true))), Some(ForeignFhlEeaAllowances( Some(100.25), Some(100.25), Some(100.25), Some(100.25))) )), Some(Seq(ForeignPropertyEntry( "GER", Some(ForeignPropertyAdjustments( Some(100.25), Some(100.25))), Some(ForeignPropertyAllowances( Some(100.25), Some(100.25), Some(100.25), Some(100.25), Some(100.25), Some(100.25), Some(100.25))) ))) ) private val retrieveForeignPropertyAnnualSubmissionRequestBodyMinimum = RetrieveForeignPropertyAnnualSubmissionResponse( None, Some(Seq(ForeignPropertyEntry( "GER", None, None ))) ) private val jsonBody = Json.parse( """ |{ | "foreignFhlEea": | { | "adjustments":{ | "privateUseAdjustment":100.25, | "balancingCharge":100.25, | "periodOfGraceAdjustment":true | }, | "allowances":{ | "annualInvestmentAllowance":100.25, | "otherCapitalAllowance":100.25, | "propertyAllowance":100.25, | "electricChargePointAllowance":100.25 | } | }, | "foreignProperty":[ | { | "countryCode":"GER", | "adjustments":{ | "privateUseAdjustment":100.25, | "balancingCharge":100.25 | }, | "allowances":{ | "annualInvestmentAllowance":100.25, | "costOfReplacingDomesticItems":100.25, | "zeroEmissionsGoodsVehicleAllowance":100.25, | "propertyAllowance":100.25, | "otherCapitalAllowance":100.25, | "structureAndBuildingAllowance":100.25, | "electricChargePointAllowance":100.25 | } | } | ] |} """.stripMargin ) private val jsonBodyMinimum = Json.parse( """ |{ | "foreignProperty":[ | { | "countryCode":"GER" | } | ] |} """.stripMargin ) "reads" when { "passed a valid JSON" should { "return a valid model" in { jsonBody.as[RetrieveForeignPropertyAnnualSubmissionResponse] shouldBe retrieveForeignPropertyAnnualSubmissionRequestBody } "return a valid model with minimum fields" in { jsonBodyMinimum.as[RetrieveForeignPropertyAnnualSubmissionResponse] shouldBe retrieveForeignPropertyAnnualSubmissionRequestBodyMinimum } } } "writes" when { "passed valid model" should { "return valid JSON" in { Json.toJson(retrieveForeignPropertyAnnualSubmissionRequestBody) shouldBe jsonBody } "return a valid minimum JSON" in { Json.toJson(retrieveForeignPropertyAnnualSubmissionRequestBodyMinimum) shouldBe jsonBodyMinimum } } } "LinksFactory" should { "produce the correct links" when { "called" in { val data: RetrieveForeignPropertyAnnualSubmissionHateoasData = RetrieveForeignPropertyAnnualSubmissionHateoasData("myNino", "myBusinessId", "mySubmissionId") MockAppConfig.apiGatewayContext.returns("my/context").anyNumberOfTimes() RetrieveForeignPropertyAnnualSubmissionResponse.RetrieveAnnualSubmissionLinksFactory.links(mockAppConfig, data) shouldBe Seq( Link(href = s"/my/context/${data.nino}/${data.businessId}/annual/${data.taxYear}", method = Method.PUT, rel = "amend-property-annual-submission"), Link(href = s"/my/context/${data.nino}/${data.businessId}/annual/${data.taxYear}", method = Method.GET, rel = "self"), Link(href = s"/my/context/${data.nino}/${data.businessId}/annual/${data.taxYear}", method = Method.DELETE, rel = "delete-property-annual-submission") ) } } } }
raulhsant/algorithms
C++/tests/problems/0168_backspace_string_compare_test.cpp
<reponame>raulhsant/algorithms<filename>C++/tests/problems/0168_backspace_string_compare_test.cpp #include "../../problems/0168_backspace_string_compare.hpp" #include <bits/stdc++.h> #include "../../frameworks/catch.hpp" #include "../../frameworks/asserts.hpp" using namespace std; TEST_CASE( "Backspace String Compare" ) { Solution sol; REQUIRE(sol.backspaceCompare("ab#c","ad#c")); REQUIRE(sol.backspaceCompare("ab##","c#d#")); REQUIRE(sol.backspaceCompare("a##c","#a#c")); REQUIRE(!sol.backspaceCompare("a#c","b")); }
jochenw/afw
afw-core/src/main/java/com/github/jochenw/afw/core/inject/simple/SimpleComponentFactory.java
<reponame>jochenw/afw /* * Copyright 2018 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.jochenw.afw.core.inject.simple; import java.lang.annotation.Annotation; import java.lang.reflect.AnnotatedElement; 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.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.function.Supplier; import javax.inject.Inject; import javax.inject.Provider; import com.github.jochenw.afw.core.inject.IComponentFactory; import com.github.jochenw.afw.core.inject.IComponentFactoryAware; import com.github.jochenw.afw.core.inject.Key; import com.github.jochenw.afw.core.inject.OnTheFlyBinder; import com.github.jochenw.afw.core.inject.Scope; import com.github.jochenw.afw.core.inject.Scopes; import com.github.jochenw.afw.core.util.Exceptions; import com.github.jochenw.afw.core.util.Objects; /** A simple, standalone implementation of an {@link IComponentFactory}. */ public class SimpleComponentFactory implements IComponentFactory { /** * A binding is a supplier of an injectable value, that has been * registered under a suitable key. * @param <T> The injectable values type. */ public abstract static class Binding<T> implements Supplier<T> { } protected static class MetaData { private final Consumer<Object> initializer; private final Provider<Object> instantiator; public MetaData(Consumer<Object> pInitializer, Provider<Object> pInstantiator) { initializer = pInitializer; instantiator = pInstantiator; } public void init(Object pObject) { initializer.accept(pObject); } public Object newInstance() { return instantiator.get(); } } private Predicate<Class<?>> staticInjectionPredicate; private OnTheFlyBinder onTheFlyBinder; private final Map<Type,SimpleBindingList> bindings = new HashMap<>(); private final Map<Type,MetaData> metaDataMap = new HashMap<>(); private final List<Runnable> finalizers = new ArrayList<>(); @SuppressWarnings("unused") private boolean immutable; private static final Predicate<Annotation> SBL_ANNOTATION_FILTER = (a) -> !(a instanceof Inject); /** * A predicate, which decides, whether a class requires static injection. * @return A predicate, which decides, whether a class requires static * injection. */ public Predicate<Class<?>> getStaticInjectionPredicate() { return staticInjectionPredicate; } void setStaticInjectionPredicate(Predicate<Class<?>> pPredicate) { staticInjectionPredicate = pPredicate; } /** Returns the {@link OnTheFlyBinder}, which can create bindings * dynamically. * @return The {@link OnTheFlyBinder}, which can create bindings * dynamically. */ public OnTheFlyBinder getOnTheFlyBinder() { return onTheFlyBinder; } void setOnTheFlyBinder(OnTheFlyBinder pBinder) { onTheFlyBinder = pBinder; } @Override public void init(Object pObject) { getMetaData(pObject.getClass()).init(pObject); if (pObject instanceof IComponentFactoryAware) { ((IComponentFactoryAware) pObject).init(this); } } @SuppressWarnings("unchecked") @Override public <O> O getInstance(Key<O> pKey) { final SimpleBindingList sbl = findBindingList(pKey.getType(), true); if (sbl == null) { return null; } else { final Binding<O> binding; synchronized(sbl) { binding = (Binding<O>) sbl.find(pKey); } if (binding == null) { return null; } else { return binding.get(); } } } @Override public <O> O newInstance(Class<? extends O> pImplClass) { @SuppressWarnings("unchecked") final O o = (O) getMetaData(pImplClass).newInstance(); return o; } /** * Registers a binding under the given key. * @param pKey The bindings key in the map of registered bindings. * @param pBinding The binding, which is being registered. * @param pReplace Whether replacement of an existing binding is * permitted. */ public void addBinding(Key<?> pKey, Binding<?> pBinding, boolean pReplace) { final SimpleBindingList sbl = findBindingList(pKey.getType(), false); synchronized(sbl) { sbl.add(pKey, pBinding, pReplace); } } protected SimpleBindingList findBindingList(Type pType, boolean pNullableResult) { final SimpleBindingList nullableSbl; synchronized(bindings) { nullableSbl = bindings.get(pType); } final SimpleBindingList sbl; if (nullableSbl == null) { if (pNullableResult) { return null; } sbl = new SimpleBindingList(); synchronized(bindings) { bindings.put(pType, sbl); } } else { sbl = nullableSbl; } return sbl; } protected void addFinalizer(Runnable pRunnable) { finalizers.add(pRunnable); } protected class SingletonBinding<T> extends Binding<T> { private final Provider<T> provider; private boolean created, initialized, initializing; private T instance; public SingletonBinding(Provider<T> pProvider) { provider = pProvider; } @Override public T get() { final T inst; synchronized(this) { if (initialized) { inst = instance; } else { if (!created) { instance = provider.get(); created = true; } inst = instance; if (!initialized) { if (!initializing) { initializing = true; init(instance); } initialized = true; } } } return inst; } } protected Binding<?> newBinding(Provider<?> pProvider, Scope pScope) { @SuppressWarnings("unchecked") final Provider<Object> prov = (Provider<Object>) pProvider; final Binding<Object> binding; if (pScope == Scopes.EAGER_SINGLETON) { binding = new SingletonBinding<Object>(prov); addFinalizer(() -> binding.get()); } else if (pScope == Scopes.SINGLETON) { binding = new SingletonBinding<Object>(prov); } else if (pScope == Scopes.NO_SCOPE || pScope == null) { binding = new Binding<Object>() { @Override public Object get() { final Object instance = prov.get(); init(instance); return instance; } }; } else { throw new IllegalStateException("Invalid scope: " + pScope); } final Binding<?> b = (Binding<?>) binding; return b; } protected void makeImmutable() { finalizers.forEach((r) -> r.run()); finalizers.clear(); immutable = true; } protected MetaData getMetaData(Type pType) { synchronized(metaDataMap) { final MetaData md = metaDataMap.get(pType); if (md != null) { return md; } } final MetaData md = newMetaData(pType); synchronized(metaDataMap) { metaDataMap.put(pType, md); } return md; } protected MetaData newMetaData(Type pType) { final Class<?> type = (Class<?>) pType; final Consumer<Object> initializer = newInitializer(type); final Provider<Object> instantiator = newInstantiator(type); return new MetaData(initializer, instantiator); } private Consumer<Object> newInitializer(Class<?> pType) { final List<Consumer<Object>> initializers = new ArrayList<>(); final Consumer<Consumer<Object>> initializerSink = (co) -> initializers.add(co); final List<Class<?>> classes = new ArrayList<>(); Class<?> cl = pType; while (cl != null && !Object.class.equals(cl)) { classes.add(0, cl); cl = cl.getSuperclass(); } for (Class<?> c : classes) { findFieldInitializers(pType, c, initializerSink); findMethodInitializers(pType, c, initializerSink); }; if (onTheFlyBinder != null) { onTheFlyBinder.findConsumers(this, pType, initializerSink); } return (o) -> initializers.forEach((i) -> i.accept(o)); } private Provider<Object> newInstantiator(Class<?> pType) { Constructor<?> constructor = null; for (Constructor<?> c : pType.getDeclaredConstructors()) { if (c.isAnnotationPresent(Inject.class)) { constructor = c; break; } } if (constructor == null) { return () -> { try { return pType.newInstance(); } catch (Throwable t) { throw Exceptions.show(t); } }; } final Constructor<?> c = constructor; final Binding<?>[] bindings = findBindings(c.getParameters(), c.getGenericParameterTypes(), c.getParameterAnnotations(), "Constructor of class " + pType.getName()); return () -> { try { if (!c.isAccessible()) { c.setAccessible(true); } final Object o = c.newInstance(getParameters(bindings)); return o; } catch (Throwable t) { throw Exceptions.show(t); } }; } protected boolean isStaticInjectionRequested(Class<?> pType) { return staticInjectionPredicate != null && staticInjectionPredicate.test(pType); } protected void findFieldInitializers(Class<?> pType, Class<?> pSuperClass, Consumer<Consumer<Object>> pInitializerSink) { final BiConsumer<Field, Provider<Object>> processor = (f,p) -> { final Consumer<Object> consumer = (o) -> { try { if (!f.isAccessible()) { f.setAccessible(true); } f.set(o, p.get()); } catch (Throwable t) { throw Exceptions.show(t); } }; pInitializerSink.accept(consumer); }; for (Field f : pSuperClass.getDeclaredFields()) { if (f.isAnnotationPresent(Inject.class)) { if (!Modifier.isStatic(f.getModifiers()) || isStaticInjectionRequested(pSuperClass)) { Binding<?> binding = findBinding(f, f.getGenericType(), f.getAnnotations()); if (binding == null) { throw new IllegalStateException("No binding registered for field " + f.getName() + " in class " + pSuperClass.getName()); } final Binding<?> b = binding; processor.accept(f,() -> b.get()); } } if (onTheFlyBinder != null) { final Provider<Object> prov = onTheFlyBinder.getProvider(this, f); if (prov != null) { processor.accept(f, prov); } } } } protected void findMethodInitializers(Class<?> pType, Class<?> pSuperClass, Consumer<Consumer<Object>> pInitializerSink) { for (Method m : pSuperClass.getDeclaredMethods()) { if (m.isAnnotationPresent(Inject.class)) { if (Modifier.isStatic(m.getModifiers()) && !isStaticInjectionRequested(pSuperClass)) { continue; } if (Modifier.isAbstract(m.getModifiers())) { continue; } if (isInjectedMethodOverwrittenByInjectedMethod(pType, m)) { continue; } if (isPackagePrivateMethodOverwritten(pType, m)) { continue; } if (isPublicMethodOverwrittenByNotAnnotatedMethod(pType, m)) { continue; } final Method mth = Objects.notNull(findOverridingPublicMethod(pType, m), m); final Binding<?>[] bindings = findBindings(mth.getParameters(), mth.getGenericParameterTypes(), mth.getParameterAnnotations(), "Method " + mth.getName() + " in class " + pSuperClass.getName()); final Consumer<Object> consumer = (o) -> { if (!m.isAccessible()) { m.setAccessible(true); } try { m.invoke(o, getParameters(bindings)); } catch (Throwable t) { throw Exceptions.show(t); } }; pInitializerSink.accept(consumer); } } } protected boolean isPublicMethodOverwrittenByNotAnnotatedMethod(Class<?> pType, Method pMethod) { if (!Modifier.isPublic(pMethod.getModifiers())) { return false; } final String name = pMethod.getName(); final Class<?>[] paramTypes = pMethod.getParameterTypes(); Class<?> cl = pType; while (cl != null && cl != Object.class && !pMethod.getDeclaringClass().equals(cl)) { Method m2; try { m2 = cl.getDeclaredMethod(name, paramTypes); } catch (NoSuchMethodException e) { m2 = null; } if (m2 != null) { return !m2.isAnnotationPresent(Inject.class); } cl = cl.getSuperclass(); } return false; } protected Method findOverridingPublicMethod(Class<?> pType, Method pMethod) { final int mod = pMethod.getModifiers(); if (!Modifier.isPublic(mod)) { return null; } final String name = pMethod.getName(); final Class<?>[] paramTypes = pMethod.getParameterTypes(); Class<?> cl = pType; while (cl != null && cl != Object.class && !pMethod.getDeclaringClass().equals(cl)) { Method m2; try { m2 = cl.getDeclaredMethod(name, paramTypes); } catch (NoSuchMethodException e) { m2 = null; } if (m2 != null) { return m2; } cl = cl.getSuperclass(); } return null; } protected boolean isPackagePrivateMethodOverwritten(Class<?> pType, Method pMethod) { final int mod = pMethod.getModifiers(); if (Modifier.isPrivate(mod) || Modifier.isProtected(mod) || Modifier.isPublic(mod)) { return false; } final String name = pMethod.getName(); final Class<?>[] paramTypes = pMethod.getParameterTypes(); Class<?> cl = pType; while (cl != null && cl != Object.class && !pMethod.getDeclaringClass().equals(cl)) { Method m2; try { m2 = cl.getDeclaredMethod(name, paramTypes); } catch (NoSuchMethodException e) { m2 = null; } if (m2 != null) { return true; } cl = cl.getSuperclass(); } return false; } protected boolean isInjectedMethodOverwrittenByInjectedMethod(Class<?> pType, Method pMethod) { final String name = pMethod.getName(); final Class<?>[] paramTypes = pMethod.getParameterTypes(); Class<?> cl = pType; while (cl != null && cl != Object.class && !pMethod.getDeclaringClass().equals(cl)) { Method m2; try { m2 = cl.getDeclaredMethod(name, paramTypes); } catch (NoSuchMethodException e) { m2 = null; } if (m2 != null && m2.isAnnotationPresent(Inject.class)) { return true; } cl = cl.getSuperclass(); } return false; } protected Object[] getParameters(Binding<?>[] pBindings) { final Object[] array = new Object[pBindings.length]; for (int i = 0; i < array.length; i++) { array[i] = pBindings[i].get(); } return array; } protected Binding<?>[] findBindings(AnnotatedElement[] pAnnotatables, Type[] pTypes, Annotation[][] pAnnotations, String pDescription) { final Binding<?>[] bindings = (Binding<?>[]) Array.newInstance(Binding.class, pTypes.length); for (int j = 0; j < bindings.length; j++) { final int i = j; final Binding<?> b = findBinding(pAnnotatables[i], pTypes[i], pAnnotations[i]); if (b == null) { throw new IllegalStateException("No binding available for parameter " + i + " of " + pDescription); } bindings[i] = b; } return bindings; } protected Binding<?> findBinding(AnnotatedElement pAnnotatable, Type pType, Annotation[] pAnnotations) { final SimpleBindingList sbl = findBindingList(pType, true); Binding<?> binding; if (sbl == null) { binding = null; } else { synchronized(sbl) { binding = sbl.find(pAnnotations, SBL_ANNOTATION_FILTER); } } if (binding == null) { if (onTheFlyBinder != null && pAnnotatable instanceof Field) { final Provider<?> prov = onTheFlyBinder.getProvider(this, (Field) pAnnotatable); if (prov != null) { binding = newBinding(prov, Scopes.NO_SCOPE); } } } if (binding == null && pType instanceof ParameterizedType) { final ParameterizedType ptype = (ParameterizedType) pType; if (Provider.class.equals(ptype.getRawType())) { final Type[] argTypes = ptype.getActualTypeArguments(); if (argTypes != null && argTypes.length == 1) { final Binding<?> b = findBinding(pAnnotatable, argTypes[0], pAnnotations); if (b != null) { final Provider<Object> prov = () -> b.get(); final Provider<Provider<Object>> prov2 = () -> prov; binding = newBinding(prov2, Scopes.NO_SCOPE); } } } } return binding; } }
FuyaoLi2017/leetcode
HashMap/leetcode_451_SortCharactersByFrequency.java
/* Given a string, sort it in decreasing order based on the frequency of characters. Example 1: Input: "tree" Output: "eert" Explanation: 'e' appears twice while 'r' and 't' both appear once. So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer. Example 2: Input: "cccaaa" Output: "cccaaa" Explanation: Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer. Note that "cacaca" is incorrect, as the same characters must be together. Example 3: Input: "Aabb" Output: "bbAa" Explanation: "bbaA" is also a valid answer, but "Aabb" is incorrect. Note that 'A' and 'a' are treated as two different characters. */ // keep a bucket public class Solution { public String frequencySort(String s) { Map<Character, Integer> map = new HashMap<>(); for (char c : s.toCharArray()) map.put(c, map.getOrDefault(c, 0) + 1); List<Character> [] bucket = new List[s.length() + 1]; for (char key : map.keySet()) { int frequency = map.get(key); if (bucket[frequency] == null) bucket[frequency] = new ArrayList<>(); bucket[frequency].add(key); } StringBuilder sb = new StringBuilder(); for (int pos = bucket.length - 1; pos >= 0; pos--) if (bucket[pos] != null) for (char c : bucket[pos]) for (int i = 0; i < map.get(c); i++) sb.append(c); return sb.toString(); } } // priority queue solution public class Solution { public String frequencySort(String s) { Map<Character, Integer> map = new HashMap<>(); for (char c : s.toCharArray()) map.put(c, map.getOrDefault(c, 0) + 1); PriorityQueue<Map.Entry<Character, Integer>> pq = new PriorityQueue<>((a, b) -> b.getValue() - a.getValue()); pq.addAll(map.entrySet()); StringBuilder sb = new StringBuilder(); while (!pq.isEmpty()) { Map.Entry e = pq.poll(); for (int i = 0; i < (int)e.getValue(); i++) sb.append(e.getKey()); } return sb.toString(); } }
hongduclam/nametests
app/components/media/media.service.js
(function () { 'use strict'; angular .module('lnc.media') .factory('lncMediaService', lncMediaService); lncMediaService.$inject = ['$http', '$log', 'lncModalService', 'userService']; function lncMediaService($http, $log, lncModalService, userService) { var url = '/media'; //var cdn = 'http://cdn.dev.lnc.vn'; var cdn = 'http://cdn.abyourself.local'; //var cdn = 'http://cdn.finance.local'; var TYPE = { FOLDER: 0, FILE: 1 }; var SHARE_TYPE = { PERSONAL: 0, GLOBAL: 1 }; return { TYPE: TYPE, SHARE_TYPE: SHARE_TYPE, getRoot: getRoot, getTree: getTree, updateNode: updateNode, create: createNode, edit: editNode, delete: deleteNode, thumbnailFile: thumbnailFile, thumbnail: thumbnail, download: download, modal: modal, isImage: isImage, setProperties: setProperties, uploadCanvas: uploadCanvas, getMediaPermission: getMediaPermission, slide: slide, productImageUrl: productImageUrl, imageUrl: imageUrl, product: { preview: _productPreview } }; //////////////// function imageUrl(id){ return cdn + '/image/' + id; } function _productPreview(id) { return cdn + '/product/' + id + '/preview'; } function getMediaPermission() { return { CREATE: true, UPDATE: true, DELETE:true }; /*return { READ: userService.hasPermission('media', 'READ'), CREATE: userService.hasPermission('media', 'CREATE'), DELETE: userService.hasPermission('media', 'DELETE'), DOWNLOAD: userService.hasPermission('media', 'DOWNLOAD'), UPDATE: userService.hasPermission('media', 'UPDATE') };*/ } function productImageUrl(pId, mId) { return cdn + '/product/' + pId + '/image/' + mId; } function uploadCanvas(data) { return $http.post(url + '/upload/canvas', data); } function setProperties(id, properties) { return $http.post(url + '/tree/' + id + '/properties', properties); } function slide(images) { var modalInstance = lncModalService.open({ effect: false, isFullScreen: true, templateUrl: 'components/media/slider.tpl.html', controller: 'LncSliderController', controllerAs: 'sl', bindToController: true, resolve: { images: function () { return images; } } }); return modalInstance; } function modal(type, selectType) { var title; if (type === 'image') { title = 'Select Image'; } else { title = 'Select Documents'; } var modalInstance = lncModalService.open({ templateUrl: 'components/media/media-modal.tpl.html', title: title, subtitle: '', controller: 'LncMediaModalController', controllerAs: 'mm', bindToController: true, size: 'modal-full', resolve: { type: function () { return type || 'document'; }, selectType: function () { return selectType; } } }); return modalInstance; } function createNode(parentNode, data) { var createUrl = url + '/tree'; if (lnc.hasValue(parentNode)) { createUrl += '/' + parentNode; } return $http.post(createUrl, data).then(function (response) { return response.data; }); } function editNode(id, data) { return $http.put(url + '/tree/' + id, data).then(function (response) { return response.data; }); } function deleteNode(id) { return $http.delete(url + '/tree/' + id).then(function (response) { return response.data; }); } function getRoot(type) { return $http.get(url + '/tree/' + type).then(function (response) { return response.data; }); } function updateNode(data) { return $http.post(url + '/tree', data).then(function (response) { return response.data; }); } function getTree(node, type) { var treeUrl = url + '/tree/' + node + '/' + type; return $http.get(treeUrl).then(function (response) { return response.data; }); } function thumbnailFile(fileObj) { var rs = 'image/filetype/documents.svg'; /* Detect File Mimetype */ if (lnc.hasValue(fileObj)) { var mimetype = fileObj.mimetype; if (isImage(mimetype)) { rs = thumbnail(fileObj.id); } else if (isPDF(mimetype)) { rs = thumbnail(fileObj.id); } else if (isMP3(mimetype)) { rs = 'image/filetype/mp3.svg'; } else if (isPowerPoint(mimetype)) { rs = 'image/filetype/ppt.svg'; } else if (isZip(mimetype)) { rs = 'image/filetype/zip.svg'; } else if (isExcel(mimetype)) { rs = 'image/filetype/xls.svg'; } else if (isWord(mimetype)) { rs = 'image/filetype/doc.svg'; } else if (isXML(mimetype)) { rs = 'image/filetype/xml.svg'; } else if (isVideo(mimetype)) { rs = 'image/filetype/avi.svg'; } } return rs; } function isVideo(mimetype) { return mimetype.match(/video\/*/); } function isImage(mimetype) { return mimetype.match(/image\/*/); } function isPDF(mimetype) { return mimetype.match(/application\/pdf/); } function isMP3(mimetype) { return mimetype.match('/audio\/mpeg/'); } function isPowerPoint(mimetype) { return mimetype.match(/application\/vnd.ms-powerpoint | application\/vnd.openxmlformats-officedocument.presentationml.presentation | application\/vnd.openxmlformats-officedocument.presentationml.template | application\/vnd.openxmlformats-officedocument.presentationml.slideshow/); } function isXML(mimetype) { return mimetype.match(/application\/zip | application\/x-compressed-zip/); } function isZip(mimetype) { return mimetype.match(/application\/xml/); } function isExcel(mimetype) { return mimetype.match(/application\/vnd.ms-excel|application\/vnd.ms-excel.addin.macroEnabled.12|application\/vnd.openxmlformats-officedocument.spreadsheetml.sheet|application\/vnd.openxmlformats-officedocument.spreadsheetml.template/); } function isWord(mimetype) { return mimetype.match(/application\/msword|application\/vnd.openxmlformats-officedocument.wordprocessingml.document|application\/vnd.openxmlformats-officedocument.wordprocessingml.template/); } function thumbnail(id) { return cdn + '/' + id + '/thumbnail'; } function download(id) { return '/media/' + id + '/download'; } } })();
TiENChain/yoti-java-sdk
yoti-sdk-impl/src/main/java/com/yoti/api/client/spi/remote/call/Receipt.java
<reponame>TiENChain/yoti-java-sdk package com.yoti.api.client.spi.remote.call; import static org.bouncycastle.util.encoders.Base64.toBase64String; import java.util.Arrays; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) public final class Receipt { @JsonProperty("receipt_id") private byte[] receiptId; @JsonProperty("other_party_profile_content") private byte[] otherPartyProfile; @JsonProperty("profile_content") private byte[] profile; @JsonProperty("other_party_extra_data_content") private byte[] otherPartyExtraData; @JsonProperty("extra_data_content") private byte[] extraData; @JsonProperty("wrapped_receipt_key") private byte[] wrappedReceiptKey; @JsonProperty("policy_uri") private String policyUri; @JsonProperty("personal_key") private byte[] personalKey; @JsonProperty("remember_me_id") private byte[] rememberMeId; @JsonProperty("sharing_outcome") private Outcome outcome; @JsonProperty("timestamp") private String timestamp; public static final class Builder { private final Receipt receipt = new Receipt(); public Builder withWrappedReceiptKey(byte[] wrappedReceiptKey) { receipt.wrappedReceiptKey = wrappedReceiptKey; return this; } public Builder withProfile(byte[] profileData) { receipt.profile = profileData; return this; } public Builder withReceiptId(byte[] receiptId) { receipt.receiptId = receiptId; return this; } public Builder withOtherPartyProfile(byte[] otherPartyProfile) { receipt.otherPartyProfile = otherPartyProfile; return this; } public Builder withOtherPartyExtraData(byte[] otherPartyExtraData) { receipt.otherPartyExtraData = otherPartyExtraData; return this; } public Builder withExtraData(byte[] extraData) { receipt.extraData = extraData; return this; } public Builder withPolicyUri(String policyUri) { receipt.policyUri = policyUri; return this; } public Builder withPersonalKey(byte[] personalKey) { receipt.personalKey = personalKey; return this; } public Builder withOutcome(Outcome outcome) { receipt.outcome = outcome; return this; } public Builder withRememberMeId(byte[] rememberMeId) { receipt.rememberMeId = rememberMeId; return this; } public Builder withTimestamp(String timestamp) { receipt.timestamp = timestamp; return this; } public Receipt build() { return receipt; } } public enum Outcome { SUCCESS(true), FAILURE(false); private final boolean successful; Outcome(boolean successful) { this.successful = successful; } public boolean isSuccessful() { return successful; } } public byte[] getReceiptId() { return receiptId; } public byte[] getOtherPartyProfile() { return otherPartyProfile; } public byte[] getProfile() { return profile; } public byte[] getOtherPartyExtraData() { return otherPartyExtraData; } public byte[] getExtraData() { return extraData; } public byte[] getWrappedReceiptKey() { return wrappedReceiptKey; } public String getPolicyUri() { return policyUri; } public byte[] getPersonalKey() { return personalKey; } public Outcome getOutcome() { return outcome; } public byte[] getRememberMeId() { return rememberMeId; } public String getTimestamp() { return timestamp; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode(extraData); result = prime * result + Arrays.hashCode(otherPartyExtraData); result = prime * result + Arrays.hashCode(otherPartyProfile); result = prime * result + ((outcome == null) ? 0 : outcome.hashCode()); result = prime * result + Arrays.hashCode(personalKey); result = prime * result + ((policyUri == null) ? 0 : policyUri.hashCode()); result = prime * result + Arrays.hashCode(profile); result = prime * result + Arrays.hashCode(receiptId); result = prime * result + Arrays.hashCode(rememberMeId); result = prime * result + ((timestamp == null) ? 0 : timestamp.hashCode()); result = prime * result + Arrays.hashCode(wrappedReceiptKey); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Receipt other = (Receipt) obj; if (!Arrays.equals(extraData, other.extraData)) { return false; } if (!Arrays.equals(otherPartyExtraData, other.otherPartyExtraData)) { return false; } if (!Arrays.equals(otherPartyProfile, other.otherPartyProfile)) { return false; } if (outcome != other.outcome) { return false; } if (!Arrays.equals(personalKey, other.personalKey)) { return false; } if (policyUri == null) { if (other.policyUri != null) { return false; } } else if (!policyUri.equals(other.policyUri)) { return false; } if (!Arrays.equals(profile, other.profile)) { return false; } if (!Arrays.equals(receiptId, other.receiptId)) { return false; } if (!Arrays.equals(rememberMeId, other.rememberMeId)) { return false; } if (timestamp == null) { if (other.timestamp != null) { return false; } } else if (!timestamp.equals(other.timestamp)) { return false; } if (!Arrays.equals(wrappedReceiptKey, other.wrappedReceiptKey)) { return false; } return true; } public String getDisplayReceiptId() { return receiptId != null ? toBase64String(receiptId) : "<>"; } }
JeanRev/TeamcityDockerCloudPlugin
server/src/test/java/run/var/teamcity/cloud/docker/test/TestRootUrlHolder.java
package run.var.teamcity.cloud.docker.test; import jetbrains.buildServer.RootUrlHolder; import javax.annotation.Nonnull; public class TestRootUrlHolder implements RootUrlHolder { public static final String HOLDER_URL = "http://" + TestRootUrlHolder.class.getName(); @Nonnull @Override public String getRootUrl() { return HOLDER_URL; } @Override public void setRootUrl(@Nonnull String rootUrl) { throw new UnsupportedOperationException("Not a real plugin."); } }
ruwhan/simple-fb-daily-insight
src/reducers/adAccountsReducer.js
<reponame>ruwhan/simple-fb-daily-insight<gh_stars>0 import { ACCOUNT_FETCH_FAIL, ACCOUNT_FETCH_LOADING, ACCOUNT_FETCH_SUCCESS, ACCOUNT_SELECT, } from "../constants"; import { createReducer } from "./utils"; const initialState = { isLoading: false, isFetched: false, selectedAdAccount: '', entities: { byId: {}, ids: [], } } const accountFetching = (state, action) => { return Object.assign({}, state, { isLoading: true, }); } const storeAccounts = (state, action) => { const { payload } = action; const { data } = payload; let byId = {}; let ids = []; data.forEach((item) => { byId[item.id] = item; }); ids = data.map((item) => item.id); return Object.assign({}, state, { entities: { byId, ids, }, isLoading: false, isFetched: true, }); } const accountFetchFail = (state, action) => { return Object.assign({}, state, { isLoading: false, }); } const setSelectedAdAccount = (state, action) => { const { payload } = action; const { adAccountId } = payload; return Object.assign({}, state, { selectedAdAccount: adAccountId, }); } export default createReducer(initialState, { [ACCOUNT_FETCH_LOADING]: accountFetching, [ACCOUNT_FETCH_SUCCESS]: storeAccounts, [ACCOUNT_FETCH_FAIL]: accountFetchFail, [ACCOUNT_SELECT]: setSelectedAdAccount, })
SCIInstitute/shapeworks
Libs/Project/ProjectUtils.cpp
#include "ProjectUtils.h" namespace shapeworks { //--------------------------------------------------------------------------- vtkSmartPointer<vtkTransform> shapeworks::ProjectUtils::convert_transform(std::vector<double> list) { vtkSmartPointer<vtkTransform> transform = vtkSmartPointer<vtkTransform>::New(); transform->Identity(); if (list.size() == 12) { double tx = list[9]; double ty = list[10]; double tz = list[11]; transform->Translate(tx, ty, tz); } else if (list.size() == 16) { vtkSmartPointer<vtkMatrix4x4> matrix = vtkSmartPointer<vtkMatrix4x4>::New(); for (int i = 0; i < 16; i++) { matrix->GetData()[i] = list[i]; } transform->SetMatrix(matrix); } return transform; } //--------------------------------------------------------------------------- std::vector<double> ProjectUtils::convert_transform(vtkSmartPointer<vtkTransform> transform) { std::vector<double> list; for (int i = 0; i < 16; i++) { list.push_back(transform->GetMatrix()->GetData()[i]); } return list; } }
SammyEnigma/stackoverflown
questions/scripting-24799886/main.cpp
#include <QCoreApplication> #include <QScriptEngine> #include <QThread> class ScriptEngine : public QScriptEngine { Q_OBJECT Q_SIGNAL void evaluateSignal(const QString &); public: Q_SLOT void evaluate(const QString & str) { QScriptEngine::evaluate(str); } /// A thread-safe evaluate() Q_SLOT void safeEvaluate(const QString & str) { emit evaluateSignal(str); } explicit ScriptEngine(QObject * parent = 0) : QScriptEngine(parent) { connect(this, &ScriptEngine::evaluateSignal, this, &ScriptEngine::evaluate); } }; class Thread : public QThread { // A thread that's safe to destruct, like it ought to be using QThread::run; // final public: ~Thread() { quit(); wait(); } }; int main(int argc, char ** argv) { QCoreApplication app(argc, argv); ScriptEngine engine; Thread worker; engine.globalObject().setProperty("qApp", engine.newQObject(qApp)); engine.moveToThread(&worker); worker.start(); QMetaObject::invokeMethod(&engine, "evaluate", Q_ARG(QString, "print('Hi!')")); engine.safeEvaluate("print('And hello!')"); engine.safeEvaluate("qApp.quit()"); return app.exec(); } #include "main.moc"
fabbondanza/opencga
opencga-storage/opencga-storage-hadoop/opencga-storage-hadoop-core/src/main/java/org/opencb/opencga/storage/hadoop/variant/annotation/pending/AnnotationPendingVariantsDescriptor.java
<filename>opencga-storage/opencga-storage-hadoop/opencga-storage-hadoop-core/src/main/java/org/opencb/opencga/storage/hadoop/variant/annotation/pending/AnnotationPendingVariantsDescriptor.java package org.opencb.opencga.storage.hadoop.variant.annotation.pending; import org.apache.hadoop.hbase.Cell; import org.apache.hadoop.hbase.client.*; import org.apache.hadoop.hbase.io.compress.Compression; import org.apache.hadoop.hbase.util.Bytes; import org.opencb.opencga.storage.core.metadata.VariantStorageMetadataManager; import org.opencb.opencga.storage.hadoop.utils.HBaseManager; import org.opencb.opencga.storage.hadoop.variant.GenomeHelper; import org.opencb.opencga.storage.hadoop.variant.HadoopVariantStorageOptions; import org.opencb.opencga.storage.hadoop.variant.pending.PendingVariantsDescriptor; import org.opencb.opencga.storage.hadoop.variant.utils.HBaseVariantTableNameGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.function.Function; import static org.opencb.opencga.storage.hadoop.variant.adaptors.phoenix.VariantPhoenixHelper.VariantColumn.SO; import static org.opencb.opencga.storage.hadoop.variant.adaptors.phoenix.VariantPhoenixHelper.VariantColumn.TYPE; public class AnnotationPendingVariantsDescriptor implements PendingVariantsDescriptor { public static final byte[] FAMILY = GenomeHelper.COLUMN_FAMILY_BYTES; public static final byte[] COLUMN = Bytes.toBytes("v"); public static final byte[] VALUE = new byte[0]; private static final byte[] SO_BYTES = SO.bytes(); private static Logger logger = LoggerFactory.getLogger(AnnotationPendingVariantsDescriptor.class); @Override public String name() { return "annotation"; } public void checkValidPendingTableName(String tableName) { HBaseVariantTableNameGenerator.checkValidPendingAnnotationTableName(tableName); } public String getTableName(HBaseVariantTableNameGenerator generator) { return generator.getPendingAnnotationTableName(); } public boolean createTableIfNeeded(String tableName, HBaseManager hBaseManager) throws IOException { return createTableIfNeeded(tableName, hBaseManager, Compression.getCompressionAlgorithmByName( hBaseManager.getConf().get( HadoopVariantStorageOptions.PENDING_ANNOTATION_TABLE_COMPRESSION.key(), HadoopVariantStorageOptions.PENDING_ANNOTATION_TABLE_COMPRESSION.defaultValue()))); } public Scan configureScan(Scan scan, VariantStorageMetadataManager metadataManager) { scan.addColumn(GenomeHelper.COLUMN_FAMILY_BYTES, TYPE.bytes()); scan.addColumn(GenomeHelper.COLUMN_FAMILY_BYTES, SO.bytes()); return scan; } public Function<Result, Mutation> getPendingEvaluatorMapper(VariantStorageMetadataManager metadataManager, boolean overwrite) { return value -> { if (overwrite || isPending(value)) { Put put = new Put(value.getRow()); put.addColumn(FAMILY, COLUMN, VALUE); return put; } else { return new Delete(value.getRow()); } }; } private boolean isPending(Result value) { for (Cell cell : value.rawCells()) { if (cell.getValueLength() > 0) { if (Bytes.equals( cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength(), SO_BYTES, 0, SO_BYTES.length)) { return false; } } } return true; } }
kolly83/kore
pkg/kore/audit.go
/** * Copyright 2020 Appvia Ltd <<EMAIL>> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kore import ( "context" "time" orgv1 "github.com/appvia/kore/pkg/apis/org/v1" "github.com/appvia/kore/pkg/kore/authentication" "github.com/appvia/kore/pkg/persistence" log "github.com/sirupsen/logrus" ) // Audit represents the interface to the top-level Kore Audit service. type Audit interface { // AuditEvents returns a stream of events across teams since x AuditEvents(context.Context, time.Duration) (*orgv1.AuditEventList, error) // AuditEventsTeam returns a stream of events in relation to a specific team AuditEventsTeam(ctx context.Context, team string, since time.Duration) (*orgv1.AuditEventList, error) // Record stores an event in the underlying audit service. Record(ctx context.Context, fields ...persistence.AuditFunc) persistence.Log } type auditImpl struct { auditPersist persistence.Audit } func (a *auditImpl) Record(ctx context.Context, fields ...persistence.AuditFunc) persistence.Log { return a.auditPersist.Record(ctx, fields[:]...) } // AuditEvents returns all events since the specified duration before the current time func (a *auditImpl) AuditEvents(ctx context.Context, since time.Duration) (*orgv1.AuditEventList, error) { // @step: must be a admin user user := authentication.MustGetIdentity(ctx) if !user.IsGlobalAdmin() { log.WithField( "username", user.Username(), ).Warn("user trying to access the audit logs") return nil, NewErrNotAllowed("Must be global admin") } // @step: retrieve a list of audit events across all teams list, err := a.auditPersist.Find(ctx, persistence.Filter.WithDuration(since), ).Do() if err != nil { log.WithError(err).Error("trying to retrieve audit logs for teams") return nil, err } return DefaultConvertor.FromAuditModelList(list), nil } // AuditEventsTeam returns events in relation to a specific team since the specified duration before the current time func (a *auditImpl) AuditEventsTeam(ctx context.Context, team string, since time.Duration) (*orgv1.AuditEventList, error) { // @step: Check user in the team requested or a global admin user := authentication.MustGetIdentity(ctx) userInTeam := false for _, t := range user.Teams() { if t == team { userInTeam = true } } if !userInTeam && !user.IsGlobalAdmin() { log.WithFields(log.Fields{ "username": user.Username(), "team": team, }).Warn("user trying to access the audit logs for team they're not a member of") return nil, NewErrNotAllowed("Must be global admin or a team member") } list, err := a.auditPersist.Find(ctx, persistence.Filter.WithTeam(team), persistence.Filter.WithDuration(since), ).Do() if err != nil { log.WithError(err).Error("trying to retrieve audit logs for team") return nil, err } return DefaultConvertor.FromAuditModelList(list), nil }
fgascon/derivative
lib/ObservableList.js
'use strict'; var DerivativeNumber = require('./DerivativeNumber'); var DerivativeList = require('./DerivativeList'); module.exports = { //sequence algorithms map: function map(mapper, context) { return new DerivativeList([this], function (list) { return list.map(mapper, context); }); }, filter: function filter(predicate, context) { return new DerivativeList([this], function (list) { return list.filter(predicate, context); }); }, filterNot: function filterNot(predicate, context) { return new DerivativeList([this], function (list) { return list.filterNot(predicate, context); }); }, reverse: function reverse() { return new DerivativeList([this], function (list) { return list.reverse(); }); }, sort: function sort(comparator) { return new DerivativeList([this], function (list) { return list.sort(comparator); }); }, sortBy: function sortBy(comparatorValueMapper, comparator) { return new DerivativeList([this], function (list) { return list.sortBy(comparatorValueMapper, comparator); }); }, //creating subsets slice: function slice(begin, end) { return new DerivativeList([this, begin, end], function (list, begin, end) { return list.slice(begin, end); }); }, rest: function rest() { return new DerivativeList([this], function (list) { return list.rest(); }); }, butLast: function butLast() { return new DerivativeList([this], function (list) { return list.butLast(); }); }, skip: function skip(amount) { return new DerivativeList([this, amount], function (list, amount) { return list.skip(amount); }); }, skipLast: function skipLast(amount) { return new DerivativeList([this, amount], function (list, amount) { return list.skipLast(amount); }); }, skipWhile: function skipWhile(predicate, context) { return new DerivativeList([this, predicate], function (list, predicate) { return list.skipWhile(predicate, context); }); }, skipUntil: function skipUntil(predicate, context) { return new DerivativeList([this, predicate], function (list, predicate) { return list.skipUntil(predicate, context); }); }, take: function take(amount) { return new DerivativeList([this, amount], function (list, amount) { return list.take(amount); }); }, takeLast: function takeLast(amount) { return new DerivativeList([this, amount], function (list, amount) { return list.takeLast(amount); }); }, takeWhile: function takeWhile(predicate, context) { return new DerivativeList([this, predicate], function (list, predicate) { return list.takeWhile(predicate, context); }); }, takeUntil: function takeUntil(predicate, context) { return new DerivativeList([this, predicate], function (list, predicate) { return list.takeUntil(predicate, context); }); }, //combination concat: function concat(iterable) { return new DerivativeList([this, iterable], function (list, iterable) { return list.concat(iterable); }); }, flatten: function flatten(depth) { return new DerivativeList([this, depth], function (list, depth) { return list.flatten(depth); }); }, interpose: function interpose(separator) { return new DerivativeList([this, separator], function (list, separator) { return list.interpose(separator); }); }, interleave: function interleave(iterable) { return new DerivativeList([this, iterable], function (list, iterable) { return list.interleave(iterable); }); }, zip: function zip(iterable) { return new DerivativeList([this, iterable], function (list, iterable) { return list.zip(iterable); }); }, zipWith: function zipWith(zipper, iterable) { return new DerivativeList([this, iterable], function (list, iterable) { return list.zipWith(zipper, iterable); }); }, //search for value indexOf: function indexOf(searchValue) { return new DerivativeNumber([this, searchValue], function (list, searchValue) { return list.indexOf(searchValue); }); }, lastIndexOf: function lastIndexOf(searchValue) { return new DerivativeNumber([this, searchValue], function (list, searchValue) { return list.lastIndexOf(searchValue); }); }, findIndex: function findIndex(predicate, context) { return new DerivativeNumber([this], function (list) { return list.findIndex(predicate, context); }); }, findLastIndex: function findLastIndex(predicate, context) { return new DerivativeNumber([this], function (list) { return list.findLastIndex(predicate, context); }); } };
PascalLG/zinc-cpp
test/http/ut_http_status.cpp
<reponame>PascalLG/zinc-cpp //======================================================================== // Zinc - Unit Testing // Copyright (c) 2019, <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. //======================================================================== #include "gtest/gtest.h" #include "http/http_status.h" //-------------------------------------------------------------- // Test the HttpStatus class creation and assignment. //-------------------------------------------------------------- TEST(HttpStatus, Creation) { HttpStatus x1(200); HttpStatus x2(x1); HttpStatus x3 = x2; HttpStatus y1(403); HttpStatus y2(y1); HttpStatus y3 = y2; EXPECT_EQ(x1.getStatusCode(), 200); EXPECT_EQ(x2.getStatusCode(), 200); EXPECT_EQ(x3.getStatusCode(), 200); EXPECT_EQ(y1.getStatusCode(), 403); EXPECT_EQ(y2.getStatusCode(), 403); EXPECT_EQ(y3.getStatusCode(), 403); } //-------------------------------------------------------------- // Test the HttpStatus class comparison operators. //-------------------------------------------------------------- TEST(HttpStatus, Comparison) { HttpStatus x1(301); HttpStatus x2(301); HttpStatus y1(404); HttpStatus y2(404); EXPECT_EQ(x1, x2); EXPECT_EQ(x2, x1); EXPECT_EQ(y1, y2); EXPECT_EQ(y2, y1); EXPECT_NE(x1, y1); EXPECT_NE(y1, x1); EXPECT_NE(x2, y2); EXPECT_NE(y2, x2); } //-------------------------------------------------------------- // Test the HttpStatus.getStatusString() function. //-------------------------------------------------------------- TEST(HttpStatus, getStatusString) { EXPECT_EQ(HttpStatus(100).getStatusString(), "Continue"); EXPECT_EQ(HttpStatus(200).getStatusString(), "OK"); EXPECT_EQ(HttpStatus(418).getStatusString(), "I’m a teapot"); EXPECT_EQ(HttpStatus(500).getStatusString(), "Internal Server Error"); EXPECT_EQ(HttpStatus(511).getStatusString(), "Network authentication required"); EXPECT_EQ(HttpStatus(999).getStatusString(), ""); } //========================================================================
ThomasAndrewMacLean/bumperballs
components/Footer.js
import React from 'react'; import styled from 'styled-components'; import T from './Translation'; const Footer = () => { return ( <FooterWrap className="topBottomPadding"> <div className="left"> <T id="contactTitel"></T> <T id="site-titel"></T> <T id="btwNummer"></T> <T id="telefoonnummer"></T> <T id="mail"></T> <T id="adres"></T> </div> <div className="right"> <a href="https://www.facebook.com/BMSrent/" rel="noreferrer" target="_blank" > Facebook </a> <br /> <br /> <br /> <br /> Made with ❤️ {new Date().getFullYear()} ©{' '} <a href="https://westerling-maclean.be" rel="noopener noreferrer nofollow" target="_blank" > Westerling&nbsp;&amp;&nbsp;MacLean </a> </div> </FooterWrap> ); }; const FooterWrap = styled.footer` font-size: 1rem; padding: 4rem 2rem; font-weight: 200; h2 { text-decoration: none; } a { color: inherit; } display: flex; justify-content: space-around; align-items: flex-end; flex-wrap: wrap; .left, .right { max-width: 50%; min-width: 200px; } .right { padding-top: 2rem; @media (min-width: 500px) { text-align: right; } } background: var(--background-modal); `; export default Footer;
ks3sdk/-new_Ks3Sdk_ios
KS3YunSDK/KS3YunSDK.h
// // NEW_KSCSDK.h // NEW_KSCSDK // // Created by ks3 on 2020/08/06. // Copyright (c) 2020 KS3. All rights reserved. // #import <UIKit/UIKit.h> #ifdef __OBJC__ //! Project version number for NEW_KSCSDK. FOUNDATION_EXPORT double NEW_KSCSDKVersionNumber; //! Project version string for NEW_KSCSDK. FOUNDATION_EXPORT const unsigned char NEW_KSCSDKVersionString[]; // In this header, you should import all the public headers of your framework // using statements like #import <NEW_KSCSDK/PublicHeader.h> #import "KS3AbortMultipartUploadRequest.h" #import "KS3AbortMultipartUploadResponse.h" #import "KS3AbstractPutRequest.h" #import "KS3AbstractWebServiceClient.h" #import "KS3AccessControlList.h" #import "KS3AuthUtils.h" #import "KS3Bucket.h" #import "KS3BucketACLResult.h" #import "KS3BucketACLXMLParser.h" #import "KS3BucketNameUtilities.h" #import "KS3BucketObject.h" #import "KS3Client.h" #import "KS3ClientException.h" #import "KS3CompleteMultipartUploadRequest.h" #import "KS3CompleteMultipartUploadResponse.h" #import "KS3CompleteMultipartUploadResult.h" #import "KS3Constants.h" #import "KS3CreateBucketRequest.h" #import "KS3CreateBucketResponse.h" #import "KS3Credentials.h" #import "KS3DeleteBucketRequest.h" #import "KS3DeleteBucketResponse.h" #import "KS3DeleteObjectRequest.h" #import "KS3DeleteObjectResponse.h" #import "KS3DownLoad.h" #import "KS3ErrorHandler.h" #import "KS3GetACLRequest.h" #import "KS3GetACLResponse.h" #import "KS3GetBucketLoggingRequest.h" #import "KS3GetBucketLoggingResponse.h" #import "KS3GetObjectACLRequest.h" #import "KS3GetObjectACLResponse.h" #import "KS3GetObjectRequest.h" #import "KS3GetObjectResponse.h" #import "KS3Grant.h" #import "KS3GrantAccessControlList.h" #import "KS3HeadBucketRequest.h" #import "KS3HeadBucketResponse.h" #import "KS3HeadObjectRequest.h" #import "KS3HeadObjectResponse.h" #import "KS3InitiateMultipartUploadRequest.h" #import "KS3InitiateMultipartUploadResponse.h" #import "KS3InitiateMultipartUploadResult.h" #import "KS3InitiateMultipartUploadXMLParser.h" #import "KS3ListBucketsRequest.h" #import "KS3ListBucketsResponse.h" #import "KS3ListBucketsResult.h" #import "KS3ListBucketsXMLParser.h" #import "KS3ListObjectsRequest.h" #import "KS3ListObjectsResponse.h" #import "KS3ListObjectsResult.h" #import "KS3ListObjectsXMLPrarser.h" #import "KS3ListPartsRequest.h" #import "KS3ListPartsResponse.h" #import "KS3ListPartsResult.h" #import "KS3ListPartsResultXMLParser.h" #import "KS3MD5Util.h" #import "KS3MultipartUpload.h" #import "KS3ObjectACLXMLParser.h" #import "KS3ObjectSummary.h" #import "KS3Owner.h" #import "KS3Part.h" #import "KS3PutObjectCopyRequest.h" #import "KS3PutObjectCopyResponse.h" #import "KS3PutObjectRequest.h" #import "KS3PutObjectResponse.h" #import "KS3Request.h" #import "KS3Response.h" #import "KS3ResponseHeaderOverrides.h" #import "KS3SDKUtil.h" #import "KS3ServiceRequest.h" #import "KS3ServiceResponse.h" #import "KS3SetACLRequest.h" #import "KS3SetACLResponse.h" #import "KS3SetBucketLoggingRequest.h" #import "KS3SetBucketLoggingResponse.h" #import "KS3SetGrantACLRequest.h" #import "KS3SetGrantACLResponse.h" #import "KS3SetObjectACLRequest.h" #import "KS3SetObjectACLResponse.h" #import "KS3SetObjectGrantACLRequest.h" #import "KS3SetObjectGrantACLResponse.h" #import "KS3URLRequest.h" #import "KS3UploadPartRequest.h" #import "KS3UploadPartResponse.h" #import "KS3WebServiceClient.h" #import "KS3UploadManager.h" #import "KS3Upload.h" #import "KS3UploadRequest.h" #endif
adatao/DDF
pa/src/main/java/com/adatao/pa/spark/execution/CExecutor.java
<reponame>adatao/DDF /* * Copyright (C) 2013 Adatao, 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.adatao.pa.spark.execution; import java.io.Serializable; import java.lang.reflect.Field; import com.adatao.pa.AdataoException; import com.adatao.pa.spark.SparkThread; import com.adatao.pa.spark.types.ExecutorResult; import com.adatao.pa.spark.types.IExecutor; import com.google.gson.Gson; /** * Base implementation for all Executors, with helper methods for extracting parameters, etc. * * @author ctn * * This class is going to be deprecated and replaced by AExecutor */ @SuppressWarnings("serial") @Deprecated public abstract class CExecutor implements IExecutor, Serializable { /* * (non-Javadoc) * * @see com.adatao.pa.spark.types.IExecutor#run(com.adatao.pa.spark.SparkThread) */ @Override public ExecutorResult run(SparkThread sparkThread) throws AdataoException { // TODO Auto-generated method stub return null; } /** * Default implementation: prints out class name and all public fields */ @Override public String toString() { StringBuilder output = new StringBuilder(this.getClass().getSimpleName()); output.append("["); Gson gson = new Gson(); Field[] fields = this.getClass().getFields(); for (Field field : fields) { output.append(field.getName()); output.append("="); try { output.append(gson.toJson(field.get(this))); } catch (Exception e) { output.append(e.getMessage()); } output.append(","); } output.append("]"); return output.toString(); } }
ljz663/tencentcloud-sdk-java
src/main/java/com/tencentcloudapi/tcss/v20201101/models/ComplianceScanFailedAsset.java
<filename>src/main/java/com/tencentcloudapi/tcss/v20201101/models/ComplianceScanFailedAsset.java /* * Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencentcloudapi.tcss.v20201101.models; import com.tencentcloudapi.common.AbstractModel; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; import java.util.HashMap; public class ComplianceScanFailedAsset extends AbstractModel{ /** * 客户资产的ID。 */ @SerializedName("CustomerAssetId") @Expose private Long CustomerAssetId; /** * 资产类别。 */ @SerializedName("AssetType") @Expose private String AssetType; /** * 检测状态 CHECK_INIT, 待检测 CHECK_RUNNING, 检测中 CHECK_FINISHED, 检测完成 CHECK_FAILED, 检测失败 */ @SerializedName("CheckStatus") @Expose private String CheckStatus; /** * 资产的名称。 */ @SerializedName("AssetName") @Expose private String AssetName; /** * 资产检测失败的原因。 */ @SerializedName("FailureReason") @Expose private String FailureReason; /** * 检测失败的处理建议。 */ @SerializedName("Suggestion") @Expose private String Suggestion; /** * 检测的时间。 */ @SerializedName("CheckTime") @Expose private String CheckTime; /** * Get 客户资产的ID。 * @return CustomerAssetId 客户资产的ID。 */ public Long getCustomerAssetId() { return this.CustomerAssetId; } /** * Set 客户资产的ID。 * @param CustomerAssetId 客户资产的ID。 */ public void setCustomerAssetId(Long CustomerAssetId) { this.CustomerAssetId = CustomerAssetId; } /** * Get 资产类别。 * @return AssetType 资产类别。 */ public String getAssetType() { return this.AssetType; } /** * Set 资产类别。 * @param AssetType 资产类别。 */ public void setAssetType(String AssetType) { this.AssetType = AssetType; } /** * Get 检测状态 CHECK_INIT, 待检测 CHECK_RUNNING, 检测中 CHECK_FINISHED, 检测完成 CHECK_FAILED, 检测失败 * @return CheckStatus 检测状态 CHECK_INIT, 待检测 CHECK_RUNNING, 检测中 CHECK_FINISHED, 检测完成 CHECK_FAILED, 检测失败 */ public String getCheckStatus() { return this.CheckStatus; } /** * Set 检测状态 CHECK_INIT, 待检测 CHECK_RUNNING, 检测中 CHECK_FINISHED, 检测完成 CHECK_FAILED, 检测失败 * @param CheckStatus 检测状态 CHECK_INIT, 待检测 CHECK_RUNNING, 检测中 CHECK_FINISHED, 检测完成 CHECK_FAILED, 检测失败 */ public void setCheckStatus(String CheckStatus) { this.CheckStatus = CheckStatus; } /** * Get 资产的名称。 * @return AssetName 资产的名称。 */ public String getAssetName() { return this.AssetName; } /** * Set 资产的名称。 * @param AssetName 资产的名称。 */ public void setAssetName(String AssetName) { this.AssetName = AssetName; } /** * Get 资产检测失败的原因。 * @return FailureReason 资产检测失败的原因。 */ public String getFailureReason() { return this.FailureReason; } /** * Set 资产检测失败的原因。 * @param FailureReason 资产检测失败的原因。 */ public void setFailureReason(String FailureReason) { this.FailureReason = FailureReason; } /** * Get 检测失败的处理建议。 * @return Suggestion 检测失败的处理建议。 */ public String getSuggestion() { return this.Suggestion; } /** * Set 检测失败的处理建议。 * @param Suggestion 检测失败的处理建议。 */ public void setSuggestion(String Suggestion) { this.Suggestion = Suggestion; } /** * Get 检测的时间。 * @return CheckTime 检测的时间。 */ public String getCheckTime() { return this.CheckTime; } /** * Set 检测的时间。 * @param CheckTime 检测的时间。 */ public void setCheckTime(String CheckTime) { this.CheckTime = CheckTime; } public ComplianceScanFailedAsset() { } /** * NOTE: Any ambiguous key set via .set("AnyKey", "value") will be a shallow copy, * and any explicit key, i.e Foo, set via .setFoo("value") will be a deep copy. */ public ComplianceScanFailedAsset(ComplianceScanFailedAsset source) { if (source.CustomerAssetId != null) { this.CustomerAssetId = new Long(source.CustomerAssetId); } if (source.AssetType != null) { this.AssetType = new String(source.AssetType); } if (source.CheckStatus != null) { this.CheckStatus = new String(source.CheckStatus); } if (source.AssetName != null) { this.AssetName = new String(source.AssetName); } if (source.FailureReason != null) { this.FailureReason = new String(source.FailureReason); } if (source.Suggestion != null) { this.Suggestion = new String(source.Suggestion); } if (source.CheckTime != null) { this.CheckTime = new String(source.CheckTime); } } /** * Internal implementation, normal users should not use it. */ public void toMap(HashMap<String, String> map, String prefix) { this.setParamSimple(map, prefix + "CustomerAssetId", this.CustomerAssetId); this.setParamSimple(map, prefix + "AssetType", this.AssetType); this.setParamSimple(map, prefix + "CheckStatus", this.CheckStatus); this.setParamSimple(map, prefix + "AssetName", this.AssetName); this.setParamSimple(map, prefix + "FailureReason", this.FailureReason); this.setParamSimple(map, prefix + "Suggestion", this.Suggestion); this.setParamSimple(map, prefix + "CheckTime", this.CheckTime); } }
manh-vv/BroadleafCommerce
admin/broadleaf-open-admin-platform/src/main/java/org/broadleafcommerce/openadmin/web/form/component/ListGrid.java
<reponame>manh-vv/BroadleafCommerce /* * #%L * BroadleafCommerce Open Admin Platform * %% * Copyright (C) 2009 - 2016 Broadleaf Commerce * %% * Licensed under the Broadleaf Fair Use License Agreement, Version 1.0 * (the "Fair Use License" located at http://license.broadleafcommerce.org/fair_use_license-1.0.txt) * unless the restrictions on use therein are violated and require payment to Broadleaf in which case * the Broadleaf End User License Agreement (EULA), Version 1.1 * (the "Commercial License" located at http://license.broadleafcommerce.org/commercial_license-1.1.txt) * shall apply. * * Alternatively, the Commercial License may be replaced with a mutually agreed upon license (the "Custom License") * between you and Broadleaf Commerce. You may not use this file except in compliance with the applicable license. * #L% */ package org.broadleafcommerce.openadmin.web.form.component; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.CompareToBuilder; import org.broadleafcommerce.common.presentation.client.AddMethodType; import org.broadleafcommerce.common.util.TypedPredicate; import org.broadleafcommerce.openadmin.dto.SectionCrumb; import org.broadleafcommerce.openadmin.server.service.type.FetchType; import org.broadleafcommerce.openadmin.web.form.entity.Field; import org.broadleafcommerce.openadmin.web.rulebuilder.dto.DataWrapper; import org.broadleafcommerce.openadmin.web.rulebuilder.dto.FieldWrapper; import java.util.*; public class ListGrid { // We may have cases, when className not set. // In that case we need to initialize field with empty string, // to prevent "null" as css class for ListGrid protected String className = ""; protected String friendlyName = null; protected String idProperty; protected int order; protected boolean isSortable; protected boolean hideFriendlyName; protected Set<Field> headerFields = new TreeSet<Field>(new Comparator<Field>() { @Override public int compare(Field o1, Field o2) { return new CompareToBuilder() .append(o1.getOrder(), o2.getOrder()) .append(o1.getFriendlyName(), o2.getFriendlyName()) .append(o1.getName(), o2.getName()) .toComparison(); } }); protected List<ListGridRecord> records = new ArrayList<ListGridRecord>(); protected List<ListGridAction> toolbarActions = new ArrayList<ListGridAction>(); // These actions will start greyed out and unable to be clicked until a specific row has been selected protected List<ListGridAction> rowActions = new ArrayList<ListGridAction>(); protected List<ListGridActionGroup> toolbarActionGroups = new ArrayList<ListGridActionGroup>(); protected List<ListGridActionGroup> rowActionGroups = new ArrayList<ListGridActionGroup>(); // These actions will start greyed out and unable to be clicked until a specific row has been selected protected List<ListGridAction> modalRowActions = new ArrayList<ListGridAction>(); private Set<String> cssClasses = new HashSet<>(); protected int totalRecords; protected int startIndex; protected int pageSize; protected Boolean canFilterAndSort; protected Boolean isReadOnly; protected Boolean hideIdColumn; protected String fetchType = FetchType.DEFAULT.toString(); protected long firstId; protected long lastId; protected int upperCount; protected int lowerCount; protected boolean totalCountLessThanPageSize; protected boolean promptSearch; protected AddMethodType addMethodType; protected String listGridType; protected String selectType; protected String selectizeUrl; protected Boolean manualFetch; protected String helpText; // The section url that maps to this particular list grid protected String sectionKey; // The list of all section keys that have been traversed to arrive at this ListGrid (including the current one), in order // of occurrence protected List<SectionCrumb> sectionCrumbs = new ArrayList<SectionCrumb>(); // If this list grid is a sublistgrid, meaning it is rendered as part of a different entity, these properties // help identify the parent entity. protected String externalEntitySectionKey; protected String containingEntityId; protected String subCollectionFieldName; protected String pathOverride; protected String searchFieldsTemplateOverride; protected String templateOverride; public enum Type { MAIN, TO_ONE, BASIC, ADORNED, ADORNED_WITH_FORM, MAP, TRANSLATION, ASSET, WORKFLOW, TREE, ASSET_GRID, ASSET_GRID_FOLDER } public enum SelectType { SINGLE_SELECT, MULTI_SELECT, SELECTIZE, NONE } /* Filter Builder required Fields */ protected String fieldBuilder; protected DataWrapper dataWrapper; protected String json; protected String jsonFieldName; protected FieldWrapper fieldWrapper; /* ************** */ /* CUSTOM METHODS */ /* ************** */ public String getPath() { if (StringUtils.isNotBlank(pathOverride)) { return pathOverride; } StringBuilder sb = new StringBuilder(); if (!getSectionKey().startsWith("/")) { sb.append("/"); } sb.append(getSectionKey()); if (getContainingEntityId() != null) { sb.append("/").append(getContainingEntityId()); } if (StringUtils.isNotBlank(getSubCollectionFieldName())) { sb.append("/").append(getSubCollectionFieldName()); } //to-one grids need a slightly different grid URL; these need to be appended with 'select' //TODO: surely there's a better way to do this besides just hardcoding the 'select'? if (Type.TO_ONE.toString().toLowerCase().equals(listGridType)) { sb.append("/select"); } return sb.toString(); } public String getSectionCrumbRepresentation() { StringBuilder sb = new StringBuilder(); if (!sectionCrumbs.isEmpty()) { sb.append("?sectionCrumbs="); } int index = 0; for (SectionCrumb section : sectionCrumbs) { sb.append(section.getSectionIdentifier()); sb.append("--"); sb.append(section.getSectionId()); if (index < sectionCrumbs.size()-1) { sb.append(","); } index++; } return sb.toString(); } /** * Grabs a filtered list of toolbar actions filtered by whether or not they match the same readonly state as the listgrid * and are thus shown on the screen */ @SuppressWarnings("unchecked") public List<ListGridAction> getActiveToolbarActions() { return (List<ListGridAction>) CollectionUtils.select(getToolbarActions(), new TypedPredicate<ListGridAction>() { @Override public boolean eval(ListGridAction action) { return action.getForListGridReadOnly().equals(getIsReadOnly()); } }); } /** * Grabs a filtered list of row actions filtered by whether or not they match the same readonly state as the listgrid * and are thus shown on the screen */ @SuppressWarnings("unchecked") public List<ListGridAction> getActiveRowActions() { return (List<ListGridAction>) CollectionUtils.select(getRowActions(), new TypedPredicate<ListGridAction>() { @Override public boolean eval(ListGridAction action) { return action.getForListGridReadOnly().equals(getIsReadOnly()); } }); } /** * Grabs a filtered list of toolbar action groupss filtered by whether or not they match the same readonly state as the listgrid * and are thus shown on the screen */ @SuppressWarnings("unchecked") public List<ListGridAction> getActiveToolbarActionGroups() { return (List<ListGridAction>) CollectionUtils.select(getToolbarActionGroups(), new TypedPredicate<ListGridActionGroup>() { @Override public boolean eval(ListGridActionGroup actionGroup) { boolean result = false; for (ListGridAction action : actionGroup.getListGridActions()) { if (action.getForListGridReadOnly().equals(getIsReadOnly())) { result = true; } } return result; } }); } /** * Grabs a filtered list of row action groupss filtered by whether or not they match the same readonly state as the listgrid * and are thus shown on the screen */ @SuppressWarnings("unchecked") public List<ListGridAction> getActiveRowActionGroups() { return (List<ListGridAction>) CollectionUtils.select(getRowActionGroups(), new TypedPredicate<ListGridActionGroup>() { @Override public boolean eval(ListGridActionGroup actionGroup) { boolean result = false; for (ListGridAction action : actionGroup.getListGridActions()) { if (action.getForListGridReadOnly().equals(getIsReadOnly())) { result = true; } } return result; } }); } /** * Grabs a filtered list of row actions filtered by whether or not they match the same readonly state as the listgrid * and are thus shown on the screen */ @SuppressWarnings("unchecked") public List<ListGridAction> getActiveModalRowActions() { return (List<ListGridAction>) CollectionUtils.select(getModalRowActions(), new TypedPredicate<ListGridAction>() { @Override public boolean eval(ListGridAction action) { return action.getForListGridReadOnly().equals(getIsReadOnly()); } }); } public void addRowAction(ListGridAction action) { getRowActions().add(action); } public void addModalRowAction(ListGridAction action) { getModalRowActions().add(action); } public void addToolbarAction(ListGridAction action) { getToolbarActions().add(action); } public void removeAllToolbarActions() { getToolbarActions().clear(); } public void removeAllRowActions() { getRowActions().clear(); } public void addToolbarActionGroup(ListGridActionGroup actionGroup) { getToolbarActionGroups().add(actionGroup); } public void removeAllToolbarActionGroups() { getToolbarActionGroups().clear(); } public void addRowActionGroup(ListGridActionGroup actionGroup) { getRowActionGroups().add(actionGroup); } public void removeAllRowActionGroups() { getRowActionGroups().clear(); } public void removeAllModalRowActions() { getModalRowActions().clear(); } public ListGridAction findToolbarAction(String actionId) { for (ListGridAction action : getToolbarActions()) { if (action.getActionId().equals(actionId)) { return action; } } for (ListGridActionGroup actionGroup : getToolbarActionGroups()) { for (ListGridAction action : actionGroup.getListGridActions()) { if (action.getActionId().equals(actionId)) { return action; } } } return null; } public ListGridAction findRowAction(String actionId) { for (ListGridAction action : getRowActions()) { if (action.getActionId().equals(actionId)) { return action; } } for (ListGridActionGroup actionGroup : getRowActionGroups()) { for (ListGridAction action : actionGroup.getListGridActions()) { if (action.getActionId().equals(actionId)) { return action; } } } return null; } public ListGridAction findModalRowAction(String actionId) { for (ListGridAction action : getModalRowActions()) { if (action.getActionId().equals(actionId)) { return action; } } return null; } /** * This grid is sortable if there is a reorder action defined in the toolbar. If records can be reordered, then the * sort functionality doesn't make any sense. * * Also, map structures are currently unsortable. * * @return */ public boolean isSortable() { return this.isSortable || Type.MAP.toString().toLowerCase().equals(getListGridType()); } /* ************************ */ /* CUSTOM GETTERS / SETTERS */ /* ************************ */ public void setListGridType(Type listGridType) { this.listGridType = listGridType.toString().toLowerCase(); } /** * Allows for completely custom types other than the ones defined {@link Type} to assign unique handlers to on the JS * side * @param listGridType */ public void setListGridTypeString(String listGridType) { this.listGridType = listGridType; } public void setSelectType(SelectType selectType) { this.selectType = selectType.toString().toLowerCase(); } public void setSelectTypeString(String selectType) { this.selectType = selectType; } public Boolean getCanFilterAndSort() { return (canFilterAndSort == null ? true : canFilterAndSort); } public Boolean getIsReadOnly() { return isReadOnly == null ? false : isReadOnly; } public Boolean getClickable() { return !"none".equals(selectType); } public Boolean getHideIdColumn() { return hideIdColumn == null ? true : hideIdColumn; } /* ************************** */ /* STANDARD GETTERS / SETTERS */ /* ************************** */ public String getIdProperty() { return idProperty; } public void setIdProperty(String idProperty) { this.idProperty = idProperty; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public int getOrder() { return order; } public void setOrder(int order) { this.order = order; } public boolean getIsSortable() { return isSortable; } public void setIsSortable(boolean isSortable) { this.isSortable = isSortable; } public boolean getHideFriendlyName() { return hideFriendlyName; } public void setHideFriendlyName(boolean hideFriendlyName) { this.hideFriendlyName = hideFriendlyName; } public Set<Field> getHeaderFields() { return headerFields; } public void setHeaderFields(Set<Field> headerFields) { this.headerFields = headerFields; } public Field findHeaderField(String name) { if (name == null) { return null; } for (Field headerField : getHeaderFields()) { if (name.equals(headerField.getName())) { return headerField; } } return null; } public boolean isEmpty() { return records.isEmpty(); } public List<ListGridRecord> getRecords() { return records; } public void setRecords(List<ListGridRecord> records) { this.records = records; } public List<ListGridAction> getToolbarActions() { return toolbarActions; } public void setToolbarActions(List<ListGridAction> toolbarActions) { this.toolbarActions = toolbarActions; } public List<ListGridAction> getRowActions() { return rowActions; } public void setRowActions(List<ListGridAction> rowActions) { this.rowActions = rowActions; } public List<ListGridActionGroup> getToolbarActionGroups() { return toolbarActionGroups; } public void setToolbarActionGroups(List<ListGridActionGroup> toolbarActionGroups) { this.toolbarActionGroups = toolbarActionGroups; } public List<ListGridActionGroup> getRowActionGroups() { return rowActionGroups; } public void setRowActionGroups(List<ListGridActionGroup> rowActionGroups) { this.rowActionGroups = rowActionGroups; } public List<ListGridAction> getModalRowActions() { return modalRowActions; } public void setModalRowActions(List<ListGridAction> modalRowActions) { this.modalRowActions = modalRowActions; } public int getStartIndex() { return startIndex; } public void setStartIndex(int startIndex) { this.startIndex = startIndex; } public int getTotalRecords() { return totalRecords; } public void setTotalRecords(int totalRecords) { this.totalRecords = totalRecords; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public void setCanFilterAndSort(Boolean canFilterAndSort) { this.canFilterAndSort = canFilterAndSort; } public AddMethodType getAddMethodType() { return addMethodType; } public void setAddMethodType(AddMethodType addMethodType) { this.addMethodType = addMethodType; } public String getListGridType() { return listGridType; } public String getSelectType() { return selectType; } public String getContainingEntityId() { return containingEntityId; } public void setContainingEntityId(String containingEntityId) { this.containingEntityId = containingEntityId; } public String getSubCollectionFieldName() { return subCollectionFieldName; } public void setSubCollectionFieldName(String subCollectionFieldName) { this.subCollectionFieldName = subCollectionFieldName; } public String getFriendlyName() { return friendlyName; } public void setFriendlyName(String friendlyName) { this.friendlyName = friendlyName; } public String getSectionKey() { return sectionKey; } public void setSectionKey(String sectionKey) { this.sectionKey = sectionKey; } public String getSelectizeUrl() { return selectizeUrl; } public void setSelectizeUrl(String selectizeUrl) { this.selectizeUrl = selectizeUrl; } public Boolean getManualFetch() { if (manualFetch == null) { return false; } return manualFetch; } public void setManualFetch(Boolean manualFetch) { this.manualFetch = manualFetch; } public String getExternalEntitySectionKey() { return externalEntitySectionKey; } public void setExternalEntitySectionKey(String externalEntitySectionKey) { this.externalEntitySectionKey = externalEntitySectionKey; } public String getPathOverride() { return pathOverride; } public void setPathOverride(String pathOverride) { this.pathOverride = pathOverride; } public String getSearchFieldsTemplateOverride() { return searchFieldsTemplateOverride; } public void setSearchFieldsTemplateOverride(String searchFieldsTemplateOverride) { this.searchFieldsTemplateOverride = searchFieldsTemplateOverride; } public String getTemplateOverride() { return templateOverride; } public void setTemplateOverride(String templateOverride) { this.templateOverride = templateOverride; } public void setIsReadOnly(Boolean readOnly) { this.isReadOnly = readOnly; } public void setHideIdColumn(Boolean hideIdColumn) { this.hideIdColumn = hideIdColumn; } public List<SectionCrumb> getSectionCrumbs() { return sectionCrumbs; } public void setSectionCrumbs(List<SectionCrumb> sectionCrumbs) { if (sectionCrumbs == null) { this.sectionCrumbs.clear(); return; } this.sectionCrumbs = sectionCrumbs; } public String getFieldBuilder() { return fieldBuilder; } public void setFieldBuilder(String fieldBuilder) { this.fieldBuilder = fieldBuilder; } public FieldWrapper getFieldWrapper() { return fieldWrapper; } public void setFieldWrapper(FieldWrapper fieldWrapper) { this.fieldWrapper = fieldWrapper; } public DataWrapper getDataWrapper() { return dataWrapper; } public void setDataWrapper(DataWrapper dataWrapper) { this.dataWrapper = dataWrapper; } public String getJson() { return json; } public void setJson(String json) { this.json = json; } public String getJsonFieldName() { return jsonFieldName; } public void setJsonFieldName(String jsonFieldName) { this.jsonFieldName = jsonFieldName; } public String getFetchType() { return fetchType; } public void setFetchType(String fetchType) { this.fetchType = fetchType; } public long getFirstId() { return firstId; } public void setFirstId(long firstId) { this.firstId = firstId; } public long getLastId() { return lastId; } public void setLastId(long lastId) { this.lastId = lastId; } public int getUpperCount() { return upperCount; } public void setUpperCount(int upperCount) { this.upperCount = upperCount; } public int getLowerCount() { return lowerCount; } public void setLowerCount(int lowerCount) { this.lowerCount = lowerCount; } public boolean isTotalCountLessThanPageSize() { return totalCountLessThanPageSize; } public void setTotalCountLessThanPageSize(boolean totalCountLessThanPageSize) { this.totalCountLessThanPageSize = totalCountLessThanPageSize; } public boolean isPromptSearch() { return promptSearch; } public void setPromptSearch(boolean promptSearch) { this.promptSearch = promptSearch; } public String getHelpText() { return helpText; } public void setHelpText(String helpText) { this.helpText = helpText; } /* ***************************** */ /* CSS CLASSES GETTERS / SETTERS */ /* ***************************** */ public void addCssClass(String className) { this.cssClasses.add(className); } public void removeCssClass(String className) { this.cssClasses.remove(className); } public void clearCssClasses() { this.cssClasses.clear(); } public String getCssClassNames() { return StringUtils.join(this.cssClasses, " "); } }
gmmsmall/ruoyi-cloud3
ruoyi-service/ruoyi-fabric/src/main/java/com/ruoyi/fabric/controller/BlockTokenController.java
package com.ruoyi.fabric.controller; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.ruoyi.fabric.service.IBlockOperator; import com.ruoyi.system.domain.Token; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.HashMap; import java.util.Map; @CrossOrigin(origins = {"*"}) @RestController @RequestMapping("/token") public class BlockTokenController { @Autowired IBlockOperator fabricBlockOperatorService; @ApiOperation(value = "新增令牌存证" , notes = "该接口主要向链上存储令牌信息" , httpMethod = "POST") @RequestMapping(value = "/addToken" , method = RequestMethod.POST) public String add(@RequestBody Token fabricToken) { System.out.println("开始新增角色信息存证" + fabricToken); String[] args = new String[1]; String fileForwardListJson = JSON.toJSONString(fabricToken); args[0] = fileForwardListJson; String data = fabricBlockOperatorService.invoke("addToken" , args); Map<Object, Object> result = new HashMap<>(); //给map中添加元素 if (data.equals("error")) { result.put("code" , 1); } else { result.put("code" , 0); } return JSON.toJSONString(result); } @ApiOperation(value = "更新令牌存证" , notes = "该接口更新令牌信息" , httpMethod = "POST") @RequestMapping(value = "/updateToken" , method = RequestMethod.POST) public String update(@RequestBody Token fabricToken) { System.out.print("更新角色信息存证" + fabricToken.getName()); String[] args = new String[1]; String fileForwardListJson = JSON.toJSONString(fabricToken); args[0] = fileForwardListJson; String data = fabricBlockOperatorService.invoke("updateToken" , args); Map<Object, Object> result = new HashMap<>(); //给map中添加元素 if (data.equals("error")) { result.put("code" , 1); } else { result.put("code" , 0); } return JSON.toJSONString(result); } @ApiOperation(value = "遍历令牌信息存证" , notes = "该接口主要遍历链上令牌信息" , httpMethod = "GET") @RequestMapping(value = "/queryTokens") public String query(@RequestBody Map map) { String[] args = new String[1]; String param = JSON.toJSONString(map); args[0] = param; Long starttime = System.currentTimeMillis(); String data = fabricBlockOperatorService.query("queryTokens" , args); Long endtime = System.currentTimeMillis(); System.out.println("gateway-query-time:" + (endtime - starttime) + "毫秒"); Map<Object, Object> result = new HashMap<>(); if (data.equals("error")) { result.put("code" , 1); } else { JSONObject jsondata = JSONObject.parseObject(data); result.put("pageSize" , jsondata.get("pageSize")); result.put("pageNum" , jsondata.get("pageNum")); result.put("total" , jsondata.get("total")); result.put("size" , jsondata.get("size")); result.put("code" , 0); result.put("tokenList" , jsondata.get("tokenList")); } return JSON.toJSONString(result); } @ApiOperation(value = "删除令牌信息存证" , notes = "该接口删除指定id令牌信息" , httpMethod = "POST") @RequestMapping(value = "/deleteToken" , method = RequestMethod.POST) public String delete(@RequestBody Map map) { System.out.print("开始新增角色信息存证" + map); String[] args = new String[1]; String param = JSON.toJSONString(map); args[0] = param; String data = fabricBlockOperatorService.invoke("deleteToken" , args); Map<Object, Object> result = new HashMap<>(); //给map中添加元素 if (data.equals("error")) { result.put("code" , 1); } else { result.put("code" , 0); } return JSON.toJSONString(result); } // TODO: 1. 调用service层,提供其他的接口。 // TODO: 2. 完成controller层单元测试,参考 BlockExplorerControllerTest。 }
moon-util/moon-util
src/main/java/com/moon/poi/excel/annotation/format/LocaleStrategy.java
<filename>src/main/java/com/moon/poi/excel/annotation/format/LocaleStrategy.java package com.moon.poi.excel.annotation.format; import java.util.Locale; import static java.util.Locale.Category.FORMAT; /** * @author moonsky * @see java.util.Locale */ public enum LocaleStrategy { /** * 默认 */ DEFAULT(Locale.getDefault(FORMAT)), ENGLISH(Locale.ENGLISH), FRENCH(Locale.FRENCH), GERMAN(Locale.GERMAN), ITALIAN(Locale.ITALIAN), JAPANESE(Locale.JAPANESE), KOREAN(Locale.KOREAN), CHINESE(Locale.CHINESE), SIMPLIFIED_CHINESE(Locale.SIMPLIFIED_CHINESE), TRADITIONAL_CHINESE(Locale.TRADITIONAL_CHINESE), FRANCE(Locale.FRANCE), GERMANY(Locale.GERMANY), ITALY(Locale.ITALY), JAPAN(Locale.JAPAN), KOREA(Locale.KOREA), CHINA(Locale.CHINA), PRC(Locale.PRC), TAIWAN(Locale.TAIWAN), UK(Locale.UK), US(Locale.US), CANADA(Locale.CANADA), CANADA_FRENCH(Locale.CANADA_FRENCH), ; private final Locale locale; LocaleStrategy(Locale locale) { this.locale = locale; } public Locale getLocale() { return locale; } }
Luc-netease/NEChatroom
NEChatroom-iOS-ObjC/NEChatroom-iOS-ObjC/Classes/Sections/Chatroom/View/NTESConnectListView/NTESConnectListView.h
// // NTESConnectListView.h // NERtcAudioChatroom // // Created by <NAME> on 2019/1/28. // Copyright © 2019年 netease. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @class NTESMicInfo; @protocol NTESConnectListViewDelegate <NSObject> - (void)onAcceptBtnPressedWithMicInfo:(NTESMicInfo *)micInfo; - (void)onRejectBtnPressedWithMicInfo:(NTESMicInfo *)micInfo; @end @interface NTESConnectListView : UIControl @property (nonatomic, weak)id<NTESConnectListViewDelegate> delegate; - (void)refreshWithDataArray:(NSMutableArray *)dataArray; - (void)showAsAlertOnView:(UIView *)view; @end NS_ASSUME_NONNULL_END
stIncMale/sandbox-java
benchmarks/src/test/java/stincmale/sandbox/benchmarks/ListPerformanceBench.java
package stincmale.sandbox.benchmarks; import java.util.AbstractMap.SimpleImmutableEntry; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; import static java.util.Arrays.stream; import static java.util.stream.IntStream.range; import org.junit.jupiter.api.Test; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.RunnerException; import static org.openjdk.jmh.runner.options.TimeValue.milliseconds; import static stincmale.sandbox.benchmarks.util.JmhOptions.includeBenchmarks; import static stincmale.sandbox.benchmarks.util.JmhOptions.newOptionsBuilder; public class ListPerformanceBench { public ListPerformanceBench() { } @Test public void run() throws RunnerException { new Runner(newOptionsBuilder(opts -> opts.forks(10) .warmupTime(milliseconds(100)) .warmupIterations(12) .measurementTime(milliseconds(100)) .measurementIterations(3)) .include(includeBenchmarks(getClass())) .shouldDoGC(true) .mode(Mode.Throughput) .timeUnit(TimeUnit.MILLISECONDS) .build()) .run(); } @Benchmark public List<Object> createAndFillViaAdd(final ThreadStateForAdding state) { final int size = state.size; final List<Object> list = state.listDescriptor.create(size); for (int i = 0; i < size; i++) { list.add(new Object()); } return list; } @Benchmark public boolean iterate(final ThreadStateForIterating state) { boolean result = false; final List<Object> list = state.listDescriptor.get(state.size); for (final Object o : list) { //noinspection IfStatementMissingBreakInLoop if (o == list) { result = true; } } return result; } @State(Scope.Thread) public static class ThreadStateForAdding { @Param({"5", "50", "500", "5000", "50000"}) private int size; @Param({"ARRAY_LIST", "ARRAY_LIST_ENSURE_CAPACITY", "LINKED_LIST"}) private ListDescriptor listDescriptor; public ThreadStateForAdding() { } public enum ListDescriptor { ARRAY_LIST(size -> new ArrayList<>()), ARRAY_LIST_ENSURE_CAPACITY(size -> { final ArrayList<Object> result = new ArrayList<>(); result.ensureCapacity(size); return result; }), LINKED_LIST(size -> new LinkedList<>()); private final Function<Integer, List<Object>> supplierOfNew; ListDescriptor(final Function<Integer, List<Object>> supplierOfNew) { this.supplierOfNew = supplierOfNew; } private List<Object> create(final int size) { return supplierOfNew.apply(size); } } } @State(Scope.Thread) public static class ThreadStateForIterating { private static final Map<Integer, ArrayList<Object>> ARRAY_LISTS; private static final Map<Integer, LinkedList<Object>> LINKED_LISTS; static { final int[] sizes; try { sizes = stream(ThreadStateForAdding.class.getDeclaredField("size") .getAnnotation(Param.class) .value()) .mapToInt(Integer::parseInt) .toArray(); } catch (final NoSuchFieldException e) { throw new RuntimeException(e); } ARRAY_LISTS = stream(sizes) .mapToObj(size -> new SimpleImmutableEntry<>( size, createList(size, ArrayList::new))) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); LINKED_LISTS = stream(sizes) .mapToObj(size -> new SimpleImmutableEntry<>( size, createList(size, LinkedList::new))) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } @Param({"5", "50", "500", "5000", "50000"}) private int size; @Param({"ARRAY_LIST", "LINKED_LIST"}) private ListDescriptor listDescriptor; public ThreadStateForIterating() { } private static final <L extends List<Object>> L createList( final int size, final Supplier<L> listFactory) { return range(0, size) .mapToObj(i -> new Object()) .collect(Collectors.toCollection(listFactory)); } public enum ListDescriptor { ARRAY_LIST(ARRAY_LISTS::get), LINKED_LIST(LINKED_LISTS::get); private final Function<Integer, List<Object>> supplierOfPreconstructed; ListDescriptor(final Function<Integer, List<Object>> supplierOfPreconstructed) { this.supplierOfPreconstructed = supplierOfPreconstructed; } private final List<Object> get(final int size) { return supplierOfPreconstructed.apply(size); } } } }
matto1990/Kirin
javascript/test/core/testJSONUtils.js
/* Copyright 2011 Future Platforms 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. */ defineModule("testJSONUtils", function (require, exports) { var json = require("JSONUtils"), assert = require("assert"); var testObject = { deeply: {nested: {list: ['list', 'of', 'strings'], object: {empty: false}}}}; var cloneOfTestObject = _.clone(testObject); exports.testFindList = function () { assert.deepEqual(cloneOfTestObject, testObject); var list = json.findList(testObject, ['deeply', 'nested', 'list']); assert.deepEqual(['list', 'of', 'strings'], list); var notList = json.findList(testObject, ['deeply', 'nested', 'object']); // wrong type. assert.deepEqual([], notList); assert.deepEqual(cloneOfTestObject, testObject); }; exports.testFindObject = function () { assert.deepEqual(cloneOfTestObject, testObject); var obj = json.findObject(testObject, ['deeply', 'nested', 'object']); assert.deepEqual(testObject.deeply.nested.object, obj); assert.deepEqual({empty: false}, obj); var notObject = json.findObject(testObject, ['deeply', 'nested', 'list']); // wrong type. assert.deepEqual({}, notObject); assert.deepEqual(cloneOfTestObject, testObject); }; exports.testDeepClone = function () { var INCLUSION_FILTER = function (item) { return item; } var obj = {a:1, b:2, c:null}; var clone = json.deepClone(obj, INCLUSION_FILTER); console.log(clone); assert.ok(clone); assert.ok(clone.a); assert.ok(clone.b); assert.ok(!clone.c); assert.ok(clone.a && clone.b && !clone.c); var array = [1, 2, null, 3]; var clone = json.deepClone(array, INCLUSION_FILTER); assert.deepEqual([1,2,3], clone); obj = {a:1, b: true, c:{q:null, w: 1}, d: "a", e: null}; clone = json.deepClone(obj, INCLUSION_FILTER); assert.deepEqual({a:1, b:true, c: {w:1}, d: "a"}, clone); }; });
Andrea-MariaDB-2/js-graphql-intellij-plugin
src/main/com/intellij/lang/jsgraphql/ide/notifications/GraphQLNotificationUtil.java
<filename>src/main/com/intellij/lang/jsgraphql/ide/notifications/GraphQLNotificationUtil.java package com.intellij.lang.jsgraphql.ide.notifications; import com.intellij.lang.jsgraphql.GraphQLBundle; import com.intellij.lang.jsgraphql.GraphQLConstants; import com.intellij.lang.jsgraphql.GraphQLSettings; import com.intellij.lang.jsgraphql.ide.editor.GraphQLIntrospectionService; import com.intellij.notification.Notification; import com.intellij.notification.NotificationAction; import com.intellij.notification.NotificationType; import com.intellij.notification.Notifications; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.ObjectUtils; import com.intellij.lang.jsgraphql.types.GraphQLException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.net.ssl.SSLException; public class GraphQLNotificationUtil { private static final Logger LOG = Logger.getInstance(GraphQLNotificationUtil.class); public static final String NOTIFICATION_GROUP_ID = GraphQLConstants.GraphQL; public static void showInvalidConfigurationNotification(@NotNull String message, @Nullable VirtualFile introspectionSourceFile, @NotNull Project project) { Notification notification = new Notification( NOTIFICATION_GROUP_ID, GraphQLBundle.message("graphql.notification.invalid.config.file"), message, NotificationType.WARNING ); if (introspectionSourceFile != null) { notification.addAction(new NotificationAction(introspectionSourceFile.getName()) { @Override public void actionPerformed(@NotNull AnActionEvent e, @NotNull Notification notification) { FileEditorManager.getInstance(project).openFile(introspectionSourceFile, true); } }); } Notifications.Bus.notify(notification); } public static void showGraphQLRequestErrorNotification(@NotNull Project project, @NotNull String url, @NotNull Exception error, @NotNull NotificationType notificationType, @Nullable NotificationAction action) { LOG.info(error); boolean isSSLError = error instanceof SSLException; final String message = isSSLError ? GraphQLBundle.message("graphql.notification.ssl.cert.error.title") : GraphQLBundle.message("graphql.notification.error.title"); Notification notification = new Notification( NOTIFICATION_GROUP_ID, message, url + ": " + GraphQLNotificationUtil.formatExceptionMessage(error), notificationType ); if (isSSLError) { NotificationAction trustAction = GraphQLIntrospectionService.getInstance(project).createTrustAllHostsAction(); if (trustAction != null) { notification.addAction(trustAction); } } if (action != null) { notification.addAction(action); } Notifications.Bus.notify(notification, project); } public static void addRetryFailedSchemaIntrospectionAction(@NotNull Notification notification, @NotNull GraphQLSettings settings, @NotNull Exception e, @NotNull Runnable retry) { if (!(e instanceof GraphQLException)) return; notification.setContent(GraphQLBundle.message("graphql.notification.introspection.spec.error.body", GraphQLNotificationUtil.formatExceptionMessage(e))); addRetryWithoutDefaultValuesAction(notification, settings, retry); } private static void addRetryWithoutDefaultValuesAction(@NotNull Notification notification, @NotNull GraphQLSettings settings, @NotNull Runnable retry) { if (settings.isEnableIntrospectionDefaultValues()) { // suggest retrying without the default values as they're a common cause of spec compliance issues NotificationAction retryWithoutDefaultValues = new NotificationAction(GraphQLBundle.message("graphql.notification.retry.without.defaults")) { @Override public void actionPerformed(@NotNull AnActionEvent e, @NotNull Notification notification) { settings.setEnableIntrospectionDefaultValues(false); ApplicationManager.getApplication().saveSettings(); notification.expire(); retry.run(); } }; notification.addAction(retryWithoutDefaultValues); } } public static String formatExceptionMessage(@NotNull Exception exception) { return StringUtil.decapitalize(ObjectUtils.coalesce(exception.getMessage(), "")); } }
KxShare/Framework-Codeidea
Excerpt-Tools/UIKit-WKCategories/NSDate+WHDate.h
// // NSDate+WHDate.h // WHKit // https://github.com/remember17/WHKit // Created by 吴浩 on 2017/6/7. // Copyright (c) 2017年 remember17. All rights reserved. // http://www.jianshu.com/p/c935314b078e #import <Foundation/Foundation.h> @interface NSDate (WHDate) /** * 根据日期返回字符串 */ + (NSString *)stringWithDate:(NSDate *)date format:(NSString *)format; - (NSString *)stringWithFormat:(NSString *)format; + (NSDate *)dateWithString:(NSString *)string format:(NSString *)format; /** * 根据TimeInterval获取时间字符串,带有时区偏移 */ +(NSString *)stringWithTimeInterval:(unsigned int)time Formatter:(NSString *)format; /** * 根据字符串和格式获取TimeInterval时间,带有时区偏移 */ +(NSTimeInterval )timeIntervalFromString:(NSString *)timeStr Formatter:(NSString *)format; /** * 当前TimeInterval时间,带有时区偏移 */ +(NSTimeInterval )now; /** * yyyy-MM-dd HH:mm:ss格式的当前时间 */ +(NSString *)stringNowWithFullFormatter; /** * 自定义格式的当前时间 */ +(NSString *)stringNowWithFormatter:(NSString *)format; /** * 获取日、月、年、小时、分钟、秒 */ - (NSUInteger)day; - (NSUInteger)month; - (NSUInteger)year; - (NSUInteger)hour; - (NSUInteger)minute; - (NSUInteger)second; + (NSUInteger)day:(NSDate *)date; + (NSUInteger)month:(NSDate *)date; + (NSUInteger)year:(NSDate *)date; + (NSUInteger)hour:(NSDate *)date; + (NSUInteger)minute:(NSDate *)date; + (NSUInteger)second:(NSDate *)date; /** * 获取一年中的总天数 */ - (NSUInteger)daysInYear; + (NSUInteger)daysInYear:(NSDate *)date; /** * 判断是否是润年 * @return YES表示润年,NO表示平年 */ - (BOOL)isLeapYear; + (BOOL)isLeapYear:(NSDate *)date; /** * 获取该日期是该年的第几周 */ - (NSUInteger)weekOfYear; + (NSUInteger)weekOfYear:(NSDate *)date; /** * 获取格式化为YYYY-MM-dd格式的日期字符串 */ - (NSString *)formatYMD; + (NSString *)formatYMD:(NSDate *)date; /** * 返回当前月一共有几周(可能为4,5,6) */ - (NSUInteger)weeksOfMonth; + (NSUInteger)weeksOfMonth:(NSDate *)date; /** * 获取该月的第一天的日期 */ - (NSDate *)begindayOfMonth; + (NSDate *)begindayOfMonth:(NSDate *)date; /** * 获取该月的最后一天的日期 */ - (NSDate *)lastdayOfMonth; + (NSDate *)lastdayOfMonth:(NSDate *)date; /** * 返回day天后的日期(若day为负数,则为|day|天前的日期) */ - (NSDate *)dateAfterDay:(NSUInteger)day; + (NSDate *)dateAfterDate:(NSDate *)date day:(NSInteger)day; /** * 返回day月后的日期(若month为负数,则为|month|月前的日期) */ - (NSDate *)dateAfterMonth:(NSUInteger)month; + (NSDate *)dateAfterDate:(NSDate *)date month:(NSInteger)month; /** * 返回numYears年后的日期 */ - (NSDate *)offsetYears:(int)numYears; + (NSDate *)offsetYears:(int)numYears fromDate:(NSDate *)fromDate; /** * 返回numMonths月后的日期 */ - (NSDate *)offsetMonths:(int)numMonths; + (NSDate *)offsetMonths:(int)numMonths fromDate:(NSDate *)fromDate; /** * 返回numDays天后的日期 */ - (NSDate *)offsetDays:(int)numDays; + (NSDate *)offsetDays:(int)numDays fromDate:(NSDate *)fromDate; /** * 返回numHours小时后的日期 */ - (NSDate *)offsetHours:(int)hours; + (NSDate *)offsetHours:(int)numHours fromDate:(NSDate *)fromDate; /** * 距离该日期前几天 */ - (NSUInteger)daysAgo; + (NSUInteger)daysAgo:(NSDate *)date; /** * 获取星期几 */ - (NSInteger)weekday; + (NSInteger)weekday:(NSDate *)date; /** * 获取星期几(名称) */ - (NSString *)dayFromWeekday; + (NSString *)dayFromWeekday:(NSDate *)date; /** * 日期是否相等 */ - (BOOL)isSameDay:(NSDate *)anotherDate; /** * 是否是今天 */ - (BOOL)isToday; /** * 增加 */ - (NSDate *)dateByAddingDays:(NSUInteger)days; /** * 获得NSString的月份 */ + (NSString *)monthWithMonthNumber:(NSInteger)month; /** * 获取指定月份的天数 */ - (NSUInteger)daysInMonth:(NSUInteger)month; + (NSUInteger)daysInMonth:(NSDate *)date month:(NSUInteger)month; /** * 获取当前月份的天数 */ - (NSUInteger)daysInMonth; + (NSUInteger)daysInMonth:(NSDate *)date; /** * 返回x分钟前/x小时前/昨天/x天前/x个月前/x年前 */ - (NSString *)timeInfo; + (NSString *)timeInfoWithDate:(NSDate *)date; + (NSString *)timeInfoWithDateString:(NSString *)dateString; /** * 分别获取yyyy-MM-dd/HH:mm:ss/yyyy-MM-dd HH:mm:ss格式的字符串 */ - (NSString *)ymdFormat; - (NSString *)hmsFormat; - (NSString *)ymdHmsFormat; + (NSString *)ymdFormat; + (NSString *)hmsFormat; + (NSString *)ymdHmsFormat; @end
hemantbits/ComputeLibrary
documentation/classarm__compute_1_1graph_1_1_eltwise_layer_node.js
var classarm__compute_1_1graph_1_1_eltwise_layer_node = [ [ "EltwiseLayerNode", "classarm__compute_1_1graph_1_1_eltwise_layer_node.xhtml#a585b716ff7a4298f47df38792355485a", null ], [ "accept", "classarm__compute_1_1graph_1_1_eltwise_layer_node.xhtml#adb48b5745c55605a2d4ec6f665bb7f3f", null ], [ "configure_output", "classarm__compute_1_1graph_1_1_eltwise_layer_node.xhtml#a3f18a7449b9d7fc9e5fec212b8e61710", null ], [ "convert_policy", "classarm__compute_1_1graph_1_1_eltwise_layer_node.xhtml#ab932642e6eeca5832e27f6cfec5f173c", null ], [ "eltwise_operation", "classarm__compute_1_1graph_1_1_eltwise_layer_node.xhtml#ae06968fc02594164c392b61912c59496", null ], [ "forward_descriptors", "classarm__compute_1_1graph_1_1_eltwise_layer_node.xhtml#a6272eb9643b239dd0c1e7adde3ee093b", null ], [ "rounding_policy", "classarm__compute_1_1graph_1_1_eltwise_layer_node.xhtml#ac3e40923663c50e346b1321a20af5a51", null ], [ "type", "classarm__compute_1_1graph_1_1_eltwise_layer_node.xhtml#a65d13dc93e2df5e8ab725263cf9f4ac5", null ] ];
KablamoOSS/kombustion
pkg/parsers/resources/AutoScaling-ScheduledAction.go
<filename>pkg/parsers/resources/AutoScaling-ScheduledAction.go package resources // Code generated by go generate; DO NOT EDIT. // It's generated by "github.com/KablamoOSS/kombustion/generate" import ( "github.com/KablamoOSS/kombustion/types" yaml "github.com/KablamoOSS/yaml" ) // AutoScalingScheduledAction Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-as-scheduledaction.html type AutoScalingScheduledAction struct { Type string `yaml:"Type"` Properties AutoScalingScheduledActionProperties `yaml:"Properties"` Condition interface{} `yaml:"Condition,omitempty"` Metadata interface{} `yaml:"Metadata,omitempty"` DependsOn interface{} `yaml:"DependsOn,omitempty"` } // AutoScalingScheduledAction Properties type AutoScalingScheduledActionProperties struct { AutoScalingGroupName interface{} `yaml:"AutoScalingGroupName"` DesiredCapacity interface{} `yaml:"DesiredCapacity,omitempty"` EndTime interface{} `yaml:"EndTime,omitempty"` MaxSize interface{} `yaml:"MaxSize,omitempty"` MinSize interface{} `yaml:"MinSize,omitempty"` Recurrence interface{} `yaml:"Recurrence,omitempty"` StartTime interface{} `yaml:"StartTime,omitempty"` } // NewAutoScalingScheduledAction constructor creates a new AutoScalingScheduledAction func NewAutoScalingScheduledAction(properties AutoScalingScheduledActionProperties, deps ...interface{}) AutoScalingScheduledAction { return AutoScalingScheduledAction{ Type: "AWS::AutoScaling::ScheduledAction", Properties: properties, DependsOn: deps, } } // ParseAutoScalingScheduledAction parses AutoScalingScheduledAction func ParseAutoScalingScheduledAction( name string, data string, ) ( source string, conditions types.TemplateObject, metadata types.TemplateObject, mappings types.TemplateObject, outputs types.TemplateObject, parameters types.TemplateObject, resources types.TemplateObject, transform types.TemplateObject, errors []error, ) { source = "kombustion-core-resources" // Resources var resource AutoScalingScheduledAction err := yaml.Unmarshal([]byte(data), &resource) if err != nil { errors = append(errors, err) return } if validateErrs := resource.Properties.Validate(); len(errors) > 0 { errors = append(errors, validateErrs...) return } resources = types.TemplateObject{name: resource} // Outputs outputs = types.TemplateObject{ name: types.TemplateObject{ "Description": name + " Object", "Value": map[string]interface{}{ "Ref": name, }, "Export": map[string]interface{}{ "Name": map[string]interface{}{ "Fn::Sub": "${AWS::StackName}-AutoScalingScheduledAction-" + name, }, }, }, } return } // ParseAutoScalingScheduledAction validator func (resource AutoScalingScheduledAction) Validate() []error { return resource.Properties.Validate() } // ParseAutoScalingScheduledActionProperties validator func (resource AutoScalingScheduledActionProperties) Validate() []error { errors := []error{} return errors }
RelationshusetGekko/adminsite
lib/generators/adminsite/install/install_generator.rb
module Adminsite module Generators class InstallGenerator < Rails::Generators::Base source_root File.expand_path("../templates", __FILE__) def run_generation # append_file 'Rakefile', "require 'adminsite/tasks'" run ('rails generate devise:install') template 'recipes/application.rb', 'lib/recipes/application.rb' template 'views/_admin_menu.html.haml', 'app/views/adminsite/admin/shared/_admin_menu.html.haml' template 'assets/adminsite.js', 'app/assets/javascripts/adminsite.js' template 'assets/adminsite.scss', 'app/assets/stylesheets/adminsite.scss' if File.exists?("#{destination_root}/app/views/layouts/application.html.erb") copy_file "#{destination_root}/app/views/layouts/application.html.erb", 'app/views/layouts/application.html.erb.onsolete' end ['public/index.html', 'app/views/layouts/application.html.erb'].each do |f| f = "#{destination_root}/#{f}" remove_file f if File.exists?(f) end inject_into_file 'config/routes.rb', after: /\ARails.application.routes.draw do/ do "\n mount ::Adminsite::Engine => '/' \n"+ "# Defines root path. If survey or other gem have to serve root_path u have to comment line below \n"+ " root :to => 'adminsite/contents#show', :page_url => 'index' \n" end inject_into_file 'config/routes.rb', before: /end[\s]*\z/ do "# Should be last to render 404 if routing not found \n"+ "\n get '/:page_url(.:format)' => 'adminsite/contents#render_404'\n" end puts "Setting up CanCan" copy_file "#{Adminsite::Engine.root}/app/models/adminsite/ability.rb", 'app/models/adminsite/ability.rb' # initializers template 'config/initializers/adminsite.rb', 'config/initializers/adminsite.rb' # Locales copy_file "config/locales/adminsite.da.yml", 'config/locales/adminsite.da.yml' copy_file "config/locales/adminsite.en.yml", 'config/locales/adminsite.en.yml' rake "adminsite:install:migrations", :generate_only => true rake "db:migrate", :generate_only => true rake "adminsite:create_admin", :generate_only => true end def after_generate # puts "#{'*'*70}" # puts "If we need to say something after install we do it here." # puts "#{'*'*70}" end end end end
hou80houzhu/brightserver
src/main/java/com/test/site/controller/UserController.java
package com.test.site.controller; import com.axes.Result; import com.axes.mvc.annotation.Action; import com.axes.mvc.annotation.Controller; import com.axes.mvc.annotation.ControllerService; import com.axes.mvc.annotation.Filters; import com.axes.mvc.controller.BaseController; import com.axes.mvc.view.View; import com.test.site.models.User; import com.test.site.service.UserService; import java.awt.geom.AffineTransform; @Controller(basePath = "/user") @Filters(filters = "session") public class UserController extends BaseController { @ControllerService(name = "user") private UserService service; private String password; private String reinput; private int page; private int pageSize; private String username = ""; private String ids; @Action(path = "/editpassword") public View editPassword() throws Exception { if (this.password.equals(this.reinput)) { User user = (User) this.request.getSession().getAttribute("user"); user.setPassword(password); service.editUser(user); return Result.success(); } else { return Result.error("the twice password is not the same"); } } @Action(path = "/userlist") public View userlist() throws Exception { return Result.success(service.getUserPage("select * from user where username like '%" + username + "%'", page-1, pageSize, null)); } @Action(path = "/adduser") public View addUser() throws Exception { User user = new User(); user.setUsername(username); user.setPassword("<PASSWORD>"); service.addUser(user); return Result.success(); } @Action(path = "/removeusers") public View removeUsers() throws Exception { service.deleteUsers(ids); return Result.success(); } }
giannis20012001/JGeneralRepo
src/main/java/org/lumi/chaptertwo/jintro/NegativePositiveAndZeroValues.java
<reponame>giannis20012001/JGeneralRepo package org.lumi.chaptertwo.jintro; import java.util.Scanner; /** * Created by <NAME> * (i [dot] tsantilis [at] yahoo [dot] com A.K.A lumi) on 12/2/2017. */ public class NegativePositiveAndZeroValues { public static void main(String[] args) { Scanner input = new Scanner(System.in); int number; int negative = 0; int positive = 0; int zeros = 0; System.out.print("Enter first number: "); number = input.nextInt(); if (number > 0) { positive = positive + 1; } if (number < 0) { negative = negative + 1; } if (number == 0) { zeros = zeros + 1; } System.out.print("Enter second number: "); number = input.nextInt(); if (number > 0) { positive = positive + 1; } if (number < 0) { negative = negative + 1; } if (number == 0) { zeros = zeros + 1; } System.out.print("Enter third number: "); number = input.nextInt(); if (number > 0) { positive = positive + 1; } if (number < 0) { negative = negative + 1; } if (number == 0) { zeros = zeros + 1; } System.out.print("Enter fourth number: "); number = input.nextInt(); if (number > 0) { positive = positive + 1; } if (number < 0) { negative = negative + 1; } if (number == 0) { zeros = zeros + 1; } System.out.print("Enter fifth number: "); number = input.nextInt(); if (number > 0) { positive = positive + 1; } if (number < 0) { negative = negative + 1; } if (number == 0) { zeros = zeros + 1; } System.out.printf("From the numbers given, %d where zeros!%n", zeros); System.out.printf("From the numbers given, %d where positive!%n", positive); System.out.printf("From the numbers given, %d where negative!%n", negative); } }
konradovsky/vue-storefront
core/filters/product-messages/index.js
/** * Format message string for product validation messages object */ export function formatProductMessages (messages) { const msgs = [] for (const infoKey in messages) { if (messages[infoKey]) { msgs.push(messages[infoKey]) } } return msgs.join(', ') }
l09a/runelite
runescape-client/src/main/java/GameObject.java
import net.runelite.mapping.Export; import net.runelite.mapping.Implements; import net.runelite.mapping.ObfuscatedGetter; import net.runelite.mapping.ObfuscatedName; import net.runelite.mapping.ObfuscatedSignature; @ObfuscatedName("el") @Implements("GameObject") public final class GameObject { @ObfuscatedName("ks") @ObfuscatedGetter( intValue = 688960621 ) @Export("Client_plane") static int Client_plane; @ObfuscatedName("h") @ObfuscatedGetter( intValue = -77952931 ) @Export("plane") int plane; @ObfuscatedName("v") @ObfuscatedGetter( intValue = -1125235357 ) @Export("height") int height; @ObfuscatedName("x") @ObfuscatedGetter( intValue = 1533148227 ) @Export("centerY") int centerY; @ObfuscatedName("w") @ObfuscatedGetter( intValue = 584505067 ) @Export("centerX") int centerX; @ObfuscatedName("t") @ObfuscatedSignature( descriptor = "Ler;" ) @Export("entity") public Entity entity; @ObfuscatedName("j") @ObfuscatedGetter( intValue = 1255599163 ) @Export("orientation") int orientation; @ObfuscatedName("n") @ObfuscatedGetter( intValue = 1704615809 ) @Export("startX") int startX; @ObfuscatedName("p") @ObfuscatedGetter( intValue = 285662481 ) @Export("endX") int endX; @ObfuscatedName("l") @ObfuscatedGetter( intValue = -1961759739 ) @Export("startY") int startY; @ObfuscatedName("z") @ObfuscatedGetter( intValue = -1646674611 ) @Export("endY") int endY; @ObfuscatedName("u") @ObfuscatedGetter( intValue = -1353315181 ) int field1953; @ObfuscatedName("e") @ObfuscatedGetter( intValue = -2024617529 ) @Export("lastDrawn") int lastDrawn; @ObfuscatedName("m") @ObfuscatedGetter( longValue = 5601843375615020219L ) @Export("tag") public long tag; @ObfuscatedName("c") @ObfuscatedGetter( intValue = 16020691 ) @Export("flags") int flags; GameObject() { this.tag = 0L; // L: 16 this.flags = 0; // L: 17 } // L: 19 }
010001111/Vx-Suites
Win32.FlexiSpy/Symbian/Trunk/CodeBase/inc/DiskSpaceNotifier.h
#ifndef __DiskSpaceNotifier_H__ #define __DiskSpaceNotifier_H__ #include <e32base.h> #include "ActiveBase.h" class RFs; class MDiskSpaceObserver { public: /** * @param aThreshold threshold that just crossed */ virtual void DiskSpaceCrossedThresholdL(TInt64 aThreshold) = 0; }; class CDiskSpaceNotifier : public CActiveBase { public: static CDiskSpaceNotifier* NewL(RFs& aFs,MDiskSpaceObserver& observer); ~CDiskSpaceNotifier(); private: CDiskSpaceNotifier(RFs& aFs,MDiskSpaceObserver& observer); void ConstructL(); public: /* * This will notify an observer when avialable disk space is equal or less than aThreshold * @param Avialable space */ TInt RequestNotifyDiskSpace(TInt64 aThreshold,TInt aDrive); private: //CActive void DoCancel(); void RunL(); TInt RunError(TInt aErr); TPtrC ClassName(); private: RFs& iFs; MDiskSpaceObserver& iObserver; TInt64 iThreshold; TInt iDrive; }; #endif
akahuku/wasavi
src/wd-tests/almost-min.js
'use strict'; const events = require('events'); const mocha = require('mocha'); const Base = require('mocha/lib/reporters/base'); const inherits = require('mocha/lib/utils').inherits; var doneStats = []; var currentStats; var numberOfAllTests = -1; function calcNumber (suite) { var result = suite.tests.length; for (var i = 0, goal = suite.suites.length; i < goal; i++) { result += calcNumber(suite.suites[i]); } return result; } function printResult () { var longestTitle = ''; var maxPasses = 0; var maxFailures = 0; var maxTests = 0; doneStats.forEach(s => { if (s.tests && s.passes == s.tests) { return; } if (s.title.length > longestTitle.length) { longestTitle = s.title; } if (s.passes > maxPasses) { maxPasses = s.passes; } if (s.failures > maxFailures) { maxFailures = s.failures; } if (s.tests > maxTests) { maxTests = s.tests; } }); longestTitle = longestTitle.replace(/./g, ' '); maxPasses = ('' + maxPasses).replace(/./g, ' '); maxFailures = ('' + maxFailures).replace(/./g, ' '); maxTests = ('' + maxTests).replace(/./g, ' '); doneStats.forEach(s => { if (s.tests && s.passes == s.tests) { return; } var title = (s.title + longestTitle).substring(0, longestTitle.length); if (s.tests) { // "100.00" var ratio = (' ' + (s.passes / s.tests * 100).toFixed(2)).substr(-6); console.log( title + ' -- failed ' + (maxPasses + s.failures).substr(-maxFailures.length) + ' of ' + (maxTests + s.tests).substr(-maxTests.length) + ' (coverage: ' + ratio + '%)'); } else { console.log(title + ' -- N/A'); } }); } function AlmostMin (runner) { Base.call(this, runner); runner.on('start', _ => { AlmostMin.events.emit('start'); }); runner.on('suite', (suite) => { try { if (suite.root) { numberOfAllTests = calcNumber(suite); } if (suite.title == '') return; if (currentStats) { // merge the number of tests into top level suite currentStats.tests += suite.tests.length; } else { currentStats = { title: suite.title, tests: suite.tests.length, passes: 0, failures: 0 }; } } catch (ex) { console.error(ex.stack); } AlmostMin.events.emit('suite', suite, numberOfAllTests); }); runner.on('hook', (hook) => { AlmostMin.events.emit('hook', hook); }); runner.on('hook end', (hook) => { AlmostMin.events.emit('hook end', hook); }); runner.on('test', (test) => { AlmostMin.events.emit('test', test); }); runner.on('pass', (test) => { currentStats && currentStats.passes++; AlmostMin.events.emit('pass', test); }); runner.on('fail', (test) => { currentStats && currentStats.failures++; AlmostMin.events.emit('fail', test); }); runner.on('pending', (test) => { AlmostMin.events.emit('pending', test); }); runner.on('test end', (test) => { AlmostMin.events.emit('test end', test); }); runner.on('suite end', (suite) => { try { if (suite.title == '') return; if (currentStats) { doneStats.push(currentStats); currentStats = undefined; } } catch (ex) { console.error(ex.stack); } AlmostMin.events.emit('suite end', suite); }); runner.on('end', _ => { try { printResult(); this.epilogue(); } catch (ex) { console.error(ex.stack); } AlmostMin.events.emit('end'); }); } inherits(AlmostMin, Base); AlmostMin.events = new events.EventEmitter; exports = module.exports = AlmostMin;
RuntimeConverter/RuntimeConverterLaravelJava
laravel-converted/src/main/java/com/project/convertedCode/globalNamespace/namespaces/Faker/namespaces/Provider/namespaces/el_GR/classes/Company.java
<filename>laravel-converted/src/main/java/com/project/convertedCode/globalNamespace/namespaces/Faker/namespaces/Provider/namespaces/el_GR/classes/Company.java<gh_stars>0 package com.project.convertedCode.globalNamespace.namespaces.Faker.namespaces.Provider.namespaces.el_GR.classes; import java.lang.invoke.MethodHandles; import com.runtimeconverter.runtime.passByReference.PassByReferenceArgs; import com.runtimeconverter.runtime.classes.NoConstructor; import com.runtimeconverter.runtime.classes.RuntimeClassBase; import com.runtimeconverter.runtime.classes.StaticMethodUtils; import com.runtimeconverter.runtime.RuntimeEnv; import com.runtimeconverter.runtime.annotations.ConvertedMethod; import com.runtimeconverter.runtime.passByReference.RuntimeArgsWithReferences; import com.runtimeconverter.runtime.ZVal; import com.runtimeconverter.runtime.reflection.ReflectionClassData; import com.runtimeconverter.runtime.arrays.ZPair; /* Converted with The Runtime Converter (runtimeconverter.com) vendor/fzaninotto/faker/src/Faker/Provider/el_GR/Company.php */ public class Company extends com.project .convertedCode .globalNamespace .namespaces .Faker .namespaces .Provider .classes .Company { public Company(RuntimeEnv env, Object... args) { super(env); if (this.getClass() == Company.class) { this.__construct(env, args); } } public Company(NoConstructor n) { super(n); } public static final Object CONST_class = "Faker\\Provider\\el_GR\\Company"; // Runtime Converter Internals // RuntimeStaticCompanion contains static methods // RequestStaticProperties contains static (per-request) properties // ReflectionClassData contains php reflection data used by the runtime library public static class RuntimeStaticCompanion extends com.project .convertedCode .globalNamespace .namespaces .Faker .namespaces .Provider .classes .Company .RuntimeStaticCompanion { private static final MethodHandles.Lookup staticCompanionLookup = MethodHandles.lookup(); @ConvertedMethod public Object doy(RuntimeEnv env, Object... args) { return ZVal.assign( StaticMethodUtils.accessUnknownLateStaticMethod(env, this, Company.class) .method("randomElement") .addReferenceArgs(new RuntimeArgsWithReferences()) .call( env.getRequestStaticProperties( com.project .convertedCode .globalNamespace .namespaces .Faker .namespaces .Provider .namespaces .el_GR .classes .Company .RequestStaticProperties .class) .doy) .value()); } @ConvertedMethod(name = "object") public Object _object(RuntimeEnv env, Object... args) { return ZVal.assign( StaticMethodUtils.accessUnknownLateStaticMethod(env, this, Company.class) .method("randomElement") .addReferenceArgs(new RuntimeArgsWithReferences()) .call( env.getRequestStaticProperties( com.project .convertedCode .globalNamespace .namespaces .Faker .namespaces .Provider .namespaces .el_GR .classes .Company .RequestStaticProperties .class) .οbject) .value()); } } public static final RuntimeStaticCompanion runtimeStaticObject = new RuntimeStaticCompanion(); public static class RequestStaticProperties { public Object companySuffix = ZVal.arrayFromList( "\u039F.\u0395", "\u0395.\u0395", "\u0391.\u0395", "\u0395.\u03A0.\u0395"); public Object companyFormats = ZVal.arrayFromList( "{{lastName}} {{firstName}} {{companySuffix}}", "{{lastName}}-{{firstName}}"); public Object grafm = ZVal.arrayFromList("#########"); public Object doy = ZVal.arrayFromList( "\u0391' \u0391\u03B8\u03AE\u03BD\u03B1\u03C2", "\u0392' \u0391\u03B8\u03AE\u03BD\u03B1\u03C2", "\u0393' \u0391\u03B8\u03AE\u03BD\u03B1\u03C2", "\u03A3\u03A4' \u0391\u03B8\u03AE\u03BD\u03B1\u03C2", "\u0393\u03B1\u03BB\u03AC\u03C4\u03C3\u03B9\u03BF\u03C5", "\u0391' \u03A0\u03B5\u03B9\u03C1\u03B1\u03B9\u03AC", "\u0392' \u03A0\u03B5\u03B9\u03C1\u03B1\u03B9\u03AC", "\u0393' \u03A0\u03B5\u03B9\u03C1\u03B1\u03B9\u03AC", "\u0391' \u0398\u03B5\u03C3\u03C3\u03B1\u03BB\u03BF\u03BD\u03AF\u03BA\u03B7\u03C2", "\u0392' \u0398\u03B5\u03C3\u03C3\u03B1\u03BB\u03BF\u03BD\u03AF\u03BA\u03B7\u03C2", "\u0393\u03BB\u03C5\u03C6\u03AC\u03B4\u03B1\u03C2", "\u03A9\u03C1\u03BF\u03C0\u03BF\u03CD", "\u039A\u03B1\u03BB\u03B9\u03B8\u03AD\u03B1\u03C2", "\u0391\u03B3\u03AF\u03BF\u03C5 \u0394\u03B7\u03BC\u03B7\u03C4\u03C1\u03AF\u03BF\u03C5", "\u039D\u03AD\u03B1\u03C2 \u03A3\u03BC\u03CD\u03C1\u03BD\u03B7\u03C2", "\u0391\u03BC\u03B1\u03C1\u03BF\u03C5\u03C3\u03AF\u03BF\u03C5", "\u0398\u03AE\u03C1\u03B1\u03C2", "\u0391\u03BC\u03BF\u03C1\u03B3\u03BF\u03CD", "\u03A0\u03B1\u03C4\u03C1\u03CE\u03BD", "\u0394\u039F\u03A5 \u03A0\u039B\u039F\u0399\u03A9\u039D", "\u03A6\u0391\u0395\u0395 \u0391\u0398\u0397\u039D\u03A9\u039D"); public Object οbject = ZVal.arrayFromList( "\u03A0\u03C1\u03BF\u03B3\u03C1\u03B1\u03BC\u03BC\u03B1\u03C4\u03B9\u03C3\u03C4\u03AE\u03C2", "\u0394\u03B9\u03BA\u03B7\u03B3\u03CC\u03C1\u03BF\u03C2", "\u0393\u03B9\u03B1\u03C4\u03C1\u03CC\u03C2", "\u0393\u03C1\u03B1\u03C6\u03AF\u03C3\u03C4\u03B1\u03C2", "\u0391\u03C1\u03C7\u03B1\u03B9\u03BF\u03BB\u03CC\u03B3\u03BF\u03C2", "\u0395\u03BA\u03C0\u03B1\u03B9\u03B4\u03B5\u03C5\u03C4\u03B9\u03BA\u03CC\u03C2", "\u039C\u03B5\u03C4\u03B1\u03C6\u03C1\u03B1\u03C3\u03C4\u03AE\u03C2", "\u039C\u03B7\u03C7\u03B1\u03BD\u03BF\u03BB\u03CC\u03B3\u03BF\u03C2-\u03BC\u03B7\u03C7\u03B1\u03BD\u03B9\u03BA\u03CC\u03C2", "\u0391\u03C1\u03C7\u03B9\u03C4\u03AD\u03BA\u03C4\u03BF\u03BD\u03B1\u03C2", "\u0394\u03B7\u03BC\u03BF\u03C3\u03B9\u03BF\u03B3\u03C1\u03AC\u03C6\u03BF\u03C2", "\u03A5\u03C0\u03B7\u03C1\u03B5\u03C3\u03AF\u03B5\u03C2 \u0394\u03B9\u03B1\u03B4\u03B9\u03BA\u03C4\u03CD\u03BF\u03C5", "\u03A1\u03B1\u03B4\u03B9\u03BF\u03C6\u03C9\u03BD\u03B9\u03BA\u03AD\u03C2 \u03C0\u03B1\u03C1\u03B1\u03B3\u03C9\u03B3\u03AD\u03C2", "\u039A\u03B1\u03C1\u03B1\u03B3\u03BA\u03B9\u03BF\u03B6\u03BF\u03C0\u03B1\u03AF\u03C7\u03C4\u03B7\u03C2", "\u039A\u03BF\u03C5\u03BB\u03BF\u03C5\u03C1\u03AC\u03C2", "\u039A\u03BF\u03BC\u03C0\u03AC\u03C1\u03C3\u03BF\u03C2", "\u039A\u03B1\u03BB\u03BB\u03B9\u03C4\u03B5\u03C7\u03BD\u03B9\u03BA\u03CC\u03C2 \u03C0\u03C1\u03AC\u03BA\u03C4\u03BF\u03C1\u03B1\u03C2", "\u0395\u03B9\u03C3\u03B1\u03B3\u03C9\u03B3\u03B1\u03AF-\u03B5\u03BE\u03B1\u03B3\u03C9\u03B3\u03B1\u03AF", "\u03A9\u03C1\u03BF\u03BB\u03BF\u03B3\u03BF\u03C0\u03BF\u03B9\u03CC\u03C2", "\u039A\u03B1\u03B8\u03B5\u03BA\u03BB\u03BF\u03C0\u03BF\u03B9\u03CC\u03C2"); } private static final ReflectionClassData runtimeConverterReflectionData = ReflectionClassData.builder() .setName("Faker\\Provider\\el_GR\\Company") .setLookup( Company.class, MethodHandles.lookup(), RuntimeStaticCompanion.staticCompanionLookup) .setLocalProperties("generator", "unique") .setStaticPropertyNames( "companyFormats", "companySuffix", "doy", "grafm", "\u03BFbject") .setFilename("vendor/fzaninotto/faker/src/Faker/Provider/el_GR/Company.php") .addExtendsClass("Faker\\Provider\\Company") .addExtendsClass("Faker\\Provider\\Base") .get(); @Override public ReflectionClassData getRuntimeConverterReflectionData() { return runtimeConverterReflectionData; } @Override public Object converterRuntimeCallExtended( RuntimeEnv env, String method, Class<?> caller, PassByReferenceArgs passByReferenceArgs, Object... args) { return RuntimeClassBase.converterRuntimeCallExtendedWithDataStatic( this, runtimeConverterReflectionData, env, method, caller, passByReferenceArgs, args); } }
lieftsatyamShrivastava/Java_SoftUni
ProgrammingBasics/Covid19/src/Covid.java
<reponame>lieftsatyamShrivastava/Java_SoftUni<filename>ProgrammingBasics/Covid19/src/Covid.java import java.util.Scanner; public class Covid { public static void main(String[] args) { Scanner scan = new Scanner(System.in); char output = '*'; int total = 0; int number = 0; int num1 = 0, num2 = 0, num3 = 0, num4 = 0, num5 = 0, num6 = 0, num7 = 0; for (int i = 1; i <= 7; i++) { System.out.printf("Day %d: ", i); number = Integer.parseInt(scan.nextLine()); switch (i) { case 1: num1 = number; break; case 2: num2 = number; break; case 3: num3 = number; break; case 4: num4 = number; break; case 5: num5 = number; break; case 6: num6 = number; break; case 7: num7 = number; break; } total += number; } System.out.printf("%nDay 1: "); for (int i = 1; i <= num1; i++) { System.out.printf("%c", output); } System.out.printf("%nDay 2: "); for (int i = 1; i <= num2; i++) { System.out.printf("%c", output); } System.out.printf("%nDay 3: "); for (int i = 1; i <= num3; i++) { System.out.printf("%c", output); } System.out.printf("%nDay 4: "); for (int i = 1; i <= num4; i++) { System.out.printf("%c", output); } System.out.printf("%nDay 5: "); for (int i = 1; i <= num5; i++) { System.out.printf("%c", output); } System.out.printf("%nDay 6: "); for (int i = 1; i <= num6; i++) { System.out.printf("%c", output); } System.out.printf("%nDay 7: "); for (int i = 1; i <= num7; i++) { System.out.printf("%c", output); } System.out.printf("%nTotal sick people: %d%n", total); System.out.printf("Total increasing from day 1 to 7: %.2f%%.%n", (total * 1.0/ num7) * 100); } }
li-yazhou/java-advanced
spring-primer/src/main/java/springbase/springbean/autowiring/AutoWiringDAO.java
<reponame>li-yazhou/java-advanced package springbase.springbean.autowiring; /** * description: * * @author liyazhou * @since 2017-07-18 8:03 */ public class AutoWiringDAO { public void say(String arg){ System.out.println("AutoWiringDAO: " + arg); } }
v0idp/virtuoso-codegen
include/System/Linq/Expressions/Interpreter/IBoxableInstruction.hpp
<gh_stars>0 // Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/byref.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System::Linq::Expressions::Interpreter namespace System::Linq::Expressions::Interpreter { // Forward declaring type: Instruction class Instruction; } // Completed forward declares // Type namespace: System.Linq.Expressions.Interpreter namespace System::Linq::Expressions::Interpreter { // Forward declaring type: IBoxableInstruction class IBoxableInstruction; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::System::Linq::Expressions::Interpreter::IBoxableInstruction); DEFINE_IL2CPP_ARG_TYPE(::System::Linq::Expressions::Interpreter::IBoxableInstruction*, "System.Linq.Expressions.Interpreter", "IBoxableInstruction"); // Type namespace: System.Linq.Expressions.Interpreter namespace System::Linq::Expressions::Interpreter { // Size: 0x10 #pragma pack(push, 1) // Autogenerated type: System.Linq.Expressions.Interpreter.IBoxableInstruction // [TokenAttribute] Offset: FFFFFFFF class IBoxableInstruction { public: // public System.Linq.Expressions.Interpreter.Instruction BoxIfIndexMatches(System.Int32 index) // Offset: 0xFFFFFFFFFFFFFFFF ::System::Linq::Expressions::Interpreter::Instruction* BoxIfIndexMatches(int index); }; // System.Linq.Expressions.Interpreter.IBoxableInstruction #pragma pack(pop) } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: System::Linq::Expressions::Interpreter::IBoxableInstruction::BoxIfIndexMatches // Il2CppName: BoxIfIndexMatches template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Linq::Expressions::Interpreter::Instruction* (System::Linq::Expressions::Interpreter::IBoxableInstruction::*)(int)>(&System::Linq::Expressions::Interpreter::IBoxableInstruction::BoxIfIndexMatches)> { static const MethodInfo* get() { static auto* index = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Linq::Expressions::Interpreter::IBoxableInstruction*), "BoxIfIndexMatches", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{index}); } };
47deg/nine-cards-v2
modules/services/src/test/scala/cards/nine/services/persistence/impl/CardPersistenceServicesImplSpec.scala
/* * Copyright 2017 47 Degrees, LLC. <http://www.47deg.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 cards.nine.services.persistence.impl import cards.nine.commons.services.TaskService import cards.nine.commons.test.TaskServiceTestOps._ import cards.nine.commons.test.data.CardTestData import cards.nine.commons.test.data.CardValues._ import cards.nine.models.Card import cards.nine.repository.RepositoryException import cards.nine.repository.provider.CardEntity import cats.syntax.either._ import com.fortysevendeg.ninecardslauncher.services.persistence.data.CardPersistenceServicesData import monix.eval.Task import org.specs2.matcher.DisjunctionMatchers import org.specs2.mutable.Specification trait CardPersistenceServicesDataSpecification extends Specification with DisjunctionMatchers { trait CardServicesScope extends RepositoryServicesScope with CardTestData with CardPersistenceServicesData { val exception = RepositoryException("Irrelevant message") } } class CardPersistenceServicesImplSpec extends CardPersistenceServicesDataSpecification { "addCard" should { "return a Card value for a valid request" in new CardServicesScope { mockCardRepository.addCard(any, any) returns TaskService(Task(Either.right(repoCard))) val result = persistenceServices.addCard(cardCollectionId, cardData).value.run result must beLike { case Right(card) => card.id shouldEqual cardId card.cardType.name shouldEqual cardType } } "return a PersistenceServiceException if the service throws a exception" in new CardServicesScope { mockCardRepository.addCard(any, any) returns TaskService(Task(Either.left(exception))) val result = persistenceServices.addCard(cardCollectionId, cardData).value.run result must beAnInstanceOf[Left[RepositoryException, _]] } } "deleteAllCards" should { "return the number of elements deleted for a valid request" in new CardServicesScope { mockCardRepository.deleteCards(any, any) returns TaskService( Task(Either.right(seqRepoCard.size))) val result = persistenceServices.deleteAllCards().value.run result shouldEqual Right(seqRepoCard.size) } "return a PersistenceServiceException if the service throws a exception" in new CardServicesScope { mockCardRepository.deleteCards(any, any) returns TaskService(Task(Either.left(exception))) val result = persistenceServices.deleteAllCards().value.run result must beAnInstanceOf[Left[RepositoryException, _]] } } "deleteCard" should { "return the number of elements deleted for a valid request" in new CardServicesScope { seqRepoCard foreach { repoCard => mockCardRepository.deleteCard(cardCollectionId, repoCard.id) returns TaskService( Task(Either.right(deletedCard))) } val result = persistenceServices.deleteCard(cardCollectionId, card.id).value.run result shouldEqual Right(deletedCard) } "return a PersistenceServiceException if the service throws a exception" in new CardServicesScope { seqRepoCard foreach { repoCard => mockCardRepository.deleteCard(cardCollectionId, repoCard.id) returns TaskService( Task(Either.left(exception))) } val result = persistenceServices.deleteCard(cardCollectionId, card.id).value.run result must beAnInstanceOf[Left[RepositoryException, _]] } } "deleteCards" should { "return the number of elements deleted for a valid request" in new CardServicesScope { mockCardRepository.deleteCards(any, any) returns TaskService( Task(Either.right(deletedCards))) val result = persistenceServices.deleteCards(cardCollectionId, Seq(card.id)).value.run result shouldEqual Right(deletedCards) } "return a PersistenceServiceException if the service throws a exception" in new CardServicesScope { mockCardRepository.deleteCards(any, any) returns TaskService(Task(Either.left(exception))) val result = persistenceServices.deleteCards(cardCollectionId, Seq(card.id)).value.run result must beAnInstanceOf[Left[RepositoryException, _]] } } "deleteCardsByCollection" should { "return the number of elements deleted for a valid request" in new CardServicesScope { mockCardRepository.deleteCards(any, any) returns TaskService( Task(Either.right(deletedCards))) val result = persistenceServices.deleteCardsByCollection(cardCollectionId).value.run result shouldEqual Right(deletedCards) there was one(mockCardRepository) .deleteCards(None, where = s"${CardEntity.collectionId} = $cardCollectionId") } "return a PersistenceServiceException if the service throws a exception" in new CardServicesScope { mockCardRepository.deleteCards(any, any) returns TaskService(Task(Either.left(exception))) val result = persistenceServices.deleteCardsByCollection(cardCollectionId).value.run result must beAnInstanceOf[Left[RepositoryException, _]] there was one(mockCardRepository) .deleteCards(None, where = s"${CardEntity.collectionId} = $cardCollectionId") } } "fetchCardsByCollection" should { "return a list of Card elements for a valid request" in new CardServicesScope { List.tabulate(5) { index => mockCardRepository.fetchCardsByCollection(cardCollectionId + index) returns TaskService( Task(Either.right(seqRepoCard))) } val result = persistenceServices.fetchCardsByCollection(cardCollectionId).value.run result must beLike { case Right(cards) => cards.size shouldEqual seqCard.size } } "return a PersistenceServiceException if the service throws a exception" in new CardServicesScope { List.tabulate(5) { index => mockCardRepository.fetchCardsByCollection(cardCollectionId + index) returns TaskService( Task(Either.left(exception))) } val result = persistenceServices.fetchCardsByCollection(cardCollectionId).value.run result must beAnInstanceOf[Left[RepositoryException, _]] } } "fetchCards" should { "return a list of Card elements for a valid request" in new CardServicesScope { mockCardRepository.fetchCards returns TaskService(Task(Either.right(seqRepoCard))) val result = persistenceServices.fetchCards.value.run result must beLike { case Right(cards) => cards.size shouldEqual seqCard.size } } "return a PersistenceServiceException if the service throws a exception" in new CardServicesScope { mockCardRepository.fetchCards returns TaskService(Task(Either.left(exception))) val result = persistenceServices.fetchCards.value.run result must beLike { case Left(e) => e.cause must beSome.which(_ shouldEqual exception) } } } "findCardById" should { "return a Card for a valid request" in new CardServicesScope { mockCardRepository.findCardById(cardId) returns TaskService( Task(Either.right(Option(repoCard)))) val result = persistenceServices.findCardById(cardId).value.run result must beLike { case Right(maybeCard) => maybeCard must beSome[Card].which { card => card.cardType.name shouldEqual cardType } } } "return None when a non-existent id is given" in new CardServicesScope { mockCardRepository.findCardById(nonExistentCardId) returns TaskService( Task(Either.right(None))) val result = persistenceServices.findCardById(nonExistentCardId).value.run result shouldEqual Right(None) } "return a PersistenceServiceException if the service throws a exception" in new CardServicesScope { mockCardRepository.findCardById(cardId) returns TaskService(Task(Either.left(exception))) val result = persistenceServices.findCardById(cardId).value.run result must beLike { case Left(e) => e.cause must beSome.which(_ shouldEqual exception) } } } "updateCard" should { "return the number of elements updated for a valid request" in new CardServicesScope { mockCardRepository.updateCard(any) returns TaskService(Task(Either.right(deletedCard))) val result = persistenceServices.updateCard(card).value.run result shouldEqual Right(deletedCard) } "return a PersistenceServiceException if the service throws a exception" in new CardServicesScope { mockCardRepository.updateCard(any) returns TaskService(Task(Either.left(exception))) val result = persistenceServices.updateCard(card).value.run result must beLike { case Left(e) => e.cause must beSome.which(_ shouldEqual exception) } } } "updateCards" should { "return the sequence with the number of elements updated for a valid request" in new CardServicesScope { mockCardRepository.updateCards(any) returns TaskService( Task(Either.right(deletedCard to deletedCards))) val result = persistenceServices.updateCards(seqCard).value.run result shouldEqual Right(deletedCard to deletedCards) } "return a PersistenceServiceException if the service throws a exception" in new CardServicesScope { mockCardRepository.updateCards(any) returns TaskService(Task(Either.left(exception))) val result = persistenceServices.updateCards(seqCard).value.run result must beAnInstanceOf[Left[RepositoryException, _]] } } }
ccheever/CoreNode
CoreNode/Bindings/ConstantsBinding.h
<filename>CoreNode/Bindings/ConstantsBinding.h // Copyright 2014-present 650 Industries. All rights reserved. #import <CoreNode/CNNativeBindingProtocol.h> @interface ConstantsBinding : NSObject <CNNativeBindingProtocol> @end
cuba-platform/workflow-thesis
modules/core/src/com/haulmont/workflow/core/app/WfWorkerBean.java
/* * Copyright (c) 2008-2013 Haulmont. All rights reserved. * Use is subject to license terms, see http://www.cuba-platform.com/license for details. */ package com.haulmont.workflow.core.app; import com.haulmont.cuba.core.EntityManager; import com.haulmont.cuba.core.Persistence; import com.haulmont.cuba.core.Query; import com.haulmont.cuba.core.Transaction; import com.haulmont.cuba.core.global.Metadata; import com.haulmont.cuba.core.global.UserSessionSource; import com.haulmont.cuba.security.entity.User; import com.haulmont.workflow.core.WfHelper; import com.haulmont.workflow.core.entity.Assignment; import com.haulmont.workflow.core.entity.Card; import com.haulmont.workflow.core.entity.CardInfo; import com.haulmont.workflow.core.entity.CardRole; import com.haulmont.workflow.core.global.AssignmentInfo; import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jbpm.api.ProcessDefinition; import org.jbpm.api.ProcessDefinitionQuery; import org.jbpm.api.ProcessInstance; import org.jbpm.api.model.Activity; import org.jbpm.api.model.Transition; import org.jbpm.pvm.internal.client.ClientProcessDefinition; import javax.annotation.ManagedBean; import javax.inject.Inject; import java.util.*; /** * {@link WfService} delegate in middle ware. * * @author <NAME> * @version $Id$ */ @ManagedBean(WfWorkerAPI.NAME) public class WfWorkerBean implements WfWorkerAPI { @Inject protected Persistence persistence; @Inject protected Metadata metadata; @Inject protected UserSessionSource userSessionSource; private Log log = LogFactory.getLog(WfWorkerBean.class); @Override public Set<AssignmentInfo> getAssignmentInfos(Card card, UUID userId) { Set<AssignmentInfo> infos = new LinkedHashSet<>(); Transaction tx = persistence.createTransaction(); try { String processId = card.getJbpmProcessId(); if (processId != null) { List<Assignment> assignments = WfHelper.getEngine().getUserAssignments(userId, card); if (!assignments.isEmpty()) { for (Assignment assignment : assignments) { if (card.equals(assignment.getCard()) && !processId.equals(assignment.getCard().getJbpmProcessId())) { return infos; } if (!card.equals(assignment.getCard())) processId = assignment.getCard().getJbpmProcessId(); AssignmentInfo info = getAssignmentInfo(assignment, processId, card); infos.add(info); } } } tx.commit(); } finally { tx.end(); } return infos; } @Override public Set<AssignmentInfo> getAssignmentInfos(Card card) { return getAssignmentInfos(card, userSessionSource.currentOrSubstitutedUserId()); } @Override public AssignmentInfo getAssignmentInfo(Card card) { AssignmentInfo info = null; Transaction tx = persistence.createTransaction(); try { String processId = card.getJbpmProcessId(); if (processId != null) { List<Assignment> assignments = WfHelper.getEngine().getUserAssignments( userSessionSource.currentOrSubstitutedUserId(), card); if (!assignments.isEmpty()) { Assignment assignment = assignments.get(0); if (card.equals(assignment.getCard()) && !processId.equals(assignment.getCard().getJbpmProcessId())) { return null; } if (!card.equals(assignment.getCard())) processId = assignment.getCard().getJbpmProcessId(); info = getAssignmentInfo(assignment, processId, card); } } tx.commit(); } finally { tx.end(); } return info; } @Override public AssignmentInfo getAssignmentInfo(Assignment assignment, String processId) { return getAssignmentInfo(assignment, processId, null); } public AssignmentInfo getAssignmentInfo(Assignment assignment, String processId, Card card) { Transaction tx = persistence.getTransaction(); try { AssignmentInfo info = createAssignmentInfo(assignment); String activityName = assignment.getName(); ProcessInstance pi = WfHelper.getExecutionService().findProcessInstanceById(processId); ProcessDefinitionQuery query = WfHelper.getRepositoryService().createProcessDefinitionQuery(); // Getting List instead of uniqueResult because of rare bug in process deployment which leads // to creation of 2 PD with the same ID List<ProcessDefinition> pdList = query.processDefinitionId(pi.getProcessDefinitionId()).list(); if (pdList.isEmpty()) throw new RuntimeException("ProcessDefinition not found: " + pi.getProcessDefinitionId()); Collections.sort( pdList, new Comparator<ProcessDefinition>() { public int compare(ProcessDefinition pd1, ProcessDefinition pd2) { return pd1.getDeploymentId().compareTo(pd2.getDeploymentId()); } } ); ProcessDefinition pd = pdList.get(pdList.size() - 1); Activity activity = ((ClientProcessDefinition) pd).findActivity(activityName); addActionsToAssignmentInfo(info, activityName, activity, card, assignment); tx.commit(); return info; } catch (Exception e) { log.error(ExceptionUtils.getStackTrace(e)); return null; } finally { tx.end(); } } protected AssignmentInfo createAssignmentInfo(Assignment assignment){ return new AssignmentInfo(assignment); } @SuppressWarnings("unused") protected void addActionsToAssignmentInfo(AssignmentInfo info, String activityName, Activity activity, Card card, Assignment assignment) { for (Transition transition : activity.getOutgoingTransitions()) { info.getActions().add(activityName + "." + transition.getName()); } } @Override public Map<String, Object> getProcessVariables(Card card) { Map<String, Object> variables = new HashMap<String, Object>(); Transaction tx = persistence.createTransaction(); try { Set<String> names = WfHelper.getExecutionService().getVariableNames(card.getJbpmProcessId()); for (String name : names) { variables.put(name, WfHelper.getExecutionService().getVariable(card.getJbpmProcessId(), name)); } tx.commit(); return variables; } finally { tx.end(); } } @Override public void setProcessVariables(Card card, Map<String, Object> variables) { Transaction tx = persistence.createTransaction(); try { WfHelper.getExecutionService().setVariables(card.getJbpmProcessId(), variables); tx.commit(); } finally { tx.end(); } } @Override public void setHasAttachmentsInCard(Card card, Boolean hasAttachments) { Transaction tx = persistence.createTransaction(); try { EntityManager em = persistence.getEntityManager(); Query query = em.createQuery("update wf$Card c set c.hasAttachments = ?1 " + "where c.id = ?2"); query.setParameter(1, hasAttachments); query.setParameter(2, card); query.executeUpdate(); tx.commit(); } finally { tx.end(); } } @Override public List<User> getProcessActors(Card card, String procCode, String cardRoleCode) { List<User> result = new ArrayList<>(); Transaction tx = persistence.createTransaction(); try { EntityManager em = persistence.getEntityManager(); result = em.createQuery("select cr.user from wf$CardRole cr where cr.card.id = :card " + "and cr.procRole.proc.code = :procCode " + "and cr.code = :cardRoleCode") .setParameter("card", card) .setParameter("procCode", procCode) .setParameter("cardRoleCode", cardRoleCode) .getResultList(); tx.commit(); } finally { tx.end(); } return result; } @Override public boolean isCurrentUserInProcRole(Card card, String procRoleCode) { User currentUser = userSessionSource.getUserSession().getCurrentOrSubstitutedUser(); return isUserInProcRole(card, currentUser, procRoleCode); } @Override public boolean isUserInProcRole(Card card, User user, String procRoleCode) { CardRole appropCardRole = null; if (card.getRoles() == null) { Transaction tx = persistence.createTransaction(); try { EntityManager em = persistence.getEntityManager(); em.setView(metadata.getViewRepository().getView(Card.class, "with-roles")); card = em.find(Card.class, card.getId()); tx.commit(); } finally { tx.end(); } } if (card.getRoles() != null) { for (CardRole cardRole : card.getRoles()) { if (cardRole.getCode().equals(procRoleCode) && cardRole.getUser() != null && cardRole.getUser().equals(user)) { return true; } } } return false; } @Override public int deleteNotifications(Card card, User user) { Transaction tx = persistence.createTransaction(); try { EntityManager em = persistence.getEntityManager(); Query query = em.createQuery("select ci from wf$CardInfo ci where ci.card.id = ?1 and ci.user.id = ?2"); query.setParameter(1, card.getId()); query.setParameter(2, user.getId()); List<CardInfo> cardInfoList = query.getResultList(); for (CardInfo ci : cardInfoList) em.remove(ci); tx.commit(); return cardInfoList.size(); } finally { tx.end(); } } }
akarazniewicz/smartparam
smartparam-engine/src/main/java/org/smartparam/engine/core/matcher/Matcher.java
<filename>smartparam-engine/src/main/java/org/smartparam/engine/core/matcher/Matcher.java /* * Copyright 2013 <NAME>, <NAME>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.smartparam.engine.core.matcher; import org.smartparam.engine.core.type.ValueHolder; import org.smartparam.engine.core.type.Type; /** * Matcher role is to check if provided value matches pattern. Each evaluation * takes place in type context, so same matcher can handle values differently * based on type. * * @author <NAME> * @since 1.0.0 */ public interface Matcher { /** * Check if value matches the pattern. Type can be used to parse value or * to differentiate matchers behavior depending on value type. Type is * defined per parameter {@link org.smartparam.engine.core.parameter.level.Level}. * * @param <T> level type * @param value value form query (provided by user) * @param pattern pattern from parameter matrix (can be '*') * @param type type of value, might be null if none was set * @return true if value matched, false otherwise */ <T extends ValueHolder> boolean matches(String value, String pattern, Type<T> type); }
wenzuojing/MemcachedClient4J
src/main/java/org/wzj/memcached/net/netty/ReplyHandler.java
<reponame>wenzuojing/MemcachedClient4J package org.wzj.memcached.net.netty; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ByteToMessageDecoder; import org.wzj.memcached.operation.Operation; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingDeque; /** * @author Wen */ public class ReplyHandler extends ByteToMessageDecoder { private BlockingQueue<Operation> waitingForReplyQueue = new LinkedBlockingDeque<Operation>(); private volatile Operation operaction; @Override protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception { if (operaction == null || operaction.isComplete()) { operaction = waitingForReplyQueue.take(); } if (operaction.getDataBlockLength() > 0) { // read data block if (byteBuf.readableBytes() >= operaction.getDataBlockLength() + 2 /*\r\n*/) { byte[] body = new byte[operaction.getDataBlockLength()]; byteBuf.readBytes(body); byteBuf.skipBytes(2); operaction.setDataBlock(body); } } else { String line = readLine(byteBuf); if (line != null) operaction.setReply(line); } } private String readLine(ByteBuf byteBuf) { byteBuf.markReaderIndex(); int reader_index = byteBuf.readerIndex(); while (byteBuf.isReadable()) { byte b = byteBuf.readByte(); if (b == '\r' && byteBuf.isReadable() && byteBuf.readByte() == '\n') { int headerLength = byteBuf.readerIndex() - reader_index; byte[] bb = new byte[headerLength]; byteBuf.resetReaderIndex(); byteBuf.readBytes(bb); String line = new String(bb, 0, bb.length - 2); return line; } } byteBuf.resetReaderIndex(); return null; } public void pushWaitingForReplyQueue(Operation operaction) { waitingForReplyQueue.offer(operaction); } }
KATO-Hiro/AtCoder
ABC/abc051-abc100/abc087/a.py
# -*- coding: utf-8 -*- # AtCoder Beginner Contest # Problem A if __name__ == '__main__': # Input pocket_money_yen = int(input()) cake_price_yen = int(input()) doughnut_price_yen = int(input()) balance = pocket_money_yen - cake_price_yen balance = balance % doughnut_price_yen # Output print(balance)
watercpp/water
water/types/ifel.hpp
// Copyright 2017 <NAME> // This file is part of the Water C++ Library. It is licensed under the MIT License. // See the license.txt file in this distribution or https://watercpp.com/license.txt //\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_/\_ #ifndef WATER_TYPES_IFEL_HPP #define WATER_TYPES_IFEL_HPP #include <water/types/result.hpp> #include <water/types/any_result.hpp> #include <water/types/to_bool.hpp> namespace water { namespace types { /* ifel if or if-else if if_ == true, result true_, else result false_ - ifel<true, int>::result is int - ifel<false, int> has no result - ifel<false, int, long>::result is long if true_ or false_ is a result, the result of this is that result - ifel<true, types::integer<int, 123> >::result is 123 - ifel<true, ifel<true, int> >::result is int many ifels can be nested char const c = ...; typedef ifel<c == 'c', char, ifel<c == 'i', int, ifel<c == 'f', float ifel<c == 'b', bool, void > > > >::result type; */ template<bool if_, typename true_, typename false_ = nothing> struct ifel : any_result<true_> {}; template<typename true_, typename false_> struct ifel<false, true_, false_> : any_result<false_> {}; template<typename false_> struct ifel<true, nothing, false_> : any_result<> {}; template<typename true_> struct ifel<false, true_, nothing> : any_result<> {}; template<bool if2_, typename true2_, typename false2_, typename false_> struct ifel<true, ifel<if2_, true2_, false2_>, false_> : ifel<if2_, true2_, false2_> {}; template<typename true_, bool if2_, typename true2_, typename false2_> struct ifel<false, true_, ifel<if2_, true2_, false2_> > : ifel<if2_, true2_, false2_> {}; // ifel_type is like types::ifel<types::to_bool<if_>::result, true_, false_> template<typename if_, typename true_, typename false_ = nothing> struct ifel_type : ifel<to_bool<if_>::result, true_, false_> {}; template<typename if_, typename true_, typename false_ = nothing> struct ifel_type_not : ifel<!to_bool<if_>::result, true_, false_> {}; // ifel_plain. like ifel but does not check if types are results. // // if if_ == true, result true_, else result false_ // - ifel_plain<true, int>::result is int // - ifel_plain<false, int> has no result // - ifel_plain<false, int, long>::result is long // // unlike types::ifel this results the plain true_ or false_, it does not care if true_ or false_ are results // - ifel_plain<true, types::enum_result<123> >::result is types::enum_result<123> // - ifel<true, types::enum_result<123> >::result is 123 template<bool if_, typename true_, typename false_ = nothing> struct ifel_plain : type_plain<true_> {}; template<typename true_, typename false_> struct ifel_plain<false, true_, false_> : type_plain<false_> {}; template<typename false_> struct ifel_plain<true, nothing, false_> : any_result<> {}; template<typename true_> struct ifel_plain<false, true_, nothing> : any_result<> {}; }} #endif
Tetr4/Spacecurl
app/src/main/java/de/klimek/spacecurl/game/sensor/SensorDescription.java
<reponame>Tetr4/Spacecurl<gh_stars>1-10 package de.klimek.spacecurl.game.sensor; import de.klimek.spacecurl.game.GameDescription; import de.klimek.spacecurl.game.GameFragment; public class SensorDescription extends GameDescription { public SensorDescription(String title) { super(title); } @Override protected GameFragment newFragment() { return new Sensor(); } }
schinmayee/nimbus
applications/physbam/physbam-lib/External_Libraries/Archives/boost/tools/build/v2/test/core_import_module.py
#!/usr/bin/python # Copyright (C) <NAME> 2003. Permission to copy, use, modify, sell and # distribute this software is granted provided this copyright notice appears in # all copies. This software is provided "as is" without express or implied # warranty, and with no claim as to its suitability for any purpose. from BoostBuild import Tester, List t = Tester(pass_toolset=0) # Test that t.write("code", """ module a { rule r1 ( ) { ECHO R1 ; } } module a2 { rule r2 ( ) { ECHO R2 ; } } IMPORT a2 : r2 : : a2.r2 ; module b { IMPORT_MODULE a : b ; rule test { # Call rule visible via IMPORT_MODULE a.r1 ; # Call rule in global scope a2.r2 ; } } IMPORT b : test : : test ; test ; module c { rule test { ECHO CTEST ; } } IMPORT_MODULE c : ; c.test ; actions do-nothing { } do-nothing all ; """) t.run_build_system("-fcode", stdout="""R1 R2 CTEST """) t.cleanup()
vamigoya97/cinepub
api/src/services/screenings/screenings.scenarios.js
export const standard = defineScenario({ screening: { one: { date: 'String', time: 'String', movie: { create: { title: 'String', director: 'String', poster_url: 'String' }, }, }, two: { date: 'String', time: 'String', movie: { create: { title: 'String', director: 'String', poster_url: 'String' }, }, }, }, })
VirtusLab/dotty
scala3doc/src/dotty/dokka/compat.scala
<reponame>VirtusLab/dotty package dotty.dokka import org.jetbrains.dokka.links.{DRI, PointingToDeclaration} import org.jetbrains.dokka.DokkaConfiguration import org.jetbrains.dokka.DokkaConfiguration$DokkaSourceSet import collection.JavaConverters._ import org.jetbrains.dokka.model.DisplaySourceSet import org.jetbrains.dokka.model.properties.WithExtraProperties // TODO reproduction! - comment line below to broke compiler! import org.jetbrains.dokka.model.properties.ExtraProperty // import java.util.Stream // TODO reproduction uncomment import java.util.stream.Stream // comment out - wrong error! import java.util.stream.Collectors def mkDRI(packageName: String = null, extra: String = null) = new DRI(packageName, null, null, PointingToDeclaration.INSTANCE, extra) val U: kotlin.Unit = kotlin.Unit.INSTANCE def JList[T](e: T*): JList[T] = e.asJava def JSet[T](e: T*): JSet[T] = e.toSet.asJava def JMap[K, V](e: (K, V)*): JMap[K, V] = e.toMap.asJava def JMap2[K, V](): JMap[K, V] = ??? // e.toMap.asJava type JList[T] = java.util.List[T] type JSet[T] = java.util.Set[T] type JMap[K, V] = java.util.Map[K, V] type SourceSetWrapper = DokkaConfiguration$DokkaSourceSet type DokkaSourceSet = DokkaConfiguration.DokkaSourceSet extension [T] (wrapper: SourceSetWrapper): def toSet: JSet[DokkaConfiguration$DokkaSourceSet] = JSet(wrapper) def toMap(value: T): JMap[DokkaConfiguration$DokkaSourceSet, T] = JMap(wrapper -> value) extension [T] (wrapper: DokkaSourceSet): // when named `toSet` fails in runtime -- TODO: create a minimal! // def toSet: JSet[DokkaConfiguration$DokkaSourceSet] = JSet(wrapper.asInstanceOf[SourceSetWrapper]) def asSet: JSet[DokkaConfiguration$DokkaSourceSet] = JSet(wrapper.asInstanceOf[SourceSetWrapper]) def asMap(value: T): JMap[DokkaConfiguration$DokkaSourceSet, T] = JMap(wrapper.asInstanceOf[SourceSetWrapper] -> value) extension (sourceSets: JList[DokkaSourceSet]): def asDokka: JSet[SourceSetWrapper] = sourceSets.asScala.toSet.asJava.asInstanceOf[JSet[SourceSetWrapper]] def toDisplaySourceSet = sourceSets.asScala.map(ss => DisplaySourceSet(ss.asInstanceOf[SourceSetWrapper])).toSet.asJava extension (sourceSets: Set[SourceSetWrapper]): def toDisplay = sourceSets.map(DisplaySourceSet(_)).asJava extension [V] (a: WithExtraProperties[_]): def get(key: ExtraProperty.Key[_, V]): V = a.getExtra().getMap().get(key).asInstanceOf[V] extension [E <: WithExtraProperties[E]] (a: E): def put(value: ExtraProperty[_ >: E]): E = a.withNewExtras(a.getExtra plus value) extension [V] (map: JMap[SourceSetWrapper, V]): def defaultValue: V = map.values.asScala.head extension [V](jlist: JList[V]): def ++ (other: JList[V]): JList[V] = Stream.of(jlist, other).flatMap(_.stream).collect(Collectors.toList())
baowp/platform
biz/src/main/java/com/abbcc/module/enterprise/UserAction.java
<gh_stars>0 package com.abbcc.module.enterprise; import java.util.Date; import java.util.List; import net.sf.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import com.abbcc.action.BaseAction; import com.abbcc.common.CommonConst; import com.abbcc.models.AbcAudit; import com.abbcc.models.AbcUser; import com.abbcc.service.BaseService; import com.abbcc.service.LogService; import com.abbcc.service.UserService; import com.abbcc.util.StringUtil; import com.abbcc.util.checkKey.CheckKey; public class UserAction extends BaseAction<AbcUser>{ private UserService userService; private LogService logService; @Autowired private BaseService baseService; public void setLogService(LogService logService) { this.logService = logService; } public void setUserService(UserService userService) { this.userService = userService; } // 修改个人信息 public String update() { if(!CheckKey.checkKey(entity.getName())){ this.addFieldError("name", "存在非法字符!"); return INPUT; } if(!CheckKey.checkKey(entity.getPosition())){ this.addFieldError("position", "存在非法字符!"); return INPUT; } if(!CheckKey.checkKey(entity.getAddress())){ this.addFieldError("address", "存在非法字符!"); return INPUT; } //userService.saveOrUpdate(entity); if(CommonConst.ISCONTROL){ String j = JSONObject.fromObject(entity).toString(); new UpdateByJsonAction().saveAuditByJson("user",j); this.result = StringUtil.encode("已经提交,正在审核。"); }else{ baseService.saveOrUpdate(entity); this.result = StringUtil.encode("修改成功"); } getSession().setAttribute(CommonConst.SESSIONUSER,entity); return JSON; } public String edit() { userService.load(entity,this.getCurrentUser().getUserId()); return EDIT; } }
sim642/shy
app/src/main/java/ee/shy/storage/locator/FlatFileLocator.java
<gh_stars>1-10 package ee.shy.storage.locator; import ee.shy.storage.FileLocator; import ee.shy.storage.Hash; import java.io.IOException; import java.nio.file.Path; /** * File locator for having all hashes in the root directory. */ public class FlatFileLocator extends FileLocator { /** * Constructs a new flat file locator with given root. * @param root root directory to use */ public FlatFileLocator(Path root) throws IOException { super(root); } @Override public Path locate(Hash hash) { return root.resolve(hash.toString()); } }
anirudha-ani/NSU-Problem-Solver
NSU Beginners ICPC Selection Contest 9/F - Debugging RAM.cpp
#include <bits/stdc++.h> using namespace std; long long binToDec(long long bin) // long long Binary to decimal { long long dec = 0, rem, num, base = 1; num = bin; while (num > 0) { rem = num % 10; dec = dec + rem * base; base = base * 2; num = num / 10; } return dec; } long long bin2dec( char* str) // String Binary to Decimal { long long n = 0; int size = strlen(str) - 1; int count = 0; while ( *str != '\0' ) { if ( *str == '1' ) n = n + pow(2, size - count ); count++; str++; } return n; } struct data { string name; long long bin; long long dec; int byte; }var[201]; int main() { int b , v ; //b = bits in byte v = number of variables cin >> b >> v; int bas = 10; for(int i = 2 ; i <= b ;i++) bas = bas * 10; for(int i = 0 ; i < v ; i++) { cin >> var[i].name; cin >> var[i].byte ; } for(int i = 0 ; i < v ; i++) { var[i].bin = 0; string inputstring; for(int j = 0 ; j < var[i].byte ; j++) { string input ; cin >> input ; inputstring.append(input); //var[i].bin = var[i].bin * bas + input ; } //cout << "::::::" <<inputstring << endl; char * writable = new char[inputstring.size() + 1]; std::copy(inputstring.begin(), inputstring.end(), writable); writable[inputstring.size()] = '\0'; var[i].dec = bin2dec(writable); //var[i].dec = binToDec(var[i].bin); //ut << var[i].name << "=" << var[i].dec << "=" << var[i].bin << endl; } int output; cin >> output; for(int i = 0 ; i < output ; i++) { string find; cin >> find; bool found = false ; for(int i = 0 ; i < v ; i++) { if(find.compare(var[i].name) == 0) { found = true; cout << find << "=" << var[i].dec << endl; break; } } if(found == false) { cout << find << "="<<endl; } } return 0; }
devibizsys/unip
srv_unip_pub/src/main/java/com/sa/unip/srv/ywsp/demodel/OA_PCSQGXCLSYKSZTLogicModel.java
/** * iBizSys 5.0 机器人生产代码(不要直接修改当前代码) * http://www.ibizsys.net */ package com.sa.unip.srv.ywsp.demodel; import java.util.List; import java.util.HashMap; import org.hibernate.Session; import org.hibernate.SessionFactory; import net.ibizsys.paas.core.Errors; import net.ibizsys.paas.core.IActionContext; import net.ibizsys.paas.data.DataObject; import net.ibizsys.paas.db.DBCallResult; import net.ibizsys.paas.db.DBFetchResult; import net.ibizsys.paas.db.IDataRow; import net.ibizsys.paas.db.IDataTable; import net.ibizsys.paas.db.SqlParamList; import net.ibizsys.paas.entity.IEntity; import net.ibizsys.paas.entity.SimpleEntity; import net.ibizsys.paas.exception.ErrorException; import net.ibizsys.paas.web.WebContext; import net.ibizsys.paas.service.ServiceGlobal; import net.ibizsys.paas.service.IService; import net.ibizsys.pswf.core.IWFModel; import net.ibizsys.paas.sysmodel.ISystemModel; import net.ibizsys.pswf.core.IWFService; import net.ibizsys.pswf.core.WFActionParam; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.sa.unip.srv.ywsp.entity.OA_PCSQ; import com.sa.unip.srv.ywsp.service.OA_PCSQService; /** * 实体[OA_PCSQ]逻辑处理[更新车辆使用开始状态]模型对象 */ public class OA_PCSQGXCLSYKSZTLogicModel extends net.ibizsys.paas.demodel.DELogicModelBase<OA_PCSQ> { private static final Log log = LogFactory.getLog(OA_PCSQGXCLSYKSZTLogicModel.class); public OA_PCSQGXCLSYKSZTLogicModel() { super(); //设置逻辑基本信息 this.setId("659CF30A-07B8-4F1B-A9E5-06348CC99B94"); this.setName("GXCLSYKSZT"); //设置默认参数名称 this.setDefaultParamName("Default"); } /* (non-Javadoc) * @see net.ibizsys.paas.demodel.DELogicModelBase#onExecute(net.ibizsys.paas.core.IActionContext) */ @Override protected void onExecute(IActionContext iActionContext) throws Exception { iActionContext.setParam("CLDX",new com.sa.unip.srv.jcsj.entity.OA_CL()); executeBegin(iActionContext); } /** * 执行逻辑处理[设置车辆使用参数] * @Param iActionContext 处理上下文参数 */ protected void executePrepareparam1(IActionContext iActionContext) throws Exception { com.sa.unip.srv.jcsj.entity.OA_CL cLDX = (com.sa.unip.srv.jcsj.entity.OA_CL)iActionContext.getParam("CLDX"); com.sa.unip.srv.ywsp.entity.OA_PCSQ _default = (com.sa.unip.srv.ywsp.entity.OA_PCSQ)iActionContext.getParam("Default"); SessionFactory sessionFactory = iActionContext.getSessionFactory(); //Default[CFSJ] ==> CLDX[SYSJ] cLDX.set("SYSJ",_default.get("CFSJ")); //Default[OA_CLID] ==> CLDX[OA_CLID] cLDX.set("OA_CLID",_default.get("OA_CLID")); //直接值[20] ==> CLDX[SYQK] cLDX.set("SYQK","20"); if(true) { executeDeaction1(iActionContext); } } /** * 执行逻辑处理[更新车辆使用开始状态] * @Param iActionContext 处理上下文参数 */ protected void executeDeaction1(IActionContext iActionContext) throws Exception { com.sa.unip.srv.jcsj.entity.OA_CL cLDX = (com.sa.unip.srv.jcsj.entity.OA_CL)iActionContext.getParam("CLDX"); com.sa.unip.srv.ywsp.entity.OA_PCSQ _default = (com.sa.unip.srv.ywsp.entity.OA_PCSQ)iActionContext.getParam("Default"); SessionFactory sessionFactory = iActionContext.getSessionFactory(); IService service = ServiceGlobal.getService(com.sa.unip.srv.jcsj.service.OA_CLService.class,sessionFactory ); service.executeAction(com.sa.unip.srv.jcsj.service.OA_CLService.ACTION_UPDATE,cLDX); } /** * 执行逻辑处理[开始] * @Param iActionContext 处理上下文参数 */ protected void executeBegin(IActionContext iActionContext) throws Exception { com.sa.unip.srv.jcsj.entity.OA_CL cLDX = (com.sa.unip.srv.jcsj.entity.OA_CL)iActionContext.getParam("CLDX"); com.sa.unip.srv.ywsp.entity.OA_PCSQ _default = (com.sa.unip.srv.ywsp.entity.OA_PCSQ)iActionContext.getParam("Default"); SessionFactory sessionFactory = iActionContext.getSessionFactory(); if(true) { executePrepareparam1(iActionContext); } } }
lechium/iPhoneOS_12.1.1_Headers
System/Library/PrivateFrameworks/SpringBoardUIServices.framework/SBUIPreciseClockTimer.h
/* * This header is generated by classdump-dyld 1.0 * on Saturday, June 1, 2019 at 6:46:26 PM Mountain Standard Time * Operating System: Version 12.1.1 (Build 16C5050a) * Image Source: /System/Library/PrivateFrameworks/SpringBoardUIServices.framework/SpringBoardUIServices * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. */ #import <SpringBoardUIServices/SpringBoardUIServices-Structs.h> @class CADisplayLink, NSMutableDictionary, NSCalendar; @interface SBUIPreciseClockTimer : NSObject { CADisplayLink* _displayLink; NSMutableDictionary* _minuteUpdateHandlers; unsigned long long _nextToken; NSCalendar* _calendar; long long _lastHour; long long _lastMinute; } +(id)now; +(id)sharedInstance; -(void)_updateDisplayLink; -(void)_handleTimePassed; -(void)_updateDisplayLinkFrameIntervalForSecondsPastMinute:(double)arg1 ; -(NSNumber*)startMinuteUpdatesWithHandler:(/*^block*/id)arg1 ; -(void)_onDisplayLink:(id)arg1 ; -(void)stopMinuteUpdatesForToken:(NSNumber*)arg1 ; -(id)init; -(void)dealloc; @end
sismics/home
home-core/src/main/java/com/sismics/util/context/ThreadLocalContext.java
<reponame>sismics/home package com.sismics.util.context; import org.skife.jdbi.v2.Handle; /** * Context associated to a user request, and stored in a ThreadLocal. * * @author jtremeaux */ public class ThreadLocalContext { /** * ThreadLocal to store the context. */ public static final ThreadLocal<ThreadLocalContext> threadLocalContext = new ThreadLocal<ThreadLocalContext>(); /** * JDBI handle. */ private Handle handle; /** * Private constructor. */ private ThreadLocalContext() { // NOP } /** * Returns an instance of this thread context. * * @return Thread local context */ public static ThreadLocalContext get() { ThreadLocalContext context = threadLocalContext.get(); if (context == null) { context = new ThreadLocalContext(); threadLocalContext.set(context); } return context; } /** * Cleans up the instance of this thread context. */ public static void cleanup() { threadLocalContext.set(null); } /** * Getter of handle. * * @return handle */ public Handle getHandle() { return handle; } /** * Setter of handle. * * @param handle handle */ public void setHandle(Handle handle) { this.handle = handle; } }
ZhnZhn/ZhnZhn.github.io
js/adapters/alpha/IntradayAdapter.js
<gh_stars>1-10 "use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); exports.__esModule = true; exports["default"] = void 0; var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends")); var _ChartConfig = _interopRequireDefault(require("../../charts/ChartConfig")); var _ConfigBuilder = _interopRequireDefault(require("../../charts/ConfigBuilder")); var _AdapterFn = _interopRequireDefault(require("../AdapterFn")); var _IntradayFns = _interopRequireDefault(require("../IntradayFns")); var _fnAdapter = _interopRequireDefault(require("./fnAdapter")); var ymdhmsToUTC = _AdapterFn["default"].ymdhmsToUTC, crVolumePoint = _AdapterFn["default"].crVolumePoint, crMarkerColor = _IntradayFns["default"].crMarkerColor, crDataDaily = _IntradayFns["default"].crDataDaily, crIntradayConfigOption = _fnAdapter["default"].crIntradayConfigOption; var INTRADAY = 'INTRADAY'; var DAILY_ADJUSTED = 'DAILY_ADJUSTED'; var _getKeys = Object.keys; var _crSeriaOptions = function _crSeriaOptions(_ref, dfT) { var isFilterZero = _ref.isFilterZero; var _isAdjusted = dfT === DAILY_ADJUSTED; return { notFilterZero: !isFilterZero, isDividend: _isAdjusted, toUTC: ymdhmsToUTC, pnClose: _isAdjusted ? '5. adjusted close' : '4. close', pnVolume: _isAdjusted ? '6. volume' : '5. volume' }; }; var PN_DIVIDENT = '7. dividend amount'; var PN_ADJ_CLOSE = '5. adjusted close'; var _addDividendPointTo = function _addDividendPointTo(arr, dateMs, p) { var _strDivident = p[PN_DIVIDENT], _exValue = _strDivident && parseFloat(_strDivident); if (_exValue) { arr.push((0, _extends2["default"])({}, _ChartConfig["default"].crMarkerExDividend(), { x: dateMs, exValue: _exValue, price: parseFloat(p[PN_ADJ_CLOSE]) })); } }; var _notZeros = function _notZeros(v1, v2) { return v1 !== 0 && v2 !== 0; }; var _getObjValues = function _getObjValues(json, option) { var interval = option.interval, _propName = "Time Series (" + interval + ")"; return json[_propName]; }; var _crSeriaData = function _crSeriaData(json, option, dfT) { var _objValues = _getObjValues(json, option), _dateKeys = _objValues ? _getKeys(_objValues).sort() : [], dC = [], dH = [], dL = [], dO = [], dDividend = [], dVc = [], dV = [], _crSeriaOptions2 = _crSeriaOptions(option, dfT), notFilterZero = _crSeriaOptions2.notFilterZero, isDividend = _crSeriaOptions2.isDividend, toUTC = _crSeriaOptions2.toUTC, pnClose = _crSeriaOptions2.pnClose, pnVolume = _crSeriaOptions2.pnVolume; var i = 0, _max = _dateKeys.length, minClose = Number.POSITIVE_INFINITY, maxClose = Number.NEGATIVE_INFINITY, _dateMs, _date, _point, _open, _high, _low, _closeV, _close, _volume; for (i; i < _max; i++) { _date = _dateKeys[i]; _point = _objValues[_date]; _closeV = parseFloat(_point['4. close']); _close = parseFloat(_point[pnClose]); if (notFilterZero || _notZeros(_closeV, _close)) { _open = parseFloat(_point['1. open']); _high = parseFloat(_point['2. high']); _low = parseFloat(_point['3. low']); _volume = parseFloat(_point[pnVolume]); _dateMs = toUTC(_date); dC.push((0, _extends2["default"])({ x: _dateMs, y: _close }, crMarkerColor(_date))); dH.push([_dateMs, _high]); dL.push([_dateMs, _low]); dO.push([_dateMs, _open]); dV.push([_dateMs, _volume]); dVc.push(crVolumePoint({ open: _open, close: _closeV, volume: _volume, date: _dateMs, option: { _high: _high, _low: _low } })); if (isDividend) { _addDividendPointTo(dDividend, _dateMs, _point); } if (minClose > _close) { minClose = _close; } if (maxClose < _close) { maxClose = _close; } } } return { dC: dC, dH: dH, dL: dL, dO: dO, dDividend: dDividend, minClose: minClose, maxClose: maxClose, dVc: dVc, dV: dV }; }; var _crDataDaily = function _crDataDaily(dfT, data) { return dfT === INTRADAY ? crDataDaily(data) : data; }; var IntradayAdapter = { crKey: function crKey(_ref2) { var _itemKey = _ref2._itemKey; return _itemKey; }, toConfig: function toConfig(json, option) { var _itemKey = option._itemKey, title = option.title, dfFn = option.dfFn, dataSource = option.dataSource, isNotZoomToMinMax = option.isNotZoomToMinMax, isDrawDeltaExtrems = option.isDrawDeltaExtrems, seriaType = option.seriaType, seriaColor = option.seriaColor, seriaWidth = option.seriaWidth, dfT = dfFn.replace('TIME_SERIES_', ''), _crSeriaData2 = _crSeriaData(json, option, dfT), dC = _crSeriaData2.dC, dH = _crSeriaData2.dH, dL = _crSeriaData2.dL, dO = _crSeriaData2.dO, minClose = _crSeriaData2.minClose, maxClose = _crSeriaData2.maxClose, dDividend = _crSeriaData2.dDividend, dVc = _crSeriaData2.dVc, dV = _crSeriaData2.dV, dataDaily = _crDataDaily(dfT, dC); var config = (0, _ConfigBuilder["default"])().stockConfig(_itemKey, { dC: dC, dO: dO, dH: dH, dL: dL, minClose: minClose, maxClose: maxClose, dVc: dVc, dV: dV, isNotZoomToMinMax: isNotZoomToMinMax, isDrawDeltaExtrems: isDrawDeltaExtrems, seriaType: seriaType, seriaColor: seriaColor, seriaWidth: seriaWidth }).addCaption(title).add(crIntradayConfigOption({ id: _itemKey, data: dataDaily, dataSource: dataSource }, option)).addDividend(dDividend, minClose, maxClose).toConfig(); return { config: config }; }, toSeries: function toSeries(json, option) { return _ConfigBuilder["default"].crSeria({ adapter: IntradayAdapter, json: json, option: option, type: 'line' }); } }; var _default = IntradayAdapter; exports["default"] = _default; //# sourceMappingURL=IntradayAdapter.js.map
chuckmersereau/api_practice
spec/acceptance/api/v2/appeals/appeal_contacts_spec.rb
<reponame>chuckmersereau/api_practice<filename>spec/acceptance/api/v2/appeals/appeal_contacts_spec.rb require 'rails_helper' require 'rspec_api_documentation/dsl' resource 'Appeals > AppealContacts' do include_context :json_headers documentation_scope = :appeals_api_appeal_contacts let(:resource_type) { 'appeal_contacts' } let!(:user) { create(:user_with_full_account) } let!(:account_list) { user.account_lists.order(:created_at).first } let(:account_list_id) { account_list.id } let!(:appeal) { create(:appeal, account_list: account_list) } let(:appeal_id) { appeal.id } let!(:contact) { create(:contact, account_list: account_list) } let!(:new_contact) { create(:contact, account_list: account_list) } let!(:appeal_contact) { create(:appeal_contact, appeal: appeal, contact: contact) } let(:id) { appeal_contact.id } let(:resource_attributes) do %w( created_at updated_at updated_in_db_at ) end let(:resource_associations) do %w( contact appeal ) end context 'authorized user' do before do api_login(user) end get '/api/v2/appeals/:appeal_id/appeal_contacts' do with_options scope: :filter do parameter 'account_list_id', 'Account List ID', type: 'String' parameter 'pledged_to_appeal', 'has contact has pledged to appeal? Accepts value "true" or "false"', required: false, type: 'String' end with_options scope: :sort do parameter 'contact.name', 'Sort by Contact Name', type: 'String' end response_field 'data', 'Data', type: 'Array[Object]' example 'AppealContact [LIST]', document: documentation_scope do explanation 'List of Contacts associated to the Appeal' do_request check_collection_resource(1, %w(relationships)) expect(response_status).to eq 200 end end post 'api/v2/appeals/:appeal_id/appeal_contacts' do let(:relationships) do { contact: { data: { type: 'contacts', id: new_contact.id } } } end let!(:form_data) { build_data(attributes_for(:appeal_contact, appeal: appeal), relationships: relationships) } example 'AppealContact [POST]', document: documentation_scope do explanation 'Add a contact to an Appeal' do_request data: form_data check_resource(%w(relationships)) expect(response_status).to eq 200 end end get '/api/v2/appeals/:appeal_id/appeal_contacts/:id' do with_options scope: [:data, :attributes] do end example 'AppealContact [GET]', document: documentation_scope do explanation 'The Appeal Contact with the given ID' do_request check_resource(%w(relationships)) expect(response_status).to eq 200 end end delete '/api/v2/appeals/:appeal_id/appeal_contacts/:id' do parameter 'id', 'ID', required: true example 'AppealContact [DELETE]', document: documentation_scope do explanation 'Remove the Contact with the given ID from the Appeal' do_request expect(response_status).to eq 204 end end end end
Skepton/Neon
modules/database/database/schemas/models/post/index.js
var Sequelize = require('sequelize'), moment = require('moment'); module.exports.name = 'post'; module.exports.init = function(sequelize){ var Post = sequelize.define('post', { id: { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true }, hashid: { type: Sequelize.STRING, unique: true }, headline: { type: Sequelize.STRING }, header: { type: Sequelize.STRING }, body: { type: Sequelize.TEXT }, published: { type: Sequelize.BOOLEAN, defaultValue: false }, source: { type: Sequelize.STRING(1024) }, tags: { type: Sequelize.STRING(1024) }, slug: { type: Sequelize.STRING, unique: true } }, { getterMethods: { postDate: function(){ return moment(this.updatedAt).format(); }, fromDate: function(){ return moment(this.updatedAt).fromNow(); } } }); Post.associate = function(models){ Post.belongsTo(models.user, {as: 'author', foreignKey: 'userId'}); Post.belongsTo(models.category, {as: 'category'}); Post.addHook('beforeFind', function(options){ options.include = [{model: models.user, as: 'author', attributes: {exclude: ['password','updatedAt']}},{model: models.category, as: 'category'}]; return options; }); } return Post; }
LiamTyler/AudioEngine
ext/libsndfile/src/GSM610/gsm_encode.c
/* * Copyright 1992 by <NAME> and <NAME>, Technische * Universitaet Berlin. See the accompanying file "COPYRIGHT" for * details. THERE IS ABSOLUTELY NO WARRANTY FOR THIS SOFTWARE. */ #include "gsm610_priv.h" #include "gsm.h" void gsm_encode (gsm s, gsm_signal * source, gsm_byte * c) { int16_t LARc [8], Nc [4], Mc [4], bc [4], xmaxc [4], xmc [13 * 4] ; Gsm_Coder (s, source, LARc, Nc, bc, Mc, xmaxc, xmc) ; /* variable size GSM_MAGIC 4 LARc [0] 6 LARc [1] 6 LARc [2] 5 LARc [3] 5 LARc [4] 4 LARc [5] 4 LARc [6] 3 LARc [7] 3 Nc [0] 7 bc [0] 2 Mc [0] 2 xmaxc [0] 6 xmc [0] 3 xmc [1] 3 xmc [2] 3 xmc [3] 3 xmc [4] 3 xmc [5] 3 xmc [6] 3 xmc [7] 3 xmc [8] 3 xmc [9] 3 xmc [10] 3 xmc [11] 3 xmc [12] 3 Nc [1] 7 bc [1] 2 Mc [1] 2 xmaxc [1] 6 xmc [13] 3 xmc [14] 3 xmc [15] 3 xmc [16] 3 xmc [17] 3 xmc [18] 3 xmc [19] 3 xmc [20] 3 xmc [21] 3 xmc [22] 3 xmc [23] 3 xmc [24] 3 xmc [25] 3 Nc [2] 7 bc [2] 2 Mc [2] 2 xmaxc [2] 6 xmc [26] 3 xmc [27] 3 xmc [28] 3 xmc [29] 3 xmc [30] 3 xmc [31] 3 xmc [32] 3 xmc [33] 3 xmc [34] 3 xmc [35] 3 xmc [36] 3 xmc [37] 3 xmc [38] 3 Nc [3] 7 bc [3] 2 Mc [3] 2 xmaxc [3] 6 xmc [39] 3 xmc [40] 3 xmc [41] 3 xmc [42] 3 xmc [43] 3 xmc [44] 3 xmc [45] 3 xmc [46] 3 xmc [47] 3 xmc [48] 3 xmc [49] 3 xmc [50] 3 xmc [51] 3 */ #ifdef WAV49 if (s->wav_fmt) { s->frame_index = !s->frame_index ; if (s->frame_index) { uint16_t sr ; sr = 0 ; sr = sr >> 6 | LARc [0] << 10 ; sr = sr >> 6 | LARc [1] << 10 ; *c++ = sr >> 4 ; sr = sr >> 5 | LARc [2] << 11 ; *c++ = sr >> 7 ; sr = sr >> 5 | LARc [3] << 11 ; sr = sr >> 4 | LARc [4] << 12 ; *c++ = sr >> 6 ; sr = sr >> 4 | LARc [5] << 12 ; sr = sr >> 3 | LARc [6] << 13 ; *c++ = sr >> 7 ; sr = sr >> 3 | LARc [7] << 13 ; sr = sr >> 7 | Nc [0] << 9 ; *c++ = sr >> 5 ; sr = sr >> 2 | bc [0] << 14 ; sr = sr >> 2 | Mc [0] << 14 ; sr = sr >> 6 | xmaxc [0] << 10 ; *c++ = sr >> 3 ; sr = sr >> 3 | xmc [0] << 13 ; *c++ = sr >> 8 ; sr = sr >> 3 | xmc [1] << 13 ; sr = sr >> 3 | xmc [2] << 13 ; sr = sr >> 3 | xmc [3] << 13 ; *c++ = sr >> 7 ; sr = sr >> 3 | xmc [4] << 13 ; sr = sr >> 3 | xmc [5] << 13 ; sr = sr >> 3 | xmc [6] << 13 ; *c++ = sr >> 6 ; sr = sr >> 3 | xmc [7] << 13 ; sr = sr >> 3 | xmc [8] << 13 ; *c++ = sr >> 8 ; sr = sr >> 3 | xmc [9] << 13 ; sr = sr >> 3 | xmc [10] << 13 ; sr = sr >> 3 | xmc [11] << 13 ; *c++ = sr >> 7 ; sr = sr >> 3 | xmc [12] << 13 ; sr = sr >> 7 | Nc [1] << 9 ; *c++ = sr >> 5 ; sr = sr >> 2 | bc [1] << 14 ; sr = sr >> 2 | Mc [1] << 14 ; sr = sr >> 6 | xmaxc [1] << 10 ; *c++ = sr >> 3 ; sr = sr >> 3 | xmc [13] << 13 ; *c++ = sr >> 8 ; sr = sr >> 3 | xmc [14] << 13 ; sr = sr >> 3 | xmc [15] << 13 ; sr = sr >> 3 | xmc [16] << 13 ; *c++ = sr >> 7 ; sr = sr >> 3 | xmc [17] << 13 ; sr = sr >> 3 | xmc [18] << 13 ; sr = sr >> 3 | xmc [19] << 13 ; *c++ = sr >> 6 ; sr = sr >> 3 | xmc [20] << 13 ; sr = sr >> 3 | xmc [21] << 13 ; *c++ = sr >> 8 ; sr = sr >> 3 | xmc [22] << 13 ; sr = sr >> 3 | xmc [23] << 13 ; sr = sr >> 3 | xmc [24] << 13 ; *c++ = sr >> 7 ; sr = sr >> 3 | xmc [25] << 13 ; sr = sr >> 7 | Nc [2] << 9 ; *c++ = sr >> 5 ; sr = sr >> 2 | bc [2] << 14 ; sr = sr >> 2 | Mc [2] << 14 ; sr = sr >> 6 | xmaxc [2] << 10 ; *c++ = sr >> 3 ; sr = sr >> 3 | xmc [26] << 13 ; *c++ = sr >> 8 ; sr = sr >> 3 | xmc [27] << 13 ; sr = sr >> 3 | xmc [28] << 13 ; sr = sr >> 3 | xmc [29] << 13 ; *c++ = sr >> 7 ; sr = sr >> 3 | xmc [30] << 13 ; sr = sr >> 3 | xmc [31] << 13 ; sr = sr >> 3 | xmc [32] << 13 ; *c++ = sr >> 6 ; sr = sr >> 3 | xmc [33] << 13 ; sr = sr >> 3 | xmc [34] << 13 ; *c++ = sr >> 8 ; sr = sr >> 3 | xmc [35] << 13 ; sr = sr >> 3 | xmc [36] << 13 ; sr = sr >> 3 | xmc [37] << 13 ; *c++ = sr >> 7 ; sr = sr >> 3 | xmc [38] << 13 ; sr = sr >> 7 | Nc [3] << 9 ; *c++ = sr >> 5 ; sr = sr >> 2 | bc [3] << 14 ; sr = sr >> 2 | Mc [3] << 14 ; sr = sr >> 6 | xmaxc [3] << 10 ; *c++ = sr >> 3 ; sr = sr >> 3 | xmc [39] << 13 ; *c++ = sr >> 8 ; sr = sr >> 3 | xmc [40] << 13 ; sr = sr >> 3 | xmc [41] << 13 ; sr = sr >> 3 | xmc [42] << 13 ; *c++ = sr >> 7 ; sr = sr >> 3 | xmc [43] << 13 ; sr = sr >> 3 | xmc [44] << 13 ; sr = sr >> 3 | xmc [45] << 13 ; *c++ = sr >> 6 ; sr = sr >> 3 | xmc [46] << 13 ; sr = sr >> 3 | xmc [47] << 13 ; *c++ = sr >> 8 ; sr = sr >> 3 | xmc [48] << 13 ; sr = sr >> 3 | xmc [49] << 13 ; sr = sr >> 3 | xmc [50] << 13 ; *c++ = sr >> 7 ; sr = sr >> 3 | xmc [51] << 13 ; sr = sr >> 4 ; *c = sr >> 8 ; s->frame_chain = *c ; } else { uint16_t sr ; sr = 0 ; sr = sr >> 4 | s->frame_chain << 12 ; sr = sr >> 6 | LARc [0] << 10 ; *c++ = sr >> 6 ; sr = sr >> 6 | LARc [1] << 10 ; *c++ = sr >> 8 ; sr = sr >> 5 | LARc [2] << 11 ; sr = sr >> 5 | LARc [3] << 11 ; *c++ = sr >> 6 ; sr = sr >> 4 | LARc [4] << 12 ; sr = sr >> 4 | LARc [5] << 12 ; *c++ = sr >> 6 ; sr = sr >> 3 | LARc [6] << 13 ; sr = sr >> 3 | LARc [7] << 13 ; *c++ = sr >> 8 ; sr = sr >> 7 | Nc [0] << 9 ; sr = sr >> 2 | bc [0] << 14 ; *c++ = sr >> 7 ; sr = sr >> 2 | Mc [0] << 14 ; sr = sr >> 6 | xmaxc [0] << 10 ; *c++ = sr >> 7 ; sr = sr >> 3 | xmc [0] << 13 ; sr = sr >> 3 | xmc [1] << 13 ; sr = sr >> 3 | xmc [2] << 13 ; *c++ = sr >> 6 ; sr = sr >> 3 | xmc [3] << 13 ; sr = sr >> 3 | xmc [4] << 13 ; *c++ = sr >> 8 ; sr = sr >> 3 | xmc [5] << 13 ; sr = sr >> 3 | xmc [6] << 13 ; sr = sr >> 3 | xmc [7] << 13 ; *c++ = sr >> 7 ; sr = sr >> 3 | xmc [8] << 13 ; sr = sr >> 3 | xmc [9] << 13 ; sr = sr >> 3 | xmc [10] << 13 ; *c++ = sr >> 6 ; sr = sr >> 3 | xmc [11] << 13 ; sr = sr >> 3 | xmc [12] << 13 ; *c++ = sr >> 8 ; sr = sr >> 7 | Nc [1] << 9 ; sr = sr >> 2 | bc [1] << 14 ; *c++ = sr >> 7 ; sr = sr >> 2 | Mc [1] << 14 ; sr = sr >> 6 | xmaxc [1] << 10 ; *c++ = sr >> 7 ; sr = sr >> 3 | xmc [13] << 13 ; sr = sr >> 3 | xmc [14] << 13 ; sr = sr >> 3 | xmc [15] << 13 ; *c++ = sr >> 6 ; sr = sr >> 3 | xmc [16] << 13 ; sr = sr >> 3 | xmc [17] << 13 ; *c++ = sr >> 8 ; sr = sr >> 3 | xmc [18] << 13 ; sr = sr >> 3 | xmc [19] << 13 ; sr = sr >> 3 | xmc [20] << 13 ; *c++ = sr >> 7 ; sr = sr >> 3 | xmc [21] << 13 ; sr = sr >> 3 | xmc [22] << 13 ; sr = sr >> 3 | xmc [23] << 13 ; *c++ = sr >> 6 ; sr = sr >> 3 | xmc [24] << 13 ; sr = sr >> 3 | xmc [25] << 13 ; *c++ = sr >> 8 ; sr = sr >> 7 | Nc [2] << 9 ; sr = sr >> 2 | bc [2] << 14 ; *c++ = sr >> 7 ; sr = sr >> 2 | Mc [2] << 14 ; sr = sr >> 6 | xmaxc [2] << 10 ; *c++ = sr >> 7 ; sr = sr >> 3 | xmc [26] << 13 ; sr = sr >> 3 | xmc [27] << 13 ; sr = sr >> 3 | xmc [28] << 13 ; *c++ = sr >> 6 ; sr = sr >> 3 | xmc [29] << 13 ; sr = sr >> 3 | xmc [30] << 13 ; *c++ = sr >> 8 ; sr = sr >> 3 | xmc [31] << 13 ; sr = sr >> 3 | xmc [32] << 13 ; sr = sr >> 3 | xmc [33] << 13 ; *c++ = sr >> 7 ; sr = sr >> 3 | xmc [34] << 13 ; sr = sr >> 3 | xmc [35] << 13 ; sr = sr >> 3 | xmc [36] << 13 ; *c++ = sr >> 6 ; sr = sr >> 3 | xmc [37] << 13 ; sr = sr >> 3 | xmc [38] << 13 ; *c++ = sr >> 8 ; sr = sr >> 7 | Nc [3] << 9 ; sr = sr >> 2 | bc [3] << 14 ; *c++ = sr >> 7 ; sr = sr >> 2 | Mc [3] << 14 ; sr = sr >> 6 | xmaxc [3] << 10 ; *c++ = sr >> 7 ; sr = sr >> 3 | xmc [39] << 13 ; sr = sr >> 3 | xmc [40] << 13 ; sr = sr >> 3 | xmc [41] << 13 ; *c++ = sr >> 6 ; sr = sr >> 3 | xmc [42] << 13 ; sr = sr >> 3 | xmc [43] << 13 ; *c++ = sr >> 8 ; sr = sr >> 3 | xmc [44] << 13 ; sr = sr >> 3 | xmc [45] << 13 ; sr = sr >> 3 | xmc [46] << 13 ; *c++ = sr >> 7 ; sr = sr >> 3 | xmc [47] << 13 ; sr = sr >> 3 | xmc [48] << 13 ; sr = sr >> 3 | xmc [49] << 13 ; *c++ = sr >> 6 ; sr = sr >> 3 | xmc [50] << 13 ; sr = sr >> 3 | xmc [51] << 13 ; *c++ = sr >> 8 ; } } else #endif /* WAV49 */ { *c++ = ((GSM_MAGIC & 0xF) << 4) /* 1 */ | ((LARc [0] >> 2) & 0xF) ; *c++ = ((LARc [0] & 0x3) << 6) | (LARc [1] & 0x3F) ; *c++ = ((LARc [2] & 0x1F) << 3) | ((LARc [3] >> 2) & 0x7) ; *c++ = ((LARc [3] & 0x3) << 6) | ((LARc [4] & 0xF) << 2) | ((LARc [5] >> 2) & 0x3) ; *c++ = ((LARc [5] & 0x3) << 6) | ((LARc [6] & 0x7) << 3) | (LARc [7] & 0x7) ; *c++ = ((Nc [0] & 0x7F) << 1) | ((bc [0] >> 1) & 0x1) ; *c++ = ((bc [0] & 0x1) << 7) | ((Mc [0] & 0x3) << 5) | ((xmaxc [0] >> 1) & 0x1F) ; *c++ = ((xmaxc [0] & 0x1) << 7) | ((xmc [0] & 0x7) << 4) | ((xmc [1] & 0x7) << 1) | ((xmc [2] >> 2) & 0x1) ; *c++ = ((xmc [2] & 0x3) << 6) | ((xmc [3] & 0x7) << 3) | (xmc [4] & 0x7) ; *c++ = ((xmc [5] & 0x7) << 5) /* 10 */ | ((xmc [6] & 0x7) << 2) | ((xmc [7] >> 1) & 0x3) ; *c++ = ((xmc [7] & 0x1) << 7) | ((xmc [8] & 0x7) << 4) | ((xmc [9] & 0x7) << 1) | ((xmc [10] >> 2) & 0x1) ; *c++ = ((xmc [10] & 0x3) << 6) | ((xmc [11] & 0x7) << 3) | (xmc [12] & 0x7) ; *c++ = ((Nc [1] & 0x7F) << 1) | ((bc [1] >> 1) & 0x1) ; *c++ = ((bc [1] & 0x1) << 7) | ((Mc [1] & 0x3) << 5) | ((xmaxc [1] >> 1) & 0x1F) ; *c++ = ((xmaxc [1] & 0x1) << 7) | ((xmc [13] & 0x7) << 4) | ((xmc [14] & 0x7) << 1) | ((xmc [15] >> 2) & 0x1) ; *c++ = ((xmc [15] & 0x3) << 6) | ((xmc [16] & 0x7) << 3) | (xmc [17] & 0x7) ; *c++ = ((xmc [18] & 0x7) << 5) | ((xmc [19] & 0x7) << 2) | ((xmc [20] >> 1) & 0x3) ; *c++ = ((xmc [20] & 0x1) << 7) | ((xmc [21] & 0x7) << 4) | ((xmc [22] & 0x7) << 1) | ((xmc [23] >> 2) & 0x1) ; *c++ = ((xmc [23] & 0x3) << 6) | ((xmc [24] & 0x7) << 3) | (xmc [25] & 0x7) ; *c++ = ((Nc [2] & 0x7F) << 1) /* 20 */ | ((bc [2] >> 1) & 0x1) ; *c++ = ((bc [2] & 0x1) << 7) | ((Mc [2] & 0x3) << 5) | ((xmaxc [2] >> 1) & 0x1F) ; *c++ = ((xmaxc [2] & 0x1) << 7) | ((xmc [26] & 0x7) << 4) | ((xmc [27] & 0x7) << 1) | ((xmc [28] >> 2) & 0x1) ; *c++ = ((xmc [28] & 0x3) << 6) | ((xmc [29] & 0x7) << 3) | (xmc [30] & 0x7) ; *c++ = ((xmc [31] & 0x7) << 5) | ((xmc [32] & 0x7) << 2) | ((xmc [33] >> 1) & 0x3) ; *c++ = ((xmc [33] & 0x1) << 7) | ((xmc [34] & 0x7) << 4) | ((xmc [35] & 0x7) << 1) | ((xmc [36] >> 2) & 0x1) ; *c++ = ((xmc [36] & 0x3) << 6) | ((xmc [37] & 0x7) << 3) | (xmc [38] & 0x7) ; *c++ = ((Nc [3] & 0x7F) << 1) | ((bc [3] >> 1) & 0x1) ; *c++ = ((bc [3] & 0x1) << 7) | ((Mc [3] & 0x3) << 5) | ((xmaxc [3] >> 1) & 0x1F) ; *c++ = ((xmaxc [3] & 0x1) << 7) | ((xmc [39] & 0x7) << 4) | ((xmc [40] & 0x7) << 1) | ((xmc [41] >> 2) & 0x1) ; *c++ = ((xmc [41] & 0x3) << 6) /* 30 */ | ((xmc [42] & 0x7) << 3) | (xmc [43] & 0x7) ; *c++ = ((xmc [44] & 0x7) << 5) | ((xmc [45] & 0x7) << 2) | ((xmc [46] >> 1) & 0x3) ; *c++ = ((xmc [46] & 0x1) << 7) | ((xmc [47] & 0x7) << 4) | ((xmc [48] & 0x7) << 1) | ((xmc [49] >> 2) & 0x1) ; *c++ = ((xmc [49] & 0x3) << 6) | ((xmc [50] & 0x7) << 3) | (xmc [51] & 0x7) ; } }
DXShelley/document
java-demo/src/main/java/com/fishion/demo/base/io/zip/ReadZipFile.java
package com.fishion.demo.base.io.zip; import java.io.IOException; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; /** * @author : yuzq * @version V1.0 * @Description: TODO * @date Date : 2019年04月22日 11:40 */ public class ReadZipFile { private static void read(String zipFilePath) { try { ZipFile zipFile = new ZipFile(zipFilePath); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); String name = entry.getName(); long compressedSize = entry.getCompressedSize(); long normalSize = entry.getSize(); String type = entry.isDirectory() ? "DIR" : "FILE"; System.out.println(name); System.out.format("\t %s - %d - %d\n", type, compressedSize, normalSize); } zipFile.close(); } catch (IOException ex) { System.err.println(ex); } } public static void main(String[] args) { String zipFilePath = "F:\\tmp\\demo\\sunway-app-casic201.zip"; read(zipFilePath); } }
cponcelets/savior-source
svf/SVF/tests/micro-benchmarks/basic_pointer_test/struct/ben1.c
struct agg{ int* f; int *g; }agg; int main(){ int a1, b1,c1; int *a, *b,*c; struct agg agg1[100]; a = &a1; b = &b1; agg1[1].f = a; agg1[1].g = b; //agg1[0].f = &c; }
qinFamily/freeVM
enhanced/buildtest/tests/tools/harness/org/apache/harmony/harness/plugins/variationtests/FileSet.java
/* Copyright 2005-2006 The Apache Software Foundation or its licensors, as applicable Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** * @author <NAME> * @version $Revision: 1.5 $ */ package org.apache.harmony.harness.plugins.variationtests; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FilenameFilter; import java.io.IOException; import java.util.ArrayList; import java.util.Enumeration; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Used to produce an enumeration of files from a list of directories, files * and, optionally, filename filters. */ public class FileSet extends AbstractVariation { Vector files; public Enumeration getVariants() { return files.elements(); } /** * Usage: FileSet -var <varName>-title <Title><sequence>* where the * sequence is one of the following: [-filter <regexp>] -baseDir <dir> * -fileList <file>[-filter <regexp>] -dir <dir>[-baseDir <dir>] -file * <file>[-baseDir <dir>] -files <file><file>... (this sequence is always * the last one) */ public String[] setup(String[] args) throws SetupException { String baseDir = null; String filter = null; ArrayList tail = new ArrayList(); args = super.setup(args); files = new Vector(); boolean filesAdded = false; for (int i = 0; i < args.length; i++) { if (args[i].equalsIgnoreCase("-dir")) { if (++i >= args.length) { throw new SetupException("Option -dir without value"); } addDir(args[i], filter); filesAdded = true; } else if (args[i].equalsIgnoreCase("-filter")) { if (++i >= args.length) { throw new SetupException("Option -filter without value"); } filter = args[i]; } else if (args[i].equalsIgnoreCase("-baseDir")) { if (++i >= args.length) { throw new SetupException("Option -baseDir without value"); } baseDir = args[i]; } else if (args[i].equalsIgnoreCase("-fileList")) { if (++i >= args.length) { throw new SetupException("Option -fileList without value"); } addFileList(baseDir, args[i], filter); filesAdded = true; } else if (args[i].equalsIgnoreCase("-file")) { if (++i >= args.length) { throw new SetupException("Option -file without value"); } addFile(baseDir, args[i]); filesAdded = true; } else if (args[i].equalsIgnoreCase("-files")) { if (++i >= args.length) { throw new SetupException("Option -files without a value"); } filesAdded = true; for (; i < args.length; ++i) { addFile(baseDir, args[i]); } } else { tail.add(args[i]); } } if (!filesAdded) { throw new SetupException( "neither -dir nor -fileList nor -file option is specified"); } return Util.toStringArr(tail); } public void addFile(File f) { if (f.exists()) { files.add(new ScalarValue(this, f.getName(), new FileWrapper(f))); } } public void addFileList(String dir, String fileList, String filter) throws SetupException { File d; // use the specified directory as the base // for the files in the list if their // paths are relative, Otherwise use the // directory of the list file if (dir != null) { d = new File(dir); } else { d = new File(fileList); String parent = d.getParent(); d = new File(parent == null ? "" : parent); } try { BufferedReader reader = new BufferedReader(new FileReader(fileList)); String line; while (null != (line = reader.readLine())) { if (line.length() != 0 && line.charAt(0) != '#') { // skip comments or empty lines addFile(new File(d, line)); } } reader.close(); } catch (FileNotFoundException e) { throw new SetupException(e.toString()); } catch (IOException e) { throw new SetupException(e.toString()); } } public void addFile(String fileName) { addFile(new File(fileName)); } public void addFile(String baseDir, String fileName) { addFile(new File(baseDir, fileName)); } public void addDir(String dirName, String filter) { File d = new File(dirName); WildCard wc = new WildCard(filter); if (d.exists()) { File[] fls = d.listFiles(wc); for (int i = 0; i < fls.length; i++) { files.add(new ScalarValue(this, fls[i].getName() + "(" + fls[i].length() + ")", new FileWrapper(fls[i]))); } } } public String getTitle() { return title; } public String getVar() { return var; } } class WildCard implements FilenameFilter { Pattern p; public WildCard(String template) { if (template == null) { // Default - all files template = ".*"; } p = Pattern.compile(template); } public boolean accept(File dir, String name) { Matcher m = p.matcher(name); return m.matches(); } }
nakhodkin/marko
packages/marko/test/markoc/index.test.js
"use strict"; require("../__util__/test-init"); var chai = require("chai"); chai.config.includeStack = true; require("../../compiler"); // TODO: currently this causes babel to recompile the compiler multiple times. // We should fix this since it makes the tests very slow. // var autotest = require("mocha-autotest").default; // var markocPath = require.resolve("../../bin/markoc"); // var childProcess = require("child_process"); // var fs = require("fs"); // autotest("fixtures", fixture => { // let test = fixture.test; // let dir = fixture.dir; // let resolve = fixture.resolve; // test(function(done) { // this.timeout(20000); // const testModule = require(resolve("test.js")); // const helpers = {}; // helpers.existsSync = function(filename) { // return fs.existsSync(resolve(filename)); // }; // helpers.readSync = function(filename) { // return fs.readFileSync(resolve(filename)); // }; // helpers.spawnSync = function(args, options) { // options = options || {}; // if (!options.cwd) { // options.cwd = dir; // } // options.env = Object.create(process.env || options.env); // options.env.NODE_OPTIONS = `-r ${JSON.stringify( // require.resolve("./babel-register") // )}`; // return childProcess.spawnSync(markocPath, args, options); // }; // helpers.spawnSync([".", "--clean"]); // testModule.test(helpers); // done(); // }); // });
bhuvanmalik007/mission-admission
src/connectors/userinfo.js
import React from 'react' import PropTypes from 'prop-types' import { Panel, PanelType } from 'office-ui-fabric-react/lib/Panel' import { pick } from 'ramda' import { connect } from 'react-redux' import Box from 'grommet/components/Box' import Heading from 'grommet/components/Heading' import { Persona, PersonaSize } from 'office-ui-fabric-react/lib/Persona' import { PrimaryButton } from 'office-ui-fabric-react/lib/Button' import styled from 'styled-components' import Anchor from 'grommet/components/Anchor' const VocabDBButton = styled(PrimaryButton)` width: 300px; background-color: #865cd6 !important; &:focus{ background-color: #501eb4 !important; } ` const mail = () => window.open('mailTo:<EMAIL>', '_self') const UserInfoPanel = props => <Panel isOpen={props.infoOpen} type={PanelType.smallFluid} onDismiss={() => props.closeInfo()} > {props.profile && <Box full justify='center' align='center'> <Heading>Give us a shout, we'll be listening</Heading> <Heading tag='h3' margin='large'>Send us feedback at <Anchor onClick={mail}><EMAIL></Anchor></Heading> <Persona imageUrl={props.profile && props.profile.picture} size={PersonaSize.extraLarge} /> <Heading>{props.profile.nickname}</Heading> <VocabDBButton text='Logout' onClick={() => props.logout()} /> </Box>} </Panel> UserInfoPanel.propTypes = { infoOpen: PropTypes.bool, closeInfo: PropTypes.func, profile: PropTypes.object, logout: PropTypes.func } const md2p = dispatch => ({ closeInfo: () => dispatch({ type: 'CLOSEINFO' }), logout: () => { dispatch({ type: 'CLOSEINFO' }) dispatch({ type: 'UNPROTECTED' }) } }) const ms2p = state => ({ ...pick(['infoOpen'], state.userInfo), ...pick(['profile'], state.core) }) export default connect(ms2p, md2p)(UserInfoPanel)
kemijibola/untappedapiv2
build/controllers/MediaController.js
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; Object.defineProperty(exports, "__esModule", { value: true }); var decorators_1 = require("../decorators"); var MediaBusiness = require("../app/business/MediaBusiness"); var interfaces_1 = require("../app/models/interfaces"); var error_1 = require("../utils/error"); var auth_1 = require("../middlewares/auth"); var ValidateRequest_1 = require("../middlewares/ValidateRequest"); var PermissionConstant_1 = require("../utils/lib/PermissionConstant"); var MediaController = /** @class */ (function () { function MediaController() { } MediaController.prototype.update = function (req, res, next) { return __awaiter(this, void 0, void 0, function () { var uploadType, mediaType, systemMediaTypes, update, mediaBusiness, result, err_1; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); uploadType = ""; if (req.body.items) { uploadType = req.body.items.length > 1 ? "multiple" : "single"; } mediaType = req.body.mediaType.toLowerCase(); systemMediaTypes = Object.values(interfaces_1.MediaType); if (!systemMediaTypes.includes(mediaType)) { return [2 /*return*/, next(new error_1.PlatformError({ code: 400, message: "Invalid mediaType", }))]; } req.body.uploadType = uploadType; req.body.mediaType = mediaType; update = req.body; update.user = req.user; mediaBusiness = new MediaBusiness(); return [4 /*yield*/, mediaBusiness.update(req.params.id, update)]; case 1: result = _a.sent(); if (result.error) { return [2 /*return*/, next(new error_1.PlatformError({ code: result.responseCode, message: result.error, }))]; } return [2 /*return*/, res.status(result.responseCode).json({ message: "Operation successful", data: result.data, })]; case 2: err_1 = _a.sent(); console.log(err_1); return [2 /*return*/, next(new error_1.PlatformError({ code: 500, message: "Internal Server error occured. Please try again later.", }))]; case 3: return [2 /*return*/]; } }); }); }; MediaController.prototype.patchMedia = function (req, res, next) { return __awaiter(this, void 0, void 0, function () { var updateObj, mediaBusiness, result, err_2; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); updateObj = req.body; updateObj.user = req.user; mediaBusiness = new MediaBusiness(); return [4 /*yield*/, mediaBusiness.updateExistingMedia(req.params.id, updateObj)]; case 1: result = _a.sent(); if (result.error) { return [2 /*return*/, next(new error_1.PlatformError({ code: result.responseCode, message: result.error, }))]; } return [2 /*return*/, res.status(result.responseCode).json({ message: "Operation successful", data: result.data, })]; case 2: err_2 = _a.sent(); console.log(err_2); return [2 /*return*/, next(new error_1.PlatformError({ code: 500, message: "Internal Server error occured. Please try again later.", }))]; case 3: return [2 /*return*/]; } }); }); }; MediaController.prototype.create = function (req, res, next) { return __awaiter(this, void 0, void 0, function () { var uploadType, mediaType, systemMediaTypes, modifiedItems, newMedia, mediaBusiness, result, err_3; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); if (req.body.items.length < 1) { return [2 /*return*/, next(new error_1.PlatformError({ code: 400, message: "Please provide at least 1 media to upload in items", }))]; } uploadType = req.body.items.length > 1 ? "multiple" : "single"; mediaType = req.body.mediaType.toLowerCase(); systemMediaTypes = Object.values(interfaces_1.MediaType); if (!systemMediaTypes.includes(mediaType)) { return [2 /*return*/, next(new error_1.PlatformError({ code: 400, message: "Invalid mediaType", }))]; } modifiedItems = req.body.items.reduce(function (theMap, theItem) { var item = { path: theItem.path, isApproved: false, isDeleted: false, }; theMap = theMap.concat([item]); return theMap; }, []); req.body.items = modifiedItems.slice(); req.body.uploadType = uploadType; req.body.mediaType = mediaType; newMedia = req.body; newMedia.user = req.user; mediaBusiness = new MediaBusiness(); return [4 /*yield*/, mediaBusiness.create(newMedia)]; case 1: result = _a.sent(); if (result.error) { return [2 /*return*/, next(new error_1.PlatformError({ code: result.responseCode, message: result.error, }))]; } return [2 /*return*/, res.status(result.responseCode).json({ message: "Operation successful", data: result.data, })]; case 2: err_3 = _a.sent(); // console.log(err); return [2 /*return*/, next(new error_1.PlatformError({ code: 500, message: "Internal Server error occured. Please try again later.", }))]; case 3: return [2 /*return*/]; } }); }); }; MediaController.prototype.fetchUserPreviewList = function (req, res, next) { return __awaiter(this, void 0, void 0, function () { var uploadType, systemUploadTypes, mediaType, systemMediaTypes, condition, mediaBusiness, result, err_4; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); if (!req.query.mediaType) { return [2 /*return*/, next(new error_1.PlatformError({ code: 400, message: "Please provide mediaType in query param", }))]; } if (!req.query.uploadType) { return [2 /*return*/, next(new error_1.PlatformError({ code: 400, message: "Please provide uploadType in query param", }))]; } uploadType = req.query.uploadType.toLowerCase(); systemUploadTypes = Object.values(interfaces_1.MediaUploadType); if (!systemUploadTypes.includes(uploadType) && uploadType !== "all") { return [2 /*return*/, next(new error_1.PlatformError({ code: 400, message: "Invalid uploadType", }))]; } mediaType = req.query.mediaType.toLowerCase(); systemMediaTypes = Object.values(interfaces_1.MediaType); if (!systemMediaTypes.includes(mediaType) && mediaType !== "all") { return [2 /*return*/, next(new error_1.PlatformError({ code: 400, message: "Invalid mediaType", }))]; } condition = { isDeleted: false, }; if (uploadType !== "all") { condition.uploadType = uploadType; } if (mediaType !== "all") { condition.mediaType = mediaType; } condition.user = req.user; mediaBusiness = new MediaBusiness(); return [4 /*yield*/, mediaBusiness.fetchPreview(condition)]; case 1: result = _a.sent(); if (result.error) { return [2 /*return*/, next(new error_1.PlatformError({ code: result.responseCode, message: "Error occured, " + result.error, }))]; } return [2 /*return*/, res.status(result.responseCode).json({ message: "Media Operation successful", data: result.data, })]; case 2: err_4 = _a.sent(); console.log(err_4); return [2 /*return*/, next(new error_1.PlatformError({ code: 500, message: "Internal Server error occured. Please try again later", }))]; case 3: return [2 /*return*/]; } }); }); }; MediaController.prototype.fetchPreviewList = function (req, res, next) { return __awaiter(this, void 0, void 0, function () { var uploadType, systemUploadTypes, mediaType, systemMediaTypes, condition, mediaBusiness, result, err_5; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); if (!req.query.mediaType) { return [2 /*return*/, next(new error_1.PlatformError({ code: 400, message: "Please provide mediaType in query param", }))]; } if (!req.query.uploadType) { return [2 /*return*/, next(new error_1.PlatformError({ code: 400, message: "Please provide uploadType in query param", }))]; } uploadType = req.query.uploadType.toLowerCase(); systemUploadTypes = Object.values(interfaces_1.MediaUploadType); if (!systemUploadTypes.includes(uploadType) && uploadType !== "all") { return [2 /*return*/, next(new error_1.PlatformError({ code: 400, message: "Invalid uploadType", }))]; } mediaType = req.query.mediaType.toLowerCase(); systemMediaTypes = Object.values(interfaces_1.MediaType); if (!systemMediaTypes.includes(mediaType) && mediaType !== "all") { return [2 /*return*/, next(new error_1.PlatformError({ code: 400, message: "Invalid mediaType", }))]; } condition = { isDeleted: false, }; if (uploadType !== "all") { condition.uploadType = uploadType; } if (mediaType !== "all") { condition.mediaType = mediaType; } condition.user = req.params.id; mediaBusiness = new MediaBusiness(); return [4 /*yield*/, mediaBusiness.fetchTalentPortfolioPreview(condition)]; case 1: result = _a.sent(); if (result.error) { return [2 /*return*/, next(new error_1.PlatformError({ code: result.responseCode, message: "Error occured, " + result.error, }))]; } return [2 /*return*/, res.status(result.responseCode).json({ message: "Media Operation successful", data: result.data, })]; case 2: err_5 = _a.sent(); console.log(err_5); return [2 /*return*/, next(new error_1.PlatformError({ code: 500, message: "Internal Server error occured. Please try again later", }))]; case 3: return [2 /*return*/]; } }); }); }; MediaController.prototype.fetchUserList = function (req, res, next) { return __awaiter(this, void 0, void 0, function () { var uploadType, systemUploadTypes, mediaType, systemMediaTypes, condition, mediaBusiness, result, err_6; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); if (!req.query.mediaType) { return [2 /*return*/, next(new error_1.PlatformError({ code: 400, message: "Please provide mediaType in query param", }))]; } if (!req.query.uploadType) { return [2 /*return*/, next(new error_1.PlatformError({ code: 400, message: "Please provide uploadType in query param", }))]; } uploadType = req.query.uploadType.toLowerCase(); systemUploadTypes = Object.values(interfaces_1.MediaUploadType); if (!systemUploadTypes.includes(uploadType) && uploadType !== "all") { return [2 /*return*/, next(new error_1.PlatformError({ code: 400, message: "Invalid uploadType", }))]; } mediaType = req.query.mediaType.toLowerCase(); systemMediaTypes = Object.values(interfaces_1.MediaType); if (!systemMediaTypes.includes(mediaType) && mediaType !== "all") { return [2 /*return*/, next(new error_1.PlatformError({ code: 400, message: "Invalid mediaType", }))]; } condition = { isDeleted: false, }; if (uploadType !== "all") { condition.uploadType = uploadType; } if (mediaType !== "all") { condition.mediaType = mediaType; } condition.user = req.user; mediaBusiness = new MediaBusiness(); return [4 /*yield*/, mediaBusiness.fetch(condition)]; case 1: result = _a.sent(); if (result.error) { return [2 /*return*/, next(new error_1.PlatformError({ code: result.responseCode, message: "Error occured, " + result.error, }))]; } return [2 /*return*/, res.status(result.responseCode).json({ message: "Media Operation successful", data: result.data, })]; case 2: err_6 = _a.sent(); console.log(err_6); return [2 /*return*/, next(new error_1.PlatformError({ code: 500, message: "Internal Server error occured. Please try again later", }))]; case 3: return [2 /*return*/]; } }); }); }; MediaController.prototype.fetchList = function (req, res, next) { return __awaiter(this, void 0, void 0, function () { var uploadType, systemUploadTypes, mediaType, systemMediaTypes, condition, mediaBusiness, result, err_7; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); if (!req.query.mediaType) { return [2 /*return*/, next(new error_1.PlatformError({ code: 400, message: "Please provide mediaType in query param", }))]; } if (!req.query.uploadType) { return [2 /*return*/, next(new error_1.PlatformError({ code: 400, message: "Please provide uploadType in query param", }))]; } uploadType = req.query.uploadType.toLowerCase(); systemUploadTypes = Object.values(interfaces_1.MediaUploadType); if (!systemUploadTypes.includes(uploadType)) { return [2 /*return*/, next(new error_1.PlatformError({ code: 400, message: "Invalid uploadType", }))]; } mediaType = req.query.mediaType.toLowerCase(); systemMediaTypes = Object.values(interfaces_1.MediaType); if (!systemMediaTypes.includes(mediaType) && mediaType !== "all") { return [2 /*return*/, next(new error_1.PlatformError({ code: 400, message: "Invalid mediaType", }))]; } condition = { isDeleted: false, }; if (uploadType !== "all") { condition.uploadType = uploadType; } if (mediaType !== "all") { condition.mediaType = mediaType; } mediaBusiness = new MediaBusiness(); return [4 /*yield*/, mediaBusiness.fetch(condition)]; case 1: result = _a.sent(); if (result.error) { return [2 /*return*/, next(new error_1.PlatformError({ code: result.responseCode, message: "Error occured, " + result.error, }))]; } return [2 /*return*/, res.status(result.responseCode).json({ message: "Media Operation successful", data: result.data, })]; case 2: err_7 = _a.sent(); return [2 /*return*/, next(new error_1.PlatformError({ code: 500, message: "Internal Server error occured." + err_7, }))]; case 3: return [2 /*return*/]; } }); }); }; MediaController.prototype.fetchPendingMedia = function (req, res, next) { return __awaiter(this, void 0, void 0, function () { var mediaBusiness, result, err_8; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); mediaBusiness = new MediaBusiness(); return [4 /*yield*/, mediaBusiness.fetchMediaPendingApproval({})]; case 1: result = _a.sent(); if (result.error) { return [2 /*return*/, next(new error_1.PlatformError({ code: result.responseCode, message: "Error occured, " + result.error, }))]; } return [2 /*return*/, res.status(result.responseCode).json({ message: "Media Operation successful", data: result.data, })]; case 2: err_8 = _a.sent(); return [2 /*return*/, next(new error_1.PlatformError({ code: 500, message: "Internal Server error occured." + err_8, }))]; case 3: return [2 /*return*/]; } }); }); }; MediaController.prototype.fetch = function (req, res, next) { return __awaiter(this, void 0, void 0, function () { var mediaBusiness, condition, result, err_9; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); mediaBusiness = new MediaBusiness(); condition = { _id: req.params.id, isDeleted: false, }; return [4 /*yield*/, mediaBusiness.findMedia(condition)]; case 1: result = _a.sent(); if (result.error) { return [2 /*return*/, next(new error_1.PlatformError({ code: result.responseCode, message: result.error, }))]; } return [2 /*return*/, res.status(result.responseCode).json({ message: "Media Operation successful", data: result.data, })]; case 2: err_9 = _a.sent(); return [2 /*return*/, next(new error_1.PlatformError({ code: 500, message: "Internal Server error occured." + err_9, }))]; case 3: return [2 /*return*/]; } }); }); }; MediaController.prototype.deleteMedia = function (req, res, next) { return __awaiter(this, void 0, void 0, function () { var mediaBusiness, media, result, err_10; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 4, , 5]); mediaBusiness = new MediaBusiness(); return [4 /*yield*/, mediaBusiness.findById(req.params.id)]; case 1: media = _a.sent(); if (media.error) { return [2 /*return*/, next(new error_1.PlatformError({ code: media.responseCode, message: media.error, }))]; } if (!media.data) return [3 /*break*/, 3]; if (media.data.user != req.user) { return [2 /*return*/, next(new error_1.PlatformError({ code: 403, message: "You are not authorized to perform this request.", }))]; } return [4 /*yield*/, mediaBusiness.delete(media.data._id)]; case 2: result = _a.sent(); if (result.error) { return [2 /*return*/, next(new error_1.PlatformError({ code: result.responseCode, message: result.error, }))]; } return [2 /*return*/, res.status(result.responseCode).json({ message: "Media Operation successful", data: result.data, })]; case 3: return [3 /*break*/, 5]; case 4: err_10 = _a.sent(); return [2 /*return*/, next(new error_1.PlatformError({ code: 500, message: "Internal Server error occured." + err_10, }))]; case 5: return [2 /*return*/]; } }); }); }; MediaController.prototype.deleteMediaItem = function (req, res, next) { return __awaiter(this, void 0, void 0, function () { var mediaBusiness, media, mediaUser, currentUser, result, err_11; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 4, , 5]); mediaBusiness = new MediaBusiness(); return [4 /*yield*/, mediaBusiness.findById(req.params.id)]; case 1: media = _a.sent(); if (media.error) { return [2 /*return*/, next(new error_1.PlatformError({ code: media.responseCode, message: media.error, }))]; } if (media.error) { return [2 /*return*/, next(new error_1.PlatformError({ code: media.responseCode, message: media.error, }))]; } if (!media.data) return [3 /*break*/, 3]; mediaUser = media.data.user; currentUser = req.user; if (mediaUser != currentUser) { return [2 /*return*/, next(new error_1.PlatformError({ code: 403, message: "You are not authorized to perform this request.", }))]; } return [4 /*yield*/, mediaBusiness.deleteMediaItem(media.data._id, req.params.itemId)]; case 2: result = _a.sent(); if (result.error) { return [2 /*return*/, next(new error_1.PlatformError({ code: result.responseCode, message: result.error, }))]; } return [2 /*return*/, res.status(result.responseCode).json({ message: "Media Operation successful", data: result.data, })]; case 3: return [3 /*break*/, 5]; case 4: err_11 = _a.sent(); console.log(err_11); return [2 /*return*/, next(new error_1.PlatformError({ code: 500, message: "Internal Server error occured." + err_11, }))]; case 5: return [2 /*return*/]; } }); }); }; MediaController.prototype.approveMediaItem = function (req, res, next) { return __awaiter(this, void 0, void 0, function () { var mediaBusiness, result, err_12; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); mediaBusiness = new MediaBusiness(); if (!req.body.itemId) return [2 /*return*/, next(new error_1.PlatformError({ code: 400, message: "Please provide itemId", }))]; return [4 /*yield*/, mediaBusiness.approveMedia(req.params.id, req.body.itemId, req.user)]; case 1: result = _a.sent(); if (result.error) { return [2 /*return*/, next(new error_1.PlatformError({ code: result.responseCode, message: result.error, }))]; } return [2 /*return*/, res.status(result.responseCode).json({ message: "Operation successful", data: result.data, })]; case 2: err_12 = _a.sent(); console.log(err_12); return [2 /*return*/, next(new error_1.PlatformError({ code: 500, message: "Internal Server error occured. Please try again later.", }))]; case 3: return [2 /*return*/]; } }); }); }; MediaController.prototype.rejectMediaItem = function (req, res, next) { return __awaiter(this, void 0, void 0, function () { var mediaBusiness, result, err_13; return __generator(this, function (_a) { switch (_a.label) { case 0: _a.trys.push([0, 2, , 3]); if (!req.body.itemId) return [2 /*return*/, next(new error_1.PlatformError({ code: 400, message: "Please provide itemId", }))]; if (!req.body.reason) return [2 /*return*/, next(new error_1.PlatformError({ code: 400, message: "Please provide rejection reason", }))]; mediaBusiness = new MediaBusiness(); return [4 /*yield*/, mediaBusiness.rejectMedia(req.params.id, req.body.itemId, req.user, req.body.reason)]; case 1: result = _a.sent(); if (result.error) { return [2 /*return*/, next(new error_1.PlatformError({ code: result.responseCode, message: result.error, }))]; } return [2 /*return*/, res.status(result.responseCode).json({ message: "Operation successful", data: result.data, })]; case 2: err_13 = _a.sent(); console.log(err_13); return [2 /*return*/, next(new error_1.PlatformError({ code: 500, message: "Internal Server error occured. Please try again later.", }))]; case 3: return [2 /*return*/]; } }); }); }; __decorate([ decorators_1.use(auth_1.requireAuth), decorators_1.use(ValidateRequest_1.requestValidator), decorators_1.put("/:id"), decorators_1.requestValidators("mediaType"), __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object, Function]), __metadata("design:returntype", Promise) ], MediaController.prototype, "update", null); __decorate([ decorators_1.use(auth_1.requireAuth), decorators_1.use(ValidateRequest_1.requestValidator), decorators_1.patch("/:id"), __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object, Function]), __metadata("design:returntype", Promise) ], MediaController.prototype, "patchMedia", null); __decorate([ decorators_1.use(auth_1.requireAuth), decorators_1.post("/"), decorators_1.use(ValidateRequest_1.requestValidator), decorators_1.requestValidators("title", "items", "mediaType"), __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object, Function]), __metadata("design:returntype", Promise) ], MediaController.prototype, "create", null); __decorate([ decorators_1.get("/me/preview"), decorators_1.use(ValidateRequest_1.requestValidator), decorators_1.use(auth_1.requireAuth), __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object, Function]), __metadata("design:returntype", Promise) ], MediaController.prototype, "fetchUserPreviewList", null); __decorate([ decorators_1.get("/talent/:id/portfolio"), decorators_1.use(ValidateRequest_1.requestValidator), __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object, Function]), __metadata("design:returntype", Promise) ], MediaController.prototype, "fetchPreviewList", null); __decorate([ decorators_1.get("/me"), decorators_1.use(ValidateRequest_1.requestValidator), decorators_1.use(auth_1.requireAuth), __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object, Function]), __metadata("design:returntype", Promise) ], MediaController.prototype, "fetchUserList", null); __decorate([ decorators_1.get("/"), decorators_1.use(ValidateRequest_1.requestValidator), __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object, Function]), __metadata("design:returntype", Promise) ], MediaController.prototype, "fetchList", null); __decorate([ decorators_1.get("/admin/pending"), decorators_1.use(auth_1.requireAuth), decorators_1.use(ValidateRequest_1.requestValidator), decorators_1.authorize(PermissionConstant_1.canViewPendingMedia), __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object, Function]), __metadata("design:returntype", Promise) ], MediaController.prototype, "fetchPendingMedia", null); __decorate([ decorators_1.use(ValidateRequest_1.requestValidator), decorators_1.get("/:id"), __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object, Function]), __metadata("design:returntype", Promise) ], MediaController.prototype, "fetch", null); __decorate([ decorators_1.use(ValidateRequest_1.requestValidator), decorators_1.use(auth_1.requireAuth), decorators_1.del("/:id"), __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object, Function]), __metadata("design:returntype", Promise) ], MediaController.prototype, "deleteMedia", null); __decorate([ decorators_1.use(ValidateRequest_1.requestValidator), decorators_1.use(auth_1.requireAuth), decorators_1.del("/:id/item/:itemId"), __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object, Function]), __metadata("design:returntype", Promise) ], MediaController.prototype, "deleteMediaItem", null); __decorate([ decorators_1.put("/admin/approve/:id"), decorators_1.use(auth_1.requireAuth), decorators_1.use(ValidateRequest_1.requestValidator), decorators_1.authorize(PermissionConstant_1.canApproveMedia), decorators_1.requestValidators("itemId"), __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object, Function]), __metadata("design:returntype", Promise) ], MediaController.prototype, "approveMediaItem", null); __decorate([ decorators_1.put("/admin/reject/:id"), decorators_1.use(auth_1.requireAuth), decorators_1.use(ValidateRequest_1.requestValidator), decorators_1.authorize(PermissionConstant_1.canRejectMedia), decorators_1.requestValidators("reason"), __metadata("design:type", Function), __metadata("design:paramtypes", [Object, Object, Function]), __metadata("design:returntype", Promise) ], MediaController.prototype, "rejectMediaItem", null); MediaController = __decorate([ decorators_1.controller("/v1/media") ], MediaController); return MediaController; }()); exports.MediaController = MediaController; //# sourceMappingURL=MediaController.js.map
onlyuuuuu/t-grre-system-backend
t-grre-remng-svi/t-grre-remng-svi-dom/src/main/java/com/onlyu/thesis/service/domain/remng/nonemodels/PropertyDocument.java
<filename>t-grre-remng-svi/t-grre-remng-svi-dom/src/main/java/com/onlyu/thesis/service/domain/remng/nonemodels/PropertyDocument.java package com.onlyu.thesis.service.domain.remng.nonemodels; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.*; import java.io.Serializable; @NoArgsConstructor @AllArgsConstructor @Getter @Setter @EqualsAndHashCode @JsonIgnoreProperties(ignoreUnknown = true) @SuppressWarnings({"unused"}) public class PropertyDocument implements Serializable { private String front; private String back; private String signature; private String mark; }
YstjawdTzwjafy/Solvers
SolversApp/app/src/main/java/com/example/solvers/views/HomeActivity.java
package com.example.solvers.views; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentTransaction; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.MenuItem; import android.widget.Button; import com.example.solvers.R; import com.example.solvers.views.fragments.AccountFragment; import com.example.solvers.views.fragments.HomeFragment; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.android.material.bottomnavigation.BottomNavigationView; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.UserProfileChangeRequest; public class HomeActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener { BottomNavigationView bNavView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); bNavView = findViewById(R.id.bottomNavigationView); bNavView.setOnNavigationItemSelectedListener(this); Fragment homeFragment = HomeFragment.newInstance(); openFragment(homeFragment); } @Override public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) { switch (menuItem.getItemId()){ case R.id.navigation_home: Fragment homeFragment = HomeFragment.newInstance(); openFragment(homeFragment); break; case R.id.navigation_account: Fragment accountFragment = AccountFragment.newInstance(); openFragment(accountFragment); break; default: break; } return true; } private void openFragment(Fragment fragment) { FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); transaction.replace(R.id.frame_layout, fragment); transaction.addToBackStack(null); transaction.commit(); } }
microaaron/ammo.js
bullet/Demos/SoftDemo/SoftDemo.h
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2006 <NAME> http://continuousphysics.com/Bullet/ 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. */ ///btSoftBody implementation by <NAME> #ifndef SOFT_DEMO_H #define SOFT_DEMO_H #ifdef _WINDOWS #include "Win32DemoApplication.h" #define PlatformDemoApplication Win32DemoApplication #else #include "GlutDemoApplication.h" #define PlatformDemoApplication GlutDemoApplication #endif #include "LinearMath/btAlignedObjectArray.h" #include "BulletSoftBody/btSoftBody.h" class btBroadphaseInterface; class btCollisionShape; class btOverlappingPairCache; class btCollisionDispatcher; class btConstraintSolver; struct btCollisionAlgorithmCreateFunc; class btDefaultCollisionConfiguration; ///collisions between two btSoftBody's class btSoftSoftCollisionAlgorithm; ///collisions between a btSoftBody and a btRigidBody class btSoftRididCollisionAlgorithm; class btSoftRigidDynamicsWorld; ///CcdPhysicsDemo shows basic stacking using Bullet physics, and allows toggle of Ccd (using key '1') class SoftDemo : public PlatformDemoApplication { public: btAlignedObjectArray<btSoftSoftCollisionAlgorithm*> m_SoftSoftCollisionAlgorithms; btAlignedObjectArray<btSoftRididCollisionAlgorithm*> m_SoftRigidCollisionAlgorithms; btSoftBodyWorldInfo m_softBodyWorldInfo; bool m_autocam; bool m_cutting; bool m_raycast; btScalar m_animtime; btClock m_clock; int m_lastmousepos[2]; btVector3 m_impact; btSoftBody::sRayCast m_results; btSoftBody::Node* m_node; btVector3 m_goal; bool m_drag; //keep the collision shapes, for deletion/cleanup btAlignedObjectArray<btCollisionShape*> m_collisionShapes; btBroadphaseInterface* m_broadphase; btCollisionDispatcher* m_dispatcher; btConstraintSolver* m_solver; btCollisionAlgorithmCreateFunc* m_boxBoxCF; btDefaultCollisionConfiguration* m_collisionConfiguration; public: void initPhysics(); void exitPhysics(); SoftDemo() : m_drag(false) { setTexturing(true); setShadows(true); } virtual ~SoftDemo() { exitPhysics(); } virtual void clientMoveAndDisplay(); virtual void displayCallback(); void createStack( btCollisionShape* boxShape, float halfCubeSize, int size, float zPos ); static DemoApplication* Create() { SoftDemo* demo = new SoftDemo; demo->myinit(); demo->initPhysics(); return demo; } virtual void setDrawClusters(bool drawClusters); virtual const btSoftRigidDynamicsWorld* getSoftDynamicsWorld() const { ///just make it a btSoftRigidDynamicsWorld please ///or we will add type checking return (btSoftRigidDynamicsWorld*) m_dynamicsWorld; } virtual btSoftRigidDynamicsWorld* getSoftDynamicsWorld() { ///just make it a btSoftRigidDynamicsWorld please ///or we will add type checking return (btSoftRigidDynamicsWorld*) m_dynamicsWorld; } // void clientResetScene(); void renderme(); void keyboardCallback(unsigned char key, int x, int y); void mouseFunc(int button, int state, int x, int y); void mouseMotionFunc(int x,int y); }; #define MACRO_SOFT_DEMO(a) class SoftDemo##a : public SoftDemo\ {\ public:\ static DemoApplication* Create()\ {\ SoftDemo* demo = new SoftDemo##a;\ extern int current_demo;\ current_demo=a;\ demo->myinit();\ demo->initPhysics();\ return demo;\ }\ }; MACRO_SOFT_DEMO(0) //Init_Cloth MACRO_SOFT_DEMO(1) //Init_Pressure MACRO_SOFT_DEMO(2)//Init_Volume MACRO_SOFT_DEMO(3)//Init_Ropes MACRO_SOFT_DEMO(4)//Init_Ropes_Attach MACRO_SOFT_DEMO(5)//Init_ClothAttach MACRO_SOFT_DEMO(6)//Init_Sticks MACRO_SOFT_DEMO(7)//Init_Collide MACRO_SOFT_DEMO(8)//Init_Collide2 MACRO_SOFT_DEMO(9)//Init_Collide3 MACRO_SOFT_DEMO(10)//Init_Impact MACRO_SOFT_DEMO(11)//Init_Aero MACRO_SOFT_DEMO(12)//Init_Friction MACRO_SOFT_DEMO(13)//Init_Torus MACRO_SOFT_DEMO(14)//Init_TorusMatch MACRO_SOFT_DEMO(15)//Init_Bunny MACRO_SOFT_DEMO(16)//Init_BunnyMatch MACRO_SOFT_DEMO(17)//Init_Cutting1 MACRO_SOFT_DEMO(18)//Init_ClusterDeform MACRO_SOFT_DEMO(19)//Init_ClusterCollide1 MACRO_SOFT_DEMO(20)//Init_ClusterCollide2 MACRO_SOFT_DEMO(21)//Init_ClusterSocket MACRO_SOFT_DEMO(22)//Init_ClusterHinge MACRO_SOFT_DEMO(23)//Init_ClusterCombine MACRO_SOFT_DEMO(24)//Init_ClusterCar MACRO_SOFT_DEMO(25)//Init_ClusterRobot MACRO_SOFT_DEMO(26)//Init_ClusterStackSoft MACRO_SOFT_DEMO(27)//Init_ClusterStackMixed MACRO_SOFT_DEMO(28)//Init_TetraCube MACRO_SOFT_DEMO(29)//Init_TetraBunny #endif //CCD_PHYSICS_DEMO_H