Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Add convenience function to calculate the integer representation of the version
#pragma once #include <string> struct Version { public: Version(int major = 0, int minor = 0, int revision = 0) : _major(major), _minor(minor), _revision(revision) { } const int Major() { return _major; } const int Minor() { return _minor; } const int Revision() { return _revision; } } std::wstring ToString() { return std::to_wstring(_major) + L"." + std::to_wstring(_minor) + L"." + std::to_wstring(_revision); } private: int _major; int _minor; int _revision; };
#pragma once #include <string> struct Version { public: Version(int major = 0, int minor = 0, int revision = 0) : _major(major), _minor(minor), _revision(revision) { } const int Major() { return _major; } const int Minor() { return _minor; } const int Revision() { return _revision; } unsigned int ToInt() { return (_major << 16) | (_minor << 8) | (_revision); } std::wstring ToString() { return std::to_wstring(_major) + L"." + std::to_wstring(_minor) + L"." + std::to_wstring(_revision); } private: int _major; int _minor; int _revision; };
Change server port to the correct jet port.
#ifndef CJET_CONFIG_H #define CJET_CONFIG_H #define SERVER_PORT 7899 #define LISTEN_BACKLOG 40 #define MAX_MESSAGE_SIZE 128 /* Linux specific configs */ #define MAX_EPOLL_EVENTS 100 #endif
#ifndef CJET_CONFIG_H #define CJET_CONFIG_H #define SERVER_PORT 11122 #define LISTEN_BACKLOG 40 #define MAX_MESSAGE_SIZE 128 /* Linux specific configs */ #define MAX_EPOLL_EVENTS 100 #endif
Fix linker error by changing init function names to represent module names
#include <uEye.h> #include "core.h" #if PY_MAJOR_VERSION >= 3 /* * This is only needed for Python3 * IDS module initialization * Based on https://docs.python.org/3/extending/extending.html#the-module-s-method-table-and-initialization-function */ static struct PyModuleDef idsModule = { PyModuleDef_HEAD_INIT, "ids", /* name of module */ NULL, /* module documentation */ -1, /* size of perinterpreter state of the module, or -1 if the module keeps state in global variables. */ idsMethods }; #endif #if PY_MAJOR_VERSION >= 3 PyMODINIT_FUNC PyInit_ids(void) { return PyModule_Create(&idsModule); } #else PyMODINIT_FUNC initids(void) { (void) Py_InitModule("ids", idsMethods); } #endif int main(int argc, char *argv[]) { #if PY_MAJOR_VERSION >= 3 wchar_t name[128]; mbstowcs(name, argv[0], 128); #else char name[128]; strncpy(name, argv[0], 128); #endif /* Pass argv[0] to the Pythin interpreter */ Py_SetProgramName(name); /* Initialize the Python interpreter */ Py_Initialize(); /* Add a static module */ #if PY_MAJOR_VERSION >= 3 PyInit_ids(); #else initids(); #endif }
#include <uEye.h> #include "core.h" #if PY_MAJOR_VERSION >= 3 /* * This is only needed for Python3 * IDS module initialization * Based on https://docs.python.org/3/extending/extending.html#the-module-s-method-table-and-initialization-function */ static struct PyModuleDef idsModule = { PyModuleDef_HEAD_INIT, "ids", /* name of module */ NULL, /* module documentation */ -1, /* size of perinterpreter state of the module, or -1 if the module keeps state in global variables. */ idsMethods }; #endif #if PY_MAJOR_VERSION >= 3 PyMODINIT_FUNC PyInit_core(void) { return PyModule_Create(&idsModule); } #else PyMODINIT_FUNC initcore(void) { (void) Py_InitModule("core", idsMethods); } #endif int main(int argc, char *argv[]) { #if PY_MAJOR_VERSION >= 3 wchar_t name[128]; mbstowcs(name, argv[0], 128); #else char name[128]; strncpy(name, argv[0], 128); #endif /* Pass argv[0] to the Pythin interpreter */ Py_SetProgramName(name); /* Initialize the Python interpreter */ Py_Initialize(); /* Add a static module */ #if PY_MAJOR_VERSION >= 3 PyInit_core(); #else initcore(); #endif }
Add macros for setting Endpoint buffers length,
#ifndef USB_H #define USB_H void setup_usb(); void usb_interrupt_handler(); #endif
#ifndef USB_H #define USB_H #define PHYS_ADDR(VIRTUAL_ADDR) (unsigned int)(VIRTUAL_ADDR) #define EP0_BUFLEN 8 #define EP1_BUFLEN 8 #define USB_PID_SETUP 0x0d #define USB_REQ_GET_DESCRIPTOR 0x06 #define USB_GET_DEVICE_DESCRIPTOR 0x01 #define USB_GET_CONFIG_DESCRIPTOR 0x02 #define USB_GET_STRING_DESCRIPTOR 0x03 #define USB_REQ_GET_STATUS 0x00 #define USB_REQ_SET_ADDRESS 0x05 #define USB_REQ_SET_CONFIGURATION 0x09 void reset_usb ( ); void usb_interrupt_handler ( ); bool usb_in_endpoint_busy ( uint8_t ep ); void usb_arm_in_transfert ( ); #endif
Remove static declaration of line diff
#ifndef DASHBOARD_H #define DASHBOARD_H #include <sys/types.h> #include "src/process/process.h" #include "src/system/sys_stats.h" typedef struct { int max_x; int max_y; int prev_x; int prev_y; char *fieldbar; sysaux *system; ps_node *process_list; Tree *process_tree; } Board; void print_usage(void); char set_sort_option(char *opt); void dashboard_mainloop(char attr_sort); void update_process_stats(Tree *ps_tree, ps_node *ps, sysaux *sys); static int calculate_ln_diff(Board *board, int ln, int prev_ln); Board *init_board(void); void free_board(Board *board); #endif
#ifndef DASHBOARD_H #define DASHBOARD_H #include <sys/types.h> #include "src/process/process.h" #include "src/system/sys_stats.h" typedef struct { int max_x; int max_y; int prev_x; int prev_y; char *fieldbar; sysaux *system; ps_node *process_list; Tree *process_tree; } Board; void print_usage(void); char set_sort_option(char *opt); void dashboard_mainloop(char attr_sort); void update_process_stats(Tree *ps_tree, ps_node *ps, sysaux *sys); Board *init_board(void); void free_board(Board *board); #endif
Fix for [MPLY-9800]. Doc string didn't link correctly. Buddy: Sam A.
#pragma once #import "WRLDRoutingQuery.h" #import "WRLDRoutingQueryOptions.h" NS_ASSUME_NONNULL_BEGIN /*! A service which allows you to find routes between locations. Created by the createRoutingService method of the WRLDMapView object. This is an Objective-c interface to the WRLD Routing REST API (https://github.com/wrld3d/wrld-routing-api). */ @interface WRLDRoutingService : NSObject /*! Asynchronously query the routing service. The results of the query will be passed as a WRLDRoutingQueryResponse to the routingQueryDidComplete method in WRLDMapViewDelegate. @param options The parameters of the routing query. @returns A handle to the ongoing query, which can be used to cancel it. */ - (WRLDRoutingQuery*)findRoutes:(WRLDRoutingQueryOptions*)options; @end NS_ASSUME_NONNULL_END
#pragma once #import "WRLDRoutingQuery.h" #import "WRLDRoutingQueryOptions.h" NS_ASSUME_NONNULL_BEGIN /*! A service which allows you to find routes between locations. Created by the createRoutingService method of the WRLDMapView object. This is an Objective-c interface to the [WRLD Routing REST API](https://github.com/wrld3d/wrld-routing-api). */ @interface WRLDRoutingService : NSObject /*! Asynchronously query the routing service. The results of the query will be passed as a WRLDRoutingQueryResponse to the routingQueryDidComplete method in WRLDMapViewDelegate. @param options The parameters of the routing query. @returns A handle to the ongoing query, which can be used to cancel it. */ - (WRLDRoutingQuery*)findRoutes:(WRLDRoutingQueryOptions*)options; @end NS_ASSUME_NONNULL_END
Add funcoes para converter graus <-> rad
#include "local.h" float soluc(float x, float y) { float r; r = sqrt(x * x + y * y); return r; } float radians_degrees(float degrees) { return degrees*180/PI; } float degrees_radians(float radians) { return radians*PI/180; }
Reorder mm_context_t to remove x86_64 alignment padding and thus shrink mm_struct
#ifndef _ASM_X86_MMU_H #define _ASM_X86_MMU_H #include <linux/spinlock.h> #include <linux/mutex.h> /* * The x86 doesn't have a mmu context, but * we put the segment information here. */ typedef struct { void *ldt; int size; struct mutex lock; void *vdso; #ifdef CONFIG_X86_64 /* True if mm supports a task running in 32 bit compatibility mode. */ unsigned short ia32_compat; #endif } mm_context_t; #ifdef CONFIG_SMP void leave_mm(int cpu); #else static inline void leave_mm(int cpu) { } #endif #endif /* _ASM_X86_MMU_H */
#ifndef _ASM_X86_MMU_H #define _ASM_X86_MMU_H #include <linux/spinlock.h> #include <linux/mutex.h> /* * The x86 doesn't have a mmu context, but * we put the segment information here. */ typedef struct { void *ldt; int size; #ifdef CONFIG_X86_64 /* True if mm supports a task running in 32 bit compatibility mode. */ unsigned short ia32_compat; #endif struct mutex lock; void *vdso; } mm_context_t; #ifdef CONFIG_SMP void leave_mm(int cpu); #else static inline void leave_mm(int cpu) { } #endif #endif /* _ASM_X86_MMU_H */
Add xcb headers to linux platform, needed for vulkan
/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2015 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #ifndef XENIA_BASE_PLATFORM_X11_H_ #define XENIA_BASE_PLATFORM_X11_H_ // NOTE: if you're including this file it means you are explicitly depending // on Linux headers. Including this file outside of linux platform specific // source code will break portability #include "xenia/base/platform.h" // Xlib is used only for GLX interaction, the window management and input // events are done with gtk/gdk #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/Xos.h> //Used for window management. Gtk is for GUI and wigets, gdk is for lower //level events like key presses, mouse events, etc #include <gtk/gtk.h> #include <gdk/gdk.h> #endif // XENIA_BASE_PLATFORM_X11_H_
/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2015 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #ifndef XENIA_BASE_PLATFORM_X11_H_ #define XENIA_BASE_PLATFORM_X11_H_ // NOTE: if you're including this file it means you are explicitly depending // on Linux headers. Including this file outside of linux platform specific // source code will break portability #include "xenia/base/platform.h" // Xlib/Xcb is used only for GLX/Vulkan interaction, the window management // and input events are done with gtk/gdk #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/Xos.h> #include <xcb/xcb.h> //Used for window management. Gtk is for GUI and wigets, gdk is for lower //level events like key presses, mouse events, etc #include <gtk/gtk.h> #include <gdk/gdk.h> #endif // XENIA_BASE_PLATFORM_X11_H_
Add Documentation for BufferLockManger, BufferRange and BufferLock.
#ifndef SRC_GRAPHICS_BUFFER_LOCK_MANAGER_H_ #define SRC_GRAPHICS_BUFFER_LOCK_MANAGER_H_ #include <vector> #include "./gl.h" namespace Graphics { struct BufferRange { size_t startOffset; size_t length; size_t endOffset() const { return startOffset + length; } bool overlaps(const BufferRange &other) const { return startOffset < other.endOffset() && other.startOffset < endOffset(); } }; struct BufferLock { BufferRange range; GLsync syncObject; }; /** * \brief * * */ class BufferLockManager { public: explicit BufferLockManager(bool runUpdatesOnCPU); ~BufferLockManager(); void initialize(Gl *gl); void waitForLockedRange(size_t lockBeginBytes, size_t lockLength); void lockRange(size_t lockBeginBytes, size_t lockLength); private: void wait(GLsync *syncObject); void cleanup(BufferLock *bufferLock); std::vector<BufferLock> bufferLocks; bool runUpdatesOnCPU; Gl *gl; }; } // namespace Graphics #endif // SRC_GRAPHICS_BUFFER_LOCK_MANAGER_H_
#ifndef SRC_GRAPHICS_BUFFER_LOCK_MANAGER_H_ #define SRC_GRAPHICS_BUFFER_LOCK_MANAGER_H_ #include <vector> #include "./gl.h" namespace Graphics { /** * \brief Encapsulates a locked buffer range * * It stores the start offset in the buffer and the length of the range. * The end offset can be retrieved with #endOffset(). * * The method #overlaps() checks if the range overlaps with the * given range. */ struct BufferRange { size_t startOffset; size_t length; size_t endOffset() const { return startOffset + length; } bool overlaps(const BufferRange &other) const { return startOffset < other.endOffset() && other.startOffset < endOffset(); } }; /** * \brief Lock on a buffer determined by \link BufferRange range \endlink and * a sync object */ struct BufferLock { BufferRange range; GLsync syncObject; }; /** * \brief Manages locks for a buffer * * Locks can be acquired with #lockRange() and #waitForLockedRange() waits until * the range is free again. */ class BufferLockManager { public: explicit BufferLockManager(bool runUpdatesOnCPU); ~BufferLockManager(); void initialize(Gl *gl); void waitForLockedRange(size_t lockBeginBytes, size_t lockLength); void lockRange(size_t lockBeginBytes, size_t lockLength); private: void wait(GLsync *syncObject); void cleanup(BufferLock *bufferLock); std::vector<BufferLock> bufferLocks; bool runUpdatesOnCPU; Gl *gl; }; } // namespace Graphics #endif // SRC_GRAPHICS_BUFFER_LOCK_MANAGER_H_
Add fallback path for Foundation lookup
#include <objc/runtime.h> #include <objc/message.h> #include <stdio.h> #include <dlfcn.h> #include <string.h> static void pyobjc_internal_init() { static void *foundation = NULL; if ( foundation == NULL ) { foundation = dlopen( "/Groups/System/Library/Frameworks/Foundation.framework/Versions/Current/Foundation", RTLD_LAZY); if ( foundation == NULL ) { printf("Got dlopen error on Foundation\n"); return; } } } id allocAndInitAutoreleasePool() { Class NSAutoreleasePoolClass = (Class)objc_getClass("NSAutoreleasePool"); id pool = class_createInstance(NSAutoreleasePoolClass, 0); return objc_msgSend(pool, sel_registerName("init")); } void drainAutoreleasePool(id pool) { (void)objc_msgSend(pool, sel_registerName("drain")); }
#include <objc/runtime.h> #include <objc/message.h> #include <stdio.h> #include <dlfcn.h> #include <string.h> static void pyobjc_internal_init() { static void *foundation = NULL; if ( foundation == NULL ) { foundation = dlopen( "/System/Library/Frameworks/Foundation.framework/Versions/Current/Foundation", RTLD_LAZY); if ( foundation == NULL ) { foundation = dlopen( "/Groups/System/Library/Frameworks/Foundation.framework/Versions/Current/Foundation", RTLD_LAZY); if ( foundation == NULL ) { printf("Got dlopen error on Foundation\n"); return; } } } } id allocAndInitAutoreleasePool() { Class NSAutoreleasePoolClass = (Class)objc_getClass("NSAutoreleasePool"); id pool = class_createInstance(NSAutoreleasePoolClass, 0); return objc_msgSend(pool, sel_registerName("init")); } void drainAutoreleasePool(id pool) { (void)objc_msgSend(pool, sel_registerName("drain")); }
Refactor STMRecordingOverlayDelegate to inherit from CreateShoutDelegate
// // STMRecordingOverlayViewController.h // Pods // // Created by Tyler Clemens on 9/14/15. // // #import <UIKit/UIKit.h> #import "VoiceCmdView.h" @protocol STMRecordingOverlayDelegate; @interface STMRecordingOverlayViewController : UIViewController<VoiceCmdViewDelegate, SendShoutDelegate> @property (atomic) id<STMRecordingOverlayDelegate> delegate; @property double MaxListeningSeconds; @property NSString *tags; @property NSString *topic; -(void)userRequestsStopListening; -(id)initWithTags:(NSString *)tags andTopic:(NSString *)topic; @end @protocol STMRecordingOverlayDelegate <NSObject> -(void)shoutCreated:(STMShout*)shout error:(NSError*)err; -(void)overlayClosed:(BOOL)bDismissed; @end
// // STMRecordingOverlayViewController.h // Pods // // Created by Tyler Clemens on 9/14/15. // // #import <UIKit/UIKit.h> #import "VoiceCmdView.h" @protocol STMRecordingOverlayDelegate <CreateShoutDelegate> -(void)overlayClosed:(BOOL)bDismissed; @end @interface STMRecordingOverlayViewController : UIViewController<VoiceCmdViewDelegate, SendShoutDelegate> @property (atomic) id<STMRecordingOverlayDelegate> delegate; @property double MaxListeningSeconds; @property NSString *tags; @property NSString *topic; -(void)userRequestsStopListening; -(id)initWithTags:(NSString *)tags andTopic:(NSString *)topic; @end
Increase the asynchronous testing timeout
// // AsyncTesting.h // ContentfulSDK // // Created by Boris Bügling on 05/03/14. // // // Set the flag for a block completion handler #define StartBlock() __block BOOL waitingForBlock = YES // Set the flag to stop the loop #define EndBlock() waitingForBlock = NO // Wait and loop until flag is set #define WaitUntilBlockCompletes() WaitWhile(waitingForBlock) // Macro - Wait for condition to be NO/false in blocks and asynchronous calls #define WaitWhile(condition) \ do { \ NSDate* __startTime = [NSDate date]; \ while(condition) { \ [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; \ if ([[NSDate date] timeIntervalSinceDate:__startTime] > 20.0) { \ XCTAssertFalse(true, @"Asynchronous test timed out."); \ break; \ } \ } \ } while(0)
// // AsyncTesting.h // ContentfulSDK // // Created by Boris Bügling on 05/03/14. // // // Set the flag for a block completion handler #define StartBlock() __block BOOL waitingForBlock = YES // Set the flag to stop the loop #define EndBlock() waitingForBlock = NO // Wait and loop until flag is set #define WaitUntilBlockCompletes() WaitWhile(waitingForBlock) // Macro - Wait for condition to be NO/false in blocks and asynchronous calls #define WaitWhile(condition) \ do { \ NSDate* __startTime = [NSDate date]; \ while(condition) { \ [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]]; \ if ([[NSDate date] timeIntervalSinceDate:__startTime] > 30.0) { \ XCTAssertFalse(true, @"Asynchronous test timed out."); \ break; \ } \ } \ } while(0)
Fix clang's stupid warning to work around a bug in OS X headers...
#ifndef _OBJC_MESSAGE_H_ #define _OBJC_MESSAGE_H_ #if defined(__x86_64) || defined(__i386) || defined(__arm__) || \ defined(__mips_n64) || defined(__mips_n32) /** * Standard message sending function. This function must be cast to the * correct types for the function before use. The first argument is the * receiver and the second the selector. * * Note that this function is not available on all architectures. For a more * portable solution to sending arbitrary messages, consider using * objc_msg_lookup_sender() and then calling the returned IMP directly. * * This version of the function is used for all messages that return either an * integer, a pointer, or a small structure value that is returned in * registers. Be aware that calling conventions differ between operating * systems even within the same architecture, so take great care if using this * function for small (two integer) structures. */ id objc_msgSend(id self, SEL _cmd, ...); /** * Standard message sending function. This function must be cast to the * correct types for the function before use. The first argument is the * receiver and the second the selector. * * Note that this function is not available on all architectures. For a more * portable solution to sending arbitrary messages, consider using * objc_msg_lookup_sender() and then calling the returned IMP directly. * * This version of the function is used for all messages that return a * structure that is not returned in registers. Be aware that calling * conventions differ between operating systems even within the same * architecture, so take great care if using this function for small (two * integer) structures. */ #ifdef __cplusplus id objc_msgSend_stret(id self, SEL _cmd, ...); #else void objc_msgSend_stret(id self, SEL _cmd, ...); #endif /** * Standard message sending function. This function must be cast to the * correct types for the function before use. The first argument is the * receiver and the second the selector. * * Note that this function is not available on all architectures. For a more * portable solution to sending arbitrary messages, consider using * objc_msg_lookup_sender() and then calling the returned IMP directly. * * This version of the function is used for all messages that return floating * point values. */ long double objc_msgSend_fpret(id self, SEL _cmd, ...); #endif #endif //_OBJC_MESSAGE_H_
Add flag byte to packet structure.
#ifndef RADIO_H_INCLUDED #define RADIO_H_INCLUDED #include <stdint.h> #define RADIO_PACKET_MAX_LEN 64 #define RADIO_PACKET_BUFFER_SIZE 1 typedef enum { PACKET_RECEIVED, } radio_evt_type_t; typedef struct { uint8_t len; uint8_t data[RADIO_PACKET_MAX_LEN]; } radio_packet_t; typedef struct { radio_evt_type_t type; union { radio_packet_t packet; }; } radio_evt_t; typedef void (radio_evt_handler_t)(radio_evt_t * evt); uint32_t radio_init(radio_evt_handler_t * evt_handler); uint32_t radio_send(radio_packet_t * packet); uint32_t radio_receive_start(void); #endif
#ifndef RADIO_H_INCLUDED #define RADIO_H_INCLUDED #include <stdint.h> #define RADIO_PACKET_MAX_LEN 64 #define RADIO_PACKET_BUFFER_SIZE 1 typedef enum { PACKET_RECEIVED, } radio_evt_type_t; typedef struct { uint8_t len; struct __attribute__((packed)) { uint8_t padding : 7; uint8_t ack : 1; } flags; uint8_t data[RADIO_PACKET_MAX_LEN]; } radio_packet_t; typedef struct { radio_evt_type_t type; union { radio_packet_t packet; }; } radio_evt_t; typedef void (radio_evt_handler_t)(radio_evt_t * evt); uint32_t radio_init(radio_evt_handler_t * evt_handler); uint32_t radio_send(radio_packet_t * packet); uint32_t radio_receive_start(void); #endif
Change -ffp-contract=fast test to run on Aarch64
// RUN: %clang_cc1 -O3 -ffp-contract=fast -triple=powerpc-apple-darwin10 -S -o - %s | FileCheck %s // REQUIRES: powerpc-registered-target float fma_test1(float a, float b, float c) { // CHECK: fmadds float x = a * b; float y = x + c; return y; }
// RUN: %clang_cc1 -O3 -ffp-contract=fast -triple=aarch64-apple-darwin -S -o - %s | FileCheck %s // REQUIRES: aarch64-registered-target float fma_test1(float a, float b, float c) { // CHECK: fmadd float x = a * b; float y = x + c; return y; }
Add a missing import to fix compilation of Fruit tests.
/* * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef FRUIT_CLASS_CONSTRUCTION_TRACKER_H #define FRUIT_CLASS_CONSTRUCTION_TRACKER_H /** * This class is useful to keep track of how many instances of a given type are created during the entire program * execution. * * Example use: * class Foo : public ConstructionTracker<Foo> { * ... * }; * * int main() { * ... * assert(Foo::num_objects_constructed == 3); * } */ template <typename T> struct ConstructionTracker { static std::size_t num_objects_constructed; ConstructionTracker() { ++num_objects_constructed; } }; template <typename T> std::size_t ConstructionTracker<T>::num_objects_constructed = 0; #endif // FRUIT_CLASS_CONSTRUCTION_TRACKER_H
/* * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef FRUIT_CLASS_CONSTRUCTION_TRACKER_H #define FRUIT_CLASS_CONSTRUCTION_TRACKER_H #include <cstddef> /** * This class is useful to keep track of how many instances of a given type are created during the entire program * execution. * * Example use: * class Foo : public ConstructionTracker<Foo> { * ... * }; * * int main() { * ... * assert(Foo::num_objects_constructed == 3); * } */ template <typename T> struct ConstructionTracker { static std::size_t num_objects_constructed; ConstructionTracker() { ++num_objects_constructed; } }; template <typename T> std::size_t ConstructionTracker<T>::num_objects_constructed = 0; #endif // FRUIT_CLASS_CONSTRUCTION_TRACKER_H
Test expsplit with multiple simultaneous splits
// PARAM: --set ana.activated[+] expsplit #include <stddef.h> #include <assert.h> #include <goblint.h> int main() { int r, r2; // rand int x, y, z; __goblint_split_begin(x); __goblint_split_begin(y); if (r) { x = 1; if (r2) { y = 1; z = 1; } else { y = 2; z = 2; } } else { x = 2; if (r2) { y = 1; z = 3; } else { y = 2; z = 4; } } __goblint_check((x == 1 && y == 1 && z == 1) || (x == 1 && y == 2 && z == 2) || (x == 2 && y == 1 && z == 3) || (x == 2 && y == 2 && z == 4)); __goblint_split_end(x); __goblint_check((x == 1 && y == 1 && z == 1) || (x == 1 && y == 2 && z == 2) || (x == 2 && y == 1 && z == 3) || (x == 2 && y == 2 && z == 4)); // UNKNOWN (intentionally) __goblint_split_end(y); __goblint_check((x == 1 && y == 1 && z == 1) || (x == 1 && y == 2 && z == 2) || (x == 2 && y == 1 && z == 3) || (x == 2 && y == 2 && z == 4)); // UNKNOWN (intentionally) return 0; }
Remove first parameter of DBG()
/* See LICENSE file for copyright and license details. */ #include <sys/types.h> #ifndef NDEBUG extern int debug; #define DBG(fmt, ...) dbg(fmt, __VA_ARGS__) #define DBGON() (debug = 1) #else #define DBG(...) #define DBGON() #endif #ifndef PREFIX #define PREFIX "/usr/local/" #endif #define TINT long long #define TUINT unsigned long long #define TFLOAT double struct items { char **s; unsigned n; }; extern void die(const char *fmt, ...); extern void dbg(const char *fmt, ...); extern void newitem(struct items *items, char *item); extern void *xmalloc(size_t size); extern void *xcalloc(size_t nmemb, size_t size); extern char *xstrdup(const char *s); extern void *xrealloc(void *buff, register size_t size);
/* See LICENSE file for copyright and license details. */ #include <sys/types.h> #ifndef NDEBUG extern int debug; #define DBG(...) dbg(__VA_ARGS__) #define DBGON() (debug = 1) #else #define DBG(...) #define DBGON() #endif #ifndef PREFIX #define PREFIX "/usr/local/" #endif #define TINT long long #define TUINT unsigned long long #define TFLOAT double struct items { char **s; unsigned n; }; extern void die(const char *fmt, ...); extern void dbg(const char *fmt, ...); extern void newitem(struct items *items, char *item); extern void *xmalloc(size_t size); extern void *xcalloc(size_t nmemb, size_t size); extern char *xstrdup(const char *s); extern void *xrealloc(void *buff, register size_t size);
Fix void * casting to char * warning
// cc dict_example.c dict.c #include <assert.h> #include <stdio.h> #include <string.h> #include "bool.h" #include "dict.h" int main(int argc, const char *argv[]) { /* allocate a new dict */ struct dict *dict = dict(); /* set key and values to dict */ char *key1 = "key1"; char *key2 = "key2"; char *val1 = "val1"; char *val2 = "val2"; assert(dict_set(dict, key1, strlen(key1), val1) == DICT_OK); assert(dict_set(dict, key2, strlen(key2), val2) == DICT_OK); /* get dict length */ assert(dict_len(dict) == 2); /* get data by key */ assert(dict_get(dict, key1, strlen(key1)) == val1); assert(dict_get(dict, key2, strlen(key2)) == val2); /* iterate dict */ struct dict_iter *iter = dict_iter(dict); struct dict_node *node = NULL; while ((node = dict_iter_next(iter)) != NULL) { printf("%.*s => %s\n", (int)node->len, node->key, node->val); } /* free dict iterator */ dict_iter_free(iter); /* free the dict */ dict_free(dict); return 0; }
// cc dict_example.c dict.c md5.c #include <assert.h> #include <stdio.h> #include <string.h> #include "bool.h" #include "dict.h" int main(int argc, const char *argv[]) { /* allocate a new dict */ struct dict *dict = dict(); /* set key and values to dict */ char *key1 = "key1"; char *key2 = "key2"; char *val1 = "val1"; char *val2 = "val2"; assert(dict_set(dict, key1, strlen(key1), val1) == DICT_OK); assert(dict_set(dict, key2, strlen(key2), val2) == DICT_OK); /* get dict length */ assert(dict_len(dict) == 2); /* get data by key */ assert(dict_get(dict, key1, strlen(key1)) == val1); assert(dict_get(dict, key2, strlen(key2)) == val2); /* iterate dict */ struct dict_iter *iter = dict_iter(dict); struct dict_node *node = NULL; while ((node = dict_iter_next(iter)) != NULL) { printf("%.*s => %s\n", (int)node->len, node->key, (char *)node->val); } /* free dict iterator */ dict_iter_free(iter); /* free the dict */ dict_free(dict); return 0; }
Update Skia milestone to 101
/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef SK_MILESTONE #define SK_MILESTONE 100 #endif
/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef SK_MILESTONE #define SK_MILESTONE 101 #endif
Add Bit Manipulation to find lonely integer by XOR trick
/* Problem Statement There are N integers in an array A. All but one integer occur in pairs. Your task is to find the number that occurs only once. Input Format The first line of the input contains an integer N, indicating the number of integers. The next line contains N space-separated integers that form the array A. Constraints 1≤N<100 N % 2=1 (N is an odd number) 0≤A[i]≤100,∀i∈[1,N] Output Format Output S, the number that occurs only once. Sample Input:1 1 1 Sample Output:1 1 Sample Input:2 3 1 1 2 Sample Output:2 2 Sample Input:3 5 0 0 1 2 1 Sample Output:3 2 Explanation In the first input, we see only one element (1) and that element is the answer. In the second input, we see three elements; 1 occurs at two places and 2 only once. Thus, the answer is 2. In the third input, we see five elements. 1 and 0 occur twice. The element that occurs only once is 2. */ #include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> #include <assert.h> int lonelyinteger(int a_size, int* a) { int result; result = 0; for(int i=0 ; i<a_size ; i++){ result = result ^ a[i]; } return result; } int main() { int res; int _a_size, _a_i; scanf("%d", &_a_size); int _a[_a_size]; for(_a_i = 0; _a_i < _a_size; _a_i++) { int _a_item; scanf("%d", &_a_item); _a[_a_i] = _a_item; } res = lonelyinteger(_a_size, _a); printf("%d", res); return 0; }
Add description to internal header
#ifndef BUGSNAG_PRIVATE_H #define BUGSNAG_PRIVATE_H #import "Bugsnag.h" #import "BugsnagBreadcrumb.h" @interface BugsnagBreadcrumbs () /** * Reads and return breadcrumb data currently stored on disk */ - (NSArray *_Nullable)cachedBreadcrumbs; @end @interface Bugsnag () /** Get the current Bugsnag configuration. * * This method returns nil if called before +startBugsnagWithApiKey: or * +startBugsnagWithConfiguration:, and otherwise returns the current * configuration for Bugsnag. * * @return The configuration, or nil. */ + (BugsnagConfiguration *_Nullable)configuration; @end #endif // BUGSNAG_PRIVATE_H
/** * Exposes non-public interfaces between the components of the library for * internal use */ #ifndef BUGSNAG_PRIVATE_H #define BUGSNAG_PRIVATE_H #import "Bugsnag.h" #import "BugsnagBreadcrumb.h" @interface BugsnagBreadcrumbs () /** * Reads and return breadcrumb data currently stored on disk */ - (NSArray *_Nullable)cachedBreadcrumbs; @end @interface Bugsnag () /** Get the current Bugsnag configuration. * * This method returns nil if called before +startBugsnagWithApiKey: or * +startBugsnagWithConfiguration:, and otherwise returns the current * configuration for Bugsnag. * * @return The configuration, or nil. */ + (BugsnagConfiguration *_Nullable)configuration; @end #endif // BUGSNAG_PRIVATE_H
Fix compiler warning for unused function.
// // HLError.h // HLSpriteKit // // Created by Karl Voskuil on 6/6/14. // Copyright (c) 2014 Hilo Games. All rights reserved. // #import <Foundation/Foundation.h> /** The error level for logging non-critical errors using `HLError()`. */ typedef NS_ENUM(NSInteger, HLErrorLevel) { /** Errors. */ HLLevelError, /** Warnings. */ HLLevelWarning, /** Information. */ HLLevelInfo, }; /** Logs a non-critical error. */ static void HLError(HLErrorLevel level, NSString *message) { // TODO: This is a placeholder for a better mechanism for non-critical error logging, // e.g. CocoaLumberjack. NSString *levelLabel; switch (level) { case HLLevelInfo: levelLabel = @"INFO"; break; case HLLevelWarning: levelLabel = @"WARNING"; break; case HLLevelError: levelLabel = @"ERROR"; break; } NSLog(@"%@: %@", levelLabel, message); }
// // HLError.h // HLSpriteKit // // Created by Karl Voskuil on 6/6/14. // Copyright (c) 2014 Hilo Games. All rights reserved. // #import <Foundation/Foundation.h> /** The error level for logging non-critical errors using `HLError()`. */ typedef NS_ENUM(NSInteger, HLErrorLevel) { /** Errors. */ HLLevelError, /** Warnings. */ HLLevelWarning, /** Information. */ HLLevelInfo, }; /** Logs a non-critical error. */ static inline void HLError(HLErrorLevel level, NSString *message) { // TODO: This is a placeholder for a better mechanism for non-critical error logging, // e.g. CocoaLumberjack. NSString *levelLabel; switch (level) { case HLLevelInfo: levelLabel = @"INFO"; break; case HLLevelWarning: levelLabel = @"WARNING"; break; case HLLevelError: levelLabel = @"ERROR"; break; } NSLog(@"%@: %@", levelLabel, message); }
Tidy up the umbrella header.
// // Set.h // Set // // Created by Rob Rix on 2014-06-22. // Copyright (c) 2014 Rob Rix. All rights reserved. // #import <Cocoa/Cocoa.h> //! Project version number for Set. FOUNDATION_EXPORT double SetVersionNumber; //! Project version string for Set. FOUNDATION_EXPORT const unsigned char SetVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <Set/PublicHeader.h>
// Copyright (c) 2014 Rob Rix. All rights reserved. /// Project version number for Set. extern double SetVersionNumber; /// Project version string for Set. extern const unsigned char SetVersionString[];
Include zmq utils if necessary.
/* Copyright (c) 2017 Rolf Timmermans */ #pragma once #include <napi.h> #include <zmq.h> #include <node.h> #include <cassert> #include <iostream> #include "inline/arguments.h" #include "inline/error.h" #include "inline/util.h" #ifdef __MSVC__ #define force_inline inline __forceinline #else #define force_inline inline __attribute__((always_inline)) #endif
/* Copyright (c) 2017 Rolf Timmermans */ #pragma once #include <napi.h> #include <zmq.h> #if ZMQ_VERSION < ZMQ_MAKE_VERSION(4,1,0) # include <zmq_utils.h> #endif #include <node.h> #include <cassert> #include "inline/arguments.h" #include "inline/error.h" #include "inline/util.h" #ifdef __MSVC__ #define force_inline inline __forceinline #else #define force_inline inline __attribute__((always_inline)) #endif
Print function name at DBG
#ifndef __DEBUG_H__ #define __DEBUG_H__ #undef ENABLE_DEBUG #ifdef ENABLE_DEBUG #include <sstream> #define DBG(x...) \ do {\ std::cout<< "DBG " << x << std::endl;\ } while(0) #define DBGHEXTOSTRING(_b, _size) \ do { \ char *b = (char*)(_b);\ uint64_t size = (uint64_t) (_size);\ DBG(" size: "<< size); \ std::stringstream stream; \ for (uint64_t i = 0; i<size; i++) { \ stream << std::hex << int(b[i]); \ } \ DBG( stream.str() ); \ } while(0) #else #define DBG(x...) #define DBGHEXTOSTRING(b,size) #endif #endif /* __DEBUG_H__ */
#ifndef __DEBUG_H__ #define __DEBUG_H__ #undef ENABLE_DEBUG #ifdef ENABLE_DEBUG #include <sstream> #if __STDC_VERSION__ < 199901L # if __GNUC__ >= 2 # define __func__ __FUNCTION__ # else # define __func__ "<unknown>" # endif #endif #define DBG(x...) \ do {\ std::cout<< "DBG " << __func__ << ": " << x << std::endl;\ } while(0) #define DBGHEXTOSTRING(_b, _size) \ do { \ char *b = (char*)(_b);\ uint64_t size = (uint64_t) (_size);\ DBG(" size: "<< size); \ std::stringstream stream; \ for (uint64_t i = 0; i<size; i++) { \ stream << std::hex << int(b[i]); \ } \ DBG( stream.str() ); \ } while(0) #else #define DBG(x...) #define DBGHEXTOSTRING(b,size) #endif #endif /* __DEBUG_H__ */
Add TD3 test where complex self-abort causes verify error
// SKIP PARAM: --set ana.activated[+] apron #include <pthread.h> #include <assert.h> int g = 1; int h = 1; pthread_mutex_t A = PTHREAD_MUTEX_INITIALIZER; void *t_fun(void *arg) { int x, y; // rand pthread_mutex_lock(&A); g = x; h = x; pthread_mutex_unlock(&A); pthread_mutex_lock(&A); pthread_mutex_unlock(&A); pthread_mutex_lock(&A); if (y) g = x; assert(g == h); // UNKNOWN? pthread_mutex_unlock(&A); return NULL; } int main(void) { pthread_t id; pthread_create(&id, NULL, t_fun, NULL); return 0; }
Add further simplification of 13/51
#include <pthread.h> #include <assert.h> int g = 0; pthread_mutex_t A = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t B = PTHREAD_MUTEX_INITIALIZER; void *worker(void *arg ) { while (1) { pthread_mutex_lock(&A); g = 1000; assert(g != 0); if (g > 0) { g--; } pthread_mutex_unlock(&A); // extra mutex makes mine-W more precise than mine-lazy pthread_mutex_lock(&B); pthread_mutex_unlock(&B); } return NULL; } int main(int argc , char **argv ) { pthread_t tid; pthread_create(& tid, NULL, & worker, NULL); return 0; }
Add skstd version of std::exchange
/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef SkExchange_DEFINED #define SkExchange_DEFINED #include <utility> namespace skstd { // std::exchange is in C++14 template<typename T, typename U = T> inline static T exchange(T& obj, U&& new_val) { T old_val = std::move(obj); obj = std::forward<U>(new_val); return old_val; } } #endif // SkExchange_DEFINED
Move serialization interface into sub namespace
#pragma once #include <cstddef> namespace util { // The interface is tuned for reuse and avoids boilerplate length calculations. // Looking at implementation examples helps understand the decisions behind it. // Serialization functions should not throw. // Upon success, serialize functions shall return end of serialized data. // Otherwise, nullptr shall be returned, indicating insufficinet destination capacity. using serializeFunc = void* (*)(void* dest, const void* destEnd, const void* obj); // Upon success, deserialize function shall return end of consumed src. Otherwise, nullptr shall be returned. using deserializeFunc = const void* (*)(void* sharedDest, const void* src, const void* srcEnd); } // namespace util
#pragma once namespace util { namespace serde { // The interface is tuned for reuse and avoids boilerplate length calculations. // Looking at implementation examples helps understand the decisions behind it. // Serialization functions should not throw. // Upon success, serialize functions shall return end of serialized data. // Otherwise, nullptr shall be returned, indicating insufficinet destination capacity. using serializeFun = void* (*)(void* dest, const void* destEnd, const void* obj); // Upon success, deserialize function shall return end of consumed src. Otherwise, nullptr shall be returned. using deserializeFun = const void* (*)(void* sharedDest, const void* src, const void* srcEnd); } // namespace serde } // namespace util
Add a file with common definitions to be used by all testcases.
//---------------------------- tests.h --------------------------- // $Id$ // Version: $Name$ // // Copyright (C) 2004 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //---------------------------- tests.h --------------------------- // common definitions used in all the tests #include <base/logstream.h> #include <cmath> // overload floating point output operators for LogStream so that small // numbers below a certain threshold are simply printed as zeros. this removes // a number of possible places where output may differ depending on platform, // compiler options, etc, simply because round-off is different. LogStream & operator << (LogStream &logstream, const double d) { if (std::fabs (d) < 1e-10) logstream << 0.; else logstream << d; return logstream; } LogStream & operator << (LogStream &logstream, const float d) { if (std::fabs (d) < 1e-8) logstream << 0.; else logstream << d; return logstream; }
Add poll implementation for Muen
/* * Copyright (c) 2017 Contributors as noted in the AUTHORS file * * This file is part of Solo5, a unikernel base layer. * * Permission to use, copy, modify, and/or 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 "../kernel.h" #include "muen-net.h" int solo5_poll(uint64_t until_nsecs) { int rc = 0; do { if (muen_net_pending_data()) { rc = 1; break; } __asm__ __volatile__("pause"); } while (solo5_clock_monotonic() < until_nsecs); if (muen_net_pending_data()) { rc = 1; } return rc; }
Add [[noreturn]] to pure throwing method
#ifndef GENE_H #define GENE_H #include <map> #include <string> #include <iosfwd> class Board; class Piece_Strength_Gene; class Gene { public: Gene(); virtual ~Gene() = default; void read_from(std::istream& is); void mutate(); double evaluate(const Board& board) const; virtual Gene* duplicate() const = 0; virtual std::string name() const = 0; void print(std::ostream& os) const; virtual void reset_piece_strength_gene(const Piece_Strength_Gene* psg); protected: mutable std::map<std::string, double> properties; // used to simplify reading/writing from/to files virtual void reset_properties() const; virtual void load_properties(); void make_priority_non_negative(); private: virtual double score_board(const Board& board) const = 0; void throw_on_invalid_line(const std::string& line, const std::string& reason) const; virtual void gene_specific_mutation(); double priority; bool priority_non_negative; }; #endif // GENE_H
#ifndef GENE_H #define GENE_H #include <map> #include <string> #include <iosfwd> class Board; class Piece_Strength_Gene; class Gene { public: Gene(); virtual ~Gene() = default; void read_from(std::istream& is); void mutate(); double evaluate(const Board& board) const; virtual Gene* duplicate() const = 0; virtual std::string name() const = 0; void print(std::ostream& os) const; virtual void reset_piece_strength_gene(const Piece_Strength_Gene* psg); protected: mutable std::map<std::string, double> properties; // used to simplify reading/writing from/to files virtual void reset_properties() const; virtual void load_properties(); void make_priority_non_negative(); private: virtual double score_board(const Board& board) const = 0; [[noreturn]] void throw_on_invalid_line(const std::string& line, const std::string& reason) const; virtual void gene_specific_mutation(); double priority; bool priority_non_negative; }; #endif // GENE_H
Add shader structure for GLSL compile extension
/* IN DEVELOPMENT. DO NOT SHIP. */ #ifndef __XGLINTELEXT_H__ #define __XGLINTELEXT_H__ #include <xcb/xcb.h> #include <xcb/randr.h> #include "xgl.h" #ifdef __cplusplus extern "C" { #endif // __cplusplus typedef enum _XGL_INTEL_STRUCTURE_TYPE { XGL_INTEL_STRUCTURE_TYPE_SHADER_CREATE_INFO = 1000, } XGL_INTEL_STRUCTURE_TYPE; #ifdef __cplusplus } // extern "C" #endif // __cplusplus #endif // __XGLINTELEXT_H__
/* IN DEVELOPMENT. DO NOT SHIP. */ #ifndef __XGLINTELEXT_H__ #define __XGLINTELEXT_H__ #include <xcb/xcb.h> #include <xcb/randr.h> #include "xgl.h" #ifdef __cplusplus extern "C" { #endif // __cplusplus typedef enum _XGL_INTEL_STRUCTURE_TYPE { XGL_INTEL_STRUCTURE_TYPE_SHADER_CREATE_INFO = 1000, } XGL_INTEL_STRUCTURE_TYPE; typedef struct _XGL_INTEL_COMPILE_GLSL { XGL_PIPELINE_SHADER_STAGE stage; const char *pCode; } XGL_INTEL_COMPILE_GLSL; #ifdef __cplusplus } // extern "C" #endif // __cplusplus #endif // __XGLINTELEXT_H__
Comment explaining what a valid NaPTAN code is.
// // LJSStop.h // LJSYourNextBus // // Created by Luke Stringer on 29/01/2014. // Copyright (c) 2014 Luke Stringer. All rights reserved. // #import <Foundation/Foundation.h> @interface LJSStop : NSObject <NSCopying> @property (nonatomic, copy, readonly) NSString *NaPTANCode; @property (nonatomic, copy, readonly) NSString *title; @property (nonatomic, copy, readonly) NSDate *liveDate; @property (nonatomic, copy, readonly) NSArray *services; - (BOOL)isEqualToStop:(LJSStop *)stop; @end
// // LJSStop.h // LJSYourNextBus // // Created by Luke Stringer on 29/01/2014. // Copyright (c) 2014 Luke Stringer. All rights reserved. // #import <Foundation/Foundation.h> @interface LJSStop : NSObject <NSCopying> /** * An 8 digit stop number starting with e.g. 450 for West Yorkshire or 370 for South Yorkshire */ @property (nonatomic, copy, readonly) NSString *NaPTANCode; @property (nonatomic, copy, readonly) NSString *title; @property (nonatomic, copy, readonly) NSDate *liveDate; @property (nonatomic, copy, readonly) NSArray *services; - (BOOL)isEqualToStop:(LJSStop *)stop; @end
Add shader structure for GLSL compile extension
/* IN DEVELOPMENT. DO NOT SHIP. */ #ifndef __XGLINTELEXT_H__ #define __XGLINTELEXT_H__ #include <xcb/xcb.h> #include <xcb/randr.h> #include "xgl.h" #ifdef __cplusplus extern "C" { #endif // __cplusplus typedef enum _XGL_INTEL_STRUCTURE_TYPE { XGL_INTEL_STRUCTURE_TYPE_SHADER_CREATE_INFO = 1000, } XGL_INTEL_STRUCTURE_TYPE; #ifdef __cplusplus } // extern "C" #endif // __cplusplus #endif // __XGLINTELEXT_H__
/* IN DEVELOPMENT. DO NOT SHIP. */ #ifndef __XGLINTELEXT_H__ #define __XGLINTELEXT_H__ #include <xcb/xcb.h> #include <xcb/randr.h> #include "xgl.h" #ifdef __cplusplus extern "C" { #endif // __cplusplus typedef enum _XGL_INTEL_STRUCTURE_TYPE { XGL_INTEL_STRUCTURE_TYPE_SHADER_CREATE_INFO = 1000, } XGL_INTEL_STRUCTURE_TYPE; typedef struct _XGL_INTEL_COMPILE_GLSL { XGL_PIPELINE_SHADER_STAGE stage; const char *pCode; } XGL_INTEL_COMPILE_GLSL; #ifdef __cplusplus } // extern "C" #endif // __cplusplus #endif // __XGLINTELEXT_H__
Add missing newline at EOF after d1943e187f47
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef MINI_CHROMIUM_BASE_METRICS_HISTOGRAM_FUNCTIONS_H_ #define MINI_CHROMIUM_BASE_METRICS_HISTOGRAM_FUNCTIONS_H_ #include <string> // These are no-op stub versions of a subset of the functions from Chromium's // base/metrics/histogram_functions.h. This allows us to instrument the Crashpad // code as necessary, while not affecting out-of-Chromium builds. namespace base { void UmaHistogramSparse(const std::string& name, int sample) {} } // namespace base #endif // MINI_CHROMIUM_BASE_METRICS_HISTOGRAM_FUNCTIONS_H_
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef MINI_CHROMIUM_BASE_METRICS_HISTOGRAM_FUNCTIONS_H_ #define MINI_CHROMIUM_BASE_METRICS_HISTOGRAM_FUNCTIONS_H_ #include <string> // These are no-op stub versions of a subset of the functions from Chromium's // base/metrics/histogram_functions.h. This allows us to instrument the Crashpad // code as necessary, while not affecting out-of-Chromium builds. namespace base { void UmaHistogramSparse(const std::string& name, int sample) {} } // namespace base #endif // MINI_CHROMIUM_BASE_METRICS_HISTOGRAM_FUNCTIONS_H_
Add function for getting a variable's string representation
#ifndef MICROPYTHON_WRAP_UTIL_H #define MICROPYTHON_WRAP_UTIL_H #include "detail/micropython.h" namespace upywrap { inline std::string ExceptionToString( mp_obj_t ex ) { std::string exMessage; const mp_print_t mp_my_print{ &exMessage, [] ( void* data, const char* str, mp_uint_t len ) { ( (std::string*) data )->append( str, len ); } }; mp_obj_print_exception( &mp_my_print, ex ); return exMessage; } } #endif //#ifndef MICROPYTHON_WRAP_UTIL_H
#ifndef MICROPYTHON_WRAP_UTIL_H #define MICROPYTHON_WRAP_UTIL_H #include "detail/micropython.h" namespace upywrap { inline mp_print_t PrintToString( std::string& dest ) { return mp_print_t{ &dest, [] ( void* data, const char* str, mp_uint_t len ) { ( (std::string*) data )->append( str, len ); } }; } inline std::string ExceptionToString( mp_obj_t ex ) { std::string exMessage; const auto mp_my_print( PrintToString( exMessage ) ); mp_obj_print_exception( &mp_my_print, ex ); return exMessage; } inline std::string VariableValueToString( mp_obj_t obj, mp_print_kind_t kind = PRINT_REPR ) { std::string var; const auto mp_my_print( PrintToString( var ) ); mp_obj_print_helper( &mp_my_print, obj, kind ); return var; } } #endif //#ifndef MICROPYTHON_WRAP_UTIL_H
Add type 'clock_t' to minilibc.
#ifndef __TYPES_H__ #define __TYPES_H__ typedef long off_t; typedef unsigned long size_t; typedef signed long ssize_t; /* Used for a count of bytes or an error indication. */ typedef unsigned char u_char; typedef unsigned short u_short; typedef unsigned int u_int; typedef unsigned long u_long; typedef int mode_t; typedef unsigned long clockid_t; typedef int pid_t; #ifndef NULL #define NULL (0) #endif #define __u_char_defined #endif
#ifndef __TYPES_H__ #define __TYPES_H__ typedef long off_t; typedef unsigned long size_t; typedef signed long ssize_t; /* Used for a count of bytes or an error indication. */ typedef unsigned char u_char; typedef unsigned short u_short; typedef unsigned int u_int; typedef unsigned long u_long; typedef int mode_t; typedef unsigned long clockid_t; typedef int pid_t; typedef unsigned long clock_t; /* clock() */ #ifndef NULL #define NULL (0) #endif #define __u_char_defined #endif
Change the way execution results are collected.
#pragma once #include <libevm/VMFace.h> #include <evmjit/libevmjit/ExecutionEngine.h> namespace dev { namespace eth { class JitVM: public VMFace { public: virtual bytesConstRef execImpl(u256& io_gas, ExtVMFace& _ext, OnOpFunc const& _onOp = {}, uint64_t _steps = (uint64_t)-1) override final; private: jit::RuntimeData m_data; jit::ExecutionEngine m_engine; std::unique_ptr<VMFace> m_fallbackVM; ///< VM used in case of input data rejected by JIT }; } }
#pragma once #include <libevm/VMFace.h> #include <evmjit/libevmjit/ExecutionEngine.h> namespace dev { namespace eth { class JitVM: public VMFace { public: virtual bytesConstRef execImpl(u256& io_gas, ExtVMFace& _ext, OnOpFunc const& _onOp, uint64_t _steps) override final; private: jit::RuntimeData m_data; jit::ExecutionEngine m_engine; std::unique_ptr<VMFace> m_fallbackVM; ///< VM used in case of input data rejected by JIT }; } }
Add missing header file `stdint.h`
/** * Copyright (c) 2015, Chao Wang <hit9@icloud.com> * * md5 hash function. */ /* * This is an OpenSSL-compatible implementation of the RSA Data Security, Inc. * MD5 Message-Digest Algorithm (RFC 1321). * * Homepage: http://openwall.info/wiki/people/solar/software/public-domain-source-code/md5 * * Author: Alexander Peslyak, better known as Solar Designer <solar at openwall.com> */ #ifndef _CW_MD5_H #define _CW_MD5_H 1 #if defined(__cplusplus) extern "C" { #endif void md5_signature(unsigned char *key, unsigned long length, unsigned char *result); uint32_t hash_md5(const char *key, size_t key_length); #if defined(__cplusplus) } #endif #endif
/** * Copyright (c) 2015, Chao Wang <hit9@icloud.com> * * md5 hash function. */ /* * This is an OpenSSL-compatible implementation of the RSA Data Security, Inc. * MD5 Message-Digest Algorithm (RFC 1321). * * Homepage: http://openwall.info/wiki/people/solar/software/public-domain-source-code/md5 * * Author: Alexander Peslyak, better known as Solar Designer <solar at openwall.com> */ #ifndef _CW_MD5_H #define _CW_MD5_H 1 #include <stdint.h> #if defined(__cplusplus) extern "C" { #endif void md5_signature(unsigned char *key, unsigned long length, unsigned char *result); uint32_t hash_md5(const char *key, size_t key_length); #if defined(__cplusplus) } #endif #endif
Move the QVideoFrame scope lock to a header file
#ifndef Q_VIDEO_FRAME_SCOPE_MAP #define Q_VIDEO_FRAME_SCOPE_MAP 1 // TODO: move to QVideoFrameScope struct QVideoFrameScopeMap { QVideoFrameScopeMap(QVideoFrame *frame, QAbstractVideoBuffer::MapMode mode) : frame(frame) { if(frame) { status = frame->map(mode); if (!status) { qWarning("Can't map!"); } } } ~QVideoFrameScopeMap() { if(frame) { frame->unmap(); } } operator bool() const { return status; } QVideoFrame *frame = nullptr; bool status = false; }; #endif // Q_VIDEO_FRAME_SCOPE_MAP
Add feature letting you include one .c file which automatically selects the driver.
#if defined(WINDOWS) || defined(WIN32) || defined(WIN64) #include "CNFGWinDriver.c" #elif defined( __android__ ) #include "CNFGOGLEGLDriver.c" #else #include "CNFGXDriver.c" #endif
Remove old audio player header
// // Use this file to import your target's public headers that you would like to expose to Swift. // #import "STKAudioPlayer.h"
// // Use this file to import your target's public headers that you would like to expose to Swift. //
Update a test case to work with old Darwin SDK's
// RUN: %clangxx_asan -std=c++11 -O0 %s -o %t // RUN: not %run %t 2>&1 | FileCheck %s --check-prefix=READ // RUN: not %run %t write 2>&1 | FileCheck %s --check-prefix=WRITE // REQUIRES: x86-target-arch #include <sys/mman.h> static volatile int sink; __attribute__((noinline)) void Read(int *ptr) { sink = *ptr; } __attribute__((noinline)) void Write(int *ptr) { *ptr = 0; } int main(int argc, char **argv) { // Writes to shadow are detected as reads from shadow gap (because of how the // shadow mapping works). This is kinda hard to fix. Test a random address in // the application part of the address space. void *volatile p = mmap(nullptr, 4096, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0); munmap(p, 4096); if (argc == 1) Read((int *)p); else Write((int *)p); } // READ: AddressSanitizer: SEGV on unknown address // READ: The signal is caused by a READ memory access. // WRITE: AddressSanitizer: SEGV on unknown address // WRITE: The signal is caused by a WRITE memory access.
// RUN: %clangxx_asan -std=c++11 -O0 %s -o %t // RUN: not %run %t 2>&1 | FileCheck %s --check-prefix=READ // RUN: not %run %t write 2>&1 | FileCheck %s --check-prefix=WRITE // REQUIRES: x86-target-arch #include <sys/mman.h> static volatile int sink; __attribute__((noinline)) void Read(int *ptr) { sink = *ptr; } __attribute__((noinline)) void Write(int *ptr) { *ptr = 0; } int main(int argc, char **argv) { // Writes to shadow are detected as reads from shadow gap (because of how the // shadow mapping works). This is kinda hard to fix. Test a random address in // the application part of the address space. void *volatile p = mmap(nullptr, 4096, PROT_READ, MAP_PRIVATE | MAP_ANON, 0, 0); munmap(p, 4096); if (argc == 1) Read((int *)p); else Write((int *)p); } // READ: AddressSanitizer: SEGV on unknown address // READ: The signal is caused by a READ memory access. // WRITE: AddressSanitizer: SEGV on unknown address // WRITE: The signal is caused by a WRITE memory access.
Add a new line to satisfy clang.
#pragma once #include <string> #include <iostream> struct Customer { int id; std::string name; }; inline std::ostream& operator<<(std::ostream& os, const Customer& obj) { os << "Customer (id: " << obj.id << ", name: " << obj.name << ")"; return os; }
#pragma once #include <string> #include <iostream> struct Customer { int id; std::string name; }; inline std::ostream& operator<<(std::ostream& os, const Customer& obj) { os << "Customer (id: " << obj.id << ", name: " << obj.name << ")"; return os; }
Move unknown enum entry to top.
#import <WebKit/WebKit.h> typedef NS_ENUM (NSInteger, WMFWKScriptMessageType) { WMFWKScriptMessagePeek, WMFWKScriptMessageConsoleMessage, WMFWKScriptMessageClickLink, WMFWKScriptMessageClickImage, WMFWKScriptMessageClickReference, WMFWKScriptMessageClickEdit, WMFWKScriptMessageNonAnchorTouchEndedWithoutDragging, WMFWKScriptMessageLateJavascriptTransform, WMFWKScriptMessageArticleState, WMFWKScriptMessageUnknown }; @interface WKScriptMessage (WMFScriptMessage) + (WMFWKScriptMessageType)wmf_typeForMessageName:(NSString*)name; + (Class)wmf_expectedMessageBodyClassForType:(WMFWKScriptMessageType)type; @end
#import <WebKit/WebKit.h> typedef NS_ENUM (NSInteger, WMFWKScriptMessageType) { WMFWKScriptMessageUnknown, WMFWKScriptMessagePeek, WMFWKScriptMessageConsoleMessage, WMFWKScriptMessageClickLink, WMFWKScriptMessageClickImage, WMFWKScriptMessageClickReference, WMFWKScriptMessageClickEdit, WMFWKScriptMessageNonAnchorTouchEndedWithoutDragging, WMFWKScriptMessageLateJavascriptTransform, WMFWKScriptMessageArticleState }; @interface WKScriptMessage (WMFScriptMessage) + (WMFWKScriptMessageType)wmf_typeForMessageName:(NSString*)name; + (Class)wmf_expectedMessageBodyClassForType:(WMFWKScriptMessageType)type; @end
Fix build warning with clang 10.0.1
#include <limits.h> #include "utils/random.h" // A simple psuedorandom number generator static struct random_t rand_state = { 1 }; void random_seed(struct random_t *r, uint32_t seed) { r->seed = seed; } uint32_t random_get_seed(struct random_t *r) { return r->seed; } uint32_t random_int(struct random_t *r, uint32_t upperbound) { return random_intmax(r) % upperbound; } uint32_t random_intmax(struct random_t *r) { r->seed = r->seed * 1664525 + 1013904223; return r->seed; } float random_float(struct random_t *r) { return (float)random_intmax(r) / UINT_MAX; } void rand_seed(uint32_t seed) { random_seed(&rand_state, seed); } uint32_t rand_get_seed(void) { return random_get_seed(&rand_state); } uint32_t rand_int(uint32_t upperbound) { return random_int(&rand_state, upperbound); } uint32_t rand_intmax(void) { return random_intmax(&rand_state); } float rand_float(void) { return random_float(&rand_state); }
#include <limits.h> #include "utils/random.h" // A simple psuedorandom number generator static struct random_t rand_state = { 1 }; void random_seed(struct random_t *r, uint32_t seed) { r->seed = seed; } uint32_t random_get_seed(struct random_t *r) { return r->seed; } uint32_t random_int(struct random_t *r, uint32_t upperbound) { return random_intmax(r) % upperbound; } uint32_t random_intmax(struct random_t *r) { r->seed = r->seed * 1664525 + 1013904223; return r->seed; } float random_float(struct random_t *r) { return (float)random_intmax(r) / (float)UINT_MAX; } void rand_seed(uint32_t seed) { random_seed(&rand_state, seed); } uint32_t rand_get_seed(void) { return random_get_seed(&rand_state); } uint32_t rand_int(uint32_t upperbound) { return random_int(&rand_state, upperbound); } uint32_t rand_intmax(void) { return random_intmax(&rand_state); } float rand_float(void) { return random_float(&rand_state); }
Fix a typo in the argument type.
/* trace.h * Copyright: (When this is determined...it will go here) * CVS Info * $Id$ * Overview: * Tracing support for runops_cores.c. * Data Structure and Algorithms: * History: * Notes: * References: */ #ifndef PARROT_TRACE_H_GUARD #define PARROT_TRACE_H_GUARD #include "parrot/parrot.h" void trace_op_dump(struct Parrot_Interp *interpreter, opcode_t *code_start, opcode_t *pc); void trace_op(struct Parrot_Interp *interpreter, opcode_t *code_start, opcode_t *code_end, opcode_t *pc); void trace_op_b0(struct Parrot_Interp *interpreter, opcode_t *code_start, opcode_t *pc); void trace_op_b1(struct Parrot_Interp *interpreter, opcode_t *code_start, opcode_t *code_end, code_t *pc); #endif /* * Local variables: * c-indentation-style: bsd * c-basic-offset: 4 * indent-tabs-mode: nil * End: * * vim: expandtab shiftwidth=4: */
/* trace.h * Copyright: (When this is determined...it will go here) * CVS Info * $Id$ * Overview: * Tracing support for runops_cores.c. * Data Structure and Algorithms: * History: * Notes: * References: */ #ifndef PARROT_TRACE_H_GUARD #define PARROT_TRACE_H_GUARD #include "parrot/parrot.h" void trace_op_dump(struct Parrot_Interp *interpreter, opcode_t *code_start, opcode_t *pc); void trace_op(struct Parrot_Interp *interpreter, opcode_t *code_start, opcode_t *code_end, opcode_t *pc); void trace_op_b0(struct Parrot_Interp *interpreter, opcode_t *code_start, opcode_t *pc); void trace_op_b1(struct Parrot_Interp *interpreter, opcode_t *code_start, opcode_t *code_end, opcode_t *pc); #endif /* * Local variables: * c-indentation-style: bsd * c-basic-offset: 4 * indent-tabs-mode: nil * End: * * vim: expandtab shiftwidth=4: */
Add text output for integers.
#include "custom-type.h" #include "cmd.h" #include "common.h" #include <string.h> #include <hiredis/hiredis.h> #include <hiredis/async.h> void custom_type_reply(redisAsyncContext *c, void *r, void *privdata) { redisReply *reply = r; struct cmd *cmd = privdata; (void)c; if(reply == NULL) { evhttp_send_reply(cmd->rq, 404, "Not Found", NULL); return; } if(cmd->mime) { /* use the given content-type, but only for strings */ switch(reply->type) { case REDIS_REPLY_NIL: /* or nil values */ format_send_reply(cmd, "", 0, cmd->mime); return; case REDIS_REPLY_STRING: format_send_reply(cmd, reply->str, reply->len, cmd->mime); return; } } /* couldn't make sense of what the client wanted. */ evhttp_send_reply(cmd->rq, 400, "Bad request", NULL); cmd_free(cmd); }
#include "custom-type.h" #include "cmd.h" #include "common.h" #include <string.h> #include <hiredis/hiredis.h> #include <hiredis/async.h> void custom_type_reply(redisAsyncContext *c, void *r, void *privdata) { redisReply *reply = r; struct cmd *cmd = privdata; (void)c; char int_buffer[50]; int int_len; if(reply == NULL) { evhttp_send_reply(cmd->rq, 404, "Not Found", NULL); return; } if(cmd->mime) { /* use the given content-type, but only for strings */ switch(reply->type) { case REDIS_REPLY_NIL: /* or nil values */ format_send_reply(cmd, "", 0, cmd->mime); return; case REDIS_REPLY_STRING: format_send_reply(cmd, reply->str, reply->len, cmd->mime); return; case REDIS_REPLY_INTEGER: int_len = sprintf(int_buffer, "%lld", reply->integer); format_send_reply(cmd, int_buffer, int_len, cmd->mime); return; } } /* couldn't make sense of what the client wanted. */ evhttp_send_reply(cmd->rq, 400, "Bad request", NULL); cmd_free(cmd); }
Add analysis stub for bsearch
#include <stddef.h> void qsort(void *ptr, size_t count, size_t size, int (*comp)(const void*, const void*)) { // call all possible compares first, before invalidating array elements for (size_t i = 0; i < count; i++) { for (size_t j = 0; j < count; j++) { comp(ptr + i * size, ptr + j * size); } } // randomly swap all possible, invalidates array elements for (size_t i = 0; i < count; i++) { for (size_t j = 0; j < count; j++) { int r; // rand if (r) { // swap elements byte-by-byte, no other way to do it, because we cannot allocate and copy/swap abstract elements for (size_t k = 0; k < size; k++) { char *a = ptr + i * size + k; char *b = ptr + j * size + k; char c = *a; *a = *b; *b = c; } } } } // array isn't actually sorted! just pretent calls for Goblint }
#include <stddef.h> void qsort(void *ptr, size_t count, size_t size, int (*comp)(const void*, const void*)) { // call all possible compares first, before invalidating array elements for (size_t i = 0; i < count; i++) { for (size_t j = 0; j < count; j++) { comp(ptr + i * size, ptr + j * size); } } // randomly swap all possible, invalidates array elements for (size_t i = 0; i < count; i++) { for (size_t j = 0; j < count; j++) { int r; // rand if (r) { // swap elements byte-by-byte, no other way to do it, because we cannot allocate and copy/swap abstract elements for (size_t k = 0; k < size; k++) { char *a = ptr + i * size + k; char *b = ptr + j * size + k; char c = *a; *a = *b; *b = c; } } } } // array isn't actually sorted! just pretent calls for Goblint } void* bsearch(const void *key, void *ptr, size_t count, size_t size, int (*comp)(const void*, const void*)) { // linear search for simplicity for (size_t i = 0; i < count; i++) { const void *a = ptr + i * size; if (comp(key, a) == 0) { return a; } } return NULL; }
Remove malicious semicolon from array constant
#include <check.h> /* * Include test files below */ typedef Suite* (*suite_creator_f)(void); int main(void) { int nfailed = 0; Suite* s; SRunner* sr; suite_creator_f iter; /* * Insert suite creator functions here */ suite_creator_f suite_funcs[] = { NULL; }; for (iter = suite_funcs[0]; *iter, iter++) { s = iter(); sr = srunner_create(s); srunner_run_all(sr, CK_NORMAL); nfailed += srunner_ntests_failed(sr); srunner_free(sr); } return (nfailed == 0) ? EXIT_SUCCESS : EXIT_FAILURE; }
#include <check.h> /* * Include test files below */ typedef Suite* (*suite_creator_f)(void); int main(void) { int nfailed = 0; Suite* s; SRunner* sr; suite_creator_f iter; /* * Insert suite creator functions here */ suite_creator_f suite_funcs[] = { NULL }; for (iter = suite_funcs[0]; *iter, iter++) { s = iter(); sr = srunner_create(s); srunner_run_all(sr, CK_NORMAL); nfailed += srunner_ntests_failed(sr); srunner_free(sr); } return (nfailed == 0) ? EXIT_SUCCESS : EXIT_FAILURE; }
Update version number to 8.01.07-k7.
/* * QLogic Fibre Channel HBA Driver * Copyright (c) 2003-2005 QLogic Corporation * * See LICENSE.qla2xxx for copyright and licensing details. */ /* * Driver version */ #define QLA2XXX_VERSION "8.01.07-k6" #define QLA_DRIVER_MAJOR_VER 8 #define QLA_DRIVER_MINOR_VER 1 #define QLA_DRIVER_PATCH_VER 7 #define QLA_DRIVER_BETA_VER 0
/* * QLogic Fibre Channel HBA Driver * Copyright (c) 2003-2005 QLogic Corporation * * See LICENSE.qla2xxx for copyright and licensing details. */ /* * Driver version */ #define QLA2XXX_VERSION "8.01.07-k7" #define QLA_DRIVER_MAJOR_VER 8 #define QLA_DRIVER_MINOR_VER 1 #define QLA_DRIVER_PATCH_VER 7 #define QLA_DRIVER_BETA_VER 0
Include what you use fixes.
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_GRPC_REMOTE_WORKER_H_ #define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_GRPC_REMOTE_WORKER_H_ #include <memory> #include "tensorflow/core/distributed_runtime/rpc/grpc_util.h" #include "tensorflow/core/lib/core/threadpool.h" namespace grpc { class CompletionQueue; } namespace tensorflow { class WorkerCacheLogger; class WorkerInterface; WorkerInterface* NewGrpcRemoteWorker(SharedGrpcChannelPtr channel, ::grpc::CompletionQueue* completion_queue, thread::ThreadPool* callback_threadpool, WorkerCacheLogger* logger); } // namespace tensorflow #endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_GRPC_REMOTE_WORKER_H_
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_GRPC_REMOTE_WORKER_H_ #define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_GRPC_REMOTE_WORKER_H_ #include <memory> #include "grpcpp/completion_queue.h" #include "tensorflow/core/distributed_runtime/rpc/grpc_util.h" #include "tensorflow/core/lib/core/threadpool.h" namespace tensorflow { class WorkerCacheLogger; class WorkerInterface; WorkerInterface* NewGrpcRemoteWorker(SharedGrpcChannelPtr channel, ::grpc::CompletionQueue* completion_queue, thread::ThreadPool* callback_threadpool, WorkerCacheLogger* logger); } // namespace tensorflow #endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_RPC_GRPC_REMOTE_WORKER_H_
Add result set benchmark program without GLib
/* Copyright (C) 2015-2019 Sutou Kouhei <kou@clear-code.com> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License version 2.1 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <stdio.h> #include <stdlib.h> #include <groonga.h> int main(int argc, char **argv) { grn_rc rc; grn_ctx ctx; int n = 10000000; rc = grn_init(); if (rc != GRN_SUCCESS) { printf("failed to initialize Groonga: <%d>: %s\n", rc, grn_get_global_error_message()); return EXIT_FAILURE; } grn_ctx_init(&ctx, 0); grn_obj *db = grn_db_open(&ctx, "db/db"); if (ctx.rc != GRN_SUCCESS) { printf("failed to open database: <%d>: %s\n", rc, grn_get_global_error_message()); return EXIT_FAILURE; } grn_obj *source_table = grn_ctx_get(&ctx, "Sources", -1); grn_obj *result_set = grn_table_create(&ctx, NULL, 0, NULL, GRN_TABLE_HASH_KEY | GRN_OBJ_WITH_SUBREC, source_table, NULL); grn_timeval start; grn_timeval_now(&ctx, &start); for (int i = 0; i < n; i++) { grn_id id = i; grn_hash_add(&ctx, (grn_hash *)result_set, &id, sizeof(grn_id), NULL, NULL); } grn_timeval end; grn_timeval_now(&ctx, &end); double elapsed = (end.tv_sec + (end.tv_nsec / GRN_TIME_NSEC_PER_SEC_F)) - (start.tv_sec + (start.tv_nsec / GRN_TIME_NSEC_PER_SEC_F)); printf("%f:%d\n", elapsed, grn_table_size(&ctx, result_set)); grn_obj_close(&ctx, result_set); grn_obj_close(&ctx, db); grn_ctx_fin(&ctx); grn_fin(); return EXIT_SUCCESS; }
Add test case that makes goblint crash
// Test case taken from sqlite3.c #include <string.h> typedef unsigned long u64; # define EXP754 (((u64)0x7ff)<<52) # define MAN754 ((((u64)1)<<52)-1) # define IsNaN(X) (((X)&EXP754)==EXP754 && ((X)&MAN754)!=0) static int sqlite3IsNaN(double x){ int rc; /* The value return */ u64 y; memcpy(&y,&x,sizeof(y)); // Goblint used to crash here rc = IsNaN(y); return rc; } int main(){ sqlite3IsNaN(23.0); return 0; }
Add documentation to the headers
// // DAKeyboardControl.h // DAKeyboardControlExample // // Created by Daniel Amitay on 7/14/12. // Copyright (c) 2012 Daniel Amitay. All rights reserved. // #import <UIKit/UIKit.h> typedef void (^DAKeyboardDidMoveBlock)(CGRect keyboardFrameInView); @interface UIView (DAKeyboardControl) @property (nonatomic) CGFloat keyboardTriggerOffset; @property (nonatomic, readonly) BOOL keyboardWillRecede; - (void)addKeyboardPanningWithActionHandler:(DAKeyboardDidMoveBlock)didMoveBlock; - (void)addKeyboardNonpanningWithActionHandler:(DAKeyboardDidMoveBlock)didMoveBlock; - (void)removeKeyboardControl; - (CGRect)keyboardFrameInView; - (void)hideKeyboard; @end
// // DAKeyboardControl.h // DAKeyboardControlExample // // Created by Daniel Amitay on 7/14/12. // Copyright (c) 2012 Daniel Amitay. All rights reserved. // #import <UIKit/UIKit.h> typedef void (^DAKeyboardDidMoveBlock)(CGRect keyboardFrameInView); /** DAKeyboardControl allows you to easily add keyboard awareness and scrolling dismissal (a receding keyboard ala iMessages app) to any UIView, UIScrollView or UITableView with only 1 line of code. DAKeyboardControl automatically extends UIView and provides a block callback with the keyboard's current origin. */ @interface UIView (DAKeyboardControl) /** The keyboardTriggerOffset property allows you to choose at what point the user's finger "engages" the keyboard. */ @property (nonatomic) CGFloat keyboardTriggerOffset; @property (nonatomic, readonly) BOOL keyboardWillRecede; /** Adding pan-to-dismiss (functionality introduced in iMessages) @param didMoveBlock called everytime the keyboard is moved so you can update the frames of your views @see addKeyboardNonpanningWithActionHandler: @see removeKeyboardControl */ - (void)addKeyboardPanningWithActionHandler:(DAKeyboardDidMoveBlock)didMoveBlock; /** Adding keyboard awareness (appearance and disappearance only) @param didMoveBlock called everytime the keyboard is moved so you can update the frames of your views @see addKeyboardPanningWithActionHandler: @see removeKeyboardControl */ - (void)addKeyboardNonpanningWithActionHandler:(DAKeyboardDidMoveBlock)didMoveBlock; /** Remove the keyboard action handler @note You MUST call this method to remove the keyboard handler before the view goes out of memory. */ - (void)removeKeyboardControl; /** Returns the keyboard frame in the view */ - (CGRect)keyboardFrameInView; /** Convenience method to dismiss the keyboard */ - (void)hideKeyboard; @end
Add program to create a lot of files in a directory
/* * 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 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * This program is used to create many empty files for testing file system performance */ #include <stdio.h> #include <time.h> #include <stdlib.h> #define MAX_COUNT 100000 const char alphanum[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; void gen_random(char *s, const int len) { int i; for (i = 0; i < len; i++) { s[i] = alphanum[rand() % (sizeof(alphanum) - 1)]; } s[len] = 0; } int main() { int i; FILE *f; char fname[15]; time_t start, end; time(&start); for (i = 0; i < MAX_COUNT; i++) { gen_random(fname, 15); f = fopen(fname, "w"); if (f != NULL) { fclose(f); } else { perror("Error creating file\n"); exit(1); } } time(&end); printf("Time taken %f\n", difftime(end, start)); return 0; }
Check if `size == 0` in `safe_malloc_function()`
#include "safe-memory.h" #include <stdio.h> #include <stdlib.h> #include <string.h> void* safe_malloc_function(size_t size, const char* calling_function) { void* memory = malloc(size); if (!memory) { fprintf(stderr, "Error: not enough memory for malloc in function: %s", calling_function); exit(EXIT_FAILURE); } memset(memory, 0, size); return memory; }
#include "safe-memory.h" #include <stdio.h> #include <stdlib.h> #include <string.h> void* safe_malloc_function(size_t size, const char* calling_function) { if (size == 0) { return NULL; } void* memory = malloc(size); if (!memory) { fprintf(stderr, "Error: not enough memory for malloc in function: %s", calling_function); exit(EXIT_FAILURE); } memset(memory, 0, size); return memory; }
Reduce the amount of process activity for incoming I/O read responses.
#ifndef IORESPONSEMUX_H #define IORESPONSEMUX_H #ifndef PROCESSOR_H #error This file should be included in Processor.h #endif class IOResponseMultiplexer : public Object { private: RegisterFile& m_regFile; struct IOResponse { IODeviceID device; IOData data; }; Buffer<IOResponse> m_incoming; typedef Buffer<RegAddr> WriteBackQueue; std::vector<WriteBackQueue*> m_wb_buffers; Process p_dummy; Result DoNothing() { return SUCCESS; } public: IOResponseMultiplexer(const std::string& name, Object& parent, Clock& clock, RegisterFile& rf, size_t numDevices, Config& config); ~IOResponseMultiplexer(); // sent by device select upon an I/O read from the processor bool QueueWriteBackAddress(IODeviceID dev, const RegAddr& addr); // triggered by the IOBusInterface bool OnReadResponseReceived(IODeviceID from, MemAddr address, const IOData& data); Process p_IncomingReadResponses; // upon data available on m_incoming Result DoReceivedReadResponses(); }; #endif
#ifndef IORESPONSEMUX_H #define IORESPONSEMUX_H #ifndef PROCESSOR_H #error This file should be included in Processor.h #endif class IOResponseMultiplexer : public Object { private: RegisterFile& m_regFile; struct IOResponse { IODeviceID device; IOData data; }; Buffer<IOResponse> m_incoming; typedef Buffer<RegAddr> WriteBackQueue; std::vector<WriteBackQueue*> m_wb_buffers; Process p_dummy; Result DoNothing() { p_dummy.Deactivate(); return SUCCESS; } public: IOResponseMultiplexer(const std::string& name, Object& parent, Clock& clock, RegisterFile& rf, size_t numDevices, Config& config); ~IOResponseMultiplexer(); // sent by device select upon an I/O read from the processor bool QueueWriteBackAddress(IODeviceID dev, const RegAddr& addr); // triggered by the IOBusInterface bool OnReadResponseReceived(IODeviceID from, MemAddr address, const IOData& data); Process p_IncomingReadResponses; // upon data available on m_incoming Result DoReceivedReadResponses(); }; #endif
Add solution for problem 3
/* * he prime factors of 13195 are 5, 7, 13 and 29. * * What is the largest prime factor of the number 600851475143 ? */ #include <stdio.h> int main(int argc, char **argv) { long long int num = 600851475143; int x; for(x = 2; x < num; x++) { if(num % x == 0) { num /= x; x--; } } printf("%i\n", x); return 0; }
Add a solution for problem 9
#include <stdio.h> #include <stdint.h> #include "euler.h" #define PROBLEM 9 #define ANSWER 31875000 int main(int argc, char **argv) { int a, b, c, a2, b2, c2; int product = 0; for(a = 1; a < 1000; a++) { for(b = 1; b < 1000; b++) { a2 = a * a; b2 = b * b; for(c = 1; c < 1000; c++) { c2 = c * c; if((a2 + b2 == c2) && (a + b + c == 1000)) { product = a * b * c; } } } } return check(PROBLEM, ANSWER, product); }
Add super simple thread creation case
#include <stdio.h> #include <assert.h> #include "uv.h" static uv_thread_t thread; static void thread_cb(void* arg) { printf("hello thread!\n"); } int main() { int r = uv_thread_create(&thread, thread_cb, NULL); assert(r == 0); /* pause execution of this thread until the spawned thread has had * time to finish execution. */ uv_thread_join(&thread); return 0; }
Add newline to end of file
#include <string> #include "Type.h" class VarStack; enum ArithmeticOperator { NEGATE = 0, SUM, DIFFERENCE, MULTIPLY, DIVIDE }; #define NUM_ARITHMETIC_OPERATORS 5 enum LogicOperator { LESS_THAN = 0, LESS_THAN_OR_EQUAL, EQUAL, GREATER_THAN_OR_EQUAL, GREATER_THAN }; #define NUM_LOGIC_OPERATORS 5 class ExprGen { public: ExprGen(); void setVarStack(VarStack *vStack); string genArithmeticExpr(SupportedType type); private: VarStack *variableStack; string getRandVarOrValue(SupportedType type); }; extern ExprGen g_exprGen;
#include <string> #include "Type.h" class VarStack; enum ArithmeticOperator { NEGATE = 0, SUM, DIFFERENCE, MULTIPLY, DIVIDE }; #define NUM_ARITHMETIC_OPERATORS 5 enum LogicOperator { LESS_THAN = 0, LESS_THAN_OR_EQUAL, EQUAL, GREATER_THAN_OR_EQUAL, GREATER_THAN }; #define NUM_LOGIC_OPERATORS 5 class ExprGen { public: ExprGen(); void setVarStack(VarStack *vStack); string genArithmeticExpr(SupportedType type); private: VarStack *variableStack; string getRandVarOrValue(SupportedType type); }; extern ExprGen g_exprGen;
Add a file for some ObjC class ABI constants.
//===--- Class.h - Compiler/runtime class-metadata values -------*- C++ -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This header provides target-independent information about class // metadata. // //===----------------------------------------------------------------------===// #ifndef SWIFT_ABI_CLASS_H #define SWIFT_ABI_CLASS_H #include <stdint.h> namespace swift { /// Flags which enum class ClassFlags : uint32_t { /// This class is a meta-class. Meta = 0x00001, /// This class is a root class. Root = 0x00002, /// This class provides a non-trivial .cxx_construct or .cxx_destruct /// implementation. HasCXXStructors = 0x00004, /// This class has hidden visibility. Hidden = 0x00010, /// This class has the exception attribute. Exception = 0x00020, /// (Obsolete) ARC-specific: this class has a .release_ivars method HasIvarReleaser = 0x00040, /// This class implementation was compiled under ARC. CompiledByARC = 0x00080, /// This class provides a non-trivial .cxx_destruct method, but /// its .cxx_construct is trivial. For backwards compatibility, /// when setting this flag, HasCXXStructors must be set as well. HasCXXDestructorOnly = 0x00100 }; inline ClassFlags &operator|=(ClassFlags &lhs, ClassFlags rhs) { lhs = ClassFlags(uint32_t(lhs) | uint32_t(rhs)); return lhs; } inline ClassFlags operator|(ClassFlags lhs, ClassFlags rhs) { return (lhs |= rhs); } } #endif
Add a simple server abstraction.
#ifndef IO_SOCKET_SIMPLE_SERVER_H #define IO_SOCKET_SIMPLE_SERVER_H #include <io/socket/socket.h> /* * XXX * This is just one level up from using macros. Would be nice to use abstract * base classes and something a bit tidier. */ template<typename A, typename C, typename L> class SimpleServer { LogHandle log_; A arg_; L *server_; Action *accept_action_; Action *close_action_; Action *stop_action_; public: SimpleServer(LogHandle log, A arg, SocketAddressFamily family, const std::string& interface) : log_(log), arg_(arg), server_(NULL), accept_action_(NULL), close_action_(NULL), stop_action_(NULL) { server_ = L::listen(family, interface); if (server_ == NULL) HALT(log_) << "Unable to create listener."; INFO(log_) << "Listening on: " << server_->getsockname(); EventCallback *cb = callback(this, &SimpleServer::accept_complete); accept_action_ = server_->accept(cb); Callback *scb = callback(this, &SimpleServer::stop); stop_action_ = EventSystem::instance()->register_interest(EventInterestStop, scb); } ~SimpleServer() { ASSERT(server_ == NULL); ASSERT(accept_action_ == NULL); ASSERT(close_action_ == NULL); ASSERT(stop_action_ == NULL); } private: void accept_complete(Event e) { accept_action_->cancel(); accept_action_ = NULL; switch (e.type_) { case Event::Done: break; case Event::Error: ERROR(log_) << "Accept error: " << e; break; default: ERROR(log_) << "Unexpected event: " << e; break; } if (e.type_ == Event::Done) { Socket *client = (Socket *)e.data_; INFO(log_) << "Accepted client: " << client->getpeername(); new C(arg_, client); } EventCallback *cb = callback(this, &SimpleServer::accept_complete); accept_action_ = server_->accept(cb); } void close_complete(void) { close_action_->cancel(); close_action_ = NULL; ASSERT(server_ != NULL); delete server_; server_ = NULL; delete this; } void stop(void) { stop_action_->cancel(); stop_action_ = NULL; accept_action_->cancel(); accept_action_ = NULL; ASSERT(close_action_ == NULL); Callback *cb = callback(this, &SimpleServer::close_complete); close_action_ = server_->close(cb); } }; #endif /* !IO_SOCKET_SIMPLE_SERVER_H */
Implement a test that demonstrates the exponential blowup of our system
#include "rmc.h" extern int coin(void); // A test that should be really bad because exponents. // Only takes like a minute or so! void welp(int *p, int *q) { VEDGE(a, b); L(a, *p = 1); if (coin()){} if (coin()){} if (coin()){} if (coin()){} // 4 if (coin()){} if (coin()){} if (coin()){} if (coin()){} // 8 if (coin()){} if (coin()){} if (coin()){} if (coin()){} if (coin()){} if (coin()){} if (coin()){} if (coin()){} // 16 L(b, *q = 1); }
Disable assert checks as default
#ifndef CTCONFIG_H #define CTCONFIG_H #define ENABLE_ASSERT_CHECKS //#define CT_NODE_DEBUG //#define ENABLE_INTEGRITY_CHECK //#define ENABLE_COUNTERS //#define ENABLE_PAGING #endif // CTCONFIG_H
#ifndef CTCONFIG_H #define CTCONFIG_H //#define ENABLE_ASSERT_CHECKS //#define CT_NODE_DEBUG //#define ENABLE_INTEGRITY_CHECK //#define ENABLE_COUNTERS //#define ENABLE_PAGING #endif // CTCONFIG_H
Remove readonly from member name and availability so we can create entries locally.
// // TSDKEventLinupEntry.h // TeamSnapSDK // // Created by Jason Rahaim on 4/10/18. // Copyright © 2018 teamsnap. All rights reserved. // #import <TeamSnapSDK/TeamSnapSDK.h> @interface TSDKEventLineupEntry : TSDKCollectionObject @property (nonatomic, weak) NSString *_Nullable eventLineupId; @property (nonatomic, weak) NSString *_Nullable memberId; @property (nonatomic, assign) NSInteger sequence; @property (nonatomic, weak) NSString *_Nullable label; //(max 50) @property (nonatomic, weak, readonly) NSString *_Nullable memberName; @property (nonatomic, weak, readonly) NSString *_Nullable memberPhoto; @property (nonatomic, assign, readonly) TSDKAvailabilityState availabilityStatusCode; @end
// // TSDKEventLinupEntry.h // TeamSnapSDK // // Created by Jason Rahaim on 4/10/18. // Copyright © 2018 teamsnap. All rights reserved. // #import <TeamSnapSDK/TeamSnapSDK.h> @interface TSDKEventLineupEntry : TSDKCollectionObject @property (nonatomic, weak) NSString *_Nullable eventLineupId; @property (nonatomic, weak) NSString *_Nullable memberId; @property (nonatomic, assign) NSInteger sequence; @property (nonatomic, weak) NSString *_Nullable label; //(max 50) @property (nonatomic, weak) NSString *_Nullable memberName; @property (nonatomic, weak, readonly) NSString *_Nullable memberPhoto; @property (nonatomic, assign) TSDKAvailabilityState availabilityStatusCode; @end
Add Gridcoin structs to forward file.
#pragma once // Block data structures. class CBlock; class CBlockIndex;
#pragma once // Block data structures. class CBlock; class CBlockIndex; // Gridcoin struct MiningCPID; struct StructCPID; struct StructCPIDCache;
Create a general interrupt handler
#include <rose/screen.h> #include <rose/descriptor-tables.h> extern void protected_mode_start(void); void kmain(void) { screen_clear(); gdt_init(); protected_mode_start(); screen_write_string_at("Hello from rOSe (in protected mode!)", 0, 0); }
#include <rose/screen.h> #include <rose/stdint.h> #include <rose/descriptor-tables.h> extern void protected_mode_start(void); struct registers { uint32_t ds; uint32_t edi; uint32_t esi; uint32_t ebp; uint32_t esp; uint32_t ebx; uint32_t edx; uint32_t ecx; uint32_t eax; uint32_t interrupt_no; uint32_t error_code; uint32_t eip; uint32_t cs; uint32_t eflags; } __attribute__((packed)); void general_isr(struct registers regs) { screen_write_string_at("Handling interrupt: 0x", 0, 1); screen_write_integer_at(regs.interrupt_no, 16, 22, 1); } void kmain(void) { screen_clear(); gdt_init(); protected_mode_start(); screen_write_string_at("Hello from rOSe (in protected mode!)", 0, 0); }
Convert tabs to spaces and indent
#define MODULE_NAME "fish" #include <irssi-config.h> #include <common.h> #include <core/servers.h> #include <core/settings.h> #include <core/levels.h> #include <core/signals.h> #include <core/commands.h> #include <core/queries.h> #include <core/channels.h> #include <core/recode.h> #include <core/servers.h> #include <fe-common/core/printtext.h> #include <fe-common/core/window-items.h> #include <fe-common/core/keyboard.h> #include <fe-common/irc/module-formats.h> #include <irc/core/irc.h> #ifdef ischannel #undef ischannel #endif #include <irc/core/irc-commands.h> #include <irc/core/irc-servers.h> void irssi_redraw(void); QUERY_REC *irc_query_create(const char *server_tag, const char *nick, int automatic);
#define MODULE_NAME "fish" #include <irssi-config.h> #include <common.h> #include <core/servers.h> #include <core/settings.h> #include <core/levels.h> #include <core/signals.h> #include <core/commands.h> #include <core/queries.h> #include <core/channels.h> #include <core/recode.h> #include <core/servers.h> #include <fe-common/core/printtext.h> #include <fe-common/core/window-items.h> #include <fe-common/core/keyboard.h> #include <fe-common/irc/module-formats.h> #include <irc/core/irc.h> #ifdef ischannel #undef ischannel #endif #include <irc/core/irc-commands.h> #include <irc/core/irc-servers.h> void irssi_redraw(void); QUERY_REC *irc_query_create(const char *server_tag, const char *nick, int automatic);
Fix undefined GLint in Mac builds
/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef SkMesaGLContext_DEFINED #define SkMesaGLContext_DEFINED #include "SkGLContext.h" #if SK_MESA class SkMesaGLContext : public SkGLContext { private: typedef intptr_t Context; public: SkMesaGLContext(); virtual ~SkMesaGLContext(); virtual void makeCurrent() const SK_OVERRIDE; class AutoContextRestore { public: AutoContextRestore(); ~AutoContextRestore(); private: Context fOldContext; GLint fOldWidth; GLint fOldHeight; GLint fOldFormat; void* fOldImage; }; protected: virtual const GrGLInterface* createGLContext() SK_OVERRIDE; virtual void destroyGLContext() SK_OVERRIDE; private: Context fContext; GrGLubyte *fImage; }; #endif #endif
/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef SkMesaGLContext_DEFINED #define SkMesaGLContext_DEFINED #include "SkGLContext.h" #if SK_MESA class SkMesaGLContext : public SkGLContext { private: typedef intptr_t Context; public: SkMesaGLContext(); virtual ~SkMesaGLContext(); virtual void makeCurrent() const SK_OVERRIDE; class AutoContextRestore { public: AutoContextRestore(); ~AutoContextRestore(); private: Context fOldContext; GrGLint fOldWidth; GrGLint fOldHeight; GrGLint fOldFormat; void* fOldImage; }; protected: virtual const GrGLInterface* createGLContext() SK_OVERRIDE; virtual void destroyGLContext() SK_OVERRIDE; private: Context fContext; GrGLubyte *fImage; }; #endif #endif
Add prototype to header file for compilation to succeed if no TFLM model included in Makefile
/* * Copyright 2021 The CFU-Playground Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _MODELS_H #define _MODELS_H #ifdef __cplusplus extern "C" { #endif // For integration into menu system void models_menu(); #ifdef __cplusplus } #endif #endif // _MODELS_H
/* * Copyright 2021 The CFU-Playground Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _MODELS_H #define _MODELS_H #ifdef __cplusplus extern "C" { #endif // For integration into menu system void models_menu(); void no_menu(); #ifdef __cplusplus } #endif #endif // _MODELS_H
Copy a constant value to a variable and print it
/* * printconst - Read a constant and print it * * Written in 2012 by Prashant P Shah <pshah.mumbai@gmail.com> * * To the extent possible under law, the author(s) have dedicated * all copyright and related and neighboring rights to this software * to the public domain worldwide. This software is distributed * without any warranty. * * You should have received a copy of the CC0 Public Domain Dedication * along with this software. * If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include <stdio.h> int main(int argc, char *argv[]) { int val = 0; asm("MOV $100, %0" : "=r"(val)); printf("val = %d\n", val); return 0; }
Implement a hash table in the kernel.
/* Copyright (c) 2021 Dennis Wölfing * * Permission to use, copy, modify, and/or 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. */ /* kernel/include/dennix/kernel/hashtable.h * Hash table. */ #ifndef KERNEL_HASHTABLE_H #define KERNEL_HASHTABLE_H #include <string.h> #include <dennix/kernel/kernel.h> // The type T must have a function hashKey() returning a unique TKey. It also // needs to have a member T* nextInHashTable that is managed by the hash table. // An object can only be member of one hash table at a time. That way we can // implement the hash table in a way that operations cannot fail. template <typename T, typename TKey = size_t> class HashTable { public: HashTable(size_t capacity, T* buffer[]) { table = buffer; memset(table, 0, capacity * sizeof(T*)); this->capacity = capacity; } void add(T* object) { size_t hash = object->hashKey() % capacity; object->nextInHashTable = table[hash]; table[hash] = object; } T* get(TKey key) { size_t hash = key % capacity; T* obj = table[hash]; while (obj) { if (obj->hashKey() == key) { return obj; } obj = obj->nextInHashTable; } return nullptr; } void remove(TKey key) { size_t hash = key % capacity; T* obj = table[hash]; if (obj->hashKey() == key) { table[hash] = obj->nextInHashTable; return; } while (obj->nextInHashTable) { T* next = obj->nextInHashTable; if (next->hashKey() == key) { obj->nextInHashTable = next->nextInHashTable; return; } obj = next; } } private: T** table; size_t capacity; }; #endif
Add basic test for incomplete structs
/* name: TEST034 description: Basic test for incomplete structures output: X3 S2 x F4 I E X5 F4 foo G6 F4 main { \ X7 S2 x r X7 'P #P0 !I } G5 F4 foo { \ X3 M9 .I #I0 :I r X3 M9 .I } */ extern struct X x; int foo(); int main() { extern struct X x; return &x != 0; } struct X {int v;}; int foo() { x.v = 0; return x.v; }
Fix this test to use -cc1.
// RUN: %clang -E %s | FileCheck %s #line 21 "" int foo() { return 42; } #line 4 "bug.c" int bar() { return 21; } // CHECK: # 21 "" // CHECK: int foo() { return 42; } // CHECK: # 4 "bug.c" // CHECK: int bar() { return 21; }
// RUN: %clang_cc1 -E %s | FileCheck %s #line 21 "" int foo() { return 42; } #line 4 "bug.c" int bar() { return 21; } // CHECK: # 21 "" // CHECK: int foo() { return 42; } // CHECK: # 4 "bug.c" // CHECK: int bar() { return 21; }
Remove error from Elektra struct
/** * @file * * @brief Private declarations. * * @copyright BSD License (see doc/LICENSE.md or http://www.libelektra.org) */ #ifndef ELEKTRAPRIVATE_H #define ELEKTRAPRIVATE_H #include "kdb.h" struct _ElektraError { int errorNr; const char * msg; }; struct _Elektra { KDB * kdb; KeySet * config; Key * parentKey; struct _ElektraError * error; }; #endif //ELEKTRAPRIVATE_H
/** * @file * * @brief Private declarations. * * @copyright BSD License (see doc/LICENSE.md or http://www.libelektra.org) */ #ifndef ELEKTRAPRIVATE_H #define ELEKTRAPRIVATE_H #include "kdb.h" struct _ElektraError { int errorNr; const char * msg; }; struct _Elektra { KDB * kdb; KeySet * config; Key * parentKey; }; #endif //ELEKTRAPRIVATE_H
Use "" instead of <> for local includes
/*! NFmiDictionaryFunction.h * Tämä on Editorin käyttämä sana kirja funktio. * Kieli versiot stringeihin tulevat täältä. */ #ifndef NFMIDICTIONARYFUNCTION_H #define NFMIDICTIONARYFUNCTION_H #include <NFmiSettings.h> // HUOM! Tämä on kopio NFmiEditMapGeneralDataDoc-luokan metodista, kun en voinut antaa tänne // dokumenttia std::string GetDictionaryString(const char *theMagicWord); #endif
/*! NFmiDictionaryFunction.h * Tämä on Editorin käyttämä sana kirja funktio. * Kieli versiot stringeihin tulevat täältä. */ #ifndef NFMIDICTIONARYFUNCTION_H #define NFMIDICTIONARYFUNCTION_H #include "NFmiSettings.h" // HUOM! Tämä on kopio NFmiEditMapGeneralDataDoc-luokan metodista, kun en voinut antaa tänne // dokumenttia std::string GetDictionaryString(const char *theMagicWord); #endif
ADD : Class implementing an Event storing a pointer to a itk::ProcessObject and a string describing it.
/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef __otbWrapperAddProcessToWatchEvent_h #define __otbWrapperAddProcessToWatchEvent_h #include "itkEventObject.h" #include "itkProcessObject.h" namespace otb { namespace Wrapper { /** \class AddProcessToWatchEvent * \brief This class implements an event storing a pointer to * itk::ProcessObject and a string describing the process. * */ class ITK_EXPORT AddProcessToWatchEvent: public itk::EventObject { public: typedef AddProcessToWatchEvent Self; typedef itk::EventObject Superclass; AddProcessToWatchEvent(){} AddProcessToWatchEvent(const Self& s) :itk::EventObject(s){}; virtual ~AddProcessToWatchEvent() {} /** Set/Get the process to watch */ virtual void SetProcess(itk::ProcessObject * process) { m_Process = process; } virtual itk::ProcessObject * GetProcess() const { return m_Process; } /** Set/Get the process description */ virtual void SetProcessDescription(const std::string desc) { m_ProcessDescription = desc; } virtual std::string GetProcessDescription() const { return m_ProcessDescription; } /** Virtual pure method to implement */ virtual itk::EventObject* MakeObject() const { return new Self; } virtual const char* GetEventName() const { return "AddProcess"; } virtual bool CheckEvent(const itk::EventObject* e) const { return dynamic_cast<const Self*>(e); } private: itk::ProcessObject::Pointer m_Process; std::string m_ProcessDescription; }; } } #endif
Make sure we include M_PI, and if the system does not define it for us, we'll give it our best shot.
/*** * @file mlpack_core.h * * Include all of the base components required to write MLPACK methods. */ #ifndef __MLPACK_CORE_H #define __MLPACK_CORE_H // First, standard includes. #include <stdlib.h> #include <stdio.h> #include <string.h> #include <ctype.h> #include <cmath> #include <math.h> #include <limits.h> #include <float.h> #include <stdint.h> #include <iostream> // And then the Armadillo library. #include <armadillo> // Now MLPACK-specific includes. #include <mlpack/core/data/dataset.h> #include <mlpack/core/math/math_lib.h> #include <mlpack/core/math/range.h> #include <mlpack/core/math/kernel.h> #include <mlpack/core/file/textfile.h> #include <mlpack/core/io/io.h> #include <mlpack/core/arma_extend/arma_extend.h> #endif
/*** * @file mlpack_core.h * * Include all of the base components required to write MLPACK methods. */ #ifndef __MLPACK_CORE_H #define __MLPACK_CORE_H // First, standard includes. #include <stdlib.h> #include <stdio.h> #include <string.h> #include <ctype.h> #include <limits.h> #include <float.h> #include <stdint.h> #include <iostream> // Defining __USE_MATH_DEFINES should set M_PI. #define _USE_MATH_DEFINES #include <math.h> // But if it's not defined, we'll do it. #ifndef M_PI #define M_PI 3.141592653589793238462643383279 #endif // And then the Armadillo library. #include <armadillo> // Now MLPACK-specific includes. #include <mlpack/core/data/dataset.h> #include <mlpack/core/math/math_lib.h> #include <mlpack/core/math/range.h> #include <mlpack/core/math/kernel.h> #include <mlpack/core/file/textfile.h> #include <mlpack/core/io/io.h> #include <mlpack/core/arma_extend/arma_extend.h> #endif
Add fields to the plugin struct
#if !defined(_INTELLIBOT_H) #define _INTELLIBOT_H #include <sys/types.h> #include <time.h> #include "queue.h" #include "sock.h" struct _intellibot; struct _server; struct _plugin; struct _plugin_ctx; struct _queue; #define SOCK_FLAG_DISCONNECTED 0 #define SOCK_FLAG_CONNECTED 1 #define SOCK_FLAG_REGISTERED 2 typedef struct _server { SOCK *sock; struct _server *prev, *next; } SERVER; typedef struct _plugin_ctx { struct _plugin *plugin; struct _intellibot *bot; void *ctx; } PLUGIN_CTX; typedef struct _plugin { void *handle; void *ctx; QUEUE *queue; struct _plugin *prev, *next; } PLUGIN; typedef struct _intellibot { PLUGIN *plugins; SERVER *servers; } INTELLIBOT; #endif
#if !defined(_INTELLIBOT_H) #define _INTELLIBOT_H #include <sys/types.h> #include <time.h> #include "queue.h" #include "sock.h" struct _intellibot; struct _server; struct _plugin; struct _plugin_ctx; struct _queue; #define SOCK_FLAG_DISCONNECTED 0 #define SOCK_FLAG_CONNECTED 1 #define SOCK_FLAG_REGISTERED 2 typedef struct _server { SOCK *sock; struct _server *prev, *next; } SERVER; typedef struct _plugin_ctx { struct _plugin *plugin; struct _intellibot *bot; void *ctx; } PLUGIN_CTX; #define SUBSCRIPTION_JOIN 0x00000001 #define SUBSCRIPTION_PART 0x00000002 #define SUBSCRIPTION_CONNECT 0x00000004 #define SUBSCRIPTION_DISCONNECT 0x00000008 #define SUBSCRIPTION_PRIVMSG 0x00000010 typedef struct _plugin { pthread_t tid; void *handle; void *ctx; unsigned int subscriptions; QUEUE *queue; int (*run)(struct _plugin *, char *); struct _plugin *prev, *next; } PLUGIN; typedef struct _intellibot { PLUGIN *plugins; SERVER *servers; } INTELLIBOT; #endif
Modify sim-hab so that the digital inputs are accounted for.
#include "sim-hab.h" #include <stdlib.h> int poll_arduino() { char response[256]; uint32_t content; bionet_resource_t *res; bionet_node_t *node; node = bionet_hab_get_node_by_index(hab, 0); // send command 100. requests analog0's value // read value and set resource arduino_write(100); arduino_read_until(response, '\n'); content = atoi(response); res = bionet_node_get_resource_by_index(node, 24); bionet_resource_set_uint32(res, content, NULL); // send command 101. requests analog1's value // read value and set resource arduino_write(101); arduino_read_until(response, '\n'); content = atoi(response); res = bionet_node_get_resource_by_index(node, 25); bionet_resource_set_uint32(res, content, NULL); // testing arduino_write(200); arduino_read_until(response, '\n'); content = atoi(response); printf("digital 0: %d\n", content); // report new data hab_report_datapoints(node); return 1; }
#include "sim-hab.h" #include <stdlib.h> int poll_arduino() { char response[256]; uint32_t content; bionet_resource_t *res; bionet_node_t *node; node = bionet_hab_get_node_by_index(hab, 0); // send command 100. requests analog0's value // read value and set resource arduino_write(100); arduino_read_until(response, '\n'); content = atoi(response); res = bionet_node_get_resource_by_index(node, 24); bionet_resource_set_uint32(res, content, NULL); // send command 101. requests analog1's value // read value and set resource arduino_write(101); arduino_read_until(response, '\n'); content = atoi(response); res = bionet_node_get_resource_by_index(node, 25); bionet_resource_set_uint32(res, content, NULL); // send command 200. requests the 8 digital values // read values and set resource arduino_write(200); arduino_read_until(response, '\n'); for(int i=0; i<8; i++) { content = atoi(&response[i]); res = bionet_node_get_resource_by_index(node, 16+i); bionet_resource_set_binary(res, content, NULL); } // report new data hab_report_datapoints(node); return 1; }
Add static function to convert NPN strings to an enum.
// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef NET_SOCKET_SSL_CLIENT_SOCKET_H_ #define NET_SOCKET_SSL_CLIENT_SOCKET_H_ #include "net/socket/client_socket.h" namespace net { class SSLCertRequestInfo; class SSLInfo; // A client socket that uses SSL as the transport layer. // // NOTE: The SSL handshake occurs within the Connect method after a TCP // connection is established. If a SSL error occurs during the handshake, // Connect will fail. // class SSLClientSocket : public ClientSocket { public: // Gets the SSL connection information of the socket. virtual void GetSSLInfo(SSLInfo* ssl_info) = 0; // Gets the SSL CertificateRequest info of the socket after Connect failed // with ERR_SSL_CLIENT_AUTH_CERT_NEEDED. virtual void GetSSLCertRequestInfo( SSLCertRequestInfo* cert_request_info) = 0; }; } // namespace net #endif // NET_SOCKET_SSL_CLIENT_SOCKET_H_
// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef NET_SOCKET_SSL_CLIENT_SOCKET_H_ #define NET_SOCKET_SSL_CLIENT_SOCKET_H_ #include "net/socket/client_socket.h" namespace net { class SSLCertRequestInfo; class SSLInfo; // A client socket that uses SSL as the transport layer. // // NOTE: The SSL handshake occurs within the Connect method after a TCP // connection is established. If a SSL error occurs during the handshake, // Connect will fail. // class SSLClientSocket : public ClientSocket { public: // Next Protocol Negotiation (NPN), if successful, results in agreement on an // application-level string that specifies the application level protocol to // use over the TLS connection. NextProto enumerates the application level // protocols that we recognise. enum NextProto { kProtoUnknown = 0, kProtoHTTP11 = 1, kProtoSPDY = 2, }; // Gets the SSL connection information of the socket. virtual void GetSSLInfo(SSLInfo* ssl_info) = 0; // Gets the SSL CertificateRequest info of the socket after Connect failed // with ERR_SSL_CLIENT_AUTH_CERT_NEEDED. virtual void GetSSLCertRequestInfo( SSLCertRequestInfo* cert_request_info) = 0; static NextProto NextProtoFromString(const std::string& proto_string) { if (proto_string == "http1.1") { return kProtoHTTP11; } else if (proto_string == "spdy") { return kProtoSPDY; } else { return kProtoUnknown; } } }; } // namespace net #endif // NET_SOCKET_SSL_CLIENT_SOCKET_H_
Fix SDLProtocol delegate table being released too early
// SDLAbstractProtocol.h // @class SDLAbstractTransport; @class SDLRPCMessage; @class SDLRPCRequest; #import "SDLProtocolListener.h" #import "SDLTransportDelegate.h" @interface SDLAbstractProtocol : NSObject <SDLTransportDelegate> @property (strong) NSString *debugConsoleGroupName; @property (weak) SDLAbstractTransport *transport; @property (weak) NSHashTable *protocolDelegateTable; // table of id<SDLProtocolListener> // Sending - (void)sendStartSessionWithType:(SDLServiceType)serviceType; - (void)sendEndSessionWithType:(SDLServiceType)serviceType; - (void)sendRPC:(SDLRPCMessage *)message; - (void)sendRPCRequest:(SDLRPCRequest *)rpcRequest __deprecated_msg(("Use sendRPC: instead")); - (void)sendHeartbeat; - (void)sendRawDataStream:(NSInputStream *)inputStream withServiceType:(SDLServiceType)serviceType; - (void)sendRawData:(NSData *)data withServiceType:(SDLServiceType)serviceType; // Recieving - (void)handleBytesFromTransport:(NSData *)receivedData; - (void)dispose; @end
// SDLAbstractProtocol.h // @class SDLAbstractTransport; @class SDLRPCMessage; @class SDLRPCRequest; #import "SDLProtocolListener.h" #import "SDLTransportDelegate.h" @interface SDLAbstractProtocol : NSObject <SDLTransportDelegate> @property (strong) NSString *debugConsoleGroupName; @property (weak) SDLAbstractTransport *transport; @property (strong) NSHashTable *protocolDelegateTable; // table of id<SDLProtocolListener> // Sending - (void)sendStartSessionWithType:(SDLServiceType)serviceType; - (void)sendEndSessionWithType:(SDLServiceType)serviceType; - (void)sendRPC:(SDLRPCMessage *)message; - (void)sendRPCRequest:(SDLRPCRequest *)rpcRequest __deprecated_msg(("Use sendRPC: instead")); - (void)sendHeartbeat; - (void)sendRawDataStream:(NSInputStream *)inputStream withServiceType:(SDLServiceType)serviceType; - (void)sendRawData:(NSData *)data withServiceType:(SDLServiceType)serviceType; // Recieving - (void)handleBytesFromTransport:(NSData *)receivedData; - (void)dispose; @end
Solve Collectable Cards in c
#include <stdint.h> #include <stdio.h> int gcd(int a, int b) { int32_t x; while (b > 0) { x = b; b = a % b; a = x; } return a; } int main() { int32_t n, a, b; scanf("%d", &n); while (n--) { scanf("%d %d", &a, &b); printf("%d\n", gcd(a, b)); } return 0; }
Fix os_SUITE compilation issue on win32
#ifdef __WIN32__ #include <windows.h> int wmain(int argc, wchar_t **argv) { char* sep = ""; int len; /* * Echo all arguments separated with '::', so that we can check that * quotes are interpreted correctly. */ while (argc-- > 1) { char *utf8; len = WideCharToMultiByte(CP_UTF8, 0, argv[1], -1, NULL, 0, NULL, NULL); utf8 = malloc(len*sizeof(char)); WideCharToMultiByte(CP_UTF8, 0, argv++[1], -1, utf8, len, NULL, NULL); printf("%s%s", sep, utf8); free(utf8); sep = "::"; } putchar('\n'); return 0; } #else #include <stdio.h> int main(int argc, char** argv) { char* sep = ""; /* * Echo all arguments separated with '::', so that we can check that * quotes are interpreted correctly. */ while (argc-- > 1) { printf("%s%s", sep, argv++[1]); sep = "::"; } putchar('\n'); return 0; } #endif
#include <stdio.h> #ifdef __WIN32__ #include <windows.h> int wmain(int argc, wchar_t **argv) { char* sep = ""; int len; /* * Echo all arguments separated with '::', so that we can check that * quotes are interpreted correctly. */ while (argc-- > 1) { char *utf8; len = WideCharToMultiByte(CP_UTF8, 0, argv[1], -1, NULL, 0, NULL, NULL); utf8 = malloc(len*sizeof(char)); WideCharToMultiByte(CP_UTF8, 0, argv++[1], -1, utf8, len, NULL, NULL); printf("%s%s", sep, utf8); free(utf8); sep = "::"; } putchar('\n'); return 0; } #else int main(int argc, char** argv) { char* sep = ""; /* * Echo all arguments separated with '::', so that we can check that * quotes are interpreted correctly. */ while (argc-- > 1) { printf("%s%s", sep, argv++[1]); sep = "::"; } putchar('\n'); return 0; } #endif
FIX duplicate includes of GraphicsHandler
#ifndef SSPAPPLICATION_COMPONENTHANDLER_H #define SSPAPPLICATION_COMPONENTHANDLER_H #include "../GraphicsDLL/GraphicsHandler.h" //#include "ComponentStructs.h" #include "../GraphicsDLL/GraphicsHandler.h" #include "../physicsDLL/PhysicsHandler.h" #include "../AIDLL/AIHandler.h" class ComponentHandler { private: GraphicsHandler* m_graphicsHandler; PhysicsHandler* m_physicsHandler; AIHandler* m_aiHandler; public: ComponentHandler(); ~ComponentHandler(); //Returns 0 if the graphicsHandler or physicshandler is a nullptr int Initialize(GraphicsHandler* graphicsHandler, PhysicsHandler* physicsHandler, AIHandler* aiHandler); GraphicsComponent* GetGraphicsComponent(); PhysicsComponent* GetPhysicsComponent(); void UpdateGraphicsComponents(); void SetGraphicsComponentListSize(int gCompSize); //temporary function PhysicsHandler* GetPhysicsHandler() const; }; #endif
#ifndef SSPAPPLICATION_COMPONENTHANDLER_H #define SSPAPPLICATION_COMPONENTHANDLER_H //#include "ComponentStructs.h" #include "../GraphicsDLL/GraphicsHandler.h" #include "../physicsDLL/PhysicsHandler.h" #include "../AIDLL/AIHandler.h" class ComponentHandler { private: GraphicsHandler* m_graphicsHandler; PhysicsHandler* m_physicsHandler; AIHandler* m_aiHandler; public: ComponentHandler(); ~ComponentHandler(); //Returns 0 if the graphicsHandler or physicshandler is a nullptr int Initialize(GraphicsHandler* graphicsHandler, PhysicsHandler* physicsHandler, AIHandler* aiHandler); GraphicsComponent* GetGraphicsComponent(); PhysicsComponent* GetPhysicsComponent(); void UpdateGraphicsComponents(); void SetGraphicsComponentListSize(int gCompSize); //temporary function PhysicsHandler* GetPhysicsHandler() const; }; #endif
Fix implicit conversion warning when building with floating point Lua
/** * \file string_hash.c * \brief Computes a hash value for a string. * \author Copyright (c) 2012-2014 Jason Perkins and the Premake project */ #include "premake.h" #include <string.h> int string_hash(lua_State* L) { const char* str = luaL_checkstring(L, 1); unsigned long seed = luaL_optint(L, 2, 0); lua_pushnumber(L, do_hash(str, seed)); return 1; } unsigned long do_hash(const char* str, int seed) { /* DJB2 hashing; see http://www.cse.yorku.ca/~oz/hash.html */ unsigned long hash = 5381; if (seed != 0) { hash = hash * 33 + seed; } while (*str) { hash = hash * 33 + (*str); str++; } return hash; }
/** * \file string_hash.c * \brief Computes a hash value for a string. * \author Copyright (c) 2012-2014 Jason Perkins and the Premake project */ #include "premake.h" #include <string.h> int string_hash(lua_State* L) { const char* str = luaL_checkstring(L, 1); unsigned long seed = luaL_optint(L, 2, 0); lua_pushnumber(L, (lua_Number)do_hash(str, seed)); return 1; } unsigned long do_hash(const char* str, int seed) { /* DJB2 hashing; see http://www.cse.yorku.ca/~oz/hash.html */ unsigned long hash = 5381; if (seed != 0) { hash = hash * 33 + seed; } while (*str) { hash = hash * 33 + (*str); str++; } return hash; }
Add test case for PR 3675.
// RUN: clang -verify %s // // This example was reduced from actual code in Wine 1.1.13. GCC accepts this // code, while the correct behavior is to reject it. // typedef struct _IRP { union { struct { union {} u; // expected-note{{previous declaration is here}} struct { union {} u; // expected-error{{error: member of anonymous struct redeclares 'u'}} }; } Overlay; } Tail; } IRP;
Use clang-cc in this test.
// RUN: clang -ccc-host-triple armv6-unknown-unknown -emit-llvm -S -o %t %s void test0(void) { asm volatile("mov r0, r0" :: ); } void test1(void) { asm volatile("mov r0, r0" ::: "cc", "memory" ); } void test2(void) { asm volatile("mov r0, r0" ::: "r0", "r1", "r2", "r3"); asm volatile("mov r0, r0" ::: "r4", "r5", "r6", "r8"); } void test3(void) { asm volatile("mov r0, r0" ::: "a1", "a2", "a3", "a4"); asm volatile("mov r0, r0" ::: "v1", "v2", "v3", "v5"); }
// RUN: clang-cc -triple armv6-unknown-unknown -emit-llvm -o %t %s void test0(void) { asm volatile("mov r0, r0" :: ); } void test1(void) { asm volatile("mov r0, r0" ::: "cc", "memory" ); } void test2(void) { asm volatile("mov r0, r0" ::: "r0", "r1", "r2", "r3"); asm volatile("mov r0, r0" ::: "r4", "r5", "r6", "r8"); } void test3(void) { asm volatile("mov r0, r0" ::: "a1", "a2", "a3", "a4"); asm volatile("mov r0, r0" ::: "v1", "v2", "v3", "v5"); }
Define ODP_THREAD_WORKER and ODP_THREAD_CONTROL for odp versions < 102.
/* Copyright (c) 2015, ENEA Software AB * Copyright (c) 2015, Nokia * All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ #if ODP_VERSION < 105 typedef uint64_t odp_time_t; #endif /* ODP_VERSION < 105 */ #if ODP_VERSION < 104 && ODP_VERSION > 101 #define odp_cpumask_default_worker(cpumask, num_workers) odp_cpumask_def_worker(cpumask, num_workers) #elif ODP_VERSION < 102 #define odp_cpumask_default_worker(cpumask, num_workers) odp_cpumask_count(cpumask) #endif
/* Copyright (c) 2015, ENEA Software AB * Copyright (c) 2015, Nokia * All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ #if ODP_VERSION < 105 typedef uint64_t odp_time_t; #endif /* ODP_VERSION < 105 */ #if ODP_VERSION < 104 && ODP_VERSION > 101 #define odp_cpumask_default_worker(cpumask, num_workers) odp_cpumask_def_worker(cpumask, num_workers) #elif ODP_VERSION < 102 #define odp_cpumask_default_worker(cpumask, num_workers) odp_cpumask_count(cpumask) #define ODP_THREAD_WORKER #define ODP_THREAD_CONTROL #endif
Add "equal to" operator to Vector3
#pragma once template <typename T> class Vector3 { public: T x, y, z; Vector3(T x, T y, T z) { this->x = x; this->y = y; this->z = z; } Vector3() : Vector3(0, 0, 0) { } T &operator[](unsigned i) { return (&x)[i]; } }; static_assert(sizeof(Vector3<float>) == 12); template <typename T> class Vector4 { public: T x, y, z, w; Vector4() {} Vector4(T x, T y, T z, T w) { this->x = x; this->y = y; this->z = z; this->w = w; } T &operator[](unsigned i) { return (&x)[i]; } };
#pragma once template <typename T> class Vector3 { public: T x, y, z; Vector3(T x, T y, T z) { this->x = x; this->y = y; this->z = z; } Vector3() : Vector3(0, 0, 0) { } T &operator[](unsigned i) { return (&x)[i]; } bool operator==(const Vector3 &v) const { return x == v.x && y == v.y && z == v.z; } }; static_assert(sizeof(Vector3<float>) == 12); template <typename T> class Vector4 { public: T x, y, z, w; Vector4() {} Vector4(T x, T y, T z, T w) { this->x = x; this->y = y; this->z = z; this->w = w; } T &operator[](unsigned i) { return (&x)[i]; } };
Add test of clone syscall with CLONE_THREAD
#define _GNU_SOURCE #include <stdio.h> #include <unistd.h> #include <sched.h> #include <stdlib.h> #define CHILD_STACK_SIZE 16384 int variable; int do_something() { printf("Running...\n"); variable = 1337; _exit(0); } int main(int argc, char *argv[]) { char *child_stack; char *child_stack_top; child_stack = malloc(CHILD_STACK_SIZE); child_stack_top = child_stack + CHILD_STACK_SIZE; variable = 42; printf("The variable was %d\n", variable); clone(do_something, child_stack_top, CLONE_THREAD, NULL); sleep(10); printf("The variable is now %d\n", variable); return 0; }
Add lazy property synthesis directives
// // SMRPreprocessor.h // MicroReasoner // // Created by Ivano Bilenchi on 05/05/16. // Copyright © 2016 SisInf Lab. All rights reserved. // #ifndef SMRPreprocessor_h #define SMRPreprocessor_h // Pseudo-abstract class convenience macros. #define ABSTRACT_METHOD {\ @throw [NSException exceptionWithName:NSInternalInconsistencyException \ reason:@"This method should be overridden in a subclass." \ userInfo:nil]; \ } #endif /* SMRPreprocessor_h */
// // SMRPreprocessor.h // MicroReasoner // // Created by Ivano Bilenchi on 05/05/16. // Copyright © 2016 SisInf Lab. All rights reserved. // #ifndef SMRPreprocessor_h #define SMRPreprocessor_h /** * Use this directive to mark method implementations that should be overridden * by concrete subclasses. */ #define ABSTRACT_METHOD {\ @throw [NSException exceptionWithName:NSInternalInconsistencyException \ reason:@"This method should be overridden in a subclass." \ userInfo:nil]; \ } /** * Use this directive in place of @synthesize to automatically create a * lazy getter for the specified property. Example syntax: * * SYNTHESIZE_LAZY(NSMutableString, myMutableString) { * return [NSMutableString stringWithString:@"my mutable string"]; * } * * @param type The type of the property. * @param name The name of the property. */ #define SYNTHESIZE_LAZY(type, name) \ @synthesize name = _##name; \ - (type *)name { \ if (_##name == nil) { _##name = [self __##name##LazyInit]; } \ return _##name; \ } \ - (type *)__##name##LazyInit /** * Use this directive in place of @synthesize to automatically create a * lazy getter for the specified property. The getter calls the default * 'init' constructor. * * @param type The type of the property. * @param name The name of the property. */ #define SYNTHESIZE_LAZY_INIT(type, name) \ @synthesize name = _##name; \ - (type *)name { \ if (_##name == nil) { _##name = [[type alloc] init]; } \ return _##name; \ } #endif /* SMRPreprocessor_h */
Test case for r154451 (redefining system functions).
// RUN: %clang_cc1 -analyze -analyzer-checker=unix,core,experimental.security.taint -w -verify %s // Make sure we don't crash when someone redefines a system function we reason about. char memmove (); char malloc(); char system(); char stdin(); char memccpy(); char free(); char strdup(); char atoi(); int foo () { return memmove() + malloc() + system + stdin() + memccpy() + free() + strdup() + atoi(); }
Remove old UIContext class declaration
#pragma once #include <Windows.h> #include <unordered_map> #include "../Controls/Control.h" #include "../Controls/Controls.h" class UIContext; #define INIT_CONTROL(ctrlId, ctrlType, var) { \ var = ctrlType(ctrlId, _hWnd); \ _controlMap[ctrlId] = &var; \ } /// <summary> /// Abstract class that encapsulates functionality for dealing with /// property sheet pages (tabs). /// </summary> class Tab { public: Tab(); ~Tab(); /// <summary>Processes messages sent to the tab page.</summary> virtual DLGPROC TabProc( HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam); /// <summary>Persists changes made on the tab page</summary> virtual void SaveSettings() = 0; protected: /// <summary>Window handle of this tab.</summary> HWND _hWnd; /// <summary>Maps control IDs to their respective instances.</summary> std::unordered_map<int, Control *> _controlMap; /// <summary> /// Performs intitialization for the tab page, similar to a constructor. /// Since tab page windows are created on demand, this method could be /// called much later than the constructor for the tab. /// </summary> virtual void Initialize() = 0; /// <summary>Applies the current settings state to the tab page.</summary> virtual void LoadSettings() = 0; };
#pragma once #include <Windows.h> #include <unordered_map> #include "../Controls/Control.h" #include "../Controls/Controls.h" #define INIT_CONTROL(ctrlId, ctrlType, var) { \ var = ctrlType(ctrlId, _hWnd); \ _controlMap[ctrlId] = &var; \ } /// <summary> /// Abstract class that encapsulates functionality for dealing with /// property sheet pages (tabs). /// </summary> class Tab { public: Tab(); ~Tab(); /// <summary>Processes messages sent to the tab page.</summary> virtual DLGPROC TabProc( HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam); /// <summary>Persists changes made on the tab page</summary> virtual void SaveSettings() = 0; protected: /// <summary>Window handle of this tab.</summary> HWND _hWnd; /// <summary>Maps control IDs to their respective instances.</summary> std::unordered_map<int, Control *> _controlMap; /// <summary> /// Performs intitialization for the tab page, similar to a constructor. /// Since tab page windows are created on demand, this method could be /// called much later than the constructor for the tab. /// </summary> virtual void Initialize() = 0; /// <summary>Applies the current settings state to the tab page.</summary> virtual void LoadSettings() = 0; };
Add separate header for stream operators.
#pragma once #include "jwt.h" #include <ostream> namespace JWTXX { std::ostream& operator<<(std::ostream& stream, const Algorithm& alg) { stream << algToString(alg); return stream; } }