max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
993
# Copyright (c) 2021 PPViT Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """utils for transGAN Contains AverageMeter for monitoring, get_exclude_from_decay_fn for training and WarmupCosineScheduler for training """ import math import pickle from scipy import special import numpy as np import paddle import paddle.nn as nn import paddle.distributed as dist from paddle.optimizer.lr import LRScheduler import paddle.nn.functional as F # Several initialization methods @paddle.no_grad() def constant_(x, value): temp_value = paddle.full(x.shape, value, x.dtype) x.set_value(temp_value) return x @paddle.no_grad() def normal_(x, mean=0., std=1.): temp_value = paddle.normal(mean, std, shape=x.shape) x.set_value(temp_value) return x @paddle.no_grad() def uniform_(x, a=-1., b=1.): temp_value = paddle.uniform(min=a, max=b, shape=x.shape) x.set_value(temp_value) return x def gelu(x): """ Original Implementation of the gelu activation function in Google Bert repo when initialy created. For information: OpenAI GPT's gelu is slightly different (and gives slightly different results): 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))) Also see https://arxiv.org/abs/1606.08415 """ return x * 0.5 * (1.0 + paddle.erf(x / math.sqrt(2.0))) def leakyrelu(x): """ An activation function๏ผš if x > 0, return x. else return negative_slope * x. the value of negative_slope is 0.2. more information can see https://www.paddlepaddle.org.cn/documentation/ docs/zh/api/paddle/nn/functional/leaky_relu_cn.html#leaky-relu """ return F.leaky_relu(x, 0.2) def _no_grad_trunc_normal_(tensor, mean, std, a, b): # Cut & paste from PyTorch official master until it's in a few official releases - RW # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf def norm_cdf(x): # Computes standard normal cumulative distribution function return (1. + math.erf(x / math.sqrt(2.))) / 2. if (mean < a - 2 * std) or (mean > b + 2 * std): warnings.warn("mean is more than 2 std from [a, b] in nn.init.trunc_normal_. " "The distribution of values may be incorrect.", stacklevel=2) with paddle.no_grad(): # Values are generated by using a truncated uniform distribution and # then using the inverse CDF for the normal distribution. # Get upper and lower cdf values l = norm_cdf((a - mean) / std) u = norm_cdf((b - mean) / std) # Uniformly fill tensor with values from [l, u], then translate to # [2l-1, 2u-1]. tensor = paddle.uniform(tensor.shape, min=(2 * l - 1), max=(2 * u - 1)) # Use inverse cdf transform for normal distribution to get truncated # standard normal tensor = paddle.to_tensor(special.erfinv(tensor.numpy())) # Transform to proper mean, std tensor = paddle.multiply(tensor, paddle.to_tensor(std * math.sqrt(2.))) tensor = paddle.add(tensor, paddle.to_tensor(mean)) # Clamp to ensure it's in the proper range tensor = paddle.clip(tensor, min=a, max=b) return tensor def trunc_normal_(tensor, mean=0., std=1., a=-2., b=2.): # type: (Tensor, float, float, float, float) -> Tensor r"""Fills the input Tensor with values drawn from a truncated normal distribution. The values are effectively drawn from the normal distribution :math:`\mathcal{N}(\text{mean}, \text{std}^2)` with values outside :math:`[a, b]` redrawn until they are within the bounds. The method used for generating the random values works best when :math:`a \leq \text{mean} \leq b`. Args: tensor: an n-dimensional `paddle.Tensor` mean: the mean of the normal distribution std: the standard deviation of the normal distribution a: the minimum cutoff value b: the maximum cutoff value Examples: >>> w = paddle.empty(3, 5) >>> trunc_normal_(w) """ return _no_grad_trunc_normal_(tensor, mean, std, a, b) class AverageMeter(): """ Meter for monitoring losses""" def __init__(self): self.avg = 0 self.sum = 0 self.cnt = 0 self.reset() def reset(self): """reset all values to zeros""" self.avg = 0 self.sum = 0 self.cnt = 0 def update(self, val, n=1): """update avg by val and n, where val is the avg of n values""" self.sum += val * n self.cnt += n self.avg = self.sum / self.cnt def get_exclude_from_weight_decay_fn(exclude_list=[]): """ Set params with no weight decay during the training For certain params, e.g., positional encoding in ViT, weight decay may not needed during the learning, this method is used to find these params. Args: exclude_list: a list of params names which need to exclude from weight decay. Returns: exclude_from_weight_decay_fn: a function returns True if param will be excluded from weight decay """ if len(exclude_list) == 0: exclude_from_weight_decay_fn = None else: def exclude_fn(param): for name in exclude_list: if param.endswith(name): return False return True exclude_from_weight_decay_fn = exclude_fn return exclude_from_weight_decay_fn class WarmupCosineScheduler(LRScheduler): """Warmup Cosine Scheduler First apply linear warmup, then apply cosine decay schedule. Linearly increase learning rate from "warmup_start_lr" to "start_lr" over "warmup_epochs" Cosinely decrease learning rate from "start_lr" to "end_lr" over remaining "total_epochs - warmup_epochs" Attributes: learning_rate: the starting learning rate (without warmup), not used here! warmup_start_lr: warmup starting learning rate start_lr: the starting learning rate (without warmup) end_lr: the ending learning rate after whole loop warmup_epochs: # of epochs for warmup total_epochs: # of total epochs (include warmup) """ def __init__(self, learning_rate, warmup_start_lr, start_lr, end_lr, warmup_epochs, total_epochs, cycles=0.5, last_epoch=-1, verbose=False): """init WarmupCosineScheduler """ self.warmup_epochs = warmup_epochs self.total_epochs = total_epochs self.warmup_start_lr = warmup_start_lr self.start_lr = start_lr self.end_lr = end_lr self.cycles = cycles super(WarmupCosineScheduler, self).__init__(learning_rate, last_epoch, verbose) def get_lr(self): """ return lr value """ if self.last_epoch < self.warmup_epochs: val = (self.start_lr - self.warmup_start_lr) * float( self.last_epoch)/float(self.warmup_epochs) + self.warmup_start_lr return val progress = float(self.last_epoch - self.warmup_epochs) / float( max(1, self.total_epochs - self.warmup_epochs)) val = max(0.0, 0.5 * (1. + math.cos(math.pi * float(self.cycles) * 2.0 * progress))) val = max(0.0, val * (self.start_lr - self.end_lr) + self.end_lr) return val def leakyrelu(x): return nn.functional.leaky_relu(x, 0.2) def DiffAugment(x, policy='', channels_first=True, affine=None): if policy: if not channels_first: x = x.transpose(0, 3, 1, 2) for p in policy.split(','): for f in AUGMENT_FNS[p]: x = f(x, affine=affine) if not channels_first: x = x.transpose(0, 2, 3, 1) return x # belong to DiffAugment def rand_brightness(x, affine=None): x = x + (paddle.rand(x.size(0), 1, 1, 1, dtype=x.dtype, device=x.device) - 0.5) return x # belong to DiffAugment def rand_saturation(x, affine=None): x_mean = x.mean(dim=1, keepdim=True) x = (x - x_mean) * (paddle.rand( x.size(0), 1, 1, 1, dtype=x.dtype, device=x.device) * 2) + x_mean return x # belong to DiffAugment def rand_contrast(x, affine=None): x_mean = x.mean(dim=[1, 2, 3], keepdim=True) x = (x - x_mean) * (paddle.rand( x.size(0), 1, 1, 1, dtype=x.dtype, device=x.device) + 0.5) + x_mean return x # belong to DiffAugment def rand_cutout(x, ratio=0.5, affine=None): if random.random() < 0.3: cutout_size = int(x.size(2) * ratio + 0.5), int(x.size(3) * ratio + 0.5) offset_x =paddle.randint(0, x.size(2) + (1 - cutout_size[0] % 2), size=[x.size(0), 1, 1], device=x.device) offset_y = paddle.randint(0, x.size(3) + (1 - cutout_size[1] % 2), size=[x.size(0), 1, 1], device=x.device) grid_batch, grid_x, grid_y = paddle.meshgrid( paddle.arange(x.size(0), dtype=paddle.long, device=x.device), paddle.arange(cutout_size[0], dtype=paddle.long, device=x.device), paddle.arange(cutout_size[1], dtype=paddle.long, device=x.device), ) grid_x = paddle.clamp(grid_x + offset_x - cutout_size[0] // 2, min=0, max=x.size(2) - 1) grid_y = paddle.clamp(grid_y + offset_y - cutout_size[1] // 2, min=0, max=x.size(3) - 1) del offset_x del offset_y mask = paddle.ones(x.size(0), x.size(2), x.size(3), dtype=x.dtype, device=x.device) mask[grid_batch, grid_x, grid_y] = 0 x = x * mask.unsqueeze(1) del mask del grid_x del grid_y del grid_batch return x # belong to DiffAugment def rand_translation(x, ratio=0.2, affine=None): shift_x, shift_y = int(x.shape[2] * ratio + 0.5), int(x.shape[3] * ratio + 0.5) translation_x = paddle.randint(-shift_x, shift_x + 1, shape=[x.shape[0], 1, 1]) translation_y = paddle.randint(-shift_y, shift_y + 1, shape=[x.shape[0], 1, 1]) grid_batch, grid_x, grid_y = paddle.meshgrid( paddle.arange(x.shape[0]), paddle.arange(x.shape[2]), paddle.arange(x.shape[3]), ) grid_x = paddle.clip(grid_x + translation_x + 1, 0, x.shape[2] + 1) grid_y = paddle.clip(grid_y + translation_y + 1, 0, x.shape[3] + 1) x_pad = F.pad(x, [1, 1, 1, 1, 0, 0, 0, 0]) x = x_pad.transpose([0, 2, 3, 1])[grid_batch, grid_x, grid_y].transpose([0, 3, 1, 2]) return x AUGMENT_FNS = { 'color': [rand_brightness, rand_saturation, rand_contrast], 'translation': [rand_translation], 'cutout': [rand_cutout], } def drop_path(x, drop_prob: float = 0., training: bool = False): """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). This is the same as the DropConnect impl author created for EfficientNet, etc networks, however,the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper... See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... author have opted for changing the layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the argument. """ if drop_prob == 0. or not training: return x keep_prob = 1 - drop_prob shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets random_tensor = keep_prob + paddle.rand(shape, dtype=x.dtype, device=x.device) random_tensor.floor_() # binarize output = x.div(keep_prob) * random_tensor return output def pixel_upsample(x, H, W): B, N, C = x.shape assert N == H*W x = x.transpose((0, 2, 1)) x = x.reshape((-1, C, H, W)) x = nn.PixelShuffle(2)(x) B, C, H, W = x.shape x = x.reshape((-1, C, H*W)) x = x.transpose((0, 2, 1)) return x, H, W def all_gather(data): """ run all_gather on any picklable data (do not requires tensors) Args: data: picklable object Returns: data_list: list of data gathered from each rank """ world_size = dist.get_world_size() if world_size == 1: return [data] buffer = pickle.dumps(data) #write data into Bytes and stores in buffer np_buffer = np.frombuffer(buffer, dtype=np.int8) tensor = paddle.to_tensor(np_buffer, dtype='int32') # uint8 doese not have many ops in paddle # obtain Tensor size of each rank local_size = paddle.to_tensor([tensor.shape[0]]) size_list = [] dist.all_gather(size_list, local_size) max_size = max(size_list) # receiving tensors from all ranks, # all_gather does not support different shape, so we use padding tensor_list = [] if local_size != max_size: padding = paddle.empty(shape=(max_size - local_size, ), dtype='int32') tensor = paddle.concat((tensor, padding), axis=0) dist.all_gather(tensor_list, tensor) data_list = [] for size, tensor in zip(size_list, tensor_list): buffer = tensor.astype('uint8').cpu().numpy().tobytes()[:size] data_list.append(pickle.loads(buffer)) return data_list
6,074
885
<reponame>Sollertix/PnP /******************************************************************************* **NOTE** This code was generated by a tool and will occasionally be overwritten. We welcome comments and issues regarding this code; they will be addressed in the generation tool. If you wish to submit pull requests, please do so for the templates in that tool. This code was generated by Vipr (https://github.com/microsoft/vipr) using the T4TemplateWriter (https://github.com/msopentech/vipr-t4templatewriter). Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the Apache License 2.0; see LICENSE in the source repository root for authoritative license information.๏ปฟ ******************************************************************************/ #ifndef MSGRAPHSERVICEUSEROPERATIONS_H #define MSGRAPHSERVICEUSEROPERATIONS_H #import "MSGraphServiceModels.h" #import "api/api.h" #import "core/core.h" #import "MSGraphServiceDirectoryObjectOperations.h" /** MSGraphServiceUserOperations * */ @interface MSGraphServiceUserOperations : MSGraphServiceDirectoryObjectOperations - (instancetype)initOperationWithUrl:(NSString *)urlComponent parent:(id<MSOrcExecutable>)parent; - (void)assignLicenseWithAddLicenses:(MSGraphServiceAssignedLicense *)addLicenses removeLicenses:(NSString *)removeLicenses callback:(void (^)(MSGraphServiceUser *, MSOrcError*))callback ; - (void)assignLicenseRawWithAddLicenses:(NSString *)addLicenses removeLicenses:(NSString *)removeLicenses callback:(void (^)(NSString *, MSOrcError*))callback ; - (void)changePasswordWithCurrentPassword:(NSString *)currentPassword newPassword:(NSString *)newPassword callback:(void (^)(int, MSOrcError*))callback ; - (void)changePasswordRawWithCurrentPassword:(NSString *)currentPassword newPassword:(NSString *)newPassword callback:(void (^)(NSString *, MSOrcError*))callback ; - (void)sendMailWithMessage:(MSGraphServiceMessage *)message saveToSentItems:(bool)saveToSentItems callback:(void (^)(int, MSOrcError*))callback ; - (void)sendMailRawWithMessage:(NSString *)message saveToSentItems:(NSString *)saveToSentItems callback:(void (^)(NSString *, MSOrcError*))callback ; - (void)reminderViewWithStartDateTime:(NSString *)startDateTime endDateTime:(NSString *)endDateTime callback:(void (^)(MSGraphServiceReminder *, MSOrcError*))callback ; @end #endif
655
809
<gh_stars>100-1000 /** * @file * @brief nxt touch sensor driver * * @date 02.12.10 * @author <NAME> */ #include <stdint.h> #include <embox/test.h> #include <unistd.h> #include <drivers/nxt/avr.h> #include <drivers/nxt/touch_sensor.h> #define TOUCH_ADC_EDGE 500 static touch_hnd_t touch_sens_hnds[NXT_AVR_N_INPUTS]; typedef enum { NXT_TOUCH_STATE_UP, NXT_TOUCH_STATE_DOWN } touch_state_t; static touch_state_t state = NXT_TOUCH_STATE_UP; static void touch_handler(nxt_sensor_t *sensor, sensor_val_t val) { touch_state_t new_state = (val <= TOUCH_ADC_EDGE ? NXT_TOUCH_STATE_DOWN : NXT_TOUCH_STATE_UP); if (new_state != state) { state = new_state; touch_sens_hnds[sensor->id](sensor); } } void touch_sensor_init (nxt_sensor_t *sensor, touch_hnd_t handler) { touch_sens_hnds[sensor->id] = handler; nxt_sensor_conf_pass(sensor, (sensor_handler_t) touch_handler); }
404
879
package org.zstack.zql; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.atomic.AtomicLong; public class ZQLStatistic { private List<SlowZQLStatistic> slowZQLStatistics = Collections.synchronizedList(new ArrayList<>()); private AtomicLong executedZqlCount = new AtomicLong(0); public List<SlowZQLStatistic> getSlowZQLStatistics() { return slowZQLStatistics; } public void setSlowZQLStatistics(List<SlowZQLStatistic> slowZQLStatistics) { this.slowZQLStatistics = slowZQLStatistics; } public AtomicLong getExecutedZqlCount() { return executedZqlCount; } public void setExecutedZqlCount(AtomicLong executedZqlCount) { this.executedZqlCount = executedZqlCount; } public void count() { executedZqlCount.incrementAndGet(); } public void resetCount() { executedZqlCount.set(0); } }
348
2,685
/* * Copyright (C) <NAME> (vozlt) */ #ifndef _NGX_HTTP_VTS_DISPLAY_H_INCLUDED_ #define _NGX_HTTP_VTS_DISPLAY_H_INCLUDED_ ngx_int_t ngx_http_vhost_traffic_status_display_get_upstream_nelts( ngx_http_request_t *r); ngx_int_t ngx_http_vhost_traffic_status_display_get_size( ngx_http_request_t *r, ngx_int_t format); u_char *ngx_http_vhost_traffic_status_display_get_time_queue( ngx_http_request_t *r, ngx_http_vhost_traffic_status_node_time_queue_t *q, ngx_uint_t offset); u_char *ngx_http_vhost_traffic_status_display_get_time_queue_times( ngx_http_request_t *r, ngx_http_vhost_traffic_status_node_time_queue_t *q); u_char *ngx_http_vhost_traffic_status_display_get_time_queue_msecs( ngx_http_request_t *r, ngx_http_vhost_traffic_status_node_time_queue_t *q); u_char *ngx_http_vhost_traffic_status_display_get_histogram_bucket( ngx_http_request_t *r, ngx_http_vhost_traffic_status_node_histogram_bucket_t *b, ngx_uint_t offset, const char *fmt); u_char *ngx_http_vhost_traffic_status_display_get_histogram_bucket_msecs( ngx_http_request_t *r, ngx_http_vhost_traffic_status_node_histogram_bucket_t *b); u_char *ngx_http_vhost_traffic_status_display_get_histogram_bucket_counters( ngx_http_request_t *r, ngx_http_vhost_traffic_status_node_histogram_bucket_t *q); char *ngx_http_vhost_traffic_status_display(ngx_conf_t *cf, ngx_command_t *cmd, void *conf); #endif /* _NGX_HTTP_VTS_DISPLAY_H_INCLUDED_ */ /* vi:set ft=c ts=4 sw=4 et fdm=marker: */
717
910
<gh_stars>100-1000 /* * Copyright (c) 2021 VMware, Inc. * SPDX-License-Identifier: MIT * * 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. */ package org.dbsp.circuits.operators; import org.dbsp.algebraic.staticTyping.Group; import org.dbsp.algebraic.dynamicTyping.types.Type; import org.dbsp.circuits.Scheduler; import javax.annotation.Nullable; import java.util.Objects; public class IntOperator extends UnaryOperator { private Object value; final Group<Object> group; private final CircuitOperator body; // Int operators are always associated with a Delta final DeltaOperator delta; protected IntOperator(Type type, DeltaOperator delta, CircuitOperator body) { super(type, type); this.delta = delta; this.group = Objects.requireNonNull(type.getGroup()); this.body = body; this.value = this.group.zero(); } @Override public Object evaluate(Object input, Scheduler scheduler) { this.value = this.group.add(this.value, input); return input; } @Override public void reset(Scheduler scheduler) { this.log(scheduler, "reset"); this.value = this.group.zero(); this.body.reset(scheduler); this.delta.reset(scheduler); } @Override public void emitOutput(Object result, Scheduler scheduler) { // int does not emit an output when expected, only when it is actually zero if (this.group.isZero(Objects.requireNonNull(result))) { this.output.setValue(Objects.requireNonNull(this.value), scheduler); this.output.notifyConsumers(scheduler); this.reset(scheduler); } else { this.body.circuit.step(scheduler); this.delta.repeat(scheduler); } } @Override public String toString() { return "Int"; } }
997
547
<filename>renderer-macos/lib/stubs/BriskWindowDelegate.c #import "BriskWindowDelegate.h" @implementation BriskWindowDelegate { value didResizeCallback; } - (void)windowDidResize:(NSNotification *)__unused aNotification { if (didResizeCallback) { brisk_caml_call(didResizeCallback); } } - (void)setOnWindowDidResize:(value)callback { if (didResizeCallback) { caml_modify_generational_global_root(&didResizeCallback, callback); } else { didResizeCallback = callback; caml_register_generational_global_root(&didResizeCallback); } } @end
205
992
/* Copyright (c) 2006, <NAME> and <NAME> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the Johns Hopkins University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /////////////////////////// // MemoryInputDataStream // /////////////////////////// template< typename Data > MemoryInputDataStream< Data >::MemoryInputDataStream( size_t size , const Data *data ) : _data(data) , _size(size) , _current(0) {} template< typename Data > MemoryInputDataStream< Data >::~MemoryInputDataStream( void ){ ; } template< typename Data > void MemoryInputDataStream< Data >::reset( void ) { _current=0; } template< typename Data > bool MemoryInputDataStream< Data >::next( Data &d ) { if( _current>=_size ) return false; d = _data[_current++]; return true; } //////////////////////////// // MemoryOutputDataStream // //////////////////////////// template< typename Data > MemoryOutputDataStream< Data >::MemoryOutputDataStream( size_t size , Data *data ) : _data(data) , _size(size) , _current(0) {} template< typename Data > MemoryOutputDataStream< Data >::~MemoryOutputDataStream( void ){ ; } template< typename Data > void MemoryOutputDataStream< Data >::next( const Data &d ) { _data[_current++] = d; } ////////////////////////// // ASCIIInputDataStream // ////////////////////////// template< typename Factory > ASCIIInputDataStream< Factory >::ASCIIInputDataStream( const char* fileName , const Factory &factory ) : _factory( factory ) { _fp = fopen( fileName , "r" ); if( !_fp ) ERROR_OUT( "Failed to open file for reading: %s" , fileName ); } template< typename Factory > ASCIIInputDataStream< Factory >::~ASCIIInputDataStream( void ) { fclose( _fp ); _fp = NULL; } template< typename Factory > void ASCIIInputDataStream< Factory >::reset( void ) { fseek( _fp , SEEK_SET , 0 ); } template< typename Factory > bool ASCIIInputDataStream< Factory >::next( Data &d ) { d = _factory(); return _factory.readASCII( _fp , d ); } /////////////////////////// // ASCIIOutputDataStream // /////////////////////////// template< typename Factory > ASCIIOutputDataStream< Factory >::ASCIIOutputDataStream( const char* fileName , const Factory &factory ) : _factory( factory ) { _fp = fopen( fileName , "w" ); if( !_fp ) ERROR_OUT( "Failed to open file for writing: %s" , fileName ); } template< typename Factory > ASCIIOutputDataStream< Factory >::~ASCIIOutputDataStream( void ) { fclose( _fp ); _fp = NULL; } template< typename Factory > void ASCIIOutputDataStream< Factory >::next( const Data &d ) { _factory.writeASCII( _fp , d ); } /////////////////////////// // BinaryInputDataStream // /////////////////////////// template< typename Factory > BinaryInputDataStream< Factory >::BinaryInputDataStream( const char* fileName , const Factory &factory ) : _factory(factory) { _fp = fopen( fileName , "rb" ); if( !_fp ) ERROR_OUT( "Failed to open file for reading: %s" , fileName ); } template< typename Factory > void BinaryInputDataStream< Factory >::reset( void ) { fseek( _fp , SEEK_SET , 0 ); } template< typename Factory > bool BinaryInputDataStream< Factory >::next( Data &d ) { d = _factory(); return _factory.readBinary( _fp , d ); } //////////////////////////// // BinaryOutputDataStream // //////////////////////////// template< typename Factory > BinaryOutputDataStream< Factory >::BinaryOutputDataStream( const char* fileName , const Factory &factory ) : _factory(factory) { _fp = fopen( fileName , "wb" ); if( !_fp ) ERROR_OUT( "Failed to open file for writing: %s" , fileName ); } template< typename Factory > void BinaryOutputDataStream< Factory >::next( const Data &d ){ return _factory.writeBinary( _fp , d ); } //////////////////////// // PLYInputDataStream // //////////////////////// template< typename Factory > PLYInputDataStream< Factory >::PLYInputDataStream( const char* fileName , const Factory &factory ) : _factory(factory) { _fileName = new char[ strlen( fileName )+1 ]; strcpy( _fileName , fileName ); _ply = NULL; if( factory.bufferSize() ) _buffer = new char[ factory.bufferSize() ]; else _buffer = NULL; reset(); } template< typename Factory > void PLYInputDataStream< Factory >::reset( void ) { int fileType; float version; std::vector< PlyProperty > plist; if( _ply ) _free(); _ply = PlyFile::Read( _fileName, _elist, fileType, version ); if( !_ply ) ERROR_OUT( "Failed to open ply file for reading: %s" , _fileName ); bool foundData = false; for( int i=0 ; i<_elist.size() ; i++ ) { size_t num_elems; std::string &elem_name = _elist[i]; plist = _ply->get_element_description( elem_name , num_elems ); if( !plist.size() ) ERROR_OUT( "Failed to get element description: %s" , elem_name ); if( elem_name=="vertex" ) { foundData = true; _pCount = num_elems , _pIdx = 0; bool* properties = new bool[ _factory.plyReadNum() ]; for( unsigned int i=0 ; i<_factory.plyReadNum() ; i++ ) { PlyProperty prop = _factory.isStaticallyAllocated() ? _factory.plyStaticReadProperty(i) : _factory.plyReadProperty(i); if( !_ply->get_property( elem_name , &prop ) ) properties[i] = false; else properties[i] = true; } bool valid = _factory.plyValidReadProperties( properties ); delete[] properties; if( !valid ) ERROR_OUT( "Failed to validate properties in file" ); } } if( !foundData ) ERROR_OUT( "Could not find data in ply file" ); } template< typename Factory > void PLYInputDataStream< Factory >::_free( void ){ delete _ply; } template< typename Factory > PLYInputDataStream< Factory >::~PLYInputDataStream( void ) { _free(); if( _fileName ) delete[] _fileName , _fileName = NULL; if( _buffer ) delete[] _buffer , _buffer = NULL; } template< typename Factory > bool PLYInputDataStream< Factory >::next( Data &d ) { if( _pIdx<_pCount ) { d = _factory(); if( _factory.isStaticallyAllocated() ) _ply->get_element( (void *)&d ); else { _ply->get_element( (void *)_buffer ); _factory.fromBuffer( _buffer , d ); } _pIdx++; return true; } else return false; } ///////////////////////// // PLYOutputDataStream // ///////////////////////// template< typename Factory > PLYOutputDataStream< Factory >::PLYOutputDataStream( const char* fileName , const Factory &factory , size_t count , int fileType ) : _factory(factory) { float version; std::vector< std::string > elem_names = { std::string( "vertex" ) }; _ply = PlyFile::Write( fileName , elem_names , fileType , version ); if( !_ply ) ERROR_OUT( "Failed to open ply file for writing: " , fileName ); _pIdx = 0; _pCount = count; _ply->element_count( "vertex" , _pCount ); for( unsigned int i=0 ; i<_factory.plyWriteNum() ; i++ ) { PlyProperty prop = _factory.isStaticallyAllocated() ? _factory.plyStaticWriteProperty(i) : _factory.plyWriteProperty(i); _ply->describe_property( "vertex" , &prop ); } _ply->header_complete(); _ply->put_element_setup( "vertex" ); if( _factory.bufferSize() ) _buffer = new char[ _factory.bufferSize() ]; else _buffer = NULL; } template< typename Factory > PLYOutputDataStream< Factory >::~PLYOutputDataStream( void ) { if( _pIdx!=_pCount ) ERROR_OUT( "Streamed points not equal to total count: " , _pIdx , " != " , _pCount ); delete _ply; if( _buffer ) delete[] _buffer , _buffer = NULL; } template< typename Factory > void PLYOutputDataStream< Factory >::next( const Data &d ) { if( _pIdx==_pCount ) ERROR_OUT( "Trying to add more points than total: " , _pIdx , " < " , _pCount ); if( _factory.isStaticallyAllocated() ) _ply->put_element( (void *)&d ); else { _factory.toBuffer( d , _buffer ); _ply->put_element( (void *)_buffer ); } _pIdx++; }
3,005
2,338
<reponame>mkinsner/llvm<filename>cross-project-tests/debuginfo-tests/dexter-tests/dbg-arg.c // REQUIRES: lldb // UNSUPPORTED: system-windows // // This test case checks debug info during register moves for an argument. // RUN: %dexter --fail-lt 1.0 -w \ // RUN: --builder clang-c --debugger 'lldb' \ // RUN: --cflags "-m64 -mllvm -fast-isel=false -g" -- %s // // Radar 8412415 struct _mtx { long unsigned int ptr; int waiters; struct { int tag; int pad; } mtxi; }; int foobar(struct _mtx *mutex) { int r = 1; int l = 0; // DexLabel('l_assign') int j = 0; do { if (mutex->waiters) { r = 2; } j = bar(r, l); ++l; } while (l < j); return r + j; } int bar(int i, int j) { return i + j; } int main() { struct _mtx m; m.waiters = 0; return foobar(&m); } /* DexExpectProgramState({ 'frames': [ { 'location': { 'lineno': ref('l_assign') }, 'watches': { '*mutex': { 'is_irretrievable': False } } } ] }) */
466
393
<filename>DMHY/NavigationView.h<gh_stars>100-1000 // // NavigationView.h // DMHY // // Created by ๅฐ็ฌ ๅŽŸใ‚„ใใ‚“ on 9/9/15. // Copyright ยฉ 2015 yaqinking. All rights reserved. // #import <Cocoa/Cocoa.h> @interface NavigationView : NSView @end
103
401
/* * Hedgewars, a free turn based strategy game * Copyright (C) 2012 <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "room.h" #include "../util/logging.h" #include <stdlib.h> void flib_room_destroy(flib_room *room) { if(room) { free(room->map); free(room->name); free(room->owner); free(room->scheme); free(room->weapons); free(room); } }
357
945
<reponame>floryst/ITK<gh_stars>100-1000 /*: Self-sorting in-place generalized prime factor (complex) double fft */ extern int v3p_netlib_dgpfa_( v3p_netlib_doublereal *a, /*!< (IN/OUT) Real part of input/output vectors */ v3p_netlib_doublereal *b, /*!< (IN/OUT) Imaginary part of input/output vectors */ v3p_netlib_doublereal v3p_netlib_const *trigs, /*!< (IN) output of dsetgfpa_ (twiddle factors) */ v3p_netlib_integer v3p_netlib_const *inc, /*!< (IN) increment within each data vector (normally 1) */ v3p_netlib_integer v3p_netlib_const *jump, /*!< (IN) increment between data vectors */ v3p_netlib_integer v3p_netlib_const *n, /*!< (IN) length of the transforms; should only have 2,3,5 as prime factors */ v3p_netlib_integer v3p_netlib_const *lot, /*!< (IN) number of transforms */ v3p_netlib_integer v3p_netlib_const *isign, /*!< (IN) forward transform: +1; backward: -1 */ v3p_netlib_integer v3p_netlib_const *npqr /*!< (IN) 3-array with the number of factors of 2,3,5 */ );
389
669
<filename>onnxruntime/test/testdata/custom_execution_provider_library/my_ep_factory.cc // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "core/common/gsl_suppress.h" #include "my_ep_factory.h" #include "my_execution_provider.h" #include "core/providers/shared/common.h" #include <iostream> #include "core/framework/provider_options_utils.h" using namespace onnxruntime; namespace onnxruntime { struct MyProviderFactory : IExecutionProviderFactory { MyProviderFactory(const MyProviderInfo& info) : info_{info} {} ~MyProviderFactory() override {} std::unique_ptr<IExecutionProvider> CreateProvider() override; private: MyProviderInfo info_; }; std::unique_ptr<IExecutionProvider> MyProviderFactory::CreateProvider() { std::cout << "My EP provider created, with device id: " << info_.device_id << ", some_option: " << info_.some_config << std::endl; return std::make_unique<MyExecutionProvider>(info_); } std::shared_ptr<IExecutionProviderFactory> CreateExecutionProviderFactory_MyEP(const MyProviderInfo& info) { return std::make_shared<onnxruntime::MyProviderFactory>(info); } struct MyEP_Provider : Provider { GSL_SUPPRESS(c.35) std::shared_ptr<IExecutionProviderFactory> CreateExecutionProviderFactory(const void* provider_options) override { ProviderOptions* options = (ProviderOptions*)(provider_options); MyProviderInfo info; ORT_THROW_IF_ERROR( ProviderOptionsParser{} .AddValueParser( "device_id", [&info](const std::string& value_str) -> Status { ORT_RETURN_IF_ERROR(ParseStringWithClassicLocale(value_str, info.device_id)); return Status::OK(); }) .AddValueParser( "some_config", [&info](const std::string& value_str) -> Status { ORT_RETURN_IF_ERROR(ParseStringWithClassicLocale(value_str, info.some_config)); return Status::OK(); }) .Parse(*options)); return std::make_shared<MyProviderFactory>(info); } void Initialize() override { } void Shutdown() override { } } g_provider; } // namespace onnxruntime extern "C" { ORT_API(onnxruntime::Provider*, GetProvider) { return &onnxruntime::g_provider; } ORT_API(size_t, ProviderHashFunc, const void* provider_options){ ProviderOptions* options = (ProviderOptions*)(provider_options); MyProviderInfo info; ORT_IGNORE_RETURN_VALUE(ProviderOptionsParser{} .AddValueParser( "device_id", [&info](const std::string& value_str) -> Status { ORT_RETURN_IF_ERROR(ParseStringWithClassicLocale(value_str, info.device_id)); return Status::OK(); }) .AddValueParser( "some_config", [&info](const std::string& value_str) -> Status { ORT_RETURN_IF_ERROR(ParseStringWithClassicLocale(value_str, info.some_config)); return Status::OK(); }) .Parse(*options)); // use device id as hash key return info.device_id; } }
1,232
14,668
<gh_stars>1000+ // Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_SECURITY_STATE_CONTENT_ANDROID_SECURITY_STATE_CLIENT_H_ #define COMPONENTS_SECURITY_STATE_CONTENT_ANDROID_SECURITY_STATE_CLIENT_H_ #include <memory> #include "components/security_state/content/android/security_state_model_delegate.h" namespace security_state { class SecurityStateClient; void SetSecurityStateClient(SecurityStateClient* security_state_client); SecurityStateClient* GetSecurityStateClient(); class SecurityStateClient { public: SecurityStateClient() = default; ~SecurityStateClient() = default; // Create a SecurityStateModelDelegate. This can return a nullptr. virtual std::unique_ptr<SecurityStateModelDelegate> MaybeCreateSecurityStateModelDelegate(); }; } // namespace security_state #endif // COMPONENTS_SECURITY_STATE_CONTENT_ANDROID_SECURITY_STATE_CLIENT_H_
305
852
<reponame>ckamtsikis/cmssw #ifndef CSCSPCounters_h #define CSCSPCounters_h #include <cstring> class CSCSPCounters { private: // Block of counters /////// word 1 /////// unsigned track_counter_low : 15; // unsigned zero_1 : 1; // /////// word 2 /////// unsigned track_counter_high : 15; // unsigned zero_2 : 1; // /////// word 3 /////// unsigned orbit_counter_low : 15; // unsigned zero_3 : 1; // /////// word 4 /////// unsigned orbit_counter_high : 15; // unsigned zero_4 : 1; // friend class CSCTFPacker; public: bool check(void) const throw() { return zero_1 != 0 || zero_2 != 0 || zero_3 != 0 || zero_4 != 0; } bool unpack(const unsigned short *&buf) throw() { std::memcpy((void *)this, buf, 4 * sizeof(short)); buf += 4; return check(); } int track_counter(void) const throw() { return (track_counter_high << 15) | track_counter_low; } int orbit_counter(void) const throw() { return (orbit_counter_high << 15) | orbit_counter_low; } CSCSPCounters(void) {} }; #endif
434
2,872
{ "editor.insertSpaces": true, "editor.tabSize": 2, // For eslint "eslint.enable": true, "eslint.autoFixOnSave": true, "tslint.enable": false, // For flow "flow.runOnAllFiles": true, "flow.useNPMPackagedFlow": true, "javascript.validate.enable": false, }
111
450
<reponame>YangHao666666/hawq<filename>src/backend/cdb/cdbdisp.c /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*------------------------------------------------------------------------- * * cdbdisp.c * Functions to dispatch commands to QExecutors. * *------------------------------------------------------------------------- */ #include "postgres.h" #include <pthread.h> #include <limits.h> #ifdef HAVE_POLL_H #include <poll.h> #endif #ifdef HAVE_SYS_POLL_H #include <sys/poll.h> #endif #include "catalog/catquery.h" #include "executor/execdesc.h" /* QueryDesc */ #include "storage/ipc.h" /* For proc_exit_inprogress */ #include "miscadmin.h" #include "utils/memutils.h" #include "utils/tqual.h" /*for the snapshot */ #include "storage/proc.h" /* MyProc */ #include "storage/procarray.h" /* updateSharedLocalSnapshot */ #include "access/xact.h" /*for GetCurrentTransactionId */ #include "utils/syscache.h" #include "utils/lsyscache.h" #include "catalog/pg_authid.h" #include "catalog/pg_proc.h" #include "catalog/pg_type.h" #include "nodes/makefuncs.h" #include "utils/datum.h" #include "utils/guc.h" #include "utils/faultinjector.h" #include "executor/executor.h" #include "optimizer/clauses.h" #include "optimizer/planmain.h" #include "tcop/tcopprot.h" #include "cdb/cdbplan.h" #include "postmaster/syslogger.h" #include "cdb/cdbselect.h" #include "cdb/cdbdisp.h" #include "cdb/cdbdispatchresult.h" #include "cdb/cdbfts.h" #include "cdb/cdbgang.h" #include "cdb/cdblink.h" /* just for our CdbProcess population hack. */ #include "cdb/cdbsrlz.h" #include "cdb/cdbsubplan.h" #include "cdb/cdbvars.h" #include "cdb/cdbllize.h" #include "cdb/cdbsreh.h" #include "cdb/cdbrelsize.h" #include "gp-libpq-fe.h" #include "libpq/libpq-be.h" #include "commands/vacuum.h" /* VUpdatedStats */ #include "cdb/cdbanalyze.h" /* cdbanalyze_get_columnstats */ #include "parser/parsetree.h" #include "parser/parse_oper.h" #include "parser/parse_relation.h" #include "utils/builtins.h" #include "utils/portal.h" #include "cdb/cdbinmemheapam.h" extern bool Test_print_direct_dispatch_info; extern pthread_t main_tid; #ifndef _WIN32 #define mythread() ((unsigned long) pthread_self()) #else #define mythread() ((unsigned long) pthread_self().p) #endif static void bindCurrentOfParams(char *cursor_name, Oid target_relid, ItemPointer ctid, int *gp_segment_id, Oid *tableoid); #define GP_PARTITION_SELECTION_OID 6084 #define GP_PARTITION_EXPANSION_OID 6085 #define GP_PARTITION_INVERSE_OID 6086 /* * We need an array describing the relationship between a slice and * the number of "child" slices which depend on it. */ typedef struct { int sliceIndex; int children; Slice *slice; } sliceVec; /* determines which dispatchOptions need to be set. */ /*static int generateTxnOptions(bool needTwoPhase);*/ typedef struct { plan_tree_base_prefix base; /* Required prefix for plan_tree_walker/mutator */ bool single_row_insert; } pre_dispatch_function_evaluation_context; static Node *pre_dispatch_function_evaluation_mutator(Node *node, pre_dispatch_function_evaluation_context * context); /* * We can't use elog to write to the log if we are running in a thread. * * So, write some thread-safe routines to write to the log. * * Ugly: This write in a fixed format, and ignore what the log_prefix guc says. */ static pthread_mutex_t send_mutex = PTHREAD_MUTEX_INITIALIZER; #ifdef WIN32 static void write_eventlog(int level, const char *line); /* * Write a message line to the windows event log */ static void write_eventlog(int level, const char *line) { int eventlevel = EVENTLOG_ERROR_TYPE; static HANDLE evtHandle = INVALID_HANDLE_VALUE; if (evtHandle == INVALID_HANDLE_VALUE) { evtHandle = RegisterEventSource(NULL, "PostgreSQL"); if (evtHandle == NULL) { evtHandle = INVALID_HANDLE_VALUE; return; } } ReportEvent(evtHandle, eventlevel, 0, 0, /* All events are Id 0 */ NULL, 1, 0, &line, NULL); } #endif /* WIN32 */ void get_timestamp(char * strfbuf, int length) { pg_time_t stamp_time; char msbuf[8]; struct timeval tv; gettimeofday(&tv, NULL); stamp_time = tv.tv_sec; pg_strftime(strfbuf, length, /* leave room for microseconds... */ /* Win32 timezone names are too long so don't print them */ #ifndef WIN32 "%Y-%m-%d %H:%M:%S %Z", #else "%Y-%m-%d %H:%M:%S ", #endif pg_localtime(&stamp_time, log_timezone ? log_timezone : gmt_timezone)); /* 'paste' milliseconds into place... */ sprintf(msbuf, ".%06d", (int) (tv.tv_usec)); strncpy(strfbuf + 19, msbuf, 7); } void write_log(const char *fmt,...) { char logprefix[1024]; char tempbuf[25]; va_list ap; fmt = _(fmt); va_start(ap, fmt); if (Redirect_stderr && gp_log_format == 1) { char errbuf[2048]; /* Arbitrary size? */ vsnprintf(errbuf, sizeof(errbuf), fmt, ap); /* Write the message in the CSV format */ write_message_to_server_log(LOG, 0, errbuf, NULL, NULL, NULL, 0, 0, NULL, NULL, NULL, false, NULL, 0, 0, true, /* This is a real hack... We want to send alerts on these errors, but we aren't using ereport() */ strstr(errbuf, "Master unable to connect") != NULL || strstr(errbuf, "Found a fault with a segment") != NULL, NULL, false); va_end(ap); return; } get_timestamp(logprefix, sizeof(logprefix)); strcat(logprefix,"|"); if (MyProcPort) { const char *username = MyProcPort->user_name; if (username == NULL || *username == '\0') username = ""; strcat(logprefix,username); /* user */ } strcat(logprefix,"|"); if (MyProcPort) { const char *dbname = MyProcPort->database_name; if (dbname == NULL || *dbname == '\0') dbname = ""; strcat(logprefix, dbname); } strcat(logprefix,"|"); sprintf(tempbuf,"%d",MyProcPid); strcat(logprefix,tempbuf); /* pid */ strcat(logprefix,"|"); sprintf(tempbuf,"con%d cmd%d",gp_session_id,gp_command_count); strcat(logprefix,tempbuf); strcat(logprefix,"|"); strcat(logprefix,":-THREAD "); if (pthread_equal(main_tid, pthread_self())) strcat(logprefix,"MAIN"); else { sprintf(tempbuf,"%lu",mythread()); strcat(logprefix,tempbuf); } strcat(logprefix,": "); strcat(logprefix,fmt); if (fmt[strlen(fmt)-1]!='\n') strcat(logprefix,"\n"); /* * We don't trust that vfprintf won't get confused if it * is being run by two threads at the same time, which could * cause interleaved messages. Let's play it safe, and * make sure only one thread is doing this at a time. */ pthread_mutex_lock(&send_mutex); #ifndef WIN32 /* On Unix, we just fprintf to stderr */ vfprintf(stderr, logprefix, ap); fflush(stderr); #else /* * On Win32, we print to stderr if running on a console, or write to * eventlog if running as a service */ if (pgwin32_is_service()) /* Running as a service */ { char errbuf[2048]; /* Arbitrary size? */ vsnprintf(errbuf, sizeof(errbuf), logprefix, ap); write_eventlog(EVENTLOG_ERROR_TYPE, errbuf); } else { /* Not running as service, write to stderr */ vfprintf(stderr, logprefix, ap); fflush(stderr); } #endif pthread_mutex_unlock(&send_mutex); va_end(ap); } /*--------------------------------------------------------------------*/ /* * I refactored this code out of the two routines * cdbdisp_dispatchRMCommand and cdbdisp_dispatchDtxProtocolCommand * when I thought I might need it in a third place. * * Not sure if this makes things cleaner or not */ struct pg_result ** cdbdisp_returnResults(int segmentNum, CdbDispatchResults *primaryResults, StringInfo errmsgbuf, int *numresults) { CdbDispatchResults *gangResults; CdbDispatchResult *dispatchResult; PGresult **resultSets = NULL; int nslots; int nresults = 0; int i; int totalResultCount=0; /* * Allocate result set ptr array. Make room for one PGresult ptr per * primary segment db, plus a null terminator slot after the * last entry. The caller must PQclear() each PGresult and free() the * array. */ nslots = 2 * segmentNum + 1; resultSets = (struct pg_result **)calloc(nslots, sizeof(*resultSets)); if (!resultSets) ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("cdbdisp_returnResults failed: out of memory"))); /* Collect results from primary gang. */ gangResults = primaryResults; if (gangResults) { totalResultCount = gangResults->resultCount; for (i = 0; i < gangResults->resultCount; ++i) { dispatchResult = &gangResults->resultArray[i]; /* Append error messages to caller's buffer. */ cdbdisp_dumpDispatchResult(dispatchResult, false, errmsgbuf); /* Take ownership of this QE's PGresult object(s). */ nresults += cdbdisp_snatchPGresults(dispatchResult, resultSets + nresults, nslots - nresults - 1); } cdbdisp_destroyDispatchResults(gangResults); } /* Put a stopper at the end of the array. */ Assert(nresults < nslots); resultSets[nresults] = NULL; /* If our caller is interested, tell them how many sets we're returning. */ if (numresults != NULL) *numresults = totalResultCount; return resultSets; } /* * Let's evaluate all STABLE functions that have constant args before dispatch, so we get a consistent * view across QEs * * Also, if this is a single_row insert, let's evaluate nextval() and currval() before dispatching * */ static Node * pre_dispatch_function_evaluation_mutator(Node *node, pre_dispatch_function_evaluation_context * context) { Node * new_node = 0; if (node == NULL) return NULL; if (IsA(node, Param)) { Param *param = (Param *) node; /* Not replaceable, so just copy the Param (no need to recurse) */ return (Node *) copyObject(param); } else if (IsA(node, FuncExpr)) { FuncExpr *expr = (FuncExpr *) node; List *args; ListCell *arg; Expr *simple; FuncExpr *newexpr; bool has_nonconst_input; Form_pg_proc funcform; EState *estate; ExprState *exprstate; MemoryContext oldcontext; Datum const_val; bool const_is_null; int16 resultTypLen; bool resultTypByVal; Oid funcid; HeapTuple func_tuple; /* * Reduce constants in the FuncExpr's arguments. We know args is * either NIL or a List node, so we can call expression_tree_mutator * directly rather than recursing to self. */ args = (List *) expression_tree_mutator((Node *) expr->args, pre_dispatch_function_evaluation_mutator, (void *) context); funcid = expr->funcid; newexpr = makeNode(FuncExpr); newexpr->funcid = expr->funcid; newexpr->funcresulttype = expr->funcresulttype; newexpr->funcretset = expr->funcretset; newexpr->funcformat = expr->funcformat; newexpr->args = args; /* * Check for constant inputs */ has_nonconst_input = false; foreach(arg, args) { if (!IsA(lfirst(arg), Const)) { has_nonconst_input = true; break; } } if (!has_nonconst_input) { bool is_seq_func = false; bool tup_or_set; cqContext *pcqCtx; pcqCtx = caql_beginscan( NULL, cql("SELECT * FROM pg_proc " " WHERE oid = :1 ", ObjectIdGetDatum(funcid))); func_tuple = caql_getnext(pcqCtx); if (!HeapTupleIsValid(func_tuple)) elog(ERROR, "cache lookup failed for function %u", funcid); funcform = (Form_pg_proc) GETSTRUCT(func_tuple); /* can't handle set returning or row returning functions */ tup_or_set = (funcform->proretset || type_is_rowtype(funcform->prorettype)); caql_endscan(pcqCtx); /* can't handle it */ if (tup_or_set) { /* * We haven't mutated this node, but we still return the * mutated arguments. * * If we don't do this, we'll miss out on transforming function * arguments which are themselves functions we need to mutated. * For example, select foo(now()). * * See MPP-3022 for what happened when we didn't do this. */ return (Node *)newexpr; } /* * Ignored evaluation of gp_partition stable functions. * TODO: garcic12 - May 30, 2013, refactor gp_partition stable functions to be truly * stable (JIRA: MPP-19541). */ if (funcid == GP_PARTITION_SELECTION_OID || funcid == GP_PARTITION_EXPANSION_OID || funcid == GP_PARTITION_INVERSE_OID) { return (Node *)newexpr; } /* * Related to MPP-1429. Here we want to mark any statement that is * going to use a sequence as dirty. Doing this means that the * QD will flush the xlog which will also flush any xlog writes that * the sequence server might do. */ if (funcid == NEXTVAL_FUNC_OID || funcid == CURRVAL_FUNC_OID || funcid == SETVAL_FUNC_OID) { ExecutorMarkTransactionUsesSequences(); is_seq_func = true; } if (funcform->provolatile == PROVOLATILE_IMMUTABLE) /* okay */ ; else if (funcform->provolatile == PROVOLATILE_STABLE) /* okay */ ; else if (context->single_row_insert && is_seq_func) ; /* Volatile, but special sequence function */ else return (Node *)newexpr; /* * Ok, we have a function that is STABLE (or IMMUTABLE), with * constant args. Let's try to evaluate it. */ /* * To use the executor, we need an EState. */ estate = CreateExecutorState(); /* We can use the estate's working context to avoid memory leaks. */ oldcontext = MemoryContextSwitchTo(estate->es_query_cxt); /* * Prepare expr for execution. */ exprstate = ExecPrepareExpr((Expr *) newexpr, estate); /* * And evaluate it. * * It is OK to use a default econtext because none of the * ExecEvalExpr() code used in this situation will use econtext. * That might seem fortuitous, but it's not so unreasonable --- a * constant expression does not depend on context, by definition, * n'est-ce pas? */ const_val = ExecEvalExprSwitchContext(exprstate, GetPerTupleExprContext(estate), &const_is_null, NULL); /* Get info needed about result datatype */ get_typlenbyval(expr->funcresulttype, &resultTypLen, &resultTypByVal); /* Get back to outer memory context */ MemoryContextSwitchTo(oldcontext); /* Must copy result out of sub-context used by expression eval */ if (!const_is_null) const_val = datumCopy(const_val, resultTypByVal, resultTypLen); /* Release all the junk we just created */ FreeExecutorState(estate); /* * Make the constant result node. */ simple = (Expr *) makeConst(expr->funcresulttype, -1, resultTypLen, const_val, const_is_null, resultTypByVal); if (simple) /* successfully simplified it */ return (Node *) simple; } /* * The expression cannot be simplified any further, so build and * return a replacement FuncExpr node using the possibly-simplified * arguments. */ return (Node *) newexpr; } else if (IsA(node, OpExpr)) { OpExpr *expr = (OpExpr *) node; List *args; OpExpr *newexpr; /* * Reduce constants in the OpExpr's arguments. We know args is either * NIL or a List node, so we can call expression_tree_mutator directly * rather than recursing to self. */ args = (List *) expression_tree_mutator((Node *) expr->args, pre_dispatch_function_evaluation_mutator, (void *) context); /* * Need to get OID of underlying function. Okay to scribble on input * to this extent. */ set_opfuncid(expr); newexpr = makeNode(OpExpr); newexpr->opno = expr->opno; newexpr->opfuncid = expr->opfuncid; newexpr->opresulttype = expr->opresulttype; newexpr->opretset = expr->opretset; newexpr->args = args; return (Node *) newexpr; } else if (IsA(node, CurrentOfExpr)) { /* * updatable cursors * * During constant folding, the CurrentOfExpr's gp_segment_id, ctid, * and tableoid fields are filled in with observed values from the * referenced cursor. For more detail, see bindCurrentOfParams below. */ CurrentOfExpr *expr = (CurrentOfExpr *) node, *newexpr = copyObject(expr); bindCurrentOfParams(newexpr->cursor_name, newexpr->target_relid, &newexpr->ctid, &newexpr->gp_segment_id, &newexpr->tableoid); return (Node *) newexpr; } /* * For any node type not handled above, we recurse using * plan_tree_mutator, which will copy the node unchanged but try to * simplify its arguments (if any) using this routine. */ new_node = plan_tree_mutator(node, pre_dispatch_function_evaluation_mutator, (void *) context); return new_node; } /* * bindCurrentOfParams * * During constant folding, we evaluate STABLE functions to give QEs a consistent view * of the query. At this stage, we will also bind observed values of * gp_segment_id/ctid/tableoid into the CurrentOfExpr. * This binding must happen only after planning, otherwise we disrupt prepared statements. * Furthermore, this binding must occur before dispatch, because a QE lacks the * the information needed to discern whether it's responsible for the currently * positioned tuple. * * The design of this parameter binding is very tightly bound to the parse/analyze * and subsequent planning of DECLARE CURSOR. We depend on the "is_simply_updatable" * calculation of parse/analyze to decide whether CURRENT OF makes sense for the * referenced cursor. Moreover, we depend on the ensuing planning of DECLARE CURSOR * to provide the junk metadata of gp_segment_id/ctid/tableoid (per tuple). * * This function will lookup the portal given by "cursor_name". If it's simply updatable, * we'll glean gp_segment_id/ctid/tableoid from the portal's most recently fetched * (raw) tuple. We bind this information into the CurrentOfExpr to precisely identify * the currently scanned tuple, ultimately for consumption of TidScan/execQual by the QEs. */ static void bindCurrentOfParams(char *cursor_name, Oid target_relid, ItemPointer ctid, int *gp_segment_id, Oid *tableoid) { char *table_name; Portal portal; QueryDesc *queryDesc; bool found_attribute, isnull; Datum value; portal = GetPortalByName(cursor_name); if (!PortalIsValid(portal)) ereport(ERROR, (errcode(ERRCODE_INVALID_CURSOR_STATE), errmsg("cursor \"%s\" does not exist", cursor_name))); queryDesc = PortalGetQueryDesc(portal); if (queryDesc == NULL) ereport(ERROR, (errcode(ERRCODE_INVALID_CURSOR_STATE), errmsg("cursor \"%s\" is held from a previous transaction", cursor_name))); /* obtain table_name for potential error messages */ table_name = get_rel_name(target_relid); /* * The referenced cursor must be simply updatable. This has already * been discerned by parse/analyze for the DECLARE CURSOR of the given * cursor. This flag assures us that gp_segment_id, ctid, and tableoid (if necessary) * will be available as junk metadata, courtesy of preprocess_targetlist. */ if (!portal->is_simply_updatable) ereport(ERROR, (errcode(ERRCODE_INVALID_CURSOR_STATE), errmsg("cursor \"%s\" is not a simply updatable scan of table \"%s\"", cursor_name, table_name))); /* * The target relation must directly match the cursor's relation. This throws out * the simple case in which a cursor is declared against table X and the update is * issued against Y. Moreover, this disallows some subtler inheritance cases where * Y inherits from X. While such cases could be implemented, it seems wiser to * simply error out cleanly. */ Index varno = extractSimplyUpdatableRTEIndex(queryDesc->plannedstmt->rtable); Oid cursor_relid = getrelid(varno, queryDesc->plannedstmt->rtable); if (target_relid != cursor_relid) ereport(ERROR, (errcode(ERRCODE_INVALID_CURSOR_STATE), errmsg("cursor \"%s\" is not a simply updatable scan of table \"%s\"", cursor_name, table_name))); /* * The cursor must have a current result row: per the SQL spec, it's * an error if not. */ if (portal->atStart || portal->atEnd) ereport(ERROR, (errcode(ERRCODE_INVALID_CURSOR_STATE), errmsg("cursor \"%s\" is not positioned on a row", cursor_name))); /* * As mentioned above, if parse/analyze recognized this cursor as simply * updatable during DECLARE CURSOR, then its subsequent planning must have * made gp_segment_id, ctid, and tableoid available as junk for each tuple. * * To retrieve this junk metadeta, we leverage the EState's junkfilter against * the raw tuple yielded by the highest most node in the plan. */ TupleTableSlot *slot = queryDesc->planstate->ps_ResultTupleSlot; Insist(!TupIsNull(slot)); Assert(queryDesc->estate->es_junkFilter); /* extract gp_segment_id metadata */ found_attribute = ExecGetJunkAttribute(queryDesc->estate->es_junkFilter, slot, "gp_segment_id", &value, &isnull); Insist(found_attribute); Assert(!isnull); *gp_segment_id = DatumGetInt32(value); /* extract ctid metadata */ found_attribute = ExecGetJunkAttribute(queryDesc->estate->es_junkFilter, slot, "ctid", &value, &isnull); Insist(found_attribute); Assert(!isnull); ItemPointerCopy(DatumGetItemPointer(value), ctid); /* * extract tableoid metadata * * DECLARE CURSOR planning only includes tableoid metadata when * scrolling a partitioned table, as this is the only case in which * gp_segment_id/ctid alone do not suffice to uniquely identify a tuple. */ found_attribute = ExecGetJunkAttribute(queryDesc->estate->es_junkFilter, slot, "tableoid", &value, &isnull); if (found_attribute) { Assert(!isnull); *tableoid = DatumGetObjectId(value); /* * This is our last opportunity to verify that the physical table given * by tableoid is, indeed, simply updatable. */ if (!isSimplyUpdatableRelation(*tableoid)) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("%s is not updatable", get_rel_name_partition(*tableoid)))); } else *tableoid = InvalidOid; pfree(table_name); } /* * Evaluate functions to constants. */ Node * exec_make_plan_constant(struct PlannedStmt *stmt, bool is_SRI) { pre_dispatch_function_evaluation_context pcontext; Assert(stmt); exec_init_plan_tree_base(&pcontext.base, stmt); pcontext.single_row_insert = is_SRI; return plan_tree_mutator((Node *)stmt->planTree, pre_dispatch_function_evaluation_mutator, &pcontext); } Node * planner_make_plan_constant(struct PlannerInfo *root, Node *n, bool is_SRI) { pre_dispatch_function_evaluation_context pcontext; planner_init_plan_tree_base(&pcontext.base, root); pcontext.single_row_insert = is_SRI; return plan_tree_mutator(n, pre_dispatch_function_evaluation_mutator, &pcontext); }
9,189
575
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/zlib/google/zip_writer.h" #include "base/files/file.h" #include "base/logging.h" #include "base/strings/string_util.h" #include "third_party/zlib/google/zip_internal.h" namespace zip { namespace internal { namespace { // Numbers of pending entries that trigger writting them to the ZIP file. constexpr size_t kMaxPendingEntriesCount = 50; bool AddFileContentToZip(zipFile zip_file, base::File file, const base::FilePath& file_path) { int num_bytes; char buf[zip::internal::kZipBufSize]; do { num_bytes = file.ReadAtCurrentPos(buf, zip::internal::kZipBufSize); if (num_bytes > 0) { if (zipWriteInFileInZip(zip_file, buf, num_bytes) != ZIP_OK) { DLOG(ERROR) << "Could not write data to zip for path " << file_path.value(); return false; } } } while (num_bytes > 0); return true; } bool OpenNewFileEntry(zipFile zip_file, const base::FilePath& path, bool is_directory, base::Time last_modified) { std::string str_path = path.AsUTF8Unsafe(); #if defined(OS_WIN) base::ReplaceSubstringsAfterOffset(&str_path, 0u, "\\", "/"); #endif if (is_directory) str_path += "/"; return zip::internal::ZipOpenNewFileInZip(zip_file, str_path, last_modified); } bool CloseNewFileEntry(zipFile zip_file) { return zipCloseFileInZip(zip_file) == ZIP_OK; } bool AddFileEntryToZip(zipFile zip_file, const base::FilePath& path, base::File file) { base::File::Info file_info; if (!file.GetInfo(&file_info)) return false; if (!OpenNewFileEntry(zip_file, path, /*is_directory=*/false, file_info.last_modified)) return false; bool success = AddFileContentToZip(zip_file, std::move(file), path); if (!CloseNewFileEntry(zip_file)) return false; return success; } bool AddDirectoryEntryToZip(zipFile zip_file, const base::FilePath& path, base::Time last_modified) { return OpenNewFileEntry(zip_file, path, /*is_directory=*/true, last_modified) && CloseNewFileEntry(zip_file); } } // namespace #if defined(OS_POSIX) // static std::unique_ptr<ZipWriter> ZipWriter::CreateWithFd( int zip_file_fd, const base::FilePath& root_dir, FileAccessor* file_accessor) { DCHECK(zip_file_fd != base::kInvalidPlatformFile); zipFile zip_file = internal::OpenFdForZipping(zip_file_fd, APPEND_STATUS_CREATE); if (!zip_file) { DLOG(ERROR) << "Couldn't create ZIP file for FD " << zip_file_fd; return nullptr; } return std::unique_ptr<ZipWriter>( new ZipWriter(zip_file, root_dir, file_accessor)); } #endif // static std::unique_ptr<ZipWriter> ZipWriter::Create( const base::FilePath& zip_file_path, const base::FilePath& root_dir, FileAccessor* file_accessor) { DCHECK(!zip_file_path.empty()); zipFile zip_file = internal::OpenForZipping(zip_file_path.AsUTF8Unsafe(), APPEND_STATUS_CREATE); if (!zip_file) { DLOG(ERROR) << "Couldn't create ZIP file at path " << zip_file_path; return nullptr; } return std::unique_ptr<ZipWriter>( new ZipWriter(zip_file, root_dir, file_accessor)); } ZipWriter::ZipWriter(zipFile zip_file, const base::FilePath& root_dir, FileAccessor* file_accessor) : zip_file_(zip_file), root_dir_(root_dir), file_accessor_(file_accessor) {} ZipWriter::~ZipWriter() { DCHECK(pending_entries_.empty()); } bool ZipWriter::WriteEntries(const std::vector<base::FilePath>& paths) { return AddEntries(paths) && Close(); } bool ZipWriter::AddEntries(const std::vector<base::FilePath>& paths) { DCHECK(zip_file_); pending_entries_.insert(pending_entries_.end(), paths.begin(), paths.end()); return FlushEntriesIfNeeded(/*force=*/false); } bool ZipWriter::Close() { bool success = FlushEntriesIfNeeded(/*force=*/true) && zipClose(zip_file_, nullptr) == ZIP_OK; zip_file_ = nullptr; return success; } bool ZipWriter::FlushEntriesIfNeeded(bool force) { if (pending_entries_.size() < kMaxPendingEntriesCount && !force) return true; while (pending_entries_.size() >= kMaxPendingEntriesCount || (force && !pending_entries_.empty())) { size_t entry_count = std::min(pending_entries_.size(), kMaxPendingEntriesCount); std::vector<base::FilePath> relative_paths; std::vector<base::FilePath> absolute_paths; relative_paths.insert(relative_paths.begin(), pending_entries_.begin(), pending_entries_.begin() + entry_count); for (auto iter = pending_entries_.begin(); iter != pending_entries_.begin() + entry_count; ++iter) { // The FileAccessor requires absolute paths. absolute_paths.push_back(root_dir_.Append(*iter)); } pending_entries_.erase(pending_entries_.begin(), pending_entries_.begin() + entry_count); // We don't know which paths are files and which ones are directories, and // we want to avoid making a call to file_accessor_ for each entry. Open the // files instead, invalid files are returned for directories. std::vector<base::File> files = file_accessor_->OpenFilesForReading(absolute_paths); DCHECK_EQ(files.size(), relative_paths.size()); for (size_t i = 0; i < files.size(); i++) { const base::FilePath& relative_path = relative_paths[i]; const base::FilePath& absolute_path = absolute_paths[i]; base::File file = std::move(files[i]); if (file.IsValid()) { if (!AddFileEntryToZip(zip_file_, relative_path, std::move(file))) { LOG(ERROR) << "Failed to write file " << relative_path.value() << " to ZIP file."; return false; } } else { // Missing file or directory case. base::Time last_modified = file_accessor_->GetLastModifiedTime(absolute_path); if (last_modified.is_null()) { LOG(ERROR) << "Failed to write entry " << relative_path.value() << " to ZIP file."; return false; } DCHECK(file_accessor_->DirectoryExists(absolute_path)); if (!AddDirectoryEntryToZip(zip_file_, relative_path, last_modified)) { LOG(ERROR) << "Failed to write directory " << relative_path.value() << " to ZIP file."; return false; } } } } return true; } } // namespace internal } // namespace zip
2,881
679
<reponame>IzaakBirch/togglz<gh_stars>100-1000 package org.togglz.core.proxy; import java.util.function.Supplier; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.togglz.core.Feature; import org.togglz.core.manager.FeatureManager; import org.togglz.core.manager.FeatureManagerBuilder; import org.togglz.core.repository.FeatureState; import org.togglz.core.repository.mem.InMemoryStateRepository; import org.togglz.core.user.NoOpUserProvider; import static org.junit.jupiter.api.Assertions.*; class ByteBuddyProxyFactoryTest { private static final Speaker sayHello = new Speaker() { // As an anonymous class @Override public String getName() { return "Hello"; } @Override public String toString() { return "Active delegate"; } }; private static final Speaker sayWorld = () -> "World"; // As a lambda private FeatureManager featureManager; public interface Speaker extends Supplier<String> { default String get() { return getName(); } String getName(); } public interface Counter extends Supplier<Integer> { default Integer get() { return getCount(); } int getCount(); } @BeforeEach void before() { featureManager = new FeatureManagerBuilder() .featureEnum(ByteBuddyProxyFactoryTest.Features.class) .stateRepository(new InMemoryStateRepository()) .userProvider(new NoOpUserProvider()) .build(); featureManager.setFeatureState(new FeatureState(Features.F1, true)); } @Test void byteBuddyProxyHasNiceName() { // Given: Class<Speaker> interfaceClass = Speaker.class; // When: Supplier<String> proxy = ByteBuddyProxyFactory.proxyFor(Features.F1, interfaceClass, sayHello, sayWorld, featureManager); // Then: assertTrue(proxy.getClass().getName().startsWith("org.togglz.core.proxy.ByteBuddyProxyFactoryTest$Speaker$togglz$")); } @Test void byteBuddyProxyDelegatesToString() { // Given: Class<Speaker> interfaceClass = Speaker.class; // When: Supplier<String> proxy = ByteBuddyProxyFactory.proxyFor(Features.F1, interfaceClass, sayHello, sayWorld, featureManager); // Then: assertEquals("Active delegate", proxy.toString()); } @Test void byteBuddyProxyListensToFeature() { // Given: Supplier<String> proxy = ByteBuddyProxyFactory.proxyFor(Features.F1, Supplier.class, sayHello, sayWorld, featureManager); // Then: featureManager.setFeatureState(new FeatureState(Features.F1, true)); assertEquals("Hello", proxy.get()); featureManager.setFeatureState(new FeatureState(Features.F1, false)); assertEquals("World", proxy.get()); } @Test void byteBuddyPassiveProxyDelegatesToString() { // Given: Supplier<String> proxy = ByteBuddyProxyFactory.passiveProxyFor(Features.F1, Speaker.class, sayHello, sayWorld, featureManager); featureManager.setFeatureState(new FeatureState(Features.F1, false)); assertEquals("Active delegate", proxy.toString()); // When: TogglzSwitchable.update(proxy); // Then: assertNotEquals("Active delegate", proxy.toString()); } @Test void byteBuddyPassiveProxyListensToFeatureOnlyWhenUpdated() { // Given: Supplier<String> proxy = ByteBuddyProxyFactory.passiveProxyFor(Features.F1, Supplier.class, sayHello, sayWorld, featureManager); featureManager.setFeatureState(new FeatureState(Features.F1, false)); assertEquals("Hello", proxy.get()); // inactive state is ignored // When: TogglzSwitchable.update(proxy); // Then: assertEquals("World", proxy.get()); } private enum Features implements Feature { F1 } }
1,234
365
<filename>super-boot-gateway/src/main/java/org/superboot/entity/response/ResDate.java package org.superboot.entity.response; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import java.io.Serializable; /** * <b> </b> * <p> * ๅŠŸ่ƒฝๆ่ฟฐ: * </p> * * @author zhangshuai * @date 2018/4/18 * @time 15:37 * @Path cn.phxg.entity.response.ResDate */ @Data @ApiModel("ๆœๅŠกๅ™จๆ—ถ้—ดไฟกๆฏ") public class ResDate implements Serializable { @ApiModelProperty("ๅฝ“ๅ‰ๆ—ถ้—ด") private String currTime; @ApiModelProperty("ๅฝ“ๅ‰ๆ—ฅๆœŸ") private String currDate; @ApiModelProperty("ๅฝ“ๅ‰ๆœˆไปฝ") private String currMonth; @ApiModelProperty("ๅฝ“ๅ‰ๅนดไปฝ") private String currYear; @ApiModelProperty("ๅฝ“ๅ‰ๅ‘จ") private int currWeek; @ApiModelProperty("ๅฝ“ๅ‰ๅญฃๅบฆ") private int currQuarter; @ApiModelProperty("ๅฝ“ๅ‰ๅ‘จ็š„็ฌฌไธ€ๅคฉ") private String firstDayOfWeek; @ApiModelProperty("ๅฝ“ๅ‰ๅ‘จ็š„ๆœ€ๅŽไธ€ๅคฉ") private String lastDayOfWeek; @ApiModelProperty("ๅฝ“ๅ‰ๅญฃๅบฆ็š„็ฌฌไธ€ๅคฉ") private String firstDayOfQuarter; @ApiModelProperty("ๅฝ“ๅ‰ๅญฃๅบฆ็š„ๆœ€ๅŽไธ€ๅคฉ") private String lastDayOfQuarter; @ApiModelProperty("ๅฝ“ๅ‰ๆ•ฐๅญ—ๆ˜ŸๆœŸ") private int currNumXq; @ApiModelProperty("ๅฝ“ๅ‰ไธญๆ–‡ๆ˜ŸๆœŸ") private String currCnXq; @ApiModelProperty("ๅฝ“ๆœˆ่ตทๅง‹ๆ—ฅๆœŸ") private String beginDate; @ApiModelProperty("ๅฝ“ๆœˆๆˆชๆญขๆ—ฅๆœŸ") private String endDate; @ApiModelProperty("ๆ˜ฏๅฆ็‘žๅนด") private boolean leapYear; }
692
743
<filename>pebble/src/main/java/com/mitchellbosecke/pebble/extension/ExtensionRegistryFactory.java package com.mitchellbosecke.pebble.extension; import com.mitchellbosecke.pebble.extension.core.AttributeResolverExtension; import com.mitchellbosecke.pebble.extension.core.CoreExtension; import com.mitchellbosecke.pebble.extension.escaper.EscaperExtension; import com.mitchellbosecke.pebble.extension.escaper.EscapingStrategy; import com.mitchellbosecke.pebble.extension.i18n.I18nExtension; import java.util.*; import java.util.function.Function; import java.util.stream.Stream; /** * Provides configuration methods and builds the {@link ExtensionRegistry}. Used only internally by * the {@link com.mitchellbosecke.pebble.PebbleEngine.Builder}. * */ public class ExtensionRegistryFactory { private final List<Extension> userProvidedExtensions = new ArrayList<>(); private final EscaperExtension escaperExtension = new EscaperExtension(); private boolean allowOverrideCoreOperators = false; private Function<Extension, Extension> customizer = Function.identity(); public ExtensionRegistry buildExtensionRegistry() { ExtensionRegistry extensionRegistry = new ExtensionRegistry(); Stream.of(new CoreExtension(), this.escaperExtension, new I18nExtension()) .map(customizer::apply) .forEach(extensionRegistry::addExtension); for (Extension userProvidedExtension : this.userProvidedExtensions) { if (this.allowOverrideCoreOperators) { extensionRegistry.addOperatorOverridingExtension(userProvidedExtension); } else { extensionRegistry.addExtension(userProvidedExtension); } } extensionRegistry.addExtension(customizer.apply(new AttributeResolverExtension())); return extensionRegistry; } public void autoEscaping(boolean autoEscaping) { this.escaperExtension.setAutoEscaping(autoEscaping); } public void addEscapingStrategy(String name, EscapingStrategy strategy) { this.escaperExtension.addEscapingStrategy(name, strategy); } public void extension(Extension... extensions) { Collections.addAll(this.userProvidedExtensions, extensions); } public void allowOverrideCoreOperators(boolean allowOverrideCoreOperators) { this.allowOverrideCoreOperators = allowOverrideCoreOperators; } public void defaultEscapingStrategy(String strategy) { this.escaperExtension.setDefaultStrategy(strategy); } public void registerExtensionCustomizer(Function<Extension, ExtensionCustomizer> customizer) { this.customizer = customizer::apply; } }
827
374
<gh_stars>100-1000 /* * Copyright (c) 2017 Trail of Bits, 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. */ #pragma once namespace { template <typename D, typename S1> DEF_SEM(CMOVNLE, D dst, S1 src1) { WriteZExt( dst, Select(__remill_compare_sgt(BAnd(BNot(FLAG_ZF), BXnor(FLAG_SF, FLAG_OF))), Read(src1), TruncTo<S1>(Read(dst)))); return memory; } template <typename D, typename S1> DEF_SEM(CMOVNS, D dst, S1 src1) { WriteZExt(dst, Select(BNot(FLAG_SF), Read(src1), TruncTo<S1>(Read(dst)))); return memory; } template <typename D, typename S1> DEF_SEM(CMOVL, D dst, S1 src1) { WriteZExt(dst, Select(__remill_compare_slt(BXor(FLAG_SF, FLAG_OF)), Read(src1), TruncTo<S1>(Read(dst)))); return memory; } template <typename D, typename S1> DEF_SEM(CMOVNP, D dst, S1 src1) { WriteZExt(dst, Select(BNot(FLAG_PF), Read(src1), TruncTo<S1>(Read(dst)))); return memory; } template <typename D, typename S1> DEF_SEM(CMOVNZ, D dst, S1 src1) { WriteZExt(dst, Select(__remill_compare_neq(BNot(FLAG_ZF)), Read(src1), TruncTo<S1>(Read(dst)))); return memory; } template <typename D, typename S1> DEF_SEM(CMOVNB, D dst, S1 src1) { WriteZExt(dst, Select(__remill_compare_uge(BNot(FLAG_CF)), Read(src1), TruncTo<S1>(Read(dst)))); return memory; } template <typename D, typename S1> DEF_SEM(CMOVNO, D dst, S1 src1) { WriteZExt(dst, Select(BNot(FLAG_OF), Read(src1), TruncTo<S1>(Read(dst)))); return memory; } template <typename D, typename S1> DEF_SEM(CMOVNL, D dst, S1 src1) { WriteZExt(dst, Select(__remill_compare_sge(BXnor(FLAG_SF, FLAG_OF)), Read(src1), TruncTo<S1>(Read(dst)))); return memory; } template <typename D, typename S1> DEF_SEM(CMOVNBE, D dst, S1 src1) { WriteZExt(dst, Select(__remill_compare_ugt(BNot(BOr(FLAG_CF, FLAG_ZF))), Read(src1), TruncTo<S1>(Read(dst)))); return memory; } template <typename D, typename S1> DEF_SEM(CMOVBE, D dst, S1 src1) { WriteZExt(dst, Select(__remill_compare_ule(BOr(FLAG_CF, FLAG_ZF)), Read(src1), TruncTo<S1>(Read(dst)))); return memory; } template <typename D, typename S1> DEF_SEM(CMOVZ, D dst, S1 src1) { WriteZExt(dst, Select(__remill_compare_eq(FLAG_ZF), Read(src1), TruncTo<S1>(Read(dst)))); return memory; } template <typename D, typename S1> DEF_SEM(CMOVP, D dst, S1 src1) { WriteZExt(dst, Select(FLAG_PF, Read(src1), TruncTo<S1>(Read(dst)))); return memory; } template <typename D, typename S1> DEF_SEM(CMOVS, D dst, S1 src1) { WriteZExt(dst, Select(FLAG_SF, Read(src1), TruncTo<S1>(Read(dst)))); return memory; } template <typename D, typename S1> DEF_SEM(CMOVO, D dst, S1 src1) { WriteZExt(dst, Select(FLAG_OF, Read(src1), TruncTo<S1>(Read(dst)))); return memory; } template <typename D, typename S1> DEF_SEM(CMOVB, D dst, S1 src1) { WriteZExt(dst, Select(__remill_compare_ult(FLAG_CF), Read(src1), TruncTo<S1>(Read(dst)))); return memory; } template <typename D, typename S1> DEF_SEM(CMOVLE, D dst, S1 src1) { WriteZExt(dst, Select(__remill_compare_sle(BOr(FLAG_ZF, BXor(FLAG_SF, FLAG_OF))), Read(src1), TruncTo<S1>(Read(dst)))); return memory; } } // namespace DEF_ISEL_RnW_Mn(CMOVBE_GPRv_MEMv, CMOVBE); DEF_ISEL_RnW_Rn(CMOVBE_GPRv_GPRv, CMOVBE); DEF_ISEL_RnW_Mn(CMOVLE_GPRv_MEMv, CMOVLE); DEF_ISEL_RnW_Rn(CMOVLE_GPRv_GPRv, CMOVLE); DEF_ISEL_RnW_Mn(CMOVNLE_GPRv_MEMv, CMOVNLE); DEF_ISEL_RnW_Rn(CMOVNLE_GPRv_GPRv, CMOVNLE); DEF_ISEL_RnW_Mn(CMOVNP_GPRv_MEMv, CMOVNP); DEF_ISEL_RnW_Rn(CMOVNP_GPRv_GPRv, CMOVNP); DEF_ISEL_RnW_Mn(CMOVNZ_GPRv_MEMv, CMOVNZ); DEF_ISEL_RnW_Rn(CMOVNZ_GPRv_GPRv, CMOVNZ); DEF_ISEL_RnW_Mn(CMOVNS_GPRv_MEMv, CMOVNS); DEF_ISEL_RnW_Rn(CMOVNS_GPRv_GPRv, CMOVNS); DEF_ISEL_RnW_Mn(CMOVNO_GPRv_MEMv, CMOVNO); DEF_ISEL_RnW_Rn(CMOVNO_GPRv_GPRv, CMOVNO); DEF_ISEL_RnW_Mn(CMOVNL_GPRv_MEMv, CMOVNL); DEF_ISEL_RnW_Rn(CMOVNL_GPRv_GPRv, CMOVNL); DEF_ISEL_RnW_Mn(CMOVNB_GPRv_MEMv, CMOVNB); DEF_ISEL_RnW_Rn(CMOVNB_GPRv_GPRv, CMOVNB); DEF_ISEL_RnW_Mn(CMOVO_GPRv_MEMv, CMOVO); DEF_ISEL_RnW_Rn(CMOVO_GPRv_GPRv, CMOVO); DEF_ISEL_RnW_Mn(CMOVZ_GPRv_MEMv, CMOVZ); DEF_ISEL_RnW_Rn(CMOVZ_GPRv_GPRv, CMOVZ); DEF_ISEL_RnW_Mn(CMOVP_GPRv_MEMv, CMOVP); DEF_ISEL_RnW_Rn(CMOVP_GPRv_GPRv, CMOVP); DEF_ISEL_RnW_Mn(CMOVS_GPRv_MEMv, CMOVS); DEF_ISEL_RnW_Rn(CMOVS_GPRv_GPRv, CMOVS); DEF_ISEL_RnW_Mn(CMOVL_GPRv_MEMv, CMOVL); DEF_ISEL_RnW_Rn(CMOVL_GPRv_GPRv, CMOVL); DEF_ISEL_RnW_Mn(CMOVB_GPRv_MEMv, CMOVB); DEF_ISEL_RnW_Rn(CMOVB_GPRv_GPRv, CMOVB); DEF_ISEL_RnW_Mn(CMOVNBE_GPRv_MEMv, CMOVNBE); DEF_ISEL_RnW_Rn(CMOVNBE_GPRv_GPRv, CMOVNBE);
2,730
2,400
<reponame>mayurhole/optaplanner<filename>optaplanner-core/src/main/java/org/optaplanner/core/impl/score/stream/quad/AbstractQuadJoiner.java /* * Copyright 2020 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.optaplanner.core.impl.score.stream.quad; import java.util.ArrayList; import java.util.List; import java.util.function.Function; import org.optaplanner.core.api.function.QuadPredicate; import org.optaplanner.core.api.function.TriFunction; import org.optaplanner.core.api.score.stream.quad.QuadJoiner; import org.optaplanner.core.impl.score.stream.common.AbstractJoiner; import org.optaplanner.core.impl.score.stream.common.JoinerType; public abstract class AbstractQuadJoiner<A, B, C, D> extends AbstractJoiner implements QuadJoiner<A, B, C, D> { private final QuadPredicate<A, B, C, D> filter; protected AbstractQuadJoiner() { this.filter = null; } protected AbstractQuadJoiner(QuadPredicate<A, B, C, D> filter) { this.filter = filter; } @SafeVarargs public static <A, B, C, D> AbstractQuadJoiner<A, B, C, D> merge(QuadJoiner<A, B, C, D>... joiners) { List<SingleQuadJoiner<A, B, C, D>> joinerList = new ArrayList<>(); for (QuadJoiner<A, B, C, D> joiner : joiners) { if (joiner instanceof NoneQuadJoiner) { // Ignore it } else if (joiner instanceof SingleQuadJoiner) { joinerList.add((SingleQuadJoiner<A, B, C, D>) joiner); } else if (joiner instanceof CompositeQuadJoiner) { joinerList.addAll(((CompositeQuadJoiner<A, B, C, D>) joiner).getJoinerList()); } else { throw new IllegalArgumentException("The joiner class (" + joiner.getClass() + ") is not supported."); } } if (joinerList.isEmpty()) { return new NoneQuadJoiner<>(); } else if (joinerList.size() == 1) { return joinerList.get(0); } return new CompositeQuadJoiner<>(joinerList); } public boolean matches(A a, B b, C c, D d) { JoinerType[] joinerTypes = getJoinerTypes(); for (int i = 0; i < joinerTypes.length; i++) { JoinerType joinerType = joinerTypes[i]; Object leftMapping = getLeftMapping(i).apply(a, b, c); Object rightMapping = getRightMapping(i).apply(d); if (!joinerType.matches(leftMapping, rightMapping)) { return false; } } return true; } public abstract TriFunction<A, B, C, Object> getLeftMapping(int index); public abstract TriFunction<A, B, C, Object[]> getLeftCombinedMapping(); public abstract Function<D, Object> getRightMapping(int index); public abstract Function<D, Object[]> getRightCombinedMapping(); public QuadPredicate<A, B, C, D> getFilter() { return filter; } }
1,381
798
<gh_stars>100-1000 package picard.util; import htsjdk.samtools.util.Md5CalculatingInputStream; import htsjdk.samtools.util.Md5CalculatingOutputStream; import org.testng.Assert; import org.testng.annotations.Test; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.util.Random; /** * Tests for the FifoBuffer class. Generates (deterministically!) random files of certain sizes * and then pipes them through the FifoBuffer class and checks that input and output MD5s match. */ public class FifoBufferTest { /* Simply invokes the real test method many times with different inputs. */ @Test public void testFifoBuffer() throws IOException { test(1); test(2); test(3); test(4); test(5); test(6); test(7); test(8); test(9); test(10); test(10.1345); test(150); } /** * Writes a file of the given size in megabytes fill with random bytes, initialized using (int) megabytes as the * seed to the random number generator. Then pipes through FifoBuffer and confirms that output == input via md5. */ public void test(final double megabytes) throws IOException { final File inputFile = File.createTempFile("fifo_input.", ".foo"); inputFile.deleteOnExit(); // Generate a file with a set number of megabytes of random data final int nBytes = (int) (megabytes * 1024 * 1024); { final Random random = new Random(nBytes); final BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(inputFile)); final int bytesPerWrite = 127; final byte[] bytes = new byte[bytesPerWrite]; for (int i=0; i<nBytes; i+=bytesPerWrite) { random.nextBytes(bytes); out.write(bytes); } out.close(); } // Run the input file through the FifoBuffer and back into another file final Md5CalculatingInputStream in = new Md5CalculatingInputStream(new FileInputStream(inputFile), (File) null); final Md5CalculatingOutputStream out = new Md5CalculatingOutputStream(new FileOutputStream("/dev/null"), (File) null); final PrintStream outStream = new PrintStream(out); final FifoBuffer buffer = new FifoBuffer(in, outStream); buffer.BUFFER_SIZE = 128 * 1024 * 1024; buffer.doWork(); in.close(); out.close(); final String inputMd5 = in.md5(); final String outputMd5 = out.md5(); Assert.assertEquals(outputMd5, inputMd5, "MD5s do not match between input and output."); inputFile.delete(); } }
1,104
393
package pl.otros.swing.rulerbar; import javax.swing.text.JTextComponent; import java.awt.*; public class LineInTextMarker extends Marker { private final int caretPosition; private final JTextComponent textComponent; public LineInTextMarker(String message, Color color, float percentValue, int caretPosition, JTextComponent jTextPane) { super(message, color, percentValue); this.caretPosition = caretPosition; textComponent = jTextPane; } @Override public void markerClicked() { textComponent.setCaretPosition(caretPosition); } @Override public String toString() { return "LineInTextMarker [caretPosition=" + caretPosition + ", message=" + message + "]"; } }
292
435
<reponame>cirnoftw/android-openslmediaplayer // // Copyright (C) 2014 <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. // #ifndef AUDIODATATYPES_HPP_ #define AUDIODATATYPES_HPP_ #include <cstddef> namespace oslmp { namespace impl { enum sample_format_type { kAudioSampleFormatType_Unknown, kAudioSampleFormatType_S16, kAudioSampleFormatType_F32, }; inline size_t getBytesPerSample(sample_format_type fmt) { switch (fmt) { case kAudioSampleFormatType_S16: return 2; case kAudioSampleFormatType_F32: return 4; default: return 0; } } } // namespace impl } // namespace oslmp #endif // AUDIODATATYPES_HPP_
427
11,884
<reponame>zouxifeng/teleport /* Copyright 2021 Gravitational, 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. */ #include "../vmlinux.h" #include <bpf/bpf_helpers.h> /* most used helpers: SEC, __always_inline, etc */ #include <bpf/bpf_core_read.h> /* for BPF CO-RE helpers */ #include <bpf/bpf_tracing.h> /* for getting kprobe arguments */ #include "../helpers.h" char LICENSE[] SEC("license") = "Dual BSD/GPL"; // Maximum number of in-flight connect syscalls supported #define INFLIGHT_MAX 8192 // Size, in bytes, of the ring buffer used to report // audit events to userspace. This is the default, // the userspace can adjust this value based on config. #define EVENTS_BUF_SIZE (4096*8) BPF_HASH(currsock, u32, struct sock *, INFLIGHT_MAX); // separate data structs for ipv4 and ipv6 struct ipv4_data_t { u64 cgroup; u64 ip; u32 pid; u32 saddr; u32 daddr; u16 dport; char task[TASK_COMM_LEN]; }; BPF_RING_BUF(ipv4_events, EVENTS_BUF_SIZE); struct ipv6_data_t { u64 cgroup; u64 ip; u32 pid; struct in6_addr saddr; struct in6_addr daddr; u16 dport; char task[TASK_COMM_LEN]; }; BPF_RING_BUF(ipv6_events, EVENTS_BUF_SIZE); BPF_COUNTER(lost); static int trace_connect_entry(struct sock *sk) { u32 id = bpf_get_current_pid_tgid(); // Stash the sock ptr for lookup on return. bpf_map_update_elem(&currsock, &id, &sk, 0); return 0; }; static int trace_connect_return(int ret, short ipver) { u64 pid_tgid = bpf_get_current_pid_tgid(); u32 id = (u32)pid_tgid; struct sock **skpp; skpp = bpf_map_lookup_elem(&currsock, &id); if (skpp == 0) { return 0; // missed entry } if (ret != 0) { // failed to send SYNC packet, may not have populated // socket __sk_common.{skc_rcv_saddr, ...} bpf_map_delete_elem(&currsock, &id); return 0; } // pull in details struct sock *skp = *skpp; u16 dport = BPF_CORE_READ(skp, __sk_common.skc_dport); if (ipver == 4) { struct ipv4_data_t data4 = {.pid = pid_tgid >> 32, .ip = ipver}; data4.saddr = BPF_CORE_READ(skp, __sk_common.skc_rcv_saddr); data4.daddr = BPF_CORE_READ(skp, __sk_common.skc_daddr); data4.dport = __builtin_bswap16(dport); data4.cgroup = bpf_get_current_cgroup_id(); bpf_get_current_comm(&data4.task, sizeof(data4.task)); if (bpf_ringbuf_output(&ipv4_events, &data4, sizeof(data4), 0) != 0) INCR_COUNTER(lost); } else /* 6 */ { struct ipv6_data_t data6 = {.pid = pid_tgid >> 32, .ip = ipver}; BPF_CORE_READ_INTO(&data6.saddr, skp, __sk_common.skc_v6_rcv_saddr); BPF_CORE_READ_INTO(&data6.daddr, skp, __sk_common.skc_v6_daddr); data6.dport = __builtin_bswap16(dport); data6.cgroup = bpf_get_current_cgroup_id(); bpf_get_current_comm(&data6.task, sizeof(data6.task)); if (bpf_ringbuf_output(&ipv6_events, &data6, sizeof(data6), 0) != 0) INCR_COUNTER(lost); } bpf_map_delete_elem(&currsock, &id); return 0; } SEC("kprobe/tcp_v4_connect") int BPF_KPROBE(kprobe__tcp_v4_connect, struct sock *sk) { return trace_connect_entry(sk); } SEC("kretprobe/tcp_v4_connect") int kretprobe__tcp_v4_connect(struct pt_regs *ctx) { return trace_connect_return(PT_REGS_RC(ctx), 4); } SEC("kprobe/tcp_v6_connect") int BPF_KPROBE(kprobe__tcp_v6_connect, struct sock *sk) { return trace_connect_entry(sk); } SEC("kretprobe/tcp_v6_connect") int kretprobe__tcp_v6_connect(struct pt_regs *ctx) { return trace_connect_return(PT_REGS_RC(ctx), 6); }
1,835
10,225
package org.jboss.resteasy.reactive.common.headers; import java.util.List; import javax.ws.rs.core.CacheControl; import javax.ws.rs.ext.RuntimeDelegate; import org.jboss.resteasy.reactive.common.util.ExtendedCacheControl; /** * @author <a href="mailto:<EMAIL>"><NAME></a> */ public class CacheControlDelegate implements RuntimeDelegate.HeaderDelegate<CacheControl> { public static final CacheControlDelegate INSTANCE = new CacheControlDelegate(); public CacheControl fromString(String value) throws IllegalArgumentException { if (value == null) throw new IllegalArgumentException("Param was null"); ExtendedCacheControl result = new ExtendedCacheControl(); result.setNoTransform(false); String[] directives = value.split(","); for (String directive : directives) { directive = directive.trim(); String[] nv = directive.split("="); String name = nv[0].trim(); String val = null; if (nv.length > 1) { val = nv[1].trim(); if (val.startsWith("\"")) val = val.substring(1); if (val.endsWith("\"")) val = val.substring(0, val.length() - 1); } String lowercase = name.toLowerCase(); if ("no-cache".equals(lowercase)) { result.setNoCache(true); if (val != null && !"".equals(val)) { result.getNoCacheFields().add(val); } } else if ("private".equals(lowercase)) { result.setPrivate(true); if (val != null && !"".equals(val)) { result.getPrivateFields().add(val); } } else if ("no-store".equals(lowercase)) { result.setNoStore(true); } else if ("max-age".equals(lowercase)) { if (val == null) throw new IllegalArgumentException("null max age"); result.setMaxAge(Integer.valueOf(val)); } else if ("s-maxage".equals(lowercase)) { if (val == null) throw new IllegalArgumentException("null s-maxage"); result.setSMaxAge(Integer.valueOf(val)); } else if ("no-transform".equals(lowercase)) { result.setNoTransform(true); } else if ("must-revalidate".equals(lowercase)) { result.setMustRevalidate(true); } else if ("proxy-revalidate".equals(lowercase)) { result.setProxyRevalidate(true); } else if ("public".equals(lowercase)) { result.setPublic(true); } else { if (val == null) val = ""; result.getCacheExtension().put(name, val); } } return result; } private static StringBuffer addDirective(String directive, StringBuffer buffer) { if (buffer.length() > 0) buffer.append(", "); buffer.append(directive); return buffer; } public String toString(CacheControl value) { if (value == null) throw new IllegalArgumentException("param was null"); StringBuffer buffer = new StringBuffer(); if (value.isNoCache()) { List<String> fields = value.getNoCacheFields(); if (fields.size() < 1) { addDirective("no-cache", buffer); } else { for (String field : value.getNoCacheFields()) { addDirective("no-cache", buffer).append("=\"").append(field).append("\""); } } } if (value instanceof ExtendedCacheControl) { ExtendedCacheControl ecc = (ExtendedCacheControl) value; if (ecc.isPublic()) { addDirective("public", buffer); } } if (value.isMustRevalidate()) addDirective("must-revalidate", buffer); if (value.isNoTransform()) addDirective("no-transform", buffer); if (value.isNoStore()) addDirective("no-store", buffer); if (value.isProxyRevalidate()) addDirective("proxy-revalidate", buffer); if (value.getSMaxAge() > -1) addDirective("s-maxage", buffer).append("=").append(value.getSMaxAge()); if (value.getMaxAge() > -1) addDirective("max-age", buffer).append("=").append(value.getMaxAge()); if (value.isPrivate()) { List<String> fields = value.getPrivateFields(); if (fields.size() < 1) addDirective("private", buffer); else { for (String field : value.getPrivateFields()) { addDirective("private", buffer).append("=\"").append(field).append("\""); } } } for (String key : value.getCacheExtension().keySet()) { String val = value.getCacheExtension().get(key); addDirective(key, buffer); if (val != null && !"".equals(val)) { buffer.append("=\"").append(val).append("\""); } } return buffer.toString(); } }
2,545
9,724
#include "alutInternal.h" static enum { Unintialized, /* ALUT has not been initialized yet or has been de-initialised */ ALUTDeviceAndContext, /* alutInit has been called successfully */ ExternalDeviceAndContext /* alutInitWithoutContext has been called */ } initialisationState = Unintialized; /* * Note: alutContext contains something valid only when initialisationState * contains ALUTDeviceAndContext. */ static ALCcontext *alutContext; ALboolean _alutSanityCheck(void) { ALCcontext *context; if (initialisationState == Unintialized) { _alutSetError(ALUT_ERROR_INVALID_OPERATION); return AL_FALSE; } context = alcGetCurrentContext(); if (context == NULL) { _alutSetError(ALUT_ERROR_NO_CURRENT_CONTEXT); return AL_FALSE; } if (alGetError() != AL_NO_ERROR) { _alutSetError(ALUT_ERROR_AL_ERROR_ON_ENTRY); return AL_FALSE; } if (alcGetError(alcGetContextsDevice(context)) != ALC_NO_ERROR) { _alutSetError(ALUT_ERROR_ALC_ERROR_ON_ENTRY); return AL_FALSE; } return AL_TRUE; } ALboolean alutInit(int *argcp, char **argv) { ALCdevice *device; ALCcontext *context; if (initialisationState != Unintialized) { _alutSetError(ALUT_ERROR_INVALID_OPERATION); return AL_FALSE; } if ((argcp == NULL) != (argv == NULL)) { _alutSetError(ALUT_ERROR_INVALID_VALUE); return AL_FALSE; } device = alcOpenDevice(NULL); if (device == NULL) { _alutSetError(ALUT_ERROR_OPEN_DEVICE); return AL_FALSE; } context = alcCreateContext(device, NULL); if (context == NULL) { alcCloseDevice(device); _alutSetError(ALUT_ERROR_CREATE_CONTEXT); return AL_FALSE; } if (!alcMakeContextCurrent(context)) { alcDestroyContext(context); alcCloseDevice(device); _alutSetError(ALUT_ERROR_MAKE_CONTEXT_CURRENT); return AL_FALSE; } initialisationState = ALUTDeviceAndContext; alutContext = context; return AL_TRUE; } ALboolean alutInitWithoutContext(int *argcp, char **argv) { if (initialisationState != Unintialized) { _alutSetError(ALUT_ERROR_INVALID_OPERATION); return AL_FALSE; } if ((argcp == NULL) != (argv == NULL)) { _alutSetError(ALUT_ERROR_INVALID_VALUE); return AL_FALSE; } initialisationState = ExternalDeviceAndContext; return AL_TRUE; } ALboolean alutExit(void) { ALCdevice *device; if (initialisationState == Unintialized) { _alutSetError(ALUT_ERROR_INVALID_OPERATION); return AL_FALSE; } if (initialisationState == ExternalDeviceAndContext) { initialisationState = Unintialized; return AL_TRUE; } if (!_alutSanityCheck()) { return AL_FALSE; } if (!alcMakeContextCurrent(NULL)) { _alutSetError(ALUT_ERROR_MAKE_CONTEXT_CURRENT); return AL_FALSE; } device = alcGetContextsDevice(alutContext); alcDestroyContext(alutContext); if (alcGetError(device) != ALC_NO_ERROR) { _alutSetError(ALUT_ERROR_DESTROY_CONTEXT); return AL_FALSE; } if (!alcCloseDevice(device)) { _alutSetError(ALUT_ERROR_CLOSE_DEVICE); return AL_FALSE; } initialisationState = Unintialized; return AL_TRUE; }
1,277
14,668
<reponame>zealoussnow/chromium { "getAvailableSinks": { "urn:x-org.chromium.media:source:desktop": [{"id" : "id1", "friendlyName" : "test-sink-1"}] } }
80
2,232
<reponame>solson/lean /* Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: <NAME> */ #include "library/trace.h" #include "library/norm_num.h" #include "library/util.h" #include "library/constants.h" #include "library/comp_val.h" namespace lean { bool norm_num_context::is_numeral(expr const & e) const { return is_num(e); } bool norm_num_context::is_nat_const(expr const & e) const { return is_constant(e) && const_name(e) == get_nat_name(); } bool norm_num_context::is_neg_app(expr const & e) const { return is_const_app(e, get_has_neg_neg_name(), 3); } bool norm_num_context::is_div(expr const & e) const { return is_const_app(e, get_has_div_div_name(), 4); } expr norm_num_context::mk_const(name const & n) { return mk_constant(n, m_ainst.get_levels()); } expr norm_num_context::mk_cong(expr const & op, expr const & type, expr const & a, expr const & b, expr const & eq) { return mk_app({mk_const(get_norm_num_mk_cong_name()), type, op, a, b, eq}); } // returns <t, p> such that p is a proof that lhs + rhs = t. pair<expr, expr> norm_num_context::mk_norm_add(expr const & lhs, expr const & rhs) { buffer<expr> args_lhs; buffer<expr> args_rhs; expr lhs_head = get_app_args (lhs, args_lhs); expr rhs_head = get_app_args (rhs, args_rhs); if (!is_constant(lhs_head) || !is_constant(rhs_head)) { throw exception("cannot take norm_add of nonconstant"); } auto type = args_lhs[0]; auto typec = args_lhs[1]; expr rv; expr prf; if (is_bit0(lhs) && is_bit0(rhs)) { // typec is has_add auto p = mk_norm_add(args_lhs[2], args_rhs[2]); rv = mk_app(lhs_head, type, typec, p.first); prf = mk_app({mk_const(get_norm_num_bit0_add_bit0_helper_name()), type, mk_add_comm(), args_lhs[2], args_rhs[2], p.first, p.second}); } else if (is_bit0(lhs) && is_bit1(rhs)) { auto p = mk_norm_add(args_lhs[2], args_rhs[3]); rv = mk_app({rhs_head, type, args_rhs[1], args_rhs[2], p.first}); prf = mk_app({mk_const(get_norm_num_bit0_add_bit1_helper_name()), type, mk_add_comm(), args_rhs[1], args_lhs[2], args_rhs[3], p.first, p.second}); } else if (is_bit0(lhs) && is_one(rhs)) { rv = mk_bit1(args_lhs[2]); prf = mk_app({mk_const(get_norm_num_bit0_add_one_name()), type, typec, args_rhs[1], args_lhs[2]}); } else if (is_bit1(lhs) && is_bit0(rhs)) { // typec is has_one auto p = mk_norm_add(args_lhs[3], args_rhs[2]); rv = mk_app(lhs_head, type, typec, args_lhs[2], p.first); prf = mk_app({mk_const(get_norm_num_bit1_add_bit0_helper_name()), type, mk_add_comm(), typec, args_lhs[3], args_rhs[2], p.first, p.second}); } else if (is_bit1(lhs) && is_bit1(rhs)) { // typec is has_one auto add_ts = mk_norm_add(args_lhs[3], args_rhs[3]); expr add1 = mk_app({mk_const(get_norm_num_add1_name()), type, args_lhs[2], typec, add_ts.first}); auto p = mk_norm_add1(add1); rv = mk_bit0(p.first); prf = mk_app({mk_const(get_norm_num_bit1_add_bit1_helper_name()), type, mk_add_comm(), typec, args_lhs[3], args_rhs[3], add_ts.first, p.first, add_ts.second, p.second}); } else if (is_bit1(lhs) && is_one(rhs)) { // typec is has_one expr add1 = mk_app({mk_const(get_norm_num_add1_name()), type, args_lhs[2], typec, lhs}); auto p = mk_norm_add1(add1); rv = p.first; prf = mk_app({mk_const(get_norm_num_bit1_add_one_helper_name()), type, args_lhs[2], typec, args_lhs[3], p.first, p.second}); } else if (is_one(lhs) && is_bit0(rhs)) { // typec is has_one rv = mk_bit1(args_rhs[2]); prf = mk_app({mk_const(get_norm_num_one_add_bit0_name()), type, mk_add_comm(), typec, args_rhs[2]}); } else if (is_one(lhs) && is_bit1(rhs)) { // typec is has_one expr add1 = mk_app({mk_const(get_norm_num_add1_name()), type, args_rhs[2], args_rhs[1], rhs}); auto p = mk_norm_add1(add1); rv = p.first; prf = mk_app({mk_const(get_norm_num_one_add_bit1_helper_name()), type, mk_add_comm(), typec, args_rhs[3], p.first, p.second}); } else if (is_one(lhs) && is_one(rhs)) { rv = mk_bit0(lhs); prf = mk_app({mk_const(get_norm_num_one_add_one_name()), type, mk_has_add(), typec}); } else if (is_zero(lhs)) { rv = rhs; prf = mk_app({mk_const(get_norm_num_bin_zero_add_name()), type, mk_add_monoid(), rhs}); } else if (is_zero(rhs)) { rv = lhs; prf = mk_app({mk_const(get_norm_num_bin_add_zero_name()), type, mk_add_monoid(), lhs}); } else { throw exception("mk_norm_add got malformed args"); } return pair<expr, expr>(rv, prf); } pair<expr, expr> norm_num_context::mk_norm_add1(expr const & e) { buffer<expr> args; expr f = get_app_args(e, args); expr p = args[3]; buffer<expr> ne_args; expr ne = get_app_args(p, ne_args); expr rv; expr prf; // args[1] = has_add, args[2] = has_one if (is_bit0(p)) { auto has_one = args[2]; rv = mk_bit1(ne_args[2]); prf = mk_app({mk_const(get_norm_num_add1_bit0_name()), args[0], args[1], args[2], ne_args[2]}); } else if (is_bit1(p)) { // ne_args : has_one, has_add auto np = mk_norm_add1(mk_app({mk_const(get_norm_num_add1_name()), args[0], args[1], args[2], ne_args[3]})); rv = mk_bit0(np.first); prf = mk_app({mk_const(get_norm_num_add1_bit1_helper_name()), args[0], mk_add_comm(), args[2], ne_args[3], np.first, np.second}); } else if (is_zero(p)) { rv = mk_one(); prf = mk_app({mk_const(get_norm_num_add1_zero_name()), args[0], mk_add_monoid(), args[2]}); } else if (is_one(p)) { rv = mk_bit0(mk_one()); prf = mk_app({mk_const(get_norm_num_add1_one_name()), args[0], args[1], args[2]}); } else { throw exception("malformed add1"); } return pair<expr, expr>(rv, prf); } pair<expr, expr> norm_num_context::mk_norm_mul(expr const & lhs, expr const & rhs) { buffer<expr> args_lhs; buffer<expr> args_rhs; expr lhs_head = get_app_args (lhs, args_lhs); expr rhs_head = get_app_args (rhs, args_rhs); if (!is_constant(lhs_head) || !is_constant(rhs_head)) { throw exception("cannot take norm_add of nonconstant"); } auto type = args_rhs[0]; auto typec = args_rhs[1]; expr rv; expr prf; if (is_zero(rhs)) { rv = rhs; prf = mk_app({mk_const(get_mul_zero_name()), type, mk_mul_zero_class(), lhs}); } else if (is_zero(lhs)) { rv = lhs; prf = mk_app({mk_const(get_zero_mul_name()), type, mk_mul_zero_class(), rhs}); } else if (is_one(rhs)) { rv = lhs; prf = mk_app({mk_const(get_mul_one_name()), type, mk_monoid(), lhs}); } else if (is_bit0(rhs)) { auto mtp = mk_norm_mul(lhs, args_rhs[2]); rv = mk_app({rhs_head, type, typec, mtp.first}); prf = mk_app({mk_const(get_norm_num_mul_bit0_helper_name()), type, mk_distrib(), lhs, args_rhs[2], mtp.first, mtp.second}); } else if (is_bit1(rhs)) { auto mtp = mk_norm_mul(lhs, args_rhs[3]); auto atp = mk_norm_add(mk_bit0(mtp.first), lhs); rv = atp.first; prf = mk_app({mk_const(get_norm_num_mul_bit1_helper_name()), type, mk_semiring(), lhs, args_rhs[3], mtp.first, atp.first, mtp.second, atp.second}); } else { throw exception("mk_norm_mul got malformed args"); } return pair<expr, expr>(rv, prf); } optional<mpq> norm_num_context::to_mpq(expr const & e) { auto v = to_num(e); if (v) { return optional<mpq>(mpq(*v)); } else { return optional<mpq>(); } } mpq norm_num_context::mpq_of_expr(expr const & e) { if (auto r = m_ainst.eval(e)) return *r; else throw exception("failed to evaluate arithmetic expression"); } pair<expr, expr> norm_num_context::get_type_and_arg_of_neg(expr const & e) { lean_assert(is_neg_app(e)); buffer<expr> args; expr f = get_app_args(e, args); return pair<expr, expr>(args[0], args[2]); } // returns a proof that s_lhs + s_rhs = rhs, where all are negated numerals expr norm_num_context::mk_norm_eq_neg_add_neg(expr const & s_lhs, expr const & s_rhs, expr const & rhs) { lean_assert(is_neg_app(s_lhs)); lean_assert(is_neg_app(s_rhs)); lean_assert(is_neg_app(rhs)); auto s_lhs_v = get_type_and_arg_of_neg(s_lhs).second; auto s_rhs_v = get_type_and_arg_of_neg(s_rhs).second; auto rhs_v = get_type_and_arg_of_neg(rhs); expr type = rhs_v.first; auto sum_pr = mk_norm(mk_add(s_lhs_v, s_rhs_v)).second; return mk_app({mk_const(get_norm_num_neg_add_neg_helper_name()), type, mk_add_comm_group(), s_lhs_v, s_rhs_v, rhs_v.second, sum_pr}); } expr norm_num_context::mk_norm_eq_neg_add_pos(expr const & s_lhs, expr const & s_rhs, expr const & rhs) { lean_assert(is_neg_app(s_lhs)); lean_assert(!is_neg_app(s_rhs)); auto s_lhs_v = get_type_and_arg_of_neg(s_lhs); expr type = s_lhs_v.first; if (is_neg_app(rhs)) { auto rhs_v = get_type_and_arg_of_neg(rhs).second; auto sum_pr = mk_norm(mk_add(s_rhs, rhs_v)).second; return mk_app({mk_const(get_norm_num_neg_add_pos_helper1_name()), type, mk_add_comm_group(), s_lhs_v.second, s_rhs, rhs_v, sum_pr}); } else { auto sum_pr = mk_norm(mk_add(s_lhs_v.second, rhs)).second; return mk_app({mk_const(get_norm_num_neg_add_pos_helper2_name()), type, mk_add_comm_group(), s_lhs_v.second, s_rhs, rhs, sum_pr}); } } expr norm_num_context::mk_norm_eq_pos_add_neg(expr const & s_lhs, expr const & s_rhs, expr const & rhs) { lean_assert(is_neg_app(s_rhs)); lean_assert(!is_neg_app(s_lhs)); expr prf = mk_norm_eq_neg_add_pos(s_rhs, s_lhs, rhs); expr type = get_type_and_arg_of_neg(s_rhs).first; return mk_app({mk_const(get_norm_num_pos_add_neg_helper_name()), type, mk_add_comm_group(), s_lhs, s_rhs, rhs, prf}); } // returns a proof that s_lhs + s_rhs = rhs, where all are nonneg normalized numerals expr norm_num_context::mk_norm_eq_pos_add_pos(expr const & s_lhs, expr const & s_rhs, expr const & DEBUG_CODE(rhs)) { lean_assert(!is_neg_app(s_lhs)); lean_assert(!is_neg_app(s_rhs)); lean_assert(!is_neg_app(rhs)); auto p = mk_norm_add(s_lhs, s_rhs); lean_assert(to_num(rhs) == to_num(p.first)); return p.second; } expr norm_num_context::mk_norm_eq_neg_mul_neg(expr const & s_lhs, expr const & s_rhs, expr const & rhs) { lean_assert(is_neg_app(s_lhs)); lean_assert(is_neg_app(s_rhs)); lean_assert(!is_neg_app(rhs)); auto s_lhs_v = get_type_and_arg_of_neg(s_lhs).second; expr s_rhs_v, type; std::tie(type, s_rhs_v) = get_type_and_arg_of_neg(s_rhs); auto prod_pr = mk_norm(mk_mul(s_lhs_v, s_rhs_v)); lean_assert(to_num(rhs) == to_num(prod_pr.first)); return mk_app({mk_const(get_norm_num_neg_mul_neg_helper_name()), type, mk_ring(), s_lhs_v, s_rhs_v, rhs, prod_pr.second}); } expr norm_num_context::mk_norm_eq_neg_mul_pos(expr const & s_lhs, expr const & s_rhs, expr const & rhs) { lean_assert(is_neg_app(s_lhs)); lean_assert(!is_neg_app(s_rhs)); lean_assert(is_neg_app(rhs)); expr s_lhs_v, type; std::tie(type, s_lhs_v) = get_type_and_arg_of_neg(s_lhs); auto rhs_v = get_type_and_arg_of_neg(rhs).second; auto prod_pr = mk_norm(mk_mul(s_lhs_v, s_rhs)); return mk_app({mk_const(get_norm_num_neg_mul_pos_helper_name()), type, mk_ring(), s_lhs_v, s_rhs, rhs_v, prod_pr.second}); } expr norm_num_context::mk_norm_eq_pos_mul_neg(expr const & s_lhs, expr const & s_rhs, expr const & rhs) { lean_assert(!is_neg_app(s_lhs)); lean_assert(is_neg_app(s_rhs)); lean_assert(is_neg_app(rhs)); expr s_rhs_v, type; std::tie(type, s_rhs_v) = get_type_and_arg_of_neg(s_rhs); auto rhs_v = get_type_and_arg_of_neg(rhs).second; auto prod_pr = mk_norm(mk_mul(s_lhs, s_rhs_v)); return mk_app({mk_const(get_norm_num_pos_mul_neg_helper_name()), type, mk_ring(), s_lhs, s_rhs_v, rhs_v, prod_pr.second}); } // returns a proof that s_lhs + s_rhs = rhs, where all are nonneg normalized numerals expr norm_num_context::mk_norm_eq_pos_mul_pos(expr const & s_lhs, expr const & s_rhs, expr const & DEBUG_CODE(rhs)) { lean_assert(!is_neg_app(s_lhs)); lean_assert(!is_neg_app(s_rhs)); lean_assert(!is_neg_app(rhs)); auto p = mk_norm_mul(s_lhs, s_rhs); lean_assert(to_num(rhs) == to_num(p.first)); return p.second; } // s_lhs is div. returns proof that s_lhs + s_rhs = rhs expr norm_num_context::mk_norm_div_add(expr const & s_lhs, expr const & s_rhs, expr const & rhs) { buffer<expr> s_lhs_args; get_app_args(s_lhs, s_lhs_args); expr type = s_lhs_args[0]; expr num = s_lhs_args[2], den = s_lhs_args[3]; expr new_lhs = mk_add(num, mk_mul(s_rhs, den)); auto npr_l = mk_norm(new_lhs); auto npr_r = mk_norm(mk_mul(rhs, den)); lean_assert(to_mpq(npr_l.first) == to_mpq(npr_r.first)); expr den_neq_zero = mk_nonzero_prf(den); return mk_app({mk_const(get_norm_num_div_add_helper_name()), type, mk_field(), num, den, s_rhs, rhs, npr_l.first, den_neq_zero, npr_l.second, npr_r.second}); } // s_rhs is div. returns proof that s_lhs + s_rhs = rhs expr norm_num_context::mk_norm_add_div(expr const & s_lhs, expr const & s_rhs, expr const & rhs) { buffer<expr> s_rhs_args; get_app_args(s_rhs, s_rhs_args); expr type = s_rhs_args[0]; expr num = s_rhs_args[2], den = s_rhs_args[3]; expr new_lhs = mk_add(mk_mul(den, s_lhs), num); auto npr_l = mk_norm(new_lhs); auto npr_r = mk_norm(mk_mul(den, rhs)); lean_assert(to_mpq(npr_l.first) == to_mpq(npr_r.first)); expr den_neq_zero = mk_nonzero_prf(den); return mk_app({mk_const(get_norm_num_add_div_helper_name()), type, mk_field(), num, den, s_lhs, rhs, npr_l.first, den_neq_zero, npr_l.second, npr_r.second}); } // if e is a numeral or a negation of a numeral or division, returns proof that e != 0 expr norm_num_context::mk_nonzero_prf(expr const & e) { buffer<expr> args; expr f = get_app_args(e, args); if (const_name(f) == get_has_neg_neg_name()) { return mk_app({mk_const(get_norm_num_nonzero_of_neg_helper_name()), args[0], mk_lin_ord_ring(), args[2], mk_nonzero_prf(args[2])}); } else if (const_name(f) == get_has_div_div_name()) { expr num_pr = mk_nonzero_prf(args[2]), den_pr = mk_nonzero_prf(args[3]); return mk_app({mk_const(get_norm_num_nonzero_of_div_helper_name()), args[0], mk_field(), args[2], args[3], num_pr, den_pr}); } else { return mk_app({mk_const(get_norm_num_nonzero_of_pos_helper_name()), args[0], mk_lin_ord_semiring(), e, mk_pos_prf(e)}); } } // if e is a numeral, makes a proof that e > 0 expr norm_num_context::mk_pos_prf(expr const & e) { buffer<expr> args; get_app_args(e, args); expr type = args[0]; expr prf; if (is_bit0(e)) { prf = mk_pos_prf(args[2]); return mk_app({mk_const(get_norm_num_pos_bit0_helper_name()), type, mk_lin_ord_semiring(), args[2], prf}); } else if (is_bit1(e)) { prf = mk_nonneg_prf(args[3]); return mk_app({mk_const(get_norm_num_pos_bit1_helper_name()), type, mk_lin_ord_semiring(), args[3], prf}); } else if (is_one(e)) { return mk_app({mk_const(get_zero_lt_one_name()), type, mk_lin_ord_semiring()}); } else { throw exception("mk_pos_proof called on zero or non_numeral"); } } expr norm_num_context::mk_nonneg_prf(expr const & e) { buffer<expr> args; get_app_args(e, args); expr type = args[0]; expr prf; if (is_bit0(e)) { prf = mk_nonneg_prf(args[2]); return mk_app({mk_const(get_norm_num_nonneg_bit0_helper_name()), type, mk_lin_ord_semiring(), args[2], prf}); } else if (is_bit1(e)) { prf = mk_nonneg_prf(args[3]); return mk_app({mk_const(get_norm_num_nonneg_bit1_helper_name()), type, mk_lin_ord_semiring(), args[3], prf}); } else if (is_one(e)) { return mk_app({mk_const(get_zero_le_one_name()), type, mk_lin_ord_semiring()}); } else if (is_zero(e)) { return mk_app({mk_const(get_le_refl_name()), type, mk_partial_order(), mk_zero()}); } else { throw exception("mk_nonneg_proof called on zero or non_numeral"); } } // s_lhs is div. returns proof that s_lhs * s_rhs = rhs expr norm_num_context::mk_norm_div_mul(expr const & s_lhs, expr const & s_rhs, expr const & rhs) { buffer<expr> args; get_app_args(s_lhs, args); expr type = args[0]; expr new_num = mk_mul(args[2], s_rhs); auto prf = mk_norm(mk_div(new_num, args[3])); lean_assert(to_mpq(prf.first) == to_mpq(rhs)); expr den_ne_zero = mk_nonzero_prf(args[3]); return mk_app({mk_const(get_norm_num_div_mul_helper_name()), type, mk_field(), args[2], args[3], s_rhs, rhs, den_ne_zero, prf.second}); } expr norm_num_context::mk_norm_mul_div(expr const & s_lhs, expr const & s_rhs, expr const & rhs) { buffer<expr> args; get_app_args(s_rhs, args); expr type = args[0]; expr new_num = mk_mul(s_lhs, args[2]); auto prf = mk_norm(mk_div(new_num, args[3])); lean_assert(to_mpq(prf.first) == to_mpq(rhs)); expr den_ne_zero = mk_nonzero_prf(args[3]); return mk_app({mk_const(get_norm_num_mul_div_helper_name()), type, mk_field(), s_lhs, args[2], args[3], rhs, den_ne_zero, prf.second}); } expr_pair norm_num_context::mk_norm_nat_sub(expr const & s_lhs, expr const & s_rhs) { auto norm_lhs = mk_norm(s_lhs); auto norm_rhs = mk_norm(s_rhs); mpq vall = mpq_of_expr(norm_lhs.first); mpq valr = mpq_of_expr(norm_rhs.first); if (valr > vall) { if (auto lt_pr = mk_nat_val_lt_proof(norm_lhs.first, norm_rhs.first)) { expr zeropr = mk_app({mk_constant(get_norm_num_sub_nat_zero_helper_name()), s_lhs, s_rhs, norm_lhs.first, norm_rhs.first, norm_lhs.second, norm_rhs.second, *lt_pr}); return expr_pair(mk_zero(), zeropr); } else { throw exception("mk_norm_nat_sub failed to make lt proof"); } } else { expr e = mk_num(vall - valr); auto seq_pr = mk_norm(mk_add(e, norm_rhs.first)); expr rpr = mk_app({mk_constant(get_norm_num_sub_nat_pos_helper_name()), s_lhs, s_rhs, norm_lhs.first, norm_rhs.first, e, norm_lhs.second, norm_rhs.second, seq_pr.second}); return expr_pair(e, rpr); } } pair<expr, expr> norm_num_context::mk_norm(expr const & e) { buffer<expr> args; expr f = get_app_args(e, args); if (!is_constant(f) || args.size() == 0) { throw exception("malformed argument to mk_norm"); } expr type = args[0]; m_ainst.set_type(type); if (is_numeral(e)) { expr prf = mk_eq_refl(m_ctx, e); return pair<expr, expr>(e, prf); } mpq val = mpq_of_expr(e); expr nval = mk_num(val); if (const_name(f) == get_has_add_add_name() && args.size() == 4) { expr prf; auto lhs_p = mk_norm(args[2]); auto rhs_p = mk_norm(args[3]); if (is_neg_app(lhs_p.first)) { if (is_neg_app(rhs_p.first)) { prf = mk_norm_eq_neg_add_neg(lhs_p.first, rhs_p.first, nval); } else { prf = mk_norm_eq_neg_add_pos(lhs_p.first, rhs_p.first, nval); } } else { if (is_neg_app(rhs_p.first)) { prf = mk_norm_eq_pos_add_neg(lhs_p.first, rhs_p.first, nval); } else { if (is_div(lhs_p.first)) { prf = mk_norm_div_add(lhs_p.first, rhs_p.first, nval); } else if (is_div(rhs_p.first)) { prf = mk_norm_add_div(lhs_p.first, rhs_p.first, nval); } else { prf = mk_norm_eq_pos_add_pos(lhs_p.first, rhs_p.first, nval); } } } expr rprf = mk_app({mk_const(get_norm_num_subst_into_sum_name()), type, mk_has_add(), args[2], args[3], lhs_p.first, rhs_p.first, nval, lhs_p.second, rhs_p.second, prf}); return pair<expr, expr>(nval, rprf); } else if (const_name(f) == get_has_sub_sub_name() && args.size() == 4) { if (is_nat_const(args[0])) { return mk_norm_nat_sub(args[2], args[3]); } expr sum = mk_add(args[2], mk_neg(args[3])); auto anprf = mk_norm(sum); expr rprf = mk_app({mk_const(get_norm_num_subst_into_subtr_name()), type, mk_add_group(), args[2], args[3], anprf.first, anprf.second}); return expr_pair(nval, rprf); } else if (const_name(f) == get_has_neg_neg_name() && args.size() == 3) { auto prf = mk_norm(args[2]); lean_assert(mpq_of_expr(prf.first) == neg(val)); if (is_zero(prf.first)) { expr rprf = mk_app({mk_const(get_norm_num_neg_zero_helper_name()), type, mk_add_group(), args[2], prf.second}); return pair<expr, expr>(prf.first, rprf); } if (is_neg_app(nval)) { buffer<expr> nval_args; get_app_args(nval, nval_args); expr rprf = mk_cong(mk_app(f, args[0], args[1]), type, args[2], nval_args[2], prf.second); return pair<expr, expr>(nval, rprf); } else { expr rprf = mk_app({mk_const(get_norm_num_neg_neg_helper_name()), type, mk_add_group(), args[2], nval, prf.second}); return pair<expr, expr>(nval, rprf); } } else if (const_name(f) == get_has_mul_mul_name() && args.size() == 4) { auto lhs_p = mk_norm(args[2]); auto rhs_p = mk_norm(args[3]); expr prf; if (is_div(lhs_p.first)) { prf = mk_norm_div_mul(lhs_p.first, rhs_p.first, nval); } else if (is_div(rhs_p.first)) { prf = mk_norm_mul_div(lhs_p.first, rhs_p.first, nval); } else if (is_zero(lhs_p.first) || is_zero(rhs_p.first)) { prf = mk_norm_mul(lhs_p.first, rhs_p.first).second; } else if (is_neg_app(lhs_p.first)) { if (is_neg_app(rhs_p.first)) { prf = mk_norm_eq_neg_mul_neg(lhs_p.first, rhs_p.first, nval); } else { // bad args passing here prf = mk_norm_eq_neg_mul_pos(lhs_p.first, rhs_p.first, nval); } } else { if (is_neg_app(rhs_p.first)) { prf = mk_norm_eq_pos_mul_neg(lhs_p.first, rhs_p.first, nval); } else { prf = mk_norm_eq_pos_mul_pos(lhs_p.first, rhs_p.first, nval); } } expr rprf = mk_app({mk_const(get_norm_num_subst_into_prod_name()), type, mk_has_mul(), args[2], args[3], lhs_p.first, rhs_p.first, nval, lhs_p.second, rhs_p.second, prf}); return pair<expr, expr>(nval, rprf); } else if (const_name(f) == get_has_div_div_name() && args.size() == 4) { auto lhs_p = mk_norm(args[2]); auto rhs_p = mk_norm(args[3]); expr prf; if (is_div(nval)) { buffer<expr> nval_args; get_app_args(nval, nval_args); expr nval_num = nval_args[2], nval_den = nval_args[3]; auto lhs_mul = mk_norm(mk_mul(lhs_p.first, nval_den)); auto rhs_mul = mk_norm(mk_mul(nval_num, rhs_p.first)); expr den_nonzero = mk_nonzero_prf(rhs_p.first); expr nval_den_nonzero = mk_nonzero_prf(nval_den); prf = mk_app({mk_const(get_norm_num_div_eq_div_helper_name()), type, mk_field(), lhs_p.first, rhs_p.first, nval_num, nval_den, lhs_mul.first, lhs_mul.second, rhs_mul.second, den_nonzero, nval_den_nonzero}); } else { auto prod = mk_norm(mk_mul(nval, rhs_p.first)); auto val1 = to_mpq(prod.first), val2 = to_mpq(lhs_p.first); if (val1 && val2) { lean_assert(*val1 == *val2); } expr den_nonzero = mk_nonzero_prf(rhs_p.first); prf = mk_app({mk_const(get_norm_num_div_helper_name()), type, mk_field(), lhs_p.first, rhs_p.first, nval, den_nonzero, prod.second}); } expr rprf = mk_app({mk_const(get_norm_num_subst_into_div_name()), type, mk_has_div(), lhs_p.first, rhs_p.first, args[2], args[3], nval, prf, lhs_p.second, rhs_p.second}); return pair<expr, expr>(nval, rprf); } else if (const_name(f) == get_bit0_name() && args.size() == 3) { lean_assert(is_bit0(nval)); buffer<expr> nval_args; get_app_args(nval, nval_args); auto prf = mk_norm(args[2]); auto rprf = mk_cong(mk_app(f, args[0], args[1]), type, args[2], nval_args[2], prf.second); return pair<expr, expr>(nval, rprf); } else if (const_name(f) == get_bit1_name() && args.size() == 4) { lean_assert(is_bit1(nval)); buffer<expr> nval_args; get_app_args(nval, nval_args); auto prf = mk_norm(args[3]); auto rprf = mk_cong(mk_app(f, args[0], args[1], args[2]), type, args[3], nval_args[3], prf.second); return pair<expr, expr>(nval, rprf); } else if ((const_name(f) == get_has_zero_zero_name() || const_name(f) == get_has_one_one_name()) && args.size() == 2) { return pair<expr, expr>(e, mk_eq_refl(m_ctx, e)); } else { throw exception("mk_norm found unrecognized combo "); } } }
13,408
1,694
<filename>stagemonitor-core/src/main/java/org/stagemonitor/core/util/http/ErrorLoggingResponseHandler.java package org.stagemonitor.core.util.http; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.stagemonitor.core.util.HttpClient; import org.stagemonitor.util.IOUtils; import java.io.IOException; import java.io.InputStream; public class ErrorLoggingResponseHandler<T> implements HttpClient.ResponseHandler<T> { private static final Logger logger = LoggerFactory.getLogger(ErrorLoggingResponseHandler.class); private static final ErrorLoggingResponseHandler INSTANCE = new ErrorLoggingResponseHandler(); public static <T> ErrorLoggingResponseHandler<T> getInstance() { return INSTANCE; } public ErrorLoggingResponseHandler() { } @Override public T handleResponse(HttpRequest<?> httpRequest, InputStream is, Integer statusCode, IOException e) throws IOException { if (statusCode != null && statusCode >= 400) { logger.warn(httpRequest.getSafeUrl() + ": " + statusCode + " " + IOUtils.toString(is)); } else { IOUtils.consumeAndClose(is); } return null; } }
363
784
package io.jboot.test.cache.caffeine; import io.jboot.Jboot; import io.jboot.app.JbootApplication; import io.jboot.components.cache.JbootCache; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class CaffeineTester { private static final String cacheName = "cachename"; @Test public void testPut() { Jboot.getCache().put(cacheName, "key", "value"); String value = Jboot.getCache().get(cacheName, "key"); Assert.assertNotNull(value); } @Test public void testGet() { JbootCache cache = Jboot.getCache(); cache.put(cacheName, "key", "value~~~~~~~"); String value = cache.get(cacheName, "key"); System.out.println("value:"+value); Assert.assertTrue("value~~~~~~~".equals(value)); } @Test public void testTtl() throws InterruptedException { JbootCache cache = Jboot.getCache(); cache.put(cacheName, "key", "value~~~~~~~",10); for (int i = 0;i<10;i++){ System.out.println(cache.getTtl(cacheName,"key")); Thread.sleep(1000); } } @Test public void testDue() throws InterruptedException { JbootCache cache = Jboot.getCache(); cache.put(cacheName, "key", "value~~~~~~~",10); for (int i = 0;i<15;i++){ System.out.println((String) cache.get(cacheName,"key")); Thread.sleep(1000); } } @Before public void config() { JbootApplication.setBootArg("jboot.cache.type", "caffeine"); } }
677
375
/* * Copyright 2015 Nokia Solutions and Networks * Licensed under the Apache License, Version 2.0, * see license.txt file for details. */ package org.robotframework.ide.eclipse.main.plugin.model.cmd; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.robotframework.ide.eclipse.main.plugin.model.IRobotCodeHoldingElement; import org.robotframework.ide.eclipse.main.plugin.model.RobotKeywordCall; import org.robotframework.ide.eclipse.main.plugin.model.RobotModelEvents; import org.robotframework.ide.eclipse.main.plugin.tableeditor.EditorCommand; public class DeleteKeywordCallCommand extends EditorCommand { protected final List<? extends RobotKeywordCall> callsToDelete; private final String eventTopic; protected final List<Integer> deletedCallsIndexes = new ArrayList<>(); public DeleteKeywordCallCommand(final List<? extends RobotKeywordCall> callsToDelete) { this(callsToDelete, RobotModelEvents.ROBOT_KEYWORD_CALL_REMOVED); } protected DeleteKeywordCallCommand(final List<? extends RobotKeywordCall> callsToDelete, final String topic) { this.callsToDelete = callsToDelete; this.eventTopic = topic; } @Override public void execute() throws CommandExecutionException { if (callsToDelete.isEmpty()) { return; } for (final RobotKeywordCall call : callsToDelete) { deletedCallsIndexes.add(call.getIndex()); } final Set<IRobotCodeHoldingElement> parentsWhereRemovalWasPerformed = new HashSet<>(); for (final RobotKeywordCall call : callsToDelete) { final IRobotCodeHoldingElement parent = call.getParent(); parent.removeChild(call); parentsWhereRemovalWasPerformed.add(parent); } for (final IRobotCodeHoldingElement parent : parentsWhereRemovalWasPerformed) { eventBroker.send(eventTopic, parent); } } @Override public List<EditorCommand> getUndoCommands() { return newUndoCommands(setupUndoCommandsForDeletedCalls()); } private List<EditorCommand> setupUndoCommandsForDeletedCalls() { final List<EditorCommand> commands = new ArrayList<>(); if (callsToDelete.size() == deletedCallsIndexes.size()) { for (int i = 0; i < callsToDelete.size(); i++) { final RobotKeywordCall call = callsToDelete.get(i); commands.add(new InsertKeywordCallsCommand(call.getParent(), deletedCallsIndexes.get(i), new RobotKeywordCall[] { call })); } } return commands; } }
1,008
914
<gh_stars>100-1000 package top.crossoverjie.cicada.db.core.handle; import com.healthmarketscience.sqlbuilder.BinaryCondition; import com.healthmarketscience.sqlbuilder.InsertQuery; import com.healthmarketscience.sqlbuilder.UpdateQuery; import com.healthmarketscience.sqlbuilder.dbspec.basic.DbColumn; import com.healthmarketscience.sqlbuilder.dbspec.basic.DbTable; import lombok.extern.slf4j.Slf4j; import top.crossoverjie.cicada.db.annotation.OriginName; import top.crossoverjie.cicada.db.annotation.PrimaryId; import top.crossoverjie.cicada.db.core.SqlSessionFactory; import top.crossoverjie.cicada.db.model.Model; import top.crossoverjie.cicada.db.reflect.Instance; import top.crossoverjie.cicada.db.reflect.ReflectTools; import java.lang.reflect.Field; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Function: * * @author crossoverJie * Date: 2019-12-03 23:53 * @since JDK 1.8 */ @Slf4j public class DBHandler extends SqlSessionFactory implements DBHandle { private DbTable dbTable; @Override public int update(Object obj) { if (obj instanceof Model) { dbTable = super.origin().addTable(obj.getClass().getAnnotation(OriginName.class).value()); Map<DbColumn, Integer> primaryCondition = new HashMap<>(1); UpdateQuery updateQuery = new UpdateQuery(dbTable); for (Field field : obj.getClass().getDeclaredFields()) { String dbField = ReflectTools.getDbField(field); Object filedValue = Instance.getFiledValue(obj, field); if (null == filedValue) { continue; } if (field.getAnnotation(PrimaryId.class) != null) { primaryCondition.put(dbTable.addColumn(dbField), (Integer) filedValue); } else { DbColumn dbColumn = dbTable.addColumn(dbField); updateQuery.addSetClause(dbColumn, filedValue); } } for (Map.Entry<DbColumn, Integer> entry : primaryCondition.entrySet()) { updateQuery.addCondition(BinaryCondition.equalTo(entry.getKey(), entry.getValue())); } Statement statement = null; try { statement = super.origin().getConnection().createStatement(); log.debug("execute sql>>>>>{}", updateQuery.validate().toString()); return statement.executeUpdate(updateQuery.toString()); } catch (SQLException e) { log.error("SQLException", e); } finally { try { statement.close(); } catch (SQLException e) { log.error("SQLException", e); } } return 0; } else { return 0; } } @Override public void insert(Object obj) { dbTable = super.origin().addTable(obj.getClass().getAnnotation(OriginName.class).value()); InsertQuery insertSelectQuery = new InsertQuery(dbTable); List<Field> values = new ArrayList<>(); for (Field field : obj.getClass().getDeclaredFields()) { String dbField = ReflectTools.getDbField(field); Object filedValue = Instance.getFiledValue(obj, field); if (null == filedValue) { continue; } insertSelectQuery.addPreparedColumns(dbTable.addColumn(dbField)); values.add(field); } log.debug("execute sql>>>>>{}", insertSelectQuery.validate().toString()); StringBuilder sb = new StringBuilder(); PreparedStatement statement = null; try { statement = super.origin().getConnection().prepareStatement(insertSelectQuery.toString()); for (int i = 0; i < values.size(); i++) { Field value = values.get(i); if (value.getType() == Integer.class) { statement.setInt(i+1, (Integer) Instance.getFiledValue(obj, value)); } if (value.getType() == String.class) { statement.setString(i+1, (String) Instance.getFiledValue(obj, value)); } sb.append(value.getName() + "=" + Instance.getFiledValue(obj, value) + "\t") ; } log.debug("params >>>>>>>>>[{}]", sb.toString()); statement.execute() ; } catch (SQLException e) { log.error("SQLException", e); } finally { try { statement.close(); } catch (SQLException e) { log.error("SQLException", e); } } } }
2,221
52,316
<reponame>oleksandr-pavlyk/cpython import binascii import functools import hmac import hashlib import unittest import unittest.mock import warnings from test.support import hashlib_helper, check_disallow_instantiation from _operator import _compare_digest as operator_compare_digest try: import _hashlib as _hashopenssl from _hashlib import HMAC as C_HMAC from _hashlib import hmac_new as c_hmac_new from _hashlib import compare_digest as openssl_compare_digest except ImportError: _hashopenssl = None C_HMAC = None c_hmac_new = None openssl_compare_digest = None try: import _sha256 as sha256_module except ImportError: sha256_module = None def ignore_warning(func): @functools.wraps(func) def wrapper(*args, **kwargs): with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=DeprecationWarning) return func(*args, **kwargs) return wrapper class TestVectorsTestCase(unittest.TestCase): def assert_hmac_internals( self, h, digest, hashname, digest_size, block_size ): self.assertEqual(h.hexdigest().upper(), digest.upper()) self.assertEqual(h.digest(), binascii.unhexlify(digest)) self.assertEqual(h.name, f"hmac-{hashname}") self.assertEqual(h.digest_size, digest_size) self.assertEqual(h.block_size, block_size) def assert_hmac( self, key, data, digest, hashfunc, hashname, digest_size, block_size ): h = hmac.HMAC(key, data, digestmod=hashfunc) self.assert_hmac_internals( h, digest, hashname, digest_size, block_size ) h = hmac.HMAC(key, data, digestmod=hashname) self.assert_hmac_internals( h, digest, hashname, digest_size, block_size ) h = hmac.HMAC(key, digestmod=hashname) h2 = h.copy() h2.update(b"test update") h.update(data) self.assertEqual(h.hexdigest().upper(), digest.upper()) h = hmac.new(key, data, digestmod=hashname) self.assert_hmac_internals( h, digest, hashname, digest_size, block_size ) h = hmac.new(key, None, digestmod=hashname) h.update(data) self.assertEqual(h.hexdigest().upper(), digest.upper()) h = hmac.new(key, digestmod=hashname) h.update(data) self.assertEqual(h.hexdigest().upper(), digest.upper()) h = hmac.new(key, data, digestmod=hashfunc) self.assertEqual(h.hexdigest().upper(), digest.upper()) self.assertEqual( hmac.digest(key, data, digest=hashname), binascii.unhexlify(digest) ) self.assertEqual( hmac.digest(key, data, digest=hashfunc), binascii.unhexlify(digest) ) h = hmac.HMAC.__new__(hmac.HMAC) h._init_old(key, data, digestmod=hashname) self.assert_hmac_internals( h, digest, hashname, digest_size, block_size ) if c_hmac_new is not None: h = c_hmac_new(key, data, digestmod=hashname) self.assert_hmac_internals( h, digest, hashname, digest_size, block_size ) h = c_hmac_new(key, digestmod=hashname) h2 = h.copy() h2.update(b"test update") h.update(data) self.assertEqual(h.hexdigest().upper(), digest.upper()) func = getattr(_hashopenssl, f"openssl_{hashname}") h = c_hmac_new(key, data, digestmod=func) self.assert_hmac_internals( h, digest, hashname, digest_size, block_size ) h = hmac.HMAC.__new__(hmac.HMAC) h._init_hmac(key, data, digestmod=hashname) self.assert_hmac_internals( h, digest, hashname, digest_size, block_size ) @hashlib_helper.requires_hashdigest('md5', openssl=True) def test_md5_vectors(self): # Test the HMAC module against test vectors from the RFC. def md5test(key, data, digest): self.assert_hmac( key, data, digest, hashfunc=hashlib.md5, hashname="md5", digest_size=16, block_size=64 ) md5test(b"\x0b" * 16, b"Hi There", "9294727A3638BB1C13F48EF8158BFC9D") md5test(b"Jefe", b"what do ya want for nothing?", "750c783e6ab0b503eaa86e310a5db738") md5test(b"\xaa" * 16, b"\xdd" * 50, "56be34521d144c88dbb8c733f0e8b3f6") md5test(bytes(range(1, 26)), b"\xcd" * 50, "697eaf0aca3a3aea3a75164746ffaa79") md5test(b"\x0C" * 16, b"Test With Truncation", "56461ef2342edc00f9bab995690efd4c") md5test(b"\xaa" * 80, b"Test Using Larger Than Block-Size Key - Hash Key First", "6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd") md5test(b"\xaa" * 80, (b"Test Using Larger Than Block-Size Key " b"and Larger Than One Block-Size Data"), "6f630fad67cda0ee1fb1f562db3aa53e") @hashlib_helper.requires_hashdigest('sha1', openssl=True) def test_sha_vectors(self): def shatest(key, data, digest): self.assert_hmac( key, data, digest, hashfunc=hashlib.sha1, hashname="sha1", digest_size=20, block_size=64 ) shatest(b"\x0b" * 20, b"Hi There", "b617318655057264e28bc0b6fb378c8ef146be00") shatest(b"Jefe", b"what do ya want for nothing?", "effcdf6ae5eb2fa2d27416d5f184df9c259a7c79") shatest(b"\xAA" * 20, b"\xDD" * 50, "125d7342b9ac11cd91a39af48aa17b4f63f175d3") shatest(bytes(range(1, 26)), b"\xCD" * 50, "4c9007f4026250c6bc8414f9bf50c86c2d7235da") shatest(b"\x0C" * 20, b"Test With Truncation", "4c1a03424b55e07fe7f27be1d58bb9324a9a5a04") shatest(b"\xAA" * 80, b"Test Using Larger Than Block-Size Key - Hash Key First", "aa4ae5e15272d00e95705637ce8a3b55ed402112") shatest(b"\xAA" * 80, (b"Test Using Larger Than Block-Size Key " b"and Larger Than One Block-Size Data"), "e8e99d0f45237d786d6bbaa7965c7808bbff1a91") def _rfc4231_test_cases(self, hashfunc, hash_name, digest_size, block_size): def hmactest(key, data, hexdigests): digest = hexdigests[hashfunc] self.assert_hmac( key, data, digest, hashfunc=hashfunc, hashname=hash_name, digest_size=digest_size, block_size=block_size ) # 4.2. Test Case 1 hmactest(key = b'\x0b'*20, data = b'Hi There', hexdigests = { hashlib.sha224: '896fb1128abbdf196832107cd49df33f' '47b4b1169912ba4f53684b22', hashlib.sha256: 'b0344c61d8db38535ca8afceaf0bf12b' '881dc200c9833da726e9376c2e32cff7', hashlib.sha384: 'afd03944d84895626b0825f4ab46907f' '15f9dadbe4101ec682aa034c7cebc59c' 'faea9ea9076ede7f4af152e8b2fa9cb6', hashlib.sha512: '87aa7cdea5ef619d4ff0b4241a1d6cb0' '2379f4e2ce4ec2787ad0b30545e17cde' 'daa833b7d6b8a702038b274eaea3f4e4' 'be9d914eeb61f1702e696c203a126854', }) # 4.3. Test Case 2 hmactest(key = b'Jefe', data = b'what do ya want for nothing?', hexdigests = { hashlib.sha224: 'a30e01098bc6dbbf45690f3a7e9e6d0f' '8bbea2a39e6148008fd05e44', hashlib.sha256: '5bdcc146bf60754e6a042426089575c7' '5a003f089d2739839dec58b964ec3843', hashlib.sha384: 'af45d2e376484031617f78d2b58a6b1b' '9c7ef464f5a01b47e42ec3736322445e' '8e2240ca5e69e2c78b3239ecfab21649', hashlib.sha512: '164b7a7bfcf819e2e395fbe73b56e0a3' '87bd64222e831fd610270cd7ea250554' '9758bf75c05a994a6d034f65f8f0e6fd' 'caeab1a34d4a6b4b636e070a38bce737', }) # 4.4. Test Case 3 hmactest(key = b'\xaa'*20, data = b'\xdd'*50, hexdigests = { hashlib.sha224: '7fb3cb3588c6c1f6ffa9694d7d6ad264' '9365b0c1f65d69d1ec8333ea', hashlib.sha256: '773ea91e36800e46854db8ebd09181a7' '2959098b3ef8c122d9635514ced565fe', hashlib.sha384: '88062608d3e6ad8a0aa2ace014c8a86f' '0aa635d947ac9febe83ef4e55966144b' '2a5ab39dc13814b94e3ab6e101a34f27', hashlib.sha512: 'fa73b0089d56a284efb0f0756c890be9' 'b1b5dbdd8ee81a3655f83e33b2279d39' 'bf3e848279a722c806b485a47e67c807' 'b946a337bee8942674278859e13292fb', }) # 4.5. Test Case 4 hmactest(key = bytes(x for x in range(0x01, 0x19+1)), data = b'\xcd'*50, hexdigests = { hashlib.sha224: '6c11506874013cac6a2abc1bb382627c' 'ec6a90d86efc012de7afec5a', hashlib.sha256: '82558a389a443c0ea4cc819899f2083a' '85f0faa3e578f8077a2e3ff46729665b', hashlib.sha384: '3e8a69b7783c25851933ab6290af6ca7' '7a9981480850009cc5577c6e1f573b4e' '6801dd23c4a7d679ccf8a386c674cffb', hashlib.sha512: 'b0ba465637458c6990e5a8c5f61d4af7' 'e576d97ff94b872de76f8050361ee3db' 'a91ca5c11aa25eb4d679275cc5788063' 'a5f19741120c4f2de2adebeb10a298dd', }) # 4.7. Test Case 6 hmactest(key = b'\xaa'*131, data = b'Test Using Larger Than Block-Siz' b'e Key - Hash Key First', hexdigests = { hashlib.sha224: '95e9a0db962095adaebe9b2d6f0dbce2' 'd499f112f2d2b7273fa6870e', hashlib.sha256: '60e431591ee0b67f0d8a26aacbf5b77f' '8e0bc6213728c5140546040f0ee37f54', hashlib.sha384: '4ece084485813e9088d2c63a041bc5b4' '4f9ef1012a2b588f3cd11f05033ac4c6' '0c2ef6ab4030fe8296248df163f44952', hashlib.sha512: '80b24263c7c1a3ebb71493c1dd7be8b4' '9b46d1f41b4aeec1121b013783f8f352' '6b56d037e05f2598bd0fd2215d6a1e52' '95e64f73f63f0aec8b915a985d786598', }) # 4.8. Test Case 7 hmactest(key = b'\xaa'*131, data = b'This is a test using a larger th' b'an block-size key and a larger t' b'han block-size data. The key nee' b'ds to be hashed before being use' b'd by the HMAC algorithm.', hexdigests = { hashlib.sha224: '3a854166ac5d9f023f54d517d0b39dbd' '946770db9c2b95c9f6f565d1', hashlib.sha256: '9b09ffa71b942fcb27635fbcd5b0e944' 'bfdc63644f0713938a7f51535c3a35e2', hashlib.sha384: '6617178e941f020d351e2f254e8fd32c' '602420feb0b8fb9adccebb82461e99c5' 'a678cc31e799176d3860e6110c46523e', hashlib.sha512: 'e37b6a775dc87dbaa4dfa9f96e5e3ffd' 'debd71f8867289865df5a32d20cdc944' 'b6022cac3c4982b10d5eeb55c3e4de15' '134676fb6de0446065c97440fa8c6a58', }) @hashlib_helper.requires_hashdigest('sha224', openssl=True) def test_sha224_rfc4231(self): self._rfc4231_test_cases(hashlib.sha224, 'sha224', 28, 64) @hashlib_helper.requires_hashdigest('sha256', openssl=True) def test_sha256_rfc4231(self): self._rfc4231_test_cases(hashlib.sha256, 'sha256', 32, 64) @hashlib_helper.requires_hashdigest('sha384', openssl=True) def test_sha384_rfc4231(self): self._rfc4231_test_cases(hashlib.sha384, 'sha384', 48, 128) @hashlib_helper.requires_hashdigest('sha512', openssl=True) def test_sha512_rfc4231(self): self._rfc4231_test_cases(hashlib.sha512, 'sha512', 64, 128) @hashlib_helper.requires_hashdigest('sha256') def test_legacy_block_size_warnings(self): class MockCrazyHash(object): """Ain't no block_size attribute here.""" def __init__(self, *args): self._x = hashlib.sha256(*args) self.digest_size = self._x.digest_size def update(self, v): self._x.update(v) def digest(self): return self._x.digest() with warnings.catch_warnings(): warnings.simplefilter('error', RuntimeWarning) with self.assertRaises(RuntimeWarning): hmac.HMAC(b'a', b'b', digestmod=MockCrazyHash) self.fail('Expected warning about missing block_size') MockCrazyHash.block_size = 1 with self.assertRaises(RuntimeWarning): hmac.HMAC(b'a', b'b', digestmod=MockCrazyHash) self.fail('Expected warning about small block_size') def test_with_digestmod_no_default(self): """The digestmod parameter is required as of Python 3.8.""" with self.assertRaisesRegex(TypeError, r'required.*digestmod'): key = b"\x0b" * 16 data = b"Hi There" hmac.HMAC(key, data, digestmod=None) with self.assertRaisesRegex(TypeError, r'required.*digestmod'): hmac.new(key, data) with self.assertRaisesRegex(TypeError, r'required.*digestmod'): hmac.HMAC(key, msg=data, digestmod='') class ConstructorTestCase(unittest.TestCase): expected = ( "6c845b47f52b3b47f6590c502db7825aad757bf4fadc8fa972f7cd2e76a5bdeb" ) @hashlib_helper.requires_hashdigest('sha256') def test_normal(self): # Standard constructor call. try: hmac.HMAC(b"key", digestmod='sha256') except Exception: self.fail("Standard constructor call raised exception.") @hashlib_helper.requires_hashdigest('sha256') def test_with_str_key(self): # Pass a key of type str, which is an error, because it expects a key # of type bytes with self.assertRaises(TypeError): h = hmac.HMAC("key", digestmod='sha256') @hashlib_helper.requires_hashdigest('sha256') def test_dot_new_with_str_key(self): # Pass a key of type str, which is an error, because it expects a key # of type bytes with self.assertRaises(TypeError): h = hmac.new("key", digestmod='sha256') @hashlib_helper.requires_hashdigest('sha256') def test_withtext(self): # Constructor call with text. try: h = hmac.HMAC(b"key", b"hash this!", digestmod='sha256') except Exception: self.fail("Constructor call with text argument raised exception.") self.assertEqual(h.hexdigest(), self.expected) @hashlib_helper.requires_hashdigest('sha256') def test_with_bytearray(self): try: h = hmac.HMAC(bytearray(b"key"), bytearray(b"hash this!"), digestmod="sha256") except Exception: self.fail("Constructor call with bytearray arguments raised exception.") self.assertEqual(h.hexdigest(), self.expected) @hashlib_helper.requires_hashdigest('sha256') def test_with_memoryview_msg(self): try: h = hmac.HMAC(b"key", memoryview(b"hash this!"), digestmod="sha256") except Exception: self.fail("Constructor call with memoryview msg raised exception.") self.assertEqual(h.hexdigest(), self.expected) @hashlib_helper.requires_hashdigest('sha256') def test_withmodule(self): # Constructor call with text and digest module. try: h = hmac.HMAC(b"key", b"", hashlib.sha256) except Exception: self.fail("Constructor call with hashlib.sha256 raised exception.") @unittest.skipUnless(C_HMAC is not None, 'need _hashlib') def test_internal_types(self): # internal types like _hashlib.C_HMAC are not constructable check_disallow_instantiation(self, C_HMAC) with self.assertRaisesRegex(TypeError, "immutable type"): C_HMAC.value = None @unittest.skipUnless(sha256_module is not None, 'need _sha256') def test_with_sha256_module(self): h = hmac.HMAC(b"key", b"hash this!", digestmod=sha256_module.sha256) self.assertEqual(h.hexdigest(), self.expected) self.assertEqual(h.name, "hmac-sha256") digest = hmac.digest(b"key", b"hash this!", sha256_module.sha256) self.assertEqual(digest, binascii.unhexlify(self.expected)) class SanityTestCase(unittest.TestCase): @hashlib_helper.requires_hashdigest('sha256') def test_exercise_all_methods(self): # Exercising all methods once. # This must not raise any exceptions try: h = hmac.HMAC(b"my secret key", digestmod="sha256") h.update(b"compute the hash of this text!") h.digest() h.hexdigest() h.copy() except Exception: self.fail("Exception raised during normal usage of HMAC class.") class CopyTestCase(unittest.TestCase): @hashlib_helper.requires_hashdigest('sha256') def test_attributes_old(self): # Testing if attributes are of same type. h1 = hmac.HMAC.__new__(hmac.HMAC) h1._init_old(b"key", b"msg", digestmod="sha256") h2 = h1.copy() self.assertEqual(type(h1._inner), type(h2._inner), "Types of inner don't match.") self.assertEqual(type(h1._outer), type(h2._outer), "Types of outer don't match.") @hashlib_helper.requires_hashdigest('sha256') def test_realcopy_old(self): # Testing if the copy method created a real copy. h1 = hmac.HMAC.__new__(hmac.HMAC) h1._init_old(b"key", b"msg", digestmod="sha256") h2 = h1.copy() # Using id() in case somebody has overridden __eq__/__ne__. self.assertTrue(id(h1) != id(h2), "No real copy of the HMAC instance.") self.assertTrue(id(h1._inner) != id(h2._inner), "No real copy of the attribute 'inner'.") self.assertTrue(id(h1._outer) != id(h2._outer), "No real copy of the attribute 'outer'.") self.assertIs(h1._hmac, None) @unittest.skipIf(_hashopenssl is None, "test requires _hashopenssl") @hashlib_helper.requires_hashdigest('sha256') def test_realcopy_hmac(self): h1 = hmac.HMAC.__new__(hmac.HMAC) h1._init_hmac(b"key", b"msg", digestmod="sha256") h2 = h1.copy() self.assertTrue(id(h1._hmac) != id(h2._hmac)) @hashlib_helper.requires_hashdigest('sha256') def test_equality(self): # Testing if the copy has the same digests. h1 = hmac.HMAC(b"key", digestmod="sha256") h1.update(b"some random text") h2 = h1.copy() self.assertEqual(h1.digest(), h2.digest(), "Digest of copy doesn't match original digest.") self.assertEqual(h1.hexdigest(), h2.hexdigest(), "Hexdigest of copy doesn't match original hexdigest.") @hashlib_helper.requires_hashdigest('sha256') def test_equality_new(self): # Testing if the copy has the same digests with hmac.new(). h1 = hmac.new(b"key", digestmod="sha256") h1.update(b"some random text") h2 = h1.copy() self.assertTrue( id(h1) != id(h2), "No real copy of the HMAC instance." ) self.assertEqual(h1.digest(), h2.digest(), "Digest of copy doesn't match original digest.") self.assertEqual(h1.hexdigest(), h2.hexdigest(), "Hexdigest of copy doesn't match original hexdigest.") class CompareDigestTestCase(unittest.TestCase): def test_hmac_compare_digest(self): self._test_compare_digest(hmac.compare_digest) if openssl_compare_digest is not None: self.assertIs(hmac.compare_digest, openssl_compare_digest) else: self.assertIs(hmac.compare_digest, operator_compare_digest) def test_operator_compare_digest(self): self._test_compare_digest(operator_compare_digest) @unittest.skipIf(openssl_compare_digest is None, "test requires _hashlib") def test_openssl_compare_digest(self): self._test_compare_digest(openssl_compare_digest) def _test_compare_digest(self, compare_digest): # Testing input type exception handling a, b = 100, 200 self.assertRaises(TypeError, compare_digest, a, b) a, b = 100, b"foobar" self.assertRaises(TypeError, compare_digest, a, b) a, b = b"foobar", 200 self.assertRaises(TypeError, compare_digest, a, b) a, b = "foobar", b"foobar" self.assertRaises(TypeError, compare_digest, a, b) a, b = b"foobar", "foobar" self.assertRaises(TypeError, compare_digest, a, b) # Testing bytes of different lengths a, b = b"foobar", b"foo" self.assertFalse(compare_digest(a, b)) a, b = b"\xde\xad\xbe\xef", b"\xde\xad" self.assertFalse(compare_digest(a, b)) # Testing bytes of same lengths, different values a, b = b"foobar", b"foobaz" self.assertFalse(compare_digest(a, b)) a, b = b"\xde\xad\xbe\xef", b"\xab\xad\x1d\xea" self.assertFalse(compare_digest(a, b)) # Testing bytes of same lengths, same values a, b = b"foobar", b"foobar" self.assertTrue(compare_digest(a, b)) a, b = b"\xde\xad\xbe\xef", b"\xde\xad\xbe\xef" self.assertTrue(compare_digest(a, b)) # Testing bytearrays of same lengths, same values a, b = bytearray(b"foobar"), bytearray(b"foobar") self.assertTrue(compare_digest(a, b)) # Testing bytearrays of different lengths a, b = bytearray(b"foobar"), bytearray(b"foo") self.assertFalse(compare_digest(a, b)) # Testing bytearrays of same lengths, different values a, b = bytearray(b"foobar"), bytearray(b"foobaz") self.assertFalse(compare_digest(a, b)) # Testing byte and bytearray of same lengths, same values a, b = bytearray(b"foobar"), b"foobar" self.assertTrue(compare_digest(a, b)) self.assertTrue(compare_digest(b, a)) # Testing byte bytearray of different lengths a, b = bytearray(b"foobar"), b"foo" self.assertFalse(compare_digest(a, b)) self.assertFalse(compare_digest(b, a)) # Testing byte and bytearray of same lengths, different values a, b = bytearray(b"foobar"), b"foobaz" self.assertFalse(compare_digest(a, b)) self.assertFalse(compare_digest(b, a)) # Testing str of same lengths a, b = "foobar", "foobar" self.assertTrue(compare_digest(a, b)) # Testing str of different lengths a, b = "foo", "foobar" self.assertFalse(compare_digest(a, b)) # Testing bytes of same lengths, different values a, b = "foobar", "foobaz" self.assertFalse(compare_digest(a, b)) # Testing error cases a, b = "foobar", b"foobar" self.assertRaises(TypeError, compare_digest, a, b) a, b = b"foobar", "foobar" self.assertRaises(TypeError, compare_digest, a, b) a, b = b"foobar", 1 self.assertRaises(TypeError, compare_digest, a, b) a, b = 100, 200 self.assertRaises(TypeError, compare_digest, a, b) a, b = "fooรค", "fooรค" self.assertRaises(TypeError, compare_digest, a, b) # subclasses are supported by ignore __eq__ class mystr(str): def __eq__(self, other): return False a, b = mystr("foobar"), mystr("foobar") self.assertTrue(compare_digest(a, b)) a, b = mystr("foobar"), "foobar" self.assertTrue(compare_digest(a, b)) a, b = mystr("foobar"), mystr("foobaz") self.assertFalse(compare_digest(a, b)) class mybytes(bytes): def __eq__(self, other): return False a, b = mybytes(b"foobar"), mybytes(b"foobar") self.assertTrue(compare_digest(a, b)) a, b = mybytes(b"foobar"), b"foobar" self.assertTrue(compare_digest(a, b)) a, b = mybytes(b"foobar"), mybytes(b"foobaz") self.assertFalse(compare_digest(a, b)) if __name__ == "__main__": unittest.main()
14,224
1,350
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.analytics.synapse.spark.models; import com.azure.core.util.ExpandableStringEnum; import com.fasterxml.jackson.annotation.JsonCreator; import java.util.Collection; /** Defines values for LivyStatementStates. */ public final class LivyStatementStates extends ExpandableStringEnum<LivyStatementStates> { /** Static value waiting for LivyStatementStates. */ public static final LivyStatementStates WAITING = fromString("waiting"); /** Static value running for LivyStatementStates. */ public static final LivyStatementStates RUNNING = fromString("running"); /** Static value available for LivyStatementStates. */ public static final LivyStatementStates AVAILABLE = fromString("available"); /** Static value error for LivyStatementStates. */ public static final LivyStatementStates ERROR = fromString("error"); /** Static value cancelling for LivyStatementStates. */ public static final LivyStatementStates CANCELLING = fromString("cancelling"); /** Static value cancelled for LivyStatementStates. */ public static final LivyStatementStates CANCELLED = fromString("cancelled"); /** * Creates or finds a LivyStatementStates from its string representation. * * @param name a name to look for. * @return the corresponding LivyStatementStates. */ @JsonCreator public static LivyStatementStates fromString(String name) { return fromString(name, LivyStatementStates.class); } /** @return known LivyStatementStates values. */ public static Collection<LivyStatementStates> values() { return values(LivyStatementStates.class); } }
528
407
package com.alibaba.smart.framework.engine.test.process.bean; import lombok.Data; @Data public class Order { private Double yzje; }
50
1,534
{ "appDesc": { "message": "Ne gubite vreme na komplikacije. Universal Bypass zaobilazi dosadne link shortenere." }, "firstrunTitle": { "message": "Hvala vam za instaliranje Universal Bypass!" }, "firstrunNoScript": { "message": "Meฤ‘utim, izgleda da koristite NoScript ili sliฤno, s ฤime Universal Bypass nije kompatibilan." }, "version": { "message": "Verzija" }, "definitionsVersion": { "message": "Definicija bypassera" }, "changelog": { "message": "Promene" }, "update": { "message": "Proveri ima li aลพuriranja" }, "updating": { "message": "Preuzimanje definicije bypassera..." }, "updateYes": { "message": "Uspeลกno instaliran bypass" } }
293
497
<reponame>jhseodev/ngx_dynamic_upstream<gh_stars>100-1000 #include <ngx_config.h> #include <ngx_core.h> #include <ngx_http.h> #include "ngx_dynamic_upstream_op.h" static ngx_http_upstream_srv_conf_t * ngx_dynamic_upstream_get_zone(ngx_http_request_t *r, ngx_dynamic_upstream_op_t *op); static ngx_int_t ngx_dynamic_upstream_create_response_buf(ngx_http_upstream_rr_peers_t *peers, ngx_buf_t *b, size_t size, ngx_int_t verbose); static ngx_int_t ngx_dynamic_upstream_handler(ngx_http_request_t *r); static char * ngx_dynamic_upstream(ngx_conf_t *cf, ngx_command_t *cmd, void *conf); static ngx_command_t ngx_dynamic_upstream_commands[] = { { ngx_string("dynamic_upstream"), NGX_HTTP_LOC_CONF|NGX_CONF_NOARGS, ngx_dynamic_upstream, 0, 0, NULL }, ngx_null_command }; static ngx_http_module_t ngx_dynamic_upstream_module_ctx = { NULL, /* preconfiguration */ NULL, /* postconfiguration */ NULL, /* create main configuration */ NULL, /* init main configuration */ NULL, /* create server configuration */ NULL, /* merge server configuration */ NULL, /* create location configuration */ NULL /* merge location configuration */ }; ngx_module_t ngx_dynamic_upstream_module = { NGX_MODULE_V1, &ngx_dynamic_upstream_module_ctx, /* module context */ ngx_dynamic_upstream_commands, /* module directives */ NGX_HTTP_MODULE, /* module type */ NULL, /* init master */ NULL, /* init module */ NULL, /* init process */ NULL, /* init thread */ NULL, /* exit thread */ NULL, /* exit process */ NULL, /* exit master */ NGX_MODULE_V1_PADDING }; static ngx_http_upstream_srv_conf_t * ngx_dynamic_upstream_get_zone(ngx_http_request_t *r, ngx_dynamic_upstream_op_t *op) { ngx_uint_t i; ngx_http_upstream_srv_conf_t *uscf, **uscfp; ngx_http_upstream_main_conf_t *umcf; umcf = ngx_http_get_module_main_conf(r, ngx_http_upstream_module); uscfp = umcf->upstreams.elts; for (i = 0; i < umcf->upstreams.nelts; i++) { uscf = uscfp[i]; if (uscf->shm_zone != NULL && uscf->shm_zone->shm.name.len == op->upstream.len && ngx_strncmp(uscf->shm_zone->shm.name.data, op->upstream.data, op->upstream.len) == 0) { return uscf; } } return NULL; } static ngx_int_t ngx_dynamic_upstream_create_response_buf(ngx_http_upstream_rr_peers_t *peers, ngx_buf_t *b, size_t size, ngx_int_t verbose) { ngx_http_upstream_rr_peer_t *peer; u_char namebuf[512], *last; last = b->last + size; for (peer = peers->peer; peer; peer = peer->next) { if (peer->name.len > 511) { return NGX_ERROR; } ngx_cpystrn(namebuf, peer->name.data, peer->name.len + 1); if (verbose) { b->last = ngx_snprintf(b->last, last - b->last, "server %s weight=%d max_fails=%d fail_timeout=%d", namebuf, peer->weight, peer->max_fails, peer->fail_timeout, peer->down); } else { b->last = ngx_snprintf(b->last, last - b->last, "server %s", namebuf); } b->last = peer->down ? ngx_snprintf(b->last, last - b->last, " down;\n") : ngx_snprintf(b->last, last - b->last, ";\n"); } return NGX_OK; } static ngx_int_t ngx_dynamic_upstream_handler(ngx_http_request_t *r) { size_t size; ngx_int_t rc; ngx_chain_t out; ngx_dynamic_upstream_op_t op; ngx_buf_t *b; ngx_http_upstream_srv_conf_t *uscf; ngx_slab_pool_t *shpool; if (r->method != NGX_HTTP_GET && r->method != NGX_HTTP_HEAD) { return NGX_HTTP_NOT_ALLOWED; } rc = ngx_http_discard_request_body(r); if (rc != NGX_OK) { return rc; } r->headers_out.content_type_len = sizeof("text/plain") - 1; ngx_str_set(&r->headers_out.content_type, "text/plain"); r->headers_out.content_type_lowcase = NULL; if (r->method == NGX_HTTP_HEAD) { r->headers_out.status = NGX_HTTP_OK; rc = ngx_http_send_header(r); if (rc == NGX_ERROR || rc > NGX_OK || r->header_only) { return rc; } } rc = ngx_dynamic_upstream_build_op(r, &op); if (rc != NGX_OK) { if (op.status == NGX_HTTP_OK) { return NGX_HTTP_INTERNAL_SERVER_ERROR; } return op.status; } uscf = ngx_dynamic_upstream_get_zone(r, &op); if (uscf == NULL) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "upstream is not found. %s:%d", __FUNCTION__, __LINE__); return NGX_HTTP_NOT_FOUND; } shpool = (ngx_slab_pool_t *) uscf->shm_zone->shm.addr; ngx_shmtx_lock(&shpool->mutex); rc = ngx_dynamic_upstream_op(r, &op, shpool, uscf); if (rc != NGX_OK) { ngx_shmtx_unlock(&shpool->mutex); if (op.status == NGX_HTTP_OK) { return NGX_HTTP_INTERNAL_SERVER_ERROR; } return op.status; } ngx_shmtx_unlock(&shpool->mutex); size = uscf->shm_zone->shm.size; b = ngx_create_temp_buf(r->pool, size); if (b == NULL) { return NGX_HTTP_INTERNAL_SERVER_ERROR; } out.buf = b; out.next = NULL; rc = ngx_dynamic_upstream_create_response_buf((ngx_http_upstream_rr_peers_t *)uscf->peer.data, b, size, op.verbose); if (rc == NGX_ERROR) { ngx_log_error(NGX_LOG_ERR, r->connection->log, 0, "failed to create a response. %s:%d", __FUNCTION__, __LINE__); return NGX_HTTP_INTERNAL_SERVER_ERROR; } r->headers_out.status = NGX_HTTP_OK; r->headers_out.content_length_n = b->last - b->pos; b->last_buf = (r == r->main) ? 1 : 0; b->last_in_chain = 1; rc = ngx_http_send_header(r); if (rc == NGX_ERROR || rc > NGX_OK || r->header_only) { return rc; } return ngx_http_output_filter(r, &out); } static char * ngx_dynamic_upstream(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) { ngx_http_core_loc_conf_t *clcf; clcf = ngx_http_conf_get_module_loc_conf(cf, ngx_http_core_module); clcf->handler = ngx_dynamic_upstream_handler; return NGX_CONF_OK; }
3,720
4,816
/** * @file src/ctypes/reference_type.cpp * @brief Implementation of ReferenceType. * @copyright (c) 2018 Avast Software, licensed under the MIT license */ #include <cassert> #include "retdec/ctypes/context.h" #include "retdec/ctypes/reference_type.h" #include "retdec/ctypes/visitor.h" namespace retdec { namespace ctypes { /** * @brief Constructs new reference type. */ ReferenceType::ReferenceType( const std::shared_ptr<Type> &referencedType, unsigned int bitWidth) : Type("", bitWidth), referencedType(referencedType) {} /** * Creates reference type. * * @param context Storage for already created functions, types. * @param referencedType Type that reference references. * @param bitWidth Number of bits used by this type. * * @par Preconditions * - @a context is not null * - @a referencedType is not null * * Does not create new pointer type, if one * has already been created and stored in @c context. */ std::shared_ptr<ReferenceType> ReferenceType::create( const std::shared_ptr<Context> &context, const std::shared_ptr<Type> &referencedType, unsigned int bitWidth) { assert(context && "violated precondition - context cannot be null"); assert(referencedType && "violated precondition - referencedType cannot be null"); auto type = context->getReferenceType(referencedType); if (type) { return type; } std::shared_ptr<ReferenceType> newType(new ReferenceType(referencedType, bitWidth)); context->addReferenceType(newType); return newType; } /** * @brief Returns referencedType. */ std::shared_ptr<Type> ReferenceType::getReferencedType() const { return referencedType; } /** * Returns @c true when Type is pointer, @c false otherwise. */ bool ReferenceType::isReference() const { return true; } void ReferenceType::accept(Visitor *v) { v->visit(std::static_pointer_cast<ReferenceType>(shared_from_this())); } } // namespace ctypes } // namespace retdec
594
5,133
<gh_stars>1000+ /* * Copyright MapStruct Authors. * * Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0 */ package org.mapstruct.ap.test.nestedproperties.simple.source; public class SourceRoot { private SourceProps props; public void setProps(SourceProps props) { this.props = props; } public SourceProps getProps() { return props; } }
157
16,461
// Copyright ยฉ 2018 650 Industries. All rights reserved. #import <ExpoModulesCore/EXExportedModule.h> #import <ExpoModulesCore/EXModuleRegistryConsumer.h> static NSString *const EXNetworkTypeUnknown = @"UNKNOWN"; static NSString *const EXNetworkTypeNone = @"NONE"; static NSString *const EXNetworkTypeWifi = @"WIFI"; static NSString *const EXNetworkTypeCellular = @"CELLULAR"; @interface EXNetwork : EXExportedModule <EXModuleRegistryConsumer> @end
139
892
{ "schema_version": "1.2.0", "id": "GHSA-72w6-jr6g-jmgh", "modified": "2022-05-01T06:42:32Z", "published": "2022-05-01T06:42:32Z", "aliases": [ "CVE-2006-0766" ], "details": "ICQ Inc. (formerly Mirabilis) ICQ 2003a, 2003b, Lite 4.0, Lite 4.1, and possibly other Windows versions allows user-assisted remote attackers to hide malicious file extensions and bypass Windows security warnings via a filename that ends in an assumed-safe extension such as JPG, and possibly containing other modified properties such as company name, icon, and description, which could trick a user into executing arbitrary programs.", "severity": [ ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2006-0766" }, { "type": "WEB", "url": "http://www.securityfocus.com/archive/1/425078/100/0/threaded" }, { "type": "WEB", "url": "http://www.securityfocus.com/bid/16655" } ], "database_specific": { "cwe_ids": [ ], "severity": "MODERATE", "github_reviewed": false } }
439
711
package com.java110.goods.bmo.storeOrderCartReturn.impl; import com.java110.core.annotation.Java110Transactional; import com.java110.goods.bmo.storeOrderCartReturn.IDeleteStoreOrderCartReturnBMO; import com.java110.intf.goods.IStoreOrderCartReturnInnerServiceSMO; import com.java110.po.storeOrderCartReturn.StoreOrderCartReturnPo; import com.java110.vo.ResultVo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; @Service("deleteStoreOrderCartReturnBMOImpl") public class DeleteStoreOrderCartReturnBMOImpl implements IDeleteStoreOrderCartReturnBMO { @Autowired private IStoreOrderCartReturnInnerServiceSMO storeOrderCartReturnInnerServiceSMOImpl; /** * @param storeOrderCartReturnPo ๆ•ฐๆฎ * @return ่ฎขๅ•ๆœๅŠก่ƒฝๅคŸๆŽฅๅ—็š„ๆŠฅๆ–‡ */ @Java110Transactional public ResponseEntity<String> delete(StoreOrderCartReturnPo storeOrderCartReturnPo) { int flag = storeOrderCartReturnInnerServiceSMOImpl.deleteStoreOrderCartReturn(storeOrderCartReturnPo); if (flag > 0) { return ResultVo.createResponseEntity(ResultVo.CODE_OK, "ไฟๅญ˜ๆˆๅŠŸ"); } return ResultVo.createResponseEntity(ResultVo.CODE_ERROR, "ไฟๅญ˜ๅคฑ่ดฅ"); } }
472
3,182
<reponame>Junzerg/lombok import java.util.List; public class SuperBuilderBasicToBuilder { @lombok.experimental.SuperBuilder(toBuilder=true) public static class Parent { private int field1; @lombok.Builder.ObtainVia(field="field1") int obtainViaField; @lombok.Builder.ObtainVia(method="method") int obtainViaMethod; @lombok.Builder.ObtainVia(method = "staticMethod", isStatic = true) String obtainViaStaticMethod; @lombok.Singular List<String> items; private int method() { return 2; } private static String staticMethod(Parent instance) { return "staticMethod"; } } @lombok.experimental.SuperBuilder(toBuilder=true) public static class Child extends Parent { private double field3; } public static void test() { Child x = Child.builder().field3(0.0).field1(5).item("").build().toBuilder().build(); } }
305
4,339
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.internal.visor.verify; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import org.apache.ignite.internal.util.typedef.internal.S; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.internal.visor.VisorDataTransferObject; /** * */ public class VisorViewCacheTaskArg extends VisorDataTransferObject { /** */ private static final long serialVersionUID = 0L; /** Regex. */ private String regex; /** Type. */ private VisorViewCacheCmd cmd; /** * @param regex Regex. * @param cmd Command. */ public VisorViewCacheTaskArg(String regex, VisorViewCacheCmd cmd) { this.regex = regex; this.cmd = cmd; } /** * For externalization only. */ public VisorViewCacheTaskArg() { } /** * @return Regex. */ public String regex() { return regex; } /** * @return Command. */ public VisorViewCacheCmd command() { return cmd; } /** {@inheritDoc} */ @Override protected void writeExternalData(ObjectOutput out) throws IOException { U.writeString(out, regex); U.writeEnum(out, cmd); } /** {@inheritDoc} */ @Override protected void readExternalData(byte protoVer, ObjectInput in) throws IOException, ClassNotFoundException { regex = U.readString(in); cmd = VisorViewCacheCmd.fromOrdinal(in.readByte()); } /** {@inheritDoc} */ @Override public String toString() { return S.toString(VisorViewCacheTaskArg.class, this); } }
827
1,125
<gh_stars>1000+ /* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.client.security; import org.elasticsearch.client.Validatable; import org.elasticsearch.client.security.user.privileges.ApplicationPrivilege; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.xcontent.ToXContentObject; import org.elasticsearch.common.xcontent.XContentBuilder; import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.TreeMap; import java.util.stream.Collectors; /** * Request object for creating/updating application privileges. */ public final class PutPrivilegesRequest implements Validatable, ToXContentObject { private final Map<String, List<ApplicationPrivilege>> privileges; private final RefreshPolicy refreshPolicy; public PutPrivilegesRequest(final List<ApplicationPrivilege> privileges, @Nullable final RefreshPolicy refreshPolicy) { if (privileges == null || privileges.isEmpty()) { throw new IllegalArgumentException("privileges are required"); } this.privileges = Collections.unmodifiableMap(privileges.stream() .collect(Collectors.groupingBy(ApplicationPrivilege::getApplication, TreeMap::new, Collectors.toList()))); this.refreshPolicy = refreshPolicy == null ? RefreshPolicy.IMMEDIATE : refreshPolicy; } /** * @return a map of application name to list of * {@link ApplicationPrivilege}s */ public Map<String, List<ApplicationPrivilege>> getPrivileges() { return privileges; } public RefreshPolicy getRefreshPolicy() { return refreshPolicy; } @Override public int hashCode() { return Objects.hash(privileges, refreshPolicy); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || (this.getClass() != o.getClass())) { return false; } final PutPrivilegesRequest that = (PutPrivilegesRequest) o; return privileges.equals(that.privileges) && (refreshPolicy == that.refreshPolicy); } @Override public XContentBuilder toXContent(final XContentBuilder builder, final Params params) throws IOException { builder.startObject(); for (Entry<String, List<ApplicationPrivilege>> entry : privileges.entrySet()) { builder.field(entry.getKey()); builder.startObject(); for (ApplicationPrivilege applicationPrivilege : entry.getValue()) { builder.field(applicationPrivilege.getName()); applicationPrivilege.toXContent(builder, params); } builder.endObject(); } return builder.endObject(); } }
1,199
1,038
import kopf @kopf.on.create('zalando.org', 'v1', 'kopfexamples') def create_fn(logger, **kwargs): logger.info("Something was logged here.")
59
458
package com.example.gitnb.module.repos; import android.content.Context; import android.graphics.Color; import android.graphics.Paint; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.RecyclerView.ViewHolder; import android.text.Html; import android.util.StringBuilderPrinter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.example.gitnb.R; import com.example.gitnb.model.Content; import com.example.gitnb.module.viewholder.RepoContentViewHolder; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ReposPathAdapter extends RecyclerView.Adapter<ViewHolder>{ private Context mContext; private static final int TYPE_NORMAL_VIEW = 0; private OnItemClickListener mItemClickListener; protected final LayoutInflater mInflater; private ArrayList<String> mPaths; public interface OnItemClickListener { void onItemClick(View view, int position); } public ReposPathAdapter(Context context, String reposName) { mContext = context; mPaths = new ArrayList<>(); mPaths.add(reposName); mInflater = LayoutInflater.from(mContext); } public void SetOnItemClickListener(final OnItemClickListener mItemClickListener) { this.mItemClickListener = mItemClickListener; } public String getItem(int position) { return mPaths == null ? null : mPaths.get(position); } @Override public long getItemId(int position) { return position; } public void update(ArrayList<String> data){ mPaths= data; reset(); } public void insertAtBack(ArrayList<String> data){ if (data != null && data.size() > 0){ mPaths.addAll(data); } reset(); } public void insertAtBack(String value){ mPaths.add(value); notifyItemInserted(getItemCount() - 1); // if you want trigger the item animation, //do not call notifyDataSetChanged() function } public String getPathString(){ StringBuilder result = new StringBuilder(); for(int i=1; i< mPaths.size(); i++){ result.append(mPaths.get(i)); if(i!=mPaths.size()-1){ result.append("/"); } } return result.toString(); } public void reset(){ notifyDataSetChanged(); } public boolean isRoot(){ return mPaths.size() >1; } public void goPrevious(){ mPaths = new ArrayList<>(mPaths.subList(0, mPaths.size()-1)); reset(); } @Override public int getItemCount() { return mPaths == null ? 0 : mPaths.size(); } @Override public int getItemViewType(int position) { return TYPE_NORMAL_VIEW; } @Override public ViewHolder onCreateViewHolder(ViewGroup viewgroup, int viewType) { View v = mInflater.inflate(R.layout.path_list_item,viewgroup,false); return new ReposPathView(v); } @Override public void onBindViewHolder(ViewHolder vh, int position) { switch(getItemViewType(position)){ case TYPE_NORMAL_VIEW: ReposPathView viewHolder = (ReposPathView) vh; viewHolder.path_name.setText(Html.fromHtml("<u>" + getItem(position) + "</u>")); if(position == 0) { viewHolder.path_seperator.setVisibility(View.GONE); } else{ viewHolder.path_seperator.setVisibility(View.VISIBLE); } break; } } private class ReposPathView extends RecyclerView.ViewHolder{ public TextView path_name; public TextView path_seperator; public ReposPathView(View view) { super(view); path_name = (TextView) view.findViewById(R.id.path_name); path_seperator = (TextView) view.findViewById(R.id.path_seperator); view.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { if (getLayoutPosition() != getItemCount()-1 && mItemClickListener != null) { mPaths = new ArrayList<>(mPaths.subList(0, getLayoutPosition()+1)); reset(); mItemClickListener.onItemClick(v, getLayoutPosition()); } } }); } } }
1,738
679
<reponame>Grosskopf/openoffice /************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_file.hxx" #include <stdio.h> #include "filglob.hxx" #ifndef _FILERROR_HXX_ #include "filerror.hxx" #endif #include "shell.hxx" #include "bc.hxx" #include <osl/file.hxx> #ifndef INCLUDED_STL_VECTOR #include <vector> #define INCLUDED_STL_VECTOR #endif #include <ucbhelper/cancelcommandexecution.hxx> #include <com/sun/star/ucb/CommandAbortedException.hpp> #include <com/sun/star/ucb/UnsupportedCommandException.hpp> #include <com/sun/star/ucb/UnsupportedOpenModeException.hpp> #include <com/sun/star/lang/IllegalArgumentException.hpp> #include <com/sun/star/ucb/IOErrorCode.hpp> #include <com/sun/star/ucb/MissingPropertiesException.hpp> #include <com/sun/star/ucb/MissingInputStreamException.hpp> #include <com/sun/star/ucb/NameClashException.hpp> #include <com/sun/star/ucb/InteractiveBadTransferURLException.hpp> #include <com/sun/star/ucb/UnsupportedNameClashException.hpp> #include "com/sun/star/beans/PropertyState.hpp" #include "com/sun/star/beans/PropertyValue.hpp" #include <com/sun/star/ucb/InteractiveAugmentedIOException.hpp> #include "com/sun/star/uno/Any.hxx" #include "com/sun/star/uno/Sequence.hxx" #include "osl/diagnose.h" #include "rtl/ustrbuf.hxx" #include <rtl/uri.hxx> #include <rtl/ustring.hxx> #include "sal/types.h" using namespace ucbhelper; using namespace osl; using namespace ::com::sun::star; using namespace com::sun::star::task; using namespace com::sun::star::beans; using namespace com::sun::star::lang; using namespace com::sun::star::uno; using namespace com::sun::star::ucb; namespace { Sequence< Any > generateErrorArguments( rtl::OUString const & rPhysicalUrl) { rtl::OUString aResourceName; rtl::OUString aResourceType; sal_Bool bRemovable; bool bResourceName = false; bool bResourceType = false; bool bRemoveProperty = false; if (osl::FileBase::getSystemPathFromFileURL( rPhysicalUrl, aResourceName) == osl::FileBase::E_None) bResourceName = true; // The resource types "folder" (i.e., directory) and // "volume" seem to be // the most interesting when producing meaningful error messages: osl::DirectoryItem aItem; if (osl::DirectoryItem::get(rPhysicalUrl, aItem) == osl::FileBase::E_None) { osl::FileStatus aStatus( FileStatusMask_Type ); if (aItem.getFileStatus(aStatus) == osl::FileBase::E_None) switch (aStatus.getFileType()) { case osl::FileStatus::Directory: aResourceType = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("folder")); bResourceType = true; break; case osl::FileStatus::Volume: { aResourceType = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("volume")); bResourceType = true; osl::VolumeInfo aVolumeInfo( VolumeInfoMask_Attributes ); if( osl::Directory::getVolumeInfo( rPhysicalUrl,aVolumeInfo ) == osl::FileBase::E_None ) { bRemovable = aVolumeInfo.getRemoveableFlag(); bRemoveProperty = true; } } break; case osl::FileStatus::Regular: case osl::FileStatus::Fifo: case osl::FileStatus::Socket: case osl::FileStatus::Link: case osl::FileStatus::Special: case osl::FileStatus::Unknown: // do nothing for now break; } } Sequence< Any > aArguments( 1 + (bResourceName ? 1 : 0) + (bResourceType ? 1 : 0) + (bRemoveProperty ? 1 : 0) ); sal_Int32 i = 0; aArguments[i++] <<= PropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "Uri")), -1, makeAny(rPhysicalUrl), PropertyState_DIRECT_VALUE); if (bResourceName) aArguments[i++] <<= PropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "ResourceName")), -1, makeAny(aResourceName), PropertyState_DIRECT_VALUE); if (bResourceType) aArguments[i++] <<= PropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "ResourceType")), -1, makeAny(aResourceType), PropertyState_DIRECT_VALUE); if (bRemoveProperty) aArguments[i++] <<= PropertyValue(rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "Removable")), -1, makeAny(bRemovable), PropertyState_DIRECT_VALUE); return aArguments; } } namespace fileaccess { sal_Bool isChild( const rtl::OUString& srcUnqPath, const rtl::OUString& dstUnqPath ) { static sal_Unicode slash = '/'; // Simple lexical comparison sal_Int32 srcL = srcUnqPath.getLength(); sal_Int32 dstL = dstUnqPath.getLength(); return ( ( srcUnqPath == dstUnqPath ) || ( ( dstL > srcL ) && ( srcUnqPath.compareTo( dstUnqPath, srcL ) == 0 ) && ( dstUnqPath[ srcL ] == slash ) ) ); } rtl::OUString newName( const rtl::OUString& aNewPrefix, const rtl::OUString& aOldPrefix, const rtl::OUString& old_Name ) { sal_Int32 srcL = aOldPrefix.getLength(); rtl::OUString new_Name = old_Name.copy( srcL ); new_Name = ( aNewPrefix + new_Name ); return new_Name; } rtl::OUString getTitle( const rtl::OUString& aPath ) { sal_Unicode slash = '/'; sal_Int32 lastIndex = aPath.lastIndexOf( slash ); return aPath.copy( lastIndex + 1 ); } rtl::OUString getParentName( const rtl::OUString& aFileName ) { sal_Int32 lastIndex = aFileName.lastIndexOf( sal_Unicode('/') ); rtl::OUString aParent = aFileName.copy( 0,lastIndex ); if( aParent[ aParent.getLength()-1] == sal_Unicode(':') && aParent.getLength() == 6 ) aParent += rtl::OUString::createFromAscii( "/" ); if( 0 == aParent.compareToAscii( "file://" ) ) aParent = rtl::OUString::createFromAscii( "file:///" ); return aParent; } osl::FileBase::RC osl_File_copy( const rtl::OUString& strPath, const rtl::OUString& strDestPath, sal_Bool test ) { if( test ) { osl::DirectoryItem aItem; if( osl::DirectoryItem::get( strDestPath,aItem ) != osl::FileBase:: E_NOENT ) return osl::FileBase::E_EXIST; } return osl::File::copy( strPath,strDestPath ); } osl::FileBase::RC osl_File_move( const rtl::OUString& strPath, const rtl::OUString& strDestPath, sal_Bool test ) { if( test ) { osl::DirectoryItem aItem; if( osl::DirectoryItem::get( strDestPath,aItem ) != osl::FileBase:: E_NOENT ) return osl::FileBase::E_EXIST; } return osl::File::move( strPath,strDestPath ); } void throw_handler( sal_Int32 errorCode, sal_Int32 minorCode, const Reference< XCommandEnvironment >& xEnv, const rtl::OUString& aUncPath, BaseContent* pContent, bool isHandled ) { Reference<XCommandProcessor> xComProc(pContent); Any aAny; IOErrorCode ioErrorCode; if( errorCode == TASKHANDLER_UNSUPPORTED_COMMAND ) { aAny <<= UnsupportedCommandException( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( OSL_LOG_PREFIX ) ), uno::Reference< uno::XInterface >() ); cancelCommandExecution( aAny,xEnv ); } else if( errorCode == TASKHANDLING_WRONG_SETPROPERTYVALUES_ARGUMENT || errorCode == TASKHANDLING_WRONG_GETPROPERTYVALUES_ARGUMENT || errorCode == TASKHANDLING_WRONG_OPEN_ARGUMENT || errorCode == TASKHANDLING_WRONG_DELETE_ARGUMENT || errorCode == TASKHANDLING_WRONG_TRANSFER_ARGUMENT || errorCode == TASKHANDLING_WRONG_INSERT_ARGUMENT || errorCode == TASKHANDLING_WRONG_CREATENEWCONTENT_ARGUMENT ) { IllegalArgumentException excep; excep.ArgumentPosition = 0; aAny <<= excep; cancelCommandExecution( aAny,xEnv); } else if( errorCode == TASKHANDLING_UNSUPPORTED_OPEN_MODE ) { UnsupportedOpenModeException excep; excep.Mode = sal::static_int_cast< sal_Int16 >(minorCode); aAny <<= excep; cancelCommandExecution( aAny,xEnv ); } else if(errorCode == TASKHANDLING_DELETED_STATE_IN_OPEN_COMMAND || errorCode == TASKHANDLING_INSERTED_STATE_IN_OPEN_COMMAND || errorCode == TASKHANDLING_NOFRESHINSERT_IN_INSERT_COMMAND ) { // What to do here? } else if( // error in opening file errorCode == TASKHANDLING_NO_OPEN_FILE_FOR_OVERWRITE || // error in opening file errorCode == TASKHANDLING_NO_OPEN_FILE_FOR_WRITE || // error in opening file errorCode == TASKHANDLING_OPEN_FOR_STREAM || // error in opening file errorCode == TASKHANDLING_OPEN_FOR_INPUTSTREAM || // error in opening file errorCode == TASKHANDLING_OPEN_FILE_FOR_PAGING ) { switch( minorCode ) { case FileBase::E_NAMETOOLONG: // pathname was too long ioErrorCode = IOErrorCode_NAME_TOO_LONG; break; case FileBase::E_NXIO: // No such device or address case FileBase::E_NODEV: // No such device ioErrorCode = IOErrorCode_INVALID_DEVICE; break; case FileBase::E_NOENT: // No such file or directory ioErrorCode = IOErrorCode_NOT_EXISTING; break; case FileBase::E_ROFS: // #i4735# handle ROFS transparently as ACCESS_DENIED case FileBase::E_ACCES: // permission denied<P> ioErrorCode = IOErrorCode_ACCESS_DENIED; break; case FileBase::E_ISDIR: // Is a directory<p> ioErrorCode = IOErrorCode_NO_FILE; break; case FileBase::E_NOTREADY: ioErrorCode = IOErrorCode_DEVICE_NOT_READY; break; case FileBase::E_MFILE: // too many open files used by the process case FileBase::E_NFILE: // too many open files in the system ioErrorCode = IOErrorCode_OUT_OF_FILE_HANDLES; break; case FileBase::E_INVAL: // the format of the parameters was not valid ioErrorCode = IOErrorCode_INVALID_PARAMETER; break; case FileBase::E_NOMEM: // not enough memory for allocating structures ioErrorCode = IOErrorCode_OUT_OF_MEMORY; break; case FileBase::E_BUSY: // Text file busy ioErrorCode = IOErrorCode_LOCKING_VIOLATION; break; case FileBase::E_AGAIN: // Operation would block ioErrorCode = IOErrorCode_LOCKING_VIOLATION; break; case FileBase::E_NOLCK: // No record locks available ioErrorCode = IOErrorCode_LOCKING_VIOLATION; break; case FileBase::E_LOCKED: // file is locked by another user ioErrorCode = IOErrorCode_LOCKING_VIOLATION; break; case FileBase::E_FAULT: // Bad address case FileBase::E_LOOP: // Too many symbolic links encountered case FileBase::E_NOSPC: // No space left on device case FileBase::E_INTR: // function call was interrupted case FileBase::E_IO: // I/O error case FileBase::E_MULTIHOP: // Multihop attempted case FileBase::E_NOLINK: // Link has been severed default: ioErrorCode = IOErrorCode_GENERAL; break; } cancelCommandExecution( ioErrorCode, generateErrorArguments(aUncPath), xEnv, rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "an error occurred during file opening")), xComProc); } else if( errorCode == TASKHANDLING_OPEN_FOR_DIRECTORYLISTING || errorCode == TASKHANDLING_OPENDIRECTORY_FOR_REMOVE ) { switch( minorCode ) { case FileBase::E_INVAL: // the format of the parameters was not valid ioErrorCode = IOErrorCode_INVALID_PARAMETER; break; case FileBase::E_NOENT: // the specified path doesn't exist ioErrorCode = IOErrorCode_NOT_EXISTING; break; case FileBase::E_NOTDIR: // the specified path is not an directory ioErrorCode = IOErrorCode_NO_DIRECTORY; break; case FileBase::E_NOMEM: // not enough memory for allocating structures ioErrorCode = IOErrorCode_OUT_OF_MEMORY; break; case FileBase::E_ROFS: // #i4735# handle ROFS transparently as ACCESS_DENIED case FileBase::E_ACCES: // permission denied ioErrorCode = IOErrorCode_ACCESS_DENIED; break; case FileBase::E_NOTREADY: ioErrorCode = IOErrorCode_DEVICE_NOT_READY; break; case FileBase::E_MFILE: // too many open files used by the process case FileBase::E_NFILE: // too many open files in the system ioErrorCode = IOErrorCode_OUT_OF_FILE_HANDLES; break; case FileBase::E_NAMETOOLONG: // File name too long ioErrorCode = IOErrorCode_NAME_TOO_LONG; break; case FileBase::E_LOOP: // Too many symbolic links encountered<p> default: ioErrorCode = IOErrorCode_GENERAL; break; } cancelCommandExecution( ioErrorCode, generateErrorArguments(aUncPath), xEnv, rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "an error occurred during opening a directory")), xComProc); } else if( errorCode == TASKHANDLING_NOTCONNECTED_FOR_WRITE || errorCode == TASKHANDLING_BUFFERSIZEEXCEEDED_FOR_WRITE || errorCode == TASKHANDLING_IOEXCEPTION_FOR_WRITE || errorCode == TASKHANDLING_NOTCONNECTED_FOR_PAGING || errorCode == TASKHANDLING_BUFFERSIZEEXCEEDED_FOR_PAGING || errorCode == TASKHANDLING_IOEXCEPTION_FOR_PAGING ) { ioErrorCode = IOErrorCode_UNKNOWN; cancelCommandExecution( ioErrorCode, generateErrorArguments(aUncPath), xEnv, rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "an error occurred writing or reading from a file")), xComProc ); } else if( errorCode == TASKHANDLING_FILEIOERROR_FOR_NO_SPACE ) { ioErrorCode = IOErrorCode_OUT_OF_DISK_SPACE; cancelCommandExecution( ioErrorCode, generateErrorArguments(aUncPath), xEnv, rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "device full")), xComProc); } else if( errorCode == TASKHANDLING_FILEIOERROR_FOR_WRITE || errorCode == TASKHANDLING_READING_FILE_FOR_PAGING ) { switch( minorCode ) { case FileBase::E_INVAL: // the format of the parameters was not valid ioErrorCode = IOErrorCode_INVALID_PARAMETER; break; case FileBase::E_FBIG: // File too large ioErrorCode = IOErrorCode_CANT_WRITE; break; case FileBase::E_NOSPC: // No space left on device ioErrorCode = IOErrorCode_OUT_OF_DISK_SPACE; break; case FileBase::E_NXIO: // No such device or address ioErrorCode = IOErrorCode_INVALID_DEVICE; break; case FileBase::E_NOLINK: // Link has been severed case FileBase::E_ISDIR: // Is a directory ioErrorCode = IOErrorCode_NO_FILE; break; case FileBase::E_AGAIN: // Operation would block ioErrorCode = IOErrorCode_LOCKING_VIOLATION; break; case FileBase::E_TIMEDOUT: ioErrorCode = IOErrorCode_DEVICE_NOT_READY; break; case FileBase::E_NOLCK: // No record locks available ioErrorCode = IOErrorCode_LOCKING_VIOLATION; break; case FileBase::E_IO: // I/O error case FileBase::E_BADF: // Bad file case FileBase::E_FAULT: // Bad address case FileBase::E_INTR: // function call was interrupted default: ioErrorCode = IOErrorCode_GENERAL; break; } cancelCommandExecution( ioErrorCode, generateErrorArguments(aUncPath), xEnv, rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "an error occurred during opening a file")), xComProc); } else if( errorCode == TASKHANDLING_NONAMESET_INSERT_COMMAND || errorCode == TASKHANDLING_NOCONTENTTYPE_INSERT_COMMAND ) { Sequence< ::rtl::OUString > aSeq( 1 ); aSeq[0] = ( errorCode == TASKHANDLING_NONAMESET_INSERT_COMMAND ) ? rtl::OUString::createFromAscii( "Title" ) : rtl::OUString::createFromAscii( "ContentType" ); aAny <<= MissingPropertiesException( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "a property is missing necessary" "to create a content")), xComProc, aSeq); cancelCommandExecution(aAny,xEnv); } else if( errorCode == TASKHANDLING_FILESIZE_FOR_WRITE ) { switch( minorCode ) { case FileBase::E_INVAL: // the format of the parameters was not valid case FileBase::E_OVERFLOW: // The resulting file offset would be a value which cannot // be represented correctly for regular files ioErrorCode = IOErrorCode_INVALID_PARAMETER; break; default: ioErrorCode = IOErrorCode_GENERAL; break; } cancelCommandExecution( ioErrorCode, generateErrorArguments(aUncPath), xEnv, rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "there were problems with the filesize")), xComProc); } else if(errorCode == TASKHANDLING_INPUTSTREAM_FOR_WRITE) { Reference<XInterface> xContext(xComProc,UNO_QUERY); aAny <<= MissingInputStreamException( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "the inputstream is missing necessary" "to create a content")), xContext); cancelCommandExecution(aAny,xEnv); } else if( errorCode == TASKHANDLING_NOREPLACE_FOR_WRITE ) // Overwrite = false and file exists { NameClashException excep; excep.Name = getTitle(aUncPath); excep.Classification = InteractionClassification_ERROR; Reference<XInterface> xContext(xComProc,UNO_QUERY); excep.Context = xContext; excep.Message = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "file exists and overwrite forbidden")); aAny <<= excep; cancelCommandExecution( aAny,xEnv ); } else if( errorCode == TASKHANDLING_INVALID_NAME_MKDIR ) { InteractiveAugmentedIOException excep; excep.Code = IOErrorCode_INVALID_CHARACTER; PropertyValue prop; prop.Name = rtl::OUString::createFromAscii("ResourceName"); prop.Handle = -1; rtl::OUString m_aClashingName( rtl::Uri::decode( getTitle(aUncPath), rtl_UriDecodeWithCharset, RTL_TEXTENCODING_UTF8)); prop.Value <<= m_aClashingName; Sequence<Any> seq(1); seq[0] <<= prop; excep.Arguments = seq; excep.Classification = InteractionClassification_ERROR; Reference<XInterface> xContext(xComProc,UNO_QUERY); excep.Context = xContext; excep.Message = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "the name contained invalid characters")); if(isHandled) throw excep; else { aAny <<= excep; cancelCommandExecution( aAny,xEnv ); } // ioErrorCode = IOErrorCode_INVALID_CHARACTER; // cancelCommandExecution( // ioErrorCode, // generateErrorArguments(aUncPath), // xEnv, // rtl::OUString( // RTL_CONSTASCII_USTRINGPARAM( // "the name contained invalid characters")), // xComProc ); } else if( errorCode == TASKHANDLING_FOLDER_EXISTS_MKDIR ) { NameClashException excep; excep.Name = getTitle(aUncPath); excep.Classification = InteractionClassification_ERROR; Reference<XInterface> xContext(xComProc,UNO_QUERY); excep.Context = xContext; excep.Message = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "folder exists and overwrite forbidden")); if(isHandled) throw excep; else { aAny <<= excep; cancelCommandExecution( aAny,xEnv ); } // ioErrorCode = IOErrorCode_ALREADY_EXISTING; // cancelCommandExecution( // ioErrorCode, // generateErrorArguments(aUncPath), // xEnv, // rtl::OUString( // RTL_CONSTASCII_USTRINGPARAM( // "the folder exists")), // xComProc ); } else if( errorCode == TASKHANDLING_ENSUREDIR_FOR_WRITE || errorCode == TASKHANDLING_CREATEDIRECTORY_MKDIR ) { switch( minorCode ) { case FileBase::E_ACCES: ioErrorCode = IOErrorCode_ACCESS_DENIED; break; case FileBase::E_ROFS: ioErrorCode = IOErrorCode_WRITE_PROTECTED; break; case FileBase::E_NAMETOOLONG: ioErrorCode = IOErrorCode_NAME_TOO_LONG; break; default: ioErrorCode = IOErrorCode_NOT_EXISTING_PATH; break; } cancelCommandExecution( ioErrorCode, generateErrorArguments(getParentName(aUncPath)), //TODO! ok to supply physical URL to getParentName()? xEnv, rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "a folder could not be created")), xComProc ); } else if( errorCode == TASKHANDLING_VALIDFILESTATUSWHILE_FOR_REMOVE || errorCode == TASKHANDLING_VALIDFILESTATUS_FOR_REMOVE || errorCode == TASKHANDLING_NOSUCHFILEORDIR_FOR_REMOVE ) { switch( minorCode ) { case FileBase::E_INVAL: // the format of the parameters was not valid ioErrorCode = IOErrorCode_INVALID_PARAMETER; break; case FileBase::E_NOMEM: // not enough memory for allocating structures ioErrorCode = IOErrorCode_OUT_OF_MEMORY; break; case FileBase::E_ROFS: // #i4735# handle ROFS transparently as ACCESS_DENIED case FileBase::E_ACCES: // permission denied ioErrorCode = IOErrorCode_ACCESS_DENIED; break; case FileBase::E_MFILE: // too many open files used by the process case FileBase::E_NFILE: // too many open files in the system ioErrorCode = IOErrorCode_OUT_OF_FILE_HANDLES; break; case FileBase::E_NOLINK: // Link has been severed case FileBase::E_NOENT: // No such file or directory ioErrorCode = IOErrorCode_NOT_EXISTING; break; case FileBase::E_NAMETOOLONG: // File name too long ioErrorCode = IOErrorCode_NAME_TOO_LONG; break; case FileBase::E_NOTDIR: // A component of the path prefix of path is not a directory ioErrorCode = IOErrorCode_NOT_EXISTING_PATH; break; case FileBase::E_LOOP: // Too many symbolic links encountered case FileBase::E_IO: // I/O error case FileBase::E_MULTIHOP: // Multihop attempted case FileBase::E_FAULT: // Bad address case FileBase::E_INTR: // function call was interrupted case FileBase::E_NOSYS: // Function not implemented case FileBase::E_NOSPC: // No space left on device case FileBase::E_NXIO: // No such device or address case FileBase::E_OVERFLOW: // Value too large for defined data type case FileBase::E_BADF: // Invalid oslDirectoryItem parameter default: ioErrorCode = IOErrorCode_GENERAL; break; } cancelCommandExecution( ioErrorCode, generateErrorArguments(aUncPath), xEnv, rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "a file status object could not be filled")), xComProc ); } else if( errorCode == TASKHANDLING_DELETEFILE_FOR_REMOVE || errorCode == TASKHANDLING_DELETEDIRECTORY_FOR_REMOVE ) { switch( minorCode ) { case FileBase::E_INVAL: // the format of the parameters was not valid ioErrorCode = IOErrorCode_INVALID_PARAMETER; break; case FileBase::E_NOMEM: // not enough memory for allocating structures ioErrorCode = IOErrorCode_OUT_OF_MEMORY; break; case FileBase::E_ACCES: // Permission denied ioErrorCode = IOErrorCode_ACCESS_DENIED; break; case FileBase::E_PERM: // Operation not permitted ioErrorCode = IOErrorCode_NOT_SUPPORTED; break; case FileBase::E_NAMETOOLONG: // File name too long ioErrorCode = IOErrorCode_NAME_TOO_LONG; break; case FileBase::E_NOLINK: // Link has been severed case FileBase::E_NOENT: // No such file or directory ioErrorCode = IOErrorCode_NOT_EXISTING; break; case FileBase::E_ISDIR: // Is a directory case FileBase::E_ROFS: // Read-only file system ioErrorCode = IOErrorCode_NOT_SUPPORTED; break; case FileBase::E_BUSY: // Device or resource busy ioErrorCode = IOErrorCode_LOCKING_VIOLATION; break; case FileBase::E_FAULT: // Bad address case FileBase::E_LOOP: // Too many symbolic links encountered case FileBase::E_IO: // I/O error case FileBase::E_INTR: // function call was interrupted case FileBase::E_MULTIHOP: // Multihop attempted default: ioErrorCode = IOErrorCode_GENERAL; break; } cancelCommandExecution( ioErrorCode, generateErrorArguments(aUncPath), xEnv, rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "a file or directory could not be deleted")), xComProc ); } else if( errorCode == TASKHANDLING_TRANSFER_BY_COPY_SOURCE || errorCode == TASKHANDLING_TRANSFER_BY_COPY_SOURCESTAT || errorCode == TASKHANDLING_TRANSFER_BY_MOVE_SOURCE || errorCode == TASKHANDLING_TRANSFER_BY_MOVE_SOURCESTAT || errorCode == TASKHANDLING_TRANSFER_DESTFILETYPE || errorCode == TASKHANDLING_FILETYPE_FOR_REMOVE || errorCode == TASKHANDLING_DIRECTORYEXHAUSTED_FOR_REMOVE || errorCode == TASKHANDLING_TRANSFER_INVALIDURL ) { rtl::OUString aMsg; switch( minorCode ) { case FileBase::E_NOENT: // No such file or directory if ( errorCode == TASKHANDLING_TRANSFER_BY_COPY_SOURCE || errorCode == TASKHANDLING_TRANSFER_BY_COPY_SOURCESTAT || errorCode == TASKHANDLING_TRANSFER_BY_MOVE_SOURCE || errorCode == TASKHANDLING_TRANSFER_BY_MOVE_SOURCESTAT ) { ioErrorCode = IOErrorCode_NOT_EXISTING; aMsg = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "source file/folder does not exist")); break; } else { ioErrorCode = IOErrorCode_GENERAL; aMsg = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "a general error during transfer command")); break; } default: ioErrorCode = IOErrorCode_GENERAL; aMsg = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "a general error during transfer command")); break; } cancelCommandExecution( ioErrorCode, generateErrorArguments(aUncPath), xEnv, aMsg, xComProc ); } else if( errorCode == TASKHANDLING_TRANSFER_ACCESSINGROOT ) { ioErrorCode = IOErrorCode_WRITE_PROTECTED; cancelCommandExecution( ioErrorCode, generateErrorArguments(aUncPath), xEnv, rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "accessing the root during transfer")), xComProc ); } else if( errorCode == TASKHANDLING_TRANSFER_INVALIDSCHEME ) { Reference<XInterface> xContext(xComProc,UNO_QUERY); aAny <<= InteractiveBadTransferURLException( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "bad transfer url")), xContext); cancelCommandExecution( aAny,xEnv ); } else if( errorCode == TASKHANDLING_OVERWRITE_FOR_MOVE || errorCode == TASKHANDLING_OVERWRITE_FOR_COPY || errorCode == TASKHANDLING_NAMECLASHMOVE_FOR_MOVE || errorCode == TASKHANDLING_NAMECLASHMOVE_FOR_COPY || errorCode == TASKHANDLING_KEEPERROR_FOR_MOVE || errorCode == TASKHANDLING_KEEPERROR_FOR_COPY || errorCode == TASKHANDLING_RENAME_FOR_MOVE || errorCode == TASKHANDLING_RENAME_FOR_COPY || errorCode == TASKHANDLING_RENAMEMOVE_FOR_MOVE || errorCode == TASKHANDLING_RENAMEMOVE_FOR_COPY ) { rtl::OUString aMsg(RTL_CONSTASCII_USTRINGPARAM( "general error during transfer")); switch( minorCode ) { case FileBase::E_EXIST: ioErrorCode = IOErrorCode_ALREADY_EXISTING; break; case FileBase::E_INVAL: // the format of the parameters was not valid ioErrorCode = IOErrorCode_INVALID_PARAMETER; break; case FileBase::E_NOMEM: // not enough memory for allocating structures ioErrorCode = IOErrorCode_OUT_OF_MEMORY; break; case FileBase::E_ACCES: // Permission denied ioErrorCode = IOErrorCode_ACCESS_DENIED; break; case FileBase::E_PERM: // Operation not permitted ioErrorCode = IOErrorCode_NOT_SUPPORTED; break; case FileBase::E_NAMETOOLONG: // File name too long ioErrorCode = IOErrorCode_NAME_TOO_LONG; break; case FileBase::E_NOENT: // No such file or directory ioErrorCode = IOErrorCode_NOT_EXISTING; aMsg = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( "file/folder does not exist")); break; case FileBase::E_ROFS: // Read-only file system<p> ioErrorCode = IOErrorCode_NOT_EXISTING; break; default: ioErrorCode = IOErrorCode_GENERAL; break; } cancelCommandExecution( ioErrorCode, generateErrorArguments(aUncPath), xEnv, aMsg, xComProc ); } else if( errorCode == TASKHANDLING_NAMECLASH_FOR_COPY || errorCode == TASKHANDLING_NAMECLASH_FOR_MOVE ) { NameClashException excep; excep.Name = getTitle(aUncPath); excep.Classification = InteractionClassification_ERROR; Reference<XInterface> xContext(xComProc,UNO_QUERY); excep.Context = xContext; excep.Message = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "name clash during copy or move")); aAny <<= excep; cancelCommandExecution(aAny,xEnv); } else if( errorCode == TASKHANDLING_NAMECLASHSUPPORT_FOR_MOVE || errorCode == TASKHANDLING_NAMECLASHSUPPORT_FOR_COPY ) { Reference<XInterface> xContext( xComProc,UNO_QUERY); UnsupportedNameClashException excep; excep.NameClash = minorCode; excep.Context = xContext; excep.Message = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "name clash value not supported during copy or move")); aAny <<= excep; cancelCommandExecution(aAny,xEnv); } else { // case TASKHANDLER_NO_ERROR: return; } } } // end namespace fileaccess
22,670
552
<reponame>lygstate/MIEngine #pragma once typedef void (*func4)(); typedef int (*func5)(int, int); int* func6(func4 f4, func5 f5); void func7(); int func8(int x, int y);
73
1,247
<filename>libpharos/delta.hpp // Copyright 2015-2018 <NAME>. See LICENSE file for terms. #ifndef Pharos_Delta_H #define Pharos_Delta_H #include "enums.hpp" namespace pharos { // Our confidence in the correctness of the stack delta. This is a strict ordering from least // confident to most confident. Comparisons of the form (confidence <= DeltaConfident) are // explicitly allowed so take caution. enum GenericConfidence { ConfidenceNone, ConfidenceWrong, ConfidenceGuess, ConfidenceMissing, ConfidenceConfident, ConfidenceUser, ConfidenceCertain, ConfidenceUnspecified }; extern template std::string Enum2Str<GenericConfidence>(GenericConfidence); // A helper function to print negative hexadecimal values. std::string neghex(int x); // StackDelta is basically a glorified struct, but we might want to put some accessors and // convience methods on the confidence and delta members. class StackDelta { public: // The stack delta before the instruction executes. Stack deltas are measured from the value // zero occuring before the first instruction at the entry point of the function. e.g. after // any call has pushed the return address onto the stack, but before any code in this // function has executed. // Because the stack pointer usually has a negative value relative to the start of the // function, and because lots of negative numbers are unpleasant to look at (especially in // hexadecimal), we're going to adopt the same convention that IDA Pro has, which is to // reverse the sign of the delta. Thus a push instruction subtracts 4 from ESP, buts adds 4 // to the delta. Care needs to be taken to correct sign when interacting with parts of the // system that use the real semantics of the architecture. int delta; // This is our confidence in the current stack delta value. It allows us to decide the // confidence derivative values for things like stack memory access, to decide whether we // should try harder to determine a correct answer, and whether we need to repeat previous // analysis in the presence of improved data. GenericConfidence confidence; StackDelta(int d, GenericConfidence c) { delta = d; confidence = c; } StackDelta() { delta = 0; confidence = ConfidenceNone; } void print(std::ostream &o) const { o << neghex(delta) << "(" << Enum2Str(confidence) << ")"; } friend std::ostream& operator<<(std::ostream &o, const StackDelta &sd) { sd.print(o); return o; } }; } // namespace pharos #endif /* Local Variables: */ /* mode: c++ */ /* fill-column: 95 */ /* comment-column: 0 */ /* End: */
742
14,325
package seaweedfs.file; import org.junit.Assert; import org.junit.Test; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.util.Random; public class RandomeAccessFileTest { @Test public void testRandomWriteAndRead() throws IOException { File f = new File(MmapFileTest.dir, "mmap_file.txt"); RandomAccessFile af = new RandomAccessFile(f, "rw"); af.setLength(0); af.close(); Random r = new Random(); int maxLength = 5000; byte[] data = new byte[maxLength]; byte[] readData = new byte[maxLength]; for (int i = 4096; i < maxLength; i++) { RandomAccessFile raf = new RandomAccessFile(f, "rw"); long fileSize = raf.length(); raf.readFully(readData, 0, (int)fileSize); for (int x=0;x<fileSize;x++){ Assert.assertEquals(data[x], readData[x]); } int start = r.nextInt(i); int stop = r.nextInt(i); if (start > stop) { int t = stop; stop = start; start = t; } if (stop > fileSize) { fileSize = stop; raf.setLength(fileSize); } randomize(r, data, start, stop); raf.seek(start); raf.write(data, start, stop-start); raf.close(); } } private static void randomize(Random r, byte[] bytes, int start, int stop) { for (int i = start; i < stop; i++) { int rnd = r.nextInt(); bytes[i] = (byte) rnd; } } }
845
348
{"nom":"Plouรซc-du-Trieux","circ":"5รจme circonscription","dpt":"Cรดtes-d'Armor","inscrits":919,"abs":458,"votants":461,"blancs":12,"nuls":57,"exp":392,"res":[{"nuance":"REM","nom":"<NAME>","voix":257},{"nuance":"UDI","nom":"<NAME>","voix":135}]}
102
4,202
<filename>tests/__init__.py # -*- coding:utf-8 -*- #!/usr/bin/env python """ Date: 2019/12/12 18:16 Desc: """
51
3,102
// RUN: %clang_cc1 -fsyntax-only -std=c++11 %s template <typename T> struct A { // Used to crash when field was named after class. int A = 0; }; A<int> a;
66
648
<gh_stars>100-1000 import torch import torch.nn as nn from mmcv.cnn import ConvModule, kaiming_init from mmcv.runner import _load_checkpoint, load_checkpoint from mmcv.utils import print_log from ...utils import get_root_logger from ..builder import BACKBONES from .resnet3d import ResNet3d try: from mmdet.models import BACKBONES as MMDET_BACKBONES mmdet_imported = True except (ImportError, ModuleNotFoundError): mmdet_imported = False class ResNet3dPathway(ResNet3d): """A pathway of Slowfast based on ResNet3d. Args: *args (arguments): Arguments same as :class:``ResNet3d``. lateral (bool): Determines whether to enable the lateral connection from another pathway. Default: False. speed_ratio (int): Speed ratio indicating the ratio between time dimension of the fast and slow pathway, corresponding to the ``alpha`` in the paper. Default: 8. channel_ratio (int): Reduce the channel number of fast pathway by ``channel_ratio``, corresponding to ``beta`` in the paper. Default: 8. fusion_kernel (int): The kernel size of lateral fusion. Default: 5. **kwargs (keyword arguments): Keywords arguments for ResNet3d. """ def __init__(self, *args, lateral=False, speed_ratio=8, channel_ratio=8, fusion_kernel=5, **kwargs): self.lateral = lateral self.speed_ratio = speed_ratio self.channel_ratio = channel_ratio self.fusion_kernel = fusion_kernel super().__init__(*args, **kwargs) self.inplanes = self.base_channels if self.lateral: self.conv1_lateral = ConvModule( self.inplanes // self.channel_ratio, # https://arxiv.org/abs/1812.03982, the # third type of lateral connection has out_channel: # 2 * \beta * C self.inplanes * 2 // self.channel_ratio, kernel_size=(fusion_kernel, 1, 1), stride=(self.speed_ratio, 1, 1), padding=((fusion_kernel - 1) // 2, 0, 0), bias=False, conv_cfg=self.conv_cfg, norm_cfg=None, act_cfg=None) self.lateral_connections = [] for i in range(len(self.stage_blocks)): planes = self.base_channels * 2**i self.inplanes = planes * self.block.expansion if lateral and i != self.num_stages - 1: # no lateral connection needed in final stage lateral_name = f'layer{(i + 1)}_lateral' setattr( self, lateral_name, ConvModule( self.inplanes // self.channel_ratio, self.inplanes * 2 // self.channel_ratio, kernel_size=(fusion_kernel, 1, 1), stride=(self.speed_ratio, 1, 1), padding=((fusion_kernel - 1) // 2, 0, 0), bias=False, conv_cfg=self.conv_cfg, norm_cfg=None, act_cfg=None)) self.lateral_connections.append(lateral_name) def make_res_layer(self, block, inplanes, planes, blocks, spatial_stride=1, temporal_stride=1, dilation=1, style='pytorch', inflate=1, inflate_style='3x1x1', non_local=0, non_local_cfg=dict(), conv_cfg=None, norm_cfg=None, act_cfg=None, with_cp=False): """Build residual layer for Slowfast. Args: block (nn.Module): Residual module to be built. inplanes (int): Number of channels for the input feature in each block. planes (int): Number of channels for the output feature in each block. blocks (int): Number of residual blocks. spatial_stride (int | Sequence[int]): Spatial strides in residual and conv layers. Default: 1. temporal_stride (int | Sequence[int]): Temporal strides in residual and conv layers. Default: 1. dilation (int): Spacing between kernel elements. Default: 1. style (str): ``pytorch`` or ``caffe``. If set to ``pytorch``, the stride-two layer is the 3x3 conv layer, otherwise the stride-two layer is the first 1x1 conv layer. Default: ``pytorch``. inflate (int | Sequence[int]): Determine whether to inflate for each block. Default: 1. inflate_style (str): ``3x1x1`` or ``3x3x3``. which determines the kernel sizes and padding strides for conv1 and conv2 in each block. Default: ``3x1x1``. non_local (int | Sequence[int]): Determine whether to apply non-local module in the corresponding block of each stages. Default: 0. non_local_cfg (dict): Config for non-local module. Default: ``dict()``. conv_cfg (dict | None): Config for conv layers. Default: None. norm_cfg (dict | None): Config for norm layers. Default: None. act_cfg (dict | None): Config for activate layers. Default: None. with_cp (bool): Use checkpoint or not. Using checkpoint will save some memory while slowing down the training speed. Default: False. Returns: nn.Module: A residual layer for the given config. """ inflate = inflate if not isinstance(inflate, int) else (inflate, ) * blocks non_local = non_local if not isinstance( non_local, int) else (non_local, ) * blocks assert len(inflate) == blocks and len(non_local) == blocks if self.lateral: lateral_inplanes = inplanes * 2 // self.channel_ratio else: lateral_inplanes = 0 if (spatial_stride != 1 or (inplanes + lateral_inplanes) != planes * block.expansion): downsample = ConvModule( inplanes + lateral_inplanes, planes * block.expansion, kernel_size=1, stride=(temporal_stride, spatial_stride, spatial_stride), bias=False, conv_cfg=conv_cfg, norm_cfg=norm_cfg, act_cfg=None) else: downsample = None layers = [] layers.append( block( inplanes + lateral_inplanes, planes, spatial_stride, temporal_stride, dilation, downsample, style=style, inflate=(inflate[0] == 1), inflate_style=inflate_style, non_local=(non_local[0] == 1), non_local_cfg=non_local_cfg, conv_cfg=conv_cfg, norm_cfg=norm_cfg, act_cfg=act_cfg, with_cp=with_cp)) inplanes = planes * block.expansion for i in range(1, blocks): layers.append( block( inplanes, planes, 1, 1, dilation, style=style, inflate=(inflate[i] == 1), inflate_style=inflate_style, non_local=(non_local[i] == 1), non_local_cfg=non_local_cfg, conv_cfg=conv_cfg, norm_cfg=norm_cfg, act_cfg=act_cfg, with_cp=with_cp)) return nn.Sequential(*layers) def inflate_weights(self, logger): """Inflate the resnet2d parameters to resnet3d pathway. The differences between resnet3d and resnet2d mainly lie in an extra axis of conv kernel. To utilize the pretrained parameters in 2d model, the weight of conv2d models should be inflated to fit in the shapes of the 3d counterpart. For pathway the ``lateral_connection`` part should not be inflated from 2d weights. Args: logger (logging.Logger): The logger used to print debugging infomation. """ state_dict_r2d = _load_checkpoint(self.pretrained) if 'state_dict' in state_dict_r2d: state_dict_r2d = state_dict_r2d['state_dict'] inflated_param_names = [] for name, module in self.named_modules(): if 'lateral' in name: continue if isinstance(module, ConvModule): # we use a ConvModule to wrap conv+bn+relu layers, thus the # name mapping is needed if 'downsample' in name: # layer{X}.{Y}.downsample.conv->layer{X}.{Y}.downsample.0 original_conv_name = name + '.0' # layer{X}.{Y}.downsample.bn->layer{X}.{Y}.downsample.1 original_bn_name = name + '.1' else: # layer{X}.{Y}.conv{n}.conv->layer{X}.{Y}.conv{n} original_conv_name = name # layer{X}.{Y}.conv{n}.bn->layer{X}.{Y}.bn{n} original_bn_name = name.replace('conv', 'bn') if original_conv_name + '.weight' not in state_dict_r2d: logger.warning(f'Module not exist in the state_dict_r2d' f': {original_conv_name}') else: self._inflate_conv_params(module.conv, state_dict_r2d, original_conv_name, inflated_param_names) if original_bn_name + '.weight' not in state_dict_r2d: logger.warning(f'Module not exist in the state_dict_r2d' f': {original_bn_name}') else: self._inflate_bn_params(module.bn, state_dict_r2d, original_bn_name, inflated_param_names) # check if any parameters in the 2d checkpoint are not loaded remaining_names = set( state_dict_r2d.keys()) - set(inflated_param_names) if remaining_names: logger.info(f'These parameters in the 2d checkpoint are not loaded' f': {remaining_names}') def _inflate_conv_params(self, conv3d, state_dict_2d, module_name_2d, inflated_param_names): """Inflate a conv module from 2d to 3d. The differences of conv modules betweene 2d and 3d in Pathway mainly lie in the inplanes due to lateral connections. To fit the shapes of the lateral connection counterpart, it will expand parameters by concatting conv2d parameters and extra zero paddings. Args: conv3d (nn.Module): The destination conv3d module. state_dict_2d (OrderedDict): The state dict of pretrained 2d model. module_name_2d (str): The name of corresponding conv module in the 2d model. inflated_param_names (list[str]): List of parameters that have been inflated. """ weight_2d_name = module_name_2d + '.weight' conv2d_weight = state_dict_2d[weight_2d_name] old_shape = conv2d_weight.shape new_shape = conv3d.weight.data.shape kernel_t = new_shape[2] if new_shape[1] != old_shape[1]: # Inplanes may be different due to lateral connections new_channels = new_shape[1] - old_shape[1] pad_shape = old_shape pad_shape = pad_shape[:1] + (new_channels, ) + pad_shape[2:] # Expand parameters by concat extra channels conv2d_weight = torch.cat( (conv2d_weight, torch.zeros(pad_shape).type_as(conv2d_weight).to( conv2d_weight.device)), dim=1) new_weight = conv2d_weight.data.unsqueeze(2).expand_as( conv3d.weight) / kernel_t conv3d.weight.data.copy_(new_weight) inflated_param_names.append(weight_2d_name) if getattr(conv3d, 'bias') is not None: bias_2d_name = module_name_2d + '.bias' conv3d.bias.data.copy_(state_dict_2d[bias_2d_name]) inflated_param_names.append(bias_2d_name) def _freeze_stages(self): """Prevent all the parameters from being optimized before `self.frozen_stages`.""" if self.frozen_stages >= 0: self.conv1.eval() for param in self.conv1.parameters(): param.requires_grad = False for i in range(1, self.frozen_stages + 1): m = getattr(self, f'layer{i}') m.eval() for param in m.parameters(): param.requires_grad = False if i != len(self.res_layers) and self.lateral: # No fusion needed in the final stage lateral_name = self.lateral_connections[i - 1] conv_lateral = getattr(self, lateral_name) conv_lateral.eval() for param in conv_lateral.parameters(): param.requires_grad = False def init_weights(self, pretrained=None): """Initiate the parameters either from existing checkpoint or from scratch.""" if pretrained: self.pretrained = pretrained # Override the init_weights of i3d super().init_weights() for module_name in self.lateral_connections: layer = getattr(self, module_name) for m in layer.modules(): if isinstance(m, (nn.Conv3d, nn.Conv2d)): kaiming_init(m) pathway_cfg = { 'resnet3d': ResNet3dPathway, # TODO: BNInceptionPathway } def build_pathway(cfg, *args, **kwargs): """Build pathway. Args: cfg (None or dict): cfg should contain: - type (str): identify conv layer type. Returns: nn.Module: Created pathway. """ if not (isinstance(cfg, dict) and 'type' in cfg): raise TypeError('cfg must be a dict containing the key "type"') cfg_ = cfg.copy() pathway_type = cfg_.pop('type') if pathway_type not in pathway_cfg: raise KeyError(f'Unrecognized pathway type {pathway_type}') pathway_cls = pathway_cfg[pathway_type] pathway = pathway_cls(*args, **kwargs, **cfg_) return pathway @BACKBONES.register_module() class ResNet3dSlowFast(nn.Module): """Slowfast backbone. This module is proposed in `SlowFast Networks for Video Recognition <https://arxiv.org/abs/1812.03982>`_ Args: pretrained (str): The file path to a pretrained model. resample_rate (int): A large temporal stride ``resample_rate`` on input frames. The actual resample rate is calculated by multipling the ``interval`` in ``SampleFrames`` in the pipeline with ``resample_rate``, equivalent to the :math:`\\tau` in the paper, i.e. it processes only one out of ``resample_rate * interval`` frames. Default: 8. speed_ratio (int): Speed ratio indicating the ratio between time dimension of the fast and slow pathway, corresponding to the :math:`\\alpha` in the paper. Default: 8. channel_ratio (int): Reduce the channel number of fast pathway by ``channel_ratio``, corresponding to :math:`\\beta` in the paper. Default: 8. slow_pathway (dict): Configuration of slow branch, should contain necessary arguments for building the specific type of pathway and: type (str): type of backbone the pathway bases on. lateral (bool): determine whether to build lateral connection for the pathway.Default: .. code-block:: Python dict(type='ResNetPathway', lateral=True, depth=50, pretrained=None, conv1_kernel=(1, 7, 7), dilations=(1, 1, 1, 1), conv1_stride_t=1, pool1_stride_t=1, inflate=(0, 0, 1, 1)) fast_pathway (dict): Configuration of fast branch, similar to `slow_pathway`. Default: .. code-block:: Python dict(type='ResNetPathway', lateral=False, depth=50, pretrained=None, base_channels=8, conv1_kernel=(5, 7, 7), conv1_stride_t=1, pool1_stride_t=1) """ def __init__(self, pretrained, resample_rate=8, speed_ratio=8, channel_ratio=8, slow_pathway=dict( type='resnet3d', depth=50, pretrained=None, lateral=True, conv1_kernel=(1, 7, 7), dilations=(1, 1, 1, 1), conv1_stride_t=1, pool1_stride_t=1, inflate=(0, 0, 1, 1)), fast_pathway=dict( type='resnet3d', depth=50, pretrained=None, lateral=False, base_channels=8, conv1_kernel=(5, 7, 7), conv1_stride_t=1, pool1_stride_t=1)): super().__init__() self.pretrained = pretrained self.resample_rate = resample_rate self.speed_ratio = speed_ratio self.channel_ratio = channel_ratio if slow_pathway['lateral']: slow_pathway['speed_ratio'] = speed_ratio slow_pathway['channel_ratio'] = channel_ratio self.slow_path = build_pathway(slow_pathway) self.fast_path = build_pathway(fast_pathway) def init_weights(self, pretrained=None): """Initiate the parameters either from existing checkpoint or from scratch.""" if pretrained: self.pretrained = pretrained if isinstance(self.pretrained, str): logger = get_root_logger() msg = f'load model from: {self.pretrained}' print_log(msg, logger=logger) # Directly load 3D model. load_checkpoint(self, self.pretrained, strict=True, logger=logger) elif self.pretrained is None: # Init two branch seperately. self.fast_path.init_weights() self.slow_path.init_weights() else: raise TypeError('pretrained must be a str or None') def forward(self, x): """Defines the computation performed at every call. Args: x (torch.Tensor): The input data. Returns: tuple[torch.Tensor]: The feature of the input samples extracted by the backbone. """ x_slow = nn.functional.interpolate( x, mode='nearest', scale_factor=(1.0 / self.resample_rate, 1.0, 1.0)) x_slow = self.slow_path.conv1(x_slow) x_slow = self.slow_path.maxpool(x_slow) x_fast = nn.functional.interpolate( x, mode='nearest', scale_factor=(1.0 / (self.resample_rate // self.speed_ratio), 1.0, 1.0)) x_fast = self.fast_path.conv1(x_fast) x_fast = self.fast_path.maxpool(x_fast) if self.slow_path.lateral: x_fast_lateral = self.slow_path.conv1_lateral(x_fast) x_slow = torch.cat((x_slow, x_fast_lateral), dim=1) for i, layer_name in enumerate(self.slow_path.res_layers): res_layer = getattr(self.slow_path, layer_name) x_slow = res_layer(x_slow) res_layer_fast = getattr(self.fast_path, layer_name) x_fast = res_layer_fast(x_fast) if (i != len(self.slow_path.res_layers) - 1 and self.slow_path.lateral): # No fusion needed in the final stage lateral_name = self.slow_path.lateral_connections[i] conv_lateral = getattr(self.slow_path, lateral_name) x_fast_lateral = conv_lateral(x_fast) x_slow = torch.cat((x_slow, x_fast_lateral), dim=1) out = (x_slow, x_fast) return out if mmdet_imported: MMDET_BACKBONES.register_module()(ResNet3dSlowFast)
10,809
538
<reponame>mrarronz/react-native-blog-examples package com.datatransfer; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class TestActivity extends Activity { private Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test); button = (Button) findViewById(R.id.test_button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); MainApplication.getTransferPackage().transferModule.sendEvent("CustomEventName"); } }); } }
303
1,004
<reponame>d6t/d6tflow import d6tflow import pandas as pd # define 2 tasks that load raw data class Task1(d6tflow.tasks.TaskCache): def run(self): df = pd.DataFrame({'a': range(3)}) self.save(df) # quickly save dataframe class Task2(Task1): pass # define another task that depends on data from task1 and task2 @d6tflow.requires({'input1': Task1, 'input2': Task2}) class Task3(d6tflow.tasks.TaskCache): multiplier = d6tflow.IntParameter(default=2) def run(self): df1 = self.input()['input1'].load() # quickly load input data df2 = self.input()['input2'].load() # quickly load input data df = df1.join(df2, lsuffix='1', rsuffix='2') df['b'] = df['a1'] * self.multiplier # use task parameter self.save(df) # Execute task including all its dependencies flow = d6tflow.Workflow(Task3) flow.run() ''' * 3 ran successfully: - 1 Task1() - 1 Task2() - 1 Task3(multiplier=2) ''' # quickly load output data. Task1().outputLoad() also works flow.outputLoad() ''' a1 a2 b 0 0 0 0 1 1 1 2 2 2 2 4 ''' # Intelligently rerun workflow after changing parameters flow2 = d6tflow.Workflow(Task3, {'multiplier': 3}) flow2.preview() ''' โ””โ”€--[Task3-{'multiplier': '3'} (PENDING)] => this changed and needs to run |--[Task1-{} (COMPLETE)] => this doesn't change and doesn't need to rerun โ””โ”€--[Task2-{} (COMPLETE)] => this doesn't change and doesn't need to rerun '''
603
928
# This test verifies that __name__ == "__main__" works properly in Python Loader if __name__ == "__main__": print('Test: 1234567890abcd')
47
2,151
<reponame>Keneral/aframeworks<filename>opt/net/wifi/service/java/com/android/server/wifi/hotspot2/omadm/ManagementTreeRoot.java<gh_stars>1000+ /* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.server.wifi.hotspot2.omadm; import java.util.Map; /** * A specialized OMAConstructed OMA-DM node used as the MgmtTree root node in Passpoint * management trees. */ public class ManagementTreeRoot extends OMAConstructed { private final String mDtdRev; public ManagementTreeRoot(XMLNode node, String dtdRev) { super(null, MOTree.MgmtTreeTag, null, new MultiValueMap<OMANode>(), node.getTextualAttributes()); mDtdRev = dtdRev; } public ManagementTreeRoot(String dtdRev) { super(null, MOTree.MgmtTreeTag, null, "xmlns", OMAConstants.SyncML); mDtdRev = dtdRev; } @Override public void toXml(StringBuilder sb) { sb.append('<').append(MOTree.MgmtTreeTag); if (getAttributes() != null && !getAttributes().isEmpty()) { for (Map.Entry<String, String> avp : getAttributes().entrySet()) { sb.append(' ').append(avp.getKey()).append("=\"") .append(escape(avp.getValue())).append('"'); } } sb.append(">\n"); sb.append('<').append(OMAConstants.SyncMLVersionTag) .append('>').append(mDtdRev) .append("</").append(OMAConstants.SyncMLVersionTag).append(">\n"); for (OMANode child : getChildren()) { child.toXml(sb); } sb.append("</").append(MOTree.MgmtTreeTag).append(">\n"); } }
878
337
#pragma once #include <openvr_driver.h> class VRWatchdogProvider : public vr::IVRWatchdogProvider { /** initializes the driver in watchdog mode. */ virtual vr::EVRInitError Init(vr::IVRDriverContext *pDriverContext) { VR_INIT_WATCHDOG_DRIVER_CONTEXT(pDriverContext); return vr::VRInitError_None; } /** cleans up the driver right before it is unloaded */ virtual void Cleanup() { VR_CLEANUP_WATCHDOG_DRIVER_CONTEXT() } };
160
1,273
<reponame>sunboy0523/gatk<gh_stars>1000+ package org.broadinstitute.hellbender.tools.htsgetreader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Base64; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonRootName; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.broadinstitute.hellbender.exceptions.UserException; import org.broadinstitute.hellbender.utils.HttpUtils; import org.broadinstitute.hellbender.utils.io.IOUtils; /** * Class allowing deserialization from json htsget response */ @JsonRootName(value = "htsget") public class HtsgetResponse { public static class Block { @JsonProperty("url") private URI uri; @JsonProperty("headers") @JsonDeserialize(as = HashMap.class, keyAs = String.class, contentAs = String.class) private Map<String, String> headers; @JsonProperty("class") private HtsgetClass dataClass; public URI getUri() { return this.uri; } public Map<String, String> getHeaders() { return Collections.unmodifiableMap(this.headers); } public HtsgetClass getDataClass() { return this.dataClass; } /** * Returns InputStream containing data of a single block from the htsget response * * Large blocks (those behind an http(s) URI) are first saved * to a temp file that is deleted upon program exit */ public InputStream getData() { switch (this.getUri().getScheme()) { case "http": case "https": final HttpGet get = new HttpGet(this.getUri()); this.getHeaders().forEach(get::addHeader); try (final CloseableHttpResponse resp = HttpUtils.getClient().execute(get)) { final Path outputFile = IOUtils.createTempPath("htsget-temp", ""); try (final OutputStream ostream = Files.newOutputStream(outputFile); final InputStream istream = resp.getEntity().getContent()) { org.apache.commons.io.IOUtils.copy(istream, ostream); } catch (final IOException e) { throw new UserException("Could not write to temp file", e); } return Files.newInputStream(outputFile); } catch (final IOException e) { throw new UserException("Could not retrieve data from block", e); } case "data": final String dataUri = this.getUri().toString(); if (!dataUri.matches("^data:.*;base64,.*")) { throw new UserException("data URI must be base64 encoded: " + dataUri); } return new ByteArrayInputStream( Base64.getDecoder().decode(dataUri.replaceFirst("^data:.*;base64,", ""))); default: throw new UserException("Unrecognized URI scheme in data block: " + this.getUri().getScheme()); } } } @JsonProperty("format") private HtsgetFormat format; @JsonProperty("urls") @JsonDeserialize(as = ArrayList.class, contentAs = Block.class) private List<Block> blocks; @JsonProperty("md5") private String md5; public HtsgetFormat getFormat() { return this.format; } public List<Block> getBlocks() { return Collections.unmodifiableList(this.blocks); } public String getMd5() { return this.md5; } }
1,848
323
<filename>lib/ros_lib/moveit_msgs/GetMotionSequence.h #ifndef _ROS_SERVICE_GetMotionSequence_h #define _ROS_SERVICE_GetMotionSequence_h #include <stdint.h> #include <string.h> #include <stdlib.h> #include "ros/msg.h" #include "moveit_msgs/MotionSequenceRequest.h" #include "moveit_msgs/MotionSequenceResponse.h" namespace moveit_msgs { static const char GETMOTIONSEQUENCE[] = "moveit_msgs/GetMotionSequence"; class GetMotionSequenceRequest : public ros::Msg { public: typedef moveit_msgs::MotionSequenceRequest _request_type; _request_type request; GetMotionSequenceRequest(): request() { } virtual int serialize(unsigned char *outbuffer) const { int offset = 0; offset += this->request.serialize(outbuffer + offset); return offset; } virtual int deserialize(unsigned char *inbuffer) { int offset = 0; offset += this->request.deserialize(inbuffer + offset); return offset; } const char * getType(){ return GETMOTIONSEQUENCE; }; const char * getMD5(){ return "bae3996834a2cd1013b32c29e6a79b4e"; }; }; class GetMotionSequenceResponse : public ros::Msg { public: typedef moveit_msgs::MotionSequenceResponse _response_type; _response_type response; GetMotionSequenceResponse(): response() { } virtual int serialize(unsigned char *outbuffer) const { int offset = 0; offset += this->response.serialize(outbuffer + offset); return offset; } virtual int deserialize(unsigned char *inbuffer) { int offset = 0; offset += this->response.deserialize(inbuffer + offset); return offset; } const char * getType(){ return GETMOTIONSEQUENCE; }; const char * getMD5(){ return "039cee462ada3f0feb5f4e2e12baefae"; }; }; class GetMotionSequence { public: typedef GetMotionSequenceRequest Request; typedef GetMotionSequenceResponse Response; }; } #endif
766
1,701
package com.google.maps.android; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** Helper class for obtaining information about an Android app's signing certificate. */ public class CertificateHelper { /** * Obtains the SHA-1 fingerprint of the certificate used to sign the app. * * @param context a Context * @return the SHA-1 fingerprint if obtainable, otherwise, <code>null</code> */ @Nullable public static String getSigningCertificateSha1Fingerprint(@NotNull Context context) { final PackageManager pm = context.getPackageManager(); if (pm == null) { return null; } // PackageManage.GET_SIGNATURES == 64 PackageInfo packageInfo = pm.getPackageInfo(context.getPackageName(), 64); if (packageInfo == null) { return null; } Object signingSignature = packageInfo.signingSignature(); if (signingSignature == null) { return null; } try { MessageDigest md = MessageDigest.getInstance("SHA-1"); Class<?> signatureClass = Class.forName("android.content.pm.Signature"); Method toByteArrayMethod = signatureClass.getMethod("toByteArray"); byte[] byteArray = (byte[]) toByteArrayMethod.invoke(signingSignature); byte[] digest = md.digest(byteArray); return bytesToHex(digest); } catch (NoSuchAlgorithmException | ClassNotFoundException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { return null; } } private static String bytesToHex(byte[] byteArray) { final StringBuilder sb = new StringBuilder(); for (byte b : byteArray) { sb.append(String.format("%02X", b)); } return sb.toString(); } }
654
9,156
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.pulsar.client.impl.schema.generic; import lombok.extern.slf4j.Slf4j; import org.apache.pulsar.client.api.Schema; import org.apache.pulsar.client.api.schema.GenericRecord; import org.apache.pulsar.client.api.schema.GenericSchema; import org.apache.pulsar.client.impl.schema.AutoConsumeSchema; import org.apache.pulsar.common.schema.LongSchemaVersion; import org.testng.annotations.Test; import java.util.concurrent.CompletableFuture; import static java.nio.charset.StandardCharsets.UTF_8; import static org.mockito.Mockito.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; /** * Unit testing AbstractGenericSchema for non-avroBasedGenericSchema. */ @Slf4j public class AbstractGenericSchemaTest { @Test public void testGenericProtobufNativeSchema() { Schema<org.apache.pulsar.client.schema.proto.Test.TestMessage> encodeSchema = Schema.PROTOBUF_NATIVE(org.apache.pulsar.client.schema.proto.Test.TestMessage.class); GenericSchema decodeSchema = GenericProtobufNativeSchema.of(encodeSchema.getSchemaInfo()); testEncodeAndDecodeGenericRecord(encodeSchema, decodeSchema); } @Test public void testAutoProtobufNativeSchema() { // configure the schema info provider MultiVersionSchemaInfoProvider multiVersionSchemaInfoProvider = mock(MultiVersionSchemaInfoProvider.class); GenericSchema genericProtobufNativeSchema = GenericProtobufNativeSchema.of(Schema.PROTOBUF_NATIVE(org.apache.pulsar.client.schema.proto.Test.TestMessage.class).getSchemaInfo()); when(multiVersionSchemaInfoProvider.getSchemaByVersion(any(byte[].class))) .thenReturn(CompletableFuture.completedFuture(genericProtobufNativeSchema.getSchemaInfo())); // configure encode schema Schema<org.apache.pulsar.client.schema.proto.Test.TestMessage> encodeSchema = Schema.PROTOBUF_NATIVE(org.apache.pulsar.client.schema.proto.Test.TestMessage.class); // configure decode schema AutoConsumeSchema decodeSchema = new AutoConsumeSchema(); decodeSchema.configureSchemaInfo("test-topic", "topic", encodeSchema.getSchemaInfo()); decodeSchema.setSchemaInfoProvider(multiVersionSchemaInfoProvider); testEncodeAndDecodeGenericRecord(encodeSchema, decodeSchema); } private void testEncodeAndDecodeGenericRecord(Schema<org.apache.pulsar.client.schema.proto.Test.TestMessage> encodeSchema, Schema<GenericRecord> decodeSchema) { int numRecords = 10; for (int i = 0; i < numRecords; i++) { org.apache.pulsar.client.schema.proto.Test.TestMessage testMessage = newTestMessage(i); byte[] data = encodeSchema.encode(testMessage); log.info("Decoding : {}", new String(data, UTF_8)); GenericRecord record; if (decodeSchema instanceof AutoConsumeSchema) { record = decodeSchema.decode(data, new LongSchemaVersion(0L).bytes()); } else { record = decodeSchema.decode(data); } verifyTestMessageRecord(record, i); } } private static org.apache.pulsar.client.schema.proto.Test.TestMessage newTestMessage(int i) { return org.apache.pulsar.client.schema.proto.Test.TestMessage.newBuilder().setStringField("field-value-" + i) .setIntField(i).build(); } private static void verifyTestMessageRecord(GenericRecord record, int i) { Object stringField = record.getField("stringField"); assertEquals("field-value-" + i, stringField); Object intField = record.getField("intField"); assertEquals(+i, intField); } }
1,687
468
<filename>OpenGLDLL/GLFunctions/Misc/EXT_framebuffer_blit_Include.h #define GLI_INCLUDE_EXT_FRAMEBUFFER_BLIT void glBlitFramebufferEXT(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum[Main] filter);
118
343
from mayan.apps.views.forms import DetailForm from .models import Cache, CachePartition class CacheDetailForm(DetailForm): class Meta: fields = ('defined_storage_name',) model = Cache class CachePartitionDetailForm(DetailForm): class Meta: fields = ('cache', 'name') model = CachePartition
122
501
#!/usr/bin/env python # Copyright 2014-2018 The PySCF Developers. 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. import unittest from functools import reduce import numpy from pyscf import gto from pyscf import scf from pyscf.lo import nao mol = gto.Mole() mol.verbose = 0 mol.output = None mol.atom = ''' O 0. 0. 0 1 0. -0.757 0.587 1 0. 0.757 0.587''' mol.basis = 'cc-pvdz' mol.build() mf = scf.RHF(mol) mf.conv_tol = 1e-14 mf.scf() mol1 = mol.copy() mol1.cart = True mf1 = scf.RHF(mol1).set(conv_tol=1e-14).run() class KnowValues(unittest.TestCase): def test_pre_nao(self): c = nao.prenao(mol, mf.make_rdm1()) self.assertAlmostEqual(numpy.linalg.norm(c), 5.7742626195362039, 9) self.assertAlmostEqual(abs(c).sum(), 33.214804163888289, 6) c = nao.prenao(mol1, mf1.make_rdm1()) self.assertAlmostEqual(numpy.linalg.norm(c), 5.5434134741828105, 9) self.assertAlmostEqual(abs(c).sum(), 31.999905597187052, 6) def test_nao(self): c = nao.nao(mol, mf) s = mf.get_ovlp() self.assertTrue(numpy.allclose(reduce(numpy.dot, (c.T, s, c)), numpy.eye(s.shape[0]))) self.assertAlmostEqual(numpy.linalg.norm(c), 8.982385484322208, 9) self.assertAlmostEqual(abs(c).sum(), 90.443872916389637, 6) c = nao.nao(mol1, mf1) s = mf1.get_ovlp() self.assertTrue(numpy.allclose(reduce(numpy.dot, (c.T, s, c)), numpy.eye(s.shape[0]))) self.assertAlmostEqual(numpy.linalg.norm(c), 9.4629575662640129, 9) self.assertAlmostEqual(abs(c).sum(), 100.24554485355642, 6) if __name__ == "__main__": print("Test orth") unittest.main()
1,068
6,989
<gh_stars>1000+ #include "par_log.h"
18
3,366
<gh_stars>1000+ #include"query.h" #include<ostream> using std::ostream; ostream& operator<<(ostream &os, const Query &query) { return os << query.rep(); }
62
439
<reponame>JananiPalanisamy/java { "blurb": "Write a function to determine if a list is a sublist of another list.", "authors": [ "stkent" ], "contributors": [ "aadityakulkarni", "FridaTveit", "hgvanpariya", "jmrunkle", "jtigger", "kytrinyx", "lemoncurry", "mirkoperillo", "morrme", "msomji", "muzimuzhi", "redshirt4", "SleeplessByte", "Smarticles101", "sshine", "vivshaw", "Zaldrick" ], "files": { "solution": [ "src/main/java/RelationshipComputer.java" ], "test": [ "src/test/java/RelationshipComputerTest.java" ], "example": [ ".meta/src/reference/java/RelationshipComputer.java" ] } }
346
507
# terrascript/resource/brightbox.py # Automatically generated by tools/makecode.py (24-Sep-2021 15:13:43 UTC) # # For imports without namespace, e.g. # # >>> import terrascript.resource.brightbox # # instead of # # >>> import terrascript.resource.brightbox.brightbox # # This is only available for 'official' and 'partner' providers. from terrascript.resource.brightbox.brightbox import *
123
372
<reponame>kbore/pbis-open /* * Copyright ยฉ BeyondTrust Software 2004 - 2019 * 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. * * BEYONDTRUST MAKES THIS SOFTWARE AVAILABLE UNDER OTHER LICENSING TERMS AS * WELL. IF YOU HAVE ENTERED INTO A SEPARATE LICENSE AGREEMENT WITH * BEYONDTRUST, THEN YOU MAY ELECT TO USE THE SOFTWARE UNDER THE TERMS OF THAT * SOFTWARE LICENSE AGREEMENT INSTEAD OF THE TERMS OF THE APACHE LICENSE, * NOTWITHSTANDING THE ABOVE NOTICE. IF YOU HAVE QUESTIONS, OR WISH TO REQUEST * A COPY OF THE ALTERNATE LICENSING TERMS OFFERED BY BEYONDTRUST, PLEASE CONTACT * BEYONDTRUST AT beyondtrust.com/contact */ /* * Module Name: * * session.c * * Abstract: * * Session management API * Primary entry points * * Authors: <NAME> (<EMAIL>) * */ #include "util-private.h" #include "session-private.h" #include "mt19937ar.h" #include <lwmsg/time.h> #include <stddef.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <time.h> #include <unistd.h> #include <string.h> #include <stdio.h> void lwmsg_session_id_to_string( const LWMsgSessionID* id, LWMsgSessionString buffer ) { sprintf(buffer, "%.2x%.2x%.2x%.2x%.2x%.2x%.2x%.2x-%.2x%.2x%.2x%.2x%.2x%.2x%.2x%.2x", (unsigned int) id->connect_id.bytes[0], (unsigned int) id->connect_id.bytes[1], (unsigned int) id->connect_id.bytes[2], (unsigned int) id->connect_id.bytes[3], (unsigned int) id->connect_id.bytes[4], (unsigned int) id->connect_id.bytes[5], (unsigned int) id->connect_id.bytes[6], (unsigned int) id->connect_id.bytes[7], (unsigned int) id->accept_id.bytes[0], (unsigned int) id->accept_id.bytes[1], (unsigned int) id->accept_id.bytes[2], (unsigned int) id->accept_id.bytes[3], (unsigned int) id->accept_id.bytes[4], (unsigned int) id->accept_id.bytes[5], (unsigned int) id->accept_id.bytes[6], (unsigned int) id->accept_id.bytes[7]); } void lwmsg_session_generate_cookie( LWMsgSessionCookie* cookie ) { mt m; uint32_t seed[3]; uint32_t s; int i; LWMsgTime now; lwmsg_time_now(&now); /* Add in 32 bits of data from the address of the cookie */ seed[0] = (uint32_t) (size_t) cookie; /* Add in 32 bits of data from the current pid */ seed[1] = (uint32_t) getpid(); /* Add in 32 bits of data from the current time */ seed[2] = (uint32_t) now.microseconds; mt_init_by_array(&m, seed, sizeof(seed) / sizeof(*seed)); for (i = 0; i < sizeof(cookie->bytes); i += sizeof(s)) { s = mt_genrand_int32(&m); memcpy(cookie->bytes + i, &s, sizeof(s)); } } void lwmsg_session_release( LWMsgSession* session ) { if (session && session->sclass->release) { session->sclass->release(session); } } size_t lwmsg_session_get_assoc_count( LWMsgSession* session ) { return session->sclass->get_assoc_count(session); } size_t lwmsg_session_get_handle_count( LWMsgSession* session ) { return session->sclass->get_handle_count(session); } LWMsgStatus lwmsg_session_register_handle( LWMsgSession* session, const char* typename, void* data, LWMsgHandleCleanupFunction cleanup, LWMsgHandle** handle ) { return session->sclass->register_handle_local( session, typename, data, cleanup, handle); } void lwmsg_session_retain_handle( LWMsgSession* session, LWMsgHandle* handle ) { session->sclass->retain_handle(session, handle); } void lwmsg_session_release_handle( LWMsgSession* session, LWMsgHandle* handle ) { session->sclass->release_handle(session, handle); } LWMsgStatus lwmsg_session_unregister_handle( LWMsgSession* session, LWMsgHandle* handle ) { return session->sclass->unregister_handle(session, handle); } LWMsgStatus lwmsg_session_get_handle_data( LWMsgSession* session, LWMsgHandle* handle, void** data ) { return session->sclass->get_handle_data(session, handle, data); } LWMsgStatus lwmsg_session_get_handle_location( LWMsgSession* session, LWMsgHandle* handle, LWMsgHandleType* location ) { LWMsgStatus status = LWMSG_STATUS_SUCCESS; status = session->sclass->resolve_handle_to_id( session, handle, NULL, location, NULL); return status; } void* lwmsg_session_get_data( LWMsgSession* session ) { return session->sclass->get_data(session); } LWMsgSecurityToken* lwmsg_session_get_peer_security_token( LWMsgSession* session ) { return session->sclass->get_peer_security_token(session); } LWMsgStatus lwmsg_session_acquire_call( LWMsgSession* session, LWMsgCall** call ) { return session->sclass->acquire_call(session, call); } const LWMsgSessionID* lwmsg_session_get_id( LWMsgSession* session ) { return session->sclass->get_id(session); }
2,355
775
<reponame>Isaac-DeFrain/rchain /* Mode: -*- C++ -*- */ // vim: set ai ts=4 sw=4 expandtab /* @BC * Copyright (c) 1993 * by Microelectronics and Computer Technology Corporation (MCC) * All Rights Reserved * * Permission to use, copy, modify, and distribute this software and its * documentation for any purpose and without fee is hereby granted, * provided that this notice be retained unaltered, and that the name of * MCC and its shareholders and participants shall not be used in * advertising or publicity pertaining to distribution of the software * without specific written prior permission. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #if !defined(_RBL_Reader_h) #define _RBL_Reader_h 1 #include "rosette.h" #include "BinaryOb.h" #include "ObStk.h" #define OPTIMIZE_ATOMS class ReadMacro; class ReaderFrame; class ReadTable; class FrameStk; class Reader; class FrameStk { int topframe; int nexttop; char* stk; int stksize; FrameStk(); ~FrameStk(); void* alloc(int); int link(int); ReaderFrame* top(); void pop(); int empty(); void reset(); friend class Reader; }; enum ReaderMode { START, CONTINUE, STOP, #if defined(OPTIMIZE_ATOMS) GROK_ATOM #endif }; #undef ftop class Reader : public BinaryOb { STD_DECLS(Reader); protected: char* buf; int bufsize; int bufp; char errorEncountered; enum { NOT_WAITING, WAITING_FOR_EXPR, WAITING_FOR_CHAR } waitingOnIO; uint16_t filler_up_please; FrameStk fstk; ObStk ostk; Reader(ReadTable*, FILE*); Ob* resumeExpr(); Ob* resumeCh(); Ob* suspendReader(); Ob* finish(Ob*); void growBuffer(); ReaderMode acceptEscChar(int, int); public: virtual ~Reader(); static Reader* create(FILE*); ReadTable* rt; ReaderMode mode; FILE* file; int digitSeen; void buffer(int); void resetBuffer(); char* finalizeBuffer(); Ob* finalizeAtom(); Ob* readExpr(); Ob* readCh(); Ob* resume(); Ob* error(const char*, ...); void resetState(); void opush(Ob*); Ob*& otop(int); Ob* opop(); void odel(int); void* falloc(int); int flink(int); ReaderFrame* ftop(); void fpop(); ReaderMode accept(int, int = false); ReaderMode receiveOb(Ob*); ReaderMode receiveChar(int); ReaderMode receiveTerminator(int); ReaderMode receiveDot(int); virtual Ob* cloneTo(Ob*, Ob*); virtual int traversePtrs(PSOb__PSOb); virtual int traversePtrs(SI__PSOb); virtual void traversePtrs(V__PSOb); }; extern Reader* StdinReader; #endif
1,088
348
{"nom":"Sonnac-sur-l'Hers","circ":"3รจme circonscription","dpt":"Aude","inscrits":120,"abs":49,"votants":71,"blancs":9,"nuls":3,"exp":59,"res":[{"nuance":"REM","nom":"<NAME>","voix":37},{"nuance":"SOC","nom":"<NAME>","voix":22}]}
96
676
<gh_stars>100-1000 package com.alorma.github.presenter.repos; import com.alorma.github.presenter.BaseRxPresenter; import com.alorma.github.presenter.View; import java.util.List; import core.datasource.CacheDataSource; import core.datasource.CloudDataSource; import core.repositories.Repo; import core.repository.GenericRepository; import rx.Scheduler; public class UserRepositoriesPresenter extends BaseRxPresenter<String, List<Repo>, View<List<Repo>>> { public UserRepositoriesPresenter( Scheduler mainScheduler, Scheduler ioScheduler, GenericRepository<String, List<Repo>> repository) { super(mainScheduler, ioScheduler, repository); } }
246
375
{ "name": "obs-websocket-js", "version": "4.0.3", "description": "OBS Websocket API in Javascript, consumes @Palakis/obs-websocket", "author": "<NAME> (haganbmj)", "license": "MIT", "repository": "obs-websocket-community-projects/obs-websocket-js", "repoUrl": "https://github.com/obs-websocket-community-projects/obs-websocket-js", "keywords": [ "obs", "studio", "websocket", "node", "node.js" ], "main": "dist/index.js", "browser": "browser-dist/index.js", "types": "dist/index.d.ts", "files": [ "dist", "browser-dist" ], "scripts": { "build": "npm-run-all build:*", "build:obs-types": "cross-env-shell TS_NODE_PROJECT=tsconfig.json \"node $NODE_DEBUG_OPTION -r ts-node/register scripts/build-types-v2.ts\"", "postbuild:obs-types": "npm run lint", "build:ts": "rimraf dist && tsc", "build:web": "rimraf browser-dist && webpack", "watch": "webpack --watch", "test": "npm-run-all test:*", "test:static": "npm run lint", "test:ava": "npm run ava", "test:types": "dtslint types", "report": "nyc report --reporter=text-lcov", "node-coveralls": "npm run report | coveralls", "ava": "nyc ava --verbose", "lint": "eslint ./src/*" }, "dependencies": { "crypto-js": "^4.0.0", "debug": "^4.3.1", "eventemitter3": "^4.0.7", "isomorphic-ws": "^4.0.1", "ws": "^7.2.0" }, "devDependencies": { "@types/crypto-js": "^4.0.1", "@types/debug": "^4.1.5", "@types/lodash.deburr": "^4.1.6", "@types/node": "^10.17.6", "@types/node-fetch": "^2.5.10", "@types/prettier": "^1.19.0", "@types/ws": "^7.4.4", "@typescript-eslint/eslint-plugin": "^4.28.0", "@typescript-eslint/parser": "^4.28.0", "ava": "^3.15.0", "buffer": "^6.0.3", "coveralls": "^3.1.0", "cross-env": "^7.0.3", "eslint": "^7.28.0", "eslint-config-xo": "^0.37.0", "eslint-config-xo-typescript": "^0.42.0", "eslint-plugin-ava": "^12.0.0", "lodash.deburr": "^4.1.0", "node-fetch": "^2.6.1", "npm-run-all": "^4.1.5", "nyc": "^15.1.0", "prettier": "^2.3.1", "rimraf": "^3.0.2", "terser-webpack-plugin": "^5.1.3", "ts-node": "^10.0.0", "typescript": "^4.3.2", "uglifyjs-webpack-plugin": "^2.2.0", "webpack": "^5.39.0", "webpack-cli": "^4.7.2" }, "bugs": { "url": "https://github.com/obs-websocket-community-projects/obs-websocket-js/issues" }, "homepage": "https://github.com/obs-websocket-community-projects/obs-websocket-js#readme", "ava": { "files": [ "test/*.spec.js", "!setup/environment.js" ], "concurrency": 1, "timeout": "10s", "verbose": true } }
1,355
2,962
<filename>storio-sqlite/src/test/java/com/pushtorefresh/storio3/sqlite/operations/put/PutObjectsStub.java package com.pushtorefresh.storio3.sqlite.operations.put; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.pushtorefresh.storio3.sqlite.Changes; import com.pushtorefresh.storio3.sqlite.SQLiteTypeMapping; import com.pushtorefresh.storio3.sqlite.StorIOSQLite; import com.pushtorefresh.storio3.test.FlowableBehaviorChecker; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import io.reactivex.Completable; import io.reactivex.Flowable; import io.reactivex.Single; import io.reactivex.functions.Consumer; import static java.util.Collections.singleton; import static java.util.Collections.singletonMap; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; // stub class to avoid violation of DRY in tests class PutObjectsStub { @NonNull final StorIOSQLite storIOSQLite; @NonNull private final StorIOSQLite.LowLevel lowLevel; @NonNull final List<TestItem> items; @NonNull final PutResolver<TestItem> putResolver; @NonNull private final SQLiteTypeMapping<TestItem> typeMapping; @NonNull private final Map<TestItem, PutResult> itemsToPutResultsMap; private final boolean withTypeMapping, useTransaction; @NonNull private final Map<Changes, Integer> expectedNotifications; @NonNull private static final PutResultCreator DEFAULT_PUT_RESULT_CREATOR = new PutResultCreator() { @Override @NonNull public PutResult newPutResult(@NonNull TestItem testItem) { return PutResult.newInsertResult(1, TestItem.TABLE, singleton("test_tag")); } }; @NonNull private static final PutResultCreator MOCK_PUT_RESULT_CREATOR = new PutResultCreator() { @Override @NonNull public PutResult newPutResult(@NonNull TestItem testItem) { return mock(PutResult.class); } }; @SuppressWarnings("unchecked") private PutObjectsStub( boolean withTypeMapping, boolean useTransaction, int numberOfItems, @NonNull PutResultCreator putResultCreator ) { this.withTypeMapping = withTypeMapping; this.useTransaction = useTransaction; storIOSQLite = mock(StorIOSQLite.class); lowLevel = mock(StorIOSQLite.LowLevel.class); when(storIOSQLite.lowLevel()).thenReturn(lowLevel); when(storIOSQLite.put()) .thenReturn(new PreparedPut.Builder(storIOSQLite)); items = new ArrayList<TestItem>(numberOfItems); itemsToPutResultsMap = new HashMap<TestItem, PutResult>(numberOfItems); expectedNotifications = new HashMap<Changes, Integer>(items.size()); for (int i = 0; i < numberOfItems; i++) { final TestItem testItem = TestItem.newInstance(); items.add(testItem); final PutResult putResult = putResultCreator.newPutResult(testItem); itemsToPutResultsMap.put(testItem, putResult); if (!useTransaction && (!putResult.affectedTables().isEmpty() || !putResult.affectedTags().isEmpty())) { Changes changes = Changes.newInstance(putResult.affectedTables(), putResult.affectedTags()); Integer notificationsCount = expectedNotifications.get(changes); expectedNotifications.put(changes, notificationsCount == null ? 1 : notificationsCount + 1); } } if (useTransaction) { Set<String> tables = new HashSet<String>(); Set<String> tags = new HashSet<String>(); for (PutResult putResult : itemsToPutResultsMap.values()) { tables.addAll(putResult.affectedTables()); tags.addAll(putResult.affectedTags()); } if (!tables.isEmpty() || !tags.isEmpty()) { expectedNotifications.put(Changes.newInstance(tables, tags), 1); } } putResolver = (PutResolver<TestItem>) mock(PutResolver.class); when(putResolver.performPut(eq(storIOSQLite), any(TestItem.class))) .thenAnswer(new Answer<PutResult>() { @SuppressWarnings("SuspiciousMethodCalls") @Override public PutResult answer(InvocationOnMock invocation) throws Throwable { return itemsToPutResultsMap.get(invocation.getArguments()[1]); } }); typeMapping = mock(SQLiteTypeMapping.class); if (withTypeMapping) { when(lowLevel.typeMapping(TestItem.class)).thenReturn(typeMapping); when(typeMapping.putResolver()).thenReturn(putResolver); } } @NonNull static PutObjectsStub newPutStubForEmptyCollectionWithoutTransaction() { return new PutObjectsStub(true, false, 0, DEFAULT_PUT_RESULT_CREATOR); } @NonNull static PutObjectsStub newPutStubForEmptyCollectionWithTransaction() { return new PutObjectsStub(true, true, 0, DEFAULT_PUT_RESULT_CREATOR); } @NonNull static PutObjectsStub newPutStubForOneObjectWithoutTypeMapping() { return new PutObjectsStub(false, false, 1, DEFAULT_PUT_RESULT_CREATOR); } @NonNull static PutObjectsStub newPutStubForOneObjectWithTypeMapping() { return new PutObjectsStub(true, false, 1, DEFAULT_PUT_RESULT_CREATOR); } @NonNull static PutObjectsStub newPutStubForOneObjectWithoutInsertsAndUpdatesWithoutTypeMapping() { return new PutObjectsStub(false, false, 1, MOCK_PUT_RESULT_CREATOR); } @NonNull static PutObjectsStub newPutStubForOneObjectWithoutInsertsAndUpdatesWithTypeMapping() { return new PutObjectsStub(true, false, 1, MOCK_PUT_RESULT_CREATOR); } @NonNull static PutObjectsStub newPutStubForMultipleObjectsWithoutTypeMappingWithTransaction() { return new PutObjectsStub(false, true, 3, DEFAULT_PUT_RESULT_CREATOR); } @NonNull static PutObjectsStub newPutStubForMultipleObjectsWithTypeMappingWithTransaction() { return new PutObjectsStub(true, true, 3, DEFAULT_PUT_RESULT_CREATOR); } @NonNull static PutObjectsStub newPutStubForMultipleObjectsWithoutTypeMappingWithoutTransaction() { return new PutObjectsStub(false, false, 3, DEFAULT_PUT_RESULT_CREATOR); } @NonNull static PutObjectsStub newPutStubForMultipleObjectsWithTypeMappingWithoutTransaction() { return new PutObjectsStub(true, false, 3, DEFAULT_PUT_RESULT_CREATOR); } @NonNull static PutObjectsStub newPutStubForMultipleObjectsWithoutInsertsAndUpdatesWithTypeMappingWithTransaction() { return new PutObjectsStub(true, true, 3, MOCK_PUT_RESULT_CREATOR); } @NonNull static PutObjectsStub newPutStubForMultipleObjectsWithoutInsertsAndUpdatesWithoutTypeMappingWithTransaction() { return new PutObjectsStub(false, true, 3, MOCK_PUT_RESULT_CREATOR); } @NonNull static PutObjectsStub newPutStubForMultipleObjectsWithoutInsertsAndUpdatesWithTypeMappingWithoutTransaction() { return new PutObjectsStub(true, false, 3, MOCK_PUT_RESULT_CREATOR); } @NonNull static PutObjectsStub newPutStubForMultipleObjectsWithoutInsertsAndUpdatesWithoutTypeMappingWithoutTransaction() { return new PutObjectsStub(false, false, 3, MOCK_PUT_RESULT_CREATOR); } void verifyBehaviorForMultipleObjects(@Nullable PutResults<TestItem> putResults) { assertThat(putResults).isNotNull(); // should be called once because of Performance! verify(storIOSQLite).lowLevel(); // should be called once verify(storIOSQLite).interceptors(); // only one call to storIOSQLite.put() should occur verify(storIOSQLite).put(); // number of calls to putResolver's performPut() should be equal to number of objects verify(putResolver, times(items.size())).performPut(eq(storIOSQLite), any(TestItem.class)); for (final TestItem testItem : items) { // put resolver should be invoked for each item verify(putResolver).performPut(storIOSQLite, testItem); final PutResult expectedPutResult = itemsToPutResultsMap.get(testItem); assertThat(putResults.results().get(testItem)).isEqualTo(expectedPutResult); } assertThat(putResults.results()).hasSize(itemsToPutResultsMap.size()); verifyNotificationsAndTransactionBehavior(); if (withTypeMapping) { // should be called for each item verify(lowLevel, times(items.size())).typeMapping(TestItem.class); // should be called for each item verify(typeMapping, times(items.size())).putResolver(); } verifyNoMoreInteractions(storIOSQLite, lowLevel, typeMapping, putResolver); } void verifyBehaviorForMultipleObjects(@NonNull Flowable<PutResults<TestItem>> putResultsFlowable) { new FlowableBehaviorChecker<PutResults<TestItem>>() .flowable(putResultsFlowable) .expectedNumberOfEmissions(1) .testAction(new Consumer<PutResults<TestItem>>() { @Override public void accept(PutResults<TestItem> testItemPutResults) { verify(storIOSQLite).defaultRxScheduler(); verifyBehaviorForMultipleObjects(testItemPutResults); } }) .checkBehaviorOfFlowable(); } void verifyBehaviorForMultipleObjects(@NonNull Single<PutResults<TestItem>> putResultsSingle) { new FlowableBehaviorChecker<PutResults<TestItem>>() .flowable(putResultsSingle.toFlowable()) .expectedNumberOfEmissions(1) .testAction(new Consumer<PutResults<TestItem>>() { @Override public void accept(PutResults<TestItem> testItemPutResults) { verify(storIOSQLite).defaultRxScheduler(); verifyBehaviorForMultipleObjects(testItemPutResults); } }) .checkBehaviorOfFlowable(); } void verifyBehaviorForMultipleObjects(@NonNull Completable completable) { verifyBehaviorForMultipleObjects(completable.<PutResults<TestItem>>toFlowable()); } void verifyBehaviorForOneObject(@Nullable PutResult putResult) { assertThat(putResult).isNotNull(); verifyBehaviorForMultipleObjects(PutResults.newInstance(singletonMap(items.get(0), putResult))); } void verifyBehaviorForOneObject(@NonNull Flowable<PutResult> putResultFlowable) { new FlowableBehaviorChecker<PutResult>() .flowable(putResultFlowable) .expectedNumberOfEmissions(1) .testAction(new Consumer<PutResult>() { @Override public void accept(PutResult putResult) { verify(storIOSQLite).defaultRxScheduler(); verifyBehaviorForOneObject(putResult); } }) .checkBehaviorOfFlowable(); } void verifyBehaviorForOneObject(@NonNull Single<PutResult> putResultSingle) { new FlowableBehaviorChecker<PutResult>() .flowable(putResultSingle.toFlowable()) .expectedNumberOfEmissions(1) .testAction(new Consumer<PutResult>() { @Override public void accept(PutResult putResult) { verify(storIOSQLite).defaultRxScheduler(); verifyBehaviorForOneObject(putResult); } }) .checkBehaviorOfFlowable(); } void verifyBehaviorForOneObject(@NonNull Completable completable) { verifyBehaviorForOneObject(completable.<PutResult>toFlowable()); } private void verifyNotificationsAndTransactionBehavior() { if (useTransaction) { verify(lowLevel).beginTransaction(); verify(lowLevel).setTransactionSuccessful(); verify(lowLevel).endTransaction(); if (!expectedNotifications.isEmpty()) { assertThat(expectedNotifications).hasSize(1); final Map.Entry<Changes, Integer> expectedNotification = expectedNotifications.entrySet().iterator().next(); assertThat(expectedNotification.getValue()).isEqualTo(1); // if put() operation used transaction, only one notification should be thrown verify(lowLevel).notifyAboutChanges(expectedNotification.getKey()); } else { verify(lowLevel, never()).notifyAboutChanges(any(Changes.class)); } } else { verify(lowLevel, never()).beginTransaction(); verify(lowLevel, never()).setTransactionSuccessful(); verify(lowLevel, never()).endTransaction(); // if put() operation didn't use transaction, // number of notifications should be equal to number of objects for (Map.Entry<Changes, Integer> expectedNotification : expectedNotifications.entrySet()) { verify(lowLevel, times(expectedNotification.getValue())).notifyAboutChanges(expectedNotification.getKey()); } } } private interface PutResultCreator { @NonNull PutResult newPutResult(@NonNull TestItem testItem); } }
5,895
696
<reponame>hwang-pku/Strata /* * Copyright (C) 2016 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.strata.product; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import java.util.NoSuchElementException; import java.util.Optional; import org.joda.beans.Bean; import org.joda.beans.BeanBuilder; import org.joda.beans.ImmutableBean; import org.joda.beans.JodaBeanUtils; import org.joda.beans.MetaBean; import org.joda.beans.MetaProperty; import org.joda.beans.gen.BeanDefinition; import org.joda.beans.gen.PropertyDefinition; import org.joda.beans.impl.direct.DirectMetaBean; import org.joda.beans.impl.direct.DirectMetaProperty; import org.joda.beans.impl.direct.DirectMetaPropertyMap; import org.joda.beans.impl.direct.DirectPrivateBeanBuilder; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.opengamma.strata.basics.ReferenceData; import com.opengamma.strata.basics.currency.CurrencyAmount; /** * Information about a security. * <p> * This provides common information about a security. * This includes the identifier, information about the price and an extensible data map. */ @BeanDefinition(builderScope = "private", constructorScope = "package") public final class SecurityInfo implements Attributes, ImmutableBean, Serializable { /** * The security identifier. * <p> * This identifier uniquely identifies the security within the system. * It is the key used to lookup the security in {@link ReferenceData}. * <p> * A real-world security will typically have multiple identifiers. * The only restriction placed on the identifier is that it is sufficiently * unique for the reference data lookup. As such, it is acceptable to use * an identifier from a well-known global or vendor symbology. */ @PropertyDefinition(validate = "notNull") private final SecurityId id; /** * The information about the security price. * <p> * This provides information about the security price. * This can be used to convert the price into a monetary value. */ @PropertyDefinition(validate = "notNull") private final SecurityPriceInfo priceInfo; /** * The security attributes. * <p> * Security attributes provide the ability to associate arbitrary information in a key-value map. */ @PropertyDefinition(validate = "notNull") private final ImmutableMap<AttributeType<?>, Object> attributes; //------------------------------------------------------------------------- /** * Obtains an instance from the identifier, tick size and tick value. * <p> * This creates an instance, building the {@link SecurityPriceInfo} from * the tick size and tick value, setting the contract size to 1. * <p> * A {@code SecurityInfo} also contains a hash map of additional information, * keyed by {@link AttributeType}. This hash map may contain anything * of interest, and is populated using {@link #withAttribute(AttributeType, Object)}. * * @param id the security identifier * @param tickSize the size of each tick, not negative or zero * @param tickValue the value of each tick * @return the security information */ public static SecurityInfo of(SecurityId id, double tickSize, CurrencyAmount tickValue) { return new SecurityInfo(id, SecurityPriceInfo.of(tickSize, tickValue), ImmutableMap.of()); } /** * Obtains an instance from the identifier and pricing info. * <p> * A {@code SecurityInfo} also contains a hash map of additional information, * keyed by {@link AttributeType}. This hash map may contain anything * of interest, and is populated using {@link #withAttribute(AttributeType, Object)}. * * @param id the security identifier * @param priceInfo the information about the price * @return the security information */ public static SecurityInfo of(SecurityId id, SecurityPriceInfo priceInfo) { return new SecurityInfo(id, priceInfo, ImmutableMap.of()); } /** * Returns a builder used to create an instance of the bean. * * @return the builder, not null */ public static SecurityInfoBuilder builder() { return new SecurityInfoBuilder(); } //------------------------------------------------------------------------- @Override public ImmutableSet<AttributeType<?>> getAttributeTypes() { return attributes.keySet(); } @Override public <T> Optional<T> findAttribute(AttributeType<T> type) { return Optional.ofNullable(type.fromStoredForm(attributes.get(type))); } @Override public <T> SecurityInfo withAttribute(AttributeType<T> type, T value) { // ImmutableMap.Builder would not provide Map.put semantics Map<AttributeType<?>, Object> updatedAttributes = new HashMap<>(attributes); if (value == null) { updatedAttributes.remove(type); } else { updatedAttributes.put(type, type.toStoredForm(value)); } return new SecurityInfo(id, priceInfo, updatedAttributes); } @Override public SecurityInfo withAttributes(Attributes other) { SecurityInfoBuilder builder = toBuilder(); for (AttributeType<?> attrType : other.getAttributeTypes()) { builder.addAttribute(attrType.captureWildcard(), other.getAttribute(attrType)); } return builder.build(); } /** * Returns a builder populated with the values of this instance. * * @return a builder populated with the values of this instance */ public SecurityInfoBuilder toBuilder() { return new SecurityInfoBuilder(id, priceInfo, attributes); } //------------------------- AUTOGENERATED START ------------------------- /** * The meta-bean for {@code SecurityInfo}. * @return the meta-bean, not null */ public static SecurityInfo.Meta meta() { return SecurityInfo.Meta.INSTANCE; } static { MetaBean.register(SecurityInfo.Meta.INSTANCE); } /** * The serialization version id. */ private static final long serialVersionUID = 1L; /** * Creates an instance. * @param id the value of the property, not null * @param priceInfo the value of the property, not null * @param attributes the value of the property, not null */ SecurityInfo( SecurityId id, SecurityPriceInfo priceInfo, Map<AttributeType<?>, Object> attributes) { JodaBeanUtils.notNull(id, "id"); JodaBeanUtils.notNull(priceInfo, "priceInfo"); JodaBeanUtils.notNull(attributes, "attributes"); this.id = id; this.priceInfo = priceInfo; this.attributes = ImmutableMap.copyOf(attributes); } @Override public SecurityInfo.Meta metaBean() { return SecurityInfo.Meta.INSTANCE; } //----------------------------------------------------------------------- /** * Gets the security identifier. * <p> * This identifier uniquely identifies the security within the system. * It is the key used to lookup the security in {@link ReferenceData}. * <p> * A real-world security will typically have multiple identifiers. * The only restriction placed on the identifier is that it is sufficiently * unique for the reference data lookup. As such, it is acceptable to use * an identifier from a well-known global or vendor symbology. * @return the value of the property, not null */ public SecurityId getId() { return id; } //----------------------------------------------------------------------- /** * Gets the information about the security price. * <p> * This provides information about the security price. * This can be used to convert the price into a monetary value. * @return the value of the property, not null */ public SecurityPriceInfo getPriceInfo() { return priceInfo; } //----------------------------------------------------------------------- /** * Gets the security attributes. * <p> * Security attributes provide the ability to associate arbitrary information in a key-value map. * @return the value of the property, not null */ public ImmutableMap<AttributeType<?>, Object> getAttributes() { return attributes; } //----------------------------------------------------------------------- @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj != null && obj.getClass() == this.getClass()) { SecurityInfo other = (SecurityInfo) obj; return JodaBeanUtils.equal(id, other.id) && JodaBeanUtils.equal(priceInfo, other.priceInfo) && JodaBeanUtils.equal(attributes, other.attributes); } return false; } @Override public int hashCode() { int hash = getClass().hashCode(); hash = hash * 31 + JodaBeanUtils.hashCode(id); hash = hash * 31 + JodaBeanUtils.hashCode(priceInfo); hash = hash * 31 + JodaBeanUtils.hashCode(attributes); return hash; } @Override public String toString() { StringBuilder buf = new StringBuilder(128); buf.append("SecurityInfo{"); buf.append("id").append('=').append(JodaBeanUtils.toString(id)).append(',').append(' '); buf.append("priceInfo").append('=').append(JodaBeanUtils.toString(priceInfo)).append(',').append(' '); buf.append("attributes").append('=').append(JodaBeanUtils.toString(attributes)); buf.append('}'); return buf.toString(); } //----------------------------------------------------------------------- /** * The meta-bean for {@code SecurityInfo}. */ public static final class Meta extends DirectMetaBean { /** * The singleton instance of the meta-bean. */ static final Meta INSTANCE = new Meta(); /** * The meta-property for the {@code id} property. */ private final MetaProperty<SecurityId> id = DirectMetaProperty.ofImmutable( this, "id", SecurityInfo.class, SecurityId.class); /** * The meta-property for the {@code priceInfo} property. */ private final MetaProperty<SecurityPriceInfo> priceInfo = DirectMetaProperty.ofImmutable( this, "priceInfo", SecurityInfo.class, SecurityPriceInfo.class); /** * The meta-property for the {@code attributes} property. */ @SuppressWarnings({"unchecked", "rawtypes" }) private final MetaProperty<ImmutableMap<AttributeType<?>, Object>> attributes = DirectMetaProperty.ofImmutable( this, "attributes", SecurityInfo.class, (Class) ImmutableMap.class); /** * The meta-properties. */ private final Map<String, MetaProperty<?>> metaPropertyMap$ = new DirectMetaPropertyMap( this, null, "id", "priceInfo", "attributes"); /** * Restricted constructor. */ private Meta() { } @Override protected MetaProperty<?> metaPropertyGet(String propertyName) { switch (propertyName.hashCode()) { case 3355: // id return id; case -2126070377: // priceInfo return priceInfo; case 405645655: // attributes return attributes; } return super.metaPropertyGet(propertyName); } @Override public BeanBuilder<? extends SecurityInfo> builder() { return new SecurityInfo.Builder(); } @Override public Class<? extends SecurityInfo> beanType() { return SecurityInfo.class; } @Override public Map<String, MetaProperty<?>> metaPropertyMap() { return metaPropertyMap$; } //----------------------------------------------------------------------- /** * The meta-property for the {@code id} property. * @return the meta-property, not null */ public MetaProperty<SecurityId> id() { return id; } /** * The meta-property for the {@code priceInfo} property. * @return the meta-property, not null */ public MetaProperty<SecurityPriceInfo> priceInfo() { return priceInfo; } /** * The meta-property for the {@code attributes} property. * @return the meta-property, not null */ public MetaProperty<ImmutableMap<AttributeType<?>, Object>> attributes() { return attributes; } //----------------------------------------------------------------------- @Override protected Object propertyGet(Bean bean, String propertyName, boolean quiet) { switch (propertyName.hashCode()) { case 3355: // id return ((SecurityInfo) bean).getId(); case -2126070377: // priceInfo return ((SecurityInfo) bean).getPriceInfo(); case 405645655: // attributes return ((SecurityInfo) bean).getAttributes(); } return super.propertyGet(bean, propertyName, quiet); } @Override protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) { metaProperty(propertyName); if (quiet) { return; } throw new UnsupportedOperationException("Property cannot be written: " + propertyName); } } //----------------------------------------------------------------------- /** * The bean-builder for {@code SecurityInfo}. */ private static final class Builder extends DirectPrivateBeanBuilder<SecurityInfo> { private SecurityId id; private SecurityPriceInfo priceInfo; private Map<AttributeType<?>, Object> attributes = ImmutableMap.of(); /** * Restricted constructor. */ private Builder() { } //----------------------------------------------------------------------- @Override public Object get(String propertyName) { switch (propertyName.hashCode()) { case 3355: // id return id; case -2126070377: // priceInfo return priceInfo; case 405645655: // attributes return attributes; default: throw new NoSuchElementException("Unknown property: " + propertyName); } } @SuppressWarnings("unchecked") @Override public Builder set(String propertyName, Object newValue) { switch (propertyName.hashCode()) { case 3355: // id this.id = (SecurityId) newValue; break; case -2126070377: // priceInfo this.priceInfo = (SecurityPriceInfo) newValue; break; case 405645655: // attributes this.attributes = (Map<AttributeType<?>, Object>) newValue; break; default: throw new NoSuchElementException("Unknown property: " + propertyName); } return this; } @Override public SecurityInfo build() { return new SecurityInfo( id, priceInfo, attributes); } //----------------------------------------------------------------------- @Override public String toString() { StringBuilder buf = new StringBuilder(128); buf.append("SecurityInfo.Builder{"); buf.append("id").append('=').append(JodaBeanUtils.toString(id)).append(',').append(' '); buf.append("priceInfo").append('=').append(JodaBeanUtils.toString(priceInfo)).append(',').append(' '); buf.append("attributes").append('=').append(JodaBeanUtils.toString(attributes)); buf.append('}'); return buf.toString(); } } //-------------------------- AUTOGENERATED END -------------------------- }
4,936
892
{ "schema_version": "1.2.0", "id": "GHSA-6ghc-48vx-2m7g", "modified": "2022-05-13T01:13:45Z", "published": "2022-05-13T01:13:45Z", "aliases": [ "CVE-2017-8244" ], "details": "In core_info_read and inst_info_read in all Android releases from CAF using the Linux kernel, variable \"dbg_buf\", \"dbg_buf->curr\" and \"dbg_buf->filled_size\" could be modified by different threads at the same time, but they are not protected with mutex or locks. Buffer overflow is possible on race conditions. \"buffer->curr\" itself could also be overwritten, which means that it may point to anywhere of kernel memory (for write).", "severity": [ { "type": "CVSS_V3", "score": "CVSS:3.1/AV:L/AC:H/PR:L/UI:N/S:U/C:H/I:H/A:H" } ], "affected": [ ], "references": [ { "type": "ADVISORY", "url": "https://nvd.nist.gov/vuln/detail/CVE-2017-8244" }, { "type": "WEB", "url": "https://source.android.com/security/bulletin/pixel/2017-12-01" }, { "type": "WEB", "url": "https://www.codeaurora.org/buffer-overflow-msmvidc-debugfs-driver-coreinforead-and-instinforead-cve-2017-8244" }, { "type": "WEB", "url": "http://www.securityfocus.com/bid/98547" } ], "database_specific": { "cwe_ids": [ "CWE-362" ], "severity": "HIGH", "github_reviewed": false } }
620
1,694
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by <NAME>. // #import "MMUIViewController.h" #import "EditBottleProfileDelegate-Protocol.h" #import "PBMessageObserverDelegate-Protocol.h" #import "UIAlertViewDelegate-Protocol.h" #import "UITableViewDataSource-Protocol.h" #import "UITableViewDelegate-Protocol.h" @class CBottleContact, MMHDHeadImageView, MMHeadImageView, MMTableView, NSString, UIImageView, UILabel; @interface BottleProfileViewController : MMUIViewController <PBMessageObserverDelegate, EditBottleProfileDelegate, UITableViewDelegate, UITableViewDataSource, UIAlertViewDelegate> { MMTableView *m_tableView; MMHeadImageView *m_headImage; UILabel *m_cityLabel; UIImageView *m_sexView; MMHDHeadImageView *m_HDHeadView; CBottleContact *m_contact; } @property(retain, nonatomic) CBottleContact *m_contact; // @synthesize m_contact; - (void).cxx_destruct; - (id)initWithContact:(id)arg1; - (id)init; - (id)tableView:(id)arg1 cellForRowAtIndexPath:(id)arg2; - (double)tableView:(id)arg1 heightForRowAtIndexPath:(id)arg2; - (long long)tableView:(id)arg1 numberOfRowsInSection:(long long)arg2; - (void)makeSignatureCell:(id)arg1; - (int)getLinesForSignature:(id)arg1; - (void)dealloc; - (void)viewDidLoad; - (void)initView; - (void)initHeaderView; - (void)initHDHeadImage; - (void)onSayHello; - (void)initExposeView; - (void)initSayHelloToContactBtn; - (void)viewWillAppear:(_Bool)arg1; - (void)SaveImg:(id)arg1; - (void)updateInfo; - (void)onEdit:(id)arg1; - (void)MessageReturn:(id)arg1 Event:(unsigned int)arg2; - (void)onExpose; - (void)alertView:(id)arg1 clickedButtonAtIndex:(long long)arg2; - (void)confirmExpose:(unsigned int)arg1; // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) unsigned long long hash; @property(readonly) Class superclass; @end
757
335
<reponame>tsbohc/ProjectE package moze_intel.projecte.api.capabilities; import java.math.BigInteger; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Nonnull; import moze_intel.projecte.api.ItemInfo; import net.minecraft.entity.player.ServerPlayerEntity; import net.minecraft.item.ItemStack; import net.minecraft.nbt.CompoundNBT; import net.minecraft.util.Direction; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.util.INBTSerializable; import net.minecraftforge.items.IItemHandler; /** * This interface defines the contract for some object that exposes transmutation knowledge through the Capability system. * * Acquire an instance of this using {@link net.minecraft.entity.Entity#getCapability(Capability, Direction)}. */ public interface IKnowledgeProvider extends INBTSerializable<CompoundNBT> { /** * @return Whether the player has the "tome" flag set, meaning all knowledge checks automatically return true */ boolean hasFullKnowledge(); /** * @param fullKnowledge Whether the player has the "tome" flag set, meaning all knowledge checks automatically return true */ void setFullKnowledge(boolean fullKnowledge); /** * Clears all knowledge. Additionally, clears the "tome" flag. */ void clearKnowledge(); /** * @param stack The stack to query * * @return Whether the player has transmutation knowledge for this stack * * @implNote This method defaults to making sure the stack is not empty and then wrapping the stack into an {@link ItemInfo} and calling {@link * #hasKnowledge(ItemInfo)} */ default boolean hasKnowledge(@Nonnull ItemStack stack) { return !stack.isEmpty() && hasKnowledge(ItemInfo.fromStack(stack)); } /** * @param info The {@link ItemInfo} to query * * @return Whether the player has transmutation knowledge for this {@link ItemInfo} */ boolean hasKnowledge(@Nonnull ItemInfo info); /** * @param stack The stack to add to knowledge * * @return Whether the operation was successful * * @implNote This method defaults to making sure the stack is not empty and then wrapping the stack into an {@link ItemInfo} and calling {@link * #addKnowledge(ItemInfo)} */ default boolean addKnowledge(@Nonnull ItemStack stack) { return !stack.isEmpty() && addKnowledge(ItemInfo.fromStack(stack)); } /** * @param info The {@link ItemInfo} to add to knowledge * * @return Whether the operation was successful */ boolean addKnowledge(@Nonnull ItemInfo info); /** * @param stack The stack to remove from knowledge * * @return Whether the operation was successful * * @implNote This method defaults to making sure the stack is not empty and then wrapping the stack into an {@link ItemInfo} and calling {@link * #removeKnowledge(ItemInfo)} */ default boolean removeKnowledge(@Nonnull ItemStack stack) { return !stack.isEmpty() && removeKnowledge(ItemInfo.fromStack(stack)); } /** * @param info The {@link ItemInfo} to remove from knowledge * * @return Whether the operation was successful */ boolean removeKnowledge(@Nonnull ItemInfo info); /** * @return An unmodifiable but live view of the knowledge list. */ @Nonnull Set<ItemInfo> getKnowledge(); /** * @return The player's input and lock slots */ @Nonnull IItemHandler getInputAndLocks(); /** * @return The emc in this player's transmutation tablet network */ BigInteger getEmc(); /** * @param emc The emc to set in this player's transmutation tablet network */ void setEmc(BigInteger emc); /** * Syncs this provider to the given player. * * @param player The player to sync to. */ void sync(@Nonnull ServerPlayerEntity player); /** * Syncs the emc stored in this provider to the given player. * * @param player The player to sync to. */ void syncEmc(@Nonnull ServerPlayerEntity player); /** * Syncs that a specific item's knowledge changed (either learned or unlearned) to the given player. * * @param player The player to sync to. * @param change The item that changed. (Should be the persistent variant) * @param learned True if learned, false if unlearned. */ void syncKnowledgeChange(@Nonnull ServerPlayerEntity player, ItemInfo change, boolean learned); /** * Syncs the inputs and locks stored in this provider to the given player. * * @param player The player to sync to. * @param slotsChanged The indices of the slots that need to be synced (may be empty, in which case nothing should happen). * @param updateTargets How the targets should be updated on the client. */ void syncInputAndLocks(@Nonnull ServerPlayerEntity player, List<Integer> slotsChanged, TargetUpdateType updateTargets); /** * @param changes Slot index to stack for the changes that occurred. * * @apiNote Should only really be used on the client for purposes of receiving/handling {@link #syncInputAndLocks(ServerPlayerEntity, List, TargetUpdateType)} */ void receiveInputsAndLocks(Map<Integer, ItemStack> changes); enum TargetUpdateType { /** * Don't update targets. */ NONE, /** * Only update if "needed", the emc value is below the highest item. */ IF_NEEDED, /** * Update targets. */ ALL } }
1,557
4,372
<filename>shardingsphere-proxy/shardingsphere-proxy-backend/src/main/java/org/apache/shardingsphere/proxy/backend/communication/jdbc/statement/JDBCBackendStatement.java /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.shardingsphere.proxy.backend.communication.jdbc.statement; import lombok.Getter; import lombok.Setter; import org.apache.shardingsphere.db.protocol.parameter.TypeUnspecifiedSQLParameter; import org.apache.shardingsphere.infra.database.type.DatabaseType; import org.apache.shardingsphere.infra.executor.sql.context.ExecutionUnit; import org.apache.shardingsphere.infra.executor.sql.execute.engine.ConnectionMode; import org.apache.shardingsphere.infra.executor.sql.prepare.driver.jdbc.ExecutorJDBCStatementManager; import org.apache.shardingsphere.infra.executor.sql.prepare.driver.jdbc.StatementOption; import org.apache.shardingsphere.proxy.backend.communication.SQLStatementDatabaseHolder; import org.apache.shardingsphere.proxy.backend.context.ProxyContext; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; import java.sql.Types; import java.util.List; import java.util.Optional; /** * JDBC backend statement. */ @Getter @Setter public final class JDBCBackendStatement implements ExecutorJDBCStatementManager { private String databaseName; @Override public Statement createStorageResource(final Connection connection, final ConnectionMode connectionMode, final StatementOption option) throws SQLException { Statement result = connection.createStatement(); if (ConnectionMode.MEMORY_STRICTLY == connectionMode) { setFetchSize(result); } return result; } @Override public Statement createStorageResource(final ExecutionUnit executionUnit, final Connection connection, final ConnectionMode connectionMode, final StatementOption option) throws SQLException { String sql = executionUnit.getSqlUnit().getSql(); List<Object> parameters = executionUnit.getSqlUnit().getParameters(); PreparedStatement result = option.isReturnGeneratedKeys() ? connection.prepareStatement(executionUnit.getSqlUnit().getSql(), Statement.RETURN_GENERATED_KEYS) : connection.prepareStatement(sql); for (int i = 0; i < parameters.size(); i++) { Object parameter = parameters.get(i); if (parameter instanceof TypeUnspecifiedSQLParameter) { result.setObject(i + 1, parameter, Types.OTHER); } else { result.setObject(i + 1, parameter); } } if (ConnectionMode.MEMORY_STRICTLY == connectionMode) { setFetchSize(result); } return result; } private void setFetchSize(final Statement statement) throws SQLException { DatabaseType databaseType = ProxyContext.getInstance().getContextManager().getMetaDataContexts() .getMetaData(null == databaseName ? SQLStatementDatabaseHolder.get() : databaseName).getResource().getDatabaseType(); Optional<StatementMemoryStrictlyFetchSizeSetter> fetchSizeSetter = StatementMemoryStrictlyFetchSizeSetterFactory.findInstance(databaseType.getType()); if (fetchSizeSetter.isPresent()) { fetchSizeSetter.get().setFetchSize(statement); } } }
1,386
442
<reponame>violet-Bin/read-spring-code /* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cache.config; import java.io.IOException; import java.util.concurrent.atomic.AtomicLong; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CachePut; import org.springframework.cache.annotation.Cacheable; import org.springframework.cache.annotation.Caching; /** * Simple cacheable service * * @author <NAME> * @author <NAME> * @author <NAME> */ public class DefaultCacheableService implements CacheableService<Long> { private final AtomicLong counter = new AtomicLong(); private final AtomicLong nullInvocations = new AtomicLong(); @Override @Cacheable("testCache") public Long cache(Object arg1) { return counter.getAndIncrement(); } @Override @Cacheable("testCache") public Long cacheNull(Object arg1) { return null; } @Override @Cacheable(cacheNames = "testCache", sync = true) public Long cacheSync(Object arg1) { return counter.getAndIncrement(); } @Override @Cacheable(cacheNames = "testCache", sync = true) public Long cacheSyncNull(Object arg1) { return null; } @Override @CacheEvict("testCache") public void invalidate(Object arg1) { } @Override @CacheEvict("testCache") public void evictWithException(Object arg1) { throw new RuntimeException("exception thrown - evict should NOT occur"); } @Override @CacheEvict(cacheNames = "testCache", allEntries = true) public void evictAll(Object arg1) { } @Override @CacheEvict(cacheNames = "testCache", beforeInvocation = true) public void evictEarly(Object arg1) { throw new RuntimeException("exception thrown - evict should still occur"); } @Override @CacheEvict(cacheNames = "testCache", key = "#p0") public void evict(Object arg1, Object arg2) { } @Override @CacheEvict(cacheNames = "testCache", key = "#p0", beforeInvocation = true) public void invalidateEarly(Object arg1, Object arg2) { throw new RuntimeException("exception thrown - evict should still occur"); } @Override @Cacheable(cacheNames = "testCache", condition = "#p0 == 3") public Long conditional(int classField) { return counter.getAndIncrement(); } @Override @Cacheable(cacheNames = "testCache", sync = true, condition = "#p0 == 3") public Long conditionalSync(int field) { return counter.getAndIncrement(); } @Override @Cacheable(cacheNames = "testCache", unless = "#result > 10") public Long unless(int arg) { return (long) arg; } @Override @Cacheable(cacheNames = "testCache", key = "#p0") public Long key(Object arg1, Object arg2) { return counter.getAndIncrement(); } @Override @Cacheable(cacheNames = "testCache") public Long varArgsKey(Object... args) { return counter.getAndIncrement(); } @Override @Cacheable(cacheNames = "testCache", key = "#root.methodName") public Long name(Object arg1) { return counter.getAndIncrement(); } @Override @Cacheable(cacheNames = "testCache", key = "#root.methodName + #root.method.name + #root.targetClass + #root.target") public Long rootVars(Object arg1) { return counter.getAndIncrement(); } @Override @Cacheable(cacheNames = "testCache", keyGenerator = "customKeyGenerator") public Long customKeyGenerator(Object arg1) { return counter.getAndIncrement(); } @Override @Cacheable(cacheNames = "testCache", keyGenerator = "unknownBeanName") public Long unknownCustomKeyGenerator(Object arg1) { return counter.getAndIncrement(); } @Override @Cacheable(cacheNames = "testCache", cacheManager = "customCacheManager") public Long customCacheManager(Object arg1) { return counter.getAndIncrement(); } @Override @Cacheable(cacheNames = "testCache", cacheManager = "unknownBeanName") public Long unknownCustomCacheManager(Object arg1) { return counter.getAndIncrement(); } @Override @CachePut("testCache") public Long update(Object arg1) { return counter.getAndIncrement(); } @Override @CachePut(cacheNames = "testCache", condition = "#arg.equals(3)") public Long conditionalUpdate(Object arg) { return Long.valueOf(arg.toString()); } @Override @Cacheable("testCache") public Long nullValue(Object arg1) { nullInvocations.incrementAndGet(); return null; } @Override public Number nullInvocations() { return nullInvocations.get(); } @Override @Cacheable("testCache") public Long throwChecked(Object arg1) throws Exception { throw new IOException(arg1.toString()); } @Override @Cacheable("testCache") public Long throwUnchecked(Object arg1) { throw new UnsupportedOperationException(arg1.toString()); } @Override @Cacheable(cacheNames = "testCache", sync = true) public Long throwCheckedSync(Object arg1) throws Exception { throw new IOException(arg1.toString()); } @Override @Cacheable(cacheNames = "testCache", sync = true) public Long throwUncheckedSync(Object arg1) { throw new UnsupportedOperationException(arg1.toString()); } // multi annotations @Override @Caching(cacheable = { @Cacheable("primary"), @Cacheable("secondary") }) public Long multiCache(Object arg1) { return counter.getAndIncrement(); } @Override @Caching(evict = { @CacheEvict("primary"), @CacheEvict(cacheNames = "secondary", key = "#p0"), @CacheEvict(cacheNames = "primary", key = "#p0 + 'A'") }) public Long multiEvict(Object arg1) { return counter.getAndIncrement(); } @Override @Caching(cacheable = { @Cacheable(cacheNames = "primary", key = "#root.methodName") }, evict = { @CacheEvict("secondary") }) public Long multiCacheAndEvict(Object arg1) { return counter.getAndIncrement(); } @Override @Caching(cacheable = { @Cacheable(cacheNames = "primary", condition = "#p0 == 3") }, evict = { @CacheEvict("secondary") }) public Long multiConditionalCacheAndEvict(Object arg1) { return counter.getAndIncrement(); } @Override @Caching(put = { @CachePut("primary"), @CachePut("secondary") }) public Long multiUpdate(Object arg1) { return Long.valueOf(arg1.toString()); } @Override @CachePut(cacheNames = "primary", key = "#result.id") public TestEntity putRefersToResult(TestEntity arg1) { arg1.setId(Long.MIN_VALUE); return arg1; } }
2,160
385
""" Displays a NetworkX octahedral graph to screen using a ArcPlot. """ import matplotlib.pyplot as plt import networkx as nx from nxviz.plots import ArcPlot G = nx.octahedral_graph() c = ArcPlot(G) c.draw() plt.show()
85
343
// // TonicTests.h // TonicTests // // Created by <NAME> on 4/19/13. // Copyright (c) 2013 <NAME>. All rights reserved. // #import <XCTest/XCTest.h> @interface TonicTests : XCTestCase @end
84
381
import thread # ^^ relative import of __pypy__.thread. Note that some tests depend on # this (test_enable_signals in test_signal.py) to work properly, # otherwise they get caught in some deadlock waiting for the import # lock... class SignalsEnabled(object): '''A context manager to use in non-main threads: enables receiving signals in a "with" statement. More precisely, if a signal is received by the process, then the signal handler might be called either in the main thread (as usual) or within another thread that is within a "with signals_enabled:". This other thread should be ready to handle unexpected exceptions that the signal handler might raise --- notably KeyboardInterrupt.''' __enter__ = thread._signals_enter __exit__ = thread._signals_exit signals_enabled = SignalsEnabled()
217
4,140
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hive.ql.parse; import org.apache.hadoop.hive.ql.optimizer.calcite.CalciteSemanticException; import org.apache.hadoop.hive.ql.optimizer.calcite.CalciteSubqueryRuntimeException; import org.apache.hadoop.hive.ql.optimizer.calcite.CalciteSubquerySemanticException; import org.apache.hadoop.hive.ql.optimizer.calcite.CalciteViewSemanticException; /** * A strategy defining when CBO fallbacks to the legacy optimizer. */ enum CBOFallbackStrategy { /** * Never use the legacy optimizer, all CBO errors are fatal. */ NEVER { @Override boolean isFatal(Exception e) { return true; } }, /** * Use the legacy optimizer only when the CBO exception is not related to subqueries and views. */ CONSERVATIVE { @Override boolean isFatal(Exception e) { // Non-CBO path for the following exceptions fail with completely different error and mask the original failure return e instanceof CalciteSubquerySemanticException || e instanceof CalciteViewSemanticException || e instanceof CalciteSubqueryRuntimeException; } }, /** * Always use the legacy optimizer, CBO errors are not fatal. */ ALWAYS { @Override boolean isFatal(Exception e) { return false; } }, /** * Specific strategy only for tests. */ TEST { @Override boolean isFatal(Exception e) { if (e instanceof CalciteSubquerySemanticException || e instanceof CalciteViewSemanticException || e instanceof CalciteSubqueryRuntimeException) { return true; } return !(e instanceof CalciteSemanticException); } }; /** * Returns true if the specified exception is fatal (must not fallback to legacy optimizer), and false otherwise. */ abstract boolean isFatal(Exception e); }
815
2,151
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.services.service_manager; import org.chromium.mojo.bindings.ConnectionErrorHandler; import org.chromium.mojo.bindings.Interface; import org.chromium.mojo.bindings.InterfaceRequest; import org.chromium.mojo.system.MessagePipeHandle; import org.chromium.mojo.system.MojoException; import org.chromium.service_manager.mojom.ConstantsConstants; import org.chromium.service_manager.mojom.Identity; /** * This class exposes the ability to bind interfaces from other services in the system. */ public class Connector implements ConnectionErrorHandler { private org.chromium.service_manager.mojom.Connector.Proxy mConnector; private static class ConnectorBindInterfaceResponseImpl implements org.chromium.service_manager.mojom.Connector.BindInterfaceResponse { @Override public void call(Integer result, Identity userId) {} } public Connector(MessagePipeHandle handle) { mConnector = org.chromium.service_manager.mojom.Connector.MANAGER.attachProxy(handle, 0); mConnector.getProxyHandler().setErrorHandler(this); } /** * Asks a service to bind an interface request. * * @param serviceName The name of the service. * @param interfaceName The name of interface I. * @param request The request for the interface I. */ public <I extends Interface, P extends Interface.Proxy> void bindInterface( String serviceName, String interfaceName, InterfaceRequest<I> request) { Identity target = new Identity(); target.name = serviceName; target.userId = ConstantsConstants.INHERIT_USER_ID; target.instance = ""; org.chromium.service_manager.mojom.Connector.BindInterfaceResponse callback = new ConnectorBindInterfaceResponseImpl(); mConnector.bindInterface(target, interfaceName, request.passHandle(), callback); } @Override public void onConnectionError(MojoException e) { mConnector.close(); } }
712
800
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # 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. """Integration code for Eclipser fuzzer. Note that starting from v2.0, Eclipser relies on AFL to perform random-based fuzzing.""" import shutil import subprocess import os import threading from fuzzers import utils from fuzzers.afl import fuzzer as afl_fuzzer def get_uninstrumented_outdir(target_directory): """Return path to uninstrumented target directory.""" return os.path.join(target_directory, 'uninstrumented') def build(): """Build benchmark.""" # Backup the environment. new_env = os.environ.copy() # First, build an instrumented binary for AFL. afl_fuzzer.prepare_build_environment() src = os.getenv('SRC') work = os.getenv('WORK') with utils.restore_directory(src), utils.restore_directory(work): # Restore SRC to its initial state so we can build again without any # trouble. For some OSS-Fuzz projects, build_benchmark cannot be run # twice in the same directory without this. utils.build_benchmark() print('[build] Copying afl-fuzz to $OUT directory') shutil.copy('/afl/afl-fuzz', os.environ['OUT']) # Next, build an uninstrumented binary for Eclipser. new_env['CC'] = 'clang' new_env['CXX'] = 'clang++' new_env['FUZZER_LIB'] = '/libStandaloneFuzzTarget.a' # Ensure to compile with NO_SANITIZER_COMPAT* flags even for bug benchmarks, # as QEMU is incompatible with sanitizers. Also, Eclipser prefers clean and # unoptimized binaries. We leave fast random fuzzing as AFL's job. new_env['CFLAGS'] = ' '.join(utils.NO_SANITIZER_COMPAT_CFLAGS) cxxflags = [utils.LIBCPLUSPLUS_FLAG] + utils.NO_SANITIZER_COMPAT_CFLAGS new_env['CXXFLAGS'] = ' '.join(cxxflags) uninstrumented_outdir = get_uninstrumented_outdir(os.environ['OUT']) os.mkdir(uninstrumented_outdir) new_env['OUT'] = uninstrumented_outdir fuzz_target = os.getenv('FUZZ_TARGET') if fuzz_target: targ_name = os.path.basename(fuzz_target) new_env['FUZZ_TARGET'] = os.path.join(uninstrumented_outdir, targ_name) print('[build] Re-building benchmark for uninstrumented fuzzing target') utils.build_benchmark(env=new_env) def eclipser(input_corpus, output_corpus, target_binary): """Run Eclipser.""" # We will use output_corpus as a directory where AFL and Eclipser sync their # test cases with each other. For Eclipser, we should explicitly specify an # output directory under this sync directory. eclipser_out = os.path.join(output_corpus, "eclipser_output") command = [ 'dotnet', '/Eclipser/build/Eclipser.dll', '-p', target_binary, '-s', output_corpus, '-o', eclipser_out, '--arg', # Specifies the command-line of the program. 'foo', '-f', # Specifies the path of file input to fuzz. 'foo', '-v', # Controls the verbosity. '2', '--exectimeout', '5000', ] if os.listdir(input_corpus): # Specify inputs only if any seed exists. command += ['-i', input_corpus] print('[eclipser] Run Eclipser with command: ' + ' '.join(command)) subprocess.Popen(command) def afl_worker(input_corpus, output_corpus, target_binary): """Run AFL worker instance.""" print('[afl_worker] Run AFL worker') afl_fuzzer.run_afl_fuzz(input_corpus, output_corpus, target_binary, ['-S', 'afl-worker'], True) def fuzz(input_corpus, output_corpus, target_binary): """Run fuzzer.""" # Calculate uninstrumented binary path from the instrumented target binary. target_binary_directory = os.path.dirname(target_binary) uninstrumented_target_binary_directory = ( get_uninstrumented_outdir(target_binary_directory)) target_binary_name = os.path.basename(target_binary) uninstrumented_target_binary = os.path.join( uninstrumented_target_binary_directory, target_binary_name) afl_fuzzer.prepare_fuzz_environment(input_corpus) afl_args = (input_corpus, output_corpus, target_binary) eclipser_args = (input_corpus, output_corpus, uninstrumented_target_binary) # Do not launch AFL master instance for now, to reduce memory usage and # align with the vanilla AFL. print('[fuzz] Running AFL worker') afl_worker_thread = threading.Thread(target=afl_worker, args=afl_args) afl_worker_thread.start() print('[fuzz] Running Eclipser') eclipser_thread = threading.Thread(target=eclipser, args=eclipser_args) eclipser_thread.start() print('[fuzz] Now waiting for threads to finish...') afl_worker_thread.join() eclipser_thread.join()
1,969
407
#include <iostream> #include <algorithm> #include <string> typedef long long int ll; using namespace std; #define NM 100005 int N, cnt[30], kind; string A; void input() { cin >> N; cin >> A; } void add(char x) { // x ๋ผ๋Š” ์•ŒํŒŒ๋ฒณ ์ถ”๊ฐ€ cnt[x - 'a']++; if (cnt[x - 'a'] == 1) // ์ƒˆ๋กญ๊ฒŒ ๋‚˜ํƒ€๋‚œ ์•ŒํŒŒ๋ฒณ์ด๋ผ๋Š” ๋œป kind++; } void erase(char x) { // x ๋ผ๋Š” ์•ŒํŒŒ๋ฒณ ์ œ๊ฑฐ cnt[x - 'a']--; if (cnt[x - 'a'] == 0) // ์ธ์‹ํ•ด์•ผ ํ•˜๋Š” ์•ŒํŒŒ๋ฒณ์—์„œ ๋น ์ง€๋Š” ์ˆœ๊ฐ„ kind--; } void pro() { int len = A.length(), ans = 0; for (int R = 0, L = 0; R < len; R++) { // R ๋ฒˆ์งธ ๋ฌธ์ž๋ฅผ ์˜ค๋ฅธ์ชฝ์— ์ถ”๊ฐ€ add(A[R]); // ๋ถˆ๊ฐ€๋Šฅํ•˜๋ฉด, ๊ฐ€๋Šฅํ•  ๋•Œ๊นŒ์ง€ L์„ ์ด๋™ while (kind > N) { erase(A[L++]); } // ์ •๋‹ต ๊ฐฑ์‹  ans = max(ans, R - L + 1); } cout << ans; } int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); input(); pro(); return 0; }
547
401
/* * Hedgewars, a free turn based strategy game * Copyright (C) 2012 <NAME> <<EMAIL>> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** * A complete game configuration that contains all settings the engine needs to start a * local or networked game. */ #ifndef MODEL_GAMESETUP_H_ #define MODEL_GAMESETUP_H_ #include "scheme.h" #include "weapon.h" #include "map.h" #include "teamlist.h" typedef struct { char *style; //!< e.g. "Capture the Flag" flib_scheme *gamescheme; flib_map *map; flib_teamlist *teamlist; } flib_gamesetup; void flib_gamesetup_destroy(flib_gamesetup *gamesetup); /** * Deep-copy of the flib_gamesetup. */ flib_gamesetup *flib_gamesetup_copy(const flib_gamesetup *gamesetup); #endif
466
724
# -*- coding:utf-8 -*- # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # This program is free software; you can redistribute it and/or modify # it under the terms of the MIT License. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MIT License for more details. """Backend Register.""" import os import sys __all__ = [ "set_backend", "is_cpu_device", "is_gpu_device", "is_npu_device", "is_ms_backend", "is_tf_backend", "is_torch_backend", "get_devices", ] def set_backend(backend='pytorch', device_category='GPU'): """Set backend. :param backend: backend type, default pytorch :type backend: str """ devices = os.environ.get("NPU_VISIBLE_DEVICES", None) or os.environ.get("NPU-VISIBLE-DEVICES", None) if devices: os.environ['NPU_VISIBLE_DEVICES'] = devices # CUDA visible if 'CUDA_VISIBLE_DEVICES' in os.environ: os.environ['DEVICE_CATEGORY'] = 'GPU' elif 'NPU_VISIBLE_DEVICES' in os.environ: os.environ['DEVICE_CATEGORY'] = 'NPU' # CUDA_VISIBLE_DEVICES if device_category.upper() == "GPU" and "CUDA_VISIBLE_DEVICES" not in os.environ: if backend.lower() in ['pytorch', "p"]: import torch os.environ["CUDA_VISIBLE_DEVICES"] = ",".join( [str(x) for x in list(range(torch.cuda.device_count()))]) elif backend.lower() in ['tensorflow', "t"]: from tensorflow.python.client import device_lib devices = device_lib.list_local_devices() os.environ["CUDA_VISIBLE_DEVICES"] = ",".join( [x.name.split(":")[2] for x in devices if x.device_type == "GPU"]) # device if device_category is not None: os.environ['DEVICE_CATEGORY'] = device_category.upper() from vega.common.general import General General.device_category = device_category # backend if backend.lower() in ['pytorch', "p"]: os.environ['BACKEND_TYPE'] = 'PYTORCH' elif backend.lower() in ['tensorflow', "t"]: os.environ['BACKEND_TYPE'] = 'TENSORFLOW' import warnings warnings.filterwarnings("ignore", category=FutureWarning) elif backend.lower() in ['mindspore', "m"]: os.environ['BACKEND_TYPE'] = 'MINDSPORE' else: raise Exception('backend must be pytorch, tensorflow or mindspore') # register from vega.datasets import register_datasets from vega.modules import register_modules from vega.networks import register_networks from vega.metrics import register_metrics from vega.model_zoo import register_modelzoo from vega.core import search_algs from vega import algorithms, evaluator register_datasets(backend) register_metrics(backend) register_modules() register_networks(backend) register_modelzoo(backend) # register ascend automl modules ascend_automl_path = os.environ.get("ASCEND_AUTOML_PATH") if ascend_automl_path: sys.path.append(ascend_automl_path) try: import ascend_automl except ImportError: pass # backup config from vega.common.config_serializable import backup_configs backup_configs() def is_cpu_device(): """Return whether is cpu device or not.""" return os.environ.get('DEVICE_CATEGORY', None) == 'CPU' def is_gpu_device(): """Return whether is gpu device or not.""" return os.environ.get('DEVICE_CATEGORY', None) == 'GPU' def is_npu_device(): """Return whether is npu device or not.""" return os.environ.get('DEVICE_CATEGORY', None) == 'NPU' def is_torch_backend(): """Return whether is pytorch backend or not.""" return os.environ.get('BACKEND_TYPE', None) == 'PYTORCH' def is_tf_backend(): """Return whether is tensorflow backend or not.""" return os.environ.get('BACKEND_TYPE', None) == 'TENSORFLOW' def is_ms_backend(): """Return whether is tensorflow backend or not.""" return os.environ.get('BACKEND_TYPE', None) == 'MINDSPORE' def get_devices(): """Get devices.""" device_id = os.environ.get('DEVICE_ID', 0) device_category = os.environ.get('DEVICE_CATEGORY', 'CPU') if device_category == 'GPU': device_category = 'cuda' if "CUDA_VISIBLE_DEVICES" in os.environ: device_id = int(os.environ["CUDA_VISIBLE_DEVICES"].split(",")[0]) return "{}:{}".format(device_category.lower(), device_id)
1,838
450
#pragma once #include <stdint.h> #include <stdbool.h> void ONNC_RUNTIME_min_float( void * restrict onnc_runtime_context ,const float * const * restrict input_data_0 ,int32_t input_data_0_ntensor ,const int32_t * input_data_0_ndim, const int32_t * const * restrict input_data_0_dims ,float * restrict output_min ,int32_t output_min_ndim, const int32_t * restrict output_min_dims );
157
2,221
<reponame>10088/flume<gh_stars>1000+ /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flume.node; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.time.LocalDateTime; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.apache.flume.CounterGroup; import org.apache.flume.conf.ConfigurationException; import org.apache.flume.conf.FlumeConfiguration; import org.apache.flume.lifecycle.LifecycleAware; import org.apache.flume.lifecycle.LifecycleState; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.eventbus.EventBus; import com.google.common.util.concurrent.ThreadFactoryBuilder; /** * <p> * A configuration provider that uses properties for specifying * configuration. The configurations follow the Java properties file syntax * rules specified at {@link Properties#load(java.io.Reader)}. Every * configuration value specified in the properties is prefixed by an * <em>Agent Name</em> which helps isolate an individual agent&apos;s namespace. * </p> * <p> * Valid configurations must observe the following rules for every agent * namespace. * <ul> * <li>For every &lt;agent name&gt; there must be three lists specified that * include <tt>&lt;agent name&gt;.sources</tt>, * <tt>&lt;agent name&gt;.sinks</tt>, and <tt>&lt;agent name&gt;.channels</tt>. * Each of these lists must contain a space separated list of names * corresponding to that particular entity.</li> * <li>For each source named in <tt>&lt;agent name&gt;.sources</tt>, there must * be a non-empty <tt>type</tt> attribute specified from the valid set of source * types. For example: * <tt>&lt;agent name&gt;.sources.&lt;source name&gt;.type = event</tt></li> * <li>For each source named in <tt>&lt;agent name&gt;.sources</tt>, there must * be a space-separated list of channel names that the source will associate * with during runtime. Each of these names must be contained in the channels * list specified by <tt>&lt;agent name&gt;.channels</tt>. For example: * <tt>&lt;agent name&gt;.sources.&lt;source name&gt;.channels = * &lt;channel-1 name&gt; &lt;channel-2 name&gt;</tt></li> * <li>For each source named in the <tt>&lt;agent name&gt;.sources</tt>, there * must be a <tt>runner</tt> namespace of configuration that configures the * associated source runner. For example: * <tt>&lt;agent name&gt;.sources.&lt;source name&gt;.runner.type = avro</tt>. * This namespace can also be used to configure other configuration of the * source runner as needed. For example: * <tt>&lt;agent name&gt;.sources.&lt;source name&gt;.runner.port = 10101</tt> * </li> * <li>For each source named in <tt>&lt;sources&gt;.sources</tt> there can * be an optional <tt>selector.type</tt> specified that identifies the type * of channel selector associated with the source. If not specified, the * default replicating channel selector is used. * </li><li>For each channel named in the <tt>&lt;agent name&gt;.channels</tt>, * there must be a non-empty <tt>type</tt> attribute specified from the valid * set of channel types. For example: * <tt>&lt;agent name&gt;.channels.&lt;channel name&gt;.type = mem</tt></li> * <li>For each sink named in the <tt>&lt;agent name&gt;.sinks</tt>, there must * be a non-empty <tt>type</tt> attribute specified from the valid set of sink * types. For example: * <tt>&lt;agent name&gt;.sinks.&lt;sink name&gt;.type = hdfs</tt></li> * <li>For each sink named in the <tt>&lt;agent name&gt;.sinks</tt>, there must * be a non-empty single-valued channel name specified as the value of the * <tt>channel</tt> attribute. This value must be contained in the channels list * specified by <tt>&lt;agent name&gt;.channels</tt>. For example: * <tt>&lt;agent name&gt;.sinks.&lt;sink name&gt;.channel = * &lt;channel name&gt;</tt></li> * <li>For each sink named in the <tt>&lt;agent name&gt;.sinks</tt>, there must * be a <tt>runner</tt> namespace of configuration that configures the * associated sink runner. For example: * <tt>&lt;agent name&gt;.sinks.&lt;sink name&gt;.runner.type = polling</tt>. * This namespace can also be used to configure other configuration of the sink * runner as needed. For example: * <tt>&lt;agent name&gt;.sinks.&lt;sink name&gt;.runner.polling.interval = * 60</tt></li> * <li>A fourth optional list <tt>&lt;agent name&gt;.sinkgroups</tt> * may be added to each agent, consisting of unique space separated names * for groups</li> * <li>Each sinkgroup must specify sinks, containing a list of all sinks * belonging to it. These cannot be shared by multiple groups. * Further, one can set a processor and behavioral parameters to determine * how sink selection is made via <tt>&lt;agent name&gt;.sinkgroups.&lt; * group name&lt.processor</tt>. For further detail refer to individual processor * documentation</li> * <li>Sinks not assigned to a group will be assigned to default single sink * groups.</li> * </ul> * <p> * Apart from the above required configuration values, each source, sink or * channel can have its own set of arbitrary configuration as required by the * implementation. Each of these configuration values are expressed by fully * namespace qualified configuration keys. For example, the configuration * property called <tt>capacity</tt> for a channel called <tt>ch1</tt> for the * agent named <tt>host1</tt> with value <tt>1000</tt> will be expressed as: * <tt>host1.channels.ch1.capacity = 1000</tt>. * </p> * <p> * Any information contained in the configuration file other than what pertains * to the configured agents, sources, sinks and channels via the explicitly * enumerated list of sources, sinks and channels per agent name are ignored by * this provider. Moreover, if any of the required configuration values are not * present in the configuration file for the configured entities, that entity * and anything that depends upon it is considered invalid and consequently not * configured. For example, if a channel is missing its <tt>type</tt> attribute, * it is considered misconfigured. Also, any sources or sinks that depend upon * this channel are also considered misconfigured and not initialized. * </p> * <p> * Example configuration file: * * <pre> * # * # Flume Configuration * # This file contains configuration for one Agent identified as host1. * # * * host1.sources = avroSource thriftSource * host1.channels = jdbcChannel * host1.sinks = hdfsSink * * # avroSource configuration * host1.sources.avroSource.type = org.apache.flume.source.AvroSource * host1.sources.avroSource.runner.type = avro * host1.sources.avroSource.runner.port = 11001 * host1.sources.avroSource.channels = jdbcChannel * host1.sources.avroSource.selector.type = replicating * * # thriftSource configuration * host1.sources.thriftSource.type = org.apache.flume.source.ThriftSource * host1.sources.thriftSource.runner.type = thrift * host1.sources.thriftSource.runner.port = 12001 * host1.sources.thriftSource.channels = jdbcChannel * * # jdbcChannel configuration * host1.channels.jdbcChannel.type = jdbc * host1.channels.jdbcChannel.jdbc.driver = com.mysql.jdbc.Driver * host1.channels.jdbcChannel.jdbc.connect.url = http://localhost/flumedb * host1.channels.jdbcChannel.jdbc.username = flume * host1.channels.jdbcChannel.jdbc.password = <PASSWORD> * * # hdfsSink configuration * host1.sinks.hdfsSink.type = hdfs * host1.sinks.hdfsSink.hdfs.path = hdfs://localhost/ * host1.sinks.hdfsSink.batchsize = 1000 * host1.sinks.hdfsSink.runner.type = polling * host1.sinks.hdfsSink.runner.polling.interval = 60 * </pre> * * </p> * * @see Properties#load(java.io.Reader) */ public class UriConfigurationProvider extends AbstractConfigurationProvider implements LifecycleAware { private static final Logger LOGGER = LoggerFactory.getLogger(UriConfigurationProvider.class); private final List<ConfigurationSource> configurationSources; private final File backupDirectory; private final EventBus eventBus; private final int interval; private final CounterGroup counterGroup; private LifecycleState lifecycleState = LifecycleState.IDLE; private ScheduledExecutorService executorService; public UriConfigurationProvider(String agentName, List<ConfigurationSource> sourceList, String backupDirectory, EventBus eventBus, int pollInterval) { super(agentName); this.configurationSources = sourceList; this.backupDirectory = backupDirectory != null ? new File(backupDirectory) : null; this.eventBus = eventBus; this.interval = pollInterval; counterGroup = new CounterGroup(); } @Override public void start() { if (eventBus != null && interval > 0) { executorService = Executors.newSingleThreadScheduledExecutor( new ThreadFactoryBuilder().setNameFormat("conf-file-poller-%d") .build()); WatcherRunnable watcherRunnable = new WatcherRunnable(configurationSources, counterGroup, eventBus); executorService.scheduleWithFixedDelay(watcherRunnable, 0, interval, TimeUnit.SECONDS); } lifecycleState = LifecycleState.START; } @Override public void stop() { if (executorService != null) { executorService.shutdown(); try { if (!executorService.awaitTermination(500, TimeUnit.MILLISECONDS)) { LOGGER.debug("File watcher has not terminated. Forcing shutdown of executor."); executorService.shutdownNow(); while (!executorService.awaitTermination(500, TimeUnit.MILLISECONDS)) { LOGGER.debug("Waiting for file watcher to terminate"); } } } catch (InterruptedException e) { LOGGER.debug("Interrupted while waiting for file watcher to terminate"); Thread.currentThread().interrupt(); } } lifecycleState = LifecycleState.STOP; } @Override public LifecycleState getLifecycleState() { return lifecycleState; } protected List<ConfigurationSource> getConfigurationSources() { return configurationSources; } @Override public FlumeConfiguration getFlumeConfiguration() { Map<String, String> configMap = null; Properties properties = new Properties(); for (ConfigurationSource configurationSource : configurationSources) { try (InputStream is = configurationSource.getInputStream()) { if (is != null) { switch (configurationSource.getExtension()) { case ConfigurationSource.JSON: case ConfigurationSource.YAML: case ConfigurationSource.XML: { LOGGER.warn("File extension type {} is unsupported", configurationSource.getExtension()); break; } default: { properties.load(is); break; } } } } catch (IOException ioe) { LOGGER.warn("Unable to load properties from {}: {}", configurationSource.getUri(), ioe.getMessage()); } if (properties.size() > 0) { configMap = MapResolver.resolveProperties(properties); } } if (configMap != null) { Properties props = new Properties(); props.putAll(configMap); if (backupDirectory != null) { if (backupDirectory.mkdirs()) { // This is only being logged to keep Spotbugs happy. We can't ignore the result of mkdirs. LOGGER.debug("Created directories for {}", backupDirectory.toString()); } File backupFile = getBackupFile(backupDirectory, getAgentName()); try (OutputStream os = new FileOutputStream(backupFile)) { props.store(os, "Backup created at " + LocalDateTime.now().toString()); } catch (IOException ioe) { LOGGER.warn("Unable to create backup properties file: {}" + ioe.getMessage()); } } } else { if (backupDirectory != null) { File backup = getBackupFile(backupDirectory, getAgentName()); if (backup.exists()) { Properties props = new Properties(); try (InputStream is = new FileInputStream(backup)) { LOGGER.warn("Unable to access primary configuration. Trying backup"); props.load(is); configMap = MapResolver.resolveProperties(props); } catch (IOException ex) { LOGGER.warn("Error reading backup file: {}", ex.getMessage()); } } } } if (configMap != null) { return new FlumeConfiguration(configMap); } else { LOGGER.error("No configuration could be found"); return null; } } private File getBackupFile(File backupDirectory, String agentName) { if (backupDirectory != null) { return new File(backupDirectory, "." + agentName + ".properties"); } return null; } private class WatcherRunnable implements Runnable { private List<ConfigurationSource> configurationSources; private final CounterGroup counterGroup; private final EventBus eventBus; public WatcherRunnable(List<ConfigurationSource> sources, CounterGroup counterGroup, EventBus eventBus) { this.configurationSources = sources; this.counterGroup = counterGroup; this.eventBus = eventBus; } @Override public void run() { LOGGER.debug("Checking for changes to sources"); counterGroup.incrementAndGet("uri.checks"); try { boolean isModified = false; for (ConfigurationSource source : configurationSources) { if (source.isModified()) { isModified = true; } } if (isModified) { eventBus.post(getConfiguration()); } } catch (ConfigurationException ex) { LOGGER.warn("Unable to update configuration: {}", ex.getMessage()); } } } }
4,986
460
/* This file is part of the KDE project. Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). This library is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 2.1 or 3 of the License. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #ifndef Phonon_GSTREAMER_MESSAGE_H #define Phonon_GSTREAMER_MESSAGE_H #include "common.h" #include <QtCore/QMetaType> #include <gst/gst.h> QT_BEGIN_NAMESPACE namespace Phonon { namespace Gstreamer { class MediaObject; class Message { public: Message(); Message(GstMessage* message, MediaObject *source); ~Message(); GstMessage* rawMessage() const; MediaObject *source() const; Message(const Message &other); private: GstMessage* m_message; MediaObject *m_source; }; } // ns gstreamer } // ns phonon QT_END_NAMESPACE Q_DECLARE_METATYPE(Phonon::Gstreamer::Message) #endif // Phonon_GSTREAMER_MESSAGE_H
552
600
<filename>engine/source/preprocessorlib/test/calculator.c /** * Calculates the value of the constant integer expressions that are used * in #if and #elif directives in the C preprocessor. * * @author Plombo * @date 6 March 2012 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include <assert.h> #include "pp_parser.h" #include "pp_expr.h" char *get_full_path(char *filename) { return filename; } // for testing infixparser and calculator int main() { char buffer[1024]; pp_expr *expression; pp_context ctx; pp_parser parser; TEXTPOS startpos = {0, 0}; while(1) { // get the user's input (i.e. the expression to evaluate) printf(">> "); fgets(buffer, sizeof(buffer), stdin); // end the program if the user enters a blank line, a null char, or Ctrl+D if(buffer[0] == '\r' || buffer[0] == '\n' || buffer[0] == '\0') { break; } else if(feof(stdin)) { printf("\n"); break; } // parse the input and correct the parsed tree for operator precedence pp_context_init(&ctx); pp_parser_init(&parser, &ctx, "<stdin>", buffer, startpos); expression = pp_expr_parse(&parser, false); if(expression == NULL) { pp_context_destroy(&ctx); continue; } pp_expr_fix_precedence(expression); // evaluate the expression and display the result printf("%i\n", pp_expr_eval(expression)); pp_expr_destroy(expression); pp_context_destroy(&ctx); } return 0; }
719
956
<reponame>ajitkhaparde/trex-core /* SPDX-License-Identifier: BSD-3-Clause * * Copyright 2017 NXP * */ #ifndef _DPAA_LOGS_H_ #define _DPAA_LOGS_H_ #include <rte_log.h> extern int dpaa_logtype_bus; #define DPAA_BUS_LOG(level, fmt, args...) \ rte_log(RTE_LOG_ ## level, dpaa_logtype_bus, "dpaa: " fmt "\n", ##args) #ifdef RTE_LIBRTE_DPAA_DEBUG_BUS #define DPAA_BUS_HWWARN(cond, fmt, args...) \ do {\ if (cond) \ DPAA_BUS_LOG(DEBUG, "WARN: " fmt, ##args); \ } while (0) #else #define DPAA_BUS_HWWARN(cond, fmt, args...) do { } while (0) #endif #define DPAA_BUS_DEBUG(fmt, args...) \ rte_log(RTE_LOG_DEBUG, dpaa_logtype_bus, "dpaa: %s(): " fmt "\n", \ __func__, ##args) #define BUS_INIT_FUNC_TRACE() DPAA_BUS_DEBUG(" >>") #define DPAA_BUS_INFO(fmt, args...) \ DPAA_BUS_LOG(INFO, fmt, ## args) #define DPAA_BUS_ERR(fmt, args...) \ DPAA_BUS_LOG(ERR, fmt, ## args) #define DPAA_BUS_WARN(fmt, args...) \ DPAA_BUS_LOG(WARNING, fmt, ## args) #endif /* _DPAA_LOGS_H_ */
465