text
stringlengths
4
6.14k
// // TalkfunSettingView.h // CloudLive // // Created by LuoLiuyou on 16/8/19. // Copyright © 2016年 Talkfun. All rights reserved. // #import <UIKit/UIKit.h> @interface TalkfunSettingView : UIView @end
/* * test-utils.c * Copyright (c) 2016-2017 Arkadiusz Bokowy * * This file is a part of bluez-alsa. * * This project is licensed under the terms of the MIT license. * */ #include "inc/test.inc" #include "../src/utils.c" #include "../src/shared/ffb.c" #include "../src/shared/rt.c" int test_dbus_profile_object_path(void) { static const struct { enum bluetooth_profile profile; int16_t codec; const char *path; } profiles[] = { /* test null/invalid path */ { BLUETOOTH_PROFILE_NULL, -1, "/" }, { BLUETOOTH_PROFILE_NULL, -1, "/Invalid" }, /* test A2DP profiles */ { BLUETOOTH_PROFILE_A2DP_SOURCE, A2DP_CODEC_SBC, "/A2DP/SBC/Source" }, { BLUETOOTH_PROFILE_A2DP_SOURCE, A2DP_CODEC_SBC, "/A2DP/SBC/Source/1" }, { BLUETOOTH_PROFILE_A2DP_SOURCE, A2DP_CODEC_SBC, "/A2DP/SBC/Source/2" }, { BLUETOOTH_PROFILE_A2DP_SINK, A2DP_CODEC_SBC, "/A2DP/SBC/Sink" }, #if ENABLE_MP3 { BLUETOOTH_PROFILE_A2DP_SOURCE, A2DP_CODEC_MPEG12, "/A2DP/MPEG12/Source" }, { BLUETOOTH_PROFILE_A2DP_SINK, A2DP_CODEC_MPEG12, "/A2DP/MPEG12/Sink" }, #endif #if ENABLE_AAC { BLUETOOTH_PROFILE_A2DP_SOURCE, A2DP_CODEC_MPEG24, "/A2DP/MPEG24/Source" }, { BLUETOOTH_PROFILE_A2DP_SINK, A2DP_CODEC_MPEG24, "/A2DP/MPEG24/Sink" }, #endif #if ENABLE_APTX { BLUETOOTH_PROFILE_A2DP_SOURCE, A2DP_CODEC_VENDOR_APTX, "/A2DP/APTX/Source" }, { BLUETOOTH_PROFILE_A2DP_SINK, A2DP_CODEC_VENDOR_APTX, "/A2DP/APTX/Sink" }, #endif /* test HSP/HFP profiles */ { BLUETOOTH_PROFILE_HSP_HS, -1, "/HSP/Headset" }, { BLUETOOTH_PROFILE_HSP_AG, -1, "/HSP/AudioGateway" }, { BLUETOOTH_PROFILE_HFP_HF, -1, "/HFP/HandsFree" }, { BLUETOOTH_PROFILE_HFP_AG, -1, "/HFP/AudioGateway" }, }; size_t i; for (i = 0; i < sizeof(profiles) / sizeof(*profiles); i++) { const char *path = g_dbus_get_profile_object_path(profiles[i].profile, profiles[i].codec); assert(strstr(profiles[i].path, path) == profiles[i].path); assert(g_dbus_object_path_to_profile(profiles[i].path) == profiles[i].profile); if (profiles[i].codec != -1) assert(g_dbus_object_path_to_a2dp_codec(profiles[i].path) == profiles[i].codec); } return 0; } int test_pcm_scale_s16le(void) { const int16_t mute[] = { 0x0000, 0x0000, 0x0000, 0x0000 }; const int16_t half[] = { 0x1234 / 2, 0x2345 / 2, (int16_t)0xBCDE / 2, (int16_t)0xCDEF / 2 }; const int16_t halfl[] = { 0x1234 / 2, 0x2345, (int16_t)0xBCDE / 2, 0xCDEF }; const int16_t halfr[] = { 0x1234, 0x2345 / 2, 0xBCDE, (int16_t)0xCDEF / 2 }; const int16_t in[] = { 0x1234, 0x2345, 0xBCDE, 0xCDEF }; int16_t tmp[sizeof(in) / sizeof(*in)]; memcpy(tmp, in, sizeof(tmp)); snd_pcm_scale_s16le(tmp, sizeof(tmp) / sizeof(*tmp), 1, 0, 0); assert(memcmp(tmp, mute, sizeof(mute)) == 0); memcpy(tmp, in, sizeof(tmp)); snd_pcm_scale_s16le(tmp, sizeof(tmp) / sizeof(*tmp), 1, 1.0, 1.0); assert(memcmp(tmp, in, sizeof(in)) == 0); memcpy(tmp, in, sizeof(tmp)); snd_pcm_scale_s16le(tmp, sizeof(tmp) / sizeof(*tmp), 1, 0.5, 0.5); assert(memcmp(tmp, half, sizeof(half)) == 0); memcpy(tmp, in, sizeof(tmp)); snd_pcm_scale_s16le(tmp, sizeof(tmp) / sizeof(*tmp), 2, 0.5, 1.0); assert(memcmp(tmp, halfl, sizeof(halfl)) == 0); memcpy(tmp, in, sizeof(tmp)); snd_pcm_scale_s16le(tmp, sizeof(tmp) / sizeof(*tmp), 2, 1.0, 0.5); assert(memcmp(tmp, halfr, sizeof(halfr)) == 0); return 0; } int test_difftimespec(void) { struct timespec ts1, ts2, ts; ts1.tv_sec = ts2.tv_sec = 12345; ts1.tv_nsec = ts2.tv_nsec = 67890; assert(difftimespec(&ts1, &ts2, &ts) == 0); assert(ts.tv_sec == 0 && ts.tv_nsec == 0); ts1.tv_sec = 10; ts1.tv_nsec = 100000000; ts2.tv_sec = 10; ts2.tv_nsec = 500000000; assert(difftimespec(&ts1, &ts2, &ts) > 0); assert(ts.tv_sec == 0 && ts.tv_nsec == 400000000); ts1.tv_sec = 10; ts1.tv_nsec = 800000000; ts2.tv_sec = 12; ts2.tv_nsec = 100000000; assert(difftimespec(&ts1, &ts2, &ts) > 0); assert(ts.tv_sec == 1 && ts.tv_nsec == 300000000); ts1.tv_sec = 10; ts1.tv_nsec = 500000000; ts2.tv_sec = 10; ts2.tv_nsec = 100000000; assert(difftimespec(&ts1, &ts2, &ts) < 0); assert(ts.tv_sec == 0 && ts.tv_nsec == 400000000); ts1.tv_sec = 12; ts1.tv_nsec = 100000000; ts2.tv_sec = 10; ts2.tv_nsec = 800000000; assert(difftimespec(&ts1, &ts2, &ts) < 0); assert(ts.tv_sec == 1 && ts.tv_nsec == 300000000); return 0; } int test_fifo_buffer(void) { struct ffb ffb = { 0 }; assert(ffb_init(&ffb, 64) == 0); assert(ffb.data == ffb.tail); assert(ffb.size == 64); memcpy(ffb.data, "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ", 36); ffb_seek(&ffb, 36); assert(ffb_len_in(&ffb) == 64 - 36); assert(ffb_len_out(&ffb) == 36); assert(ffb.tail[-1] == 'Z'); ffb_rewind(&ffb, 15); assert(ffb_len_in(&ffb) == 64 - (36 - 15)); assert(ffb_len_out(&ffb) == 36 - 15); assert(memcmp(ffb.data, "FGHIJKLMNOPQRSTUVWXYZ", ffb_len_out(&ffb)) == 0); assert(ffb.tail[-1] == 'Z'); return 0; } int main(void) { test_run(test_dbus_profile_object_path); test_run(test_pcm_scale_s16le); test_run(test_difftimespec); test_run(test_fifo_buffer); return 0; }
#import <UIKit/UIKit.h> FOUNDATION_EXPORT double Pods_LGBCycleScrollView_ExampleVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_LGBCycleScrollView_ExampleVersionString[];
// dllmain.h : Declaration of module class. #include <fstream> typedef std::list< std::basic_string<TCHAR> > string_list; typedef struct { std::basic_string<TCHAR> path; std::basic_string<TCHAR> name; }target; typedef std::list< target > target_list; class CFb2EpubExtModule : public CAtlDllModuleT< CFb2EpubExtModule > { public : std::basic_string<TCHAR> m_INIPath; target_list m_targets; bool m_bAllowAllExtension; bool m_bAllowAllZip; bool m_bAllowAllRar; bool m_bUseSingleDestination; DECLARE_LIBID(LIBID_Fb2EpubExtLib) DECLARE_REGISTRY_APPID_RESOURCEID(IDR_FB2EPUBEXT, "{4A62D35B-DFF9-4901-A0EF-397236523B33}") void LoadINI(); static LPCTSTR GetPathWithoutFileName(LPTSTR); void StartLog(BOOL bOverwrite = FALSE); void EndLog(); void SetDllPath(HMODULE hModule); void Init(); private: // Read target from INI void ReadTargets(); // Read extension filter settings from INI void ReadFilters(); BOOL FindConverterApp(LPTSTR,unsigned int); std::basic_string<TCHAR> m_DLLPath; std::ofstream out; }; extern class CFb2EpubExtModule _AtlModule;
/* TFT_button.h - An object for the SEEEDStudio as an HMI type screen object Created by Christopher R. Stradling, April 14, 2015. Released unsigned into the public domain. */ #ifndef TFT_HMI_h #define TFT_HMI_h #include <Arduino.h> #include <stdint.h> #include <SeeedTouchScreen.h> #include <TFTv2.h> #include <SPI.h> #define OPEN 0 #define HELD 1 #define TOUCH 2 #define RELEASE 3 class TFT_button { public: TFT_button(unsigned int x, unsigned int y, const char *text, unsigned int text_size, unsigned int text_color, unsigned int background); TFT_button(unsigned int x, unsigned int y, unsigned int width, unsigned int height, unsigned int background); int state(unsigned int x, unsigned int y, unsigned int z); void set_sensitivity(unsigned int sensitivity); void set_background(unsigned int background); void redraw(); private: unsigned int _type; unsigned int _x; unsigned int _y; unsigned int _x_end; unsigned int _y_end; char _text[]; unsigned int _text_size; unsigned int _text_color; unsigned int _text_width; unsigned int _text_height; unsigned int _box_width; unsigned int _box_height; unsigned int _background; unsigned int _sensitivity; boolean _last_state; boolean _state; }; #endif
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard. // #import <IDEFoundation/IDERunOperation.h> @class DVTFilePath; @interface IDEOCUnitTestRunnerOperation : IDERunOperation { DVTFilePath *_testScopeFilePath; } @property(retain) DVTFilePath *testScopeFilePath; // @synthesize testScopeFilePath=_testScopeFilePath; - (void).cxx_destruct; - (void)runningDidFinish; @end
/* This Class contains members and member functions for a Phone object Phone objects access PhoneCall members so, PhoneCall.h is included <vector> is introduced here, the following references contributed to this code: http://stackoverflow.com/questions/8221702/accessing-elements-of-a-vector-in-c http://www.cplusplus.com/reference/vector/vector/operator[]/ */ //#include "PhoneCall.h" #include "SMS.h" #include "PhoneBook.h" #include<vector> using namespace std; class Phone{ private: string phoneNumber; double phoneCredit; vector<PhoneCall>callHistory; vector<SMS>smsHistory; public: Phone(); Phone(int id); vector<PhoneBook>myPhoneBook; void setPhoneNumber(int personId); void setPhoneCredit(double phoneCredit); string getPhoneNumber(); double getPhoneCredit(); static string basePhoneNumber; static int phoneCount; static int getPhoneCount(); void newPhoneCall(string num); PhoneCall getCallHistory(int index); int getCallHistorySize(); void newSMS(string num,string text); SMS getSmsHistory(int index); int getSmsHistorySize(); string getYear(); }; Phone::Phone(){ this->phoneNumber=""; this->phoneCredit=0; } Phone::Phone(int id){ phoneCount++; this->setPhoneNumber(id); this->phoneCredit=0; } void Phone::setPhoneNumber(int personId){ stringstream ss1,ss2,ss3,ss4,ss5; string temp; long int i_number; string number=basePhoneNumber+getYear(); number=number+"000"; ss1<<number; ss1>>i_number; i_number=i_number+personId; ss2<<i_number; ss2>>number; number=number+"00"; ss3<<number; ss3>>i_number; i_number=i_number+phoneCount; ss4<<i_number; ss4>>number; int lnum=rand()%10; ss5<<lnum; ss5>>temp; number="0"+number+temp; this->phoneNumber=number; } void Phone::setPhoneCredit(double phoneCredit){ this->phoneCredit=phoneCredit; } //Call void Phone::newPhoneCall(string num){ PhoneCall call(num); double credit=this->getPhoneCredit()-call.getCallCost(); this->setPhoneCredit(credit); this->callHistory.push_back(call); } //SMS void Phone::newSMS(string num,string text){ SMS sms(num,text); double credit=this->getPhoneCredit()-sms.getTextCost(); this->setPhoneCredit(credit); this->smsHistory.push_back(sms); } string Phone::getPhoneNumber(){ return this->phoneNumber; } double Phone::getPhoneCredit(){ return this->phoneCredit; } //static members string Phone::basePhoneNumber="017"; int Phone::phoneCount=0; int Phone::getPhoneCount(){ return phoneCount; } //Call PhoneCall Phone::getCallHistory(int index){ return this->callHistory[index]; } int Phone::getCallHistorySize(){ return this->callHistory.size(); //returns the size of the callHistory vector } //SMS SMS Phone::getSmsHistory(int index){ return this->smsHistory[index]; } int Phone::getSmsHistorySize(){ return this->smsHistory.size(); } string Phone::getYear(){ time_t clock=time(0); tm *now=localtime(&clock); int year=1900+(now->tm_year); string newYear=""; for(int i=0;i<2;i++){ stringstream ss; string stDigit; int digit=year%10; year=year/10; ss<<digit; ss>>stDigit; newYear=stDigit+newYear; } return newYear; }
///////////////////////////////////////////////////////////////////////////// // Name: wx/osx/srchctrl.h // Purpose: mac carbon wxSearchCtrl class // Author: Vince Harron // Created: 2006-02-19 // Copyright: Vince Harron // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// #ifndef _WX_SEARCHCTRL_H_ # define _WX_SEARCHCTRL_H_ # if wxUSE_SEARCHCTRL class wxSearchWidgetImpl; class WXDLLIMPEXP_CORE wxSearchCtrl : public wxSearchCtrlBase { public: // creation // -------- wxSearchCtrl(); wxSearchCtrl(wxWindow* parent, wxWindowID id, const wxString& value = wxEmptyString, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = 0, const wxValidator& validator = wxDefaultValidator, const wxString& name = wxASCII_STR(wxSearchCtrlNameStr)); virtual ~wxSearchCtrl(); bool Create(wxWindow* parent, wxWindowID id, const wxString& value = wxEmptyString, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = 0, const wxValidator& validator = wxDefaultValidator, const wxString& name = wxASCII_STR(wxSearchCtrlNameStr)); # if wxUSE_MENUS // get/set search button menu // -------------------------- void SetMenu(wxMenu* menu) override; wxMenu* GetMenu() override; # endif // get/set search options // ---------------------- void ShowSearchButton(bool show) override; bool IsSearchButtonVisible() const override; void ShowCancelButton(bool show) override; bool IsCancelButtonVisible() const override; void SetDescriptiveText(const wxString& text) override; wxString GetDescriptiveText() const override; virtual bool HandleSearchFieldSearchHit(); virtual bool HandleSearchFieldCancelHit(); wxSearchWidgetImpl* GetSearchPeer() const; protected: wxSize DoGetBestSize() const override; void Init(); # if wxUSE_MENUS wxMenu* m_menu; # endif wxString m_descriptiveText; private: wxDECLARE_DYNAMIC_CLASS(wxSearchCtrl); wxDECLARE_EVENT_TABLE(); }; # endif #endif
// This file was generated based on 'C:\ProgramData\Uno\Packages\UnoCore\0.13.2\Source\Uno\Collections\$.uno'. // WARNING: Changes might be lost if you edit this file directly. #ifndef __APP_UNO_COLLECTIONS_I_DICTIONARY__CHAR__FLOAT_H__ #define __APP_UNO_COLLECTIONS_I_DICTIONARY__CHAR__FLOAT_H__ #include <app/Uno.Collections.IEnumerable__Uno_Collections_KeyValuePair_char_float_.h> #include <app/Uno.Object.h> #include <Uno.h> namespace app { namespace Uno { namespace Collections { ::uInterfaceType* IDictionary__char__float__typeof(); struct IDictionary__char__float { }; }}} #endif
///////////////////////////////////////////////////////////////////////////// // Name: wx/imagbmp.h // Purpose: wxImage BMP, ICO, CUR and ANI handlers // Author: Robert Roebling, Chris Elliott // Copyright: (c) Robert Roebling, Chris Elliott // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// #ifndef _WX_IMAGBMP_H_ # define _WX_IMAGBMP_H_ # include "wx/image.h" // defines for saving the BMP file in different formats, Bits Per Pixel // USE: wximage.SetOption( wxIMAGE_OPTION_BMP_FORMAT, wxBMP_xBPP ); # define wxIMAGE_OPTION_BMP_FORMAT wxString(wxT("wxBMP_FORMAT")) // These two options are filled in upon reading CUR file and can (should) be // specified when saving a CUR file - they define the hotspot of the cursor: # define wxIMAGE_OPTION_CUR_HOTSPOT_X wxT("HotSpotX") # define wxIMAGE_OPTION_CUR_HOTSPOT_Y wxT("HotSpotY") enum { wxBMP_24BPP = 24, //wxBMP_16BPP = 16, // wxQuantize can only do 236 colors? wxBMP_8BPP = 8, wxBMP_8BPP_GREY = 9, wxBMP_8BPP_GRAY = wxBMP_8BPP_GREY, wxBMP_8BPP_RED = 10, wxBMP_8BPP_PALETTE = 11, wxBMP_4BPP = 4, wxBMP_1BPP = 1, wxBMP_1BPP_BW = 2 }; // ---------------------------------------------------------------------------- // wxBMPHandler // ---------------------------------------------------------------------------- class WXDLLIMPEXP_CORE wxBMPHandler : public wxImageHandler { public: wxBMPHandler() { m_name = wxT("Windows bitmap file"); m_extension = wxT("bmp"); m_type = wxBITMAP_TYPE_BMP; m_mime = wxT("image/x-bmp"); } # if wxUSE_STREAMS bool SaveFile(wxImage* image, wxOutputStream& stream, bool verbose = true) override; bool LoadFile(wxImage* image, wxInputStream& stream, bool verbose = true, int index = -1) override; protected: bool DoCanRead(wxInputStream& stream) override; bool SaveDib(wxImage* image, wxOutputStream& stream, bool verbose, bool IsBmp, bool IsMask); bool DoLoadDib(wxImage* image, int width, int height, int bpp, int ncolors, int comp, wxFileOffset bmpOffset, wxInputStream& stream, bool verbose, bool IsBmp, bool hasPalette, int colEntrySize = 4); bool LoadDib(wxImage* image, wxInputStream& stream, bool verbose, bool IsBmp); # endif private: wxDECLARE_DYNAMIC_CLASS(wxBMPHandler); }; # if wxUSE_ICO_CUR // ---------------------------------------------------------------------------- // wxICOHandler // ---------------------------------------------------------------------------- class WXDLLIMPEXP_CORE wxICOHandler : public wxBMPHandler { public: wxICOHandler() { m_name = wxT("Windows icon file"); m_extension = wxT("ico"); m_type = wxBITMAP_TYPE_ICO; m_mime = wxT("image/x-ico"); } # if wxUSE_STREAMS bool SaveFile(wxImage* image, wxOutputStream& stream, bool verbose = true) override; bool LoadFile(wxImage* image, wxInputStream& stream, bool verbose = true, int index = -1) override; virtual bool DoLoadFile(wxImage* image, wxInputStream& stream, bool verbose, int index); protected: int DoGetImageCount(wxInputStream& stream) override; bool DoCanRead(wxInputStream& stream) override; # endif private: wxDECLARE_DYNAMIC_CLASS(wxICOHandler); }; // ---------------------------------------------------------------------------- // wxCURHandler // ---------------------------------------------------------------------------- class WXDLLIMPEXP_CORE wxCURHandler : public wxICOHandler { public: wxCURHandler() { m_name = wxT("Windows cursor file"); m_extension = wxT("cur"); m_type = wxBITMAP_TYPE_CUR; m_mime = wxT("image/x-cur"); } // VS: This handler's meat is implemented inside wxICOHandler (the two // formats are almost identical), but we hide this fact at // the API level, since it is a mere implementation detail. # if wxUSE_STREAMS protected: bool DoCanRead(wxInputStream& stream) override; # endif private: wxDECLARE_DYNAMIC_CLASS(wxCURHandler); }; // ---------------------------------------------------------------------------- // wxANIHandler // ---------------------------------------------------------------------------- class WXDLLIMPEXP_CORE wxANIHandler : public wxCURHandler { public: wxANIHandler() { m_name = wxT("Windows animated cursor file"); m_extension = wxT("ani"); m_type = wxBITMAP_TYPE_ANI; m_mime = wxT("image/x-ani"); } # if wxUSE_STREAMS bool SaveFile(wxImage*, wxOutputStream&, bool) override { return false; } bool LoadFile(wxImage* image, wxInputStream& stream, bool verbose = true, int index = -1) override; protected: int DoGetImageCount(wxInputStream& stream) override; bool DoCanRead(wxInputStream& stream) override; # endif private: wxDECLARE_DYNAMIC_CLASS(wxANIHandler); }; # endif #endif
/*! NSString extension RFKit Copyright (c) 2012-2013 BB9z https://github.com/bb9z/RFKit The MIT License (MIT) http://www.opensource.org/licenses/mit-license.php */ #import <Foundation/Foundation.h> @interface NSString (RFKit) + (NSString *)MD5String:(NSString *)string; //! http://lldong.github.com/blog/2012/11/06/hanzi-to-pinyin/ // + (NSString *)pinyinFromString:(NSString *)orgString; /** Reverse a NSString @return String reversed */ - (NSString *)reverseString; /** 给定字体,屏幕长度,将字符串截断到指定长度 这个方法不改变原始字符串 @param length 屏幕长度 @param font 计算所用字体 @return 符合长度的字符串 */ - (NSString *)stringTrimToWidthLength:(CGFloat)length WithFont:(UIFont *)font; @end
/** * \file bsort_public.h * \brief Bsort public functions * \author J.Amores (biomol at gmail dot com) */ /* * Dummy 'bubble sort' implementation, to be compiled either for 'SPACE' and 'SPEED' * */ #ifndef BSORT_PUBLIC_H #define BSORT_PUBLIC_H /**/ /* Includes */ /**/ #include <avr/io.h> /**/ /* Functions' headers */ /**/ void Bsort_00(void); void Bsort_01(void); #endif /* EXAMPLE_01_PUBLIC_H */
/* * ofxCv2Constants.h * ofxOpenCv2 * * Created by Marynel Vazquez on 3/12/11. * Copyright 2011 Robotics Institute. Carnegie Mellon University. All rights reserved. * */ #ifndef OFXCV2_CONSTANTS #define OFXCV2_CONSTANTS #include <vector> #include "ofMain.h" #include "opencv.hpp" using namespace cv; #endif
/* $Id$ */ #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <stdio.h> int udp_server(int *sock, int *port) /* Create a datagram socket in the internet domain (i.e. udp) and bind it to a port. Return the socket file descriptor and the port number in the argument list. Returned is 0 if all is OK or -1 if an error is detected. */ { int len; struct sockaddr_in name; if((*sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) return -1; name.sin_family = AF_INET; name.sin_addr.s_addr = INADDR_ANY; name.sin_port = 0; if (bind(*sock, (struct sockaddr *) &name, sizeof name) < 0) return -1; len = sizeof(name); if (getsockname(*sock, (struct sockaddr *) &name, &len) < 0) return -1; *port = ntohs(name.sin_port); return 0; } int udp_recv(int sock, char *buf, int lenbuf) /* Read data from the unconnected udp socket sock. lenbuf is the size of buf. Returned is the amount of data actually read or -1 if an error was detected. Note that udp datagrams are forced to be small (typicall <=2048 bytes) by the protocol. */ { int zero = 0; return recvfrom(sock, buf, lenbuf, 0, (struct sockaddr *) NULL, &zero); } int udp_send(const char *hostname, int port, const char *buf, int lenbuf) /* Send a udp packet of lenbuf bytes from buffer buf to the specified port and host. Returned is the number of bytes actually sent or -1 if any error was detected. */ { int sock, len; struct sockaddr_in name; struct hostent *hp, *gethostbyname(); if((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) return -1; if((hp = gethostbyname(hostname)) == (struct hostent *) 0) return -1; bcopy((char *)hp->h_addr, (char *)&name.sin_addr, hp->h_length); name.sin_family = AF_INET; name.sin_port = htons((u_short) port); len = sendto(sock, buf, lenbuf, 0, (struct sockaddr *) &name, sizeof name); (void) close(sock); return len; }
// // NTJContext.h // NTJJavaScriptCoreLogicSample // // Created by joshua may on 16/02/2014. // Copyright (c) 2014 notjosh, inc. All rights reserved. // #import <JavaScriptCore/JavaScriptCore.h> @interface NTJContext : JSContext - (void)loadScript:(NSString *)script; @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 "MPMediaQuery.h" @interface MPMediaQuery (MPUSearchDataSourceAdditions) - (id)_MPUSDS_searchPredicate; @end
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // 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 _DEFERREDSHADINGGLSL_H_ #define _DEFERREDSHADINGGLSL_H_ #include "shaderGen/GLSL/shaderFeatureGLSL.h" #include "shaderGen/GLSL/bumpGLSL.h" #include "shaderGen/GLSL/pixSpecularGLSL.h" // Specular Outputs class DeferredSpecMapGLSL : public ShaderFeatureGLSL { public: virtual String getName() { return "Deferred Shading: Specular Map"; } virtual void processPix( Vector<ShaderComponent*> &componentList, const MaterialFeatureData &fd ); virtual Resources getResources( const MaterialFeatureData &fd ); // Sets textures and texture flags for current pass virtual void setTexData( Material::StageData &stageDat, const MaterialFeatureData &fd, RenderPassData &passData, U32 &texIndex ); virtual void processVert( Vector<ShaderComponent*> &componentList, const MaterialFeatureData &fd ); }; class DeferredMatInfoFlagsGLSL : public ShaderFeatureGLSL { public: virtual String getName() { return "Deferred Shading: Mat Info Flags"; } virtual void processPix( Vector<ShaderComponent*> &componentList, const MaterialFeatureData &fd ); virtual U32 getOutputTargets( const MaterialFeatureData &fd ) const { return ShaderFeature::RenderTarget2; } }; class DeferredSpecVarsGLSL : public ShaderFeatureGLSL { public: virtual String getName() { return "Deferred Shading: Specular Explicit Numbers"; } virtual void processPix( Vector<ShaderComponent*> &componentList, const MaterialFeatureData &fd ); virtual U32 getOutputTargets( const MaterialFeatureData &fd ) const { return ShaderFeature::RenderTarget2; } }; #endif
/* Search 2D Matrix. */ #include <stdio.h> #include <stdbool.h> /* Binary Search. */ bool _exist(int* n, int l, int r, int target) { if (l > r) return false; int mid = (r + l) / 2; if (n[mid] == target) return true; if (n[mid] > target) return _exist(n, l, mid-1, target); else return _exist(n, mid+1, r, target); } bool exist(int* n, int size, int target) { if(target >= n[0] && target <= n[size - 1]) return _exist(n, 0, size-1, target); return false; } bool searchMatrix(int** matrix, int matrixRowSize, int matrixColSize, int target) { if (matrixRowSize == 0 || matrixColSize == 0) return false; if (target < matrix[0][0] || target > matrix[matrixRowSize - 1][matrixColSize - 1]) return false; if (matrixRowSize == 1) return exist(matrix[0], matrixColSize, target); int mid = matrixRowSize / 2; if (matrix[mid][0] <= target) { if (exist(matrix[mid], matrixColSize, target)) return true; return searchMatrix(matrix + mid + 1, matrixRowSize - mid - 1, matrixColSize, target); } return searchMatrix(matrix, mid, matrixColSize, target); } int main() { // TO-DO: test case. return 0; }
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE78_OS_Command_Injection__wchar_t_listen_socket_w32spawnl_65a.c Label Definition File: CWE78_OS_Command_Injection.strings.label.xml Template File: sources-sink-65a.tmpl.c */ /* * @description * CWE: 78 OS Command Injection * BadSource: listen_socket Read data using a listen socket (server side) * GoodSource: Fixed string * Sinks: w32spawnl * BadSink : execute command with wspawnl * Flow Variant: 65 Data/control flow: data passed as an argument from one function to a function in a different source file called via a function pointer * * */ #include "std_testcase.h" #include <wchar.h> #ifdef _WIN32 #define COMMAND_INT_PATH L"%WINDIR%\\system32\\cmd.exe" #define COMMAND_INT L"cmd.exe" #define COMMAND_ARG1 L"/c" #define COMMAND_ARG2 L"dir" #define COMMAND_ARG3 data #else /* NOT _WIN32 */ #include <unistd.h> #define COMMAND_INT_PATH L"/bin/sh" #define COMMAND_INT L"sh" #define COMMAND_ARG1 L"ls" #define COMMAND_ARG2 L"-la" #define COMMAND_ARG3 data #endif #ifdef _WIN32 #include <winsock2.h> #include <windows.h> #include <direct.h> #pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */ #define CLOSE_SOCKET closesocket #else #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #define INVALID_SOCKET -1 #define SOCKET_ERROR -1 #define CLOSE_SOCKET close #define SOCKET int #endif #define TCP_PORT 27015 #define LISTEN_BACKLOG 5 #include <process.h> #ifndef OMITBAD /* bad function declaration */ void CWE78_OS_Command_Injection__wchar_t_listen_socket_w32spawnl_65b_badSink(wchar_t * data); void CWE78_OS_Command_Injection__wchar_t_listen_socket_w32spawnl_65_bad() { wchar_t * data; /* define a function pointer */ void (*funcPtr) (wchar_t *) = CWE78_OS_Command_Injection__wchar_t_listen_socket_w32spawnl_65b_badSink; wchar_t dataBuffer[100] = L""; data = dataBuffer; { #ifdef _WIN32 WSADATA wsaData; int wsaDataInit = 0; #endif int recvResult; struct sockaddr_in service; wchar_t *replace; SOCKET listenSocket = INVALID_SOCKET; SOCKET acceptSocket = INVALID_SOCKET; size_t dataLen = wcslen(data); do { #ifdef _WIN32 if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) { break; } wsaDataInit = 1; #endif /* POTENTIAL FLAW: Read data using a listen socket */ listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (listenSocket == INVALID_SOCKET) { break; } memset(&service, 0, sizeof(service)); service.sin_family = AF_INET; service.sin_addr.s_addr = INADDR_ANY; service.sin_port = htons(TCP_PORT); if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) { break; } if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR) { break; } acceptSocket = accept(listenSocket, NULL, NULL); if (acceptSocket == SOCKET_ERROR) { break; } /* Abort on error or the connection was closed */ recvResult = recv(acceptSocket, (char *)(data + dataLen), sizeof(wchar_t) * (100 - dataLen - 1), 0); if (recvResult == SOCKET_ERROR || recvResult == 0) { break; } /* Append null terminator */ data[dataLen + recvResult / sizeof(wchar_t)] = L'\0'; /* Eliminate CRLF */ replace = wcschr(data, L'\r'); if (replace) { *replace = L'\0'; } replace = wcschr(data, L'\n'); if (replace) { *replace = L'\0'; } } while (0); if (listenSocket != INVALID_SOCKET) { CLOSE_SOCKET(listenSocket); } if (acceptSocket != INVALID_SOCKET) { CLOSE_SOCKET(acceptSocket); } #ifdef _WIN32 if (wsaDataInit) { WSACleanup(); } #endif } /* use the function pointer */ funcPtr(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void CWE78_OS_Command_Injection__wchar_t_listen_socket_w32spawnl_65b_goodG2BSink(wchar_t * data); static void goodG2B() { wchar_t * data; void (*funcPtr) (wchar_t *) = CWE78_OS_Command_Injection__wchar_t_listen_socket_w32spawnl_65b_goodG2BSink; wchar_t dataBuffer[100] = L""; data = dataBuffer; /* FIX: Append a fixed string to data (not user / external input) */ wcscat(data, L"*.*"); funcPtr(data); } void CWE78_OS_Command_Injection__wchar_t_listen_socket_w32spawnl_65_good() { goodG2B(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on * its own for testing or for building a binary to use in testing binary * analysis tools. It is not used when compiling all the testcases as one * application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE78_OS_Command_Injection__wchar_t_listen_socket_w32spawnl_65_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE78_OS_Command_Injection__wchar_t_listen_socket_w32spawnl_65_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
#pragma once #include <Tools/nstring.h> #include <iostream> #include <string> #include <sstream> #include <time.h> #include <inttypes.h> #include <vector> namespace Utils { void setNostalePath(std::string path); void setMD5(std::string nostaleX, std::string nostale); uint32_t seedRandom(uint32_t p0); std::string hex2decimal_str(uint32_t p0); uint32_t decimal_str2hex(std::string id); std::vector<std::string> tokenize(const std::string &s, char delim = ' '); uint8_t encrypt_number(uint32_t id); uint8_t encrypt_key(uint32_t id); namespace Login { std::string decryptPass(std::string& password); std::string encryptPass(std::string& password); NString makePacket(std::string username, std::string password); } namespace Game { class Session { public: Session(); void reset(); void setID(uint32_t id); void setAlive(uint16_t alive); uint16_t alive(); bool check_alive(std::string& alive); inline uint16_t peek_alive() { return _alive; } inline uint32_t id() { return _idHex; } inline uint8_t number() { return _number; } inline uint8_t key() { return _key; } private: uint32_t _idHex; uint16_t _alive; uint8_t _number; uint8_t _key; }; }; }
#include <dict/dict_ii.h> #include <assert.h> int main(int argc, char* argv[]) { dict_context_ii_t* dict_context_ii = dict_new_ii(); assert(dict_context_ii != NULL); dict_context_ii_t* dict_context_ii_retain = dict_retain_ii(dict_context_ii); assert(dict_retain_count_ii(dict_context_ii) == 2); assert(dict_retain_count_ii(dict_context_ii_retain) == 2); dict_delete_ii(dict_context_ii_retain); assert(dict_retain_count_ii(dict_context_ii) == 1); assert(dict_retain_count_ii(dict_context_ii_retain) == 1); dict_context_ii_t* dict_context_ii_copy = dict_copy_ii(dict_context_ii); assert(dict_context_ii_copy != NULL); assert(dict_retain_count_ii(dict_context_ii_copy) == 1); dict_delete_ii(dict_context_ii_copy); for (int i = 0; i < 2; i++) { assert(dict_set_ii(dict_context_ii, 1, 111) == 0); assert(dict_set_ii(dict_context_ii, 2, 222) == 0); assert(dict_set_ii(dict_context_ii, 3, 333) == 0); assert(dict_count_ii(dict_context_ii) == 3); assert(dict_has_key_ii(dict_context_ii, 1) == 0); assert(dict_has_key_ii(dict_context_ii, 2) == 0); assert(dict_has_key_ii(dict_context_ii, 3) == 0); assert(dict_has_key_ii(dict_context_ii, 4) != 0); int value; assert(dict_get_ii(dict_context_ii, 1, &value) == 0); assert(value == 111); assert(dict_get_ii(dict_context_ii, 2, &value) == 0); assert(value == 222); assert(dict_get_ii(dict_context_ii, 3, &value) == 0); assert(value == 333); assert(dict_get_ii(dict_context_ii, 4, &value) != 0); dict_iter_ii_t* dict_iter_ii = dict_iter_new_ii(dict_context_ii); assert(dict_iter_ii != NULL); int key; assert(dict_iter_get_ii(dict_iter_ii, &key, &value) == 0); assert(key == 1); assert(value == 111); assert(dict_iter_get_ii(dict_iter_ii, &key, &value) == 0); assert(key == 2); assert(value == 222); assert(dict_iter_get_ii(dict_iter_ii, &key, &value) == 0); assert(key == 3); assert(value == 333); assert(dict_iter_get_ii(dict_iter_ii, &key, &value) != 0); dict_iter_delete_ii(dict_iter_ii); assert(dict_remove_ii(dict_context_ii, 1) == 0); assert(dict_has_key_ii(dict_context_ii, 1) != 0); assert(dict_remove_ii(dict_context_ii, 2) == 0); assert(dict_has_key_ii(dict_context_ii, 2) != 0); assert(dict_remove_ii(dict_context_ii, 4) != 0); assert(dict_has_key_ii(dict_context_ii, 4) != 0); assert(dict_count_ii(dict_context_ii) == 1); assert(dict_clear_ii(dict_context_ii) == 0); assert(dict_count_ii(dict_context_ii) == 0); } dict_delete_ii(dict_context_ii); return 0; }
// // CMHProfileViewController.h // MHDevelopExample // // Created by lx on 2018/5/24. // Copyright © 2018年 CoderMikeHe. All rights reserved. // #import "CMHTableViewController.h" @interface CMHProfileViewController : CMHTableViewController @end
#ifndef __GAMEBOARD_H #define __GAMEBOARD_H #include "joyos.h" typedef struct point { float x; float y; } point_t; static point_t centers[6] = { {1024, 0}, \ {768, 887}, \ {-768, 887}, \ {-1024, 0}, \ {-768, -887}, \ {768, -887} }; static point_t outer_vertices[6] = { {2047, 0}, \ {1024, 1773}, \ {-1024, 1773}, \ {-2047, 0}, \ {-1024, -1773}, \ {1024, -1773} }; static point_t inner_vertices[6] = { {443, 256}, \ {0, 512}, \ {-443, 256}, \ {-443, -256}, \ {0, -512}, \ {443, -256} }; static point_t targets[2] = { {-128, 221.5}, \ {128, -221.4} }; static point_t blue_lever_offsets[6] = { {256, 5}, \ {242, -22}, \ {240, 35}, \ {250, 28}, \ {256, 30}, \ {260, 0} }; static point_t red_lever_offsets[6] = { {260, -10}, \ {242, -30}, \ {235, 15}, \ {240, 44}, \ {256, 10}, \ {250, 0} }; typedef struct territory { point_t gearbox; point_t lever; } territory_t; static territory_t territories[6] = { { {1791, 443}, {1791, -443} }, \ { {512, 1773}, {1280, 1330} }, \ { {-1280, 1330}, {-512, 1773} }, \ { {-1791, -443}, {-1791, 443} }, \ { {-512, -1773}, {-1280, -1330} }, \ { {1280, -1330}, {512, -1773} } }; float distanceTo(point_t p); uint8_t opponentPosition(void); uint8_t closestTerritory(void); point_t closestGearbox(void); point_t closestLever(void); point_t gearboxOffset(float nOffset, float pOffset, uint8_t territory); point_t leverOffset(float nOffset, float pOffset, uint8_t territory); point_t leverTargetOffset(float nOffset, float pOffset, uint8_t territory); void decomposeLeverTarget(float x, float y); #endif
/** This file contains Buffer and OutBuffer classes for API operations. */ //----------------------------------------------------------------------------- // <Buffer> // Input Buffer used to send data to the API. //----------------------------------------------------------------------------- typedef struct Buffer { PVOID pData; // this may contain a single or multiple records size_t DataLength; // length of data in pData ChemFormat DataFormat; // format of data in pData int recordCount; // approximate number of records in pData Buffer(bool releaseData = true) : pData(NULL), DataLength(0), DataFormat(fmtUnknown), recordCount(1), m_releaseData(releaseData) {} ~Buffer() { if(m_releaseData) DeleteAndNull(pData); } private: bool m_releaseData; // Default: True. Set to False in ctor to avoid releasing pData } BUFFER, *LPBUFFER; //----------------------------------------------------------------------------- // <OutBuffer> // Output Buffer used to get values back from the API. //----------------------------------------------------------------------------- typedef struct OutBuffer { PVOID pData; size_t DataLength; OutBuffer() : pData(NULL), DataLength(0) {} } OUTBUFFER, *LPOUTBUFFER;
#pragma once namespace Engine { namespace Scripting { namespace Python3 { struct PyObjectFieldAccessor; struct PyDictPtr; struct MADGINE_PYTHON3_EXPORT PyObjectPtr { PyObjectPtr() = default; PyObjectPtr(PyObject *object); PyObjectPtr(const PyObjectPtr &other); PyObjectPtr(PyObjectPtr &&other); ~PyObjectPtr(); PyObjectPtr get(std::string_view name) const; PyObjectPtr call(std::string_view name, const char *format, ...) const; PyObjectPtr call(std::string_view name, const PyDictPtr &kwargs, const char *format, ...) const; PyObjectPtr call(std::string_view name, const PyObjectPtr &args, const PyObjectPtr &kwargs) const; PyObjectFieldAccessor operator[](const PyObjectPtr &name) const; void reset(); PyObjectPtr &operator=(PyObjectPtr &&other); explicit operator bool() const; operator PyObject *() const; static PyObjectPtr None(); protected: PyObject *mObject = nullptr; }; struct MADGINE_PYTHON3_EXPORT PyObjectFieldAccessor { PyObjectFieldAccessor &operator=(const PyObjectPtr &value); PyObjectPtr mObject; PyObjectPtr mKey; }; } } }
// // IFIndoorLocationManager.h // ifinitySDK // // Created by GetIfinity on 17.10.2014. // Copyright (c) 2014 GetIfinity. All rights reserved. // #import <Foundation/Foundation.h> #import <CoreLocation/CoreLocation.h> #import "IFBluetoothManager.h" /** * IFIndoorLocationManager is used to track user position within the buildings, notifies when user enters into area, or leaves it */ @class IFIndoorLocationManager; /** * Delegate for `IFIndoorLocationManager` */ @protocol IFIndoorLocationManagerDelegate <NSObject> @optional /** * We've just enter into the new area * * @param area Active area. */ - (void)manager:(IFIndoorLocationManager *)manager didUpdateIndoorLocation:(CLLocation *)location; /** * We've just enter into the new area * * @param area Active area. */ - (void)manager:(IFIndoorLocationManager *)manager didEnterArea:(IFMArea *)area; /** * We've just leave the area * * @param area Area we've just left */ - (void)manager:(IFIndoorLocationManager *)manager didExitArea:(IFMArea *)area; /** * Method to provide to IFIndoorLocationManager beacon coordinates. * If this method is immplemented it overrides data from internal cache (data from geos). * In theory this delegate should allow to implement own beacons source for navigation logic. * * @param area Area we've just left */ - (CLLocation *)manager:(IFIndoorLocationManager *)manager locationForTransmitter:(IFTransmitter *)transmitter; @end /** * The `IFIndoorLocationManager` class is central point for delivering information about indoor device position. * */ @interface IFIndoorLocationManager : NSObject @property (nonatomic, weak) id<IFIndoorLocationManagerDelegate> delegate; /** * Current user position (indoors) */ @property (nonatomic, readonly) CLLocation *currentLocation; /** * shared instance of IFBluetoothManager */ - (instancetype)initWithBluetoothManager:(IFBluetoothManager *)manager; /** * Once we want to be notified about user indoor position updates */ - (void)startUpdatingIndoorLocation; /** * Shuts down the indoor monitoring process */ - (void)stopUpdatingIndoorLocation; /** * Start detecting current area base on calculated position. When area changed notify about it by calling methods in delegate (didEnterArea, didExitArea). * * @param floorplan A floorplan we're interested in */ - (void)startCheckingAreasForFloorplan:(IFMFloorplan *)floorplan; /** * Stop checking areas for current position. */ - (void)stopCheckingAreas; /** * Current area base on position * * @return area model object */ - (IFMArea *)currentArea; @end
// // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // // Developed by Minigraph // // Author: James Stanard // #pragma once #include "EngineTuning.h" // Forward declarations namespace Math { class Matrix4; class Camera; } class ColorBuffer; class CommandContext; namespace MotionBlur { extern BoolVar Enable; void Initialize( void ); void Shutdown( void ); // Generate motion blur only associated with the camera. Does not handle fast-moving objects well, but // does not require a full screen velocity buffer. void RenderCameraBlur( CommandContext& Context, const Math::Camera& camera, bool UseLinearZ = true ); void RenderCameraBlur( CommandContext& Context, const Math::Matrix4& reprojectionMatrix, float nearClip, float farClip, bool UseLinearZ = true); // Generate proper motion blur that takes into account the velocity of each pixel. Requires a pre-generated // velocity buffer (R16G16_FLOAT preferred.) void RenderObjectBlur( CommandContext& Context, ColorBuffer& velocityBuffer ); } namespace TemporalAA { extern BoolVar Enable; void ApplyTemporalAA(CommandContext& Context); }
// // Barbeiro.c: Este programa implementa um dos classicos de programação // concorrente: o barbeiro dorminhoco. // O objetivo deste programa é testar a implementação do // micro kernel desenvolvido na disciplina INF01142 // // Primitivas testadas: ccreate, cjoin, cyield, cwait e csignal. // // Este programa é basedo na solução de Tanenbaum apresentada no livro // "Modern Operating System" (Prentice Hall International 2 ed.). // // Disclamer: este programa foi desenvolvido para auxiliar no desenvolvimento // de testes para o micronúcleo. NÃO HÁ garantias de estar correto. #include<stdlib.h> #include<unistd.h> #include<pthread.h> #include<errno.h> #include "../include/support.h" #include "../include/cthread.h" #include <stdio.h> #define CHAIRS 5 time_t end_time; csem_t customers; csem_t mutex; csem_t barbers; int waiting = 0; void sleepao() { int i = 0; i = rand()%5 + 1; for (; i<0; i--) cyield(); return; } void cut_hair(void) { cyield(); cyield(); cyield(); cyield; return; } void* barber(void* arg) { while(time(NULL)<end_time || waiting > 0) { cwait(&customers); cwait(&mutex); waiting = waiting - 1; printf("Barbeiro trabalhando, %d clientes esperam!! \n",waiting); csignal(&mutex); cut_hair(); csignal(&barbers); } return; } void* customer(void* arg) { while(time(NULL) < end_time) { cwait(&mutex); if (waiting < CHAIRS) { waiting = waiting + 1; printf(" ---> Cliente chegando. Há %d clientes esperando.\n", waiting); csignal(&customers); csignal(&mutex); cwait(&barbers); } else { printf(" ***Cliente indo embora. Não há mais cadeiras.\n"); csignal(&mutex); } sleepao(); } return; } int main(int argc, char **argv) { int tidBarber, tidCustomer; end_time=time(NULL)+120; /*Barbearia fica aberta 120 s */ srand((unsigned)time(NULL)); csem_init(&customers, 0); csem_init(&barbers, 1); csem_init(&mutex, 1); tidBarber = ccreate (barber, (void *) NULL); if (tidBarber < 0 ) perror("Erro na criação do Barbeiro...\n"); tidCustomer = ccreate (customer, (void *) NULL); if (tidCustomer < 0 ) perror("Erro na criação do gerador de clientes...\n"); cjoin(tidBarber); cjoin(tidCustomer); exit(0); }
/*============================================================================== Copyright (c) 2012-2013 Qualcomm Connected Experiences, Inc. All Rights Reserved. ==============================================================================*/ #import <UIKit/UIKit.h> #import "TextRecoEAGLView.h" #import "SampleApplicationSession.h" #import <QCAR/DataSet.h> #import "SampleAppMenu.h" @interface TextRecoViewController : UIViewController <SampleApplicationControl, SampleAppMenuCommandProtocol>{ CGRect viewFrame; CGRect viewQCARFrame; TextRecoEAGLView* eaglView; UITapGestureRecognizer * tapGestureRecognizer; SampleApplicationSession * vapp; id backgroundObserver; id activeObserver; int ROICenterX; int ROICenterY; int ROIWidth; int ROIHeight; } @end
#include <stdio.h> int main() { float length, width; printf("Enter the length of the rectangle:\n"); while (scanf("%f", &length) == 1) { printf("Length = %0.2f:\n", length); printf("Enter its width:\n"); if (scanf("%f", &width) != 1) break; printf("Width = %0.2f:\n", width); printf("Area = %0.2f:\n", length * width); printf("Enter the length of the rectangle:\n"); } printf("Done.\n"); return 0; }
// // ECLocalizer.h // ECLocalizer // // Created by Eric Cerney on 3/28/14. // Copyright (c) 2014 Eric Cerney. All rights reserved. // #import <AppKit/AppKit.h> @interface ECLocalizer : NSObject @end
// // VDHookElement.h // objcTempUtilities // // Created by Deng on 16/6/17. // Copyright © Deng. All rights reserved. // #import <Foundation/Foundation.h> #import "VDHookInvocationInfo.h" @class VDHookElement; @interface VDHookElement : NSObject #pragma mark Public Method + (instancetype)elementWithTarget:(id)target selector:(SEL)selector block:(void (^)(VDHookElement *element, VDHookInvocationInfo *info))block; + (instancetype)elementWithTarget:(id)target selector:(SEL)selector block:(void (^)(VDHookElement *element, VDHookInvocationInfo *info))block autoRemove:(BOOL)autoRemove; - (void)invokeBlock:(VDHookInvocationInfo *)invocationInfo; - (void)dispose; #pragma mark Properties @property (nonatomic, weak) id target; @property (nonatomic, assign) SEL selector; @property (nonatomic, strong) void(^block)(VDHookElement *element, VDHookInvocationInfo *info); @property (nonatomic, assign, readonly) BOOL autoRemove; @property (nonatomic, assign, readonly) BOOL isDisposed; @end
// // Avatar.h // Vampires // // Created by Jon Taylor on 12-03-13. // Copyright (c) 2012 Subject Reality Software. All rights reserved. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #import <OpenGLES/EAGL.h> #import <OpenGLES/ES1/gl.h> #import <OpenGLES/ES1/glext.h> #import "OpenGLWaveFrontObject.h" #import "Sound.h" @interface Avatar : NSObject { OpenGLWaveFrontObject* boyObject; OpenGLWaveFrontObject* boyLeftObject; OpenGLWaveFrontObject* boyRightObject; int stage; int stages; float stageDuration; float durationIndex; Sound * sound; } - (id)init; -(void)draw:(float)frs isWalking:(float)walkingSpeed; -(OpenGLWaveFrontObject*) loadBoyObject:(NSString*)n; -(void)setSound:(Sound *)s; @end
#ifndef CQTAB_WIDGET_H #define CQTAB_WIDGET_H #define CQTAB_WIDGET_MOVABLE 1 #include <QTabWidget> #include <QTabBar> class CQFloatEdit; class CQTabWidgetTabBar; class QMenu; class CQTabWidget : public QTabWidget { Q_OBJECT Q_PROPERTY(bool showMoveButtons READ getShowMoveButtons WRITE setShowMoveButtons) public: CQTabWidget(QWidget *parent=nullptr); ~CQTabWidget(); void addCreateButton(); bool getShowMoveButtons() const { return moveButtons_; } void setShowMoveButtons(bool show); void contextMenuEvent(QContextMenuEvent *e) override; QMenu *createTabMenu() const; public slots: void moveTabLeft (); void moveTabRight(); void moveTab(int fromIndex, int toIndex); void tabSlot(); signals: void tabChanged(int ind); void createTab(); void swapTabs(int ind1, int ind2); private: CQTabWidgetTabBar* tabBar_ { nullptr }; bool moveButtons_ { false }; QWidget* moveTabWidget_ { nullptr }; }; //------ class CQTabWidgetTabBar : public QTabBar { Q_OBJECT public: CQTabWidgetTabBar(CQTabWidget *tabWidget); void stopEdit(); protected: void mouseDoubleClickEvent(QMouseEvent *event) override; #ifndef CQTAB_WIDGET_MOVABLE void mousePressEvent(QMouseEvent *event) override; void mouseMoveEvent (QMouseEvent *event) override; void dragEnterEvent(QDragEnterEvent *event) override; void dropEvent (QDropEvent *event) override; #endif void paintEvent(QPaintEvent *event) override; void contextMenuEvent(QContextMenuEvent *e) override; signals: void tabChanged(int ind); void tabMoveRequested(int fromIndex, int toIndex); private slots: void tabEditFinished(const QString &text); private: CQTabWidget* tabWidget_ { nullptr }; CQFloatEdit *edit_ { nullptr }; int ind_ { -1 }; QPoint pressPos_; }; #endif
// // Created by Sanjay Madan on 1/26/17. // Copyright © 2017 mowglii.com. All rights reserved. // // Make using Visual Format Language (VFL) nicer. #import <Cocoa/Cocoa.h> @interface MoVFLHelper : NSObject - (instancetype)initWithSuperview:(NSView *)superview metrics:(NSDictionary<NSString *, NSNumber *> *)metrics views:(NSDictionary<NSString *, id> *)views; // Create constraints with VFL format. - (void):(NSString *)format; // Create constraints with VFL format and options. - (void):(NSString *)format :(NSLayoutFormatOptions)options; @end
// Generates bulk traffic with no external congestion control loop. Similar to // attaching a lot of UDP generators to a FlowDriver, but adds all packets to a // single pipe. #ifndef NCODE_HTSIM_BULK_GEN_H #define NCODE_HTSIM_BULK_GEN_H #include <chrono> #include <cstdint> #include <iostream> #include <memory> #include <random> #include <thread> #include <vector> #include "../common.h" #include "../event_queue.h" #include "../ptr_queue.h" #include "../net/net_common.h" #include "packet.h" namespace nc { namespace htsim { // A source of packets that the generator uses. The packets do not need to come // from the same five tuple. class BulkPacketSource { public: virtual ~BulkPacketSource() {} // Returns the next packet. The packet will be sent according to the time_sent // field. This assumes that the time_sent field of packets is increasing. virtual PacketPtr NextPacket() = 0; }; // Common things for all BulkPacket generators. class BulkPacketGeneratorBase { public: BulkPacketGeneratorBase( std::vector<std::unique_ptr<BulkPacketSource>> sources, htsim::PacketHandler* out); void set_default_tag(PacketTag tag) { default_tag_ = tag; } // Sets a new output handler. void set_out(htsim::PacketHandler* out) { CHECK(out != nullptr); out_ = out; } protected: struct Event { Event(PacketPtr pkt, BulkPacketSource* source) : pkt(std::move(pkt)), source(source) {} PacketPtr pkt; BulkPacketSource* source; }; struct Comparator { bool operator()(const Event& lhs, const Event& rhs) { return lhs.pkt->time_sent() > rhs.pkt->time_sent(); } }; // Adds initial events for each source. void AddInitialEvents(); // Adds a new event to queue_ from a given source. void AddEventFromSource(BulkPacketSource* source); // Fetches the next packet from the queue. PacketPtr NextPacket(); // Handler to output packets to. htsim::PacketHandler* out_; // Sources. std::vector<std::unique_ptr<BulkPacketSource>> sources_; // The queue that contains events. VectorPriorityQueue<Event, Comparator> queue_; // All packets will be tagged with this tag. PacketTag default_tag_; }; class BulkPacketGenerator : public BulkPacketGeneratorBase, public EventConsumer { public: // A number of packets are cached in a background thread, while the current // batch is being processed. static constexpr size_t kBatchSize = 10000; BulkPacketGenerator(const std::string& id, std::vector<std::unique_ptr<BulkPacketSource>> sources, htsim::PacketHandler* out, EventQueue* event_queue); ~BulkPacketGenerator(); void HandleEvent() override; void StopQueueWhenDone() { stop_queue_when_done_ = true; } private: using Batch = std::vector<PacketPtr>; void GetNewBatchIfNeeded(); // Adds initial events for each source. void Init(); // Populates batches. Will block until no sources produce packets. Called by // batch_populator_. void PopulateBatches(); // Adds the next packet to a batch. bool Next(Batch* out); // Passes batches between the thread that generates them and the one that // consumes them. PtrQueue<Batch, 1> ptr_queue_; // The current batch. Batch current_batch_; size_t current_batch_index_; // Populates batches. std::thread batch_populator_; bool stop_queue_when_done_; }; class SingleThreadBulkPacketGenerator : public BulkPacketGeneratorBase, public EventConsumer { public: SingleThreadBulkPacketGenerator( const std::string& id, std::vector<std::unique_ptr<BulkPacketSource>> sources, htsim::PacketHandler* out, EventQueue* event_queue); void HandleEvent() override; private: void EnqueueNextPacket(); PacketPtr next_pkt_; }; // Generates a stream of UDP packets that have exponentially distributed gaps of // time between them. class ExpPacketSource : public htsim::BulkPacketSource { public: ExpPacketSource(const net::FiveTuple& five_tuple, std::chrono::nanoseconds mean_time_between_packets, size_t packet_size_bytes, size_t seed, EventQueue* event_queue); htsim::PacketPtr NextPacket() override; private: net::FiveTuple five_tuple_; size_t pkt_size_; std::mt19937 generator_; std::exponential_distribution<double> distribution_; // Used to convert to/from time. EventQueue* event_queue_; EventQueueTime time_; }; // Generates a constant stream of UDP packets. class ConstantPacketSource : public htsim::BulkPacketSource { public: ConstantPacketSource(const net::FiveTuple& five_tuple, std::chrono::nanoseconds mean_time_between_packets, size_t packet_size_bytes, EventQueue* event_queue); PacketPtr NextPacket() override; private: net::FiveTuple five_tuple_; size_t pkt_size_; EventQueueTime gap_; EventQueueTime time_; }; // A spike in load -- identified by its start time, duration and the rate it // will achieve for the duration. struct SpikeInTrafficLevel { std::chrono::milliseconds at; std::chrono::milliseconds duration; uint64_t rate_bps; }; class SpikyPacketSource : public htsim::BulkPacketSource { public: SpikyPacketSource(const net::FiveTuple& five_tuple, const std::vector<SpikeInTrafficLevel>& spikes, size_t packet_size_bytes, EventQueue* event_queue); PacketPtr NextPacket() override; private: net::FiveTuple five_tuple_; size_t pkt_size_; // A list of spikes to be generated. std::vector<SpikeInTrafficLevel> spikes_; // Index into spikes_. size_t current_spike_; size_t packets_generated_from_current_spike_; EventQueue* event_queue_; }; } // namespace htsim } // namespace ncode #endif
#ifndef __VECTOR_H__ #define __VECTOR_H__ #include"Serializer.h" #include<cmath> #include<memory> class Vector2f; typedef shared_ptr<Vector2f> Vector2fPtr; typedef weak_ptr<Vector2f> WeakVector2fPtr; class Vector2f { public: Vector2f() : x(0), y(0) {} Vector2f(Vector2fPtr copy) { x = copy->x; y = copy->y; } Vector2f(float x, float y) { this->x = x; this->y = y; } Vector2f(const rapidjson::Value& root) { x = root["x"].GetDouble(); y = root["y"].GetDouble(); } void set(const Vector2f& vector) { x = vector.x; y = vector.y; } void set(float x, float y) { this->x = x; this->y = y; } Vector2f operator*(float scalar) const { return Vector2f(x * scalar, y * scalar); } Vector2f operator+(const Vector2f& other) const { return Vector2f(x + other.x, y + other.y); } Vector2f operator-(const Vector2f& other) const { return Vector2f(x - other.x, y - other.y); } Vector2f& operator*=(float scalar) { x *= scalar; y *= scalar; return *this; } Vector2f& operator+=(const Vector2f& other) { x += other.x; y += other.y; return *this; } Vector2f& operator-=(const Vector2f& other) { x -= other.x; y -= other.y; return *this; } Vector2f dot(const Vector2f& other) const { return Vector2f(x * other.x, y * other.y); } float magnitude() { return std::sqrt((x * x) + (y * y)); } void normalize() { float mag = magnitude(); if (mag == 0) { return; } x /= mag; y /= mag; } void truncate(float max) { if (this->magnitude() < max) { return; } this->normalize(); this->x *= max; this->y *= max; } float x, y; void serialize(Serializer& serializer) const { serializer.writer.StartObject(); serializer.writer.String("x"); serializer.writer.Double(x); serializer.writer.String("y"); serializer.writer.Double(y); serializer.writer.EndObject(); } }; static const Vector2fPtr ZERO_VECTOR{ GCC_NEW Vector2f(0, 0) }; #endif // !__VECTOR_H__
// // <%prefix%><%module%>Controller.h // <%project%> // // Created by ANODA on 6/2/15. // Copyright (c) 2015 ANODA. All rights reserved. // #import "ANTableController.h" @class <%prefix%><%module%>DataSource; @class <%prefix%><%module%>CellViewModel; @protocol <%prefix%><%module%>ControllerDelegate <NSObject> - (void)itemSelectedWithModel:(<%prefix%><%module%>CellViewModel *)model; @end @interface <%prefix%><%module%>Controller : ANTableController @property (nonatomic, weak) id<<%prefix%><%module%>ControllerDelegate> delegate; - (void)updateDataSource:(<%prefix%><%module%>DataSource*)dataSource; @end
#ifndef COLORSPACE_H #define COLORSPACE_H #pragma warning(disable:4731) typedef void (*color_convert_func)( \ unsigned char *py, unsigned char *pu, unsigned char *pv, \ unsigned char *dst,\ unsigned long pitch, \ int width, \ int height); inline void yuv2yv12( unsigned char *py, unsigned char *pu, unsigned char *pv, unsigned char *dst, unsigned long pitch, int width, int height) { register unsigned char *tmpdst; register unsigned char *y, *u, *v; register int i; register int halfh,halfw,halfp; y = py; u = pu; v = pv; halfw = (width>>1); halfh = (height>>1); halfp = (pitch>>1); tmpdst = dst; for (i=0;i<height;++i) { memcpy(tmpdst, y, width); y+=width; tmpdst+=pitch; } tmpdst = dst + height*pitch; for(i=0;i<halfh;++i) { memcpy(tmpdst,v,halfw); v+=halfw; tmpdst+=halfp; } tmpdst = dst + height*pitch*5/4; for (i=0;i<halfh;++i) { memcpy(tmpdst,u,halfw); u+=halfw; tmpdst+=halfp; } } inline void yuv2uyvy16_mmx( unsigned char *py, // [esp+4+16] unsigned char *pu, // [esp+8+16] unsigned char *pv, // [esp+12+16] unsigned char *dst, // [esp+16+16] unsigned long pitch, // [esp+20+16] int w, // [esp+24+16] int h) // [esp+28+16] { int width = w/2; __asm { push ebp push edi push esi push ebx mov edx,[width]; ;load width (mult of 8) mov ebx,[pu] ;load source U ptr mov ecx,[pv] ;load source V ptr mov eax,[py] ;load source Y ptr mov edi,[dst] ;load destination ptr mov esi,[pitch] ;load destination pitch mov ebp,[h] ;load height lea ebx,[ebx+edx] ;bias pointers lea ecx,[ecx+edx] ;(we count from -n to 0) lea eax,[eax+edx*2] lea edi,[edi+edx*4] neg edx mov [esp+24+16],edx xyloop: movq mm0,[ebx+edx] ;U0-U7 movq mm7,[ecx+edx] ;V0-V7 movq mm2,mm0 ;U0-U7 movq mm4,[eax+edx*2] punpcklbw mm0,mm7 ;[V3][U3][V2][U2][V1][U1][V0][U0] movq mm5,[eax+edx*2+8] punpckhbw mm2,mm7 ;[V7][U7][V6][U6][V5][U5][V4][U4] movq mm1,mm0 punpcklbw mm0,mm4 ;[Y3][V1][Y2][U1][Y1][V0][Y0][U0] punpckhbw mm1,mm4 ;[Y7][V3][Y6][U3][Y5][V2][Y4][U2] movq mm3,mm2 movq [edi+edx*4+ 0],mm0 punpcklbw mm2,mm5 ;[YB][V5][YA][U5][Y9][V4][Y8][U4] movq [edi+edx*4+ 8],mm1 punpckhbw mm3,mm5 ;[YF][V7][YE][U7][YD][V6][YC][U6] movq [edi+edx*4+16],mm2 movq [edi+edx*4+24],mm3 add edx,8 jnc xyloop mov edx,[esp+24+16] ;reload width counter test ebp,1 ;update U/V row every other row only jz oddline sub ebx,edx ;advance U pointer sub ecx,edx ;advance V pointer oddline: sub eax,edx ;advance Y pointer sub eax,edx ;advance Y pointer add edi,esi ;advance dest ptr dec ebp jne xyloop pop ebx pop esi pop edi pop ebp emms } } inline void yuv2yuyv16_mmx( unsigned char *py, // [esp+4+16] unsigned char *pu, // [esp+8+16] unsigned char *pv, // [esp+12+16] unsigned char *dst, // [esp+16+16] unsigned long pitch, // [esp+20+16] int w, // [esp+24+16] int h) // [esp+28+16] { int width = w/2; __asm { push ebp push edi push esi push ebx mov edx,[width]; ;load width (mult of 8) mov ebx,[pu] ;load source U ptr mov ecx,[pv] ;load source V ptr mov eax,[py] ;load source Y ptr mov edi,[dst] ;load destination ptr mov esi,[pitch] ;load destination pitch mov ebp,[h] ;load height lea ebx,[ebx+edx] ;bias pointers lea ecx,[ecx+edx] ;(we count from -n to 0) lea eax,[eax+edx*2] lea edi,[edi+edx*4] neg edx mov [esp+24+16],edx xyloop: movq mm0,[ebx+edx] ;U0-U7 movq mm7,[ecx+edx] ;V0-V7 movq mm1,mm0 ;U0-U7 movq mm2,[eax+edx*2] ;Y0-Y7 punpcklbw mm0,mm7 ;[V3][U3][V2][U2][V1][U1][V0][U0] movq mm4,[eax+edx*2+8] ;Y8-YF punpckhbw mm1,mm7 ;[V7][U7][V6][U6][V5][U5][V4][U4] movq mm3,mm2 punpcklbw mm2,mm0 ;[V1][Y3][U1][Y2][V0][Y1][U0][Y0] movq mm5,mm4 punpckhbw mm3,mm0 ;[V3][Y7][U3][Y6][V2][Y5][U2][Y4] movq [edi+edx*4+ 0],mm2 punpcklbw mm4,mm1 ;[V5][YB][U5][YA][V4][Y9][U4][Y8] movq [edi+edx*4+ 8],mm3 punpckhbw mm5,mm1 ;[V7][YF][U7][YE][V6][YD][U6][YC] movq [edi+edx*4+16],mm4 movq [edi+edx*4+24],mm5 add edx,8 jnc xyloop mov edx,[esp+24+16] ;reload width counter test ebp,1 ;update U/V row every other row only jz oddline sub ebx,edx ;advance U pointer sub ecx,edx ;advance V pointer oddline: sub eax,edx ;advance Y pointer sub eax,edx ;advance Y pointer add edi,esi ;advance dest ptr dec ebp jne xyloop pop ebx pop esi pop edi pop ebp emms } } #endif // COLORSPACE_H
/// /// \file Event.h /// /// \author Michel Steuwer <michel.steuwer@ed.ac.uk> /// #ifndef EVENT_H_ #define EVENT_H_ #include <initializer_list> #include <vector> #define __CL_ENABLE_EXCEPTIONS #include <CL/cl.hpp> #undef __CL_ENABLE_EXCEPTIONS namespace executor { class Event { public: Event(); Event(const std::vector<cl::Event>& events); Event(std::initializer_list<cl::Event> events); //Event(const Event& rhs) = default; Event(Event&& rhs); //Event& operator=(const Event& rhs) = default; Event& operator=(Event&& rhs); //~Event() = default; void insert(const cl::Event& event); void wait(); private: std::vector<cl::Event> _events; }; } // namespace executor #endif // EVENT_H_
#ifndef INCLUDED_com_gamekit_text_LatexParser #define INCLUDED_com_gamekit_text_LatexParser #ifndef HXCPP_H #include <hxcpp.h> #endif HX_DECLARE_CLASS0(EReg) HX_DECLARE_CLASS0(IMap) HX_DECLARE_CLASS3(com,gamekit,text,LatexParser) HX_DECLARE_CLASS2(haxe,ds,StringMap) namespace com{ namespace gamekit{ namespace text{ class HXCPP_CLASS_ATTRIBUTES LatexParser_obj : public hx::Object{ public: typedef hx::Object super; typedef LatexParser_obj OBJ_; LatexParser_obj(); Void __construct(); public: static hx::ObjectPtr< LatexParser_obj > __new(); static Dynamic __CreateEmpty(); static Dynamic __Create(hx::DynamicArray inArgs); ~LatexParser_obj(); HX_DO_RTTI; static void __boot(); static void __register(); void __Mark(HX_MARK_PARAMS); void __Visit(HX_VISIT_PARAMS); ::String __ToString() const { return HX_CSTRING("LatexParser"); } static int baseFontSize; static ::haxe::ds::StringMap standardColors; static ::String toHtml( ::String latex); static Dynamic toHtml_dyn(); static ::String _replaceSize( ::EReg reg); static Dynamic _replaceSize_dyn(); static ::String _replaceColor( ::EReg reg); static Dynamic _replaceColor_dyn(); static ::String _replaceSub( ::EReg reg); static Dynamic _replaceSub_dyn(); static ::String _replaceSup( ::EReg reg); static Dynamic _replaceSup_dyn(); }; } // end namespace com } // end namespace gamekit } // end namespace text #endif /* INCLUDED_com_gamekit_text_LatexParser */
/* oid.c */ #include <stdlib.h> #include <stdint.h> #include "crypto/oid.h" #include "common/error.h" struct OID_DATA { unsigned int type; const uint8_t *data; size_t len; }; static const uint8_t oid_sha1[] = { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14 }; static const uint8_t oid_sha256[] = { 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20, }; static const uint8_t oid_sha512[] = { 0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, 0x00, 0x04, 0x40 }; static const struct OID_DATA hash_oids[] = { { SSH_HASH_SHA1, oid_sha1, sizeof(oid_sha1) }, { SSH_HASH_SHA2_256, oid_sha256, sizeof(oid_sha256) }, { SSH_HASH_SHA2_512, oid_sha512, sizeof(oid_sha512) }, }; int crypto_oid_get_for_hash(enum SSH_HASH_TYPE hash_type, struct SSH_STRING *out) { int i; for (i = 0; i < sizeof(hash_oids)/sizeof(hash_oids[0]); i++) { if (hash_oids[i].type == hash_type) { *out = ssh_str_new((uint8_t *) hash_oids[i].data, hash_oids[i].len); return 0; } } ssh_set_error("unknown hash type for OID"); return -1; }
// Copyright (c) 2012-2014 The Phtevencoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef PHTEVENCOIN_BLOOM_H #define PHTEVENCOIN_BLOOM_H #include "serialize.h" #include <vector> class COutPoint; class CTransaction; class uint256; //! 20,000 items with fp rate < 0.1% or 10,000 items and <0.0001% static const unsigned int MAX_BLOOM_FILTER_SIZE = 36000; // bytes static const unsigned int MAX_HASH_FUNCS = 50; /** * First two bits of nFlags control how much IsRelevantAndUpdate actually updates * The remaining bits are reserved */ enum bloomflags { BLOOM_UPDATE_NONE = 0, BLOOM_UPDATE_ALL = 1, // Only adds outpoints to the filter if the output is a pay-to-pubkey/pay-to-multisig script BLOOM_UPDATE_P2PUBKEY_ONLY = 2, BLOOM_UPDATE_MASK = 3, }; /** * BloomFilter is a probabilistic filter which SPV clients provide * so that we can filter the transactions we send them. * * This allows for significantly more efficient transaction and block downloads. * * Because bloom filters are probabilistic, a SPV node can increase the false- * positive rate, making us send it transactions which aren't actually its, * allowing clients to trade more bandwidth for more privacy by obfuscating which * keys are controlled by them. */ class CBloomFilter { private: std::vector<unsigned char> vData; bool isFull; bool isEmpty; unsigned int nHashFuncs; unsigned int nTweak; unsigned char nFlags; unsigned int Hash(unsigned int nHashNum, const std::vector<unsigned char>& vDataToHash) const; // Private constructor for CRollingBloomFilter, no restrictions on size CBloomFilter(unsigned int nElements, double nFPRate, unsigned int nTweak); friend class CRollingBloomFilter; public: /** * Creates a new bloom filter which will provide the given fp rate when filled with the given number of elements * Note that if the given parameters will result in a filter outside the bounds of the protocol limits, * the filter created will be as close to the given parameters as possible within the protocol limits. * This will apply if nFPRate is very low or nElements is unreasonably high. * nTweak is a constant which is added to the seed value passed to the hash function * It should generally always be a random value (and is largely only exposed for unit testing) * nFlags should be one of the BLOOM_UPDATE_* enums (not _MASK) */ CBloomFilter(unsigned int nElements, double nFPRate, unsigned int nTweak, unsigned char nFlagsIn); CBloomFilter() : isFull(true), isEmpty(false), nHashFuncs(0), nTweak(0), nFlags(0) {} ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { READWRITE(vData); READWRITE(nHashFuncs); READWRITE(nTweak); READWRITE(nFlags); } void insert(const std::vector<unsigned char>& vKey); void insert(const COutPoint& outpoint); void insert(const uint256& hash); bool contains(const std::vector<unsigned char>& vKey) const; bool contains(const COutPoint& outpoint) const; bool contains(const uint256& hash) const; void clear(); void reset(unsigned int nNewTweak); //! True if the size is <= MAX_BLOOM_FILTER_SIZE and the number of hash functions is <= MAX_HASH_FUNCS //! (catch a filter which was just deserialized which was too big) bool IsWithinSizeConstraints() const; //! Also adds any outputs which match the filter to the filter (to match their spending txes) bool IsRelevantAndUpdate(const CTransaction& tx); //! Checks for empty and full filters to avoid wasting cpu void UpdateEmptyFull(); }; /** * RollingBloomFilter is a probabilistic "keep track of most recently inserted" set. * Construct it with the number of items to keep track of, and a false-positive * rate. Unlike CBloomFilter, by default nTweak is set to a cryptographically * secure random value for you. Similarly rather than clear() the method * reset() is provided, which also changes nTweak to decrease the impact of * false-positives. * * contains(item) will always return true if item was one of the last N things * insert()'ed ... but may also return true for items that were not inserted. */ class CRollingBloomFilter { public: // A random bloom filter calls GetRand() at creation time. // Don't create global CRollingBloomFilter objects, as they may be // constructed before the randomizer is properly initialized. CRollingBloomFilter(unsigned int nElements, double nFPRate); void insert(const std::vector<unsigned char>& vKey); void insert(const uint256& hash); bool contains(const std::vector<unsigned char>& vKey) const; bool contains(const uint256& hash) const; void reset(); private: unsigned int nBloomSize; unsigned int nInsertions; CBloomFilter b1, b2; }; #endif // PHTEVENCOIN_BLOOM_H
/* Copyright (c) 2018, Johnathan Corkery. (jcorkery@umich.edu) All rights reserved. This file is part of the Dynacoe project (https://github.com/jcorks/Dynacoe) Dynacoe was released under the MIT License, as detailed below. 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. */ #if ( defined DC_BACKENDS_SHADERGL_X11 || defined DC_BACKENDS_SHADERGL_WIN32 ) #ifndef H_DC_BACKENDS_GL_RENDERER2D_INCLUDED #define H_DC_BACKENDS_GL_RENDERER2D_INCLUDED #include <Dynacoe/Backends/Renderer/ShaderGL_Multi.h> class Renderer2DData; namespace Dynacoe { class TextureManager; class Renderer2D { public: Renderer2D(TextureManager * textureSource); // Adds a new symbolic 2D object and returns its ID. the object may be referred to // within vertices as the object parameter. uint32_t Add2DObject(); // Forgets an object void Remove2DObject(uint32_t); // Sets the parameters to use for the object void Set2DObjectParameters(uint32_t object, Renderer::Render2DObjectParameters); // Adds a new vertex and returns its index uint32_t Add2DVertex(); // Removes the object. Uzing its object ID in rendering is probably not a great idea void Remove2DVertex(uint32_t object); // Sets the data for the vertex void Set2DVertex(uint32_t vertex, Renderer::Vertex2D); // Gets the data stored for the particular vertex. Renderer::Vertex2D Get2DVertex(uint32_t vertex); // Queues additional vertices to be drawn sequentially void Queue2DVertices( const uint32_t * indices, uint32_t count ); // renders all currently queued vertices. This clears the queue upon completion. uint32_t Render2DVertices(GLenum drawMode, const Renderer::Render2DStaticParameters &); // Clears all requests queued before the last RenderDynamicQueue void Clear2DQueue(); private: Renderer2DData * data; }; } #endif #endif
/** * Libstatsd * * @author Axel Etcheverry (http://twitter.com/euskadi31) * @copyright Copyright (c) 2013 Axel Etcheverry * @license http://creativecommons.org/licenses/MIT/deed.fr MIT */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <netdb.h> #include <time.h> #include <unistd.h> #include <sys/types.h> #include <netinet/in.h> #include "statsd.h" /* will change the original string */ static void cleanup(char *stat) { char *p; for (p = stat; *p; p++) { if (*p == ':' || *p == '|' || *p == '@') { *p = '_'; } } } static int should_send(float sample_rate) { if (sample_rate < 1.0) { float p = ((float)random() / RAND_MAX); return sample_rate > p; } else { return 1; } } static int send_stat( statsd_t *link, char *stat, size_t value, const char *type, float sample_rate ) { char message[MAX_MSG_LEN]; if (!should_send(sample_rate)) { return 0; } statsd_prepare( link, stat, value, type, sample_rate, message, MAX_MSG_LEN, 0 ); return statsd_send(link, message); } statsd_t *statsd_init_with_namespace( const char *host, int port, const char *ns_ ) { size_t len = strlen(ns_); statsd_t *temp = statsd_init(host, port); if ((temp->ns = malloc(len + 2)) == NULL) { perror("malloc"); return NULL; } strcpy(temp->ns, ns_); temp->ns[len++] = '.'; temp->ns[len] = 0; return temp; } statsd_t *statsd_init(const char *host, int port) { statsd_t *temp = malloc(sizeof(statsd_t)); if ((temp->sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) { perror("socket"); return NULL; } memset(&temp->server, 0, sizeof(temp->server)); temp->server.sin_family = AF_INET; temp->server.sin_port = htons(port); struct addrinfo *result = NULL, hints; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_DGRAM; int error; if ((error = getaddrinfo(host, NULL, &hints, &result))) { fprintf(stderr, "%s\n", gai_strerror(error)); return NULL; } memcpy( &(temp->server).sin_addr, &((struct sockaddr_in*)result->ai_addr)->sin_addr, sizeof(struct in_addr) ); freeaddrinfo(result); if (inet_aton(host, &(temp->server).sin_addr) == 0) { perror("inet_aton"); return NULL; } srandom(time(NULL)); return temp; } void statsd_finalize(statsd_t *link) { // close socket if (link->sock != -1) { close(link->sock); link->sock = -1; } // freeing ns if (link->ns) { free(link->ns); link->ns = NULL; } // free sockaddr_in free(&link->server); // free whole link //free(&link); } int statsd_send(statsd_t *link, const char *message) { int slen = sizeof(link->server); if (sendto( link->sock, message, strlen(message), 0, (struct sockaddr *) &link->server, slen ) == -1) { perror("sendto"); return -1; } return 0; } void statsd_prepare( statsd_t *link, char *stat, size_t value, const char *type, float sample_rate, char *message, size_t buflen, int lf ) { cleanup(stat); if (sample_rate == 1.0) { snprintf( message, buflen, "%s%s:%zd|%s%s", link->ns ? link->ns : "", stat, value, type, lf ? "\n" : "" ); } else { snprintf( message, buflen, "%s%s:%zd|%s|@%.2f%s", link->ns ? link->ns : "", stat, value, type, sample_rate, lf ? "\n" : "" ); } } int statsd_count(statsd_t *link, char *stat, size_t value, float sample_rate) { return send_stat(link, stat, value, "c", sample_rate); } int statsd_dec(statsd_t *link, char *stat, float sample_rate) { return statsd_count(link, stat, -1, sample_rate); } int statsd_inc(statsd_t *link, char *stat, float sample_rate) { return statsd_count(link, stat, 1, sample_rate); } int statsd_gauge(statsd_t *link, char *stat, size_t value) { return send_stat(link, stat, value, "g", 1.0); } int statsd_timing(statsd_t *link, char *stat, size_t ms) { return send_stat(link, stat, ms, "ms", 1.0); }
/* * Generated by class-dump 3.3.4 (64 bit). * * class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2011 by Steve Nygard. */ #import "NSObject.h" @interface DVTAnnotation : NSObject { double _precedence; id _representedObject; BOOL _visible; } @property(retain) id representedObject; // @synthesize representedObject=_representedObject; @property(getter=isVisible) BOOL visible; // @synthesize visible=_visible; @property double precedence; // @synthesize precedence=_precedence; - (void).cxx_destruct; @property(readonly) BOOL hideCarets; - (id)annotationDisplayDescription; - (id)annotationDisplayName; - (long long)comparePrecedence:(id)arg1; - (id)init; @end
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_snprintf_08.c Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_CWE806.label.xml Template File: sources-sink-08.tmpl.c */ /* * @description * CWE: 122 Heap Based Buffer Overflow * BadSource: Initialize data as a large string * GoodSource: Initialize data as a small string * Sink: snprintf * BadSink : Copy data to string using snprintf * Flow Variant: 08 Control flow: if(staticReturnsTrue()) and if(staticReturnsFalse()) * * */ #include "std_testcase.h" #include <wchar.h> #ifdef _WIN32 #define SNPRINTF _snwprintf #else #define SNPRINTF snprintf #endif /* The two function below always return the same value, so a tool * should be able to identify that calls to the functions will always * return a fixed value. */ static int staticReturnsTrue() { return 1; } static int staticReturnsFalse() { return 0; } #ifndef OMITBAD void CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_snprintf_08_bad() { wchar_t * data; data = (wchar_t *)malloc(100*sizeof(wchar_t)); if(staticReturnsTrue()) { /* FLAW: Initialize data as a large buffer that is larger than the small buffer used in the sink */ wmemset(data, L'A', 100-1); /* fill with L'A's */ data[100-1] = L'\0'; /* null terminate */ } { wchar_t dest[50] = L""; /* POTENTIAL FLAW: Possible buffer overflow if data is larger than dest */ SNPRINTF(dest, wcslen(data), L"%s", data); printWLine(data); free(data); } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B1() - use goodsource and badsink by changing the staticReturnsTrue() to staticReturnsFalse() */ static void goodG2B1() { wchar_t * data; data = (wchar_t *)malloc(100*sizeof(wchar_t)); if(staticReturnsFalse()) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { /* FIX: Initialize data as a small buffer that as small or smaller than the small buffer used in the sink */ wmemset(data, L'A', 50-1); /* fill with L'A's */ data[50-1] = L'\0'; /* null terminate */ } { wchar_t dest[50] = L""; /* POTENTIAL FLAW: Possible buffer overflow if data is larger than dest */ SNPRINTF(dest, wcslen(data), L"%s", data); printWLine(data); free(data); } } /* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */ static void goodG2B2() { wchar_t * data; data = (wchar_t *)malloc(100*sizeof(wchar_t)); if(staticReturnsTrue()) { /* FIX: Initialize data as a small buffer that as small or smaller than the small buffer used in the sink */ wmemset(data, L'A', 50-1); /* fill with L'A's */ data[50-1] = L'\0'; /* null terminate */ } { wchar_t dest[50] = L""; /* POTENTIAL FLAW: Possible buffer overflow if data is larger than dest */ SNPRINTF(dest, wcslen(data), L"%s", data); printWLine(data); free(data); } } void CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_snprintf_08_good() { goodG2B1(); goodG2B2(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on * its own for testing or for building a binary to use in testing binary * analysis tools. It is not used when compiling all the testcases as one * application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_snprintf_08_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE122_Heap_Based_Buffer_Overflow__c_CWE806_wchar_t_snprintf_08_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
// // PacketUdp.h // peacemaker // // The MIT License (MIT) // // Copyright (c) 2014 Tomas Korcak <korczis@gmail.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. #ifndef __peacemaker__PacketUdp__ #define __peacemaker__PacketUdp__ #include "Packet.h" #include <arpa/inet.h> namespace pm { class PacketUdp : public Packet { public: inline unsigned short Sport() const { return ntohs(mSport); } inline unsigned short Dport() const { return ntohs(mDport); } inline unsigned short Length() const { return mLength; } inline unsigned short Checksum() const { return mChecksum; } inline unsigned char* GetData() { return ((unsigned char*)this) + sizeof(*this); } inline const unsigned char* GetData() const { return ((const unsigned char*)this) + sizeof(*this); } template<typename T> inline T* GetData() { return (T*)GetData(); } template<typename T> inline const T* GetData() const { return (const T*)GetData(); } private: unsigned short mSport; // Source port unsigned short mDport; // Destination port unsigned short mLength; // Datagram length unsigned short mChecksum; // Checksum }; // class PacketUdp }; /* namespace pm */ #endif /* defined(__peacemaker__PacketUdp__) */
// Copyright (c) 2011-2015 The Bitcoin Core developers // Copyright (c) 2014-2019 The Dash Core developers // Copyright (c) 2018-2020 The Ion Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_QT_CLIENTMODEL_H #define BITCOIN_QT_CLIENTMODEL_H #include "evo/deterministicmns.h" #include "sync.h" #include <QObject> #include <QDateTime> #include <atomic> class BanTableModel; class OptionsModel; class PeerTableModel; class CBlockIndex; QT_BEGIN_NAMESPACE class QTimer; QT_END_NAMESPACE enum BlockSource { BLOCK_SOURCE_NONE, BLOCK_SOURCE_REINDEX, BLOCK_SOURCE_DISK, BLOCK_SOURCE_NETWORK }; enum NumConnections { CONNECTIONS_NONE = 0, CONNECTIONS_IN = (1U << 0), CONNECTIONS_OUT = (1U << 1), CONNECTIONS_ALL = (CONNECTIONS_IN | CONNECTIONS_OUT), }; /** Model for Ion network client. */ class ClientModel : public QObject { Q_OBJECT public: explicit ClientModel(OptionsModel *optionsModel, QObject *parent = 0); ~ClientModel(); OptionsModel *getOptionsModel(); PeerTableModel *getPeerTableModel(); BanTableModel *getBanTableModel(); //! Return number of connections, default is in- and outbound (total) int getNumConnections(unsigned int flags = CONNECTIONS_ALL) const; int getNumBlocks() const; int getHeaderTipHeight() const; int64_t getHeaderTipTime() const; //! Return number of transactions in the mempool long getMempoolSize() const; //! Return the dynamic memory usage of the mempool size_t getMempoolDynamicUsage() const; //! Return number of ISLOCKs size_t getInstantSentLockCount() const; void setMasternodeList(const CDeterministicMNList& mnList); CDeterministicMNList getMasternodeList() const; void refreshMasternodeList(); quint64 getTotalBytesRecv() const; quint64 getTotalBytesSent() const; double getVerificationProgress(const CBlockIndex *tip) const; QDateTime getLastBlockDate() const; //! Return true if core is doing initial block download bool inInitialBlockDownload() const; //! Returns enum BlockSource of the current importing/syncing state enum BlockSource getBlockSource() const; //! Return true if network activity in core is enabled bool getNetworkActive() const; //! Toggle network activity state in core void setNetworkActive(bool active); //! Return warnings to be displayed in status bar QString getStatusBarWarnings() const; QString formatFullVersion() const; QString formatSubVersion() const; bool isReleaseVersion() const; QString formatClientStartupTime() const; QString dataDir() const; // caches for the best header mutable std::atomic<int> cachedBestHeaderHeight; mutable std::atomic<int64_t> cachedBestHeaderTime; private: OptionsModel *optionsModel; PeerTableModel *peerTableModel; BanTableModel *banTableModel; QTimer *pollTimer; // The cache for mn list is not technically needed because CDeterministicMNManager // caches it internally for recent blocks but it's not enough to get consistent // representation of the list in UI during initial sync/reindex, so we cache it here too. mutable CCriticalSection cs_mnlinst; // protects mnListCached CDeterministicMNList mnListCached; void subscribeToCoreSignals(); void unsubscribeFromCoreSignals(); Q_SIGNALS: void numConnectionsChanged(int count); void masternodeListChanged() const; void numBlocksChanged(int count, const QDateTime& blockDate, double nVerificationProgress, bool header); void additionalDataSyncProgressChanged(double nSyncProgress); void mempoolSizeChanged(long count, size_t mempoolSizeInBytes); void islockCountChanged(size_t count); void networkActiveChanged(bool networkActive); void alertsChanged(const QString &warnings); void bytesChanged(quint64 totalBytesIn, quint64 totalBytesOut); //! Fired when a message should be reported to the user void message(const QString &title, const QString &message, unsigned int style); // Show progress dialog e.g. for verifychain void showProgress(const QString &title, int nProgress); public Q_SLOTS: void updateTimer(); void updateNumConnections(int numConnections); void updateNetworkActive(bool networkActive); void updateAlert(); void updateBanlist(); }; #endif // BITCOIN_QT_CLIENTMODEL_H
// // Generated by the J2ObjC translator. DO NOT EDIT! // source: ./queryparser/src/java/org/apache/lucene/queryparser/xml/builders/SpanNotBuilder.java // #include "J2ObjC_header.h" #pragma push_macro("INCLUDE_ALL_OrgApacheLuceneQueryparserXmlBuildersSpanNotBuilder") #ifdef RESTRICT_OrgApacheLuceneQueryparserXmlBuildersSpanNotBuilder #define INCLUDE_ALL_OrgApacheLuceneQueryparserXmlBuildersSpanNotBuilder 0 #else #define INCLUDE_ALL_OrgApacheLuceneQueryparserXmlBuildersSpanNotBuilder 1 #endif #undef RESTRICT_OrgApacheLuceneQueryparserXmlBuildersSpanNotBuilder #if __has_feature(nullability) #pragma clang diagnostic push #pragma GCC diagnostic ignored "-Wnullability" #pragma GCC diagnostic ignored "-Wnullability-completeness" #endif #if !defined (OrgApacheLuceneQueryparserXmlBuildersSpanNotBuilder_) && (INCLUDE_ALL_OrgApacheLuceneQueryparserXmlBuildersSpanNotBuilder || defined(INCLUDE_OrgApacheLuceneQueryparserXmlBuildersSpanNotBuilder)) #define OrgApacheLuceneQueryparserXmlBuildersSpanNotBuilder_ #define RESTRICT_OrgApacheLuceneQueryparserXmlBuildersSpanBuilderBase 1 #define INCLUDE_OrgApacheLuceneQueryparserXmlBuildersSpanBuilderBase 1 #include "org/apache/lucene/queryparser/xml/builders/SpanBuilderBase.h" @class OrgApacheLuceneSearchSpansSpanQuery; @protocol OrgApacheLuceneQueryparserXmlBuildersSpanQueryBuilder; @protocol OrgW3cDomElement; /*! @brief Builder for <code>SpanNotQuery</code> */ @interface OrgApacheLuceneQueryparserXmlBuildersSpanNotBuilder : OrgApacheLuceneQueryparserXmlBuildersSpanBuilderBase #pragma mark Public - (instancetype __nonnull)initWithOrgApacheLuceneQueryparserXmlBuildersSpanQueryBuilder:(id<OrgApacheLuceneQueryparserXmlBuildersSpanQueryBuilder>)factory; - (OrgApacheLuceneSearchSpansSpanQuery *)getSpanQueryWithOrgW3cDomElement:(id<OrgW3cDomElement>)e; // Disallowed inherited constructors, do not use. - (instancetype __nonnull)init NS_UNAVAILABLE; @end J2OBJC_EMPTY_STATIC_INIT(OrgApacheLuceneQueryparserXmlBuildersSpanNotBuilder) FOUNDATION_EXPORT void OrgApacheLuceneQueryparserXmlBuildersSpanNotBuilder_initWithOrgApacheLuceneQueryparserXmlBuildersSpanQueryBuilder_(OrgApacheLuceneQueryparserXmlBuildersSpanNotBuilder *self, id<OrgApacheLuceneQueryparserXmlBuildersSpanQueryBuilder> factory); FOUNDATION_EXPORT OrgApacheLuceneQueryparserXmlBuildersSpanNotBuilder *new_OrgApacheLuceneQueryparserXmlBuildersSpanNotBuilder_initWithOrgApacheLuceneQueryparserXmlBuildersSpanQueryBuilder_(id<OrgApacheLuceneQueryparserXmlBuildersSpanQueryBuilder> factory) NS_RETURNS_RETAINED; FOUNDATION_EXPORT OrgApacheLuceneQueryparserXmlBuildersSpanNotBuilder *create_OrgApacheLuceneQueryparserXmlBuildersSpanNotBuilder_initWithOrgApacheLuceneQueryparserXmlBuildersSpanQueryBuilder_(id<OrgApacheLuceneQueryparserXmlBuildersSpanQueryBuilder> factory); J2OBJC_TYPE_LITERAL_HEADER(OrgApacheLuceneQueryparserXmlBuildersSpanNotBuilder) #endif #if __has_feature(nullability) #pragma clang diagnostic pop #endif #pragma pop_macro("INCLUDE_ALL_OrgApacheLuceneQueryparserXmlBuildersSpanNotBuilder")
#include "C:\Factory\Common\all.h" #define RET_PREFIX "*RET=" static void Main2(void) { if(argIs("/F")) { cout(RET_PREFIX "%s\n", toFairFullPathFltr(makeFullPath(nextArg()))); // gomi return; } } int main(int argc, char **argv) { Main2(); termination(0); }
#ifndef _AVALANCHE_FACTORY_H_ #define _AVALANCHE_FACTORY_H_ #include <unordered_map> #include <memory> #include <algorithm> #include <cctype> namespace avalanche { template <typename T, typename... Args> class Factory { public: using MethodCreator = std::unique_ptr<T>(*)(Args... args); using MethodRegistry = std::unordered_map<std::string, MethodCreator>; private: MethodRegistry m_Methods; public: Factory() = default; Factory(const MethodRegistry& registry) { m_Methods = registry; } template <typename Method> void Register(const std::string& name) { auto creator = [](Args... args) -> std::unique_ptr<T> { return std::make_unique<Method>(args...); }; m_Methods.insert(std::make_pair(name, creator)); } bool Contains(const std::string& name) const { return m_Methods.find(name) != m_Methods.end(); } std::unique_ptr<T> Create(std::string name, Args... args) const { std::transform(name.begin(), name.end(), name.begin(), ::tolower); auto iter = m_Methods.find(name); if (iter == m_Methods.end()) return nullptr; return iter->second(args...); } }; } // ns avalanche #endif
// // SHKFormFieldCellText.h // ShareKit // // Created by Vilem Kurz on 30/05/2012. // 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 "SHKFormFieldCell_PrivateProperties.h" @interface SHKFormFieldCellText : SHKFormFieldCell <UITextFieldDelegate> @property (nonatomic, retain) UITextField *textField; @end
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE126_Buffer_Overread__malloc_wchar_t_memcpy_18.c Label Definition File: CWE126_Buffer_Overread__malloc.label.xml Template File: sources-sink-18.tmpl.c */ /* * @description * CWE: 126 Buffer Over-read * BadSource: Use a small buffer * GoodSource: Use a large buffer * Sink: memcpy * BadSink : Copy data to string using memcpy * Flow Variant: 18 Control flow: goto statements * * */ #include "std_testcase.h" #include <wchar.h> #ifndef OMITBAD void CWE126_Buffer_Overread__malloc_wchar_t_memcpy_18_bad() { wchar_t * data; data = NULL; goto source; source: /* FLAW: Use a small buffer */ data = (wchar_t *)malloc(50*sizeof(wchar_t)); wmemset(data, L'A', 50-1); /* fill with 'A's */ data[50-1] = L'\0'; /* null terminate */ { wchar_t dest[100]; wmemset(dest, L'C', 100-1); dest[100-1] = L'\0'; /* null terminate */ /* POTENTIAL FLAW: using memcpy with the length of the dest where data * could be smaller than dest causing buffer overread */ memcpy(dest, data, wcslen(dest)*sizeof(wchar_t)); dest[100-1] = L'\0'; printWLine(dest); free(data); } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B() - use goodsource and badsink by reversing the blocks on the goto statement */ static void goodG2B() { wchar_t * data; data = NULL; goto source; source: /* FIX: Use a large buffer */ data = (wchar_t *)malloc(100*sizeof(wchar_t)); wmemset(data, L'A', 100-1); /* fill with 'A's */ data[100-1] = L'\0'; /* null terminate */ { wchar_t dest[100]; wmemset(dest, L'C', 100-1); dest[100-1] = L'\0'; /* null terminate */ /* POTENTIAL FLAW: using memcpy with the length of the dest where data * could be smaller than dest causing buffer overread */ memcpy(dest, data, wcslen(dest)*sizeof(wchar_t)); dest[100-1] = L'\0'; printWLine(dest); free(data); } } void CWE126_Buffer_Overread__malloc_wchar_t_memcpy_18_good() { goodG2B(); } #endif /* OMITGOOD */ /* Below is the main(). It is only used when building this testcase on * its own for testing or for building a binary to use in testing binary * analysis tools. It is not used when compiling all the testcases as one * application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); CWE126_Buffer_Overread__malloc_wchar_t_memcpy_18_good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); CWE126_Buffer_Overread__malloc_wchar_t_memcpy_18_bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
#pragma once #include <string> #include <memory> #include <map> #include <folly/futures/Future.h> #include <folly/futures/helpers.h> #include "gen-cpp2/Relevanced.h" #include "declarations.h" namespace relevanced { namespace server { /** * `ThriftRelevanceServer` is not really responsible for relevanced's * core functionality. * * Its job is to proxy requests back to its injected `RelevanceServerIf` * instance, and then interpret the responses in a way that makes sense * for the defined Thrift protocol. * */ class ThriftRelevanceServer : public thrift_protocol::RelevancedSvIf { std::shared_ptr<RelevanceServerIf> server_; public: ThriftRelevanceServer(std::shared_ptr<RelevanceServerIf> server); void ping() override; folly::Future<std::unique_ptr<std::map<std::string, std::string>>> future_getServerMetadata() override; folly::Future<double> future_getDocumentSimilarity( std::unique_ptr<std::string> centroidId, std::unique_ptr<std::string> docId) override; folly::Future<std::unique_ptr<thrift_protocol::MultiSimilarityResponse>> future_multiGetTextSimilarity( std::unique_ptr<std::vector<std::string>> centroidIds, std::unique_ptr<std::string> text, thrift_protocol::Language) override; folly::Future<std::unique_ptr<thrift_protocol::MultiSimilarityResponse>> future_multiGetDocumentSimilarity( std::unique_ptr<std::vector<std::string>> centroidIds, std::unique_ptr<std::string> docId) override; folly::Future<double> future_getTextSimilarity( std::unique_ptr<std::string> centroidId, std::unique_ptr<std::string> text, thrift_protocol::Language) override; folly::Future<double> future_getCentroidSimilarity( std::unique_ptr<std::string> centroid1Id, std::unique_ptr<std::string> centroid2Id) override; folly::Future<std::unique_ptr<thrift_protocol::CreateDocumentResponse>> future_createDocument( std::unique_ptr<std::string> text, thrift_protocol::Language lang ) override; folly::Future<std::unique_ptr<thrift_protocol::CreateDocumentResponse>> future_createDocumentWithID( std::unique_ptr<std::string> id, std::unique_ptr<std::string> text, thrift_protocol::Language lang ) override; folly::Future<std::unique_ptr<thrift_protocol::DeleteDocumentResponse>> future_deleteDocument(std::unique_ptr<thrift_protocol::DeleteDocumentRequest> request) override; folly::Future<std::unique_ptr<thrift_protocol::MultiDeleteDocumentsResponse>> future_multiDeleteDocuments(std::unique_ptr<thrift_protocol::MultiDeleteDocumentsRequest> request) override; folly::Future<std::unique_ptr<thrift_protocol::CreateCentroidResponse>> future_createCentroid(std::unique_ptr<thrift_protocol::CreateCentroidRequest> centroidId) override; folly::Future<std::unique_ptr<thrift_protocol::MultiCreateCentroidsResponse>> future_multiCreateCentroids(std::unique_ptr<thrift_protocol::MultiCreateCentroidsRequest> request) override; folly::Future<std::unique_ptr<thrift_protocol::DeleteCentroidResponse>> future_deleteCentroid(std::unique_ptr<thrift_protocol::DeleteCentroidRequest> request) override; folly::Future<std::unique_ptr<thrift_protocol::MultiDeleteCentroidsResponse>> future_multiDeleteCentroids(std::unique_ptr<thrift_protocol::MultiDeleteCentroidsRequest> request) override; folly::Future<std::unique_ptr<thrift_protocol::ListCentroidDocumentsResponse>> future_listAllDocumentsForCentroid( std::unique_ptr<std::string> centroidId) override; folly::Future<std::unique_ptr<thrift_protocol::ListCentroidDocumentsResponse>> future_listCentroidDocumentRange(std::unique_ptr<std::string> centroidId, int64_t offset, int64_t count) override; folly::Future<std::unique_ptr<thrift_protocol::ListCentroidDocumentsResponse>> future_listCentroidDocumentRangeFromID(std::unique_ptr<std::string> centroidId, std::unique_ptr<std::string> docId, int64_t count) override; folly::Future<std::unique_ptr<thrift_protocol::AddDocumentsToCentroidResponse>> future_addDocumentsToCentroid( std::unique_ptr<thrift_protocol::AddDocumentsToCentroidRequest> request ) override; folly::Future<std::unique_ptr<thrift_protocol::RemoveDocumentsFromCentroidResponse>> future_removeDocumentsFromCentroid( std::unique_ptr<thrift_protocol::RemoveDocumentsFromCentroidRequest> request ) override; folly::Future<std::unique_ptr<thrift_protocol::JoinCentroidResponse>> future_joinCentroid( std::unique_ptr<thrift_protocol::JoinCentroidRequest> request ) override; folly::Future<std::unique_ptr<thrift_protocol::MultiJoinCentroidsResponse>> future_multiJoinCentroids( std::unique_ptr<thrift_protocol::MultiJoinCentroidsRequest> request ) override; folly::Future<std::unique_ptr<thrift_protocol::ListCentroidsResponse>> future_listAllCentroids() override; folly::Future<std::unique_ptr<thrift_protocol::ListCentroidsResponse>> future_listCentroidRange(int64_t offset, int64_t count) override; folly::Future<std::unique_ptr<thrift_protocol::ListCentroidsResponse>> future_listCentroidRangeFromID(std::unique_ptr<std::string> startId, int64_t count) override; folly::Future<std::unique_ptr<thrift_protocol::ListDocumentsResponse>> future_listAllDocuments() override; folly::Future<std::unique_ptr<thrift_protocol::ListDocumentsResponse>> future_listUnusedDocuments(int64_t count) override; folly::Future<std::unique_ptr<thrift_protocol::ListDocumentsResponse>> future_listDocumentRange(int64_t offset, int64_t count) override; folly::Future<std::unique_ptr<thrift_protocol::ListDocumentsResponse>> future_listDocumentRangeFromID(std::unique_ptr<std::string> startId, int64_t count) override; folly::Future<folly::Unit> future_debugEraseAllData() override; folly::Future<std::unique_ptr<thrift_protocol::CentroidDTO>> future_debugGetFullCentroid(std::unique_ptr<std::string>) override; folly::Future<std::unique_ptr<thrift_protocol::ProcessedDocumentDTO>> future_debugGetFullProcessedDocument(std::unique_ptr<std::string>) override; }; } // server } // relevanced
/* * * TINKER Source Code * * * [2009] - [2013] Samuel Steven Truscott * All Rights Reserved. */ #ifndef OPIC_TIMER_H_ #define OPIC_TIMER_H_ #include "alarm_manager.h" void opic_tmr_get_timer(mem_pool_info_t * const pool, uint32_t * base_address, timer_t * timer); #endif /* OPIC_TIMER_H_ */
/******************************************************************************* * Copyright (c) 2007 4DIAC - consortium. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ #ifndef _E_SWITCH_H_ #define _E_SWITCH_H_ #include <funcbloc.h> #include <forte_bool.h> class E_SWITCH: public CFunctionBlock{ DECLARE_FIRMWARE_FB(E_SWITCH) private: static const CStringDictionary::TStringId scm_anDataInputNames[], scm_aunDIDataTypeIds[]; static const TEventID scm_nEventEIID = 0; static const TForteInt16 scm_anEIWithIndexes[]; static const TDataIOID scm_anEIWith[]; static const CStringDictionary::TStringId scm_anEventInputNames[]; static const TEventID scm_nEventEO0ID = 0; static const TEventID scm_nEventEO1ID = 1; static const CStringDictionary::TStringId scm_anEventOutputNames[]; virtual void executeEvent(int pa_nEIID); static const SFBInterfaceSpec scm_stFBInterfaceSpec; FORTE_FB_DATA_ARRAY(2,1,0, 0); CIEC_BOOL& G() { return *static_cast<CIEC_BOOL*>(getDI(0)); } public: FUNCTION_BLOCK_CTOR(E_SWITCH){ }; virtual ~E_SWITCH(){}; }; #endif //close the ifdef sequence from the beginning of the file
/* $Id: libgraph.h,v 1.8 2008/06/09 16:57:01 erg Exp $ $Revision: 1.8 $ */ /* vim:set shiftwidth=4 ts=8: */ /********************************************************** * This software is part of the graphviz package * * http://www.graphviz.org/ * * * * Copyright (c) 1994-2004 AT&T Corp. * * and is licensed under the * * Common Public License, Version 1.0 * * by AT&T Corp. * * * * Information and Software Systems Research * * AT&T Research, Florham Park NJ * **********************************************************/ #ifdef __cplusplus extern "C" { #endif #ifndef _LIBGRAPH_H #define _LIBGRAPH_H 1 #if _PACKAGE_ast #include <ast.h> #else #include <string.h> #include <stdlib.h> #ifndef MSWIN32 #include <unistd.h> #endif #endif #include <ctype.h> #ifndef EXTERN #define EXTERN extern #endif #ifndef NIL #define NIL(t) ((t)0) #endif void ag_yyerror(char *); int ag_yylex(void); typedef struct Agraphinfo_t { char notused; } Agraphinfo_t; typedef struct Agnodeinfo_t { char notused; } Agnodeinfo_t; typedef struct Agedgeinfo_t { char notused; } Agedgeinfo_t; #ifndef _BLD_graph #define _BLD_graph 1 #endif #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "graph.h" #ifdef HAVE_STDINT_H #include <stdint.h> #endif #ifdef HAVE_INTTYPES_H #include <inttypes.h> #endif #ifdef offsetof #undef offsetof #endif #ifdef HAVE_INTPTR_T #define offsetof(typ,fld) ((intptr_t)(&(((typ*)0)->fld))) #else #define offsetof(typ,fld) ((int)(&(((typ*)0)->fld))) #endif #ifndef NOT #define NOT(v) (!(v)) #endif #ifndef FALSE #define FALSE 0 #endif #ifndef TRUE #define TRUE NOT(FALSE) #endif #define NEW(t) (t*)calloc(1,sizeof(t)) #define N_NEW(n,t) (t*)calloc((n),sizeof(t)) #define ALLOC(size,ptr,type) (ptr? (type*)realloc(ptr,(size)*sizeof(type)):(type*)malloc((size)*sizeof(type))) #define MIN(a,b) ((a)<(b)?(a):(b)) #define MAX(a,b) ((a)>(b)?(a):(b)) #define SMALLBUF 128 #define ISALNUM(c) ((isalnum(c)) || ((c) == '_') || (!isascii(c))) #define NOPRINT 0 #define MULTIPLE 1 #define MUSTPRINT 2 #define ISEMPTYSTR(s) (((s) == NULL) || (*(s) == '\0')) #define NULL_FN(t) (t(*)())0 #define ZFREE(p) if (p) free(p); #define TAG_NODE 1 #define TAG_EDGE 2 #define TAG_GRAPH 3 #define TAG_OF(p) (((Agraph_t*)(p))->tag) #define AGFLAG_STRICT (1<<1) #define AGFLAG_METAGRAPH (1<<2) #define METAGRAPH (AGFLAG_DIRECTED | AGFLAG_STRICT | AGFLAG_METAGRAPH) #define KEY_ID "key" #define KEYX 0 #define TAILX 1 #define HEADX 2 EXTERN struct AG_s { int graph_nbytes, node_nbytes, edge_nbytes; Agraph_t *proto_g, *parsed_g; char *edge_op; char *linebuf; short syntax_errors; unsigned char accepting_state, init_called; } AG; /* follow structs used in graph parser */ typedef struct objport_t { void *obj; char *port; } objport_t; typedef struct objlist_t { objport_t data; struct objlist_t *link; } objlist_t; typedef struct objstack_t { Agraph_t *subg; objlist_t *list, *last; int in_edge_stmt; struct objstack_t *link; } objstack_t; Agdict_t *agdictof(void *); Agnode_t *agidnode(Agraph_t *, int); Agdict_t *agNEWdict(char *); Agedge_t *agNEWedge(Agraph_t *, Agnode_t *, Agnode_t *, Agedge_t *); Agnode_t *agNEWnode(Agraph_t *, char *, Agnode_t *); Agsym_t *agNEWsym(Agdict_t *, char *, char *); int agcmpid(Dt_t *, int *, int *, Dtdisc_t *); int agcmpin(Dt_t *, Agedge_t *, Agedge_t *, Dtdisc_t *); int agcmpout(Dt_t *, Agedge_t *, Agedge_t *, Dtdisc_t *); void agcopydict(Agdict_t *, Agdict_t *); void agDELedge(Agraph_t *, Agedge_t *); void agDELnode(Agraph_t *, Agnode_t *); void agerror(char *); void agFREEdict(Agraph_t *, Agdict_t *); void agFREEedge(Agedge_t *); void agFREEnode(Agnode_t *); void aginitlib(int, int, int); void agINSedge(Agraph_t *, Agedge_t *); void agINSgraph(Agraph_t *, Agraph_t *); void agINSnode(Agraph_t *, Agnode_t *); int aglex(void); void aglexinit(FILE *, gets_f mygets); int agparse(void); void agpopproto(Agraph_t *); void agpushproto(Agraph_t *); int agtoken(char *); int aglinenumber(void); void agwredge(Agraph_t *, FILE *, Agedge_t *, int); void agwrnode(Agraph_t *, FILE *, Agnode_t *, int, int); extern Dtdisc_t agNamedisc, agNodedisc, agOutdisc, agIndisc, agEdgedisc; #endif #ifdef __cplusplus } #endif
/************************************************************************* *** FORTE Library Element *** *** This file was generated using the 4DIAC FORTE Export Filter V1.0.x! *** *** Name: F_SINT_TO_BOOL *** Description: Service Interface Function Block Type *** Version: *** 0.0: 2013-04-15/4DIAC-IDE - 4DIAC-Consortium - null *************************************************************************/ #ifndef _F_SINT_TO_BOOL_H_ #define _F_SINT_TO_BOOL_H_ #include <funcbloc.h> #include <forte_sint.h> #include <forte_bool.h> class FORTE_F_SINT_TO_BOOL: public CFunctionBlock{ DECLARE_FIRMWARE_FB(FORTE_F_SINT_TO_BOOL) private: static const CStringDictionary::TStringId scm_anDataInputNames[]; static const CStringDictionary::TStringId scm_anDataInputTypeIds[]; CIEC_SINT &IN() { return *static_cast<CIEC_SINT*>(getDI(0)); }; static const CStringDictionary::TStringId scm_anDataOutputNames[]; static const CStringDictionary::TStringId scm_anDataOutputTypeIds[]; CIEC_BOOL &OUT() { return *static_cast<CIEC_BOOL*>(getDO(0)); }; static const TEventID scm_nEventREQID = 0; static const TForteInt16 scm_anEIWithIndexes[]; static const TDataIOID scm_anEIWith[]; static const CStringDictionary::TStringId scm_anEventInputNames[]; static const TEventID scm_nEventCNFID = 0; static const TForteInt16 scm_anEOWithIndexes[]; static const TDataIOID scm_anEOWith[]; static const CStringDictionary::TStringId scm_anEventOutputNames[]; static const SFBInterfaceSpec scm_stFBInterfaceSpec; FORTE_FB_DATA_ARRAY(1, 1, 1, 0); void executeEvent(int pa_nEIID); public: FUNCTION_BLOCK_CTOR(FORTE_F_SINT_TO_BOOL){ }; virtual ~FORTE_F_SINT_TO_BOOL(){}; }; #endif //close the ifdef sequence from the beginning of the file
/* * Copyright (c) 2013-2015 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html * */ #ifndef OPENBMP_KAFKAPEERPARTITIONERCALLBACK_H #define OPENBMP_KAFKAPEERPARTITIONERCALLBACK_H #include <map> #include <librdkafka/rdkafkacpp.h> class KafkaPeerPartitionerCallback : public RdKafka::PartitionerCb{ public: KafkaPeerPartitionerCallback(); int32_t partitioner_cb (const RdKafka::Topic *topic, const std::string *key, int32_t partition_cnt, void *msg_opaque); private: }; #endif //OPENBMP_KAFKAPARTITIONERCALLBACK_H
/* * pv_thread.h * * Created on: Dec 6, 2008 * Author: rasmussn */ #ifndef PV_THREAD_H_ #define PV_THREAD_H_ #include "../../include/pv_arch.h" #ifdef PV_USE_PTHREADS #include "../../include/pv_types.h" #include <assert.h> #include <pthread.h> #include <stdint.h> /* or <inttypes.h> (<sys/types.h> doesn't work on Darwin) */ #define ADDR_MASK 0xfffffff0 #define CODE_MASK 0xf #ifdef IBM_CELL_BE # include <libspe2.h> # define pv_thread_context_ptr_t spe_context_ptr_t #else # define pv_thread_context_ptr_t int #endif typedef struct { int tid; int column; // column id pthread_t pthread; pv_thread_context_ptr_t ctx; void * tinfo; } pv_thread_env_t; /* TODO - tinfo above should be of this type? */ /* TODO - make sure this is properly aligned */ typedef struct { int id; size_t max_recv_size; float * data; int padding; } pv_thread_params_t; /* global parameters (WARNING - accessed from multiple threads) */ extern pv_thread_env_t thread_env_g[MAX_THREADS]; /* used by main or main_ppu only */ #ifdef CHARLES typedef struct { uint32_t myspu; uint32_t num_steps; uint32_t xpe, ype; uint32_t mype, numpe; int32_t nbr_list[9]; uint32_t dummy; /* for alignment */ uint64_t ppu_phdata_ea; uint64_t ppu_xdata_ea; uint64_t ppu_ydata_ea; uint64_t ppu_thdata_ea; uint64_t ppu_xpdata_ea; uint64_t ppu_ypdata_ea; uint64_t ppu_fdata_ea; uint64_t ppu_timing_ea; uint64_t ppu_mboard_ea; uint64_t prev_ls_base_ea; uint64_t next_ls_base_ea; uint64_t dummy64; /* for alignment */ } spu_param_t; typedef struct{ uint64_t cyc_compute; uint64_t cyc_p2s_get; uint64_t cyc_s2s_put; uint64_t cyc_s2p_put; } spu_timing_t; typedef struct{ float ph[CHUNK_SIZE]; float x[CHUNK_SIZE]; float y[CHUNK_SIZE]; float dummy[CHUNK_SIZE]; /* for alignment */ } data_chunk_t; #endif /* CHARLES */ #ifdef __cplusplus extern "C" { #endif int pv_thread_init(int column, int numThreads); int pv_thread_finalize(int column, int numThreads); int pv_signal_threads_recv(void * addr, unsigned char msg); int pv_in_mbox_write(pv_thread_context_ptr_t ctx, unsigned int * mbox_data, int count, unsigned int behavior); static inline uint32_t encode_msg(void * buf, char code) { #ifdef PV_ARCH_64 /* send only the low portion of the address */ assert( ((uint64_t) buf & ADDR_MASK) == ((uint64_t) buf & 0xffffffff) ); return (((uint64_t) buf) & 0xffffffff) | (code & CODE_MASK); #else assert(((uint32_t) buf & ADDR_MASK) == (uint32_t) buf); return ((uint32_t) buf) | (code & CODE_MASK); #endif } static inline char decode_msg(uint32_t msg, void ** addr) { #ifdef PV_ARCH_64 *addr = (void*) ((uint64_t) msg & ADDR_MASK); #else *addr = (void*) (msg & ADDR_MASK); #endif return (msg & CODE_MASK); } #ifdef __cplusplus } #endif #endif /* PV_USE_PTHREADS */ #endif /* PV_THREAD_H_ */
/* $OpenBSD: setvbuf.c,v 1.8 2005/08/08 08:05:36 espie Exp $ */ /*- * Copyright (c) 1990, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Chris Torek. * * 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 <stdio.h> #include <stdlib.h> #include "local.h" /* * Set one of the three kinds of buffering, optionally including * a buffer. */ int setvbuf(FILE *fp, char *buf, int mode, size_t size) { int ret, flags; size_t iosize; int ttyflag; /* * Verify arguments. The `int' limit on `size' is due to this * particular implementation. Note, buf and size are ignored * when setting _IONBF. */ if (mode != _IONBF) if ((mode != _IOFBF && mode != _IOLBF) || (int)size < 0) return (EOF); /* * Write current buffer, if any. Discard unread input (including * ungetc data), cancel line buffering, and free old buffer if * malloc()ed. We also clear any eof condition, as if this were * a seek. */ ret = 0; (void)__sflush(fp); if (HASUB(fp)) FREEUB(fp); WCIO_FREE(fp); fp->_r = fp->_lbfsize = 0; flags = fp->_flags; if (flags & __SMBF) free((void *)fp->_bf._base); flags &= ~(__SLBF | __SNBF | __SMBF | __SOPT | __SNPT | __SEOF); /* If setting unbuffered mode, skip all the hard work. */ if (mode == _IONBF) goto nbf; /* * Find optimal I/O size for seek optimization. This also returns * a `tty flag' to suggest that we check isatty(fd), but we do not * care since our caller told us how to buffer. */ flags |= __swhatbuf(fp, &iosize, &ttyflag); if (size == 0) { buf = NULL; /* force local allocation */ size = iosize; } /* Allocate buffer if needed. */ if (buf == NULL) { if ((buf = malloc(size)) == NULL) { /* * Unable to honor user's request. We will return * failure, but try again with file system size. */ ret = EOF; if (size != iosize) { size = iosize; buf = malloc(size); } } if (buf == NULL) { /* No luck; switch to unbuffered I/O. */ nbf: fp->_flags = flags | __SNBF; fp->_w = 0; fp->_bf._base = fp->_p = fp->_nbuf; fp->_bf._size = 1; return (ret); } flags |= __SMBF; } /* * Kill any seek optimization if the buffer is not the * right size. * * SHOULD WE ALLOW MULTIPLES HERE (i.e., ok iff (size % iosize) == 0)? */ if (size != iosize) flags |= __SNPT; /* * Fix up the FILE fields, and set __cleanup for output flush on * exit (since we are buffered in some way). */ if (mode == _IOLBF) flags |= __SLBF; fp->_flags = flags; fp->_bf._base = fp->_p = (unsigned char *)buf; fp->_bf._size = size; /* fp->_lbfsize is still 0 */ if (flags & __SWR) { /* * Begin or continue writing: see __swsetup(). Note * that __SNBF is impossible (it was handled earlier). */ if (flags & __SLBF) { fp->_w = 0; fp->_lbfsize = -fp->_bf._size; } else fp->_w = size; } else { /* begin/continue reading, or stay in intermediate state */ fp->_w = 0; } __atexit_register_cleanup(_cleanup); return (ret); }
/* * Partition Manager * * * COPYRIGHT (c) 1989-2007. * On-Line Applications Research Corporation (OAR). * * The license and distribution terms for this file may be * found in the file LICENSE in this distribution or at * http://www.rtems.com/license/LICENSE. * * $Id$ */ #if HAVE_CONFIG_H #include "config.h" #endif #include <rtems/system.h> #include <rtems/rtems/status.h> #include <rtems/rtems/support.h> #include <rtems/score/address.h> #include <rtems/score/object.h> #include <rtems/rtems/part.h> #include <rtems/score/thread.h> #include <rtems/score/sysstate.h> /*PAGE * * rtems_partition_return_buffer * * This directive will return the given buffer to the specified * buffer partition. * * Input parameters: * id - partition id * buffer - pointer to buffer address * * Output parameters: * RTEMS_SUCCESSFUL - if successful * error code - if unsuccessful */ rtems_status_code rtems_partition_return_buffer( rtems_id id, void *buffer ) { register Partition_Control *the_partition; Objects_Locations location; the_partition = _Partition_Get( id, &location ); switch ( location ) { case OBJECTS_LOCAL: if ( _Partition_Is_buffer_valid( buffer, the_partition ) ) { _Partition_Free_buffer( the_partition, buffer ); the_partition->number_of_used_blocks -= 1; _Thread_Enable_dispatch(); return RTEMS_SUCCESSFUL; } _Thread_Enable_dispatch(); return RTEMS_INVALID_ADDRESS; #if defined(RTEMS_MULTIPROCESSING) case OBJECTS_REMOTE: return _Partition_MP_Send_request_packet( PARTITION_MP_RETURN_BUFFER_REQUEST, id, buffer ); #endif case OBJECTS_ERROR: break; } return RTEMS_INVALID_ID; }
#ifndef __LOGIC_SERVER_H__ #define __LOGIC_SERVER_H__ #include <map> #include "server_conn.h" #include "server_status.h" #include "json/json.h" #include "net/ef_server.h" #include "base/ef_loader.h" namespace gim{ typedef int (*ServerObjInit)(void* obj, LogicServer* s); typedef int (*ServerObjClean)(void* obj, LogicServer* s); class ZKClient; class ZKConfig; class ZKServerNode; class ZKServerListOb; struct LogicConfig{ int ID; int Type; int ThreadCount; int KeepaliveSpanMS; int ReconnectSpanMS; std::string LogConfig; std::string NetLogName; std::string LogName; Json::Value SessCacheConfig; LogicConfig():ThreadCount(12), KeepaliveSpanMS(30000), ReconnectSpanMS(10000){ } }; class LogicServer: public ef::Server{ public: LogicServer(); ~LogicServer(); void setSvConFactory(SvConFactory* f){ m_confac = f; } SvConFactory* getSvConFactory(){ return m_confac; } int init(const std::string& zkurl, const std::string& confpath, const std::string& connectstatuspath, const std::string& statuspath, int type, int id, const std::string& logconf); int setObj(void* obj, ServerObjInit i, ServerObjClean c){ if(m_obclean){ m_obclean(m_obj, this); } m_obj = obj; m_obinit = i; m_obclean = c; return 0; } int start(); int stop(); const LogicConfig& getConfig() const{ return m_conf; } ef::DataSrc<Json::Value>& getJsonConfig(){ return m_jsonconf; } int free(); int reportStatus(); private: typedef std::map<int, ServerStatus> SMap; int initConfig(const std::string& zkurl, const std::string& confpath, int type, int id); int initStatusNode(const std::string& statuspath); int initSvListOb(const std::string& connectstatuspath); int initEventLoop(); int initLog(); int initCompent(); int freeCompent(); int loadConfig(const Json::Value& conf); int notifySvlistChange(); int initDispatcher(); static void ConfUpdateCallback(void* ctx, int ver, const Json::Value& notify); static int ServerListChangeCallback(void* ctx, const std::map<std::string, Json::Value>& notify); LogicConfig m_conf; ef::Server m_serv; ef::DataSrc<Json::Value> m_jsonconf; Json::Value m_status; bool m_run; ZKClient* m_zkc; ZKConfig* m_zkcnf; ZKServerListOb* m_zksvob; ZKServerNode* m_zksvnd; SvConFactory* m_confac; ef::DataSrc<SMap> m_svlst; void* m_obj; ServerObjInit m_obinit; ServerObjClean m_obclean; }; }; #endif
/* * arch/s390/kernel/cpcmd.c * * S390 version * Copyright (C) 1999,2005 IBM Deutschland Entwicklung GmbH, IBM Corporation * Author(s): Martin Schwidefsky (schwidefsky@de.ibm.com), * Christian Borntraeger (cborntra@de.ibm.com), */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/spinlock.h> #include <linux/stddef.h> #include <linux/string.h> #include <asm/ebcdic.h> #include <asm/cpcmd.h> #include <asm/system.h> static DEFINE_SPINLOCK(cpcmd_lock); static char cpcmd_buf[241]; /* * __cpcmd has some restrictions over cpcmd * - the response buffer must reside below 2GB (if any) * - __cpcmd is unlocked and therefore not SMP-safe */ int __cpcmd(const char *cmd, char *response, int rlen, int *response_code) { unsigned cmdlen; int return_code, return_len; cmdlen = strlen(cmd); BUG_ON(cmdlen > 240); memcpy(cpcmd_buf, cmd, cmdlen); ASCEBC(cpcmd_buf, cmdlen); if (response != NULL && rlen > 0) { register unsigned long reg2 asm ("2") = (addr_t) cpcmd_buf; register unsigned long reg3 asm ("3") = (addr_t) response; register unsigned long reg4 asm ("4") = cmdlen | 0x40000000L; register unsigned long reg5 asm ("5") = rlen; memset(response, 0, rlen); asm volatile( #ifndef CONFIG_64BIT " diag %2,%0,0x8\n" " brc 8,1f\n" " ar %1,%4\n" #else /* CONFIG_64BIT */ " sam31\n" " diag %2,%0,0x8\n" " sam64\n" " brc 8,1f\n" " agr %1,%4\n" #endif /* CONFIG_64BIT */ "1:\n" : "+d" (reg4), "+d" (reg5) : "d" (reg2), "d" (reg3), "d" (rlen) : "cc"); return_code = (int) reg4; return_len = (int) reg5; EBCASC(response, rlen); } else { register unsigned long reg2 asm ("2") = (addr_t) cpcmd_buf; register unsigned long reg3 asm ("3") = cmdlen; return_len = 0; asm volatile( #ifndef CONFIG_64BIT " diag %1,%0,0x8\n" #else /* CONFIG_64BIT */ " sam31\n" " diag %1,%0,0x8\n" " sam64\n" #endif /* CONFIG_64BIT */ : "+d" (reg3) : "d" (reg2) : "cc"); return_code = (int) reg3; } if (response_code != NULL) *response_code = return_code; return return_len; } EXPORT_SYMBOL(__cpcmd); int cpcmd(const char *cmd, char *response, int rlen, int *response_code) { char *lowbuf; int len; unsigned long flags; if ((rlen == 0) || (response == NULL) || !((unsigned long)response >> 31)) { spin_lock_irqsave(&cpcmd_lock, flags); len = __cpcmd(cmd, response, rlen, response_code); spin_unlock_irqrestore(&cpcmd_lock, flags); } else { lowbuf = kmalloc(rlen, GFP_KERNEL | GFP_DMA); if (!lowbuf) { printk(KERN_WARNING "cpcmd: could not allocate response buffer\n"); return -ENOMEM; } spin_lock_irqsave(&cpcmd_lock, flags); len = __cpcmd(cmd, lowbuf, rlen, response_code); spin_unlock_irqrestore(&cpcmd_lock, flags); memcpy(response, lowbuf, rlen); kfree(lowbuf); } return len; } EXPORT_SYMBOL(cpcmd);
/** * @file sys.c * @brief Implements system specific accounting and monitoring functions. * @author Mikey Austin * @date 2012-2013 */ #include <stdio.h> #include <stdlib.h> #include <avr/interrupt.h> #include <avr/pgmspace.h> #include "cache.h" #include "sys.h" #define T Sys_cmd_T #define SYS_TOT_MEM 4096 static int Sys_tx_count; static int Sys_tx_bytes_count; static int Sys_parse_err_count; static int Sys_parse_ok_count; static int Sys_sys_cmd_count; static void Sys_cmd_status(void *args); static void Sys_cmd_help(void *args); static void Sys_cmd_cache_clear(void *args); static void Sys_cmd_cache_show(void *args); extern void Sys_init(void) { Sys_tx_count = 0; Sys_tx_bytes_count = 0; Sys_parse_err_count = 0; Sys_parse_ok_count = 0; Sys_sys_cmd_count = 0; } extern T Sys_cmd_create(uint8_t type, void *args) { T cmd; cmd = (T) malloc(sizeof(*cmd)); if(cmd == NULL) { return NULL; } cmd->type = type; cmd->args = args; switch(cmd->type) { case SYS_CMD_TYPE_STATUS: cmd->call = Sys_cmd_status; break; case SYS_CMD_TYPE_HELP: cmd->call = Sys_cmd_help; break; case SYS_CMD_TYPE_CACHE_CLEAR: cmd->call = Sys_cmd_cache_clear; break; case SYS_CMD_TYPE_CACHE_SHOW: cmd->call = Sys_cmd_cache_show; break; default: cmd->call = NULL; break; } return cmd; } extern void Sys_cmd_destroy(T cmd, void (*free_args)(void *args)) { if(cmd) { if(cmd->args != NULL && free_args != NULL) { free_args(cmd->args); } free(cmd); } } extern void Sys_process_dcc_tx(DCC_packet_T packet) { Sys_tx_count++; Sys_tx_bytes_count += packet->size; } extern void Sys_process_sys_cmd(T cmd) { Sys_sys_cmd_count++; } extern void Sys_parse_err_increment(void) { Sys_parse_err_count++; } extern void Sys_parse_ok_increment(void) { Sys_parse_ok_count++; } static void Sys_cmd_status(void *args) { int v, mem_free, cache_total, cache_used; double mem_free_percentage; extern int __heap_start, *__brkval; /* Calculate free heap memory. */ mem_free = (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval); mem_free_percentage = (mem_free / (double) SYS_TOT_MEM) * 100; /* Output all counters. */ printf_P(PSTR("system details\n")); printf_P(PSTR(" mem_used_bytes:\t%d\n"), (SYS_TOT_MEM - mem_free)); printf_P(PSTR(" mem_free_bytes:\t%d\n"), mem_free); printf_P(PSTR(" mem_free_percent:\t%.2f%%\n"), mem_free_percentage); printf_P(PSTR(" sys_cmd_total:\t%d\n"), Sys_sys_cmd_count); printf_P(PSTR(" dcc_tx_packets:\t%d\n"), Sys_tx_count); printf_P(PSTR(" dcc_tx_bytes:\t\t%d\n"), Sys_tx_bytes_count); printf_P(PSTR(" parse_errors:\t\t%d\n"), Sys_parse_err_count); printf_P(PSTR(" parse_ok:\t\t%d\n"), Sys_parse_ok_count); printf_P(PSTR(" parse_total:\t\t%d\n"), (Sys_parse_ok_count + Sys_parse_err_count)); printf_P(PSTR(" cache_used:\t\t%d/%d\n"), (cache_used = Cache_report_current_size()), (cache_total = Cache_report_total_size())); printf_P(PSTR(" cache_free_percent:\t%.2f%%\n\n"), ((cache_total - cache_used) / (double) cache_total) * 100); } static void Sys_cmd_help(void *args) { printf_P(PSTR("system help message goes here...\n\n")); } static void Sys_cmd_cache_clear(void *args) { int curr; curr = Cache_report_current_size(); Cache_clear(); printf_P(PSTR("%d item(s) purged\n\n"), curr); } static void Sys_cmd_cache_show(void *args) { int *address = (int*) args; char *hex_dump, *binary_dump; DCC_packet_T cached; if((cached = Cache_get(*address)) == NULL) { printf_P(PSTR("no cached packet for loco with address %d\n\n"), *address); } else { hex_dump = DCC_hex_dump(cached); binary_dump = DCC_dump(cached); printf_P(PSTR("cached packet details\n")); printf_P(PSTR(" address:\t%d\n"), *address); printf_P(PSTR(" speed:\t%d\n"), DCC_get_speed_step(cached)); printf_P(PSTR(" direction:\t%s\n"), (DCC_get_direction(cached) ? "forward" : "reverse")); printf_P(PSTR(" hex:\t\t%s\n"), hex_dump); printf_P(PSTR(" binary:\t%s\n\n"), binary_dump); if(hex_dump) free(hex_dump); if(binary_dump) free(binary_dump); } }
/* * \brief AHCI driver declaration * \author Martin Stein <martin.stein@genode-labs.com> * \date 2013-04-10 */ /* * Copyright (C) 2013 Genode Labs GmbH * * This file is part of the Genode OS framework, which is distributed * under the terms of the GNU General Public License version 2. */ #ifndef _AHCI_DRIVER_H_ #define _AHCI_DRIVER_H_ /* Genode includes */ #include <block/component.h> #include <ram_session/ram_session.h> /** * AHCI driver */ class Ahci_driver : public Block::Driver { enum { VERBOSE = 0 }; /* import Genode symbols */ typedef Genode::size_t size_t; typedef Genode::uint64_t uint64_t; typedef Genode::addr_t addr_t; int _ncq_command(uint64_t lba, unsigned cnt, addr_t phys, bool w); public: /** * Constructor */ Ahci_driver(); /***************************** ** Block::Driver interface ** *****************************/ Block::Session::Operations ops() { Block::Session::Operations o; o.set_operation(Block::Packet_descriptor::READ); o.set_operation(Block::Packet_descriptor::WRITE); return o; } size_t block_size(); Block::sector_t block_count(); bool dma_enabled() { return true; } Genode::Ram_dataspace_capability alloc_dma_buffer(Genode::size_t size) { return Genode::env()->ram_session()->alloc(size, false); } void free_dma_buffer(Genode::Ram_dataspace_capability c) { return Genode::env()->ram_session()->free(c); } void read_dma(Block::sector_t block_nr, size_t block_cnt, addr_t phys, Block::Packet_descriptor &packet) { if (_ncq_command(block_nr, block_cnt, phys, 0)) throw Io_error(); ack_packet(packet); } void write_dma(Block::sector_t block_nr, size_t block_cnt, addr_t phys, Block::Packet_descriptor &packet) { if (_ncq_command(block_nr, block_cnt, phys, 1)) throw Io_error(); ack_packet(packet); } }; #endif /* _AHCI_DRIVER_H_ */
/** * This header is generated by class-dump-z 0.2b. * * Source: /System/Library/PrivateFrameworks/IMCore.framework/Frameworks/IMFoundation.framework/IMFoundation */ #import <IMFoundation/IMXMLParserFrame.h> @interface IMToSuperParserFrame : IMXMLParserFrame { } - (void)parser:(id)parser context:(id)context foundIgnorableWhitespace:(id)whitespace; // 0x120ed - (void)parser:(id)parser context:(id)context foundCharacters:(id)characters; // 0x5de5 - (void)parser:(id)parser context:(id)context didEndElement:(id)element namespaceURI:(id)uri qualifiedName:(id)name; // 0x5fb1 - (void)parser:(id)parser context:(id)context didStartElement:(id)element namespaceURI:(id)uri qualifiedName:(id)name attributes:(id)attributes; // 0x5be5 @end
/* * libuwifi - Userspace Wifi Library * * Copyright (C) 2005-2016 Bruno Randolf (br1@einfach.org) * * This source code is licensed under the GNU Lesser General Public License, * Version 3. See the file COPYING for more details. */ #include <unistd.h> #include "conf.h" #include "ifctrl.h" #include "netdev.h" #include "packet_sock.h" #include "util.h" #include "node.h" bool uwifi_init(struct uwifi_interface* intf) { list_head_init(&intf->wlan_nodes); intf->channel_idx = -1; intf->last_channelchange = plat_time_usec(); intf->sock = packet_socket_open(intf->ifname); if (intf->sock < 0) { printlog(LOG_ERR, "Could not open packet socket on '%s'", intf->ifname); return false; } if (!netdev_set_up_promisc(intf->ifname, true, true)) { printlog(LOG_ERR, "Failed to bring '%s' up", intf->ifname); return false; } intf->arphdr = netdev_get_hwinfo(intf->ifname); if (intf->arphdr != ARPHRD_IEEE80211_RADIOTAP && intf->arphdr != ARPHRD_IEEE80211_PRISM) { printlog(LOG_ERR, "Interface '%s' not in monitor mode", intf->ifname); return false; } if (!ifctrl_iwget_interface_info(intf)) return false; if (!uwifi_channel_init(intf)) { printlog(LOG_ERR, "Failed to initialize channels"); return false; } return true; } void uwifi_fini(struct uwifi_interface* intf) { if (intf->sock > 0) { close(intf->sock); intf->sock = -1; } netdev_set_up_promisc(intf->ifname, true, false); uwifi_nodes_free(&intf->wlan_nodes); }
/*****************************************************************************\ * Copyright (C) 2007-2010 Lawrence Livermore National Security, LLC. * Copyright (C) 2007 The Regents of the University of California. * Produced at Lawrence Livermore National Laboratory (cf, DISCLAIMER). * Written by Brian Behlendorf <behlendorf1@llnl.gov>. * UCRL-CODE-235197 * * This file is part of the SPL, Solaris Porting Layer. * For details, see <http://github.com/behlendorf/spl/>. * * The SPL is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * The SPL 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 the SPL. If not, see <http://www.gnu.org/licenses/>. \*****************************************************************************/ #ifndef _SPL_MUTEX_H #define _SPL_MUTEX_H #include <sys/types.h> //#include <linux/mutex.h> #include <osx/mutex.h> //#include <linux/compiler_compat.h> #endif /* _SPL_MUTEX_H */
/* File: file_3ds.c Copyright (C) 2019 Christophe GRENIER <grenier@cgsecurity.org> This software is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #if !defined(SINGLE_FORMAT) || defined(SINGLE_FORMAT_3ds) #ifdef HAVE_CONFIG_H #include <config.h> #endif #ifdef HAVE_STRING_H #include <string.h> #endif #include <stdio.h> #include "types.h" #include "filegen.h" #include "common.h" /*@ requires valid_register_header_check(file_stat); */ static void register_header_check_3ds(file_stat_t *file_stat); const file_hint_t file_hint_3ds= { .extension="3ds", .description="3d Studio", .max_filesize=PHOTOREC_MAX_FILE_SIZE, .recover=1, .enable_by_default=1, .register_header_check=&register_header_check_3ds }; struct chunk_3ds { uint16_t chunk_id; uint32_t next_chunk; } __attribute__ ((gcc_struct, __packed__)); /*@ @ requires buffer_size >= sizeof(struct chunk_3ds); @ requires separation: \separated(&file_hint_3ds, buffer+(..), file_recovery, file_recovery_new); @ requires valid_header_check_param(buffer, buffer_size, safe_header_only, file_recovery, file_recovery_new); @ ensures valid_header_check_result(\result, file_recovery_new); @ assigns *file_recovery_new; @*/ static int header_check_3ds(const unsigned char *buffer, const unsigned int buffer_size, const unsigned int safe_header_only, const file_recovery_t *file_recovery, file_recovery_t *file_recovery_new) { uint64_t fs; const struct chunk_3ds *hdr=(const struct chunk_3ds *)buffer; if(buffer_size < 0x12) return 0; if(buffer[0]!=0x4d || buffer[1]!=0x4d || buffer[0x10]!=0x3d || buffer[0x11]!=0x3d) return 0; fs=le32(hdr->next_chunk); if(fs <= 0x12) return 0; reset_file_recovery(file_recovery_new); file_recovery_new->extension=file_hint_3ds.extension; file_recovery_new->calculated_file_size=fs; file_recovery_new->data_check=&data_check_size; file_recovery_new->file_check=&file_check_size; return 1; } static void register_header_check_3ds(file_stat_t *file_stat) { static const unsigned char header_3ds[4]= { 0x02, 0x00, 0x0a, 0x00 }; register_header_check(6, header_3ds, sizeof(header_3ds), &header_check_3ds, file_stat); } #endif
#include "pathes.h" #include <string.h> #include <stdlib.h> #include <stdio.h> pathes_t pathes = {NULL}; void pathes_rompath(const char *rompath) { pathes.rom = realloc(pathes.rom, strlen(rompath) + 1); strcpy(pathes.rom, rompath); char *pathend = strrchr(pathes.rom, '/'); if(pathend == NULL) { pathes.romdir = realloc(pathes.romdir, 3); pathes.romname = realloc(pathes.romname, strlen(pathes.rom) + 1); strcpy(pathes.romdir, "./"); strcpy(pathes.romname, pathes.rom); } else { int sep = pathend - pathes.rom + 1; pathes.romdir = realloc(pathes.romdir, sep + 1); memcpy(pathes.romdir, pathes.rom, sep); pathes.romdir[sep] = '\0'; pathes.romname = realloc(pathes.romname, strlen(pathes.rom) - sep + 1); strcpy(pathes.romname, &pathes.rom[sep]); } int pathlen = strlen(pathes.romname); pathes.config = realloc(pathes.config, pathlen + 7 + 1); sprintf(pathes.config, "%s.config", pathes.romname); pathes.continue_state = realloc(pathes.continue_state, pathlen + 15 + 1); sprintf(pathes.continue_state, "%s.continue.state", pathes.romname); int s; for(s = 0; s < 10; s++) { pathes.states[s] = realloc(pathes.states[s], pathlen + 5 + 1); sprintf(pathes.states[s], "%s.sav%i", pathes.romname, s); } pathes.card = realloc(pathes.card, pathlen + 5 + 1); sprintf(pathes.card, "%s.card", pathes.romname); } void pathes_close() { free(pathes.rom); free(pathes.romdir); free(pathes.config); int s; for(s = 0; s < 10; s++) { free(pathes.states[s]); } free(pathes.card); }
#ifndef MY_MEAN_SHIFT #define MY_MEAN_SHIFT #include "globalInclude.h" #include "MeanShiftParam.h" #include "HashParam.h" #define LSH_NEIGHBOR extern int shiftTime; //check up the convex trend of a random selected point extern vector<float> convexTrend; extern vector<int> iters; #ifdef LSH_NEIGHBOR //the retained point after LSH in search neighbors in every iteration step //these point at least have a same hash value extern vector<int> candidatesNumber; //the retained point after LSH in search neighbors in every iteration step //after all the hash function votes extern vector<int> neighborFileterNumber; #endif void meanshiftCluster(const Mat& feature, Mat& convexPoint); void boostSample(int sample_m, int sample_n, Mat& proj, int maxSampleValue); int setWindow(HashParam hp, const Mat& feature, const Mat& proj); vector<int> getCandidates(HashParam hp, vector<float> sp, const Mat& proj); #endif
/* * FILE: base64.h * AUTHORS: Colin Perkins * * Copyright (c) 1998-2000 University College London * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, is 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 acknowledgement: * This product includes software developed by the Computer Science * Department at University College London * 4. Neither the name of the University nor of the Department may be used * to endorse or promote products derived from this software without * specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``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 AUTHORS 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. */ #ifndef MBUS_BASE64_H #define MBUS_BASE64_H #include <glib.h> #ifdef __cplusplus extern "C" { #endif gint base64encode( const GByteArray * input, GByteArray * output ); gint base64decode( const GByteArray * input, GByteArray * output ); #ifdef __cplusplus } #endif #endif /* MBUS_BASE64_H */
/* ** rq_termstruct_mapping.c ** ** Written by Brett Hutley - brett@hutley.net ** ** Copyright (C) 2002-2008 Brett Hutley ** ** This file is part of the Risk Quantify Library ** ** Risk Quantify is free software; you can redistribute it and/or ** modify it under the terms of the GNU Library General Public ** License as published by the Free Software Foundation; either ** version 2 of the License, or (at your option) any later version. ** ** Risk Quantify 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 ** Library General Public License for more details. ** ** You should have received a copy of the GNU Library General Public ** License along with Risk Quantify; if not, write to the Free ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "rq_termstruct_mapping.h" #include <stdlib.h> #include <string.h> RQ_EXPORT rq_termstruct_mapping_t rq_termstruct_mapping_alloc() { rq_termstruct_mapping_t termstruct_mapping = (rq_termstruct_mapping_t) RQ_CALLOC(1, sizeof(struct rq_termstruct_mapping)); return termstruct_mapping; } RQ_EXPORT rq_termstruct_mapping_t rq_termstruct_mapping_build( const char *asset_id, const char *termstruct_group_id, const char *curve_id ) { rq_termstruct_mapping_t termstruct_mapping = (rq_termstruct_mapping_t) RQ_MALLOC(sizeof(struct rq_termstruct_mapping)); termstruct_mapping->termstruct_group_id = RQ_STRDUP(termstruct_group_id); termstruct_mapping->asset_id = RQ_STRDUP(asset_id); termstruct_mapping->curve_id = RQ_STRDUP(curve_id); return termstruct_mapping; } RQ_EXPORT void rq_termstruct_mapping_free(rq_termstruct_mapping_t termstruct_mapping) { if (termstruct_mapping->asset_id) RQ_FREE((char *)termstruct_mapping->asset_id); if (termstruct_mapping->termstruct_group_id) RQ_FREE((char *)termstruct_mapping->termstruct_group_id); if (termstruct_mapping->curve_id) RQ_FREE((char *)termstruct_mapping->curve_id); RQ_FREE(termstruct_mapping); } RQ_EXPORT int rq_termstruct_mapping_is_null(rq_termstruct_mapping_t obj) { return RQ_IS_NULL(obj); }
#ifndef RESIZEEVENTABSTRACTOR_H #define RESIZEEVENTABSTRACTOR_H #include "Interfaces/IResizeEvent.h" template< class T > class ResizeEventAbstractor : public IResizeEvent { public: virtual bool OnResize( IWindow &Window, float NewWidth, float NewHeight ) = 0; virtual bool OnResized( IWindow &Window ) = 0; }; #endif
#ifndef VIDEOOUT_IVTV_H_ #define VIDEOOUT_IVTV_H_ #include <qstring.h> #include <qmutex.h> #include "videooutbase.h" class NuppelVideoPlayer; class VideoOutputIvtvPriv; class VideoOutputIvtv: public VideoOutput { public: VideoOutputIvtv(); ~VideoOutputIvtv(); bool Init(int width, int height, float aspect, WId winid, int winx, int winy, int winw, int winh, WId embedid = 0); void PrepareFrame(VideoFrame *buffer, FrameScanType); void Show(FrameScanType ); bool InputChanged(const QSize &input_size, float aspect, MythCodecID av_codec_id, void *codec_private); int GetRefreshRate(void); void DrawUnusedRects(bool sync = true); void UpdatePauseFrame(void); void ProcessFrame(VideoFrame *frame, OSD *osd, FilterChain *filterList, NuppelVideoPlayer *pipPlayer); uint WriteBuffer(unsigned char *buf, int count); int Poll(int delay); void Pause(void); void Start(int skip, int mute); void Stop(bool hide); void Open(void); void Close(void); void SetFPS(float lfps) { fps = lfps; } void ClearOSD(void); bool Play(float speed, bool normal, int mask); bool Play(void) { return Play(last_speed, last_normal, last_mask); }; void NextPlay(float speed, bool normal, int mask) { last_speed = speed; last_normal = normal; last_mask = mask; }; void Flush(void); void Step(void); long long GetFramesPlayed(void); VideoFrame *GetNextFreeFrame(bool with_lock = false, bool allow_unsafe = false) { (void) with_lock; (void) allow_unsafe; return NULL; } int ValidVideoFrames(void) const; static QStringList GetAllowedRenderers(MythCodecID myth_codec_id, const QSize &video_dim); private: typedef enum { kAlpha_Solid, kAlpha_Local, kAlpha_Clear, kAlpha_Embedded } eAlphaState; void ShowPip(VideoFrame *frame, NuppelVideoPlayer *pipplayer); void SetAlpha(eAlphaState newAlpha); void SetColorKey(int state, int color); long long GetFirmwareFramesPlayed(void); int videofd; int fbfd; float fps; QString videoDevice; unsigned int driver_version; bool has_v4l2_api; bool has_pause_bug; QMutex lock; int mapped_offset; int mapped_memlen; char *mapped_mem; char *pixels; int stride; bool lastcleared; bool pipon; bool osdon; char *osdbuffer; char *osdbuf_aligned; int osdbufsize; int osdbuf_revision; float last_speed; int internal_offset; int frame_at_speed_change; bool last_normal; int last_mask; eAlphaState alphaState; bool old_fb_ioctl; int fb_dma_ioctl; bool color_key; bool decoder_flush; bool paused; VideoOutputIvtvPriv *priv; }; #endif
extern void *add_node(void *root, void *data); extern void *traverse_tree(void *n, int (*cb)(void *, void *), void *arg); extern int height_tree(void *n);
/* Copyright (c) 2004-2009 Gordon Gremme <gremme@zbh.uni-hamburg.de> Copyright (c) 2004-2008 Center for Bioinformatics, University of Hamburg Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "gth/ags.h" struct GthAGSObject { const GthPGL *pgl; }; GthAGS* gth_ags_new(const GthPGL *pgl) { GthAGS *ags; gt_assert(pgl); ags = gt_malloc(sizeof *ags); ags->agso = gt_malloc(sizeof *ags->agso); ags->agso->pgl = pgl; ags->gen_id = NULL; ags->exons = gt_array_new(sizeof (GthExonAGS)); ags->splicesiteprobs = gt_array_new(sizeof (GthSpliceSiteProb)); ags->alignments = gt_array_new(sizeof (GthSA*)); ags->numofstoredsaclusters = 0; ags->overallscore = GTH_UNDEF_GTHDBL; return ags; } void gth_ags_delete(GthAGS *ags) { if (!ags) return; gt_str_delete(ags->gen_id); gt_array_delete(ags->exons); gt_array_delete(ags->splicesiteprobs); gt_array_delete(ags->alignments); gt_free(ags->agso); gt_free(ags); } bool gth_ags_is_forward(const GthAGS *ags) { gt_assert(ags); return gth_pgl_is_forward(ags->agso->pgl); } unsigned long gth_ags_filenum(const GthAGS *ags) { gt_assert(ags); return gth_pgl_filenum(ags->agso->pgl); } unsigned long gth_ags_total_length(const GthAGS *ags) { gt_assert(ags); return gth_pgl_total_length(ags->agso->pgl); } unsigned long gth_ags_genomic_offset(const GthAGS *ags) { gt_assert(ags); return gth_pgl_genomic_offset(ags->agso->pgl); } GtStr* gth_ags_get_gen_id(const GthAGS *ags) { gt_assert(ags && ags->gen_id); return ags->gen_id; } GthExonAGS* gth_ags_get_exon(const GthAGS *ags, unsigned long exon) { gt_assert(ags && ags->exons); gt_assert(exon < gt_array_size(ags->exons)); return gt_array_get(ags->exons, exon); } unsigned long gth_ags_num_of_exons(const GthAGS *ags) { gt_assert(ags && ags->exons); return gt_array_size(ags->exons); } GtStrand gth_ags_genomic_strand(const GthAGS *ags) { gt_assert(ags); return gth_ags_is_forward(ags) ? GT_STRAND_FORWARD : GT_STRAND_REVERSE; } static unsigned long gth_ags_left_intron_border(const GthAGS *ags, unsigned long intron) { GthExonAGS *exon; gt_assert(ags); exon = gth_ags_get_exon(ags, intron); return SHOWGENPOSAGS(exon->range.end + 1); } static unsigned long gth_ags_right_intron_border(const GthAGS *ags, unsigned long intron) { GthExonAGS *exon; gt_assert(ags); exon = gth_ags_get_exon(ags, intron + 1); return SHOWGENPOSAGS(exon->range.start - 1); } GtRange gth_ags_donor_site_range(const GthAGS *ags, unsigned long intron) { GtRange range; gt_assert(ags); range.start = gth_ags_left_intron_border(ags, intron); range.end = range.start + 1; return range; } GtRange gth_ags_acceptor_site_range(const GthAGS *ags, unsigned long intron) { GtRange range; gt_assert(ags); range.end = gth_ags_right_intron_border(ags, intron); range.start = range.end - 1; return range; } double gth_ags_donor_site_prob(const GthAGS *ags, unsigned long intron) { gt_assert(ags); return ((GthSpliceSiteProb*) gt_array_get(ags->splicesiteprobs, intron)) ->donorsiteprob; } double gth_ags_acceptor_site_prob(const GthAGS *ags, unsigned long intron) { gt_assert(ags); return ((GthSpliceSiteProb*) gt_array_get(ags->splicesiteprobs, intron)) ->acceptorsiteprob; }
/* * Copyright 2013 The Android Open Source Project * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Google Inc. 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 Google 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 Google Inc. 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 <string.h> #include "./mincrypt/dsa_sig.h" #include "./mincrypt/p256.h" /** * Trims off the leading zero bytes and copy it to a buffer aligning it to the end. */ static inline int trim_to_p256_bytes(unsigned char dst[P256_NBYTES], unsigned char *src, int src_len) { int dst_offset; while (*src == '\0' && src_len > 0) { src++; src_len--; } if (src_len > P256_NBYTES || src_len < 1) { return 0; } dst_offset = P256_NBYTES - src_len; memset(dst, 0, dst_offset); memcpy(dst + dst_offset, src, src_len); return 1; } /** * Unpacks the ASN.1 DSA signature sequence. */ int dsa_sig_unpack(unsigned char* sig, int sig_len, p256_int* r_int, p256_int* s_int) { /* * Structure is: * 0x30 0xNN SEQUENCE + s_length * 0x02 0xNN INTEGER + r_length * 0xAA 0xBB .. r_length bytes of "r" (offset 4) * 0x02 0xNN INTEGER + s_length * 0xMM 0xNN .. s_length bytes of "s" (offset 6 + r_len) */ int seq_len; unsigned char r_bytes[P256_NBYTES]; unsigned char s_bytes[P256_NBYTES]; int r_len; int s_len; memset(r_bytes, 0, sizeof(r_bytes)); memset(s_bytes, 0, sizeof(s_bytes)); /* * Must have at least: * 2 bytes sequence header and length * 2 bytes R integer header and length * 1 byte of R * 2 bytes S integer header and length * 1 byte of S * * 8 bytes total */ if (sig_len < 8 || sig[0] != 0x30 || sig[2] != 0x02) { return 0; } seq_len = sig[1]; if ((seq_len <= 0) || (seq_len + 2 != sig_len)) { return 0; } r_len = sig[3]; /* * Must have at least: * 2 bytes for R header and length * 2 bytes S integer header and length * 1 byte of S */ if ((r_len < 1) || (r_len > seq_len - 5) || (sig[4 + r_len] != 0x02)) { return 0; } s_len = sig[5 + r_len]; /** * Must have: * 2 bytes for R header and length * r_len bytes for R * 2 bytes S integer header and length */ if ((s_len < 1) || (s_len != seq_len - 4 - r_len)) { return 0; } /* * ASN.1 encoded integers are zero-padded for positive integers. Make sure we have * a correctly-sized buffer and that the resulting integer isn't too large. */ if (!trim_to_p256_bytes(r_bytes, &sig[4], r_len) || !trim_to_p256_bytes(s_bytes, &sig[6 + r_len], s_len)) { return 0; } p256_from_bin(r_bytes, r_int); p256_from_bin(s_bytes, s_int); return 1; }
#include <pj/types.h> #include <pjsua.h> #include "../bob/types.h" #include "../bob/FastDelegate/FastDelegate.h" typedef fastdelegate::FastDelegate2<u08*,u32,u32> DelBlockPush; typedef fastdelegate::FastDelegate2<u08*,u32,u32> DelBlockPull; struct direct_port { pjmedia_port base; pjsua_conf_port_id id; pj_bool_t eof; pj_timestamp timestamp; pj_pool_t *pool; struct softphone_config *cfg; }; struct softphone_config { // DelPush dst; // DelPull src; DelBlockPush push; DelBlockPull pull; bool available; pjsua_transport_id transp_id; pjsua_acc_id acc_id; }; #ifdef _WINDLL #define DLL_CALL __declspec(dllexport) #else #pragma comment(lib, "softphone.lib") #define DLL_CALL __declspec(dllimport) #endif int DLL_CALL softphone_init( struct softphone_config *csip ); int DLL_CALL softphone_listen(); int DLL_CALL softphone_connect( const char *account ); int DLL_CALL softphone_connect( char *domain, char *username, char *password ); int DLL_CALL softphone_destroy();
/*! \file * Contains the definition of an opaque data structure that contains raw * configuration information for a clock group. */ /****************************************************************************** * * Copyright 2013 Altera Corporation. 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. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "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 AUTHOR 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. * ******************************************************************************/ #ifndef __ALT_CLK_GRP_H__ #define __ALT_CLK_GRP_H__ #include "hwlib.h" #include "socal/alt_clkmgr.h" #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /*! This type definition enumerates the clock groups */ typedef enum ALT_CLK_GRP_e { ALT_MAIN_PLL_CLK_GRP, /*!< Main PLL clock group */ ALT_PERIPH_PLL_CLK_GRP, /*!< Peripheral PLL clock group */ ALT_SDRAM_PLL_CLK_GRP /*!< SDRAM PLL clock group */ } ALT_CLK_GRP_t; /*! This type definition defines an opaque data structure for holding the * configuration settings for a complete clock group. */ typedef struct ALT_CLK_GROUP_RAW_CFG_s { uint32_t verid; /*!< SoC FPGA version identifier. This field * encapsulates the silicon identifier and * version information associated with this * clock group configuration. It is used to * assert that this clock group configuration * is valid for this device. */ uint32_t siliid2; /*!< Reserved register - reserved for future * device IDs or capability flags/ */ ALT_CLK_GRP_t clkgrpsel; /*!< Clock group union discriminator */ /*! This union holds the raw register values for configuration of the set of * possible clock groups on the SoC FPGA. The \e clkgrpsel discriminator * identifies the valid clock group union data member. */ union ALT_CLK_GROUP_RAW_CFG_u { ALT_CLKMGR_MAINPLL_t mainpllgrp; /*!< Raw clock group configuration for Main PLL group */ ALT_CLKMGR_PERPLL_t perpllgrp; /*!< Raw clock group configuration for Peripheral PLL group */ ALT_CLKMGR_SDRPLL_t sdrpllgrp; /*!< Raw clock group configuration for SDRAM PLL group */ } clkgrp; } ALT_CLK_GROUP_RAW_CFG_t; #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* __ALT_CLK_GRP_H__ */
/* * SOURCE: pktgen-main.c * STUB: pktgen.h rte_cycles.h rte_debug.h rte_eal.h rte_timer.h cmdline.h * STUB: l2p.h pcap.h pktgen-display.h copyright_info.h * STUB: port_config.h rte_pci.h lua-socket.h pktgen-port-cfg.h * STUB: rte_launch.h pktgen-cmds.h commands.h pktgen-log.h */ #include <scrn.h> scrn_t *scrn = NULL; /* scrn.h function stub */ void scrn_printf(int16_t r, int16_t c, const char *fmt, ...) { } #include "pktgen.h" pktgen_t pktgen; int rte_cycles_vmware_tsc_map; enum timer_source eal_timer_source; __thread unsigned per_lcore__lcore_id; struct rte_logs rte_logs; /* Stub functions for rte_ethdev.h. The genstub script has difficulties parsing * that header file correctly. */ int rte_igb_pmd_init(void) { return 0; } int rte_igbvf_pmd_init(void) { return 0; } int rte_em_pmd_init(void) { return 0; } int rte_ixgbe_pmd_init(void) { return 0; } int rte_ixgbevf_pmd_init(void) { return 0; } int rte_virtio_pmd_init(void) { return 0; } int rte_vmxnet3_pmd_init(void) { return 0; } /* Stub functions for rte_log.h. Functions declared with __attribute__(())'s * are not parsed correctly. */ int rte_log(uint32_t level, uint32_t logtype, const char *format, ...) { return 0; } /* Stub functions for rte_errno.h. The genstub script has difficulties parsing * that header file correctly. */ const char * rte_strerror(int errnum) { return NULL; } /* Test driver */ int main(void) { plan(1); ok(1, "ok works"); done_testing(); return 0; }
#pragma once /* * Copyright (C) 2011 Pulse-Eight * http://www.pulse-eight.com/ * * This Program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This Program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with XBMC; see the file COPYING. If not, write to * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. * http://www.gnu.org/copyleft/gpl.html * */ #include "libXBMC_addon.h" #include "libXBMC_pvr.h" extern bool m_bCreated; extern std::string g_strUserPath; extern std::string g_strClientPath; extern ADDON::CHelper_libXBMC_addon *XBMC; extern CHelper_libXBMC_pvr *PVR;
#ifndef _ARM_IPCCONST_H_ #define _ARM_IPCCONST_H_ #define KERVEC 32 /* syscall trap to kernel */ #define IPCVEC 33 /* ipc trap to kernel */ #define IPC_STATUS_REG r1 #endif /* _ARM_IPCCONST_H_ */
/* * COPYRIGHT (c) 1989-2009. * On-Line Applications Research Corporation (OAR). * * The license and distribution terms for this file may be * found in the file LICENSE in this distribution or at * http://www.rtems.com/license/LICENSE. */ #if HAVE_CONFIG_H #include "config.h" #endif #include <pthread.h> #include <rtems/system.h> #include <rtems/score/thread.h> #include <rtems/posix/cancel.h> #include <rtems/posix/pthread.h> void _POSIX_Thread_Evaluate_cancellation_and_enable_dispatch( Thread_Control *the_thread ) { POSIX_API_Control *thread_support; thread_support = the_thread->API_Extensions[ THREAD_API_POSIX ]; if ( thread_support->cancelability_state == PTHREAD_CANCEL_ENABLE && thread_support->cancelability_type == PTHREAD_CANCEL_ASYNCHRONOUS && thread_support->cancelation_requested ) { _Thread_Unnest_dispatch(); _POSIX_Thread_Exit( the_thread, PTHREAD_CANCELED ); } else _Thread_Enable_dispatch(); }
#pragma once namespace cnc { struct PairHash { template <typename T, typename U> std::size_t operator() (const std::pair<T, U>& x) const { return std::hash<T>()(x.first) ^ std::hash<U>()(x.second); } }; }
/* Copyright Statement: * * This software/firmware and related documentation ("MediaTek Software") are * protected under relevant copyright laws. The information contained herein * is confidential and proprietary to MediaTek Inc. and/or its licensors. * Without the prior written permission of MediaTek inc. and/or its licensors, * any reproduction, modification, use or disclosure of MediaTek Software, * and information contained herein, in whole or in part, shall be strictly prohibited. * * MediaTek Inc. (C) 2010. All rights reserved. * * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON * AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT. * NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR * SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES * CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND * CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE, * AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE, * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO * MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. * * The following software/firmware and/or related documentation ("MediaTek Software") * have been modified by MediaTek Inc. All revisions are subject to any receiver's * applicable license agreements with MediaTek Inc. */ /* * Copyright 2008 Extreme Engineering Solutions, Inc. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this software; if not, write to the * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef __MINGW_SUPPORT_H_ #define __WINGW_SUPPORT_H_ 1 /* Defining __INSIDE_MSYS__ helps to prevent u-boot/mingw overlap */ #define __INSIDE_MSYS__ 1 #include <windows.h> /* mmap protections */ #define PROT_READ 0x1 /* Page can be read */ #define PROT_WRITE 0x2 /* Page can be written */ #define PROT_EXEC 0x4 /* Page can be executed */ #define PROT_NONE 0x0 /* Page can not be accessed */ /* Sharing types (must choose one and only one of these) */ #define MAP_SHARED 0x01 /* Share changes */ #define MAP_PRIVATE 0x02 /* Changes are private */ /* Windows 64-bit access macros */ #define LODWORD(x) ((DWORD)((DWORDLONG)(x))) #define HIDWORD(x) ((DWORD)(((DWORDLONG)(x) >> 32) & 0xffffffff)) typedef UINT uint; typedef ULONG ulong; int fsync(int fd); void *mmap(void *, size_t, int, int, int, int); int munmap(void *, size_t); char *strtok_r(char *s, const char *delim, char **save_ptr); #include "getline.h" #endif /* __MINGW_SUPPORT_H_ */
#include <linux/module.h> #include <linux/vermagic.h> #include <linux/compiler.h> MODULE_INFO(vermagic, VERMAGIC_STRING); struct module __this_module __attribute__((section(".gnu.linkonce.this_module"))) = { .name = KBUILD_MODNAME, .init = init_module, #ifdef CONFIG_MODULE_UNLOAD .exit = cleanup_module, #endif .arch = MODULE_ARCH_INIT, }; static const struct modversion_info ____versions[] __used __attribute__((section("__versions"))) = { { 0xb76c596d, "module_layout" }, { 0xfb06a4dc, "register_nls" }, { 0xfcc2a43c, "utf32_to_utf8" }, { 0xb2682405, "utf8_to_utf32" }, { 0xefd6cf06, "__aeabi_unwind_cpp_pr0" }, { 0xb5ea4092, "unregister_nls" }, }; static const char __module_depends[] __used __attribute__((section(".modinfo"))) = "depends=";
// FILE: mystring.h // CLASS PROVIDED: string // This is a simple version of the Standard Library string. // It is part of the namespace main_savitch_4, from the textbook // "Data Structures and Other Objects Using C++" // by Michal Main and Walter Savitch // // CONSTRUCTOR for the string class: // string(const char str[ ] = "") -- default argument is the empty string. // Precondition: str is an ordinary null-terminated string. // Postcondition: The string contains the sequence of chars from str. // // CONSTANT MEMBER FUNCTIONS for the string class: // size_t length( ) const // Postcondition: The return value is the number of characters in the // string. // // char operator [ ](size_t position) const // Precondition: position < length( ). // Postcondition: The value returned is the character at the specified // position of the string. A string's positions start from 0 at the start // of the sequence and go up to length( )-1 at the right end. // // MODIFICATION MEMBER FUNCTIONS for the string class: // void operator +=(const string& addend) // Postcondition: addend has been catenated to the end of the string. // // void operator +=(const char addend[ ]) // Precondition: addend is an ordinary null-terminated string. // Postcondition: addend has been catenated to the end of the string. // // void operator +=(char addend) // Postcondition: The single character addend has been catenated to the // end of the string. // // void reserve(size_t n) // Postcondition: All functions will now work efficiently (without // allocating new memory) until n characters are in the string. // // NON-MEMBER FUNCTIONS for the string class: // string operator +(const string& s1, const string& s2) // Postcondition: The string returned is the catenation of s1 and s2. // // istream& operator >>(istream& ins, string& target) // Postcondition: A string has been read from the istream ins, and the // istream ins is then returned by the function. The reading operation // skips white space (i.e., blanks, newlines, tabs) at the start of ins. // Then the string is read up to the next white space or the end of the // file. The white space character that terminates the string has not // been read. // // ostream& operator <<(ostream& outs, const string& source) // Postcondition: The sequence of characters in source has been written // to outs. The return value is the ostream outs. // // void getline(istream& ins, string& target, char delimiter) // Postcondition: A string has been read from the istream ins. The reading // operation starts by skipping any white space, then reading all characters // (including white space) until the delimiter is read and discarded (but // not added to the end of the string). The return value is ins. // // VALUE SEMANTICS for the string class: // Assignments and the copy constructor may be used with string objects. // // TOTAL ORDER SEMANTICS for the string class: // The six comparison operators (==, !=, >=, <=, >, and <) are implemented // for the string class, forming a total order semantics, using the usual // lexicographic order on strings. // // DYNAMIC MEMORY usage by the string class: // If there is insufficient dynamic memory then the following functions call // new_handler: The constructors, resize, operator +=, operator +, and the // assignment operator. #ifndef MAIN_SAVITCH_CHAPTER4_MYSTRING_H #define MAIN_SAVITCH_CHAPTER4_MYSTRING_H #include <cstdlib> // Provides size_t namespace main_savitch_4 { class string { public: // CONSTRUCTORS and DESTRUCTOR string(const char str[ ] = ""); string(const string& source); ~string( ); // MODIFICATION MEMBER FUNCTIONS void operator +=(const string& addend); void operator +=(const char addend[ ]); void operator +=(char addend); void reserve(size_t n); void operator =(const string& source); // CONSTANT MEMBER FUNCTIONS size_t length( ) const { return current_length; } char operator [ ](size_t position) const; // FRIEND FUNCTIONS friend ostream& operator <<(ostream& outs, const string& source); friend bool operator ==(const string& s1, const string& s2); friend bool operator !=(const string& s1, const string& s2); friend bool operator >=(const string& s1, const string& s2); friend bool operator <=(const string& s1, const string& s2); friend bool operator > (const string& s1, const string& s2); friend bool operator < (const string& s1, const string& s2); private: char *sequence; size_t allocated; size_t current_length; }; // NON-MEMBER FUNCTIONS for the string class string operator +(const string& s1, const string& s2); istream& operator >>(istream& ins, string& target); void getline(istream& ins, string& target, char delimiter); } #endif
#ifndef INCREMENTCUSTOMERSTOPREQUEST_H #define INCREMENTCUSTOMERSTOPREQUEST_H #include <TaoApiCpp/TaoRequest.h> #include <TaoApiCpp/TaoParser.h> #include <TaoApiCpp/response/IncrementCustomerStopResponse.h> /** * TOP API: 供应用关闭其用户的增量消息服务功能,这样可以节省ISV的流量。 * * @author sd44 <sd44sdd44@yeah.net> */ class IncrementCustomerStopRequest : public TaoRequest { public: virtual QString getApiMethodName() const; QString getNick() const ; void setNick (QString nick); QString getType() const ; void setType (QString type); virtual IncrementCustomerStopResponse *getResponseClass(const QString &session = "", const QString &accessToken = ""); private: /** * @brief 应用要关闭增量消息服务的用户昵称 **/ QString nick; /** * @brief 应用需要关闭用户的功能。取值可为get,notify和syn分别表示增量api取消息,主动发送消息和同步数据功能。用户关闭相应功能前,需应用已为用户经开通了相应的功能。这三个参数可无序任意组合。在关闭时,type里面的参数会根据应用订阅的类型进行相应的过虑。如应用只订阅主动通知,则默认值过滤后为get,notify,如果应用只订阅数据同步服务,默认值过滤后为syn。 **/ QString type; }; #endif /* INCREMENTCUSTOMERSTOPREQUEST_H */
/* SPDX-License-Identifier: LGPL-2.1+ */ #pragma once #include "sd-netlink.h" #include "util.h" int rtnl_message_new_synthetic_error(sd_netlink *rtnl, int error, uint32_t serial, sd_netlink_message **ret); uint32_t rtnl_message_get_serial(sd_netlink_message *m); void rtnl_message_seal(sd_netlink_message *m); static inline bool rtnl_message_type_is_neigh(uint16_t type) { return IN_SET(type, RTM_NEWNEIGH, RTM_GETNEIGH, RTM_DELNEIGH); } static inline bool rtnl_message_type_is_route(uint16_t type) { return IN_SET(type, RTM_NEWROUTE, RTM_GETROUTE, RTM_DELROUTE); } static inline bool rtnl_message_type_is_link(uint16_t type) { return IN_SET(type, RTM_NEWLINK, RTM_SETLINK, RTM_GETLINK, RTM_DELLINK); } static inline bool rtnl_message_type_is_addr(uint16_t type) { return IN_SET(type, RTM_NEWADDR, RTM_GETADDR, RTM_DELADDR); } static inline bool rtnl_message_type_is_addrlabel(uint16_t type) { return IN_SET(type, RTM_NEWADDRLABEL, RTM_DELADDRLABEL, RTM_GETADDRLABEL); } static inline bool rtnl_message_type_is_routing_policy_rule(uint16_t type) { return IN_SET(type, RTM_NEWRULE, RTM_DELRULE, RTM_GETRULE); } int rtnl_set_link_name(sd_netlink **rtnl, int ifindex, const char *name); int rtnl_set_link_properties(sd_netlink **rtnl, int ifindex, const char *alias, const struct ether_addr *mac, uint32_t mtu); int rtnl_log_parse_error(int r); int rtnl_log_create_error(int r);
#ifndef PRIMITIVEEMITER_H #define PRIMITIVEEMITER_H #include "Emiter.h" #include <glm/glm.hpp> #include "Particle.h" class PrimitiveEmiter : public Emiter { public: PrimitiveEmiter (); Particle* GetParticle (); protected: virtual glm::vec3 GetParticlePosition (); }; #endif
/** * Port of the KSPIO code (c) by 'zitronen' to AVR C * http://forum.kerbalspaceprogram.com/threads/66393 * * Zitronen's code is released under Creative Commons Attribution (BY). * The same is true for my port. * * Zitronen's code was based around the Arduino library and * mostly intended as a demonstration, to get people started. * * I'm porting this to AVR's variant of C to shrink things down * and speed it up a little bit. Other than that, the code is * unaltered. * * This port is based off of the "KSPIODemo8" and expects to * be communicating with v0.15.3 of the KSPIO plugin. * * @author Dominique Stender <dst@st-webdevelopment.com> */ #ifndef KSPIO_H #define KSPIO_H // structs typedef struct { uint8_t id; //1 float AP; //2 float PE; //3 float SemiMajorAxis; //4 float SemiMinorAxis; //5 float VVI; //6 float e; //7 float inc; //8 float G; //9 int32_t TAp; //10 int32_t TPe; //11 float TrueAnomaly; //12 float Density; //13 int32_t period; //14 float RAlt; //15 float Alt; //16 float Vsurf; //17 float Lat; //18 float Lon; //19 float LiquidFuelTot; //20 float LiquidFuel; //21 float OxidizerTot; //22 float Oxidizer; //23 float EChargeTot; //24 float ECharge; //25 float MonoPropTot; //26 float MonoProp; //27 float IntakeAirTot; //28 float IntakeAir; //29 float SolidFuelTot; //30 float SolidFuel; //31 float XenonGasTot; //32 float XenonGas; //33 float LiquidFuelTotS; //34 float LiquidFuelS; //35 float OxidizerTotS; //36 float OxidizerS; //37 uint32_t MissionTime; //38 float deltaTime; //39 float VOrbit; //40 uint32_t MNTime; //41 float MNDeltaV; //42 float Pitch; //43 float Roll; //44 float Heading; //45 } vesselData_t; typedef struct { uint8_t id; uint8_t M1; uint8_t M2; uint8_t M3; } handShakePacket_t; typedef struct { uint8_t id; uint8_t MainControls; //SAS RCS Lights Gear Brakes Precision Abort Stage uint8_t Mode; //0 = stage, 1 = docking, 2 = map uint16_t ControlGroup; //control groups 1-10 in 2 bytes uint8_t AdditionalControlByte1; //other stuff uint8_t AdditionalControlByte2; int16_t Pitch; //-1000 -> 1000 int16_t Roll; //-1000 -> 1000 int16_t Yaw; //-1000 -> 1000 int16_t TX; //-1000 -> 1000 int16_t TY; //-1000 -> 1000 int16_t TZ; //-1000 -> 1000 int16_t Throttle; // 0 -> 1000 } controlPacket_t; extern vesselData_t kspio_vData; extern void kspio_init(); extern int8_t kspio_input(); void kspio_initTXPackets(); void kspio_handshake(); uint8_t kspio_boardReceiveData(); void kspio_boardSendData(uint8_t * address, uint8_t len); #endif // KSPIO_H
#include "QMIThread.h" #include <sys/time.h> #if defined(__STDC__) #include <stdarg.h> #define __V(x) x #else #include <varargs.h> #define __V(x) (va_alist) va_dcl #define const #define volatile #endif #ifdef ANDROID #define LOG_TAG "NDIS" #include "../ql-log.h" #else #include <syslog.h> #endif int debug = 0; #ifndef ANDROID //defined in atchannel.c static void setTimespecRelative(struct timespec *p_ts, long long msec) { struct timeval tv; gettimeofday(&tv, (struct timezone *) NULL); /* what's really funny about this is that I know pthread_cond_timedwait just turns around and makes this a relative time again */ p_ts->tv_sec = tv.tv_sec + (msec / 1000); p_ts->tv_nsec = (tv.tv_usec + (msec % 1000) * 1000L ) * 1000L; } int pthread_cond_timeout_np(pthread_cond_t *cond, pthread_mutex_t * mutex, unsigned msecs) { if (msecs != 0) { struct timespec ts; setTimespecRelative(&ts, msecs); return pthread_cond_timedwait(cond, mutex, &ts); } else { return pthread_cond_wait(cond, mutex); } } #endif static const char * get_time(void) { static char time_buf[68] = {0}; struct timeval tv; time_t time; suseconds_t millitm; struct tm *ti; gettimeofday (&tv, NULL); time= tv.tv_sec; millitm = (tv.tv_usec + 500) / 1000; if (millitm == 1000) { ++time; millitm = 0; } ti = localtime(&time); sprintf(time_buf, "[%02d-%02d_%02d:%02d:%02d:%03d]", ti->tm_mon+1, ti->tm_mday, ti->tm_hour, ti->tm_min, ti->tm_sec, (int)millitm); return time_buf; } FILE *logfilefp = NULL; static pthread_mutex_t printfMutex = PTHREAD_MUTEX_INITIALIZER; static char line[1024]; void dbg_time (const char *fmt, ...) { va_list args; va_start(args, fmt); pthread_mutex_lock(&printfMutex); #ifdef ANDROID vsnprintf(line, sizeof(line), fmt, args); RLOGD("%s", line); #else #ifdef LINUX_RIL_SHLIB line[0] = '\0'; #else snprintf(line, sizeof(line), "%s ", get_time()); #endif vsnprintf(line + strlen(line), sizeof(line) - strlen(line), fmt, args); fprintf(stdout, "%s\n", line); #endif if (logfilefp) { fprintf(logfilefp, "%s\n", line); } pthread_mutex_unlock(&printfMutex); } const int i = 1; #define is_bigendian() ( (*(char*)&i) == 0 ) USHORT le16_to_cpu(USHORT v16) { USHORT tmp = v16; if (is_bigendian()) { unsigned char *s = (unsigned char *)(&v16); unsigned char *d = (unsigned char *)(&tmp); d[0] = s[1]; d[1] = s[0]; } return tmp; } UINT le32_to_cpu (UINT v32) { UINT tmp = v32; if (is_bigendian()) { unsigned char *s = (unsigned char *)(&v32); unsigned char *d = (unsigned char *)(&tmp); d[0] = s[3]; d[1] = s[2]; d[2] = s[1]; d[3] = s[0]; } return tmp; } UINT ql_swap32(UINT v32) { UINT tmp = v32; { unsigned char *s = (unsigned char *)(&v32); unsigned char *d = (unsigned char *)(&tmp); d[0] = s[3]; d[1] = s[2]; d[2] = s[1]; d[3] = s[0]; } return tmp; } USHORT cpu_to_le16(USHORT v16) { USHORT tmp = v16; if (is_bigendian()) { unsigned char *s = (unsigned char *)(&v16); unsigned char *d = (unsigned char *)(&tmp); d[0] = s[1]; d[1] = s[0]; } return tmp; } UINT cpu_to_le32 (UINT v32) { UINT tmp = v32; if (is_bigendian()) { unsigned char *s = (unsigned char *)(&v32); unsigned char *d = (unsigned char *)(&tmp); d[0] = s[3]; d[1] = s[2]; d[2] = s[1]; d[3] = s[0]; } return tmp; }
/* IP-related user commands */ #include <stdio.h> #include <string.h> #include "global.h" #include "mbuf.h" #include "internet.h" #include "timer.h" #include "netuser.h" #include "iface.h" #include "ip.h" #include "cmdparse.h" int doipaddr(),doipstat(),dottl(); extern char badhost[]; struct cmds ipcmds[] = { "address", doipaddr, 0, NULLCHAR, NULLCHAR, "status", doipstat, 0, NULLCHAR, NULLCHAR, "ttl", dottl, 0, NULLCHAR, NULLCHAR, NULLCHAR, NULLFP, 0, "ip subcommands: address status ttl", NULLCHAR, }; doip(argc,argv) int argc; char *argv[]; { return subcmd(ipcmds,argc,argv); } int doipaddr(argc,argv) int argc; char *argv[]; { char *inet_ntoa(); int32 n; if(argc < 2) { printf("%s\n",inet_ntoa(ip_addr)); } else if((n = resolve(argv[1])) == 0){ printf(badhost,argv[1]); return 1; } else ip_addr = n; return 0; } int dottl(argc,argv) char *argv[]; { if(argc < 2) printf("%u\n",uchar(ip_ttl)); else ip_ttl = atoi(argv[1]); return 0; } /* "route" subcommands */ int doadd(),dodrop(); static struct cmds rtcmds[] = { "add", doadd, 3, "route add <dest addr>[/<bits>] <if name> [gateway] [metric]", "Add failed", "drop", dodrop, 2, "route drop <dest addr>[/<bits>]", "Not in table", NULLCHAR, NULLFP, 0, "route subcommands: add, drop", NULLCHAR, }; /* Display and/or manipulate routing table */ int doroute(argc,argv) int argc; char *argv[]; { if(argc < 2){ dumproute(); return 0; } return subcmd(rtcmds,argc,argv); } /* Add an entry to the routing table * E.g., "add 1.2.3.4 ax0 5.6.7.8 3" */ int doadd(argc,argv) int argc; char *argv[]; { struct interface *ifp; int32 dest,gateway; unsigned bits; char *bitp; int metric; if(strcmp(argv[1],"default") == 0){ dest = 0; bits = 0; } else { if((dest = resolve(argv[1])) == 0){ printf(badhost,argv[1]); return 1; } /* If IP address is followed by an optional slash and * a length field, (e.g., 128.96/16) get it; * otherwise assume a full 32-bit address */ if((bitp = index(argv[1],'/')) != NULLCHAR){ bitp++; bits = atoi(bitp); } else bits = 32; } for(ifp=ifaces;ifp != NULLIF;ifp = ifp->next){ if(strcmp(argv[2],ifp->name) == 0) break; } if(ifp == NULLIF){ printf("Interface \"%s\" unknown\n",argv[2]); return 1; } if(argc > 3){ if((gateway = resolve(argv[3])) == 0){ printf(badhost,argv[3]); return 1; } } else { gateway = 0; } if(argc > 4) metric = atoi(argv[4]); else metric = 0; rt_add(dest,bits,gateway,metric,ifp); return 0; } /* Drop an entry from the routing table * E.g., "drop 128.96/16 */ /*ARGSUSED*/ int dodrop(argc,argv) int argc; char *argv[]; { char *bitp; unsigned bits; int32 n; if(strcmp(argv[1],"default") == 0){ n = 0; bits = 0; } else { /* If IP address is followed by an optional slash and length field, * (e.g., 128.96/16) get it; otherwise assume a full 32-bit address */ if((bitp = index(argv[1],'/')) != NULLCHAR){ bitp++; bits = atoi(bitp); } else bits = 32; if((n = resolve(argv[1])) == 0){ printf(badhost,argv[1]); return 1; } } return rt_drop(n,bits); } /* Dump IP routing table * Dest Length Interface Gateway Metric * 192.001.002.003 32 sl0 192.002.003.004 4 */ int dumproute() { register unsigned int i,bits; register struct route *rp; printf("Dest Length Interface Gateway Metric\n"); if(r_default.interface != NULLIF){ printf("default 0 %-13s", r_default.interface->name); if(r_default.gateway != 0) printf("%-17s",inet_ntoa(r_default.gateway)); else printf("%-17s",""); printf("%6u\n",r_default.metric); } for(bits=1;bits<=32;bits++){ for(i=0;i<NROUTE;i++){ for(rp = routes[bits-1][i];rp != NULLROUTE;rp = rp->next){ printf("%-18s",inet_ntoa(rp->target)); printf("%-10u",bits); printf("%-13s",rp->interface->name); if(rp->gateway != 0) printf("%-17s",inet_ntoa(rp->gateway)); else printf("%-17s",""); printf("%6u\n",rp->metric); } } } return 0; } /*ARGSUSED*/ int doipstat(argc,argv) int argc; char *argv[]; { extern struct ip_stats ip_stats; extern struct reasm *reasmq; register struct reasm *rp; register struct frag *fp; char *inet_ntoa(); printf("IP: total %ld runt %u len err %u vers err %u", ip_stats.total,ip_stats.runt,ip_stats.length,ip_stats.version); printf(" chksum err %u badproto %u\n", ip_stats.checksum,ip_stats.badproto); if(reasmq != NULLREASM) printf("Reassembly fragments:\n"); for(rp = reasmq;rp != NULLREASM;rp = rp->next){ printf("src %s",inet_ntoa(rp->source)); printf(" dest %s",inet_ntoa(rp->dest)); printf(" id %u pctl %u time %lu len %u\n", rp->id,uchar(rp->protocol),rp->timer.count,rp->length); for(fp = rp->fraglist;fp != NULLFRAG;fp = fp->next){ printf(" offset %u last %u\n",fp->offset,fp->last); } } doicmpstat(); doslipstat(); return 0; }
int main(int argc, char **argv) { int i; for (i=0; i<10; i++) { } typedef int MyType; for (MyType j=0; j<10; j++) { j++; } j++; }
#include "builtin.h" #include "parse-options.h" #include "refs.h" static char const * const pack_refs_usage[] = { N_("git pack-refs [<options>]"), NULL }; int cmd_pack_refs(int argc, const char **argv, const char *prefix) { unsigned int flags = PACK_REFS_PRUNE; struct option opts[] = { OPT_BIT(0, "all", &flags, N_("pack everything"), PACK_REFS_ALL), OPT_BIT(0, "prune", &flags, N_("prune loose refs (default)"), PACK_REFS_PRUNE), OPT_END(), }; if (parse_options(argc, argv, prefix, opts, pack_refs_usage, 0)) usage_with_options(pack_refs_usage, opts); return pack_refs(flags); }
/** * @file mt_clk_buf_ctl.c * @brief Driver for RF clock buffer control * */ #ifndef __MT_CLK_BUF_CTL_H__ #define __MT_CLK_BUF_CTL_H__ #include <linux/kernel.h> #include <linux/mutex.h> #include <cust_clk_buf.h> #ifndef GPIO_RFIC0_BSI_CK #define GPIO_RFIC0_BSI_CK (GPIO68|0x80000000) /* RFIC0_BSI_CK = GPIO68 */ #endif #ifndef GPIO_RFIC0_BSI_D0 #define GPIO_RFIC0_BSI_D0 (GPIO69|0x80000000) /* RFIC0_BSI_D0 = GPIO69 */ #endif #ifndef GPIO_RFIC0_BSI_D1 #define GPIO_RFIC0_BSI_D1 (GPIO70|0x80000000) /* RFIC0_BSI_D1 = GPIO70 */ #endif #ifndef GPIO_RFIC0_BSI_D2 #define GPIO_RFIC0_BSI_D2 (GPIO71|0x80000000) /* RFIC0_BSI_D2 = GPIO71 */ #endif #ifndef GPIO_RFIC0_BSI_CS #define GPIO_RFIC0_BSI_CS (GPIO72|0x80000000) /* RFIC0_BSI_CS = GPIO72 */ #endif enum clk_buf_id{ CLK_BUF_BB = 0, CLK_BUF_6605 = 1, CLK_BUF_5193 = 2, CLK_BUF_AUDIO = 3, CLK_BUF_INVALID = 4, }; typedef enum { CLK_BUF_SW_DISABLE = 0, CLK_BUF_SW_ENABLE = 1, }CLK_BUF_SWCTRL_STATUS_T; #define CLKBUF_NUM 4 #if 0 typedef struct{ CLK_BUF_SWCTRL_STATUS_T ClkBuf_SWCtrl_Status[CLKBUF_NUM]; }CLKBUF_SWCTRL_RESULT_T; #endif #define STA_CLK_ON 1 #define STA_CLK_OFF 0 bool clk_buf_ctrl(enum clk_buf_id id,bool onoff); void clk_buf_get_swctrl_status(CLK_BUF_SWCTRL_STATUS_T *status); bool clk_buf_init(void); extern struct mutex clk_buf_ctrl_lock; //extern DEFINE_MUTEX(clk_buf_ctrl_lock); #endif
/*************************************************************************** * Copyright (C) 2010 by Kai Dombrowe <just89@gmx.de> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . * ***************************************************************************/ #ifndef RECORDITNOW_SCRIPT_H #define RECORDITNOW_SCRIPT_H // KDE #include <kplugininfo.h> // Qt #include <QtCore/QObject> #include <QtScript/QScriptValue> class QScriptEngine; namespace RecordItNow { class Script : public QObject { Q_OBJECT public: enum ScriptType { InvalidType = -1, RecorderType = 0, EncoderType = 1, UIType = 2 }; explicit Script(QObject *parent, const KPluginInfo &info); ~Script(); QScriptEngine *engine() const; KPluginInfo info() const; bool isRunning() const; QString name() const; RecordItNow::Script::ScriptType type() const; bool load(); void unload(); void addAdaptor(QObject *adaptor, const QString &name); void handleException(const QScriptValue &exception); static QString scriptFile(const KPluginInfo &info); static QByteArray scriptContent(const QString &path); private: KPluginInfo m_info; QScriptEngine *m_engine; QObject *m_importer; private slots: void signalHandlerException(const QScriptValue &exception); signals: void scriptError(const QString &error); }; } // namespace RecordItNow #endif // RECORDITNOW_SCRIPT_H