text
stringlengths
2
99.9k
meta
dict
// Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go package ipv4 const ( sysIP_TOS = 0x1 sysIP_TTL = 0x2 sysIP_HDRINCL = 0x3 sysIP_OPTIONS = 0x4 sysIP_ROUTER_ALERT = 0x5 sysIP_RECVOPTS = 0x6 sysIP_RETOPTS = 0x7 sysIP_PKTINFO = 0x8 sysIP_PKTOPTIONS = 0x9 sysIP_MTU_DISCOVER = 0xa sysIP_RECVERR = 0xb sysIP_RECVTTL = 0xc sysIP_RECVTOS = 0xd sysIP_MTU = 0xe sysIP_FREEBIND = 0xf sysIP_TRANSPARENT = 0x13 sysIP_RECVRETOPTS = 0x7 sysIP_ORIGDSTADDR = 0x14 sysIP_RECVORIGDSTADDR = 0x14 sysIP_MINTTL = 0x15 sysIP_NODEFRAG = 0x16 sysIP_UNICAST_IF = 0x32 sysIP_MULTICAST_IF = 0x20 sysIP_MULTICAST_TTL = 0x21 sysIP_MULTICAST_LOOP = 0x22 sysIP_ADD_MEMBERSHIP = 0x23 sysIP_DROP_MEMBERSHIP = 0x24 sysIP_UNBLOCK_SOURCE = 0x25 sysIP_BLOCK_SOURCE = 0x26 sysIP_ADD_SOURCE_MEMBERSHIP = 0x27 sysIP_DROP_SOURCE_MEMBERSHIP = 0x28 sysIP_MSFILTER = 0x29 sysMCAST_JOIN_GROUP = 0x2a sysMCAST_LEAVE_GROUP = 0x2d sysMCAST_JOIN_SOURCE_GROUP = 0x2e sysMCAST_LEAVE_SOURCE_GROUP = 0x2f sysMCAST_BLOCK_SOURCE = 0x2b sysMCAST_UNBLOCK_SOURCE = 0x2c sysMCAST_MSFILTER = 0x30 sysIP_MULTICAST_ALL = 0x31 sysICMP_FILTER = 0x1 sysSO_EE_ORIGIN_NONE = 0x0 sysSO_EE_ORIGIN_LOCAL = 0x1 sysSO_EE_ORIGIN_ICMP = 0x2 sysSO_EE_ORIGIN_ICMP6 = 0x3 sysSO_EE_ORIGIN_TXSTATUS = 0x4 sysSO_EE_ORIGIN_TIMESTAMPING = 0x4 sysSOL_SOCKET = 0x1 sysSO_ATTACH_FILTER = 0x1a sizeofKernelSockaddrStorage = 0x80 sizeofSockaddrInet = 0x10 sizeofInetPktinfo = 0xc sizeofSockExtendedErr = 0x10 sizeofIPMreq = 0x8 sizeofIPMreqn = 0xc sizeofIPMreqSource = 0xc sizeofGroupReq = 0x84 sizeofGroupSourceReq = 0x104 sizeofICMPFilter = 0x4 ) type kernelSockaddrStorage struct { Family uint16 X__data [126]uint8 } type sockaddrInet struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ X__pad [8]uint8 } type inetPktinfo struct { Ifindex int32 Spec_dst [4]byte /* in_addr */ Addr [4]byte /* in_addr */ } type sockExtendedErr struct { Errno uint32 Origin uint8 Type uint8 Code uint8 Pad uint8 Info uint32 Data uint32 } type ipMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type ipMreqn struct { Multiaddr [4]byte /* in_addr */ Address [4]byte /* in_addr */ Ifindex int32 } type ipMreqSource struct { Multiaddr uint32 Interface uint32 Sourceaddr uint32 } type groupReq struct { Interface uint32 Group kernelSockaddrStorage } type groupSourceReq struct { Interface uint32 Group kernelSockaddrStorage Source kernelSockaddrStorage } type icmpFilter struct { Data uint32 } type sockFProg struct { Len uint16 Pad_cgo_0 [2]byte Filter *sockFilter } type sockFilter struct { Code uint16 Jt uint8 Jf uint8 K uint32 }
{ "pile_set_name": "Github" }
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include "hud.h" #include <vgui_controls/Controls.h> #include <Color.h> #include "c_vehicle_crane.h" #include "view.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" int ScreenTransform( const Vector& point, Vector& screen ); IMPLEMENT_CLIENTCLASS_DT(C_PropCrane, DT_PropCrane, CPropCrane) RecvPropEHandle( RECVINFO(m_hPlayer) ), RecvPropBool( RECVINFO(m_bMagnetOn) ), RecvPropBool( RECVINFO( m_bEnterAnimOn ) ), RecvPropBool( RECVINFO( m_bExitAnimOn ) ), RecvPropVector( RECVINFO( m_vecEyeExitEndpoint ) ), END_RECV_TABLE() BEGIN_DATADESC( C_PropCrane ) DEFINE_EMBEDDED( m_ViewSmoothingData ), END_DATADESC() #define ROLL_CURVE_ZERO 5 // roll less than this is clamped to zero #define ROLL_CURVE_LINEAR 45 // roll greater than this is copied out #define PITCH_CURVE_ZERO 10 // pitch less than this is clamped to zero #define PITCH_CURVE_LINEAR 45 // pitch greater than this is copied out // spline in between #define CRANE_FOV 75 //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- C_PropCrane::C_PropCrane( void ) { memset( &m_ViewSmoothingData, 0, sizeof( m_ViewSmoothingData ) ); m_ViewSmoothingData.pVehicle = this; m_ViewSmoothingData.flFOV = CRANE_FOV; } //----------------------------------------------------------------------------- // Purpose: // Input : updateType - //----------------------------------------------------------------------------- void C_PropCrane::PreDataUpdate( DataUpdateType_t updateType ) { BaseClass::PreDataUpdate( updateType ); m_hPrevPlayer = m_hPlayer; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void C_PropCrane::PostDataUpdate( DataUpdateType_t updateType ) { BaseClass::PostDataUpdate( updateType ); // Store off the old shadow direction if ( m_hPlayer && !m_hPrevPlayer ) { m_vecOldShadowDir = g_pClientShadowMgr->GetShadowDirection(); //Vector vecDown = m_vecOldShadowDir - Vector(0,0,0.5); //VectorNormalize( vecDown ); Vector vecDown = Vector(0,0,-1); g_pClientShadowMgr->SetShadowDirection( vecDown ); } else if ( !m_hPlayer && m_hPrevPlayer ) { g_pClientShadowMgr->SetShadowDirection( m_vecOldShadowDir ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- C_BaseCombatCharacter *C_PropCrane::GetPassenger( int nRole ) { if ( nRole == VEHICLE_ROLE_DRIVER ) return m_hPlayer.Get(); return NULL; } //----------------------------------------------------------------------------- // Returns the role of the passenger //----------------------------------------------------------------------------- int C_PropCrane::GetPassengerRole( C_BaseCombatCharacter *pPassenger ) { if ( m_hPlayer.Get() == pPassenger ) return VEHICLE_ROLE_DRIVER; return VEHICLE_ROLE_NONE; } //----------------------------------------------------------------------------- // Purpose: Modify the player view/camera while in a vehicle //----------------------------------------------------------------------------- void C_PropCrane::GetVehicleViewPosition( int nRole, Vector *pAbsOrigin, QAngle *pAbsAngles, float *pFOV /*=NULL*/ ) { SharedVehicleViewSmoothing( m_hPlayer, pAbsOrigin, pAbsAngles, m_bEnterAnimOn, m_bExitAnimOn, m_vecEyeExitEndpoint, &m_ViewSmoothingData, pFOV ); } //----------------------------------------------------------------------------- // Futzes with the clip planes //----------------------------------------------------------------------------- void C_PropCrane::GetVehicleClipPlanes( float &flZNear, float &flZFar ) const { // FIXME: Need something a better long-term, this fixes the buggy. flZNear = 6; } //----------------------------------------------------------------------------- // Renders hud elements //----------------------------------------------------------------------------- void C_PropCrane::DrawHudElements( ) { } //----------------------------------------------------------------------------- // Purpose: // Input : theMins - // theMaxs - //----------------------------------------------------------------------------- void C_PropCrane::GetRenderBounds( Vector &theMins, Vector &theMaxs ) { // This is kind of hacky:( Add 660.0 to the y coordinate of the bounding box to // allow for the full extension of the crane arm. BaseClass::GetRenderBounds( theMins, theMaxs ); theMaxs.y += 660.0f; }
{ "pile_set_name": "Github" }
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_int64_t_memmove_73b.cpp Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805.label.xml Template File: sources-sink-73b.tmpl.cpp */ /* * @description * CWE: 122 Heap Based Buffer Overflow * BadSource: Allocate using new[] and set data pointer to a small buffer * GoodSource: Allocate using new[] and set data pointer to a large buffer * Sinks: memmove * BadSink : Copy int64_t array to data using memmove * Flow Variant: 73 Data flow: data passed in a list from one function to another in different source files * * */ #include "std_testcase.h" #include <list> using namespace std; namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_int64_t_memmove_73 { #ifndef OMITBAD void badSink(list<int64_t *> dataList) { /* copy data out of dataList */ int64_t * data = dataList.back(); { int64_t source[100] = {0}; /* fill with 0's */ /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */ memmove(data, source, 100*sizeof(int64_t)); printLongLongLine(data[0]); delete [] data; } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void goodG2BSink(list<int64_t *> dataList) { int64_t * data = dataList.back(); { int64_t source[100] = {0}; /* fill with 0's */ /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */ memmove(data, source, 100*sizeof(int64_t)); printLongLongLine(data[0]); delete [] data; } } #endif /* OMITGOOD */ } /* close namespace */
{ "pile_set_name": "Github" }
# SPDX-License-Identifier: GPL-2.0-only # # Copyright (C) ST-Ericsson SA 2010 # Author: Shujuan Chen (shujuan.chen@stericsson.com) # ifdef CONFIG_CRYPTO_DEV_UX500_DEBUG CFLAGS_hash_core.o := -DDEBUG endif obj-$(CONFIG_CRYPTO_DEV_UX500_HASH) += ux500_hash.o ux500_hash-objs := hash_core.o
{ "pile_set_name": "Github" }
.navicon-widgets { background-image:url(images/menu.widgets.png) !important; } .navicon-widgets:hover { background-position:0 -30px !important; }
{ "pile_set_name": "Github" }
#!/bin/bash ## give a module name, grep the codebase for calls to that module ## create a list of beam files and feed it to dialyzer pushd $(dirname $0) > /dev/null cd $(pwd -P)/.. if [ -z ${ERL_FILES+x} ]; then MODULE=$1 ERL_FILES=$(grep -rl "$1:" {core,applications} --include "*.erl" --exclude="\*pqc.erl" | grep -v "test/") MOD_BEAM=$(find {core,applications} -name "$MODULE.beam") echo "dialyzing usages of $MODULE" shift fi BEAM_FILES=() BEAM="" for ERL in $ERL_FILES; do APP_PATH=${ERL%%/src*} ## core/APP or applications/APP BASENAME=${ERL##*/} ## file.erl BEAM_FILE=${BASENAME/erl/beam} ## file.beam BEAM="$APP_PATH/ebin/$BEAM_FILE" BEAM_FILES+=($BEAM) done BEAM_FILES+=("core/kazoo_stdlib/ebin/kz_types.beam") ARGS=${BEAM_FILES[@]} dialyzer --plt .kazoo.plt $MOD_BEAM $ARGS $@ popd > /dev/null
{ "pile_set_name": "Github" }
#include <vector> #include "caffe/layers/im2col_layer.hpp" #include "caffe/util/im2col.hpp" namespace caffe { template <typename Dtype> void Im2colLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { ConvolutionParameter conv_param = this->layer_param_.convolution_param(); force_nd_im2col_ = conv_param.force_nd_im2col(); const int input_num_dims = bottom[0]->shape().size(); channel_axis_ = bottom[0]->CanonicalAxisIndex(conv_param.axis()); const int first_spatial_dim = channel_axis_ + 1; num_spatial_axes_ = input_num_dims - first_spatial_dim; CHECK_GE(num_spatial_axes_, 1); vector<int> dim_blob_shape(1, num_spatial_axes_); // Setup filter kernel dimensions (kernel_shape_). kernel_shape_.Reshape(dim_blob_shape); int* kernel_shape_data = kernel_shape_.mutable_cpu_data(); if (conv_param.has_kernel_h() || conv_param.has_kernel_w()) { CHECK_EQ(num_spatial_axes_, 2) << "kernel_h & kernel_w can only be used for 2D convolution."; CHECK_EQ(0, conv_param.kernel_size_size()) << "Either kernel_size or kernel_h/w should be specified; not both."; kernel_shape_data[0] = conv_param.kernel_h(); kernel_shape_data[1] = conv_param.kernel_w(); } else { const int num_kernel_dims = conv_param.kernel_size_size(); CHECK(num_kernel_dims == 1 || num_kernel_dims == num_spatial_axes_) << "kernel_size must be specified once, or once per spatial dimension " << "(kernel_size specified " << num_kernel_dims << " times; " << num_spatial_axes_ << " spatial dims);"; for (int i = 0; i < num_spatial_axes_; ++i) { kernel_shape_data[i] = conv_param.kernel_size((num_kernel_dims == 1) ? 0 : i); } } for (int i = 0; i < num_spatial_axes_; ++i) { CHECK_GT(kernel_shape_data[i], 0) << "Filter dimensions must be nonzero."; } // Setup stride dimensions (stride_). stride_.Reshape(dim_blob_shape); int* stride_data = stride_.mutable_cpu_data(); if (conv_param.has_stride_h() || conv_param.has_stride_w()) { CHECK_EQ(num_spatial_axes_, 2) << "stride_h & stride_w can only be used for 2D convolution."; CHECK_EQ(0, conv_param.stride_size()) << "Either stride or stride_h/w should be specified; not both."; stride_data[0] = conv_param.stride_h(); stride_data[1] = conv_param.stride_w(); } else { const int num_stride_dims = conv_param.stride_size(); CHECK(num_stride_dims == 0 || num_stride_dims == 1 || num_stride_dims == num_spatial_axes_) << "stride must be specified once, or once per spatial dimension " << "(stride specified " << num_stride_dims << " times; " << num_spatial_axes_ << " spatial dims);"; const int kDefaultStride = 1; for (int i = 0; i < num_spatial_axes_; ++i) { stride_data[i] = (num_stride_dims == 0) ? kDefaultStride : conv_param.stride((num_stride_dims == 1) ? 0 : i); CHECK_GT(stride_data[i], 0) << "Stride dimensions must be nonzero."; } } // Setup pad dimensions (pad_). pad_.Reshape(dim_blob_shape); int* pad_data = pad_.mutable_cpu_data(); if (conv_param.has_pad_h() || conv_param.has_pad_w()) { CHECK_EQ(num_spatial_axes_, 2) << "pad_h & pad_w can only be used for 2D convolution."; CHECK_EQ(0, conv_param.pad_size()) << "Either pad or pad_h/w should be specified; not both."; pad_data[0] = conv_param.pad_h(); pad_data[1] = conv_param.pad_w(); } else { const int num_pad_dims = conv_param.pad_size(); CHECK(num_pad_dims == 0 || num_pad_dims == 1 || num_pad_dims == num_spatial_axes_) << "pad must be specified once, or once per spatial dimension " << "(pad specified " << num_pad_dims << " times; " << num_spatial_axes_ << " spatial dims);"; const int kDefaultPad = 0; for (int i = 0; i < num_spatial_axes_; ++i) { pad_data[i] = (num_pad_dims == 0) ? kDefaultPad : conv_param.pad((num_pad_dims == 1) ? 0 : i); } } // Setup dilation dimensions (dilation_). dilation_.Reshape(dim_blob_shape); int* dilation_data = dilation_.mutable_cpu_data(); const int num_dilation_dims = conv_param.dilation_size(); CHECK(num_dilation_dims == 0 || num_dilation_dims == 1 || num_dilation_dims == num_spatial_axes_) << "dilation must be specified once, or once per spatial dimension " << "(dilation specified " << num_dilation_dims << " times; " << num_spatial_axes_ << " spatial dims)."; const int kDefaultDilation = 1; for (int i = 0; i < num_spatial_axes_; ++i) { dilation_data[i] = (num_dilation_dims == 0) ? kDefaultDilation : conv_param.dilation((num_dilation_dims == 1) ? 0 : i); } } template <typename Dtype> void Im2colLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { vector<int> top_shape = bottom[0]->shape(); const int* kernel_shape_data = kernel_shape_.cpu_data(); const int* stride_data = stride_.cpu_data(); const int* pad_data = pad_.cpu_data(); const int* dilation_data = dilation_.cpu_data(); for (int i = 0; i < num_spatial_axes_; ++i) { top_shape[channel_axis_] *= kernel_shape_data[i]; const int input_dim = bottom[0]->shape(channel_axis_ + i + 1); const int kernel_extent = dilation_data[i] * (kernel_shape_data[i] - 1) + 1; const int output_dim = (input_dim + 2 * pad_data[i] - kernel_extent) / stride_data[i] + 1; top_shape[channel_axis_ + i + 1] = output_dim; } top[0]->Reshape(top_shape); num_ = bottom[0]->count(0, channel_axis_); bottom_dim_ = bottom[0]->count(channel_axis_); top_dim_ = top[0]->count(channel_axis_); channels_ = bottom[0]->shape(channel_axis_); } template <typename Dtype> void Im2colLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { const Dtype* bottom_data = bottom[0]->cpu_data(); Dtype* top_data = top[0]->mutable_cpu_data(); for (int n = 0; n < num_; ++n) { DCHECK_EQ(bottom[0]->shape().size() - channel_axis_, num_spatial_axes_ + 1); DCHECK_EQ(top[0]->shape().size() - channel_axis_, num_spatial_axes_ + 1); DCHECK_EQ(kernel_shape_.count(), num_spatial_axes_); DCHECK_EQ(pad_.count(), num_spatial_axes_); DCHECK_EQ(stride_.count(), num_spatial_axes_); DCHECK_EQ(dilation_.count(), num_spatial_axes_); if (!force_nd_im2col_ && num_spatial_axes_ == 2) { im2col_cpu(bottom_data + n * bottom_dim_, channels_, bottom[0]->shape(channel_axis_ + 1), bottom[0]->shape(channel_axis_ + 2), kernel_shape_.cpu_data()[0], kernel_shape_.cpu_data()[1], pad_.cpu_data()[0], pad_.cpu_data()[1], stride_.cpu_data()[0], stride_.cpu_data()[1], dilation_.cpu_data()[0], dilation_.cpu_data()[1], top_data + n * top_dim_); } else { im2col_nd_cpu(bottom_data + n * bottom_dim_, num_spatial_axes_, bottom[0]->shape().data() + channel_axis_, top[0]->shape().data() + channel_axis_, kernel_shape_.cpu_data(), pad_.cpu_data(), stride_.cpu_data(), dilation_.cpu_data(), top_data + n * top_dim_); } } } template <typename Dtype> void Im2colLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { const Dtype* top_diff = top[0]->cpu_diff(); Dtype* bottom_diff = bottom[0]->mutable_cpu_diff(); for (int n = 0; n < num_; ++n) { if (!force_nd_im2col_ && num_spatial_axes_ == 2) { col2im_cpu(top_diff + n * top_dim_, channels_, bottom[0]->shape(channel_axis_ + 1), bottom[0]->shape(channel_axis_ + 2), kernel_shape_.cpu_data()[0], kernel_shape_.cpu_data()[1], pad_.cpu_data()[0], pad_.cpu_data()[1], stride_.cpu_data()[0], stride_.cpu_data()[1], dilation_.cpu_data()[0], dilation_.cpu_data()[1], bottom_diff + n * bottom_dim_); } else { col2im_nd_cpu(top_diff + n * top_dim_, num_spatial_axes_, bottom[0]->shape().data() + channel_axis_, top[0]->shape().data() + channel_axis_, kernel_shape_.cpu_data(), pad_.cpu_data(), stride_.cpu_data(), dilation_.cpu_data(), bottom_diff + n * bottom_dim_); } } } #ifdef CPU_ONLY STUB_GPU(Im2colLayer); #endif INSTANTIATE_CLASS(Im2colLayer); REGISTER_LAYER_CLASS(Im2col); } // namespace caffe
{ "pile_set_name": "Github" }
/*! * angular-translate - v2.11.1 - 2016-07-17 * * Copyright (c) 2016 The angular-translate team, Pascal Precht; Licensed MIT */ (function (root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module unless amdModuleId is set define(["messageformat"], function (a0) { return (factory(a0)); }); } else if (typeof exports === 'object') { // Node. Does not work with strict CommonJS, but // only CommonJS-like environments that support module.exports, // like Node. module.exports = factory(require("messageformat")); } else { factory(MessageFormat); } }(this, function (MessageFormat) { $translateMessageFormatInterpolation.$inject = ['$translateSanitization', '$cacheFactory', 'TRANSLATE_MF_INTERPOLATION_CACHE']; angular.module('pascalprecht.translate') /** * @ngdoc property * @name pascalprecht.translate.TRANSLATE_MF_INTERPOLATION_CACHE * @requires TRANSLATE_MF_INTERPOLATION_CACHE * * @description * Uses MessageFormat.js to interpolate strings against some values. */ .constant('TRANSLATE_MF_INTERPOLATION_CACHE', '$translateMessageFormatInterpolation') /** * @ngdoc object * @name pascalprecht.translate.$translateMessageFormatInterpolation * @requires pascalprecht.translate.TRANSLATE_MF_INTERPOLATION_CACHE * * @description * Uses MessageFormat.js to interpolate strings against some values. * * Be aware to configure a proper sanitization strategy. * * See also: * * {@link pascalprecht.translate.$translateSanitization} * * {@link https://github.com/SlexAxton/messageformat.js} * * @return {object} $translateMessageFormatInterpolation Interpolator service */ .factory('$translateMessageFormatInterpolation', $translateMessageFormatInterpolation); function $translateMessageFormatInterpolation($translateSanitization, $cacheFactory, TRANSLATE_MF_INTERPOLATION_CACHE) { 'use strict'; var $translateInterpolator = {}, $cache = $cacheFactory.get(TRANSLATE_MF_INTERPOLATION_CACHE), // instantiate with default locale (which is 'en') $mf = new MessageFormat('en'), $identifier = 'messageformat'; if (!$cache) { // create cache if it doesn't exist already $cache = $cacheFactory(TRANSLATE_MF_INTERPOLATION_CACHE); } $cache.put('en', $mf); /** * @ngdoc function * @name pascalprecht.translate.$translateMessageFormatInterpolation#setLocale * @methodOf pascalprecht.translate.$translateMessageFormatInterpolation * * @description * Sets current locale (this is currently not use in this interpolation). * * @param {string} locale Language key or locale. */ $translateInterpolator.setLocale = function (locale) { $mf = $cache.get(locale); if (!$mf) { $mf = new MessageFormat(locale); $cache.put(locale, $mf); } }; /** * @ngdoc function * @name pascalprecht.translate.$translateMessageFormatInterpolation#getInterpolationIdentifier * @methodOf pascalprecht.translate.$translateMessageFormatInterpolation * * @description * Returns an identifier for this interpolation service. * * @returns {string} $identifier */ $translateInterpolator.getInterpolationIdentifier = function () { return $identifier; }; /** * @deprecated will be removed in 3.0 * @see {@link pascalprecht.translate.$translateSanitization} */ $translateInterpolator.useSanitizeValueStrategy = function (value) { $translateSanitization.useStrategy(value); return this; }; /** * @ngdoc function * @name pascalprecht.translate.$translateMessageFormatInterpolation#interpolate * @methodOf pascalprecht.translate.$translateMessageFormatInterpolation * * @description * Interpolates given string against given interpolate params using MessageFormat.js. * * @returns {string} interpolated string. */ $translateInterpolator.interpolate = function (string, interpolationParams) { interpolationParams = interpolationParams || {}; interpolationParams = $translateSanitization.sanitize(interpolationParams, 'params'); var compiledFunction = $cache.get('mf:' + string); // if given string wasn't compiled yet, we do so now and never have to do it again if (!compiledFunction) { // Ensure explicit type if possible // MessageFormat checks the actual type (i.e. for amount based conditions) for (var key in interpolationParams) { if (interpolationParams.hasOwnProperty(key)) { // ensure number var number = parseInt(interpolationParams[key], 10); if (angular.isNumber(number) && ('' + number) === interpolationParams[key]) { interpolationParams[key] = number; } } } compiledFunction = $mf.compile(string); $cache.put('mf:' + string, compiledFunction); } var interpolatedText = compiledFunction(interpolationParams); return $translateSanitization.sanitize(interpolatedText, 'text'); }; return $translateInterpolator; } $translateMessageFormatInterpolation.displayName = '$translateMessageFormatInterpolation'; return 'pascalprecht.translate'; }));
{ "pile_set_name": "Github" }
/* Copyright 2005-2013 Intel Corporation. All Rights Reserved. This file is part of Threading Building Blocks. Threading Building Blocks is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. Threading Building Blocks 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 Threading Building Blocks; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA As a special exception, you may use this file as part of a free software library without restriction. Specifically, if other files instantiate templates or use macros or inline functions from this file, or you compile this file and link it with other files to produce an executable, this file does not by itself cause the resulting executable to be covered by the GNU General Public License. This exception does not however invalidate any other reasons why the executable file might be covered by the GNU General Public License. */ #ifndef __TBB_concurrent_priority_queue_H #define __TBB_concurrent_priority_queue_H #include "atomic.h" #include "cache_aligned_allocator.h" #include "tbb_exception.h" #include "tbb_stddef.h" #include "tbb_profiling.h" #include "internal/_aggregator_impl.h" #include <vector> #include <iterator> #include <functional> namespace tbb { namespace interface5 { using namespace tbb::internal; //! Concurrent priority queue template <typename T, typename Compare=std::less<T>, typename A=cache_aligned_allocator<T> > class concurrent_priority_queue { public: //! Element type in the queue. typedef T value_type; //! Reference type typedef T& reference; //! Const reference type typedef const T& const_reference; //! Integral type for representing size of the queue. typedef size_t size_type; //! Difference type for iterator typedef ptrdiff_t difference_type; //! Allocator type typedef A allocator_type; //! Constructs a new concurrent_priority_queue with default capacity explicit concurrent_priority_queue(const allocator_type& a = allocator_type()) : mark(0), my_size(0), data(a) { my_aggregator.initialize_handler(my_functor_t(this)); } //! Constructs a new concurrent_priority_queue with init_sz capacity explicit concurrent_priority_queue(size_type init_capacity, const allocator_type& a = allocator_type()) : mark(0), my_size(0), data(a) { data.reserve(init_capacity); my_aggregator.initialize_handler(my_functor_t(this)); } //! [begin,end) constructor template<typename InputIterator> concurrent_priority_queue(InputIterator begin, InputIterator end, const allocator_type& a = allocator_type()) : data(begin, end, a) { mark = 0; my_aggregator.initialize_handler(my_functor_t(this)); heapify(); my_size = data.size(); } //! Copy constructor /** This operation is unsafe if there are pending concurrent operations on the src queue. */ explicit concurrent_priority_queue(const concurrent_priority_queue& src) : mark(src.mark), my_size(src.my_size), data(src.data.begin(), src.data.end(), src.data.get_allocator()) { my_aggregator.initialize_handler(my_functor_t(this)); heapify(); } //! Copy constructor with specific allocator /** This operation is unsafe if there are pending concurrent operations on the src queue. */ concurrent_priority_queue(const concurrent_priority_queue& src, const allocator_type& a) : mark(src.mark), my_size(src.my_size), data(src.data.begin(), src.data.end(), a) { my_aggregator.initialize_handler(my_functor_t(this)); heapify(); } //! Assignment operator /** This operation is unsafe if there are pending concurrent operations on the src queue. */ concurrent_priority_queue& operator=(const concurrent_priority_queue& src) { if (this != &src) { std::vector<value_type, allocator_type>(src.data.begin(), src.data.end(), src.data.get_allocator()).swap(data); mark = src.mark; my_size = src.my_size; } return *this; } //! Returns true if empty, false otherwise /** Returned value may not reflect results of pending operations. This operation reads shared data and will trigger a race condition. */ bool empty() const { return size()==0; } //! Returns the current number of elements contained in the queue /** Returned value may not reflect results of pending operations. This operation reads shared data and will trigger a race condition. */ size_type size() const { return __TBB_load_with_acquire(my_size); } //! Pushes elem onto the queue, increasing capacity of queue if necessary /** This operation can be safely used concurrently with other push, try_pop or reserve operations. */ void push(const_reference elem) { cpq_operation op_data(elem, PUSH_OP); my_aggregator.execute(&op_data); if (op_data.status == FAILED) // exception thrown throw_exception(eid_bad_alloc); } //! Gets a reference to and removes highest priority element /** If a highest priority element was found, sets elem and returns true, otherwise returns false. This operation can be safely used concurrently with other push, try_pop or reserve operations. */ bool try_pop(reference elem) { cpq_operation op_data(POP_OP); op_data.elem = &elem; my_aggregator.execute(&op_data); return op_data.status==SUCCEEDED; } //! Clear the queue; not thread-safe /** This operation is unsafe if there are pending concurrent operations on the queue. Resets size, effectively emptying queue; does not free space. May not clear elements added in pending operations. */ void clear() { data.clear(); mark = 0; my_size = 0; } //! Swap this queue with another; not thread-safe /** This operation is unsafe if there are pending concurrent operations on the queue. */ void swap(concurrent_priority_queue& q) { data.swap(q.data); std::swap(mark, q.mark); std::swap(my_size, q.my_size); } //! Return allocator object allocator_type get_allocator() const { return data.get_allocator(); } private: enum operation_type {INVALID_OP, PUSH_OP, POP_OP}; enum operation_status { WAIT=0, SUCCEEDED, FAILED }; class cpq_operation : public aggregated_operation<cpq_operation> { public: operation_type type; union { value_type *elem; size_type sz; }; cpq_operation(const_reference e, operation_type t) : type(t), elem(const_cast<value_type*>(&e)) {} cpq_operation(operation_type t) : type(t) {} }; class my_functor_t { concurrent_priority_queue<T, Compare, A> *cpq; public: my_functor_t() {} my_functor_t(concurrent_priority_queue<T, Compare, A> *cpq_) : cpq(cpq_) {} void operator()(cpq_operation* op_list) { cpq->handle_operations(op_list); } }; aggregator< my_functor_t, cpq_operation> my_aggregator; //! Padding added to avoid false sharing char padding1[NFS_MaxLineSize - sizeof(aggregator< my_functor_t, cpq_operation >)]; //! The point at which unsorted elements begin size_type mark; __TBB_atomic size_type my_size; Compare compare; //! Padding added to avoid false sharing char padding2[NFS_MaxLineSize - (2*sizeof(size_type)) - sizeof(Compare)]; //! Storage for the heap of elements in queue, plus unheapified elements /** data has the following structure: binary unheapified heap elements ____|_______|____ | | | v v v [_|...|_|_|...|_| |...| ] 0 ^ ^ ^ | | |__capacity | |__my_size |__mark Thus, data stores the binary heap starting at position 0 through mark-1 (it may be empty). Then there are 0 or more elements that have not yet been inserted into the heap, in positions mark through my_size-1. */ std::vector<value_type, allocator_type> data; void handle_operations(cpq_operation *op_list) { cpq_operation *tmp, *pop_list=NULL; __TBB_ASSERT(mark == data.size(), NULL); // First pass processes all constant (amortized; reallocation may happen) time pushes and pops. while (op_list) { // ITT note: &(op_list->status) tag is used to cover accesses to op_list // node. This thread is going to handle the operation, and so will acquire it // and perform the associated operation w/o triggering a race condition; the // thread that created the operation is waiting on the status field, so when // this thread is done with the operation, it will perform a // store_with_release to give control back to the waiting thread in // aggregator::insert_operation. call_itt_notify(acquired, &(op_list->status)); __TBB_ASSERT(op_list->type != INVALID_OP, NULL); tmp = op_list; op_list = itt_hide_load_word(op_list->next); if (tmp->type == PUSH_OP) { __TBB_TRY { data.push_back(*(tmp->elem)); __TBB_store_with_release(my_size, my_size+1); itt_store_word_with_release(tmp->status, uintptr_t(SUCCEEDED)); } __TBB_CATCH(...) { itt_store_word_with_release(tmp->status, uintptr_t(FAILED)); } } else { // tmp->type == POP_OP __TBB_ASSERT(tmp->type == POP_OP, NULL); if (mark < data.size() && compare(data[0], data[data.size()-1])) { // there are newly pushed elems and the last one // is higher than top *(tmp->elem) = data[data.size()-1]; // copy the data __TBB_store_with_release(my_size, my_size-1); itt_store_word_with_release(tmp->status, uintptr_t(SUCCEEDED)); data.pop_back(); __TBB_ASSERT(mark<=data.size(), NULL); } else { // no convenient item to pop; postpone itt_hide_store_word(tmp->next, pop_list); pop_list = tmp; } } } // second pass processes pop operations while (pop_list) { tmp = pop_list; pop_list = itt_hide_load_word(pop_list->next); __TBB_ASSERT(tmp->type == POP_OP, NULL); if (data.empty()) { itt_store_word_with_release(tmp->status, uintptr_t(FAILED)); } else { __TBB_ASSERT(mark<=data.size(), NULL); if (mark < data.size() && compare(data[0], data[data.size()-1])) { // there are newly pushed elems and the last one is // higher than top *(tmp->elem) = data[data.size()-1]; // copy the data __TBB_store_with_release(my_size, my_size-1); itt_store_word_with_release(tmp->status, uintptr_t(SUCCEEDED)); data.pop_back(); } else { // extract top and push last element down heap *(tmp->elem) = data[0]; // copy the data __TBB_store_with_release(my_size, my_size-1); itt_store_word_with_release(tmp->status, uintptr_t(SUCCEEDED)); reheap(); } } } // heapify any leftover pushed elements before doing the next // batch of operations if (mark<data.size()) heapify(); __TBB_ASSERT(mark == data.size(), NULL); } //! Merge unsorted elements into heap void heapify() { if (!mark && data.size()>0) mark = 1; for (; mark<data.size(); ++mark) { // for each unheapified element under size size_type cur_pos = mark; value_type to_place = data[mark]; do { // push to_place up the heap size_type parent = (cur_pos-1)>>1; if (!compare(data[parent], to_place)) break; data[cur_pos] = data[parent]; cur_pos = parent; } while( cur_pos ); data[cur_pos] = to_place; } } //! Re-heapify after an extraction /** Re-heapify by pushing last element down the heap from the root. */ void reheap() { size_type cur_pos=0, child=1; while (child < mark) { size_type target = child; if (child+1 < mark && compare(data[child], data[child+1])) ++target; // target now has the higher priority child if (compare(data[target], data[data.size()-1])) break; data[cur_pos] = data[target]; cur_pos = target; child = (cur_pos<<1)+1; } data[cur_pos] = data[data.size()-1]; data.pop_back(); if (mark > data.size()) mark = data.size(); } }; } // namespace interface5 using interface5::concurrent_priority_queue; } // namespace tbb #endif /* __TBB_concurrent_priority_queue_H */
{ "pile_set_name": "Github" }
import React from 'react'; import * as TestUtils from 'react-dom/test-utils'; import UserLayout from '../../src/components/UserLayout'; function shallowRender(Component) { const render = TestUtils.createRenderer(); render.render(<Component />); return render.getRenderOutput(); } describe('title', () => { it('UserLayout\'s title should be Fabric Desktop', () => { const userLayout = shallowRender(UserLayout); expect(userLayout.props.children[1].props.children.props.children[0].type).toBe('div'); expect(userLayout.props.children[1].props.children.props.children[0].props.children.props.children).toBe('Fabric Desktop'); }); }); describe('Some variable should change with the value of the input box', () => { const userLayout = TestUtils.renderIntoDocument(<UserLayout />); let inputItem = TestUtils.scryRenderedDOMComponentsWithTag(userLayout, 'input'); inputItem = inputItem.slice(1, inputItem.length); it('peerGrpcUrl', () => { const input = inputItem[0]; input.value = 'grpc://127.0.1.1:7051'; TestUtils.Simulate.change(input); TestUtils.Simulate.keyDown(input, { key: 'Enter', keyCode: 13, which: 13 }); expect(input.value).toBe('grpc://127.0.1.1:7051'); expect(userLayout.state.peerGrpcUrl).toBe('grpc://127.0.1.1:7051'); }); it('peerEventUrl', () => { const input = inputItem[1]; input.value = 'grpc://127.0.1.1:7053'; TestUtils.Simulate.change(input); TestUtils.Simulate.keyDown(input, { key: 'Enter', keyCode: 13, which: 13 }); expect(input.value).toBe('grpc://127.0.1.1:7053'); expect(userLayout.state.peerEventUrl).toBe('grpc://127.0.1.1:7053'); }); it('ordererUrl', () => { const input = inputItem[2]; input.value = 'grpc://127.0.1.1:7050'; TestUtils.Simulate.change(input); TestUtils.Simulate.keyDown(input, { key: 'Enter', keyCode: 13, which: 13 }); expect(input.value).toBe('grpc://127.0.1.1:7050'); expect(userLayout.state.ordererUrl).toBe('grpc://127.0.1.1:7050'); }); it('username', () => { const input = inputItem[3]; input.value = 'testOrg1Admin'; TestUtils.Simulate.change(input); TestUtils.Simulate.keyDown(input, { key: 'Enter', keyCode: 13, which: 13 }); expect(input.value).toBe('testOrg1Admin'); expect(userLayout.state.username).toBe('testOrg1Admin'); }); }); describe('Some variable should be the file path selected by the selector', () => { const userLayout = TestUtils.renderIntoDocument(<UserLayout />); const inputItem = TestUtils.scryRenderedDOMComponentsWithTag(userLayout, 'input'); it('certPath', () => { const input = inputItem[4]; input.files.path = '/home/hjs/admin/a05e3c5fc2c10dee7f20a2750a4397c456918526284608ca5f7a12eda496e1e1_sk'; expect(input.files.path).toBe('/home/hjs/admin/a05e3c5fc2c10dee7f20a2750a4397c456918526284608ca5f7a12eda496e1e1_sk'); }); }); describe('fill inputs by config file', () => { const userLayout = TestUtils.renderIntoDocument(<UserLayout />); it('import config file', () => { }); });
{ "pile_set_name": "Github" }
var test = require('tape'); var balanced = require('..'); test('balanced', function(t) { t.deepEqual(balanced('{', '}', 'pre{in{nest}}post'), { start: 3, end: 12, pre: 'pre', body: 'in{nest}', post: 'post' }); t.deepEqual(balanced('{', '}', '{{{{{{{{{in}post'), { start: 8, end: 11, pre: '{{{{{{{{', body: 'in', post: 'post' }); t.deepEqual(balanced('{', '}', 'pre{body{in}post'), { start: 8, end: 11, pre: 'pre{body', body: 'in', post: 'post' }); t.deepEqual(balanced('{', '}', 'pre}{in{nest}}post'), { start: 4, end: 13, pre: 'pre}', body: 'in{nest}', post: 'post' }); t.deepEqual(balanced('{', '}', 'pre{body}between{body2}post'), { start: 3, end: 8, pre: 'pre', body: 'body', post: 'between{body2}post' }); t.notOk(balanced('{', '}', 'nope'), 'should be notOk'); t.deepEqual(balanced('<b>', '</b>', 'pre<b>in<b>nest</b></b>post'), { start: 3, end: 19, pre: 'pre', body: 'in<b>nest</b>', post: 'post' }); t.deepEqual(balanced('<b>', '</b>', 'pre</b><b>in<b>nest</b></b>post'), { start: 7, end: 23, pre: 'pre</b>', body: 'in<b>nest</b>', post: 'post' }); t.end(); });
{ "pile_set_name": "Github" }
using System; using NetRuntimeSystem = System; using System.ComponentModel; using NetOffice.Attributes; namespace NetOffice.ExcelApi { /// <summary> /// DispatchInterface Interior /// SupportByVersion Excel, 9,10,11,12,14,15,16 /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff196598.aspx </remarks> [SupportByVersion("Excel", 9,10,11,12,14,15,16)] [EntityType(EntityType.IsDispatchInterface)] public class Interior : COMObject { #pragma warning disable #region Type Information /// <summary> /// Instance Type /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden] public override Type InstanceType { get { return LateBindingApiWrapperType; } } private static Type _type; [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public static Type LateBindingApiWrapperType { get { if (null == _type) _type = typeof(Interior); return _type; } } #endregion #region Ctor /// <param name="factory">current used factory core</param> /// <param name="parentObject">object there has created the proxy</param> /// <param name="proxyShare">proxy share instead if com proxy</param> public Interior(Core factory, ICOMObject parentObject, COMProxyShare proxyShare) : base(factory, parentObject, proxyShare) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> public Interior(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Interior(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Interior(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Interior(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType) { } ///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Interior(ICOMObject replacedObject) : base(replacedObject) { } [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Interior() : base() { } /// <param name="progId">registered progID</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Interior(string progId) : base(progId) { } #endregion #region Properties /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff839431.aspx </remarks> [SupportByVersion("Excel", 9,10,11,12,14,15,16)] public NetOffice.ExcelApi.Application Application { get { return Factory.ExecuteKnownReferencePropertyGet<NetOffice.ExcelApi.Application>(this, "Application", NetOffice.ExcelApi.Application.LateBindingApiWrapperType); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff840138.aspx </remarks> [SupportByVersion("Excel", 9,10,11,12,14,15,16)] public NetOffice.ExcelApi.Enums.XlCreator Creator { get { return Factory.ExecuteEnumPropertyGet<NetOffice.ExcelApi.Enums.XlCreator>(this, "Creator"); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get /// Unknown COM Proxy /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff194389.aspx </remarks> [SupportByVersion("Excel", 9,10,11,12,14,15,16), ProxyResult] public object Parent { get { return Factory.ExecuteReferencePropertyGet(this, "Parent"); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff840499.aspx </remarks> [SupportByVersion("Excel", 9,10,11,12,14,15,16)] public object Color { get { return Factory.ExecuteVariantPropertyGet(this, "Color"); } set { Factory.ExecuteVariantPropertySet(this, "Color", value); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff822603.aspx </remarks> [SupportByVersion("Excel", 9,10,11,12,14,15,16)] public object ColorIndex { get { return Factory.ExecuteVariantPropertyGet(this, "ColorIndex"); } set { Factory.ExecuteVariantPropertySet(this, "ColorIndex", value); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff197910.aspx </remarks> [SupportByVersion("Excel", 9,10,11,12,14,15,16)] public object InvertIfNegative { get { return Factory.ExecuteVariantPropertyGet(this, "InvertIfNegative"); } set { Factory.ExecuteVariantPropertySet(this, "InvertIfNegative", value); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff835883.aspx </remarks> [SupportByVersion("Excel", 9,10,11,12,14,15,16)] public object Pattern { get { return Factory.ExecuteVariantPropertyGet(this, "Pattern"); } set { Factory.ExecuteVariantPropertySet(this, "Pattern", value); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff197513.aspx </remarks> [SupportByVersion("Excel", 9,10,11,12,14,15,16)] public object PatternColor { get { return Factory.ExecuteVariantPropertyGet(this, "PatternColor"); } set { Factory.ExecuteVariantPropertySet(this, "PatternColor", value); } } /// <summary> /// SupportByVersion Excel 9, 10, 11, 12, 14, 15, 16 /// Get/Set /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff840377.aspx </remarks> [SupportByVersion("Excel", 9,10,11,12,14,15,16)] public object PatternColorIndex { get { return Factory.ExecuteVariantPropertyGet(this, "PatternColorIndex"); } set { Factory.ExecuteVariantPropertySet(this, "PatternColorIndex", value); } } /// <summary> /// SupportByVersion Excel 12, 14, 15, 16 /// Get/Set /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff820778.aspx </remarks> [SupportByVersion("Excel", 12,14,15,16)] public object ThemeColor { get { return Factory.ExecuteVariantPropertyGet(this, "ThemeColor"); } set { Factory.ExecuteVariantPropertySet(this, "ThemeColor", value); } } /// <summary> /// SupportByVersion Excel 12, 14, 15, 16 /// Get/Set /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff197557.aspx </remarks> [SupportByVersion("Excel", 12,14,15,16)] public object TintAndShade { get { return Factory.ExecuteVariantPropertyGet(this, "TintAndShade"); } set { Factory.ExecuteVariantPropertySet(this, "TintAndShade", value); } } /// <summary> /// SupportByVersion Excel 12, 14, 15, 16 /// Get/Set /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff839013.aspx </remarks> [SupportByVersion("Excel", 12,14,15,16)] public object PatternThemeColor { get { return Factory.ExecuteVariantPropertyGet(this, "PatternThemeColor"); } set { Factory.ExecuteVariantPropertySet(this, "PatternThemeColor", value); } } /// <summary> /// SupportByVersion Excel 12, 14, 15, 16 /// Get/Set /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff192986.aspx </remarks> [SupportByVersion("Excel", 12,14,15,16)] public object PatternTintAndShade { get { return Factory.ExecuteVariantPropertyGet(this, "PatternTintAndShade"); } set { Factory.ExecuteVariantPropertySet(this, "PatternTintAndShade", value); } } /// <summary> /// SupportByVersion Excel 12, 14, 15, 16 /// Get /// Unknown COM Proxy /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff195190.aspx </remarks> [SupportByVersion("Excel", 12,14,15,16), ProxyResult] public object Gradient { get { return Factory.ExecuteReferencePropertyGet(this, "Gradient"); } } #endregion #region Methods #endregion #pragma warning restore } }
{ "pile_set_name": "Github" }
#include <QCryptographicHash> #include <QNetworkRequest> #include <QNetworkAccessManager> #include <QDateTime> #include <QByteArray> #include <QDebug> #include <QDataStream> #include <QStringList> #if QT_VERSION >= 0x050000 #include <QUrlQuery> #endif #if QT_VERSION >= 0x050100 #include <QMessageAuthenticationCode> #endif #include "o1.h" #include "o2replyserver.h" #include "o0globals.h" #include "o0settingsstore.h" O1::O1(QObject *parent, QNetworkAccessManager *manager): O0BaseAuth(parent) { setSignatureMethod(O2_SIGNATURE_TYPE_HMAC_SHA1); manager_ = manager ? manager : new QNetworkAccessManager(this); replyServer_ = new O2ReplyServer(this); qRegisterMetaType<QNetworkReply::NetworkError>("QNetworkReply::NetworkError"); connect(replyServer_, SIGNAL(verificationReceived(QMap<QString,QString>)), this, SLOT(onVerificationReceived(QMap<QString,QString>))); setCallbackUrl(O2_CALLBACK_URL); } QUrl O1::requestTokenUrl() { return requestTokenUrl_; } void O1::setRequestTokenUrl(const QUrl &v) { requestTokenUrl_ = v; Q_EMIT requestTokenUrlChanged(); } QList<O0RequestParameter> O1::requestParameters() { return requestParameters_; } void O1::setRequestParameters(const QList<O0RequestParameter> &v) { requestParameters_ = v; } QString O1::callbackUrl() { return callbackUrl_; } void O1::setCallbackUrl(const QString &v) { callbackUrl_ = v; } QUrl O1::authorizeUrl() { return authorizeUrl_; } void O1::setAuthorizeUrl(const QUrl &value) { authorizeUrl_ = value; Q_EMIT authorizeUrlChanged(); } QUrl O1::accessTokenUrl() { return accessTokenUrl_; } void O1::setAccessTokenUrl(const QUrl &value) { accessTokenUrl_ = value; Q_EMIT accessTokenUrlChanged(); } QString O1::signatureMethod() { return signatureMethod_; } void O1::setSignatureMethod(const QString &value) { qDebug() << "O1::setSignatureMethod: " << value; signatureMethod_ = value; } void O1::unlink() { qDebug() << "O1::unlink"; setLinked(false); setToken(""); setTokenSecret(""); setExtraTokens(QVariantMap()); Q_EMIT linkingSucceeded(); } #if QT_VERSION < 0x050100 /// Calculate the HMAC variant of SHA1 hash. /// @author http://qt-project.org/wiki/HMAC-SHA1. /// @copyright Creative Commons Attribution-ShareAlike 2.5 Generic. static QByteArray hmacSha1(QByteArray key, QByteArray baseString) { int blockSize = 64; if (key.length() > blockSize) { key = QCryptographicHash::hash(key, QCryptographicHash::Sha1); } QByteArray innerPadding(blockSize, char(0x36)); QByteArray outerPadding(blockSize, char(0x5c)); for (int i = 0; i < key.length(); i++) { innerPadding[i] = innerPadding[i] ^ key.at(i); outerPadding[i] = outerPadding[i] ^ key.at(i); } QByteArray total = outerPadding; QByteArray part = innerPadding; part.append(baseString); total.append(QCryptographicHash::hash(part, QCryptographicHash::Sha1)); QByteArray hashed = QCryptographicHash::hash(total, QCryptographicHash::Sha1); return hashed.toBase64(); } #endif /// Get HTTP operation name. static QString getOperationName(QNetworkAccessManager::Operation op) { switch (op) { case QNetworkAccessManager::GetOperation: return "GET"; case QNetworkAccessManager::PostOperation: return "POST"; case QNetworkAccessManager::PutOperation: return "PUT"; case QNetworkAccessManager::DeleteOperation: return "DEL"; default: return ""; } } /// Build a concatenated/percent-encoded string from a list of headers. QByteArray O1::encodeHeaders(const QList<O0RequestParameter> &headers) { return QUrl::toPercentEncoding(createQueryParameters(headers)); } /// Build a base string for signing. QByteArray O1::getRequestBase(const QList<O0RequestParameter> &oauthParams, const QList<O0RequestParameter> &otherParams, const QUrl &url, QNetworkAccessManager::Operation op) { QByteArray base; // Initialize base string with the operation name (e.g. "GET") and the base URL base.append(getOperationName(op).toUtf8() + "&"); base.append(QUrl::toPercentEncoding(url.toString(QUrl::RemoveQuery)) + "&"); // Append a sorted+encoded list of all request parameters to the base string QList<O0RequestParameter> headers(oauthParams); headers.append(otherParams); qSort(headers); base.append(encodeHeaders(headers)); return base; } QByteArray O1::sign(const QList<O0RequestParameter> &oauthParams, const QList<O0RequestParameter> &otherParams, const QUrl &url, QNetworkAccessManager::Operation op, const QString &consumerSecret, const QString &tokenSecret) { QByteArray baseString = getRequestBase(oauthParams, otherParams, url, op); QByteArray secret = QUrl::toPercentEncoding(consumerSecret) + "&" + QUrl::toPercentEncoding(tokenSecret); #if QT_VERSION >= 0x050100 return QMessageAuthenticationCode::hash(baseString, secret, QCryptographicHash::Sha1).toBase64(); #else return hmacSha1(secret, baseString); #endif } QByteArray O1::buildAuthorizationHeader(const QList<O0RequestParameter> &oauthParams) { bool first = true; QByteArray ret("OAuth "); QList<O0RequestParameter> headers(oauthParams); qSort(headers); foreach (O0RequestParameter h, headers) { if (first) { first = false; } else { ret.append(","); } ret.append(h.name); ret.append("=\""); ret.append(QUrl::toPercentEncoding(h.value)); ret.append("\""); } return ret; } QByteArray O1::generateSignature(const QList<O0RequestParameter> headers, const QNetworkRequest &req, const QList<O0RequestParameter> &signingParameters, QNetworkAccessManager::Operation operation) { QByteArray signature; if (signatureMethod() == O2_SIGNATURE_TYPE_HMAC_SHA1) { signature = sign(headers, signingParameters, req.url(), operation, clientSecret(), tokenSecret()); } else if (signatureMethod() == O2_SIGNATURE_TYPE_PLAINTEXT) { signature = clientSecret().toLatin1() + "&" + tokenSecret().toLatin1(); } return signature; } void O1::link() { qDebug() << "O1::link"; if (linked()) { qDebug() << "O1::link: Linked already"; Q_EMIT linkingSucceeded(); return; } setLinked(false); setToken(""); setTokenSecret(""); setExtraTokens(QVariantMap()); // Start reply server if (!replyServer_->isListening()) replyServer_->listen(QHostAddress::Any, localPort()); // Get any query parameters for the request #if QT_VERSION >= 0x050000 QUrlQuery requestData; #else QUrl requestData = requestTokenUrl(); #endif O0RequestParameter param("", ""); foreach(param, requestParameters()) requestData.addQueryItem(QString(param.name), QUrl::toPercentEncoding(QString(param.value))); // Get the request url and add parameters #if QT_VERSION >= 0x050000 QUrl requestUrl = requestTokenUrl(); requestUrl.setQuery(requestData); // Create request QNetworkRequest request(requestUrl); #else // Create request QNetworkRequest request(requestData); #endif // Create initial token request QList<O0RequestParameter> headers; headers.append(O0RequestParameter(O2_OAUTH_CALLBACK, callbackUrl().arg(replyServer_->serverPort()).toLatin1())); headers.append(O0RequestParameter(O2_OAUTH_CONSUMER_KEY, clientId().toLatin1())); headers.append(O0RequestParameter(O2_OAUTH_NONCE, nonce())); headers.append(O0RequestParameter(O2_OAUTH_TIMESTAMP, QString::number(QDateTime::currentDateTimeUtc().toTime_t()).toLatin1())); headers.append(O0RequestParameter(O2_OAUTH_VERSION, "1.0")); headers.append(O0RequestParameter(O2_OAUTH_SIGNATURE_METHOD, signatureMethod().toLatin1())); headers.append(O0RequestParameter(O2_OAUTH_SIGNATURE, generateSignature(headers, request, requestParameters(), QNetworkAccessManager::PostOperation))); // Clear request token requestToken_.clear(); requestTokenSecret_.clear(); // Post request request.setRawHeader(O2_HTTP_AUTHORIZATION_HEADER, buildAuthorizationHeader(headers)); request.setHeader(QNetworkRequest::ContentTypeHeader, O2_MIME_TYPE_XFORM); QNetworkReply *reply = manager_->post(request, QByteArray()); connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onTokenRequestError(QNetworkReply::NetworkError))); connect(reply, SIGNAL(finished()), this, SLOT(onTokenRequestFinished())); } void O1::onTokenRequestError(QNetworkReply::NetworkError error) { QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender()); qWarning() << "O1::onTokenRequestError:" << (int)error << reply->errorString() << reply->readAll(); Q_EMIT linkingFailed(); } void O1::onTokenRequestFinished() { qDebug() << "O1::onTokenRequestFinished"; QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender()); qDebug() << QString( "Request: %1" ).arg(reply->request().url().toString()); reply->deleteLater(); if (reply->error() != QNetworkReply::NoError) { qWarning() << "O1::onTokenRequestFinished: " << reply->errorString(); return; } // Get request token and secret QByteArray data = reply->readAll(); QMap<QString, QString> response = parseResponse(data); requestToken_ = response.value(O2_OAUTH_TOKEN, ""); requestTokenSecret_ = response.value(O2_OAUTH_TOKEN_SECRET, ""); setToken(requestToken_); setTokenSecret(requestTokenSecret_); // Checking for "oauth_callback_confirmed" is present and set to true QString oAuthCbConfirmed = response.value(O2_OAUTH_CALLBACK_CONFIRMED, "false"); if (requestToken_.isEmpty() || requestTokenSecret_.isEmpty() || (oAuthCbConfirmed == "false")) { qWarning() << "O1::onTokenRequestFinished: No oauth_token, oauth_token_secret or oauth_callback_confirmed in response :" << data; Q_EMIT linkingFailed(); return; } // Continue authorization flow in the browser QUrl url(authorizeUrl()); #if QT_VERSION < 0x050000 url.addQueryItem(O2_OAUTH_TOKEN, requestToken_); url.addQueryItem(O2_OAUTH_CALLBACK, callbackUrl().arg(replyServer_->serverPort()).toLatin1()); #else QUrlQuery query(url); query.addQueryItem(O2_OAUTH_TOKEN, requestToken_); query.addQueryItem(O2_OAUTH_CALLBACK, callbackUrl().arg(replyServer_->serverPort()).toLatin1()); url.setQuery(query); #endif Q_EMIT openBrowser(url); } void O1::onVerificationReceived(QMap<QString, QString> params) { qDebug() << "O1::onVerificationReceived"; Q_EMIT closeBrowser(); verifier_ = params.value(O2_OAUTH_VERFIER, ""); if (params.value(O2_OAUTH_TOKEN) == requestToken_) { // Exchange request token for access token exchangeToken(); } else { qWarning() << "O1::onVerificationReceived: oauth_token missing or doesn't match"; Q_EMIT linkingFailed(); } } void O1::exchangeToken() { qDebug() << "O1::exchangeToken"; // Create token exchange request QNetworkRequest request(accessTokenUrl()); QList<O0RequestParameter> oauthParams; oauthParams.append(O0RequestParameter(O2_OAUTH_CONSUMER_KEY, clientId().toLatin1())); oauthParams.append(O0RequestParameter(O2_OAUTH_VERSION, "1.0")); oauthParams.append(O0RequestParameter(O2_OAUTH_TIMESTAMP, QString::number(QDateTime::currentDateTimeUtc().toTime_t()).toLatin1())); oauthParams.append(O0RequestParameter(O2_OAUTH_NONCE, nonce())); oauthParams.append(O0RequestParameter(O2_OAUTH_TOKEN, requestToken_.toLatin1())); oauthParams.append(O0RequestParameter(O2_OAUTH_VERFIER, verifier_.toLatin1())); oauthParams.append(O0RequestParameter(O2_OAUTH_SIGNATURE_METHOD, signatureMethod().toLatin1())); oauthParams.append(O0RequestParameter(O2_OAUTH_SIGNATURE, generateSignature(oauthParams, request, QList<O0RequestParameter>(), QNetworkAccessManager::PostOperation))); // Post request request.setRawHeader(O2_HTTP_AUTHORIZATION_HEADER, buildAuthorizationHeader(oauthParams)); request.setHeader(QNetworkRequest::ContentTypeHeader, O2_MIME_TYPE_XFORM); QNetworkReply *reply = manager_->post(request, QByteArray()); connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onTokenExchangeError(QNetworkReply::NetworkError))); connect(reply, SIGNAL(finished()), this, SLOT(onTokenExchangeFinished())); } void O1::onTokenExchangeError(QNetworkReply::NetworkError error) { QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender()); qWarning() << "O1::onTokenExchangeError:" << (int)error << reply->errorString() << reply->readAll(); Q_EMIT linkingFailed(); } void O1::onTokenExchangeFinished() { qDebug() << "O1::onTokenExchangeFinished"; QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender()); reply->deleteLater(); if (reply->error() != QNetworkReply::NoError) { qWarning() << "O1::onTokenExchangeFinished: " << reply->errorString(); return; } // Get access token and secret QByteArray data = reply->readAll(); QMap<QString, QString> response = parseResponse(data); if (response.contains(O2_OAUTH_TOKEN) && response.contains(O2_OAUTH_TOKEN_SECRET)) { setToken(response.take(O2_OAUTH_TOKEN)); setTokenSecret(response.take(O2_OAUTH_TOKEN_SECRET)); // Set extra tokens if any if (!response.isEmpty()) { QVariantMap extraTokens; foreach (QString key, response.keys()) { extraTokens.insert(key, response.value(key)); } setExtraTokens(extraTokens); } setLinked(true); Q_EMIT linkingSucceeded(); } else { qWarning() << "O1::onTokenExchangeFinished: oauth_token or oauth_token_secret missing from response" << data; Q_EMIT linkingFailed(); } } QMap<QString, QString> O1::parseResponse(const QByteArray &response) { QMap<QString, QString> ret; foreach (QByteArray param, response.split('&')) { QList<QByteArray> kv = param.split('='); if (kv.length() == 2) { ret.insert(QUrl::fromPercentEncoding(kv[0]), QUrl::fromPercentEncoding(kv[1])); } } return ret; } QByteArray O1::nonce() { static bool firstTime = true; if (firstTime) { firstTime = false; qsrand(QTime::currentTime().msec()); } QString u = QString::number(QDateTime::currentDateTimeUtc().toTime_t()); u.append(QString::number(qrand())); return u.toLatin1(); }
{ "pile_set_name": "Github" }
{{>partial_header}} using System.Collections.Generic; using System.Linq; using JsonSubTypes; using Newtonsoft.Json; using NUnit.Framework; using {{packageName}}.{{apiPackage}}; using {{packageName}}.{{modelPackage}}; using {{packageName}}.Client; namespace {{packageName}}.Test.Client { public class JsonSubTypesTests { [Test] public void TestSimpleJsonSubTypesExample() { var annimal = JsonConvert.DeserializeObject<IAnimal>("{\"Kind\":\"Dog\",\"Breed\":\"Jack Russell Terrier\"}"); Assert.AreEqual("Jack Russell Terrier", (annimal as Dog)?.Breed); } [Test] public void DeserializeObjectWithCustomMapping() { var annimal = JsonConvert.DeserializeObject<Animal2>("{\"Sound\":\"Bark\",\"Breed\":\"Jack Russell Terrier\"}"); Assert.AreEqual("Jack Russell Terrier", (annimal as Dog2)?.Breed); } [Test] public void DeserializeObjectMappingByPropertyPresence() { string json = "[{\"Department\":\"Department1\",\"JobTitle\":\"JobTitle1\",\"FirstName\":\"FirstName1\",\"LastName\":\"LastName1\"}," + "{\"Department\":\"Department1\",\"JobTitle\":\"JobTitle1\",\"FirstName\":\"FirstName1\",\"LastName\":\"LastName1\"}," + "{\"Skill\":\"Painter\",\"FirstName\":\"FirstName1\",\"LastName\":\"LastName1\"}]"; var persons = JsonConvert.DeserializeObject<ICollection<Person>>(json); Assert.AreEqual("Painter", (persons.Last() as Artist)?.Skill); } } [JsonConverter(typeof(JsonSubtypes), "Kind")] public interface IAnimal { string Kind { get; } } public class Dog : IAnimal { public Dog() { Kind = "Dog"; } public string Kind { get; } public string Breed { get; set; } } class Cat : IAnimal { public Cat() { Kind = "Cat"; } public string Kind { get; } bool Declawed { get; set; } } [JsonConverter(typeof(JsonSubtypes), "Sound")] [JsonSubtypes.KnownSubType(typeof(Dog2), "Bark")] [JsonSubtypes.KnownSubType(typeof(Cat2), "Meow")] public class Animal2 { public virtual string Sound { get; } public string Color { get; set; } } public class Dog2 : Animal2 { public Dog2() { Sound = "Bark"; } public override string Sound { get; } public string Breed { get; set; } } public class Cat2 : Animal2 { public Cat2() { Sound = "Meow"; } public override string Sound { get; } public bool Declawed { get; set; } } [JsonConverter(typeof(JsonSubtypes))] [JsonSubtypes.KnownSubTypeWithProperty(typeof(Employee), "JobTitle")] [JsonSubtypes.KnownSubTypeWithProperty(typeof(Artist), "Skill")] public class Person { public string FirstName { get; set; } public string LastName { get; set; } } public class Employee : Person { public string Department { get; set; } public string JobTitle { get; set; } } public class Artist : Person { public string Skill { get; set; } } }
{ "pile_set_name": "Github" }
import { UseCase } from "../../../../shared/core/UseCase"; import { IAuthService } from "../../services/authService"; import { Either, Result, left, right } from "../../../../shared/core/Result"; import { AppError } from "../../../../shared/core/AppError"; import { JWTToken, RefreshToken } from "../../domain/jwt"; import { RefreshAccessTokenErrors } from "./RefreshAccessTokenErrors"; import { IUserRepo } from "../../repos/userRepo"; import { User } from "../../domain/user"; import { RefreshAccessTokenDTO } from "./RefreshAccessTokenDTO"; type Response = Either< RefreshAccessTokenErrors.RefreshTokenNotFound | AppError.UnexpectedError, Result<JWTToken> > export class RefreshAccessToken implements UseCase<RefreshAccessTokenDTO, Promise<Response>> { private userRepo: IUserRepo; private authService: IAuthService; constructor (userRepo: IUserRepo, authService: IAuthService) { this.userRepo = userRepo; this.authService = authService; } public async execute (req: RefreshAccessTokenDTO): Promise<Response> { const { refreshToken } = req; let user: User; let username: string; try { // Get the username for the user that owns the refresh token try { username = await this.authService.getUserNameFromRefreshToken(refreshToken); } catch (err) { return left(new RefreshAccessTokenErrors.RefreshTokenNotFound()); } try { // get the user by username user = await this.userRepo.getUserByUserName(username); } catch (err) { return left(new RefreshAccessTokenErrors.UserNotFoundOrDeletedError()); } const accessToken: JWTToken = this.authService.signJWT({ username: user.username.value, email: user.email.value, isEmailVerified: user.isEmailVerified, userId: user.userId.id.toString(), adminUser: user.isAdminUser, }); // sign a new jwt for that user user.setAccessToken(accessToken, refreshToken); // save it await this.authService.saveAuthenticatedUser(user); // return the new access token return right(Result.ok<JWTToken>(accessToken)) } catch (err) { return left(new AppError.UnexpectedError(err)); } } }
{ "pile_set_name": "Github" }
# CSS Styling > __Note__ > The name inside the square bracket is optional. It may or may not appear depending on the relevant condition # Vuetable ```javascript { tableClass: 'ui blue selectable celled stackable attached table', loadingClass: 'loading', ascendingIcon: 'blue chevron up icon', descendingIcon: 'blue chevron down icon', detailRowClass: 'vuetable-detail-row', handleIcon: 'grey sidebar icon', sortableIcon: '', // since v1.7 ascendingClass: 'sorted-asc', // since v1.7 descendingClass: 'sorted-desc' // since v1.7 } ``` ## Table `<table>` ```html <table class="vuetable [css.tableClass]"></table> ``` ## Table Header Column `<th>` ### Fields ```html <th id="_{{field.name}}" class="vuetable-th-{{field.name}} [sortable] [field.titleClass]"></th> ``` ### Special Fields - __sequence ```html <th class="vuetable-th-sequence [field.titleClass]"></th> ``` - __checkbox ```html <th class="vuetable-th-checkbox-{{trackBy}} [field.titleClass]"></th> ``` - __component ```html <th class="vuetable-th-component-{{trackBy}} [sortable] [field.titleClass]"></th> ``` - __slot ```html <th class="vuetable-th-slot-{{field.name}} [sortable] [field.titleClass]"></th> ``` ## Table Column `<td>` ### Fields ```html <td class="[field.dataClass]"></td> ``` ### Special Fields - __sequence ```html <td id="vuetable-sequence [field.dataClass]"></td> ``` - __handle ```html <td id="vuetable-handle [field.dataClass]"></td> ``` - __checkbox ```html <td id="vuetable-checkboxes [field.dataClass]"></td> ``` - __component ```html <td id="vuetable-component [field.dataClass]"></td> ``` - __slot ```html <td id="vuetable-slot [field.dataClass]"></td> ``` ## Detail Row ```html <td class="[css.detailRowClass]"></td> ``` ## Other Elements ### # loadingClass ### # ascendingIcon ### # descendingIcon ### # handleIcon ## Pagination ```javascript { wrapperClass: 'ui right floated pagination menu', activeClass: 'active large', disabledClass: 'disabled', pageClass: 'item', linkClass: 'icon item', paginationClass: 'ui bottom attached segment grid', paginationInfoClass: 'left floated left aligned six wide column', dropdownClass: 'ui search dropdown', icons: { first: 'angle double left icon', prev: 'left chevron icon', next: 'right chevron icon', last: 'angle double right icon', } } ```
{ "pile_set_name": "Github" }
# Copyright 2012 Mozilla Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Main toolbar buttons (tooltips and alt text for images) previous.title=മുമ്പുള്ള താള്‍ previous_label=മുമ്പു് next.title=അടുത്ത താള്‍ next_label=അടുത്തതു് # LOCALIZATION NOTE (page_label, page_of): # These strings are concatenated to form the "Page: X of Y" string. # Do not translate "{{pageCount}}", it will be substituted with a number # representing the total number of pages. page_label=താള്‍: page_of={{pageCount}} zoom_out.title=ചെറുതാക്കുക zoom_out_label=ചെറുതാക്കുക zoom_in.title=വലുതാക്കുക zoom_in_label=വലുതാക്കുക zoom.title=വ്യാപ്തി മാറ്റുക presentation_mode.title=പ്രസന്റേഷന്‍ രീതിയിലേക്കു് മാറ്റുക presentation_mode_label=പ്രസന്റേഷന്‍ രീതി open_file.title=ഫയല്‍ തുറക്കുക open_file_label=തുറക്കുക print.title=പ്രിന്റ് ചെയ്യുക print_label=പ്രിന്റ് ചെയ്യുക download.title=ഡൌണ്‍ലോഡ് ചെയ്യുക download_label=ഡൌണ്‍ലോഡ് ചെയ്യുക bookmark.title=നിലവിലുള്ള കാഴ്ച (പുതിയ ജാലകത്തില്‍ പകര്‍ത്തുക അല്ലെങ്കില്‍ തുറക്കുക) bookmark_label=നിലവിലുള്ള കാഴ്ച # Secondary toolbar and context menu tools.title=ഉപകരണങ്ങള്‍ tools_label=ഉപകരണങ്ങള്‍ first_page.title=ആദ്യത്തെ താളിലേയ്ക്കു് പോകുക first_page.label=ആദ്യത്തെ താളിലേയ്ക്കു് പോകുക first_page_label=ആദ്യത്തെ താളിലേയ്ക്കു് പോകുക last_page.title=അവസാന താളിലേയ്ക്കു് പോകുക last_page.label=അവസാന താളിലേയ്ക്കു് പോകുക last_page_label=അവസാന താളിലേയ്ക്കു് പോകുക page_rotate_cw.title=ഘടികാരദിശയില്‍ കറക്കുക page_rotate_cw.label=ഘടികാരദിശയില്‍ കറക്കുക page_rotate_cw_label=ഘടികാരദിശയില്‍ കറക്കുക page_rotate_ccw.title=ഘടികാര ദിശയ്ക്കു് വിപരീതമായി കറക്കുക page_rotate_ccw.label=ഘടികാര ദിശയ്ക്കു് വിപരീതമായി കറക്കുക page_rotate_ccw_label=ഘടികാര ദിശയ്ക്കു് വിപരീതമായി കറക്കുക hand_tool_enable.title=ഹാന്‍ഡ് ടൂള്‍ പ്രവര്‍ത്തന സജ്ജമാക്കുക hand_tool_enable_label=ഹാന്‍ഡ് ടൂള്‍ പ്രവര്‍ത്തന സജ്ജമാക്കുക hand_tool_disable.title=ഹാന്‍ഡ് ടൂള്‍ പ്രവര്‍ത്തന രഹിതമാക്കുക hand_tool_disable_label=ഹാന്‍ഡ് ടൂള്‍ പ്രവര്‍ത്തന രഹിതമാക്കുക # Document properties dialog box document_properties.title=രേഖയുടെ വിശേഷതകള്‍... document_properties_label=രേഖയുടെ വിശേഷതകള്‍... document_properties_file_name=ഫയലിന്റെ പേര്‌: document_properties_file_size=ഫയലിന്റെ വലിപ്പം:‌‌ document_properties_kb={{size_kb}} കെബി ({{size_b}} ബൈറ്റുകള്‍) document_properties_mb={{size_mb}} എംബി ({{size_b}} ബൈറ്റുകള്‍) document_properties_title=തലക്കെട്ട്‌\u0020 document_properties_author=രചയിതാവ്: document_properties_subject=വിഷയം: document_properties_keywords=കീവേര്‍ഡുകള്‍: document_properties_creation_date=പൂര്‍ത്തിയാകുന്ന തീയതി: document_properties_modification_date=മാറ്റം വരുത്തിയ തീയതി: document_properties_date_string={{date}}, {{time}} document_properties_creator=സൃഷ്ടികര്‍ത്താവ്: document_properties_producer=പിഡിഎഫ് പ്രൊഡ്യൂസര്‍: document_properties_version=പിഡിഎഫ് പതിപ്പ്: document_properties_page_count=താളിന്റെ എണ്ണം: document_properties_close=അടയ്ക്കുക # Tooltips and alt text for side panel toolbar buttons # (the _label strings are alt text for the buttons, the .title strings are # tooltips) toggle_sidebar.title=സൈഡ് ബാറിലേക്കു് മാറ്റുക toggle_sidebar_label=സൈഡ് ബാറിലേക്കു് മാറ്റുക outline.title=രേഖയുടെ ഔട്ട്ലൈന്‍ കാണിയ്ക്കുക outline_label=രേഖയുടെ ഔട്ട്ലൈന്‍ attachments.title=അറ്റാച്മെന്റുകള്‍ കാണിയ്ക്കുക attachments_label=അറ്റാച്മെന്റുകള്‍ thumbs.title=തംബ്നെയിലുകള്‍ കാണിയ്ക്കുക thumbs_label=തംബ്നെയിലുകള്‍ findbar.title=രേഖയില്‍ കണ്ടുപിടിയ്ക്കുക findbar_label=കണ്ടെത്തുക\u0020 # Thumbnails panel item (tooltip and alt text for images) # LOCALIZATION NOTE (thumb_page_title): "{{page}}" will be replaced by the page # number. thumb_page_title=താള്‍ {{page}} # LOCALIZATION NOTE (thumb_page_canvas): "{{page}}" will be replaced by the page # number. thumb_page_canvas={{page}} താളിനുള്ള തംബ്നെയില്‍ # Find panel button title and messages find_label=കണ്ടെത്തുക find_previous.title=വാചകം ഇതിനു മുന്‍പ്‌ ആവര്‍ത്തിച്ചത്‌ കണ്ടെത്തുക\u0020 find_previous_label=മുമ്പു് find_next.title=വാചകം വീണ്ടും ആവര്‍ത്തിക്കുന്നത്‌ കണ്ടെത്തുക\u0020 find_next_label=അടുത്തതു് find_highlight=എല്ലാം എടുത്തുകാണിയ്ക്കുക find_match_case_label=അക്ഷരങ്ങള്‍ ഒത്തുനോക്കുക find_reached_top=രേഖയുടെ മുകളില്‍ എത്തിയിരിക്കുന്നു, താഴെ നിന്നും തുടരുന്നു find_reached_bottom=രേഖയുടെ അവസാനം വരെ എത്തിയിരിക്കുന്നു, മുകളില്‍ നിന്നും തുടരുന്നു\u0020 find_not_found=വാചകം കണ്ടെത്താനായില്ല\u0020 # Error panel labels error_more_info=കൂടുതല്‍ വിവരം error_less_info=കുറച്ച് വിവരം error_close=അടയ്ക്കുക # LOCALIZATION NOTE (error_version_info): "{{version}}" and "{{build}}" will be # replaced by the PDF.JS version and build ID. error_version_info=PDF.js v{{version}} (build: {{build}}) # LOCALIZATION NOTE (error_message): "{{message}}" will be replaced by an # english string describing the error. error_message=സന്ദേശം: {{message}} # LOCALIZATION NOTE (error_stack): "{{stack}}" will be replaced with a stack # trace. error_stack=സ്റ്റാക്ക്: {{stack}} # LOCALIZATION NOTE (error_file): "{{file}}" will be replaced with a filename error_file=ഫയല്‍: {{file}} # LOCALIZATION NOTE (error_line): "{{line}}" will be replaced with a line number error_line=വരി: {{line}} rendering_error=താള്‍ റെണ്ടര്‍ ചെയ്യുമ്പോള്‍‌ പിശകുണ്ടായിരിയ്ക്കുന്നു. # Predefined zoom values page_scale_width=താളിന്റെ വീതി page_scale_fit=താള്‍ പാകത്തിനാക്കുക page_scale_auto=സ്വയമായി വലുതാക്കുക page_scale_actual=യഥാര്‍ത്ഥ വ്യാപ്തി # Loading indicator messages loading_error_indicator=പിശക് loading_error=പിഡിഎഫ് ലഭ്യമാക്കുമ്പോള്‍ പിശക് ഉണ്ടായിരിയ്ക്കുന്നു. invalid_file_error=തെറ്റായ അല്ലെങ്കില്‍ തകരാറുള്ള പിഡിഎഫ് ഫയല്‍. missing_file_error=പിഡിഎഫ് ഫയല്‍ ലഭ്യമല്ല. # LOCALIZATION NOTE (text_annotation_type.alt): This is used as a tooltip. # "{{type}}" will be replaced with an annotation type from a list defined in # the PDF spec (32000-1:2008 Table 169 – Annotation types). # Some common types are e.g.: "Check", "Text", "Comment", "Note" text_annotation_type.alt=[{{type}} Annotation] password_label=ഈ പിഡിഎഫ് ഫയല്‍ തുറക്കുന്നതിനു് രഹസ്യവാക്ക് നല്‍കുക. password_invalid=തെറ്റായ രഹസ്യവാക്ക്, ദയവായി വീണ്ടും ശ്രമിയ്ക്കുക. password_ok=ശരി password_cancel=റദ്ദാക്കുക printing_not_supported=മുന്നറിയിപ്പു്: ഈ ബ്രൌസര്‍ പൂര്‍ണ്ണമായി പ്രിന്റിങ് പിന്തുണയ്ക്കുന്നില്ല. printing_not_ready=മുന്നറിയിപ്പു്: പ്രിന്റ് ചെയ്യുന്നതിനു് പിഡിഎഫ് പൂര്‍ണ്ണമായി ലഭ്യമല്ല. web_fonts_disabled=വെബിനുള്ള അക്ഷരസഞ്ചയങ്ങള്‍ പ്രവര്‍ത്തന രഹിതം: എംബഡ്ഡ് ചെയ്ത പിഡിഎഫ് അക്ഷരസഞ്ചയങ്ങള്‍ ഉപയോഗിയ്ക്കുവാന്‍ സാധ്യമല്ല. document_colors_disabled=സ്വന്തം നിറങ്ങള്‍ ഉപയോഗിയ്ക്കുവാന്‍ പിഡിഎഫ് രേഖകള്‍ക്കു് അനുവാദമില്ല: 'സ്വന്തം നിറങ്ങള്‍ ഉപയോഗിയ്ക്കുവാന്‍ താളുകളെ അനുവദിയ്ക്കുക' എന്നതു് ബ്രൌസറില്‍ നിര്‍ജീവമാണു്.
{ "pile_set_name": "Github" }
/** * Discrete charts */ $.fn.sparkline.discrete = discrete = createClass($.fn.sparkline._base, barHighlightMixin, { type: 'discrete', init: function (el, values, options, width, height) { discrete._super.init.call(this, el, values, options, width, height); this.regionShapes = {}; this.values = values = $.map(values, Number); this.min = Math.min.apply(Math, values); this.max = Math.max.apply(Math, values); this.range = this.max - this.min; this.width = width = options.get('width') === 'auto' ? values.length * 2 : this.width; this.interval = Math.floor(width / values.length); this.itemWidth = width / values.length; if (options.get('chartRangeMin') !== undefined && (options.get('chartRangeClip') || options.get('chartRangeMin') < this.min)) { this.min = options.get('chartRangeMin'); } if (options.get('chartRangeMax') !== undefined && (options.get('chartRangeClip') || options.get('chartRangeMax') > this.max)) { this.max = options.get('chartRangeMax'); } this.initTarget(); if (this.target) { this.lineHeight = options.get('lineHeight') === 'auto' ? Math.round(this.canvasHeight * 0.3) : options.get('lineHeight'); } }, getRegion: function (el, x, y) { return Math.floor(x / this.itemWidth); }, getCurrentRegionFields: function () { var currentRegion = this.currentRegion; return { isNull: this.values[currentRegion] === undefined, value: this.values[currentRegion], offset: currentRegion }; }, renderRegion: function (valuenum, highlight) { var values = this.values, options = this.options, min = this.min, max = this.max, range = this.range, interval = this.interval, target = this.target, canvasHeight = this.canvasHeight, lineHeight = this.lineHeight, pheight = canvasHeight - lineHeight, ytop, val, color, x; val = clipval(values[valuenum], min, max); x = valuenum * interval; ytop = Math.round(pheight - pheight * ((val - min) / range)); color = (options.get('thresholdColor') && val < options.get('thresholdValue')) ? options.get('thresholdColor') : options.get('lineColor'); if (highlight) { color = this.calcHighlightColor(color, options); } return target.drawLine(x, ytop, x, ytop + lineHeight, color); } });
{ "pile_set_name": "Github" }
*usr_40.txt* For Vim version 7.4. Last change: 2013 Aug 05 VIM USER MANUAL - by Bram Moolenaar Make new commands Vim is an extensible editor. You can take a sequence of commands you use often and turn it into a new command. Or redefine an existing command. Autocommands make it possible to execute commands automatically. |40.1| Key mapping |40.2| Defining command-line commands |40.3| Autocommands Next chapter: |usr_41.txt| Write a Vim script Previous chapter: |usr_32.txt| The undo tree Table of contents: |usr_toc.txt| ============================================================================== *40.1* Key mapping A simple mapping was explained in section |05.3|. The principle is that one sequence of key strokes is translated into another sequence of key strokes. This is a simple, yet powerful mechanism. The simplest form is that one key is mapped to a sequence of keys. Since the function keys, except <F1>, have no predefined meaning in Vim, these are good choices to map. Example: > :map <F2> GoDate: <Esc>:read !date<CR>kJ This shows how three modes are used. After going to the last line with "G", the "o" command opens a new line and starts Insert mode. The text "Date: " is inserted and <Esc> takes you out of insert mode. Notice the use of special keys inside <>. This is called angle bracket notation. You type these as separate characters, not by pressing the key itself. This makes the mappings better readable and you can copy and paste the text without problems. The ":" character takes Vim to the command line. The ":read !date" command reads the output from the "date" command and appends it below the current line. The <CR> is required to execute the ":read" command. At this point of execution the text looks like this: Date: ~ Fri Jun 15 12:54:34 CEST 2001 ~ Now "kJ" moves the cursor up and joins the lines together. To decide which key or keys you use for mapping, see |map-which-keys|. MAPPING AND MODES The ":map" command defines remapping for keys in Normal mode. You can also define mappings for other modes. For example, ":imap" applies to Insert mode. You can use it to insert a date below the cursor: > :imap <F2> <CR>Date: <Esc>:read !date<CR>kJ It looks a lot like the mapping for <F2> in Normal mode, only the start is different. The <F2> mapping for Normal mode is still there. Thus you can map the same key differently for each mode. Notice that, although this mapping starts in Insert mode, it ends in Normal mode. If you want it to continue in Insert mode, append an "a" to the mapping. Here is an overview of map commands and in which mode they work: :map Normal, Visual and Operator-pending :vmap Visual :nmap Normal :omap Operator-pending :map! Insert and Command-line :imap Insert :cmap Command-line Operator-pending mode is when you typed an operator character, such as "d" or "y", and you are expected to type the motion command or a text object. Thus when you type "dw", the "w" is entered in operator-pending mode. Suppose that you want to define <F7> so that the command d<F7> deletes a C program block (text enclosed in curly braces, {}). Similarly y<F7> would yank the program block into the unnamed register. Therefore, what you need to do is to define <F7> to select the current program block. You can do this with the following command: > :omap <F7> a{ This causes <F7> to perform a select block "a{" in operator-pending mode, just like you typed it. This mapping is useful if typing a { on your keyboard is a bit difficult. LISTING MAPPINGS To see the currently defined mappings, use ":map" without arguments. Or one of the variants that include the mode in which they work. The output could look like this: _g :call MyGrep(1)<CR> ~ v <F2> :s/^/> /<CR>:noh<CR>`` ~ n <F2> :.,$s/^/> /<CR>:noh<CR>`` ~ <xHome> <Home> <xEnd> <End> The first column of the list shows in which mode the mapping is effective. This is "n" for Normal mode, "i" for Insert mode, etc. A blank is used for a mapping defined with ":map", thus effective in both Normal and Visual mode. One useful purpose of listing the mapping is to check if special keys in <> form have been recognized (this only works when color is supported). For example, when <Esc> is displayed in color, it stands for the escape character. When it has the same color as the other text, it is five characters. REMAPPING The result of a mapping is inspected for other mappings in it. For example, the mappings for <F2> above could be shortened to: > :map <F2> G<F3> :imap <F2> <Esc><F3> :map <F3> oDate: <Esc>:read !date<CR>kJ For Normal mode <F2> is mapped to go to the last line, and then behave like <F3> was pressed. In Insert mode <F2> stops Insert mode with <Esc> and then also uses <F3>. Then <F3> is mapped to do the actual work. Suppose you hardly ever use Ex mode, and want to use the "Q" command to format text (this was so in old versions of Vim). This mapping will do it: > :map Q gq But, in rare cases you need to use Ex mode anyway. Let's map "gQ" to Q, so that you can still go to Ex mode: > :map gQ Q What happens now is that when you type "gQ" it is mapped to "Q". So far so good. But then "Q" is mapped to "gq", thus typing "gQ" results in "gq", and you don't get to Ex mode at all. To avoid keys to be mapped again, use the ":noremap" command: > :noremap gQ Q Now Vim knows that the "Q" is not to be inspected for mappings that apply to it. There is a similar command for every mode: :noremap Normal, Visual and Operator-pending :vnoremap Visual :nnoremap Normal :onoremap Operator-pending :noremap! Insert and Command-line :inoremap Insert :cnoremap Command-line RECURSIVE MAPPING When a mapping triggers itself, it will run forever. This can be used to repeat an action an unlimited number of times. For example, you have a list of files that contain a version number in the first line. You edit these files with "vim *.txt". You are now editing the first file. Define this mapping: > :map ,, :s/5.1/5.2/<CR>:wnext<CR>,, Now you type ",,". This triggers the mapping. It replaces "5.1" with "5.2" in the first line. Then it does a ":wnext" to write the file and edit the next one. The mapping ends in ",,". This triggers the same mapping again, thus doing the substitution, etc. This continues until there is an error. In this case it could be a file where the substitute command doesn't find a match for "5.1". You can then make a change to insert "5.1" and continue by typing ",," again. Or the ":wnext" fails, because you are in the last file in the list. When a mapping runs into an error halfway, the rest of the mapping is discarded. CTRL-C interrupts the mapping (CTRL-Break on MS-Windows). DELETE A MAPPING To remove a mapping use the ":unmap" command. Again, the mode the unmapping applies to depends on the command used: :unmap Normal, Visual and Operator-pending :vunmap Visual :nunmap Normal :ounmap Operator-pending :unmap! Insert and Command-line :iunmap Insert :cunmap Command-line There is a trick to define a mapping that works in Normal and Operator-pending mode, but not in Visual mode. First define it for all three modes, then delete it for Visual mode: > :map <C-A> /---><CR> :vunmap <C-A> Notice that the five characters "<C-A>" stand for the single key CTRL-A. To remove all mappings use the |:mapclear| command. You can guess the variations for different modes by now. Be careful with this command, it can't be undone. SPECIAL CHARACTERS The ":map" command can be followed by another command. A | character separates the two commands. This also means that a | character can't be used inside a map command. To include one, use <Bar> (five characters). Example: > :map <F8> :write <Bar> !checkin %<CR> The same problem applies to the ":unmap" command, with the addition that you have to watch out for trailing white space. These two commands are different: > :unmap a | unmap b :unmap a| unmap b The first command tries to unmap "a ", with a trailing space. When using a space inside a mapping, use <Space> (seven characters): > :map <Space> W This makes the spacebar move a blank-separated word forward. It is not possible to put a comment directly after a mapping, because the " character is considered to be part of the mapping. You can use |", this starts a new, empty command with a comment. Example: > :map <Space> W| " Use spacebar to move forward a word MAPPINGS AND ABBREVIATIONS Abbreviations are a lot like Insert mode mappings. The arguments are handled in the same way. The main difference is the way they are triggered. An abbreviation is triggered by typing a non-word character after the word. A mapping is triggered when typing the last character. Another difference is that the characters you type for an abbreviation are inserted in the text while you type them. When the abbreviation is triggered these characters are deleted and replaced by what the abbreviation produces. When typing the characters for a mapping, nothing is inserted until you type the last character that triggers it. If the 'showcmd' option is set, the typed characters are displayed in the last line of the Vim window. An exception is when a mapping is ambiguous. Suppose you have done two mappings: > :imap aa foo :imap aaa bar Now, when you type "aa", Vim doesn't know if it should apply the first or the second mapping. It waits for another character to be typed. If it is an "a", the second mapping is applied and results in "bar". If it is a space, for example, the first mapping is applied, resulting in "foo", and then the space is inserted. ADDITIONALLY... The <script> keyword can be used to make a mapping local to a script. See |:map-<script>|. The <buffer> keyword can be used to make a mapping local to a specific buffer. See |:map-<buffer>| The <unique> keyword can be used to make defining a new mapping fail when it already exists. Otherwise a new mapping simply overwrites the old one. See |:map-<unique>|. To make a key do nothing, map it to <Nop> (five characters). This will make the <F7> key do nothing at all: > :map <F7> <Nop>| map! <F7> <Nop> There must be no space after <Nop>. ============================================================================== *40.2* Defining command-line commands The Vim editor enables you to define your own commands. You execute these commands just like any other Command-line mode command. To define a command, use the ":command" command, as follows: > :command DeleteFirst 1delete Now when you execute the command ":DeleteFirst" Vim executes ":1delete", which deletes the first line. Note: User-defined commands must start with a capital letter. You cannot use ":X", ":Next" and ":Print". The underscore cannot be used! You can use digits, but this is discouraged. To list the user-defined commands, execute the following command: > :command Just like with the builtin commands, the user defined commands can be abbreviated. You need to type just enough to distinguish the command from another. Command line completion can be used to get the full name. NUMBER OF ARGUMENTS User-defined commands can take a series of arguments. The number of arguments must be specified by the -nargs option. For instance, the example :DeleteFirst command takes no arguments, so you could have defined it as follows: > :command -nargs=0 DeleteFirst 1delete However, because zero arguments is the default, you do not need to add "-nargs=0". The other values of -nargs are as follows: -nargs=0 No arguments -nargs=1 One argument -nargs=* Any number of arguments -nargs=? Zero or one argument -nargs=+ One or more arguments USING THE ARGUMENTS Inside the command definition, the arguments are represented by the <args> keyword. For example: > :command -nargs=+ Say :echo "<args>" Now when you type > :Say Hello World Vim echoes "Hello World". However, if you add a double quote, it won't work. For example: > :Say he said "hello" To get special characters turned into a string, properly escaped to use as an expression, use "<q-args>": > :command -nargs=+ Say :echo <q-args> Now the above ":Say" command will result in this to be executed: > :echo "he said \"hello\"" The <f-args> keyword contains the same information as the <args> keyword, except in a format suitable for use as function call arguments. For example: > :command -nargs=* DoIt :call AFunction(<f-args>) :DoIt a b c Executes the following command: > :call AFunction("a", "b", "c") LINE RANGE Some commands take a range as their argument. To tell Vim that you are defining such a command, you need to specify a -range option. The values for this option are as follows: -range Range is allowed; default is the current line. -range=% Range is allowed; default is the whole file. -range={count} Range is allowed; the last number in it is used as a single number whose default is {count}. When a range is specified, the keywords <line1> and <line2> get the values of the first and last line in the range. For example, the following command defines the SaveIt command, which writes out the specified range to the file "save_file": > :command -range=% SaveIt :<line1>,<line2>write! save_file OTHER OPTIONS Some of the other options and keywords are as follows: -count={number} The command can take a count whose default is {number}. The resulting count can be used through the <count> keyword. -bang You can use a !. If present, using <bang> will result in a !. -register You can specify a register. (The default is the unnamed register.) The register specification is available as <reg> (a.k.a. <register>). -complete={type} Type of command-line completion used. See |:command-completion| for the list of possible values. -bar The command can be followed by | and another command, or " and a comment. -buffer The command is only available for the current buffer. Finally, you have the <lt> keyword. It stands for the character <. Use this to escape the special meaning of the <> items mentioned. REDEFINING AND DELETING To redefine the same command use the ! argument: > :command -nargs=+ Say :echo "<args>" :command! -nargs=+ Say :echo <q-args> To delete a user command use ":delcommand". It takes a single argument, which is the name of the command. Example: > :delcommand SaveIt To delete all the user commands: > :comclear Careful, this can't be undone! More details about all this in the reference manual: |user-commands|. ============================================================================== *40.3* Autocommands An autocommand is a command that is executed automatically in response to some event, such as a file being read or written or a buffer change. Through the use of autocommands you can train Vim to edit compressed files, for example. That is used in the |gzip| plugin. Autocommands are very powerful. Use them with care and they will help you avoid typing many commands. Use them carelessly and they will cause a lot of trouble. Suppose you want to replace a datestamp on the end of a file every time it is written. First you define a function: > :function DateInsert() : $delete : read !date :endfunction You want this function to be called each time, just before a buffer is written to a file. This will make that happen: > :autocmd BufWritePre * call DateInsert() "BufWritePre" is the event for which this autocommand is triggered: Just before (pre) writing a buffer to a file. The "*" is a pattern to match with the file name. In this case it matches all files. With this command enabled, when you do a ":write", Vim checks for any matching BufWritePre autocommands and executes them, and then it performs the ":write". The general form of the :autocmd command is as follows: > :autocmd [group] {events} {file_pattern} [nested] {command} The [group] name is optional. It is used in managing and calling the commands (more on this later). The {events} parameter is a list of events (comma separated) that trigger the command. {file_pattern} is a filename, usually with wildcards. For example, using "*.txt" makes the autocommand be used for all files whose name end in ".txt". The optional [nested] flag allows for nesting of autocommands (see below), and finally, {command} is the command to be executed. EVENTS One of the most useful events is BufReadPost. It is triggered after a new file is being edited. It is commonly used to set option values. For example, you know that "*.gsm" files are GNU assembly language. To get the syntax file right, define this autocommand: > :autocmd BufReadPost *.gsm set filetype=asm If Vim is able to detect the type of file, it will set the 'filetype' option for you. This triggers the Filetype event. Use this to do something when a certain type of file is edited. For example, to load a list of abbreviations for text files: > :autocmd Filetype text source ~/.vim/abbrevs.vim When starting to edit a new file, you could make Vim insert a skeleton: > :autocmd BufNewFile *.[ch] 0read ~/skeletons/skel.c See |autocmd-events| for a complete list of events. PATTERNS The {file_pattern} argument can actually be a comma-separated list of file patterns. For example: "*.c,*.h" matches files ending in ".c" and ".h". The usual file wildcards can be used. Here is a summary of the most often used ones: * Match any character any number of times ? Match any character once [abc] Match the character a, b or c . Matches a dot a{b,c} Matches "ab" and "ac" When the pattern includes a slash (/) Vim will compare directory names. Without the slash only the last part of a file name is used. For example, "*.txt" matches "/home/biep/readme.txt". The pattern "/home/biep/*" would also match it. But "home/foo/*.txt" wouldn't. When including a slash, Vim matches the pattern against both the full path of the file ("/home/biep/readme.txt") and the relative path (e.g., "biep/readme.txt"). Note: When working on a system that uses a backslash as file separator, such as MS-Windows, you still use forward slashes in autocommands. This makes it easier to write the pattern, since a backslash has a special meaning. It also makes the autocommands portable. DELETING To delete an autocommand, use the same command as what it was defined with, but leave out the {command} at the end and use a !. Example: > :autocmd! FileWritePre * This will delete all autocommands for the "FileWritePre" event that use the "*" pattern. LISTING To list all the currently defined autocommands, use this: > :autocmd The list can be very long, especially when filetype detection is used. To list only part of the commands, specify the group, event and/or pattern. For example, to list all BufNewFile autocommands: > :autocmd BufNewFile To list all autocommands for the pattern "*.c": > :autocmd * *.c Using "*" for the event will list all the events. To list all autocommands for the cprograms group: > :autocmd cprograms GROUPS The {group} item, used when defining an autocommand, groups related autocommands together. This can be used to delete all the autocommands in a certain group, for example. When defining several autocommands for a certain group, use the ":augroup" command. For example, let's define autocommands for C programs: > :augroup cprograms : autocmd BufReadPost *.c,*.h :set sw=4 sts=4 : autocmd BufReadPost *.cpp :set sw=3 sts=3 :augroup END This will do the same as: > :autocmd cprograms BufReadPost *.c,*.h :set sw=4 sts=4 :autocmd cprograms BufReadPost *.cpp :set sw=3 sts=3 To delete all autocommands in the "cprograms" group: > :autocmd! cprograms NESTING Generally, commands executed as the result of an autocommand event will not trigger any new events. If you read a file in response to a FileChangedShell event, it will not trigger the autocommands that would set the syntax, for example. To make the events triggered, add the "nested" argument: > :autocmd FileChangedShell * nested edit EXECUTING AUTOCOMMANDS It is possible to trigger an autocommand by pretending an event has occurred. This is useful to have one autocommand trigger another one. Example: > :autocmd BufReadPost *.new execute "doautocmd BufReadPost " . expand("<afile>:r") This defines an autocommand that is triggered when a new file has been edited. The file name must end in ".new". The ":execute" command uses expression evaluation to form a new command and execute it. When editing the file "tryout.c.new" the executed command will be: > :doautocmd BufReadPost tryout.c The expand() function takes the "<afile>" argument, which stands for the file name the autocommand was executed for, and takes the root of the file name with ":r". ":doautocmd" executes on the current buffer. The ":doautoall" command works like "doautocmd" except it executes on all the buffers. USING NORMAL MODE COMMANDS The commands executed by an autocommand are Command-line commands. If you want to use a Normal mode command, the ":normal" command can be used. Example: > :autocmd BufReadPost *.log normal G This will make the cursor jump to the last line of *.log files when you start to edit it. Using the ":normal" command is a bit tricky. First of all, make sure its argument is a complete command, including all the arguments. When you use "i" to go to Insert mode, there must also be a <Esc> to leave Insert mode again. If you use a "/" to start a search pattern, there must be a <CR> to execute it. The ":normal" command uses all the text after it as commands. Thus there can be no | and another command following. To work around this, put the ":normal" command inside an ":execute" command. This also makes it possible to pass unprintable characters in a convenient way. Example: > :autocmd BufReadPost *.chg execute "normal ONew entry:\<Esc>" | \ 1read !date This also shows the use of a backslash to break a long command into more lines. This can be used in Vim scripts (not at the command line). When you want the autocommand do something complicated, which involves jumping around in the file and then returning to the original position, you may want to restore the view on the file. See |restore-position| for an example. IGNORING EVENTS At times, you will not want to trigger an autocommand. The 'eventignore' option contains a list of events that will be totally ignored. For example, the following causes events for entering and leaving a window to be ignored: > :set eventignore=WinEnter,WinLeave To ignore all events, use the following command: > :set eventignore=all To set it back to the normal behavior, make 'eventignore' empty: > :set eventignore= ============================================================================== Next chapter: |usr_41.txt| Write a Vim script Copyright: see |manual-copyright| vim:tw=78:ts=8:ft=help:norl:
{ "pile_set_name": "Github" }
------------------------------------------------------------------------ -- dqSubtract.decTest -- decQuad subtraction -- -- Copyright (c) IBM Corporation, 1981, 2008. All rights reserved. -- ------------------------------------------------------------------------ -- Please see the document "General Decimal Arithmetic Testcases" -- -- at http://www2.hursley.ibm.com/decimal for the description of -- -- these testcases. -- -- -- -- These testcases are experimental ('beta' versions), and they -- -- may contain errors. They are offered on an as-is basis. In -- -- particular, achieving the same results as the tests here is not -- -- a guarantee that an implementation complies with any Standard -- -- or specification. The tests are not exhaustive. -- -- -- -- Please send comments, suggestions, and corrections to the author: -- -- Mike Cowlishaw, IBM Fellow -- -- IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK -- -- mfc@uk.ibm.com -- ------------------------------------------------------------------------ version: 2.59 -- This set of tests are for decQuads only; all arguments are -- representable in a decQuad extended: 1 clamp: 1 precision: 34 maxExponent: 6144 minExponent: -6143 rounding: half_even -- [first group are 'quick confidence check'] dqsub001 subtract 0 0 -> '0' dqsub002 subtract 1 1 -> '0' dqsub003 subtract 1 2 -> '-1' dqsub004 subtract 2 1 -> '1' dqsub005 subtract 2 2 -> '0' dqsub006 subtract 3 2 -> '1' dqsub007 subtract 2 3 -> '-1' dqsub011 subtract -0 0 -> '-0' dqsub012 subtract -1 1 -> '-2' dqsub013 subtract -1 2 -> '-3' dqsub014 subtract -2 1 -> '-3' dqsub015 subtract -2 2 -> '-4' dqsub016 subtract -3 2 -> '-5' dqsub017 subtract -2 3 -> '-5' dqsub021 subtract 0 -0 -> '0' dqsub022 subtract 1 -1 -> '2' dqsub023 subtract 1 -2 -> '3' dqsub024 subtract 2 -1 -> '3' dqsub025 subtract 2 -2 -> '4' dqsub026 subtract 3 -2 -> '5' dqsub027 subtract 2 -3 -> '5' dqsub030 subtract 11 1 -> 10 dqsub031 subtract 10 1 -> 9 dqsub032 subtract 9 1 -> 8 dqsub033 subtract 1 1 -> 0 dqsub034 subtract 0 1 -> -1 dqsub035 subtract -1 1 -> -2 dqsub036 subtract -9 1 -> -10 dqsub037 subtract -10 1 -> -11 dqsub038 subtract -11 1 -> -12 dqsub040 subtract '5.75' '3.3' -> '2.45' dqsub041 subtract '5' '-3' -> '8' dqsub042 subtract '-5' '-3' -> '-2' dqsub043 subtract '-7' '2.5' -> '-9.5' dqsub044 subtract '0.7' '0.3' -> '0.4' dqsub045 subtract '1.3' '0.3' -> '1.0' dqsub046 subtract '1.25' '1.25' -> '0.00' dqsub050 subtract '1.23456789' '1.00000000' -> '0.23456789' dqsub051 subtract '1.23456789' '1.00000089' -> '0.23456700' dqsub060 subtract '70' '10000e+34' -> '-1.000000000000000000000000000000000E+38' Inexact Rounded dqsub061 subtract '700' '10000e+34' -> '-1.000000000000000000000000000000000E+38' Inexact Rounded dqsub062 subtract '7000' '10000e+34' -> '-9.999999999999999999999999999999999E+37' Inexact Rounded dqsub063 subtract '70000' '10000e+34' -> '-9.999999999999999999999999999999993E+37' Rounded dqsub064 subtract '700000' '10000e+34' -> '-9.999999999999999999999999999999930E+37' Rounded -- symmetry: dqsub065 subtract '10000e+34' '70' -> '1.000000000000000000000000000000000E+38' Inexact Rounded dqsub066 subtract '10000e+34' '700' -> '1.000000000000000000000000000000000E+38' Inexact Rounded dqsub067 subtract '10000e+34' '7000' -> '9.999999999999999999999999999999999E+37' Inexact Rounded dqsub068 subtract '10000e+34' '70000' -> '9.999999999999999999999999999999993E+37' Rounded dqsub069 subtract '10000e+34' '700000' -> '9.999999999999999999999999999999930E+37' Rounded -- some of the next group are really constructor tests dqsub090 subtract '00.0' '0.0' -> '0.0' dqsub091 subtract '00.0' '0.00' -> '0.00' dqsub092 subtract '0.00' '00.0' -> '0.00' dqsub093 subtract '00.0' '0.00' -> '0.00' dqsub094 subtract '0.00' '00.0' -> '0.00' dqsub095 subtract '3' '.3' -> '2.7' dqsub096 subtract '3.' '.3' -> '2.7' dqsub097 subtract '3.0' '.3' -> '2.7' dqsub098 subtract '3.00' '.3' -> '2.70' dqsub099 subtract '3' '3' -> '0' dqsub100 subtract '3' '+3' -> '0' dqsub101 subtract '3' '-3' -> '6' dqsub102 subtract '3' '0.3' -> '2.7' dqsub103 subtract '3.' '0.3' -> '2.7' dqsub104 subtract '3.0' '0.3' -> '2.7' dqsub105 subtract '3.00' '0.3' -> '2.70' dqsub106 subtract '3' '3.0' -> '0.0' dqsub107 subtract '3' '+3.0' -> '0.0' dqsub108 subtract '3' '-3.0' -> '6.0' -- the above all from add; massaged and extended. Now some new ones... -- [particularly important for comparisons] -- NB: -xE-8 below were non-exponents pre-ANSI X3-274, and -1E-7 or 0E-7 -- with input rounding. dqsub120 subtract '10.23456784' '10.23456789' -> '-5E-8' dqsub121 subtract '10.23456785' '10.23456789' -> '-4E-8' dqsub122 subtract '10.23456786' '10.23456789' -> '-3E-8' dqsub123 subtract '10.23456787' '10.23456789' -> '-2E-8' dqsub124 subtract '10.23456788' '10.23456789' -> '-1E-8' dqsub125 subtract '10.23456789' '10.23456789' -> '0E-8' dqsub126 subtract '10.23456790' '10.23456789' -> '1E-8' dqsub127 subtract '10.23456791' '10.23456789' -> '2E-8' dqsub128 subtract '10.23456792' '10.23456789' -> '3E-8' dqsub129 subtract '10.23456793' '10.23456789' -> '4E-8' dqsub130 subtract '10.23456794' '10.23456789' -> '5E-8' dqsub131 subtract '10.23456781' '10.23456786' -> '-5E-8' dqsub132 subtract '10.23456782' '10.23456786' -> '-4E-8' dqsub133 subtract '10.23456783' '10.23456786' -> '-3E-8' dqsub134 subtract '10.23456784' '10.23456786' -> '-2E-8' dqsub135 subtract '10.23456785' '10.23456786' -> '-1E-8' dqsub136 subtract '10.23456786' '10.23456786' -> '0E-8' dqsub137 subtract '10.23456787' '10.23456786' -> '1E-8' dqsub138 subtract '10.23456788' '10.23456786' -> '2E-8' dqsub139 subtract '10.23456789' '10.23456786' -> '3E-8' dqsub140 subtract '10.23456790' '10.23456786' -> '4E-8' dqsub141 subtract '10.23456791' '10.23456786' -> '5E-8' dqsub142 subtract '1' '0.999999999' -> '1E-9' dqsub143 subtract '0.999999999' '1' -> '-1E-9' dqsub144 subtract '-10.23456780' '-10.23456786' -> '6E-8' dqsub145 subtract '-10.23456790' '-10.23456786' -> '-4E-8' dqsub146 subtract '-10.23456791' '-10.23456786' -> '-5E-8' -- additional scaled arithmetic tests [0.97 problem] dqsub160 subtract '0' '.1' -> '-0.1' dqsub161 subtract '00' '.97983' -> '-0.97983' dqsub162 subtract '0' '.9' -> '-0.9' dqsub163 subtract '0' '0.102' -> '-0.102' dqsub164 subtract '0' '.4' -> '-0.4' dqsub165 subtract '0' '.307' -> '-0.307' dqsub166 subtract '0' '.43822' -> '-0.43822' dqsub167 subtract '0' '.911' -> '-0.911' dqsub168 subtract '.0' '.02' -> '-0.02' dqsub169 subtract '00' '.392' -> '-0.392' dqsub170 subtract '0' '.26' -> '-0.26' dqsub171 subtract '0' '0.51' -> '-0.51' dqsub172 subtract '0' '.2234' -> '-0.2234' dqsub173 subtract '0' '.2' -> '-0.2' dqsub174 subtract '.0' '.0008' -> '-0.0008' -- 0. on left dqsub180 subtract '0.0' '-.1' -> '0.1' dqsub181 subtract '0.00' '-.97983' -> '0.97983' dqsub182 subtract '0.0' '-.9' -> '0.9' dqsub183 subtract '0.0' '-0.102' -> '0.102' dqsub184 subtract '0.0' '-.4' -> '0.4' dqsub185 subtract '0.0' '-.307' -> '0.307' dqsub186 subtract '0.0' '-.43822' -> '0.43822' dqsub187 subtract '0.0' '-.911' -> '0.911' dqsub188 subtract '0.0' '-.02' -> '0.02' dqsub189 subtract '0.00' '-.392' -> '0.392' dqsub190 subtract '0.0' '-.26' -> '0.26' dqsub191 subtract '0.0' '-0.51' -> '0.51' dqsub192 subtract '0.0' '-.2234' -> '0.2234' dqsub193 subtract '0.0' '-.2' -> '0.2' dqsub194 subtract '0.0' '-.0008' -> '0.0008' -- negatives of same dqsub200 subtract '0' '-.1' -> '0.1' dqsub201 subtract '00' '-.97983' -> '0.97983' dqsub202 subtract '0' '-.9' -> '0.9' dqsub203 subtract '0' '-0.102' -> '0.102' dqsub204 subtract '0' '-.4' -> '0.4' dqsub205 subtract '0' '-.307' -> '0.307' dqsub206 subtract '0' '-.43822' -> '0.43822' dqsub207 subtract '0' '-.911' -> '0.911' dqsub208 subtract '.0' '-.02' -> '0.02' dqsub209 subtract '00' '-.392' -> '0.392' dqsub210 subtract '0' '-.26' -> '0.26' dqsub211 subtract '0' '-0.51' -> '0.51' dqsub212 subtract '0' '-.2234' -> '0.2234' dqsub213 subtract '0' '-.2' -> '0.2' dqsub214 subtract '.0' '-.0008' -> '0.0008' -- more fixed, LHS swaps [really the same as testcases under add] dqsub220 subtract '-56267E-12' 0 -> '-5.6267E-8' dqsub221 subtract '-56267E-11' 0 -> '-5.6267E-7' dqsub222 subtract '-56267E-10' 0 -> '-0.0000056267' dqsub223 subtract '-56267E-9' 0 -> '-0.000056267' dqsub224 subtract '-56267E-8' 0 -> '-0.00056267' dqsub225 subtract '-56267E-7' 0 -> '-0.0056267' dqsub226 subtract '-56267E-6' 0 -> '-0.056267' dqsub227 subtract '-56267E-5' 0 -> '-0.56267' dqsub228 subtract '-56267E-2' 0 -> '-562.67' dqsub229 subtract '-56267E-1' 0 -> '-5626.7' dqsub230 subtract '-56267E-0' 0 -> '-56267' -- symmetry ... dqsub240 subtract 0 '-56267E-12' -> '5.6267E-8' dqsub241 subtract 0 '-56267E-11' -> '5.6267E-7' dqsub242 subtract 0 '-56267E-10' -> '0.0000056267' dqsub243 subtract 0 '-56267E-9' -> '0.000056267' dqsub244 subtract 0 '-56267E-8' -> '0.00056267' dqsub245 subtract 0 '-56267E-7' -> '0.0056267' dqsub246 subtract 0 '-56267E-6' -> '0.056267' dqsub247 subtract 0 '-56267E-5' -> '0.56267' dqsub248 subtract 0 '-56267E-2' -> '562.67' dqsub249 subtract 0 '-56267E-1' -> '5626.7' dqsub250 subtract 0 '-56267E-0' -> '56267' -- now some more from the 'new' add dqsub301 subtract '1.23456789' '1.00000000' -> '0.23456789' dqsub302 subtract '1.23456789' '1.00000011' -> '0.23456778' -- some carrying effects dqsub321 subtract '0.9998' '0.0000' -> '0.9998' dqsub322 subtract '0.9998' '0.0001' -> '0.9997' dqsub323 subtract '0.9998' '0.0002' -> '0.9996' dqsub324 subtract '0.9998' '0.0003' -> '0.9995' dqsub325 subtract '0.9998' '-0.0000' -> '0.9998' dqsub326 subtract '0.9998' '-0.0001' -> '0.9999' dqsub327 subtract '0.9998' '-0.0002' -> '1.0000' dqsub328 subtract '0.9998' '-0.0003' -> '1.0001' -- internal boundaries dqsub346 subtract '10000e+9' '7' -> '9999999999993' dqsub347 subtract '10000e+9' '70' -> '9999999999930' dqsub348 subtract '10000e+9' '700' -> '9999999999300' dqsub349 subtract '10000e+9' '7000' -> '9999999993000' dqsub350 subtract '10000e+9' '70000' -> '9999999930000' dqsub351 subtract '10000e+9' '700000' -> '9999999300000' dqsub352 subtract '7' '10000e+9' -> '-9999999999993' dqsub353 subtract '70' '10000e+9' -> '-9999999999930' dqsub354 subtract '700' '10000e+9' -> '-9999999999300' dqsub355 subtract '7000' '10000e+9' -> '-9999999993000' dqsub356 subtract '70000' '10000e+9' -> '-9999999930000' dqsub357 subtract '700000' '10000e+9' -> '-9999999300000' -- zero preservation dqsub361 subtract 1 '0.0001' -> '0.9999' dqsub362 subtract 1 '0.00001' -> '0.99999' dqsub363 subtract 1 '0.000001' -> '0.999999' dqsub364 subtract 1 '0.0000000000000000000000000000000001' -> '0.9999999999999999999999999999999999' dqsub365 subtract 1 '0.00000000000000000000000000000000001' -> '1.000000000000000000000000000000000' Inexact Rounded dqsub366 subtract 1 '0.000000000000000000000000000000000001' -> '1.000000000000000000000000000000000' Inexact Rounded -- some funny zeros [in case of bad signum] dqsub370 subtract 1 0 -> 1 dqsub371 subtract 1 0. -> 1 dqsub372 subtract 1 .0 -> 1.0 dqsub373 subtract 1 0.0 -> 1.0 dqsub374 subtract 0 1 -> -1 dqsub375 subtract 0. 1 -> -1 dqsub376 subtract .0 1 -> -1.0 dqsub377 subtract 0.0 1 -> -1.0 -- leading 0 digit before round dqsub910 subtract -103519362 -51897955.3 -> -51621406.7 dqsub911 subtract 159579.444 89827.5229 -> 69751.9211 dqsub920 subtract 333.0000000000000000000000000123456 33.00000000000000000000000001234566 -> 299.9999999999999999999999999999999 Inexact Rounded dqsub921 subtract 333.0000000000000000000000000123456 33.00000000000000000000000001234565 -> 300.0000000000000000000000000000000 Inexact Rounded dqsub922 subtract 133.0000000000000000000000000123456 33.00000000000000000000000001234565 -> 99.99999999999999999999999999999995 dqsub923 subtract 133.0000000000000000000000000123456 33.00000000000000000000000001234564 -> 99.99999999999999999999999999999996 dqsub924 subtract 133.0000000000000000000000000123456 33.00000000000000000000000001234540 -> 100.0000000000000000000000000000002 Rounded dqsub925 subtract 133.0000000000000000000000000123456 43.00000000000000000000000001234560 -> 90.00000000000000000000000000000000 dqsub926 subtract 133.0000000000000000000000000123456 43.00000000000000000000000001234561 -> 89.99999999999999999999999999999999 dqsub927 subtract 133.0000000000000000000000000123456 43.00000000000000000000000001234566 -> 89.99999999999999999999999999999994 dqsub928 subtract 101.0000000000000000000000000123456 91.00000000000000000000000001234566 -> 9.99999999999999999999999999999994 dqsub929 subtract 101.0000000000000000000000000123456 99.00000000000000000000000001234566 -> 1.99999999999999999999999999999994 -- more LHS swaps [were fixed] dqsub390 subtract '-56267E-10' 0 -> '-0.0000056267' dqsub391 subtract '-56267E-6' 0 -> '-0.056267' dqsub392 subtract '-56267E-5' 0 -> '-0.56267' dqsub393 subtract '-56267E-4' 0 -> '-5.6267' dqsub394 subtract '-56267E-3' 0 -> '-56.267' dqsub395 subtract '-56267E-2' 0 -> '-562.67' dqsub396 subtract '-56267E-1' 0 -> '-5626.7' dqsub397 subtract '-56267E-0' 0 -> '-56267' dqsub398 subtract '-5E-10' 0 -> '-5E-10' dqsub399 subtract '-5E-7' 0 -> '-5E-7' dqsub400 subtract '-5E-6' 0 -> '-0.000005' dqsub401 subtract '-5E-5' 0 -> '-0.00005' dqsub402 subtract '-5E-4' 0 -> '-0.0005' dqsub403 subtract '-5E-1' 0 -> '-0.5' dqsub404 subtract '-5E0' 0 -> '-5' dqsub405 subtract '-5E1' 0 -> '-50' dqsub406 subtract '-5E5' 0 -> '-500000' dqsub407 subtract '-5E33' 0 -> '-5000000000000000000000000000000000' dqsub408 subtract '-5E34' 0 -> '-5.000000000000000000000000000000000E+34' Rounded dqsub409 subtract '-5E35' 0 -> '-5.000000000000000000000000000000000E+35' Rounded dqsub410 subtract '-5E36' 0 -> '-5.000000000000000000000000000000000E+36' Rounded dqsub411 subtract '-5E100' 0 -> '-5.000000000000000000000000000000000E+100' Rounded -- more RHS swaps [were fixed] dqsub420 subtract 0 '-56267E-10' -> '0.0000056267' dqsub421 subtract 0 '-56267E-6' -> '0.056267' dqsub422 subtract 0 '-56267E-5' -> '0.56267' dqsub423 subtract 0 '-56267E-4' -> '5.6267' dqsub424 subtract 0 '-56267E-3' -> '56.267' dqsub425 subtract 0 '-56267E-2' -> '562.67' dqsub426 subtract 0 '-56267E-1' -> '5626.7' dqsub427 subtract 0 '-56267E-0' -> '56267' dqsub428 subtract 0 '-5E-10' -> '5E-10' dqsub429 subtract 0 '-5E-7' -> '5E-7' dqsub430 subtract 0 '-5E-6' -> '0.000005' dqsub431 subtract 0 '-5E-5' -> '0.00005' dqsub432 subtract 0 '-5E-4' -> '0.0005' dqsub433 subtract 0 '-5E-1' -> '0.5' dqsub434 subtract 0 '-5E0' -> '5' dqsub435 subtract 0 '-5E1' -> '50' dqsub436 subtract 0 '-5E5' -> '500000' dqsub437 subtract 0 '-5E33' -> '5000000000000000000000000000000000' dqsub438 subtract 0 '-5E34' -> '5.000000000000000000000000000000000E+34' Rounded dqsub439 subtract 0 '-5E35' -> '5.000000000000000000000000000000000E+35' Rounded dqsub440 subtract 0 '-5E36' -> '5.000000000000000000000000000000000E+36' Rounded dqsub441 subtract 0 '-5E100' -> '5.000000000000000000000000000000000E+100' Rounded -- try borderline precision, with carries, etc. dqsub461 subtract '1E+16' '1' -> '9999999999999999' dqsub462 subtract '1E+12' '-1.111' -> '1000000000001.111' dqsub463 subtract '1.111' '-1E+12' -> '1000000000001.111' dqsub464 subtract '-1' '-1E+16' -> '9999999999999999' dqsub465 subtract '7E+15' '1' -> '6999999999999999' dqsub466 subtract '7E+12' '-1.111' -> '7000000000001.111' dqsub467 subtract '1.111' '-7E+12' -> '7000000000001.111' dqsub468 subtract '-1' '-7E+15' -> '6999999999999999' -- 1234567890123456 1234567890123456 1 23456789012345 dqsub470 subtract '0.4444444444444444444444444444444444' '-0.5555555555555555555555555555555563' -> '1.000000000000000000000000000000001' Inexact Rounded dqsub471 subtract '0.4444444444444444444444444444444444' '-0.5555555555555555555555555555555562' -> '1.000000000000000000000000000000001' Inexact Rounded dqsub472 subtract '0.4444444444444444444444444444444444' '-0.5555555555555555555555555555555561' -> '1.000000000000000000000000000000000' Inexact Rounded dqsub473 subtract '0.4444444444444444444444444444444444' '-0.5555555555555555555555555555555560' -> '1.000000000000000000000000000000000' Inexact Rounded dqsub474 subtract '0.4444444444444444444444444444444444' '-0.5555555555555555555555555555555559' -> '1.000000000000000000000000000000000' Inexact Rounded dqsub475 subtract '0.4444444444444444444444444444444444' '-0.5555555555555555555555555555555558' -> '1.000000000000000000000000000000000' Inexact Rounded dqsub476 subtract '0.4444444444444444444444444444444444' '-0.5555555555555555555555555555555557' -> '1.000000000000000000000000000000000' Inexact Rounded dqsub477 subtract '0.4444444444444444444444444444444444' '-0.5555555555555555555555555555555556' -> '1.000000000000000000000000000000000' Rounded dqsub478 subtract '0.4444444444444444444444444444444444' '-0.5555555555555555555555555555555555' -> '0.9999999999999999999999999999999999' dqsub479 subtract '0.4444444444444444444444444444444444' '-0.5555555555555555555555555555555554' -> '0.9999999999999999999999999999999998' dqsub480 subtract '0.4444444444444444444444444444444444' '-0.5555555555555555555555555555555553' -> '0.9999999999999999999999999999999997' dqsub481 subtract '0.4444444444444444444444444444444444' '-0.5555555555555555555555555555555552' -> '0.9999999999999999999999999999999996' dqsub482 subtract '0.4444444444444444444444444444444444' '-0.5555555555555555555555555555555551' -> '0.9999999999999999999999999999999995' dqsub483 subtract '0.4444444444444444444444444444444444' '-0.5555555555555555555555555555555550' -> '0.9999999999999999999999999999999994' -- and some more, including residue effects and different roundings rounding: half_up dqsub500 subtract '1231234555555555555555555567456789' 0 -> '1231234555555555555555555567456789' dqsub501 subtract '1231234555555555555555555567456789' 0.000000001 -> '1231234555555555555555555567456789' Inexact Rounded dqsub502 subtract '1231234555555555555555555567456789' 0.000001 -> '1231234555555555555555555567456789' Inexact Rounded dqsub503 subtract '1231234555555555555555555567456789' 0.1 -> '1231234555555555555555555567456789' Inexact Rounded dqsub504 subtract '1231234555555555555555555567456789' 0.4 -> '1231234555555555555555555567456789' Inexact Rounded dqsub505 subtract '1231234555555555555555555567456789' 0.49 -> '1231234555555555555555555567456789' Inexact Rounded dqsub506 subtract '1231234555555555555555555567456789' 0.499999 -> '1231234555555555555555555567456789' Inexact Rounded dqsub507 subtract '1231234555555555555555555567456789' 0.499999999 -> '1231234555555555555555555567456789' Inexact Rounded dqsub508 subtract '1231234555555555555555555567456789' 0.5 -> '1231234555555555555555555567456789' Inexact Rounded dqsub509 subtract '1231234555555555555555555567456789' 0.500000001 -> '1231234555555555555555555567456788' Inexact Rounded dqsub510 subtract '1231234555555555555555555567456789' 0.500001 -> '1231234555555555555555555567456788' Inexact Rounded dqsub511 subtract '1231234555555555555555555567456789' 0.51 -> '1231234555555555555555555567456788' Inexact Rounded dqsub512 subtract '1231234555555555555555555567456789' 0.6 -> '1231234555555555555555555567456788' Inexact Rounded dqsub513 subtract '1231234555555555555555555567456789' 0.9 -> '1231234555555555555555555567456788' Inexact Rounded dqsub514 subtract '1231234555555555555555555567456789' 0.99999 -> '1231234555555555555555555567456788' Inexact Rounded dqsub515 subtract '1231234555555555555555555567456789' 0.999999999 -> '1231234555555555555555555567456788' Inexact Rounded dqsub516 subtract '1231234555555555555555555567456789' 1 -> '1231234555555555555555555567456788' dqsub517 subtract '1231234555555555555555555567456789' 1.000000001 -> '1231234555555555555555555567456788' Inexact Rounded dqsub518 subtract '1231234555555555555555555567456789' 1.00001 -> '1231234555555555555555555567456788' Inexact Rounded dqsub519 subtract '1231234555555555555555555567456789' 1.1 -> '1231234555555555555555555567456788' Inexact Rounded rounding: half_even dqsub520 subtract '1231234555555555555555555567456789' 0 -> '1231234555555555555555555567456789' dqsub521 subtract '1231234555555555555555555567456789' 0.000000001 -> '1231234555555555555555555567456789' Inexact Rounded dqsub522 subtract '1231234555555555555555555567456789' 0.000001 -> '1231234555555555555555555567456789' Inexact Rounded dqsub523 subtract '1231234555555555555555555567456789' 0.1 -> '1231234555555555555555555567456789' Inexact Rounded dqsub524 subtract '1231234555555555555555555567456789' 0.4 -> '1231234555555555555555555567456789' Inexact Rounded dqsub525 subtract '1231234555555555555555555567456789' 0.49 -> '1231234555555555555555555567456789' Inexact Rounded dqsub526 subtract '1231234555555555555555555567456789' 0.499999 -> '1231234555555555555555555567456789' Inexact Rounded dqsub527 subtract '1231234555555555555555555567456789' 0.499999999 -> '1231234555555555555555555567456789' Inexact Rounded dqsub528 subtract '1231234555555555555555555567456789' 0.5 -> '1231234555555555555555555567456788' Inexact Rounded dqsub529 subtract '1231234555555555555555555567456789' 0.500000001 -> '1231234555555555555555555567456788' Inexact Rounded dqsub530 subtract '1231234555555555555555555567456789' 0.500001 -> '1231234555555555555555555567456788' Inexact Rounded dqsub531 subtract '1231234555555555555555555567456789' 0.51 -> '1231234555555555555555555567456788' Inexact Rounded dqsub532 subtract '1231234555555555555555555567456789' 0.6 -> '1231234555555555555555555567456788' Inexact Rounded dqsub533 subtract '1231234555555555555555555567456789' 0.9 -> '1231234555555555555555555567456788' Inexact Rounded dqsub534 subtract '1231234555555555555555555567456789' 0.99999 -> '1231234555555555555555555567456788' Inexact Rounded dqsub535 subtract '1231234555555555555555555567456789' 0.999999999 -> '1231234555555555555555555567456788' Inexact Rounded dqsub536 subtract '1231234555555555555555555567456789' 1 -> '1231234555555555555555555567456788' dqsub537 subtract '1231234555555555555555555567456789' 1.00000001 -> '1231234555555555555555555567456788' Inexact Rounded dqsub538 subtract '1231234555555555555555555567456789' 1.00001 -> '1231234555555555555555555567456788' Inexact Rounded dqsub539 subtract '1231234555555555555555555567456789' 1.1 -> '1231234555555555555555555567456788' Inexact Rounded -- critical few with even bottom digit... dqsub540 subtract '1231234555555555555555555567456788' 0.499999999 -> '1231234555555555555555555567456788' Inexact Rounded dqsub541 subtract '1231234555555555555555555567456788' 0.5 -> '1231234555555555555555555567456788' Inexact Rounded dqsub542 subtract '1231234555555555555555555567456788' 0.500000001 -> '1231234555555555555555555567456787' Inexact Rounded rounding: down dqsub550 subtract '1231234555555555555555555567456789' 0 -> '1231234555555555555555555567456789' dqsub551 subtract '1231234555555555555555555567456789' 0.000000001 -> '1231234555555555555555555567456788' Inexact Rounded dqsub552 subtract '1231234555555555555555555567456789' 0.000001 -> '1231234555555555555555555567456788' Inexact Rounded dqsub553 subtract '1231234555555555555555555567456789' 0.1 -> '1231234555555555555555555567456788' Inexact Rounded dqsub554 subtract '1231234555555555555555555567456789' 0.4 -> '1231234555555555555555555567456788' Inexact Rounded dqsub555 subtract '1231234555555555555555555567456789' 0.49 -> '1231234555555555555555555567456788' Inexact Rounded dqsub556 subtract '1231234555555555555555555567456789' 0.499999 -> '1231234555555555555555555567456788' Inexact Rounded dqsub557 subtract '1231234555555555555555555567456789' 0.499999999 -> '1231234555555555555555555567456788' Inexact Rounded dqsub558 subtract '1231234555555555555555555567456789' 0.5 -> '1231234555555555555555555567456788' Inexact Rounded dqsub559 subtract '1231234555555555555555555567456789' 0.500000001 -> '1231234555555555555555555567456788' Inexact Rounded dqsub560 subtract '1231234555555555555555555567456789' 0.500001 -> '1231234555555555555555555567456788' Inexact Rounded dqsub561 subtract '1231234555555555555555555567456789' 0.51 -> '1231234555555555555555555567456788' Inexact Rounded dqsub562 subtract '1231234555555555555555555567456789' 0.6 -> '1231234555555555555555555567456788' Inexact Rounded dqsub563 subtract '1231234555555555555555555567456789' 0.9 -> '1231234555555555555555555567456788' Inexact Rounded dqsub564 subtract '1231234555555555555555555567456789' 0.99999 -> '1231234555555555555555555567456788' Inexact Rounded dqsub565 subtract '1231234555555555555555555567456789' 0.999999999 -> '1231234555555555555555555567456788' Inexact Rounded dqsub566 subtract '1231234555555555555555555567456789' 1 -> '1231234555555555555555555567456788' dqsub567 subtract '1231234555555555555555555567456789' 1.00000001 -> '1231234555555555555555555567456787' Inexact Rounded dqsub568 subtract '1231234555555555555555555567456789' 1.00001 -> '1231234555555555555555555567456787' Inexact Rounded dqsub569 subtract '1231234555555555555555555567456789' 1.1 -> '1231234555555555555555555567456787' Inexact Rounded -- symmetry... rounding: half_up dqsub600 subtract 0 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456789' dqsub601 subtract 0.000000001 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456789' Inexact Rounded dqsub602 subtract 0.000001 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456789' Inexact Rounded dqsub603 subtract 0.1 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456789' Inexact Rounded dqsub604 subtract 0.4 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456789' Inexact Rounded dqsub605 subtract 0.49 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456789' Inexact Rounded dqsub606 subtract 0.499999 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456789' Inexact Rounded dqsub607 subtract 0.499999999 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456789' Inexact Rounded dqsub608 subtract 0.5 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456789' Inexact Rounded dqsub609 subtract 0.500000001 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456788' Inexact Rounded dqsub610 subtract 0.500001 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456788' Inexact Rounded dqsub611 subtract 0.51 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456788' Inexact Rounded dqsub612 subtract 0.6 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456788' Inexact Rounded dqsub613 subtract 0.9 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456788' Inexact Rounded dqsub614 subtract 0.99999 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456788' Inexact Rounded dqsub615 subtract 0.999999999 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456788' Inexact Rounded dqsub616 subtract 1 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456788' dqsub617 subtract 1.000000001 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456788' Inexact Rounded dqsub618 subtract 1.00001 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456788' Inexact Rounded dqsub619 subtract 1.1 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456788' Inexact Rounded rounding: half_even dqsub620 subtract 0 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456789' dqsub621 subtract 0.000000001 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456789' Inexact Rounded dqsub622 subtract 0.000001 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456789' Inexact Rounded dqsub623 subtract 0.1 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456789' Inexact Rounded dqsub624 subtract 0.4 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456789' Inexact Rounded dqsub625 subtract 0.49 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456789' Inexact Rounded dqsub626 subtract 0.499999 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456789' Inexact Rounded dqsub627 subtract 0.499999999 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456789' Inexact Rounded dqsub628 subtract 0.5 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456788' Inexact Rounded dqsub629 subtract 0.500000001 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456788' Inexact Rounded dqsub630 subtract 0.500001 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456788' Inexact Rounded dqsub631 subtract 0.51 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456788' Inexact Rounded dqsub632 subtract 0.6 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456788' Inexact Rounded dqsub633 subtract 0.9 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456788' Inexact Rounded dqsub634 subtract 0.99999 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456788' Inexact Rounded dqsub635 subtract 0.999999999 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456788' Inexact Rounded dqsub636 subtract 1 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456788' dqsub637 subtract 1.00000001 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456788' Inexact Rounded dqsub638 subtract 1.00001 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456788' Inexact Rounded dqsub639 subtract 1.1 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456788' Inexact Rounded -- critical few with even bottom digit... dqsub640 subtract 0.499999999 '1231234555555555555555555567456788' -> '-1231234555555555555555555567456788' Inexact Rounded dqsub641 subtract 0.5 '1231234555555555555555555567456788' -> '-1231234555555555555555555567456788' Inexact Rounded dqsub642 subtract 0.500000001 '1231234555555555555555555567456788' -> '-1231234555555555555555555567456787' Inexact Rounded rounding: down dqsub650 subtract 0 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456789' dqsub651 subtract 0.000000001 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456788' Inexact Rounded dqsub652 subtract 0.000001 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456788' Inexact Rounded dqsub653 subtract 0.1 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456788' Inexact Rounded dqsub654 subtract 0.4 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456788' Inexact Rounded dqsub655 subtract 0.49 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456788' Inexact Rounded dqsub656 subtract 0.499999 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456788' Inexact Rounded dqsub657 subtract 0.499999999 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456788' Inexact Rounded dqsub658 subtract 0.5 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456788' Inexact Rounded dqsub659 subtract 0.500000001 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456788' Inexact Rounded dqsub660 subtract 0.500001 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456788' Inexact Rounded dqsub661 subtract 0.51 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456788' Inexact Rounded dqsub662 subtract 0.6 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456788' Inexact Rounded dqsub663 subtract 0.9 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456788' Inexact Rounded dqsub664 subtract 0.99999 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456788' Inexact Rounded dqsub665 subtract 0.999999999 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456788' Inexact Rounded dqsub666 subtract 1 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456788' dqsub667 subtract 1.00000001 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456787' Inexact Rounded dqsub668 subtract 1.00001 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456787' Inexact Rounded dqsub669 subtract 1.1 '1231234555555555555555555567456789' -> '-1231234555555555555555555567456787' Inexact Rounded -- lots of leading zeros in intermediate result, and showing effects of -- input rounding would have affected the following rounding: half_up dqsub670 subtract '1234567456789' '1234567456788.1' -> 0.9 dqsub671 subtract '1234567456789' '1234567456788.9' -> 0.1 dqsub672 subtract '1234567456789' '1234567456789.1' -> -0.1 dqsub673 subtract '1234567456789' '1234567456789.5' -> -0.5 dqsub674 subtract '1234567456789' '1234567456789.9' -> -0.9 rounding: half_even dqsub680 subtract '1234567456789' '1234567456788.1' -> 0.9 dqsub681 subtract '1234567456789' '1234567456788.9' -> 0.1 dqsub682 subtract '1234567456789' '1234567456789.1' -> -0.1 dqsub683 subtract '1234567456789' '1234567456789.5' -> -0.5 dqsub684 subtract '1234567456789' '1234567456789.9' -> -0.9 dqsub685 subtract '1234567456788' '1234567456787.1' -> 0.9 dqsub686 subtract '1234567456788' '1234567456787.9' -> 0.1 dqsub687 subtract '1234567456788' '1234567456788.1' -> -0.1 dqsub688 subtract '1234567456788' '1234567456788.5' -> -0.5 dqsub689 subtract '1234567456788' '1234567456788.9' -> -0.9 rounding: down dqsub690 subtract '1234567456789' '1234567456788.1' -> 0.9 dqsub691 subtract '1234567456789' '1234567456788.9' -> 0.1 dqsub692 subtract '1234567456789' '1234567456789.1' -> -0.1 dqsub693 subtract '1234567456789' '1234567456789.5' -> -0.5 dqsub694 subtract '1234567456789' '1234567456789.9' -> -0.9 -- Specials dqsub780 subtract -Inf Inf -> -Infinity dqsub781 subtract -Inf 1000 -> -Infinity dqsub782 subtract -Inf 1 -> -Infinity dqsub783 subtract -Inf -0 -> -Infinity dqsub784 subtract -Inf -1 -> -Infinity dqsub785 subtract -Inf -1000 -> -Infinity dqsub787 subtract -1000 Inf -> -Infinity dqsub788 subtract -Inf Inf -> -Infinity dqsub789 subtract -1 Inf -> -Infinity dqsub790 subtract 0 Inf -> -Infinity dqsub791 subtract 1 Inf -> -Infinity dqsub792 subtract 1000 Inf -> -Infinity dqsub800 subtract Inf Inf -> NaN Invalid_operation dqsub801 subtract Inf 1000 -> Infinity dqsub802 subtract Inf 1 -> Infinity dqsub803 subtract Inf 0 -> Infinity dqsub804 subtract Inf -0 -> Infinity dqsub805 subtract Inf -1 -> Infinity dqsub806 subtract Inf -1000 -> Infinity dqsub807 subtract Inf -Inf -> Infinity dqsub808 subtract -1000 -Inf -> Infinity dqsub809 subtract -Inf -Inf -> NaN Invalid_operation dqsub810 subtract -1 -Inf -> Infinity dqsub811 subtract -0 -Inf -> Infinity dqsub812 subtract 0 -Inf -> Infinity dqsub813 subtract 1 -Inf -> Infinity dqsub814 subtract 1000 -Inf -> Infinity dqsub815 subtract Inf -Inf -> Infinity dqsub821 subtract NaN Inf -> NaN dqsub822 subtract -NaN 1000 -> -NaN dqsub823 subtract NaN 1 -> NaN dqsub824 subtract NaN 0 -> NaN dqsub825 subtract NaN -0 -> NaN dqsub826 subtract NaN -1 -> NaN dqsub827 subtract NaN -1000 -> NaN dqsub828 subtract NaN -Inf -> NaN dqsub829 subtract -NaN NaN -> -NaN dqsub830 subtract -Inf NaN -> NaN dqsub831 subtract -1000 NaN -> NaN dqsub832 subtract -1 NaN -> NaN dqsub833 subtract -0 NaN -> NaN dqsub834 subtract 0 NaN -> NaN dqsub835 subtract 1 NaN -> NaN dqsub836 subtract 1000 -NaN -> -NaN dqsub837 subtract Inf NaN -> NaN dqsub841 subtract sNaN Inf -> NaN Invalid_operation dqsub842 subtract -sNaN 1000 -> -NaN Invalid_operation dqsub843 subtract sNaN 1 -> NaN Invalid_operation dqsub844 subtract sNaN 0 -> NaN Invalid_operation dqsub845 subtract sNaN -0 -> NaN Invalid_operation dqsub846 subtract sNaN -1 -> NaN Invalid_operation dqsub847 subtract sNaN -1000 -> NaN Invalid_operation dqsub848 subtract sNaN NaN -> NaN Invalid_operation dqsub849 subtract sNaN sNaN -> NaN Invalid_operation dqsub850 subtract NaN sNaN -> NaN Invalid_operation dqsub851 subtract -Inf -sNaN -> -NaN Invalid_operation dqsub852 subtract -1000 sNaN -> NaN Invalid_operation dqsub853 subtract -1 sNaN -> NaN Invalid_operation dqsub854 subtract -0 sNaN -> NaN Invalid_operation dqsub855 subtract 0 sNaN -> NaN Invalid_operation dqsub856 subtract 1 sNaN -> NaN Invalid_operation dqsub857 subtract 1000 sNaN -> NaN Invalid_operation dqsub858 subtract Inf sNaN -> NaN Invalid_operation dqsub859 subtract NaN sNaN -> NaN Invalid_operation -- propagating NaNs dqsub861 subtract NaN01 -Inf -> NaN1 dqsub862 subtract -NaN02 -1000 -> -NaN2 dqsub863 subtract NaN03 1000 -> NaN3 dqsub864 subtract NaN04 Inf -> NaN4 dqsub865 subtract NaN05 NaN61 -> NaN5 dqsub866 subtract -Inf -NaN71 -> -NaN71 dqsub867 subtract -1000 NaN81 -> NaN81 dqsub868 subtract 1000 NaN91 -> NaN91 dqsub869 subtract Inf NaN101 -> NaN101 dqsub871 subtract sNaN011 -Inf -> NaN11 Invalid_operation dqsub872 subtract sNaN012 -1000 -> NaN12 Invalid_operation dqsub873 subtract -sNaN013 1000 -> -NaN13 Invalid_operation dqsub874 subtract sNaN014 NaN171 -> NaN14 Invalid_operation dqsub875 subtract sNaN015 sNaN181 -> NaN15 Invalid_operation dqsub876 subtract NaN016 sNaN191 -> NaN191 Invalid_operation dqsub877 subtract -Inf sNaN201 -> NaN201 Invalid_operation dqsub878 subtract -1000 sNaN211 -> NaN211 Invalid_operation dqsub879 subtract 1000 -sNaN221 -> -NaN221 Invalid_operation dqsub880 subtract Inf sNaN231 -> NaN231 Invalid_operation dqsub881 subtract NaN025 sNaN241 -> NaN241 Invalid_operation -- edge case spills dqsub901 subtract 2.E-3 1.002 -> -1.000 dqsub902 subtract 2.0E-3 1.002 -> -1.0000 dqsub903 subtract 2.00E-3 1.0020 -> -1.00000 dqsub904 subtract 2.000E-3 1.00200 -> -1.000000 dqsub905 subtract 2.0000E-3 1.002000 -> -1.0000000 dqsub906 subtract 2.00000E-3 1.0020000 -> -1.00000000 dqsub907 subtract 2.000000E-3 1.00200000 -> -1.000000000 dqsub908 subtract 2.0000000E-3 1.002000000 -> -1.0000000000 -- subnormals and overflows covered under Add -- Examples from SQL proposal (Krishna Kulkarni) dqsub1125 subtract 130E-2 120E-2 -> 0.10 dqsub1126 subtract 130E-2 12E-1 -> 0.10 dqsub1127 subtract 130E-2 1E0 -> 0.30 dqsub1128 subtract 1E2 1E4 -> -9.9E+3 -- Null tests dqsub9990 subtract 10 # -> NaN Invalid_operation dqsub9991 subtract # 10 -> NaN Invalid_operation
{ "pile_set_name": "Github" }
%YAML 1.1 %TAG !u! tag:unity3d.com,2011: --- !u!74 &7400000 AnimationClip: m_ObjectHideFlags: 0 m_PrefabParentObject: {fileID: 0} m_PrefabInternal: {fileID: 0} m_Name: PropGearLowered serializedVersion: 6 m_Legacy: 0 m_Compressed: 0 m_UseHighQualityCurve: 1 m_RotationCurves: [] m_CompressedRotationCurves: [] m_PositionCurves: [] m_ScaleCurves: [] m_FloatCurves: [] m_PPtrCurves: [] m_SampleRate: 60 m_WrapMode: 0 m_Bounds: m_Center: {x: 0, y: 0, z: 0} m_Extent: {x: 0, y: 0, z: 0} m_ClipBindingConstant: genericBindings: [] pptrCurveMapping: [] m_AnimationClipSettings: serializedVersion: 2 m_StartTime: 0 m_StopTime: 1 m_OrientationOffsetY: 0 m_Level: 0 m_CycleOffset: 0 m_LoopTime: 0 m_LoopBlend: 0 m_LoopBlendOrientation: 0 m_LoopBlendPositionY: 0 m_LoopBlendPositionXZ: 0 m_KeepOriginalOrientation: 0 m_KeepOriginalPositionY: 1 m_KeepOriginalPositionXZ: 0 m_HeightFromFeet: 0 m_Mirror: 0 m_EditorCurves: [] m_EulerEditorCurves: [] m_HasGenericRootTransform: 0 m_HasMotionFloatCurves: 0 m_GenerateMotionCurves: 0 m_Events: []
{ "pile_set_name": "Github" }
" Vim filetype plugin file " Language: RFC 2614 - An API for Service Location registration file " Maintainer: Nikolai Weibull <now@bitwi.se> " Latest Revision: 2008-07-09 if exists("b:did_ftplugin") finish endif let b:did_ftplugin = 1 let s:cpo_save = &cpo set cpo&vim let b:undo_ftplugin = "setl com< cms< fo<" setlocal comments=:#,:; commentstring=#\ %s setlocal formatoptions-=t formatoptions+=croql let &cpo = s:cpo_save unlet s:cpo_save
{ "pile_set_name": "Github" }
#include"io.h" int main(void) { long long rd, rs, rt; long long dsp; long long result; rs = 0x11777066; rt = 0x55AA70FF; result = 0x0F; __asm ("cmpgdu.le.qb %0, %2, %3\n\t" "rddsp %1\n\t" : "=r"(rd), "=r"(dsp) : "r"(rs), "r"(rt) ); dsp = (dsp >> 24) & 0x0F; if (rd != result) { printf("cmpgdu.le.qb error\n"); return -1; } if (dsp != result) { printf("cmpgdu.le.qb error\n"); return -1; } rs = 0x11777066; rt = 0x11707066; result = 0x0B; __asm ("cmpgdu.le.qb %0, %2, %3\n\t" "rddsp %1\n\t" : "=r"(rd), "=r"(dsp) : "r"(rs), "r"(rt) ); dsp = (dsp >> 24) & 0x0F; if (rd != result) { printf("cmpgdu.le.qb error\n"); return -1; } if (dsp != result) { printf("cmpgdu.le.qb error\n"); return -1; } return 0; }
{ "pile_set_name": "Github" }
package com.alibaba.datax.plugin.reader.mysqlreader; import com.alibaba.datax.common.spi.ErrorCode; public enum MysqlReaderErrorCode implements ErrorCode { ; private final String code; private final String description; private MysqlReaderErrorCode(String code, String description) { this.code = code; this.description = description; } @Override public String getCode() { return this.code; } @Override public String getDescription() { return this.description; } @Override public String toString() { return String.format("Code:[%s], Description:[%s]. ", this.code, this.description); } }
{ "pile_set_name": "Github" }
--- title: "Use React and JSX in ASP.NET MVC" author: [Daniel15] --- Today we're happy to announce the initial release of [ReactJS.NET](http://reactjs.net/), which makes it easier to use React and JSX in .NET applications, focusing specifically on ASP.NET MVC web applications. It has several purposes: - On-the-fly JSX to JavaScript compilation. Simply reference JSX files and they will be compiled and cached server-side. ```html <script src="@Url.Content("/Scripts/HelloWorld.jsx")"></script> ``` - JSX to JavaScript compilation via popular minification/combination libraries (Cassette and ASP.NET Bundling and Minification). This is suggested for production websites. - Server-side component rendering to make your initial render super fast. Even though we are focusing on ASP.NET MVC, ReactJS.NET can also be used in Web Forms applications as well as non-web applications (for example, in build scripts). ReactJS.NET currently only works on Microsoft .NET but we are working on support for Linux and Mac OS X via Mono as well. Installation ------------ ReactJS.NET is packaged in NuGet. Simply run `Install-Package React.Mvc4` in the package manager console or search NuGet for "React" to install it. [See the documentation](http://reactjs.net/docs) for more information. The GitHub project contains [a sample website](https://github.com/reactjs/React.NET/tree/master/src/React.Sample.Mvc4) demonstrating all of the features. Let us know what you think, and feel free to send through any feedback and report bugs [on GitHub](https://github.com/reactjs/React.NET).
{ "pile_set_name": "Github" }
/* $Id: store-inmem.cpp $ */ /** @file * IPRT - In Memory Cryptographic Certificate Store. */ /* * Copyright (C) 2006-2017 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. * * The contents of this file may alternatively be used under the terms * of the Common Development and Distribution License Version 1.0 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the * VirtualBox OSE distribution, in which case the provisions of the * CDDL are applicable instead of those of the GPL. * * You may elect to license modified versions of this file under the * terms and conditions of either the GPL or the CDDL or both. */ /********************************************************************************************************************************* * Header Files * *********************************************************************************************************************************/ #include "internal/iprt.h" #include <iprt/crypto/store.h> #include <iprt/asm.h> #include <iprt/err.h> #include <iprt/mem.h> #include <iprt/string.h> #include "store-internal.h" /********************************************************************************************************************************* * Structures and Typedefs * *********************************************************************************************************************************/ /** * A certificate entry in the in-memory store. */ typedef struct RTCRSTOREINMEMCERT { /** The core certificate context. */ RTCRCERTCTXINT Core; /** Internal copy of the flag (paranoia). */ uint32_t fFlags; /** Decoded data. */ union { /** ASN.1 core structure for generic access. */ RTASN1CORE Asn1Core; /** The decoded X.509 certificate (RTCRCERTCTX_F_ENC_X509_DER). */ RTCRX509CERTIFICATE X509Cert; /** The decoded trust anchor info (RTCRCERTCTX_F_ENC_TAF_DER). */ RTCRTAFTRUSTANCHORINFO TaInfo; } u; /** Pointer to the store if still in it (no reference). */ struct RTCRSTOREINMEM *pStore; /** The DER encoding of the certificate. */ uint8_t abEncoded[1]; } RTCRSTOREINMEMCERT; AssertCompileMembersAtSameOffset(RTCRSTOREINMEMCERT, u.X509Cert.SeqCore.Asn1Core, RTCRSTOREINMEMCERT, u.Asn1Core); AssertCompileMembersAtSameOffset(RTCRSTOREINMEMCERT, u.TaInfo.SeqCore.Asn1Core, RTCRSTOREINMEMCERT, u.Asn1Core); /** Pointer to an in-memory store certificate entry. */ typedef RTCRSTOREINMEMCERT *PRTCRSTOREINMEMCERT; /** * The per instance data of a in-memory crypto store. * * Currently we ASSUME we don't need serialization. Add that when needed! */ typedef struct RTCRSTOREINMEM { /** The number of certificates. */ uint32_t cCerts; /** The max number of certificates papCerts can store before growing it. */ uint32_t cCertsAlloc; /** Array of certificates. */ PRTCRSTOREINMEMCERT *papCerts; } RTCRSTOREINMEM; /** Pointer to an in-memory crypto store. */ typedef RTCRSTOREINMEM *PRTCRSTOREINMEM; static DECLCALLBACK(void) rtCrStoreInMemCertEntry_Dtor(PRTCRCERTCTXINT pCertCtx) { PRTCRSTOREINMEMCERT pEntry = (PRTCRSTOREINMEMCERT)pCertCtx; AssertRelease(!pEntry->pStore); pEntry->Core.pfnDtor = NULL; RTAsn1VtDelete(&pEntry->u.Asn1Core); RTMemFree(pEntry); } /** * Internal method for allocating and initalizing a certificate entry in the * in-memory store. * * @returns IPRT status code. * @param pThis The in-memory store instance. * @param fEnc RTCRCERTCTX_F_ENC_X509_DER or RTCRCERTCTX_F_ENC_TAF_DER. * @param pbSrc The DER encoded X.509 certificate to add. * @param cbSrc The size of the encoded certificate. * @param pErrInfo Where to return extended error info. Optional. * @param ppEntry Where to return the pointer to the new entry. */ static int rtCrStoreInMemCreateCertEntry(PRTCRSTOREINMEM pThis, uint32_t fEnc, uint8_t const *pbSrc, uint32_t cbSrc, PRTERRINFO pErrInfo, PRTCRSTOREINMEMCERT *ppEntry) { int rc; PRTCRSTOREINMEMCERT pEntry = (PRTCRSTOREINMEMCERT)RTMemAllocZ(RT_UOFFSETOF_DYN(RTCRSTOREINMEMCERT, abEncoded[cbSrc])); if (pEntry) { memcpy(pEntry->abEncoded, pbSrc, cbSrc); pEntry->Core.u32Magic = RTCRCERTCTXINT_MAGIC; pEntry->Core.cRefs = 1; pEntry->Core.pfnDtor = rtCrStoreInMemCertEntry_Dtor; pEntry->Core.Public.fFlags = fEnc; pEntry->Core.Public.cbEncoded = cbSrc; pEntry->Core.Public.pabEncoded = &pEntry->abEncoded[0]; if (fEnc == RTCRCERTCTX_F_ENC_X509_DER) { pEntry->Core.Public.pCert = &pEntry->u.X509Cert; pEntry->Core.Public.pTaInfo = NULL; } else { pEntry->Core.Public.pCert = NULL; pEntry->Core.Public.pTaInfo = &pEntry->u.TaInfo; } pEntry->pStore = pThis; RTASN1CURSORPRIMARY Cursor; RTAsn1CursorInitPrimary(&Cursor, &pEntry->abEncoded[0], cbSrc, pErrInfo, &g_RTAsn1DefaultAllocator, RTASN1CURSOR_FLAGS_DER, "InMem"); if (fEnc == RTCRCERTCTX_F_ENC_X509_DER) rc = RTCrX509Certificate_DecodeAsn1(&Cursor.Cursor, 0, &pEntry->u.X509Cert, "Cert"); else rc = RTCrTafTrustAnchorInfo_DecodeAsn1(&Cursor.Cursor, 0, &pEntry->u.TaInfo, "TaInfo"); if (RT_SUCCESS(rc)) { if (fEnc == RTCRCERTCTX_F_ENC_X509_DER) rc = RTCrX509Certificate_CheckSanity(&pEntry->u.X509Cert, 0, pErrInfo, "Cert"); else rc = RTCrTafTrustAnchorInfo_CheckSanity(&pEntry->u.TaInfo, 0, pErrInfo, "TaInfo"); if (RT_SUCCESS(rc)) { *ppEntry = pEntry; return VINF_SUCCESS; } RTAsn1VtDelete(&pEntry->u.Asn1Core); } RTMemFree(pEntry); } else rc = VERR_NO_MEMORY; return rc; } /** * Grows the certificate pointer array to at least @a cMin entries. * * @returns IPRT status code. * @param pThis The in-memory store instance. * @param cMin The new minimum store size. */ static int rtCrStoreInMemGrow(PRTCRSTOREINMEM pThis, uint32_t cMin) { AssertReturn(cMin <= _1M, VERR_OUT_OF_RANGE); AssertReturn(cMin > pThis->cCertsAlloc, VERR_INTERNAL_ERROR_3); if (cMin < 64) cMin = RT_ALIGN_32(cMin, 8); else cMin = RT_ALIGN_32(cMin, 32); void *pv = RTMemRealloc(pThis->papCerts, cMin * sizeof(pThis->papCerts[0])); if (pv) { pThis->papCerts = (PRTCRSTOREINMEMCERT *)pv; for (uint32_t i = pThis->cCertsAlloc; i < cMin; i++) pThis->papCerts[i] = NULL; pThis->cCertsAlloc = cMin; return VINF_SUCCESS; } return VERR_NO_MEMORY; } /** @interface_method_impl{RTCRSTOREPROVIDER,pfnDestroyStore} */ static DECLCALLBACK(void) rtCrStoreInMem_DestroyStore(void *pvProvider) { PRTCRSTOREINMEM pThis = (PRTCRSTOREINMEM)pvProvider; while (pThis->cCerts > 0) { uint32_t i = --pThis->cCerts; PRTCRSTOREINMEMCERT pEntry = pThis->papCerts[i]; pThis->papCerts[i] = NULL; AssertPtr(pEntry); pEntry->pStore = NULL; RTCrCertCtxRelease(&pEntry->Core.Public); } RTMemFree(pThis->papCerts); pThis->papCerts = NULL; RTMemFree(pThis); } /** @interface_method_impl{RTCRSTOREPROVIDER,pfnCertCtxQueryPrivateKey} */ static DECLCALLBACK(int) rtCrStoreInMem_CertCtxQueryPrivateKey(void *pvProvider, PRTCRCERTCTXINT pCertCtx, uint8_t *pbKey, size_t cbKey, size_t *pcbKeyRet) { RT_NOREF_PV(pvProvider); RT_NOREF_PV(pCertCtx); RT_NOREF_PV(pbKey); RT_NOREF_PV(cbKey); RT_NOREF_PV(pcbKeyRet); //PRTCRSTOREINMEM pThis = (PRTCRSTOREINMEM)pvProvider; return VERR_NOT_FOUND; } /** @interface_method_impl{RTCRSTOREPROVIDER,pfnCertFindAll} */ static DECLCALLBACK(int) rtCrStoreInMem_CertFindAll(void *pvProvider, PRTCRSTORECERTSEARCH pSearch) { pSearch->auOpaque[0] = ~(uintptr_t)pvProvider; pSearch->auOpaque[1] = 0; pSearch->auOpaque[2] = ~(uintptr_t)0; /* For the front-end API. */ pSearch->auOpaque[3] = ~(uintptr_t)0; /* For the front-end API. */ return VINF_SUCCESS; } /** @interface_method_impl{RTCRSTOREPROVIDER,pfnCertSearchNext} */ static DECLCALLBACK(PCRTCRCERTCTX) rtCrStoreInMem_CertSearchNext(void *pvProvider, PRTCRSTORECERTSEARCH pSearch) { PRTCRSTOREINMEM pThis = (PRTCRSTOREINMEM)pvProvider; AssertReturn(pSearch->auOpaque[0] == ~(uintptr_t)pvProvider, NULL); uintptr_t i = pSearch->auOpaque[1]; if (i < pThis->cCerts) { pSearch->auOpaque[1] = i + 1; PRTCRCERTCTXINT pCertCtx = &pThis->papCerts[i]->Core; ASMAtomicIncU32(&pCertCtx->cRefs); return &pCertCtx->Public; } return NULL; } /** @interface_method_impl{RTCRSTOREPROVIDER,pfnCertSearchDestroy} */ static DECLCALLBACK(void) rtCrStoreInMem_CertSearchDestroy(void *pvProvider, PRTCRSTORECERTSEARCH pSearch) { NOREF(pvProvider); AssertReturnVoid(pSearch->auOpaque[0] == ~(uintptr_t)pvProvider); pSearch->auOpaque[0] = 0; pSearch->auOpaque[1] = 0; pSearch->auOpaque[2] = 0; pSearch->auOpaque[3] = 0; } /** @interface_method_impl{RTCRSTOREPROVIDER,pfnCertSearchDestroy} */ static DECLCALLBACK(int) rtCrStoreInMem_CertAddEncoded(void *pvProvider, uint32_t fFlags, uint8_t const *pbEncoded, uint32_t cbEncoded, PRTERRINFO pErrInfo) { PRTCRSTOREINMEM pThis = (PRTCRSTOREINMEM)pvProvider; int rc; AssertMsgReturn( (fFlags & RTCRCERTCTX_F_ENC_MASK) == RTCRCERTCTX_F_ENC_X509_DER || (fFlags & RTCRCERTCTX_F_ENC_MASK) == RTCRCERTCTX_F_ENC_TAF_DER , ("Only X.509 and TAF DER are supported: %#x\n", fFlags), VERR_INVALID_FLAGS); /* * Check for duplicates if specified. */ if (fFlags & RTCRCERTCTX_F_ADD_IF_NOT_FOUND) { uint32_t iCert = pThis->cCerts; while (iCert-- > 0) { PRTCRSTOREINMEMCERT pCert = pThis->papCerts[iCert]; if ( pCert->Core.Public.cbEncoded == cbEncoded && pCert->Core.Public.fFlags == (fFlags & RTCRCERTCTX_F_ENC_MASK) && memcmp(pCert->Core.Public.pabEncoded, pbEncoded, cbEncoded) == 0) return VWRN_ALREADY_EXISTS; } } /* * Add it. */ if (pThis->cCerts + 1 <= pThis->cCertsAlloc) { /* likely */ } else { rc = rtCrStoreInMemGrow(pThis, pThis->cCerts + 1); if (RT_FAILURE(rc)) return rc; } rc = rtCrStoreInMemCreateCertEntry(pThis, fFlags & RTCRCERTCTX_F_ENC_MASK, pbEncoded, cbEncoded, pErrInfo, &pThis->papCerts[pThis->cCerts]); if (RT_SUCCESS(rc)) { pThis->cCerts++; return VINF_SUCCESS; } return rc; } /** * In-memory store provider. */ static RTCRSTOREPROVIDER const g_rtCrStoreInMemProvider = { "in-memory", rtCrStoreInMem_DestroyStore, rtCrStoreInMem_CertCtxQueryPrivateKey, rtCrStoreInMem_CertFindAll, rtCrStoreInMem_CertSearchNext, rtCrStoreInMem_CertSearchDestroy, rtCrStoreInMem_CertAddEncoded, NULL, 42 }; /** * Common worker for RTCrStoreCreateInMem and future constructors... * * @returns IPRT status code. * @param ppStore Where to return the store instance. */ static int rtCrStoreInMemCreateInternal(PRTCRSTOREINMEM *ppStore) { PRTCRSTOREINMEM pStore = (PRTCRSTOREINMEM)RTMemAlloc(sizeof(*pStore)); if (pStore) { pStore->cCerts = 0; pStore->cCertsAlloc = 0; pStore->papCerts = NULL; *ppStore = pStore; return VINF_SUCCESS; } *ppStore = NULL; /* shut up gcc-maybe-pita warning. */ return VERR_NO_MEMORY; } RTDECL(int) RTCrStoreCreateInMem(PRTCRSTORE phStore, uint32_t cSizeHint) { PRTCRSTOREINMEM pStore; int rc = rtCrStoreInMemCreateInternal(&pStore); if (RT_SUCCESS(rc)) { if (cSizeHint) rc = rtCrStoreInMemGrow(pStore, RT_MIN(cSizeHint, 512)); if (RT_SUCCESS(rc)) { rc = rtCrStoreCreate(&g_rtCrStoreInMemProvider, pStore, phStore); if (RT_SUCCESS(rc)) return VINF_SUCCESS; } RTMemFree(pStore); } return rc; } RT_EXPORT_SYMBOL(RTCrStoreCreateInMem);
{ "pile_set_name": "Github" }
*hw_Document_SetContent* -- Sets/replaces content of hw_document bool hw_document_setcontent(int hw_document, string content)~ Sets or replaces the content of the document. If the document is an HTML document the content is everything after the BODY tag. Information from the HEAD and BODY tag is in the stored in the object record. If you provide this information in the content of the document too, the Hyperwave server will change the object record accordingly when the document is inserted. Probably not a very good idea. If this functions fails the document will retain its old content. {hw_document} The document identifier. {content} Returns TRUE on success or &false; on failure. |hw_document_attributes| |hw_document_size| |hw_document_content| vim:ft=help:
{ "pile_set_name": "Github" }
require('../../../modules/es6.array.iterator'); module.exports = require('../../../modules/_iterators').Array;
{ "pile_set_name": "Github" }
--- title: Workarea 3.4.25 excerpt: Patch release notes for Workarea 3.4.25. --- # Workarea 3.4.25 Patch release notes for Workarea 3.4.25. ## Pin Version of `wysihtml-rails` To address a dependency issue with the `~> 0.x` version occurring with newer versions of Bundler on `wysihtml-rails`, Workarea has pinned the dependency to `0.6.0.beta2`. ### Pull Requests - [305](https://github.com/workarea-commerce/workarea/pull/305) ## Fix Final Test Hard-Coded to 2020 One more test needed to be converted to use the `next_year` helper, and now all tests should pass out-of-the-box. ### Pull Requests - [307](https://github.com/workarea-commerce/workarea/pull/307) ## Use Rack Session ID Cookie Value for User Activity Session IDs Rack versions below v2.0.8 are susceptible to a timing attack, wherein a session ID can be stolen by inferring how long it takes for the server to validate it. To address this, Rack has shipped a new version that introduces private and public session IDs so that these types of attacks can be prevented. This is mostly applicable to those who store their sessions in a database (such as Redis), because it is then possible for someone to hijack another user's session. Workarea does not store sessions in a shared database out-of-the-box, so it is not inherently vulnerable to such an attack, but had to make a change since it uses the session ID in the background for user activity reporting. This change ensures Workarea will be compatible with all future versions of Rack 2.0. For more information, check out [CVE-2019-16782](https://github.com/rack/rack/security/advisories/GHSA-hrqr-hxpp-chr3). ### Commits - [cc7d3d8a83d1b4aa15fba894f5cd586b6b5cd325](https://github.com/workarea-commerce/workarea/commit/cc7d3d8a83d1b4aa15fba894f5cd586b6b5cd325)
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html> <head> <title>swap</title> <link rel="stylesheet" href="prism.css"> <link rel="stylesheet" href="style.css"> </head> <body> <div id="header"> <div class="doc-title"><a href="folktale.html"><span class="doc-title"><span class="product-name">Folktale</span><span class="version">v2.0.1</span></span></a><ul class="navigation"><li class="navigation-item"><a href="https://github.com/origamitower/folktale" title="">GitHub</a></li><li class="navigation-item"><a href="folktale.html#cat-2-support" title="">Support</a></li><li class="navigation-item"><a href="folktale.html#cat-3-contributing" title="">Contributing</a></li></ul></div> </div> <div id="content-wrapper"><div id="content-panel"><h1 class="entity-title">swap</h1><div class="highlight-summary"><div><p>Inverts the state of a Task. That is, turns successful tasks into failed ones, and failed tasks into successful ones.</p> </div></div><div class="deprecation-section"><strong class="deprecation-title">This feature is experimental!</strong><p>This API is still experimental, so it may change or be removed in future versions. You should not rely on it for production applications.</p></div><div class="definition"><h2 class="section-title" id="signature">Signature</h2><div class="signature">value()</div><div class="type-definition"><div class="type-definition-container"><div class="type-title-container"><strong class="type-title">Type</strong><a class="info" href="guides.type-notation-used-in-signatures.html">(what is this?)</a></div><pre class="type"><code class="language-haskell">forall e, v: (Task e v).() =&gt; Task v e</code></pre></div></div></div><h2 class="section-title">Documentation</h2><div class="documentation"><div><p>Inverts the state of a Task. That is, turns successful tasks into failed ones, and failed tasks into successful ones.</p> <h2 id="example-">Example:</h2> <pre><code>const { of, rejected } = require(&#39;folktale/concurrency/task&#39;); try { const result1 = await of(1).swap().run().promise(); throw &#39;never happens&#39;; } catch (error) { $ASSERT(error == 1); } const result2 = await rejected(1).swap().run().promise(); $ASSERT(result2 == 1); </code></pre></div></div><div class="members"><h2 class="section-title" id="properties">Properties</h2></div><div class="source-code"><h2 class="section-title" id="source-code">Source Code</h2><div class="source-location">Defined in source/concurrency/task/_task.js at line 20, column 0</div><pre class="source-code"><code class="language-javascript">swap() { return new Task(resolver =&gt; { let execution = this.run(); // eslint-disable-line prefer-const resolver.onCancelled(() =&gt; execution.cancel()); execution.listen({ onCancelled: resolver.cancel, onRejected: resolver.resolve, onResolved: resolver.reject }); }); }</code></pre></div></div><div id="meta-panel"><div class="meta-section"><div class="meta-field"><strong class="meta-field-title">Stability</strong><div class="meta-field-value">experimental</div></div><div class="meta-field"><strong class="meta-field-title">Licence</strong><div class="meta-field-value">MIT</div></div><div class="meta-field"><strong class="meta-field-title">Module</strong><div class="meta-field-value">folktale/concurrency/task/_task</div></div></div><div class="table-of-contents"><div class="meta-section-title">On This Page</div><ul class="toc-list level-1"><li class="toc-item"><a href="#signature">Signature</a></li><li class="toc-item"><span class="no-anchor">Documentation</span><ul class="toc-list level-2"><li class="toc-item"><a href="#example-" title="Example:"><div><p>Example:</p> </div></a></li></ul></li><li class="toc-item"><a href="#properties">Properties</a><ul class="toc-list level-2"></ul></li><li class="toc-item"><a href="#source-code">Source Code</a></li></ul></div><div class="meta-section"><strong class="meta-section-title">Authors</strong><div class="meta-field"><strong class="meta-field-title">Copyright</strong><div class="meta-field-value">(c) 2013-2017 Quildreen Motta, and CONTRIBUTORS</div></div><div class="meta-field"><strong class="meta-field-title">Authors</strong><div class="meta-field-value"><ul class="meta-list"><li>Quildreen Motta</li></ul></div></div><div class="meta-field"><strong class="meta-field-title">Maintainers</strong><div class="meta-field-value"><ul class="meta-list"><li>Quildreen Motta &lt;queen@robotlolita.me&gt; (http://robotlolita.me/)</li></ul></div></div></div></div></div> <script> void function() { var xs = document.querySelectorAll('.documentation pre code'); for (var i = 0; i < xs.length; ++i) { xs[i].className = 'language-javascript code-block'; } }() </script> <script src="prism.js"></script> </body> </html>
{ "pile_set_name": "Github" }
// (C) Copyright Jesse Williamson 2009 // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <iostream> #include <vector> #include <boost/config.hpp> #include <boost/algorithm/clamp.hpp> #define BOOST_TEST_MAIN #include <boost/test/unit_test.hpp> namespace ba = boost::algorithm; bool intGreater ( int lhs, int rhs ) { return lhs > rhs; } bool doubleGreater ( double lhs, double rhs ) { return lhs > rhs; } class custom { public: custom ( int x ) : v(x) {} custom ( const custom &rhs ) : v(rhs.v) {} ~custom () {} custom & operator = ( const custom &rhs ) { v = rhs.v; return *this; } bool operator < ( const custom &rhs ) const { return v < rhs.v; } bool operator == ( const custom &rhs ) const { return v == rhs.v; } // need this for the test std::ostream & print ( std::ostream &os ) const { return os << v; } int v; }; std::ostream & operator << ( std::ostream & os, const custom &x ) { return x.print ( os ); } bool customLess ( const custom &lhs, const custom &rhs ) { return lhs.v < rhs.v; } void test_ints() { // Inside the range, equal to the endpoints, and outside the endpoints. BOOST_CHECK_EQUAL ( 3, ba::clamp ( 3, 1, 10 )); BOOST_CHECK_EQUAL ( 1, ba::clamp ( 1, 1, 10 )); BOOST_CHECK_EQUAL ( 1, ba::clamp ( 0, 1, 10 )); BOOST_CHECK_EQUAL ( 10, ba::clamp ( 10, 1, 10 )); BOOST_CHECK_EQUAL ( 10, ba::clamp ( 11, 1, 10 )); BOOST_CHECK_EQUAL ( 3, ba::clamp ( 3, 10, 1, intGreater )); BOOST_CHECK_EQUAL ( 1, ba::clamp ( 1, 10, 1, intGreater )); BOOST_CHECK_EQUAL ( 1, ba::clamp ( 0, 10, 1, intGreater )); BOOST_CHECK_EQUAL ( 10, ba::clamp ( 10, 10, 1, intGreater )); BOOST_CHECK_EQUAL ( 10, ba::clamp ( 11, 10, 1, intGreater )); // Negative numbers BOOST_CHECK_EQUAL ( -3, ba::clamp ( -3, -10, -1 )); BOOST_CHECK_EQUAL ( -1, ba::clamp ( -1, -10, -1 )); BOOST_CHECK_EQUAL ( -1, ba::clamp ( 0, -10, -1 )); BOOST_CHECK_EQUAL ( -10, ba::clamp ( -10, -10, -1 )); BOOST_CHECK_EQUAL ( -10, ba::clamp ( -11, -10, -1 )); // Mixed positive and negative numbers BOOST_CHECK_EQUAL ( 5, ba::clamp ( 5, -10, 10 )); BOOST_CHECK_EQUAL ( -10, ba::clamp ( -10, -10, 10 )); BOOST_CHECK_EQUAL ( -10, ba::clamp ( -15, -10, 10 )); BOOST_CHECK_EQUAL ( 10, ba::clamp ( 10, -10, 10 )); BOOST_CHECK_EQUAL ( 10, ba::clamp ( 15, -10, 10 )); // Unsigned BOOST_CHECK_EQUAL ( 5U, ba::clamp ( 5U, 1U, 10U )); BOOST_CHECK_EQUAL ( 1U, ba::clamp ( 1U, 1U, 10U )); BOOST_CHECK_EQUAL ( 1U, ba::clamp ( 0U, 1U, 10U )); BOOST_CHECK_EQUAL ( 10U, ba::clamp ( 10U, 1U, 10U )); BOOST_CHECK_EQUAL ( 10U, ba::clamp ( 15U, 1U, 10U )); // Mixed (1) BOOST_CHECK_EQUAL ( 5U, ba::clamp ( 5U, 1, 10 )); BOOST_CHECK_EQUAL ( 1U, ba::clamp ( 1U, 1, 10 )); BOOST_CHECK_EQUAL ( 1U, ba::clamp ( 0U, 1, 10 )); BOOST_CHECK_EQUAL ( 10U, ba::clamp ( 10U, 1, 10 )); BOOST_CHECK_EQUAL ( 10U, ba::clamp ( 15U, 1, 10 )); // Mixed (3) BOOST_CHECK_EQUAL ( 5U, ba::clamp ( 5U, 1, 10. )); BOOST_CHECK_EQUAL ( 1U, ba::clamp ( 1U, 1, 10. )); BOOST_CHECK_EQUAL ( 1U, ba::clamp ( 0U, 1, 10. )); BOOST_CHECK_EQUAL ( 10U, ba::clamp ( 10U, 1, 10. )); BOOST_CHECK_EQUAL ( 10U, ba::clamp ( 15U, 1, 10. )); short foo = 50; BOOST_CHECK_EQUAL ( 56, ba::clamp ( foo, 56.9, 129 )); BOOST_CHECK_EQUAL ( 24910, ba::clamp ( foo, 12345678, 123456999 )); } void test_floats() { // Inside the range, equal to the endpoints, and outside the endpoints. BOOST_CHECK_EQUAL ( 3.0, ba::clamp ( 3.0, 1.0, 10.0 )); BOOST_CHECK_EQUAL ( 1.0, ba::clamp ( 1.0, 1.0, 10.0 )); BOOST_CHECK_EQUAL ( 1.0, ba::clamp ( 0.0, 1.0, 10.0 )); BOOST_CHECK_EQUAL ( 10.0, ba::clamp ( 10.0, 1.0, 10.0 )); BOOST_CHECK_EQUAL ( 10.0, ba::clamp ( 11.0, 1.0, 10.0 )); BOOST_CHECK_EQUAL ( 3.0, ba::clamp ( 3.0, 10.0, 1.0, doubleGreater )); BOOST_CHECK_EQUAL ( 1.0, ba::clamp ( 1.0, 10.0, 1.0, doubleGreater )); BOOST_CHECK_EQUAL ( 1.0, ba::clamp ( 0.0, 10.0, 1.0, doubleGreater )); BOOST_CHECK_EQUAL ( 10.0, ba::clamp ( 10.0, 10.0, 1.0, doubleGreater )); BOOST_CHECK_EQUAL ( 10.0, ba::clamp ( 11.0, 10.0, 1.0, doubleGreater )); // Negative numbers BOOST_CHECK_EQUAL ( -3.f, ba::clamp ( -3.f, -10.f, -1.f )); BOOST_CHECK_EQUAL ( -1.f, ba::clamp ( -1.f, -10.f, -1.f )); BOOST_CHECK_EQUAL ( -1.f, ba::clamp ( 0.f, -10.f, -1.f )); BOOST_CHECK_EQUAL ( -10.f, ba::clamp ( -10.f, -10.f, -1.f )); BOOST_CHECK_EQUAL ( -10.f, ba::clamp ( -11.f, -10.f, -1.f )); // Mixed positive and negative numbers BOOST_CHECK_EQUAL ( 5.f, ba::clamp ( 5.f, -10.f, 10.f )); BOOST_CHECK_EQUAL ( -10.f, ba::clamp ( -10.f, -10.f, 10.f )); BOOST_CHECK_EQUAL ( -10.f, ba::clamp ( -15.f, -10.f, 10.f )); BOOST_CHECK_EQUAL ( 10.f, ba::clamp ( 10.f, -10.f, 10.f )); BOOST_CHECK_EQUAL ( 10.f, ba::clamp ( 15.f, -10.f, 10.f )); // Mixed (1) BOOST_CHECK_EQUAL ( 5.f, ba::clamp ( 5.f, -10., 10. )); BOOST_CHECK_EQUAL ( -10.f, ba::clamp ( -10.f, -10., 10. )); BOOST_CHECK_EQUAL ( -10.f, ba::clamp ( -15.f, -10., 10. )); BOOST_CHECK_EQUAL ( 10.f, ba::clamp ( 10.f, -10., 10. )); BOOST_CHECK_EQUAL ( 10.f, ba::clamp ( 15.f, -10., 10. )); // Mixed (2) BOOST_CHECK_EQUAL ( 5.f, ba::clamp ( 5.f, -10, 10 )); BOOST_CHECK_EQUAL ( -10.f, ba::clamp ( -10.f, -10, 10 )); BOOST_CHECK_EQUAL ( -10.f, ba::clamp ( -15.f, -10, 10 )); BOOST_CHECK_EQUAL ( 10.f, ba::clamp ( 10.f, -10, 10 )); BOOST_CHECK_EQUAL ( 10.f, ba::clamp ( 15.f, -10, 10 )); } void test_custom() { // Inside the range, equal to the endpoints, and outside the endpoints. BOOST_CHECK_EQUAL ( custom( 3), ba::clamp ( custom( 3), custom(1), custom(10))); BOOST_CHECK_EQUAL ( custom( 1), ba::clamp ( custom( 1), custom(1), custom(10))); BOOST_CHECK_EQUAL ( custom( 1), ba::clamp ( custom( 0), custom(1), custom(10))); BOOST_CHECK_EQUAL ( custom(10), ba::clamp ( custom(10), custom(1), custom(10))); BOOST_CHECK_EQUAL ( custom(10), ba::clamp ( custom(11), custom(1), custom(10))); BOOST_CHECK_EQUAL ( custom( 3), ba::clamp ( custom( 3), custom(1), custom(10), customLess )); BOOST_CHECK_EQUAL ( custom( 1), ba::clamp ( custom( 1), custom(1), custom(10), customLess )); BOOST_CHECK_EQUAL ( custom( 1), ba::clamp ( custom( 0), custom(1), custom(10), customLess )); BOOST_CHECK_EQUAL ( custom(10), ba::clamp ( custom(10), custom(1), custom(10), customLess )); BOOST_CHECK_EQUAL ( custom(10), ba::clamp ( custom(11), custom(1), custom(10), customLess )); // Fail!! // BOOST_CHECK_EQUAL ( custom(1), ba::clamp ( custom(11), custom(1), custom(10))); } #define elementsof(v) (sizeof (v) / sizeof (v[0])) #define a_begin(v) (&v[0]) #define a_end(v) (v + elementsof (v)) #define a_range(v) v #define b_e(v) a_begin(v),a_end(v) void test_int_range () { int inputs [] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 19, 99, 999, -1, -3, -99, 234234 }; int outputs [] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, -1, -1, -1, 10 }; std::vector<int> results; std::vector<int> in_v; std::copy ( a_begin(inputs), a_end(inputs), std::back_inserter ( in_v )); ba::clamp_range ( a_begin(inputs), a_end(inputs), std::back_inserter ( results ), -1, 10 ); BOOST_CHECK ( std::equal ( results.begin(), results.end (), outputs )); results.clear (); ba::clamp_range ( in_v.begin (), in_v.end (), std::back_inserter ( results ), -1, 10 ); BOOST_CHECK ( std::equal ( results.begin(), results.end (), outputs )); results.clear (); ba::clamp_range ( a_begin(inputs), a_end(inputs), std::back_inserter ( results ), 10, -1, intGreater ); BOOST_CHECK ( std::equal ( results.begin(), results.end (), outputs )); results.clear (); ba::clamp_range ( in_v.begin (), in_v.end (), std::back_inserter ( results ), 10, -1, intGreater ); BOOST_CHECK ( std::equal ( results.begin(), results.end (), outputs )); results.clear (); ba::clamp_range ( a_range(inputs), std::back_inserter ( results ), -1, 10 ); BOOST_CHECK ( std::equal ( results.begin(), results.end (), outputs )); results.clear (); ba::clamp_range ( in_v, std::back_inserter ( results ), -1, 10 ); BOOST_CHECK ( std::equal ( results.begin(), results.end (), outputs )); results.clear (); ba::clamp_range ( a_range(inputs), std::back_inserter ( results ), 10, -1, intGreater ); BOOST_CHECK ( std::equal ( results.begin(), results.end (), outputs )); results.clear (); ba::clamp_range ( in_v, std::back_inserter ( results ), 10, -1, intGreater ); BOOST_CHECK ( std::equal ( results.begin(), results.end (), outputs )); results.clear (); int junk[elementsof(inputs)]; ba::clamp_range ( inputs, junk, 10, -1, intGreater ); BOOST_CHECK ( std::equal ( b_e(junk), outputs )); } BOOST_AUTO_TEST_CASE( test_main ) { test_ints (); test_floats (); test_custom (); test_int_range (); // test_float_range (); // test_custom_range (); }
{ "pile_set_name": "Github" }
-------------------------------------------------- Name -------------------------------------------------- Easy Baked Chicken Wings -------------------------------------------------- Ingredients -------------------------------------------------- 3 pounds chicken wings 2 eggs, beaten 1/2 cup all-purpose flour for coating 3/4 cup oil for frying 1/4 cup margarine 6 tablespoons soy sauce 6 tablespoons water 2 cups white sugar 1 cup vinegar 2 tablespoons monosodium glutamate (MSG) -------------------------------------------------- Directions -------------------------------------------------- Preheat oven to 350 degrees F (175 degrees C) Pour egg beat into a shallow dish or bowl; do the same with the flour. Heat oil and margarine in a large, deep skillet over medium high heat. Dip wings in egg, then flour, then fry until browned and crisp. Lay browned wings in an 11x14 inch baking dish To Make Sauce: In a small bowl combine the soy sauce, water, sugar, vinegar and MSG. Blend well and pour sauce over chicken Bake in the preheated oven for 1 hour --------------------------------------------------
{ "pile_set_name": "Github" }
var parent = require('../../es/object/define-setter'); module.exports = parent;
{ "pile_set_name": "Github" }
package aip0141 import ( "testing" "github.com/googleapis/api-linter/lint" ) func TestAddRules(t *testing.T) { if err := AddRules(lint.NewRuleRegistry()); err != nil { t.Errorf("AddRules got an error: %v", err) } }
{ "pile_set_name": "Github" }
// NeL - MMORPG Framework <http://dev.ryzom.com/projects/nel/> // Copyright (C) 2010 Winch Gate Property Limited // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. #ifndef DIFF_TOOL_H #define DIFF_TOOL_H #include "i18n.h" namespace STRING_MANAGER { const ucstring nl("\n"); struct TStringInfo { std::string Identifier; ucstring Text; ucstring Text2; mutable ucstring Comments; uint64 HashValue; }; struct TStringDiffContext { typedef std::vector<TStringInfo>::iterator iterator; const std::vector<TStringInfo> &Addition; std::vector<TStringInfo> &Reference; std::vector<TStringInfo> &Diff; TStringDiffContext(const std::vector<TStringInfo> &addition, std::vector<TStringInfo> &reference, std::vector<TStringInfo> &diff) : Addition(addition), Reference(reference), Diff(diff) { } }; struct TClause { std::string Identifier; ucstring Conditions; ucstring Text; ucstring Comments; uint64 HashValue; }; struct TPhrase { std::string Identifier; ucstring Parameters; mutable ucstring Comments; std::vector<TClause> Clauses; uint64 HashValue; }; struct TPhraseDiffContext { typedef std::vector<TPhrase>::iterator iterator; const std::vector<TPhrase> &Addition; std::vector<TPhrase> &Reference; std::vector<TPhrase> &Diff; TPhraseDiffContext(const std::vector<TPhrase> &addition, std::vector<TPhrase> &reference, std::vector<TPhrase> &diff) : Addition(addition), Reference(reference), Diff(diff) { } }; struct TWorksheet { typedef std::vector<ucstring> TRow; typedef std::vector<TRow> TData; TData Data; uint ColCount; TWorksheet() : ColCount(0) { } std::vector<TRow>::iterator begin() { return Data.begin(); } std::vector<TRow>::iterator end() { return Data.end(); } std::vector<TRow>::const_iterator begin() const { return Data.begin(); } std::vector<TRow>::const_iterator end() const { return Data.end(); } void push_back(const TRow &row) { Data.push_back(row); } std::vector<TRow>::iterator insert(std::vector<TRow>::iterator pos, const TRow &value) { return Data.insert(pos, value); } std::vector<TRow>::iterator erase(std::vector<TRow>::iterator it) { return Data.erase(it); } TRow &back() { return Data.back(); } TRow &operator [] (uint index) { return Data[index]; } const TRow &operator [] (uint index) const { return Data[index]; } uint size() const { return (uint)Data.size(); } void insertColumn(uint colIndex) { nlassert(colIndex <= ColCount); for (uint i=0; i<Data.size(); ++i) { // insert a default value. Data[i].insert(Data[i].begin()+colIndex, ucstring()); } ColCount++; } void copyColumn(uint srcColIndex, uint dstColIndex) { nlassert(srcColIndex < ColCount); nlassert(dstColIndex < ColCount); for (uint i=0; i<Data.size(); ++i) { Data[i][dstColIndex] = Data[i][srcColIndex]; } } void eraseColumn(uint colIndex) { nlassertex(colIndex < ColCount, ("TWorksheet::eraseColumn : bad column index: colIndex(%u) is not less than ColCount(%u)", colIndex, ColCount)); for (uint i=0; i<Data.size(); ++i) { // insert a default value. Data[i].erase(Data[i].begin()+colIndex); } ColCount--; } void moveColumn(uint oldColIndex, uint newColIndex) { nlassert(oldColIndex < ColCount); nlassert(newColIndex < ColCount); if (oldColIndex == newColIndex) return; if (newColIndex > oldColIndex) { // the dst is after the src, no problem with index insertColumn(newColIndex); copyColumn(oldColIndex, newColIndex); eraseColumn(oldColIndex); } else { // the dst is before the src, need to take the column insertion into account insertColumn(newColIndex); copyColumn(oldColIndex+1, newColIndex); eraseColumn(oldColIndex+1); } } void setColCount(uint count) { if (count != ColCount) { for (uint i=0; i<Data.size(); ++i) Data[i].resize(count); } ColCount = count; } bool findId(uint& colIndex) { if (Data.empty()) return false; for (TWorksheet::TRow::iterator it=Data[0].begin(); it!=Data[0].end(); ++it) { std::string columnTitle = (*it).toString(); if ( ! columnTitle.empty() ) { // Return the first column for which the title does not begin with '*' if ( columnTitle[0] != '*' ) { colIndex = (uint)(it - Data[0].begin()); return true; } } } return false; } bool findCol(const ucstring &colName, uint &colIndex) { if (Data.empty()) return false; TWorksheet::TRow::iterator it = std::find(Data[0].begin(), Data[0].end(), colName); if (it == Data[0].end()) return false; colIndex = (uint)(it - Data[0].begin()); return true; } void insertRow(uint rowIndex, const TRow &row) { nlassertex(rowIndex <= Data.size(), ("TWorksheet::insertRow: bad row index: rowIndex(%u) is out of range (max=%u)", rowIndex, Data.size()-1)); nlassertex(row.size() == ColCount, ("TWorksheet::insertRow: bad column count : inserted row size(%u) is invalid (must be %u) at rowIndex(%u)", row.size(), ColCount, rowIndex)); Data.insert(Data.begin()+rowIndex, row); } // resize the rows void resize(uint numRows) { uint oldSize= (uint)Data.size(); Data.resize(numRows); // alloc good Column count for new lines for(uint i= oldSize;i<Data.size();i++) Data[i].resize(ColCount); } bool findRow(uint colIndex, const ucstring &colValue, uint &rowIndex) { nlassertex(colIndex < ColCount, ("TWorksheet::findRow: bad column index: colIndex(%u) is not less than ColCount(%u)", colIndex, ColCount)); TData::iterator first(Data.begin()), last(Data.end()); for (; first != last; ++first) { if (first->operator[](colIndex) == colValue) { rowIndex = (uint)(first - Data.begin()); return true; } } return false; } void setData(uint rowIndex, uint colIndex, const ucstring &value) { nlassertex(rowIndex < Data.size(), ("TWorksheet::setData: bad row index: rowIndex(%u) is out of range (max=%u)", rowIndex, Data.size())); nlassertex(colIndex < ColCount, ("TWorksheet::setData: bad column index: colIndex(%u) is not less than ColCount(%u) ar rowIndex(%u)", colIndex, ColCount, rowIndex)); Data[rowIndex][colIndex] = value; } const ucstring &getData(uint rowIndex, uint colIndex) const { nlassertex(rowIndex < Data.size(), ("TWorksheet::getData: bad row index: rowIndex(%u) is out of range (max=%u)", rowIndex, Data.size())); nlassertex(colIndex < ColCount, ("TWorksheet::getData: bad column index: colIndex(%u) is not less than ColCount(%u) at rowIndex(%u)", colIndex, ColCount, rowIndex)); return Data[rowIndex][colIndex]; } void setData(uint rowIndex, const ucstring &colName, const ucstring &value) { nlassertex(rowIndex > 0, ("TWorksheet::setData: rowIndex(%u) must be greater then 0 !", rowIndex)); nlassertex(rowIndex < Data.size(), ("TWorksheet::setData: rowIndex(%u) is out of range (max=%u)", rowIndex, Data.size())); TWorksheet::TRow::iterator it = std::find(Data[0].begin(), Data[0].end(), ucstring(colName)); nlassertex(it != Data[0].end(), ("TWorksheet::setData: invalid colName: can't find the column named '%s' at row %u", colName.toString().c_str(), rowIndex)); Data[rowIndex][it - Data[0].begin()] = value; } const ucstring &getData(uint rowIndex, const ucstring &colName) const { nlassertex(rowIndex > 0, ("TWorksheet::getData: bad row index: rowIndex(%u) must be greater then 0 !", rowIndex)); nlassertex(rowIndex < Data.size(), ("TWorksheet::getData: bad row index: rowIndex(%u) is out of range (max=%u)", rowIndex, Data.size())); TWorksheet::TRow::const_iterator it = std::find(Data[0].begin(), Data[0].end(), ucstring(colName)); nlassertex(it != Data[0].end(), ("TWorksheet::getData: invalid colName: can't find the column named '%s' at row %u", colName.toString().c_str(), rowIndex)); return Data[rowIndex][it - Data[0].begin()]; } }; struct TGetWorksheetIdentifier { std::string operator()(const TWorksheet &container, uint index) const { return container.getData(index, 1).toString(); } }; struct TGetWorksheetHashValue { uint64 operator()(const TWorksheet &container, uint index) const { return NLMISC::CI18N::stringToHash(container.getData(index, ucstring("*HASH_VALUE")).toString()); } }; struct TTestWorksheetItem : public std::unary_function<TWorksheet::TRow, bool> { ucstring Identifier; TTestWorksheetItem(const std::string &identifier) : Identifier(identifier) {} bool operator () (const TWorksheet::TRow &row) const { return row[1] == Identifier; } }; struct TWordsDiffContext { typedef TWorksheet::TData::iterator iterator; const TWorksheet &Addition; TWorksheet &Reference; TWorksheet &Diff; TWordsDiffContext(const TWorksheet &addition, TWorksheet &reference, TWorksheet &diff) : Addition(addition), Reference(reference), Diff(diff) { } }; template<class ItemType> struct TGetIdentifier { std::string operator()(const std::vector<ItemType> &container, uint index) const { return container[index].Identifier; } }; template<class ItemType> struct TGetHashValue { uint64 operator()(const std::vector<ItemType> &container, uint index) const { return container[index].HashValue; } }; template<class ItemType> struct TTestItem : public std::unary_function<ItemType, bool> { std::string Identifier; TTestItem(const std::string &identifier) : Identifier(identifier) {} bool operator () (const ItemType &item) const { return item.Identifier == Identifier; } }; /** * ItemType must have a property named Identifier that uniquely * identify each item. * ItemType must have a property named HashValue that is used * to determine the change between context.Addition and context.Reference vector. */ template <class ItemType, class Context, class GetIdentifier = TGetIdentifier<ItemType>, class GetHashValue = TGetHashValue<ItemType>, class TestItem = TTestItem<ItemType> > class CMakeDiff { public: struct IDiffCallback { virtual void onEquivalent(uint addIndex, uint refIndex, Context &context) = 0; virtual void onAdd(uint addIndex, uint refIndex, Context &context) = 0; virtual void onRemove(uint addIndex, uint refIndex, Context &context) = 0; virtual void onChanged(uint addIndex, uint refIndex, Context &context) = 0; virtual void onSwap(uint newIndex, uint refIndex, Context &context) = 0; }; void makeDiff(IDiffCallback *callback, Context &context, bool skipFirstRecord = false) { #ifdef NL_DEBUG // compile time checking // Context::iterator testIt; #endif GetIdentifier getIdentifier; GetHashValue getHashValue; // compare the context.Reference an context.Addition file, remove any equivalent strings. uint addCount, refCount; if (skipFirstRecord) { addCount = 1; refCount = 1; } else { addCount = 0; refCount=0; } while (addCount < context.Addition.size() || refCount < context.Reference.size()) { bool equal = true; if (addCount != context.Addition.size() && refCount != context.Reference.size()) { equal = getHashValue(context.Addition, addCount) == getHashValue(context.Reference, refCount); } // vector<ItemType>::iterator it; if (addCount == context.Addition.size() || ( !equal && find_if(context.Addition.begin(), context.Addition.end(), TestItem(getIdentifier(context.Reference, refCount))) == context.Addition.end() ) ) { // this can only be removal callback->onRemove(addCount, refCount, context); context.Reference.erase(context.Reference.begin()+refCount); // ++refCount; } else if (refCount == context.Reference.size() || ( !equal && find_if(context.Reference.begin(), context.Reference.end(), TestItem(getIdentifier(context.Addition, addCount))) == context.Reference.end() ) ) { // this can only be context.Addition callback->onAdd(addCount, refCount, context); context.Reference.insert(context.Reference.begin()+refCount, context.Addition[addCount]); ++refCount; ++addCount; } else if (getIdentifier(context.Addition, addCount) != getIdentifier(context.Reference, refCount)) { // swap two element. // Context::iterator it = find_if(context.Reference.begin(), context.Reference.end(), TestItem(getIdentifier(context.Addition, addCount))); // if (it == context.Reference.end()) if (find_if( context.Reference.begin(), context.Reference.end(), TestItem(getIdentifier(context.Addition, addCount))) == context.Reference.end()) { // context.Addition callback->onAdd(addCount, refCount, context); context.Reference.insert(context.Reference.begin()+refCount, context.Addition[addCount]); ++refCount; ++addCount; } else { // nlassert(it != context.Reference.begin()+refCount); uint index = (uint)(find_if(context.Reference.begin(), context.Reference.end(), TestItem(getIdentifier(context.Addition, addCount))) - context.Reference.begin()); // callback->onSwap(it - context.Reference.begin(), refCount, context); callback->onSwap(index, refCount, context); // std::swap(*it, context.Reference[refCount]); std::swap(context.Reference[index], context.Reference[refCount]); } } else if (getHashValue(context.Addition, addCount) != getHashValue(context.Reference, refCount)) { // changed element callback->onChanged(addCount, refCount, context); ++refCount; ++addCount; } else { // same entry callback->onEquivalent(addCount, refCount, context); addCount++; refCount++; } } } }; typedef CMakeDiff<TStringInfo, TStringDiffContext> TStringDiff; typedef CMakeDiff<TPhrase, TPhraseDiffContext> TPhraseDiff; typedef CMakeDiff<TWorksheet::TRow, TWordsDiffContext, TGetWorksheetIdentifier, TGetWorksheetHashValue, TTestWorksheetItem> TWorkSheetDiff; uint64 makePhraseHash(const TPhrase &phrase); bool parseHashFromComment(const ucstring &comments, uint64 &hashValue); bool loadStringFile(const std::string filename, std::vector<TStringInfo> &stringInfos, bool forceRehash, ucchar openMark = '[', ucchar closeMark = ']', bool specialCase = false); ucstring prepareStringFile(const std::vector<TStringInfo> &strings, bool removeDiffComments, bool noDiffInfo = false); bool readPhraseFile(const std::string &filename, std::vector<TPhrase> &phrases, bool forceRehash); bool readPhraseFileFromString(ucstring const& doc, const std::string &filename, std::vector<TPhrase> &phrases, bool forceRehash); ucstring tabLines(uint nbTab, const ucstring &str); ucstring preparePhraseFile(const std::vector<TPhrase> &phrases, bool removeDiffComments); bool loadExcelSheet(const std::string filename, TWorksheet &worksheet, bool checkUnique = true); bool readExcelSheet(const ucstring &text, TWorksheet &worksheet, bool checkUnique = true); void makeHashCode(TWorksheet &sheet, bool forceRehash); ucstring prepareExcelSheet(const TWorksheet &worksheet); } // namespace STRING_MANAGER #endif // DIFF_TOOL_H
{ "pile_set_name": "Github" }
<?php /* * This file is part of the Prophecy. * (c) Konstantin Kudryashov <ever.zet@gmail.com> * Marcello Duarte <marcello.duarte@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Prophecy\Comparator; use SebastianBergmann\Comparator\Comparator; use SebastianBergmann\Comparator\ComparisonFailure; /** * Closure comparator. * * @author Konstantin Kudryashov <ever.zet@gmail.com> */ final class ClosureComparator extends Comparator { public function accepts($expected, $actual) { return is_object($expected) && $expected instanceof \Closure && is_object($actual) && $actual instanceof \Closure; } public function assertEquals($expected, $actual, $delta = 0.0, $canonicalize = false, $ignoreCase = false) { throw new ComparisonFailure( $expected, $actual, // we don't need a diff '', '', false, 'all closures are born different' ); } }
{ "pile_set_name": "Github" }
RESET=$'\033[0m' BOLD=$'\033[1m' # shellcheck disable=SC2034 RED=$'\031[36m' YELLOW=$'\033[33m' # shellcheck disable=SC2034 CYAN=$'\033[36m' BLUE_BG=$'\033[44m' if [[ "$VERBOSE" = "" ]]; then VERBOSE=false fi function header() { local title="$1" echo "${BLUE_BG}${YELLOW}${BOLD}${title}${RESET}" echo "------------------------------------------" } function run() { echo "+ $*" "$@" } function verbose_run() { if $VERBOSE; then echo "+ $*" fi "$@" } function verbose_exec() { if $VERBOSE; then echo "+ $*" fi exec "$@" } function run_with_retries() { local TRY_NUM=1 local MAX_TRIES=3 while true; do echo "+ (Try $TRY_NUM/$MAX_TRIES) $*" if "$@"; then return 0 else (( TRY_NUM++ )) || true if [[ $TRY_NUM -gt $MAX_TRIES ]]; then return 1 else echo "${BOLD}${YELLOW}*** WARNING: command failed, retrying...${RESET}" fi fi done } # A single-value file is a file such as environments/ubuntu-18.04/image_tag. # It contains exactly 1 line of usable value, and may optionally contain # comments that start with '#', which are ignored. function read_single_value_file() { grep -v '^#' "$1" | head -n 1 } function require_args_exact() { local count="$1" shift if [[ $# -ne $count ]]; then echo "ERROR: $count arguments expected, but got $#." exit 1 fi } function require_envvar() { local name="$1" local value=$(eval "echo \$$name") if [[ "$value" = "" ]]; then echo "ERROR: please pass the '$name' environment variable to this script." exit 1 fi } function require_container_envvar() { local name="$1" local value=$(eval "echo \$$name") if [[ "$value" = "" ]]; then echo "ERROR: please pass the '$name' environment variable to the container." exit 1 fi } function require_container_mount() { local path="$1" if [[ ! -e "$path" ]]; then echo "ERROR: please ensure $path is mounted in the container." exit 1 fi } if command -v realpath &>/dev/null; then function absolute_path() { realpath -L "$1" } else function absolute_path() { local dir local name dir=$(dirname "$1") name=$(basename "$1") dir=$(cd "$dir" && pwd) echo "$dir/$name" } fi function list_environment_names() { ls -1 "$1" | grep -v '^utility$' | sort | xargs echo } function create_file_if_missing() { if [[ ! -e "$1" ]]; then run touch "$1" fi } function cleanup() { set +e local pids pids=$(jobs -p) if [[ "$pids" != "" ]]; then # shellcheck disable=SC2086 kill $pids 2>/dev/null fi if [[ $(type -t _cleanup) == function ]]; then _cleanup fi } trap cleanup EXIT
{ "pile_set_name": "Github" }
### [ANN] [TERA Smart money] [PoW, CPU, 1000 TPS] #### Introducing TERA | Smart money ![](https://ip.bitcointalk.org/?u=https%3A%2F%2Fraw.githubusercontent.com%2Fterafoundation%2Fwallet%2Fmaster%2FPic%2FTera.png&t=592&c=-AjXIgqy8s7IVw) We sent two important updates to the network, after which the network began to work stably. Now we will deal with smart contracts ... Last update 450: https://github.com/terafoundation/wallet #### Specification Name: TERA Consensus: PoW Algorithm: sha3 + meshhash (ASIC resistent hashing) Max emission: 1 Bln (TERA) Reward for block: 1-20 coins, depends on network power (one billionth of the remainder of undistributed amount of coins and multiplied by the hundredth part of the square of the logarithm of the network power) Block size 120 KB Premine: 5% Development fund: 1% of the mining amount Block generation time: 1 second Block confirmation time: 8 seconds Speed: from 1000 transactions per second Commission: free of charge #### Additional data: - Cryptography: sha3, secp256k1 - Protection against DDoS: PoW (hash calculation) - Platform: Node.JS - Wallets (src only): Windows, MacOS, Linux - Network launch: 01.07.2018 12:0:0 (UTC) - Mining launch: UTC "2018-07-24T15:33:20" - Type mining: CPU only #### Links and Resources - GitHub: https://github.com/terafoundation/wallet RUS description - Twitter: https://twitter.com/terafoundation - Telegram: https://web.telegram.org/#/im?p=@terafoundation - Discord: Common: https://discord.gg/CvwrbeG RUS: https://discord.gg/dzSGKyR #### Road map - Smart-contracts – July (?), 2018 - Internal voting system for adding new functions – August, 2018 - Decentralized messenger – September, 2018 - Decentralized stock exchange – Q4 2018 - Android/iOS Wallets – Q1 2019 - Sharding and increase in transaction speed to 1 million per second – Q2 2019 #### Referral mining program In the first year of the network work (when the number of the block is in the range from 2 mln to 30 mln), the referral program of mining works. If the miner indicated an adviser in his wallet, then he gets about twice the size of the reward, and his adviser receives a one-time reward. Thus, at the beginning of the action of the referral program, the emission is roughly tripled. Technically, an adviser is an account number. Any account can become an adviser, provided that it was created more than 1 mln blocks ago (i.e. approximately 12 days). In order to smooth out the emission curve, the award for referral mining is multiplied by a factor that assumes a value from 1 to 0. The factor takes the value equal to 1 at the beginning of the program and smoothly changes to 0 at the end of the program (up to 30 millionth block). An example of calculating coins emission: Let's assume that now the capacity of the network equals to 30 bits in the hash of the block, and it is 1 billion of unallocated coins in total, and we are at the very beginning of the mining program, then one award equals to 900/100 = 9 coins. Coins will be distributed as follows: 2 awards to the miner, 1 reward to the adviser, and in total there will be deducted 27 coins from the system account (3*9 = 27). In case if we are in the middle of the referral mining program, when the factor is 0.5, the emission takes the following values ​​in the example above: 1.5 of reward to the miner, 0.5 of reward to the adviser, and in total there will be deducted 18 coins from the system account (2*9 = 18) . Description of the coins storage rule The coins are kept in accounts by analogy with bank accounts. The accounts are numbered from 0 sequentially. The zero account number is for system account, to which initially 1 bln coins were issued. To create new account you need to send to the network special transaction ACCOUNT_CREATE where you need to specify a public key of the account owner and unnecessary characteristic “name of account” (a line with length up to 40 bytes). It is advisable to specify the name to check the correctness of the account number input when sending the payment. #### Transactions Minimal transaction size of coins transfer from account to account is 114 bytes. Minimal size can be obtained if there is one recipient and no description of the payment details. Transaction in text format JSON looks as follows: Code: { "Type": 110, "Version": 0, "Currency": 0, "FromID": 1, "OperationID": 40167, "To": [ { "ID": 2, "SumTER": 100, "SumCENT": 0 } ], "Description": "test", "Sign": "B39C39D91136E92C5B9530ABC683D9A1AF51E27382AFC69EA3B1F14AD7C4CDBE46D36BD743F2B4AE7760F8DDE706D81FB8201ABBF27DABF6F1EC658FE432C141" } Note: transaction in the example above has a length of 118 bytes. Text representation is packed in binary format + 12 bytes POW are added (for protection against DDoS). Payment details should be not more than 200 bytes. Actually the size is limited to a maximum of 65535 bytes, but 200 bytes is the size which can be seen by users’ wallets, if the length is more, they cut it. The longer the transaction length, the more calculation POW must be done to receive competitive transaction and its inclusion in block. Important change in update 11.07.2018: Added hash of accounts table in blockchain. This is implemented through a special transaction type 117 Code: { "Type": 117, "BlockNum": 956290, "Hash": "75455839E961080C73F1883B7758D27FC0FA63C5F599D37CD63BFC08AED1943A" } #### Starting the wallet Wait until the synchronization is complete - the green message Synchronization complete should appear. Below, when you start first time, two fields will appear: name and adviser. Enter the code of the adviser (if you have one), enter account name and click the Create button. After about 8 seconds, the account creation transaction will fit in the blockchain and you will have an open account where you can mine the coins. WARNING: To connect to the network, you must have a static IP address and an open port of 30000. Solving connection problems (when no start sync) 1. Check the presence of a direct ip-address (order from the provider) 2. Check if the port is routed from the router to your computer 3. Check the firewall (port must open on the computer)
{ "pile_set_name": "Github" }
package sts import "github.com/aws/aws-sdk-go/aws/request" func init() { initRequest = customizeRequest } func customizeRequest(r *request.Request) { r.RetryErrorCodes = append(r.RetryErrorCodes, ErrCodeIDPCommunicationErrorException) }
{ "pile_set_name": "Github" }
import React, { Component } from 'react'; import { inject, observer } from 'mobx-react'; import { ipcRenderer } from 'electron'; import helper from 'utils/helper'; @inject(stores => ({ song: stores.controller.song, scrobble: stores.controller.scrobble, next: stores.controller.next, play: () => stores.controller.play(stores.controller.song.id), tryTheNext: stores.controller.tryTheNext, playing: stores.controller.playing, volume: stores.preferences.volume, setVolume: stores.preferences.setVolume, autoPlay: stores.preferences.autoPlay, lyrics: stores.lyrics.list, })) @observer export default class AudioPlayer extends Component { componentWillReceiveProps(nextProps) { if (nextProps.playing !== this.props.playing) { try { if (!this.player.src // Avoid init player duplicate play && !this.props.autoPlay) { this.props.play(); } else { this.player[nextProps.playing ? 'play' : 'pause'](); } } catch (ex) { // Anti warnning } } if (this.props.song.id !== nextProps.song.id) { // Re-calculations the buffering progress this.bufferedDone = false; } } componentDidMount() { var player = this.player; var { volume, setVolume } = this.props; ipcRenderer.on('player-volume-up', () => { var volume = player.volume + .1; player.volume = volume > 1 ? 1 : volume; setVolume(player.volume); }); ipcRenderer.on('player-volume-down', () => { var volume = player.volume - .1; player.volume = volume < 0 ? 0 : volume; setVolume(player.volume); }); player.volume = volume; } passed = 0; progress(currentTime = 0) { var duration = this.props.song.duration; var ele = this.progress.ele; if (!ele || document.contains(ele) === false) { this.progress.ele = ele = document.all.progress; } // Reduce CPU usage, cancel the duplicate compution if (currentTime * 1000 - this.passed < 1000) { return; } clearTimeout(this.timer); this.timer = setTimeout( () => { // Some screens progress bar not visible if (ele) { let percent = (currentTime * 1000) / duration; this.setPosition(percent, ele); this.buffering(ele.lastElementChild); ele.firstElementChild.setAttribute('data-time', `${helper.getTime(currentTime * 1000)} / ${helper.getTime(duration)}`); } }, 450 ); this.passed = currentTime * 1000; } scrollerLyrics(currentTime = 0) { var lyrics = this.props.lyrics; var ele = this.scrollerLyrics.ele; if (window.location.hash !== '#/lyrics') { return false; } if (!ele || document.contains(ele) === false) { this.scrollerLyrics.ele = ele = document.getElementById('lyrics'); } if (ele) { let key = helper.getLyricsKey(currentTime * 1000, lyrics); if (key) { let playing = ele.querySelectorAll('[playing]'); Array.from(playing).map(e => e.removeAttribute('playing')); playing = ele.querySelector(`[data-times='${key}']`); if (!playing.getAttribute('playing')) { playing.setAttribute('playing', true); if (ele.querySelector('section').getAttribute('scrolling')) { // Enhancement #317 return; } playing.scrollIntoViewIfNeeded(); } } } } setPosition(percent, ele = document.all.progress) { if (!ele) return; ele = ele.firstElementChild; ele.style.transform = `translate3d(${-100 + percent * 100}%, 0, 0)`; } buffering(ele) { var player = this.player; if ( true && !this.bufferedDone && ele // Player has started && player.buffered.length ) { let buffered = player.buffered.end(player.buffered.length - 1); if (buffered >= 100) { buffered = 100; // Minimum reLayout this.bufferedDone = true; } ele.style.transform = `translate3d(${-100 + buffered}%, 0, 0)`; } } resetProgress() { clearTimeout(this.timer); this.passed = 0; this.setPosition(0); } render() { var { song, tryTheNext } = this.props; return ( <audio ref={ ele => (this.player = ele) } style={{ display: 'none' }} src={song.data ? song.data.src : null} autoPlay={true} onAbort={ e => { this.resetProgress(); } } onEnded={ e => { this.props.scrobble(); this.resetProgress(); this.props.next(true); } } onError={ e => { if (!e.target.src.startsWith('http') || song.waiting) return; console.log('Break by %o', e); this.resetProgress(); tryTheNext(); } } onSeeked={ e => { // Reset passed 0, avoid indicator can not go back this.passed = 0; } } onTimeUpdate={ e => { this.progress(e.target.currentTime); this.scrollerLyrics(e.target.currentTime); } } /> ); } }
{ "pile_set_name": "Github" }
SUBROUTINE ccsdt_lr_alpha2_7_13_1(d_a,k_a_offset,d_b,k_b_offset,d_ &c,k_c_offset) C $Id$ C This is a Fortran77 program generated by Tensor Contraction Engine v.1.0 C Copyright (c) Battelle & Pacific Northwest National Laboratory (2002) C i2 ( h2 h13 h11 h12 )_ytrbtra + = 1 * Sum ( p3 ) * tra ( p3 h11 )_tra * i3 ( h2 h13 h12 p3 )_ytrb IMPLICIT NONE #include "global.fh" #include "mafdecls.fh" #include "sym.fh" #include "errquit.fh" #include "tce.fh" INTEGER d_a INTEGER k_a_offset INTEGER d_b INTEGER k_b_offset INTEGER d_c INTEGER k_c_offset INTEGER nxtask INTEGER next INTEGER nprocs INTEGER count INTEGER h2b INTEGER h13b INTEGER h11b INTEGER h12b INTEGER dimc INTEGER l_c_sort INTEGER k_c_sort INTEGER p3b INTEGER p3b_1 INTEGER h11b_1 INTEGER h2b_2 INTEGER h13b_2 INTEGER h12b_2 INTEGER p3b_2 INTEGER dim_common INTEGER dima_sort INTEGER dima INTEGER dimb_sort INTEGER dimb INTEGER l_a_sort INTEGER k_a_sort INTEGER l_a INTEGER k_a INTEGER l_b_sort INTEGER k_b_sort INTEGER l_b INTEGER k_b INTEGER l_c INTEGER k_c EXTERNAL nxtask nprocs = GA_NNODES() count = 0 next = nxtask(nprocs,1) DO h2b = 1,noab DO h13b = h2b,noab DO h11b = 1,noab DO h12b = 1,noab IF (next.eq.count) THEN IF ((.not.restricted).or.(int_mb(k_spin+h2b-1)+int_mb(k_spin+h13b- &1)+int_mb(k_spin+h11b-1)+int_mb(k_spin+h12b-1).ne.8)) THEN IF (int_mb(k_spin+h2b-1)+int_mb(k_spin+h13b-1) .eq. int_mb(k_spin+ &h11b-1)+int_mb(k_spin+h12b-1)) THEN IF (ieor(int_mb(k_sym+h2b-1),ieor(int_mb(k_sym+h13b-1),ieor(int_mb &(k_sym+h11b-1),int_mb(k_sym+h12b-1)))) .eq. ieor(irrep_y,ieor(irre &p_trb,irrep_tra))) THEN dimc = int_mb(k_range+h2b-1) * int_mb(k_range+h13b-1) * int_mb(k_r &ange+h11b-1) * int_mb(k_range+h12b-1) IF (.not.MA_PUSH_GET(mt_dbl,dimc,'noname',l_c_sort,k_c_sort)) CALL & ERRQUIT('ccsdt_lr_alpha2_7_13_1',0,MA_ERR) CALL DFILL(dimc,0.0d0,dbl_mb(k_c_sort),1) DO p3b = noab+1,noab+nvab IF (int_mb(k_spin+p3b-1) .eq. int_mb(k_spin+h11b-1)) THEN IF (ieor(int_mb(k_sym+p3b-1),int_mb(k_sym+h11b-1)) .eq. irrep_tra) & THEN CALL TCE_RESTRICTED_2(p3b,h11b,p3b_1,h11b_1) CALL TCE_RESTRICTED_4(h2b,h13b,h12b,p3b,h2b_2,h13b_2,h12b_2,p3b_2) dim_common = int_mb(k_range+p3b-1) dima_sort = int_mb(k_range+h11b-1) dima = dim_common * dima_sort dimb_sort = int_mb(k_range+h2b-1) * int_mb(k_range+h13b-1) * int_m &b(k_range+h12b-1) dimb = dim_common * dimb_sort IF ((dima .gt. 0) .and. (dimb .gt. 0)) THEN IF (.not.MA_PUSH_GET(mt_dbl,dima,'noname',l_a_sort,k_a_sort)) CALL & ERRQUIT('ccsdt_lr_alpha2_7_13_1',1,MA_ERR) IF (.not.MA_PUSH_GET(mt_dbl,dima,'noname',l_a,k_a)) CALL ERRQUIT(' &ccsdt_lr_alpha2_7_13_1',2,MA_ERR) CALL GET_HASH_BLOCK(d_a,dbl_mb(k_a),dima,int_mb(k_a_offset),(h11b_ &1 - 1 + noab * (p3b_1 - noab - 1))) CALL TCE_SORT_2(dbl_mb(k_a),dbl_mb(k_a_sort),int_mb(k_range+p3b-1) &,int_mb(k_range+h11b-1),2,1,1.0d0) IF (.not.MA_POP_STACK(l_a)) CALL ERRQUIT('ccsdt_lr_alpha2_7_13_1', &3,MA_ERR) IF (.not.MA_PUSH_GET(mt_dbl,dimb,'noname',l_b_sort,k_b_sort)) CALL & ERRQUIT('ccsdt_lr_alpha2_7_13_1',4,MA_ERR) IF (.not.MA_PUSH_GET(mt_dbl,dimb,'noname',l_b,k_b)) CALL ERRQUIT(' &ccsdt_lr_alpha2_7_13_1',5,MA_ERR) IF ((h12b .le. p3b)) THEN CALL GET_HASH_BLOCK(d_b,dbl_mb(k_b),dimb,int_mb(k_b_offset),(p3b_2 & - noab - 1 + nvab * (h12b_2 - 1 + noab * (h13b_2 - 1 + noab * (h2 &b_2 - 1))))) CALL TCE_SORT_4(dbl_mb(k_b),dbl_mb(k_b_sort),int_mb(k_range+h2b-1) &,int_mb(k_range+h13b-1),int_mb(k_range+h12b-1),int_mb(k_range+p3b- &1),3,2,1,4,1.0d0) END IF IF (.not.MA_POP_STACK(l_b)) CALL ERRQUIT('ccsdt_lr_alpha2_7_13_1', &6,MA_ERR) CALL DGEMM('T','N',dima_sort,dimb_sort,dim_common,1.0d0,dbl_mb(k_a &_sort),dim_common,dbl_mb(k_b_sort),dim_common,1.0d0,dbl_mb(k_c_sor &t),dima_sort) IF (.not.MA_POP_STACK(l_b_sort)) CALL ERRQUIT('ccsdt_lr_alpha2_7_1 &3_1',7,MA_ERR) IF (.not.MA_POP_STACK(l_a_sort)) CALL ERRQUIT('ccsdt_lr_alpha2_7_1 &3_1',8,MA_ERR) END IF END IF END IF END DO IF (.not.MA_PUSH_GET(mt_dbl,dimc,'noname',l_c,k_c)) CALL ERRQUIT(' &ccsdt_lr_alpha2_7_13_1',9,MA_ERR) IF ((h11b .le. h12b)) THEN CALL TCE_SORT_4(dbl_mb(k_c_sort),dbl_mb(k_c),int_mb(k_range+h12b-1 &),int_mb(k_range+h13b-1),int_mb(k_range+h2b-1),int_mb(k_range+h11b &-1),3,2,4,1,1.0d0/2.0d0) CALL ADD_HASH_BLOCK(d_c,dbl_mb(k_c),dimc,int_mb(k_c_offset),(h12b &- 1 + noab * (h11b - 1 + noab * (h13b - 1 + noab * (h2b - 1))))) END IF IF ((h12b .le. h11b)) THEN CALL TCE_SORT_4(dbl_mb(k_c_sort),dbl_mb(k_c),int_mb(k_range+h12b-1 &),int_mb(k_range+h13b-1),int_mb(k_range+h2b-1),int_mb(k_range+h11b &-1),3,2,1,4,-1.0d0/2.0d0) CALL ADD_HASH_BLOCK(d_c,dbl_mb(k_c),dimc,int_mb(k_c_offset),(h11b &- 1 + noab * (h12b - 1 + noab * (h13b - 1 + noab * (h2b - 1))))) END IF IF (.not.MA_POP_STACK(l_c)) CALL ERRQUIT('ccsdt_lr_alpha2_7_13_1', &10,MA_ERR) IF (.not.MA_POP_STACK(l_c_sort)) CALL ERRQUIT('ccsdt_lr_alpha2_7_1 &3_1',11,MA_ERR) END IF END IF END IF next = nxtask(nprocs,1) END IF count = count + 1 END DO END DO END DO END DO next = nxtask(-nprocs,1) call GA_SYNC() RETURN END
{ "pile_set_name": "Github" }
/* * SonarQube * Copyright (C) 2009-2020 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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 3 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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. */ package org.sonar.xoo.lang; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import org.apache.commons.io.FileUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.sonar.api.batch.fs.InputFile; import org.sonar.api.batch.measure.MetricFinder; import org.sonar.api.batch.fs.internal.TestInputFileBuilder; import org.sonar.api.batch.sensor.internal.DefaultSensorDescriptor; import org.sonar.api.batch.sensor.internal.SensorContextTester; import org.sonar.api.measures.CoreMetrics; import org.sonar.api.measures.Metric; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class MeasureSensorTest { private MeasureSensor sensor; private SensorContextTester context; @Rule public TemporaryFolder temp = new TemporaryFolder(); @Rule public ExpectedException thrown = ExpectedException.none(); private File baseDir; private MetricFinder metricFinder; @Before public void prepare() throws IOException { baseDir = temp.newFolder(); metricFinder = mock(MetricFinder.class); sensor = new MeasureSensor(metricFinder); context = SensorContextTester.create(baseDir); } @Test public void testDescriptor() { sensor.describe(new DefaultSensorDescriptor()); } @Test public void testNoExecutionIfNoMeasureFile() { InputFile inputFile = new TestInputFileBuilder("foo", "src/foo.xoo").setLanguage("xoo").build(); context.fileSystem().add(inputFile); sensor.execute(context); } @Test public void testExecution() throws IOException { File measures = new File(baseDir, "src/foo.xoo.measures"); FileUtils.write(measures, "ncloc:12\nbranch_coverage:5.3\nsqale_index:300\nbool:true\n\n#comment", StandardCharsets.UTF_8); InputFile inputFile = new TestInputFileBuilder("foo", "src/foo.xoo").setLanguage("xoo").setModuleBaseDir(baseDir.toPath()).build(); context.fileSystem().add(inputFile); Metric<Boolean> booleanMetric = new Metric.Builder("bool", "Bool", Metric.ValueType.BOOL) .create(); when(metricFinder.<Integer>findByKey("ncloc")).thenReturn(CoreMetrics.NCLOC); when(metricFinder.<Double>findByKey("branch_coverage")).thenReturn(CoreMetrics.BRANCH_COVERAGE); when(metricFinder.<Long>findByKey("sqale_index")).thenReturn(CoreMetrics.TECHNICAL_DEBT); when(metricFinder.<Boolean>findByKey("bool")).thenReturn(booleanMetric); sensor.execute(context); assertThat(context.measure("foo:src/foo.xoo", CoreMetrics.NCLOC).value()).isEqualTo(12); assertThat(context.measure("foo:src/foo.xoo", CoreMetrics.BRANCH_COVERAGE).value()).isEqualTo(5.3); assertThat(context.measure("foo:src/foo.xoo", CoreMetrics.TECHNICAL_DEBT).value()).isEqualTo(300L); assertThat(context.measure("foo:src/foo.xoo", booleanMetric).value()).isTrue(); } @Test public void testExecutionForFoldersMeasures_no_measures() throws IOException { File measures = new File(baseDir, "src/folder.measures"); FileUtils.write(measures, "ncloc:12\nbranch_coverage:5.3\nsqale_index:300\nbool:true\n\n#comment", StandardCharsets.UTF_8); InputFile inputFile = new TestInputFileBuilder("foo", "src/foo.xoo").setLanguage("xoo").setModuleBaseDir(baseDir.toPath()).build(); context.fileSystem().add(inputFile); Metric<Boolean> booleanMetric = new Metric.Builder("bool", "Bool", Metric.ValueType.BOOL) .create(); when(metricFinder.<Integer>findByKey("ncloc")).thenReturn(CoreMetrics.NCLOC); when(metricFinder.<Double>findByKey("branch_coverage")).thenReturn(CoreMetrics.BRANCH_COVERAGE); when(metricFinder.<Long>findByKey("sqale_index")).thenReturn(CoreMetrics.TECHNICAL_DEBT); when(metricFinder.<Boolean>findByKey("bool")).thenReturn(booleanMetric); sensor.execute(context); assertThat(context.measure("foo:src", CoreMetrics.NCLOC)).isNull(); } @Test public void failIfMetricNotFound() throws IOException { File measures = new File(baseDir, "src/foo.xoo.measures"); FileUtils.write(measures, "unknow:12\n\n#comment"); InputFile inputFile = new TestInputFileBuilder("foo", "src/foo.xoo").setLanguage("xoo").setModuleBaseDir(baseDir.toPath()).build(); context.fileSystem().add(inputFile); thrown.expect(IllegalStateException.class); sensor.execute(context); } }
{ "pile_set_name": "Github" }
/* Copyright (C) 2014 Fredrik Johansson This file is part of Arb. Arb is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. See <http://www.gnu.org/licenses/>. */ #include "acb.h" void acb_get_mag_lower(mag_t z, const acb_t x) { if (arb_is_zero(acb_imagref(x))) { arb_get_mag_lower(z, acb_realref(x)); } else if (arb_is_zero(acb_realref(x))) { arb_get_mag_lower(z, acb_imagref(x)); } else { mag_t t; mag_init(t); arb_get_mag_lower(t, acb_realref(x)); arb_get_mag_lower(z, acb_imagref(x)); mag_mul_lower(t, t, t); mag_mul_lower(z, z, z); mag_add_lower(z, z, t); mag_sqrt_lower(z, z); mag_clear(t); } }
{ "pile_set_name": "Github" }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\HttpKernel\Profiler; use Psr\Log\LoggerInterface; use Symfony\Component\HttpFoundation\Exception\ConflictingHeadersException; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\DataCollector\DataCollectorInterface; use Symfony\Component\HttpKernel\DataCollector\LateDataCollectorInterface; use Symfony\Contracts\Service\ResetInterface; /** * Profiler. * * @author Fabien Potencier <fabien@symfony.com> */ class Profiler implements ResetInterface { private $storage; /** * @var DataCollectorInterface[] */ private $collectors = []; private $logger; private $initiallyEnabled = true; private $enabled = true; public function __construct(ProfilerStorageInterface $storage, LoggerInterface $logger = null, bool $enable = true) { $this->storage = $storage; $this->logger = $logger; $this->initiallyEnabled = $this->enabled = $enable; } /** * Disables the profiler. */ public function disable() { $this->enabled = false; } /** * Enables the profiler. */ public function enable() { $this->enabled = true; } /** * Loads the Profile for the given Response. * * @return Profile|null A Profile instance */ public function loadProfileFromResponse(Response $response) { if (!$token = $response->headers->get('X-Debug-Token')) { return null; } return $this->loadProfile($token); } /** * Loads the Profile for the given token. * * @return Profile|null A Profile instance */ public function loadProfile(string $token) { return $this->storage->read($token); } /** * Saves a Profile. * * @return bool */ public function saveProfile(Profile $profile) { // late collect foreach ($profile->getCollectors() as $collector) { if ($collector instanceof LateDataCollectorInterface) { $collector->lateCollect(); } } if (!($ret = $this->storage->write($profile)) && null !== $this->logger) { $this->logger->warning('Unable to store the profiler information.', ['configured_storage' => \get_class($this->storage)]); } return $ret; } /** * Purges all data from the storage. */ public function purge() { $this->storage->purge(); } /** * Finds profiler tokens for the given criteria. * * @param string|null $limit The maximum number of tokens to return * @param string|null $start The start date to search from * @param string|null $end The end date to search to * * @return array An array of tokens * * @see https://php.net/datetime.formats for the supported date/time formats */ public function find(?string $ip, ?string $url, ?string $limit, ?string $method, ?string $start, ?string $end, string $statusCode = null) { return $this->storage->find($ip, $url, $limit, $method, $this->getTimestamp($start), $this->getTimestamp($end), $statusCode); } /** * Collects data for the given Response. * * @return Profile|null A Profile instance or null if the profiler is disabled */ public function collect(Request $request, Response $response, \Throwable $exception = null) { if (false === $this->enabled) { return null; } $profile = new Profile(substr(hash('sha256', uniqid(mt_rand(), true)), 0, 6)); $profile->setTime(time()); $profile->setUrl($request->getUri()); $profile->setMethod($request->getMethod()); $profile->setStatusCode($response->getStatusCode()); try { $profile->setIp($request->getClientIp()); } catch (ConflictingHeadersException $e) { $profile->setIp('Unknown'); } if ($prevToken = $response->headers->get('X-Debug-Token')) { $response->headers->set('X-Previous-Debug-Token', $prevToken); } $response->headers->set('X-Debug-Token', $profile->getToken()); foreach ($this->collectors as $collector) { $collector->collect($request, $response, $exception); // we need to clone for sub-requests $profile->addCollector(clone $collector); } return $profile; } public function reset() { foreach ($this->collectors as $collector) { $collector->reset(); } $this->enabled = $this->initiallyEnabled; } /** * Gets the Collectors associated with this profiler. * * @return array An array of collectors */ public function all() { return $this->collectors; } /** * Sets the Collectors associated with this profiler. * * @param DataCollectorInterface[] $collectors An array of collectors */ public function set(array $collectors = []) { $this->collectors = []; foreach ($collectors as $collector) { $this->add($collector); } } /** * Adds a Collector. */ public function add(DataCollectorInterface $collector) { $this->collectors[$collector->getName()] = $collector; } /** * Returns true if a Collector for the given name exists. * * @param string $name A collector name * * @return bool */ public function has(string $name) { return isset($this->collectors[$name]); } /** * Gets a Collector by name. * * @param string $name A collector name * * @return DataCollectorInterface A DataCollectorInterface instance * * @throws \InvalidArgumentException if the collector does not exist */ public function get(string $name) { if (!isset($this->collectors[$name])) { throw new \InvalidArgumentException(sprintf('Collector "%s" does not exist.', $name)); } return $this->collectors[$name]; } private function getTimestamp(?string $value): ?int { if (null === $value || '' === $value) { return null; } try { $value = new \DateTime(is_numeric($value) ? '@'.$value : $value); } catch (\Exception $e) { return null; } return $value->getTimestamp(); } }
{ "pile_set_name": "Github" }
.radiobutton { position: relative; border: 2px solid #0070a9; border-radius: 50%; } .radiobutton-inner { position: absolute; left: 0; top: 0; width: 100%; height: 100%; background: #0070a9; border-radius: 50%; transform: scale(.6); } .radiobutton-disabled { opacity: 0.6; } .radiobutton-value { position: absolute; overflow: hidden; width: 1px; height: 1px; left: -999px; }
{ "pile_set_name": "Github" }
var Uploader = require('../../../src/uploader') describe('Uploader.File functions - file', function () { var uploader var file beforeEach(function () { uploader = new Uploader({}) var rFile = new File(['xx'], 'image.jpg', { type: 'image/png' }) file = new Uploader.File(uploader, rFile, uploader) }) it('should get type', function () { expect(file.getType()).toBe('png') file.file.type = '' expect(file.getType()).toBe('') }) it('should get extension', function () { expect(file.name).toBe('image.jpg') expect(file.getExtension()).toBe('jpg') file.name = '' expect(file.getExtension()).toBe('') file.name = 'image' expect(file.getExtension()).toBe('') file.name = '.dwq.dq.wd.qdw.E' expect(file.getExtension()).toBe('e') }) it('error', function () { expect(file.error).toBe(false) }) it('getSize', function () { expect(file.getSize()).toBe(2) }) it('getFormatSize', function () { expect(file.getFormatSize()).toBe('2 bytes') }) it('isComplete', function () { expect(file.isComplete()).toBe(false) }) it('getRoot', function () { var rootFile = file.getRoot() expect(rootFile).toBe(file) }) })
{ "pile_set_name": "Github" }
// Copyright (C) 2011-2019 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library 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 3, or (at your option) // any later version. // 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 General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. // 20.8.9 Function template bind // Verify that calls to bind() in BSD sockets API do not match std::bind() // (this is a GNU extension) // { dg-do compile { target c++11 } } #include <functional> struct my_sockaddr { }; typedef long my_socklen_t; int bind(int, const my_sockaddr*, my_socklen_t); using namespace std; int test01() { int fd = 1; my_sockaddr sa; // N.B. non-const size_t len = sizeof(sa); // N.B. size_t not my_socklen_t return bind(fd, &sa, len); }
{ "pile_set_name": "Github" }
/** * * WARNING! This file was autogenerated by: * _ _ _ _ __ __ * | | | | | | |\ \ / / * | | | | |_| | \ V / * | | | | _ | / \ * | |_| | | | |/ /^\ \ * \___/\_| |_/\/ \/ * * This file was autogenerated by UnrealHxGenerator using UHT definitions. * It only includes UPROPERTYs and UFUNCTIONs. Do not modify it! * In order to add more definitions, create or edit a type with the same name/package, but with an `_Extra` suffix **/ package unreal.displaycluster; /** WARNING: This type was not defined as DLL export on its declaration. Because of that, some of its methods are inaccessible Blueprint API function library **/ @:umodule("DisplayCluster") @:glueCppIncludes("Blueprints/DisplayClusterBlueprintLib.h") @:noClass @:uextern @:uclass extern class UDisplayClusterBlueprintLib extends unreal.UBlueprintFunctionLibrary { }
{ "pile_set_name": "Github" }
package solver import ( "context" "os" "sync" "github.com/moby/buildkit/solver/internal/pipe" "github.com/moby/buildkit/util/cond" "github.com/pkg/errors" "github.com/sirupsen/logrus" ) var debugScheduler = false // TODO: replace with logs in build trace func init() { if os.Getenv("BUILDKIT_SCHEDULER_DEBUG") == "1" { debugScheduler = true } } func newScheduler(ef edgeFactory) *scheduler { s := &scheduler{ waitq: map[*edge]struct{}{}, incoming: map[*edge][]*edgePipe{}, outgoing: map[*edge][]*edgePipe{}, stopped: make(chan struct{}), closed: make(chan struct{}), ef: ef, } s.cond = cond.NewStatefulCond(&s.mu) go s.loop() return s } type dispatcher struct { next *dispatcher e *edge } type scheduler struct { cond *cond.StatefulCond mu sync.Mutex muQ sync.Mutex ef edgeFactory waitq map[*edge]struct{} next *dispatcher last *dispatcher stopped chan struct{} stoppedOnce sync.Once closed chan struct{} incoming map[*edge][]*edgePipe outgoing map[*edge][]*edgePipe } func (s *scheduler) Stop() { s.stoppedOnce.Do(func() { close(s.stopped) }) <-s.closed } func (s *scheduler) loop() { defer func() { close(s.closed) }() go func() { <-s.stopped s.mu.Lock() s.cond.Signal() s.mu.Unlock() }() s.mu.Lock() for { select { case <-s.stopped: s.mu.Unlock() return default: } s.muQ.Lock() l := s.next if l != nil { if l == s.last { s.last = nil } s.next = l.next delete(s.waitq, l.e) } s.muQ.Unlock() if l == nil { s.cond.Wait() continue } s.dispatch(l.e) } } // dispatch schedules an edge to be processed func (s *scheduler) dispatch(e *edge) { inc := make([]pipe.Sender, len(s.incoming[e])) for i, p := range s.incoming[e] { inc[i] = p.Sender } out := make([]pipe.Receiver, len(s.outgoing[e])) for i, p := range s.outgoing[e] { out[i] = p.Receiver } e.hasActiveOutgoing = false updates := []pipe.Receiver{} for _, p := range out { if ok := p.Receive(); ok { updates = append(updates, p) } if !p.Status().Completed { e.hasActiveOutgoing = true } } pf := &pipeFactory{s: s, e: e} // unpark the edge debugSchedulerPreUnpark(e, inc, updates, out) e.unpark(inc, updates, out, pf) debugSchedulerPostUnpark(e, inc) postUnpark: // set up new requests that didn't complete/were added by this run openIncoming := make([]*edgePipe, 0, len(inc)) for _, r := range s.incoming[e] { if !r.Sender.Status().Completed { openIncoming = append(openIncoming, r) } } if len(openIncoming) > 0 { s.incoming[e] = openIncoming } else { delete(s.incoming, e) } openOutgoing := make([]*edgePipe, 0, len(out)) for _, r := range s.outgoing[e] { if !r.Receiver.Status().Completed { openOutgoing = append(openOutgoing, r) } } if len(openOutgoing) > 0 { s.outgoing[e] = openOutgoing } else { delete(s.outgoing, e) } // if keys changed there might be possiblity for merge with other edge if e.keysDidChange { if k := e.currentIndexKey(); k != nil { // skip this if not at least 1 key per dep origEdge := e.index.LoadOrStore(k, e) if origEdge != nil { logrus.Debugf("merging edge %s to %s\n", e.edge.Vertex.Name(), origEdge.edge.Vertex.Name()) if s.mergeTo(origEdge, e) { s.ef.setEdge(e.edge, origEdge) } } } e.keysDidChange = false } // validation to avoid deadlocks/resource leaks: // TODO: if these start showing up in error reports they can be changed // to error the edge instead. They can only appear from algorithm bugs in // unpark(), not for any external input. if len(openIncoming) > 0 && len(openOutgoing) == 0 { e.markFailed(pf, errors.New("buildkit scheduler error: return leaving incoming open. Please report this with BUILDKIT_SCHEDULER_DEBUG=1")) goto postUnpark } if len(openIncoming) == 0 && len(openOutgoing) > 0 { e.markFailed(pf, errors.New("buildkit scheduler error: return leaving outgoing open. Please report this with BUILDKIT_SCHEDULER_DEBUG=1")) goto postUnpark } } // signal notifies that an edge needs to be processed again func (s *scheduler) signal(e *edge) { s.muQ.Lock() if _, ok := s.waitq[e]; !ok { d := &dispatcher{e: e} if s.last == nil { s.next = d } else { s.last.next = d } s.last = d s.waitq[e] = struct{}{} s.cond.Signal() } s.muQ.Unlock() } // build evaluates edge into a result func (s *scheduler) build(ctx context.Context, edge Edge) (CachedResult, error) { s.mu.Lock() e := s.ef.getEdge(edge) if e == nil { s.mu.Unlock() return nil, errors.Errorf("invalid request %v for build", edge) } wait := make(chan struct{}) var p *pipe.Pipe p = s.newPipe(e, nil, pipe.Request{Payload: &edgeRequest{desiredState: edgeStatusComplete}}) p.OnSendCompletion = func() { p.Receiver.Receive() if p.Receiver.Status().Completed { close(wait) } } s.mu.Unlock() ctx, cancel := context.WithCancel(ctx) defer cancel() go func() { <-ctx.Done() p.Receiver.Cancel() }() <-wait if err := p.Receiver.Status().Err; err != nil { return nil, err } return p.Receiver.Status().Value.(*edgeState).result.Clone(), nil } // newPipe creates a new request pipe between two edges func (s *scheduler) newPipe(target, from *edge, req pipe.Request) *pipe.Pipe { p := &edgePipe{ Pipe: pipe.New(req), Target: target, From: from, } s.signal(target) if from != nil { p.OnSendCompletion = func() { p.mu.Lock() defer p.mu.Unlock() s.signal(p.From) } s.outgoing[from] = append(s.outgoing[from], p) } s.incoming[target] = append(s.incoming[target], p) p.OnReceiveCompletion = func() { p.mu.Lock() defer p.mu.Unlock() s.signal(p.Target) } return p.Pipe } // newRequestWithFunc creates a new request pipe that invokes a async function func (s *scheduler) newRequestWithFunc(e *edge, f func(context.Context) (interface{}, error)) pipe.Receiver { pp, start := pipe.NewWithFunction(f) p := &edgePipe{ Pipe: pp, From: e, } p.OnSendCompletion = func() { p.mu.Lock() defer p.mu.Unlock() s.signal(p.From) } s.outgoing[e] = append(s.outgoing[e], p) go start() return p.Receiver } // mergeTo merges the state from one edge to another. source edge is discarded. func (s *scheduler) mergeTo(target, src *edge) bool { if !target.edge.Vertex.Options().IgnoreCache && src.edge.Vertex.Options().IgnoreCache { return false } for _, inc := range s.incoming[src] { inc.mu.Lock() inc.Target = target s.incoming[target] = append(s.incoming[target], inc) inc.mu.Unlock() } for _, out := range s.outgoing[src] { out.mu.Lock() out.From = target s.outgoing[target] = append(s.outgoing[target], out) out.mu.Unlock() out.Receiver.Cancel() } delete(s.incoming, src) delete(s.outgoing, src) s.signal(target) for i, d := range src.deps { for _, k := range d.keys { target.secondaryExporters = append(target.secondaryExporters, expDep{i, CacheKeyWithSelector{CacheKey: k, Selector: src.cacheMap.Deps[i].Selector}}) } if d.slowCacheKey != nil { target.secondaryExporters = append(target.secondaryExporters, expDep{i, CacheKeyWithSelector{CacheKey: *d.slowCacheKey}}) } if d.result != nil { for _, dk := range d.result.CacheKeys() { target.secondaryExporters = append(target.secondaryExporters, expDep{i, CacheKeyWithSelector{CacheKey: dk, Selector: src.cacheMap.Deps[i].Selector}}) } } } // TODO(tonistiigi): merge cache providers return true } // edgeFactory allows access to the edges from a shared graph type edgeFactory interface { getEdge(Edge) *edge setEdge(Edge, *edge) } type pipeFactory struct { e *edge s *scheduler } func (pf *pipeFactory) NewInputRequest(ee Edge, req *edgeRequest) pipe.Receiver { target := pf.s.ef.getEdge(ee) if target == nil { panic("failed to get edge") // TODO: return errored pipe } p := pf.s.newPipe(target, pf.e, pipe.Request{Payload: req}) if debugScheduler { logrus.Debugf("> newPipe %s %p desiredState=%s", ee.Vertex.Name(), p, req.desiredState) } return p.Receiver } func (pf *pipeFactory) NewFuncRequest(f func(context.Context) (interface{}, error)) pipe.Receiver { p := pf.s.newRequestWithFunc(pf.e, f) if debugScheduler { logrus.Debugf("> newFunc %p", p) } return p } func debugSchedulerPreUnpark(e *edge, inc []pipe.Sender, updates, allPipes []pipe.Receiver) { if !debugScheduler { return } logrus.Debugf(">> unpark %s req=%d upt=%d out=%d state=%s %s", e.edge.Vertex.Name(), len(inc), len(updates), len(allPipes), e.state, e.edge.Vertex.Digest()) for i, dep := range e.deps { des := edgeStatusInitial if dep.req != nil { des = dep.req.Request().(*edgeRequest).desiredState } logrus.Debugf(":: dep%d %s state=%s des=%s keys=%d hasslowcache=%v", i, e.edge.Vertex.Inputs()[i].Vertex.Name(), dep.state, des, len(dep.keys), e.slowCacheFunc(dep) != nil) } for i, in := range inc { req := in.Request() logrus.Debugf("> incoming-%d: %p dstate=%s canceled=%v", i, in, req.Payload.(*edgeRequest).desiredState, req.Canceled) } for i, up := range updates { if up == e.cacheMapReq { logrus.Debugf("> update-%d: %p cacheMapReq complete=%v", i, up, up.Status().Completed) } else if up == e.execReq { logrus.Debugf("> update-%d: %p execReq complete=%v", i, up, up.Status().Completed) } else { st, ok := up.Status().Value.(*edgeState) if ok { index := -1 if dep, ok := e.depRequests[up]; ok { index = int(dep.index) } logrus.Debugf("> update-%d: %p input-%d keys=%d state=%s", i, up, index, len(st.keys), st.state) } else { logrus.Debugf("> update-%d: unknown", i) } } } } func debugSchedulerPostUnpark(e *edge, inc []pipe.Sender) { if !debugScheduler { return } for i, in := range inc { logrus.Debugf("< incoming-%d: %p completed=%v", i, in, in.Status().Completed) } logrus.Debugf("<< unpark %s\n", e.edge.Vertex.Name()) }
{ "pile_set_name": "Github" }
/* * Device driver for regulators in Hi655x IC * * Copyright (c) 2016 Hisilicon. * * Authors: * Chen Feng <puck.chen@hisilicon.com> * Fei Wang <w.f@huawei.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/bitops.h> #include <linux/device.h> #include <linux/err.h> #include <linux/module.h> #include <linux/io.h> #include <linux/of.h> #include <linux/platform_device.h> #include <linux/regmap.h> #include <linux/regulator/driver.h> #include <linux/regulator/machine.h> #include <linux/regulator/of_regulator.h> #include <linux/mfd/hi655x-pmic.h> struct hi655x_regulator { unsigned int disable_reg; unsigned int status_reg; unsigned int ctrl_regs; unsigned int ctrl_mask; struct regulator_desc rdesc; }; /* LDO7 & LDO10 */ static const unsigned int ldo7_voltages[] = { 1800000, 1850000, 2850000, 2900000, 3000000, 3100000, 3200000, 3300000, }; static const unsigned int ldo19_voltages[] = { 1800000, 1850000, 1900000, 1750000, 2800000, 2850000, 2900000, 3000000, }; static const unsigned int ldo22_voltages[] = { 900000, 1000000, 1050000, 1100000, 1150000, 1175000, 1185000, 1200000, }; enum hi655x_regulator_id { HI655X_LDO0, HI655X_LDO1, HI655X_LDO2, HI655X_LDO3, HI655X_LDO4, HI655X_LDO5, HI655X_LDO6, HI655X_LDO7, HI655X_LDO8, HI655X_LDO9, HI655X_LDO10, HI655X_LDO11, HI655X_LDO12, HI655X_LDO13, HI655X_LDO14, HI655X_LDO15, HI655X_LDO16, HI655X_LDO17, HI655X_LDO18, HI655X_LDO19, HI655X_LDO20, HI655X_LDO21, HI655X_LDO22, }; static int hi655x_is_enabled(struct regulator_dev *rdev) { unsigned int value = 0; struct hi655x_regulator *regulator = rdev_get_drvdata(rdev); regmap_read(rdev->regmap, regulator->status_reg, &value); return (value & BIT(regulator->ctrl_mask)); } static int hi655x_disable(struct regulator_dev *rdev) { int ret = 0; struct hi655x_regulator *regulator = rdev_get_drvdata(rdev); ret = regmap_write(rdev->regmap, regulator->disable_reg, BIT(regulator->ctrl_mask)); return ret; } static const struct regulator_ops hi655x_regulator_ops = { .enable = regulator_enable_regmap, .disable = hi655x_disable, .is_enabled = hi655x_is_enabled, .list_voltage = regulator_list_voltage_table, .get_voltage_sel = regulator_get_voltage_sel_regmap, .set_voltage_sel = regulator_set_voltage_sel_regmap, }; static const struct regulator_ops hi655x_ldo_linear_ops = { .enable = regulator_enable_regmap, .disable = hi655x_disable, .is_enabled = hi655x_is_enabled, .list_voltage = regulator_list_voltage_linear, .get_voltage_sel = regulator_get_voltage_sel_regmap, .set_voltage_sel = regulator_set_voltage_sel_regmap, }; #define HI655X_LDO(_ID, vreg, vmask, ereg, dreg, \ sreg, cmask, vtable) { \ .rdesc = { \ .name = #_ID, \ .of_match = of_match_ptr(#_ID), \ .ops = &hi655x_regulator_ops, \ .regulators_node = of_match_ptr("regulators"), \ .type = REGULATOR_VOLTAGE, \ .id = HI655X_##_ID, \ .owner = THIS_MODULE, \ .n_voltages = ARRAY_SIZE(vtable), \ .volt_table = vtable, \ .vsel_reg = HI655X_BUS_ADDR(vreg), \ .vsel_mask = vmask, \ .enable_reg = HI655X_BUS_ADDR(ereg), \ .enable_mask = BIT(cmask), \ }, \ .disable_reg = HI655X_BUS_ADDR(dreg), \ .status_reg = HI655X_BUS_ADDR(sreg), \ .ctrl_mask = cmask, \ } #define HI655X_LDO_LINEAR(_ID, vreg, vmask, ereg, dreg, \ sreg, cmask, minv, nvolt, vstep) { \ .rdesc = { \ .name = #_ID, \ .of_match = of_match_ptr(#_ID), \ .ops = &hi655x_ldo_linear_ops, \ .regulators_node = of_match_ptr("regulators"), \ .type = REGULATOR_VOLTAGE, \ .id = HI655X_##_ID, \ .owner = THIS_MODULE, \ .min_uV = minv, \ .n_voltages = nvolt, \ .uV_step = vstep, \ .vsel_reg = HI655X_BUS_ADDR(vreg), \ .vsel_mask = vmask, \ .enable_reg = HI655X_BUS_ADDR(ereg), \ .enable_mask = BIT(cmask), \ }, \ .disable_reg = HI655X_BUS_ADDR(dreg), \ .status_reg = HI655X_BUS_ADDR(sreg), \ .ctrl_mask = cmask, \ } static struct hi655x_regulator regulators[] = { HI655X_LDO_LINEAR(LDO2, 0x72, 0x07, 0x29, 0x2a, 0x2b, 0x01, 2500000, 8, 100000), HI655X_LDO(LDO7, 0x78, 0x07, 0x29, 0x2a, 0x2b, 0x06, ldo7_voltages), HI655X_LDO(LDO10, 0x78, 0x07, 0x29, 0x2a, 0x2b, 0x01, ldo7_voltages), HI655X_LDO_LINEAR(LDO13, 0x7e, 0x07, 0x2c, 0x2d, 0x2e, 0x04, 1600000, 8, 50000), HI655X_LDO_LINEAR(LDO14, 0x7f, 0x07, 0x2c, 0x2d, 0x2e, 0x05, 2500000, 8, 100000), HI655X_LDO_LINEAR(LDO15, 0x80, 0x07, 0x2c, 0x2d, 0x2e, 0x06, 1600000, 8, 50000), HI655X_LDO_LINEAR(LDO17, 0x82, 0x07, 0x2f, 0x30, 0x31, 0x00, 2500000, 8, 100000), HI655X_LDO(LDO19, 0x84, 0x07, 0x2f, 0x30, 0x31, 0x02, ldo19_voltages), HI655X_LDO_LINEAR(LDO21, 0x86, 0x07, 0x2f, 0x30, 0x31, 0x04, 1650000, 8, 50000), HI655X_LDO(LDO22, 0x87, 0x07, 0x2f, 0x30, 0x31, 0x05, ldo22_voltages), }; static int hi655x_regulator_probe(struct platform_device *pdev) { unsigned int i; struct hi655x_regulator *regulator; struct hi655x_pmic *pmic; struct regulator_config config = { }; struct regulator_dev *rdev; pmic = dev_get_drvdata(pdev->dev.parent); if (!pmic) { dev_err(&pdev->dev, "no pmic in the regulator parent node\n"); return -ENODEV; } regulator = devm_kzalloc(&pdev->dev, sizeof(*regulator), GFP_KERNEL); if (!regulator) return -ENOMEM; platform_set_drvdata(pdev, regulator); config.dev = pdev->dev.parent; config.regmap = pmic->regmap; config.driver_data = regulator; for (i = 0; i < ARRAY_SIZE(regulators); i++) { rdev = devm_regulator_register(&pdev->dev, &regulators[i].rdesc, &config); if (IS_ERR(rdev)) { dev_err(&pdev->dev, "failed to register regulator %s\n", regulator->rdesc.name); return PTR_ERR(rdev); } } return 0; } static const struct platform_device_id hi655x_regulator_table[] = { { .name = "hi655x-regulator" }, {}, }; MODULE_DEVICE_TABLE(platform, hi655x_regulator_table); static struct platform_driver hi655x_regulator_driver = { .id_table = hi655x_regulator_table, .driver = { .name = "hi655x-regulator", }, .probe = hi655x_regulator_probe, }; module_platform_driver(hi655x_regulator_driver); MODULE_AUTHOR("Chen Feng <puck.chen@hisilicon.com>"); MODULE_DESCRIPTION("Hisilicon Hi655x regulator driver"); MODULE_LICENSE("GPL v2");
{ "pile_set_name": "Github" }
import { Condition } from '../Condition' import { Frame } from 'puppeteer' export class TitleNotMatchCondition extends Condition { constructor(desc: string, public expectedTitle: string, public partial: boolean = false) { super(desc) } toString() { return `page title to equal '${this.expectedTitle}'` } public async waitFor(frame: Frame): Promise<boolean> { await frame.waitForFunction( (title: string, partial: boolean) => { if (typeof title === 'string') { if (title.startsWith('/') && title.endsWith('/')) { // RegExp const exp = new RegExp(title.slice(1, title.length - 1)) return !exp.test(document.title) } else if (partial) { return document.title.indexOf(title) === -1 } else { return document.title.trim() !== title.trim() } } }, { polling: 'mutation', timeout: 30e3 }, this.expectedTitle, this.partial === true, ) return true } public async waitForEvent(): Promise<any> { return } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ItemGroup> <ClInclude Include="pch.h" /> <ClInclude Include="android_native_app_glue.h" /> </ItemGroup> <ItemGroup> <ClCompile Include="android_native_app_glue.c" /> <ClCompile Include="main.cpp" /> </ItemGroup> </Project>
{ "pile_set_name": "Github" }
var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render }); function preload() { } var sprite; function create() { for (var i = 0; i < 1000; i++) { var x = game.rnd.integerInRange(10, 20); if (x === 20) { console.log('>>>', x); } else if (x === 10) { console.log('---', x); } else { // console.log(x); } } } function update() { } function render() { }
{ "pile_set_name": "Github" }
/-- Tests for reloading pre-compiled patterns. The first one gives an error right away, and can be any old pattern compiled in 8-bit mode ("abc" is typical). The others require the link size to be 2. */x <!testsaved8 %-- Generated from: /^[aL](?P<name>(?:[AaLl]+)[^xX-]*?)(?P<other>[\x{150}-\x{250}\x{300}]| [^\x{800}aAs-uS-U\x{d800}-\x{dfff}])++[^#\b\x{500}\x{1000}]{3,5}$ /x In 16-bit mode with options: S>testdata/saved16LE-1 FS>testdata/saved16BE-1 In 32-bit mode with options: S>testdata/saved32LE-1 FS>testdata/saved32BE-1 --%x <!testsaved16LE-1 <!testsaved16BE-1 <!testsaved32LE-1 <!testsaved32BE-1 /-- End of testinput21 --/
{ "pile_set_name": "Github" }
/* ** 2012 May 24 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** Implementation of the "unicode" full-text-search tokenizer. */ #ifndef SQLITE_DISABLE_FTS3_UNICODE #include "fts3Int.h" #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) #include <assert.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include "fts3_tokenizer.h" /* ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied ** from the sqlite3 source file utf.c. If this file is compiled as part ** of the amalgamation, they are not required. */ #ifndef SQLITE_AMALGAMATION static const unsigned char sqlite3Utf8Trans1[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00, }; #define READ_UTF8(zIn, zTerm, c) \ c = *(zIn++); \ if( c>=0xc0 ){ \ c = sqlite3Utf8Trans1[c-0xc0]; \ while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \ c = (c<<6) + (0x3f & *(zIn++)); \ } \ if( c<0x80 \ || (c&0xFFFFF800)==0xD800 \ || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \ } #define WRITE_UTF8(zOut, c) { \ if( c<0x00080 ){ \ *zOut++ = (u8)(c&0xFF); \ } \ else if( c<0x00800 ){ \ *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \ *zOut++ = 0x80 + (u8)(c & 0x3F); \ } \ else if( c<0x10000 ){ \ *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \ *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \ *zOut++ = 0x80 + (u8)(c & 0x3F); \ }else{ \ *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \ *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \ *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \ *zOut++ = 0x80 + (u8)(c & 0x3F); \ } \ } #endif /* ifndef SQLITE_AMALGAMATION */ typedef struct unicode_tokenizer unicode_tokenizer; typedef struct unicode_cursor unicode_cursor; struct unicode_tokenizer { sqlite3_tokenizer base; int eRemoveDiacritic; int nException; int *aiException; }; struct unicode_cursor { sqlite3_tokenizer_cursor base; const unsigned char *aInput; /* Input text being tokenized */ int nInput; /* Size of aInput[] in bytes */ int iOff; /* Current offset within aInput[] */ int iToken; /* Index of next token to be returned */ char *zToken; /* storage for current token */ int nAlloc; /* space allocated at zToken */ }; /* ** Destroy a tokenizer allocated by unicodeCreate(). */ static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){ if( pTokenizer ){ unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer; sqlite3_free(p->aiException); sqlite3_free(p); } return SQLITE_OK; } /* ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE ** statement has specified that the tokenizer for this table shall consider ** all characters in string zIn/nIn to be separators (if bAlnum==0) or ** token characters (if bAlnum==1). ** ** For each codepoint in the zIn/nIn string, this function checks if the ** sqlite3FtsUnicodeIsalnum() function already returns the desired result. ** If so, no action is taken. Otherwise, the codepoint is added to the ** unicode_tokenizer.aiException[] array. For the purposes of tokenization, ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all ** codepoints in the aiException[] array. ** ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic() ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored. ** It is not possible to change the behavior of the tokenizer with respect ** to these codepoints. */ static int unicodeAddExceptions( unicode_tokenizer *p, /* Tokenizer to add exceptions to */ int bAlnum, /* Replace Isalnum() return value with this */ const char *zIn, /* Array of characters to make exceptions */ int nIn /* Length of z in bytes */ ){ const unsigned char *z = (const unsigned char *)zIn; const unsigned char *zTerm = &z[nIn]; unsigned int iCode; int nEntry = 0; assert( bAlnum==0 || bAlnum==1 ); while( z<zTerm ){ READ_UTF8(z, zTerm, iCode); assert( (sqlite3FtsUnicodeIsalnum((int)iCode) & 0xFFFFFFFE)==0 ); if( sqlite3FtsUnicodeIsalnum((int)iCode)!=bAlnum && sqlite3FtsUnicodeIsdiacritic((int)iCode)==0 ){ nEntry++; } } if( nEntry ){ int *aNew; /* New aiException[] array */ int nNew; /* Number of valid entries in array aNew[] */ aNew = sqlite3_realloc64(p->aiException,(p->nException+nEntry)*sizeof(int)); if( aNew==0 ) return SQLITE_NOMEM; nNew = p->nException; z = (const unsigned char *)zIn; while( z<zTerm ){ READ_UTF8(z, zTerm, iCode); if( sqlite3FtsUnicodeIsalnum((int)iCode)!=bAlnum && sqlite3FtsUnicodeIsdiacritic((int)iCode)==0 ){ int i, j; for(i=0; i<nNew && aNew[i]<(int)iCode; i++); for(j=nNew; j>i; j--) aNew[j] = aNew[j-1]; aNew[i] = (int)iCode; nNew++; } } p->aiException = aNew; p->nException = nNew; } return SQLITE_OK; } /* ** Return true if the p->aiException[] array contains the value iCode. */ static int unicodeIsException(unicode_tokenizer *p, int iCode){ if( p->nException>0 ){ int *a = p->aiException; int iLo = 0; int iHi = p->nException-1; while( iHi>=iLo ){ int iTest = (iHi + iLo) / 2; if( iCode==a[iTest] ){ return 1; }else if( iCode>a[iTest] ){ iLo = iTest+1; }else{ iHi = iTest-1; } } } return 0; } /* ** Return true if, for the purposes of tokenization, codepoint iCode is ** considered a token character (not a separator). */ static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){ assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 ); return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode); } /* ** Create a new tokenizer instance. */ static int unicodeCreate( int nArg, /* Size of array argv[] */ const char * const *azArg, /* Tokenizer creation arguments */ sqlite3_tokenizer **pp /* OUT: New tokenizer handle */ ){ unicode_tokenizer *pNew; /* New tokenizer object */ int i; int rc = SQLITE_OK; pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer)); if( pNew==NULL ) return SQLITE_NOMEM; memset(pNew, 0, sizeof(unicode_tokenizer)); pNew->eRemoveDiacritic = 1; for(i=0; rc==SQLITE_OK && i<nArg; i++){ const char *z = azArg[i]; int n = (int)strlen(z); if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){ pNew->eRemoveDiacritic = 1; } else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){ pNew->eRemoveDiacritic = 0; } else if( n==19 && memcmp("remove_diacritics=2", z, 19)==0 ){ pNew->eRemoveDiacritic = 2; } else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){ rc = unicodeAddExceptions(pNew, 1, &z[11], n-11); } else if( n>=11 && memcmp("separators=", z, 11)==0 ){ rc = unicodeAddExceptions(pNew, 0, &z[11], n-11); } else{ /* Unrecognized argument */ rc = SQLITE_ERROR; } } if( rc!=SQLITE_OK ){ unicodeDestroy((sqlite3_tokenizer *)pNew); pNew = 0; } *pp = (sqlite3_tokenizer *)pNew; return rc; } /* ** Prepare to begin tokenizing a particular string. The input ** string to be tokenized is pInput[0..nBytes-1]. A cursor ** used to incrementally tokenize this string is returned in ** *ppCursor. */ static int unicodeOpen( sqlite3_tokenizer *p, /* The tokenizer */ const char *aInput, /* Input string */ int nInput, /* Size of string aInput in bytes */ sqlite3_tokenizer_cursor **pp /* OUT: New cursor object */ ){ unicode_cursor *pCsr; pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor)); if( pCsr==0 ){ return SQLITE_NOMEM; } memset(pCsr, 0, sizeof(unicode_cursor)); pCsr->aInput = (const unsigned char *)aInput; if( aInput==0 ){ pCsr->nInput = 0; }else if( nInput<0 ){ pCsr->nInput = (int)strlen(aInput); }else{ pCsr->nInput = nInput; } *pp = &pCsr->base; UNUSED_PARAMETER(p); return SQLITE_OK; } /* ** Close a tokenization cursor previously opened by a call to ** simpleOpen() above. */ static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){ unicode_cursor *pCsr = (unicode_cursor *) pCursor; sqlite3_free(pCsr->zToken); sqlite3_free(pCsr); return SQLITE_OK; } /* ** Extract the next token from a tokenization cursor. The cursor must ** have been opened by a prior call to simpleOpen(). */ static int unicodeNext( sqlite3_tokenizer_cursor *pC, /* Cursor returned by simpleOpen */ const char **paToken, /* OUT: Token text */ int *pnToken, /* OUT: Number of bytes at *paToken */ int *piStart, /* OUT: Starting offset of token */ int *piEnd, /* OUT: Ending offset of token */ int *piPos /* OUT: Position integer of token */ ){ unicode_cursor *pCsr = (unicode_cursor *)pC; unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer); unsigned int iCode = 0; char *zOut; const unsigned char *z = &pCsr->aInput[pCsr->iOff]; const unsigned char *zStart = z; const unsigned char *zEnd; const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput]; /* Scan past any delimiter characters before the start of the next token. ** Return SQLITE_DONE early if this takes us all the way to the end of ** the input. */ while( z<zTerm ){ READ_UTF8(z, zTerm, iCode); if( unicodeIsAlnum(p, (int)iCode) ) break; zStart = z; } if( zStart>=zTerm ) return SQLITE_DONE; zOut = pCsr->zToken; do { int iOut; /* Grow the output buffer if required. */ if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){ char *zNew = sqlite3_realloc64(pCsr->zToken, pCsr->nAlloc+64); if( !zNew ) return SQLITE_NOMEM; zOut = &zNew[zOut - pCsr->zToken]; pCsr->zToken = zNew; pCsr->nAlloc += 64; } /* Write the folded case of the last character read to the output */ zEnd = z; iOut = sqlite3FtsUnicodeFold((int)iCode, p->eRemoveDiacritic); if( iOut ){ WRITE_UTF8(zOut, iOut); } /* If the cursor is not at EOF, read the next character */ if( z>=zTerm ) break; READ_UTF8(z, zTerm, iCode); }while( unicodeIsAlnum(p, (int)iCode) || sqlite3FtsUnicodeIsdiacritic((int)iCode) ); /* Set the output variables and return. */ pCsr->iOff = (int)(z - pCsr->aInput); *paToken = pCsr->zToken; *pnToken = (int)(zOut - pCsr->zToken); *piStart = (int)(zStart - pCsr->aInput); *piEnd = (int)(zEnd - pCsr->aInput); *piPos = pCsr->iToken++; return SQLITE_OK; } /* ** Set *ppModule to a pointer to the sqlite3_tokenizer_module ** structure for the unicode tokenizer. */ void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){ static const sqlite3_tokenizer_module module = { 0, unicodeCreate, unicodeDestroy, unicodeOpen, unicodeClose, unicodeNext, 0, }; *ppModule = &module; } #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ #endif /* ifndef SQLITE_DISABLE_FTS3_UNICODE */
{ "pile_set_name": "Github" }
{ "compilerOptions": { "noEmitOnError": true } }
{ "pile_set_name": "Github" }
version https://git-lfs.github.com/spec/v1 oid sha256:b15248deb50af28b873eabf1b04b4364a36ed0441bc01596b869ce2f7793665b size 11886
{ "pile_set_name": "Github" }
package com.alg.top20.trie; import java.util.ArrayList; import java.util.List; class TSTNode { boolean isword; TSTNode left; TSTNode middle; TSTNode right; char data; public TSTNode(char data) { super(); this.data = data; } } public class TSTTrie implements ITrieSet { private TSTNode root; private int size; @Override public boolean add(String word) { MyBoolean isDuplicate = new MyBoolean(); TSTNode res = auxAdd(root, word, isDuplicate); if (root == null) root = res; if (isDuplicate.get() == false) ++size; return isDuplicate.get(); } private TSTNode auxAdd(TSTNode root, String word, MyBoolean isDuplicate) { if (root == null) { root = new TSTNode(word.charAt(0)); } if (root.data == word.charAt(0)) { if (word.length() == 1) { if (root.isword == true) isDuplicate.set(true); else root.isword = true; return root; } else root.middle = auxAdd(root.middle, word.substring(1), isDuplicate); } else if (word.charAt(0) < root.data) { root.left = auxAdd(root.left, word, isDuplicate); } else { root.right = auxAdd(root.right, word, isDuplicate); } return root; } @Override public boolean contains(String word) { return findLastNode(word).isword == true; } private static void auxDisplay(TSTNode root, int nspaces) { for (int i = 0; i < nspaces; ++i) System.out.print(' '); if (root == null) { System.out.println(-1); return; } else { System.out.println(root.data); // if(root.left == null && root.right == null) return; } auxDisplay(root.left, nspaces + 4); auxDisplay(root.middle, nspaces + 4); auxDisplay(root.right, nspaces + 4); } @Override public void display() { auxDisplay(root, 0); } private TSTNode findLastNode(String word) { if(word.trim().length() == 0) return root; TSTNode current = root; while (current != null) { if (word.charAt(0) < current.data) current = current.left; else if (word.charAt(0) > current.data) current = current.right; else { if (word.length() > 1) { current = current.middle; word = word.substring(1); } else break; } } if (current == null) return null; return current; } private void auxCollect(TSTNode root, String prefix, List<String> words) { if (root == null) return; auxCollect(root.left, prefix, words); if (root.isword == true) words.add(prefix + root.data); auxCollect(root.middle, prefix + root.data, words); auxCollect(root.right, prefix, words); } @Override public List<String> autocomplete(String prefix) { TSTNode tmp = findLastNode(prefix); if(tmp == null) return null; List<String> words = new ArrayList<String>(); if(tmp.isword == true) words.add(prefix); auxCollect(tmp == root? root:tmp.middle, prefix, words); return words; } @Override public boolean containsRE(String pattern) { // TODO Auto-generated method stub return false; } @Override public boolean remove(String word) { // TODO Auto-generated method stub return false; } public static void main(String[] args) { String[] words = { "cde", "abc", "aaa", "ab", "abd", "xyz", "xab" }; ITrieSet set = new TSTTrie(); for (int i = 0; i < words.length; ++i) set.add(words[i]); // set.display(); System.out.println(set.autocomplete("")); System.out.println(set.autocomplete("ab")); } }
{ "pile_set_name": "Github" }
// // ATPerson.h // ApptentiveConnect // // Created by Andrew Wooster on 10/2/12. // Copyright (c) 2012 Apptentive, Inc. All rights reserved. // #import <Foundation/Foundation.h> NSString *const ATCurrentPersonPreferenceKey; @interface ATPersonInfo : NSObject <NSCoding> { @private NSString *apptentiveID; NSString *name; NSString *facebookID; NSString *secret; BOOL needsUpdate; } @property (nonatomic, copy) NSString *apptentiveID; @property (nonatomic, copy) NSString *name; @property (nonatomic, copy) NSString *facebookID; @property (nonatomic, copy) NSString *emailAddress; @property (nonatomic, copy) NSString *secret; @property (nonatomic, assign) BOOL needsUpdate; + (BOOL)personExists; + (ATPersonInfo *)currentPerson; /*! If json is nil will not create a new person and will return nil. */ + (ATPersonInfo *)newPersonFromJSON:(NSDictionary *)json; - (NSDictionary *)apiJSON; - (void)saveAsCurrentPerson; @end
{ "pile_set_name": "Github" }
<dt><dfn>section</dfn></dt> <dd> <p>a self-contained portion of written content that deals with one or more related topics or thoughts </p> <p class="note">A section may consist of one or more paragraphs and include graphics, tables, lists and sub-sections. </p> </dd>
{ "pile_set_name": "Github" }
{ "pile_set_name": "Github" }
--- jupyter: jupytext: notebook_metadata_filter: all text_representation: extension: .md format_name: markdown format_version: '1.2' jupytext_version: 1.3.0 kernelspec: display_name: Python 3 language: python name: python3 language_info: codemirror_mode: name: ipython version: 3 file_extension: .py mimetype: text/x-python name: python nbconvert_exporter: python pygments_lexer: ipython3 version: 3.7.3 plotly: description: How to make 3D streamtube plots in Python with Plotly. display_as: 3d_charts language: python layout: base name: 3D Streamtube Plots order: 13 page_type: u-guide permalink: python/streamtube-plot/ thumbnail: thumbnail/streamtube.jpg --- ### Introduction In streamtube plots, attributes include `x`, `y`, and `z`, which set the coordinates of the vector field, and `u`, `v`, and `w`, which set the x, y, and z components of the vector field. Additionally, you can use `starts` to determine the streamtube's starting position. ### Basic Streamtube Plot ```python import plotly.graph_objects as go fig = go.Figure(data=go.Streamtube(x=[0, 0, 0], y=[0, 1, 2], z=[0, 0, 0], u=[0, 0, 0], v=[1, 1, 1], w=[0, 0, 0])) fig.show() ``` ### Starting Position and Segments By default, streamlines are initialized in the x-z plane of minimal y value. You can change this behaviour by providing directly the starting points of streamtubes. ```python import plotly.graph_objects as go import pandas as pd df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/streamtube-wind.csv').drop(['Unnamed: 0'],axis=1) fig = go.Figure(data=go.Streamtube( x = df['x'], y = df['y'], z = df['z'], u = df['u'], v = df['v'], w = df['w'], starts = dict( x = [80] * 16, y = [20,30,40,50] * 4, z = [0,0,0,0,5,5,5,5,10,10,10,10,15,15,15,15] ), sizeref = 0.3, colorscale = 'Portland', showscale = False, maxdisplayed = 3000 )) fig.update_layout( scene = dict( aspectratio = dict( x = 2, y = 1, z = 0.3 ) ), margin = dict( t = 20, b = 20, l = 20, r = 20 ) ) fig.show() ``` ### Tube color and diameter The color of tubes is determined by their local norm, and the diameter of the field by the local [divergence](https://en.wikipedia.org/wiki/Divergence) of the vector field. In all cases below the norm is proportional to `z**2` but the direction of the vector is different, resulting in a different divergence field. ```python import plotly.graph_objects as go from plotly.subplots import make_subplots import numpy as np x, y, z = np.mgrid[0:10, 0:10, 0:10] x = x.flatten() y = y.flatten() z = z.flatten() u = np.zeros_like(x) v = np.zeros_like(y) w = z**2 fig = make_subplots(rows=1, cols=3, specs=[[{'is_3d': True}, {'is_3d': True}, {'is_3d':True}]]) fig.add_trace(go.Streamtube(x=x, y=y, z=z, u=u, v=v, w=w), 1, 1) fig.add_trace(go.Streamtube(x=x, y=y, z=z, u=w, v=v, w=u), 1, 2) fig.add_trace(go.Streamtube(x=x, y=y, z=z, u=u, v=w, w=v), 1, 3) fig.update_layout(scene_camera_eye=dict(x=2, y=2, z=2), scene2_camera_eye=dict(x=2, y=2, z=2), scene3_camera_eye=dict(x=2, y=2, z=2)) fig.show() ``` #### Reference See https://plotly.com/python/reference/streamtube/ for more information and chart attribute options!
{ "pile_set_name": "Github" }
import { s__ } from '~/locale'; export const TrackingLabels = { CODE_INSTRUCTION: 'code_instruction', CONAN_INSTALLATION: 'conan_installation', MAVEN_INSTALLATION: 'maven_installation', NPM_INSTALLATION: 'npm_installation', NUGET_INSTALLATION: 'nuget_installation', PYPI_INSTALLATION: 'pypi_installation', COMPOSER_INSTALLATION: 'composer_installation', }; export const TrackingActions = { INSTALLATION: 'installation', REGISTRY_SETUP: 'registry_setup', COPY_CONAN_COMMAND: 'copy_conan_command', COPY_CONAN_SETUP_COMMAND: 'copy_conan_setup_command', COPY_MAVEN_XML: 'copy_maven_xml', COPY_MAVEN_COMMAND: 'copy_maven_command', COPY_MAVEN_SETUP: 'copy_maven_setup_xml', COPY_NPM_INSTALL_COMMAND: 'copy_npm_install_command', COPY_NPM_SETUP_COMMAND: 'copy_npm_setup_command', COPY_YARN_INSTALL_COMMAND: 'copy_yarn_install_command', COPY_YARN_SETUP_COMMAND: 'copy_yarn_setup_command', COPY_NUGET_INSTALL_COMMAND: 'copy_nuget_install_command', COPY_NUGET_SETUP_COMMAND: 'copy_nuget_setup_command', COPY_PIP_INSTALL_COMMAND: 'copy_pip_install_command', COPY_PYPI_SETUP_COMMAND: 'copy_pypi_setup_command', COPY_COMPOSER_REGISTRY_INCLUDE_COMMAND: 'copy_composer_registry_include_command', COPY_COMPOSER_PACKAGE_INCLUDE_COMMAND: 'copy_composer_package_include_command', }; export const NpmManager = { NPM: 'npm', YARN: 'yarn', }; export const FETCH_PACKAGE_VERSIONS_ERROR = s__( 'PackageRegistry|Unable to fetch package version information.', );
{ "pile_set_name": "Github" }
<?php declare(strict_types=1); namespace Zubr; /** * \Zubr\strrev() * * @link https://secure.php.net/strrev * * NOTES: same as \strrev() || in Zubr, $param_1 goes before $param_2, and we return an array instead of void */ function strrev($string) { return \strrev($string); }
{ "pile_set_name": "Github" }
define(['../lang/toString'], function(toString) { /** * Escapes a string for insertion into HTML. */ function escapeHtml(str){ str = toString(str) .replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/'/g, '&#39;') .replace(/"/g, '&quot;'); return str; } return escapeHtml; });
{ "pile_set_name": "Github" }
/* * Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencentcloudapi.scf.v20180416.models; import com.tencentcloudapi.common.AbstractModel; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; import java.util.HashMap; public class PublicNetConfigOut extends AbstractModel{ /** * 是否开启公网访问能力取值['DISABLE','ENABLE'] */ @SerializedName("PublicNetStatus") @Expose private String PublicNetStatus; /** * Eip配置 */ @SerializedName("EipConfig") @Expose private EipConfigOut EipConfig; /** * Get 是否开启公网访问能力取值['DISABLE','ENABLE'] * @return PublicNetStatus 是否开启公网访问能力取值['DISABLE','ENABLE'] */ public String getPublicNetStatus() { return this.PublicNetStatus; } /** * Set 是否开启公网访问能力取值['DISABLE','ENABLE'] * @param PublicNetStatus 是否开启公网访问能力取值['DISABLE','ENABLE'] */ public void setPublicNetStatus(String PublicNetStatus) { this.PublicNetStatus = PublicNetStatus; } /** * Get Eip配置 * @return EipConfig Eip配置 */ public EipConfigOut getEipConfig() { return this.EipConfig; } /** * Set Eip配置 * @param EipConfig Eip配置 */ public void setEipConfig(EipConfigOut EipConfig) { this.EipConfig = EipConfig; } /** * Internal implementation, normal users should not use it. */ public void toMap(HashMap<String, String> map, String prefix) { this.setParamSimple(map, prefix + "PublicNetStatus", this.PublicNetStatus); this.setParamObj(map, prefix + "EipConfig.", this.EipConfig); } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!-- ~ Copyright (c) 2017 Contributors to the Eclipse Foundation ~ ~ See the NOTICE file(s) distributed with this work for additional ~ information regarding copyright ownership. ~ ~ This program and the accompanying materials are made available under the ~ terms of the Eclipse Public License 2.0 which is available at ~ http://www.eclipse.org/legal/epl-2.0 ~ ~ SPDX-License-Identifier: EPL-2.0 --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.eclipse.ditto</groupId> <artifactId>ditto-model</artifactId> <version>${revision}</version> </parent> <artifactId>ditto-model-things</artifactId> <packaging>bundle</packaging> <name>Eclipse Ditto :: Model :: Things</name> <dependencies> <!-- ### Compile ### --> <dependency> <groupId>org.eclipse.ditto</groupId> <artifactId>ditto-model-base</artifactId> </dependency> <dependency> <groupId>org.eclipse.ditto</groupId> <artifactId>ditto-model-policies</artifactId> </dependency> <!-- ### Testing ### --> <dependency> <groupId>org.eclipse.ditto</groupId> <artifactId>ditto-model-base</artifactId> <type>test-jar</type> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <executions> <execution> <goals> <goal>test-jar</goal> </goals> <configuration> <includes> <include>org/eclipse/ditto/model/things/assertions/*</include> <include>org/eclipse/ditto/model/things/TestConstants*</include> </includes> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.apache.felix</groupId> <artifactId>maven-bundle-plugin</artifactId> <extensions>true</extensions> <configuration> <instructions> <Import-Package> !org.eclipse.ditto.utils.jsr305.annotations, org.eclipse.ditto.* </Import-Package> <Export-Package> org.eclipse.ditto.model.things.* </Export-Package> </instructions> </configuration> </plugin> <plugin> <groupId>com.github.siom79.japicmp</groupId> <artifactId>japicmp-maven-plugin</artifactId> <configuration> <parameter> <excludes> <!-- Don't add excludes here before checking with the whole Ditto team --> <!--<exclude></exclude>--> </excludes> </parameter> </configuration> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <executions> <execution> <id>produce-json-examples</id> <configuration> <mainClass>org.eclipse.ditto.model.things.examplejson.ThingModelJsonExamplesProducer </mainClass> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-site-plugin</artifactId> </plugin> </plugins> </build> </project>
{ "pile_set_name": "Github" }
package resp import ( "errors" "io" "strconv" ) var ( // Common encoding values optimized to avoid allocations. pong = []byte("+PONG\r\n") ok = []byte("+OK\r\n") t = []byte(":1\r\n") f = []byte(":0\r\n") one = t zero = f ) // ErrInvalidValue is returned if the value to encode is invalid. var ErrInvalidValue = errors.New("resp: invalid value") // Error represents an error string as defined by the RESP. It cannot // contain \r or \n characters. It must be used as a type conversion // so that Encode serializes the string as an Error. type Error string // Pong is a sentinel type used to indicate that the PONG simple string // value should be encoded. type Pong struct{} // OK is a sentinel type used to indicate that the OK simple string // value should be encoded. type OK struct{} // SimpleString represents a simple string as defined by the RESP. It // cannot contain \r or \n characters. It must be used as a type conversion // so that Encode serializes the string as a SimpleString. type SimpleString string // BulkString represents a binary-safe string as defined by the RESP. // It can be used as a type conversion so that Encode serializes the string // as a BulkString, but this is the default encoding for a normal Go string. type BulkString string // Encode encode the value v and writes the serialized data to w. func Encode(w io.Writer, v interface{}) error { return encodeValue(w, v) } // encodeValue encodes the value v and writes the serialized data to w. func encodeValue(w io.Writer, v interface{}) error { switch v := v.(type) { case OK: _, err := w.Write(ok) return err case Pong: _, err := w.Write(pong) return err case bool: if v { _, err := w.Write(t) return err } _, err := w.Write(f) return err case SimpleString: return encodeSimpleString(w, v) case Error: return encodeError(w, v) case int64: switch v { case 0: _, err := w.Write(zero) return err case 1: _, err := w.Write(one) return err default: return encodeInteger(w, v) } case string: return encodeBulkString(w, BulkString(v)) case BulkString: return encodeBulkString(w, v) case []string: return encodeStringArray(w, v) case []interface{}: return encodeArray(w, Array(v)) case Array: return encodeArray(w, v) case nil: return encodeNil(w) default: return ErrInvalidValue } } // encodeStringArray is a specialized array encoding func to avoid having to // allocate an empty slice interface and copy values to it to use encodeArray. func encodeStringArray(w io.Writer, v []string) error { // Special case for a nil array if v == nil { err := encodePrefixed(w, '*', "-1") return err } // First encode the number of elements n := len(v) err := encodePrefixed(w, '*', strconv.Itoa(n)) if err != nil { return err } // Then encode each value for _, el := range v { err = encodeBulkString(w, BulkString(el)) if err != nil { return err } } return nil } // encodeArray encodes an array value to w. func encodeArray(w io.Writer, v Array) error { // Special case for a nil array if v == nil { err := encodePrefixed(w, '*', "-1") return err } // First encode the number of elements n := len(v) err := encodePrefixed(w, '*', strconv.Itoa(n)) if err != nil { return err } // Then encode each value for _, el := range v { err = encodeValue(w, el) if err != nil { return err } } return nil } // encodeBulkString encodes a bulk string to w. func encodeBulkString(w io.Writer, v BulkString) error { n := len(v) data := strconv.Itoa(n) + "\r\n" + string(v) return encodePrefixed(w, '$', data) } // encodeInteger encodes an integer value to w. func encodeInteger(w io.Writer, v int64) error { return encodePrefixed(w, ':', strconv.FormatInt(v, 10)) } // encodeSimpleString encodes a simple string value to w. func encodeSimpleString(w io.Writer, v SimpleString) error { return encodePrefixed(w, '+', string(v)) } // encodeError encodes an error value to w. func encodeError(w io.Writer, v Error) error { return encodePrefixed(w, '-', string(v)) } // encodeNil encodes a nil value as a nil bulk string. func encodeNil(w io.Writer) error { return encodePrefixed(w, '$', "-1") } // encodePrefixed encodes the data v to w, with the specified prefix. func encodePrefixed(w io.Writer, prefix byte, v string) error { buf := make([]byte, len(v)+3) buf[0] = prefix copy(buf[1:], v) copy(buf[len(buf)-2:], "\r\n") _, err := w.Write(buf) return err }
{ "pile_set_name": "Github" }
/** * Spring Framework configuration files. */ package com.okta.developer.gateway.config;
{ "pile_set_name": "Github" }
{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Mimikatz Netlogon Unauthenticated NetrServerAuthenticate2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Metadata" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "| | |\n", "|:------------------|:---|\n", "| Author | Roberto Rodriguez @Cyb3rWard0g |\n", "| Creation Date | 2020/09/16 |\n", "| Modification Date | 2020/09/16 |\n", "| Tactics | ['[TA0008](https://attack.mitre.org/tactics/TA0008)'] |\n", "| Techniques | ['[T1210](https://attack.mitre.org/techniques/T1210)'] |\n", "| Tags | ['CVE-2020-1472', 'Password Update', 'Netlogon Insecure AES-CFB8'] |" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Dataset Description\n", "This dataset represents adversaries leveraging a vulnerability (CVE-2020-1472) in a cryptographic authentication scheme used by the Netlogon Remote Protocol, which among other things can be used to update computer passwords. This vulnerability was discovered by [@@SecuraBV](https://twitter.com/SecuraBV)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Datasets Downloads" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "| Dataset Type | Link |\n", "|:-------------|:-------|\n", "| Host | [https://raw.githubusercontent.com/OTRF/mordor/master/datasets/small/windows/lateral_movement/host/mimikatz_CVE-2020-1472_Unauthenticated_NetrServerAuthenticate2.zip](https://raw.githubusercontent.com/OTRF/mordor/master/datasets/small/windows/lateral_movement/host/mimikatz_CVE-2020-1472_Unauthenticated_NetrServerAuthenticate2.zip) |\n", "| Network | [https://raw.githubusercontent.com/OTRF/mordor/master/datasets/small/windows/lateral_movement/network/mimikatz_CVE-2020-1472_Unauthenticated_NetrServerAuthenticate2.zip](https://raw.githubusercontent.com/OTRF/mordor/master/datasets/small/windows/lateral_movement/network/mimikatz_CVE-2020-1472_Unauthenticated_NetrServerAuthenticate2.zip) |" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Notebooks\n", "Notebooks created by the community leveraging the mordor datasets" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "| Author | Name | Link |\n", "|:-------|:-----|:-----|" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Simulation Plan" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "| Environment | Tool Type | Module |\n", "|:------------|:----------|:-------|\n", "| Mordor shire | C2 | [ShellCmd](https://github.com/cobbr/Covenant/blob/7555b19ffb9401c0e37094c25e404a640b1688d7/Covenant/Data/Tasks/SharpSploit.Execution.yaml#L96) |\n", "| Mordor shire | tool | [lsadump](https://github.com/gentilkiwi/mimikatz/blob/6191b5a8ea40bbd856942cbc1e48a86c3c505dd3/mimikatz/modules/kuhl_m_lsadump.c#L23) |\n", "| Mordor shire | tool | [SharpZeroLogon](https://github.com/nccgroup/nccfsas/tree/main/Tools/SharpZeroLogon) |" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Adversary View\n", "```\n", "Mimikatz Implementation (NetrServerAuthenticate2)\n", "=================================================\n", "\n", "(wardog) > ShellCmd /shellcommand:\"C:\\Users\\pgustavo\\Downloads\\mimikatz_trunk\\x64\\mimikatz.exe \\\"lsadump::zerologon /target:MORDORDC.theshire.local /account:MORDORDC$ /exploit\\\" exit\"\n", "\n", " .#####. mimikatz 2.2.0 (x64) #19041 Sep 16 2020 12:02:22\n", ".## ^ ##. \"A La Vie, A L'Amour\" - (oe.eo)\n", "## / \\ ## /*** Benjamin DELPY `gentilkiwi` ( benjamin@gentilkiwi.com )\n", "## \\ / ## > http://blog.gentilkiwi.com/mimikatz\n", "'## v ##' Vincent LE TOUX ( vincent.letoux@gmail.com )\n", " '#####' > http://pingcastle.com / http://mysmartlogon.com ***/\n", "\n", "\n", "mimikatz(commandline) # lsadump::zerologon /target:MORDORDC.theshire.local /account:MORDORDC$ /exploit\n", "\n", "Target : MORDORDC.theshire.local\n", "Account: MORDORDC$\n", "Type : 6 (Server)\n", "Mode : exploit\n", "\n", "Trying to 'authenticate'...\n", "====================================================\n", "\n", "NetrServerAuthenticate2: 0x00000000\n", "NetrServerPasswordSet2 : 0x00000000\n", "\n", "* Authentication: OK -- vulnerable\n", "* Set password : OK -- may be unstable\n", "\n", "mimikatz(commandline) # exit\n", "\n", "Bye!\n", "\n", "DCSync Follow-up (Optional)\n", "(wardog) > ShellCmd /shellcommand:\"C:\\Users\\pgustavo\\Downloads\\mimikatz_trunk\\x64\\mimikatz.exe \\\"lsadump::dcsync /domain:theshire.local /dc:MORDORDC.theshire.local /user:krbtgt /authuser:MORDORDC$ /authdomain:theshire /authpassword:\\\\\"\\\\\" /authntlm\\\" exit\"\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Explore Mordor Dataset" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Initialize Analytics Engine" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from openhunt.mordorutils import *\n", "spark = get_spark()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Download & Process Mordor File" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mordor_file = \"https://raw.githubusercontent.com/OTRF/mordor/master/datasets/small/windows/lateral_movement/host/mimikatz_CVE-2020-1472_Unauthenticated_NetrServerAuthenticate2.zip\"\n", "registerMordorSQLTable(spark, mordor_file, \"mordorTable\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Get to know your data" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "df = spark.sql(\n", "'''\n", "SELECT Hostname,Channel,EventID, Count(*) as count\n", "FROM mordorTable\n", "GROUP BY Hostname,Channel,EventID\n", "ORDER BY count DESC\n", "'''\n", ")\n", "df.show(truncate=False)" ] } ], "metadata": { "kernelspec": { "display_name": "PySpark_Python3", "language": "python", "name": "pyspark3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.3" } }, "nbformat": 4, "nbformat_minor": 4 }
{ "pile_set_name": "Github" }
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- try: from ._models_py3 import ContainerServiceDiagnosticsProfile from ._models_py3 import ContainerServiceLinuxProfile from ._models_py3 import ContainerServiceMasterProfile from ._models_py3 import ContainerServiceNetworkProfile from ._models_py3 import ContainerServiceSshConfiguration from ._models_py3 import ContainerServiceSshPublicKey from ._models_py3 import ContainerServiceVMDiagnostics from ._models_py3 import ContainerServiceWindowsProfile from ._models_py3 import CredentialResult from ._models_py3 import CredentialResults from ._models_py3 import ManagedCluster from ._models_py3 import ManagedClusterAADProfile from ._models_py3 import ManagedClusterAccessProfile from ._models_py3 import ManagedClusterAddonProfile from ._models_py3 import ManagedClusterAgentPoolProfile from ._models_py3 import ManagedClusterPoolUpgradeProfile from ._models_py3 import ManagedClusterServicePrincipalProfile from ._models_py3 import ManagedClusterUpgradeProfile from ._models_py3 import OperationValue from ._models_py3 import OrchestratorProfile from ._models_py3 import Resource from ._models_py3 import TagsObject except (SyntaxError, ImportError): from ._models import ContainerServiceDiagnosticsProfile from ._models import ContainerServiceLinuxProfile from ._models import ContainerServiceMasterProfile from ._models import ContainerServiceNetworkProfile from ._models import ContainerServiceSshConfiguration from ._models import ContainerServiceSshPublicKey from ._models import ContainerServiceVMDiagnostics from ._models import ContainerServiceWindowsProfile from ._models import CredentialResult from ._models import CredentialResults from ._models import ManagedCluster from ._models import ManagedClusterAADProfile from ._models import ManagedClusterAccessProfile from ._models import ManagedClusterAddonProfile from ._models import ManagedClusterAgentPoolProfile from ._models import ManagedClusterPoolUpgradeProfile from ._models import ManagedClusterServicePrincipalProfile from ._models import ManagedClusterUpgradeProfile from ._models import OperationValue from ._models import OrchestratorProfile from ._models import Resource from ._models import TagsObject from ._paged_models import ManagedClusterPaged from ._paged_models import OperationValuePaged from ._container_service_client_enums import ( ContainerServiceStorageProfileTypes, ContainerServiceVMSizeTypes, OSType, NetworkPlugin, NetworkPolicy, ) __all__ = [ 'ContainerServiceDiagnosticsProfile', 'ContainerServiceLinuxProfile', 'ContainerServiceMasterProfile', 'ContainerServiceNetworkProfile', 'ContainerServiceSshConfiguration', 'ContainerServiceSshPublicKey', 'ContainerServiceVMDiagnostics', 'ContainerServiceWindowsProfile', 'CredentialResult', 'CredentialResults', 'ManagedCluster', 'ManagedClusterAADProfile', 'ManagedClusterAccessProfile', 'ManagedClusterAddonProfile', 'ManagedClusterAgentPoolProfile', 'ManagedClusterPoolUpgradeProfile', 'ManagedClusterServicePrincipalProfile', 'ManagedClusterUpgradeProfile', 'OperationValue', 'OrchestratorProfile', 'Resource', 'TagsObject', 'OperationValuePaged', 'ManagedClusterPaged', 'ContainerServiceStorageProfileTypes', 'ContainerServiceVMSizeTypes', 'OSType', 'NetworkPlugin', 'NetworkPolicy', ]
{ "pile_set_name": "Github" }
(function() { var fitopts = {min: 6, max: 1000}; var Gauge = function(json) { // Init view.View.call(this, json); this.clickFocusable = true; // Config this.query = json.query; this.title = json.title; this.commaSeparateThousands = json.commaSeparateThousands; // State this.currentEvent = null; // HTML this.el.addClass('gauge'); this.el.append( '<div class="box">' + '<div class="quickfit metric value">?</div>' + '<h2 class="quickfit"></h2>' + '</div>' ); this.box = this.el.find('.box'); this.el.find('h2').text(this.title); // When clicked, display event var self = this; this.box.click(function() { eventPane.show(self.currentEvent) }); if (this.query) { var reflowed = false; var me = this; var value = this.el.find('.value'); this.sub = subs.subscribe(this.query, function(e) { self.currentEvent = e; me.box.attr('class', 'box state ' + e.state); if (e.metric != undefined) { value.text(format.float(e.metric, 2, me.commaSeparateThousands)); } else if (e.state != undefined) { value.text(e.state) } value.attr('title', e.description); // The first time, do a full-height reflow. if (reflowed) { value.quickfit(fitopts); } else { me.reflow(); reflowed = true; } }); } } view.inherit(view.View, Gauge); view.Gauge = Gauge; view.types.Gauge = Gauge; Gauge.prototype.json = function() { return $.extend(view.View.prototype.json.call(this), { type: 'Gauge', title: this.title, query: this.query, commaSeparateThousands: this.commaSeparateThousands }); } var editTemplate = _.template( "<label for='title'>Title</label>" + "<input type='text' name='title' value='{{title}}' /><br />" + "<label for='query'>Query</label>" + '<textarea type="text" name="query" class="query">{{query}}</textarea>' + "<label for='commaSeparateThousands'>Comma Separate Thousands</label>" + "<input type='checkbox' name='commaSeparateThousands' {% if(commaSeparateThousands) { %} checked='checked' {% } %} />" ); Gauge.prototype.editForm = function() { return editTemplate(this); } Gauge.prototype.reflow = function() { // Size metric var value = this.el.find('.value'); value.quickfit({min: 6, max: 1000, font_height_scale: 1}); // Size title var title = this.el.find('h2'); title.quickfit(fitopts); } Gauge.prototype.delete = function() { if (this.sub) { subs.unsubscribe(this.sub); } view.View.prototype.delete.call(this); } })();
{ "pile_set_name": "Github" }
/* * 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.ambari.server.audit.request.creator; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.ambari.server.api.query.Query; import org.apache.ambari.server.api.query.render.Renderer; import org.apache.ambari.server.api.resources.ResourceDefinition; import org.apache.ambari.server.api.resources.ResourceInstance; import org.apache.ambari.server.api.resources.SubResourceDefinition; import org.apache.ambari.server.api.services.NamedPropertySet; import org.apache.ambari.server.api.services.Request; import org.apache.ambari.server.api.services.RequestBody; import org.apache.ambari.server.api.services.Result; import org.apache.ambari.server.api.services.ResultMetadata; import org.apache.ambari.server.api.services.ResultStatus; import org.apache.ambari.server.api.util.TreeNode; import org.apache.ambari.server.audit.AuditLogger; import org.apache.ambari.server.audit.event.AuditEvent; import org.apache.ambari.server.audit.request.RequestAuditLogger; import org.apache.ambari.server.audit.request.RequestAuditLoggerImpl; import org.apache.ambari.server.audit.request.eventcreator.RequestAuditEventCreator; import org.apache.ambari.server.controller.spi.PageRequest; import org.apache.ambari.server.controller.spi.Predicate; import org.apache.ambari.server.controller.spi.Resource; import org.apache.ambari.server.controller.spi.SortRequest; import org.apache.ambari.server.controller.spi.TemporalInfo; import org.easymock.Capture; import org.easymock.EasyMock; public class AuditEventCreatorTestHelper { public static AuditEvent getEvent(RequestAuditEventCreator eventCreator, Request request, Result result) { Set<RequestAuditEventCreator> creatorSet = new HashSet<>(); creatorSet.add(eventCreator); AuditLogger auditLogger = EasyMock.createNiceMock(AuditLogger.class); EasyMock.expect(auditLogger.isEnabled()).andReturn(true).anyTimes(); Capture<AuditEvent> capture = EasyMock.newCapture(); auditLogger.log(EasyMock.capture(capture)); EasyMock.expectLastCall(); EasyMock.replay(auditLogger); RequestAuditLogger requestAuditLogger = new RequestAuditLoggerImpl(auditLogger, creatorSet); requestAuditLogger.log(request, result); return capture.getValue(); } public static Request createRequest(final Request.Type requestType, final Resource.Type resourceType, final Map<String,Object> properties, final Map<Resource.Type, String> resource) { return createRequest(requestType, resourceType, properties, resource, ""); } public static Request createRequest(final Request.Type requestType, final Resource.Type resourceType, final Map<String,Object> properties, final Map<Resource.Type, String> resource, final String queryString) { return new Request() { RequestBody body = new RequestBody(); @Override public Result process() { return null; } @Override public ResourceInstance getResource() { return new ResourceInstance() { @Override public void setKeyValueMap(Map<Resource.Type, String> keyValueMap) { } @Override public Map<Resource.Type, String> getKeyValueMap() { return resource; } @Override public Query getQuery() { return null; } @Override public ResourceDefinition getResourceDefinition() { return new ResourceDefinition() { @Override public String getPluralName() { return null; } @Override public String getSingularName() { return null; } @Override public Resource.Type getType() { return resourceType; } @Override public Set<SubResourceDefinition> getSubResourceDefinitions() { return null; } @Override public List<PostProcessor> getPostProcessors() { return null; } @Override public Renderer getRenderer(String name) throws IllegalArgumentException { return null; } @Override public Collection<String> getCreateDirectives() { return null; } @Override public Collection<String> getReadDirectives() { return null; } @Override public boolean isCreatable() { return false; } @Override public Collection<String> getUpdateDirectives() { return null; } @Override public Collection<String> getDeleteDirectives() { return null; } }; } @Override public Map<String, ResourceInstance> getSubResources() { return null; } @Override public boolean isCollectionResource() { return false; } }; } @Override public String getURI() { return "http://example.com:8080/api/v1/test" + queryString; } @Override public Type getRequestType() { return requestType; } @Override public int getAPIVersion() { return 0; } @Override public Predicate getQueryPredicate() { return null; } @Override public Map<String, TemporalInfo> getFields() { return null; } @Override public RequestBody getBody() { if(properties != null) { NamedPropertySet nps = new NamedPropertySet("", properties); body.addPropertySet(nps); } return body; } @Override public Map<String, List<String>> getHttpHeaders() { return null; } @Override public PageRequest getPageRequest() { return null; } @Override public SortRequest getSortRequest() { return null; } @Override public Renderer getRenderer() { return null; } @Override public String getRemoteAddress() { return "1.2.3.4"; } }; } public static Result createResult(final ResultStatus status) { return createResult(status, null); } public static Result createResult(final ResultStatus status, final TreeNode<Resource> resultTree) { return new Result() { @Override public TreeNode<Resource> getResultTree() { return resultTree; } @Override public boolean isSynchronous() { return false; } @Override public ResultStatus getStatus() { return status; } @Override public void setResultStatus(ResultStatus status) { } @Override public void setResultMetadata(ResultMetadata resultMetadata) { } @Override public ResultMetadata getResultMetadata() { return null; } }; } }
{ "pile_set_name": "Github" }
id: SecBI - Test version: -1 name: SecBI - Test description: "" starttaskid: "0" tasks: "0": id: "0" taskid: 02b0cf46-1242-420e-8a44-9eb49cd49a56 type: start task: id: 02b0cf46-1242-420e-8a44-9eb49cd49a56 version: -1 name: "" iscommand: false brand: "" nexttasks: '#none#': - "2" separatecontext: false view: |- { "position": { "x": 50, "y": 50 } } note: false timertriggers: [] ignoreworker: false "1": id: "1" taskid: ee84b2ae-a1b2-491a-803d-568cb49785d6 type: regular task: id: ee84b2ae-a1b2-491a-803d-568cb49785d6 version: -1 name: Get Incidents by Query script: '|||secbi-get-incidents-list' type: regular iscommand: true brand: "" nexttasks: '#none#': - "3" scriptarguments: limit: simple: "3" separatecontext: false view: |- { "position": { "x": 50, "y": 370 } } note: false timertriggers: [] ignoreworker: false "2": id: "2" taskid: f51f7332-625c-4700-82d7-0117b5530c2c type: regular task: id: f51f7332-625c-4700-82d7-0117b5530c2c version: -1 name: Delete context description: Delete field from context scriptName: DeleteContext type: regular iscommand: false brand: "" nexttasks: '#none#': - "1" scriptarguments: all: simple: "yes" index: {} key: {} keysToKeep: {} subplaybook: {} separatecontext: false view: |- { "position": { "x": 50, "y": 195 } } note: false timertriggers: [] ignoreworker: false "3": id: "3" taskid: de3df3c5-4424-4bf8-8692-982507c0ddbb type: regular task: id: de3df3c5-4424-4bf8-8692-982507c0ddbb version: -1 name: Get SecBI Incident Data script: '|||secbi-get-incident' type: regular iscommand: true brand: "" nexttasks: '#none#': - "4" scriptarguments: incident_id: simple: ${SecBI.IncidentsList} separatecontext: false view: |- { "position": { "x": 50, "y": 545 } } note: false timertriggers: [] ignoreworker: false "4": id: "4" taskid: 5892cd5d-eabd-44c1-86a9-4910e4fe165e type: condition task: id: 5892cd5d-eabd-44c1-86a9-4910e4fe165e version: -1 name: Check results have host description: Check whether the values provided in arguments are equal. If either of the arguments are missing, no is returned. type: condition iscommand: false brand: "" nexttasks: "yes": - "5" separatecontext: false conditions: - label: "yes" condition: - - operator: isExists left: value: simple: SecBI.Incident.Host iscontext: true view: |- { "position": { "x": 50, "y": 720 } } note: false timertriggers: [] ignoreworker: false "5": id: "5" taskid: acc6c934-3b9e-4b30-8562-a7bf7463e5a3 type: regular task: id: acc6c934-3b9e-4b30-8562-a7bf7463e5a3 version: -1 name: Print description: Prints text to war room (Markdown supported) scriptName: Print type: regular iscommand: false brand: "" scriptarguments: value: simple: Found Result! separatecontext: false view: |- { "position": { "x": 60, "y": 930 } } note: false timertriggers: [] ignoreworker: false view: |- { "linkLabelsPosition": {}, "paper": { "dimensions": { "height": 975, "width": 390, "x": 50, "y": 50 } } } inputs: [] outputs: [] fromversion: 5.0.0
{ "pile_set_name": "Github" }
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Chapter&nbsp;6.&nbsp;Proprietates del projecto</title> <link rel="stylesheet" type="text/css" href="OmegaT.css"> <meta name="generator" content="DocBook XSL Stylesheets V1.79.1"> <link rel="home" href="index.html" title="OmegaT 3.5 - Guida del usator"> <link rel="up" href="index.html" title="OmegaT 3.5 - Guida del usator"> <link rel="prev" href="chapter.menu.html" title="Chapter&nbsp;5.&nbsp;Menu e vias breve del claviero"> <link rel="next" href="chapter.file.filters.html" title="Chapter&nbsp;7.&nbsp;Filtros del file"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <div class="navheader"> <table width="100%" summary="Navigation header"> <tr> <th colspan="3" align="center">Chapter&nbsp;6.&nbsp;Proprietates del projecto</th> </tr> <tr> <td width="20%" align="left"><a accesskey="p" href="chapter.menu.html">Prev</a>&nbsp; </td> <th width="60%" align="center">&nbsp;</th> <td width="20%" align="right">&nbsp;<a accesskey="n" href="chapter.file.filters.html">Next</a></td> </tr> </table> <hr> </div> <div class="chapter"> <div class="titlepage"> <div> <div> <h1 class="title"><a name="chapter.project.properties"></a>Chapter&nbsp;6.&nbsp;Proprietates del projecto<a class="indexterm" name="d0e4666"></a></h1> </div> </div> </div> <div class="toc"> <dl class="toc"> <dt><span class="section"><a href="chapter.project.properties.html#properties.dialog">1. Generalitates</a></span></dt> <dt><span class="section"><a href="chapter.project.properties.html#d0e4690">2. Linguas</a></span></dt> <dt><span class="section"><a href="chapter.project.properties.html#d0e4700">3. Optiones</a></span></dt> <dt><span class="section"><a href="chapter.project.properties.html#d0e4794">4. Locationes del files</a></span></dt> </dl> </div> <div class="section"> <div class="titlepage"> <div> <div> <h2 class="title" style="clear: both"><a name="properties.dialog"></a>1.&nbsp;Generalitates </h2> </div> </div> </div> <p>Le dialogo <span class="guimenu">Projecto</span> → <span class="guimenuitem">Proprietates...</span> (<span class="shortcut"><strong><span class="keycap"><strong>Ctrl</strong></span>+<span class="keycap"><strong>E</strong></span></strong></span>) es usate pro definir e modificar le plicas e le linguas del projecto. </p> <p>Il es possibile modificar le proprietates del projecto durante un session de traduction. Nota que le cambios al preparationes del projecto pote haber alicun consequentias, specialmente quando le projecto esseva jam initiate. Usque tu non ha qualque experientia con OmegaT, il es plus secur considerar tote le configurationes final un vice que le traduction initiava – a minus que, naturalmente, tu percipe que esseva facite un error major. Vide le section Impedir perdita del datos pro manieras e medios de protection de tu opera. </p> </div> <div class="section"> <div class="titlepage"> <div> <div> <h2 class="title" style="clear: both"><a name="d0e4690"></a>2.&nbsp;Linguas </h2> </div> </div> </div> <p>Tu pote o inscriber a mano le linguas fonte e de destination, o usar le menus a tenta cadente. Rememora te que cambiar le linguas pote render inusabile le memorias de traduction actualmente usate, pois que lor par de linguas pote non concordar plus con le nove linguas. </p> <p>Le cercatores de radices (Tokenizers) correspondente al linguas seligite es monstrate. Vider pro le detalios le <a class="link" href="appendix.Tokenizers.inOmegaT.html" title="Appendix&nbsp;D.&nbsp;Tokenizers">Appendice del cercatores de radices</a>. </p> </div> <div class="section"> <div class="titlepage"> <div> <div> <h2 class="title" style="clear: both"><a name="d0e4700"></a>3.&nbsp;Optiones </h2> </div> </div> </div> <div class="variablelist"> <dl class="variablelist"> <dt><span class="term">Habilita le segmentation a nivello de phrase</span></dt> <dd> <p>Le configurationes del segmentation adressa sol le maniera con le qual le Files fonte son tractate per <span class="application">OmegaT</span>. Le maniera prevalente del segmentation del fontes es le segmentation a nivello de phrase, ita iste quadrato de controlo deberea in caso normal restar marcate. </p> <p>In alicun rar casos le alternativa, id es le segmentation per paragraphos, pote esser preferite. Cambiar iste flag non modifica le segmentation del memorias de traduction jam existente. Si tu decide in medio al traduction de cambiar ab le segmentation per phrase al segmentation per paragrapho, le memoria de traduction interne del projecto non essera cambiate (OmegaT pote promover vetule memorias de traduction que non usa segmentation a phrase, ma non vice versa), sed OmegaT creara le concordantias partial de paragrapho, collante insimul traductiones de sententias existente. </p> <p>Cambiar le configurationes del segmentation pote producer alicun segmentos jam rendite ser fisse o mergite. Isto effectivemente los al stato "non rendite", pois que illos non concordara plus segmentos registrate in le memoria del projecto, etiam quanquam lor traduction original es adhuc eo. </p> </dd> <dt><span class="term"><span class="guibutton">Segmentation...</span> <a class="indexterm" name="d0e4722"></a></span></dt> <dd> <p>Le regulas del segmentation son generalmente valide trans tote le projectos. Le usator, tamen, pote necessitar de generar un serie de regulas, specific pro le projecto in question. Usa iste button pro aperir un fenestra de dialogo, activar le quadrato de controlo <span class="guimenuitem">Regulas de segmentation specific del projecto</span>, deinde proceder a prefixar le regulas de segmentation como desiderate. Le nove serie de regulas essera registrate conjunctemente con le projecto e non interferera con le serie general de regulas de segmentation. Pro deler le regulas de segmentation specific del projecto, leva le marca al quadrato de controlo. Vide le capitulo <a class="link" href="chapter.segmentation.html" title="Chapter&nbsp;14.&nbsp;Segmentation del texto fonte">Segmentation del Fonte</a> pro plus information sur le regulas del segmentation. </p> <p><span class="emphasis"><em>Aviso:</em></span> le serie de regulas de segmentation pro un projecto date es registrate como <code class="filename">project/omegat/segmentation.conf.</code></p> </dd> <dt><span class="term"><span class="guibutton">Filtros de File...</span><a class="indexterm" name="d0e4746"></a></span></dt> <dd> <p>In un faction similabile como precedentemente le usator pote crear Filtros de File projecto-specific, que essera immagazinate conjunctemente con le projecto e essera valide pro le the currente solmente. Pro crear un serie de filtros de file specific del projecto, clicca sur le button <span class="guibutton">Filtro de File... </span>, pois activa le quadrato de controlo <span class="guimenuitem">Habilita le filtros specific del projecto</span>, in le fenestra que se displica. Un copia del configuration del filtros cambiate essera immagazinate con le projecto. Pro deler le filtros de file specific del projecto, leva le marca al quadrato de controlo. Nota que in le menu <span class="guimenuitem">Optiones-&gt;Filtros de File</span>, son cambiate le filtros global del usator, non le filtros del projecto. Vide le capitulo<a class="link" href="chapter.file.filters.html" title="Chapter&nbsp;7.&nbsp;Filtros del file"> Filtros de File </a>pro plus de information re le subjecto.<span class="emphasis"><em></em></span></p> <p><span class="emphasis"><em>Aviso:</em></span> le serie de filtros de file pro un projecto date es registrate ut <code class="filename">project/omegat/filters.xml.</code></p> </dd> <dt><span class="term">Auto-propagation del traductiones</span></dt> <dd> <p>In caso il ha segmentos non unic in le documentos fonte, le quadrato de controlo del Auto-propagation offere al usator le duo possibilitates sequente respecto al traduction automatic: si marcate, le prime segmento rendite essera assumite como le traduction prefixate e su texto rendite essera usate automaticamente pro le occurrentias sequente durante le processo traduction. Le segmentos mal rendite pote esser naturalmente correcte plus tarde manualmente per le commando <span class="guimenuitem">Crea Traduction Alternative</span>. Si le quadrato de controlo Auto-propagation non es marcate, le segmentos con traductiones alternative son lassate non rendite dum le usator decide qual traduction ser usate. </p> </dd> <dt><span class="term">Remove le Tags</span></dt> <dd> <p>Quando habilitate, tote le tags de formato es removite del segmentos fonte. Isto es specialmente utile in le tractamento del textos ubi le formattation in linea non es vermente utile (per exemplo, PDF ex OCR, .odt o .docx mal convertite, etc.) In un caso normal il deberea semper esser possibile aperir le documentos de destination, pois que es removite sol le tags in linea. Le formattation non-visibile (id es, que non appare como tags in le editor de OmegaT) is retenite in le documentos final. </p> </dd> <dt><span class="term">Commando Externe Post-processo</span></dt> <dd> <p>Iste area permitte de scriber un commando externe post-processo (per exemplo, un script pro renominar le files) que essera applicate cata vice que es usate Crear le documentos rendite. Iste commandos externe non pote includer "pipes", et cetera, pro le qual es recommendate appellar un script. </p> </dd> </dl> </div> </div> <div class="section"> <div class="titlepage"> <div> <div> <h2 class="title" style="clear: both"><a name="d0e4794"></a>4.&nbsp;Locationes del files </h2> </div> </div> </div> <p>Ci tu pote seliger sub plicas varie, per exemplo le sub plica con le files fonte, sub plica pro le files final etc. Si tu inscribe nomines de plicas que non existe ancora, <span class="application">OmegaT</span> crea los pro te. In caso que tu decide te a modificar le plicas del projecto, mantene in mente que iste non movera le files existente ex le vetule plicas al nove ubication. </p> <p>Clicca sur <span class="guibutton">Exclusiones...</span> pro definir le files o plicas que essera ignorate per <span class="application">OmegaT</span>. Un file o un plica ignorate: </p> <div class="itemizedlist"> <ul class="itemizedlist" style="list-style-type: disc; "> <li class="listitem"> <p>non essera monstrate in le quadro Modification,</p> </li> <li class="listitem"> <p>non essera tenite in conto in le statistica,</p> </li> <li class="listitem"> <p>non essera copiate in le plica /target durante le processo de creation del files rendite.</p> </li> </ul> </div> <p>In le fenestra de dialogo de Exclusion modellos, il es possibile Adder o Remover un modello, o Modificar uno eligente un linea e pulsante F2. Il es possibile usar characteres generic, per le <a class="ulink" href="https://ant.apache.org/manual/dirtasks.html#patterns" target="_top">syntaxe ant</a>. </p> </div> </div> <div class="navfooter"> <hr> <table width="100%" summary="Navigation footer"> <tr> <td width="40%" align="left"><a accesskey="p" href="chapter.menu.html">Prev</a>&nbsp; </td> <td width="20%" align="center">&nbsp;</td> <td width="40%" align="right">&nbsp;<a accesskey="n" href="chapter.file.filters.html">Next</a></td> </tr> <tr> <td width="40%" align="left" valign="top">Chapter&nbsp;5.&nbsp;Menu e vias breve del claviero&nbsp;</td> <td width="20%" align="center"><a accesskey="h" href="index.html">Home</a></td> <td width="40%" align="right" valign="top">&nbsp;Chapter&nbsp;7.&nbsp;Filtros del file</td> </tr> </table> </div> </body> </html>
{ "pile_set_name": "Github" }
// (C) Copyright John Maddock 2007. // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // This file is machine generated, do not edit by hand // Unrolled polynomial evaluation using second order Horners rule #ifndef BOOST_MATH_TOOLS_POLY_EVAL_3_HPP #define BOOST_MATH_TOOLS_POLY_EVAL_3_HPP namespace boost{ namespace math{ namespace tools{ namespace detail{ template <class T, class V> inline V evaluate_polynomial_c_imp(const T* a, const V&, const mpl::int_<0>*) { return static_cast<V>(0); } template <class T, class V> inline V evaluate_polynomial_c_imp(const T* a, const V&, const mpl::int_<1>*) { return static_cast<V>(a[0]); } template <class T, class V> inline V evaluate_polynomial_c_imp(const T* a, const V& x, const mpl::int_<2>*) { return static_cast<V>(a[1] * x + a[0]); } template <class T, class V> inline V evaluate_polynomial_c_imp(const T* a, const V& x, const mpl::int_<3>*) { return static_cast<V>((a[2] * x + a[1]) * x + a[0]); } template <class T, class V> inline V evaluate_polynomial_c_imp(const T* a, const V& x, const mpl::int_<4>*) { return static_cast<V>(((a[3] * x + a[2]) * x + a[1]) * x + a[0]); } }}}} // namespaces #endif // include guard
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: fe8fdc0fe4319494ca810911d1e0450f MonoImporter: externalObjects: {} serializedVersion: 2 defaultReferences: [] executionOrder: 0 icon: {instanceID: 0} userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
import __config from '../etc/config' import WxResource from 'WxResource' class HttpResource { constructor(url, paramDefaults, actions, options) { Object.assign(this, { url, paramDefaults, actions, options, }) } /** * 返回实例对象 */ init() { const resource = new WxResource(this.setUrl(this.url), this.paramDefaults, this.actions, this.options) resource.setDefaults({ interceptors: this.setInterceptors() }) return resource } /** * 设置请求路径 */ setUrl(url) { return `${__config.basePath}${url}` } /** * 拦截器 */ setInterceptors() { return [{ request: function(request) { request.header = request.header || {} request.requestTimestamp = new Date().getTime() if (request.url.indexOf('/api') !== -1 && wx.getStorageSync('token')) { request.header.Authorization = 'Bearer ' + wx.getStorageSync('token') } wx.showToast({ title : '加载中', icon : 'loading', duration: 10000, mask : !0, }) return request }, requestError: function(requestError) { wx.hideToast() return requestError }, response: function(response) { response.responseTimestamp = new Date().getTime() if(response.statusCode === 401) { wx.removeStorageSync('token') wx.redirectTo({ url: '/pages/login/index' }) } wx.hideToast() return response }, responseError: function(responseError) { wx.hideToast() return responseError }, }] } } export default HttpResource
{ "pile_set_name": "Github" }
/* * Copyright 2018 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "fuzz/Fuzz.h" #include "fuzz/FuzzCommon.h" DEF_FUZZ(RegionOp, fuzz) { // `fuzz -t api -n RegionOp` SkRegion regionA, regionB, regionC; FuzzNiceRegion(fuzz, &regionA, 2000); FuzzNiceRegion(fuzz, &regionB, 2000); SkRegion::Op op; fuzz->nextRange(&op, 0, SkRegion::kLastOp); regionC.op(regionA, regionB, op); }
{ "pile_set_name": "Github" }
class Company < ActiveRecord::Base has_many :developers has_many :developer_notes, :through => :developers, :source => :notes has_many :slackers, :class_name => "Developer", :conditions => {:slacker => true} has_many :notes, :as => :notable has_many :data_types end
{ "pile_set_name": "Github" }
/* Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // +k8s:deepcopy-gen=package // +k8s:protobuf-gen=package // +k8s:openapi-gen=true package v1beta1 // import "k8s.io/api/apps/v1beta1"
{ "pile_set_name": "Github" }
// ---------------------------------------------------------------------------- // Copyright (C) 2002-2006 Marcin Kalicinski // Copyright (C) 2009 Sebastian Redl // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // For more information, see www.boost.org // ---------------------------------------------------------------------------- #ifndef BOOST_PROPERTY_TREE_INI_PARSER_HPP_INCLUDED #define BOOST_PROPERTY_TREE_INI_PARSER_HPP_INCLUDED #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/detail/ptree_utils.hpp> #include <boost/property_tree/detail/file_parser_error.hpp> #include <fstream> #include <string> #include <sstream> #include <stdexcept> #include <locale> namespace boost { namespace property_tree { namespace ini_parser { /** * Determines whether the @c flags are valid for use with the ini_parser. * @param flags value to check for validity as flags to ini_parser. * @return true if the flags are valid, false otherwise. */ inline bool validate_flags(int flags) { return flags == 0; } /** Indicates an error parsing INI formatted data. */ class ini_parser_error: public file_parser_error { public: /** * Construct an @c ini_parser_error * @param message Message describing the parser error. * @param filename The name of the file being parsed containing the * error. * @param line The line in the given file where an error was * encountered. */ ini_parser_error(const std::string &message, const std::string &filename, unsigned long line) : file_parser_error(message, filename, line) { } }; /** * Read INI from a the given stream and translate it to a property tree. * @note Clears existing contents of property tree. In case of error * the property tree is not modified. * @throw ini_parser_error If a format violation is found. * @param stream Stream from which to read in the property tree. * @param[out] pt The property tree to populate. */ template<class Ptree> void read_ini(std::basic_istream< typename Ptree::key_type::value_type> &stream, Ptree &pt) { typedef typename Ptree::key_type::value_type Ch; typedef std::basic_string<Ch> Str; const Ch semicolon = stream.widen(';'); const Ch hash = stream.widen('#'); const Ch lbracket = stream.widen('['); const Ch rbracket = stream.widen(']'); Ptree local; unsigned long line_no = 0; Ptree *section = 0; Str line; // For all lines while (stream.good()) { // Get line from stream ++line_no; std::getline(stream, line); if (!stream.good() && !stream.eof()) BOOST_PROPERTY_TREE_THROW(ini_parser_error( "read error", "", line_no)); // If line is non-empty line = property_tree::detail::trim(line, stream.getloc()); if (!line.empty()) { // Comment, section or key? if (line[0] == semicolon || line[0] == hash) { // Ignore comments } else if (line[0] == lbracket) { // If the previous section was empty, drop it again. if (section && section->empty()) local.pop_back(); typename Str::size_type end = line.find(rbracket); if (end == Str::npos) BOOST_PROPERTY_TREE_THROW(ini_parser_error( "unmatched '['", "", line_no)); Str key = property_tree::detail::trim( line.substr(1, end - 1), stream.getloc()); if (local.find(key) != local.not_found()) BOOST_PROPERTY_TREE_THROW(ini_parser_error( "duplicate section name", "", line_no)); section = &local.push_back( std::make_pair(key, Ptree()))->second; } else { Ptree &container = section ? *section : local; typename Str::size_type eqpos = line.find(Ch('=')); if (eqpos == Str::npos) BOOST_PROPERTY_TREE_THROW(ini_parser_error( "'=' character not found in line", "", line_no)); if (eqpos == 0) BOOST_PROPERTY_TREE_THROW(ini_parser_error( "key expected", "", line_no)); Str key = property_tree::detail::trim( line.substr(0, eqpos), stream.getloc()); Str data = property_tree::detail::trim( line.substr(eqpos + 1, Str::npos), stream.getloc()); if (container.find(key) != container.not_found()) BOOST_PROPERTY_TREE_THROW(ini_parser_error( "duplicate key name", "", line_no)); container.push_back(std::make_pair(key, Ptree(data))); } } } // If the last section was empty, drop it again. if (section && section->empty()) local.pop_back(); // Swap local ptree with result ptree pt.swap(local); } /** * Read INI from a the given file and translate it to a property tree. * @note Clears existing contents of property tree. In case of error the * property tree unmodified. * @throw ini_parser_error In case of error deserializing the property tree. * @param filename Name of file from which to read in the property tree. * @param[out] pt The property tree to populate. * @param loc The locale to use when reading in the file contents. */ template<class Ptree> void read_ini(const std::string &filename, Ptree &pt, const std::locale &loc = std::locale()) { std::basic_ifstream<typename Ptree::key_type::value_type> stream(filename.c_str()); if (!stream) BOOST_PROPERTY_TREE_THROW(ini_parser_error( "cannot open file", filename, 0)); stream.imbue(loc); try { read_ini(stream, pt); } catch (ini_parser_error &e) { BOOST_PROPERTY_TREE_THROW(ini_parser_error( e.message(), filename, e.line())); } } namespace detail { template<class Ptree> void check_dupes(const Ptree &pt) { if(pt.size() <= 1) return; const typename Ptree::key_type *lastkey = 0; typename Ptree::const_assoc_iterator it = pt.ordered_begin(), end = pt.not_found(); lastkey = &it->first; for(++it; it != end; ++it) { if(*lastkey == it->first) BOOST_PROPERTY_TREE_THROW(ini_parser_error( "duplicate key", "", 0)); lastkey = &it->first; } } template <typename Ptree> void write_keys(std::basic_ostream< typename Ptree::key_type::value_type > &stream, const Ptree& pt, bool throw_on_children) { typedef typename Ptree::key_type::value_type Ch; for (typename Ptree::const_iterator it = pt.begin(), end = pt.end(); it != end; ++it) { if (!it->second.empty()) { if (throw_on_children) { BOOST_PROPERTY_TREE_THROW(ini_parser_error( "ptree is too deep", "", 0)); } continue; } stream << it->first << Ch('=') << it->second.template get_value< std::basic_string<Ch> >() << Ch('\n'); } } template <typename Ptree> void write_top_level_keys(std::basic_ostream< typename Ptree::key_type::value_type > &stream, const Ptree& pt) { write_keys(stream, pt, false); } template <typename Ptree> void write_sections(std::basic_ostream< typename Ptree::key_type::value_type > &stream, const Ptree& pt) { typedef typename Ptree::key_type::value_type Ch; for (typename Ptree::const_iterator it = pt.begin(), end = pt.end(); it != end; ++it) { if (!it->second.empty()) { check_dupes(it->second); if (!it->second.data().empty()) BOOST_PROPERTY_TREE_THROW(ini_parser_error( "mixed data and children", "", 0)); stream << Ch('[') << it->first << Ch(']') << Ch('\n'); write_keys(stream, it->second, true); } } } } /** * Translates the property tree to INI and writes it the given output * stream. * @pre @e pt cannot have data in its root. * @pre @e pt cannot have keys both data and children. * @pre @e pt cannot be deeper than two levels. * @pre There cannot be duplicate keys on any given level of @e pt. * @throw ini_parser_error In case of error translating the property tree to * INI or writing to the output stream. * @param stream The stream to which to write the INI representation of the * property tree. * @param pt The property tree to tranlsate to INI and output. * @param flags The flags to use when writing the INI file. * No flags are currently supported. */ template<class Ptree> void write_ini(std::basic_ostream< typename Ptree::key_type::value_type > &stream, const Ptree &pt, int flags = 0) { BOOST_ASSERT(validate_flags(flags)); (void)flags; if (!pt.data().empty()) BOOST_PROPERTY_TREE_THROW(ini_parser_error( "ptree has data on root", "", 0)); detail::check_dupes(pt); detail::write_top_level_keys(stream, pt); detail::write_sections(stream, pt); } /** * Translates the property tree to INI and writes it the given file. * @pre @e pt cannot have data in its root. * @pre @e pt cannot have keys both data and children. * @pre @e pt cannot be deeper than two levels. * @pre There cannot be duplicate keys on any given level of @e pt. * @throw info_parser_error In case of error translating the property tree * to INI or writing to the file. * @param filename The name of the file to which to write the INI * representation of the property tree. * @param pt The property tree to tranlsate to INI and output. * @param flags The flags to use when writing the INI file. * The following flags are supported: * @li @c skip_ini_validity_check -- Skip check if ptree is a valid ini. The * validity check covers the preconditions but takes <tt>O(n log n)</tt> * time. * @param loc The locale to use when writing the file. */ template<class Ptree> void write_ini(const std::string &filename, const Ptree &pt, int flags = 0, const std::locale &loc = std::locale()) { std::basic_ofstream<typename Ptree::key_type::value_type> stream(filename.c_str()); if (!stream) BOOST_PROPERTY_TREE_THROW(ini_parser_error( "cannot open file", filename, 0)); stream.imbue(loc); try { write_ini(stream, pt, flags); } catch (ini_parser_error &e) { BOOST_PROPERTY_TREE_THROW(ini_parser_error( e.message(), filename, e.line())); } } } } } namespace boost { namespace property_tree { using ini_parser::ini_parser_error; using ini_parser::read_ini; using ini_parser::write_ini; } } #endif
{ "pile_set_name": "Github" }
./cache/g-raphael/0.4.1/javascripts/g-raphael.js ./cache/g-raphael/0.4.1/javascripts/g-raphael-min.js ./cache/highcharts/2.0.1/javascripts/highcharts.js ./cache/highcharts/2.0.1/javascripts/highcharts-min.js ./cache/jqplot/0.9.7/javascripts/jqplot.js ./cache/jqplot/0.9.7/javascripts/jqplot-min.js ./cache/jquery-gcharts/0.0.0/javascripts/jquery-gcharts.js ./cache/jquery-gcharts/0.0.0/javascripts/jquery-gcharts-min.js ./cache/protovis/3.2.0/javascripts/protovis.js ./cache/protovis/3.2.0/javascripts/protovis-min.js ./cache/raphael/1.4.7/javascripts/raphael.js ./cache/raphael/1.4.7/javascripts/raphael-min.js ./cache/960/0.0.0/stylesheets/960.css ./cache/960/0.0.0/stylesheets/960.css ./cache/blueprint/0.9.1/stylesheets/screen.css ./cache/blueprint/0.9.1/stylesheets/screen.css ./cache/dojo/1.5.0/javascripts/dojo.js ./cache/dojo/1.5.0/javascripts/dojo-min.js ./cache/ext-core/3.0.0/javascripts/ext-core.js ./cache/ext-core/3.0.0/javascripts/ext-core-min.js ./cache/html5-enabled/1.0.0/javascripts/html5-enabled.js ./cache/html5-enabled/1.0.0/javascripts/html5-enabled-min.js ./cache/modernizr/1.5.0/javascripts/modernizr.js ./cache/modernizr/1.5.0/javascripts/modernizr-min.js ./cache/dd-belated-png/0.0.8/javascripts/dd-belated-png.js ./cache/dd-belated-png/0.0.8/javascripts/dd-belated-png-min.js ./cache/explorercanvas/0.0.0/javascripts/explorercanvas.js ./cache/explorercanvas/0.0.0/javascripts/explorercanvas-min.js ./cache/jqtouch/1.0.0/javascripts/jqtouch.js ./cache/jqtouch/1.0.0/javascripts/jqtouch-min.js ./cache/jquery-anytime/4.1.1/javascripts/jquery-anytime.js ./cache/jquery-anytime/4.1.1/javascripts/jquery-anytime-min.js ./cache/jquery-approach/1.0.1/javascripts/jquery-approach.js ./cache/jquery-approach/1.0.1/javascripts/jquery-approach-min.js ./cache/jquery-autocomplete/1.1.0/javascripts/jquery-autocomplete.js ./cache/jquery-autocomplete/1.1.0/javascripts/jquery-autocomplete-min.js ./cache/jquery-autoscroll/0.0.1/javascripts/jquery-autoscroll.js ./cache/jquery-autoscroll/0.0.1/javascripts/jquery-autoscroll-min.js ./cache/jquery-autosuggest/1.4.0/javascripts/jquery-autosuggest.js ./cache/jquery-autosuggest/1.4.0/javascripts/jquery-autosuggest-min.js ./cache/jquery-bbq/1.2.1/javascripts/jquery-bbq.js ./cache/jquery-bbq/1.2.1/javascripts/jquery-bbq-min.js ./cache/jquery-blockui/2.3.3/javascripts/jquery-blockui.js ./cache/jquery-blockui/2.3.3/javascripts/jquery-blockui-min.js ./cache/jquery-class/0.0.0/javascripts/jquery-class.js ./cache/jquery-class/0.0.0/javascripts/jquery-class-min.js ./cache/jquery-classy/0.0.0/javascripts/jquery-classy.js ./cache/jquery-classy/0.0.0/javascripts/jquery-classy-min.js ./cache/jquery-color/0.0.0/javascripts/jquery-color.js ./cache/jquery-color/0.0.0/javascripts/jquery-color-min.js ./cache/jquery-colorbox/1.3.9/javascripts/jquery-colorbox.js ./cache/jquery-colorbox/1.3.9/javascripts/jquery-colorbox-min.js ./cache/jquery-cookie/0.0.0/javascripts/jquery-cookie.js ./cache/jquery-cookie/0.0.0/javascripts/jquery-cookie-min.js ./cache/jquery-corner/2.0.9/javascripts/jquery-corner.js ./cache/jquery-corner/2.0.9/javascripts/jquery-corner-min.js ./cache/jquery-cycle/2.8.6/javascripts/jquery-cycle.js ./cache/jquery-cycle/2.8.6/javascripts/jquery-cycle-min.js ./cache/jquery-disqus/1.0.0/javascripts/jquery-disqus.js ./cache/jquery-disqus/1.0.0/javascripts/jquery-disqus-min.js ./cache/jquery-dropdown-replacement/0.5.0/javascripts/jquery-dropdown-replacement.js ./cache/jquery-dropdown-replacement/0.5.0/javascripts/jquery-dropdown-replacement-min.js ./cache/jquery-dropshadow/1.2.6/javascripts/jquery-dropshadow.js ./cache/jquery-dropshadow/1.2.6/javascripts/jquery-dropshadow-min.js ./cache/jquery-easing/1.3.0/javascripts/jquery-easing.js ./cache/jquery-easing/1.3.0/javascripts/jquery-easing-min.js ./cache/jquery-easytooltip/1.0.0/javascripts/jquery-easytooltip.js ./cache/jquery-easytooltip/1.0.0/javascripts/jquery-easytooltip-min.js ./cache/jquery-elastic-textarea/1.6.4/javascripts/jquery-elastic-textarea.js ./cache/jquery-elastic-textarea/1.6.4/javascripts/jquery-elastic-textarea-min.js ./cache/jquery-facebox/1.2.0/javascripts/jquery-facebox.js ./cache/jquery-facebox/1.2.0/javascripts/jquery-facebox-min.js ./cache/jquery-fieldtag/1.1.0/javascripts/jquery-fieldtag.js ./cache/jquery-fieldtag/1.1.0/javascripts/jquery-fieldtag-min.js ./cache/jquery-filetree/1.0.1/javascripts/jquery-filetree.js ./cache/jquery-filetree/1.0.1/javascripts/jquery-filetree-min.js ./cache/jquery-form/2.4.3/javascripts/jquery-form.js ./cache/jquery-form/2.4.3/javascripts/jquery-form-min.js ./cache/jquery-fullscreenr/1.0.0/javascripts/jquery-fullscreenr.js ./cache/jquery-fullscreenr/1.0.0/javascripts/jquery-fullscreenr-min.js ./cache/jquery-glow/1.0.0/javascripts/jquery-glow.js ./cache/jquery-glow/1.0.0/javascripts/jquery-glow-min.js ./cache/jquery-google-analytics/1.1.3/javascripts/jquery-google-analytics.js ./cache/jquery-google-analytics/1.1.3/javascripts/jquery-google-analytics-min.js ./cache/jquery-google-feed-api/1.0.0/javascripts/jquery-google-feed-api.js ./cache/jquery-google-feed-api/1.0.0/javascripts/jquery-google-feed-api-min.js ./cache/jquery-highlightregex/3.0.0/javascripts/jquery-highlightregex.js ./cache/jquery-highlightregex/3.0.0/javascripts/jquery-highlightregex-min.js ./cache/jquery-hotkeys/0.0.0/javascripts/jquery-hotkeys.js ./cache/jquery-hotkeys/0.0.0/javascripts/jquery-hotkeys-min.js ./cache/jquery-hoverintent/0.0.0/javascripts/jquery-hoverintent.js ./cache/jquery-hoverintent/0.0.0/javascripts/jquery-hoverintent-min.js ./cache/jquery-html5-dataset/0.1.0/javascripts/jquery-html5-dataset.js ./cache/jquery-html5-dataset/0.1.0/javascripts/jquery-html5-dataset-min.js ./cache/jquery-in-field-label/0.1.2/javascripts/jquery-in-field-label.js ./cache/jquery-in-field-label/0.1.2/javascripts/jquery-in-field-label-min.js ./cache/jquery-jcarousel/0.2.5/javascripts/jquery-jcarousel.js ./cache/jquery-jcarousel/0.2.5/javascripts/jquery-jcarousel-min.js ./cache/jquery-jcrop/0.9.8/javascripts/jquery-jcrop.js ./cache/jquery-jcrop/0.9.8/javascripts/jquery-jcrop-min.js ./cache/jquery-jeditable/1.4.2/javascripts/jquery-jeditable.js ./cache/jquery-jeditable/1.4.2/javascripts/jquery-jeditable-min.js ./cache/jquery-jlabel/1.1.0/javascripts/jquery-jlabel.js ./cache/jquery-jlabel/1.1.0/javascripts/jquery-jlabel-min.js ./cache/jquery-jparallax/0.9.9/javascripts/jquery-jparallax.js ./cache/jquery-jparallax/0.9.9/javascripts/jquery-jparallax-min.js ./cache/jquery-jstree/1.0.0/javascripts/jquery-jstree.js ./cache/jquery-jstree/1.0.0/javascripts/jquery-jstree-min.js ./cache/jquery-jtweets-anywhere/1.1.0/javascripts/jquery-jtweets-anywhere.js ./cache/jquery-jtweets-anywhere/1.1.0/javascripts/jquery-jtweets-anywhere-min.js ./cache/jquery-labelify/1.3.0/javascripts/jquery-labelify.js ./cache/jquery-labelify/1.3.0/javascripts/jquery-labelify-min.js ./cache/jquery-lavalamp/1.3.4/javascripts/jquery-lavalamp.js ./cache/jquery-lavalamp/1.3.4/javascripts/jquery-lavalamp-min.js ./cache/jquery-lazyload/1.5.0/javascripts/jquery-lazyload.js ./cache/jquery-lazyload/1.5.0/javascripts/jquery-lazyload-min.js ./cache/jquery-livefilter/1.2.0/javascripts/jquery-livefilter.js ./cache/jquery-livefilter/1.2.0/javascripts/jquery-livefilter-min.js ./cache/jquery-liveupdate/0.0.0/javascripts/jquery-liveupdate.js ./cache/jquery-liveupdate/0.0.0/javascripts/jquery-liveupdate-min.js ./cache/jquery-localscroll/1.2.7/javascripts/jquery-localscroll.js ./cache/jquery-localscroll/1.2.7/javascripts/jquery-localscroll-min.js ./cache/jquery-magic-labels/0.6.2/javascripts/jquery-magic-labels.js ./cache/jquery-magic-labels/0.6.2/javascripts/jquery-magic-labels-min.js ./cache/jquery-metadata/0.0.0/javascripts/jquery-metadata.js ./cache/jquery-metadata/0.0.0/javascripts/jquery-metadata-min.js ./cache/jquery-mousewheel/3.0.3/javascripts/jquery-mousewheel.js ./cache/jquery-mousewheel/3.0.3/javascripts/jquery-mousewheel-min.js ./cache/jquery-nivo-slider/2.0.0/javascripts/jquery-nivo-slider.js ./cache/jquery-nivo-slider/2.0.0/javascripts/jquery-nivo-slider-min.js ./cache/jquery-overscroll/1.3.0/javascripts/jquery-overscroll.js ./cache/jquery-overscroll/1.3.0/javascripts/jquery-overscroll-min.js ./cache/jquery-page-slide/0.0.0/javascripts/jquery-page-slide.js ./cache/jquery-page-slide/0.0.0/javascripts/jquery-page-slide-min.js ./cache/jquery-path/0.0.1/javascripts/jquery-path.js ./cache/jquery-path/0.0.1/javascripts/jquery-path-min.js ./cache/jquery-picasa/1.0.0/javascripts/jquery-picasa.js ./cache/jquery-picasa/1.0.0/javascripts/jquery-picasa-min.js ./cache/jquery-postmessage/0.5.0/javascripts/jquery-postmessage.js ./cache/jquery-postmessage/0.5.0/javascripts/jquery-postmessage-min.js ./cache/jquery-pretty-checkboxes/1.1.0/javascripts/jquery-pretty-checkboxes.js ./cache/jquery-pretty-checkboxes/1.1.0/javascripts/jquery-pretty-checkboxes-min.js ./cache/jquery-pretty-photo/3.0.0/javascripts/jquery-pretty-photo.js ./cache/jquery-pretty-photo/3.0.0/javascripts/jquery-pretty-photo-min.js ./cache/jquery-quicksand/1.2.1/javascripts/jquery-quicksand.js ./cache/jquery-quicksand/1.2.1/javascripts/jquery-quicksand-min.js ./cache/jquery-rightclick/1.0.1/javascripts/jquery-rightclick.js ./cache/jquery-rightclick/1.0.1/javascripts/jquery-rightclick-min.js ./cache/jquery-scale-9-grid/0.9.3/javascripts/jquery-scale-9-grid.js ./cache/jquery-scale-9-grid/0.9.3/javascripts/jquery-scale-9-grid-min.js ./cache/jquery-scrolling-parallax/0.1.0/javascripts/jquery-scrolling-parallax.js ./cache/jquery-scrolling-parallax/0.1.0/javascripts/jquery-scrolling-parallax-min.js ./cache/jquery-scrollto/1.4.2/javascripts/jquery-scrollto.js ./cache/jquery-scrollto/1.4.2/javascripts/jquery-scrollto-min.js ./cache/jquery-sexy/0.8.0/javascripts/jquery-sexy.js ./cache/jquery-sexy/0.8.0/javascripts/jquery-sexy-min.js ./cache/jquery-simpletooltip/1.0/javascripts/jquery-simpletooltip.js ./cache/jquery-simpletooltip/1.0/javascripts/jquery-simpletooltip-min.js ./cache/jquery-simply-countable/0.4.0/javascripts/jquery-simply-countable.js ./cache/jquery-simply-countable/0.4.0/javascripts/jquery-simply-countable-min.js ./cache/jquery-string/1.0.0/javascripts/jquery-string.js ./cache/jquery-string/1.0.0/javascripts/jquery-string-min.js ./cache/jquery-superfish/1.4.8/javascripts/jquery-superfish.js ./cache/jquery-superfish/1.4.8/javascripts/jquery-superfish-min.js ./cache/jquery-supersized/2.0.0/javascripts/jquery-supersized.js ./cache/jquery-supersized/2.0.0/javascripts/jquery-supersized-min.js ./cache/jquery-swfupload/1.0.0/javascripts/jquery-swfupload.js ./cache/jquery-swfupload/1.0.0/javascripts/jquery-swfupload-min.js ./cache/jquery-table-sorter/2.0.3/javascripts/jquery-table-sorter.js ./cache/jquery-table-sorter/2.0.3/javascripts/jquery-table-sorter-min.js ./cache/jquery-timeago/0.9.0/javascripts/jquery-timeago.js ./cache/jquery-timeago/0.9.0/javascripts/jquery-timeago-min.js ./cache/jquery-tinytips/1.1.0/javascripts/jquery-tinytips.js ./cache/jquery-tinytips/1.1.0/javascripts/jquery-tinytips-min.js ./cache/jquery-transform/0.0.0/javascripts/jquery-transform.js ./cache/jquery-transform/0.0.0/javascripts/jquery-transform-min.js ./cache/jquery-ui/1.8.4/javascripts/jquery-ui.js ./cache/jquery-ui/1.8.4/javascripts/jquery-ui-min.js ./cache/jquery-uniform/1.7.3/javascripts/jquery-uniform.js ./cache/jquery-uniform/1.7.3/javascripts/jquery-uniform-min.js ./cache/jquery-upload-progress/0.0.0/javascripts/jquery-upload-progress.js ./cache/jquery-upload-progress/0.0.0/javascripts/jquery-upload-progress-min.js ./cache/jquery-url-internal/1.0.0/javascripts/jquery-url-internal.js ./cache/jquery-url-internal/1.0.0/javascripts/jquery-url-internal-min.js ./cache/jquery-validate/1.7.0/javascripts/jquery-validate.js ./cache/jquery-validate/1.7.0/javascripts/jquery-validate-min.js ./cache/jquery/1.4.2/javascripts/jquery.js ./cache/jquery/1.4.2/javascripts/jquery-min.js ./cache/mootools/1.2.4/javascripts/mootools.js ./cache/mootools/1.2.4/javascripts/mootools-min.js ./cache/box2d/1.0.0/javascripts/box2d.js ./cache/box2d/1.0.0/javascripts/box2d-min.js ./cache/processing/0.8.0/javascripts/processing.js ./cache/processing/0.8.0/javascripts/processing-min.js ./cache/three/0.0.0/javascripts/three.js ./cache/three/0.0.0/javascripts/three-min.js ./cache/activejs/0.0.0/javascripts/active.js ./cache/activejs/0.0.0/javascripts/active-min.js ./cache/jazz-record/0.7.0/javascripts/jazz-record.js ./cache/jazz-record/0.7.0/javascripts/jazz-record-min.js ./cache/js-model/0.8.4/javascripts/js-model.js ./cache/js-model/0.8.4/javascripts/js-model-min.js ./cache/sammy/0.5.4/javascripts/sammy.js ./cache/sammy/0.5.4/javascripts/sammy-min.js ./cache/prototype/1.6.1/javascripts/prototype.js ./cache/prototype/1.6.1/javascripts/prototype-min.js ./cache/scriptaculous/1.8.3/javascripts/scriptaculous.js ./cache/scriptaculous/1.8.3/javascripts/scriptaculous-min.js ./cache/sound-manager-2/2.0.0/javascripts/sound-manager-2.js ./cache/sound-manager-2/2.0.0/javascripts/sound-manager-2-min.js ./cache/flash-player/10.0.0/swfs/playerProductInstall.swf ./cache/flash-player/10.0.0/swfs/playerProductInstall.swf ./cache/swfaddress-optimizer/2.4.0/javascripts/swfaddress-optimizer.js ./cache/swfaddress-optimizer/2.4.0/javascripts/swfaddress-optimizer-min.js ./cache/swfaddress/2.4.0/javascripts/swfaddress.js ./cache/swfaddress/2.4.0/javascripts/swfaddress-min.js ./cache/swfobject/2.2.0/javascripts/swfobject.js ./cache/swfobject/2.2.0/javascripts/swfobject-min.js ./cache/swfupload/2.0.2/javascripts/swfupload.js ./cache/swfupload/2.0.2/javascripts/swfupload-min.js ./cache/mustache/0.3.0/javascripts/mustache.js ./cache/mustache/0.3.0/javascripts/mustache-min.js ./cache/jslitmus/0.0.0/javascripts/jslitmus.js ./cache/jslitmus/0.0.0/javascripts/jslitmus-min.js ./cache/qunit/1.0.0/javascripts/qunit.js ./cache/qunit/1.0.0/javascripts/qunit-min.js ./cache/cufon/1.0.9/javascripts/cufon.js ./cache/cufon/1.0.9/javascripts/cufon-min.js ./cache/markitup/1.1.8/javascripts/markitup.js ./cache/markitup/1.1.8/javascripts/markitup-min.js ./cache/prettify/1.0.0/javascripts/prettify.js ./cache/prettify/1.0.0/javascripts/prettify-min.js ./cache/showdown/1.0.0/javascripts/showdown.js ./cache/showdown/1.0.0/javascripts/showdown-min.js ./cache/syntax-highlighter/3.0.8/javascripts/syntax-highlighter.js ./cache/syntax-highlighter/3.0.8/javascripts/syntax-highlighter-min.js ./cache/webfont/1.0.6/javascripts/webfont.js ./cache/webfont/1.0.6/javascripts/webfont-min.js ./cache/wmd-editor/0.0.0/javascripts/wmd-editor.js ./cache/wmd-editor/0.0.0/javascripts/wmd-editor-min.js ./cache/datejs/1.0.0/javascripts/date.js ./cache/datejs/1.0.0/javascripts/date-min.js ./cache/json2/0.0.0/javascripts/json2.js ./cache/json2/0.0.0/javascripts/json2-min.js ./cache/sexy-js/0.8.0/javascripts/sexy.js ./cache/sexy-js/0.8.0/javascripts/sexy-min.js ./cache/underscore/1.1.0/javascripts/underscore.js ./cache/underscore/1.1.0/javascripts/underscore-min.js ./cache/zero-clipboard/1.0.7/javascripts/zero-clipboard.js ./cache/zero-clipboard/1.0.7/javascripts/zero-clipboard-min.js ./cache/yui/3.1.2/javascripts/yui.js ./cache/yui/3.1.2/javascripts/yui-min.js
{ "pile_set_name": "Github" }
/* * * Copyright 2015-present Facebook. All Rights Reserved. * * This file contains code to support IPMI2.0 Specification available @ * http://www.intel.com/content/www/us/en/servers/ipmi/ipmi-specifications.html * * 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <stdio.h> #include <stdint.h> #include <stdbool.h> #include <fcntl.h> #include <errno.h> #include <syslog.h> #include <sys/mman.h> #include <string.h> #include <pthread.h> #include <unistd.h> #include <openbmc/kv.h> #include "pal.h" #include "pal_sensors.h" #define BIT(value, index) ((value >> index) & 1) #define YOSEMITE_PLATFORM_NAME "Yosemite" #define LAST_KEY "last_key" #define YOSEMITE_MAX_NUM_SLOTS 4 #define GPIO_VAL "/sys/class/gpio/gpio%d/value" #define GPIO_DIR "/sys/class/gpio/gpio%d/direction" #define GPIO_HAND_SW_ID1 138 #define GPIO_HAND_SW_ID2 139 #define GPIO_HAND_SW_ID4 140 #define GPIO_HAND_SW_ID8 141 #define GPIO_RST_BTN 144 #define GPIO_PWR_BTN 24 #define GPIO_HB_LED 135 #define GPIO_USB_SW0 36 #define GPIO_USB_SW1 37 #define GPIO_USB_MUX_EN_N 147 #define GPIO_UART_SEL0 32 #define GPIO_UART_SEL1 33 #define GPIO_UART_SEL2 34 #define GPIO_UART_RX 35 #define GPIO_POSTCODE_0 48 #define GPIO_POSTCODE_1 49 #define GPIO_POSTCODE_2 50 #define GPIO_POSTCODE_3 51 #define GPIO_POSTCODE_4 124 #define GPIO_POSTCODE_5 125 #define GPIO_POSTCODE_6 126 #define GPIO_POSTCODE_7 127 #define GPIO_DBG_CARD_PRSNT 137 #define GPIO_BMC_READY_N 28 #define PAGE_SIZE 0x1000 #define AST_SCU_BASE 0x1e6e2000 #define PIN_CTRL1_OFFSET 0x80 #define PIN_CTRL2_OFFSET 0x84 #define WDT_OFFSET 0x3C #define UART1_TXD (1 << 22) #define UART2_TXD (1 << 30) #define UART3_TXD (1 << 22) #define UART4_TXD (1 << 30) #define DELAY_GRACEFUL_SHUTDOWN 1 #define DELAY_POWER_OFF 6 #define DELAY_POWER_CYCLE 10 #define DELAY_12V_CYCLE 5 #define CRASHDUMP_BIN "/usr/local/bin/dump.sh" #define CRASHDUMP_FILE "/mnt/data/crashdump_" #define LARGEST_DEVICE_NAME 120 #define PWM_DIR "/sys/devices/platform/ast_pwm_tacho.0" #define PWM_UNIT_MAX 96 #define MAX_READ_RETRY 10 #define MAX_CHECK_RETRY 2 #define CRASHDUMP_KEY "slot%d_crashdump" const static uint8_t gpio_rst_btn[] = { 0, 57, 56, 59, 58 }; const static uint8_t gpio_led[] = { 0, 97, 96, 99, 98 }; const static uint8_t gpio_id_led[] = { 0, 41, 40, 43, 42 }; const static uint8_t gpio_prsnt[] = { 0, 61, 60, 63, 62 }; const static uint8_t gpio_bic_ready[] = { 0, 107, 106, 109, 108 }; const static uint8_t gpio_power[] = { 0, 27, 25, 31, 29 }; const static uint8_t gpio_12v[] = { 0, 117, 116, 119, 118 }; const char pal_fru_list[] = "all, slot1, slot2, slot3, slot4, spb, nic"; const char pal_server_list[] = "slot1, slot2, slot3, slot4"; size_t pal_pwm_cnt = 2; size_t pal_tach_cnt = 2; const char pal_pwm_list[] = "0, 1"; const char pal_tach_list[] = "0, 1"; typedef struct { uint16_t flag; float ucr; float unc; float unr; float lcr; float lnc; float lnr; } _sensor_thresh_t; typedef struct { uint16_t flag; float ucr; float lcr; uint8_t retry_cnt; uint8_t val_valid; float last_val; } sensor_check_t; static sensor_check_t m_snr_chk[MAX_NUM_FRUS][MAX_SENSOR_NUM] = {0}; char * key_list[] = { "pwr_server1_last_state", "pwr_server2_last_state", "pwr_server3_last_state", "pwr_server4_last_state", "sysfw_ver_slot1", "sysfw_ver_slot2", "sysfw_ver_slot3", "sysfw_ver_slot4", "identify_sled", "identify_slot1", "identify_slot2", "identify_slot3", "identify_slot4", "timestamp_sled", "slot1_por_cfg", "slot2_por_cfg", "slot3_por_cfg", "slot4_por_cfg", "slot1_sensor_health", "slot2_sensor_health", "slot3_sensor_health", "slot4_sensor_health", "spb_sensor_health", "nic_sensor_health", "slot1_sel_error", "slot2_sel_error", "slot3_sel_error", "slot4_sel_error", "slot1_boot_order", "slot2_boot_order", "slot3_boot_order", "slot4_boot_order", /* Add more Keys here */ LAST_KEY /* This is the last key of the list */ }; char * def_val_list[] = { "on", /* pwr_server1_last_state */ "on", /* pwr_server2_last_state */ "on", /* pwr_server3_last_state */ "on", /* pwr_server4_last_state */ "0", /* sysfw_ver_slot1 */ "0", /* sysfw_ver_slot2 */ "0", /* sysfw_ver_slot3 */ "0", /* sysfw_ver_slot4 */ "off", /* identify_sled */ "off", /* identify_slot1 */ "off", /* identify_slot2 */ "off", /* identify_slot3 */ "off", /* identify_slot4 */ "0", /* timestamp_sled */ "lps", /* slot1_por_cfg */ "lps", /* slot2_por_cfg */ "lps", /* slot3_por_cfg */ "lps", /* slot4_por_cfg */ "1", /* slot1_sensor_health */ "1", /* slot2_sensor_health */ "1", /* slot3_sensor_health */ "1", /* slot4_sensor_health */ "1", /* spb_sensor_health */ "1", /* nic_sensor_health */ "1", /* slot1_sel_error */ "1", /* slot2_sel_error */ "1", /* slot3_sel_error */ "1", /* slot4_sel_error */ "000000000000", /* slot1_boot_order */ "000000000000", /* slot2_boot_order */ "000000000000", /* slot3_boot_order */ "000000000000", /* slot4_boot_order */ /* Add more def values for the correspoding keys*/ LAST_KEY /* Same as last entry of the key_list */ }; struct power_coeff { float ein; float coeff; }; /* Quanta BMC correction table */ struct power_coeff power_table[] = { {51.0, 0.98}, {115.0, 0.9775}, {178.0, 0.9755}, {228.0, 0.979}, {290.0, 0.98}, {353.0, 0.977}, {427.0, 0.977}, {476.0, 0.9765}, {526.0, 0.9745}, {598.0, 0.9745}, {0.0, 0.0} }; /* Adjust power value */ static void power_value_adjust(float *value) { float x0, x1, y0, y1, x; int i; x = *value; x0 = power_table[0].ein; y0 = power_table[0].coeff; if (x0 > *value) { *value = x * y0; return; } for (i = 0; power_table[i].ein > 0.0; i++) { if (*value < power_table[i].ein) break; x0 = power_table[i].ein; y0 = power_table[i].coeff; } if (power_table[i].ein <= 0.0) { *value = x * y0; return; } //if value is bwtween x0 and x1, use linear interpolation method. x1 = power_table[i].ein; y1 = power_table[i].coeff; *value = (y0 + (((y1 - y0)/(x1 - x0)) * (x - x0))) * x; return; } typedef struct _inlet_corr_t { uint8_t duty; float delta_t; } inlet_corr_t; static inlet_corr_t g_ict[] = { // Inlet Sensor: // duty cycle vs delta_t { 10, 2.0 }, { 16, 1.5 }, { 22, 1.0 }, { 26, 0 }, }; static uint8_t g_ict_count = sizeof(g_ict)/sizeof(inlet_corr_t); static void apply_inlet_correction(float *value) { static float dt = 0; int i; uint8_t pwm[2] = {0}; // Get PWM value if (pal_get_pwm_value(0, &pwm[0]) || pal_get_pwm_value(1, &pwm[1])) { // If error reading PWM value, use the previous deltaT *value -= dt; return; } pwm[0] = (pwm[0] + pwm[1])/2; // Scan through the correction table to get correction value for given PWM dt = g_ict[0].delta_t; for (i = 1; i < g_ict_count; i++) { if (pwm[0] >= g_ict[i].duty) dt = g_ict[i].delta_t; else break; } // Apply correction for the sensor *(float*)value -= dt; } // Helper Functions static int read_device(const char *device, int *value) { FILE *fp; int rc; fp = fopen(device, "r"); if (!fp) { int err = errno; #ifdef DEBUG syslog(LOG_INFO, "failed to open device %s", device); #endif return err; } rc = fscanf(fp, "%d", value); fclose(fp); if (rc != 1) { #ifdef DEBUG syslog(LOG_INFO, "failed to read device %s", device); #endif return ENOENT; } else { return 0; } } static int write_device(const char *device, const char *value) { FILE *fp; int rc; fp = fopen(device, "w"); if (!fp) { int err = errno; #ifdef DEBUG syslog(LOG_INFO, "failed to open device for write %s", device); #endif return err; } rc = fputs(value, fp); fclose(fp); if (rc < 0) { #ifdef DEBUG syslog(LOG_INFO, "failed to write device %s", device); #endif return ENOENT; } else { return 0; } } static int pal_key_check(char *key) { int i; i = 0; while(strcmp(key_list[i], LAST_KEY)) { // If Key is valid, return success if (!strcmp(key, key_list[i])) return 0; i++; } #ifdef DEBUG syslog(LOG_WARNING, "pal_key_check: invalid key - %s", key); #endif return -1; } int pal_get_key_value(char *key, char *value) { // Check is key is defined and valid if (pal_key_check(key)) return -1; return kv_get(key, value, NULL, KV_FPERSIST); } int pal_set_key_value(char *key, char *value) { // Check is key is defined and valid if (pal_key_check(key)) return -1; return kv_set(key, value, 0, KV_FPERSIST); } // Power On the server in a given slot static int server_power_on(uint8_t slot_id) { char vpath[64] = {0}; sprintf(vpath, GPIO_VAL, gpio_power[slot_id]); if (write_device(vpath, "1")) { return -1; } if (write_device(vpath, "0")) { return -1; } sleep(1); if (write_device(vpath, "1")) { return -1; } return 0; } // Power Off the server in given slot static int server_power_off(uint8_t slot_id, bool gs_flag) { char vpath[64] = {0}; if (slot_id < 1 || slot_id > 4) { return -1; } sprintf(vpath, GPIO_VAL, gpio_power[slot_id]); if (write_device(vpath, "1")) { return -1; } sleep(1); if (write_device(vpath, "0")) { return -1; } if (gs_flag) { sleep(DELAY_GRACEFUL_SHUTDOWN); } else { sleep(DELAY_POWER_OFF); } if (write_device(vpath, "1")) { return -1; } return 0; } // Control 12V to the server in a given slot static int server_12v_on(uint8_t slot_id) { char vpath[64] = {0}; int val; if (slot_id < 1 || slot_id > 4) { return -1; } sprintf(vpath, GPIO_VAL, gpio_12v[slot_id]); if (read_device(vpath, &val)) { return -1; } if (val == 0x1) { return 1; } if (write_device(vpath, "1")) { return -1; } return 0; } // Turn off 12V for the server in given slot static int server_12v_off(uint8_t slot_id) { char vpath[64] = {0}; int val; if (slot_id < 1 || slot_id > 4) { return -1; } sprintf(vpath, GPIO_VAL, gpio_12v[slot_id]); if (read_device(vpath, &val)) { return -1; } if (val == 0x0) { return 1; } if (write_device(vpath, "0")) { return -1; } return 0; } // Debug Card's UART and BMC/SoL port share UART port and need to enable only // one TXD i.e. either BMC's TXD or Debug Port's TXD. static int control_sol_txd(uint8_t slot) { uint32_t scu_fd; uint32_t ctrl; void *scu_reg; void *scu_pin_ctrl1; void *scu_pin_ctrl2; scu_fd = open("/dev/mem", O_RDWR | O_SYNC ); if (scu_fd < 0) { #ifdef DEBUG syslog(LOG_WARNING, "control_sol_txd: open fails\n"); #endif return -1; } scu_reg = mmap(NULL, PAGE_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, scu_fd, AST_SCU_BASE); scu_pin_ctrl1 = (char*)scu_reg + PIN_CTRL1_OFFSET; scu_pin_ctrl2 = (char*)scu_reg + PIN_CTRL2_OFFSET; switch(slot) { case 1: // Disable UART2's TXD and enable others ctrl = *(volatile uint32_t*) scu_pin_ctrl2; ctrl |= UART1_TXD; ctrl &= (~UART2_TXD); //Disable *(volatile uint32_t*) scu_pin_ctrl2 = ctrl; ctrl = *(volatile uint32_t*) scu_pin_ctrl1; ctrl |= UART3_TXD | UART4_TXD; *(volatile uint32_t*) scu_pin_ctrl1 = ctrl; break; case 2: // Disable UART1's TXD and enable others ctrl = *(volatile uint32_t*) scu_pin_ctrl2; ctrl &= (~UART1_TXD); // Disable ctrl |= UART2_TXD; *(volatile uint32_t*) scu_pin_ctrl2 = ctrl; ctrl = *(volatile uint32_t*) scu_pin_ctrl1; ctrl |= UART3_TXD | UART4_TXD; *(volatile uint32_t*) scu_pin_ctrl1 = ctrl; break; case 3: // Disable UART4's TXD and enable others ctrl = *(volatile uint32_t*) scu_pin_ctrl2; ctrl |= UART1_TXD | UART2_TXD; *(volatile uint32_t*) scu_pin_ctrl2 = ctrl; ctrl = *(volatile uint32_t*) scu_pin_ctrl1; ctrl |= UART3_TXD; ctrl &= (~UART4_TXD); // Disable *(volatile uint32_t*) scu_pin_ctrl1 = ctrl; break; case 4: // Disable UART3's TXD and enable others ctrl = *(volatile uint32_t*) scu_pin_ctrl2; ctrl |= UART1_TXD | UART2_TXD; *(volatile uint32_t*) scu_pin_ctrl2 = ctrl; ctrl = *(volatile uint32_t*) scu_pin_ctrl1; ctrl &= (~UART3_TXD); // Disable ctrl |= UART4_TXD; *(volatile uint32_t*) scu_pin_ctrl1 = ctrl; break; default: // Any other slots we need to enable all TXDs ctrl = *(volatile uint32_t*) scu_pin_ctrl2; ctrl |= UART1_TXD | UART2_TXD; *(volatile uint32_t*) scu_pin_ctrl2 = ctrl; ctrl = *(volatile uint32_t*) scu_pin_ctrl1; ctrl |= UART3_TXD | UART4_TXD; *(volatile uint32_t*) scu_pin_ctrl1 = ctrl; break; } munmap(scu_reg, PAGE_SIZE); close(scu_fd); return 0; } // Display the given POST code using GPIO port static int pal_post_display(uint8_t status) { char path[64] = {0}; int ret; char *val; #ifdef DEBUG syslog(LOG_WARNING, "pal_post_display: status is %d\n", status); #endif sprintf(path, GPIO_VAL, GPIO_POSTCODE_0); if (BIT(status, 0)) { val = "1"; } else { val = "0"; } ret = write_device(path, val); if (ret) { goto post_exit; } sprintf(path, GPIO_VAL, GPIO_POSTCODE_1); if (BIT(status, 1)) { val = "1"; } else { val = "0"; } ret = write_device(path, val); if (ret) { goto post_exit; } sprintf(path, GPIO_VAL, GPIO_POSTCODE_2); if (BIT(status, 2)) { val = "1"; } else { val = "0"; } ret = write_device(path, val); if (ret) { goto post_exit; } sprintf(path, GPIO_VAL, GPIO_POSTCODE_3); if (BIT(status, 3)) { val = "1"; } else { val = "0"; } ret = write_device(path, val); if (ret) { goto post_exit; } sprintf(path, GPIO_VAL, GPIO_POSTCODE_4); if (BIT(status, 4)) { val = "1"; } else { val = "0"; } ret = write_device(path, val); if (ret) { goto post_exit; } sprintf(path, GPIO_VAL, GPIO_POSTCODE_5); if (BIT(status, 5)) { val = "1"; } else { val = "0"; } ret = write_device(path, val); if (ret) { goto post_exit; } sprintf(path, GPIO_VAL, GPIO_POSTCODE_6); if (BIT(status, 6)) { val = "1"; } else { val = "0"; } ret = write_device(path, val); if (ret) { goto post_exit; } sprintf(path, GPIO_VAL, GPIO_POSTCODE_7); if (BIT(status, 7)) { val = "1"; } else { val = "0"; } ret = write_device(path, val); if (ret) { goto post_exit; } post_exit: if (ret) { #ifdef DEBUG syslog(LOG_WARNING, "write_device failed for %s\n", path); #endif return -1; } else { return 0; } } static int read_device_hex(const char *device, int *value) { FILE *fp; int rc; fp = fopen(device, "r"); if (!fp) { #ifdef DEBUG syslog(LOG_INFO, "failed to open device %s", device); #endif return errno; } rc = fscanf(fp, "%x", value); fclose(fp); if (rc != 1) { #ifdef DEBUG syslog(LOG_INFO, "failed to read device %s", device); #endif return ENOENT; } else { return 0; } } // Platform Abstraction Layer (PAL) Functions int pal_get_platform_name(char *name) { strcpy(name, YOSEMITE_PLATFORM_NAME); return 0; } int pal_get_num_slots(uint8_t *num) { *num = YOSEMITE_MAX_NUM_SLOTS; return 0; } int pal_is_fru_prsnt(uint8_t fru, uint8_t *status) { int val; char path[64] = {0}; switch (fru) { case FRU_SLOT1: case FRU_SLOT2: case FRU_SLOT3: case FRU_SLOT4: sprintf(path, GPIO_VAL, gpio_prsnt[fru]); if (read_device(path, &val)) { return -1; } if (val == 0x0) { *status = 1; } else { *status = 0; } break; case FRU_SPB: case FRU_NIC: *status = 1; break; default: return -1; } return 0; } int pal_is_fru_ready(uint8_t fru, uint8_t *status) { int val; char path[64] = {0}; switch (fru) { case FRU_SLOT1: case FRU_SLOT2: case FRU_SLOT3: case FRU_SLOT4: sprintf(path, GPIO_VAL, gpio_bic_ready[fru]); if (read_device(path, &val)) { return -1; } if (val == 0x0) { *status = 1; } else { *status = 0; } break; case FRU_SPB: case FRU_NIC: *status = 1; break; default: return -1; } return 0; } int pal_is_slot_server(uint8_t fru) { int ret = 0; switch(fru) { case FRU_SLOT1: case FRU_SLOT2: case FRU_SLOT3: case FRU_SLOT4: ret = 1; break; } return ret; } int pal_is_server_12v_on(uint8_t slot_id, uint8_t *status) { int val; char path[64] = {0}; if (slot_id < 1 || slot_id > 4) { return -1; } sprintf(path, GPIO_VAL, gpio_12v[slot_id]); if (read_device(path, &val)) { return -1; } if (val == 0x1) { *status = 1; } else { *status = 0; } return 0; } int pal_is_debug_card_prsnt(uint8_t *status) { int val; char path[64] = {0}; sprintf(path, GPIO_VAL, GPIO_DBG_CARD_PRSNT); if (read_device(path, &val)) { return -1; } if (val == 0x0) { *status = 1; } else { *status = 0; } return 0; } int pal_get_server_power(uint8_t slot_id, uint8_t *status) { int ret; bic_gpio_t gpio; uint8_t retry = MAX_READ_RETRY; static uint8_t last_status[MAX_NODES+1] = {0}; /* Check whether the system is 12V off or on */ ret = pal_is_server_12v_on(slot_id, status); if (ret < 0) { syslog(LOG_ERR, "pal_get_server_power: pal_is_server_12v_on failed"); return -1; } /* If 12V-off, return */ if (!(*status)) { *status = SERVER_12V_OFF; last_status[slot_id] = SERVER_POWER_OFF; return 0; } /* If 12V-on, check if the CPU is turned on or not */ while (retry) { ret = bic_get_gpio(slot_id, &gpio); if (!ret) break; msleep(50); retry--; } if (ret) { // Check for if the BIC is irresponsive due to 12V_OFF or 12V_CYCLE syslog(LOG_INFO, "pal_get_server_power: bic_get_gpio returned error hence" " using the static last status %u for fru %d", last_status[slot_id], slot_id); *status = last_status[slot_id]; return 0; } if (gpio.pwrgood_cpu) { *status = SERVER_POWER_ON; } else { *status = SERVER_POWER_OFF; } last_status[slot_id] = *status; return 0; } // Power Off, Power On, or Power Reset the server in given slot int pal_set_server_power(uint8_t slot_id, uint8_t cmd) { int ret; uint8_t status; bool gs_flag = false; if (slot_id < 1 || slot_id > 4) { return -1; } if ((cmd != SERVER_12V_OFF) && (cmd != SERVER_12V_ON) && (cmd != SERVER_12V_CYCLE)) { ret = pal_is_fru_ready(slot_id, &status); //Break out if fru is not ready if ((ret < 0) || (status == 0)) { return -2; } if (pal_get_server_power(slot_id, &status) < 0) { return -1; } } switch(cmd) { case SERVER_POWER_ON: if (status == SERVER_POWER_ON) return 1; else return server_power_on(slot_id); break; case SERVER_POWER_OFF: if (status == SERVER_POWER_OFF) return 1; else return server_power_off(slot_id, gs_flag); break; case SERVER_POWER_CYCLE: if (status == SERVER_POWER_ON) { if (server_power_off(slot_id, gs_flag)) return -1; sleep(DELAY_POWER_CYCLE); return server_power_on(slot_id); } else if (status == SERVER_POWER_OFF) { return (server_power_on(slot_id)); } break; case SERVER_POWER_RESET: if (status == SERVER_POWER_ON) { ret = pal_set_rst_btn(slot_id, 0); if (ret < 0) return ret; msleep(100); //some server miss to detect a quick pulse, so delay 100ms between low high ret = pal_set_rst_btn(slot_id, 1); if (ret < 0) return ret; } else if (status == SERVER_POWER_OFF) { printf("Ignore to execute power reset action when the power status of server is off\n"); return -2; } break; case SERVER_GRACEFUL_SHUTDOWN: if (status == SERVER_POWER_OFF) { return 1; } else { gs_flag = true; return server_power_off(slot_id, gs_flag); } break; case SERVER_12V_ON: return server_12v_on(slot_id); case SERVER_12V_OFF: return server_12v_off(slot_id); case SERVER_12V_CYCLE: if (server_12v_off(slot_id) < 0) { return -1; } sleep(DELAY_12V_CYCLE); return (server_12v_on(slot_id)); case SERVER_GLOBAL_RESET: return server_power_off(slot_id, false); default: return -1; } return 0; } int pal_sled_cycle(void) { syslog(LOG_CRIT, "SLED_CYCLE successful"); pal_update_ts_sled(); // Remove the adm1275 module as the HSC device is busy system("rmmod adm1275"); // Send command to HSC power cycle system("i2cset -y 10 0x40 0xd9 c"); return 0; } // Read the Front Panel Hand Switch and return the position int pal_get_hand_sw(uint8_t *pos) { char path[64] = {0}; int id1, id2, id4, id8; uint8_t loc; // Read 4 GPIOs to read the current position // id1: GPIOR2(138) // id2: GPIOR3(139) // id4: GPIOR4(140) // id8: GPIOR5(141) // Read ID1 sprintf(path, GPIO_VAL, GPIO_HAND_SW_ID1); if (read_device(path, &id1)) { return -1; } // Read ID2 sprintf(path, GPIO_VAL, GPIO_HAND_SW_ID2); if (read_device(path, &id2)) { return -1; } // Read ID4 sprintf(path, GPIO_VAL, GPIO_HAND_SW_ID4); if (read_device(path, &id4)) { return -1; } // Read ID8 sprintf(path, GPIO_VAL, GPIO_HAND_SW_ID8); if (read_device(path, &id8)) { return -1; } loc = ((id8 << 3) | (id4 << 2) | (id2 << 1) | (id1)); switch(loc) { case 0: case 5: *pos = HAND_SW_SERVER1; break; case 1: case 6: *pos = HAND_SW_SERVER2; break; case 2: case 7: *pos = HAND_SW_SERVER3; break; case 3: case 8: *pos = HAND_SW_SERVER4; break; default: *pos = HAND_SW_BMC; break; } return 0; } // Return the Front panel Power Button int pal_get_pwr_btn(uint8_t *status) { char path[64] = {0}; int val; sprintf(path, GPIO_VAL, GPIO_PWR_BTN); if (read_device(path, &val)) { return -1; } if (val) { *status = 0x0; } else { *status = 0x1; } return 0; } // Return the front panel's Reset Button status int pal_get_rst_btn(uint8_t *status) { char path[64] = {0}; int val; sprintf(path, GPIO_VAL, GPIO_RST_BTN); if (read_device(path, &val)) { return -1; } if (val) { *status = 0x0; } else { *status = 0x1; } return 0; } // Update the Reset button input to the server at given slot int pal_set_rst_btn(uint8_t slot, uint8_t status) { char path[64] = {0}; char *val; if (slot < 1 || slot > 4) { return -1; } if (status) { val = "1"; } else { val = "0"; } sprintf(path, GPIO_VAL, gpio_rst_btn[slot]); if (write_device(path, val)) { return -1; } return 0; } // Update the LED for the given slot with the status int pal_set_led(uint8_t slot, uint8_t status) { char path[64] = {0}; char *val; if (slot < 1 || slot > 4) { return -1; } if (status) { val = "1"; } else { val = "0"; } sprintf(path, GPIO_VAL, gpio_led[slot]); if (write_device(path, val)) { return -1; } return 0; } // Update Heartbeet LED int pal_set_hb_led(uint8_t status) { char path[64] = {0}; char *val; if (status) { val = "1"; } else { val = "0"; } sprintf(path, GPIO_VAL, GPIO_HB_LED); if (write_device(path, val)) { return -1; } return 0; } // Update the Identification LED for the given slot with the status int pal_set_id_led(uint8_t slot, uint8_t status) { char path[64] = {0}; char *val; if (slot < 1 || slot > 4) { return -1; } if (status) { val = "1"; } else { val = "0"; } sprintf(path, GPIO_VAL, gpio_id_led[slot]); if (write_device(path, val)) { return -1; } return 0; } static int set_usb_mux(uint8_t state) { int val; char *new_state; char path[64] = {0}; sprintf(path, GPIO_VAL, GPIO_USB_MUX_EN_N); if (read_device(path, &val)) { return -1; } // This GPIO Pin is active low if ((!val) == state) return 0; if (state) new_state = "0"; else new_state = "1"; if (write_device(path, new_state) < 0) { #ifdef DEBUG syslog(LOG_WARNING, "write_device failed for %s\n", path); #endif return -1; } return 0; } // Update the USB Mux to the server at given slot int pal_switch_usb_mux(uint8_t slot) { char *gpio_sw0, *gpio_sw1; char path[64] = {0}; // Based on the USB mux table in Schematics switch(slot) { case HAND_SW_SERVER1: gpio_sw0 = "1"; gpio_sw1 = "0"; break; case HAND_SW_SERVER2: gpio_sw0 = "0"; gpio_sw1 = "0"; break; case HAND_SW_SERVER3: gpio_sw0 = "1"; gpio_sw1 = "1"; break; case HAND_SW_SERVER4: gpio_sw0 = "0"; gpio_sw1 = "1"; break; case HAND_SW_BMC: // Disable the USB MUX if (set_usb_mux(USB_MUX_OFF) < 0) return -1; else return 0; default: return 0; } // Enable the USB MUX if (set_usb_mux(USB_MUX_ON) < 0) return -1; sprintf(path, GPIO_VAL, GPIO_USB_SW0); if (write_device(path, gpio_sw0) < 0) { #ifdef DEBUG syslog(LOG_WARNING, "write_device failed for %s\n", path); #endif return -1; } sprintf(path, GPIO_VAL, GPIO_USB_SW1); if (write_device(path, gpio_sw1) < 0) { #ifdef DEBUG syslog(LOG_WARNING, "write_device failed for %s\n", path); #endif return -1; } return 0; } // Switch the UART mux to the given slot int pal_switch_uart_mux(uint8_t slot) { char * gpio_uart_sel0; char * gpio_uart_sel1; char * gpio_uart_sel2; char * gpio_uart_rx; char path[64] = {0}; int ret; // Refer the UART select table in schematic switch(slot) { case HAND_SW_SERVER1: gpio_uart_sel2 = "0"; gpio_uart_sel1 = "0"; gpio_uart_sel0 = "1"; gpio_uart_rx = "0"; break; case HAND_SW_SERVER2: gpio_uart_sel2 = "0"; gpio_uart_sel1 = "0"; gpio_uart_sel0 = "0"; gpio_uart_rx = "0"; break; case HAND_SW_SERVER3: gpio_uart_sel2 = "0"; gpio_uart_sel1 = "1"; gpio_uart_sel0 = "1"; gpio_uart_rx = "0"; break; case HAND_SW_SERVER4: gpio_uart_sel2 = "0"; gpio_uart_sel1 = "1"; gpio_uart_sel0 = "0"; gpio_uart_rx = "0"; break; default: // for all other cases, assume BMC gpio_uart_sel2 = "1"; gpio_uart_sel1 = "0"; gpio_uart_sel0 = "0"; gpio_uart_rx = "1"; break; } // Diable TXD path from BMC to avoid conflict with SoL ret = control_sol_txd(slot); if (ret) { goto uart_exit; } // Enable Debug card path sprintf(path, GPIO_VAL, GPIO_UART_SEL2); ret = write_device(path, gpio_uart_sel2); if (ret) { goto uart_exit; } sprintf(path, GPIO_VAL, GPIO_UART_SEL1); ret = write_device(path, gpio_uart_sel1); if (ret) { goto uart_exit; } sprintf(path, GPIO_VAL, GPIO_UART_SEL0); ret = write_device(path, gpio_uart_sel0); if (ret) { goto uart_exit; } sprintf(path, GPIO_VAL, GPIO_UART_RX); ret = write_device(path, gpio_uart_rx); if (ret) { goto uart_exit; } uart_exit: if (ret) { #ifdef DEBUG syslog(LOG_WARNING, "pal_switch_uart_mux: write_device failed: %s\n", path); #endif return ret; } else { return 0; } } // Enable POST buffer for the server in given slot int pal_post_enable(uint8_t slot) { int ret; bic_config_t config = {0}; bic_config_u *t = (bic_config_u *) &config; ret = bic_get_config(slot, &config); if (ret) { #ifdef DEBUG syslog(LOG_WARNING, "post_enable: bic_get_config failed for fru: %d\n", slot); #endif return ret; } t->bits.post = 1; ret = bic_set_config(slot, &config); if (ret) { #ifdef DEBUG syslog(LOG_WARNING, "post_enable: bic_set_config failed\n"); #endif return ret; } return 0; } // Disable POST buffer for the server in given slot int pal_post_disable(uint8_t slot) { int ret; bic_config_t config = {0}; bic_config_u *t = (bic_config_u *) &config; ret = bic_get_config(slot, &config); if (ret) { return ret; } t->bits.post = 0; ret = bic_set_config(slot, &config); if (ret) { return ret; } return 0; } // Get the last post code of the given slot int pal_post_get_last(uint8_t slot, uint8_t *status) { int ret; uint8_t buf[MAX_IPMB_RES_LEN] = {0x0}; uint8_t len; ret = bic_get_post_buf(slot, buf, &len); if (ret) { return ret; } // The post buffer is LIFO and the first byte gives the latest post code *status = buf[0]; return 0; } // Handle the received post code, for now display it on debug card int pal_post_handle(uint8_t slot, uint8_t status) { uint8_t prsnt, pos; int ret; // Check for debug card presence ret = pal_is_debug_card_prsnt(&prsnt); if (ret) { return ret; } // No debug card present, return if (!prsnt) { return 0; } // Get the hand switch position ret = pal_get_hand_sw(&pos); if (ret) { return ret; } // If the give server is not selected, return if (pos != slot) { return 0; } // Display the post code in the debug card ret = pal_post_display(status); if (ret) { return ret; } return 0; } int pal_get_fru_list(char *list) { strcpy(list, pal_fru_list); return 0; } int pal_get_fru_id(char *str, uint8_t *fru) { return yosemite_common_fru_id(str, fru); } int pal_get_fru_name(uint8_t fru, char *name) { return yosemite_common_fru_name(fru, name); } int pal_get_fru_sdr_path(uint8_t fru, char *path) { return yosemite_sensor_sdr_path(fru, path); } int pal_get_fru_sensor_list(uint8_t fru, uint8_t **sensor_list, int *cnt) { switch(fru) { case FRU_SLOT1: case FRU_SLOT2: case FRU_SLOT3: case FRU_SLOT4: *sensor_list = (uint8_t *) bic_sensor_list; *cnt = bic_sensor_cnt; break; case FRU_SPB: *sensor_list = (uint8_t *) spb_sensor_list; *cnt = spb_sensor_cnt; break; case FRU_NIC: *sensor_list = (uint8_t *) nic_sensor_list; *cnt = nic_sensor_cnt; break; default: #ifdef DEBUG syslog(LOG_WARNING, "pal_get_fru_sensor_list: Wrong fru id %u", fru); #endif return -1; } return 0; } int pal_fruid_write(uint8_t fru, char *path) { return bic_write_fruid(fru, 0, path); } int pal_sensor_sdr_init(uint8_t fru, sensor_info_t *sinfo) { uint8_t status; switch(fru) { case FRU_SLOT1: case FRU_SLOT2: case FRU_SLOT3: case FRU_SLOT4: pal_is_fru_prsnt(fru, &status); break; case FRU_SPB: case FRU_NIC: status = 1; break; } if (status) return yosemite_sensor_sdr_init(fru, sinfo); else return -1; } static sensor_check_t * get_sensor_check(uint8_t fru, uint8_t snr_num) { if (fru < 1 || fru > MAX_NUM_FRUS) { syslog(LOG_WARNING, "get_sensor_check: Wrong FRU ID %d\n", fru); return NULL; } return &m_snr_chk[fru-1][snr_num]; } int pal_sensor_read_raw(uint8_t fru, uint8_t sensor_num, void *value) { uint8_t status; char key[MAX_KEY_LEN] = {0}; char str[MAX_VALUE_LEN] = {0}; int ret; uint8_t retry = MAX_READ_RETRY; sensor_check_t *snr_chk; switch(fru) { case FRU_SLOT1: case FRU_SLOT2: case FRU_SLOT3: case FRU_SLOT4: sprintf(key, "slot%d_sensor%d", fru, sensor_num); if(pal_is_fru_prsnt(fru, &status) < 0) return -1; if (!status) { return -1; } break; case FRU_SPB: sprintf(key, "spb_sensor%d", sensor_num); break; case FRU_NIC: sprintf(key, "nic_sensor%d", sensor_num); break; default: return -1; } snr_chk = get_sensor_check(fru, sensor_num); while (retry) { ret = yosemite_sensor_read(fru, sensor_num, value); if ((ret >= 0) || (ret == EER_UNHANDLED)) break; msleep(50); retry--; } if(ret < 0) { snr_chk->val_valid = 0; if (ret == EER_UNHANDLED) return -1; if(fru == FRU_SPB || fru == FRU_NIC) return -1; if(pal_get_server_power(fru, &status) < 0) return -1; // This check helps interpret the IPMI packet loss scenario if(status == SERVER_POWER_ON) return -1; strcpy(str, "NA"); } else { // On successful sensor read if (fru == FRU_SPB) { if (sensor_num == SP_SENSOR_INLET_TEMP) { apply_inlet_correction((float *)value); } else if (sensor_num == SP_SENSOR_HSC_IN_POWER) { power_value_adjust((float *)value); } } if ((GETBIT(snr_chk->flag, UCR_THRESH) && (*((float*)value) >= snr_chk->ucr)) || (GETBIT(snr_chk->flag, LCR_THRESH) && (*((float*)value) <= snr_chk->lcr))) { if (snr_chk->retry_cnt < MAX_CHECK_RETRY) { snr_chk->retry_cnt++; if (!snr_chk->val_valid) return -1; *((float*)value) = snr_chk->last_val; } } else { snr_chk->last_val = *((float*)value); snr_chk->val_valid = 1; snr_chk->retry_cnt = 0; } sprintf(str, "%.2f",*((float*)value)); } if(kv_set(key, str, 0, 0) < 0) { #ifdef DEBUG syslog(LOG_WARNING, "pal_sensor_read_raw: cache_set key = %s, str = %s failed.", key, str); #endif return -1; } else { return ret; } } int pal_sensor_threshold_flag(uint8_t fru, uint8_t snr_num, uint16_t *flag) { switch(fru) { case FRU_SLOT1: case FRU_SLOT2: case FRU_SLOT3: case FRU_SLOT4: if (snr_num == BIC_SENSOR_SOC_THERM_MARGIN) *flag = GETMASK(SENSOR_VALID) | GETMASK(UCR_THRESH); else if (snr_num == BIC_SENSOR_SOC_PACKAGE_PWR) *flag = GETMASK(SENSOR_VALID); else if (snr_num == BIC_SENSOR_SOC_TJMAX) *flag = GETMASK(SENSOR_VALID); break; case FRU_SPB: /* * TODO: This is a HACK (t11229576) */ switch(snr_num) { case SP_SENSOR_P12V_SLOT1: case SP_SENSOR_P12V_SLOT2: case SP_SENSOR_P12V_SLOT3: case SP_SENSOR_P12V_SLOT4: *flag = GETMASK(SENSOR_VALID); break; } case FRU_NIC: break; } return 0; } int pal_get_sensor_threshold(uint8_t fru, uint8_t sensor_num, uint8_t thresh, void *value) { return yosemite_sensor_threshold(fru, sensor_num, thresh, value); } int pal_get_sensor_name(uint8_t fru, uint8_t sensor_num, char *name) { return yosemite_sensor_name(fru, sensor_num, name); } int pal_get_sensor_units(uint8_t fru, uint8_t sensor_num, char *units) { return yosemite_sensor_units(fru, sensor_num, units); } int pal_get_fruid_path(uint8_t fru, char *path) { return yosemite_get_fruid_path(fru, path); } int pal_get_fruid_eeprom_path(uint8_t fru, char *path) { return yosemite_get_fruid_eeprom_path(fru, path); } int pal_get_fruid_name(uint8_t fru, char *name) { return yosemite_get_fruid_name(fru, name); } int pal_set_def_key_value() { int ret; int i; int fru; char key[MAX_KEY_LEN] = {0}; for(i = 0; strcmp(key_list[i], LAST_KEY) != 0; i++) { if ((ret = kv_set(key_list[i], def_val_list[i], 0, KV_FPERSIST | KV_FCREATE)) < 0) { #ifdef DEBUG syslog(LOG_WARNING, "pal_set_def_key_value: kv_set failed. %d", ret); #endif } } /* Actions to be taken on Power On Reset */ if (pal_is_bmc_por()) { for (fru = 1; fru <= MAX_NUM_FRUS; fru++) { /* Clear all the SEL errors */ memset(key, 0, MAX_KEY_LEN); switch(fru) { case FRU_SLOT1: case FRU_SLOT2: case FRU_SLOT3: case FRU_SLOT4: sprintf(key, "slot%d_sel_error", fru); break; case FRU_SPB: continue; case FRU_NIC: continue; default: return -1; } /* Write the value "1" which means FRU_STATUS_GOOD */ ret = pal_set_key_value(key, "1"); /* Clear all the sensor health files*/ memset(key, 0, MAX_KEY_LEN); switch(fru) { case FRU_SLOT1: case FRU_SLOT2: case FRU_SLOT3: case FRU_SLOT4: sprintf(key, "slot%d_sensor_health", fru); break; case FRU_SPB: continue; case FRU_NIC: continue; default: return -1; } /* Write the value "1" which means FRU_STATUS_GOOD */ ret = pal_set_key_value(key, "1"); } } return 0; } int pal_get_fru_devtty(uint8_t fru, char *devtty) { switch(fru) { case FRU_SLOT1: sprintf(devtty, "/dev/ttyS2"); break; case FRU_SLOT2: sprintf(devtty, "/dev/ttyS1"); break; case FRU_SLOT3: sprintf(devtty, "/dev/ttyS4"); break; case FRU_SLOT4: sprintf(devtty, "/dev/ttyS3"); break; default: #ifdef DEBUG syslog(LOG_WARNING, "pal_get_fru_devtty: Wrong fru id %u", fru); #endif return -1; } return 0; } void pal_dump_key_value(void) { int i = 0; int ret; char value[MAX_VALUE_LEN] = {0x0}; while (strcmp(key_list[i], LAST_KEY)) { printf("%s:", key_list[i]); if ((ret = kv_get(key_list[i], value, NULL, KV_FPERSIST)) < 0) { printf("\n"); } else { printf("%s\n", value); } i++; memset(value, 0, MAX_VALUE_LEN); } } int pal_set_last_pwr_state(uint8_t fru, char *state) { int ret; char key[MAX_KEY_LEN] = {0}; sprintf(key, "pwr_server%d_last_state", (int) fru); ret = pal_set_key_value(key, state); if (ret < 0) { #ifdef DEBUG syslog(LOG_WARNING, "pal_set_last_pwr_state: pal_set_key_value failed for " "fru %u", fru); #endif } return ret; } int pal_get_last_pwr_state(uint8_t fru, char *state) { int ret; char key[MAX_KEY_LEN] = {0}; switch(fru) { case FRU_SLOT1: case FRU_SLOT2: case FRU_SLOT3: case FRU_SLOT4: sprintf(key, "pwr_server%d_last_state", (int) fru); ret = pal_get_key_value(key, state); if (ret < 0) { #ifdef DEBUG syslog(LOG_WARNING, "pal_get_last_pwr_state: pal_get_key_value failed for " "fru %u", fru); #endif } return ret; case FRU_SPB: case FRU_NIC: sprintf(state, "on"); return 0; } return 0; } int pal_get_sys_guid(uint8_t slot, char *guid) { return bic_get_sys_guid(slot, (uint8_t*) guid); } int pal_set_sysfw_ver(uint8_t slot, uint8_t *ver) { int i; char key[MAX_KEY_LEN] = {0}; char str[MAX_VALUE_LEN] = {0}; char tstr[10] = {0}; sprintf(key, "sysfw_ver_slot%d", (int) slot); for (i = 0; i < SIZE_SYSFW_VER; i++) { sprintf(tstr, "%02x", ver[i]); strcat(str, tstr); } return pal_set_key_value(key, str); } int pal_get_sysfw_ver(uint8_t slot, uint8_t *ver) { int i; int j = 0; int ret; int msb, lsb; char key[MAX_KEY_LEN] = {0}; char str[MAX_VALUE_LEN] = {0}; char tstr[4] = {0}; sprintf(key, "sysfw_ver_slot%d", (int) slot); ret = pal_get_key_value(key, str); if (ret) { return ret; } for (i = 0; i < 2*SIZE_SYSFW_VER; i += 2) { sprintf(tstr, "%c\n", str[i]); msb = strtol(tstr, NULL, 16); sprintf(tstr, "%c\n", str[i+1]); lsb = strtol(tstr, NULL, 16); ver[j++] = (msb << 4) | lsb; } return 0; } int pal_is_bmc_por(void) { uint32_t scu_fd; uint32_t wdt; void *scu_reg; void *scu_wdt; scu_fd = open("/dev/mem", O_RDWR | O_SYNC ); if (scu_fd < 0) { return 0; } scu_reg = mmap(NULL, PAGE_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, scu_fd, AST_SCU_BASE); scu_wdt = (char*)scu_reg + WDT_OFFSET; wdt = *(volatile uint32_t*) scu_wdt; munmap(scu_reg, PAGE_SIZE); close(scu_fd); if (wdt & 0x6) { return 0; } else { return 1; } } int pal_get_fru_discrete_list(uint8_t fru, uint8_t **sensor_list, int *cnt) { switch(fru) { case FRU_SLOT1: case FRU_SLOT2: case FRU_SLOT3: case FRU_SLOT4: *sensor_list = (uint8_t *) bic_discrete_list; *cnt = bic_discrete_cnt; break; case FRU_SPB: case FRU_NIC: *sensor_list = NULL; *cnt = 0; break; default: #ifdef DEBUG syslog(LOG_WARNING, "pal_get_fru_discrete_list: Wrong fru id %u", fru); #endif return -1; } return 0; } static void _print_sensor_discrete_log(uint8_t fru, uint8_t snr_num, char *snr_name, uint8_t val, char *event) { if (val) { syslog(LOG_CRIT, "ASSERT: %s discrete - raised - FRU: %d, num: 0x%X," " snr: %-16s val: %d", event, fru, snr_num, snr_name, val); } else { syslog(LOG_CRIT, "DEASSERT: %s discrete - settled - FRU: %d, num: 0x%X," " snr: %-16s val: %d", event, fru, snr_num, snr_name, val); } pal_update_ts_sled(); } int pal_sensor_discrete_check(uint8_t fru, uint8_t snr_num, char *snr_name, uint8_t o_val, uint8_t n_val) { char name[32]; bool valid = false; uint8_t diff = o_val ^ n_val; if (GETBIT(diff, 0)) { switch(snr_num) { case BIC_SENSOR_SYSTEM_STATUS: sprintf(name, "SOC_Thermal_Trip"); valid = true; break; case BIC_SENSOR_VR_HOT: sprintf(name, "SOC_VR_Hot"); valid = true; break; } if (valid) { _print_sensor_discrete_log( fru, snr_num, snr_name, GETBIT(n_val, 0), name); valid = false; } } if (GETBIT(diff, 1)) { switch(snr_num) { case BIC_SENSOR_SYSTEM_STATUS: sprintf(name, "SOC_FIVR_Fault"); valid = true; break; case BIC_SENSOR_VR_HOT: sprintf(name, "SOC_DIMM_VR_Hot"); valid = true; break; case BIC_SENSOR_CPU_DIMM_HOT: sprintf(name, "SOC_MEMHOT"); valid = true; break; } if (valid) { _print_sensor_discrete_log( fru, snr_num, snr_name, GETBIT(n_val, 1), name); valid = false; } } if (GETBIT(diff, 2)) { switch(snr_num) { case BIC_SENSOR_SYSTEM_STATUS: sprintf(name, "SOC_Throttle"); valid = true; break; } if (valid) { _print_sensor_discrete_log( fru, snr_num, snr_name, GETBIT(n_val, 2), name); valid = false; } } return 0; } static int pal_store_crashdump(uint8_t fru) { return yosemite_common_crashdump(fru); } int pal_sel_handler(uint8_t fru, uint8_t snr_num, uint8_t *event_data) { char key[MAX_KEY_LEN] = {0}; char cvalue[MAX_VALUE_LEN] = {0}; static int assert_cnt[YOSEMITE_MAX_NUM_SLOTS] = {0}; /* For every SEL event received from the BIC, set the critical LED on */ switch(fru) { case FRU_SLOT1: case FRU_SLOT2: case FRU_SLOT3: case FRU_SLOT4: switch(snr_num) { case CATERR_B: sprintf(key, CRASHDUMP_KEY, fru); kv_set(key, "1", 0, 0); pal_store_crashdump(fru); break; case 0x00: // don't care sensor number 00h return 0; } sprintf(key, "slot%d_sel_error", fru); fru -= 1; if ((event_data[2] & 0x80) == 0) { // 0: Assertion, 1: Deassertion assert_cnt[fru]++; } else { if (--assert_cnt[fru] < 0) assert_cnt[fru] = 0; } sprintf(cvalue, "%s", (assert_cnt[fru] > 0) ? "0" : "1"); break; case FRU_SPB: return 0; case FRU_NIC: return 0; default: return -1; } /* Write the value "0" which means FRU_STATUS_BAD */ return pal_set_key_value(key, cvalue); } int pal_parse_sel(uint8_t fru, uint8_t *sel, char *error_log) { uint8_t snr_num = sel[11]; uint8_t *event_data = &sel[10]; uint8_t *ed = &event_data[3]; char temp_log[512] = {0}; uint8_t sen_type = event_data[0]; uint8_t chn_num, dimm_num; switch(snr_num) { case MEMORY_ECC_ERR: case MEMORY_ERR_LOG_DIS: strcpy(error_log, ""); if (snr_num == MEMORY_ECC_ERR) { // SEL from MEMORY_ECC_ERR Sensor if ((ed[0] & 0x0F) == 0x0) { if (sen_type == 0x0C) { strcat(error_log, "Correctable"); sprintf(temp_log, "DIMM%02X ECC err", ed[2]); pal_add_cri_sel(temp_log); } else if (sen_type == 0x10) strcat(error_log, "Correctable ECC error Logging Disabled"); } else if ((ed[0] & 0x0F) == 0x1) { strcat(error_log, "Uncorrectable"); sprintf(temp_log, "DIMM%02X UECC err", ed[2]); pal_add_cri_sel(temp_log); } else if ((ed[0] & 0x0F) == 0x5) strcat(error_log, "Correctable ECC error Logging Limit Reached"); else strcat(error_log, "Unknown"); } else { // SEL from MEMORY_ERR_LOG_DIS Sensor if ((ed[0] & 0x0F) == 0x0) strcat(error_log, "Correctable Memory Error Logging Disabled"); else strcat(error_log, "Unknown"); } // DIMM number (ed[2]): // Bit[7:5]: Socket number (Range: 0-7) // Bit[4:3]: Channel number (Range: 0-3) // Bit[2:0]: DIMM number (Range: 0-7) if (((ed[1] & 0xC) >> 2) == 0x0) { /* All Info Valid */ chn_num = (ed[2] & 0x18) >> 3; dimm_num = ed[2] & 0x7; /* If critical SEL logging is available, do it */ if (sen_type == 0x0C) { if ((ed[0] & 0x0F) == 0x0) { sprintf(temp_log, "DIMM%c%d ECC err,FRU:%u", 'A'+chn_num, dimm_num, fru); pal_add_cri_sel(temp_log); } else if ((ed[0] & 0x0F) == 0x1) { sprintf(temp_log, "DIMM%c%d UECC err,FRU:%u", 'A'+chn_num, dimm_num, fru); pal_add_cri_sel(temp_log); } } /* Then continue parse the error into a string. */ /* All Info Valid */ sprintf(temp_log, " DIMM %c%d Logical Rank %d (CPU# %d, CHN# %d, DIMM# %d)", 'A'+chn_num, dimm_num, ed[1] & 0x03, (ed[2] & 0xE0) >> 5, chn_num, dimm_num); } else if (((ed[1] & 0xC) >> 2) == 0x1) { /* DIMM info not valid */ sprintf(temp_log, " (CPU# %d, CHN# %d)", (ed[2] & 0xE0) >> 5, (ed[2] & 0x18) >> 3); } else if (((ed[1] & 0xC) >> 2) == 0x2) { /* CHN info not valid */ sprintf(temp_log, " (CPU# %d, DIMM# %d)", (ed[2] & 0xE0) >> 5, ed[2] & 0x7); } else if (((ed[1] & 0xC) >> 2) == 0x3) { /* CPU info not valid */ sprintf(temp_log, " (CHN# %d, DIMM# %d)", (ed[2] & 0x18) >> 3, ed[2] & 0x7); } strcat(error_log, temp_log); return 0; } pal_parse_sel_helper(fru, sel, error_log); return 0; } int pal_set_sensor_health(uint8_t fru, uint8_t value) { char key[MAX_KEY_LEN] = {0}; char cvalue[MAX_VALUE_LEN] = {0}; switch(fru) { case FRU_SLOT1: case FRU_SLOT2: case FRU_SLOT3: case FRU_SLOT4: sprintf(key, "slot%d_sensor_health", fru); break; case FRU_SPB: sprintf(key, "spb_sensor_health"); break; case FRU_NIC: sprintf(key, "nic_sensor_health"); break; default: return -1; } sprintf(cvalue, (value > 0) ? "1": "0"); return pal_set_key_value(key, cvalue); } int pal_get_fru_health(uint8_t fru, uint8_t *value) { char cvalue[MAX_VALUE_LEN] = {0}; char key[MAX_KEY_LEN] = {0}; int ret; switch(fru) { case FRU_SLOT1: case FRU_SLOT2: case FRU_SLOT3: case FRU_SLOT4: sprintf(key, "slot%d_sensor_health", fru); break; case FRU_SPB: sprintf(key, "spb_sensor_health"); break; case FRU_NIC: sprintf(key, "nic_sensor_health"); break; default: return -1; } ret = pal_get_key_value(key, cvalue); if (ret) { return ret; } *value = atoi(cvalue); memset(key, 0, MAX_KEY_LEN); memset(cvalue, 0, MAX_VALUE_LEN); switch(fru) { case FRU_SLOT1: case FRU_SLOT2: case FRU_SLOT3: case FRU_SLOT4: sprintf(key, "slot%d_sel_error", fru); break; case FRU_SPB: return 0; case FRU_NIC: return 0; default: return -1; } ret = pal_get_key_value(key, cvalue); if (ret) { return ret; } *value = *value & atoi(cvalue); return 0; } void pal_inform_bic_mode(uint8_t fru, uint8_t mode) { switch(mode) { case BIC_MODE_NORMAL: // Bridge IC entered normal mode // Inform BIOS that BMC is ready bic_set_gpio(fru, GPIO_BMC_READY_N, 0); break; case BIC_MODE_UPDATE: // Bridge IC entered update mode // TODO: Might need to handle in future break; default: break; } } int pal_get_fan_name(uint8_t num, char *name) { switch(num) { case FAN_0: sprintf(name, "Fan 0"); break; case FAN_1: sprintf(name, "Fan 1"); break; default: return -1; } return 0; } static int write_fan_value(const int fan, const char *device, const int value) { char full_name[LARGEST_DEVICE_NAME]; char device_name[LARGEST_DEVICE_NAME]; char output_value[LARGEST_DEVICE_NAME]; snprintf(device_name, LARGEST_DEVICE_NAME, device, fan); snprintf(full_name, LARGEST_DEVICE_NAME, "%s/%s", PWM_DIR, device_name); snprintf(output_value, LARGEST_DEVICE_NAME, "%d", value); return write_device(full_name, output_value); } int pal_set_fan_speed(uint8_t fan, uint8_t pwm) { int unit; int ret; if (fan >= pal_pwm_cnt) { syslog(LOG_INFO, "pal_set_fan_speed: fan number is invalid - %d", fan); return -1; } // Convert the percentage to our 1/96th unit. unit = pwm * PWM_UNIT_MAX / 100; // For 0%, turn off the PWM entirely if (unit == 0) { ret = write_fan_value(fan, "pwm%d_en", 0); if (ret < 0) { syslog(LOG_INFO, "set_fan_speed: write_fan_value failed"); return -1; } return 0; // For 100%, set falling and rising to the same value } else if (unit == PWM_UNIT_MAX) { unit = 0; } ret = write_fan_value(fan, "pwm%d_type", 0); if (ret < 0) { syslog(LOG_INFO, "set_fan_speed: write_fan_value failed"); return -1; } ret = write_fan_value(fan, "pwm%d_rising", 0); if (ret < 0) { syslog(LOG_INFO, "set_fan_speed: write_fan_value failed"); return -1; } ret = write_fan_value(fan, "pwm%d_falling", unit); if (ret < 0) { syslog(LOG_INFO, "set_fan_speed: write_fan_value failed"); return -1; } ret = write_fan_value(fan, "pwm%d_en", 1); if (ret < 0) { syslog(LOG_INFO, "set_fan_speed: write_fan_value failed"); return -1; } return 0; } int pal_get_fan_speed(uint8_t fan, int *rpm) { int ret; float value; // Redirect FAN to sensor cache ret = sensor_cache_read(FRU_SPB, SP_SENSOR_FAN0_TACH + fan, &value); if (0 == ret) *rpm = (int) value; return ret; } void pal_update_ts_sled() { char key[MAX_KEY_LEN] = {0}; char tstr[MAX_VALUE_LEN] = {0}; struct timespec ts; clock_gettime(CLOCK_REALTIME, &ts); sprintf(tstr, "%d", (int) ts.tv_sec); sprintf(key, "timestamp_sled"); pal_set_key_value(key, tstr); } int pal_handle_dcmi(uint8_t fru, uint8_t *request, uint8_t req_len, uint8_t *response, uint8_t *rlen) { return bic_me_xmit(fru, request, req_len, response, rlen); } void pal_log_clear(char *fru) { char key[MAX_KEY_LEN] = {0}; if (!strcmp(fru, "slot1")) { pal_set_key_value("slot1_sensor_health", "1"); pal_set_key_value("slot1_sel_error", "1"); } else if (!strcmp(fru, "slot2")) { pal_set_key_value("slot2_sensor_health", "1"); pal_set_key_value("slot2_sel_error", "1"); } else if (!strcmp(fru, "slot3")) { pal_set_key_value("slot3_sensor_health", "1"); pal_set_key_value("slot3_sel_error", "1"); } else if (!strcmp(fru, "slot4")) { pal_set_key_value("slot4_sensor_health", "1"); pal_set_key_value("slot4_sel_error", "1"); } else if (!strcmp(fru, "spb")) { pal_set_key_value("spb_sensor_health", "1"); } else if (!strcmp(fru, "nic")) { pal_set_key_value("nic_sensor_health", "1"); } else if (!strcmp(fru, "all")) { int i; for (i = 1; i <= 4; i++) { sprintf(key, "slot%d_sensor_health", i); pal_set_key_value(key, "1"); sprintf(key, "slot%d_sel_error", i); pal_set_key_value(key, "1"); } pal_set_key_value("spb_sensor_health", "1"); pal_set_key_value("nic_sensor_health", "1"); } } int pal_get_pwm_value(uint8_t fan_num, uint8_t *value) { char path[LARGEST_DEVICE_NAME] = {0}; char device_name[LARGEST_DEVICE_NAME] = {0}; int val = 0; int pwm_enable = 0; if(fan_num < 0 || fan_num >= pal_pwm_cnt) { syslog(LOG_INFO, "pal_get_pwm_value: fan number is invalid - %d", fan_num); return -1; } // Need check pwmX_en to determine the PWM is 0 or 100. snprintf(device_name, LARGEST_DEVICE_NAME, "pwm%d_en", fan_num); snprintf(path, LARGEST_DEVICE_NAME, "%s/%s", PWM_DIR, device_name); if (read_device(path, &pwm_enable)) { syslog(LOG_INFO, "pal_get_pwm_value: read %s failed", path); return -1; } if(pwm_enable) { snprintf(device_name, LARGEST_DEVICE_NAME, "pwm%d_falling", fan_num); snprintf(path, LARGEST_DEVICE_NAME, "%s/%s", PWM_DIR, device_name); if (read_device_hex(path, &val)) { syslog(LOG_INFO, "pal_get_pwm_value: read %s failed", path); return -1; } if(val == 0) *value = 100; else *value = (100 * val + (PWM_UNIT_MAX-1)) / PWM_UNIT_MAX; } else { *value = 0; } return 0; } int pal_fan_dead_handle(int fan_num) { // TODO: Add action in case of fan dead return 0; } int pal_fan_recovered_handle(int fan_num) { // TODO: Add action in case of fan recovered return 0; } int pal_get_boot_order(uint8_t slot, uint8_t *req_data, uint8_t *boot, uint8_t *res_len) { int i, j = 0; int ret; int msb, lsb; char key[MAX_KEY_LEN] = {0}; char str[MAX_VALUE_LEN] = {0}; char tstr[4] = {0}; sprintf(key, "slot%u_boot_order", slot); ret = pal_get_key_value(key, str); if (ret) { *res_len = 0; return ret; } memset(boot, 0x00, SIZE_BOOT_ORDER); for (i = 0; i < 2*SIZE_BOOT_ORDER; i += 2) { sprintf(tstr, "%c\n", str[i]); msb = strtol(tstr, NULL, 16); sprintf(tstr, "%c\n", str[i+1]); lsb = strtol(tstr, NULL, 16); boot[j++] = (msb << 4) | lsb; } *res_len = SIZE_BOOT_ORDER; return 0; } int pal_set_boot_order(uint8_t slot, uint8_t *boot, uint8_t *res_data, uint8_t *res_len) { int i; char key[MAX_KEY_LEN] = {0}; char str[MAX_VALUE_LEN] = {0}; char tstr[10] = {0}; sprintf(key, "slot%u_boot_order", slot); for (i = 0; i < SIZE_BOOT_ORDER; i++) { snprintf(tstr, 3, "%02x", boot[i]); strncat(str, tstr, 3); } *res_len = 0; return pal_set_key_value(key, str); } int pal_is_crashdump_ongoing(uint8_t slot) { char key[MAX_KEY_LEN] = {0}; char value[MAX_VALUE_LEN] = {0}; int ret; sprintf(key, CRASHDUMP_KEY, slot); ret = kv_get(key, value, NULL, 0); if (ret < 0) { #ifdef DEBUG syslog(LOG_INFO, "pal_get_crashdumpe: failed"); #endif return 0; } if (atoi(value) > 0) return 1; return 0; } bool pal_is_fw_update_ongoing_system(void) { uint8_t i; for (i = FRU_SLOT1; i <= FRU_BMC; i++) { if (pal_is_fw_update_ongoing(i) == true) return true; } return false; } int pal_set_fw_update_ongoing(uint8_t fruid, uint16_t tmout) { char key[64] = {0}; char value[64] = {0}; struct timespec ts; if (fruid == FRU_BMC) { fruid = FRU_SPB; } sprintf(key, "fru%d_fwupd", fruid); clock_gettime(CLOCK_MONOTONIC, &ts); ts.tv_sec += tmout; sprintf(value, "%ld", ts.tv_sec); if (kv_set(key, value, 0, 0) < 0) { return -1; } return 0; } int pal_init_sensor_check(uint8_t fru, uint8_t snr_num, void *snr) { sensor_check_t *snr_chk; _sensor_thresh_t *psnr = (_sensor_thresh_t *)snr; snr_chk = get_sensor_check(fru, snr_num); snr_chk->flag = psnr->flag; snr_chk->ucr = psnr->ucr; snr_chk->lcr = psnr->lcr; snr_chk->retry_cnt = 0; snr_chk->val_valid = 0; snr_chk->last_val = 0; return 0; } void pal_sensor_assert_handle(uint8_t fru, uint8_t snr_num, float val, uint8_t thresh) { } void pal_sensor_deassert_handle(uint8_t fru, uint8_t snr_num, float val, uint8_t thresh) { } void pal_add_cri_sel(char *str) { } int pal_get_board_rev_id(uint8_t *id) { return 0; } int pal_get_mb_slot_id(uint8_t *id) { return 0; } int pal_get_slot_cfg_id(uint8_t *id) { return 0; } int pal_set_dev_guid(uint8_t slot, char *guid) { return 0; } int pal_get_dev_guid(uint8_t fru, char *guid) { return 0; } void pal_get_chassis_status(uint8_t slot, uint8_t *req_data, uint8_t *res_data, uint8_t *res_len) { char key[MAX_KEY_LEN] = {0}; sprintf(key, "slot%d_por_cfg", slot); char buff[MAX_VALUE_LEN]; int policy = 3; uint8_t status, ret; unsigned char *data = res_data; // Platform Power Policy if (pal_get_key_value(key, buff) == 0) { if (!memcmp(buff, "off", strlen("off"))) policy = 0; else if (!memcmp(buff, "lps", strlen("lps"))) policy = 1; else if (!memcmp(buff, "on", strlen("on"))) policy = 2; else policy = 3; } // Current Power State ret = pal_get_server_power(slot, &status); if (ret >= 0) { *data++ = status | (policy << 5); } else { // load default syslog(LOG_WARNING, "ipmid: pal_get_server_power failed for slot1\n"); *data++ = 0x00 | (policy << 5); } *data++ = 0x00; // Last Power Event *data++ = 0x40; // Misc. Chassis Status *data++ = 0x00; // Front Panel Button Disable *res_len = data - res_data; } uint8_t pal_set_power_restore_policy(uint8_t slot, uint8_t *pwr_policy, uint8_t *res_data) { uint8_t completion_code; char key[MAX_KEY_LEN] = {0}; sprintf(key, "slot%d_por_cfg", slot); completion_code = CC_SUCCESS; // Fill response with default values unsigned char policy = *pwr_policy & 0x07; // Power restore policy switch (policy) { case 0: if (pal_set_key_value(key, "off") != 0) completion_code = CC_UNSPECIFIED_ERROR; break; case 1: if (pal_set_key_value(key, "lps") != 0) completion_code = CC_UNSPECIFIED_ERROR; break; case 2: if (pal_set_key_value(key, "on") != 0) completion_code = CC_UNSPECIFIED_ERROR; break; case 3: // no change (just get present policy support) break; default: completion_code = CC_PARAM_OUT_OF_RANGE; break; } return completion_code; } int pal_get_platform_id(uint8_t *id) { return 0; } int pal_get_fw_info(uint8_t fru, unsigned char target, unsigned char* res, unsigned char* res_len) { return -1; } //For OEM command "CMD_OEM_GET_PLAT_INFO" 0x7e int pal_get_plat_sku_id(void){ return 0; // Yosemite V1 } int pal_force_update_bic_fw(uint8_t slot_id, uint8_t comp, char *path) { return bic_update_firmware(slot_id, comp, path, 1); } int pal_get_nic_fru_id(void) { return FRU_NIC; } // OEM Command "CMD_OEM_BYPASS_CMD" 0x34 int pal_bypass_cmd(uint8_t slot, uint8_t *req_data, uint8_t req_len, uint8_t *res_data, uint8_t *res_len){ int ret; int completion_code=CC_UNSPECIFIED_ERROR; uint8_t netfn, cmd, select; uint8_t tlen, rlen; uint8_t tbuf[256] = {0x00}; uint8_t rbuf[256] = {0x00}; uint8_t status; *res_len = 0; if (slot < FRU_SLOT1 || slot > FRU_SLOT4) { return CC_PARAM_OUT_OF_RANGE; } ret = pal_is_fru_prsnt(slot, &status); if (ret < 0) { return -1; } if (status == 0) { return CC_UNSPECIFIED_ERROR; } ret = pal_is_server_12v_on(slot, &status); if(ret < 0 || 0 == status) { return CC_NOT_SUPP_IN_CURR_STATE; } if(!pal_is_slot_server(slot)) { return CC_UNSPECIFIED_ERROR; } select = req_data[0]; switch (select) { case BYPASS_BIC: tlen = req_len - 6; // payload_id, netfn, cmd, data[0] (select), data[1] (bypass netfn), data[2] (bypass cmd) if (tlen < 0) { completion_code = CC_INVALID_LENGTH; break; } netfn = req_data[1]; cmd = req_data[2]; // Bypass command to Bridge IC if (tlen != 0) { ret = bic_ipmb_wrapper(slot, netfn, cmd, &req_data[3], tlen, res_data, res_len); } else { ret = bic_ipmb_wrapper(slot, netfn, cmd, NULL, 0, res_data, res_len); } if (0 == ret) { completion_code = CC_SUCCESS; } break; case BYPASS_ME: tlen = req_len - 6; // payload_id, netfn, cmd, data[0] (select), data[1] (bypass netfn), data[2] (bypass cmd) if (tlen < 0) { completion_code = CC_INVALID_LENGTH; break; } netfn = req_data[1]; cmd = req_data[2]; tlen += 2; memcpy(tbuf, &req_data[1], tlen); tbuf[0] = tbuf[0] << 2; // Bypass command to ME ret = bic_me_xmit(slot, tbuf, tlen, rbuf, &rlen); if (0 == ret) { completion_code = CC_SUCCESS; memcpy(&res_data[0], rbuf, rlen); *res_len = rlen; } break; default: return completion_code; } return completion_code; }
{ "pile_set_name": "Github" }
{ "pagetip":"", "learn":"", "related":{}, "labels":{}, "tooltips":{}, "copy":{"version":"Current platform version:", "upgrade":"Upgrade available:", "no":"No", "yes":"Yes", "launch":"Launch the system update tool" } }
{ "pile_set_name": "Github" }
var vows = require("vows"), assert = require("../assert"), load = require("../load"), projectionTestSuite = require("./projection-test-suite"); var suite = vows.describe("d3.geo.orthographic"); suite.addBatch({ "orthographic": { topic: load("geo/orthographic").expression("d3.geo.orthographic"), "default": projectionTestSuite(function(projection) { return projection(); }, { "Null Island": [[ 0.00000000, 0.00000000], [ 480.00000000, 250.00000000]], "Honolulu, HI": [[ -21.01262744, 82.63349103], [ 473.10377192, 101.23805835]], "San Francisco, CA": [[ -46.16620803, 77.04946507], [ 455.75069916, 103.81541376]], "Svalbard": [[ 3.13977663, 61.55241523], [ 483.91363537, 118.11201123]], "Tierra del Fuego": [[ -35.62300462, -60.29317484], [ 436.70402041, 380.28587327]], "Tokyo": [[ 33.38709832, 79.49539834], [ 495.04895132, 102.51395975]], "the South Pole": [[ 0.00000000, -85.00000000], [ 480.00000000, 399.42920471]], "the North Pole": [[ 0.00000000, 85.00000000], [ 480.00000000, 100.57079529]] }), "translated to 0,0 and at scale 1": projectionTestSuite(function(projection) { return projection().translate([0, 0]).scale(1); }, { "Null Island": [[ 0.00000000, 0.00000000], [ 0.00000000, 0.00000000]], "Honolulu, HI": [[ -21.01262744, 82.63349120], [ -0.04597485, -0.99174628]], "San Francisco, CA": [[ -46.16620803, 77.04946507], [ -0.16166201, -0.97456391]], "Svalbard": [[ 3.13977663, 61.55241523], [ 0.02609090, -0.87925326]], "Tierra del Fuego": [[ -35.62300462, -60.29317484], [ -0.28863986, 0.86857249]], "Tokyo": [[ 33.38709832, 79.49539834], [ 0.10032634, -0.98324027]], "the South Pole": [[ 0.00000000, -85.00000000], [ 0.00000000, 0.99619470]], "the North Pole": [[ 0.00000000, 85.00000000], [ 0.00000000, -0.99619470]] }) } }); suite.export(module);
{ "pile_set_name": "Github" }
# coding=utf-8 ''' Created on 2016-10-12 @author: zhangtiande ''' from rest_framework import serializers from teamvision.auth_extend.user.models import ActionLog from business.auth_user.user_service import UserService import datetime from gatesidelib.datetimehelper import DateTimeHelper class ToDoSummarySerializer(serializers.Serializer): task_count = serializers.IntegerField() issue_count = serializers.IntegerField() fortesting_count = serializers.IntegerField() class Meta: read_only_fields = ('task_count', 'issue_count', 'fortesting_count') def save(self): raise Exception("only get request") class LogActionSerializer(serializers.ModelSerializer): UserName = serializers.SerializerMethodField() ActionTimeStr = serializers.SerializerMethodField() class Meta: model = ActionLog fields = '__all__' # read_only_fields = ('task_count', 'issue_count', 'fortesting_count') def get_UserName(self,obj): user = UserService.get_user(obj.User) result = '系统' if user: user_name = user.last_name + user.first_name if len(user_name) >= 3: result = user_name[1:] else: result = user_name return result def get_ActionTimeStr(self,obj): now= datetime.datetime.strptime(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),"%Y-%m-%d %H:%M:%S") action_time=datetime.datetime.strptime(obj.ActionTime.strftime("%Y-%m-%d %H:%M:%S"),"%Y-%m-%d %H:%M:%S") action_time=action_time + datetime.timedelta(hours=8) time_internal=(now-action_time).total_seconds() return DateTimeHelper.how_long_ago(time_internal) def save(self): raise Exception("only get request")
{ "pile_set_name": "Github" }
<?php /** * Mockery * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://github.com/padraic/mockery/blob/master/LICENSE * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to padraic@php.net so we can send you a copy immediately. * * @category Mockery * @package Mockery * @copyright Copyright (c) 2010-2014 Pádraic Brady (http://blog.astrumfutura.com) * @license http://github.com/padraic/mockery/blob/master/LICENSE New BSD License */ namespace Mockery; use Mockery\Generator\Generator; use Mockery\Generator\MockConfigurationBuilder; use Mockery\Loader\Loader as LoaderInterface; class Container { const BLOCKS = \Mockery::BLOCKS; /** * Store of mock objects * * @var array */ protected $_mocks = array(); /** * Order number of allocation * * @var int */ protected $_allocatedOrder = 0; /** * Current ordered number * * @var int */ protected $_currentOrder = 0; /** * Ordered groups * * @var array */ protected $_groups = array(); /** * @var Generator\Generator */ protected $_generator; /** * @var LoaderInterface */ protected $_loader; /** * @var array */ protected $_namedMocks = array(); public function __construct(Generator $generator = null, LoaderInterface $loader = null) { $this->_generator = $generator ?: \Mockery::getDefaultGenerator(); $this->_loader = $loader ?: \Mockery::getDefaultLoader(); } /** * Generates a new mock object for this container * * I apologies in advance for this. A God Method just fits the API which * doesn't require differentiating between classes, interfaces, abstracts, * names or partials - just so long as it's something that can be mocked. * I'll refactor it one day so it's easier to follow. * * @throws Exception\RuntimeException * @throws Exception * @return \Mockery\Mock */ public function mock() { $expectationClosure = null; $quickdefs = array(); $constructorArgs = null; $blocks = array(); $args = func_get_args(); if (count($args) > 1) { $finalArg = end($args); reset($args); if (is_callable($finalArg) && is_object($finalArg)) { $expectationClosure = array_pop($args); } } $builder = new MockConfigurationBuilder(); foreach ($args as $k => $arg) { if ($arg instanceof MockConfigurationBuilder) { $builder = $arg; unset($args[$k]); } } reset($args); $builder->setParameterOverrides(\Mockery::getConfiguration()->getInternalClassMethodParamMaps()); while (count($args) > 0) { $arg = current($args); // check for multiple interfaces if (is_string($arg) && strpos($arg, ',') && !strpos($arg, ']')) { $interfaces = explode(',', str_replace(' ', '', $arg)); foreach ($interfaces as $i) { if (!interface_exists($i, true) && !class_exists($i, true)) { throw new \Mockery\Exception( 'Class name follows the format for defining multiple' . ' interfaces, however one or more of the interfaces' . ' do not exist or are not included, or the base class' . ' (which you may omit from the mock definition) does not exist' ); } } $builder->addTargets($interfaces); array_shift($args); continue; } elseif (is_string($arg) && substr($arg, 0, 6) == 'alias:') { $name = array_shift($args); $name = str_replace('alias:', '', $name); $builder->addTarget('stdClass'); $builder->setName($name); continue; } elseif (is_string($arg) && substr($arg, 0, 9) == 'overload:') { $name = array_shift($args); $name = str_replace('overload:', '', $name); $builder->setInstanceMock(true); $builder->addTarget('stdClass'); $builder->setName($name); continue; } elseif (is_string($arg) && substr($arg, strlen($arg)-1, 1) == ']') { $parts = explode('[', $arg); if (!class_exists($parts[0], true) && !interface_exists($parts[0], true)) { throw new \Mockery\Exception('Can only create a partial mock from' . ' an existing class or interface'); } $class = $parts[0]; $parts[1] = str_replace(' ', '', $parts[1]); $partialMethods = explode(',', strtolower(rtrim($parts[1], ']'))); $builder->addTarget($class); $builder->setWhiteListedMethods($partialMethods); array_shift($args); continue; } elseif (is_string($arg) && (class_exists($arg, true) || interface_exists($arg, true))) { $class = array_shift($args); $builder->addTarget($class); continue; } elseif (is_string($arg)) { $class = array_shift($args); $builder->addTarget($class); continue; } elseif (is_object($arg)) { $partial = array_shift($args); $builder->addTarget($partial); continue; } elseif (is_array($arg) && !empty($arg) && array_keys($arg) !== range(0, count($arg) - 1)) { // if associative array if (array_key_exists(self::BLOCKS, $arg)) { $blocks = $arg[self::BLOCKS]; } unset($arg[self::BLOCKS]); $quickdefs = array_shift($args); continue; } elseif (is_array($arg)) { $constructorArgs = array_shift($args); continue; } throw new \Mockery\Exception( 'Unable to parse arguments sent to ' . get_class($this) . '::mock()' ); } $builder->addBlackListedMethods($blocks); if (!is_null($constructorArgs)) { $builder->addBlackListedMethod("__construct"); // we need to pass through } if (!empty($partialMethods) && $constructorArgs === null) { $constructorArgs = array(); } $config = $builder->getMockConfiguration(); $this->checkForNamedMockClashes($config); $def = $this->getGenerator()->generate($config); if (class_exists($def->getClassName(), $attemptAutoload = false)) { $rfc = new \ReflectionClass($def->getClassName()); if (!$rfc->implementsInterface("Mockery\MockInterface")) { throw new \Mockery\Exception\RuntimeException("Could not load mock {$def->getClassName()}, class already exists"); } } $this->getLoader()->load($def); $mock = $this->_getInstance($def->getClassName(), $constructorArgs); $mock->mockery_init($this, $config->getTargetObject()); if (!empty($quickdefs)) { $mock->shouldReceive($quickdefs)->byDefault(); } if (!empty($expectationClosure)) { $expectationClosure($mock); } $this->rememberMock($mock); return $mock; } public function instanceMock() { } public function getLoader() { return $this->_loader; } public function getGenerator() { return $this->_generator; } /** * @param string $method * @return string|null */ public function getKeyOfDemeterMockFor($method) { $keys = array_keys($this->_mocks); $match = preg_grep("/__demeter_{$method}$/", $keys); if (count($match) == 1) { $res = array_values($match); if (count($res) > 0) { return $res[0]; } } return null; } /** * @return array */ public function getMocks() { return $this->_mocks; } /** * Tear down tasks for this container * * @throws \Exception * @return void */ public function mockery_teardown() { try { $this->mockery_verify(); } catch (\Exception $e) { $this->mockery_close(); throw $e; } } /** * Verify the container mocks * * @return void */ public function mockery_verify() { foreach ($this->_mocks as $mock) { $mock->mockery_verify(); } } /** * Reset the container to its original state * * @return void */ public function mockery_close() { foreach ($this->_mocks as $mock) { $mock->mockery_teardown(); } $this->_mocks = array(); } /** * Fetch the next available allocation order number * * @return int */ public function mockery_allocateOrder() { $this->_allocatedOrder += 1; return $this->_allocatedOrder; } /** * Set ordering for a group * * @param mixed $group * @param int $order */ public function mockery_setGroup($group, $order) { $this->_groups[$group] = $order; } /** * Fetch array of ordered groups * * @return array */ public function mockery_getGroups() { return $this->_groups; } /** * Set current ordered number * * @param int $order * @return int The current order number that was set */ public function mockery_setCurrentOrder($order) { $this->_currentOrder = $order; return $this->_currentOrder; } /** * Get current ordered number * * @return int */ public function mockery_getCurrentOrder() { return $this->_currentOrder; } /** * Validate the current mock's ordering * * @param string $method * @param int $order * @throws \Mockery\Exception * @return void */ public function mockery_validateOrder($method, $order, \Mockery\MockInterface $mock) { if ($order < $this->_currentOrder) { $exception = new \Mockery\Exception\InvalidOrderException( 'Method ' . $method . ' called out of order: expected order ' . $order . ', was ' . $this->_currentOrder ); $exception->setMock($mock) ->setMethodName($method) ->setExpectedOrder($order) ->setActualOrder($this->_currentOrder); throw $exception; } $this->mockery_setCurrentOrder($order); } /** * Gets the count of expectations on the mocks * * @return int */ public function mockery_getExpectationCount() { $count = 0; foreach ($this->_mocks as $mock) { $count += $mock->mockery_getExpectationCount(); } return $count; } /** * Store a mock and set its container reference * * @param \Mockery\Mock * @return \Mockery\Mock */ public function rememberMock(\Mockery\MockInterface $mock) { if (!isset($this->_mocks[get_class($mock)])) { $this->_mocks[get_class($mock)] = $mock; } else { /** * This condition triggers for an instance mock where origin mock * is already remembered */ $this->_mocks[] = $mock; } return $mock; } /** * Retrieve the last remembered mock object, which is the same as saying * retrieve the current mock being programmed where you have yet to call * mock() to change it - thus why the method name is "self" since it will be * be used during the programming of the same mock. * * @return \Mockery\Mock */ public function self() { $mocks = array_values($this->_mocks); $index = count($mocks) - 1; return $mocks[$index]; } /** * Return a specific remembered mock according to the array index it * was stored to in this container instance * * @return \Mockery\Mock */ public function fetchMock($reference) { if (isset($this->_mocks[$reference])) { return $this->_mocks[$reference]; } } protected function _getInstance($mockName, $constructorArgs = null) { if ($constructorArgs !== null) { $r = new \ReflectionClass($mockName); return $r->newInstanceArgs($constructorArgs); } try { $instantiator = new Instantiator; $instance = $instantiator->instantiate($mockName); } catch (\Exception $ex) { $internalMockName = $mockName . '_Internal'; if (!class_exists($internalMockName)) { eval("class $internalMockName extends $mockName {" . 'public function __construct() {}' . '}'); } $instance = new $internalMockName(); } return $instance; } /** * Takes a class name and declares it * * @param string $fqcn */ public function declareClass($fqcn) { if (false !== strpos($fqcn, '/')) { throw new \Mockery\Exception( 'Class name contains a forward slash instead of backslash needed ' . 'when employing namespaces' ); } if (false !== strpos($fqcn, "\\")) { $parts = array_filter(explode("\\", $fqcn), function ($part) { return $part !== ""; }); $cl = array_pop($parts); $ns = implode("\\", $parts); eval(" namespace $ns { class $cl {} }"); } else { eval(" class $fqcn {} "); } } protected function checkForNamedMockClashes($config) { $name = $config->getName(); if (!$name) { return; } $hash = $config->getHash(); if (isset($this->_namedMocks[$name])) { if ($hash !== $this->_namedMocks[$name]) { throw new \Mockery\Exception( "The mock named '$name' has been already defined with a different mock configuration" ); } } $this->_namedMocks[$name] = $hash; } }
{ "pile_set_name": "Github" }
Car -1 -1 -10 492 176 551 222 1.45 1.63 3.74 -3.00 1.59 24.91 -1.58 1.00 Car -1 -1 -10 134 184 337 281 1.39 1.59 3.69 -6.30 1.62 12.55 -1.56 1.00 Car -1 -1 -10 556 173 580 193 1.38 1.60 3.67 -3.10 1.47 53.63 -1.59 0.73
{ "pile_set_name": "Github" }
<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> <jsp:useBean id="conn" scope="page" class="com.tools.ConnDB"/> <jsp:useBean id="del_goods" scope="page" class="com.dao.GoodsDaoImpl"/> <jsp:useBean id="goods" scope="page" class="com.model.Goods"> <jsp:setProperty name="goods" property="*"/> </jsp:useBean> <jsp:include page="safe.jsp"/> <% Integer id=goods.getID(); ResultSet rs=conn.executeQuery("select * from tb_goods where ID="+id); if (!rs.next()){ out.println("<script language='javascript'>alert('您的操作有误!');window.location.href='index.jsp';</script>"); }else{ int ret=0; ret=del_goods.delete(goods); if (ret!=0){ out.println("<script language='javascript'>alert('商品信息删除成功!');window.location.href='index.jsp';</script>"); }else{ out.println("<script language='javascript'>alert('该商品信息不能删除!');window.location.href='index.jsp';</script>"); } } %>
{ "pile_set_name": "Github" }
[ { "__type__": "cc.Prefab", "_name": "", "_objFlags": 0, "_rawFiles": null, "data": { "__id__": 1 } }, { "__type__": "cc.Node", "_name": "chat", "_objFlags": 0, "_parent": null, "_children": [ { "__id__": 2 }, { "__id__": 16 }, { "__id__": 20 } ], "_tag": -1, "_active": true, "_components": [ { "__id__": 70 }, { "__id__": 71 } ], "_prefab": { "__id__": 72 }, "_id": "", "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0 }, "_contentSize": { "__type__": "cc.Size", "width": 710, "height": 50 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_opacityModifyRGB": false, "groupIndex": 0, "_trs": { "__type__": "TypedArray", "ctor": "Float64Array", "array": [ 0, 0, 0, 0, 0, 0, 1, 1, 1, 1 ] } }, { "__type__": "cc.Node", "_name": "New ScrollView", "_objFlags": 0, "_parent": { "__id__": 1 }, "_children": [ { "__id__": 3 } ], "_tag": -1, "_active": true, "_components": [ { "__id__": 13 }, { "__id__": 14 } ], "_prefab": { "__id__": 15 }, "_id": "", "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 184, "g": 184, "b": 184, "a": 255 }, "_cascadeOpacityEnabled": true, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 1 }, "_contentSize": { "__type__": "cc.Size", "width": 710, "height": 50 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_opacityModifyRGB": false, "groupIndex": 0, "_trs": { "__type__": "TypedArray", "ctor": "Float64Array", "array": [ 0, 50, 0, 0, 0, 0, 1, 1, 1, 1 ] } }, { "__type__": "cc.Node", "_name": "view", "_objFlags": 0, "_parent": { "__id__": 2 }, "_children": [ { "__id__": 4 } ], "_tag": -1, "_active": true, "_components": [ { "__id__": 10 }, { "__id__": 11 } ], "_prefab": { "__id__": 12 }, "_id": "", "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 1 }, "_contentSize": { "__type__": "cc.Size", "width": 710, "height": 50 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_opacityModifyRGB": false, "groupIndex": 0, "_trs": { "__type__": "TypedArray", "ctor": "Float64Array", "array": [ 0, 0, 0, 0, 0, 0, 1, 1, 1, 1 ] } }, { "__type__": "cc.Node", "_name": "content", "_objFlags": 0, "_parent": { "__id__": 3 }, "_children": [ { "__id__": 5 } ], "_tag": -1, "_active": true, "_components": [ { "__id__": 8 } ], "_prefab": { "__id__": 9 }, "_id": "", "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 1 }, "_contentSize": { "__type__": "cc.Size", "width": 710, "height": 0 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_opacityModifyRGB": false, "groupIndex": 0, "_trs": { "__type__": "TypedArray", "ctor": "Float64Array", "array": [ 0, 0, 0, 0, 0, 0, 1, 1, 1, 1 ] } }, { "__type__": "cc.Node", "_name": "msgList", "_objFlags": 0, "_parent": { "__id__": 4 }, "_children": [], "_tag": -1, "_active": false, "_components": [ { "__id__": 6 } ], "_prefab": { "__id__": 7 }, "_id": "", "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 60, "height": 50 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_opacityModifyRGB": false, "groupIndex": 0, "_trs": { "__type__": "TypedArray", "ctor": "Float64Array", "array": [ -347, -25, 0, 0, 0, 0, 1, 1, 1, 1 ] } }, { "__type__": "cc.RichText", "_name": "", "_objFlags": 0, "node": { "__id__": 5 }, "_enabled": true, "_N$string": "消息", "_N$horizontalAlign": 0, "_N$fontSize": 30, "_N$font": { "__uuid__": "2d93ecdd-494e-4300-957e-12aadf2768ab" }, "_N$maxWidth": 0, "_N$lineHeight": 50, "_N$imageAtlas": { "__uuid__": "7e99e95a-d168-4b19-85dd-3c1f0460fd1f" }, "_N$handleTouchEvent": true }, { "__type__": "cc.PrefabInfo", "root": { "__id__": 1 }, "asset": { "__uuid__": "f4063441-0794-4c5e-8778-f584d4f58c94" }, "fileId": "95Sb9vvpBLRonqCySGSydD", "sync": false }, { "__type__": "cc.Layout", "_name": "", "_objFlags": 0, "node": { "__id__": 4 }, "_enabled": true, "_layoutSize": { "__type__": "cc.Size", "width": 710, "height": 0 }, "_resize": 1, "_N$layoutType": 2, "_N$padding": 0, "_N$cellSize": { "__type__": "cc.Size", "width": 40, "height": 40 }, "_N$startAxis": 0, "_N$paddingLeft": 0, "_N$paddingRight": 0, "_N$paddingTop": 0, "_N$paddingBottom": 0, "_N$spacingX": 0, "_N$spacingY": 0, "_N$verticalDirection": 0, "_N$horizontalDirection": 0 }, { "__type__": "cc.PrefabInfo", "root": { "__id__": 1 }, "asset": { "__uuid__": "f4063441-0794-4c5e-8778-f584d4f58c94" }, "fileId": "5bBQWVHB5E2KfaS4aOG2un", "sync": false }, { "__type__": "cc.Mask", "_name": "", "_objFlags": 0, "node": { "__id__": 3 }, "_enabled": true, "_type": 0, "_segements": 64, "_N$spriteFrame": null, "_N$alphaThreshold": 1, "_N$inverted": false }, { "__type__": "cc.Widget", "_name": "", "_objFlags": 0, "node": { "__id__": 3 }, "_enabled": true, "isAlignOnce": false, "_target": null, "_alignFlags": 5, "_left": 0, "_right": 0, "_top": 0, "_bottom": 0, "_verticalCenter": 0, "_horizontalCenter": 0, "_isAbsLeft": true, "_isAbsRight": true, "_isAbsTop": true, "_isAbsBottom": true, "_isAbsHorizontalCenter": true, "_isAbsVerticalCenter": true, "_originalWidth": 0, "_originalHeight": 65 }, { "__type__": "cc.PrefabInfo", "root": { "__id__": 1 }, "asset": { "__uuid__": "f4063441-0794-4c5e-8778-f584d4f58c94" }, "fileId": "d9u3et8eFGhZcqtInSYRBW", "sync": false }, { "__type__": "cc.ScrollView", "_name": "", "_objFlags": 0, "node": { "__id__": 2 }, "_enabled": true, "content": { "__id__": 4 }, "horizontal": false, "vertical": true, "inertia": true, "brake": 0.75, "elastic": true, "bounceDuration": 0.23, "scrollEvents": [], "cancelInnerEvents": true, "_N$horizontalScrollBar": null, "_N$verticalScrollBar": null }, { "__type__": "cc.Widget", "_name": "", "_objFlags": 0, "node": { "__id__": 2 }, "_enabled": true, "isAlignOnce": false, "_target": null, "_alignFlags": 5, "_left": 0, "_right": 0, "_top": 0, "_bottom": 0, "_verticalCenter": 0, "_horizontalCenter": 0, "_isAbsLeft": true, "_isAbsRight": true, "_isAbsTop": true, "_isAbsBottom": true, "_isAbsHorizontalCenter": true, "_isAbsVerticalCenter": true, "_originalWidth": 0, "_originalHeight": 65 }, { "__type__": "cc.PrefabInfo", "root": { "__id__": 1 }, "asset": { "__uuid__": "f4063441-0794-4c5e-8778-f584d4f58c94" }, "fileId": "76gE2Um05OhKpVMIOiDX5i", "sync": false }, { "__type__": "cc.Node", "_name": "btnArrow", "_objFlags": 0, "_parent": { "__id__": 1 }, "_children": [], "_tag": -1, "_active": true, "_components": [ { "__id__": 17 }, { "__id__": 18 } ], "_prefab": { "__id__": 19 }, "_id": "", "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 80, "height": 80 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_opacityModifyRGB": false, "groupIndex": 0, "_trs": { "__type__": "TypedArray", "ctor": "Float64Array", "array": [ 320, 26, 0, 0, 0, 0, 1, 1, 1, 1 ] } }, { "__type__": "cc.Sprite", "_name": "", "_objFlags": 0, "node": { "__id__": 16 }, "_enabled": true, "_spriteFrame": { "__uuid__": "16083852-e7d4-4859-8d27-7da66bb94803" }, "_type": 0, "_sizeMode": 2, "_fillType": 0, "_fillCenter": { "__type__": "cc.Vec2", "x": 0, "y": 0 }, "_fillStart": 0, "_fillRange": 0, "_isTrimmedMode": false, "_srcBlendFactor": 770, "_dstBlendFactor": 771, "_atlas": null }, { "__type__": "cc.Button", "_name": "", "_objFlags": 0, "node": { "__id__": 16 }, "_enabled": true, "transition": 0, "pressedColor": { "__type__": "cc.Color", "r": 211, "g": 211, "b": 211, "a": 255 }, "hoverColor": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "duration": 0.1, "zoomScale": 1.2, "clickEvents": [], "_N$interactable": true, "_N$enableAutoGrayEffect": false, "_N$normalColor": { "__type__": "cc.Color", "r": 214, "g": 214, "b": 214, "a": 255 }, "_N$disabledColor": { "__type__": "cc.Color", "r": 124, "g": 124, "b": 124, "a": 255 }, "_N$normalSprite": null, "_N$pressedSprite": null, "pressedSprite": null, "_N$hoverSprite": null, "hoverSprite": null, "_N$disabledSprite": null, "_N$target": { "__id__": 16 } }, { "__type__": "cc.PrefabInfo", "root": { "__id__": 1 }, "asset": { "__uuid__": "f4063441-0794-4c5e-8778-f584d4f58c94" }, "fileId": "a1qlvv3YhB0LQbEeP2w+6d", "sync": false }, { "__type__": "cc.Node", "_name": "chatView", "_objFlags": 0, "_parent": { "__id__": 1 }, "_children": [ { "__id__": 21 }, { "__id__": 24 }, { "__id__": 27 }, { "__id__": 34 }, { "__id__": 38 } ], "_tag": -1, "_active": false, "_components": [ { "__id__": 67 }, { "__id__": 68 } ], "_prefab": { "__id__": 69 }, "_id": "", "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 0, "height": 0 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_opacityModifyRGB": false, "groupIndex": 0, "_trs": { "__type__": "TypedArray", "ctor": "Float64Array", "array": [ 0, 69, 0, 0, 0, 0, 1, 1, 1, 1 ] } }, { "__type__": "cc.Node", "_name": "bg_chatEditBox", "_objFlags": 0, "_parent": { "__id__": 20 }, "_children": [], "_tag": -1, "_active": true, "_components": [ { "__id__": 22 } ], "_prefab": { "__id__": 23 }, "_id": "", "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 640, "height": 62 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_opacityModifyRGB": false, "groupIndex": 0, "_trs": { "__type__": "TypedArray", "ctor": "Float64Array", "array": [ 35, 28, 0, 0, 0, 0, 1, 1, 1, 1 ] } }, { "__type__": "cc.Sprite", "_name": "", "_objFlags": 0, "node": { "__id__": 21 }, "_enabled": true, "_spriteFrame": { "__uuid__": "fec9a2b7-bb60-418e-ae0b-fb410823c97a" }, "_type": 1, "_sizeMode": 0, "_fillType": 0, "_fillCenter": { "__type__": "cc.Vec2", "x": 0, "y": 0 }, "_fillStart": 0, "_fillRange": 0, "_isTrimmedMode": true, "_srcBlendFactor": 770, "_dstBlendFactor": 771, "_atlas": null }, { "__type__": "cc.PrefabInfo", "root": { "__id__": 1 }, "asset": { "__uuid__": "f4063441-0794-4c5e-8778-f584d4f58c94" }, "fileId": "65vvqnZOJOCIES34PFCg9q", "sync": false }, { "__type__": "cc.Node", "_name": "editBox", "_objFlags": 0, "_parent": { "__id__": 20 }, "_children": [], "_tag": -1, "_active": true, "_components": [ { "__id__": 25 } ], "_prefab": { "__id__": 26 }, "_id": "", "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 525, "height": 62 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_opacityModifyRGB": false, "groupIndex": 0, "_trs": { "__type__": "TypedArray", "ctor": "Float64Array", "array": [ -13, 28, 0, 0, 0, 0, 1, 1, 1, 1 ] } }, { "__type__": "cc.EditBox", "_name": "", "_objFlags": 0, "node": { "__id__": 24 }, "_enabled": true, "_useOriginalSize": false, "_string": "", "_tabIndex": 0, "editingDidBegan": [], "textChanged": [], "editingDidEnded": [], "editingReturn": [], "_N$backgroundImage": null, "_N$returnType": 0, "_N$inputFlag": 5, "_N$inputMode": 6, "_N$fontSize": 32, "_N$lineHeight": 40, "_N$fontColor": { "__type__": "cc.Color", "r": 53, "g": 224, "b": 248, "a": 255 }, "_N$placeholder": "请输入信息[30个字以内]", "_N$placeholderFontSize": 32, "_N$placeholderFontColor": { "__type__": "cc.Color", "r": 24, "g": 177, "b": 199, "a": 255 }, "_N$maxLength": 30, "_N$stayOnTop": false }, { "__type__": "cc.PrefabInfo", "root": { "__id__": 1 }, "asset": { "__uuid__": "f4063441-0794-4c5e-8778-f584d4f58c94" }, "fileId": "0aCJsO3IRBeaGSHoavkPl9", "sync": false }, { "__type__": "cc.Node", "_name": "btnSend", "_objFlags": 0, "_parent": { "__id__": 20 }, "_children": [ { "__id__": 28 } ], "_tag": -1, "_active": true, "_components": [ { "__id__": 31 }, { "__id__": 32 } ], "_prefab": { "__id__": 33 }, "_id": "", "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 240, "g": 50, "b": 14, "a": 255 }, "_cascadeOpacityEnabled": true, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 100, "height": 52 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_opacityModifyRGB": false, "groupIndex": 0, "_trs": { "__type__": "TypedArray", "ctor": "Float64Array", "array": [ 300, 28, 0, 0, 0, 0, 1, 1, 1, 1 ] } }, { "__type__": "cc.Node", "_name": "New Label", "_objFlags": 0, "_parent": { "__id__": 27 }, "_children": [], "_tag": -1, "_active": true, "_components": [ { "__id__": 29 } ], "_prefab": { "__id__": 30 }, "_id": "", "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 74.66, "height": 32 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_opacityModifyRGB": false, "groupIndex": 0, "_trs": { "__type__": "TypedArray", "ctor": "Float64Array", "array": [ 0, 0, 0, 0, 0, 0, 1, 1, 1, 1 ] } }, { "__type__": "cc.Label", "_name": "", "_objFlags": 0, "node": { "__id__": 28 }, "_enabled": true, "_useOriginalSize": false, "_actualFontSize": 32, "_fontSize": 32, "_lineHeight": 32, "_enableWrapText": true, "_N$file": { "__uuid__": "2d93ecdd-494e-4300-957e-12aadf2768ab" }, "_isSystemFontUsed": false, "_spacingX": 0, "_N$string": "发 送", "_N$horizontalAlign": 1, "_N$verticalAlign": 1, "_N$fontFamily": "Arial", "_N$overflow": 0 }, { "__type__": "cc.PrefabInfo", "root": { "__id__": 1 }, "asset": { "__uuid__": "f4063441-0794-4c5e-8778-f584d4f58c94" }, "fileId": "1d6io8qe1NIrGvtWjV1UDJ", "sync": false }, { "__type__": "cc.Sprite", "_name": "", "_objFlags": 0, "node": { "__id__": 27 }, "_enabled": true, "_spriteFrame": { "__uuid__": "a23235d1-15db-4b95-8439-a2e005bfff91" }, "_type": 0, "_sizeMode": 0, "_fillType": 0, "_fillCenter": { "__type__": "cc.Vec2", "x": 0, "y": 0 }, "_fillStart": 0, "_fillRange": 0, "_isTrimmedMode": true, "_srcBlendFactor": 770, "_dstBlendFactor": 771, "_atlas": null }, { "__type__": "cc.Button", "_name": "", "_objFlags": 0, "node": { "__id__": 27 }, "_enabled": true, "transition": 1, "pressedColor": { "__type__": "cc.Color", "r": 216, "g": 40, "b": 7, "a": 255 }, "hoverColor": { "__type__": "cc.Color", "r": 252, "g": 70, "b": 35, "a": 255 }, "duration": 0.1, "zoomScale": 1.2, "clickEvents": [], "_N$interactable": true, "_N$enableAutoGrayEffect": false, "_N$normalColor": { "__type__": "cc.Color", "r": 240, "g": 50, "b": 14, "a": 255 }, "_N$disabledColor": { "__type__": "cc.Color", "r": 124, "g": 124, "b": 124, "a": 255 }, "_N$normalSprite": null, "_N$pressedSprite": null, "pressedSprite": null, "_N$hoverSprite": null, "hoverSprite": null, "_N$disabledSprite": null, "_N$target": { "__id__": 27 } }, { "__type__": "cc.PrefabInfo", "root": { "__id__": 1 }, "asset": { "__uuid__": "f4063441-0794-4c5e-8778-f584d4f58c94" }, "fileId": "a5dUzWvjFJNbe7mTIPNDuH", "sync": false }, { "__type__": "cc.Node", "_name": "btnExpression", "_objFlags": 0, "_parent": { "__id__": 20 }, "_children": [], "_tag": -1, "_active": true, "_components": [ { "__id__": 35 }, { "__id__": 36 } ], "_prefab": { "__id__": 37 }, "_id": "", "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 104, "height": 104 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_opacityModifyRGB": false, "groupIndex": 0, "_trs": { "__type__": "TypedArray", "ctor": "Float64Array", "array": [ -321, 25, 0, 0, 0, 0, 1, 0.8, 0.8, 1 ] } }, { "__type__": "cc.Sprite", "_name": "", "_objFlags": 0, "node": { "__id__": 34 }, "_enabled": true, "_spriteFrame": { "__uuid__": "20e45d0a-cb4c-4c87-bde4-467cb22553aa" }, "_type": 0, "_sizeMode": 2, "_fillType": 0, "_fillCenter": { "__type__": "cc.Vec2", "x": 0, "y": 0 }, "_fillStart": 0, "_fillRange": 0, "_isTrimmedMode": false, "_srcBlendFactor": 770, "_dstBlendFactor": 771, "_atlas": { "__uuid__": "7e99e95a-d168-4b19-85dd-3c1f0460fd1f" } }, { "__type__": "cc.Button", "_name": "", "_objFlags": 0, "node": { "__id__": 34 }, "_enabled": true, "transition": 3, "pressedColor": { "__type__": "cc.Color", "r": 211, "g": 211, "b": 211, "a": 255 }, "hoverColor": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "duration": 0.1, "zoomScale": 1.1, "clickEvents": [], "_N$interactable": true, "_N$enableAutoGrayEffect": false, "_N$normalColor": { "__type__": "cc.Color", "r": 214, "g": 214, "b": 214, "a": 255 }, "_N$disabledColor": { "__type__": "cc.Color", "r": 124, "g": 124, "b": 124, "a": 255 }, "_N$normalSprite": null, "_N$pressedSprite": null, "pressedSprite": null, "_N$hoverSprite": null, "hoverSprite": null, "_N$disabledSprite": null, "_N$target": { "__id__": 34 } }, { "__type__": "cc.PrefabInfo", "root": { "__id__": 1 }, "asset": { "__uuid__": "f4063441-0794-4c5e-8778-f584d4f58c94" }, "fileId": "55A/BkmjtNzrc/3WuTb+sb", "sync": false }, { "__type__": "cc.Node", "_name": "bgExpression", "_objFlags": 0, "_parent": { "__id__": 20 }, "_children": [ { "__id__": 39 }, { "__id__": 42 }, { "__id__": 45 }, { "__id__": 48 }, { "__id__": 51 }, { "__id__": 54 }, { "__id__": 57 }, { "__id__": 60 } ], "_tag": -1, "_active": false, "_components": [ { "__id__": 63 }, { "__id__": 64 }, { "__id__": 65 } ], "_prefab": { "__id__": 66 }, "_id": "", "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 786, "height": 120 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_opacityModifyRGB": false, "groupIndex": 0, "_trs": { "__type__": "TypedArray", "ctor": "Float64Array", "array": [ 0, 120, 0, 0, 0, 0, 1, 0.9, 0.9, 1 ] } }, { "__type__": "cc.Node", "_name": "[笑]", "_objFlags": 0, "_parent": { "__id__": 38 }, "_children": [], "_tag": -1, "_active": true, "_components": [ { "__id__": 40 } ], "_prefab": { "__id__": 41 }, "_id": "", "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 104, "height": 104 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_opacityModifyRGB": false, "groupIndex": 0, "_trs": { "__type__": "TypedArray", "ctor": "Float64Array", "array": [ -331, -3, 0, 0, 0, 0, 1, 1, 1, 1 ] } }, { "__type__": "cc.Sprite", "_name": "", "_objFlags": 0, "node": { "__id__": 39 }, "_enabled": true, "_spriteFrame": { "__uuid__": "20e45d0a-cb4c-4c87-bde4-467cb22553aa" }, "_type": 0, "_sizeMode": 2, "_fillType": 0, "_fillCenter": { "__type__": "cc.Vec2", "x": 0, "y": 0 }, "_fillStart": 0, "_fillRange": 0, "_isTrimmedMode": false, "_srcBlendFactor": 770, "_dstBlendFactor": 771, "_atlas": { "__uuid__": "7e99e95a-d168-4b19-85dd-3c1f0460fd1f" } }, { "__type__": "cc.PrefabInfo", "root": { "__id__": 1 }, "asset": { "__uuid__": "f4063441-0794-4c5e-8778-f584d4f58c94" }, "fileId": "64tHTScLBIL5qKR0QsG7vB", "sync": false }, { "__type__": "cc.Node", "_name": "[哭]", "_objFlags": 0, "_parent": { "__id__": 38 }, "_children": [], "_tag": -1, "_active": true, "_components": [ { "__id__": 43 } ], "_prefab": { "__id__": 44 }, "_id": "", "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 104, "height": 104 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_opacityModifyRGB": false, "groupIndex": 0, "_trs": { "__type__": "TypedArray", "ctor": "Float64Array", "array": [ -235, -3, 0, 0, 0, 0, 1, 1, 1, 1 ] } }, { "__type__": "cc.Sprite", "_name": "", "_objFlags": 0, "node": { "__id__": 42 }, "_enabled": true, "_spriteFrame": { "__uuid__": "489258a6-9f52-46eb-87d2-f6b6e74e1a16" }, "_type": 0, "_sizeMode": 2, "_fillType": 0, "_fillCenter": { "__type__": "cc.Vec2", "x": 0, "y": 0 }, "_fillStart": 0, "_fillRange": 0, "_isTrimmedMode": false, "_srcBlendFactor": 770, "_dstBlendFactor": 771, "_atlas": { "__uuid__": "7e99e95a-d168-4b19-85dd-3c1f0460fd1f" } }, { "__type__": "cc.PrefabInfo", "root": { "__id__": 1 }, "asset": { "__uuid__": "f4063441-0794-4c5e-8778-f584d4f58c94" }, "fileId": "24rAqrEJZPa5NkoHvpymfA", "sync": false }, { "__type__": "cc.Node", "_name": "[色]", "_objFlags": 0, "_parent": { "__id__": 38 }, "_children": [], "_tag": -1, "_active": true, "_components": [ { "__id__": 46 } ], "_prefab": { "__id__": 47 }, "_id": "", "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 104, "height": 104 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_opacityModifyRGB": false, "groupIndex": 0, "_trs": { "__type__": "TypedArray", "ctor": "Float64Array", "array": [ -139, -3, 0, 0, 0, 0, 1, 1, 1, 1 ] } }, { "__type__": "cc.Sprite", "_name": "", "_objFlags": 0, "node": { "__id__": 45 }, "_enabled": true, "_spriteFrame": { "__uuid__": "848e334e-722a-4588-aab6-03c812f196bf" }, "_type": 0, "_sizeMode": 2, "_fillType": 0, "_fillCenter": { "__type__": "cc.Vec2", "x": 0, "y": 0 }, "_fillStart": 0, "_fillRange": 0, "_isTrimmedMode": false, "_srcBlendFactor": 770, "_dstBlendFactor": 771, "_atlas": { "__uuid__": "7e99e95a-d168-4b19-85dd-3c1f0460fd1f" } }, { "__type__": "cc.PrefabInfo", "root": { "__id__": 1 }, "asset": { "__uuid__": "f4063441-0794-4c5e-8778-f584d4f58c94" }, "fileId": "47/33NeS5LkYJwSWE0oNnX", "sync": false }, { "__type__": "cc.Node", "_name": "[汗]", "_objFlags": 0, "_parent": { "__id__": 38 }, "_children": [], "_tag": -1, "_active": true, "_components": [ { "__id__": 49 } ], "_prefab": { "__id__": 50 }, "_id": "", "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 104, "height": 104 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_opacityModifyRGB": false, "groupIndex": 0, "_trs": { "__type__": "TypedArray", "ctor": "Float64Array", "array": [ -43, -3, 0, 0, 0, 0, 1, 1, 1, 1 ] } }, { "__type__": "cc.Sprite", "_name": "", "_objFlags": 0, "node": { "__id__": 48 }, "_enabled": true, "_spriteFrame": { "__uuid__": "437c0af9-ba74-4e16-b09f-74c4181a616e" }, "_type": 0, "_sizeMode": 2, "_fillType": 0, "_fillCenter": { "__type__": "cc.Vec2", "x": 0, "y": 0 }, "_fillStart": 0, "_fillRange": 0, "_isTrimmedMode": false, "_srcBlendFactor": 770, "_dstBlendFactor": 771, "_atlas": { "__uuid__": "7e99e95a-d168-4b19-85dd-3c1f0460fd1f" } }, { "__type__": "cc.PrefabInfo", "root": { "__id__": 1 }, "asset": { "__uuid__": "f4063441-0794-4c5e-8778-f584d4f58c94" }, "fileId": "ddB8Rq8YVIiaPyrOXk/dFP", "sync": false }, { "__type__": "cc.Node", "_name": "[怒]", "_objFlags": 0, "_parent": { "__id__": 38 }, "_children": [], "_tag": -1, "_active": true, "_components": [ { "__id__": 52 } ], "_prefab": { "__id__": 53 }, "_id": "", "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 104, "height": 104 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_opacityModifyRGB": false, "groupIndex": 0, "_trs": { "__type__": "TypedArray", "ctor": "Float64Array", "array": [ 53, -3, 0, 0, 0, 0, 1, 1, 1, 1 ] } }, { "__type__": "cc.Sprite", "_name": "", "_objFlags": 0, "node": { "__id__": 51 }, "_enabled": true, "_spriteFrame": { "__uuid__": "a4aa7f22-2fdc-467f-bbda-9fab0f3d52b6" }, "_type": 0, "_sizeMode": 2, "_fillType": 0, "_fillCenter": { "__type__": "cc.Vec2", "x": 0, "y": 0 }, "_fillStart": 0, "_fillRange": 0, "_isTrimmedMode": false, "_srcBlendFactor": 770, "_dstBlendFactor": 771, "_atlas": { "__uuid__": "7e99e95a-d168-4b19-85dd-3c1f0460fd1f" } }, { "__type__": "cc.PrefabInfo", "root": { "__id__": 1 }, "asset": { "__uuid__": "f4063441-0794-4c5e-8778-f584d4f58c94" }, "fileId": "79i6iz7VFEt7qg2d4lpbcB", "sync": false }, { "__type__": "cc.Node", "_name": "[晕]", "_objFlags": 0, "_parent": { "__id__": 38 }, "_children": [], "_tag": -1, "_active": true, "_components": [ { "__id__": 55 } ], "_prefab": { "__id__": 56 }, "_id": "", "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 104, "height": 104 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_opacityModifyRGB": false, "groupIndex": 0, "_trs": { "__type__": "TypedArray", "ctor": "Float64Array", "array": [ 149, -3, 0, 0, 0, 0, 1, 1, 1, 1 ] } }, { "__type__": "cc.Sprite", "_name": "", "_objFlags": 0, "node": { "__id__": 54 }, "_enabled": true, "_spriteFrame": { "__uuid__": "ce0303f9-542a-4800-8a42-98e34f088066" }, "_type": 0, "_sizeMode": 2, "_fillType": 0, "_fillCenter": { "__type__": "cc.Vec2", "x": 0, "y": 0 }, "_fillStart": 0, "_fillRange": 0, "_isTrimmedMode": false, "_srcBlendFactor": 770, "_dstBlendFactor": 771, "_atlas": { "__uuid__": "7e99e95a-d168-4b19-85dd-3c1f0460fd1f" } }, { "__type__": "cc.PrefabInfo", "root": { "__id__": 1 }, "asset": { "__uuid__": "f4063441-0794-4c5e-8778-f584d4f58c94" }, "fileId": "43HiJvqv9PVqNB2KBmGQC+", "sync": false }, { "__type__": "cc.Node", "_name": "[哈]", "_objFlags": 0, "_parent": { "__id__": 38 }, "_children": [], "_tag": -1, "_active": true, "_components": [ { "__id__": 58 } ], "_prefab": { "__id__": 59 }, "_id": "", "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 104, "height": 104 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_opacityModifyRGB": false, "groupIndex": 0, "_trs": { "__type__": "TypedArray", "ctor": "Float64Array", "array": [ 245, -3, 0, 0, 0, 0, 1, 1, 1, 1 ] } }, { "__type__": "cc.Sprite", "_name": "", "_objFlags": 0, "node": { "__id__": 57 }, "_enabled": true, "_spriteFrame": { "__uuid__": "5a2860d5-bd96-4e3f-9508-779e663e95ba" }, "_type": 0, "_sizeMode": 2, "_fillType": 0, "_fillCenter": { "__type__": "cc.Vec2", "x": 0, "y": 0 }, "_fillStart": 0, "_fillRange": 0, "_isTrimmedMode": false, "_srcBlendFactor": 770, "_dstBlendFactor": 771, "_atlas": { "__uuid__": "7e99e95a-d168-4b19-85dd-3c1f0460fd1f" } }, { "__type__": "cc.PrefabInfo", "root": { "__id__": 1 }, "asset": { "__uuid__": "f4063441-0794-4c5e-8778-f584d4f58c94" }, "fileId": "c4CKDho1dJGISyolXWo06h", "sync": false }, { "__type__": "cc.Node", "_name": "[冷]", "_objFlags": 0, "_parent": { "__id__": 38 }, "_children": [], "_tag": -1, "_active": true, "_components": [ { "__id__": 61 } ], "_prefab": { "__id__": 62 }, "_id": "", "_opacity": 255, "_color": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "_cascadeOpacityEnabled": true, "_anchorPoint": { "__type__": "cc.Vec2", "x": 0.5, "y": 0.5 }, "_contentSize": { "__type__": "cc.Size", "width": 104, "height": 104 }, "_skewX": 0, "_skewY": 0, "_localZOrder": 0, "_globalZOrder": 0, "_opacityModifyRGB": false, "groupIndex": 0, "_trs": { "__type__": "TypedArray", "ctor": "Float64Array", "array": [ 341, -3, 0, 0, 0, 0, 1, 1, 1, 1 ] } }, { "__type__": "cc.Sprite", "_name": "", "_objFlags": 0, "node": { "__id__": 60 }, "_enabled": true, "_spriteFrame": { "__uuid__": "cec85e47-2f47-4292-aef4-fd41a5c93ae8" }, "_type": 0, "_sizeMode": 2, "_fillType": 0, "_fillCenter": { "__type__": "cc.Vec2", "x": 0, "y": 0 }, "_fillStart": 0, "_fillRange": 0, "_isTrimmedMode": false, "_srcBlendFactor": 770, "_dstBlendFactor": 771, "_atlas": { "__uuid__": "7e99e95a-d168-4b19-85dd-3c1f0460fd1f" } }, { "__type__": "cc.PrefabInfo", "root": { "__id__": 1 }, "asset": { "__uuid__": "f4063441-0794-4c5e-8778-f584d4f58c94" }, "fileId": "3fMDopNzpLxK94ppSrpdxL", "sync": false }, { "__type__": "cc.Sprite", "_name": "", "_objFlags": 0, "node": { "__id__": 38 }, "_enabled": true, "_spriteFrame": { "__uuid__": "bca48fb7-6520-4372-b684-a89b5d7528e3" }, "_type": 1, "_sizeMode": 0, "_fillType": 0, "_fillCenter": { "__type__": "cc.Vec2", "x": 0, "y": 0 }, "_fillStart": 0, "_fillRange": 0, "_isTrimmedMode": true, "_srcBlendFactor": 770, "_dstBlendFactor": 771, "_atlas": null }, { "__type__": "cc.Layout", "_name": "", "_objFlags": 0, "node": { "__id__": 38 }, "_enabled": true, "_layoutSize": { "__type__": "cc.Size", "width": 786, "height": 120 }, "_resize": 1, "_N$layoutType": 1, "_N$padding": 0, "_N$cellSize": { "__type__": "cc.Size", "width": 40, "height": 40 }, "_N$startAxis": 0, "_N$paddingLeft": 10, "_N$paddingRight": 0, "_N$paddingTop": 0, "_N$paddingBottom": 0, "_N$spacingX": -8, "_N$spacingY": 0, "_N$verticalDirection": 1, "_N$horizontalDirection": 0 }, { "__type__": "cc.Button", "_name": "", "_objFlags": 0, "node": { "__id__": 38 }, "_enabled": true, "transition": 0, "pressedColor": { "__type__": "cc.Color", "r": 211, "g": 211, "b": 211, "a": 255 }, "hoverColor": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "duration": 0.1, "zoomScale": 1.2, "clickEvents": [], "_N$interactable": true, "_N$enableAutoGrayEffect": false, "_N$normalColor": { "__type__": "cc.Color", "r": 214, "g": 214, "b": 214, "a": 255 }, "_N$disabledColor": { "__type__": "cc.Color", "r": 124, "g": 124, "b": 124, "a": 255 }, "_N$normalSprite": null, "_N$pressedSprite": null, "pressedSprite": null, "_N$hoverSprite": null, "hoverSprite": null, "_N$disabledSprite": null, "_N$target": { "__id__": 38 } }, { "__type__": "cc.PrefabInfo", "root": { "__id__": 1 }, "asset": { "__uuid__": "f4063441-0794-4c5e-8778-f584d4f58c94" }, "fileId": "e8jH36RX5N14dRu7pXhw8r", "sync": false }, { "__type__": "cc.Button", "_name": "", "_objFlags": 0, "node": { "__id__": 20 }, "_enabled": true, "transition": 0, "pressedColor": { "__type__": "cc.Color", "r": 211, "g": 211, "b": 211, "a": 255 }, "hoverColor": { "__type__": "cc.Color", "r": 255, "g": 255, "b": 255, "a": 255 }, "duration": 0.1, "zoomScale": 1.2, "clickEvents": [], "_N$interactable": true, "_N$enableAutoGrayEffect": false, "_N$normalColor": { "__type__": "cc.Color", "r": 214, "g": 214, "b": 214, "a": 255 }, "_N$disabledColor": { "__type__": "cc.Color", "r": 124, "g": 124, "b": 124, "a": 255 }, "_N$normalSprite": null, "_N$pressedSprite": null, "pressedSprite": null, "_N$hoverSprite": null, "hoverSprite": null, "_N$disabledSprite": null, "_N$target": { "__id__": 20 } }, { "__type__": "cc.Widget", "_name": "", "_objFlags": 0, "node": { "__id__": 20 }, "_enabled": true, "isAlignOnce": false, "_target": null, "_alignFlags": 1, "_left": 0, "_right": 0, "_top": -9, "_bottom": 0, "_verticalCenter": 0, "_horizontalCenter": 0, "_isAbsLeft": true, "_isAbsRight": true, "_isAbsTop": true, "_isAbsBottom": true, "_isAbsHorizontalCenter": true, "_isAbsVerticalCenter": true, "_originalWidth": 0, "_originalHeight": 0 }, { "__type__": "cc.PrefabInfo", "root": { "__id__": 1 }, "asset": { "__uuid__": "f4063441-0794-4c5e-8778-f584d4f58c94" }, "fileId": "0bywYM+adJ34zGpF6i548L", "sync": false }, { "__type__": "cc.Sprite", "_name": "", "_objFlags": 0, "node": { "__id__": 1 }, "_enabled": true, "_spriteFrame": { "__uuid__": "ba04946c-b9d3-41b7-8160-6d99973cc159" }, "_type": 1, "_sizeMode": 0, "_fillType": 0, "_fillCenter": { "__type__": "cc.Vec2", "x": 0, "y": 0 }, "_fillStart": 0, "_fillRange": 0, "_isTrimmedMode": true, "_srcBlendFactor": 770, "_dstBlendFactor": 771, "_atlas": null }, { "__type__": "cc679P6rM9LE4K9WkyN0SJo", "_name": "", "_objFlags": 0, "node": { "__id__": 1 }, "_enabled": true, "chatLab": { "__id__": 6 }, "chatView": { "__id__": 20 }, "content": { "__id__": 4 }, "btnArrow": { "__id__": 16 }, "chatEditBox": { "__id__": 25 }, "btnSend": { "__id__": 27 }, "btnExpression": { "__id__": 34 }, "bgExpression": { "__id__": 38 }, "expressions": [ { "__id__": 39 }, { "__id__": 42 }, { "__id__": 45 }, { "__id__": 48 }, { "__id__": 51 }, { "__id__": 54 }, { "__id__": 57 }, { "__id__": 60 } ] }, { "__type__": "cc.PrefabInfo", "root": { "__id__": 1 }, "asset": { "__uuid__": "f4063441-0794-4c5e-8778-f584d4f58c94" }, "fileId": "31h5Ft32pIoL9OCOUcjsk6", "sync": false } ]
{ "pile_set_name": "Github" }
#include "global.h" #include "PlayerState.h" void PlayerState::ResetNoteSkins() { m_BeatToNoteSkin.clear(); m_BeatToNoteSkin[-1000] = m_PlayerOptions.m_sNoteSkin; } void PlayerState::Update( float fDelta ) { m_CurrentPlayerOptions.Approach( m_PlayerOptions, fDelta ); } /* * (c) 2001-2004 Chris Danford, Chris Gomez * All rights reserved. * * 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, and/or sell copies of the Software, and to permit persons to * whom the Software is furnished to do so, provided that the above * copyright notice(s) and this permission notice appear in all copies of * the Software and that both the above copyright notice(s) and this * permission notice appear in supporting documentation. * * 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 OF * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */
{ "pile_set_name": "Github" }
// Package network implements the Azure ARM Network service API version . // // Network Client package network // Copyright (c) Microsoft and contributors. 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. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "context" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/tracing" "net/http" ) const ( // DefaultBaseURI is the default URI used for the service Network DefaultBaseURI = "https://management.azure.com" ) // BaseClient is the base client for Network. type BaseClient struct { autorest.Client BaseURI string SubscriptionID string } // New creates an instance of the BaseClient client. func New(subscriptionID string) BaseClient { return NewWithBaseURI(DefaultBaseURI, subscriptionID) } // NewWithBaseURI creates an instance of the BaseClient client using a custom endpoint. Use this when interacting with // an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). func NewWithBaseURI(baseURI string, subscriptionID string) BaseClient { return BaseClient{ Client: autorest.NewClientWithUserAgent(UserAgent()), BaseURI: baseURI, SubscriptionID: subscriptionID, } } // CheckDNSNameAvailability checks whether a domain name in the cloudapp.azure.com zone is available for use. // Parameters: // location - the location of the domain name. // domainNameLabel - the domain name to be verified. It must conform to the following regular expression: // ^[a-z][a-z0-9-]{1,61}[a-z0-9]$. func (client BaseClient) CheckDNSNameAvailability(ctx context.Context, location string, domainNameLabel string) (result DNSNameAvailabilityResult, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.CheckDNSNameAvailability") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.CheckDNSNameAvailabilityPreparer(ctx, location, domainNameLabel) if err != nil { err = autorest.NewErrorWithError(err, "network.BaseClient", "CheckDNSNameAvailability", nil, "Failure preparing request") return } resp, err := client.CheckDNSNameAvailabilitySender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "network.BaseClient", "CheckDNSNameAvailability", resp, "Failure sending request") return } result, err = client.CheckDNSNameAvailabilityResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "network.BaseClient", "CheckDNSNameAvailability", resp, "Failure responding to request") } return } // CheckDNSNameAvailabilityPreparer prepares the CheckDNSNameAvailability request. func (client BaseClient) CheckDNSNameAvailabilityPreparer(ctx context.Context, location string, domainNameLabel string) (*http.Request, error) { pathParameters := map[string]interface{}{ "location": autorest.Encode("path", location), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2019-04-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, "domainNameLabel": autorest.Encode("query", domainNameLabel), } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/CheckDnsNameAvailability", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // CheckDNSNameAvailabilitySender sends the CheckDNSNameAvailability request. The method will close the // http.Response Body if it receives an error. func (client BaseClient) CheckDNSNameAvailabilitySender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // CheckDNSNameAvailabilityResponder handles the response to the CheckDNSNameAvailability request. The method always // closes the http.Response Body. func (client BaseClient) CheckDNSNameAvailabilityResponder(resp *http.Response) (result DNSNameAvailabilityResult, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // SupportedSecurityProviders gives the supported security providers for the virtual wan. // Parameters: // resourceGroupName - the resource group name. // virtualWANName - the name of the VirtualWAN for which supported security providers are needed. func (client BaseClient) SupportedSecurityProviders(ctx context.Context, resourceGroupName string, virtualWANName string) (result VirtualWanSecurityProviders, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/BaseClient.SupportedSecurityProviders") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } req, err := client.SupportedSecurityProvidersPreparer(ctx, resourceGroupName, virtualWANName) if err != nil { err = autorest.NewErrorWithError(err, "network.BaseClient", "SupportedSecurityProviders", nil, "Failure preparing request") return } resp, err := client.SupportedSecurityProvidersSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "network.BaseClient", "SupportedSecurityProviders", resp, "Failure sending request") return } result, err = client.SupportedSecurityProvidersResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "network.BaseClient", "SupportedSecurityProviders", resp, "Failure responding to request") } return } // SupportedSecurityProvidersPreparer prepares the SupportedSecurityProviders request. func (client BaseClient) SupportedSecurityProvidersPreparer(ctx context.Context, resourceGroupName string, virtualWANName string) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), "virtualWANName": autorest.Encode("path", virtualWANName), } const APIVersion = "2019-04-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualWans/{virtualWANName}/supportedSecurityProviders", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // SupportedSecurityProvidersSender sends the SupportedSecurityProviders request. The method will close the // http.Response Body if it receives an error. func (client BaseClient) SupportedSecurityProvidersSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // SupportedSecurityProvidersResponder handles the response to the SupportedSecurityProviders request. The method always // closes the http.Response Body. func (client BaseClient) SupportedSecurityProvidersResponder(resp *http.Response) (result VirtualWanSecurityProviders, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return }
{ "pile_set_name": "Github" }
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stdint.h> #include "base/macros.h" #include "chrome/browser/task_manager/test_task_manager.h" #include "testing/gtest/include/gtest/gtest.h" namespace task_manager { namespace { // Defines a concrete observer that will be used for testing. class TestObserver : public TaskManagerObserver { public: TestObserver(base::TimeDelta refresh_time, int64_t resources_flags) : TaskManagerObserver(refresh_time, resources_flags) {} ~TestObserver() override {} // task_manager::TaskManagerObserver: void OnTaskAdded(TaskId id) override {} void OnTaskToBeRemoved(TaskId id) override {} void OnTasksRefreshed(const TaskIdList& task_ids) override {} private: DISALLOW_COPY_AND_ASSIGN(TestObserver); }; // Defines a test to validate the behavior of the task manager in response to // adding and removing different kind of observers. class TaskManagerObserverTest : public testing::Test { public: TaskManagerObserverTest() {} ~TaskManagerObserverTest() override {} TestTaskManager& task_manager() { return task_manager_; } private: TestTaskManager task_manager_; DISALLOW_COPY_AND_ASSIGN(TaskManagerObserverTest); }; } // namespace // Validates that the minimum refresh time to be requested is one second. Also // validates the desired resource flags. TEST_F(TaskManagerObserverTest, Basic) { base::TimeDelta refresh_time1 = base::TimeDelta::FromSeconds(2); base::TimeDelta refresh_time2 = base::TimeDelta::FromMilliseconds(999); int64_t flags1 = RefreshType::REFRESH_TYPE_CPU | RefreshType::REFRESH_TYPE_WEBCACHE_STATS | RefreshType::REFRESH_TYPE_HANDLES; int64_t flags2 = RefreshType::REFRESH_TYPE_MEMORY | RefreshType::REFRESH_TYPE_NACL; TestObserver observer1(refresh_time1, flags1); TestObserver observer2(refresh_time2, flags2); EXPECT_EQ(refresh_time1, observer1.desired_refresh_time()); EXPECT_EQ(base::TimeDelta::FromSeconds(1), observer2.desired_refresh_time()); EXPECT_EQ(flags1, observer1.desired_resources_flags()); EXPECT_EQ(flags2, observer2.desired_resources_flags()); } // Validates the behavior of the task manager in response to adding and // removing observers. TEST_F(TaskManagerObserverTest, TaskManagerResponseToObservers) { EXPECT_EQ(base::TimeDelta::Max(), task_manager().GetRefreshTime()); EXPECT_EQ(0, task_manager().GetEnabledFlags()); // Add a bunch of observers and make sure the task manager responds correctly. base::TimeDelta refresh_time1 = base::TimeDelta::FromSeconds(3); base::TimeDelta refresh_time2 = base::TimeDelta::FromSeconds(10); base::TimeDelta refresh_time3 = base::TimeDelta::FromSeconds(3); base::TimeDelta refresh_time4 = base::TimeDelta::FromSeconds(2); int64_t flags1 = RefreshType::REFRESH_TYPE_CPU | RefreshType::REFRESH_TYPE_WEBCACHE_STATS | RefreshType::REFRESH_TYPE_HANDLES; int64_t flags2 = RefreshType::REFRESH_TYPE_MEMORY | RefreshType::REFRESH_TYPE_NACL; int64_t flags3 = RefreshType::REFRESH_TYPE_MEMORY | RefreshType::REFRESH_TYPE_CPU; int64_t flags4 = RefreshType::REFRESH_TYPE_GPU_MEMORY; TestObserver observer1(refresh_time1, flags1); TestObserver observer2(refresh_time2, flags2); TestObserver observer3(refresh_time3, flags3); TestObserver observer4(refresh_time4, flags4); task_manager().AddObserver(&observer1); task_manager().AddObserver(&observer2); task_manager().AddObserver(&observer3); task_manager().AddObserver(&observer4); EXPECT_EQ(refresh_time4, task_manager().GetRefreshTime()); EXPECT_EQ(flags1 | flags2 | flags3 | flags4, task_manager().GetEnabledFlags()); // Removing observers should also reflect on the refresh time and resource // flags. task_manager().RemoveObserver(&observer4); EXPECT_EQ(refresh_time3, task_manager().GetRefreshTime()); EXPECT_EQ(flags1 | flags2 | flags3, task_manager().GetEnabledFlags()); task_manager().RemoveObserver(&observer3); EXPECT_EQ(refresh_time1, task_manager().GetRefreshTime()); EXPECT_EQ(flags1 | flags2, task_manager().GetEnabledFlags()); task_manager().RemoveObserver(&observer2); EXPECT_EQ(refresh_time1, task_manager().GetRefreshTime()); EXPECT_EQ(flags1, task_manager().GetEnabledFlags()); task_manager().RemoveObserver(&observer1); EXPECT_EQ(base::TimeDelta::Max(), task_manager().GetRefreshTime()); EXPECT_EQ(0, task_manager().GetEnabledFlags()); } } // namespace task_manager
{ "pile_set_name": "Github" }
class COwnerDrawMenu : public CMenu { public: COwnerDrawMenu(); ~COwnerDrawMenu(); virtual void MeasureItem(LPMEASUREITEMSTRUCT mis); virtual void DrawItem(LPDRAWITEMSTRUCT dis); protected: void DrawItem1(LPDRAWITEMSTRUCT dis); void DrawItem2(LPDRAWITEMSTRUCT dis); };
{ "pile_set_name": "Github" }
package cbt_build.reflect.build import cbt._ class Build(val context: Context) extends BuildBuild with CbtInternal{ override def dependencies = super.dependencies :+ cbtInternal.library }
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Form Fun</title> <link href="../_css/site.css" rel="stylesheet"> <style> #signup label.error { font-size: 0.8em; color: #F00; font-weight: bold; display: block; margin-left: 215px; } #signup input.error, #signup select.error { background: #FFA9B8; border: 1px solid red; } </style> <script src="../_js/jquery.min.js"></script> <script src="jquery_validate/jquery.validate.min.js"></script> <script> $(document).ready(function() { $('#signup').validate({ rules: { email: { required: true, email: true }, password: { required: true, rangelength:[8,16] }, confirm_password: {equalTo:'#password'}, spam: "required" }, //end rules messages: { email: { required: "Please supply an e-mail address.", email: "This is not a valid email address." }, password: { required: 'Please type a password', rangelength: 'Password must be between 8 and 16 characters long.' }, confirm_password: { equalTo: 'The two passwords do not match.' } }, errorPlacement: function(error, element) { if ( element.is(":radio") || element.is(":checkbox")) { error.appendTo( element.parent()); } else { error.insertAfter(element); } } }); // end validate }); // end ready </script> </head> <body> <div class="wrapper"> <header> JAVASCRIPT <span class="amp">&amp;</span> jQUERY: THE&nbsp;MISSING&nbsp;MANUAL </header> <div class="content"> <div class="main"> <h1>Signup</h1> <form action="process.html" method="post" name="signup" id="signup"> <div> <label for="name" class="label">Name </label> <input name="name" type="text" class="required" id="name" title="Please type your name."> </div> <div> <label for="email" class="label">E-mail Address</label> <input name="email" type="text" id="email"> </div> <div> <label for="password" class="label">Password</label> <input name="password" type="password" id="password"> </div> <div> <label for="confirm_password" class="label">Confirm Password</label> <input name="confirm_password" type="password" id="confirm_password"> </div> <div><span class="label">Hobbies</span> <input name="hobby" type="checkbox" id="heliskiing" value="heliskiing" class="required" title="Please check at least 1 hobby."> <label for="heliskiing">Heli-skiing</label> <input name="hobby" type="checkbox" id="pickle" value="pickle"> <label for="pickle">Pickle eating</label> <input name="hobby" type="checkbox" id="walnut" value="walnut"> <label for="walnut">Making walnut butter</label> </div> <div> <label for="dob" class="label">Date of birth</label> <input name="dob" type="text" id="dob" class="date" title="Please type your date of birth using this format: 01/19/2000"> </div> <div> <label for="planet" class="label">Planet of Birth</label> <select name="planet" id="planet" class="required" title="Please choose a planet."> <option value="">--Please select one--</option> <option value="earth">Earth</option> <option value="mars">Mars</option> <option value="alpha centauri">Alpha Centauri</option> <option value="forget about it">You've never heard of it</option> </select> </div> <div> <label for="comments" class="label">Comments</label> <textarea name="comments" cols="15" rows="5" id="comments"></textarea> </div> <div class="labelBlock">Would you like to receive annoying e-mail froM US? </div> <div class="indent"> <input type="radio" name="spam" id="yes" value="yes" class="required" title="Please select an option"> <label for="yes">Yes</label> <input type="radio" name="spam" id="definitely" value="definitely"> <label for="definitely">Definitely</label> <input type="radio" name="spam" id="choice" value="choice"> <label for="choice">Do I have a choice?</label> </div> <div> <input type="submit" name="submit" id="submit" value="Submit"> </div> </form> </div> </div> <footer> <p>JavaScript &amp; jQuery: The Missing Manual, 3rd Edition, by <a href="http://sawmac.com/">David McFarland</a>. Published by <a href="http://oreilly.com/">O'Reilly Media, Inc</a>.</p> </footer> </div> </body> </html>
{ "pile_set_name": "Github" }
<HTML> <HEAD> <meta charset="UTF-8"> <title>PaymentMethodsActivityStarter.Result.fromIntent - stripe</title> <link rel="stylesheet" href="../../../../style.css"> </HEAD> <BODY> <a href="../../../index.html">stripe</a>&nbsp;/&nbsp;<a href="../../index.html">com.stripe.android.view</a>&nbsp;/&nbsp;<a href="../index.html">PaymentMethodsActivityStarter</a>&nbsp;/&nbsp;<a href="index.html">Result</a>&nbsp;/&nbsp;<a href="./from-intent.html">fromIntent</a><br/> <br/> <h1>fromIntent</h1> <a name="com.stripe.android.view.PaymentMethodsActivityStarter.Result.Companion$fromIntent(android.content.Intent)"></a> <code><span class="identifier">@JvmStatic</span> <span class="keyword">fun </span><span class="identifier">fromIntent</span><span class="symbol">(</span><span class="identifier" id="com.stripe.android.view.PaymentMethodsActivityStarter.Result.Companion$fromIntent(android.content.Intent)/intent">intent</span><span class="symbol">:</span>&nbsp;<a href="https://developer.android.com/reference/android/content/Intent.html"><span class="identifier">Intent</span></a><span class="symbol">?</span><span class="symbol">)</span><span class="symbol">: </span><span class="identifier">Result</span><span class="symbol">?</span></code> <p><strong>Return</strong><br/> the <a href="index.html">Result</a> object from the given <code>Intent</code></p> </BODY> </HTML>
{ "pile_set_name": "Github" }
/*----------------------------------------------------------------------------- The MIT License (MIT) This source file is part of GDGeek (Game Develop & Game Engine Extendable Kits) For the latest info, see http://gdgeek.com/ Copyright (c) 2014-2017 GDGeek Software Ltd 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. ----------------------------------------------------------------------------- */ using UnityEngine; using System.Collections; using System; namespace GDGeek{ public class TaskManager : Singleton<TaskManager> { //public TaskFactories _factories = null; //public TaskRunner _runner = null; private TaskRunner partRunner_ = null; public TaskRunner partRunner{ set{this.partRunner_ = value as TaskRunner;} } protected void Awake(){ // base.Awake(); //TaskManager.instance_ = this; /*if (_runner == null) { _runner = this.gameObject.GetComponent<TaskRunner>(); } if (_runner == null) { _runner = this.gameObject.AddComponent<TaskRunner>(); }*/ } public static TaskManager GetInstance(){ return Singleton<TaskManager>.Instance; } public ITaskRunner globalRunner{ get{ TaskRunner runner = this.gameObject.AskComponent<TaskRunner> (); return runner; } } #if UNITY_EDITOR public ITaskRunner editorRunner{ get{ TaskRunnerInEditor runner = this.gameObject.AskComponent<TaskRunnerInEditor> (); return runner; } } #endif public ITaskRunner runner{ get{ #if UNITY_EDITOR if(!Application.isPlaying){ return editorRunner; } #endif if(partRunner_ != null){ return partRunner_; } return globalRunner; } } public static void AddOrIsOver(Task task, TaskIsOver func){ TaskIsOver oIsOver = task.isOver; task.isOver = delegate(){ return (oIsOver() || func()); }; } public static void AddAndIsOver(Task task, TaskIsOver func) { TaskIsOver oIsOver = task.isOver; task.isOver = delegate () { return (oIsOver() && func()); }; } public static void AddUpdate(Task task, TaskUpdate func){ TaskUpdate update = task.update; task.update = delegate(float d){ update(d); func(d); }; } public static void PushBack(Task task, TaskShutdown func){ TaskShutdown oShutdown = task.shutdown; task.shutdown = delegate (){ oShutdown(); func(); }; } public static void Run(Task task){ TaskManager.GetInstance().runner.addTask(task); } public static void PushFront(Task task, TaskInit func){ TaskInit oInit = task.init; task.init = delegate(){ func(); oInit(); }; } } }
{ "pile_set_name": "Github" }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Microsoft.VisualStudio.Services.Agent.Util; using System; using System.Diagnostics; using System.Globalization; using System.IO; using System.Text; namespace Microsoft.VisualStudio.Services.Agent { public sealed class HostTraceListener : TextWriterTraceListener { public bool DisableConsoleReporting { get; set; } private const string _logFileNamingPattern = "{0}_{1:yyyyMMdd-HHmmss}-utc.log"; private string _logFileDirectory; private string _logFilePrefix; private bool _enablePageLog = false; private bool _enableLogRetention = false; private int _currentPageSize; private int _pageSizeLimit; private int _retentionDays; private bool _diagErrorDetected = false; private string _logFilePath; public HostTraceListener(string logFileDirectory, string logFilePrefix, int pageSizeLimit, int retentionDays) : base() { ArgUtil.NotNullOrEmpty(logFileDirectory, nameof(logFileDirectory)); ArgUtil.NotNullOrEmpty(logFilePrefix, nameof(logFilePrefix)); _logFileDirectory = logFileDirectory; _logFilePrefix = logFilePrefix; Directory.CreateDirectory(_logFileDirectory); if (pageSizeLimit > 0) { _enablePageLog = true; _pageSizeLimit = pageSizeLimit * 1024 * 1024; _currentPageSize = 0; } if (retentionDays > 0) { _enableLogRetention = true; _retentionDays = retentionDays; } Writer = CreatePageLogWriter(); } public HostTraceListener(string logFile) : base() { ArgUtil.NotNullOrEmpty(logFile, nameof(logFile)); _logFilePath = logFile; Directory.CreateDirectory(Path.GetDirectoryName(_logFilePath)); Stream logStream = new FileStream(_logFilePath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read, bufferSize: 4096); Writer = new StreamWriter(logStream); } // Copied and modified slightly from .Net Core source code. Modification was required to make it compile. // There must be some TraceFilter extension class that is missing in this source code. public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message) { if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, message, null, null, null)) { return; } WriteHeader(source, eventType, id); WriteLine(message); WriteFooter(eventCache); if (!_diagErrorDetected && !DisableConsoleReporting && eventType < TraceEventType.Warning) { Console.WriteLine(StringUtil.Loc("FoundErrorInTrace", eventType.ToString(), _logFilePath)); _diagErrorDetected = true; } } public override void WriteLine(string message) { base.WriteLine(message); if (_enablePageLog) { int messageSize = UTF8Encoding.UTF8.GetByteCount(message); _currentPageSize += messageSize; if (_currentPageSize > _pageSizeLimit) { Flush(); if (Writer != null) { Writer.Dispose(); Writer = null; } Writer = CreatePageLogWriter(); _currentPageSize = 0; } } Flush(); } public override void Write(string message) { base.Write(message); if (_enablePageLog) { int messageSize = UTF8Encoding.UTF8.GetByteCount(message); _currentPageSize += messageSize; } Flush(); } internal bool IsEnabled(TraceOptions opts) { return (opts & TraceOutputOptions) != 0; } // Altered from the original .Net Core implementation. private void WriteHeader(string source, TraceEventType eventType, int id) { string type = null; switch (eventType) { case TraceEventType.Critical: type = "CRIT"; break; case TraceEventType.Error: type = "ERR "; break; case TraceEventType.Warning: type = "WARN"; break; case TraceEventType.Information: type = "INFO"; break; case TraceEventType.Verbose: type = "VERB"; break; default: type = eventType.ToString(); break; } Write(StringUtil.Format("[{0:u} {1} {2}] ", DateTime.UtcNow, type, source)); } // Copied and modified slightly from .Net Core source code to make it compile. The original code // accesses a private indentLevel field. In this code it has been modified to use the getter/setter. private void WriteFooter(TraceEventCache eventCache) { if (eventCache == null) return; IndentLevel++; if (IsEnabled(TraceOptions.ProcessId)) WriteLine("ProcessId=" + eventCache.ProcessId); if (IsEnabled(TraceOptions.ThreadId)) WriteLine("ThreadId=" + eventCache.ThreadId); if (IsEnabled(TraceOptions.DateTime)) WriteLine("DateTime=" + eventCache.DateTime.ToString("o", CultureInfo.InvariantCulture)); if (IsEnabled(TraceOptions.Timestamp)) WriteLine("Timestamp=" + eventCache.Timestamp); IndentLevel--; } private StreamWriter CreatePageLogWriter() { if (_enableLogRetention) { DirectoryInfo diags = new DirectoryInfo(_logFileDirectory); var logs = diags.GetFiles($"{_logFilePrefix}*.log"); foreach (var log in logs) { if (log.LastWriteTimeUtc.AddDays(_retentionDays) < DateTime.UtcNow) { try { log.Delete(); } catch (Exception) { // catch Exception and continue // we shouldn't block logging and fail the agent if the agent can't delete an older log file. } } } } string fileName = StringUtil.Format(_logFileNamingPattern, _logFilePrefix, DateTime.UtcNow); _logFilePath = Path.Combine(_logFileDirectory, fileName); Stream logStream; if (File.Exists(_logFilePath)) { logStream = new FileStream(_logFilePath, FileMode.Append, FileAccess.Write, FileShare.Read, bufferSize: 4096); } else { logStream = new FileStream(_logFilePath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read, bufferSize: 4096); } return new StreamWriter(logStream); } } }
{ "pile_set_name": "Github" }