text
stringlengths
4
6.14k
/* * PwmEsc.h * * Created on: Mar 26, 2014 * Author: fabien papleux */ #ifndef PWMESC_H_ #define PWMESC_H_ #include "PCA9685.h" /*** This class requires a PWM controller class (implemented here as PCA9685) where to send the following commands: * * int reset (void) // resets controller * int isReady (void) // returns 1 if controller is ready * int getFrequency () // Returns the current frequency used by the controller to determine pulse width * int getResolution (void) // Returns the current resolution of the PWM controller (PCA9685 is standard at 12) * int setPwm (int channel, int data) // Sets the stop PWM value for a channel. (the start value is to be assumed as 0) * int getPwm (int channel) // Gets the current stop value of the PWM * */ /* 50Hz is the typical clock for servos. it means the controller runs 50 cycles in 1 second, * which means that each cycle is 20ms. Servos typically require to be high for 1ms per frame * to be full on one side, 1.5ms to be in the middle and 2ms to be full on the other side. * If your controller is a PCA9685 (like the Adafruit 16-channel 12-bit controller), the 12-bit * definition means that your frame's scale goes from 0 to 4095. * * If your frame is 20ms and you want to be up for 1ms, you need to be up for 1/20th of the * size of your frame, which would be 4096 / 20 = 205. */ struct PwmEscConfig { int channel; // indicate what is the address/channel this Servo should provide the PWM controller to send information int frequency; // PWM frequency (determines frame size) in Hz ... this is just to provide referential sizing for the data, not to set the PWM int resolution; // resolution of the PWM value (PCA9685 is a 12-bit resolution so values should range from 0 to 4095, which means the value here should be 4096) int posInit; // position to initialize the servo at. int posIdle; // value for straight position int posMinForward; // in principle, this will be idle+-1. For ESC's, which use the same technology, there could be a difference between purely idle and the beginning of movement int posMaxForward; int posMinReverse; int posMaxReverse; }; class PwmEsc { public: PwmEsc (PwmEscConfig *config, PCA9685 *controller); ~PwmEsc (void); int init (void); int isReady (void); void printStatus(void); void set(float percent); int forwardPct (int percent); int reversePct (int percent); int stop (void); int speedPct (int percent); // going from -100% (full backward) to +100% (full forward) -- 0 being the straight/middle point int setPwm (int value); int getPwm (void); private: int ready; int lastPwm; // Holds the current PWM value (position) PwmEscConfig cfg; // actual configuration used to manipulate the esc PwmEscConfig* baseConfig; // config provided by user at initialization to be used as base during operation PCA9685 *pwm; // pointer to a PWM controller, the address of which should be provided at creation time }; #endif /* PWMESC_H_ */
#pragma once #include <config.h> namespace nspace{ template<typename Mat, typename Func> class MatrixSetFunction{ public: static inline void operation(Mat & result, Func f){ for(int i=0; i < result.rows(); i++){ for(int j=0; j < result.cols(); j++){ result(i,j)=f(i,j); } } } }; }
// ========================================================================================================== // Copyright (c) 2016 ChenChen <codingmanon@163.com> // // 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. // // -------------------------------------- // ±¾Î͍ÒåÁËAtmega16¶¨Ê±Æ÷0/1/2 Çý¶¯Ä£¿é // // ========================================================================================================== #ifndef __DRV_TIMER_H_ #define __DRV_TIMER_H_ #include <avr/interrupt.h> #include <avr/io.h> #include "sys_config.h" // -------------- // ¶¨Ê±Æ÷ÖжÏģʽ typedef enum { INT_MODE_TOV = 0, INT_MODE_OCF = 1, INT_MODE_ICF = 2, INT_MODE_OCF1A = 3, INT_MODE_OCF1B = 4 } TIMER_INT_MODE; // ¶¨Ê±Æ÷±È½ÏÆ¥ÅäÒý½ÅÊä³öģʽ typedef enum { COM_MODE_NONE = 0, COM_MODE_TOGGLE = 1, COM_MODE_CLEAR = 2, COM_MODE_SET = 3 } TIMER_COM_MODE; // ---------------------------------------------------------------------------------------------- // ¶¨Ê±Æ÷0(ÕâÀඨÒåÕ¼ÓÃflash¿Õ¼ä£¬ËùÒÔÈç¹û¿Õ¼ä²»×㣬¾ÍÆÁ±ÎÕâÀ²¢ÔÚµ÷Óô¦ÓþßÌåÊýÖµÌæ»»ÕâЩ¶¨Òå) typedef enum { T0_WGM_NOMAL = 0, T0_WGM_PHASE_PWM = 1, T0_WGM_CTC = 2, T0_WGM_FAST_PWM = 3, T0_CLK_SOURCE_NONE = 0, T0_CLK_SOURCE_DIV_1 = 1, T0_CLK_SOURCE_DIV_8 = 2, T0_CLK_SOURCE_DIV_64 = 3, T0_CLK_SOURCE_DIV_256 = 4, T0_CLK_SOURCE_DIV_1024 = 5, T0_CLK_SOURCE_T0_FALL = 6, T0_CLK_SOURCE_T0_RAISE = 7 } TIMER0_MODE; void Drv_Timer0_init(const uint8_t wave_mode, const uint8_t com_mode, const uint8_t clk_source); void Drv_Timer0_INT_Enable(const uint8_t int_mode, const uint8_t enable); void Drv_Timer0_set_TCNT0_OCR0(const uint8_t tcnt0, const uint8_t ocr0); // ---------------------------------------------------------------------------------------------- // ¶¨Ê±Æ÷1(ÕâÀඨÒåÕ¼ÓÃflash¿Õ¼ä£¬ËùÒÔÈç¹û¿Õ¼ä²»×㣬¾ÍÆÁ±ÎÕâÀ²¢ÔÚµ÷Óô¦ÓþßÌåÊýÖµÌæ»»ÕâЩ¶¨Òå) typedef enum { T1_WGM_NOMAL = 0, T1_WGM_8_PHASE_PWM = 1, T1_WGM_9_PHASE_PWM = 2, T1_WGM_10_PHASE_PWM = 3, T1_WGM_CTC = 4, T1_WGM_8_FAST_PWM = 5, T1_WGM_9_FAST_PWM = 6, T1_WGM_10_FAST_PWM = 7, T1_WGM_PHASE_FRQ_PWM_ICR1 = 8, T1_WGM_PHASE_FRQ_PWM_OCR1A = 9, T1_WGM_PHASE_PWM_ICR1 = 10, T1_WGM_PHASE_PWM_OCR1A = 11, T1_WGM_CTC_ICR1 = 12, T1_WGM_SERVED = 13, T1_WGM_FAST_PWM_ICR1 = 14, T1_WGM_FAST_PWM_OCR1A = 15, T1_CLK_SOURCE_NONE = 0, T1_CLK_SOURCE_DIV_1 = 1, T1_CLK_SOURCE_DIV_8 = 2, T1_CLK_SOURCE_DIV_64 = 3, T1_CLK_SOURCE_DIV_256 = 4, T1_CLK_SOURCE_DIV_1024 = 5, T1_CLK_SOURCE_T1_FALL = 6, T1_CLK_SOURCE_T1_RAISE = 7 } TIMER1_MODE; typedef enum { T1_ICP_FALL_EDGE = 0, T1_ICP_RAISE_EDGE = 1 } TIMER1_ICP; void Drv_Timer1_init(const uint8_t com_mode, const uint8_t OCM1A_mode, const uint8_t OCM1B_mode, const uint8_t clk_source); void Drv_Timer1_init_for_ICP(const uint8_t flit_enable, const uint8_t edge); void Drv_Timer1_INT_Enable(const uint8_t int_mode, const uint8_t enable); void Drv_Timer1_set_TCNT1_OCR1A_OCR1B_ICR1(const uint16_t tcnt1, const uint16_t ocr1a, const uint16_t ocr1b, const uint16_t icr1); // ---------------------------------------------------------------------------------------------- // ¶¨Ê±Æ÷2(ÕâÀඨÒåÕ¼ÓÃflash¿Õ¼ä£¬ËùÒÔÈç¹û¿Õ¼ä²»×㣬¾ÍÆÁ±ÎÕâÀ²¢ÔÚµ÷Óô¦ÓþßÌåÊýÖµÌæ»»ÕâЩ¶¨Òå) typedef enum { T2_WGM_NOMAL = 0, T2_WGM_PHASE_PWM = 1, T2_WGM_CTC = 2, T2_WGM_FAST_PWM = 3, T2_CLK_SOURCE_NONE = 0, T2_CLK_SOURCE_DIV_1 = 1, T2_CLK_SOURCE_DIV_8 = 2, T2_CLK_SOURCE_DIV_32 = 3, T2_CLK_SOURCE_DIV_64 = 4, T2_CLK_SOURCE_DIV_128 = 5, T2_CLK_SOURCE_DIV_256 = 6, T2_CLK_SOURCE_DIV_1024 = 7 } TIMER2_MODE; void Drv_Timer2_init(const uint8_t wave_mode, const uint8_t com_mode, const uint8_t clk_source); void Drv_Timer2_INT_Enable(const uint8_t int_mode, const uint8_t enable); void Drv_Timer2_FOC2_enable(const uint8_t enable); void Drv_Timer2_set_TCNT2_OCR2(const uint8_t tcnt2, const uint8_t ocr2); #endif // #ifndef __DRV_TIMER_H_
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. * Use of this file is governed by the BSD 3-clause license that * can be found in the LICENSE.txt file in the project root. */ #pragma once #include "Transition.h" namespace antlr4 { namespace atn { class ANTLR4CPP_PUBLIC EpsilonTransition final : public Transition { public: EpsilonTransition(ATNState *target); EpsilonTransition(ATNState *target, size_t outermostPrecedenceReturn); /** * @return the rule index of a precedence rule for which this transition is * returning from, where the precedence value is 0; otherwise, INVALID_INDEX. * * @see ATNConfig#isPrecedenceFilterSuppressed() * @see ParserATNSimulator#applyPrecedenceFilter(ATNConfigSet) * @since 4.4.1 */ size_t outermostPrecedenceReturn(); virtual SerializationType getSerializationType() const override; virtual bool isEpsilon() const override; virtual bool matches(size_t symbol, size_t minVocabSymbol, size_t maxVocabSymbol) const override; virtual std::string toString() const override; private: const size_t _outermostPrecedenceReturn; // A rule index. }; } // namespace atn } // namespace antlr4
// // RootViewController.h // VXPromotionViewController // // Created by Swift Management AG on 18.12.2014. // Copyright 2011 Swift Management AG. All rights reserved. // #import <UIKit/UIKit.h> #import "VXWalkthroughViewController.h" @interface ViewController : UIViewController<VXWalkthroughViewControllerDelegate> - (IBAction)presentViewController; @end
/* * Strategies.h * * Created on: Apr 29, 2014 * Author: khanhn */ #ifndef STRATEGIES_H_ #define STRATEGIES_H_ #include "MemoryStrat.h" #include "FileStrat.h" #endif /* STRATEGIES_H_ */
// Copyright (c) 2016 Antony Arciuolo. See License.txt regarding use. // a ring is a 2D torus (circle outline) in 3-space #pragma once #include <oMath/hlsl.h> namespace ouro { // returns true if there is an intersection // a0, a1: the line segment // center: location of the ring's center // normal: normalized normal pointing out of the circle/plane of the ring // radius: the radius of the ring - collision occurs only on the edge // eps: epsilon for where collision occurs on the radius // at0: defines the intersection points on the segment: lerp(a0, a1, *at0) bool seg_v_ring(const float3& a0, const float3& a1, const float3& center, const float3& normal, float radius, float eps, float* at0); inline bool seg_v_ring(const float3& a0, const float3& a1, const float3& center, const float3& normal, float radius, float eps, float3* out_intersection) { float t0; if (seg_v_ring(a0, a1, center, normal, radius, eps, &t0)) { *out_intersection = lerp(a0, a1, t0); return true; } return false; } }
#pragma once #ifdef _WIN32 #ifdef EXPORT_FCNS #define EXPORTED_FUNCTION __declspec(dllexport) #else #define EXPORTED_FUNCTION __declspec(dllimport) #endif //LINUX/UNIX... #else #define EXPORTED_FUNCTION #endif
// // WeakProxySubclass.h // Pie // // Created by Meiwin Fu on 7/11/14. // Copyright (c) 2014 Piethis Pte Ltd. All rights reserved. // #import "NugWeakProxy.h" #ifndef Nugget_NugProxySubclass_h #define Nugget_NugProxySubclass_h @interface NugWeakProxy (Subclass) - (void)setTarget:(id)target; @end #endif
/* * Copyright (c) 2007 - 2021 Joseph Gaeddert * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <stdio.h> #include <stdlib.h> #include "autotest/autotest.h" #include "liquid.h" // autotest helper function: measure delay assuming impulse // - set gain to 1 for a single sample // - set gain to 0 for remaining samples // -> this generates one symbol for the modulation scheme // - take fft of resulting pulse // - observe phase slope across pass-band void testbench_symstreamrcf_delay(float _bw, unsigned int _m) { // create object and get expected delay int ftype = LIQUID_FIRFILT_ARKAISER; float beta = 0.30f; int ms = LIQUID_MODEM_QPSK; symstreamrcf gen = symstreamrcf_create_linear(ftype,_bw,_m,beta,ms); float delay = symstreamrcf_get_delay(gen); float tol = 0.05; // error tolerance // compute buffer length based on delay unsigned int nfft = 2*(120 + (unsigned int)(delay/sqrtf(_bw))); float complex buf_time[nfft]; float complex buf_freq[nfft]; // write samples to buffer symstreamrcf_write_samples(gen, buf_time, 1); symstreamrcf_set_gain(gen, 0.0f); symstreamrcf_write_samples(gen, buf_time+1, nfft-1); // destroy objects symstreamrcf_destroy(gen); // take forward transform fft_run(nfft, buf_time, buf_freq, LIQUID_FFT_FORWARD, 0); // measure phase slope across pass-band unsigned int m = 0.4 * _bw * nfft; // use 0.4 to account for filter roll-off float complex p = 0.0f; int i; for (i=-(int)m; i<(int)m; i++) p += buf_freq[(nfft+i)%nfft] * conjf(buf_freq[(nfft+i+1)%nfft]); float delay_meas = cargf(p) * nfft / (2*M_PI); // print results if (liquid_autotest_verbose) { printf("expected delay: %.6f, measured: %.6f, error: %.6f (tol= %.3f)\n", delay, delay_meas, delay-delay_meas,tol); } // verify delay is relatively close to expected CONTEND_DELTA(delay, delay_meas, tol); } void autotest_symstreamrcf_delay_00() { testbench_symstreamrcf_delay(0.500f, 4); } void autotest_symstreamrcf_delay_01() { testbench_symstreamrcf_delay(0.500f, 5); } void autotest_symstreamrcf_delay_02() { testbench_symstreamrcf_delay(0.500f, 6); } void autotest_symstreamrcf_delay_03() { testbench_symstreamrcf_delay(0.500f, 7); } void autotest_symstreamrcf_delay_04() { testbench_symstreamrcf_delay(0.500f, 8); } void autotest_symstreamrcf_delay_05() { testbench_symstreamrcf_delay(0.500f, 9); } void autotest_symstreamrcf_delay_06() { testbench_symstreamrcf_delay(0.500f,10); } void autotest_symstreamrcf_delay_07() { testbench_symstreamrcf_delay(0.500f,14); } void autotest_symstreamrcf_delay_08() { testbench_symstreamrcf_delay(0.500f,20); } void autotest_symstreamrcf_delay_09() { testbench_symstreamrcf_delay(0.500f,31); } void autotest_symstreamrcf_delay_10() { testbench_symstreamrcf_delay(0.800f,12); } void autotest_symstreamrcf_delay_11() { testbench_symstreamrcf_delay(0.700f,12); } void autotest_symstreamrcf_delay_12() { testbench_symstreamrcf_delay(0.600f,12); } void autotest_symstreamrcf_delay_13() { testbench_symstreamrcf_delay(0.500f,12); } void autotest_symstreamrcf_delay_14() { testbench_symstreamrcf_delay(0.400f,12); } void autotest_symstreamrcf_delay_15() { testbench_symstreamrcf_delay(0.300f,12); } void autotest_symstreamrcf_delay_16() { testbench_symstreamrcf_delay(0.200f,12); } void autotest_symstreamrcf_delay_17() { testbench_symstreamrcf_delay(0.100f,12); } void autotest_symstreamrcf_delay_18() { testbench_symstreamrcf_delay(0.050f,12); } void autotest_symstreamrcf_delay_19() { testbench_symstreamrcf_delay(0.025f,12); }
#include <stdio.h> int main(int argc, char *argv[]) { int bugs = 100; double bug_rate = 1.2; printf("You have %d bugs at the imaginary rate of %f. \n", bugs, bug_rate); unsigned long universe_of_defects = 1L * 1024L * 1024L * 1024L * 1024L * 1024L * 1024L * 8; printf("The entire universe has %ld bugs. \n", universe_of_defects); double expected_bugs = bugs * bug_rate; printf("You are expected to have %f bugs.\n", expected_bugs); double part_of_universe = expected_bugs / universe_of_defects; printf("That is only a %e portion of the universe.\n", part_of_universe); //this makes no sense, just a demo of something weird char null_byte = "\0"; int care_percentage = bugs * null_byte; printf("Which means you should care %d%%.\n", care_percentage); return 0; }
#include <xc.h> #include "Define.h" #include "Battery.h" #include "Global.h" #include "mcc_generated_files/adc.h" float Battery_Volt[10]={3.000,3.000,3.000,3.000,3.000,3.000,3.000,3.000,3.000,3.000}; float TempBattery_Volt[10]; float PrevBattery_Volt[10]; /******************************************************************* * @brief Battery_Read * @brief sets ADC up for battery voltage read * @return nothing * @note it set's up the adc and uses ADC ISR to read all battery analog inputs *******************************************************************/ void Battery_Read() { //Set the ADC interupt to start to fill in the Battery ADC Buffer ADC_Buffer_Point = 0; Volt_Aquire = 1; //Set global flag for ADC ISR to trigger battery volt reads ADCON1 = 0x80; //Set up to run ADC from VDD to Vref- (2.5v) Put back to 0x81 ADC_StartConversion(Battery1); //We need to get the ball rolling... } /******************************************************************* * @brief Battery_Convert * @brief takes battery cell ADC counts and converts to volts * @return nothing * @note this fcn needs to take account of the -vref (configgured by above fcn) *******************************************************************/ void Battery_Convert() { for(int x = 0; x < NUMOFBATT; x++) { TempBattery_Volt[x] = ((Battery_Adc[x]/1024.0)*5.0); //Normal converson w/ 2.5v offset (vref neg = 2.5v) } Battery_Filter(); } /******************************************************************* * @brief Battery_Filter * @brief takes battery volts and does a exp. filter * @return nothing * @note May require adjustment (in define.h) *******************************************************************/ void Battery_Filter() { // This is a exponential moving average. for(int x = 0; x < NUMOFBATT; x++) { Battery_Volt[x] = (BATALPHA*TempBattery_Volt[x] + ((1- BATALPHA)*PrevBattery_Volt[x])); PrevBattery_Volt[x] = Battery_Volt[x]; } } /******************************************************************* * @brief Controls Fault * @brief takes battery volts and determans over / under conditions * @return returns 1 if over / under is met * @note used for serial comm. *******************************************************************/ char Battery_Fault() { char fault = 0; // Init fault as if there is none for(int i = 0;i<NUMOFBATT;i++) { if ((BATLOW > Battery_Volt[i]) || (BATHIGH > Battery_Volt[i])) { fault = 1; // Set fault if found! Uh-Oh!!!! } } return fault; } /******************************************************************* * @brief Battery_Get * @brief used for testing / UART stuff * @param[in] channelnum - what battery to return voltage of * @return battery cell voltage * @note getter *******************************************************************/ float Battery_Get(int channelnum) { //return TempBattery_Volt[channelnum]; return Battery_Volt[channelnum]; }//
// // SOLoadMoreItem.h // SOKit // // Created by soso on 15/5/18. // Copyright (c) 2015年 com.. All rights reserved. // #import "SOBaseItem.h" /** * @brief 是否自动加载更多的key */ extern NSString * const _KeyLoadMoreItemAutoLoadMore; /** * @brief 加载时,是否显示提示的key */ extern NSString * const _KeyLoadMoreItemShowActivity; @interface SOLoadMoreItem : SOBaseItem <NSCopying> /** * @brief 标题文本 */ @property (copy, nonatomic) NSString *title; /** * @brief 标签 */ @property (assign, nonatomic) NSInteger tag; /** * @brief 是否自动加载更多 */ @property (assign, nonatomic, getter=isAutoLoadMore) BOOL autoLoadMore; /** * @brief 加载时,是否显示提示 */ @property (assign, nonatomic, getter=isShowActivity) BOOL showActivity; /** * @brief 类初始化方法 * * @return 返回自身实例 */ + (instancetype)itemWithTitle:(NSString *)title tag:(NSInteger)tag autoLoadMore:(BOOL)autoLoadMore showActivity:(BOOL)showActivity; @end
/* crypto/cms/cms_att.c */ /* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL * project. */ /* ==================================================================== * Copyright (c) 2008 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * licensing@OpenSSL.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== */ #include <openssl/asn1t.h> #include <openssl/pem.h> #include <openssl/x509v3.h> #include <openssl/err.h> #include <openssl/cms.h> #include "cms_lcl.h" /* CMS SignedData Attribute utilities */ int CMS_signed_get_attr_count(const CMS_SignerInfo *si) { return X509at_get_attr_count(si->signedAttrs); } int CMS_signed_get_attr_by_NID(const CMS_SignerInfo *si, int nid, int lastpos) { return X509at_get_attr_by_NID(si->signedAttrs, nid, lastpos); } int CMS_signed_get_attr_by_OBJ(const CMS_SignerInfo *si, ASN1_OBJECT *obj, int lastpos) { return X509at_get_attr_by_OBJ(si->signedAttrs, obj, lastpos); } X509_ATTRIBUTE *CMS_signed_get_attr(const CMS_SignerInfo *si, int loc) { return X509at_get_attr(si->signedAttrs, loc); } X509_ATTRIBUTE *CMS_signed_delete_attr(CMS_SignerInfo *si, int loc) { return X509at_delete_attr(si->signedAttrs, loc); } int CMS_signed_add1_attr(CMS_SignerInfo *si, X509_ATTRIBUTE *attr) { if(X509at_add1_attr(&si->signedAttrs, attr)) return 1; return 0; } int CMS_signed_add1_attr_by_OBJ(CMS_SignerInfo *si, const ASN1_OBJECT *obj, int type, const void *bytes, int len) { if(X509at_add1_attr_by_OBJ(&si->signedAttrs, obj, type, bytes, len)) return 1; return 0; } int CMS_signed_add1_attr_by_NID(CMS_SignerInfo *si, int nid, int type, const void *bytes, int len) { if(X509at_add1_attr_by_NID(&si->signedAttrs, nid, type, bytes, len)) return 1; return 0; } int CMS_signed_add1_attr_by_txt(CMS_SignerInfo *si, const char *attrname, int type, const void *bytes, int len) { if(X509at_add1_attr_by_txt(&si->signedAttrs, attrname, type, bytes, len)) return 1; return 0; } void *CMS_signed_get0_data_by_OBJ(CMS_SignerInfo *si, ASN1_OBJECT *oid, int lastpos, int type) { return X509at_get0_data_by_OBJ(si->signedAttrs, oid, lastpos, type); } int CMS_unsigned_get_attr_count(const CMS_SignerInfo *si) { return X509at_get_attr_count(si->unsignedAttrs); } int CMS_unsigned_get_attr_by_NID(const CMS_SignerInfo *si, int nid, int lastpos) { return X509at_get_attr_by_NID(si->unsignedAttrs, nid, lastpos); } int CMS_unsigned_get_attr_by_OBJ(const CMS_SignerInfo *si, ASN1_OBJECT *obj, int lastpos) { return X509at_get_attr_by_OBJ(si->unsignedAttrs, obj, lastpos); } X509_ATTRIBUTE *CMS_unsigned_get_attr(const CMS_SignerInfo *si, int loc) { return X509at_get_attr(si->unsignedAttrs, loc); } X509_ATTRIBUTE *CMS_unsigned_delete_attr(CMS_SignerInfo *si, int loc) { return X509at_delete_attr(si->unsignedAttrs, loc); } int CMS_unsigned_add1_attr(CMS_SignerInfo *si, X509_ATTRIBUTE *attr) { if(X509at_add1_attr(&si->unsignedAttrs, attr)) return 1; return 0; } int CMS_unsigned_add1_attr_by_OBJ(CMS_SignerInfo *si, const ASN1_OBJECT *obj, int type, const void *bytes, int len) { if(X509at_add1_attr_by_OBJ(&si->unsignedAttrs, obj, type, bytes, len)) return 1; return 0; } int CMS_unsigned_add1_attr_by_NID(CMS_SignerInfo *si, int nid, int type, const void *bytes, int len) { if(X509at_add1_attr_by_NID(&si->unsignedAttrs, nid, type, bytes, len)) return 1; return 0; } int CMS_unsigned_add1_attr_by_txt(CMS_SignerInfo *si, const char *attrname, int type, const void *bytes, int len) { if(X509at_add1_attr_by_txt(&si->unsignedAttrs, attrname, type, bytes, len)) return 1; return 0; } void *CMS_unsigned_get0_data_by_OBJ(CMS_SignerInfo *si, ASN1_OBJECT *oid, int lastpos, int type) { return X509at_get0_data_by_OBJ(si->unsignedAttrs, oid, lastpos, type); } /* Specific attribute cases */
#ifndef _ImageSetSample_h_ #define _ImageSetSample_h_ #include <boost/shared_ptr.hpp> #include "Media/media_define.h" #include "Media/MediaSampleFactory.h" #include "Media/IImageSetSample.h" #include "Media/ImageSample.h" namespace Limitless { #pragma warning(push) #pragma warning(disable:4251) class MEDIA_EXPORT ImageSetSample:public AutoRegisterMediaSample<ImageSetSample, IImageSetSample> { public: ImageSetSample(); virtual ~ImageSetSample(); //MediaSample virtual unsigned char *buffer(){return m_buffer;} virtual size_t size() const{return m_size;} //IImageSetSample virtual IImageSample *operator[](int index); virtual size_t setSize(); void resize(unsigned int count, int width, int height, int channels=3, int channelBits=8); void resize(unsigned int count, int width, int pitch, int height, int channels, int channelBits); private: void freeBuffer(); std::vector<ImageSample *> m_imageSamples; unsigned char *m_buffer; int m_width; int m_pitch; int m_height; size_t m_size; int m_channels; int m_channelBits; }; typedef boost::shared_ptr<ImageSetSample> SharedImageSetSample; #pragma warning(pop) }//namespace Limitless #endif //_ImageSetSample_h_
#ifndef PAGEETIQUETTE_H #define PAGEETIQUETTE_H #include <QWidget> namespace Ui { class PageEtiquette; } class PageEtiquette : public QWidget { Q_OBJECT public: explicit PageEtiquette(QWidget *parent = 0); ~PageEtiquette(); private: Ui::PageEtiquette *ui; }; #endif // PAGEETIQUETTE_H
//======================================================================== // GLFW 3.1 POSIX - www.glfw.org //------------------------------------------------------------------------ // Copyright (c) 2002-2006 Marcus Geelnard // Copyright (c) 2006-2010 Camilla Berglund <elmindreda@elmindreda.org> // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would // be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must not // be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source // distribution. // //======================================================================== #ifndef _glfw3_posix_tls_h_ #define _glfw3_posix_tls_h_ #include <pthread.h> #define _GLFW_PLATFORM_LIBRARY_TLS_STATE _GLFWtlsPOSIX posix_tls // POSIX-specific global TLS data // typedef struct _GLFWtlsPOSIX { pthread_key_t context; } _GLFWtlsPOSIX; int _glfwCreateContextTLS(void); void _glfwDestroyContextTLS(void); void _glfwSetContextTLS(_GLFWwindow* context); #endif // _glfw3_posix_tls_h_
// // JoyNoDataBackView.h // Toon // // Created by wangguopeng on 16/9/1. // Copyright © 2016年 Joy. All rights reserved. // #import <UIKit/UIKit.h> @interface JoyNoDataBackView : UIView @property (nonatomic,copy)NSString *imageStr; @property(nonatomic,copy)NSString *labelStr; @end
#include "queue.h" int main (int argc, char * argv[]) { struct q_rep * q = malloc(sizeof(struct q_rep)); q->head = NULL; q->tail = NULL; // Write some tests! See if you can cover every possible case // WITHOUT looking at the implementation of the functions declared // in queue.h // // Try and test my implementation - see if it is a working // implementation... try and find a bug! for (int i = 0; i < 42; i++) { enqueue(q, i); } printQueue(q); queue_free(q); printQueue(q); for (int i = 0; i < 42; i++) { enqueue(q, i); } printQueue(q); queue_rfree(q); printQueue(q); return EXIT_SUCCESS; }
#ifndef MASTER_H #define MASTER_H #include <QtCore/QObject> #include <QtNetwork/QAbstractSocket> #include <QtNetwork/QHostAddress> #include "../src/socketconnector.h" #endif
// Copyright (c) 2018 Doyub Kim // // I am making my contributions/submissions to this project solely in my // personal capacity and am not conveying any rights to any intellectual // property of any third parties. #ifndef INCLUDE_JET_SERIAL_H_ #define INCLUDE_JET_SERIAL_H_ namespace jet { //! //! \brief Fills from \p begin to \p end with \p value. //! //! This function fills a container specified by begin and end iterators with //! single thread. The order of the filling is deterministic. //! //! \param[in] begin The begin iterator of a container. //! \param[in] end The end iterator of a container. //! \param[in] value The value to fill a container. //! //! \tparam RandomIterator Random iterator type. //! \tparam T Value type of a container. //! template <typename RandomIterator, typename T> void serialFill( const RandomIterator& begin, const RandomIterator& end, const T& value); //! //! \brief Makes a for-loop from \p beginIndex \p to endIndex. //! //! This function makes a for-loop specified by begin and end indices with //! single thread. The order of the visit is deterministic. //! //! \param[in] beginIndex The begin index. //! \param[in] endIndex The end index. //! \param[in] function The function to call for each index. //! //! \tparam IndexType Index type. //! \tparam Function Function type. //! template <typename IndexType, typename Function> void serialFor( IndexType beginIndex, IndexType endIndex, const Function& function); //! //! \brief Makes a 2D nested for-loop. //! //! This function makes a 2D nested for-loop specified by begin and end indices //! for each dimension. X will be the inner-most loop while Y is the outer-most. //! The order of the visit is deterministic. //! //! \param[in] beginIndexX The begin index in X dimension. //! \param[in] endIndexX The end index in X dimension. //! \param[in] beginIndexY The begin index in Y dimension. //! \param[in] endIndexY The end index in Y dimension. //! \param[in] function The function to call for each index (i, j). //! //! \tparam IndexType Index type. //! \tparam Function Function type. //! template <typename IndexType, typename Function> void serialFor( IndexType beginIndexX, IndexType endIndexX, IndexType beginIndexY, IndexType endIndexY, const Function& function); //! //! \brief Makes a 3D nested for-loop. //! //! This function makes a 3D nested for-loop specified by begin and end indices //! for each dimension. X will be the inner-most loop while Z is the outer-most. //! The order of the visit is deterministic. //! //! \param[in] beginIndexX The begin index in X dimension. //! \param[in] endIndexX The end index in X dimension. //! \param[in] beginIndexY The begin index in Y dimension. //! \param[in] endIndexY The end index in Y dimension. //! \param[in] beginIndexZ The begin index in Z dimension. //! \param[in] endIndexZ The end index in Z dimension. //! \param[in] function The function to call for each index (i, j, k). //! //! \tparam IndexType Index type. //! \tparam Function Function type. //! template <typename IndexType, typename Function> void serialFor( IndexType beginIndexX, IndexType endIndexX, IndexType beginIndexY, IndexType endIndexY, IndexType beginIndexZ, IndexType endIndexZ, const Function& function); //! //! \brief Sorts a container. //! //! This function sorts a container specified by begin and end iterators. //! //! \param[in] begin The begin random access iterator. //! \param[in] end The end random access iterator. //! //! \tparam RandomIterator Iterator type. //! template<typename RandomIterator> void serialSort(RandomIterator begin, RandomIterator end); //! //! \brief Sorts a container with a custom compare function. //! //! This function sorts a container specified by begin and end iterators. It //! takes extra compare function which returns true if the first argument is //! less than the second argument. //! //! \param[in] begin The begin random access iterator. //! \param[in] end The end random access iterator. //! \param[in] compare The compare function. //! //! \tparam RandomIterator Iterator type. //! \tparam CompareFunction Compare function type. //! template<typename RandomIterator, typename SortingFunction> void serialSort( RandomIterator begin, RandomIterator end, const SortingFunction& sortingFunction); } // namespace jet #include "detail/serial-inl.h" #endif // INCLUDE_JET_SERIAL_H_
// // EDWelcomeWindowController.h // Editor // // Created by Todd Ditchendorf on 9/27/13. // Copyright (c) 2013 Todd Ditchendorf. All rights reserved. // #import <Cocoa/Cocoa.h> @interface EDWelcomeWindowController : NSWindowController <NSTableViewDataSource, NSTableViewDelegate> - (id)init; // use me - (IBAction)newProject:(id)sender; - (IBAction)openSampleProject:(id)sender; @property (nonatomic, retain) IBOutlet NSTableView *tableView; @property (nonatomic, retain) NSString *titleText; @property (nonatomic, retain) NSString *versionText; @property (nonatomic, assign) BOOL busy; @property (nonatomic, assign) BOOL wantsExampleProjButton; @end
//%LICENSE//////////////////////////////////////////////////////////////// // // Licensed to The Open Group (TOG) under one or more contributor license // agreements. Refer to the OpenPegasusNOTICE.txt file distributed with // this work for additional information regarding copyright ownership. // Each contributor licenses this file to you under the OpenPegasus Open // Source License; you may not use this file except in compliance with the // License. // // 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. // ////////////////////////////////////////////////////////////////////////// // // Author: Mike Glantz, Hewlett-Packard Company <michael_glantz@hp.com> // //%//////////////////////////////////////////////////////////////////////////// #ifndef _TEST_PROCESSOR_PROVIDER_H #define _TEST_PROCESSOR_PROVIDER_H // ========================================================================== // Includes. // ========================================================================== #include "../ProcessorPlatform.h" PEGASUS_USING_STD; PEGASUS_USING_PEGASUS; #endif // #ifndef _TEST_PROCESSOR_PROVIDER_H
// // ValidatorForm.h // RYForm // // Created by xiaerfei on 16/5/24. // Copyright © 2016年 Rongyu100. All rights reserved. // #import <Foundation/Foundation.h> @interface ValidatorForm : NSObject /** * @author xiaerfei, 16-05-24 15:05:35 * * 验证值是否为空 * * @param value * * @return bool */ + (BOOL)validateValueIsEmptyWithValue:(id)value; /** * @author xiaerfei, 16-05-24 15:05:54 * * 验证身份证 * * @param cardNo * * @return bool */ + (BOOL)validateIdentityCardNo:(NSString*)cardNo; /** * @author xiaerfei, 16-05-24 15:05:19 * * 验证Email * * @param email * * @return */ + (BOOL)validateEmail:(NSString *)email; /** * @author xiaerfei, 16-05-24 16:05:51 * * 验证URL * * @param url url * * @return bool */ + (BOOL)validateURL:(NSString *)url; @end
/// -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: t -*- /// /// \file modulea.h /// \author Martin Reddy /// \brief A module that uses one of its methods as a callback. /// /// Copyright (c) 2010, Martin Reddy. All rights reserved. /// Distributed under the X11/MIT License. See LICENSE.txt. /// See http://APIBook.com/ for the latest version. /// /** More modern compilers will automatically dereference function pointers. -See moduleb.cpp -switched to "using" rather than typedef ((https://github.com/tlanc007/APIBookTweaks/blob/master/Tweak_Explainations.md#using) -switched to brace-init-list: see Tweak_Explainations.md (https://github.com/tlanc007/APIBookTweaks/blob/master/Tweak_Explainations.md#braceinitlist) -switched from nullptr from NULL **/ #ifndef MODULEA_H #define MODULEA_H #include <string> namespace apibook { /// /// An object that wishes to receive a callback from another /// module. To simplify calling an member function for a /// specific instance of this class, a static wrapper function /// can be used for the callback. This essentially accepts the /// object instance as an additional parameter. /// class ModuleA { public: /// A static function that lets you call a member function static void StaticWrapper (void *obj, const std::string &name, void *data); /// The member function callback void InstanceMethod (const std::string &name, void *data); }; } #endif
// // AppDelegate.h // NotificationsHW // // Created by Artem Belkov on 23/06/15. // Copyright © 2015 Artem Belkov. All rights reserved. // #import <UIKit/UIKit.h> @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
#ifndef TR_UI #define TR_UI #include <ncurses.h> #include "bookcase.h" int update_content(WINDOW* wp, int fp, long index[], int *now); int update_bks(WINDOW* wp, bookcase_t* bcp, int highlight); int update_bcs(WINDOW* wp, manifest_t* mp, int highlight); int switch_to_bk(WINDOW* wp, char* filename); int switch_to_bks(WINDOW* wp, bookcase_t* bcp); int display_help(WINDOW* wp); int display_ui(manifest_t* mp); #endif
#ifdef __OBJC__ #import <UIKit/UIKit.h> #endif #import "DATASource.h" FOUNDATION_EXPORT double DATASourceVersionNumber; FOUNDATION_EXPORT const unsigned char DATASourceVersionString[];
// Copyright 2015-present 650 Industries. All rights reserved. #import <UIKit/UIKit.h> #import <React/RCTBridgeModule.h> #import <React/RCTEventEmitter.h> @interface EXLinkingManager : RCTEventEmitter - (instancetype)initWithInitialUrl: (NSURL *)initialUrl; - (void)dispatchOpenUrlEvent: (NSURL *)url; @end
/* * Generated by class-dump 3.3.4 (64 bit). * * class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2011 by Steve Nygard. */ #import <UIKit/UIImageView.h> @class NSArray, NSString, UIView, _UIBadgeView, _UISegmentedControlAppearanceStorage; // Not exported @interface UISegment : UIImageView { UIView *_info; _UISegmentedControlAppearanceStorage *_appearanceStorage; double _width; struct CGSize _contentOffset; long long _barStyle; unsigned long long _rightSegmentState; NSString *_badgeValue; _UIBadgeView *_badgeView; id _objectValue; struct { unsigned int style:3; unsigned int size:2; unsigned int selected:1; unsigned int highlighted:1; unsigned int showDivider:1; unsigned int hasImage:1; unsigned int position:3; unsigned int autosizeText:1; unsigned int isMomentary:1; unsigned int wasSelected:1; } _segmentFlags; NSArray *_infoConstraints; double _requestedScaleFactor; } + (id)_backgroundImageWithStorage:(id)arg1 style:(long long)arg2 mini:(_Bool)arg3 state:(unsigned long long)arg4 position:(unsigned int)arg5 drawMode:(int *)arg6 defaultBlock:(id)arg7; @property(nonatomic) double requestedScaleFactor; // @synthesize requestedScaleFactor=_requestedScaleFactor; @property(copy, nonatomic, setter=_setInfoConstraints:) NSArray *_infoConstraints; // @synthesize _infoConstraints; - (id)viewForBaselineLayout; - (double)_idealWidth; - (struct UIEdgeInsets)_paddingInsets; - (_Bool)useBlockyMagnificationInClassic; - (id)hitTest:(struct CGPoint)arg1 forEvent:(struct __GSEvent *)arg2; - (id)hitTest:(struct CGPoint)arg1 withEvent:(id)arg2; - (id)infoName; - (void)_forceInfoDisplay; - (id)objectValue; - (void)setObjectValue:(id)arg1; - (void)setContentOffset:(struct CGSize)arg1; - (id)label; - (void)setPosition:(unsigned int)arg1; - (void)setBounds:(struct CGRect)arg1; - (void)setFrame:(struct CGRect)arg1; - (void)_positionInfo; - (void)updateConstraints; - (void)_invalidateInfoConstraints; - (struct CGSize)contentSize; - (struct CGSize)_maximumTextSize; - (double)_barHeight; - (struct CGRect)contentRect; - (struct CGRect)_contentRectForBounds:(struct CGRect)arg1; - (void)animateRemoveForWidth:(double)arg1; - (void)animateAdd:(_Bool)arg1; - (_Bool)_shouldUsePadMomentaryAppearance; - (void)setShowDivider:(_Bool)arg1; - (_Bool)showDivider; @property int controlSize; @property(getter=isMomentary) _Bool momentary; @property(readonly) UIView *badgeView; @property(copy, nonatomic) NSString *badgeValue; - (void)tintColorDidChange; - (void)setHighlighted:(_Bool)arg1; - (_Bool)isHighlighted; @property(getter=isSelected) _Bool selected; - (void)setEnabled:(_Bool)arg1; - (void)_setEnabledAppearance:(_Bool)arg1; - (void)setAutosizeText:(_Bool)arg1; - (void)setTintColor:(id)arg1; - (void)setBarStyle:(long long)arg1; - (id)disabledTextColor; - (id)_attributedTextForState:(unsigned long long)arg1 selected:(_Bool)arg2; - (void)_updateTextColors; - (void)setWasSelected:(_Bool)arg1; - (void)updateMasking; - (_Bool)_hasSelectedColor; - (id)_currentOptionsStyleTextShadowColor; - (id)_currentOptionsStyleTextColor; - (void)_updateBackgroundImage; - (void)updateDividerViewForChangedSegment:(id)arg1; - (void)insertDividerView; - (id)_dividerImage; - (void)updateForAppearance:(id)arg1 style:(int)arg2; - (id)_dividerImageIsCustom:(_Bool *)arg1; - (unsigned long long)_segmentState; - (_Bool)_isInMiniBar; - (void)dealloc; - (void)encodeWithCoder:(id)arg1; - (void)_populateArchivedSubviews:(id)arg1; - (id)_tintColorArchivingKey; - (id)initWithCoder:(id)arg1; - (id)initWithInfo:(id)arg1 style:(long long)arg2 size:(int)arg3 barStyle:(long long)arg4 tintColor:(id)arg5 appearanceStorage:(id)arg6 position:(unsigned int)arg7 autosizeText:(_Bool)arg8; - (void)_commonSegmentInit; @end
// // HXWaveRateChartViewController.h // HXChartDemo // // Created by hubery on 2017/10/28. // Copyright © 2017年 hubery. All rights reserved. // 水波进度 #import <UIKit/UIKit.h> #import "HXChart.h" @interface HXWaveRateChartViewController : UIViewController @end
// // HEROTableViewCell.h // fluidArchitecture // // Created by Moritz Ellerbrock on 23/01/17. // Copyright © 2017 fluidmobile GmbH. All rights reserved. // #import <UIKit/UIKit.h> #import "HEROBaseViewInterface.h" @interface HEROTableViewCell : UITableViewCell <HEROBaseViewInterface> @end
#ifndef _QUN_H #define _QUN_H #include "qqdef.h" typedef struct qunmember{ uint number; char nickname[NICKNAME_LEN]; ushort face; uchar age; uchar sex; uchar qqshow; uchar flag; uchar status; uchar account_flag; char account[ACCOUNT_LEN]; //email account uchar role, org; }qunmember; typedef struct qqqun{ uint number; //internal number uint ext_number; //external number char name[NICKNAME_LEN]; char ann[256]; //announcement ( too long the word ) char intro[256]; uint category; uint owner; ushort max_member; uchar auth_type; uchar type; //qun type uint order; token token_cmd; list member_list; }qqqun; struct qqclient; qqqun* qun_get( struct qqclient* qq, uint number, int create ); qqqun* qun_get_by_ext( struct qqclient* qq, uint ext_number ); void qun_remove( struct qqclient* qq, uint number ); qunmember* qun_member_get( struct qqclient* qq, qqqun* q, uint number, int create ); void qun_member_remove( struct qqclient* qq, qqqun* q, uint number ); void qun_update_memberinfo( struct qqclient* qq, qqqun* q ); void qun_update_info( struct qqclient* qq, qqqun* q ); void qun_update_online( struct qqclient* qq, qqqun* q ); void qun_update_all( struct qqclient* qq ); void qun_set_members_off( struct qqclient* qq, qqqun* q ); void qun_member_cleanup( struct qqclient* qq ); int qun_send_message( struct qqclient* qq, uint number, char* msg ); void qun_put_single_event( struct qqclient* qq, qqqun* q ); void qun_put_event( struct qqclient* qq ); void qun_update_online_all( struct qqclient* qq ); #endif
#ifndef OPTIONSMODEL_H #define OPTIONSMODEL_H #include "bignum.h" // for mpq #include <QAbstractListModel> /** Interface from Qt to configuration data structure for applebycoin client. To Qt, the options are presented as a list with the different options laid out vertically. This can be changed to a tree once the settings become sufficiently complex. */ class OptionsModel : public QAbstractListModel { Q_OBJECT public: explicit OptionsModel(QObject *parent = 0); enum OptionID { StartAtStartup, // bool MinimizeToTray, // bool MapPortUPnP, // bool MinimizeOnClose, // bool ProxyUse, // bool ProxyIP, // QString ProxyPort, // int ProxySocksVersion, // int Fee, // mpq serialized as QString DisplayUnit, // applebycoinUnits::Unit DisplayAddresses, // bool DetachDatabases, // bool Language, // QString OptionIDRowCount, }; void Init(); /* Migrate settings from wallet.dat after app initialization */ bool Upgrade(); /* returns true if settings upgraded */ int rowCount(const QModelIndex & parent = QModelIndex()) const; QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const; bool setData(const QModelIndex & index, const QVariant & value, int role = Qt::EditRole); /* Explicit getters */ mpq getTransactionFee(); bool getMinimizeToTray() { return fMinimizeToTray; } bool getMinimizeOnClose() { return fMinimizeOnClose; } int getDisplayUnit() { return nDisplayUnit; } bool getDisplayAddresses() { return bDisplayAddresses; } QString getLanguage() { return language; } private: int nDisplayUnit; bool bDisplayAddresses; bool fMinimizeToTray; bool fMinimizeOnClose; QString language; signals: void displayUnitChanged(int unit); }; #endif // OPTIONSMODEL_H
/* * Generated by class-dump 3.3.4 (64 bit). * * class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2011 by Steve Nygard. */ #import <iWorkImport/TSDKnob.h> // Not exported @interface TSDAudioKnob : TSDKnob { } - (_Bool)isHitByUnscaledPoint:(struct CGPoint)arg1 andRep:(id)arg2 returningDistance:(double *)arg3; - (void)updateHitRegionPathForRep:(id)arg1; - (id)layer; - (id)knobImage; - (id)initOnRep:(id)arg1; @end
// // ExPloreModelArr.h // MONOV3 // // Created by apple on 16/3/29. // Copyright © 2016年 JiangChile. All rights reserved. // #import "BaseModel.h" #import "Meow.h" @interface ExPloreModelArr : BaseModel + (NSMutableArray *)getExPloreModelArray:(NSDictionary *)dictionary; @end
/* * Copyright (c) 2004, Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the Institute nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * This file is part of the Contiki operating system. * * Author: Adam Dunkels <adam@sics.se> * */ #include "contiki-conf.h" #include "dev/xmem.h" #include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <stdio.h> #include <string.h> #define XMEM_SIZE 1024 * 1024 static unsigned char xmem[XMEM_SIZE]; /*---------------------------------------------------------------------------*/ int xmem_pwrite(const void *buf, int size, unsigned long offset) { /* int f; char name[400]; snprintf(name, sizeof(name), "xmem.%d.%d", node_x(), node_y()); f = open(name, O_WRONLY | O_APPEND | O_CREAT, 0644); lseek(f, addr, SEEK_SET); write(f, buf, size); close(f);*/ /* printf("xmem_write(offset 0x%02x, buf %p, size %l);\n", offset, buf, size);*/ memcpy(&xmem[offset], buf, size); return size; } /*---------------------------------------------------------------------------*/ int xmem_pread(void *buf, int size, unsigned long offset) { /* printf("xmem_read(addr 0x%02x, buf %p, size %d);\n", addr, buf, size);*/ memcpy(buf, &xmem[offset], size); return size; } /*---------------------------------------------------------------------------*/ int xmem_erase(long nbytes, unsigned long offset) { /* printf("xmem_read(addr 0x%02x, buf %p, size %d);\n", addr, buf, size);*/ memset(&xmem[offset], 0, nbytes); return nbytes; } /*---------------------------------------------------------------------------*/ void xmem_init(void) { } /*---------------------------------------------------------------------------*/
// // StylesViewController.h // LMReportDemo // // Created by Chenly on 16/4/18. // Copyright © 2016年 Little Meaning. All rights reserved. // #import <UIKit/UIKit.h> @interface StylesViewController : UIViewController @end
/* This file is part of the FruitsMania game project, distributed under the MIT license. Repository: https://github.com/AndreiDiea/fruitsMania Description: FruitsMania is a SDL match-three concept/prototype game. Copyright: (c) 2014 Andrei Diea 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. */ #ifndef GAMEHUD_H #define GAMEHUD_H #include "SimpleRectGameObject.h" #include <boost/shared_ptr.hpp> #include <boost/make_shared.hpp> /** * class GameHUD * This implements game functionality for a HUD displaying time and score */ class GameHUD : public SimpleRectGameObject { public: /** * Constructs the HUD * @param parent The parent GameObject of this object * @param textureID The texture id of this game object(hud background). * @param position The position and dimensions in parent space of this gameobject */ GameHUD (GameObject *parent, TextureIds textureID, Rect position); /** * Empty Destructor */ virtual ~GameHUD ( ); /** * Called to set the seconds remaining */ void setTime(int seconds); /** * Called to set up the score */ void setScore(int score); /** * Called to increment the score */ void incrementScore(int increment); /** * Called the first frame to set things up in the gameobject. Called first by Start() */ virtual void EarlyStart ( ); /**Handles an event Called first by OnEvent * @param pEvent Pointer to an EventType abstract base class describing the event * @return bool Return false to stop propagating this event */ virtual bool EarlyOnEvent (EventType* pEvent ); private: //the current score int m_score; //two dogits of the score boost::shared_ptr<SimpleRectGameObject> m_ScoreUnitsDigit; boost::shared_ptr<SimpleRectGameObject> m_ScoreTensDigit; //two dogits of the time boost::shared_ptr<SimpleRectGameObject> m_TimeUnitsDigit; boost::shared_ptr<SimpleRectGameObject> m_TimeTensDigit; }; #endif // GameHUD_H
#ifndef ABOUT_H #define ABOUT_H #include <QWidget> #include "config.h" namespace Ui { class About; } class About : public QWidget { Q_OBJECT public: explicit About(QWidget *parent = 0); ~About(); private slots: void on_close_clicked(); void on_License_clicked(); void on_info_clicked(); private: Ui::About *ui; }; #endif // ABOUT_H
// // XHOperationNetworkKit.h // XHOperationNetworkKit // // Created by 曾 宪华 on 14-1-2. // Copyright (c) 2014年 嗨,我是曾宪华(@xhzengAIB),曾加入YY Inc.担任高级移动开发工程师,拍立秀App联合创始人,热衷于简洁、而富有理性的事物 QQ:543413507 主页:http://zengxianhua.com All rights reserved. // #import <Foundation/Foundation.h> typedef void (^XHHTTPProgressHandler)(CGFloat progress, unsigned long long total); typedef void (^XHJSONSuccessHandler)(id json); typedef void (^XHHTTPSuccessHandler)(NSData *responseData, NSURLResponse *response); typedef void (^XHHTTPFailureHandler)(NSData *responseData, NSURLResponse *response, NSError *error); @interface XHOperationNetworkKit : NSOperation - (id)initWithRequest:(NSURLRequest *)request; - (id)initWithRequest:(NSURLRequest *)request jsonSuccessHandler:(XHJSONSuccessHandler)jsonSuccessHandler failureHandler:(XHHTTPFailureHandler)failureHandler; - (id)initWithRequest:(NSURLRequest *)request successHandler:(XHHTTPSuccessHandler)successHandler failureHandler:(XHHTTPFailureHandler)failureHandler; - (void)setSuccessHandler:(XHHTTPSuccessHandler)successHandler; - (void)setFailureHandler:(XHHTTPFailureHandler)failureHandler; - (void)setProgressHandler:(XHHTTPProgressHandler)progressHandler; - (void)startRequest; @end
#include <stdio.h> #include "framework/logging.h" #include "framework/actors.h" #include "framework/display.h" #include "framework/input.h" #include "framework/numbers.h" #include "systems.h" #include "entities.h" #include "spells.h" #include "rects.h" #include "graphics.h" #include "particles.h" #include "lights.h" #include "player.h" #include "level.h" #include "items.h" #include "intro.h" #include "ai.h" #include "ui.h" int ATTRACT_TIME = 0, ATTRACT_TIME_MAX = 8; int GAME_DELAY = 0; int GAME_DELAY_MAX = 8; void setup() { //Setup systems startLogging(LOGGING_DEBUG); logString(LOGGING_DEBUG, WINDOW_TITLE); startNumbers(); startInput(); createDisplay(); setupUi(); actorSetup(); itemSetup(); //createPlayer(); levelSetup(); startEntities(); startSystems(); startSpells(); startRects(); startParticles(); startAi(); //Attract screen generateLevel(); } int main() { character *player = NULL; setup(); //showIntro(); while (!TCOD_console_is_window_closed()) { inputLogic(); tickSystemsWithMask(getWorld(), EVENT_INPUT); playerInputLogic(); if (isTCODCharPressed(TCODK_ESCAPE)) { break; } if (!getPlayer() && isTCODCharPressed(TCODK_SPACE)) { setLevel(1); createPlayer(); generateLevel(); continue; } player = getPlayer(); while (!player || (getPlayerMoveCount() && !GAME_DELAY)) { if ((!player && !ATTRACT_TIME) || (player && getPlayerMoveCount())) { tickSystemsWithMask(getWorld(), EVENT_TICK); actorLogic(); itemLogic(); lightLogic(); } if (!player) { break; } else { if (player->nextStanceFlagsToAdd || player->nextStanceFlagsToRemove) { GAME_DELAY = GAME_DELAY_MAX; } } } if (GAME_DELAY) { GAME_DELAY --; } if (!player) { if (!ATTRACT_TIME) { ATTRACT_TIME = ATTRACT_TIME_MAX; } else { ATTRACT_TIME --; } } playerLogic(); uiLogic(); if (player && levelLogic()) { continue; } graphicsLogic(); composeScene(); displayLogic(); actorCleanup(); } actorsShutdown(); lightsShutdown(); itemsShutdown(); levelShutdown(); return 0; }
/** * hook.c * * Copyright (c) 2017 endaaman * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. */ #include "hook.h" #define HOOK_KEY_TITLE "title" #define HOOK_KEY_BELL "bell" #define HOOK_KEY_CLICKED "clicked" #define HOOK_KEY_SCROLL "scroll" #define HOOK_KEY_DRAG "drag" #define HOOK_KEY_ACTIVATED "activated" #define HOOK_KEY_DEACTIVATED "deactivated" #define HOOK_KEY_SELECTED "selected" #define HOOK_KEY_UNSELECTED "unselected" #define HOOK_KEY_SIGNAL "signal" const char* HOOK_KEYS[] = { HOOK_KEY_TITLE, HOOK_KEY_BELL, HOOK_KEY_CLICKED, HOOK_KEY_SCROLL, HOOK_KEY_DRAG, HOOK_KEY_ACTIVATED, HOOK_KEY_DEACTIVATED, HOOK_KEY_SELECTED, HOOK_KEY_UNSELECTED, HOOK_KEY_SIGNAL, NULL }; Hook* hook_init() { Hook* hook = g_malloc0(sizeof(Hook)); hook->refs = g_hash_table_new_full( g_str_hash, g_str_equal, (GDestroyNotify)g_free, (GDestroyNotify)g_free ); int i = 0; while (HOOK_KEYS[i]) { int* p = g_malloc0(sizeof(int)); *p = -1; g_hash_table_insert(hook->refs, g_strdup(HOOK_KEYS[i]), p); i += 1; } return hook; } void hook_close(Hook* hook) { g_hash_table_destroy(hook->refs); g_free(hook); } static int hook_get_ref(Hook* hook, const char* key) { int* ptr = g_hash_table_lookup(hook->refs, key); if (!ptr) { dd("invalid hook key: '%s'", key); return -1; } return *ptr; } bool hook_set_ref(Hook* hook, const char* key, int ref, int* old_ref) { assert(old_ref); void* old_key = NULL; void* old_value = NULL; bool has_value = g_hash_table_lookup_extended(hook->refs, key, &old_key, &old_value); if (old_value) { *old_ref = *(int*)old_value; } if (!has_value) { return false; } g_hash_table_remove(hook->refs, old_key); g_hash_table_insert(hook->refs, g_strdup(key), memdup(&ref, sizeof(int))); dd("hook '%s' is registered. ref: %d", key, ref); return true; } static bool hook_perform(Hook* hook, lua_State* L, const char* key, int narg, int nresult) { int ref = hook_get_ref(hook, key); if (ref < 0) { lua_pop(L, narg); return false; } lua_rawgeti(L, LUA_REGISTRYINDEX, ref); if (!lua_isfunction(L, -1)) { lua_pop(L, 1); // pop none-function dd("tried to call hook which is not function."); return false; } lua_insert(L, - narg - 1); dd("perform custom hook: %s", key); if (lua_pcall(L, narg, nresult, 0) != LUA_OK) { luaX_warn(L, "Error in hook function: '%s'", lua_tostring(L, -1)); lua_pop(L, 1); // error return false; } return true; } bool hook_perform_title(Hook* hook, lua_State* L, const char* title, bool* result) { if (!L) { return false; } lua_pushstring(L, title); bool succeeded = hook_perform(hook, L, HOOK_KEY_TITLE, 1, 1); if (!succeeded) { return false; } *result = lua_toboolean(L, -1); lua_pop(L, 1); return succeeded; } bool hook_perform_bell(Hook* hook, lua_State* L, bool* result) { assert(result); if (!L) { return false; } bool succeeded = hook_perform(hook, L, HOOK_KEY_BELL, 0, 1); if (!succeeded) { return false; } *result = lua_toboolean(L, -1); lua_pop(L, 1); return succeeded; } bool hook_perform_clicked(Hook* hook, lua_State* L, int button, const char* uri, bool* result) { assert(result); if (!L) { return false; } lua_pushinteger(L, button); lua_pushstring(L, uri); bool succeeded = hook_perform(hook, L, HOOK_KEY_CLICKED, 2, 1); if (!succeeded) { return false; } *result = lua_toboolean(L, -1); lua_pop(L, 1); return succeeded; } bool hook_perform_scroll(Hook* hook, lua_State* L, double delta_x, double delta_y, double x, double y, bool* result) { assert(result); if (!L) { return false; } lua_pushnumber(L, delta_x); lua_pushnumber(L, delta_y); lua_pushnumber(L, x); lua_pushnumber(L, x); bool succeeded = hook_perform(hook, L, HOOK_KEY_SCROLL, 4, 1); if (!succeeded) { return false; } *result = lua_toboolean(L, -1); lua_pop(L, 1); return succeeded; } bool hook_perform_drag(Hook* hook, lua_State* L, char* path, bool* result) { assert(result); lua_pushstring(L, path); bool succeeded = hook_perform(hook, L, HOOK_KEY_DRAG, 1, 1); if (!succeeded) { return false; } *result = lua_toboolean(L, -1); lua_pop(L, 1); return succeeded; } bool hook_perform_activated(Hook* hook, lua_State* L) { if (!L) { return false; } return hook_perform(hook, L, HOOK_KEY_ACTIVATED, 0, 0); } bool hook_perform_deactivated(Hook* hook, lua_State* L) { if (!L) { return false; } return hook_perform(hook, L, HOOK_KEY_DEACTIVATED, 0, 0); } bool hook_perform_selected(Hook* hook, lua_State* L, const char* text) { if (!L) { return false; } lua_pushstring(L, text); return hook_perform(hook, L, HOOK_KEY_SELECTED, 1, 0); } bool hook_perform_unselected(Hook* hook, lua_State* L) { if (!L) { return false; } return hook_perform(hook, L, HOOK_KEY_UNSELECTED, 0, 0); } bool hook_perform_signal(Hook* hook, lua_State* L, const char* param) { if (!L) { return false; } lua_pushstring(L, param); return hook_perform(hook, L, HOOK_KEY_SIGNAL, 1, 0); }
/** * @file gdt.c * @brief Handles operations with GDT. */ #include <kernel/gdt.h> #include <kernel/consts.h> #include <kernel/debug.h> #include <stdint.h> /** * @brief Will be sent to GDTR. */ struct GDTP { uint16_t size; ///< Size of GDT uint32_t off; ///< Offset of GDT } __attribute__((packed)); struct GDTP* gdtp; #define GDTP_GDT_GAP 8 extern char* setGDTR(struct GDTP* gdtp); /** * @brief Initialise GDTP */ void initGDTR() { mbp; gdtp = GDT_VMA_ADDR; gdtp->off = GDT_VMA_ADDR+GDTP_GDT_GAP; // right after gdtp } // TODO: all the structure stuff and its memory WHATEVER /** * @brief Returns GDT size. * * @return GDT size. */ uint16_t GDT_size() { return gdtp->size; } /** * @brief Returns GDT offset. * * @return GDT offset */ uint32_t GDT_offset() { return gdtp->off; } /** * @brief Sets GDT entry. * * @param[in] num The number of GDT entry * @param[in] base The base of GDT entry * @param[in] limit The limit of GDT entry * @param[in] access The access flags of GDT entry * @param[in] gran The granularity flags of GDT entry */ void gdt_set_gate(int num, unsigned long base, unsigned long limit, unsigned char access, unsigned char gran) { gdt_entry* gdte = gdtp->off+num*8; //mbp; gdte->base_low = (base & 0xFFFF); gdte->base_middle = (base >> 16) & 0xFF; gdte->base_high = (base >> 24) & 0xFF; /* Setup the descriptor limits */ gdte->limit_low = (limit & 0xFFFF); gdte->granularity = ((limit >> 16) & 0x0F); /* Finally, set up the granularity and access flags */ gdte->granularity |= (gran & 0xF0); gdte->access = access; } /** * @brief Flushes GDT into GDTR register. * * @param[in] num The number of GDT entries. */ void gdt_flush(int num) { gdtp->size = num*8; setGDTR(gdtp); }
#ifndef PLAYBACKMGR_H #define PLAYBACKMGR_H #define FFT_SIZE 4096 #include <QObject> #include <bass.h> #include "ui_playbackwidget.h" #include "dbi/dbi.h" class PlaybackWidget : public QWidget { Q_OBJECT public: explicit PlaybackWidget(QWidget *parent = 0); ~PlaybackWidget(); enum Playstate {PLAYING, STOPPED, PAUSED}; bool getFFT(void *buffer); signals: void songOver(); void stoppedPlaying(); public slots: void changeSong(QString path); void changeState(Playstate s); void togglePlay(); void seek(float ratio); private: Ui::pbwidget ui; DBI* db; int cursonglength; int cursongblength; //Byte length DWORD curchan; Playstate state; std::unique_ptr<QTimer> updateTimer; QPixmap play; QPixmap pause; void stopSong(); static inline QString msToString(int ms); private slots: void update(); }; #endif // PLAYBACKMGR_H
/* * Generated by class-dump 3.3.4 (64 bit). * * class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2011 by Steve Nygard. */ #import <PhotoBoothEffects/PBFilter.h> @interface PBNormalFilter : PBFilter { } @end
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE190_Integer_Overflow__int_fgets_square_63b.c Label Definition File: CWE190_Integer_Overflow__int.label.xml Template File: sources-sinks-63b.tmpl.c */ /* * @description * CWE: 190 Integer Overflow * BadSource: fgets Read data from the console using fgets() * GoodSource: Set data to a small, non-zero number (two) * Sinks: square * GoodSink: Ensure there will not be an overflow before squaring data * BadSink : Square data, which can lead to overflow * Flow Variant: 63 Data flow: pointer to data passed from one function to another in different source files * * */ #include "std_testcase.h" #define CHAR_ARRAY_SIZE (3 * sizeof(data) + 2) #include <math.h> #ifndef OMITBAD void CWE190_Integer_Overflow__int_fgets_square_63b_badSink(int * dataPtr) { int data = *dataPtr; { /* POTENTIAL FLAW: if (data*data) > INT_MAX, this will overflow */ int result = data * data; printIntLine(result); } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void CWE190_Integer_Overflow__int_fgets_square_63b_goodG2BSink(int * dataPtr) { int data = *dataPtr; { /* POTENTIAL FLAW: if (data*data) > INT_MAX, this will overflow */ int result = data * data; printIntLine(result); } } /* goodB2G uses the BadSource with the GoodSink */ void CWE190_Integer_Overflow__int_fgets_square_63b_goodB2GSink(int * dataPtr) { int data = *dataPtr; /* FIX: Add a check to prevent an overflow from occurring */ if (abs((long)data) <= (long)sqrt((double)INT_MAX)) { int result = data * data; printIntLine(result); } else { printLine("data value is too large to perform arithmetic safely."); } } #endif /* OMITGOOD */
// // LFViewController.h // MapViewPolygonMask // // Copyright (c) 2014 Leonardo Ascione (https://github.com/leonardfactory) // // 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. // #import <UIKit/UIKit.h> @interface LFMapViewController : UIViewController @end
/* * Copyright (c) 2017 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #ifndef LOGGING_RTC_EVENT_LOG_EVENTS_RTC_EVENT_RTP_PACKET_INCOMING_H_ #define LOGGING_RTC_EVENT_LOG_EVENTS_RTC_EVENT_RTP_PACKET_INCOMING_H_ #include <memory> #include BOSS_WEBRTC_U_logging__rtc_event_log__events__rtc_event_h //original-code:"logging/rtc_event_log/events/rtc_event.h" #include BOSS_WEBRTC_U_modules__rtp_rtcp__source__rtp_packet_h //original-code:"modules/rtp_rtcp/source/rtp_packet.h" namespace webrtc { class RtpPacketReceived; class RtcEventRtpPacketIncoming final : public RtcEvent { public: explicit RtcEventRtpPacketIncoming(const RtpPacketReceived& packet); ~RtcEventRtpPacketIncoming() override; Type GetType() const override; bool IsConfigEvent() const override; std::unique_ptr<RtcEvent> Copy() const override; RtpPacket header_; // Only the packet's header will be stored here. const size_t packet_length_; // Length before stripping away all but header. private: RtcEventRtpPacketIncoming(const RtcEventRtpPacketIncoming& other); }; } // namespace webrtc #endif // LOGGING_RTC_EVENT_LOG_EVENTS_RTC_EVENT_RTP_PACKET_INCOMING_H_
/*============================================================================ This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic Package, Release 3e, by John R. Hauser. Copyright 2011, 2012, 2013, 2014, 2015, 2016 The Regents of the University of California. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions, and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions, and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. =============================================================================*/ #include <stdbool.h> #include <stdint.h> #include "platform.h" #include "internals.h" #include "specialize.h" #include "softfloat.h" int_fast64_t f16_to_i64_r_minMag( sw_float16_t a, bool exact ) { union ui16_f16 uA; uint_fast16_t uiA; int_fast8_t exp; uint_fast16_t frac; int_fast8_t shiftDist; bool sign; int_fast32_t alignedSig; /*------------------------------------------------------------------------ *------------------------------------------------------------------------*/ uA.f = a; uiA = uA.ui; exp = expF16UI( uiA ); frac = fracF16UI( uiA ); /*------------------------------------------------------------------------ *------------------------------------------------------------------------*/ shiftDist = exp - 0x0F; if ( shiftDist < 0 ) { if ( exact && (exp | frac) ) { softfloat_exceptionFlags |= softfloat_flag_inexact; } return 0; } /*------------------------------------------------------------------------ *------------------------------------------------------------------------*/ sign = signF16UI( uiA ); if ( exp == 0x1F ) { softfloat_raiseFlags( softfloat_flag_invalid ); return (exp == 0x1F) && frac ? i64_fromNaN : sign ? i64_fromNegOverflow : i64_fromPosOverflow; } /*------------------------------------------------------------------------ *------------------------------------------------------------------------*/ alignedSig = (int_fast32_t) (frac | 0x0400)<<shiftDist; if ( exact && (alignedSig & 0x3FF) ) { softfloat_exceptionFlags |= softfloat_flag_inexact; } alignedSig >>= 10; return sign ? -alignedSig : alignedSig; }
#pragma once #include <thread> class joining_thread { std::thread t; public: joining_thread() noexcept=default; template<typename Callable,typename ... Args> explicit joining_thread(Callable&& func,Args&& ... args): t(std::forward<Callable>(func),std::forward<Args>(args)...) {} explicit joining_thread(std::thread t_) noexcept: t(std::move(t_)) {} joining_thread(joining_thread&& other) noexcept: t(std::move(other.t)) {} joining_thread& operator=(joining_thread&& other) noexcept { if (joinable()) join(); t=std::move(other.t); return *this; } joining_thread& operator=(std::thread other) noexcept { if (joinable()) join(); t=std::move(other); return *this; } ~joining_thread() noexcept { if (joinable()) join(); } void swap(joining_thread& other) noexcept { t.swap(other.t); } std::thread::id get_id() const noexcept { return t.get_id(); } bool joinable() const noexcept { return t.joinable(); } void join() { t.join(); } void detach() { t.detach(); } std::thread& as_thread() noexcept { return t; } const std::thread& as_thread() const noexcept { return t; } };
#ifndef _wicked_wsqoperator_h_ #define _wicked_wsqoperator_h_ #include <string> class WIndex; enum SQOperatorType { Creation, Annihilation }; class WSQOperator { public: WSQOperator(SQOperatorType type, WIndex index); ~WSQOperator(); bool operator<(WSQOperator const &other) const; bool operator==(WSQOperator const &other) const; /// Return the type of this operator SQOperatorType type() const; /// Return the index of this operator WIndex index() const; /// Reindex this operator void reindex(index_map_t &idx_map); /// Return a string representation std::string str() const; /// Return a LaTeX representation std::string latex() const; /// Return an ambit (C++ code) representation std::string ambit() const; private: std::pair<SQOperatorType, WIndex> operator_; }; // Helper functions /// Print to an output stream std::ostream &operator<<(std::ostream &os, const WSQOperator &op); #endif // _wicked_wsqoperator_h_
// // DateTimeHandler.h // Hockey Playoffs // // Created by Pierre-Marc Airoldi on 2014-04-07. // Copyright (c) 2015 Pierre-Marc Airoldi. All rights reserved. // #import <Foundation/Foundation.h> @interface DateTimeHandler : NSObject +(NSDate *)now; +(NSString *)getDateForDate:(NSString *)date andTime:(NSString *)time; +(NSString *)getTimeForDate:(NSString *)date andTime:(NSString *)time; +(NSString *)getStringForDate:(NSDate *)date; @end
#ifndef PROGRESSBAR #define PROGRESSBAR //My Includes #include "IControl.h" #include "../Graphics/Direct3D.h" #include "../Input/Input.h" #include "../Graphics/2D/Sprite.h" #include "../Graphics/2D/Forms/Rectangle.h" ////////////////////////////////////////////////////////////////////////// //Class: ProgressBar ////////////////////////////////////////////////////////////////////////// namespace Hydro { class ProgressBar : public IControl { public: ProgressBar(Direct3D* _direct3D, std::string _name, Hydro::Rectangle _rect, std::string _textureFileName, int _screenWidth, int _screenHeight); bool Update(float eTime); bool Draw(float eTime, ID3D11DeviceContext *deviceContext, ShaderManager *shaderManager, DirectX::XMMATRIX worldMatrix, DirectX::XMMATRIX viewMatrix, DirectX::XMMATRIX orthoMatrix); void SetPosition(ID3D11DeviceContext * deviceContext, DirectX::XMINT2 _pos); void SetValue(short _value); void IncreaseValue(short add); void DecreaseValue(short dec); void SetMaxValue(short _maxValue); short GetMaxValue() const; private: Rectangle rect; Rectangle inner; Sprite border; //Sprite borderEnd; //Sprite borderMid; Sprite filling; //Sprite fillingEnd; //Sprite fillingMid; short value = 0; short maxValue = 100; }; } #endif // !PROGRESSBAR
#ifndef M2X_UTILITY_H #define M2X_UTILITY_H #if defined(__cplusplus) extern "C" { #endif typedef int (*path_filling_function)(char *buffer, const char *args[]); int query_with_interleave_fill(char *buffer, const char *args[]); int interleave_path_and_param_fill(char *buffer, const char *args[]); int path_and_query_fill(char *buffer, const char *args[]); void fill_random_hex_string(char *buf, int len); int fill_request_buffer_with_func(char *buffer, const char *id, const char *method, path_filling_function f, const char *args[], const char *body); #if defined(__cplusplus) } /* extern "C" { */ #endif #endif /* M2X_UTILITY_H */
// -*- c++ -*- #ifndef SIM_BINARY_SAMPLER_H #define SIM_BINARY_SAMPLER_H #include <ostream> #include <string> #include <vector> #include <utility> #include <cstddef> class Config; namespace Simulator { class VariableRegistry; // BinarySampler: used by Monitor to quickly serialize scalar // variables to a binary format. class BinarySampler { private: typedef std::vector<std::pair<const char*, size_t> > vars_t; size_t m_datasize; ///< The record size in bytes vars_t m_vars; ///< The variables to sample const VariableRegistry& m_registry; ///< The related registry public: // Create a binary sampler BinarySampler(const VariableRegistry& registry); // Select a set of variables and dump a serialization // header. void SelectVariables(std::ostream& os, const Config& config, const std::vector<std::string>& pats); // Perform the sampling void SampleToBuffer(char *buf) const { for (auto& i : m_vars) for (size_t j = 0; j < i.second; ++j) *buf++ = i.first[j]; } size_t GetBufferSize() const { return m_datasize; } }; } #endif
// // Transacao.h // CrossAppTeste // // Created by Andre Luiz Costa on 24/08/15. // Copyright (c) 2015 OneBuy. All rights reserved. // #import <Foundation/Foundation.h> #import "Criptografia.h" @interface Transacao : NSObject @property (retain) NSString *DataFinal; @property (retain) NSString *DataInicial; @property (retain) NSString *NumeroTransacao; - (void)descriptografar:(NSString *) chaveCriptografia; @end
#ifndef __GK_BASE_CONCURRENCY__ #define __GK_BASE_CONCURRENCY__ #include<thread> #include<Windows.h> #include<mutex> #include<iostream> namespace gk{ namespace base{ class gkmutex{ #if _MSC_VER > 1800 mutex m_mutex; public: void lock(){ m_mutex.lock(); } void unlock(){ m_mutex.unlock(); } }; mutex gklock::m_mutex; #else CRITICAL_SECTION cs_m; public: gkmutex(){ InitializeCriticalSectionAndSpinCount(&cs_m, 1000); } ~gkmutex(){ DeleteCriticalSection(&cs_m); } void lock(){ EnterCriticalSection(&cs_m); } void unlock(){ LeaveCriticalSection(&cs_m); } }; #endif class gklock{ gkmutex &mutex; public: gklock(gkmutex&gkm) :mutex(gkm){ mutex.lock(); } ~gklock(){ mutex.unlock(); } }; } } #endif
// ring.c : Defines the entry point for the console application. // #include <stdio.h> #include <stdlib.h> #include "ring.h" /* Create a ring buffer with the specified size. Return the ring or NULL if there is not enough memory to create. */ struct ring* ring_create(int size) { struct ring *rb = (struct ring*)malloc(sizeof(struct ring )); if (rb == NULL) { printf("Does not have enough memory for creating ring_buffer.\n"); return NULL; } rb->size = size; rb->pop = 0; rb->push = 0; rb->count = 0; rb->items = (void**)malloc(sizeof(void*) ); if (rb->items == NULL) { printf("Does not have enough memory for creating item.\n"); return NULL; } return rb; }; /* Add an entry to the ring. Return 0 on success, or a sensible error code if ring is full */ int ring_push(struct ring *rb, void* data) { if ( rb->count < rb->size ){ rb->items[ rb->push ] = data; rb->push = (rb->push + 1) % rb->size; rb->count = rb->count +1; return 0; } else{ return -1; } } /* Remove an entry from the ring. Return a pointer to the data, or NULL if empty */ void* ring_pop(struct ring *rb) { if ( rb->count <= 0 ){ return NULL; } else{ void* temp; temp = rb->items[ rb->pop ]; rb->pop = (rb->pop + 1) % rb->size; rb->count = rb->count - 1; return temp; } }
/*================================================================= * Jason Tam * October 2013 * An attempt to make my Othello AI faster by using C * Syntax in MATLAB: * * [ nextBoards, actions] = getAllValid( b, tok ) *=================================================================*/ #include <math.h> #include "mex.h" #include <string.h> /* memset */ #include <unistd.h> /* close */ /* Constants */ #define L 8 #define NB_DIMS 3 #define N_DIR 8 /* Input Arguments */ #define B_IN prhs[0] #define TOK_IN prhs[1] /* Output Arguments */ #define NB_OUT plhs[0] #define A_OUT plhs[1] /* Directional Index Modifications */ static int dirIndN (int m, int n, int off){return m-off+L*n;} static int dirIndS (int m, int n, int off){return m+off+L*n;} static int dirIndW (int m, int n, int off){return m+L*(n-off);} static int dirIndE (int m, int n, int off){return m+L*(n+off);} static int dirIndNW(int m, int n, int off){return m-off+L*(n-off);} static int dirIndSE(int m, int n, int off){return m+off+L*(n+off);} static int dirIndNE(int m, int n, int off){return m-off+L*(n+off);} static int dirIndSW(int m, int n, int off){return m+off+L*(n-off);} typedef int (*dirFnPtr)(int, int, int ); dirFnPtr dirFnPtrArr[N_DIR] = {dirIndN,dirIndS,dirIndW,dirIndE,dirIndNW,dirIndSE,dirIndNE,dirIndSW}; /* Directional Boundary Index Checks */ static int bdryN (int m, int n, int off){return m-off>=0;} static int bdryS (int m, int n, int off){return m+off<L;} static int bdryW (int m, int n, int off){return n-off>=0;} static int bdryE (int m, int n, int off){return n+off<L;} static int bdryNW(int m, int n, int off){return (m-off>=0)&&(n-off>=0);} static int bdrySE(int m, int n, int off){return (m+off<L)&&(n+off<L);} static int bdryNE(int m, int n, int off){return (m-off>=0)&&(n+off<L);} static int bdrySW(int m, int n, int off){return (m+off<L)&&(n-off>=0);} typedef int (*bFnPtr)(int, int, int ); bFnPtr bFnPtrArr[N_DIR] = {bdryN,dirIndS,bdryW,bdryE,bdryNW,bdrySE,bdryNE,bdrySW}; /* Flips peices */ static int rayFlip( double b[], int m, int n, double tok, double potB[], int (*dirFnPtr)(int, int, int), int (*bFnPtr)(int, int, int)) { int off = 1; int valid = 0; while ((*bFnPtr)(m,n,off)&& (b[(*dirFnPtr)(m,n,off)]==(-tok))) { off++; } if ((b[(*dirFnPtr)(m,n,off)]==tok)&&(off>1)) { for (;off>0;off--) {potB[(*dirFnPtr)(m,n,off)]=tok;} valid = 1; } return valid; } /* Attempts to Flip peices */ static int isValid( double b[], int m, int n, double tok, double potB[] ) { int valid = 0; int off; for (int di=0; di<N_DIR; di++) { valid += rayFlip( b, m, n, tok, potB, dirFnPtrArr[di], bFnPtrArr[di]); } /////////////////// ERROR ON THIS LINE??!?! ////////////It's totally this line // if (valid>0) { // mexPrintf("m: %d | n: %d | m*n: %d \n", m, n, m*n); // potB[m+L*n]=tok; // Place the actual move down // potB[1]=tok; // memcpy(potB+m+L*n,&tok,sizeof(double)); // } return valid; } /* Get all positions that cause flips */ static int getAllValid( double nb[], double a[], double b[], double *tok ) { int i=0, m=0, n=0, c=0; // index, row, col, tempiter, count double potB[L*L]; for ( n = 0; n < L; n++) { for ( m = 0; m < L; m++) { i = m+L*n; if (b[i]==0) { // Only analyze for empty spots memcpy(potB,b,sizeof(potB)); if (isValid(b,m,n,*tok,potB)>0) { // If it's a valid move a[c] = i+1; // add the 1 for matlab indexing here ////////////////ERROR ON THIS LINE WHEN TREE IS DEEP YO // memcpy(nb+(c++)*L*L,potB,sizeof(potB)); // Workaround for (int tm=0;tm<L;tm++) for (int tn=0;tn<L;tn++) nb[tm+L*(tn+L*c)] = potB[tm+L*tn]; c++; } } } } return c; } /* Main execution function */ void mexFunction( int nlhs, mxArray *plhs[], /* Input Vars */ int nrhs, const mxArray*prhs[] ) /* Output Vars */ { double *nb,*a; double *b,*tok; size_t m,n; /* Check for proper number of arguments */ if (nrhs != 2) { mexErrMsgIdAndTxt( "MATLAB:getAllValid:invalidNumInputs", "Two input arguments required."); } else if (nlhs > 2) { mexErrMsgIdAndTxt( "MATLAB:getAllValid:maxlhs", "Too many output arguments."); } /* Check the dimensions of board_in. */ m = mxGetM(B_IN); // Should be L n = mxGetN(B_IN); // Should be L if (!mxIsDouble(B_IN) || mxIsComplex(B_IN) || (m != L) || (n != L)) { mexErrMsgIdAndTxt( "MATLAB:getAllValid:invalid board", "getAllValid requires that Y be a L x L matrix."); } /* Assign pointers to the input parameters */ b = mxGetPr(B_IN); tok = mxGetPr(TOK_IN); /* Do the actual computations in a subroutine */ int n_valid; double nb_temp[L*L*L*L]; double a_temp[L*L]; n_valid = getAllValid(nb_temp,a_temp,b,tok); /* Create a matrix for the return argument */ const mwSize dims[]={L,L,n_valid}; NB_OUT = mxCreateNumericArray( NB_DIMS, dims, mxDOUBLE_CLASS, mxREAL); A_OUT = mxCreateDoubleMatrix( n_valid, 1, mxREAL); /* Assign pointers to the output parameters */ nb = mxGetPr(NB_OUT); a = mxGetPr(A_OUT); if (n_valid>0) { memcpy(nb,nb_temp,n_valid*L*L*sizeof(double)); memcpy(a,a_temp,n_valid*sizeof(double)); } return; }
// RoundFunc.h /* * Copyright (C) 2013 Spencer T. Parkin * * This software has been released under the MIT License. * See the "License.txt" file in the project root directory * for more information about this license. * */ //========================================================================================= class CalcLib::RoundNumberFunctionEvaluator : public FunctionEvaluator { DECLARE_CALCLIB_CLASS( RoundNumberFunctionEvaluator ); public: RoundNumberFunctionEvaluator( void ); virtual ~RoundNumberFunctionEvaluator( void ); virtual bool EvaluateResult( Number& result, Environment& environment ); }; // RoundFunc.h
/* Dooba Firmware - avr8 * SSD1306 OLED Display Library * * by Eresse <eresse@dooba.io> */ #ifndef __SSD1306_TXT_H #define __SSD1306_TXT_H // External Includes #include <stdint.h> #include <stdarg.h> #include <avr/io.h> // Format String Text Printer Info Structure struct ssd1306_txt_f_print_info { // Multi-Line uint8_t multi; // Start X int startx; // Position int x; int y; }; // Draw Single Character extern void ssd1306_txt_c(uint8_t c, int x, int y); // Draw Text extern void ssd1306_txt(void *s, int x, int y); // Draw Text - Safe extern void ssd1306_txt_n(void *s, uint8_t l, int x, int y); // Draw Text - Format String extern void ssd1306_txt_f(int x, int y, void *fmt, ...); // Draw Text - va_list extern void ssd1306_txt_v(int x, int y, void *fmt, va_list ap); // Draw Multi-Line Text extern void ssd1306_txt_multi(void *s, int x, int y); // Draw Multi-Line Text - Safe extern void ssd1306_txt_multi_n(void *s, uint8_t l, int x, int y); // Draw Multi-Line Text - Format String extern void ssd1306_txt_multi_f(int x, int y, void *fmt, ...); // Draw Multi-Line Text - va_list extern void ssd1306_txt_multi_v(int x, int y, void *fmt, va_list ap); // Format String Text Printer extern void ssd1306_txt_f_print(struct ssd1306_txt_f_print_info *info, uint8_t c); #endif
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard. // #import "MMObject.h" @class NSString; @interface VPResourceItem : MMObject { unsigned int uiResId; unsigned int uiScene; NSString *nsRes; } @property(nonatomic) unsigned int uiScene; // @synthesize uiScene; @property(nonatomic) unsigned int uiResId; // @synthesize uiResId; @property(retain, nonatomic) NSString *nsRes; // @synthesize nsRes; - (void).cxx_destruct; - (void)dealloc; - (id)init; @end
// // libViewController.h // test // // Created by OMyCar on 2017/8/30. // Copyright © 2017年 com.lxh. All rights reserved. // #import <UIKit/UIKit.h> @interface libViewController : UIViewController @end
/* * Generated by class-dump 3.3.4 (64 bit). * * class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2011 by Steve Nygard. */ #import "UIViewController.h" #import "UITableViewDataSource-Protocol.h" #import "UITableViewDelegate-Protocol.h" @class MPAVController, MPRadioAVItem, NSString, RadioStation, UIButton, UIImage, UILabel, UITableView; @interface MSRadioNowPlayingOptionsViewController : UIViewController <UITableViewDataSource, UITableViewDelegate> { NSString *_headerText; UILabel *_titleLabel; UIButton *_backButton; MPRadioAVItem *_nowPlayingItem; RadioStation *_station; MPAVController *_player; id <MSCarDisplayServiceProvider> _serviceProvider; UIImage *_albumImage; UITableView *_tableView; } @property(retain, nonatomic) UITableView *tableView; // @synthesize tableView=_tableView; @property(retain, nonatomic) UIImage *albumImage; // @synthesize albumImage=_albumImage; - (void).cxx_destruct; - (void)knobBackPressed:(id)arg1; - (void)_backButtonTouchUpInside:(id)arg1; - (void)tableView:(id)arg1 didSelectRowAtIndexPath:(id)arg2; - (id)tableView:(id)arg1 cellForRowAtIndexPath:(id)arg2; - (long long)tableView:(id)arg1 numberOfRowsInSection:(long long)arg2; - (void)tableView:(id)arg1 willDisplayCell:(id)arg2 forRowAtIndexPath:(id)arg3; - (void)viewDidLayoutSubviews; - (void)viewDidAppear:(_Bool)arg1; - (void)viewDidLoad; - (void)loadView; - (id)initWithItem:(id)arg1 headerText:(id)arg2 player:(id)arg3 serviceProvider:(id)arg4; @end
/* * Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #ifndef BODY_TYPES_H #define BODY_TYPES_H class BodyTypes : public Test { public: BodyTypes() { b2Body* ground = NULL; { b2BodyDef bd; ground = m_world->CreateBody(&bd); b2EdgeShape shape; shape.Set(b2Vec2(-20.0f, 0.0f), b2Vec2(20.0f, 0.0f)); b2FixtureDef fd; fd.shape = &shape; ground->CreateFixture(&fd); } // Define attachment { b2BodyDef bd; bd.type = b2_dynamicBody; bd.position.Set(0.0f, 3.0f); m_attachment = m_world->CreateBody(&bd); b2PolygonShape shape; shape.SetAsBox(0.5f, 2.0f); m_attachment->CreateFixture(&shape, 2.0f); } // Define platform { b2BodyDef bd; bd.type = b2_dynamicBody; bd.position.Set(-4.0f, 5.0f); m_platform = m_world->CreateBody(&bd); b2PolygonShape shape; shape.SetAsBox(0.5f, 4.0f, b2Vec2(4.0f, 0.0f), 0.5f * b2_pi); b2FixtureDef fd; fd.shape = &shape; fd.friction = 0.6f; fd.density = 2.0f; m_platform->CreateFixture(&fd); b2RevoluteJointDef rjd; rjd.Initialize(m_attachment, m_platform, b2Vec2(0.0f, 5.0f)); rjd.maxMotorTorque = 50.0f; rjd.enableMotor = true; m_world->CreateJoint(&rjd); b2PrismaticJointDef pjd; pjd.Initialize(ground, m_platform, b2Vec2(0.0f, 5.0f), b2Vec2(1.0f, 0.0f)); pjd.maxMotorForce = 1000.0f; pjd.enableMotor = true; pjd.lowerTranslation = -10.0f; pjd.upperTranslation = 10.0f; pjd.enableLimit = true; m_world->CreateJoint(&pjd); m_speed = 3.0f; } // Create a payload { b2BodyDef bd; bd.type = b2_dynamicBody; bd.position.Set(0.0f, 8.0f); b2Body* body = m_world->CreateBody(&bd); b2PolygonShape shape; shape.SetAsBox(0.75f, 0.75f); b2FixtureDef fd; fd.shape = &shape; fd.friction = 0.6f; fd.density = 2.0f; body->CreateFixture(&fd); } } void Keyboard(int key) { switch (key) { case SDLK_d://GLFW_KEY_D: m_platform->SetType(b2_dynamicBody); break; case SDLK_s://GLFW_KEY_S: m_platform->SetType(b2_staticBody); break; case SDLK_k://GLFW_KEY_K: m_platform->SetType(b2_kinematicBody); m_platform->SetLinearVelocity(b2Vec2(-m_speed, 0.0f)); m_platform->SetAngularVelocity(0.0f); break; } } void Step(Settings* settings) { // Drive the kinematic body. if (m_platform->GetType() == b2_kinematicBody) { b2Vec2 p = m_platform->GetTransform().p; b2Vec2 v = m_platform->GetLinearVelocity(); if ((p.x < -10.0f && v.x < 0.0f) || (p.x > 10.0f && v.x > 0.0f)) { v.x = -v.x; m_platform->SetLinearVelocity(v); } } Test::Step(settings); g_debugDraw.DrawString(5, m_textLine, "Keys: (d) dynamic, (s) static, (k) kinematic"); m_textLine += DRAW_STRING_NEW_LINE; } static Test* Create() { return new BodyTypes; } b2Body* m_attachment; b2Body* m_platform; float32 m_speed; }; #endif
// // CSTableViewCell.h // Samples // // Created by allting on 2/13/14. // // #import <UIKit/UIKit.h> @class KRSyncItem; @interface CSTableViewCell : UITableViewCell -(void)setSyncItem:(KRSyncItem*)syncItem documentsPath:(NSString*)documentsPath; -(void)setProgressValue:(CGFloat)value; @end
#ifndef NCODE_CIRCULAR_ARRAY_H_ #define NCODE_CIRCULAR_ARRAY_H_ #include <array> #include <cstdbool> #include <vector> #include "common.h" #include "logging.h" namespace nc { // A simple circular array. template <typename T, size_t NumValues> class CircularArray { public: static constexpr size_t kMaxValues = NumValues; CircularArray() : num_values_(0), index_(0) { static_assert(IsPowerOfTwo(NumValues), "Number of values should be power of 2"); } // Adds a new value to this array. void AddValue(T value) { values_[index_++ & kMask] = value; if (num_values_ < NumValues) { num_values_++; } } // Moves a value into this array. void MoveValue(T&& value) { values_[index_++ & kMask] = std::move(value); if (num_values_ < NumValues) { num_values_++; } } // Number of elements in the array. size_t size() const { return num_values_; } // Returns true if the array has no values. bool empty() const { return num_values_ == 0; } // Returns a const reference to the most recently inserted value in the array // or dies if the array is empty. const T& MostRecentValueOrDie() const { CHECK(num_values_ > 0) << "Circular array empty"; return values_[(index_ - 1) & kMask]; } // Returns a const reference to the value that has spent the most time in the // array. const T& OldestValueOrDie() const { CHECK(num_values_ > 0) << "Circular array empty"; size_t start = (index_ - num_values_) & kMask; return values_[start]; } // Returns a vector with all values in this array, in insertion order. After // this call the array will be empty. std::vector<T> GetValues() { size_t start = (index_ - num_values_) & kMask; std::vector<T> values; values.reserve(num_values_); for (size_t i = 0; i < num_values_; ++i) { size_t value_index = (start + i) & kMask; values.emplace_back(std::move(values_[value_index])); } num_values_ = 0; index_ = 0; return values; } private: static constexpr size_t kMask = NumValues - 1; size_t num_values_; size_t index_; std::array<T, NumValues> values_; DISALLOW_COPY_AND_ASSIGN(CircularArray); }; } // namespace nc #endif
#ifndef ILLA_C_FACTORY_H #define ILLA_C_FACTORY_H #include "types.h" #include <string> #include <vector> namespace Img { class AbstractCodec; class ICodecFactory { public: typedef std::vector<std::string> ExtensionList; public: const ExtensionList& SupportedExtensions() const; const std::string& GetFormatName() const; virtual AbstractCodec* CreateCodec()=0; ICodecFactory(const std::string& name):m_name(name) {} virtual ~ICodecFactory() {} protected: void AddExtension(const std::string& extension); private: ExtensionList m_extensions; std::string m_name; }; } #endif
/* * ===================================================================================== * * Filename: SR_BamMemPool.h * * Description: * * Version: 1.0 * Created: 09/13/2011 04:14:34 PM * Revision: none * Compiler: gcc * * Author: Jiantao Wu (), * Company: * * ===================================================================================== */ #ifndef SR_BAMMEMPOOL_H #define SR_BAMMEMPOOL_H #include "../OutSources/samtools/bam.h" #include "SR_Types.h" typedef struct SR_BamNode SR_BamNode; typedef SR_BamNode* SR_BamListIter; typedef struct SR_BamList SR_BamList; typedef struct SR_BamBuff SR_BamBuff; typedef struct SR_BamMemPool SR_BamMemPool; struct SR_BamNode { bam1_t alignment; SR_BamNode* prev; SR_BamNode* next; const SR_BamBuff* whereFrom; }; struct SR_BamList { unsigned int numNode; SR_BamNode* first; SR_BamNode* last; }; struct SR_BamBuff { unsigned int numUsed; SR_BamBuff* nextBuff; SR_BamNode* pNodeArray; }; struct SR_BamMemPool { unsigned short numBuffs; unsigned int buffCapacity; SR_BamBuff* pFirstBuff; SR_BamList avlNodeList; }; SR_BamNode* SR_BamNodeAlloc(SR_BamMemPool* pMemPool); #define SR_BamNodeFree(pNode, pMemPool) SR_BamListPushHead(&((pMemPool)->avlNodeList), (pNode)) static inline SR_BamListIter SR_BamListGetIter(SR_BamList* pList) { return pList->first; } void SR_BamListPushHead(SR_BamList* pList, SR_BamNode* pNewFirstNode); void SR_BamListPushBack(SR_BamList* pList, SR_BamNode* pNewLastNode); SR_BamNode* SR_BamListPopHead(SR_BamList* pList); void SR_BamListRemove(SR_BamList* pList, SR_BamNode* pNode); void SR_BamListMergeHead(SR_BamList* dstList, SR_BamNode* first, SR_BamNode* last, unsigned int numNode); void SR_BamListReset(SR_BamList* pList, SR_BamMemPool* pMemPool); SR_BamBuff* SR_BamBuffAlloc(unsigned int buffCapacity); void SR_BamBuffFree(SR_BamBuff* pBuff, unsigned int buffCapacity); void SR_BamBuffClear(SR_BamBuff* pBuff, SR_BamMemPool* pMemPool); SR_BamMemPool* SR_BamMemPoolAlloc(unsigned int buffCapacity); void SR_BamMemPoolFree(SR_BamMemPool* pMemPool); #define SR_BamMemPoolGetSize(pMemPool) ((pMemPool)->numBuffs) SR_Status SR_BamMemPoolExpand(SR_BamMemPool* pMemPool); #endif /*SR_BAMMEMPOOL_H*/
/* * Copyright (C) 2016 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include "DisplayListItems.h" #include <wtf/FastMalloc.h> #include <wtf/Noncopyable.h> #include <wtf/text/WTFString.h> namespace WTF { class TextStream; } namespace WebCore { class FloatRect; class GraphicsContext; namespace DisplayList { class Item; enum AsTextFlag { None = 0, IncludesPlatformOperations = 1 << 0, }; typedef unsigned AsTextFlags; class DisplayList { WTF_MAKE_NONCOPYABLE(DisplayList); WTF_MAKE_FAST_ALLOCATED; friend class Recorder; friend class Replayer; public: DisplayList() = default; DisplayList(DisplayList&&) = default; DisplayList& operator=(DisplayList&&) = default; void dump(WTF::TextStream&) const; const Vector<Ref<Item>>& list() const { return m_list; } Item& itemAt(size_t index) { ASSERT(index < m_list.size()); return m_list[index].get(); } void clear(); void removeItemsFromIndex(size_t); size_t itemCount() const { return m_list.size(); } size_t sizeInBytes() const; String asText(AsTextFlags) const; #if !defined(NDEBUG) || !LOG_DISABLED WTF::CString description() const; void dump() const; #endif private: Item& append(Ref<Item>&& item) { m_list.append(WTFMove(item)); return m_list.last().get(); } // Less efficient append, only used for tracking replay. void appendItem(Item& item) { m_list.append(item); } static bool shouldDumpForFlags(AsTextFlags, const Item&); Vector<Ref<Item>>& list() { return m_list; } Vector<Ref<Item>> m_list; }; } // DisplayList WTF::TextStream& operator<<(WTF::TextStream&, const DisplayList::DisplayList&); } // WebCore using WebCore::DisplayList::DisplayList;
// // Copyright (c) 2008-2021 the Urho3D project. // // 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. // /// \file #pragma once #include "../Container/ArrayPtr.h" #include "../Core/Mutex.h" #include "../Container/RefCounted.h" #include "../Core/Thread.h" #include "../IO/Deserializer.h" namespace Urho3D { /// HTTP connection state. enum HttpRequestState { HTTP_INITIALIZING = 0, HTTP_ERROR, HTTP_OPEN, HTTP_CLOSED }; /// An HTTP connection with response data stream. class URHO3D_API HttpRequest : public RefCounted, public Deserializer, public Thread { public: /// Construct with parameters. HttpRequest(const String& url, const String& verb, const Vector<String>& headers, const String& postData); /// Destruct. Release the connection object. ~HttpRequest() override; /// Process the connection in the worker thread until closed. void ThreadFunction() override; /// Read response data from the HTTP connection and return number of bytes actually read. While the connection is open, will block while trying to read the specified size. To avoid blocking, only read up to as many bytes as GetAvailableSize() returns. unsigned Read(void* dest, unsigned size) override; /// Set position from the beginning of the stream. Not supported. unsigned Seek(unsigned position) override; /// Return whether all response data has been read. bool IsEof() const override; /// Return URL used in the request. /// @property{get_url} const String& GetURL() const { return url_; } /// Return verb used in the request. Default GET if empty verb specified on construction. /// @property const String& GetVerb() const { return verb_; } /// Return error. Only non-empty in the error state. /// @property String GetError() const; /// Return connection state. /// @property HttpRequestState GetState() const; /// Return amount of bytes in the read buffer. /// @property unsigned GetAvailableSize() const; /// Return whether connection is in the open state. /// @property bool IsOpen() const { return GetState() == HTTP_OPEN; } private: /// Check for available read data in buffer and whether end has been reached. Must only be called when the mutex is held by the main thread. Pair<unsigned, bool> CheckAvailableSizeAndEof() const; /// URL. String url_; /// Verb. String verb_; /// Error string. Empty if no error. String error_; /// Headers. Vector<String> headers_; /// POST data. String postData_; /// Connection state. HttpRequestState state_; /// Mutex for synchronizing the worker and the main thread. mutable Mutex mutex_; /// Read buffer for the worker thread. SharedArrayPtr<unsigned char> httpReadBuffer_; /// Read buffer for the main thread. SharedArrayPtr<unsigned char> readBuffer_; /// Read buffer read cursor. unsigned readPosition_; /// Read buffer write cursor. unsigned writePosition_; }; }
// // JMUIConversationDatasource.h // JMUIKit // // Created by oshumini on 16/1/5. // Copyright © 2016年 HXHG. All rights reserved. // #import <Foundation/Foundation.h> #import "JMUIChatModel.h" @interface JMUIChattingDatasource : NSObject @property (strong, nonatomic)JMSGConversation *conversation; @property (strong, nonatomic)NSMutableArray *allMessageIdArr; @property (strong, nonatomic)NSMutableDictionary *allMessageDic; @property (nonatomic, readonly)NSInteger messageLimit; //每页刷新获取消息的条数 @property (nonatomic, readonly)NSInteger messagefristPageNumber; //获取消息第一页的消息数量 @property (nonatomic, readonly)NSInteger showTimeInterval; //两条消息相隔多久显示一条时间戳 - (instancetype)initWithConversation:(JMSGConversation*)session showTimeInterval:(NSTimeInterval)timeInterval fristPageMsgNumber:(NSInteger)pageNumber limit:(NSInteger)limit; /** * 清除所有的消息缓存 */ - (void)cleanCache; /** * 把消息拼接到消息列表的最后 */ - (void)appendMessage:(JMUIChatModel *)model; /** * 拼接时间消息到消息列表最后一行 */ - (void)appendTimeData:(NSTimeInterval)timeInterVal; /** * 插入消息到消息列表的指定行 */ - (void)addmessage:(JMUIChatModel *)model toIndex:(NSInteger)index; /** * 分页获取历史消息 */ - (void)getPageMessage; /** * 返回消息数量 */ - (NSInteger)messageCount; /** * 用于标识还有没更多历史消息 */ - (BOOL)noMoreHistoryMessage; /** * 通过index 获取置顶消息model */ - (JMUIChatModel *)getMessageWithIndex:(NSInteger)index; /** * 通过msgId 获取指定消息model */ - (JMUIChatModel *)getMessageWithMsgId:(NSString *)messageId; /** * 返回最后一条消息 */ - (JMUIChatModel *)lastMessage; /** * 返回 指定message 的位置 */ - (NSIndexPath *)tableIndexPathWithMessageId:(NSString *)messageId; @end
/** ****************************************************************************** * @file FMC/FMC_SDRAM/stm32f4xx_it.c * @author MCD Application Team * @version V1.8.0 * @date 04-November-2016 * @brief Main Interrupt Service Routines. * This file provides template for all exceptions handler and * peripherals interrupt service routine. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT 2016 STMicroelectronics</center></h2> * * Licensed under MCD-ST Liberty SW License Agreement V2, (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.st.com/software_license_agreement_liberty_v2 * * 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. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_it.h" /** @addtogroup STM32F4xx_StdPeriph_Examples * @{ */ /** @addtogroup FMC_SDRAM * @{ */ /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /******************************************************************************/ /* Cortex-M4 Processor Exceptions Handlers */ /******************************************************************************/ /** * @brief This function handles NMI exception. * @param None * @retval None */ void NMI_Handler(void) { } /** * @brief This function handles Hard Fault exception. * @param None * @retval None */ void HardFault_Handler(void) { /* Go to infinite loop when Hard Fault exception occurs */ while (1) { } } /** * @brief This function handles Memory Manage exception. * @param None * @retval None */ void MemManage_Handler(void) { /* Go to infinite loop when Memory Manage exception occurs */ while (1) { } } /** * @brief This function handles Bus Fault exception. * @param None * @retval None */ void BusFault_Handler(void) { /* Go to infinite loop when Bus Fault exception occurs */ while (1) { } } /** * @brief This function handles Usage Fault exception. * @param None * @retval None */ void UsageFault_Handler(void) { /* Go to infinite loop when Usage Fault exception occurs */ while (1) { } } /** * @brief This function handles SVCall exception. * @param None * @retval None */ void SVC_Handler(void) { } /** * @brief This function handles Debug Monitor exception. * @param None * @retval None */ void DebugMon_Handler(void) { } /** * @brief This function handles PendSVC exception. * @param None * @retval None */ void PendSV_Handler(void) { } /** * @brief This function handles SysTick Handler. * @param None * @retval None */ void SysTick_Handler(void) { } /******************************************************************************/ /* STM32F4xx Peripherals Interrupt Handlers */ /* Add here the Interrupt Handler for the used peripheral(s) (PPP), for the */ /* available peripheral interrupt handler's name please refer to the startup */ /* file (startup_stm32f40xx.s/startup_stm32f427x.s/startup_stm32f429x.s). */ /******************************************************************************/ /** * @brief This function handles PPP interrupt request. * @param None * @retval None */ /*void PPP_IRQHandler(void) { }*/ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
#pragma once #include <cstddef> #include <string> #include "CommonTypes.h" namespace Common { const u32 MEM1_SIZE = 0x1800000; const u32 MEM1_START = 0x80000000; const u32 MEM1_END = 0x81800000; const u32 MEM2_SIZE = 0x4000000; const u32 MEM2_START = 0x90000000; const u32 MEM2_END = 0x94000000; enum class MemType { type_byte = 0, type_halfword, type_word, type_float, type_double, type_string, type_byteArray, type_num }; enum class MemBase { base_decimal = 0, base_hexadecimal, base_octal, base_binary, base_none // Placeholder when the base doesn't matter (ie. string) }; enum class MemOperationReturnCode { invalidInput, operationFailed, inputTooLong, invalidPointer, OK }; size_t getSizeForType(const MemType type, const size_t length); bool shouldBeBSwappedForType(const MemType type); char* formatStringToMemory(MemOperationReturnCode& returnCode, size_t& actualLength, const std::string inputString, const MemBase base, const MemType type, const size_t length); std::string formatMemoryToString(const char* memory, const MemType type, const size_t length, const MemBase base, const bool isUnsigned, const bool withBSwap = false); }
// // PropertyDemoController.h // LayZhangDemo // // Created by LayZhang on 2017/5/26. // Copyright © 2017年 Zhanglei. All rights reserved. // #import "ZLViewController.h" @interface PropertyDemoController : ZLViewController @end
// Copyright (c) 2009-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_WALLET_CRYPTER_H #define BITCOIN_WALLET_CRYPTER_H #include <keystore.h> #include <serialize.h> #include <support/allocators/secure.h> #include <atomic> const unsigned int WALLET_CRYPTO_KEY_SIZE = 32; const unsigned int WALLET_CRYPTO_SALT_SIZE = 8; const unsigned int WALLET_CRYPTO_IV_SIZE = 16; /** * Private key encryption is done based on a CMasterKey, * which holds a salt and random encryption key. * * CMasterKeys are encrypted using AES-256-CBC using a key * derived using derivation method nDerivationMethod * (0 == EVP_sha512()) and derivation iterations nDeriveIterations. * vchOtherDerivationParameters is provided for alternative algorithms * which may require more parameters (such as scrypt). * * Wallet Private Keys are then encrypted using AES-256-CBC * with the double-sha256 of the public key as the IV, and the * master key's key as the encryption key (see keystore.[ch]). */ /** Master key for wallet encryption */ class CMasterKey { public: std::vector<unsigned char> vchCryptedKey; std::vector<unsigned char> vchSalt; //! 0 = EVP_sha512() //! 1 = scrypt() unsigned int nDerivationMethod; unsigned int nDeriveIterations; //! Use this for more parameters to key derivation, //! such as the various parameters to scrypt std::vector<unsigned char> vchOtherDerivationParameters; ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action) { READWRITE(vchCryptedKey); READWRITE(vchSalt); READWRITE(nDerivationMethod); READWRITE(nDeriveIterations); READWRITE(vchOtherDerivationParameters); } CMasterKey() { // 25000 rounds is just under 0.1 seconds on a 1.86 GHz Pentium M // ie slightly lower than the lowest hardware we need bother supporting nDeriveIterations = 25000; nDerivationMethod = 0; vchOtherDerivationParameters = std::vector<unsigned char>(0); } }; typedef std::vector<unsigned char, secure_allocator<unsigned char> > CKeyingMaterial; namespace wallet_crypto_tests { class TestCrypter; } /** Encryption/decryption context with key information */ class CCrypter { friend class wallet_crypto_tests::TestCrypter; // for test access to chKey/chIV private: std::vector<unsigned char, secure_allocator<unsigned char>> vchKey; std::vector<unsigned char, secure_allocator<unsigned char>> vchIV; bool fKeySet; int BytesToKeySHA512AES(const std::vector<unsigned char>& chSalt, const SecureString& strKeyData, int count, unsigned char *key,unsigned char *iv) const; public: bool SetKeyFromPassphrase(const SecureString &strKeyData, const std::vector<unsigned char>& chSalt, const unsigned int nRounds, const unsigned int nDerivationMethod); bool Encrypt(const CKeyingMaterial& vchPlaintext, std::vector<unsigned char> &vchCiphertext) const; bool Decrypt(const std::vector<unsigned char>& vchCiphertext, CKeyingMaterial& vchPlaintext) const; bool SetKey(const CKeyingMaterial& chNewKey, const std::vector<unsigned char>& chNewIV); void CleanKey() { memory_cleanse(vchKey.data(), vchKey.size()); memory_cleanse(vchIV.data(), vchIV.size()); fKeySet = false; } CCrypter() { fKeySet = false; vchKey.resize(WALLET_CRYPTO_KEY_SIZE); vchIV.resize(WALLET_CRYPTO_IV_SIZE); } ~CCrypter() { CleanKey(); } }; /** Keystore which keeps the private keys encrypted. * It derives from the basic key store, which is used if no encryption is active. */ class CCryptoKeyStore : public CBasicKeyStore { private: CKeyingMaterial vMasterKey GUARDED_BY(cs_KeyStore); //! if fUseCrypto is true, mapKeys must be empty //! if fUseCrypto is false, vMasterKey must be empty std::atomic<bool> fUseCrypto; //! keeps track of whether Unlock has run a thorough check before bool fDecryptionThoroughlyChecked; //! if fOnlyMixingAllowed is true, only mixing should be allowed in unlocked wallet bool fOnlyMixingAllowed; protected: using CryptedKeyMap = std::map<CKeyID, std::pair<CPubKey, std::vector<unsigned char>>>; bool SetCrypted(); //! will encrypt previously unencrypted keys bool EncryptKeys(CKeyingMaterial& vMasterKeyIn); bool Unlock(const CKeyingMaterial& vMasterKeyIn, bool fForMixingOnly = false); CryptedKeyMap mapCryptedKeys GUARDED_BY(cs_KeyStore); public: CCryptoKeyStore() : fUseCrypto(false), fDecryptionThoroughlyChecked(false), fOnlyMixingAllowed(false) { } bool IsCrypted() const { return fUseCrypto; } /** * This function should be used in a different combinations to determine * if CCryptoKeyStore is fully locked so that no operations requiring access * to private keys are possible: * IsLocked(true) * or if CCryptoKeyStore's private keys are available for mixing only: * !IsLocked(true) && IsLocked() * or if they are available for everything: * !IsLocked() */ bool IsLocked(bool fForMixing = false) const; bool Lock(bool fAllowMixing = false); virtual bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret); bool AddKeyPubKey(const CKey& key, const CPubKey &pubkey) override; bool HaveKey(const CKeyID &address) const override; bool GetKey(const CKeyID &address, CKey& keyOut) const override; bool GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const override; std::set<CKeyID> GetKeys() const override; /** * Wallet status (encrypted, locked) changed. * Note: Called without locks held. */ boost::signals2::signal<void (CCryptoKeyStore* wallet)> NotifyStatusChanged; }; #endif // BITCOIN_WALLET_CRYPTER_H
// // NewController.h // BaiSi // // Created by user on 2019/2/18. // Copyright © 2019 Wu. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface NewController : UIViewController @end NS_ASSUME_NONNULL_END
// // ViewController.h // HDAlertViewDemo // // Created by HeDong on 16/9/1. // Copyright © 2016年 hedong. All rights reserved. // #import <UIKit/UIKit.h> @interface ViewController : UIViewController @end
#ifndef INCLUDED_flixel_math_FlxCallbackPoint #define INCLUDED_flixel_math_FlxCallbackPoint #ifndef HXCPP_H #include <hxcpp.h> #endif #ifndef INCLUDED_flixel_math_FlxPoint #include <flixel/math/FlxPoint.h> #endif HX_DECLARE_CLASS2(flixel,math,FlxCallbackPoint) HX_DECLARE_CLASS2(flixel,math,FlxPoint) HX_DECLARE_CLASS2(flixel,util,IFlxDestroyable) HX_DECLARE_CLASS2(flixel,util,IFlxPooled) namespace flixel{ namespace math{ class HXCPP_CLASS_ATTRIBUTES FlxCallbackPoint_obj : public ::flixel::math::FlxPoint_obj{ public: typedef ::flixel::math::FlxPoint_obj super; typedef FlxCallbackPoint_obj OBJ_; FlxCallbackPoint_obj(); Void __construct(Dynamic setXCallback,Dynamic setYCallback,Dynamic setXYCallback); public: inline void *operator new( size_t inSize, bool inContainer=true,const char *inName="flixel.math.FlxCallbackPoint") { return hx::Object::operator new(inSize,inContainer,inName); } static hx::ObjectPtr< FlxCallbackPoint_obj > __new(Dynamic setXCallback,Dynamic setYCallback,Dynamic setXYCallback); static Dynamic __CreateEmpty(); static Dynamic __Create(hx::DynamicArray inArgs); //~FlxCallbackPoint_obj(); HX_DO_RTTI_ALL; Dynamic __Field(const ::String &inString, hx::PropertyAccess inCallProp); Dynamic __SetField(const ::String &inString,const Dynamic &inValue, hx::PropertyAccess inCallProp); static void __register(); void __Mark(HX_MARK_PARAMS); void __Visit(HX_VISIT_PARAMS); ::String __ToString() const { return HX_HCSTRING("FlxCallbackPoint","\x99","\x08","\xfc","\xdd"); } Dynamic _setXCallback; Dynamic &_setXCallback_dyn() { return _setXCallback;} Dynamic _setYCallback; Dynamic &_setYCallback_dyn() { return _setYCallback;} Dynamic _setXYCallback; Dynamic &_setXYCallback_dyn() { return _setXYCallback;} virtual ::flixel::math::FlxPoint set( hx::Null< Float > X,hx::Null< Float > Y); virtual Float set_x( Float Value); virtual Float set_y( Float Value); virtual Void destroy( ); virtual Void put( ); }; } // end namespace flixel } // end namespace math #endif /* INCLUDED_flixel_math_FlxCallbackPoint */
// Copyright 2013 Room77 Inc. All Rights Reserved. // Author: pramodg@room77.com (Pramod Gupta) #ifndef _PUBLIC_UTIL_LOG_CHANNEL_CHANNEL_H_ #define _PUBLIC_UTIL_LOG_CHANNEL_CHANNEL_H_ #include <unordered_map> #include "base/common.h" #include "util/templates/container_util.h" namespace meta { namespace channel { enum { // All the channels between WebBegin and WebEnd are treated as channels where // the complete site can be displayed. kChannelWebBegin = 0, kChannelDesktopBegin = 0, // Web/Desktop channel. By default, all unknown channels are treated as web. kChannelDesktopWeb, kChannelDesktopEnd = 49, // Tablet channels. These will also be considered desktop channels by default. kChannelTabletBegin = 50, kChannelTabletWeb, kChannelTabletAppIOS, kChannelTabletAppAndroid, kChannelTabletAppWindows, kChannelTabletAppOther, kChannelTabletEnd = 99, // Done with all web channels. kChannelWebEnd = 99, // All the channels between MobileBegin and MobileEnd are treated as mobile // channels. kChannelMobileBegin = 100, kChannelMobileWeb, kChannelMobileAppIOS, kChannelMobileAppAndroid, kChannelMobileAppWindows, kChannelMobileAppOther, kChannelMobileEnd = 149, }; typedef unsigned int DeviceChannel; // Returns the CGI parameter used to define channel. inline string ChannelCGIParam() { return "channel"; } // Utility function the get channel (as a string) from the arg_map. inline string GetChannelString(const unordered_map<string, string>& arg_map) { return ::util::tl::FindWithDefault(arg_map, ChannelCGIParam(), "web"); } // Given a string, returns the appropriate channel. On empty string // returns the default channel DeviceChannel GetChannel(const string& str); // Utility function the get channel from the arg_map. inline DeviceChannel GetChannel(const unordered_map<string, string>& arg_map) { return GetChannel(::util::tl::FindWithDefault(arg_map, ChannelCGIParam(), "")); } // @return the default channel. useful for backend methods that need channels inline DeviceChannel DefaultChannel() { return GetChannel(""); } // Returns true if channel is web. These are the channels where our full site // can be displayed by default. inline bool IsWeb(DeviceChannel channel) { return kChannelWebBegin < channel && channel < kChannelWebEnd; } // Returns true for desktop. inline bool IsDesktop(DeviceChannel channel) { return kChannelDesktopBegin < channel && channel < kChannelDesktopEnd; } // Returns true for desktop web. inline bool IsDesktopWeb(DeviceChannel channel) { return channel == kChannelDesktopWeb; } // Returns true for tablet. Can be either web or apps. inline bool IsTablet(DeviceChannel channel) { return kChannelTabletBegin < channel && channel < kChannelTabletEnd; } // Returns true for desktop web. inline bool IsTabletWeb(DeviceChannel channel) { return channel == kChannelTabletWeb; } // Returns true if channel is tablet app. inline bool IsTabletApp(DeviceChannel channel) { return kChannelTabletAppIOS <= channel && channel <= kChannelTabletAppOther; } // Returns true if channel is mobile. inline bool IsMobile(DeviceChannel channel) { return kChannelMobileBegin < channel && channel < kChannelMobileEnd; } // Returns true for mobile web. inline bool IsMobileWeb(DeviceChannel channel) { return channel == kChannelMobileWeb; } // Returns true if channel is Mobile App. inline bool IsMobileApp(DeviceChannel channel) { return kChannelMobileAppIOS <= channel && channel <= kChannelMobileAppOther; } } // namespace channel } // namespace meta #endif // _PUBLIC_UTIL_LOG_CHANNEL_CHANNEL_H_
/*** *eh.h - User include file for exception handling. * * Copyright (c) 1993-2001, Microsoft Corporation. All rights reserved. * *Purpose: * User include file for exception handling. * * [Public] * ****/ #if _MSC_VER > 1000 #pragma once #endif #ifndef _INC_EH #define _INC_EH #if !defined(_WIN32) #error ERROR: Only Win32 target supported! #endif #ifdef _MSC_VER // Currently, all MS C compilers for Win32 platforms default to 8 byte // alignment. #pragma pack(push,8) #endif // _MSC_VER #ifndef __cplusplus #error "eh.h is only for C++!" #endif /* Define _CRTIMP */ #ifndef _CRTIMP #ifdef _DLL #define _CRTIMP __declspec(dllimport) #else /* ndef _DLL */ #define _CRTIMP #endif /* _DLL */ #endif /* _CRTIMP */ typedef void (__cdecl *terminate_function)(); typedef void (__cdecl *unexpected_function)(); typedef void (__cdecl *terminate_handler)(); typedef void (__cdecl *unexpected_handler)(); struct _EXCEPTION_POINTERS; typedef void (__cdecl *_se_translator_function)(unsigned int, struct _EXCEPTION_POINTERS*); #if _MSC_VER >= 1200 _CRTIMP __declspec(noreturn) void __cdecl terminate(void); _CRTIMP __declspec(noreturn) void __cdecl unexpected(void); #else _CRTIMP void __cdecl terminate(void); _CRTIMP void __cdecl unexpected(void); #endif _CRTIMP terminate_function __cdecl set_terminate(terminate_function); _CRTIMP unexpected_function __cdecl set_unexpected(unexpected_function); _CRTIMP _se_translator_function __cdecl _set_se_translator(_se_translator_function); _CRTIMP bool __uncaught_exception(); #ifdef _MSC_VER #pragma pack(pop) #endif // _MSC_VER #endif // _INC_EH
// // AppDelegate.h // FEAudioDisplayView // // Created by YamatoKira on 16/1/30. // Copyright © 2016年 feeling. All rights reserved. // #import <UIKit/UIKit.h> @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
#include "tokenizer.h" #include <stdlib.h> #include <string.h> #include <stdio.h> #include <ctype.h> #define MAX_IN_STR_LEN 128 #define STARTING_BUFFER_SIZE 256 #define BUFFER_INC_RATIO 2 static char *dynamic_cat(char s[], size_t *size, char in[]); static int is_numeric(char s[]); static int read_alpha(char *s[], char *rezult[], size_t *rezult_size, char delim[]); static int read_punct(char *s[], char *rezult[], size_t *rezult_size, char delim[]); static int read_numeric(char *s[], char *rezult[], size_t *rezult_size, char delim[]); static char *dynamic_cat(char *s, size_t *size, char *in) { while (&s[*size - 1] - strchr(s, '\0') < strlen(in)) { char *tmp = (char *)realloc(s, *size *= BUFFER_INC_RATIO); if (!tmp) return NULL; else s = tmp; } strcat(s, in); return s; } static int read_alpha(char *s[], char *rezult[], size_t *rezult_size, char delim[]) { int num_read; char tmp[MAX_IN_STR_LEN]; sscanf(*s, "%[a-zA-Z] %n", tmp, &num_read); *s += num_read; char *test; if (!(test = dynamic_cat(*rezult, rezult_size, tmp))) return -1; else *rezult = test; if (!(test = dynamic_cat(*rezult, rezult_size, delim))) return -1; else *rezult = test; return 0; } static int read_punct(char *s[], char *rezult[], size_t *rezult_size, char delim[]) { char tmp[2]; sscanf(*s, "%1s", tmp); ++*s; char *test; if (!(test = dynamic_cat(*rezult, rezult_size, tmp))) return -1; else *rezult = test; if (!(test = dynamic_cat(*rezult, rezult_size, delim))) return -1; else *rezult = test; return 0; } static int read_numeric(char *s[], char *rezult[], size_t *rezult_size, char delim[]) { int read_dot = 0; int num_read; char tmp[MAX_IN_STR_LEN * 2]; if (**s == '-' && *(*s + 1) == '.') { read_dot = 1; tmp[0] = '-'; tmp[1] = '.'; *s += 2; sscanf(*s, "%[0-9] %n", &tmp[2], &num_read); } else if (**s == '-') { tmp[0] = '-'; ++*s; sscanf(*s, "%[0-9] %n", &tmp[1], &num_read); } else if (**s == '.') { read_dot = 1; tmp[0] = '.'; ++*s; sscanf(*s, "%[0-9] %n", &tmp[1], &num_read); } else { sscanf(*s, "%[0-9] %n", tmp, &num_read); } *s += num_read; if (!read_dot && **s == '.' && isdigit(*(*s + 1))) { *s += 1; char postdot[MAX_IN_STR_LEN]; sscanf(*s, "%[0-9] %n", postdot, &num_read); *s += num_read; strcat(tmp, "."); strcat(tmp, postdot); } char *test; if (!(test = dynamic_cat(*rezult, rezult_size, tmp))) return -1; else *rezult = test; if (!(test = dynamic_cat(*rezult, rezult_size, delim))) return -1; else *rezult = test; return 0; } char *tokenize(char s[], char delim[]) { size_t rezult_size = STARTING_BUFFER_SIZE; char *rezult = (char *)malloc(sizeof(rezult) * rezult_size); rezult[0] = '\0'; int err = 0; while (*s != '\0') { if (isalpha(*s)) err = read_alpha(&s, &rezult, &rezult_size, delim); else if (is_numeric(s)) err = read_numeric(&s, &rezult, &rezult_size, delim); else if (ispunct(*s)) err = read_punct(&s, &rezult, &rezult_size, delim); else ++s; if (err) { free(rezult); return NULL; } } return rezult; } static int is_numeric(char s[]) { if (isdigit(s[0])) return 1; if (s[0] == '-' && isdigit(s[1])) return 1; if (s[0] == '.' && isdigit(s[1])) return 1; if (strlen(s) > 1 && s[0] == '-' && s[1] == '.' && isdigit(s[2])) return 1; return 0; }
/** * Appcelerator Titanium Mobile * Copyright (c) 2009-2011 by showroomApp, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. * * WARNING: This is generated code. Modify at your own risk and without support. */ #ifdef USE_TI_NETWORKSOCKET #import <Foundation/Foundation.h> #import "TiStreamProxy.h" #import "AsyncSocket.h" #import "TiNetworkSocketProxy.h" // Used to determine the type of processing typedef enum { TO_BUFFER = 1, TO_STREAM, TO_CALLBACK, } ReadDestination; @interface TiNetworkSocketTCPProxy : TiStreamProxy<AsyncSocketDelegate, TiStreamInternal> { AsyncSocket* socket; SocketState internalState; NSCondition* listening; NSThread* socketThread; // We have to have an explicit "host" property because of some 'fun' undocumented KVO // behavior - it turns out that KVO 'getters' also look for '-(type)_key' signature // selectors. TiProxy has a '_host' function. NSString* host; // We offer synchronous I/O. The underlying socket implementation is asynchronous. // So we need to ensure our own synchronicity by signaling a condition when operations // complete. NSCondition* ioCondition; NSUInteger readDataLength; NSError* socketError; // In order to put the accepted socket on the right run loop, and make sure it's constructed // properly, we need THESE as well... NSMutableDictionary* acceptArgs; NSRunLoop* acceptRunLoop; BOOL accepting; // And, last but not least, in order to make sure that socket run loops are configured AND ACTIVE before performing any work on them, // we need to be able to signal that they're NSCondition* readyCondition; BOOL socketReady; // Information used to hash callbacks and asynch ops to tags. int asynchTagCount; NSMutableDictionary* operationInfo; KrollCallback* connected; KrollCallback* accepted; KrollCallback* closed; KrollCallback* error; } // Properties: // -- Stored on TiProxy dynprops -- // int port // ---- @property (nonatomic, readwrite, retain) NSString* host; @property (nonatomic, readonly) NSNumber* state; // Req's local processing @property (nonatomic, readwrite, retain) KrollCallback* connected; @property (nonatomic, readwrite, retain) KrollCallback* accepted; @property (nonatomic, readwrite, retain) KrollCallback* closed; @property (nonatomic, readwrite, retain) KrollCallback* error; // Public API -(void)connect:(id)_void; -(void)listen:(id)arg; // arg[0]: int maxAcceptQueueSize : queue size -(void)accept:(id)arg; // arg[0]: Object params : callbacks for created socket -(void)close:(id)_void; @end #endif
// // JTabBarButton.h // JKitDemo // // Created by Zebra on 16/6/7. // Copyright © 2016年 陈杰. All rights reserved. // #import <UIKit/UIKit.h> @interface JTabBarButton : UIButton @end
/*Copyright (C) 2013 Mamadou Diop * Copyright (C) 2013 Doubango Telecom <http://www.doubango.org> * * This file is part of Open Source Doubango Framework. * * DOUBANGO 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 of the License, or * (at your option) any later version. * * DOUBANGO 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 DOUBANGO. */ /**@file tdav_producer_wasapi.h * @brief Microsoft Windows Audio Session API (WASAPI) producer. * */ #ifndef TINYDAV_PRODUCER_WASAPI_H #define TINYDAV_PRODUCER_WASAPI_H #include "tinydav_config.h" #if HAVE_WASAPI #include "tinydav/audio/tdav_producer_audio.h" TDAV_BEGIN_DECLS TINYDAV_GEXTERN const struct tmedia_producer_plugin_def_s *tdav_producer_wasapi_plugin_def_t; TDAV_END_DECLS #endif /* HAVE_WASAPI */ #endif /* TINYDAV_PRODUCER_WASAPI_H */
#include <linux/err.h> #include <plat/mcspi.h> #include <asm/uaccess.h> #include <linux/interrupt.h> #include <linux/input.h> #include <linux/spi/spi.h> #include "dac7612.h" #include <linux/module.h> #define MODULE_DEBUG 0 static struct spi_device *dac7612_spi_device = NULL; int dac7612_spi_read_reg8(u8 addr, u8* value) { struct spi_transfer t[2]; struct spi_message m; u8 cmd; u8 data = 0; /* Check for valid spi device */ if(!dac7612_spi_device) return -ENODEV; /* Create Cmd byte: * * | 0|RD| 8| ADDR | * 7 6 5 4 3 2 1 0 */ cmd = (1<<6) | (0<<5) | (addr & 0x1f); /* Init Message */ memset(t, 0, sizeof(t)); spi_message_init(&m); m.spi = dac7612_spi_device; /* Configure tx/rx buffers */ t[0].tx_buf = &cmd; t[0].rx_buf = NULL; t[0].len = 1; spi_message_add_tail(&t[0], &m); t[1].tx_buf = NULL; t[1].rx_buf = &data; t[1].len = 1; spi_message_add_tail(&t[1], &m); /* Transmit SPI Data (blocking) */ spi_sync(m.spi, &m); if(MODULE_DEBUG) printk(KERN_DEBUG "dac7612: Read Reg8 Addr 0x%02x Data: 0x%02x\n", cmd, data); *value = data; return 0; } int dac7612_spi_read_reg16(u8 addr, u16* value) { struct spi_transfer t[2]; struct spi_message m; u8 cmd; u16 data = 0; /* Check for valid spi device */ if(!dac7612_spi_device) return -ENODEV; /* Create Cmd byte: * * | 0|RD|16| ADDR | * 7 6 5 4 3 2 1 0 */ cmd = (1<<6) | (1<<5) | (addr & 0x1f); /* Init Message */ memset(t, 0, sizeof(t)); spi_message_init(&m); m.spi = dac7612_spi_device; /* Configure tx/rx buffers */ t[0].tx_buf = &cmd; t[0].rx_buf = NULL; t[0].len = 1; if(MODULE_DEBUG) printk("requesting data from addr 0x%x\n", cmd); spi_message_add_tail(&t[0], &m); t[1].tx_buf = NULL; t[1].rx_buf = &data; t[1].len = 2; spi_message_add_tail(&t[1], &m); /* Transmit SPI Data (blocking) */ spi_sync(m.spi, &m); if(MODULE_DEBUG) printk(KERN_DEBUG "dac7612: Read Reg16 Addr 0x%02x Data: 0x%04x\n", cmd, data); *value = data; return 0; } int dac7612_spi_write_reg8(u8 addr, u8 data) { struct spi_transfer t[2]; struct spi_message m; u8 cmd; /* Check for valid spi device */ if(!dac7612_spi_device) return -ENODEV; /* Create Cmd byte: * * | 0|WR| 8| ADDR | * 7 6 5 4 3 2 1 0 */ cmd = (0<<6) | (0<<5) | (addr & 0x1f); /* Init Message */ memset(&t, 0, sizeof(t)); spi_message_init(&m); m.spi = dac7612_spi_device; if(MODULE_DEBUG) printk(KERN_DEBUG "dac7612: Write Reg8 Addr 0x%x Data 0x%02x\n", addr, data); /* Configure tx/rx buffers */ t[0].tx_buf = &cmd; t[0].rx_buf = NULL; t[0].len = 1; spi_message_add_tail(&t[0], &m); t[1].tx_buf = &data; t[1].rx_buf = NULL; t[1].len = 1; spi_message_add_tail(&t[1], &m); /* Transmit SPI Data (blocking) */ spi_sync(m.spi, &m); return 0; } /* * dac7612 Probe * Used by the SPI Master to probe the device * When the SPI device is registered. */ static int __devinit dac7612_spi_probe(struct spi_device *spi) { int err; u8 value; spi->bits_per_word = 14; spi_setup(spi); /* In this case we assume just one device */ dac7612_spi_device = spi; err = dac7612_spi_read_reg8(DAC7612_ID, &value); printk(KERN_DEBUG "Probing dac7612, dac7612 Revision %i\n", value); return err; } static int __devexit dac7612_remove(struct spi_device *spi) { printk (KERN_ALERT "dac7612 SPI driver has been removed while in use\n"); dac7612_spi_device = 0; return 0; } static struct spi_driver dac7612_spi_driver = { .driver = { .name = "dac7612", .bus = &spi_bus_type, .owner = THIS_MODULE, }, .probe = dac7612_spi_probe, .remove = __devexit_p(dac7612_remove), }; /* * Init / Exit routines called from * character driver. Init registers the spi driver * and the spi host probes the device upon this. * Exit unregisters the driver and the spi host * calls _remove upon this */ int dac7612_spi_init(void) { int err; err = spi_register_driver(&dac7612_spi_driver); if(err<0) printk (KERN_ALERT "Error %d registering the dac7612 SPI driver\n", err); /* * Probe should have been called if a device is available * setting the current spi device * if not return -ENODEV */ if (dac7612_spi_device == NULL) { spi_unregister_driver(&dac7612_spi_driver); err = -ENODEV; } return err; } int dac7612_spi_exit(void) { /* * Un-register spi driver and device * Spi host calls _remove upon this */ spi_unregister_driver(&dac7612_spi_driver); return 0; }
/* This file is based on code taken from http://en.wikibooks.org/w/index.php?title=Algorithm_Implementation/Miscellaneous/Base64&oldid=2735872 on 7th January 2015. The page includes the follow text: """ This code is also public domain. This solution has been optimized using pointer math and a look-up table. This algorithm handles multiple encoding formats: with and without line breaks, with and without whitespace, and with and without padding characters. """ */ #ifndef BCJSONReader_WikiBookBase64Decode_h #define BCJSONReader_WikiBookBase64Decode_h #import <Foundation/Foundation.h> static inline NSData *BCJDataFromBase64String(NSString *base64String) { int (^base64decode)(const char *in, size_t inLen, unsigned char *out, size_t *outLen) = ^int(const char *in, size_t inLen, unsigned char *out, size_t *outLen) { static const char WHITESPACE = 64; static const char PADDING = 65; static const char INVALID = 66; static const unsigned char d[] = { 66,66,66,66,66,66,66,66,66,64,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66, 66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,62,66,66,66,63,52,53, 54,55,56,57,58,59,60,61,66,66,66,65,66,66,66, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,66,66,66,66,66,66,26,27,28, 29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,66,66, 66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66, 66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66, 66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66, 66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66, 66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66,66, 66,66,66,66,66,66 }; const char *end = in + inLen; size_t buf = 1; size_t len = 0; while (in < end) { unsigned char c = d[*in++]; switch (c) { case WHITESPACE: continue; /* skip whitespace */ case INVALID: return 1; /* invalid input, return error */ case PADDING: /* pad character, end of data */ in = end; continue; default: buf = buf << 6 | c; /* If the buffer is full, split it into bytes */ if (buf & 0x1000000) { if ((len += 3) > *outLen) return 1; /* buffer overflow */ *out++ = buf >> 16; *out++ = buf >> 8; *out++ = buf; buf = 1; } } } if (buf & 0x40000) { if ((len += 2) > *outLen) return 1; /* buffer overflow */ *out++ = buf >> 10; *out++ = buf >> 2; } else if (buf & 0x1000) { if (++len > *outLen) return 1; /* buffer overflow */ *out++ = buf >> 4; } *outLen = len; /* modify to reflect the actual output size */ return 0; }; if (base64String == nil) return nil; const char *input = base64String.UTF8String; const size_t inLength = [base64String lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; unsigned char *dataBuf = malloc(inLength * sizeof(unsigned char)); //Theoretically we could figure out the exact output size and thus make a smaller malloc, but lots of effort for little gain. size_t outLength; int result = base64decode(input, inLength, dataBuf, &outLength); BOOL didSucceed = result == 0; if (!didSucceed) { free(dataBuf); return nil; } return [[NSData alloc] initWithBytesNoCopy:dataBuf length:outLength freeWhenDone:YES]; } #endif
/* * ofxBulletBox.h * ofxBullet_v3 * * Created by Nick Hardeman on 5/23/11. * Copyright 2011 Arnold Worldwide. All rights reserved. * */ #pragma once #include "ofxBulletBaseShape.h" #include "ofVbo.h" class ofxBulletBox : public ofxBulletBaseShape { public: ofxBulletBox(); ~ofxBulletBox(); void init( float a_sizeX, float a_sizeY, float a_sizeZ ); void init( btBoxShape* a_colShape ); void create( btDiscreteDynamicsWorld* a_world, ofVec3f a_loc=ofVec3f(0,0,0), float a_mass=1.f, float a_sizeX=5.f, float a_sizeY=5.f, float a_sizeZ=5.f ); void create( btDiscreteDynamicsWorld* a_world, ofVec3f a_loc, ofQuaternion a_rot, float a_mass=1.f, float a_sizeX=5.f, float a_sizeY=5.f, float a_sizeZ=5.f ); void create( btDiscreteDynamicsWorld* a_world, btTransform a_bt_tr, float a_mass=1.f, float a_sizeX=5.f, float a_sizeY=5.f, float a_sizeZ=5.f ); void draw(); void drawBox(float sizeX, float sizeY, float sizeZ); // GETTERS // ofVec3f getSize() const; bool isInside(const ofVec3f& a_pt, float tolerance=0.1f); protected: private: };
// The MIT License (MIT) // Copyright (c) 2013 lailongwei<lailongwei@126.com> // // 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. #ifdef __LLBC_CORE_ALGO_RING_BUFFER_H__ __LLBC_NS_BEGIN template <typename ElemType> LLBC_FORCE_INLINE LLBC_RingBuffer<ElemType>::LLBC_RingBuffer(size_t cap) : _elems(LLBC_Malloc(ElemType, sizeof(ElemType) * cap)) , _capacity(cap) , _front(0) , _tail(0) , _full(false) { } template <typename ElemType> LLBC_FORCE_INLINE LLBC_RingBuffer<ElemType>::~LLBC_RingBuffer() { while (!IsEmpty()) { _elems[_front].~ElemType(); if (UNLIKELY(++_front == _capacity)) _front = 0; if (UNLIKELY(_full)) _full = false; } LLBC_Free(_elems); } template <typename ElemType> LLBC_FORCE_INLINE void LLBC_RingBuffer<ElemType>::Push(const ElemType &elem) { if (UNLIKELY(_full)) ReCapacity(_capacity << 1); new (&_elems[_tail]) ElemType(elem); if (UNLIKELY(++_tail == _capacity)) _tail = 0; _full = (_tail == _front); } template <typename ElemType> LLBC_FORCE_INLINE ElemType LLBC_RingBuffer<ElemType>::Pop() { #if LLBC_DEBUG ASSERT(!IsEmpty() && "Try pop a empty LLBC_RingBuffer!"); #endif // TODO: Use cxx11 rvalue ref construct. ElemType elem = _elems[_front]; _elems[_front].~ElemType(); if (UNLIKELY(++_front == _capacity)) _front = 0; if (UNLIKELY(_full)) _full = false; return elem; } template <typename ElemType> LLBC_FORCE_INLINE ElemType &LLBC_RingBuffer<ElemType>::Front() { return _elems[_front]; } template <typename ElemType> LLBC_FORCE_INLINE const ElemType &LLBC_RingBuffer<ElemType>::Front() const { return _elems[_front]; } template <typename ElemType> LLBC_FORCE_INLINE ElemType &LLBC_RingBuffer<ElemType>::Tail() { return _elems[_tail]; } template <typename ElemType> LLBC_FORCE_INLINE const ElemType &LLBC_RingBuffer<ElemType>::Tail() const { return _elems[_tail]; } template <typename ElemType> LLBC_FORCE_INLINE size_t LLBC_RingBuffer<ElemType>::GetSize() const { if (_tail > _front) return _tail - _front; else if (_tail == _front) return _full ? _capacity : 0; else return _capacity - _front + _tail; } template <typename ElemType> LLBC_FORCE_INLINE size_t LLBC_RingBuffer<ElemType>::GetCapacity() const { return _capacity; } template <typename ElemType> LLBC_FORCE_INLINE void LLBC_RingBuffer<ElemType>::ReCapacity(size_t newCap) { if (UNLIKELY(newCap <= _capacity)) return; size_t tail = 0; ElemType *newElems = LLBC_Malloc(ElemType, sizeof(ElemType) * newCap); while (!IsEmpty()) new (&newElems[tail++]) ElemType(Pop()); LLBC_Free(_elems); _elems = newElems; _front = 0; _tail = tail; _capacity = newCap; } template <typename ElemType> LLBC_FORCE_INLINE bool LLBC_RingBuffer<ElemType>::IsFull() const { return _full; } template <typename ElemType> LLBC_FORCE_INLINE bool LLBC_RingBuffer<ElemType>::IsEmpty() const { return !_full && _tail == _front; } template <typename ElemType> LLBC_FORCE_INLINE void LLBC_RingBuffer<ElemType>::Clear() { if (_front < _tail) { for (; _front != _tail; ++_front) _elems[_front].~ElemType(); } else { if (IsEmpty()) return; for (; _front != _capacity; ++_front) _elems[_front].~ElemType(); _front = 0; for (; _front != _tail; ++_front) _elems[_front].~ElemType(); _full = false; } } __LLBC_NS_END #endif // __LLBC_CORE_ALGO_RING_BUFFER_H__
/* * The MIT License (MIT) * * Copyright (c) 2015 vmolsa <ville.molsa@gmail.com> (http://github.com/vmolsa) * * 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. * */ #ifndef WEBRTC_GETSOURCES_H #define WEBRTC_GETSOURCES_H #include <nan.h> #include "Observers.h" #include "MediaConstraints.h" namespace WebRTC { class GetSources { public: static void Init(v8::Handle<v8::Object> exports); static rtc::scoped_refptr<webrtc::AudioTrackInterface> GetAudioSource(const rtc::scoped_refptr<MediaConstraints> &constraints); static rtc::scoped_refptr<webrtc::AudioTrackInterface> GetAudioSource(const std::string id, const rtc::scoped_refptr<MediaConstraints> &constraints); static rtc::scoped_refptr<webrtc::VideoTrackInterface> GetVideoSource(const rtc::scoped_refptr<MediaConstraints> &constraints); static rtc::scoped_refptr<webrtc::VideoTrackInterface> GetVideoSource(const std::string id, const rtc::scoped_refptr<MediaConstraints> &constraints); static v8::Local<v8::Value> GetDevices(); private: static NAN_METHOD(GetDevices); }; }; #endif
// // HFFormImageBrowserVC.h // HFFormTest // // Created by lifenglei on 17/4/6. // Copyright © 2017年 lifenglei. All rights reserved. // #import <UIKit/UIKit.h> @class HFFormImageBrowserVC; @interface HFFormImageBrowserModel : NSObject @property (nonatomic, copy) NSString *imageURL; @property (nonatomic, strong) UIImage *image; @end @protocol HFFormImageBrowserDelegate <NSObject> - (NSInteger)numberOfImagesAtImageBrowser:(HFFormImageBrowserVC *)imageBrowser; - (__kindof HFFormImageBrowserModel *)imageBrowser:(HFFormImageBrowserVC *)imageBrowser itemAtIndex:(NSUInteger)index; @optional - (void)imageBrowser:(HFFormImageBrowserVC *)imageBrowser didRemoveImageAt:(NSInteger)index; @end @interface HFFormImageBrowserVC : UIViewController @property (nonatomic, weak) id<HFFormImageBrowserDelegate>delegate; @property (nonatomic, assign) NSInteger selectedIndex; @end
#ifndef ADMIN_H #define ADMIN_H #include <Windows.h> #endif int adminPage(HWND hWnd);
#ifndef MESH_H #define MESH_H #include <gl\glew.h> #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> #include <vector> #include <math.h> class Mesh { public: std::vector<GLfloat> vertex; //Todo: Need to get Triangle Data std::vector<GLubyte> indices; Mesh(); ~Mesh(); private: }; Mesh GenerateTetrahedron(float size); Mesh GenerateOctahedron(float size); Mesh GenerateHexahedron(float size); Mesh GenerateIcosahedron(float size); #endif
#ifndef OPENTISSUE_UTILITY_GLUT_GLUT_EVENT_HANDLERS_H #define OPENTISSUE_UTILITY_GLUT_GLUT_EVENT_HANDLERS_H // // OpenTissue Template Library // - A generic toolbox for physics-based modeling and simulation. // Copyright (C) 2008 Department of Computer Science, University of Copenhagen. // // OTTL is licensed under zlib: http://opensource.org/licenses/zlib-license.php // #include <OpenTissue/configuration.h> #include <OpenTissue/utility/gl/gl.h> #include <OpenTissue/utility/glut/glut_application.h> namespace OpenTissue { namespace glut { instance_pointer application; void set_application_instance( OpenTissue::glut::instance_pointer const & ptr) { application = ptr; } void mouse( int Button, int State, int cur_x, int cur_y ) { int MODIFIERS = glutGetModifiers(); bool shift = ( MODIFIERS & GLUT_ACTIVE_SHIFT ) == GLUT_ACTIVE_SHIFT; bool alt = ( MODIFIERS & GLUT_ACTIVE_ALT ) == GLUT_ACTIVE_ALT; bool ctrl = ( MODIFIERS & GLUT_ACTIVE_CTRL ) == GLUT_ACTIVE_CTRL; bool left = (Button == GLUT_LEFT_BUTTON); bool middle = (Button == GLUT_MIDDLE_BUTTON); bool right = (Button == GLUT_RIGHT_BUTTON); bool down = (State == GLUT_DOWN); if(down) application->mouse_down(cur_x,cur_y,shift,ctrl,alt,left,middle,right); else application->mouse_up(cur_x,cur_y,shift,ctrl,alt,left,middle,right); glutPostRedisplay(); } void motion( int cur_x, int cur_y ) { application->mouse_move(cur_x,cur_y); glutPostRedisplay(); } void reshape( int cur_width, int cur_height ) { application->width() = cur_width; application->height() = cur_height; glViewport( 0, 0, application->width(), application->height() ); application->setup_model_view_projection(); application->setup_lights(); glutPostRedisplay(); } void idle() { application->run(); glutPostRedisplay(); } void key( unsigned char k, int /*x*/, int /*y*/ ) { switch (k) { case 27: case 'q': application->shutdown(); #if defined(WIN32) Sleep(2*1000); #else sleep (2); #endif exit(k); break; case ' ': application->idle() = !application->idle(); if(application->idle()) glutIdleFunc( &idle ); else glutIdleFunc(0); //break; // [micky] No, (some) applications actually want to be notified about this one!!! default: application->action(k); break; }; glutPostRedisplay(); } void specialkey(int k, int /*x*/, int /*y*/) { switch (k){ case -1 : break; default: application->special_action(k); break; }; glutPostRedisplay(); return; } void display() { application->display(); } void menu( int entry ) { key( entry, 0, 0 ); } } // namespace glut } // namespace OpenTissue // OPENTISSUE_UTILITY_GLUT_GLUT_EVENT_HANDLERS_H #endif
// // Vector.h // CObjects // // Created by averello on 4/3/13. // Copyright (c) 2013 George Boumis. All rights reserved. // #ifndef CObjects_Vector_h #define CObjects_Vector_h CO_DECLARE_CLASS(Vector) UInteger getVectorCapacity(const void *const self); UInteger getVectorCapacityIncrement(const void *const self); void setVectorCapacityIncrement(void *const self, UInteger capacityIncrement); bool setVectorSize(void *const self, UInteger size); #endif
// Copyright (c) 2013 AndroidToken Developers #ifndef PBKDF2_H #define PBKDF2_H #include <openssl/sha.h> #include <stdint.h> typedef struct HMAC_SHA256Context { SHA256_CTX ictx; SHA256_CTX octx; } HMAC_SHA256_CTX; void HMAC_SHA256_Init(HMAC_SHA256_CTX * ctx, const void * _K, size_t Klen); void HMAC_SHA256_Update(HMAC_SHA256_CTX * ctx, const void *in, size_t len); void HMAC_SHA256_Final(unsigned char digest[32], HMAC_SHA256_CTX * ctx); void PBKDF2_SHA256(const uint8_t * passwd, size_t passwdlen, const uint8_t * salt, size_t saltlen, uint64_t c, uint8_t * buf, size_t dkLen); #endif // PBKDF2_H
/* * ===================================================================================== * * Filename: <FILENAME> * * Description: I dedicate all this code,all my work,to my wife. * * Version: 1.0 * Created: <DATE> * Revision: none * Compiler: gcc * * Author: Anemone (An), x565178035@126.com * Company: None * * ===================================================================================== */ #include <errno.h> #include <math.h> #include <stdlib.h> #include <string.h> #include <stdio.h> int main() { <CURSOR> return 0; }
// // Copyright 2020 Staysail Systems, Inc. <info@staysail.tech> // // This software is supplied under the terms of the MIT License, a // copy of which should be located in the distribution where this // file was obtained (LICENSE.txt). A copy of the license may also be // found online at https://opensource.org/licenses/MIT. // #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <nng/nng.h> #include <nng/supplemental/tls/tls.h> #include <testutil.h> #include <acutest.h> void test_tls_config_version(void) { nng_tls_config *cfg; TEST_NNG_PASS(nng_tls_config_alloc(&cfg, NNG_TLS_MODE_SERVER)); // Verify that min ver < max ver TEST_NNG_FAIL(nng_tls_config_version(cfg, NNG_TLS_1_3, NNG_TLS_1_0), NNG_ENOTSUP); // Verify that we cannot configure SSL 3.0 or older. TEST_NNG_FAIL( nng_tls_config_version(cfg, NNG_TLS_1_0 - 1, NNG_TLS_1_0), NNG_ENOTSUP); // Verify that we cannot configure TLS > 1.3. TEST_NNG_FAIL( nng_tls_config_version(cfg, NNG_TLS_1_0, NNG_TLS_1_3 + 1), NNG_ENOTSUP); // Verify that we *can* configure some various ranges. TEST_NNG_PASS(nng_tls_config_version(cfg, NNG_TLS_1_0, NNG_TLS_1_0)); TEST_NNG_PASS(nng_tls_config_version(cfg, NNG_TLS_1_0, NNG_TLS_1_1)); TEST_NNG_PASS(nng_tls_config_version(cfg, NNG_TLS_1_0, NNG_TLS_1_2)); TEST_NNG_PASS(nng_tls_config_version(cfg, NNG_TLS_1_0, NNG_TLS_1_3)); TEST_NNG_PASS(nng_tls_config_version(cfg, NNG_TLS_1_1, NNG_TLS_1_1)); TEST_NNG_PASS(nng_tls_config_version(cfg, NNG_TLS_1_1, NNG_TLS_1_2)); TEST_NNG_PASS(nng_tls_config_version(cfg, NNG_TLS_1_1, NNG_TLS_1_3)); TEST_NNG_PASS(nng_tls_config_version(cfg, NNG_TLS_1_2, NNG_TLS_1_2)); TEST_NNG_PASS(nng_tls_config_version(cfg, NNG_TLS_1_2, NNG_TLS_1_3)); nng_tls_config_free(cfg); } void test_tls_conn_refused(void) { nng_stream_dialer *dialer; nng_aio * aio; TEST_NNG_PASS(nng_aio_alloc(&aio, NULL, NULL)); nng_aio_set_timeout(aio, 5000); // 5 sec // port 8 is generally not used for anything. TEST_NNG_PASS( nng_stream_dialer_alloc(&dialer, "tls+tcp://127.0.0.1:8")); nng_stream_dialer_dial(dialer, aio); nng_aio_wait(aio); TEST_NNG_FAIL(nng_aio_result(aio), NNG_ECONNREFUSED); nng_aio_free(aio); nng_stream_dialer_free(dialer); } void test_tls_large_message(void) { nng_stream_listener *l; nng_stream_dialer * d; nng_aio * aio1, *aio2; nng_stream * s1; nng_stream * s2; nng_tls_config * c1; nng_tls_config * c2; char addr[32]; uint8_t * buf1; uint8_t * buf2; size_t size = 450001; void * t1; void * t2; // allocate messages TEST_CHECK((buf1 = nng_alloc(size)) != NULL); TEST_CHECK((buf2 = nng_alloc(size)) != NULL); for (size_t i = 0; i < size; i++) { buf1[i] = rand() & 0xff; } TEST_NNG_PASS(nng_aio_alloc(&aio1, NULL, NULL)); TEST_NNG_PASS(nng_aio_alloc(&aio2, NULL, NULL)); nng_aio_set_timeout(aio1, 5000); nng_aio_set_timeout(aio2, 5000); testutil_scratch_addr("tls+tcp", sizeof(addr), addr); TEST_NNG_PASS(nng_stream_dialer_alloc(&d, addr)); TEST_NNG_PASS(nng_stream_listener_alloc(&l, addr)); // set up TLS parameters TEST_NNG_PASS(nng_tls_config_alloc(&c1, NNG_TLS_MODE_SERVER)); TEST_NNG_PASS(nng_tls_config_own_cert( c1, testutil_server_crt, testutil_server_key, NULL)); TEST_NNG_PASS(nng_tls_config_alloc(&c2, NNG_TLS_MODE_CLIENT)); TEST_NNG_PASS(nng_tls_config_ca_chain(c2, testutil_server_crt, NULL)); TEST_NNG_PASS(nng_tls_config_server_name(c2, "localhost")); TEST_NNG_PASS(nng_stream_listener_set_ptr(l, NNG_OPT_TLS_CONFIG, c1)); TEST_NNG_PASS(nng_stream_dialer_set_ptr(d, NNG_OPT_TLS_CONFIG, c2)); TEST_NNG_PASS(nng_stream_listener_listen(l)); nng_stream_listener_accept(l, aio1); nng_stream_dialer_dial(d, aio2); nng_aio_wait(aio1); nng_aio_wait(aio2); TEST_NNG_PASS(nng_aio_result(aio1)); TEST_NNG_PASS(nng_aio_result(aio2)); TEST_CHECK((s1 = nng_aio_get_output(aio1, 0)) != NULL); TEST_CHECK((s2 = nng_aio_get_output(aio2, 0)) != NULL); t1 = testutil_stream_send_start(s1, buf1, size); t2 = testutil_stream_recv_start(s2, buf2, size); TEST_NNG_PASS(testutil_stream_send_wait(t1)); TEST_NNG_PASS(testutil_stream_recv_wait(t2)); TEST_CHECK(memcmp(buf1, buf2, size) == 0); nng_free(buf1, size); nng_free(buf2, size); nng_stream_free(s1); nng_stream_free(s2); nng_stream_dialer_free(d); nng_stream_listener_free(l); nng_tls_config_free(c1); nng_tls_config_free(c2); nng_aio_free(aio1); nng_aio_free(aio2); } TEST_LIST = { { "tls config version", test_tls_config_version }, { "tls conn refused", test_tls_conn_refused }, { "tls large message", test_tls_large_message }, { NULL, NULL }, };