Instruction
stringlengths
14
778
input_code
stringlengths
0
4.24k
output_code
stringlengths
1
5.44k
Add a local memory vector implementation
/* * Lift * * Copyright (c) 2014-2015, NVIDIA CORPORATION * Copyright (c) 2015, Nuno Subtil <subtil@gmail.com> * Copyright (c) 2015, Roche Molecular Systems Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once namespace lift { #include "../types.h" #include "../backends.h" #include "../decorators.h" // a statically-sized local memory vector template <typename T, uint32 max_storage_size> struct local_memory { typedef T value_type; typedef T& reference; typedef const T& const_reference; typedef T* pointer; typedef const T* const_pointer; typedef uint32 index_type; typedef uint32 size_type; value_type storage[max_storage_size]; size_type storage_size = max_storage_size; LIFT_HOST_DEVICE local_memory() = default; LIFT_HOST_DEVICE void resize(size_type count) { storage_size = count; } LIFT_HOST_DEVICE size_type size(void) const { return storage_size; } LIFT_HOST_DEVICE pointer data(void) { return storage; } LIFT_HOST_DEVICE const_pointer data(void) const { return storage; } LIFT_HOST_DEVICE reference operator[] (const size_type index) { return storage[index]; } LIFT_HOST_DEVICE const_reference operator[] (const size_type index) const { return storage[index]; } }; } // namespace lift
Replace removed Pointer_stringify with UTF8ToString
#include "emscripten.h" #include <stdlib.h> #include <unistd.h> #include "param.h" int os_preamble() { if (access("/dev/zero", R_OK)) EM_ASM(({ FS.createDevice('/dev', 'zero', function () { return 0; }); }),/* dummy arg */0); EM_ASM_(({ if (ENVIRONMENT_IS_NODE) { var mnt = Pointer_stringify($0); FS.mkdir(mnt); FS.mount(NODEFS, { root: '/' }, mnt); FS.chdir(mnt + process.cwd()); } }), MOUNT_POINT); return 0; }
#include "emscripten.h" #include <stdlib.h> #include <unistd.h> #include "param.h" int os_preamble() { if (access("/dev/zero", R_OK)) EM_ASM(({ FS.createDevice('/dev', 'zero', function () { return 0; }); }),/* dummy arg */0); EM_ASM_(({ if (ENVIRONMENT_IS_NODE) { var len = 1024; /* arbitrary */ var mnt = UTF8ToString($0, len); FS.mkdir(mnt); FS.mount(NODEFS, { root: '/' }, mnt); FS.chdir(mnt + process.cwd()); } }), MOUNT_POINT); return 0; }
Make this test darwin specific.
// RUN: %llvmgcc -S -O2 -g %s -o - | llc -O2 -o %t.s // RUN: grep "# DW_TAG_formal_parameter" %t.s | count 4 // Radar 8122864 // XFAIL: powerpc static int foo(int a, int j) { int k = 0; if (a) k = a + j; else k = j; return k; } int bar(int o, int p) { return foo(o, p); }
// RUN: %llvmgcc -S -O2 -g %s -o - | llc -O2 -o %t.s // RUN: grep "# DW_TAG_formal_parameter" %t.s | count 4 // Radar 8122864 // XTARGET: x86,darwin static int foo(int a, int j) { int k = 0; if (a) k = a + j; else k = j; return k; } int bar(int o, int p) { return foo(o, p); }
Mark the copied-in data as being present before flushing the buffer. Without this patch, no data is ever written.
#include <unistd.h> #include "iobuf.h" /** Copy all the data from an \c ibuf to an \c obuf. */ int obuf_copyfromfd(int in, obuf* out) { long rd; if (obuf_error(out)) return 0; out->count = 0; for (;;) { if ((rd = read(in, out->io.buffer + out->bufpos, out->io.bufsize - out->bufpos)) == -1) return 0; if (rd == 0) break; out->count += rd; if (!obuf_flush(out)) return 0; } return 1; }
#include <unistd.h> #include "iobuf.h" /** Copy all the data from an \c ibuf to an \c obuf. */ int obuf_copyfromfd(int in, obuf* out) { long rd; if (obuf_error(out)) return 0; out->count = 0; for (;;) { if ((rd = read(in, out->io.buffer + out->bufpos, out->io.bufsize - out->bufpos)) == -1) return 0; if (rd == 0) break; out->bufpos += rd; if (out->io.buflen < out->bufpos) out->io.buflen = out->bufpos; if (!obuf_flush(out)) return 0; out->count += rd; } return 1; }
Use new API for and parsing
#include "test_parser.h" void and_false(void **state) { grammar_t *grammar = grammar_init( non_terminal("And"), rule_init( "And", sequence( and(terminal("hello")), terminal("h") ) ), 1 ); parse_t *result = parse("help", grammar); assert_null(result); } void and_true(void **state) { grammar_t *grammar = grammar_init( non_terminal("And"), rule_init( "And", sequence( and(terminal("hello")), terminal("h") ) ), 1 ); parse_t *result = parse("hello", grammar); assert_non_null(result); assert_int_equal(result->length, 1); assert_int_equal(result->n_children, 1); assert_int_equal(result->children[0].length, 1); assert_int_equal(result->children[0].n_children, 0); }
#include "test_parser.h" void and_false(void **state) { grammar_t *grammar = grammar_init( non_terminal("And"), rule_init( "And", sequence( and(terminal("hello")), terminal("h") ) ), 1 ); parse_result_t *result = parse("help", grammar); assert_non_null(result); assert_true(is_error(result)); } void and_true(void **state) { grammar_t *grammar = grammar_init( non_terminal("And"), rule_init( "And", sequence( and(terminal("hello")), terminal("h") ) ), 1 ); parse_result_t *result = parse("hello", grammar); assert_non_null(result); assert_true(is_success(result)); parse_t *suc = result->data.result; assert_int_equal(suc->length, 1); assert_int_equal(suc->n_children, 1); assert_int_equal(suc->children[0].length, 1); assert_int_equal(suc->children[0].n_children, 0); }
Add header that was accidentally left out of r231724.
//===------ JITSymbolFlags.h - Flags for symbols in the JIT -----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Symbol flags for symbols in the JIT (e.g. weak, exported). // //===----------------------------------------------------------------------===// #ifndef LLVM_EXECUTIONENGINE_JITSYMBOLFLAGS_H #define LLVM_EXECUTIONENGINE_JITSYMBOLFLAGS_H #include "llvm/IR/GlobalValue.h" namespace llvm { /// @brief Flags for symbols in the JIT. enum class JITSymbolFlags : char { None = 0, Weak = 1U << 0, Exported = 1U << 1 }; JITSymbolFlags operator|(JITSymbolFlags LHS, JITSymbolFlags RHS) { typedef std::underlying_type<JITSymbolFlags>::type UT; return static_cast<JITSymbolFlags>( static_cast<UT>(LHS) | static_cast<UT>(RHS)); } JITSymbolFlags& operator |=(JITSymbolFlags &LHS, JITSymbolFlags RHS) { LHS = LHS | RHS; return LHS; } JITSymbolFlags operator&(JITSymbolFlags LHS, JITSymbolFlags RHS) { typedef std::underlying_type<JITSymbolFlags>::type UT; return static_cast<JITSymbolFlags>( static_cast<UT>(LHS) & static_cast<UT>(RHS)); } JITSymbolFlags& operator &=(JITSymbolFlags &LHS, JITSymbolFlags RHS) { LHS = LHS & RHS; return LHS; } /// @brief Base class for symbols in the JIT. class JITSymbolBase { public: JITSymbolBase(JITSymbolFlags Flags) : Flags(Flags) {} JITSymbolFlags getFlags() const { return Flags; } bool isWeak() const { return (Flags & JITSymbolFlags::Weak) == JITSymbolFlags::Weak; } bool isExported() const { return (Flags & JITSymbolFlags::Exported) == JITSymbolFlags::Exported; } static JITSymbolFlags flagsFromGlobalValue(const GlobalValue &GV) { JITSymbolFlags Flags = JITSymbolFlags::None; if (GV.hasWeakLinkage()) Flags |= JITSymbolFlags::Weak; if (!GV.hasLocalLinkage() && !GV.hasHiddenVisibility()) Flags |= JITSymbolFlags::Exported; return Flags; } private: JITSymbolFlags Flags; }; } // end namespace llvm #endif
Use correct variable for number of tests
#include <stdlib.h> #include <stdio.h> #include <check.h> #include "check_check.h" int main (void) { int n; SRunner *sr; fork_setup(); setup_fixture(); sr = srunner_create (make_master_suite()); srunner_add_suite(sr, make_list_suite()); srunner_add_suite(sr, make_msg_suite()); srunner_add_suite(sr, make_log_suite()); srunner_add_suite(sr, make_limit_suite()); srunner_add_suite(sr, make_fork_suite()); srunner_add_suite(sr, make_fixture_suite()); srunner_add_suite(sr, make_pack_suite()); setup(); printf ("Ran %d tests in subordinate suite\n", sub_nfailed); srunner_run_all (sr, CK_NORMAL); cleanup(); fork_teardown(); teardown_fixture(); n = srunner_ntests_failed(sr); srunner_free(sr); return (n == 0) ? EXIT_SUCCESS : EXIT_FAILURE; }
#include <stdlib.h> #include <stdio.h> #include <check.h> #include "check_check.h" int main (void) { int n; SRunner *sr; fork_setup(); setup_fixture(); sr = srunner_create (make_master_suite()); srunner_add_suite(sr, make_list_suite()); srunner_add_suite(sr, make_msg_suite()); srunner_add_suite(sr, make_log_suite()); srunner_add_suite(sr, make_limit_suite()); srunner_add_suite(sr, make_fork_suite()); srunner_add_suite(sr, make_fixture_suite()); srunner_add_suite(sr, make_pack_suite()); setup(); printf ("Ran %d tests in subordinate suite\n", sub_ntests); srunner_run_all (sr, CK_NORMAL); cleanup(); fork_teardown(); teardown_fixture(); n = srunner_ntests_failed(sr); srunner_free(sr); return (n == 0) ? EXIT_SUCCESS : EXIT_FAILURE; }
Use correct variable for number of tests
#include <stdlib.h> #include <stdio.h> #include <check.h> #include "check_check.h" int main (void) { int n; SRunner *sr; fork_setup(); setup_fixture(); sr = srunner_create (make_master_suite()); srunner_add_suite(sr, make_list_suite()); srunner_add_suite(sr, make_msg_suite()); srunner_add_suite(sr, make_log_suite()); srunner_add_suite(sr, make_limit_suite()); srunner_add_suite(sr, make_fork_suite()); srunner_add_suite(sr, make_fixture_suite()); srunner_add_suite(sr, make_pack_suite()); setup(); printf ("Ran %d tests in subordinate suite\n", sub_nfailed); srunner_run_all (sr, CK_NORMAL); cleanup(); fork_teardown(); teardown_fixture(); n = srunner_ntests_failed(sr); srunner_free(sr); return (n == 0) ? EXIT_SUCCESS : EXIT_FAILURE; }
#include <stdlib.h> #include <stdio.h> #include <check.h> #include "check_check.h" int main (void) { int n; SRunner *sr; fork_setup(); setup_fixture(); sr = srunner_create (make_master_suite()); srunner_add_suite(sr, make_list_suite()); srunner_add_suite(sr, make_msg_suite()); srunner_add_suite(sr, make_log_suite()); srunner_add_suite(sr, make_limit_suite()); srunner_add_suite(sr, make_fork_suite()); srunner_add_suite(sr, make_fixture_suite()); srunner_add_suite(sr, make_pack_suite()); setup(); printf ("Ran %d tests in subordinate suite\n", sub_ntests); srunner_run_all (sr, CK_NORMAL); cleanup(); fork_teardown(); teardown_fixture(); n = srunner_ntests_failed(sr); srunner_free(sr); return (n == 0) ? EXIT_SUCCESS : EXIT_FAILURE; }
Include headers we need directly
/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #ifndef COMPUTEREINITIALCONDITIONTHREAD_H #define COMPUTEREINITIALCONDITIONTHREAD_H #include "ParallelUniqueId.h" // libmesh #include "libmesh/elem_range.h" class FEProblemBase; class ComputeInitialConditionThread { public: ComputeInitialConditionThread(FEProblemBase & fe_problem); // Splitting Constructor ComputeInitialConditionThread(ComputeInitialConditionThread & x, Threads::split split); void operator() (const ConstElemRange & range); void join(const ComputeInitialConditionThread & /*y*/); protected: FEProblemBase & _fe_problem; THREAD_ID _tid; }; #endif //COMPUTEINITIALCONDITIONTHREAD_H
/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #ifndef COMPUTEREINITIALCONDITIONTHREAD_H #define COMPUTEREINITIALCONDITIONTHREAD_H #include "MooseTypes.h" // libmesh #include "libmesh/elem_range.h" #include "libmesh/threads.h" class FEProblemBase; class ComputeInitialConditionThread { public: ComputeInitialConditionThread(FEProblemBase & fe_problem); // Splitting Constructor ComputeInitialConditionThread(ComputeInitialConditionThread & x, Threads::split split); void operator() (const ConstElemRange & range); void join(const ComputeInitialConditionThread & /*y*/); protected: FEProblemBase & _fe_problem; THREAD_ID _tid; }; #endif //COMPUTEINITIALCONDITIONTHREAD_H
Use pragma once instead of define hack (thanks Natalia)
#ifndef LOGDEFER_H #define LOGDEFER_H #include "picojson/picojson.h" class LogDefer { public: LogDefer(std::function<void (const std::string&)> callback); ~LogDefer(); void add_log(int verbosity, std::string msg); void error(std::string msg); void warn(std::string msg); void info(std::string msg); void debug(std::string msg); private: std::function<void (const std::string &)> callback_; struct timeval start_tv_; picojson::object o_; picojson::array logs_; picojson::array timers_; }; #endif
#pragma once #include "picojson/picojson.h" class LogDefer { public: LogDefer(std::function<void (const std::string&)> callback); ~LogDefer(); void add_log(int verbosity, std::string msg); void error(std::string msg); void warn(std::string msg); void info(std::string msg); void debug(std::string msg); private: std::function<void (const std::string &)> callback_; struct timeval start_tv_; picojson::object o_; picojson::array logs_; picojson::array timers_; };
Comment the file "doxygen style"
#ifdef __cplusplus extern "C"{ #endif typedef int vl6180; #define VL1680_DEFALUT_ADDR 0x29 int vl6180_initialise(int device, int i2cAddr); int get_distance(vl6180 handle); void set_scaling(vl6180 handle, int scaling); ///After calling that, you should discrad the handle to talk to the device and re-initialize it void vl6180_change_addr(vl6180 handle, int newAddr); //hack:add access to lower_level functions int read_byte(vl6180 handle, int reg); void write_byte(vl6180 handle, int reg, char data); void write_two_bytes(vl6180 handle, int reg, int data); #ifdef __cplusplus } #endif
#ifdef __cplusplus extern "C"{ #endif typedef int vl6180; #define VL1680_DEFALUT_ADDR 0x29 ///Initialize a vl6180 sensor on the i2c port /// \param device The I2C bus to open. e.g. "1" for using /dev/i2c-1 /// \param i2c_addr addres of the device. If you don't know, pass VL1680_DEFALUT_ADDR to it /// \return handle to the sensor. Keep this variable to talk to the sensor via the library vl6180 vl6180_initialise(int device, int i2c_addr); ///Change the address of the device. Needed if you have an address conflict (for example: using two of theses sensors on the same design). The handle will also be updated /// \param handle The handle to the sensor given by vl6180_initialise /// \param new_addr The new address to use on the i2c bus for this device void vl6180_change_addr(vl6180 handle, int new_addr); //TODO some of theses functions doesn't have the vl6180 prefix. udpate them to avoid name clashing ///Return the current distance as readed by the sensor /// \param handle The handle to the sensor given by vl6180_initialise /// \return distance in milimeter as an integer int get_distance(vl6180 handle); ///Set the scalinb mode (read datasheet to seee about the max range vs. precision deal on this sensor) /// \param handle The handle to the sensor given by vl6180_initialise /// \param scaling Index of the scaling mode to use void set_scaling(vl6180 handle, int scaling); //hack:add access to lower_level functions int read_byte(vl6180 handle, int reg); void write_byte(vl6180 handle, int reg, char data); void write_two_bytes(vl6180 handle, int reg, int data); #ifdef __cplusplus } #endif
Add everything to header file
#ifndef _SYS_IO_H #define _SYS_IO_H #include <stdint.h> unsigned char inb(uint16_t port); void outb(uint16_t port, uint8_t value); #endif
#ifndef _SYS_IO_H #define _SYS_IO_H #include <stdint.h> uint8_t inb(uint16_t port); void outb(uint16_t port, uint8_t value); uint16_t inw(uint16_t port); void outw(uint16_t port, uint16_t value); uint32_t inl(uint16_t port); void outl(uint16_t port, uint32_t value); #endif
Include Ralf Wildenhues' lclint annotations.
#ifndef CRITMEM_H #define CRITMEM_H #include <sys/types.h> void *mycritmalloc(const char *f, long, size_t size, const char *message); void *mycritcalloc(const char *f, long, size_t size, const char *message); void *mycritrealloc(const char *f, long, void *a, size_t size, const char *message); char *mycritstrdup(const char *f, long, const char *, const char *message); #define critmalloc(a,b) mycritmalloc(__FILE__,__LINE__,a,b) #define critcalloc(a,b) mycritcalloc(__FILE__,__LINE__,a,b) #define critrealloc(a,b,c) mycritrealloc(__FILE__,__LINE__,a,b,c) #define critstrdup(a,b) mycritstrdup(__FILE__,__LINE__,a,b) #endif
#ifndef CRITMEM_H #define CRITMEM_H #include <sys/types.h> /*@only@*//*@out@ */ void *mycritmalloc(const char *f, long, size_t size, const char *message); /*@only@*/ void *mycritcalloc(const char *f, long, size_t size, const char *message); /*@only@*//*@out@ *//*@notnull@ */ void *mycritrealloc(const char *f, long, /*@null@ *//*@only@ *//*@out@ *//*@returned@ */ void *a, size_t size, const char *message); /*@only@*/ char *mycritstrdup(const char *f, long, const char *, const char *message); #define critmalloc(a,b) mycritmalloc(__FILE__,(long)__LINE__,a,b) #define critcalloc(a,b) mycritcalloc(__FILE__,(long)__LINE__,a,b) #define critrealloc(a,b,c) mycritrealloc(__FILE__,(long)__LINE__,a,b,c) #define critstrdup(a,b) mycritstrdup(__FILE__,(long)__LINE__,a,b) #endif
Rename member field according to the style guide.
// Taken from https://gist.github.com/arvidsson/7231973 #ifndef BITCOIN_REVERSE_ITERATOR_HPP #define BITCOIN_REVERSE_ITERATOR_HPP /** * Template used for reverse iteration in C++11 range-based for loops. * * std::vector<int> v = {1, 2, 3, 4, 5}; * for (auto x : reverse_iterate(v)) * std::cout << x << " "; */ template <typename T> class reverse_range { T &x; public: reverse_range(T &x) : x(x) {} auto begin() const -> decltype(this->x.rbegin()) { return x.rbegin(); } auto end() const -> decltype(this->x.rend()) { return x.rend(); } }; template <typename T> reverse_range<T> reverse_iterate(T &x) { return reverse_range<T>(x); } #endif // BITCOIN_REVERSE_ITERATOR_HPP
// Taken from https://gist.github.com/arvidsson/7231973 #ifndef BITCOIN_REVERSE_ITERATOR_H #define BITCOIN_REVERSE_ITERATOR_H /** * Template used for reverse iteration in C++11 range-based for loops. * * std::vector<int> v = {1, 2, 3, 4, 5}; * for (auto x : reverse_iterate(v)) * std::cout << x << " "; */ template <typename T> class reverse_range { T &m_x; public: reverse_range(T &x) : m_x(x) {} auto begin() const -> decltype(this->m_x.rbegin()) { return m_x.rbegin(); } auto end() const -> decltype(this->m_x.rend()) { return m_x.rend(); } }; template <typename T> reverse_range<T> reverse_iterate(T &x) { return reverse_range<T>(x); } #endif // BITCOIN_REVERSE_ITERATOR_H
Add regression test for qsort
#include <kotaka/paths.h> #include <kotaka/log.h> static void create() { } void test() { }
#include <kotaka/paths.h> #include <kotaka/log.h> #include <kotaka/assert.h> static void create() { } private void test_qsort() { int *arr, i; arr = allocate(1000); for (i = 0; i < 1000; i++) { arr[i] = random(1000000); } SUBD->qsort(arr, 0, 1000); for (i = 0; i < 999; i++) { ASSERT(arr[i] <= arr[i + 1]); } } void test() { LOGD->post_message("test", LOG_DEBUG, "Testing qsort..."); test_qsort(); }
Fix warnings and remove unused header
#pragma once #include <math.h> #include "WaveShape.h" class Oscillator { public: WaveShape waveShape; double frequency = 1.0; double amplitude = 1.0; double speed = 1.0; uint32_t phaseAccumulator = 0; Oscillator() = default; Oscillator(const WaveShape &waveShape) : waveShape(waveShape), frequency(waveShape.preferredFrequency) {} static constexpr uint32_t LowerMask(unsigned int n) { return (n == 0) ? 0 : ((LowerMask(n - 1) << 1) | 1); } static constexpr uint32_t UpperMask(unsigned int n) { return LowerMask(n) << (32 - n); } inline uint16_t Tick(const double sampleRate) { double frequencyOut = frequency * speed; uint32_t frequencyControlWord = frequencyOut * static_cast<double>(1ull << 32) / sampleRate; phaseAccumulator += frequencyControlWord; return amplitude * waveShape.table[(phaseAccumulator & UpperMask(WaveShape::granularity)) >> 22]; } };
#pragma once #include "WaveShape.h" class Oscillator { public: WaveShape waveShape; double frequency = 1.0; double amplitude = 1.0; double speed = 1.0; uint32_t phaseAccumulator = 0; Oscillator() = default; Oscillator(const WaveShape &waveShape) : waveShape(waveShape), frequency(waveShape.preferredFrequency) {} static constexpr uint32_t LowerMask(unsigned int n) { return (n == 0) ? 0 : ((LowerMask(n - 1) << 1) | 1); } static constexpr uint32_t UpperMask(unsigned int n) { return LowerMask(n) << (32 - n); } inline uint16_t Tick(const double sampleRate) { double frequencyOut = frequency * speed; uint32_t frequencyControlWord = static_cast<uint32_t>(frequencyOut * static_cast<double>(1ull << 32) / sampleRate); phaseAccumulator += frequencyControlWord; return static_cast<uint32_t>(amplitude * waveShape.table[(phaseAccumulator & UpperMask(WaveShape::granularity)) >> 22]); } };
Fix logic that enables pre-ARC behavior
#if (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && (!defined(__IPHONE_6_0) || __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_6_0)) || \ (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && (!defined(__MAC_10_8) || __MAC_OS_X_VERSION_MIN_REQUIRED < __MAC_10_8)) #define PT_DISPATCH_RETAIN_RELEASE 1 #endif #if PT_DISPATCH_RETAIN_RELEASE #define PT_PRECISE_LIFETIME #define PT_PRECISE_LIFETIME_UNUSED #else #define PT_PRECISE_LIFETIME __attribute__((objc_precise_lifetime)) #define PT_PRECISE_LIFETIME_UNUSED __attribute__((objc_precise_lifetime, unused)) #endif
#if (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && (!defined(__IPHONE_6_0) || __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_6_0)) || \ (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && (!defined(__MAC_10_8) || __MAC_OS_X_VERSION_MIN_REQUIRED < __MAC_10_8)) #define PT_DISPATCH_RETAIN_RELEASE 1 #endif #define PT_PRECISE_LIFETIME #define PT_PRECISE_LIFETIME_UNUSED #if defined(PT_DISPATCH_RETAIN_RELEASE) && PT_DISPATCH_RETAIN_RELEASE #define PT_PRECISE_LIFETIME __attribute__((objc_precise_lifetime)) #define PT_PRECISE_LIFETIME_UNUSED __attribute__((objc_precise_lifetime, unused)) #endif
Define actor sized as float for type safety.
/* * Copyright © 2010 Intel Corp. * * Authors: Rob Staudinger <robert.staudinger@intel.com> * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef MPD_SHELL_DEFINES_H #define MPD_SHELL_DEFINES_H #define MPD_SHELL_WIDTH 1024 #define MPD_SHELL_HEIGHT 300 #define MPD_SHELL_PADDING 12 #define MPD_SHELL_SPACING 24 #define MPD_COMPUTER_PANE_WIDTH 320 #endif /* MPD_SHELL_DEFINES_H */
/* * Copyright © 2010 Intel Corp. * * Authors: Rob Staudinger <robert.staudinger@intel.com> * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for * more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef MPD_SHELL_DEFINES_H #define MPD_SHELL_DEFINES_H #define MPD_SHELL_WIDTH 1024.0 #define MPD_SHELL_HEIGHT 300.0 #define MPD_SHELL_PADDING 12.0 #define MPD_SHELL_SPACING 24.0 #define MPD_COMPUTER_PANE_WIDTH 320.0 #endif /* MPD_SHELL_DEFINES_H */
Change method name : `signal' => `notify'
#pragma once namespace LWP { class ICondVar { public: virtual void wait() = 0; virtual void signal() = 0; virtual void broadcast() = 0; virtual ~ICondVar() {} }; }
#pragma once namespace LWP { class ICondVar { public: virtual void wait() = 0; virtual void notify() = 0; virtual void broadcast() = 0; virtual ~ICondVar() {} }; }
Add kernel.h, task.h and types.h, forming a facade interface
#ifndef __STDLIB_H__ #define __STDLIB_H__ void assert(int boolean, char * msg); #endif // __STDLIB_H__
#ifndef __STDLIB_H__ #define __STDLIB_H__ #include <kernel.h> #include <task.h> #include <types.h> void assert(int boolean, char * msg); #endif // __STDLIB_H__
Fix case-sensitive file import from CoreNfc -> CoreNFC
#if __has_include(<React/RCTBridgeModule.h>) #import <React/RCTBridgeModule.h> #import <React/RCTEventEmitter.h> #elif __has_include(“React/RCTBridgeModule.h”) #import “React/RCTBridgeModule.h” #else #import “RCTBridgeModule.h” #import <React/RCTEventEmitter.h> #endif #import <CoreNfc/CoreNfc.h> @interface NfcManager : RCTEventEmitter <RCTBridgeModule, NFCNDEFReaderSessionDelegate> { } @property (strong, nonatomic) NFCNDEFReaderSession *session; @end
#if __has_include(<React/RCTBridgeModule.h>) #import <React/RCTBridgeModule.h> #import <React/RCTEventEmitter.h> #elif __has_include(“React/RCTBridgeModule.h”) #import “React/RCTBridgeModule.h” #else #import “RCTBridgeModule.h” #import <React/RCTEventEmitter.h> #endif #import <CoreNFC/CoreNFC.h> @interface NfcManager : RCTEventEmitter <RCTBridgeModule, NFCNDEFReaderSessionDelegate> { } @property (strong, nonatomic) NFCNDEFReaderSession *session; @end
Add name to add_job param
#ifndef __MACHINE_H__ #define __MACHINE_H__ #include <string> #include <vector> #include "job.h" class Machine { public: Machine(const std::string& machine_name); const std::string& get_name() const; void add_job(Job); private: std::string name; std::vector<Job> jobs; }; #endif /* __MACHINE_H__ */
#ifndef __MACHINE_H__ #define __MACHINE_H__ #include <string> #include <vector> #include "job.h" class Machine { public: Machine(const std::string& machine_name); const std::string& get_name() const; void add_job(Job new_job); private: std::string name; std::vector<Job> jobs; }; #endif /* __MACHINE_H__ */
Add (w)char casting operator to windows char classes
//--------------------------------------------------------------------------// /// Copyright (c) 2017 by Milos Tosic. All Rights Reserved. /// /// License: http://www.opensource.org/licenses/BSD-2-Clause /// //--------------------------------------------------------------------------// #ifndef __RTM_RBASE_WINCHAR_H__ #define __RTM_RBASE_WINCHAR_H__ #include <rbase/inc/platform.h> namespace rtm { #if RTM_PLATFORM_WINDOWS class MultiToWide { static const int S_ON_STACK_SIZE = 1024; wchar_t m_string[S_ON_STACK_SIZE]; public: wchar_t* m_ptr; MultiToWide(const char* _string, bool _path = true); ~MultiToWide(); }; class WideToMulti { static const int S_ON_STACK_SIZE = 1024; char m_string[S_ON_STACK_SIZE]; public: char* m_ptr; WideToMulti(const wchar_t* _string); ~WideToMulti(); }; #endif // RTM_PLATFORM_WINDOWS } // namespace rtm #endif // __RTM_RBASE_WINCHAR_H__
//--------------------------------------------------------------------------// /// Copyright (c) 2017 by Milos Tosic. All Rights Reserved. /// /// License: http://www.opensource.org/licenses/BSD-2-Clause /// //--------------------------------------------------------------------------// #ifndef __RTM_RBASE_WINCHAR_H__ #define __RTM_RBASE_WINCHAR_H__ #include <rbase/inc/platform.h> namespace rtm { #if RTM_PLATFORM_WINDOWS class MultiToWide { static const int S_ON_STACK_SIZE = 1024; wchar_t m_string[S_ON_STACK_SIZE]; public: wchar_t* m_ptr; MultiToWide(const char* _string, bool _path = true); ~MultiToWide(); operator wchar_t* () { return m_ptr; } }; class WideToMulti { static const int S_ON_STACK_SIZE = 1024; char m_string[S_ON_STACK_SIZE]; public: char* m_ptr; WideToMulti(const wchar_t* _string); ~WideToMulti(); operator char* () { return m_ptr; } }; #endif // RTM_PLATFORM_WINDOWS } // namespace rtm #endif // __RTM_RBASE_WINCHAR_H__
Fix header guard typo and build error.
//===- llvm/Transforms/Utils/SizeOpts.h - size optimization -----*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file contains some shared code size optimization related code. // //===----------------------------------------------------------------------===// #ifndef LLVM_TRANSFORMS_UTILS_SIZEOPTS_H #define LLVM_TRANSFORMS_UTILS_SiZEOPTS_H namespace llvm { class BasicBlock; class BlockFrequencyInfo; class Function; class ProfileSummaryInfo; /// Returns true if function \p F is suggested to be size-optimized base on the /// profile. bool shouldOptimizeForSize(Function *F, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI); /// Returns true if basic block \p BB is suggested to be size-optimized base /// on the profile. bool shouldOptimizeForSize(BasicBlock *BB, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI); } // end namespace llvm #endif // LLVM_TRANSFORMS_UTILS_SiZEOPTS_H
//===- llvm/Transforms/Utils/SizeOpts.h - size optimization -----*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file contains some shared code size optimization related code. // //===----------------------------------------------------------------------===// #ifndef LLVM_TRANSFORMS_UTILS_SIZEOPTS_H #define LLVM_TRANSFORMS_UTILS_SIZEOPTS_H namespace llvm { class BasicBlock; class BlockFrequencyInfo; class Function; class ProfileSummaryInfo; /// Returns true if function \p F is suggested to be size-optimized base on the /// profile. bool shouldOptimizeForSize(Function *F, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI); /// Returns true if basic block \p BB is suggested to be size-optimized base /// on the profile. bool shouldOptimizeForSize(BasicBlock *BB, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI); } // end namespace llvm #endif // LLVM_TRANSFORMS_UTILS_SIZEOPTS_H
Add macros to define getters and setters
#ifndef LBS_COMMON_H #define LBS_COMMON_H #include <stddef.h> #ifdef __STDC_VERSION__ # include <stdbool.h> # if __STDC_VERSION__ >= 201112L # define LBS_COMMON_ISO_C11 # define LBS_COMMON_CHECK_TYPE(x,type) (_Generic ((x), type: (x))) # else # define LBS_COMMON_ISO_C99 # define LBS_COMMON_CHECK_TYPE(x,type) (x) # endif #else # define bool char # define true 1 # define false 0 # define LBS_COMMON_ISO_C89 # define LBS_COMMON_CHECK_TYPE(x,type) (x) #endif /* __STDC_VERSION__ */ #define LBS_COMMON_NULL_PTR ((void*)NULL) #endif /* LBS_COMMON_H */
#ifndef LBS_COMMON_H #define LBS_COMMON_H #include <stddef.h> #ifdef __STDC_VERSION__ # include <stdbool.h> # if __STDC_VERSION__ >= 201112L # define LBS_COMMON_ISO_C11 # define LBS_COMMON_CHECK_TYPE(x,type) (_Generic ((x), type: (x))) # else # define LBS_COMMON_ISO_C99 # define LBS_COMMON_CHECK_TYPE(x,type) (x) # endif #else # define bool char # define true 1 # define false 0 # define inline # define LBS_COMMON_ISO_C89 # define LBS_COMMON_CHECK_TYPE(x,type) (x) #endif /* __STDC_VERSION__ */ #define LBS_COMMON_NULL_PTR ((void*)NULL) #define LBS_COMMON_DEFINE_GETTER(ns,xt,m,mt) \ static inline mt ns ## _get_ ## m (xt x) { \ return x->m; \ } #define LBS_COMMON_DEFINE_SETTER(ns,xt,m,mt) \ static inline void ns ## _set_ ## m (xt x, mt v) { \ x->m = v; \ } #endif /* LBS_COMMON_H */
Add problem transformation to shift the objective.
#include <assert.h> #include <numbbo.h> #include "numbbo_problem.c" typedef struct { double amount; } shift_objective_state_t; static void _so_evaluate_function(numbbo_problem_t *self, double *x, double *y) { assert(problem->inner_problem != NULL); assert(problem->state != NULL); numbbo_transformed_problem_t *problem = (numbbo_transformed_problem_t *)self; shift_objective_state_t *state = (shift_objective_state_t *)self->state; numbbo_evaluate_function(problem->inner_problem, x, y); y[0] += state->amount; } /* Shift the returned objective value of ${inner_problem} by ${amount}. */ numbbo_problem_t *shift_objective(const numbbo_problem_t *inner_problem, const double amount) { numbbo_transformed_problem_t *problem = numbbo_allocate_transformed_problem(inner_problem); shift_objective_state_t *state = numbbo_allocate_memory(sizeof(*state)); state->amount = amount; problem->state = state; problem->evaluate_function = _so_evaluate_function; return problem; }
Add the test program, too
#include <stdio.h> #include <string.h> #include "ausearch-string.h" slist s; int print_list(void) { int cnt = 0; slist_first(&s); do { snode *cur = slist_get_cur(&s); if (cur) { cnt++; printf("%s\n", cur->str); } } while (slist_next(&s)); return cnt; } int main(void) { snode n; int rc; slist_create(&s); slist_add_if_uniq(&s, "test1"); slist_add_if_uniq(&s, "test2"); slist_first(&s); slist_add_if_uniq(&s, "test3"); puts("should be 3"); rc = print_list(); if (s.cnt != 3 || rc !=3) { puts("test count is wrong"); return 1; } n.str = strdup("test4"); n.key = NULL; n.hits = 1; slist_append(&s, &n); puts("should add a #4"); rc = print_list(); if (s.cnt != 4 || rc != 4) { puts("test count is wrong"); return 1; } slist_add_if_uniq(&s, "test2"); puts("should be same"); rc = print_list(); if (s.cnt != 4 || rc != 4) { puts("test count is wrong"); return 1; } slist_clear(&s); puts("should be empty"); rc = print_list(); if (s.cnt != 0 || rc != 0) { puts("test count is wrong"); return 1; } return 0; }
Add client name and version constants.
// Copyright (c) 2011 The WebM project authors. All Rights Reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file in the root of the source // tree. An additional intellectual property rights grant can be found // in the file PATENTS. All contributing project authors may // be found in the AUTHORS file in the root of the source tree. #ifndef CLIENT_ENCODER_CLIENT_ENCODER_BASE_H_ #define CLIENT_ENCODER_CLIENT_ENCODER_BASE_H_ #if _WIN32 #ifndef _WIN32_WINNT # define _WIN32_WINNT 0x0501 // WinXP #endif #include <windows.h> #ifdef ERROR # undef ERROR // unused by webmlive/collides with glog. #endif #endif // _WIN32 #endif // CLIENT_ENCODER_CLIENT_ENCODER_BASE_H_
// Copyright (c) 2011 The WebM project authors. All Rights Reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file in the root of the source // tree. An additional intellectual property rights grant can be found // in the file PATENTS. All contributing project authors may // be found in the AUTHORS file in the root of the source tree. #ifndef CLIENT_ENCODER_CLIENT_ENCODER_BASE_H_ #define CLIENT_ENCODER_CLIENT_ENCODER_BASE_H_ #if _WIN32 #ifndef _WIN32_WINNT # define _WIN32_WINNT 0x0501 // WinXP #endif #include <windows.h> #ifdef ERROR # undef ERROR // unused by webmlive/collides with glog. #endif #endif // _WIN32 // App Version/Identity namespace webmlive { static const char* kClientName = "webmlive client encoder"; static const char* kClientVersion = "0.0.2.0"; } // namespace webmlive #endif // CLIENT_ENCODER_CLIENT_ENCODER_BASE_H_
Use NELEMS() instead of open code.
#include "unwind_i.h" static const char *regname[] = { "eax", "ebx", "ecx", "edx", "esi", "edi", "ebp", "eip", "esp" }; const char * unw_regname (unw_regnum_t reg) { if (reg < NELEMS (regname)) return regname[reg]; else return "???"; }
Add comment for struc Point definition
/** Author : Paul TREHIOU & Victor SENE * Date : November 2014 **/ /** * * */ typedef struct { float x; float y; }Point; /** * Function wich create a point with a specified abscisse and ordinate * abscisse - real * ordinate - real * return a new point */
/** Author : Paul TREHIOU & Victor SENE * Date : November 2014 **/ /** * Declaration Point structure * x - real wich is the abscisse of the point * y - real wich is the ordinate of the point */ typedef struct { float x; float y; }Point; /** * Function wich create a point with a specified abscisse and ordinate * abscisse - real * ordinate - real * return a new point */
Modify MAX(x,y) to not contain a scope
#ifndef __MACROS_H__ #define __MACROS_H__ /** * @file macros.h * * This file contains simple helper macros */ /** * @addtogroup internal_util_helper_macros "(internal) helper macros" * * This group contains helper macros for internal use only. * * @{ */ /** * Computes the maximum value of the two passed values * * @note Provides compile-time type checking by using temp variables before * doing the comparison. * * @note Opens own scope, so the temp variables do not show up outside of the * macro. */ #define MAX(x,y) \ ({ __typeof__ (x) _x = (x); \ __typeof__ (y) _y = (y); \ _x > _y ? _x : _y; }) /** * Computes the minimum value of the two passed values * * @note Provides compile-time type checking by using temp variables before * doing the comparison. * * @note Opens own scope, so the temp variables do not show up outside of the * macro. */ #define MIN(x,y) \ ({ __typeof__ (x) _x = (x); \ __typeof__ (y) _y = (y); \ _x < _y ? _x : _y; }) /** @} */ #endif //__MACROS_H__
#ifndef __MACROS_H__ #define __MACROS_H__ /** * @file macros.h * * This file contains simple helper macros */ /** * @addtogroup internal_util_helper_macros "(internal) helper macros" * * This group contains helper macros for internal use only. * * @{ */ /** * Computes the maximum value of the two passed values * * @note Provides compile-time type checking by using temp variables before * doing the comparison. * * @note Opens own scope, so the temp variables do not show up outside of the * macro. */ #define MAX(x,y) \ ((__typeof__(x)) x > (__typeof__(x)) y ? \ (__typeof__(x)) x : (__typeof__(x)) y) /** * Computes the minimum value of the two passed values * * @note Provides compile-time type checking by using temp variables before * doing the comparison. * * @note Opens own scope, so the temp variables do not show up outside of the * macro. */ #define MIN(x,y) \ ({ __typeof__ (x) _x = (x); \ __typeof__ (y) _y = (y); \ _x < _y ? _x : _y; }) /** @} */ #endif //__MACROS_H__
Add basis use of timers
/* * main.c * * Created on: 2 Nov 2016 * Author: rafpe */ #include "stm32f4xx.h" #include "stm32f407xx.h" int main(void) { volatile uint32_t delay; RCC->AHB1ENR |= RCC_AHB1ENR_GPIODEN | RCC_AHB1ENR_GPIOCEN; // enable the clock to GPIOD & GPIOC RCC->APB2ENR |= RCC_APB2ENR_SYSCFGEN | RCC_APB2ENR_TIM1EN; // enable SYSCFG for external interrupts & TIM1 __DSB(); // Data Synchronization Barrier TIM1->PSC = 15999; // Prescaler we want to be using 16Mhz/16000 = 1000Hz = 1ms TIM1->ARR = 499; // How many values we will count TIM1->DIER = TIM_DIER_UIE; // Update Event Interrupt TIM1->CR1 = TIM_CR1_CEN; // Enable & Start timer NVIC_EnableIRQ(TIM1_UP_TIM10_IRQn); // Set up interrupt handler GPIOD->MODER = (1 << 26); // PIND to output mode while (1) { } /* while */ } /* main */ void TIM1_UP_TIM10_IRQHandler(void) { if (TIM1->SR & TIM_SR_UIF) { GPIOD->ODR ^= (1 << 13); // Blink TIM1->SR = ~TIM_SR_UIF; // clear flag - rc_w0 => Read Clear Write 0 } }
Make int32_t available when the configure script is not used
/* * Copyright (c) 2009, 2010 Petri Lehtinen <petri@digip.org> * * Jansson is free software; you can redistribute it and/or modify * it under the terms of the MIT license. See LICENSE for details. */ #ifndef UTF_H #define UTF_H #ifdef HAVE_CONFIG_H #include <config.h> #endif #ifdef HAVE_INTTYPES_H /* inttypes.h includes stdint.h in a standard environment, so there's no need to include stdint.h separately. If inttypes.h doesn't define int32_t, it's defined in config.h. */ #include <inttypes.h> #else #ifdef _WIN32 typedef int int32_t; #endif #endif int utf8_encode(int codepoint, char *buffer, int *size); int utf8_check_first(char byte); int utf8_check_full(const char *buffer, int size, int32_t *codepoint); const char *utf8_iterate(const char *buffer, int32_t *codepoint); int utf8_check_string(const char *string, int length); #endif
/* * Copyright (c) 2009, 2010 Petri Lehtinen <petri@digip.org> * * Jansson is free software; you can redistribute it and/or modify * it under the terms of the MIT license. See LICENSE for details. */ #ifndef UTF_H #define UTF_H #ifdef HAVE_CONFIG_H #include <config.h> #ifdef HAVE_INTTYPES_H /* inttypes.h includes stdint.h in a standard environment, so there's no need to include stdint.h separately. If inttypes.h doesn't define int32_t, it's defined in config.h. */ #include <inttypes.h> #endif /* HAVE_INTTYPES_H */ #else /* !HAVE_CONFIG_H */ #ifdef _WIN32 typedef int int32_t; #else /* !_WIN32 */ /* Assume a standard environment */ #include <inttypes.h> #endif /* _WIN32 */ #endif /* HAVE_CONFIG_H */ int utf8_encode(int codepoint, char *buffer, int *size); int utf8_check_first(char byte); int utf8_check_full(const char *buffer, int size, int32_t *codepoint); const char *utf8_iterate(const char *buffer, int32_t *codepoint); int utf8_check_string(const char *string, int length); #endif
Delete redundant staff from FuncMemory class
/** * func_memory.h - Header of module implementing the concept of * programer-visible memory space accesing via memory address. * @author Alexander Titov <alexander.igorevich.titov@gmail.com> * Copyright 2012 uArchSim iLab project */ // protection from multi-include #ifndef FUNC_MEMORY__FUNC_MEMORY_H #define FUNC_MEMORY__FUNC_MEMORY_H // Generic C++ #include <string> #include <map> // uArchSim modules #include <types.h> #include <elf_parser.h> using namespace std; class FuncMemory { map<uint64 /*start addr*/, ElfSection *> sections; typedef map<uint64, ElfSection *>::iterator Iter; typedef map<uint64, ElfSection *>::const_iterator ConstIter; // You could not create the object // using this default constructor FuncMemory(){} public: FuncMemory( const char* executable_file_name, const char* const elf_sections_names[], short num_of_elf_sections); virtual ~FuncMemory(); uint64 read( uint64 addr, short num_of_bytes = 4) const; string dump( string indent = "") const; }; #endif // #ifndef FUNC_MEMORY__FUNC_MEMORY_H
/** * func_memory.h - Header of module implementing the concept of * programer-visible memory space accesing via memory address. * @author Alexander Titov <alexander.igorevich.titov@gmail.com> * Copyright 2012 uArchSim iLab project */ // protection from multi-include #ifndef FUNC_MEMORY__FUNC_MEMORY_H #define FUNC_MEMORY__FUNC_MEMORY_H // Generic C++ #include <string> // uArchSim modules #include <types.h> #include <elf_parser.h> using namespace std; class FuncMemory { // You could not create the object // using this default constructor FuncMemory(){} public: FuncMemory( const char* executable_file_name, const char* const elf_sections_names[], short num_of_elf_sections); virtual ~FuncMemory(); uint64 read( uint64 addr, short num_of_bytes = 4) const; string dump( string indent = "") const; }; #endif // #ifndef FUNC_MEMORY__FUNC_MEMORY_H
Create "checkout lines" as DLinkedList
#pragma once class RegisterQueue{ private: public: int numberOfCustomers; int maxLineLength; };
#pragma once #include "Customer.h" class RegisterQueue{ private: struct Node { Node *next; // After previous sequentially Node *previous; // First in line Customer value; // @next = NULL, this is a shorthand constructor to make NULL the default Node(Customer value, Node *previous = nullptr) { this->previous = previous; this->value = value; this->next = nullptr; } }; double minToPay; double minPerItem; Node *front; Node *rear; public: int numberOfCustomers; int maxLineLength; RegisterQueue(double minToPay, double minPerItem) { front, rear = nullptr; maxLineLength = 8; numberOfCustomers = 0; } ~RegisterQueue() { while (front) { Node *next = front->next; delete(front); front = next; } } void enqueue(Customer cust) { if(numberOfCustomers >= maxLineLength) throw("FullLineException"); Node next = new Node(cust, rear); if(!numberOfCustomers) front = next; if(rear) rear->next = next; rear = next; numberOfCustomers++; } Customer dequeue() { Customer person = front->value; front = front->next; delete(front->previous); front->previous = nullptr; numberOfCustomers--; return person; } };
Add a deprecated warning for - (void)clear.
// // Tesseract.h // Tesseract // // Created by Loïs Di Qual on 24/09/12. // Copyright (c) 2012 Loïs Di Qual. // Under MIT License. See 'LICENCE' for more informations. // #import <UIKit/UIKit.h> @class Tesseract; @protocol TesseractDelegate <NSObject> @optional - (BOOL)shouldCancelImageRecognitionForTesseract:(Tesseract*)tesseract; @end @interface Tesseract : NSObject + (NSString *)version; @property (nonatomic, strong) NSString* language; @property (nonatomic, strong) UIImage *image; @property (nonatomic, assign) CGRect rect; @property (nonatomic, readonly) short progress; // from 0 to 100 @property (nonatomic, readonly) NSString *recognizedText; @property (nonatomic, weak) id<TesseractDelegate> delegate; /// /// @warning deprecated method! /// @deprecated - (id)initWithDataPath:(NSString *)dataPath language:(NSString *)language is deprecated. Please use - (id)initWithLanguage:(NSString*)language; /// - (id)initWithDataPath:(NSString *)dataPath language:(NSString *)language DEPRECATED_ATTRIBUTE; - (id)initWithLanguage:(NSString*)language; - (void)setVariableValue:(NSString *)value forKey:(NSString *)key; - (BOOL)recognize; - (void)clear; @end
// // Tesseract.h // Tesseract // // Created by Loïs Di Qual on 24/09/12. // Copyright (c) 2012 Loïs Di Qual. // Under MIT License. See 'LICENCE' for more informations. // #import <UIKit/UIKit.h> @class Tesseract; @protocol TesseractDelegate <NSObject> @optional - (BOOL)shouldCancelImageRecognitionForTesseract:(Tesseract*)tesseract; @end @interface Tesseract : NSObject + (NSString *)version; @property (nonatomic, strong) NSString* language; @property (nonatomic, strong) UIImage *image; @property (nonatomic, assign) CGRect rect; @property (nonatomic, readonly) short progress; // from 0 to 100 @property (nonatomic, readonly) NSString *recognizedText; @property (nonatomic, weak) id<TesseractDelegate> delegate; /// /// @warning deprecated method! /// @deprecated - (id)initWithDataPath:(NSString *)dataPath language:(NSString *)language is deprecated. Please use - (id)initWithLanguage:(NSString*)language; /// - (id)initWithDataPath:(NSString *)dataPath language:(NSString *)language DEPRECATED_ATTRIBUTE; - (id)initWithLanguage:(NSString*)language; - (void)setVariableValue:(NSString *)value forKey:(NSString *)key; - (BOOL)recognize; /// /// @warning deprecated method! /// @deprecated - (void)clear is deprecated. The memory will be freed in dealloc added by ARC; /// - (void)clear DEPRECATED_ATTRIBUTE; @end
Add missing netdarray.h header file.
#ifndef __netarray_H #define __netarray_H /* * Copyright (c) 2012 Stephen Williams (steve@icarus.com) * Copyright CERN 2012 / Stephen Williams (steve@icarus.com) * * This source code is free software; you can redistribute it * and/or modify it in source code form under the terms of the GNU * General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ # include "LineInfo.h" # include <vector> class netarray_t : public LineInfo { public: explicit netarray_t(const std::list<netrange_t>&packed); ~netarray_t(); unsigned packed_width() const; private: std::list<netrange_t> packed_dims_; }; inline netarray_t::netarray_t(const std::list<netrange_t>&packed) : packed_dims_(packed) { } netarray_t::~netarray_t() { } #endif
Add source of formulas used in biquad filters
/* * Biquad_Filter.h * * Created on: 24. 6. 2017 * Author: michp */ #ifndef BIQUAD_FILTER_H_ #define BIQUAD_FILTER_H_ #include <cmath> namespace flyhero { // Many thanks to http://www.earlevel.com/main/2012/11/26/biquad-c-source-code/ class Biquad_Filter { private: const double PI = 3.14159265358979323846; float a0, a1, a2; float b1, b2; float z1, z2; public: enum Filter_Type { FILTER_LOW_PASS, FILTER_NOTCH }; Biquad_Filter(Filter_Type type, float sample_frequency, float cut_frequency); inline float Apply_Filter(float value); }; // 10 us float Biquad_Filter::Apply_Filter(float value) { float ret = value * this->a0 + this->z1; this->z1 = value * this->a1 + this->z2 - this->b1 * ret; this->z2 = value * this->a2 - this->b2 * ret; return ret; } } /* namespace flyhero */ #endif /* BIQUAD_FILTER_H_ */
/* * Biquad_Filter.h * * Created on: 24. 6. 2017 * Author: michp */ #ifndef BIQUAD_FILTER_H_ #define BIQUAD_FILTER_H_ #include <cmath> namespace flyhero { // Many thanks to http://www.earlevel.com/main/2012/11/26/biquad-c-source-code/ class Biquad_Filter { private: const double PI = 3.14159265358979323846; float a0, a1, a2; float b1, b2; float z1, z2; public: enum Filter_Type { FILTER_LOW_PASS, FILTER_NOTCH }; Biquad_Filter(Filter_Type type, float sample_frequency, float cut_frequency); inline float Apply_Filter(float value); }; // 10 us // https://en.wikipedia.org/wiki/Digital_biquad_filter - Transposed direct forms float Biquad_Filter::Apply_Filter(float value) { float ret = value * this->a0 + this->z1; this->z1 = value * this->a1 + this->z2 - this->b1 * ret; this->z2 = value * this->a2 - this->b2 * ret; return ret; } } /* namespace flyhero */ #endif /* BIQUAD_FILTER_H_ */
Test function that uses global value
#include <stdio.h> int assertCount, errorCount; void assertEq(int x, int y){ assertCount++; if(x == y) return; errorCount++; printf("ASSERTION %d FAILED: %d does not equal %d\n", assertCount, x, y); } void endTest(){ if(errorCount > 0) printf("TEST FAILED: Encountered %d assertion error%s out of %d!", errorCount, errorCount==1?"":"s", assertCount); else printf("TEST SUCCESSFUL: All %d assertions passed!", assertCount); } int a = 5; int f(int b) { return a * b; } int main() { assertEq(f(4), 20); a = 3; assertEq(f(4), 12); endTest(); }
Include "tdep.h". (unwi_full_sigmask): Define here. (mi_init): Initialize unwi_full_sigmask.
/* libunwind - a platform-independent unwind library Copyright (C) 2002-2003 Hewlett-Packard Co Contributed by David Mosberger-Tang <davidm@hpl.hp.com> This file is part of libunwind. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <stdlib.h> #include "internal.h" #include "tdep.h" sigset_t unwi_full_sigmask; HIDDEN void mi_init (void) { extern void unw_cursor_t_is_too_small (void); #if UNW_DEBUG const char *str = getenv ("UNW_DEBUG_LEVEL"); if (str) tdep_debug_level = atoi (str); #endif if (sizeof (struct cursor) > sizeof (unw_cursor_t)) unw_cursor_t_is_too_small (); sigfillset (&unwi_full_sigmask); }
Add brief description for TransferFunctionParser.
#ifndef SRC_TRANSFER_FUNCTION_PARSER_H_ #define SRC_TRANSFER_FUNCTION_PARSER_H_ #include <QGradient> #include <QString> #include <QXmlDefaultHandler> /** * \brief * * */ class QGradientContentHandler; class TransferFunctionParser { public: TransferFunctionParser(QString path); QGradient *parse(); private: QXmlSimpleReader *xmlReader; QXmlInputSource *source; QGradientContentHandler *handler; }; #endif // SRC_TRANSFER_FUNCTION_PARSER_H_
#ifndef SRC_TRANSFER_FUNCTION_PARSER_H_ #define SRC_TRANSFER_FUNCTION_PARSER_H_ #include <QGradient> #include <QString> #include <QXmlDefaultHandler> class QGradientContentHandler; /** * \brief Parser for XML representation of a QGradient used as transfer function * */ class TransferFunctionParser { public: TransferFunctionParser(QString path); QGradient *parse(); private: QXmlSimpleReader *xmlReader; QXmlInputSource *source; QGradientContentHandler *handler; }; #endif // SRC_TRANSFER_FUNCTION_PARSER_H_
Include <asm/irq.h> to fix warning.
#include <linux/pci.h> int __init pcibios_map_irq(struct pci_dev *dev, u8 slot, u8 pin) { int irq; if (!pin) return 0; irq = allocate_irqno(); if (irq < 0) return 0; return irq; } /* Do platform specific device initialization at pci_enable_device() time */ int pcibios_plat_dev_init(struct pci_dev *dev) { return 0; }
#include <linux/pci.h> #include <asm/irq.h> int __init pcibios_map_irq(struct pci_dev *dev, u8 slot, u8 pin) { int irq; if (!pin) return 0; irq = allocate_irqno(); if (irq < 0) return 0; return irq; } /* Do platform specific device initialization at pci_enable_device() time */ int pcibios_plat_dev_init(struct pci_dev *dev) { return 0; }
Fix mistake in C template
#include <stdio.h> int main(int argc, char const *argv[]) { int answer = 0; printf("%d\n"); return 0; }
#include <stdio.h> int main(int argc, char const *argv[]) { int answer = 0; printf("%d\n", answer); return 0; }
Make this explicitly inline for consistency's sake.
/* This code is subject to the terms of the Mozilla Public License, v.2.0. http://mozilla.org/MPL/2.0/. */ #pragma once #include <sstream> namespace turbo { namespace str { template <class Iter> std::string join(const Iter& start, const Iter& end, char delim=' ') { std::stringstream ss; Iter it = start; if (it != end) ss << *it++; for (; it != end; ++it) ss << delim << *it; return ss.str(); } template <class Type> std::string join(const Type& container, char delim=' ') { return join(container.begin(), container.end(), delim); } } }// namespace turbo
/* This code is subject to the terms of the Mozilla Public License, v.2.0. http://mozilla.org/MPL/2.0/. */ #pragma once #include <sstream> namespace turbo { namespace str { template <class Iter> inline std::string join(const Iter& start, const Iter& end, char delim=' ') { std::stringstream ss; Iter it = start; if (it != end) ss << *it++; for (; it != end; ++it) ss << delim << *it; return ss.str(); } template <class Type> inline std::string join(const Type& container, char delim=' ') { return join(container.begin(), container.end(), delim); } } }// namespace turbo
Revert of a previous commit "Delete main widget in BasicUi"
#ifndef BASICUI_H_ #define BASICUI_H_ #include <QMainWindow> #include "QsLog.h" #include "mainwidget.h" #include "workspace.h" #include "uicontroller.h" class BasicUi: public QMainWindow { Q_OBJECT public: BasicUi(UiController * controller, QWidget *parent = 0); void setWorkspace(Workspace *); void setUiController(UiController *); ~BasicUi(){ if(NULL != mainWidget) delete mainWidget; } private: MainWidget *mainWidget; // QGridLayout *layout; // QPushButton *editModeButton; // EditWidget *editWidget; // PlayWidget *playWidget; // bool editMode; // Workspace *wsp; // Controller *controller; }; #endif
#ifndef BASICUI_H_ #define BASICUI_H_ #include <QMainWindow> #include "QsLog.h" #include "mainwidget.h" #include "workspace.h" #include "uicontroller.h" class BasicUi: public QMainWindow { Q_OBJECT public: BasicUi(UiController * controller, QWidget *parent = 0); void setWorkspace(Workspace *); void setUiController(UiController *); private: MainWidget *mainWidget; // QGridLayout *layout; // QPushButton *editModeButton; // EditWidget *editWidget; // PlayWidget *playWidget; // bool editMode; // Workspace *wsp; // Controller *controller; }; #endif
Replace placeholder string in time module with time.
#include <stdlib.h> #include "graphics.h" #include "surface.h" #include "time-module.h" typedef struct TimeModule { Module base; } TimeModule; Module* newTimeModule() { TimeModule* module = malloc(sizeof(TimeModule)); module->base.width = 150; module->base.height = 100; module->base.updateFunc = updateTimeModule; module->base.freeFunc = freeTimeModule; return (Module*)module; } void freeTimeModule(Module* module) { free(module); } void updateTimeModule(Module* module, Surface* surface) { setDrawColor(surface, 1.0, 1.0, 1.0, 0.8); drawRect(surface, 0, 0, module->width, module->height); setDrawColor(surface, 0, 0, 0, 0.8); drawText(surface, 10, 10, 32, "monaco", "Good"); }
#include <stdlib.h> #include <time.h> #include "graphics.h" #include "surface.h" #include "time-module.h" typedef struct TimeModule { Module base; } TimeModule; Module* newTimeModule() { TimeModule* module = malloc(sizeof(TimeModule)); module->base.width = 150; module->base.height = 100; module->base.updateFunc = updateTimeModule; module->base.freeFunc = freeTimeModule; return (Module*)module; } void freeTimeModule(Module* module) { free(module); } void updateTimeModule(Module* module, Surface* surface) { // Get the current time time_t t; struct tm* tm; t = time(NULL); tm = localtime(&t); char strTime[6]; strftime(strTime, sizeof strTime, "%H:%M", tm); // Draw the rect setDrawColor(surface, 1.0, 1.0, 1.0, 0.8); drawRect(surface, 0, 0, module->width, module->height); // Draw the time setDrawColor(surface, 0, 0, 0, 0.8); drawText(surface, 10, 10, 32, "monaco", strTime); }
Print usage if the only argument is "-d"
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "emulator.h" void usage(char *programName); int main(int argsNum, char *args[]) { int i; int debugMode = 0; char *filename = NULL; emulator *e; /* Handle arguments */ for (i = 0; i < argsNum; i++) { char *arg = args[i]; if (strcmp(arg, "-d") == 0) debugMode = 1; else filename = arg; } /* Check if we have the right arguments */ if (argsNum < 2 || filename == NULL) usage(args[0]); /* Create an emulator, load in the file, and run the contents of memory */ e = emulator_new(); emulator_load_file(e, filename); emulator_run(e); /* Print out register and memory info if debug mode is enabled */ if (debugMode) { emulator_print_memory(e); emulator_print_registers(e); } /* Close the emulator */ emulator_close(e); return EXIT_SUCCESS; } void usage(char *programName) { printf("usage: %s <options> <input file>\n", programName); printf("Options:\n"); printf("-d\tDebug mode\n"); printf("\nMade by AndyRoth\n"); exit(EXIT_SUCCESS); }
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "emulator.h" void usage(char *programName); int main(int argsNum, char *args[]) { int i; int debugMode = 0; char *filename = NULL; emulator *e; /* Handle arguments */ for (i = 1; i < argsNum; i++) { char *arg = args[i]; if (strcmp(arg, "-d") == 0) debugMode = 1; else filename = arg; } /* Check if we have the right arguments */ if (argsNum < 2 || filename == NULL) usage(args[0]); /* Create an emulator, load in the file, and run the contents of memory */ e = emulator_new(); emulator_load_file(e, filename); emulator_run(e); /* Print out register and memory info if debug mode is enabled */ if (debugMode) { emulator_print_memory(e); emulator_print_registers(e); } /* Close the emulator */ emulator_close(e); return EXIT_SUCCESS; } void usage(char *programName) { printf("usage: %s <options> <input file>\n", programName); printf("Options:\n"); printf("-d\tDebug mode\n"); printf("\nMade by AndyRoth\n"); exit(EXIT_SUCCESS); }
Fix incorrect return value in psa_security_lifecycle_state (emul)
/* Copyright (c) 2019 ARM Limited * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "psa/lifecycle.h" #include "platform_srv_impl.h" uint32_t psa_security_lifecycle_state(void) { uint32_t lc_state = 0; return psa_platfrom_lifecycle_get_impl(&lc_state); } psa_status_t mbed_psa_reboot_and_request_new_security_state(uint32_t new_state) { return psa_platfrom_lifecycle_change_request_impl(new_state); }
/* Copyright (c) 2019 ARM Limited * * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "psa/lifecycle.h" #include "platform_srv_impl.h" uint32_t psa_security_lifecycle_state(void) { uint32_t lc_state = 0; psa_status_t status = PSA_LIFECYCLE_SUCCESS; status = psa_platfrom_lifecycle_get_impl(&lc_state); if (status != PSA_LIFECYCLE_SUCCESS) { lc_state = PSA_LIFECYCLE_UNKNOWN; } return lc_state; } psa_status_t mbed_psa_reboot_and_request_new_security_state(uint32_t new_state) { return psa_platfrom_lifecycle_change_request_impl(new_state); }
Add an AtomicInt class... completely untested.
/* -*- mode:linux -*- */ /** * \file atomic_int.h * * Atomic integer operations. This code uses code from * liblinuxkernel, which means that it was indirrectly taken from the * Linux kernel. * * \author Ethan Burns * \date 2008-10-14 */ #if !defined(_ATOMIC_INT_H_) #define _ATOMIC_INT_H_ #define LOCK_PREFIX "lock;" /** * This class defines an atomic integer. The operations provided as * methods of this class can be used concurrently by multiple * processors to access this interger value. * * \note A these methods are currently x86 specific. Unfortunately we * will need to add pre-processor macros to make them portable. */ class AtomicInt { public: AtomicInt(int val); inline int read(void) { return value; } inline void set(int i) { value = i; } inline void add(int i) { __asm__ __volatile__(LOCK_PREFIX "addl %1,%0" :"=m"(value) :"ir"(i), "m"(value)); } inline void sub(int i) { __asm__ __volatile__(LOCK_PREFIX "subl %1,%0" :"=m"(value) :"ir"(i), "m"(value)); } inline void inc(void) { __asm__ __volatile__(LOCK_PREFIX "incl %0" :"=m"(value) :"m"(value)); } inline void dec(void) { __asm__ __volatile__(LOCK_PREFIX "decl %0" :"=m"(value) :"m"(value)); } private: volatile int value; }; #endif /* !_ATOMIC_INT_H_ */
Remove unreachable code after goto in 00/20
#include <assert.h> void stuff() { } int main() { // MyCFG shouldn't ignore loops with exp 0 because they may have else branches bar: if (0) { foo: // label prevents CIL from optimizing away this branch stuff(); // something non-empty } else { goto bar; // direct realnode to If via goto stuff(); // something non-empty } return 0; }
#include <assert.h> void stuff() { } int main() { // MyCFG shouldn't ignore loops with exp 0 because they may have else branches bar: if (0) { foo: // label prevents CIL from optimizing away this branch stuff(); // something non-empty } else { goto bar; // direct realnode to If via goto } return 0; }
Use a strong reference for the contactObject on the contact view model. Makes it easier to use if you don't have a object that is strongly ref'ed to begin with, like a string ID.
// // ContactCollectionViewCellModel.h // MBContactPicker // // Created by Matt Bowman on 11/20/13. // Copyright (c) 2013 Citrrus, LLC. All rights reserved. // #import <Foundation/Foundation.h> @interface ContactCollectionViewCellModel : NSObject @property (nonatomic, weak) id contactObject; @property (nonatomic, copy) NSString *contactTitle; @end
// // ContactCollectionViewCellModel.h // MBContactPicker // // Created by Matt Bowman on 11/20/13. // Copyright (c) 2013 Citrrus, LLC. All rights reserved. // #import <Foundation/Foundation.h> @interface ContactCollectionViewCellModel : NSObject @property (nonatomic) id contactObject; @property (nonatomic, copy) NSString *contactTitle; @end
Add _XPG6 macro if needed..
#define _XOPEN_SOURCE 4 #define _XOPEN_SOURCE_EXTENDED 1 /* 1 needed for AIX */ #define _XOPEN_VERSION 4 #define _XPG4_2 #include <unistd.h> #include "mycrypt.h" char *mycrypt(const char *key, const char *salt) { return crypt(key, salt); }
#define _XOPEN_SOURCE 4 #define _XOPEN_SOURCE_EXTENDED 1 /* 1 needed for AIX */ #define _XOPEN_VERSION 4 #define _XPG4_2 #ifdef CRYPT_USE_XPG6 # define _XPG6 /* Some Solaris versions require this, some break with this */ #endif #include <unistd.h> #include "mycrypt.h" char *mycrypt(const char *key, const char *salt) { return crypt(key, salt); }
Remove header that is no longer present
// // Copyright (c) 2016 deltaDNA Ltd. 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 _DELTADNA_ #define _DELTADNA_ #import <DeltaDNA/DDNASDK.h> #import <DeltaDNA/DDNALog.h> #import <DeltaDNA/DDNASettings.h> #import <DeltaDNA/DDNAParams.h> #import <DeltaDNA/DDNAEvent.h> #import <DeltaDNA/DDNAProduct.h> #import <DeltaDNA/DDNATransaction.h> #import <DeltaDNA/DDNAEngagement.h> #import <DeltaDNA/DDNAEngageFactory.h> #import <DeltaDNA/DDNAImageMessage.h> #import <DeltaDNA/DDNAEventAction.h> #import <DeltaDNA/DDNAEventActionHandler.h> #import <DeltaDNA/DDNAPinpointer.h> #endif /* _DELTADNA_ */
// // Copyright (c) 2016 deltaDNA Ltd. 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 _DELTADNA_ #define _DELTADNA_ #import <DeltaDNA/DDNASDK.h> #import <DeltaDNA/DDNALog.h> #import <DeltaDNA/DDNASettings.h> #import <DeltaDNA/DDNAParams.h> #import <DeltaDNA/DDNAEvent.h> #import <DeltaDNA/DDNAProduct.h> #import <DeltaDNA/DDNATransaction.h> #import <DeltaDNA/DDNAEngagement.h> #import <DeltaDNA/DDNAEngageFactory.h> #import <DeltaDNA/DDNAImageMessage.h> #import <DeltaDNA/DDNAEventAction.h> #import <DeltaDNA/DDNAEventActionHandler.h> #endif /* _DELTADNA_ */
Add basic block tracing information as a type of "profiling" information.
/*===-- Profiling.h - Profiling support library support routines --*- C -*-===*\ |* |* The LLVM Compiler Infrastructure |* |* This file was developed by the LLVM research group and is distributed under |* the University of Illinois Open Source License. See LICENSE.TXT for details. |* |*===----------------------------------------------------------------------===*| |* |* This file defines functions shared by the various different profiling |* implementations. |* \*===----------------------------------------------------------------------===*/ #ifndef PROFILING_H #define PROFILING_H /* save_arguments - Save argc and argv as passed into the program for the file * we output. */ int save_arguments(int argc, const char **argv); enum ProfilingType { Arguments = 1, /* The command line argument block */ Function = 2, /* Function profiling information */ Block = 3, /* Block profiling information */ Edge = 4, /* Edge profiling information */ Path = 5 /* Path profiling information */ }; void write_profiling_data(enum ProfilingType PT, unsigned *Start, unsigned NumElements); #endif
/*===-- Profiling.h - Profiling support library support routines --*- C -*-===*\ |* |* The LLVM Compiler Infrastructure |* |* This file was developed by the LLVM research group and is distributed under |* the University of Illinois Open Source License. See LICENSE.TXT for details. |* |*===----------------------------------------------------------------------===*| |* |* This file defines functions shared by the various different profiling |* implementations. |* \*===----------------------------------------------------------------------===*/ #ifndef PROFILING_H #define PROFILING_H /* save_arguments - Save argc and argv as passed into the program for the file * we output. */ int save_arguments(int argc, const char **argv); enum ProfilingType { Arguments = 1, /* The command line argument block */ Function = 2, /* Function profiling information */ Block = 3, /* Block profiling information */ Edge = 4, /* Edge profiling information */ Path = 5, /* Path profiling information */ BBTrace = 6 /* Basic block trace information */ }; void write_profiling_data(enum ProfilingType PT, unsigned *Start, unsigned NumElements); #endif
Make SelfInjector aware of inherited methods.
#ifndef SAUCE_INTERNAL_SELF_INJECTOR_H_ #define SAUCE_INTERNAL_SELF_INJECTOR_H_ #include <sauce/memory.h> namespace sauce { namespace internal { /** * If a type requests injection of its own smart pointer, do so. * * An interface Iface requests this by exposing void setSelf(sauce::weak_ptr<Iface>), detected by SFINAE. */ template<typename T> class SelfInjector { typedef sauce::shared_ptr<T> Ptr; typedef void (T::* SetterMethod)(sauce::weak_ptr<T>); template<typename U, U> struct EqualTypes; template<typename DoesNotRequestSelf> void setSelfIfRequested(Ptr, ...) {} template<typename RequestsSelf> void setSelfIfRequested(Ptr ptr, EqualTypes<SetterMethod, & RequestsSelf::setSelf> *) { sauce::weak_ptr<T> weak(ptr); ptr->setSelf(weak); } public: void setSelf(Ptr ptr) { setSelfIfRequested<T>(ptr, 0); } }; } namespace i = ::sauce::internal; } #endif // SAUCE_INTERNAL_SELF_INJECTOR_H_
#ifndef SAUCE_INTERNAL_SELF_INJECTOR_H_ #define SAUCE_INTERNAL_SELF_INJECTOR_H_ #include <sauce/memory.h> namespace sauce { namespace internal { /** * If a type requests injection of its own smart pointer, do so. * * An interface Iface requests this by exposing void setSelf(sauce::weak_ptr<Iface>), detected by SFINAE. */ template<typename T> class SelfInjector { struct Guard { void setSelf(sauce::weak_ptr<T>) {} }; struct WithGuard: public T, public Guard {}; typedef sauce::shared_ptr<T> Ptr; typedef void (Guard::* NoMethod)(sauce::weak_ptr<T>); template<typename U, U> struct EqualTypes; template<typename RequestsSelf> void setSelfIfRequested(Ptr ptr, ...) { sauce::weak_ptr<T> weak(ptr); ptr->setSelf(weak); } template<typename DoesNotRequestSelf> void setSelfIfRequested(Ptr, EqualTypes<NoMethod, & DoesNotRequestSelf::setSelf> *) {} public: void setSelf(Ptr ptr) { setSelfIfRequested<WithGuard>(ptr, 0); } }; } namespace i = ::sauce::internal; } #endif // SAUCE_INTERNAL_SELF_INJECTOR_H_
REFACTOR include the more general macro collection in order_logic.h
/* a test file for ArgyrisPack */ #include <stdio.h> #include "argyris_pack.h" #define ORDER(row,col,nrows,ncols) (row)*(ncols) + (col) void print_matrix(double* matrix, int rows, int cols) { int i, j; for (i = 0; i < rows; i++) { for (j = 0; j < cols; j++) { printf("%.16f ", matrix[ORDER(i,j,rows,cols)]); } printf("\n"); } } void print_matrix_flat(double* matrix, int rows, int cols) { int i; for (i = 0; i < rows*cols; i++) { printf("%.16f ", matrix[i]); } printf("\n"); } int main(int argc, char *argv[]) { double x[3] = {0.1, 0.2, 0.3}; double y[3] = {0.2, 0.2, 0.3}; double ref_dx[21*3]; double ref_dy[21*3]; ap_local_gradients(x, y, 3, ref_dx, ref_dy); printf("ref_dx: "); print_matrix(ref_dx, 21, 3); printf("ref_dy: "); print_matrix(ref_dy, 21, 3); return 0; }
/* a test file for ArgyrisPack */ #include <stdio.h> #include "argyris_pack.h" #include "order_logic.h" void print_matrix(double* matrix, int rows, int cols) { int i, j; for (i = 0; i < rows; i++) { for (j = 0; j < cols; j++) { printf("%.16f ", matrix[ORDER(i,j,rows,cols)]); } printf("\n"); } } void print_matrix_flat(double* matrix, int rows, int cols) { int i; for (i = 0; i < rows*cols; i++) { printf("%.16f ", matrix[i]); } printf("\n"); } int main(int argc, char *argv[]) { double x[3] = {0.1, 0.2, 0.3}; double y[3] = {0.2, 0.2, 0.3}; double ref_dx[21*3]; double ref_dy[21*3]; ap_local_gradients(x, y, 3, ref_dx, ref_dy); printf("ref_dx: "); print_matrix(ref_dx, 21, 3); printf("ref_dy: "); print_matrix(ref_dy, 21, 3); return 0; }
Complete the test after adding handling of merged attributes on decls.
// RUN: clang -fsyntax-only -verify %s // CC qualifier can be applied only to functions int __attribute__((stdcall)) var1; // expected-warning{{'stdcall' attribute only applies to function types}} int __attribute__((fastcall)) var2; // expected-warning{{'fastcall' attribute only applies to function types}} // Different CC qualifiers are not compatible void __attribute__((stdcall, fastcall)) foo3(); // expected-error{{stdcall and fastcall attributes are not compatible}} // FIXME: Something went wrong recently and diagnostics is not generated anymore void __attribute__((stdcall)) foo4(); void __attribute__((fastcall)) foo4();
// RUN: clang -fsyntax-only -verify %s // CC qualifier can be applied only to functions int __attribute__((stdcall)) var1; // expected-warning{{'stdcall' attribute only applies to function types}} int __attribute__((fastcall)) var2; // expected-warning{{'fastcall' attribute only applies to function types}} // Different CC qualifiers are not compatible void __attribute__((stdcall, fastcall)) foo3(); // expected-error{{stdcall and fastcall attributes are not compatible}} void __attribute__((stdcall)) foo4(); void __attribute__((fastcall)) foo4(); // expected-error{{fastcall and stdcall attributes are not compatible}}
Fix typo in a comment: it's base58, not base48.
#ifndef BITCOINADDRESSVALIDATOR_H #define BITCOINADDRESSVALIDATOR_H #include <QValidator> /** Base48 entry widget validator. Corrects near-miss characters and refuses characters that are no part of base48. */ class BitcoinAddressValidator : public QValidator { Q_OBJECT public: explicit BitcoinAddressValidator(QObject *parent = 0); State validate(QString &input, int &pos) const; static const int MaxAddressLength = 35; }; #endif // BITCOINADDRESSVALIDATOR_H
#ifndef BITCOINADDRESSVALIDATOR_H #define BITCOINADDRESSVALIDATOR_H #include <QValidator> /** Base58 entry widget validator. Corrects near-miss characters and refuses characters that are not part of base58. */ class BitcoinAddressValidator : public QValidator { Q_OBJECT public: explicit BitcoinAddressValidator(QObject *parent = 0); State validate(QString &input, int &pos) const; static const int MaxAddressLength = 35; }; #endif // BITCOINADDRESSVALIDATOR_H
Use puts() to save 1 byte.
#define L for(char*c=a[1],y;*c;)printf("%c%c%c%c",(y="$ֶ<&"[*c++-48])&u/2?33:32,y&u?95:32,y&u/4?33:32,*c?32:10);u*=8; main(int u,char**a){L;L;L}
#define L for(char*c=a[1],y;*c;)printf("%c%c%c ",(y="$ֶ<&"[*c++-48])&u/2?33:32,y&u?95:32,y&u/4?33:32);puts("");u*=8; main(int u,char**a){L;L;L}
Declare libunwind-entry-points as PROTECTED to ensure local uses get resolved within the library itself.
/* libunwind - a platform-independent unwind library Copyright (C) 2002 Hewlett-Packard Co Contributed by David Mosberger-Tang <davidm@hpl.hp.com> This file is part of libunwind. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "unwind_i.h" PROTECTED unw_accessors_t * unw_get_accessors (unw_addr_space_t as) { if (unw.needs_initialization) ia64_init (); return &as->acc; }
Add a double check locking example
#include "rmc.h" struct mutex_t; struct foo_t; typedef struct mutex_t mutex_t; typedef struct foo_t foo_t; extern void mutex_lock(mutex_t *p); extern void mutex_unlock(mutex_t *p); extern foo_t *new_foo(void); extern mutex_t *foo_lock; foo_t *get_foo(void) { static foo_t *single_foo = 0; XEDGE(read, post); VEDGE(construct, update); L(read, foo_t *r = single_foo); if (r != 0) return r; mutex_lock(foo_lock); L(read, r = single_foo); if (r == 0) { L(construct, r = new_foo()); L(update, single_foo = r); } mutex_unlock(foo_lock); return r; }
Throw exception on cuda error to get a stack trace.
#ifndef SRC_UTILS_CUDA_HELPER_H_ #define SRC_UTILS_CUDA_HELPER_H_ #include <cuda.h> #include <cuda_runtime.h> #include <iostream> static void HandleError(cudaError_t err, const char *file, int line) { if (err != cudaSuccess) { printf("%s in %s at line %d\n", cudaGetErrorString(err), file, line); exit(EXIT_FAILURE); } } #define HANDLE_ERROR(err) (HandleError(err, __FILE__, __LINE__)) #define HANDLE_NULL(a) \ { \ if (a == NULL) \ { \ printf("Host memory failed in %s at line %d\n", __FILE__, __LINE__); \ exit(EXIT_FAILURE); \ } \ } #endif // SRC_UTILS_CUDA_HELPER_H_
#ifndef SRC_UTILS_CUDA_HELPER_H_ #define SRC_UTILS_CUDA_HELPER_H_ #include <cuda.h> #include <cuda_runtime.h> #include <iostream> #include <stdexcept> static void HandleError(cudaError_t error, const char *file, int line) { if (error != cudaSuccess) { printf("%s in %s at line %d\n", cudaGetErrorString(error), file, line); throw std::runtime_error(cudaGetErrorString(error)); } } #define HANDLE_ERROR(error) (HandleError(error, __FILE__, __LINE__)) #define HANDLE_NULL(a) \ { \ if (a == NULL) \ { \ printf("Host memory failed in %s at line %d\n", __FILE__, __LINE__); \ exit(EXIT_FAILURE); \ } \ } #endif // SRC_UTILS_CUDA_HELPER_H_
Add regression test (based on ctrace_comb) where singlethreaded mode unlock causes side effect with lazy-mine
#include <pthread.h> #include <assert.h> int g = 0; pthread_mutex_t A = PTHREAD_MUTEX_INITIALIZER; void *t_fun(void *arg) { // just for going to multithreaded mode return NULL; } int main() { pthread_mutex_lock(&A); g = 1; pthread_mutex_unlock(&A); // singlethreaded mode unlock g = 2; pthread_t id; pthread_create(&id, NULL, t_fun, NULL); assert(g == 2); return 0; }
Increase version number to 1.53
#pragma once // const float in a header file can lead to duplication of the storage // but I don't really care in this case. Just don't do it with a header // that is included hundreds of times. const float kCurrentVersion = 1.52f; // Put a "#define VERSION_SUFFIX 'b'" line here to add a minor version // increment that won't trigger the new-version checks, handy for minor // releases that I don't want to bother users about. //#define VERSION_SUFFIX 'b'
#pragma once // const float in a header file can lead to duplication of the storage // but I don't really care in this case. Just don't do it with a header // that is included hundreds of times. const float kCurrentVersion = 1.53f; // Put a "#define VERSION_SUFFIX 'b'" line here to add a minor version // increment that won't trigger the new-version checks, handy for minor // releases that I don't want to bother users about. //#define VERSION_SUFFIX 'b'
Make PathChar compatible with other platform
/* @ 0xCCCCCCCC */ #if defined(_MSC_VER) #pragma once #endif #ifndef KBASE_BASIC_TYPES_H_ #define KBASE_BASIC_TYPES_H_ #include <cstdint> #include <string> // Defines types that would be shared by among several files. namespace kbase { // |PathKey| is used by |PathService| and |BasePathProvider|. using PathKey = int; using PathChar = wchar_t; using PathString = std::basic_string<PathChar>; using byte = uint8_t; // Casts an enum value into an equivalent integer. template<typename E> constexpr auto enum_cast(E e) { return static_cast<std::underlying_type_t<E>>(e); } } // namespace kbase #endif // KBASE_BASIC_TYPES_H_
/* @ 0xCCCCCCCC */ #if defined(_MSC_VER) #pragma once #endif #ifndef KBASE_BASIC_TYPES_H_ #define KBASE_BASIC_TYPES_H_ #include <cstdint> #include <string> #include "kbase/basic_macros.h" // Defines types that would be shared by among several files. namespace kbase { // |PathKey| is used by |PathService| and |BasePathProvider|. using PathKey = int; #if defined(OS_WIN) using PathChar = wchar_t; #else using PathChar = char; #endif using PathString = std::basic_string<PathChar>; using byte = uint8_t; // Casts an enum value into an equivalent integer. template<typename E> constexpr auto enum_cast(E e) { return static_cast<std::underlying_type_t<E>>(e); } } // namespace kbase #endif // KBASE_BASIC_TYPES_H_
Fix typo in function name
/* stacks.h * Copyright: (When this is determined...it will go here) * CVS Info * $Id$ * Overview: * Stack handling routines for Parrot * Data Structure and Algorithms: * History: * Notes: * References: */ #if !defined(PARROT_STACKS_H_GUARD) #define PARROT_STACKS_H_GUARD #include "parrot/parrot.h" #define STACK_CHUNK_DEPTH 256 struct Stack_Entry { INTVAL entry_type; INTVAL flags; void (*cleanup)(struct Stack_Entry *); union { FLOATVAL num_val; INTVAL int_val; PMC *pmc_val; STRING *string_val; void *generic_pointer; } entry; }; struct Stack { INTVAL used; INTVAL free; struct StackChunk *next; struct StackChunk *prev; struct Stack_Entry entry[STACK_CHUNK_DEPTH]; }; struct Stack_Entry *push_generic_entry(struct Perl_Interp *, void *thing, INTVAL type, void *cleanup); void *pop_generic_entry(struct Perl_Interp *, void *where, INTVAL type); void toss_geleric_entry(struct Perl_Interp *, INTVAL type); #endif /* * Local variables: * c-indentation-style: bsd * c-basic-offset: 4 * indent-tabs-mode: nil * End: * * vim: expandtab shiftwidth=4: */
/* stacks.h * Copyright: (When this is determined...it will go here) * CVS Info * $Id$ * Overview: * Stack handling routines for Parrot * Data Structure and Algorithms: * History: * Notes: * References: */ #if !defined(PARROT_STACKS_H_GUARD) #define PARROT_STACKS_H_GUARD #include "parrot/parrot.h" #define STACK_CHUNK_DEPTH 256 struct Stack_Entry { INTVAL entry_type; INTVAL flags; void (*cleanup)(struct Stack_Entry *); union { FLOATVAL num_val; INTVAL int_val; PMC *pmc_val; STRING *string_val; void *generic_pointer; } entry; }; struct Stack { INTVAL used; INTVAL free; struct StackChunk *next; struct StackChunk *prev; struct Stack_Entry entry[STACK_CHUNK_DEPTH]; }; struct Stack_Entry *push_generic_entry(struct Perl_Interp *, void *thing, INTVAL type, void *cleanup); void *pop_generic_entry(struct Perl_Interp *, void *where, INTVAL type); void toss_generic_entry(struct Perl_Interp *, INTVAL type); #endif /* * Local variables: * c-indentation-style: bsd * c-basic-offset: 4 * indent-tabs-mode: nil * End: * * vim: expandtab shiftwidth=4: */
Add license header to source
#include <lua.h> #include <lauxlib.h> #include <string.h> static char * find_argv0(lua_State *L) { extern char *__progname; return __progname; } static int set_proctitle(lua_State *L) { const char *title = luaL_checkstring(L, 1); char *argv0 = find_argv0(L); // XXX no length check strcpy(argv0, title); return 0; } int luaopen_proctitle(lua_State *L) { lua_pushcfunction(L, set_proctitle); return 1; }
/* * Copyright (c) 2015 Rob Hoelz <rob AT SIGN hoelz.ro> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <lua.h> #include <lauxlib.h> #include <string.h> static char * find_argv0(lua_State *L) { extern char *__progname; return __progname; } static int set_proctitle(lua_State *L) { const char *title = luaL_checkstring(L, 1); char *argv0 = find_argv0(L); // XXX no length check strcpy(argv0, title); return 0; } int luaopen_proctitle(lua_State *L) { lua_pushcfunction(L, set_proctitle); return 1; }
Simplify SFINAE expression for RequiresScalar
#ifndef TCFRAME_TYPE_H #define TCFRAME_TYPE_H #include <ostream> #include <type_traits> using std::enable_if; using std::integral_constant; using std::is_arithmetic; using std::is_same; using std::ostream; using std::string; namespace tcframe { class Variable { public: virtual void printTo(ostream& out) = 0; virtual ~Variable() { }; }; template<typename T> using RequiresScalar = typename enable_if<integral_constant<bool, is_arithmetic<T>::value || is_same<string, T>::value>::value>::type; template<typename T> class Scalar : public Variable { private: T* value; public: explicit Scalar(T& value) { this->value = &value; } void printTo(ostream& out) { out << *value; } }; } #endif
#ifndef TCFRAME_TYPE_H #define TCFRAME_TYPE_H #include <ostream> #include <type_traits> using std::enable_if; using std::integral_constant; using std::is_arithmetic; using std::is_same; using std::ostream; using std::string; namespace tcframe { class Variable { public: virtual void printTo(ostream& out) = 0; virtual ~Variable() { }; }; template<typename T> using RequiresScalar = typename enable_if<is_arithmetic<T>::value || is_same<string, T>::value>::type; template<typename T> class Scalar : public Variable { private: T* value; public: explicit Scalar(T& value) { this->value = &value; } void printTo(ostream& out) { out << *value; } }; } #endif
Add missing declaration of zebra_hello()
/* * OLSRd Quagga plugin * * Copyright (C) 2006-2008 Immo 'FaUl' Wehrenberg <immo@chaostreff-dortmund.de> * Copyright (C) 2007-2010 Vasilis Tsiligiannis <acinonyxs@yahoo.gr> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation or - at your option - under * the terms of the GNU General Public Licence version 2 but can be * linked to any BSD-Licenced Software with public available sourcecode * */ /* ------------------------------------------------------------------------- * File : quagga.h * Description : header file for quagga.c * ------------------------------------------------------------------------- */ #include "routing_table.h" /* Zebra socket */ #ifndef ZEBRA_SOCKPATH #define ZEBRA_SOCKPATH "/var/run/quagga/zserv.api" #endif /* Quagga plugin flags */ void zebra_init(void); void zebra_fini(void); int zebra_addroute(const struct rt_entry *); int zebra_delroute(const struct rt_entry *); void zebra_redistribute(uint16_t cmd); /* * Local Variables: * c-basic-offset: 2 * indent-tabs-mode: nil * End: */
/* * OLSRd Quagga plugin * * Copyright (C) 2006-2008 Immo 'FaUl' Wehrenberg <immo@chaostreff-dortmund.de> * Copyright (C) 2007-2012 Vasilis Tsiligiannis <acinonyxs@yahoo.gr> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation or - at your option - under * the terms of the GNU General Public Licence version 2 but can be * linked to any BSD-Licenced Software with public available sourcecode * */ /* ------------------------------------------------------------------------- * File : quagga.h * Description : header file for quagga.c * ------------------------------------------------------------------------- */ #include "routing_table.h" /* Zebra socket */ #ifndef ZEBRA_SOCKPATH #define ZEBRA_SOCKPATH "/var/run/quagga/zserv.api" #endif /* Quagga plugin flags */ void zebra_init(void); void zebra_fini(void); int zebra_addroute(const struct rt_entry *); int zebra_delroute(const struct rt_entry *); void zebra_redistribute(uint16_t cmd); void zebra_hello(uint16_t cmd); /* * Local Variables: * c-basic-offset: 2 * indent-tabs-mode: nil * End: */
Use normalized case and include method.
//===- Win32/Win32.h - Common Win32 Include File ----------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines things specific to Win32 implementations. // //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// //=== WARNING: Implementation here must contain only generic Win32 code that //=== is guaranteed to work on *all* Win32 variants. //===----------------------------------------------------------------------===// // Require at least Windows 2000 API. #define _WIN32_WINNT 0x0500 #include "llvm/Config/config.h" // Get build system configuration settings #include "windows.h" #include <cassert> #include <string> inline bool MakeErrMsg(std::string* ErrMsg, const std::string& prefix) { if (!ErrMsg) return true; char *buffer = NULL; FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), 0, (LPSTR)&buffer, 1, NULL); *ErrMsg = prefix + buffer; LocalFree(buffer); return true; } class AutoHandle { HANDLE handle; public: AutoHandle(HANDLE h) : handle(h) {} ~AutoHandle() { if (handle) CloseHandle(handle); } operator HANDLE() { return handle; } AutoHandle &operator=(HANDLE h) { handle = h; return *this; } };
//===- Win32/Win32.h - Common Win32 Include File ----------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines things specific to Win32 implementations. // //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// //=== WARNING: Implementation here must contain only generic Win32 code that //=== is guaranteed to work on *all* Win32 variants. //===----------------------------------------------------------------------===// // Require at least Windows 2000 API. #define _WIN32_WINNT 0x0500 #include "llvm/Config/config.h" // Get build system configuration settings #include <Windows.h> #include <cassert> #include <string> inline bool MakeErrMsg(std::string* ErrMsg, const std::string& prefix) { if (!ErrMsg) return true; char *buffer = NULL; FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), 0, (LPSTR)&buffer, 1, NULL); *ErrMsg = prefix + buffer; LocalFree(buffer); return true; } class AutoHandle { HANDLE handle; public: AutoHandle(HANDLE h) : handle(h) {} ~AutoHandle() { if (handle) CloseHandle(handle); } operator HANDLE() { return handle; } AutoHandle &operator=(HANDLE h) { handle = h; return *this; } };
Add NSBundle+Universal.h to toolkit header
// // Toolkit header to include the main headers of the 'AFToolkit' library. // #import "AFDefines.h" #import "AFLogHelper.h" #import "AFFileHelper.h" #import "AFPlatformHelper.h" #import "AFKVO.h" #import "AFArray.h" #import "AFMutableArray.h" #import "UITableViewCell+Universal.h" #import "AFDBClient.h" #import "AFView.h" #import "AFViewController.h"
// // Toolkit header to include the main headers of the 'AFToolkit' library. // #import "AFDefines.h" #import "AFLogHelper.h" #import "AFFileHelper.h" #import "AFPlatformHelper.h" #import "AFKVO.h" #import "AFArray.h" #import "AFMutableArray.h" #import "NSBundle+Universal.h" #import "UITableViewCell+Universal.h" #import "AFDBClient.h" #import "AFView.h" #import "AFViewController.h"
Add test for concatenation in the preprocessor
/* name: TEST031 description: Test concatenation in preprocessor output: F5 I G6 F5 main { \ A7 I foo A8 I bar A9 I foobar A9 A7 A8 +I :I A9 A7 A8 +I :I r #I0 } */ #define CAT(x,y) x ## y #define XCAT(x,y) CAT(x,y) #define FOO foo #define BAR bar int main(void) { int foo, bar, foobar; CAT(foo,bar) = foo + bar; XCAT(FOO,BAR) = foo + bar; return 0; }
Use zeroes for fcntl constants on Windows
#include <fcntl.h> #include <stdio.h> int main(void) { printf("F_GETFL=%d\n", F_GETFL); printf("F_SETFL=%d\n", F_SETFL); printf("O_NONBLOCK=%d\n", O_NONBLOCK); return 0; }
#if _WIN32 || _WIN64 # define F_GETFL 0 # define F_SETFL 0 # define O_NONBLOCK 0 #else # include <fcntl.h> #endif #include <stdio.h> int main(void) { printf("F_GETFL=%d\n", F_GETFL); printf("F_SETFL=%d\n", F_SETFL); printf("O_NONBLOCK=%d\n", O_NONBLOCK); return 0; }
Add demo of magic primes.
/* * Compute prime numbers up to 67. * * https://spamsink.dreamwidth.org/1197779.html */ #include <stdio.h> #include <math.h> double magic(double f) { double ff = floor(f); double r = log(ff + 6) * (log(ff + 6) - 1); return (f - ff) * floor(r) + f; } double C = 2.6358597414547913; int main() { int i; for (i = 1; i < 20; ++i) { printf("%d\n", (int)C); C = magic(C); } return 0; }
Add USART enum for pyboard skin labels.
typedef enum { PYB_USART_NONE = 0, PYB_USART_1 = 1, PYB_USART_2 = 2, PYB_USART_3 = 3, PYB_USART_6 = 4, PYB_USART_MAX = 4, } pyb_usart_t; extern pyb_usart_t pyb_usart_global_debug; void usart_init(pyb_usart_t usart_id, uint32_t baudrate); bool usart_rx_any(pyb_usart_t usart_id); int usart_rx_char(pyb_usart_t usart_id); void usart_tx_str(pyb_usart_t usart_id, const char *str); void usart_tx_strn_cooked(pyb_usart_t usart_id, const char *str, int len); mp_obj_t pyb_Usart(mp_obj_t usart_id, mp_obj_t baudrate);
typedef enum { PYB_USART_NONE = 0, PYB_USART_1 = 1, PYB_USART_2 = 2, PYB_USART_3 = 3, PYB_USART_6 = 4, PYB_USART_MAX = 4, //PYB_USART_XA = // USART4 on X1, X2 = PA0, PA1 PYB_USART_XB = 1, // USART1 on X9, X10 = PB6, PB7 PYB_USART_YA = 4, // USART6 on Y1, Y2 = PC6, PC7 PYB_USART_YB = 3, // USART3 on Y9, Y10 = PB10, PB11 } pyb_usart_t; extern pyb_usart_t pyb_usart_global_debug; void usart_init(pyb_usart_t usart_id, uint32_t baudrate); bool usart_rx_any(pyb_usart_t usart_id); int usart_rx_char(pyb_usart_t usart_id); void usart_tx_str(pyb_usart_t usart_id, const char *str); void usart_tx_strn_cooked(pyb_usart_t usart_id, const char *str, int len); mp_obj_t pyb_Usart(mp_obj_t usart_id, mp_obj_t baudrate);
Set MIDPOINT to 90 instead of 128 (servo lib goes from 0 to 180)
#ifndef __MOTORS_H_ #define __MOTORS_H_ #include <Servo.h> #define MIDPOINT 128 class Motors { private: Servo port, vertical, starbord; int port_pin, vertical_pin, starbord_pin; public: Motors(int p_pin, int v_pin, int s_pin); void reset(); void go(int p, int v, int s); void stop(); }; #endif
#ifndef __MOTORS_H_ #define __MOTORS_H_ #include <Servo.h> #define MIDPOINT 90 class Motors { private: Servo port, vertical, starbord; int port_pin, vertical_pin, starbord_pin; public: Motors(int p_pin, int v_pin, int s_pin); void reset(); void go(int p, int v, int s); void stop(); }; #endif
Change default serial to USART2 for bluepill stm32f103 board
#ifndef PINS_H_ #define PINS_H_ typedef GPIO_PIN_LED<3,13,false> LED_BUILTIN_; typedef GPIO_PIN<1,9> TX1_PIN; typedef GPIO_PIN<1,10> RX1_PIN; typedef TX1_PIN TX_PIN; typedef RX1_PIN RX_PIN; typedef GPIO_PIN<1,2> TX2_PIN; typedef GPIO_PIN<1,3> RX2_PIN; typedef GPIO_PIN<2,10> TX3_PIN; typedef GPIO_PIN<2,11> RX3_PIN; typedef GPIO_PIN<0,0xFFFF> NO_PIN; #endif
#ifndef PINS_H_ #define PINS_H_ typedef GPIO_PIN_LED<3,13,false> LED_BUILTIN_; typedef GPIO_PIN<1,9> TX1_PIN; typedef GPIO_PIN<1,10> RX1_PIN; typedef GPIO_PIN<1,2> TX2_PIN; typedef GPIO_PIN<1,3> RX2_PIN; typedef GPIO_PIN<2,10> TX3_PIN; typedef GPIO_PIN<2,11> RX3_PIN; typedef GPIO_PIN<0,0xFFFF> NO_PIN; typedef TX2_PIN TX_PIN; typedef RX2_PIN RX_PIN; #endif
Add trailing return type to type printing test
// RUN: %ucc -Xprint %s 2>/dev/null | grep 'typeof' | %output_check -w "/typeof\(int \*\) ip.*/" "/typeof\(int \*\) \*a1.*/" "/typeof\(int \*\) a2\[2\].*/" "/typeof\(int \*\) a3\(\).*/" "typeof(expr: identifier) (aka 'long *') xyz()" long *x; __typeof(int *) ip; __typeof(int *) *a1; __typeof(int *) a2[2]; __typeof(int *) a3(); __typeof(x) xyz() { }
// RUN: %ucc -Xprint %s 2>/dev/null | grep 'typeof' | %output_check -w "/typeof\(int \*\) ip.*/" "/typeof\(int \*\) \*a1.*/" "/typeof\(int \*\) a2\[2\].*/" "/typeof\(int \*\) a3\(\).*/" "typeof(expr: identifier) (aka 'long *') abc()" "typeof(expr: identifier) (aka 'long *') xyz()" long *x; __typeof(int *) ip; __typeof(int *) *a1; __typeof(int *) a2[2]; __typeof(int *) a3(); auto abc() -> __typeof(x) { } __typeof(x) xyz() { }
Remove extra public declaration (still compiles but extraneous)
#ifndef _CUTIE_H_ #define _CUTIE_H_ class Cutie { private: bool respondsToHugs; unsigned int hugs; unsigned int tlc; public: Cutie(); public: void setAcceptsHugs(bool value); bool acceptsHugs(); void hug(); void empathy(); unsigned int showHugs(); unsigned int showTlc(); }; #endif
#ifndef _CUTIE_H_ #define _CUTIE_H_ class Cutie { private: bool respondsToHugs; unsigned int hugs; unsigned int tlc; public: Cutie(); void setAcceptsHugs(bool value); bool acceptsHugs(); void hug(); void empathy(); unsigned int showHugs(); unsigned int showTlc(); }; #endif
Include the sparc register in this file
//===-- Passes.h - Target independent code generation passes ----*- C++ -*-===// // // This file defines interfaces to access the target independent code generation // passes provided by the LLVM backend. // //===----------------------------------------------------------------------===// #ifndef LLVM_CODEGEN_PASSES_H #define LLVM_CODEGEN_PASSES_H class FunctionPass; class PassInfo; // PHIElimination pass - This pass eliminates machine instruction PHI nodes by // inserting copy instructions. This destroys SSA information, but is the // desired input for some register allocators. This pass is "required" by these // register allocator like this: AU.addRequiredID(PHIEliminationID); // extern const PassInfo *PHIEliminationID; /// SimpleRegisterAllocation Pass - This pass converts the input machine code /// from SSA form to use explicit registers by spilling every register. Wow, /// great policy huh? /// FunctionPass *createSimpleRegisterAllocator(); /// LocalRegisterAllocation Pass - This pass register allocates the input code a /// basic block at a time, yielding code better than the simple register /// allocator, but not as good as a global allocator. /// FunctionPass *createLocalRegisterAllocator(); /// PrologEpilogCodeInserter Pass - This pass inserts prolog and epilog code, /// and eliminates abstract frame references. /// FunctionPass *createPrologEpilogCodeInserter(); #endif
//===-- Passes.h - Target independent code generation passes ----*- C++ -*-===// // // This file defines interfaces to access the target independent code generation // passes provided by the LLVM backend. // //===----------------------------------------------------------------------===// #ifndef LLVM_CODEGEN_PASSES_H #define LLVM_CODEGEN_PASSES_H class FunctionPass; class PassInfo; // PHIElimination pass - This pass eliminates machine instruction PHI nodes by // inserting copy instructions. This destroys SSA information, but is the // desired input for some register allocators. This pass is "required" by these // register allocator like this: AU.addRequiredID(PHIEliminationID); // extern const PassInfo *PHIEliminationID; /// SimpleRegisterAllocation Pass - This pass converts the input machine code /// from SSA form to use explicit registers by spilling every register. Wow, /// great policy huh? /// FunctionPass *createSimpleRegisterAllocator(); /// LocalRegisterAllocation Pass - This pass register allocates the input code a /// basic block at a time, yielding code better than the simple register /// allocator, but not as good as a global allocator. /// FunctionPass *createLocalRegisterAllocator(); /// PrologEpilogCodeInserter Pass - This pass inserts prolog and epilog code, /// and eliminates abstract frame references. /// FunctionPass *createPrologEpilogCodeInserter(); /// getRegisterAllocator - This creates an instance of the register allocator /// for the Sparc. FunctionPass *getRegisterAllocator(TargetMachine &T); #endif
Solve exercise of Chapter 1, Paragraph 3.
#include <stdio.h> main() { int fahr; for (fahr = 300; fahr >= 0; fahr = fahr - 20) printf("%3d %6.1f\n", fahr, (5.0/9.0) * (fahr - 32.0)); }
Add name to DOLIT entry
#include <stdlib.h> #include <stdarg.h> #include <string.h> #include <stack_machine/common.h> #include <stack_machine/compiler.h> state_t __DOLIT(context_t *ctx) { pushnum(ctx->ds, (*(int *)ctx->ip++)); return OK; } void literal(context_t *ctx, int n) { static entry_t dolit = { .code_ptr = &__DOLIT }; compile(ctx, 2, &dolit, n); } void compile(context_t *ctx, int n, ...) { va_list params; va_start(params, n); for (int i = 0; i < n; i++) { word_t arg = va_arg(params, word_t); comma(ctx, arg); } va_end(params); }
#include <stdlib.h> #include <stdarg.h> #include <string.h> #include <stack_machine/common.h> #include <stack_machine/compiler.h> state_t __DOLIT(context_t *ctx) { pushnum(ctx->ds, (*(int *)ctx->ip++)); return OK; } void literal(context_t *ctx, int n) { static entry_t dolit = { .code_ptr = &__DOLIT, .name = "DOLIT" }; compile(ctx, 2, &dolit, n); } void compile(context_t *ctx, int n, ...) { va_list params; va_start(params, n); for (int i = 0; i < n; i++) { word_t arg = va_arg(params, word_t); comma(ctx, arg); } va_end(params); }
Add platform-specific string formatters for size_t
/* Copyright 2015 John Bailey 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. */ #if !defined WD_H #define WD_H #define WD_SUCCESS -1 #define WD_GENERIC_FAIL 0 #define WD_SUCCEEDED( _x ) (( _x ) == WD_SUCCESS ) #endif
/* Copyright 2015 John Bailey 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. */ #if !defined WD_H #define WD_H #define WD_SUCCESS -1 #define WD_GENERIC_FAIL 0 #define WD_SUCCEEDED( _x ) (( _x ) == WD_SUCCESS ) #if defined WIN32 /** Printf format string for size_t */ #define PFFST "%Iu" #else #define PFFST "%zu" #endif #endif
Update the source code file names
// // BleBeaconSignInModel.h // BleToolBox // // Created by Mark on 2018/1/26. // Copyright © 2018年 MarkCJ. All rights reserved. // #import "BleBaseModel.h" @interface BleBeaconSignInModel : BleBaseModel @property NSString *beaconName; // the beacon name. @property NSString *beaconDeviceUUID; // the beacon UUID. @property NSString *beaconServiceUUID; // the beacon service UUID. @property NSInteger signInRSSI; // the beacon RSSI when sign in. @property NSDate *signInTime; // time then sign in. /** Init the beacon model by beacon information @param name Device name @param deviceUUID Device UUID @param serviceUUID Device Service UUID @param rssi RSSI value @param time Sign in time @return */ -(instancetype)initWithBeaconName:(NSString *)name deviceUUID:(NSString *)deviceUUID serviceUUID:(NSString *)serviceUUID RSSI:(NSInteger)rssi signInTime:(NSDate *)time; @end
// // BleBeaconSignInModel.h // BleToolBox // // Created by Mark on 2018/1/26. // Copyright © 2018年 MarkCJ. All rights reserved. // #import "BleBaseModel.h" @interface BleBeaconSignInModel : BleBaseModel @property NSString *beaconName; // the beacon name. @property NSString *beaconDeviceUUID; // the beacon UUID. @property NSString *beaconServiceUUID; // the beacon service UUID. @property NSInteger signInRSSI; // the beacon RSSI when sign in. @property NSDate *signInTime; // time then sign in. /** Init the beacon model by beacon information @param name Device name @param deviceUUID Device UUID @param serviceUUID Device Service UUID @param rssi RSSI value @param time Sign in time */ -(instancetype)initWithBeaconName:(NSString *)name deviceUUID:(NSString *)deviceUUID serviceUUID:(NSString *)serviceUUID RSSI:(NSInteger)rssi signInTime:(NSDate *)time; @end
Add log option for loading cookies
// // NSData+DK.h // // Created by dkhamsing on 2/24/14. // #import <Foundation/Foundation.h> @interface NSData (DK) /** Load session cookies. Credits: http://stackoverflow.com/questions/14387662/afnetworking-persisting-cookies-automatically */ + (void)dk_cookiesLoad; /** Save session cookies. Credits: http://stackoverflow.com/questions/14387662/afnetworking-persisting-cookies-automatically */ + (void)dk_cookiesSave; @end
// // NSData+DK.h // // Created by dkhamsing on 2/24/14. // #import <Foundation/Foundation.h> @interface NSData (DK) /** Load session cookies. @param log Boolean that outputs with NSLog. Credits: http://stackoverflow.com/questions/14387662/afnetworking-persisting-cookies-automatically */ + (void)dk_cookiesLoadWithLog:(BOOL)log; /** Load session cookies without logging. */ + (void)dk_cookiesLoad; /** Save session cookies. Credits: http://stackoverflow.com/questions/14387662/afnetworking-persisting-cookies-automatically */ + (void)dk_cookiesSave; @end
Use primitive std::int32_t instead of reference type
#ifndef CPR_LOW_SPEED_H #define CPR_LOW_SPEED_H #include <cstdint> namespace cpr { class LowSpeed { public: LowSpeed(const std::int32_t& limit, const std::int32_t& time) : limit(limit), time(time) {} std::int32_t limit; std::int32_t time; }; } // namespace cpr #endif
#ifndef CPR_LOW_SPEED_H #define CPR_LOW_SPEED_H #include <cstdint> namespace cpr { class LowSpeed { public: LowSpeed(const std::int32_t limit, const std::int32_t time) : limit(limit), time(time) {} std::int32_t limit; std::int32_t time; }; } // namespace cpr #endif
Add command to allow non incremental statedumps
/* * This file is part of Kotaka, a mud library for DGD * http://github.com/shentino/kotaka * * Copyright (C) 2012 Raymond Jennings * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <kotaka/paths.h> #include <text/paths.h> inherit LIB_WIZBIN; void main(string args) { int count; if (query_user()->query_class() < 3) { send_out("You do not have sufficient access rights to dump the mud.\n"); return; } proxy_call("dump_state"); }
Fix memory leak in tests
#include "parser.h" #include "ast.h" #include "tests.h" void test_parse_number(); int main() { test_parse_number(); return 0; } struct token *make_token(enum token_type tk_type, char* str, double dbl, int number) { struct token *tk = malloc(sizeof(struct token)); tk->type = tk_type; if (tk_type == tok_dbl) { tk->value.dbl = dbl; } else if (tk_type == tok_number) { tk->value.num = number; } else { tk->value.string = str; } return tk; } void test_parse_number() { struct token_list *tkl = make_token_list(); struct token *tk = make_token(tok_number, NULL, 0.0, 42); append_token_list(tkl, tk); struct ast_node *result = parse_number(tkl); EXPECT_EQ(result->val, tk); EXPECT_EQ(result->num_children, 0); destroy_token_list(tkl); }
#include "parser.h" #include "ast.h" #include "tests.h" void test_parse_number(); int main() { test_parse_number(); return 0; } struct token *make_token(enum token_type tk_type, char* str, double dbl, int number) { struct token *tk = malloc(sizeof(struct token)); tk->type = tk_type; if (tk_type == tok_dbl) { tk->value.dbl = dbl; } else if (tk_type == tok_number) { tk->value.num = number; } else { tk->value.string = str; } return tk; } void test_parse_number() { struct token_list *tkl = make_token_list(); struct token *tk = make_token(tok_number, NULL, 0.0, 42); append_token_list(tkl, tk); struct ast_node *result = parse_number(tkl); EXPECT_EQ(result->val, tk); EXPECT_EQ(result->num_children, 0); destroy_token_list(tkl); delete_node(result); }
Move namespaces declarations to the top of the file.
// This file is part of MorphoDiTa <http://github.com/ufal/morphodita/>. // // Copyright 2015 Institute of Formal and Applied Linguistics, Faculty of // Mathematics and Physics, Charles University in Prague, Czech Republic. // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #pragma once // Headers available in all sources #include <cassert> #include <cstddef> #include <cstdint> #include <cstdlib> #include <iomanip> #include <iostream> #include <memory> #include <string> #include <vector> // Assert that int is at least 4B static_assert(sizeof(int) >= sizeof(int32_t), "Int must be at least 4B wide!"); // Assert that we are on a little endian system #ifdef __BYTE_ORDER__ static_assert(__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__, "Only little endian systems are supported!"); #endif #define runtime_failure(message) exit((cerr << message << endl, 1)) // Define namespace ufal::morphodita. namespace ufal { namespace morphodita { using namespace std; } // namespace morphodita } // namespace ufal
// This file is part of MorphoDiTa <http://github.com/ufal/morphodita/>. // // Copyright 2015 Institute of Formal and Applied Linguistics, Faculty of // Mathematics and Physics, Charles University in Prague, Czech Republic. // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #pragma once // Headers available in all sources #include <cassert> #include <cstddef> #include <cstdint> #include <cstdlib> #include <iomanip> #include <iostream> #include <memory> #include <string> #include <vector> // Define namespace ufal::morphodita. namespace ufal { namespace morphodita { using namespace std; // Assert that int is at least 4B static_assert(sizeof(int) >= sizeof(int32_t), "Int must be at least 4B wide!"); // Assert that we are on a little endian system #ifdef __BYTE_ORDER__ static_assert(__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__, "Only little endian systems are supported!"); #endif #define runtime_failure(message) exit((cerr << message << endl, 1)) } // namespace morphodita } // namespace ufal
Fix include of DTTimePeriod in DateTools cocoapod
// // AKEvent.h // Example // // Created by ak on 18.01.2016. // Copyright © 2016 Eric Horacek. All rights reserved. // #import <Foundation/Foundation.h> #import "DTTimePeriod.h" @interface MSEvent : DTTimePeriod @property (nonatomic, strong) NSString *title; @property (nonatomic, strong) NSString *location; +(instancetype)make:(NSDate*)start title:(NSString*)title subtitle:(NSString*)subtitle; +(instancetype)make:(NSDate*)start end:(NSDate*)end title:(NSString*)title subtitle:(NSString*)subtitle; +(instancetype)make:(NSDate*)start duration:(int)minutes title:(NSString*)title subtitle:(NSString*)subtitle; - (NSDate *)day; @end
// // AKEvent.h // Example // // Created by ak on 18.01.2016. // Copyright © 2016 Eric Horacek. All rights reserved. // #import <Foundation/Foundation.h> #import <DateTools/DTTimePeriod.h> @interface MSEvent : DTTimePeriod @property (nonatomic, strong) NSString *title; @property (nonatomic, strong) NSString *location; +(instancetype)make:(NSDate*)start title:(NSString*)title subtitle:(NSString*)subtitle; +(instancetype)make:(NSDate*)start end:(NSDate*)end title:(NSString*)title subtitle:(NSString*)subtitle; +(instancetype)make:(NSDate*)start duration:(int)minutes title:(NSString*)title subtitle:(NSString*)subtitle; - (NSDate *)day; @end
Remove extern decl of no longer used/included SHA-1 SSE2 function
/* * SHA-160 * (C) 1999-2007 Jack Lloyd * * Distributed under the terms of the Botan license */ #ifndef BOTAN_SHA_160_SSE2_H__ #define BOTAN_SHA_160_SSE2_H__ #include <botan/sha160.h> namespace Botan { /* * SHA-160 */ class BOTAN_DLL SHA_160_SSE2 : public SHA_160 { public: HashFunction* clone() const { return new SHA_160_SSE2; } SHA_160_SSE2() : SHA_160(0) {} // no W needed private: void compress_n(const byte[], u32bit blocks); }; extern "C" void botan_sha1_sse2_compress(u32bit[5], const u32bit*); } #endif
/* * SHA-160 * (C) 1999-2007 Jack Lloyd * * Distributed under the terms of the Botan license */ #ifndef BOTAN_SHA_160_SSE2_H__ #define BOTAN_SHA_160_SSE2_H__ #include <botan/sha160.h> namespace Botan { /* * SHA-160 */ class BOTAN_DLL SHA_160_SSE2 : public SHA_160 { public: HashFunction* clone() const { return new SHA_160_SSE2; } SHA_160_SSE2() : SHA_160(0) {} // no W needed private: void compress_n(const byte[], u32bit blocks); }; } #endif
Fix missing braces warning for initialization of subobjects
/* @ 0xCCCCCCCC */ #if defined(_MSC_VER) #pragma once #endif #ifndef KBASE_STACK_WALKER_H_ #define KBASE_STACK_WALKER_H_ #include <array> #include "kbase/basic_macros.h" #if defined(OS_WIN) struct _CONTEXT; using CONTEXT = _CONTEXT; #endif namespace kbase { class StackWalker { public: StackWalker() noexcept; #if defined(OS_WIN) // Dumps a callstack for an exception case. explicit StackWalker(CONTEXT* context); #endif ~StackWalker() = default; DEFAULT_COPY(StackWalker); DEFAULT_MOVE(StackWalker); void DumpCallStack(std::ostream& stream); std::string CallStackToString(); private: static constexpr size_t kMaxStackFrames = 64U; std::array<void*, kMaxStackFrames> stack_frames_ { nullptr }; size_t valid_frame_count_ = 0; }; } // namespace kbase #endif // KBASE_STACK_WALKER_H_
/* @ 0xCCCCCCCC */ #if defined(_MSC_VER) #pragma once #endif #ifndef KBASE_STACK_WALKER_H_ #define KBASE_STACK_WALKER_H_ #include <array> #include "kbase/basic_macros.h" #if defined(OS_WIN) struct _CONTEXT; using CONTEXT = _CONTEXT; #endif namespace kbase { class StackWalker { public: StackWalker() noexcept; #if defined(OS_WIN) // Dumps a callstack for an exception case. explicit StackWalker(CONTEXT* context); #endif ~StackWalker() = default; DEFAULT_COPY(StackWalker); DEFAULT_MOVE(StackWalker); void DumpCallStack(std::ostream& stream); std::string CallStackToString(); private: static constexpr size_t kMaxStackFrames = 64U; std::array<void*, kMaxStackFrames> stack_frames_ {{nullptr}}; size_t valid_frame_count_ = 0; }; } // namespace kbase #endif // KBASE_STACK_WALKER_H_
Change Pods to BonMot in header.
// // BonMot+UIKit.h // Pods // // Created by Nora Trapp on 3/10/16. // // #import "BONTextAlignmentConstraint.h" #import "UILabel+BonMotUtilities.h" #import "UITextField+BonMotUtilities.h" #import "UITextView+BonMotUtilities.h"
// // BonMot+UIKit.h // BonMot // // Created by Nora Trapp on 3/10/16. // // #import "BONTextAlignmentConstraint.h" #import "UILabel+BonMotUtilities.h" #import "UITextField+BonMotUtilities.h" #import "UITextView+BonMotUtilities.h"
Convert 0-63 indicies <-> (row,col)
// for all of these conversions, 0 <= row,col < 8 static inline uint8_t bb_index_of(uint8_t row, uint8_t col) { return row + (col << 3); } static inline uint8_t bb_row_of(uint8_t index) { return index % 8; } static inline uint8_t bb_col_of(uint8_t index) { return (uint8_t)(index / 8); }
Make bundle property read only
// // ObSFileLoader.h // GameChanger // // Created by Kiril Savino on Tuesday, April 16, 2013 // Copyright 2013 GameChanger. All rights reserved. // @class ObSInPort; @protocol ObSFileLoader <NSObject> - (ObSInPort*)findFile:(NSString*)filename; - (NSString*)qualifyFileName:(NSString*)filename; @end @interface ObSBundleFileLoader : NSObject <ObSFileLoader> @property (nonatomic, strong) NSBundle *bundle; - (instancetype)initWithBundle:(NSBundle *)bundle; @end @interface ObSFilesystemFileLoader : NSObject <ObSFileLoader> { NSString* _directoryPath; } + (ObSFilesystemFileLoader*)loaderForPath:(NSString*)path; @end
// // ObSFileLoader.h // GameChanger // // Created by Kiril Savino on Tuesday, April 16, 2013 // Copyright 2013 GameChanger. All rights reserved. // @class ObSInPort; @protocol ObSFileLoader <NSObject> - (ObSInPort*)findFile:(NSString*)filename; - (NSString*)qualifyFileName:(NSString*)filename; @end @interface ObSBundleFileLoader : NSObject <ObSFileLoader> @property (nonatomic, strong, readonly) NSBundle *bundle; - (instancetype)initWithBundle:(NSBundle *)bundle; @end @interface ObSFilesystemFileLoader : NSObject <ObSFileLoader> { NSString* _directoryPath; } + (ObSFilesystemFileLoader*)loaderForPath:(NSString*)path; @end
Add NOMINMAX before including Windows.h
#ifndef _R2BOT_CONFIG #define _R2BOT_CONFIG #define _WINSOCK_DEPRECATED_NO_WARNINGS #define DEBUG_PRINTS #define DEVICE_NAME "NUC" #undef USE_KINECT1 #undef USE_KINECT2 #undef USE_MOTORS #undef USE_ULTRASONIC #define USE_R2SERVER #endif
#ifndef _R2BOT_CONFIG #define _R2BOT_CONFIG #define NOMINMAX #define _WINSOCK_DEPRECATED_NO_WARNINGS #define DEBUG_PRINTS #define DEVICE_NAME "NUC" #undef USE_KINECT1 #undef USE_KINECT2 #undef USE_MOTORS #undef USE_ULTRASONIC #define USE_R2SERVER #endif
Add an initial test script for the flowers.
int pin_r = 9; int pin_g = 10; int pin_b = 11; int brightness = 0; int increment = 1; void setup() { pinMode(pin_r, OUTPUT); pinMode(pin_g, OUTPUT); pinMode(pin_b, OUTPUT); /* Serial.begin(9600); */ } void loop() { brightness = brightness + increment; if (brightness <= 0 || brightness >= 128) { increment = -increment; } analogWrite(pin_r, brightness/2); analogWrite(pin_g, brightness); analogWrite(pin_b, 128); delay(20); }
Add missing header from last commit
/** * tapcfg - A cross-platform configuration utility for TAP driver * Copyright (C) 2008 Juho Vähä-Herttua * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ #ifndef SERVERSOCK_H #define SERVERSOCK_H #include "tapcfg.h" typedef struct serversock_s serversock_t; serversock_t *serversock_tcp(unsigned short *local_port, int use_ipv6, int public); int serversock_get_fd(serversock_t *server); int serversock_accept(serversock_t *server); void serversock_destroy(serversock_t *server); #endif
Define OpenGLES support for ARM
// Copyright (C) 2016 Elviss Strazdins // This file is part of the Ouzel engine. #pragma once #if defined(_WIN32) || defined(_WIN64) || defined(WIN32) || defined(WIN64) #define OUZEL_PLATFORM_WINDOWS 1 #define OUZEL_SUPPORTS_DIRECT3D11 1 #elif defined(__APPLE__) #include <TargetConditionals.h> #if TARGET_OS_IOS #define OUZEL_PLATFORM_IOS 1 #define OUZEL_SUPPORTS_OPENGLES 1 #define OUZEL_SUPPORTS_METAL 1 #elif TARGET_OS_TV #define OUZEL_PLATFORM_TVOS 1 #define OUZEL_SUPPORTS_OPENGLES 1 #define OUZEL_SUPPORTS_METAL 1 #elif TARGET_OS_MAC #define OUZEL_PLATFORM_OSX 1 #define OUZEL_SUPPORTS_OPENGL 1 #define OUZEL_SUPPORTS_METAL 1 #endif #elif defined(__ANDROID__) #define OUZEL_PLATFORM_ANDROID 1 #define OUZEL_SUPPORTS_OPENGLES 1 #elif defined(__linux__) #define OUZEL_PLATFORM_LINUX 1 #define OUZEL_SUPPORTS_OPENGL 1 #endif
// Copyright (C) 2016 Elviss Strazdins // This file is part of the Ouzel engine. #pragma once #if defined(_WIN32) || defined(_WIN64) || defined(WIN32) || defined(WIN64) #define OUZEL_PLATFORM_WINDOWS 1 #define OUZEL_SUPPORTS_DIRECT3D11 1 #elif defined(__APPLE__) #include <TargetConditionals.h> #if TARGET_OS_IOS #define OUZEL_PLATFORM_IOS 1 #define OUZEL_SUPPORTS_OPENGLES 1 #define OUZEL_SUPPORTS_METAL 1 #elif TARGET_OS_TV #define OUZEL_PLATFORM_TVOS 1 #define OUZEL_SUPPORTS_OPENGLES 1 #define OUZEL_SUPPORTS_METAL 1 #elif TARGET_OS_MAC #define OUZEL_PLATFORM_OSX 1 #define OUZEL_SUPPORTS_OPENGL 1 #define OUZEL_SUPPORTS_METAL 1 #endif #elif defined(__ANDROID__) #define OUZEL_PLATFORM_ANDROID 1 #define OUZEL_SUPPORTS_OPENGLES 1 #elif defined(__linux__) #define OUZEL_PLATFORM_LINUX 1 #if defined(__i386__) || defined(__x86_64__) #define OUZEL_SUPPORTS_OPENGL 1 #else defined(__arm__) || defined(__aarch64__) #define OUZEL_SUPPORTS_OPENGLES 1 #endif #endif
Add insert node at head fn
/* Input Format You have to complete the Node* Insert(Node* head, int data) method which takes two arguments - the head of the linked list and the integer to insert. You should NOT read any input from stdin/console. Output Format Insert the new node at the head and return the head of the updated linked list. Do NOT print anything to stdout/console. Sample Input NULL , data = 1 1 --> NULL , data = 2 Sample Output 1 --> NULL 2 --> 1 --> NULL Explanation 1. We have an empty list, on inserting 1, 1 becomes new head. 2. We have a list with 1 as head, on inserting 2, 2 becomes the new head. */ /* Insert Node at the begining of a linked list Initially head pointer argument could be NULL for empty list Node is defined as struct Node { int data; struct Node *next; } return back the pointer to the head of the linked list in the below method. */ Node* Insert(Node *head,int data) { Node* temp; temp = (Node*)malloc(sizeof(Node)); temp->data = data; temp->next = head; head = temp; return head; }