content
stringlengths
12
2.72M
/* * Copyright (c) 2021 LiquidFenrir * zlib License, see LICENSE file. */ #ifndef NC_SCENE_H #define NC_SCENE_H #include "bn_optional.h" namespace nc { enum class scene_type { INTRO, TRANSITION_TO_SPLASH, SPLASH_DEV, SPLASH_JAM, TITLE, TITLE_TUTORIAL, PLAY_TUTORIAL, TRANSITION_TO_GAME, REACTOR, RESEARCH, PREVIEW, INDEX, }; class UpdateResult { public: UpdateResult& operator=(const scene_type); bn::optional<scene_type> change_scene() const; bool should_skip_transition() const; void skip_transition(); private: bn::optional<scene_type> _next_scene; bool _skip_transition{false}; }; class scene { public: virtual ~scene() = default; [[nodiscard]] virtual UpdateResult update() = 0; protected: scene() = default; }; } #endif
<reponame>Lxq5696184/SHYJHttpTool<gh_stars>0 // // HttpTool+RequestManager.h // HttpToolDemo // // Created by VinDiesel on 2019/7/24. // Copyright © 2019 jieyi. All rights reserved. // #import "SHYJHttpTool.h" NS_ASSUME_NONNULL_BEGIN @interface SHYJHttpTool (RequestManager) /** * 判断网络请求池中d是否有相同的请求 * * @param task 网络请求任务 * * @return bool */ + (BOOL)haveSameRequestInTasksPool:(HTURLSessionTask *)task; /** * 如果有旧请求则取消旧请求 * * @param task 新请求 * * @return 旧请求 */ + (HTURLSessionTask *)cancelSameRequestTasksPool:(HTURLSessionTask *)task; @end NS_ASSUME_NONNULL_END
<filename>content/browser/renderer_host/media/video_capture_buffer_pool.h<gh_stars>1-10 // Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_BROWSER_RENDERER_HOST_MEDIA_VIDEO_CAPTURE_BUFFER_POOL_H_ #define CONTENT_BROWSER_RENDERER_HOST_MEDIA_VIDEO_CAPTURE_BUFFER_POOL_H_ #include "base/basictypes.h" #include "base/memory/ref_counted.h" #include "base/memory/scoped_vector.h" #include "base/process.h" #include "base/shared_memory.h" #include "base/synchronization/lock.h" #include "content/common/content_export.h" #include "media/base/video_frame.h" #include "ui/gfx/size.h" namespace content { // A thread-safe class that does the bookkeeping and lifetime management for a // pool of shared-memory pixel buffers cycled between an in-process producer // (e.g. a VideoCaptureDevice) and a set of out-of-process consumers. The pool // is intended to be allocated and orchestrated by a VideoCaptureController, but // is designed to outlive the controller if necessary. // // Producers access buffers by means of a VideoFrame container. Producers get // a buffer by calling ReserveForProducer(), and pass on their ownership // of the buffer by calling HoldForConsumers(). Consumers signal that they // are done with the buffer by calling RelinquishConsumerHold(). // // Buffers are identified by an int value called |buffer_id|. Callers may depend // on the buffer IDs being dense in the range 1 to count(), inclusive, so long // as the Allocate() step succeeded. 0 is never a valid ID, and is returned by // some methods to indicate failure. class CONTENT_EXPORT VideoCaptureBufferPool : public base::RefCountedThreadSafe<VideoCaptureBufferPool> { public: VideoCaptureBufferPool(const gfx::Size& size, int count); // One-time initialization to allocate the shared memory buffers. Returns true // on success. bool Allocate(); // One-time (per client/per-buffer) initialization to share a particular // buffer to a process. base::SharedMemoryHandle ShareToProcess(int buffer_id, base::ProcessHandle process_handle); // Locate a buffer (if any) that's not in use by the producer or consumers, // and reserve it as a VideoFrame. The buffer remains reserved (and writable // by the producer) until either the VideoFrame is destroyed, or until // ownership is transferred to the consumer via HoldForConsumers(). // // The resulting VideoFrames will reference this VideoCaptureBufferPool, and // so the pool will stay alive so long as these VideoFrames do. // // |rotation| is used for a clear optimization. scoped_refptr<media::VideoFrame> ReserveForProducer(int rotation); // Transfer a buffer from producer to consumer ownership. // |producer_held_buffer| must be a frame previously returned by // ReserveForProducer(), and not already passed to HoldForConsumers(). The // caller should promptly release all references to |producer_held_buffer| // after calling this method, so that the buffer may be eventually reused once // the consumers finish with it. void HoldForConsumers( const scoped_refptr<media::VideoFrame>& producer_held_buffer, int buffer_id, int num_clients); // Indicate that one or more consumers are done with a particular buffer. This // effectively is the opposite of HoldForConsumers(). Once the consumers are // done, a buffer is returned to the pool for reuse. void RelinquishConsumerHold(int buffer_id, int num_clients); // Detect whether a particular VideoFrame is backed by a buffer that belongs // to this pool -- that is, whether it was allocated by an earlier call to // ReserveForProducer(). If so, return its buffer_id (a value between 1 and // count()). If not, return 0, indicating the buffer is not recognized (it may // be a valid frame, but we didn't allocate it). int RecognizeReservedBuffer( const scoped_refptr<media::VideoFrame>& maybe_belongs_to_pool); int count() const { return count_; } size_t GetMemorySize() const; bool IsAnyBufferHeldForConsumers(); private: friend class base::RefCountedThreadSafe<VideoCaptureBufferPool>; // Per-buffer state. struct Buffer { Buffer(); // The memory created to be shared with renderer processes. base::SharedMemory shared_memory; // Rotation in degrees of the buffer. int rotation; // Tracks whether this buffer is currently referenced by the producer. bool held_by_producer; // Number of consumer processes which hold this shared memory. int consumer_hold_count; }; virtual ~VideoCaptureBufferPool(); // Callback for VideoFrame destruction. void OnVideoFrameDestroyed(int buffer_id); bool IsAllocated() const; // Protects |buffers_| and contents thereof. base::Lock lock_; // The buffers, indexed by |buffer_id|. Element 0 is always NULL. ScopedVector<Buffer> buffers_; const gfx::Size size_; const int count_; DISALLOW_IMPLICIT_CONSTRUCTORS(VideoCaptureBufferPool); }; } // namespace content #endif // CONTENT_BROWSER_RENDERER_HOST_MEDIA_VIDEO_CAPTURE_BUFFER_POOL_H_
<reponame>ggvl/lvgl<gh_stars>1000+ #include "../lv_examples.h" #if LV_BUILD_EXAMPLES && LV_USE_LABEL /** * Using the text style properties */ void lv_example_style_8(void) { static lv_style_t style; lv_style_init(&style); lv_style_set_radius(&style, 5); lv_style_set_bg_opa(&style, LV_OPA_COVER); lv_style_set_bg_color(&style, lv_palette_lighten(LV_PALETTE_GREY, 2)); lv_style_set_border_width(&style, 2); lv_style_set_border_color(&style, lv_palette_main(LV_PALETTE_BLUE)); lv_style_set_pad_all(&style, 10); lv_style_set_text_color(&style, lv_palette_main(LV_PALETTE_BLUE)); lv_style_set_text_letter_space(&style, 5); lv_style_set_text_line_space(&style, 20); lv_style_set_text_decor(&style, LV_TEXT_DECOR_UNDERLINE); /*Create an object with the new style*/ lv_obj_t * obj = lv_label_create(lv_scr_act()); lv_obj_add_style(obj, &style, 0); lv_label_set_text(obj, "Text of\n" "a label"); lv_obj_center(obj); } #endif
/* Copyright (c) 2008-2009 TrueCrypt Developers Association. All rights reserved. Governed by the TrueCrypt License 3.0 the full text of which is contained in the file License.txt included in TrueCrypt binary and source code distribution packages. */ #ifndef TC_HEADER_Platform_Solaris_System #define TC_HEADER_Platform_Solaris_System #endif // TC_HEADER_Platform_Solaris_System
#include <iostream> #include "printable.h" #pragma once #ifndef COLORPRINTER_H #define COLORPRINTER_H class ColorPrinter : public Printable { public: // Output the print. void Print(); }; #endif
/*! \file bcma_bcmpccmd_diagstat.c * * CLI 'phy diag prbstat and fecstat' command handler. */ /* * This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file. * * Copyright 2007-2020 Broadcom Inc. All rights reserved. */ #include <bsl/bsl.h> #include <sal/sal_alloc.h> #include <sal/sal_libc.h> #include <sal/sal_mutex.h> #include <shr/shr_thread.h> #include <shr/shr_debug.h> #include <shr/shr_pb_format.h> #include <bcmpc/bcmpc_diag.h> #include <bcmpc/bcmpc_lport.h> #include <bcma/bcmpc/bcma_bcmpc_diag.h> #include "bcma_bcmpc_diag_internal.h" /******************************************************************************* * Local definitions */ #define BSL_LOG_MODULE BSL_LS_APPL_PORTDIAG #define STAT_LOCK(lock) \ if (lock) { \ sal_mutex_take(lock, SAL_MUTEX_FOREVER); \ } #define STAT_UNLOCK(lock) \ if (lock) { \ sal_mutex_give(lock); \ } /* PRBS error and loss of lock state. */ typedef struct prbs_stat_subcounter_s { uint64_t errors; uint64_t losslock; } prbs_stat_subcounter_t; /* PRBS error counter. */ typedef struct prbs_stat_counter_s { prbs_stat_subcounter_t acc; prbs_stat_subcounter_t cur; } prbs_stat_counter_t; /* * Per port information */ typedef struct prbs_stat_pinfo_s { /*! Port speed. */ uint32_t speed; /*! Number of lane on the port. */ int lanes; /*! FEC type the port. */ bcmpc_cmd_fec_t fec_type; /*! Interval per lane. */ int intervals[BCMA_BCMPC_PM_MAX_LANES]; /*! PRBS lock status per lane. */ int prbs_lock[BCMA_BCMPC_PM_MAX_LANES]; /*! PRBS error counter per lane. */ prbs_stat_counter_t counters[BCMA_BCMPC_PM_MAX_LANES]; /*! PRBS ber per lane. */ double ber[BCMA_BCMPC_PM_MAX_LANES]; } prbs_stat_pinfo_t; /*! * Priodically collect PRBS error and compute BER. * * Hardware polling interval is stored in secs, the interval determines how fast * new data is available to be examined with displaying counters and ber. * If command <counters> or <ber> are called before an interval has transpired, * there will be no new errors or ber computation available. */ typedef struct prbs_stat_cb_s { /*! Hardware polling interval time. */ int secs; /*! Port map. */ bcmdrd_pbmp_t pbmp; /*! stat port infomation. */ prbs_stat_pinfo_t pinfo[BCMDRD_CONFIG_MAX_PORTS]; /*! Thread id. */ shr_thread_t thread_hndl; /*! Mutex handle. */ sal_mutex_t lock; } prbs_stat_cb_t; static prbs_stat_cb_t *prbs_stat_cb[BCMDRD_CONFIG_MAX_UNITS]; /******************************************************************************* * Private functions */ static void prbs_stat_counter_init(int unit) { int lane; bcmpc_lport_t lport = BCMPC_INVALID_LPORT; bcmpc_pport_t pport = BCMPC_INVALID_PPORT; prbs_stat_cb_t *pscb; prbs_stat_pinfo_t *pspi; pscb = prbs_stat_cb[unit]; BCMDRD_PBMP_ITER(pscb->pbmp, lport) { pport = bcmpc_lport_to_pport(unit, lport); if (pport == BCMPC_INVALID_PPORT) { continue; } pspi = &pscb->pinfo[lport]; sal_memset(&pspi->counters, 0, sizeof(pspi->counters)); sal_memset(&pspi->ber, 0, sizeof(pspi->ber)); /* Clear hardware counters. */ for (lane = 0; lane < pspi->lanes; lane++) { pspi->intervals[lane] = 0; } } } static int prbs_stat_ber_compute(int unit, shr_port_t lport, int lanes, uint32_t delta, sal_time_t secs, double *ber) { double rate; double nbits; prbs_stat_pinfo_t *pspi; if (secs < 1) { return SHR_E_FAIL; } /* Make sure BER is computed at max if no errors. */ if (delta == 0) { delta = 1; } pspi = &prbs_stat_cb[unit]->pinfo[lport]; bcma_bcmpc_diag_speed_rate_get(pspi->speed, pspi->lanes, pspi->fec_type, &rate); /* Convert rate from Gbps to bps. */ rate = rate * 1024 * 1024 * 1024; nbits = rate * lanes; *ber = delta / (nbits * secs); return SHR_E_NONE; } static void prbs_stat_ber_update(int unit, shr_port_t lport, int lane, uint32_t delta) { double ber; prbs_stat_cb_t *pscb; prbs_stat_pinfo_t *pspi; pscb = prbs_stat_cb[unit]; pspi = &pscb->pinfo[lport]; if (prbs_stat_ber_compute(unit, lport, 1, delta, pscb->secs, &ber)) { LOG_INFO(BSL_LOG_MODULE, (BSL_META_U(unit, "%d[%d]: could not compute BER\n"), lport, lane)); return; } pspi->ber[lane] = ber; LOG_INFO(BSL_LOG_MODULE, (BSL_META_U(unit, "Updated BER for port %d: %8.2e (delta = %"PRIu32"\n"), lport, ber, delta)); } static int prbs_stat_pinfo_update(int unit, shr_port_t lport) { int rv = SHR_E_NONE; prbs_stat_cb_t *pscb; prbs_stat_pinfo_t *pspi; bcmpc_cmd_port_cfg_t port_cfg; bcmpc_pport_t pport = BCMPC_INVALID_PPORT; pscb = prbs_stat_cb[unit]; pspi = &pscb->pinfo[lport]; pport = bcmpc_lport_to_pport(unit, lport); rv = bcmpc_phy_port_port_cfg_get(unit, pport, &port_cfg); if (SHR_FAILURE(rv)) { return rv; } if (pspi->speed == port_cfg.speed && pspi->lanes == port_cfg.lanes && pspi->fec_type == port_cfg.fec_type) { return rv; } LOG_INFO(BSL_LOG_MODULE, (BSL_META_U(unit, "Updating port %d configuration\n"), lport)); STAT_LOCK(pscb->lock); pspi->speed = port_cfg.speed; pspi->lanes = port_cfg.lanes; pspi->fec_type = port_cfg.fec_type; sal_memset(&pspi->counters, 0, sizeof(pspi->counters)); sal_memset(&pspi->ber, 0, sizeof(pspi->ber)); STAT_UNLOCK(pscb->lock); return rv; } static int prbs_stat_collect(int unit, shr_port_t lport) { int rv = SHR_E_NONE, lane; bcmpc_phy_prbs_status_t status; prbs_stat_cb_t *pscb; prbs_stat_pinfo_t *pspi; prbs_stat_counter_t *psco; bcmpc_pport_t pport = BCMPC_INVALID_PPORT; rv = prbs_stat_pinfo_update(unit, lport); if (SHR_FAILURE(rv)) { return rv; } pscb = prbs_stat_cb[unit]; pspi = &pscb->pinfo[lport]; psco = pspi->counters; pport = bcmpc_lport_to_pport(unit, lport); STAT_LOCK(pscb->lock); for (lane = 0; lane < pspi->lanes; lane++) { rv = bcmpc_phy_prbs_status_get(unit, pport, lane, 0, &status); if (SHR_FAILURE(rv)) { STAT_UNLOCK(pscb->lock); return rv; } if (!status.prbs_lock) { pspi->prbs_lock[lane] = 0; pspi->ber[lane] = 0; LOG_INFO(BSL_LOG_MODULE, (BSL_META_U(unit, "%d : Collecting status.prbs_lock " "%"PRIu32"\n"), lport, status.prbs_lock)); } else if (status.prbs_lock_loss) { pspi->prbs_lock[lane] = 1; psco[lane].acc.losslock = 1; pspi->ber[lane] = -2; LOG_INFO(BSL_LOG_MODULE, (BSL_META_U(unit, "%d : Collecting status.prbs_lock_loss " "%"PRIu32"\n"), lport, status.prbs_lock_loss)); } else { pspi->prbs_lock[lane] = 1; pspi->intervals[lane]++; psco[lane].acc.errors += status.error_count; LOG_INFO(BSL_LOG_MODULE, (BSL_META_U(unit, "%d : Collecting status.prbs_error_count " "%"PRIu32"\n"), lport, status.error_count)); if (pspi->ber[lane] != -2 ){ prbs_stat_ber_update(unit, lport, lane, status.error_count); } } } STAT_UNLOCK(pscb->lock); return rv; } static bool prbs_stat_running(int unit) { prbs_stat_cb_t *pscb = prbs_stat_cb[unit]; if (pscb && pscb->thread_hndl) { return true; } return false; } static void prbs_stat_thread(shr_thread_t th, void *arg) { int unit = (int)(uintptr_t)arg; shr_port_t lport; prbs_stat_cb_t *pscb; prbs_stat_pinfo_t *pspi; pscb = prbs_stat_cb[unit]; while (1) { BCMDRD_PBMP_ITER(pscb->pbmp, lport) { LOG_INFO(BSL_LOG_MODULE, (BSL_META_U(unit, "Collecting PRBS stats for port %d.\n"), lport)); if (SHR_FAILURE(prbs_stat_collect(unit, lport))) { LOG_INFO(BSL_LOG_MODULE, (BSL_META_U(unit, "Failed collecting PRBS stats for " "port %d.\n "), lport)); } } shr_thread_sleep(th, pscb->secs * SECOND_USEC); if (shr_thread_stopping(th)) { break; } } STAT_LOCK(pscb->lock); BCMDRD_PBMP_ITER(pscb->pbmp, lport) { pspi = &pscb->pinfo[lport]; sal_memset(&pspi->counters, 0, sizeof(pspi->counters)); } STAT_UNLOCK(pscb->lock); } static void prbs_stat_counter_show(char *name, int lport, int lane, uint64_t acc_counter, uint64_t cur_counter, sal_time_t secs, int show_rate) { char chdr[32]; uint64_t delta = 0; sal_sprintf(chdr, "%s.%d[%d]", name, lport, lane); delta = acc_counter; delta -= cur_counter; if (delta) { /* Show counters since beginning.*/ cli_out("%-s : %20"PRIu64"", chdr, acc_counter); /* Show counters since last show.*/ cli_out("%20"PRIu64"", delta); if (show_rate) { /* Show counters per second.*/ cli_out("%12"PRIu64"/s", delta/secs); } cli_out("\n"); } } static int prbs_stat_port_counter(int unit, shr_port_t lport) { int rv = SHR_E_NONE; int lane, unlocked = 0; prbs_stat_cb_t *pscb; prbs_stat_pinfo_t *pspi; prbs_stat_counter_t *psco; pscb = prbs_stat_cb[unit]; pspi = &pscb->pinfo[lport]; psco = pspi->counters; for (lane = 0; lane < pspi->lanes; lane++) { if (!pspi->prbs_lock[lane]) { unlocked++; } } if (unlocked == pspi->lanes) { cli_out("%d: no PRBS lock\n", lport); } for (lane = 0; lane < pspi->lanes; lane++) { prbs_stat_counter_show("ERRORS", lport, lane, psco[lane].acc.errors, psco[lane].cur.errors, pscb->secs * pspi->intervals[lane], 1); pspi->intervals[lane] = 0; psco[lane].cur.errors = psco[lane].acc.errors; } for (lane = 0; lane < pspi->lanes; lane++) { prbs_stat_counter_show("LOSSLOCK", lport, lane, psco[lane].acc.losslock, psco[lane].cur.losslock, 0, 0); psco[lane].cur.losslock = psco[lane].acc.losslock; } return rv; } /******************************************************************************* * Public functions */ int bcma_bcmpc_diag_prbsstat_init(int unit) { prbs_stat_cb_t *pscb; pscb = prbs_stat_cb[unit]; if (pscb) { return SHR_E_NONE; } pscb = sal_alloc(sizeof(prbs_stat_cb_t), "bcmaBcmpcDiagPRBSStat"); if (pscb == NULL) { return SHR_E_MEMORY; } sal_memset(pscb, 0, sizeof(*pscb)); if ((pscb->lock = sal_mutex_create("PRBSStat lock")) == NULL) { sal_free(pscb); return SHR_E_FAIL; } prbs_stat_cb[unit] = pscb; return SHR_E_NONE; } int bcma_bcmpc_diag_prbsstat_cleanup(int unit) { int u; int rv; prbs_stat_cb_t *pscb; for (u = 0; u < BCMDRD_CONFIG_MAX_UNITS; u++) { if (unit >= 0 && unit != u) { continue; } pscb = prbs_stat_cb[u]; if (pscb) { if (pscb->thread_hndl) { rv = shr_thread_stop(pscb->thread_hndl, 500 * MSEC_USEC); if (SHR_FAILURE(rv)) { cli_out("Failed to stop PRBSStat thread (%s)\n", shr_errmsg(rv)); } } sal_mutex_destroy(pscb->lock); sal_free(pscb); prbs_stat_cb[u] = NULL; } } return SHR_E_NONE; } int bcma_bcmpc_diag_prbsstat_status(int unit) { if (prbs_stat_running(unit)) { prbs_stat_cb_t *pscb = prbs_stat_cb[unit]; shr_pb_t *pb = shr_pb_create(); shr_pb_printf(pb, "PRBSStat: Polling interval: %d sec\n", pscb->secs); shr_pb_format_uint32(pb, "PRBSStat: Port bitmap: ", pscb->pbmp.w, COUNTOF(pscb->pbmp.w), 0); cli_out("%s\n", shr_pb_str(pb)); shr_pb_destroy(pb); } else { cli_out(("PRBSStat not started\n")); } return SHR_E_NONE; } int bcma_bcmpc_diag_prbsstat_start(int unit, bcmdrd_pbmp_t *pbmp, uint32_t time) { prbs_stat_cb_t *pscb; bool prbsstat_running = prbs_stat_running(unit); if (time == 0 || time > 180) { cli_out("Internval time must be between 1 and 180 seconds\n"); return SHR_E_PARAM; } pscb = prbs_stat_cb[unit]; if (pscb == NULL) { return SHR_E_INIT; } if (prbsstat_running) { STAT_LOCK(pscb->lock); } pscb->secs = time; BCMDRD_PBMP_ASSIGN(pscb->pbmp, *pbmp); prbs_stat_counter_init(unit); if (prbsstat_running) { /* Must return without starting new thread. */ STAT_UNLOCK(pscb->lock); return SHR_E_NONE; } pscb->thread_hndl = shr_thread_start("bcmaBcmpcPrbsStat", -1, prbs_stat_thread, (void *)(uintptr_t)unit); if (pscb->thread_hndl == NULL) { return SHR_E_FAIL; } cli_out("PRBSStat thread started ...\n"); return SHR_E_NONE; } int bcma_bcmpc_diag_prbsstat_stop(int unit) { int rv; prbs_stat_cb_t *pscb; pscb = prbs_stat_cb[unit]; if (prbs_stat_running(unit)) { /* Signal thread to stop running. */ pscb->secs = 0; rv = shr_thread_stop(pscb->thread_hndl, 500 * MSEC_USEC); if (SHR_FAILURE(rv)) { cli_out("Failed to stop PRBSStat thread (%s)\n", shr_errmsg(rv)); return SHR_E_FAIL; } pscb->thread_hndl = NULL; cli_out("Stopping PRBSStat thread\n"); } else { cli_out("PRBSStat already stopped\n"); } return SHR_E_NONE; } int bcma_bcmpc_diag_prbsstat_counter(int unit, bcmdrd_pbmp_t *pbmp) { int rv = SHR_E_NONE; prbs_stat_cb_t *pscb; bcmpc_lport_t lport = BCMPC_INVALID_LPORT; bcmpc_pport_t pport = BCMPC_INVALID_PPORT; pscb = prbs_stat_cb[unit]; if (!prbs_stat_running(unit)) { cli_out("PRBSStat: not running\n"); return SHR_E_FAIL; } STAT_LOCK(pscb->lock); cli_out("%12s %20s %20s %12s", "port", "accumulated count", "last count", "count per sec\n"); BCMDRD_PBMP_ITER(pscb->pbmp, lport) { pport = bcmpc_lport_to_pport(unit, lport); if (pport == BCMPC_INVALID_PPORT) { continue; } rv = prbs_stat_port_counter(unit, lport); if (SHR_FAILURE(rv)) { break; } } STAT_UNLOCK(pscb->lock); return rv; } int bcma_bcmpc_diag_prbsstat_ber(int unit, bcmdrd_pbmp_t *pbmp) { int lane; prbs_stat_cb_t *pscb; prbs_stat_pinfo_t *pspi; bcmpc_lport_t lport = BCMPC_INVALID_LPORT; bcmpc_pport_t pport = BCMPC_INVALID_PPORT; pscb = prbs_stat_cb[unit]; if (!prbs_stat_running(unit)) { cli_out("PRBSStat: not running\n"); return SHR_E_FAIL; } cli_out("%-6s %s\n", "port", "BER"); cli_out("====\n"); STAT_LOCK(pscb->lock); BCMDRD_PBMP_ITER(*pbmp, lport) { pport = bcmpc_lport_to_pport(unit, lport); if (pport == BCMPC_INVALID_PPORT) { continue; } pspi = &pscb->pinfo[lport]; for (lane = 0; lane < pspi->lanes; lane++) { if (pspi->ber[lane] == -2) { cli_out("%d[%d] : LossOfLock\n", lport, lane); /* Clear it that has been displayed. */ pspi->ber[lane] = 0; } else if (pspi->ber[lane]) { cli_out("%d[%d] : %4.2e\n", lport, lane, pspi->ber[lane]); } else { cli_out("%d[%d] : Nolock\n", lport, lane); } } cli_out("====\n"); } STAT_UNLOCK(pscb->lock); return SHR_E_NONE; } int bcma_bcmpc_diag_prbsstat_clear(int unit, bcmdrd_pbmp_t *pbmp) { prbs_stat_cb_t *pscb; prbs_stat_pinfo_t *pspi; bcmpc_lport_t lport = BCMPC_INVALID_LPORT; bcmpc_pport_t pport = BCMPC_INVALID_PPORT; pscb = prbs_stat_cb[unit]; if (pscb == NULL) { return SHR_E_INIT; } STAT_LOCK(pscb->lock); BCMDRD_PBMP_ITER(pscb->pbmp, lport) { pport = bcmpc_lport_to_pport(unit, lport); if (pport == BCMPC_INVALID_PPORT) { continue; } pspi = &pscb->pinfo[lport]; sal_memset(&pspi->counters, 0, sizeof(pspi->counters)); } STAT_UNLOCK(pscb->lock); return SHR_E_NONE; }
/* BSD 3-Clause License Copyright (c) 2021, NewTec GmbH All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder 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 HOLDER 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. */ /** * @file Zumo32U4Specification.h * @author <NAME> * @brief Zumo32U4Specification header * @date 08/23/2021 * * @{ */ #ifndef __ZUMO32U4Specification_H__ #define __ZUMO32U4Specification_H__ #include <Arduino.h> /** Simple struct for specifying Zumo commands */ template <int size> struct ZumoCommand { /** The binary buffer for the command data */ uint8_t commandData[size]; /** Size of command data buffer in bytes */ uint8_t commandSize; }; /** Simple struct for specifying Zumo data */ template <int size> struct ZumoData { /** The binary buffer for the response Zumo data */ uint8_t data[size]; /** Size of the response data in bytes */ uint8_t dataSize; }; /** Namespace for specifying all used Zumo32U4 commands, return codes and expected return values */ namespace Zumo32U4Specification { /** Command for reading the software ID */ static const struct ZumoCommand<1> READ_SW_ID = {{0x53}, 1}; /** Command for reading the software version */ static const struct ZumoCommand<1> READ_SW_VERSION = {{0x56}, 1}; /** Command for reading the hardware version */ static const struct ZumoCommand<1> READ_HW_VERSION = {{0x76}, 1}; /** Command for getting the programmer type */ static const struct ZumoCommand<1> READ_PROGRAMMER_TYPE = {{0x70}, 1}; /** Command for getting the supported bootlaoder device codes */ static const struct ZumoCommand<1> READ_SUPPORTED_DEVICE_CODE = {{0x74}, 1}; /** Command for reading the signature */ static const struct ZumoCommand<1> READ_SIGNATURE = {{0x73}, 1}; /** Command for reading the low byte AVR fuse */ static const struct ZumoCommand<1> READ_LSB_FUSE = {{0x46}, 1}; /** Command for reading the high byte AVR fuse */ static const struct ZumoCommand<1> READ_MSB_FUSE = {{0x4E}, 1}; /** Command for reading the extended byte AVR fuse */ static const struct ZumoCommand<1> READ_EXTENDED_FUSE = {{0x51}, 1}; /** Command for checking if the bootloader supports block/page flashing */ static const struct ZumoCommand<1> CHECK_BLOCK_FLASH_SUPPORT = {{0x62}, 1}; /** Command for setting the current R/W flash memory/page address */ static const struct ZumoCommand<1> SET_MEMORY_ADDR = {{0x41}, 1}; /** Command for checking if the bootloader supports automatically incrementing byte addresses when flashing a page */ static const struct ZumoCommand<1> CHECK_AUTO_MEM_ADDR_INC_SUPPORT = {{0x61}, 1}; /** Command for setting the device type for flashing */ static const struct ZumoCommand<1> SET_DEVICE_TYPE = {{0x54}, 1}; /** Command for switching the bootloader into the programmer mode */ static const struct ZumoCommand<1> ENTER_PROGRAMMING_MODE = {{0x50}, 1}; /** Command for leaving the bootloader from the programmer mode */ static const struct ZumoCommand<1> EXIT_PROGRAMMING_MODE = {{0x4C}, 1}; /** Command for exiting the bootloader */ static const struct ZumoCommand<1> EXIT_BOOTLOADER_MODE = {{0x45}, 1}; /** Command for writing a memory page with 128 bytes into the flash/program memory */ static const struct ZumoCommand<4> WRITE_MEMORY_PAGE = {{0x42, 0x00, 0x80, 0x46}, 4}; /** Command for reading a memory page with 128 bytes from the flash/program memory */ static const struct ZumoCommand<4> READ_MEMORY_PAGE = {{0x67, 0x00, 0x80, 0x46}, 4}; /** Carriage return for successful return code */ static const struct ZumoData<1> RET_OK = {{0x0D}, 1}; /** The expected bootloader ID string */ static const struct ZumoData<7> EXPECTED_SOFTWARE_ID = {{'C', 'A', 'T', 'E', 'R', 'I', 'N'}, 7}; /** The expected bootloader version */ static const struct ZumoData<2> EXPECTED_SW_VERSION = {{0x31, 0x30}, 2}; /** The expected hardware version */ static const struct ZumoData<1> EXPECTED_HW_VERSION = {{0x3F}, 1}; /** The expected programmer type */ static const struct ZumoData<1> EXPECTED_PROGRAMMER_TYPE = {{0x53}, 1}; /** The expected supported device code */ static const struct ZumoData<1> EXPECTED_DEVICE_CODE = {{0x44}, 1}; /** The expected result when checking if bootloader supports auto incrementing page byte addresses */ static const struct ZumoData<1> EXPECTED_SUPPORTS_AUTO_MEM_ADDR_INC = {{0x59}, 1}; /** The expected block size result in bytes when checking if bootloader supports page/block flashing */ static const struct ZumoData<1> EXPECTED_BLOCK_BUFFER_SIZE = {{0x59}, 1}; /** The expected AVR low byte fuse value */ static const struct ZumoData<1> EXPECTED_LSB_FUSE_VALUE = {{0xFF}, 1}; /** The expected AVR high byte fuse value */ static const struct ZumoData<1> EXPECTED_MSB_FUSE_VALUE = {{0xD0}, 1}; /** The expected AVR extended byte fuse value */ static const struct ZumoData<1> EXPECTED_EXTENDED_FUSE_VALUE = {{0xC8}, 1}; /** The expected signature value */ static const struct ZumoData<3> EXPECTED_SIGNATURE = {{0x87, 0x95, 0x1E}, 3}; }; #endif /** __ZUMO32U4Specification_H__ */
<gh_stars>0 /***************************************************************************** Copyright(c) 2012 FCI Inc. All Rights Reserved File name : fc8151_tun.c (WLCSP) Description : fc8150 tuner driver History : ---------------------------------------------------------------------- 2012/01/20 initial 0.1 version 2012/01/25 initial 0.3 version 2012/01/27 initial 0.5 version 2012/01/31 initial 1.0 version 2012/01/31 initial 1.1 version 2012/02/06 initial 1.2 version 2012/02/09 initial 1.3 Version 2012/02/15 initial 1.4 Version 2012/02/15 initial 2.0 Version 2012/02/24 initial 2.01 Version 2012/03/30 initial 3.0 Version *******************************************************************************/ #include "fci_types.h" #include "fci_oal.h" #include "fci_tun.h" #include "fc8150_regs.h" #include "fci_hal.h" #define FC8150_FREQ_XTAL BBM_XTAL_FREQ /* 26MHZ */ static int high_crnt_mode = 1; static int fc8151_write(HANDLE hDevice, u8 addr, u8 data) { int res; u8 tmp; tmp = data; res = tuner_i2c_write(hDevice, addr, 1, &tmp, 1); return res; } static int fc8151_read(HANDLE hDevice, u8 addr, u8 *data) { int res; res = tuner_i2c_read(hDevice, addr, 1, data, 1); return res; } static int fc8151_bb_read(HANDLE hDevice, u16 addr, u8 *data) { int res; res = bbm_read(hDevice, addr, data); return res; } static int fc8151_bb_write(HANDLE hDevice, u16 addr, u8 data) { return BBM_OK; } static int KbdFunc(HANDLE hDevice) { int i = 0; u8 CSF = 0x00; int res = BBM_OK; int crnt_mode[5] = {0, 0, 0, 0, 0}; int pre_crnt_mode = 0; high_crnt_mode = 2; fc8151_write(hDevice, 0x13, 0xF4); fc8151_write(hDevice, 0x1F, 0x06); fc8151_write(hDevice, 0x33, 0x08); fc8151_write(hDevice, 0x34, 0x68); fc8151_write(hDevice, 0x35, 0x0A); while (1) { while (1) { for (i = 0; i < 5; i++) { msWait(100); res = fc8151_read(hDevice, 0xA6, &CSF); if (CSF < 4) crnt_mode[i] = 2; if (CSF == 4) crnt_mode[i] = 1; if (4 < CSF) crnt_mode[i] = 0; } pre_crnt_mode = high_crnt_mode; if ((crnt_mode[0] + crnt_mode[1] + crnt_mode[2] + crnt_mode[3] + crnt_mode[4]) == 10) high_crnt_mode = 2; else if ((crnt_mode[0] + crnt_mode[1] + crnt_mode[2] + crnt_mode[3] + crnt_mode[4]) == 5) high_crnt_mode = 1; else if ((crnt_mode[0] + crnt_mode[1] + crnt_mode[2] + crnt_mode[3] + crnt_mode[4]) == 0) high_crnt_mode = 0; else high_crnt_mode = pre_crnt_mode; if (!(high_crnt_mode == pre_crnt_mode)) break; } if (high_crnt_mode == 2) { fc8151_write(hDevice, 0x13, 0xF4); fc8151_write(hDevice, 0x1F, 0x06); fc8151_write(hDevice, 0x33, 0x08); fc8151_write(hDevice, 0x34, 0x68); fc8151_write(hDevice, 0x35, 0x0A); } else if (high_crnt_mode == 1) { fc8151_write(hDevice, 0x13, 0x44); fc8151_write(hDevice, 0x1F, 0x06); fc8151_write(hDevice, 0x33, 0x08); fc8151_write(hDevice, 0x34, 0x68); fc8151_write(hDevice, 0x35, 0x0A); } else if (high_crnt_mode == 0) { fc8151_write(hDevice, 0x13, 0x44); fc8151_write(hDevice, 0x1F, 0x02); fc8151_write(hDevice, 0x33, 0x04); fc8151_write(hDevice, 0x34, 0x48); fc8151_write(hDevice, 0x35, 0x0C); } } return res; } static int fc8151_set_filter(HANDLE hDevice) { int i; u8 cal_mon = 0; #if (FC8151_FREQ_XTAL == 16000) fc8151_write(hDevice, 0x3B, 0x01); fc8151_write(hDevice, 0x3D, 0x20); fc8151_write(hDevice, 0x3B, 0x00); #elif (FC8150_FREQ_XTAL == 16384) fc8151_write(hDevice, 0x3B, 0x01); fc8151_write(hDevice, 0x3D, 0x21); fc8151_write(hDevice, 0x3B, 0x00); #elif (FC8150_FREQ_XTAL == 18000) fc8151_write(hDevice, 0x3B, 0x01); fc8151_write(hDevice, 0x3D, 0x24); fc8151_write(hDevice, 0x3B, 0x00); #elif (FC8150_FREQ_XTAL == 19200) fc8151_write(hDevice, 0x3B, 0x01); fc8151_write(hDevice, 0x3D, 0x26); fc8151_write(hDevice, 0x3B, 0x00); #elif (FC8150_FREQ_XTAL == 24000) fc8151_write(hDevice, 0x3B, 0x01); fc8151_write(hDevice, 0x3D, 0x30); fc8151_write(hDevice, 0x3B, 0x00); #elif (FC8150_FREQ_XTAL == 24576) fc8151_write(hDevice, 0x3B, 0x01); fc8151_write(hDevice, 0x3D, 0x31); fc8151_write(hDevice, 0x3B, 0x00); #elif (FC8150_FREQ_XTAL == 26000) fc8151_write(hDevice, 0x3B, 0x01); fc8151_write(hDevice, 0x3D, 0x34); fc8151_write(hDevice, 0x3B, 0x00); #elif (FC8150_FREQ_XTAL == 27000) fc8151_write(hDevice, 0x3B, 0x01); fc8151_write(hDevice, 0x3D, 0x36); fc8151_write(hDevice, 0x3B, 0x00); #elif (FC8150_FREQ_XTAL == 27120) fc8151_write(hDevice, 0x3B, 0x01); fc8151_write(hDevice, 0x3D, 0x36); fc8151_write(hDevice, 0x3B, 0x00); #elif (FC8150_FREQ_XTAL == 32000) fc8151_write(hDevice, 0x3B, 0x01); fc8151_write(hDevice, 0x3D, 0x40); fc8151_write(hDevice, 0x3B, 0x00); #elif (FC8150_FREQ_XTAL == 37400) fc8151_write(hDevice, 0x3B, 0x01); fc8151_write(hDevice, 0x3D, 0x4B); fc8151_write(hDevice, 0x3B, 0x00); #elif (FC8150_FREQ_XTAL == 38400) fc8151_write(hDevice, 0x3B, 0x01); fc8151_write(hDevice, 0x3D, 0x4D); fc8151_write(hDevice, 0x3B, 0x00); #else return BBM_NOK; #endif for (i = 0; i < 10; i++) { msWait(5); fc8151_read(hDevice, 0x33, &cal_mon); if ((cal_mon & 0xC0) == 0xC0) break; fc8151_write(hDevice, 0x32, 0x01); fc8151_write(hDevice, 0x32, 0x09); } fc8151_write(hDevice, 0x32, 0x01); return BBM_OK; } int fc8151_tuner_init(HANDLE hDevice, u32 band) { u8 RFPD_REF, MIXPD_REF; int res = BBM_OK; PRINTF(hDevice, "fc8151_init\n"); fc8151_write(hDevice, 0x00, 0x00); fc8151_write(hDevice, 0x02, 0x81); fc8151_write(hDevice, 0x13, 0xF4); fc8151_write(hDevice, 0x30, 0x0A); fc8151_write(hDevice, 0x3B, 0x01); fc8151_set_filter(hDevice); fc8151_write(hDevice, 0x3B, 0x00); fc8151_write(hDevice, 0x34, 0x68); fc8151_write(hDevice, 0x36, 0xFF); fc8151_write(hDevice, 0x37, 0xFF); fc8151_write(hDevice, 0x39, 0x11); fc8151_write(hDevice, 0x3A, 0x00); fc8151_write(hDevice, 0x52, 0x20); fc8151_write(hDevice, 0x53, 0x5F); fc8151_write(hDevice, 0x54, 0x00); fc8151_write(hDevice, 0x5E, 0x00); fc8151_write(hDevice, 0x63, 0x30); fc8151_write(hDevice, 0x56, 0x0F); fc8151_write(hDevice, 0x57, 0x1F); fc8151_write(hDevice, 0x58, 0x09); fc8151_write(hDevice, 0x59, 0x5E); fc8151_write(hDevice, 0x29, 0x00); fc8151_write(hDevice, 0x94, 0x00); fc8151_write(hDevice, 0x95, 0x01); fc8151_write(hDevice, 0x96, 0x11); fc8151_write(hDevice, 0x97, 0x21); fc8151_write(hDevice, 0x98, 0x31); fc8151_write(hDevice, 0x99, 0x32); fc8151_write(hDevice, 0x9A, 0x42); fc8151_write(hDevice, 0x9B, 0x52); fc8151_write(hDevice, 0x9C, 0x53); fc8151_write(hDevice, 0x9D, 0x63); fc8151_write(hDevice, 0x9E, 0x63); fc8151_write(hDevice, 0x9F, 0x63); fc8151_write(hDevice, 0x79, 0x2A); fc8151_write(hDevice, 0x7A, 0x24); fc8151_write(hDevice, 0x7B, 0xFF); fc8151_write(hDevice, 0x7C, 0x16); fc8151_write(hDevice, 0x7D, 0x12); fc8151_write(hDevice, 0x84, 0x00); fc8151_write(hDevice, 0x85, 0x08); fc8151_write(hDevice, 0x86, 0x00); fc8151_write(hDevice, 0x87, 0x08); fc8151_write(hDevice, 0x88, 0x00); fc8151_write(hDevice, 0x89, 0x08); fc8151_write(hDevice, 0x8A, 0x00); fc8151_write(hDevice, 0x8B, 0x08); fc8151_write(hDevice, 0x8C, 0x00); fc8151_write(hDevice, 0x8D, 0x1D); fc8151_write(hDevice, 0x8E, 0x13); fc8151_write(hDevice, 0x8F, 0x1D); fc8151_write(hDevice, 0x90, 0x13); fc8151_write(hDevice, 0x91, 0x1D); fc8151_write(hDevice, 0x92, 0x13); fc8151_write(hDevice, 0x93, 0x1D); fc8151_write(hDevice, 0x80, 0x1F); fc8151_write(hDevice, 0x81, 0x0A); fc8151_write(hDevice, 0x82, 0x40); fc8151_write(hDevice, 0x83, 0x0A); fc8151_write(hDevice, 0xA0, 0xC0); fc8151_write(hDevice, 0x7E, 0x7F); fc8151_write(hDevice, 0x7F, 0x7F); fc8151_write(hDevice, 0xD0, 0x0A); fc8151_write(hDevice, 0xD2, 0x28); fc8151_write(hDevice, 0xD4, 0x28); /* _beginthread(KbdFunc,0,&x); */ fc8151_write(hDevice, 0xA0, 0x17); fc8151_write(hDevice, 0xD0, 0x00); fc8151_write(hDevice, 0xA1, 0x1D); msWait(100); res = fc8151_read(hDevice, 0xD6, &RFPD_REF); res = fc8151_read(hDevice, 0xD8, &MIXPD_REF); fc8151_write(hDevice, 0xA0, 0xD7); fc8151_write(hDevice, 0xD0, 0x0A); fc8151_write(hDevice, 0x7E, RFPD_REF); fc8151_write(hDevice, 0x7F, MIXPD_REF); fc8151_write(hDevice, 0xA0, 0xC0); fc8151_write(hDevice, 0xA1, 0x00); return res; } int fc8151_set_freq(HANDLE hDevice, band_type band, u32 rf_kHz) { int res = BBM_OK; int n_captune = 0; unsigned long f_diff, f_diff_shifted, n_val, k_val; unsigned long f_vco, f_comp; unsigned char r_val, data_0x56; unsigned char pre_shift_bits = 4; f_vco = (rf_kHz) << 2; if (f_vco < FC8150_FREQ_XTAL*40) r_val = 2; else r_val = 1; f_comp = FC8150_FREQ_XTAL / r_val; n_val = f_vco / f_comp; f_diff = f_vco - f_comp * n_val; f_diff_shifted = f_diff << (20 - pre_shift_bits); k_val = (f_diff_shifted + (f_comp >> (pre_shift_bits+1))) / (f_comp >> pre_shift_bits); k_val = (k_val | 1); if (470000 < rf_kHz && rf_kHz <= 505000) n_captune = 4; else if (505000 < rf_kHz && rf_kHz <= 545000) n_captune = 3; else if (545000 < rf_kHz && rf_kHz <= 610000) n_captune = 2; else if (610000 < rf_kHz && rf_kHz <= 695000) n_captune = 1; else if (695000 < rf_kHz) n_captune = 0; fc8151_write(hDevice, 0x1E, (unsigned char)n_captune); data_0x56 = ((r_val == 1) ? 0 : 0x10) + (unsigned char)(k_val >> 16); fc8151_write(hDevice, 0x56, data_0x56); fc8151_write(hDevice, 0x57, (unsigned char)((k_val >> 8) & 0xFF)); fc8151_write(hDevice, 0x58, (unsigned char)(((k_val) & 0xFF))); fc8151_write(hDevice, 0x59, (unsigned char) n_val); if (rf_kHz <= 600000) fc8151_write(hDevice, 0x55, 0x07); else fc8151_write(hDevice, 0x55, 0x05); if ((490000 < rf_kHz) && (560000 >= rf_kHz)) fc8151_write(hDevice, 0x1F, 0x0E); else fc8151_write(hDevice, 0x1F, 0x06); return res; } int fc8151_get_rssi(HANDLE hDevice, int *rssi) { int res = BBM_OK; u8 LNA, RFVGA, CSF, PREAMP_PGA = 0x00; int K = -101.25; float Gain_diff = 0; int PGA = 0; res |= fc8151_read(hDevice, 0xA3, &LNA); res |= fc8151_read(hDevice, 0xA4, &RFVGA); res |= fc8151_read(hDevice, 0xA6, &CSF); res |= fc8151_bb_read(hDevice, 0x106E, &PREAMP_PGA); if (res != BBM_OK) return res; if (127 < PREAMP_PGA) PGA = -1 * ((256 - PREAMP_PGA) + 1); else if (PREAMP_PGA <= 127) PGA = PREAMP_PGA; if (high_crnt_mode == 2) Gain_diff = 0; else if (high_crnt_mode == 1) Gain_diff = 0; else if (high_crnt_mode == 0) Gain_diff = -3.5; *rssi = (LNA & 0x07) * 6 + (RFVGA) + (CSF & 0x0F) * 6 - PGA * 0.25f + K - Gain_diff; return BBM_OK; } int fc8151_tuner_deinit(HANDLE hDevice) { return BBM_OK; }
<reponame>DDManager/Baekjoon-Online-Judge<gh_stars>1-10 /** * BOJ 10989번 C언어 소스 코드 * 작성자 : 동동매니저 (DDManager) * * ※ 실행 결과 * 사용 메모리 : 1,112 KB / 8,192 KB * 소요 시간 : 2,352 ms / 3,000 ms * * Copyright 2020. DDManager all rights reserved. */ #include <stdio.h> int main(void){ int N; int A[10001]={0}; int i,j; scanf("%d",&N); while(N--){ int read; scanf("%d",&read); A[read]++; } for(i=0;i<=10000;i++) for(j=0;j<A[i];j++) printf("%d\n",i); return 0; }
<reponame>AsahiOS/gate /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2009 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #include <sys/types.h> #include <sys/errno.h> #include <sys/kmem.h> #include <sys/vnode.h> #include <sys/pathname.h> #include <sys/door.h> #include <sys/cmn_err.h> #include <sys/sunddi.h> /* for string functions */ #include <sys/vscan.h> #define VS_DOOR_RETRIES 3 /* max time (secs) to wait for door calls to complete during door_close */ #define VS_DOOR_CLOSE_TIMEOUT_DEFAULT 30 uint32_t vs_door_close_timeout = VS_DOOR_CLOSE_TIMEOUT_DEFAULT; static door_handle_t vscan_door_handle = NULL; static kmutex_t vscan_door_mutex; static kcondvar_t vscan_door_cv; static int vscan_door_call_count = 0; /* * vscan_door_init */ int vscan_door_init(void) { mutex_init(&vscan_door_mutex, NULL, MUTEX_DEFAULT, NULL); cv_init(&vscan_door_cv, NULL, CV_DEFAULT, NULL); return (0); } /* * vscan_door_fini */ void vscan_door_fini(void) { mutex_destroy(&vscan_door_mutex); cv_destroy(&vscan_door_cv); } /* * vscan_door_open */ int vscan_door_open(int door_id) { mutex_enter(&vscan_door_mutex); if (vscan_door_handle == NULL) vscan_door_handle = door_ki_lookup(door_id); if (vscan_door_handle == NULL) { cmn_err(CE_WARN, "Internal communication error " "- failed to access vscan service daemon."); mutex_exit(&vscan_door_mutex); return (-1); } mutex_exit(&vscan_door_mutex); return (0); } /* * vscan_door_close */ void vscan_door_close(void) { clock_t timeout, time_left; mutex_enter(&vscan_door_mutex); /* wait for any in-progress requests to complete */ time_left = SEC_TO_TICK(vs_door_close_timeout); while ((vscan_door_call_count > 0) && (time_left > 0)) { timeout = time_left; time_left = cv_reltimedwait(&vscan_door_cv, &vscan_door_mutex, timeout, TR_CLOCK_TICK); } if (time_left == -1) cmn_err(CE_WARN, "Timeout waiting for door calls to complete"); if (vscan_door_handle) { door_ki_rele(vscan_door_handle); vscan_door_handle = NULL; } mutex_exit(&vscan_door_mutex); } /* * vscan_door_scan_file * * Returns: result returned in door response or VS_STATUS_ERROR */ int vscan_door_scan_file(vs_scan_req_t *scan_req) { int err; int i; door_arg_t arg; uint32_t result = 0; if (!vscan_door_handle) return (VS_STATUS_ERROR); mutex_enter(&vscan_door_mutex); vscan_door_call_count++; mutex_exit(&vscan_door_mutex); arg.data_ptr = (char *)scan_req; arg.data_size = sizeof (vs_scan_req_t); arg.desc_ptr = NULL; arg.desc_num = 0; arg.rbuf = (char *)&result; arg.rsize = sizeof (uint32_t); for (i = 0; i < VS_DOOR_RETRIES; ++i) { if ((err = door_ki_upcall_limited(vscan_door_handle, &arg, NULL, SIZE_MAX, 0)) == 0) break; if (err != EAGAIN && err != EINTR) break; } if (err != 0) { cmn_err(CE_WARN, "Internal communication error (%d)" "- failed to send scan request to vscand", err); result = VS_STATUS_ERROR; } mutex_enter(&vscan_door_mutex); vscan_door_call_count--; cv_signal(&vscan_door_cv); mutex_exit(&vscan_door_mutex); return (result); }
/** \ingroup rpmcli * \file build/poptBT.c * Popt tables for build modes. */ #include "system.h" #include <rpmio.h> #include <rpmiotypes.h> #include <rpmlog.h> #include <rpmtypes.h> #include <rpmtag.h> #include <rpmbuild.h> #include "build.h" #include <rpmcli.h> #include "debug.h" /*@unchecked@*/ extern int _pkg_debug; /*@unchecked@*/ extern int _spec_debug; /*@unchecked@*/ struct rpmBuildArguments_s rpmBTArgs; #define POPT_NOLANG -1012 #define POPT_REBUILD 0x4220 #define POPT_RECOMPILE 0x4320 #define POPT_BA 0x6261 #define POPT_BB 0x6262 #define POPT_BC 0x6263 #define POPT_BI 0x6269 #define POPT_BL 0x626c #define POPT_BP 0x6270 #define POPT_BS 0x6273 #define POPT_BT 0x6274 /* support "%track" script/section */ #define POPT_BF 0x6266 #define POPT_TA 0x7461 #define POPT_TB 0x7462 #define POPT_TC 0x7463 #define POPT_TI 0x7469 #define POPT_TL 0x746c #define POPT_TP 0x7470 #define POPT_TS 0x7473 /*@unchecked@*/ int _rpmbuildFlags = 3; /*@-exportlocal@*/ /*@unchecked@*/ int noLang = 0; /*@=exportlocal@*/ /** */ static void buildArgCallback( /*@unused@*/ poptContext con, /*@unused@*/ enum poptCallbackReason reason, const struct poptOption * opt, /*@unused@*/ const char * arg, /*@unused@*/ const void * data) { BTA_t rba = &rpmBTArgs; switch (opt->val) { case POPT_REBUILD: case POPT_RECOMPILE: case POPT_BA: case POPT_BB: case POPT_BC: case POPT_BI: case POPT_BL: case POPT_BP: case POPT_BS: case POPT_BT: /* support "%track" script/section */ case POPT_BF: case POPT_TA: case POPT_TB: case POPT_TC: case POPT_TI: case POPT_TL: case POPT_TP: case POPT_TS: if (rba->buildMode == '\0' && rba->buildChar == '\0') { rba->buildMode = (char)((((unsigned int)opt->val) >> 8) & 0xff); rba->buildChar = (char)(opt->val & 0xff); } break; case POPT_NOLANG: rba->noLang = 1; break; case RPMCLI_POPT_NODIGEST: rba->qva_flags |= VERIFY_DIGEST; break; case RPMCLI_POPT_NOSIGNATURE: rba->qva_flags |= VERIFY_SIGNATURE; break; case RPMCLI_POPT_NOHDRCHK: rba->qva_flags |= VERIFY_HDRCHK; break; case RPMCLI_POPT_NODEPS: rba->noDeps = 1; break; } } /** */ /*@-bitwisesigned -compmempass @*/ /*@unchecked@*/ struct poptOption rpmBuildPoptTable[] = { /*@-type@*/ /* FIX: cast? */ { NULL, '\0', POPT_ARG_CALLBACK | POPT_CBFLAG_INC_DATA | POPT_CBFLAG_CONTINUE, buildArgCallback, 0, NULL, NULL }, /*@=type@*/ { "bp", 0, POPT_ARGFLAG_ONEDASH, NULL, POPT_BP, N_("build through %prep (unpack sources and apply patches) from <specfile>"), N_("<specfile>") }, { "bc", 0, POPT_ARGFLAG_ONEDASH, NULL, POPT_BC, N_("build through %build (%prep, then compile) from <specfile>"), N_("<specfile>") }, { "bi", 0, POPT_ARGFLAG_ONEDASH, NULL, POPT_BI, N_("build through %install (%prep, %build, then install) from <specfile>"), N_("<specfile>") }, { "bl", 0, POPT_ARGFLAG_ONEDASH, NULL, POPT_BL, N_("verify %files section from <specfile>"), N_("<specfile>") }, { "ba", 0, POPT_ARGFLAG_ONEDASH, NULL, POPT_BA, N_("build source and binary packages from <specfile>"), N_("<specfile>") }, { "bb", 0, POPT_ARGFLAG_ONEDASH, NULL, POPT_BB, N_("build binary package only from <specfile>"), N_("<specfile>") }, { "bs", 0, POPT_ARGFLAG_ONEDASH, NULL, POPT_BS, N_("build source package only from <specfile>"), N_("<specfile>") }, /* support "%track" script/section */ { "bt", 0, POPT_ARGFLAG_ONEDASH, 0, POPT_BT, N_("track versions of sources from <specfile>"), N_("<specfile>") }, { "bf", 0, POPT_ARGFLAG_ONEDASH, 0, POPT_BF, N_("fetch missing source and patch files"), N_("<specfile>") }, { "tp", 0, POPT_ARGFLAG_ONEDASH, NULL, POPT_TP, N_("build through %prep (unpack sources and apply patches) from <tarball>"), N_("<tarball>") }, { "tc", 0, POPT_ARGFLAG_ONEDASH, NULL, POPT_TC, N_("build through %build (%prep, then compile) from <tarball>"), N_("<tarball>") }, { "ti", 0, POPT_ARGFLAG_ONEDASH, NULL, POPT_TI, N_("build through %install (%prep, %build, then install) from <tarball>"), N_("<tarball>") }, { "tl", 0, POPT_ARGFLAG_ONEDASH|POPT_ARGFLAG_DOC_HIDDEN, NULL, POPT_TL, N_("verify %files section from <tarball>"), N_("<tarball>") }, { "ta", 0, POPT_ARGFLAG_ONEDASH, NULL, POPT_TA, N_("build source and binary packages from <tarball>"), N_("<tarball>") }, { "tb", 0, POPT_ARGFLAG_ONEDASH, NULL, POPT_TB, N_("build binary package only from <tarball>"), N_("<tarball>") }, { "ts", 0, POPT_ARGFLAG_ONEDASH, NULL, POPT_TS, N_("build source package only from <tarball>"), N_("<tarball>") }, { "rebuild", '\0', 0, NULL, POPT_REBUILD, N_("build binary package from <source package>"), N_("<source package>") }, { "recompile", '\0', 0, NULL, POPT_RECOMPILE, N_("build through %install (%prep, %build, then install) from <source package>"), N_("<source package>") }, { "clean", '\0', POPT_BIT_SET, &rpmBTArgs.buildAmount, RPMBUILD_RMBUILD, N_("remove build tree when done"), NULL}, { "nobuild", '\0', POPT_ARG_VAL, &rpmBTArgs.noBuild, 1, N_("do not execute any stages of the build"), NULL }, { "nodeps", '\0', 0, NULL, RPMCLI_POPT_NODEPS, N_("do not verify build dependencies"), NULL }, { "noautoprov", '\0', POPT_BIT_CLR|POPT_ARGFLAG_DOC_HIDDEN, &_rpmbuildFlags, 1, N_("disable automagic Provides: extraction"), NULL }, { "noautoreq", '\0', POPT_BIT_CLR|POPT_ARGFLAG_DOC_HIDDEN, &_rpmbuildFlags, 2, N_("disable automagic Requires: extraction"), NULL }, { "notinlsb", '\0', POPT_BIT_SET|POPT_ARGFLAG_DOC_HIDDEN, &_rpmbuildFlags, 4, N_("disable tags forbidden by LSB"), NULL }, { "nodigest", '\0', POPT_ARGFLAG_DOC_HIDDEN, NULL, RPMCLI_POPT_NODIGEST, N_("don't verify package digest(s)"), NULL }, { "nohdrchk", '\0', POPT_ARGFLAG_DOC_HIDDEN, NULL, RPMCLI_POPT_NOHDRCHK, N_("don't verify database header(s) when retrieved"), NULL }, { "nosignature", '\0', POPT_ARGFLAG_DOC_HIDDEN, NULL, RPMCLI_POPT_NOSIGNATURE, N_("don't verify package signature(s)"), NULL }, { "pkgdebug", '\0', POPT_ARG_VAL|POPT_ARGFLAG_DOC_HIDDEN, &_pkg_debug, -1, N_("Debug Package objects"), NULL}, { "specdebug", '\0', POPT_ARG_VAL|POPT_ARGFLAG_DOC_HIDDEN, &_spec_debug, -1, N_("Debug Spec objects"), NULL}, { "nolang", '\0', POPT_ARGFLAG_DOC_HIDDEN, &noLang, POPT_NOLANG, N_("do not accept i18n msgstr's from specfile"), NULL}, { "rmsource", '\0', POPT_BIT_SET, &rpmBTArgs.buildAmount, RPMBUILD_RMSOURCE, N_("remove sources when done"), NULL}, { "rmspec", '\0', POPT_BIT_SET, &rpmBTArgs.buildAmount, RPMBUILD_RMSPEC, N_("remove specfile when done"), NULL}, { "short-circuit", '\0', POPT_ARG_VAL, &rpmBTArgs.shortCircuit, 1, N_("skip straight to specified stage (only for c,i)"), NULL }, { "sign", '\0', POPT_ARG_VAL|POPT_ARGFLAG_DOC_HIDDEN, &rpmBTArgs.sign, 1, N_("generate PGP/GPG signature"), NULL }, { "target", '\0', POPT_ARG_STRING, NULL, RPMCLI_POPT_TARGETPLATFORM, N_("override target platform"), N_("CPU-VENDOR-OS") }, POPT_TABLEEND }; /*@=bitwisesigned =compmempass @*/
// // m3_info.h // m3 // // Created by <NAME> on 12/6/19. // Copyright © 2019 <NAME>. All rights reserved. // #ifndef m3_info_h #define m3_info_h #include "m3_compile.h" typedef struct OpInfo { IM3OpInfo info; u8 opcode; } OpInfo; OpInfo find_operation_info (IM3Operation i_operation); void dump_type_stack (IM3Compilation o); void log_opcode (IM3Compilation o, u8 i_opcode); const char * get_indention_string (IM3Compilation o); void emit_stack_dump (IM3Compilation o); void log_emit (IM3Compilation o, IM3Operation i_operation); #endif /* m3_info_h */
<filename>src/ldap/SearchRequestOperation.h<gh_stars>1-10 /* * SearchRequestOperation.h * * Created on: 14.05.2017 * Author: felix */ #ifndef SRC_LDAP_SEARCHREQUESTOPERATION_H_ #define SRC_LDAP_SEARCHREQUESTOPERATION_H_ #include <asn-one-objects/LdapSearchRequestAsnOneObject.h> #include <ldap/GenericOperation.h> namespace Flix { class SearchRequestOperation: public GenericOperation { public: SearchRequestOperation(); virtual ~SearchRequestOperation(); const std::string& getBaseDn(void) const; SearchScope getSearchScope(void) const; DereferenceAliases getDereferenceAliases(void) const; int getSizeLimit(void) const; int getTimeLimit(void) const; bool getOnlyTypesFlag(void) const; void setBaseDn(const std::string& baseDn); void setSearchScope(SearchScope searchScope); void setDereferenceAliases(DereferenceAliases dereferenceAliases); void setSizeLimit(int sizeLimit); void setTimeLimit(int timeLimit); void setOnlyTypesFlag(bool onlyTypesFlag); virtual Operations execute(void) const; virtual GenericAsnOneObject* getAsnOneObject(void) const; virtual std::string dump(void) const; static SearchRequestOperation* fromAsnOneObject(LdapSearchRequestAsnOneObject* asnOneObject); private: std::string baseDn; SearchScope searchScope; DereferenceAliases dereferenceAliases; int sizeLimit; int timeLimit; bool onlyTypesFlag; }; } /* namespace Flix */ #endif /* SRC_LDAP_SEARCHREQUESTOPERATION_H_ */
<filename>modules/common/clib/c/shared/container/IAHashMapIterator.h #ifndef IAHashMapIterator_h #define IAHashMapIterator_h #include "IAHashMap.h" typedef struct{ //@extend IAObject base; const IAHashMap * hashMap; size_t listIndex; IAHashMapList * currentListElement; void * (*returnResult)(IAHashMapList*); } IAHashMapIterator; void IAHashMapIterator_makeIteratorOverValues(IAHashMapIterator *, const IAHashMap * hashMap); void IAHashMapIterator_makeIteratorOverKeys(IAHashMapIterator *, const IAHashMap * hashMap); void * IAHashMapIterator_getNextObject(IAHashMapIterator *); #include "IAHashMapIterator+Generated.h" #define hashMapKeys(...) keys(IAHashMap, __VA_ARGS__) #define hashMapValues(...) values(IAHashMap, __VA_ARGS__) #endif
/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3, or (at your option) * any later version. * * GNU Radio 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 GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef INCLUDED_FILTER_POLYPHASE_FILTERBANK_H #define INCLUDED_FILTER_POLYPHASE_FILTERBANK_H #include <gnuradio/filter/api.h> #include <gnuradio/filter/fir_filter.h> #include <gnuradio/filter/fft_filter.h> #include <gnuradio/fft/fft.h> namespace gr { namespace filter { namespace kernel { /*! * \brief Polyphase filterbank parent class * \ingroup filter_blk * \ingroup pfb_blk * * \details * This block takes in complex inputs and channelizes it to * <EM>M</EM> channels of equal bandwidth. Each of the resulting * channels is decimated to the new rate that is the input * sampling rate <EM>fs</EM> divided by the number of channels, * <EM>M</EM>. * * The PFB channelizer code takes the taps generated above and * builds a set of filters. The set contains <EM>M</EM> * filters and each filter contains ceil(taps.size()/decim) * taps. Each tap from the filter prototype is * sequentially inserted into the next filter. When all of the * input taps are used, the remaining filters in the filterbank * are filled out with 0's to make sure each filter has the same * number of taps. * * Each filter operates using the gr::filter::fir_filter_XXX * class of GNU Radio, which takes the input stream at * <EM>i</EM> and performs the inner product calculation to * <EM>i+(n-1)</EM> where <EM>n</EM> is the number of filter * taps. To efficiently handle this in the GNU Radio structure, * each filter input must come from its own input stream. So the * channelizer must be provided with <EM>M</EM> streams where * the input stream has been deinterleaved. This is most easily * done using the gr::blocks::stream_to_streams block. * * The output is then produced as a vector, where index * <EM>i</EM> in the vector is the next sample from the * <EM>i</EM>th channel. This is most easily handled by sending * the output to a gr::blocks::vector_to_streams block to handle * the conversion and passing <EM>M</EM> streams out. * * The input and output formatting is done using a hier_block2 * called pfb_channelizer_ccf. This can take in a single stream * and outputs <EM>M</EM> streams based on the behavior * described above. * * The filter's taps should be based on the input sampling rate. * * For example, using the GNU Radio's firdes utility to building * filters, we build a low-pass filter with a sampling rate of * <EM>fs</EM>, a 3-dB bandwidth of <EM>BW</EM> and a transition * bandwidth of <EM>TB</EM>. We can also specify the out-of-band * attenuation to use, <EM>ATT</EM>, and the filter window * function (a Blackman-harris window in this case). The first * input is the gain of the filter, which we specify here as * unity. * * <B><EM>self._taps = filter.firdes.low_pass_2(1, fs, BW, TB, * attenuation_dB=ATT, window=filter.firdes.WIN_BLACKMAN_hARRIS)</EM></B> * * More on the theory of polyphase filterbanks can be found in * the following book: * * <B><EM><NAME>, "Multirate Signal Processing for * Communication Systems," Upper Saddle River, NJ: * Prentice Hall, Inc. 2004.</EM></B> * */ class FILTER_API polyphase_filterbank { protected: unsigned int d_nfilts; std::vector<kernel::fir_filter_ccf*> d_fir_filters; std::vector<kernel::fft_filter_ccf*> d_fft_filters; std::vector< std::vector<float> > d_taps; unsigned int d_taps_per_filter; fft::fft_complex *d_fft; public: /*! * Build the polyphase filterbank decimator. * \param nfilts (unsigned integer) Specifies the number of * channels <EM>M</EM> * \param taps (vector/list of floats) The prototype filter to * populate the filterbank. * \param fft_forward (bool) use a forward or inverse FFT (default=false). */ polyphase_filterbank(unsigned int nfilts, const std::vector<float> &taps, bool fft_forward=false); ~polyphase_filterbank(); /*! * Update the filterbank's filter taps from a prototype * filter. * * \param taps (vector/list of floats) The prototype filter to * populate the filterbank. */ virtual void set_taps(const std::vector<float> &taps); /*! * Print all of the filterbank taps to screen. */ void print_taps(); /*! * Return a vector<vector<>> of the filterbank taps */ std::vector<std::vector<float> > taps() const; }; } /* namespace kernel */ } /* namespace filter */ } /* namespace gr */ #endif /* INCLUDED_FILTER_POLYPHASE_FILTERBANK_H */
/* wage.h -*- C++ -*- ** Include file for Wage Worker base class ** ** COPYRIGHT (C) 1994 <NAME> ** ** Written : <NAME> Loyola College ** By ** ** Written : <NAME> Loyola College ** For ** ** Acknowledgements: ** This code is based on code that appears in: ** C++ How to Program by <NAME> and <NAME> ** Prentice Hall, New Jersey, p. 536 ** ** RCS : ** ** $Source$ ** $Revision$ ** $Date$ ** ** $Log$ ** Revision 1.2 2004/10/05 00:37:32 lattner ** Stop using deprecated headers ** ** Revision 1.1 2004/10/04 20:01:13 lattner ** Initial checkin of all of the source ** ** Revision 0.1 1994/12/24 01:45:27 bkuhn ** # initial version ** ** */ #ifndef _WAGE_H #define _WAGE_H #include "employee.h" #define WAGE_WORKER_ID 3 #include <iostream> #include <stdlib.h> using namespace std; /* A wage worker gets paid for every (item, hour, etc) worked/produced */ class WageWorker : public Employee { private: float wage; // wage per thing protected: float Wage(); public: WageWorker(const char *, const char * , float = 0.0); void SetWage(float); virtual void Raise(int); // pure virtual functions virtual float Earnings() = 0; virtual void Print() = 0; virtual void NewWeek() = 0; }; /*****************************************************************************/ WageWorker::WageWorker(const char *first, const char *last, float startWage) : Employee(first, last) // this will call Employee's constructor { SetWage(startWage); } /*****************************************************************************/ void WageWorker::SetWage(float newWage) { wage = (newWage > 0.0) ? newWage : 0.0; } /*****************************************************************************/ float WageWorker::Wage() { return wage; } /*****************************************************************************/ void WageWorker::Raise(int units) { if (units > 0) wage += units * dollarsToRaise; } #endif
<gh_stars>1-10 #ifndef MKL_HELPER_H #define MKL_HELPER_H #include <mkl.h> namespace gnn { inline float MKL_Dot(const MKL_INT n, const float* x, const float* y) { return cblas_sdot(n, x, 1, y, 1); } inline double MKL_Dot(const MKL_INT n, const double* x, const double* y) { return cblas_ddot(n, x, 1, y, 1); } inline CBLAS_INDEX MKL_Amax(const MKL_INT n, const float *x) { return cblas_isamax(n, x, 1); } inline CBLAS_INDEX MKL_Amax(const MKL_INT n, const double *x) { return cblas_idamax(n, x, 1); } inline float MKL_ASum(const MKL_INT n, const float *x) { return cblas_sasum(n, x, 1); } inline double MKL_ASum(const MKL_INT n, const double *x) { return cblas_dasum(n, x, 1); } inline float MKL_Norm2(const MKL_INT n, const float *x) { return cblas_snrm2(n, x, 1); } inline double MKL_Norm2(const MKL_INT n, const double *x) { return cblas_dnrm2(n, x, 1); } inline void MKL_Ger(const CBLAS_LAYOUT Layout, const MKL_INT m, const MKL_INT n, const float alpha, const float *x, const float *y, float *a) { const MKL_INT lda = Layout == CblasRowMajor ? n : m; cblas_sger(Layout, m, n, alpha, x, 1, y, 1, a, lda); } inline void MKL_Ger(const CBLAS_LAYOUT Layout, const MKL_INT m, const MKL_INT n, const double alpha, const double *x, const double *y, double *a) { const MKL_INT lda = Layout == CblasRowMajor ? n : m; cblas_dger(Layout, m, n, alpha, x, 1, y, 1, a, lda); } inline void MKL_Axpy(const MKL_INT n, const float a, const float *x, float *y) { cblas_saxpy(n, a, x, 1, y, 1); } inline void MKL_Axpy(const MKL_INT n, const double a, const double *x, double *y) { cblas_daxpy(n, a, x, 1, y, 1); } inline void MKL_Axpby(const MKL_INT n, const float a, const float *x, const float b, float *y) { cblas_saxpby(n, a, x, 1, b, y, 1); } inline void MKL_Axpby(const MKL_INT n, const double a, const double *x, const double b, double *y) { cblas_daxpby(n, a, x, 1, b, y, 1); } inline void MKL_Omatadd(char ordering, char transa, char transb, size_t m, size_t n, const float alpha, const float * A, size_t lda, const float beta, const float * B, size_t ldb, float * C, size_t ldc) { mkl_somatadd(ordering, transa, transb, m, n, alpha, A, lda, beta, B, ldb, C, ldc); } inline void MKL_Omatadd(char ordering, char transa, char transb, size_t m, size_t n, const double alpha, const double * A, size_t lda, const double beta, const double * B, size_t ldb, double * C, size_t ldc) { mkl_domatadd(ordering, transa, transb, m, n, alpha, A, lda, beta, B, ldb, C, ldc); } inline void MKL_GeMV(const CBLAS_LAYOUT Layout, const CBLAS_TRANSPOSE trans, const MKL_INT m, const MKL_INT n, const float alpha, const float *a, const MKL_INT lda, const float *x, const MKL_INT incx, const float beta, float *y, const MKL_INT incy) { cblas_sgemv(Layout, trans, m, n, alpha, a, lda, x, incx, beta, y, incy); } inline void MKL_GeMV(const CBLAS_LAYOUT Layout, const CBLAS_TRANSPOSE trans, const MKL_INT m, const MKL_INT n, const double alpha, const double *a, const MKL_INT lda, const double *x, const MKL_INT incx, const double beta, double *y, const MKL_INT incy) { cblas_dgemv(Layout, trans, m, n, alpha, a, lda, x, incx, beta, y, incy); } inline void MKL_GeMM(const CBLAS_LAYOUT Layout, const CBLAS_TRANSPOSE transa, const CBLAS_TRANSPOSE transb, const MKL_INT m, const MKL_INT n, const MKL_INT k, const float alpha, const float *a, const MKL_INT lda, const float *b, const MKL_INT ldb, const float beta, float *c, const MKL_INT ldc) { //std::cout << "Doing MKL_GeMM1, transa=" << transa << ", transb=" << transb << std::endl; cblas_sgemm(Layout, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); //std::cout << "MKL_GeMM1 done." << std::endl; } inline void MKL_GeMM(const CBLAS_LAYOUT Layout, const CBLAS_TRANSPOSE transa, const CBLAS_TRANSPOSE transb, const MKL_INT m, const MKL_INT n, const MKL_INT k, const double alpha, const double *a, const MKL_INT lda, const double *b, const MKL_INT ldb, const double beta, double *c, const MKL_INT ldc) { //std::cout << "Doing MKL_GeMM2, transa="<<transa<<", transb="<< transb << std::endl; cblas_dgemm(Layout, transa, transb, m, n, k, alpha, a, lda, b, ldb, beta, c, ldc); //std::cout << "MKL_GeMM2 done." << std::endl; } inline void MKL_CSRMM(char trans, MKL_INT m, MKL_INT n, MKL_INT k, float alpha, char *matdescra, float *val, MKL_INT *indx, MKL_INT *pntrb, MKL_INT *pntre, float *b, MKL_INT ldb, float beta, float *c, MKL_INT ldc) { mkl_scsrmm(&trans, &m, &n, &k, &alpha, matdescra, val, indx, pntrb, pntre, b, &ldb, &beta, c, &ldc); } inline void MKL_CSRMM(char trans, MKL_INT m, MKL_INT n, MKL_INT k, double alpha, char *matdescra, double *val, MKL_INT *indx, MKL_INT *pntrb, MKL_INT *pntre, double *b, MKL_INT ldb, double beta, double *c, MKL_INT ldc) { mkl_dcsrmm(&trans, &m, &n, &k, &alpha, matdescra, val, indx, pntrb, pntre, b, &ldb, &beta, c, &ldc); } inline void MKL_Abs(const MKL_INT n, float* a, float* y) { vsAbs(n, a, y); } inline void MKL_Abs(const MKL_INT n, double* a, double* y) { vdAbs(n, a, y); } inline void MKL_Sin(const MKL_INT n, float* a, float* y) { vsSin(n, a, y); } inline void MKL_Sin(const MKL_INT n, double* a, double* y) { vdSin(n, a, y); } inline void MKL_Cos(const MKL_INT n, float* a, float* y) { vsCos(n, a, y); } inline void MKL_Cos(const MKL_INT n, double* a, double* y) { vdCos(n, a, y); } inline void MKL_Exp(const MKL_INT n, float* a, float* y) { vsExp(n, a, y); } inline void MKL_Exp(const MKL_INT n, double* a, double* y) { vdExp(n, a, y); } inline void MKL_Log(const MKL_INT n, float* a, float* y) { vsLn(n, a, y); } inline void MKL_Log(const MKL_INT n, double* a, double* y) { vdLn(n, a, y); } inline void MKL_Mul(const MKL_INT n, float* a, float* b, float* y) { vsMul(n, a, b, y); } inline void MKL_Mul(const MKL_INT n, double* a, double* b, double* y) { vdMul(n, a, b, y); } inline void MKL_Div(const MKL_INT n, float* a, float* b, float* y) { vsDiv(n, a, b, y); } inline void MKL_Div(const MKL_INT n, double* a, double* b, double* y) { vdDiv(n, a, b, y); } inline void MKL_Sqrt(const MKL_INT n, float* a, float* y) { vsSqrt(n, a, y); } inline void MKL_Sqrt(const MKL_INT n, double* a, double* y) { vdSqrt(n, a, y); } inline void MKL_InvSqrt(const MKL_INT n, float* a, float* y) { vsInvSqrt(n, a, y); } inline void MKL_InvSqrt(const MKL_INT n, double* a, double* y) { vdInvSqrt(n, a, y); } inline void MKL_Inv(const MKL_INT n, float* a, float* y) { vsInv(n, a, y); } inline void MKL_Inv(const MKL_INT n, double* a, double* y) { vdInv(n, a, y); } inline void MKL_Square(const MKL_INT n, float* a, float* y) { vsSqr(n, a, y); } inline void MKL_Square(const MKL_INT n, double* a, double* y) { vdSqr(n, a, y); } inline void MKL_PowerX(const MKL_INT n, float* a, float b, float* y) { vsPowx(n, a, b, y); } inline void MKL_PowerX(const MKL_INT n, double* a, double b, double* y) { vdPowx(n, a, b, y); } } #endif
<reponame>hachaSegovia/phonegap-estimotebeacons-master // // BeaconsManager.h // OutSystems // // Created by <NAME> on 19/03/16. // // #import <Foundation/Foundation.h> @interface BeaconsManager : NSObject { NSMutableArray *notifications; } @property (nonatomic, retain) NSMutableArray *notifications; + (id)sharedManager; - (void) addNewNotification: (UILocalNotification *) notification; - (NSMutableArray *) getNotifications; - (void) removeNotification: (UILocalNotification *) notification; - (BOOL) clearNotifications; @end
#ifndef KKEEPCONNECTIONACL_H #define KKEEPCONNECTIONACL_H #include "KAcl.h" //@deprecated use work_model instead class KKeepConnectionAcl : public KAcl { public: KKeepConnectionAcl() { } ~KKeepConnectionAcl() { } KAcl *newInstance() { return new KKeepConnectionAcl(); } const char *getName() { return "keep_connection"; } bool match(KHttpRequest *rq, KHttpObject *obj) { return TEST(rq->workModel,WORK_MODEL_KA)>0; } std::string getDisplay() { std::stringstream s; s << "deprecated use work_model"; return s.str(); } void editHtml(std::map<std::string, std::string> &attibute) throw (KHtmlSupportException) { } void buildXML(std::stringstream &s) { s << ">"; } std::string getHtml(KModel *model) { return "deprecated please use work_model acl ka flag"; } private: }; #endif
/*++ EfiTianoDecompress.c Copyright (c) 2018, LongSoft. All rights reserved.<BR> Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.<BR> Portions copyright (c) 2008 - 2009, Apple Inc. All rights reserved.<BR> This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. Module Name: Decompress.c Abstract: UEFI Decompress Library implementation refer to UEFI specification. --*/ #include "EfiTianoDecompress.h" // // Decompression algorithm begins here // #define BITBUFSIZ 32 #define MAXMATCH 256 #define THRESHOLD 3 #define CODE_BIT 16 #ifndef UINT8_MAX #define UINT8_MAX 0xff #endif #define BAD_TABLE - 1 // // C: Char&Len Set; P: Position Set; T: exTra Set // #define NC (0xff + MAXMATCH + 2 - THRESHOLD) #define CBIT 9 #define MAXPBIT 5 #define TBIT 5 #define MAXNP ((1U << MAXPBIT) - 1) #define NT (CODE_BIT + 3) #if NT > MAXNP #define NPT NT #else #define NPT MAXNP #endif typedef struct { UINT8 *mSrcBase; // Starting address of compressed data UINT8 *mDstBase; // Starting address of decompressed data UINT32 mOutBuf; UINT32 mInBuf; UINT16 mBitCount; UINT32 mBitBuf; UINT32 mSubBitBuf; UINT16 mBlockSize; UINT32 mCompSize; UINT32 mOrigSize; UINT16 mBadTableFlag; UINT16 mLeft[2 * NC - 1]; UINT16 mRight[2 * NC - 1]; UINT8 mCLen[NC]; UINT8 mPTLen[NPT]; UINT16 mCTable[4096]; UINT16 mPTTable[256]; // // The length of the field 'Position Set Code Length Array Size' in Block Header. // For EFI 1.1 de/compression algorithm, mPBit = 4 // For Tiano de/compression algorithm, mPBit = 5 // UINT8 mPBit; } SCRATCH_DATA; STATIC UINT64 EFIAPI LShiftU64 ( UINT64 Operand, UINT32 Count ) { return Operand << Count; } STATIC VOID * EFIAPI SetMem ( OUT VOID *Buffer, IN UINTN Length, IN UINT8 Value ) { return memset (Buffer, Value, Length); } STATIC VOID * EFIAPI SetMem16 ( OUT VOID *Buffer, IN UINTN Length, IN UINT16 Value ) { UINTN Index; UINT16* Buf = (UINT16*)Buffer; if (Buffer == NULL || Length == 0) { return Buffer; } Length /= sizeof(UINT16); for (Index = 0; Index < Length; Index++) { Buf[Index] = Value; } return Buffer; } /** Read NumOfBit of bits from source into mBitBuf. Shift mBitBuf NumOfBits left. Read in NumOfBits of bits from source. @param Sd The global scratch data. @param NumOfBits The number of bits to shift and read. **/ STATIC VOID FillBuf ( IN SCRATCH_DATA *Sd, IN UINT16 NumOfBits ) { // // Left shift NumOfBits of bits in advance // Sd->mBitBuf = (UINT32)LShiftU64 (((UINT64)Sd->mBitBuf), NumOfBits); // // Copy data needed in bytes into mSbuBitBuf // while (NumOfBits > Sd->mBitCount) { NumOfBits = (UINT16)(NumOfBits - Sd->mBitCount); Sd->mBitBuf |= (UINT32)LShiftU64 (((UINT64)Sd->mSubBitBuf), NumOfBits); if (Sd->mCompSize > 0) { // // Get 1 byte into SubBitBuf // Sd->mCompSize--; Sd->mSubBitBuf = Sd->mSrcBase[Sd->mInBuf++]; Sd->mBitCount = 8; } else { // // No more bits from the source, just pad zero bit. // Sd->mSubBitBuf = 0; Sd->mBitCount = 8; } } // // Calculate additional bit count read to update mBitCount // Sd->mBitCount = (UINT16)(Sd->mBitCount - NumOfBits); // // Copy NumOfBits of bits from mSubBitBuf into mBitBuf // Sd->mBitBuf |= Sd->mSubBitBuf >> Sd->mBitCount; } /** Get NumOfBits of bits out from mBitBuf. Get NumOfBits of bits out from mBitBuf. Fill mBitBuf with subsequent NumOfBits of bits from source. Returns NumOfBits of bits that are popped out. @param Sd The global scratch data. @param NumOfBits The number of bits to pop and read. @return The bits that are popped out. **/ STATIC UINT32 GetBits ( IN SCRATCH_DATA *Sd, IN UINT16 NumOfBits ) { UINT32 OutBits; // // Pop NumOfBits of Bits from Left // OutBits = (UINT32)(Sd->mBitBuf >> (BITBUFSIZ - NumOfBits)); // // Fill up mBitBuf from source // FillBuf (Sd, NumOfBits); return OutBits; } /** Creates Huffman Code mapping table according to code length array. Creates Huffman Code mapping table for Extra Set, Char&Len Set and Position Set according to code length array. If TableBits > 16, then ASSERT (). @param Sd The global scratch data. @param NumOfChar The number of symbols in the symbol set. @param BitLen Code length array. @param TableBits The width of the mapping table. @param Table The table to be created. @retval 0 OK. @retval BAD_TABLE The table is corrupted. **/ STATIC UINT16 MakeTable ( IN SCRATCH_DATA *Sd, IN UINT16 NumOfChar, IN UINT8 *BitLen, IN UINT16 TableBits, OUT UINT16 *Table ) { UINT16 Count[17]; UINT16 Weight[17]; UINT16 Start[18]; UINT16 *Pointer; UINT16 Index3; UINT16 Index; UINT16 Len; UINT16 Char; UINT16 JuBits; UINT16 Avail; UINT16 NextCode; UINT16 Mask; UINT16 WordOfStart; UINT16 WordOfCount; UINT16 MaxTableLength; // // The maximum mapping table width supported by this internal // working function is 16. // if (TableBits >= (sizeof(Count) / sizeof(UINT16))) { return (UINT16)BAD_TABLE; } // // Initialize Count array starting from Index 0, as there is a possibility of Count array being uninitialized. // for (Index = 0; Index <= 16; Index++) { Count[Index] = 0; } for (Index = 0; Index < NumOfChar; Index++) { if (BitLen[Index] > 16) { return (UINT16)BAD_TABLE; } Count[BitLen[Index]]++; } Start[0] = 0; Start[1] = 0; for (Index = 1; Index <= 16; Index++) { WordOfStart = Start[Index]; WordOfCount = Count[Index]; Start[Index + 1] = (UINT16)(WordOfStart + (WordOfCount << (16 - Index))); } if (Start[17] != 0) { /*(1U << 16)*/ return (UINT16)BAD_TABLE; } JuBits = (UINT16)(16 - TableBits); Weight[0] = 0; for (Index = 1; Index <= TableBits; Index++) { Start[Index] >>= JuBits; Weight[Index] = (UINT16)(1U << (TableBits - Index)); } while (Index <= 16) { Weight[Index] = (UINT16)(1U << (16 - Index)); Index++; } Index = (UINT16)(Start[TableBits + 1] >> JuBits); if (Index != 0) { Index3 = (UINT16)(1U << TableBits); if (Index < Index3) { SetMem16 (Table + Index, (Index3 - Index) * sizeof(*Table), 0); } } Avail = NumOfChar; Mask = (UINT16)(1U << (15 - TableBits)); MaxTableLength = (UINT16)(1U << TableBits); for (Char = 0; Char < NumOfChar; Char++) { Len = BitLen[Char]; if (Len == 0 || Len >= 17) { continue; } NextCode = (UINT16)(Start[Len] + Weight[Len]); if (Len <= TableBits) { for (Index = Start[Len]; Index < NextCode; Index++) { if (Index >= MaxTableLength) { return (UINT16)BAD_TABLE; } Table[Index] = Char; } } else { Index3 = Start[Len]; Pointer = &Table[Index3 >> JuBits]; Index = (UINT16)(Len - TableBits); while (Index != 0) { if (*Pointer == 0 && Avail < (2 * NC - 1)) { Sd->mRight[Avail] = Sd->mLeft[Avail] = 0; *Pointer = Avail++; } if (*Pointer < (2 * NC - 1)) { if ((Index3 & Mask) != 0) { Pointer = &Sd->mRight[*Pointer]; } else { Pointer = &Sd->mLeft[*Pointer]; } } Index3 <<= 1; Index--; } *Pointer = Char; } Start[Len] = NextCode; } // // Succeeds // return 0; } /** Decodes a position value. Get a position value according to Position Huffman Table. @param Sd The global scratch data. @return The position value decoded. **/ UINT32 DecodeP ( IN SCRATCH_DATA *Sd ) { UINT16 Val; UINT32 Mask; UINT32 Pos; Val = Sd->mPTTable[Sd->mBitBuf >> (BITBUFSIZ - 8)]; if (Val >= MAXNP) { Mask = 1U << (BITBUFSIZ - 1 - 8); do { if ((Sd->mBitBuf & Mask) != 0) { Val = Sd->mRight[Val]; } else { Val = Sd->mLeft[Val]; } Mask >>= 1; } while (Val >= MAXNP); } // // Advance what we have read // FillBuf (Sd, Sd->mPTLen[Val]); Pos = Val; if (Val > 1) { Pos = (UINT32)((1U << (Val - 1)) + GetBits (Sd, (UINT16)(Val - 1))); } return Pos; } /** Reads code lengths for the Extra Set or the Position Set. Read in the Extra Set or Position Set Length Array, then generate the Huffman code mapping for them. @param Sd The global scratch data. @param nn The number of symbols. @param nbit The number of bits needed to represent nn. @param Special The special symbol that needs to be taken care of. @retval 0 OK. @retval BAD_TABLE Table is corrupted. **/ STATIC UINT16 ReadPTLen ( IN SCRATCH_DATA *Sd, IN UINT16 nn, IN UINT16 nbit, IN UINT16 Special ) { UINT16 Number; UINT16 CharC; UINT16 Index; UINT32 Mask; // // Read Extra Set Code Length Array size // Number = (UINT16)GetBits (Sd, nbit); if ((Number > sizeof(Sd->mPTLen)) || (nn > sizeof(Sd->mPTLen))) { // // Fail if Number or nn is greater than size of mPTLen // return (UINT16)BAD_TABLE; } if (Number == 0) { // // This represents only Huffman code used // CharC = (UINT16)GetBits (Sd, nbit); SetMem16 (&Sd->mPTTable[0], sizeof(Sd->mPTTable), CharC); SetMem (Sd->mPTLen, nn, 0); return 0; } Index = 0; while (Index < Number && Index < NPT) { CharC = (UINT16)(Sd->mBitBuf >> (BITBUFSIZ - 3)); // // If a code length is less than 7, then it is encoded as a 3-bit // value. Or it is encoded as a series of "1"s followed by a // terminating "0". The number of "1"s = Code length - 4. // if (CharC == 7) { Mask = 1U << (BITBUFSIZ - 1 - 3); while (Mask & Sd->mBitBuf) { Mask >>= 1; CharC += 1; } } FillBuf(Sd, (UINT16)((CharC < 7) ? 3 : CharC - 3)); Sd->mPTLen[Index++] = (UINT8)CharC; // // For Code&Len Set, // After the third length of the code length concatenation, // a 2-bit value is used to indicated the number of consecutive // zero lengths after the third length. // if (Index == Special) { CharC = (UINT16)GetBits (Sd, 2); while ((INT16)(--CharC) >= 0 && Index < NPT) { Sd->mPTLen[Index++] = 0; } } } while (Index < nn && Index < NPT) { Sd->mPTLen[Index++] = 0; } return MakeTable (Sd, nn, Sd->mPTLen, 8, Sd->mPTTable); } /** Reads code lengths for Char&Len Set. Read in and decode the Char&Len Set Code Length Array, then generate the Huffman Code mapping table for the Char&Len Set. @param Sd The global scratch data. **/ STATIC VOID ReadCLen ( SCRATCH_DATA *Sd ) { UINT16 Number; UINT16 CharC; UINT16 Index; UINT32 Mask; Number = (UINT16)GetBits (Sd, CBIT); if (Number == 0) { // // This represents only Huffman code used // CharC = (UINT16)GetBits (Sd, CBIT); SetMem (Sd->mCLen, NC, 0); SetMem16 (&Sd->mCTable[0], sizeof(Sd->mCTable), CharC); return; } Index = 0; while (Index < Number && Index < NC) { CharC = Sd->mPTTable[Sd->mBitBuf >> (BITBUFSIZ - 8)]; if (CharC >= NT) { Mask = 1U << (BITBUFSIZ - 1 - 8); do { if (Mask & Sd->mBitBuf) { CharC = Sd->mRight[CharC]; } else { CharC = Sd->mLeft[CharC]; } Mask >>= 1; } while (CharC >= NT); } // // Advance what we have read // FillBuf (Sd, Sd->mPTLen[CharC]); if (CharC <= 2) { if (CharC == 0) { CharC = 1; } else if (CharC == 1) { CharC = (UINT16)(GetBits (Sd, 4) + 3); } else if (CharC == 2) { CharC = (UINT16)(GetBits (Sd, CBIT) + 20); } while ((INT16)(--CharC) >= 0 && Index < NC) { Sd->mCLen[Index++] = 0; } } else { Sd->mCLen[Index++] = (UINT8)(CharC - 2); } } SetMem (Sd->mCLen + Index, NC - Index, 0); MakeTable (Sd, NC, Sd->mCLen, 12, Sd->mCTable); return; } /** Decode a character/length value. Read one value from mBitBuf, Get one code from mBitBuf. If it is at block boundary, generates Huffman code mapping table for Extra Set, Code&Len Set and Position Set. @param Sd The global scratch data. @return The value decoded. **/ STATIC UINT16 DecodeC ( SCRATCH_DATA *Sd ) { UINT16 Index2; UINT32 Mask; if (Sd->mBlockSize == 0) { // // Starting a new block // Read BlockSize from block header // Sd->mBlockSize = (UINT16)GetBits (Sd, 16); // // Read in the Extra Set Code Length Array, // Generate the Huffman code mapping table for Extra Set. // Sd->mBadTableFlag = ReadPTLen (Sd, NT, TBIT, 3); if (Sd->mBadTableFlag != 0) { return 0; } // // Read in and decode the Char&Len Set Code Length Array, // Generate the Huffman code mapping table for Char&Len Set. // ReadCLen (Sd); // // Read in the Position Set Code Length Array, // Generate the Huffman code mapping table for the Position Set. // Sd->mBadTableFlag = ReadPTLen (Sd, MAXNP, Sd->mPBit, (UINT16)(-1)); if (Sd->mBadTableFlag != 0) { return 0; } } // // Get one code according to Code&Set Huffman Table // Sd->mBlockSize--; Index2 = Sd->mCTable[Sd->mBitBuf >> (BITBUFSIZ - 12)]; if (Index2 >= NC) { Mask = 1U << (BITBUFSIZ - 1 - 12); do { if ((Sd->mBitBuf & Mask) != 0) { Index2 = Sd->mRight[Index2]; } else { Index2 = Sd->mLeft[Index2]; } Mask >>= 1; } while (Index2 >= NC); } // // Advance what we have read // FillBuf (Sd, Sd->mCLen[Index2]); return Index2; } /** Decode the source data and put the resulting data into the destination buffer. @param Sd The global scratch data. **/ STATIC VOID Decode ( SCRATCH_DATA *Sd ) { UINT16 BytesRemain; UINT32 DataIdx; UINT16 CharC; for (;;) { // // Get one code from mBitBuf // CharC = DecodeC(Sd); if (Sd->mBadTableFlag != 0) { goto Done; } if (CharC < 256) { // // Process an Original character // if (Sd->mOutBuf >= Sd->mOrigSize) { goto Done; } else { // // Write orignal character into mDstBase // Sd->mDstBase[Sd->mOutBuf++] = (UINT8)CharC; } } else { // // Process a Pointer // CharC = (UINT16)(CharC - (0x00000100U - THRESHOLD)); // // Get string length // BytesRemain = CharC; // // Locate string position // DataIdx = Sd->mOutBuf - DecodeP(Sd) - 1; // // Write BytesRemain of bytes into mDstBase // BytesRemain--; while ((INT16)(BytesRemain) >= 0) { if (Sd->mOutBuf >= Sd->mOrigSize) { goto Done; } if (DataIdx >= Sd->mOrigSize) { Sd->mBadTableFlag = (UINT16)BAD_TABLE; goto Done; } Sd->mDstBase[Sd->mOutBuf++] = Sd->mDstBase[DataIdx++]; BytesRemain--; } // // Once mOutBuf is fully filled, directly return // if (Sd->mOutBuf >= Sd->mOrigSize) { goto Done; } } } Done: return; } /** Given a compressed source buffer, this function retrieves the size of the uncompressed buffer and the size of the scratch buffer required to decompress the compressed source buffer. Retrieves the size of the uncompressed buffer and the temporary scratch buffer required to decompress the buffer specified by Source and SourceSize. If the size of the uncompressed buffer or the size of the scratch buffer cannot be determined from the compressed data specified by Source and SourceData, then EFI_INVALID_PARAMETER is returned. Otherwise, the size of the uncompressed buffer is returned in DestinationSize, the size of the scratch buffer is returned in ScratchSize, and EFI_SUCCESS is returned. This function does not have scratch buffer available to perform a thorough checking of the validity of the source data. It just retrieves the "Original Size" field from the beginning bytes of the source data and output it as DestinationSize. And ScratchSize is specific to the decompression implementation. @param Source The source buffer containing the compressed data. @param SourceSize The size, in bytes, of the source buffer. @param DestinationSize A pointer to the size, in bytes, of the uncompressed buffer that will be generated when the compressed buffer specified by Source and SourceSize is decompressed. @param ScratchSize A pointer to the size, in bytes, of the scratch buffer that is required to decompress the compressed buffer specified by Source and SourceSize. @retval EFI_SUCCESS The size of the uncompressed data was returned in DestinationSize, and the size of the scratch buffer was returned in ScratchSize. @retval EFI_INVALID_PARAMETER The size of the uncompressed data or the size of the scratch buffer cannot be determined from the compressed data specified by Source and SourceSize. **/ EFI_STATUS EFIAPI GetInfo ( IN CONST VOID *Source, IN UINT32 SourceSize, OUT UINT32 *DestinationSize, OUT UINT32 *ScratchSize ) { UINT32 CompressedSize; if (Source == NULL || DestinationSize == NULL || ScratchSize == NULL || SourceSize < 8) { return EFI_INVALID_PARAMETER; } CompressedSize = *(UINT32 *)Source; if (SourceSize < (CompressedSize + 8) || (CompressedSize + 8) < 8) { return EFI_INVALID_PARAMETER; } *ScratchSize = sizeof(SCRATCH_DATA); *DestinationSize = *((UINT32 *)Source + 1); return EFI_SUCCESS; } /** Decompresses a compressed source buffer. Extracts decompressed data to its original form. This function is designed so that the decompression algorithm can be implemented without using any memory services. As a result, this function is not allowed to call any memory allocation services in its implementation. It is the caller's responsibility to allocate and free the Destination and Scratch buffers. If the compressed source data specified by Source is successfully decompressed into Destination, then RETURN_SUCCESS is returned. If the compressed source data specified by Source is not in a valid compressed data format, then RETURN_INVALID_PARAMETER is returned. @param Source The source buffer containing the compressed data. @param Destination The destination buffer to store the decompressed data. @param Scratch A temporary scratch buffer that is used to perform the decompression. This is an optional parameter that may be NULL if the required scratch buffer size is 0. @retval EFI_SUCCESS Decompression completed successfully, and the uncompressed buffer is returned in Destination. @retval EFI_INVALID_PARAMETER The source buffer specified by Source is corrupted (not in a valid compressed format). **/ EFI_STATUS EFIAPI Decompress ( IN CONST VOID *Source, IN UINT32 SrcSize, IN OUT VOID *Destination, IN UINT32 DstSize, IN OUT VOID *Scratch, IN UINT32 ScratchSize, IN UINT8 Version ) { UINT32 CompSize; UINT32 OrigSize; SCRATCH_DATA *Sd; CONST UINT8 *Src = Source; UINT8 *Dst = Destination; EFI_STATUS Status = EFI_SUCCESS; if (ScratchSize < sizeof(SCRATCH_DATA)) { return EFI_INVALID_PARAMETER; } Sd = (SCRATCH_DATA *)Scratch; if (SrcSize < 8) { return EFI_INVALID_PARAMETER; } CompSize = Src[0] + (Src[1] << 8) + (Src[2] << 16) + (Src[3] << 24); OrigSize = Src[4] + (Src[5] << 8) + (Src[6] << 16) + (Src[7] << 24); // // If compressed file size is 0, return // if (OrigSize == 0) { return Status; } if (SrcSize < CompSize + 8) { return EFI_INVALID_PARAMETER; } if (DstSize != OrigSize) { return EFI_INVALID_PARAMETER; } Src = Src + 8; SetMem (Sd, sizeof(SCRATCH_DATA), 0); // // The length of the field 'Position Set Code Length Array Size' in Block Header. // For EFI 1.1 de/compression algorithm(Version 1), mPBit = 4 // For Tiano de/compression algorithm(Version 2), mPBit = 5 // switch (Version) { case 1: Sd->mPBit = 4; break; case 2: Sd->mPBit = 5; break; default: // // Currently, only have 2 versions // return EFI_INVALID_PARAMETER; } Sd->mSrcBase = (UINT8*)Src; Sd->mDstBase = Dst; // // CompSize and OrigSize are calculated in bytes // Sd->mCompSize = CompSize; Sd->mOrigSize = OrigSize; // // Fill the first BITBUFSIZ bits // FillBuf (Sd, BITBUFSIZ); // // Decompress it // Decode (Sd); if (Sd->mBadTableFlag != 0) { // // Something wrong with the source // Status = EFI_INVALID_PARAMETER; } return Status; } /*++ Routine Description: The implementation of EFI_DECOMPRESS_PROTOCOL.GetInfo(). Arguments: This - The protocol instance pointer Source - The source buffer containing the compressed data. SrcSize - The size of source buffer DstSize - The size of destination buffer. ScratchSize - The size of scratch buffer. Returns: EFI_SUCCESS - The size of destination buffer and the size of scratch buffer are successful retrieved. EFI_INVALID_PARAMETER - The source data is corrupted --*/ EFI_STATUS EFIAPI EfiTianoGetInfo ( IN CONST VOID *Source, IN UINT32 SrcSize, OUT UINT32 *DstSize, OUT UINT32 *ScratchSize ) { return GetInfo (Source, SrcSize, DstSize, ScratchSize); } /*++ Routine Description: The implementation of EFI_DECOMPRESS_PROTOCOL.Decompress(). Arguments: This - The protocol instance pointer Source - The source buffer containing the compressed data. SrcSize - The size of source buffer Destination - The destination buffer to store the decompressed data DstSize - The size of destination buffer. Scratch - The buffer used internally by the decompress routine. This buffer is needed to store intermediate data. ScratchSize - The size of scratch buffer. Returns: EFI_SUCCESS - Decompression is successful EFI_INVALID_PARAMETER - The source data is corrupted --*/ EFI_STATUS EFIAPI EfiDecompress ( IN CONST VOID *Source, IN UINT32 SrcSize, IN OUT VOID *Destination, IN UINT32 DstSize, IN OUT VOID *Scratch, IN UINT32 ScratchSize ) { // // For EFI 1.1 de/compression algorithm, the version is 1. // return Decompress ( Source, SrcSize, Destination, DstSize, Scratch, ScratchSize, 1 ); } /*++ Routine Description: The implementation of EFI_TIANO_DECOMPRESS_PROTOCOL.Decompress(). Arguments: This - The protocol instance pointer Source - The source buffer containing the compressed data. SrcSize - The size of source buffer Destination - The destination buffer to store the decompressed data DstSize - The size of destination buffer. Scratch - The buffer used internally by the decompress routine. This buffer is needed to store intermediate data. ScratchSize - The size of scratch buffer. Returns: EFI_SUCCESS - Decompression is successful EFI_INVALID_PARAMETER - The source data is corrupted --*/ EFI_STATUS EFIAPI TianoDecompress ( IN CONST VOID *Source, IN UINT32 SrcSize, IN OUT VOID *Destination, IN UINT32 DstSize, IN OUT VOID *Scratch, IN UINT32 ScratchSize ) { // // For Tiano de/compression algorithm, the version is 2. // return Decompress ( Source, SrcSize, Destination, DstSize, Scratch, ScratchSize, 2 ); }
<filename>utils/elf_parser.c<gh_stars>1-10 // Copyright (c) 2021 <NAME> // This code is licensed under a 3-clause BSD license - see LICENSE.txt #include <assert.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> const uint32_t ELF_HEADER_MAG = 0x464c457F; const uint8_t ELF_HEADER_MACHINE_RISCV = 0xf3; struct __attribute__((packed)) elf_header { uint32_t e_ident_mag; uint8_t e_ident_class; uint8_t e_ident_data; uint8_t e_ident_version; uint8_t e_ident_abi; uint8_t e_ident_abiversion; uint8_t e_ident_pad[7]; uint16_t e_type; uint16_t e_machine; uint32_t e_version; uint32_t e_entry; uint32_t e_phoff; uint32_t e_shoff; uint32_t e_flags; uint16_t e_ehsize; uint16_t e_phentsize; uint16_t e_phnum; uint16_t e_shentsize; uint16_t e_shnum; uint16_t e_shstrndx; }; struct __attribute__((packed)) ph_entry { uint32_t p_type; uint32_t p_offset; uint32_t p_vaddr; uint32_t p_paddr; uint32_t p_filesz; uint32_t p_memsz; uint32_t p_flags; uint32_t p_align; }; struct __attribute__((packed)) sh_entry { uint32_t sh_name; uint32_t sh_type; uint32_t sh_flags; uint32_t sh_addr; uint32_t sh_offset; uint32_t sh_size; uint32_t sh_link; uint32_t sh_info; uint32_t sh_addralign; uint32_t sh_entsize; }; void print_header(struct elf_header* hdr) { printf("ELF header\n"); printf(" magic number = %x ", hdr->e_ident_mag); printf("%s", hdr->e_ident_mag == ELF_HEADER_MAG ? "(OK)" : "(ERROR)"); printf("\n"); // clang-format off printf(" class = %s\n", hdr->e_ident_class == 1 ? "32b" : hdr->e_ident_class == 2 ? "64b" : "ERROR: unrecognized" ); // clang-format ong printf(" ABI = 0x%x\n", hdr->e_ident_abi); printf(" version = %d\n", hdr->e_version); printf(" machine = 0x%x (%s)\n", hdr->e_machine, hdr->e_machine == ELF_HEADER_MACHINE_RISCV ? "RISC-V" : "unsupported"); printf(" entry = 0x%x\n", hdr->e_entry); printf("\n"); printf(" prog header offs = 0x%x\n", hdr->e_phoff); printf(" ph entry size = %d\n", hdr->e_phentsize); printf(" ph num = %d\n", hdr->e_phnum); printf("\n"); printf(" sect header offs = 0x%x\n", hdr->e_shoff); printf(" sh entry size = %d\n", hdr->e_shentsize); printf(" sh num = %d\n", hdr->e_shnum); printf(" sh str index = %d\n", hdr->e_shstrndx); } void print_prog_header(struct ph_entry* entry) { printf(" type = 0x%x [", entry->p_type); switch (entry->p_type) { case 1: printf("LOAD"); break; case 2: printf("DYNAMIC"); break; case 3: printf("INTERP"); break; case 4: printf("NOTE"); break; case 5: printf("SHLIB"); break; case 6: printf("PHDR"); break; case 7: printf("TLS"); break; case 0x6474e553: printf("GNU_PROPERTY"); break; case 0x6474e550: printf("GNU_EH_FRAME"); break; case 0x6474e551: printf("GNU_STACK"); break; case 0x6474e552: printf("GNU_RELRO"); break; } printf("]\n"); printf(" flags = 0x%x (", entry->p_flags); printf("%c", (entry->p_flags & (1 << 2)) ? 'R' : '-'); printf("%c", (entry->p_flags & (1 << 1)) ? 'W' : '-'); printf("%c", (entry->p_flags & (1 << 0)) ? 'X' : '-'); printf(")\n"); printf(" offset = 0x%x\n", entry->p_offset); printf(" vaddr = 0x%x\n", entry->p_vaddr); printf(" paddr = 0x%x\n", entry->p_paddr); printf(" filesz = 0x%x\n", entry->p_filesz); printf(" memsz = 0x%x\n", entry->p_memsz); printf(" align = 0x%x\n", entry->p_align); } void print_prog_headers(int fd, struct elf_header* hdr) { printf("Program headers\n"); lseek(fd, hdr->e_phoff, SEEK_SET); struct ph_entry entry; for (int i = 0; i < hdr->e_phnum; i++) { read(fd, &entry, sizeof(entry)); printf(" Prog header %d\n", i); print_prog_header(&entry); } } // caller is responsible for free-ing the returned buffer char* get_sh_name_buffer(int fd, struct elf_header* hdr) { off_t cur_pos = lseek(fd, 0, SEEK_CUR); struct sh_entry entry; pread(fd, &entry, sizeof(entry), hdr->e_shoff + hdr->e_shentsize*hdr->e_shstrndx); off_t str_pos = entry.sh_offset; size_t str_len = entry.sh_size; char* str = malloc(str_len); assert(str != NULL); pread(fd, str, str_len, str_pos); lseek(fd, cur_pos, SEEK_SET); return str; } void print_section_header(struct sh_entry *entry, const char* section_names) { printf(" name = %s (%d)\n", section_names + entry->sh_name, entry->sh_name); printf(" type = 0x%x [", entry->sh_type); switch (entry->sh_type) { case 0 : printf("NULL"); break; case 1 : printf("PROGBITS"); break; case 2 : printf("SYMTAB"); break; case 3 : printf("STRTAB"); break; case 4 : printf("RELA"); break; case 5 : printf("HASH"); break; case 6 : printf("DYNAMIC"); break; case 7 : printf("NOTE"); break; case 8 : printf("NOBITS"); break; case 9 : printf("REL"); break; case 10 : printf("SHLIB"); break; case 11 : printf("DYNSYM"); break; case 14 : printf("INIT_ARRAY"); break; case 15 : printf("FINI_ARRAY"); break; case 16 : printf("PREINIT_ARRAY"); break; case 17 : printf("GROUP"); break; case 18 : printf("SYMTAB_SHNDX"); break; case 19 : printf("NUM"); break; default: if ((entry->sh_type >= 0x70000000) && (entry->sh_type <= 0x7fffffff)) { printf("PROC"); break; } } printf("]\n"); printf(" flags = 0x%x [", entry->sh_flags); printf("%s", entry->sh_flags & (1 << 0) ? "WRITE, " : ""); printf("%s", entry->sh_flags & (1 << 1) ? "ALLOC, " : ""); printf("%s", entry->sh_flags & (1 << 2) ? "EXECINSTR, " : ""); printf("%s", entry->sh_flags & (1 << 4) ? "MERGE, " : ""); printf("%s", entry->sh_flags & (1 << 5) ? "STRINGS, " : ""); printf("%s", entry->sh_flags & (1 << 6) ? "INFO_LINK, " : ""); printf("%s", entry->sh_flags & (1 << 7) ? "LINK_ORDER, " : ""); printf("%s", entry->sh_flags & (1 << 8) ? "OS_NONCONFORMING, " : ""); printf("%s", entry->sh_flags & (1 << 9) ? "GROUP, " : ""); printf("%s", entry->sh_flags & (1 << 10) ? "TLS, " : ""); printf("%s", entry->sh_flags & (1 << 11) ? "COMPRESSED, " : ""); if (entry->sh_flags) { printf("\b\b]\n"); } else { printf("]\n"); } printf(" addr = 0x%x\n", entry->sh_addr); printf(" offset = 0x%x\n", entry->sh_offset); printf(" size = 0x%x\n", entry->sh_size); printf(" link = 0x%0x\n", entry->sh_link); printf(" info = 0x%0x\n", entry->sh_info); printf(" aalign = 0x%x\n", entry->sh_addralign); printf(" ent sz = 0x%x\n", entry->sh_entsize); } void print_section_headers(int fd, struct elf_header* hdr) { printf("Section headers\n"); lseek(fd, hdr->e_shoff, SEEK_SET); char* section_names = get_sh_name_buffer(fd, hdr); struct sh_entry entry; for (int i = 0; i < hdr->e_shnum; i++) { read(fd, &entry, sizeof(entry)); printf(" Section header %d\n", i); print_section_header(&entry, section_names); } free(section_names); } int main(int argc, char* argv[]) { if (argc != 2) { printf("Usage: %s ELF_FILE\n", argv[0]); return EXIT_FAILURE; } int fd = open(argv[1], O_RDWR); if (fd < 0) { printf("Error opening file\n"); return EXIT_FAILURE; } struct elf_header hdr; read(fd, &hdr, sizeof(hdr)); print_header(&hdr); print_prog_headers(fd, &hdr); print_section_headers(fd, &hdr); }
#import <UIKit/UIKit.h> FOUNDATION_EXPORT double Pods_Forest_GuardianUITestsVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_Forest_GuardianUITestsVersionString[];
<filename>aswscommon/common/xml/xml_traverser.h #pragma once // xml_traverser.h // // (C) Copyright 2014 <NAME> // #include <map> //-------------------------------------------------------------------------------- #include "../../../3rdparty/pugixml-1.4/src/pugixml.hpp" //-------------------------------------------------------------------------------- #include "xml_rule_set.h" //-------------------------------------------------------------------------------- namespace asws { namespace common { namespace xml { //-------------------------------------------------------------------------------- /* XML node traverser Traverses the tree, passes the control to the underlying traversers specified for specific nodes Performs the validation */ class xml_traverser { public: /* Function executed while traversing the tree Should call traverser->descend() to descend down the tree */ typedef std::function<void(pugi::xml_node, xml_traverser*)> parse_func; /* Constructor */ xml_traverser(xml_rule_set& rules, parse_func fnc) : _parse_func(fnc), _rules(rules) { } /* Set handler for specific child node */ void set_sub_traverser(const std::string& node, xml_traverser& traverser) { // if item exists - erase auto itr = _sub_traversers.find(node); if (itr != _sub_traversers.end()) _sub_traversers.erase(itr); _sub_traversers.insert( std::map<std::string, xml_traverser&>::value_type(node, traverser) ); } /* Traverse the node Executes: - Validator - Parse function - Parse function should execute pass call If any of them throws an exception parsing is terminated */ void traverse(pugi::xml_node node); /* Returns control to the traverser Continues parsing the children nodes */ void pass(pugi::xml_node node); /* Traverser initializer Overloads operator() for clever initialization */ class xml_sub_traverser_init { friend class xml_traverser; private: /* Constructor */ xml_sub_traverser_init(xml_traverser* traverser) : _owner(traverser) { } public: /* Add new handler */ xml_sub_traverser_init& operator() (std::string node, xml_traverser& traverser) { _owner->set_sub_traverser(node, traverser); return *this; } private: // parent traverser xml_traverser* _owner; }; // class xml_sub_traverser_initializer /* Set handlers */ xml_sub_traverser_init set_sub_traversers() { return xml_sub_traverser_init(this); } private: // Specified parse function parse_func _parse_func; // Specified rule set xml_rule_set& _rules; // Sub-traversers std::map<std::string, xml_traverser&> _sub_traversers; }; // class xml_traverser //-------------------------------------------------------------------------------- } // namespace xml } // namespace common } // namespace asws //--------------------------------------------------------------------------------
<gh_stars>0 #pragma once #include "particle.h" #include "vector.h" #include "airfoil.h" #include "sat_poly_collision.h" namespace wingworks { class AirfoilCollision { private: const Airfoil& foil_m; public: // Bit of a lifetime issue, there... AirfoilCollision(const Airfoil& foil) : foil_m(foil) { } bool is_colliding(const Particle& particle, Vector& recoil_vec_result); Vector resolve_collision(Particle& particle, Vector& recoil_vec) const; double accel_from_foil(const Particle& particle, const Vector& normal) const; }; }
/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2013-2015 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY 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 OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #pragma once #include <modules/tools/toolsmoduledefine.h> #include <modules/tools/filelistproperty.h> #include <modules/tools/volumesourceseriesdata.h> #include <modules/tools/simplelrucache.h> #include <inviwo/core/common/inviwo.h> #include <inviwo/core/processors/processor.h> #include <inviwo/core/ports/volumeport.h> #include <inviwo/core/properties/ordinalproperty.h> #include <inviwo/core/properties/stringproperty.h> #include <modules/base/properties/basisproperty.h> #include <modules/base/properties/volumeinformationproperty.h> #include <inviwo/core/properties/boolproperty.h> namespace inviwo { namespace kth { /** \docpage{org.inviwo.VolumeSourceSeries, Volume Series} * ![](org.inviwo.VolumeSourceSeries.png?classIdentifier=org.inviwo.VolumeSourceSeries) * * Loads a series of volumes, one at the time. * * ### Outports * * __Outport__ The currently loaded volume. * * ### Properties * * __File names__ Files to load. * * __Time step__ To select the current volume. * */ class IVW_MODULE_TOOLS_API VolumeSourceSeries : public Processor { //Friends //Types public: //Construction / Deconstruction public: VolumeSourceSeries(); virtual ~VolumeSourceSeries() = default; //Info public: virtual const ProcessorInfo getProcessorInfo() const override; static const ProcessorInfo processorInfo_; //Methods public: ///Returns number of volumes in the series. virtual size_t GetNumFiles() const; ///Returns a particular volume of the series. @note May be NULL. std::shared_ptr< Volume > GetVolume(const size_t Idx); protected: ///Updates User Interface. virtual void update(); ///Our main computation method. virtual void process(); ///Adds the file extension filters to the filelistproperty void addFileNameFilters(); ///Updates the info display void updateCacheInfo() const { propCacheInfo.set("Filled " + std::to_string(VolumeCache.GetCacheSize()) + " / " + std::to_string(VolumeCache.GetMaxCacheSize())); } //Ports private: ///Resulting volume series VolumeSeriesOutport resVolumeSeries; ///Result as a current time step VolumeOutport resVolume; //Properties public: ///File names of volumes to load. FileListProperty propFileNames; ///Maximal cache size IntProperty propMaxCacheSize; ///Info about the cache mutable StringProperty propCacheInfo; ///Which volume to load. IntProperty propFileIndex; ///Information on the bounding box //BasisProperty propBasisInfo; ///Information about values and resolution VolumeInformationProperty propVolumeInfo; ///Whether to override the data range BoolProperty propOptionOverRideDataRange; ///Values for enforced data range DoubleMinMaxProperty propOverRideDataRange; //Attributes protected: ///The Series Data object to be put into the VolumeSeriesOutport resVolumeSeries. VolumeSourceSeriesData SSD; ///Cache of loaded volumes. mutable SimpleLRUCache<size_t, Volume> VolumeCache; private: ///Settings in case a RAW Reader is used bool bRAWSettingsInitialized; bool littleEndian; ivec3 dimensions; DataFormatBase* format; DataMapper dataMap; }; } // namespace kth } // namespace
// Copyright (c) 2021, k-noya // Distributed under the BSD 3-Clause License. // See accompanying file LICENSE #ifndef MH2C_FRAME_FRAME_TYPE_REGISTRY_H_ #define MH2C_FRAME_FRAME_TYPE_REGISTRY_H_ #include <cstdint> #include "mh2c/frame/frame_header.h" namespace mh2c { // cf. https://tools.ietf.org/html/rfc7540#section-11.2 enum class frame_type_registry : fh_type_t { DATA, HEADERS, PRIORITY, RST_STREAM, SETTINGS, PUSH_PROMISE, PING, GOAWAY, WINDOW_UPDATE, CONTINUATION }; template <typename T> inline frame_type_registry cast_to_frame_type_registry(T frame_type); } // namespace mh2c #include "mh2c/frame/frame_type_registry.ipp" #endif // MH2C_FRAME_FRAME_TYPE_REGISTRY_H_
<gh_stars>1-10 /* * * BlueZ - Bluetooth protocol stack for Linux * * Copyright (C) 2006-2010 Nokia Corporation * Copyright (C) 2004-2010 <NAME> <<EMAIL>> * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <stdlib.h> #include <stdint.h> #include <errno.h> #include <unistd.h> #include <assert.h> #include <signal.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <netinet/in.h> #include <bluetooth/bluetooth.h> #include <bluetooth/sdp.h> #include <bluetooth/sdp_lib.h> #include <glib.h> #include <dbus/dbus.h> #include <gdbus.h> #include "log.h" #include "error.h" #include "uinput.h" #include "adapter.h" #include "../src/device.h" #include "device.h" #include "manager.h" #include "avdtp.h" #include "control.h" #include "sdpd.h" #include "glib-helper.h" #include "btio.h" #include "dbus-common.h" #define AVCTP_PSM 23 /* Message types */ #define AVCTP_COMMAND 0 #define AVCTP_RESPONSE 1 /* Packet types */ #define AVCTP_PACKET_SINGLE 0 #define AVCTP_PACKET_START 1 #define AVCTP_PACKET_CONTINUE 2 #define AVCTP_PACKET_END 3 /* ctype entries */ #define CTYPE_CONTROL 0x0 #define CTYPE_STATUS 0x1 #define CTYPE_NOT_IMPLEMENTED 0x8 #define CTYPE_ACCEPTED 0x9 #define CTYPE_REJECTED 0xA #define CTYPE_STABLE 0xC /* opcodes */ #define OP_UNITINFO 0x30 #define OP_SUBUNITINFO 0x31 #define OP_PASSTHROUGH 0x7c /* subunits of interest */ #define SUBUNIT_PANEL 0x09 /* operands in passthrough commands */ #define VOL_UP_OP 0x41 #define VOL_DOWN_OP 0x42 #define MUTE_OP 0x43 #define PLAY_OP 0x44 #define STOP_OP 0x45 #define PAUSE_OP 0x46 #define RECORD_OP 0x47 #define REWIND_OP 0x48 #define FAST_FORWARD_OP 0x49 #define EJECT_OP 0x4a #define FORWARD_OP 0x4b #define BACKWARD_OP 0x4c #define QUIRK_NO_RELEASE 1 << 0 static DBusConnection *connection = NULL; static gchar *input_device_name = NULL; static GSList *servers = NULL; #if __BYTE_ORDER == __LITTLE_ENDIAN struct avctp_header { uint8_t ipid:1; uint8_t cr:1; uint8_t packet_type:2; uint8_t transaction:4; uint16_t pid; } __attribute__ ((packed)); #define AVCTP_HEADER_LENGTH 3 struct avrcp_header { uint8_t code:4; uint8_t _hdr0:4; uint8_t subunit_id:3; uint8_t subunit_type:5; uint8_t opcode; } __attribute__ ((packed)); #define AVRCP_HEADER_LENGTH 3 #elif __BYTE_ORDER == __BIG_ENDIAN struct avctp_header { uint8_t transaction:4; uint8_t packet_type:2; uint8_t cr:1; uint8_t ipid:1; uint16_t pid; } __attribute__ ((packed)); #define AVCTP_HEADER_LENGTH 3 struct avrcp_header { uint8_t _hdr0:4; uint8_t code:4; uint8_t subunit_type:5; uint8_t subunit_id:3; uint8_t opcode; } __attribute__ ((packed)); #define AVRCP_HEADER_LENGTH 3 #else #error "Unknown byte order" #endif struct avctp_state_callback { avctp_state_cb cb; void *user_data; unsigned int id; }; struct avctp_server { bdaddr_t src; GIOChannel *io; uint32_t tg_record_id; #ifndef ANDROID uint32_t ct_record_id; #endif }; struct control { struct audio_device *dev; avctp_state_t state; int uinput; GIOChannel *io; guint io_id; uint16_t mtu; gboolean target; uint8_t key_quirks[256]; }; static struct { const char *name; uint8_t avrcp; uint16_t uinput; } key_map[] = { { "PLAY", PLAY_OP, KEY_PLAYCD }, { "STOP", STOP_OP, KEY_STOPCD }, { "PAUSE", PAUSE_OP, KEY_PAUSECD }, { "FORWARD", FORWARD_OP, KEY_NEXTSONG }, { "BACKWARD", BACKWARD_OP, KEY_PREVIOUSSONG }, { "REWIND", REWIND_OP, KEY_REWIND }, { "FAST FORWARD", FAST_FORWARD_OP, KEY_FASTFORWARD }, { NULL } }; static GSList *avctp_callbacks = NULL; static void auth_cb(DBusError *derr, void *user_data); static sdp_record_t *avrcp_ct_record(void) { sdp_list_t *svclass_id, *pfseq, *apseq, *root; uuid_t root_uuid, l2cap, avctp, avrct; sdp_profile_desc_t profile[1]; sdp_list_t *aproto, *proto[2]; sdp_record_t *record; sdp_data_t *psm, *version, *features; uint16_t lp = AVCTP_PSM; uint16_t avrcp_ver = 0x0100, avctp_ver = 0x0103, feat = 0x000f; record = sdp_record_alloc(); if (!record) return NULL; sdp_uuid16_create(&root_uuid, PUBLIC_BROWSE_GROUP); root = sdp_list_append(0, &root_uuid); sdp_set_browse_groups(record, root); /* Service Class ID List */ sdp_uuid16_create(&avrct, AV_REMOTE_SVCLASS_ID); svclass_id = sdp_list_append(0, &avrct); sdp_set_service_classes(record, svclass_id); /* Protocol Descriptor List */ sdp_uuid16_create(&l2cap, L2CAP_UUID); proto[0] = sdp_list_append(0, &l2cap); psm = sdp_data_alloc(SDP_UINT16, &lp); proto[0] = sdp_list_append(proto[0], psm); apseq = sdp_list_append(0, proto[0]); sdp_uuid16_create(&avctp, AVCTP_UUID); proto[1] = sdp_list_append(0, &avctp); version = sdp_data_alloc(SDP_UINT16, &avctp_ver); proto[1] = sdp_list_append(proto[1], version); apseq = sdp_list_append(apseq, proto[1]); aproto = sdp_list_append(0, apseq); sdp_set_access_protos(record, aproto); /* Bluetooth Profile Descriptor List */ sdp_uuid16_create(&profile[0].uuid, AV_REMOTE_PROFILE_ID); profile[0].version = avrcp_ver; pfseq = sdp_list_append(0, &profile[0]); sdp_set_profile_descs(record, pfseq); features = sdp_data_alloc(SDP_UINT16, &feat); sdp_attr_add(record, SDP_ATTR_SUPPORTED_FEATURES, features); sdp_set_info_attr(record, "AVRCP CT", 0, 0); free(psm); free(version); sdp_list_free(proto[0], 0); sdp_list_free(proto[1], 0); sdp_list_free(apseq, 0); sdp_list_free(pfseq, 0); sdp_list_free(aproto, 0); sdp_list_free(root, 0); sdp_list_free(svclass_id, 0); return record; } static sdp_record_t *avrcp_tg_record(void) { sdp_list_t *svclass_id, *pfseq, *apseq, *root; uuid_t root_uuid, l2cap, avctp, avrtg; sdp_profile_desc_t profile[1]; sdp_list_t *aproto, *proto[2]; sdp_record_t *record; sdp_data_t *psm, *version, *features; uint16_t lp = AVCTP_PSM; uint16_t avrcp_ver = 0x0100, avctp_ver = 0x0103, feat = 0x000f; #ifdef ANDROID feat = 0x0001; #endif record = sdp_record_alloc(); if (!record) return NULL; sdp_uuid16_create(&root_uuid, PUBLIC_BROWSE_GROUP); root = sdp_list_append(0, &root_uuid); sdp_set_browse_groups(record, root); /* Service Class ID List */ sdp_uuid16_create(&avrtg, AV_REMOTE_TARGET_SVCLASS_ID); svclass_id = sdp_list_append(0, &avrtg); sdp_set_service_classes(record, svclass_id); /* Protocol Descriptor List */ sdp_uuid16_create(&l2cap, L2CAP_UUID); proto[0] = sdp_list_append(0, &l2cap); psm = sdp_data_alloc(SDP_UINT16, &lp); proto[0] = sdp_list_append(proto[0], psm); apseq = sdp_list_append(0, proto[0]); sdp_uuid16_create(&avctp, AVCTP_UUID); proto[1] = sdp_list_append(0, &avctp); version = sdp_data_alloc(SDP_UINT16, &avctp_ver); proto[1] = sdp_list_append(proto[1], version); apseq = sdp_list_append(apseq, proto[1]); aproto = sdp_list_append(0, apseq); sdp_set_access_protos(record, aproto); /* Bluetooth Profile Descriptor List */ sdp_uuid16_create(&profile[0].uuid, AV_REMOTE_PROFILE_ID); profile[0].version = avrcp_ver; pfseq = sdp_list_append(0, &profile[0]); sdp_set_profile_descs(record, pfseq); features = sdp_data_alloc(SDP_UINT16, &feat); sdp_attr_add(record, SDP_ATTR_SUPPORTED_FEATURES, features); sdp_set_info_attr(record, "AVRCP TG", 0, 0); free(psm); free(version); sdp_list_free(proto[0], 0); sdp_list_free(proto[1], 0); sdp_list_free(apseq, 0); sdp_list_free(aproto, 0); sdp_list_free(pfseq, 0); sdp_list_free(root, 0); sdp_list_free(svclass_id, 0); return record; } static int send_event(int fd, uint16_t type, uint16_t code, int32_t value) { struct uinput_event event; memset(&event, 0, sizeof(event)); event.type = type; event.code = code; event.value = value; return write(fd, &event, sizeof(event)); } static void send_key(int fd, uint16_t key, int pressed) { if (fd < 0) return; send_event(fd, EV_KEY, key, pressed); send_event(fd, EV_SYN, SYN_REPORT, 0); } static void handle_panel_passthrough(struct control *control, const unsigned char *operands, int operand_count) { const char *status; int pressed, i; if (operand_count == 0) return; if (operands[0] & 0x80) { status = "released"; pressed = 0; } else { status = "pressed"; pressed = 1; } for (i = 0; key_map[i].name != NULL; i++) { uint8_t key_quirks; if ((operands[0] & 0x7F) != key_map[i].avrcp) continue; DBG("AVRCP: %s %s", key_map[i].name, status); key_quirks = control->key_quirks[key_map[i].avrcp]; if (key_quirks & QUIRK_NO_RELEASE) { if (!pressed) { DBG("AVRCP: Ignoring release"); break; } DBG("AVRCP: treating key press as press + release"); send_key(control->uinput, key_map[i].uinput, 1); send_key(control->uinput, key_map[i].uinput, 0); break; } send_key(control->uinput, key_map[i].uinput, pressed); break; } if (key_map[i].name == NULL) DBG("AVRCP: unknown button 0x%02X %s", operands[0] & 0x7F, status); } static void avctp_disconnected(struct audio_device *dev) { struct control *control = dev->control; if (!control) return; if (control->io) { g_io_channel_shutdown(control->io, TRUE, NULL); g_io_channel_unref(control->io); control->io = NULL; } if (control->io_id) { g_source_remove(control->io_id); control->io_id = 0; if (control->state == AVCTP_STATE_CONNECTING) audio_device_cancel_authorization(dev, auth_cb, control); } if (control->uinput >= 0) { char address[18]; ba2str(&dev->dst, address); DBG("AVRCP: closing uinput for %s", address); ioctl(control->uinput, UI_DEV_DESTROY); close(control->uinput); control->uinput = -1; } } static void avctp_set_state(struct control *control, avctp_state_t new_state) { GSList *l; struct audio_device *dev = control->dev; avctp_state_t old_state = control->state; gboolean value; switch (new_state) { case AVCTP_STATE_DISCONNECTED: DBG("AVCTP Disconnected"); avctp_disconnected(control->dev); if (old_state != AVCTP_STATE_CONNECTED) break; value = FALSE; g_dbus_emit_signal(dev->conn, dev->path, AUDIO_CONTROL_INTERFACE, "Disconnected", DBUS_TYPE_INVALID); emit_property_changed(dev->conn, dev->path, AUDIO_CONTROL_INTERFACE, "Connected", DBUS_TYPE_BOOLEAN, &value); if (!audio_device_is_active(dev, NULL)) audio_device_set_authorized(dev, FALSE); break; case AVCTP_STATE_CONNECTING: DBG("AVCTP Connecting"); break; case AVCTP_STATE_CONNECTED: DBG("AVCTP Connected"); value = TRUE; g_dbus_emit_signal(control->dev->conn, control->dev->path, AUDIO_CONTROL_INTERFACE, "Connected", DBUS_TYPE_INVALID); emit_property_changed(control->dev->conn, control->dev->path, AUDIO_CONTROL_INTERFACE, "Connected", DBUS_TYPE_BOOLEAN, &value); break; default: error("Invalid AVCTP state %d", new_state); return; } control->state = new_state; for (l = avctp_callbacks; l != NULL; l = l->next) { struct avctp_state_callback *cb = l->data; cb->cb(control->dev, old_state, new_state, cb->user_data); } } static gboolean control_cb(GIOChannel *chan, GIOCondition cond, gpointer data) { struct control *control = data; unsigned char buf[1024], *operands; struct avctp_header *avctp; struct avrcp_header *avrcp; int ret, packet_size, operand_count, sock; if (cond & (G_IO_ERR | G_IO_HUP | G_IO_NVAL)) goto failed; sock = g_io_channel_unix_get_fd(control->io); ret = read(sock, buf, sizeof(buf)); if (ret <= 0) goto failed; DBG("Got %d bytes of data for AVCTP session %p", ret, control); if ((unsigned int) ret < sizeof(struct avctp_header)) { error("Too small AVCTP packet"); goto failed; } packet_size = ret; avctp = (struct avctp_header *) buf; DBG("AVCTP transaction %u, packet type %u, C/R %u, IPID %u, " "PID 0x%04X", avctp->transaction, avctp->packet_type, avctp->cr, avctp->ipid, ntohs(avctp->pid)); ret -= sizeof(struct avctp_header); if ((unsigned int) ret < sizeof(struct avrcp_header)) { error("Too small AVRCP packet"); goto failed; } avrcp = (struct avrcp_header *) (buf + sizeof(struct avctp_header)); ret -= sizeof(struct avrcp_header); operands = buf + sizeof(struct avctp_header) + sizeof(struct avrcp_header); operand_count = ret; DBG("AVRCP %s 0x%01X, subunit_type 0x%02X, subunit_id 0x%01X, " "opcode 0x%02X, %d operands", avctp->cr ? "response" : "command", avrcp->code, avrcp->subunit_type, avrcp->subunit_id, avrcp->opcode, operand_count); if (avctp->packet_type != AVCTP_PACKET_SINGLE) { avctp->cr = AVCTP_RESPONSE; avrcp->code = CTYPE_NOT_IMPLEMENTED; } else if (avctp->pid != htons(AV_REMOTE_SVCLASS_ID)) { avctp->ipid = 1; avctp->cr = AVCTP_RESPONSE; avrcp->code = CTYPE_REJECTED; } else if (avctp->cr == AVCTP_COMMAND && avrcp->code == CTYPE_CONTROL && avrcp->subunit_type == SUBUNIT_PANEL && avrcp->opcode == OP_PASSTHROUGH) { handle_panel_passthrough(control, operands, operand_count); avctp->cr = AVCTP_RESPONSE; avrcp->code = CTYPE_ACCEPTED; } else if (avctp->cr == AVCTP_COMMAND && avrcp->code == CTYPE_STATUS && (avrcp->opcode == OP_UNITINFO || avrcp->opcode == OP_SUBUNITINFO)) { avctp->cr = AVCTP_RESPONSE; avrcp->code = CTYPE_STABLE; /* The first operand should be 0x07 for the UNITINFO response. * Neither AVRCP (section 22.1, page 117) nor AVC Digital * Interface Command Set (section 9.2.1, page 45) specs * explain this value but both use it */ if (operand_count >= 1 && avrcp->opcode == OP_UNITINFO) operands[0] = 0x07; if (operand_count >= 2) operands[1] = SUBUNIT_PANEL << 3; DBG("reply to %s", avrcp->opcode == OP_UNITINFO ? "OP_UNITINFO" : "OP_SUBUNITINFO"); } else { avctp->cr = AVCTP_RESPONSE; avrcp->code = CTYPE_REJECTED; } ret = write(sock, buf, packet_size); if (ret != packet_size) goto failed; return TRUE; failed: DBG("AVCTP session %p got disconnected", control); avctp_set_state(control, AVCTP_STATE_DISCONNECTED); return FALSE; } static int uinput_create(char *name) { struct uinput_dev dev; int fd, err, i; fd = open("/dev/uinput", O_RDWR); if (fd < 0) { fd = open("/dev/input/uinput", O_RDWR); if (fd < 0) { fd = open("/dev/misc/uinput", O_RDWR); if (fd < 0) { err = errno; error("Can't open input device: %s (%d)", strerror(err), err); return -err; } } } memset(&dev, 0, sizeof(dev)); if (name) strncpy(dev.name, name, UINPUT_MAX_NAME_SIZE - 1); dev.id.bustype = BUS_BLUETOOTH; dev.id.vendor = 0x0000; dev.id.product = 0x0000; dev.id.version = 0x0000; if (write(fd, &dev, sizeof(dev)) < 0) { err = errno; error("Can't write device information: %s (%d)", strerror(err), err); close(fd); errno = err; return -err; } ioctl(fd, UI_SET_EVBIT, EV_KEY); ioctl(fd, UI_SET_EVBIT, EV_REL); ioctl(fd, UI_SET_EVBIT, EV_REP); ioctl(fd, UI_SET_EVBIT, EV_SYN); for (i = 0; key_map[i].name != NULL; i++) ioctl(fd, UI_SET_KEYBIT, key_map[i].uinput); if (ioctl(fd, UI_DEV_CREATE, NULL) < 0) { err = errno; error("Can't create uinput device: %s (%d)", strerror(err), err); close(fd); errno = err; return -err; } return fd; } static void init_uinput(struct control *control) { struct audio_device *dev = control->dev; char address[18], name[248 + 1], *uinput_dev_name; device_get_name(dev->btd_dev, name, sizeof(name)); if (g_str_equal(name, "Nokia CK-20W")) { control->key_quirks[FORWARD_OP] |= QUIRK_NO_RELEASE; control->key_quirks[BACKWARD_OP] |= QUIRK_NO_RELEASE; control->key_quirks[PLAY_OP] |= QUIRK_NO_RELEASE; control->key_quirks[PAUSE_OP] |= QUIRK_NO_RELEASE; } ba2str(&dev->dst, address); /* Use device name from config file if specified */ uinput_dev_name = input_device_name; if (!uinput_dev_name) uinput_dev_name = address; control->uinput = uinput_create(uinput_dev_name); if (control->uinput < 0) error("AVRCP: failed to init uinput for %s", address); else DBG("AVRCP: uinput initialized for %s", address); } static void avctp_connect_cb(GIOChannel *chan, GError *err, gpointer data) { struct control *control = data; char address[18]; uint16_t imtu; GError *gerr = NULL; if (err) { avctp_set_state(control, AVCTP_STATE_DISCONNECTED); error("%s", err->message); return; } bt_io_get(chan, BT_IO_L2CAP, &gerr, BT_IO_OPT_DEST, &address, BT_IO_OPT_IMTU, &imtu, BT_IO_OPT_INVALID); if (gerr) { avctp_set_state(control, AVCTP_STATE_DISCONNECTED); error("%s", gerr->message); g_error_free(gerr); return; } DBG("AVCTP: connected to %s", address); if (!control->io) control->io = g_io_channel_ref(chan); init_uinput(control); avctp_set_state(control, AVCTP_STATE_CONNECTED); control->mtu = imtu; control->io_id = g_io_add_watch(chan, G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL, (GIOFunc) control_cb, control); } static void auth_cb(DBusError *derr, void *user_data) { struct control *control = user_data; GError *err = NULL; if (control->io_id) { g_source_remove(control->io_id); control->io_id = 0; } if (derr && dbus_error_is_set(derr)) { error("Access denied: %s", derr->message); avctp_set_state(control, AVCTP_STATE_DISCONNECTED); return; } if (!bt_io_accept(control->io, avctp_connect_cb, control, NULL, &err)) { error("bt_io_accept: %s", err->message); g_error_free(err); avctp_set_state(control, AVCTP_STATE_DISCONNECTED); } } static void avctp_confirm_cb(GIOChannel *chan, gpointer data) { struct control *control = NULL; struct audio_device *dev; char address[18]; bdaddr_t src, dst; GError *err = NULL; bt_io_get(chan, BT_IO_L2CAP, &err, BT_IO_OPT_SOURCE_BDADDR, &src, BT_IO_OPT_DEST_BDADDR, &dst, BT_IO_OPT_DEST, address, BT_IO_OPT_INVALID); if (err) { error("%s", err->message); g_error_free(err); g_io_channel_shutdown(chan, TRUE, NULL); return; } dev = manager_get_device(&src, &dst, TRUE); if (!dev) { error("Unable to get audio device object for %s", address); goto drop; } if (!dev->control) { btd_device_add_uuid(dev->btd_dev, AVRCP_REMOTE_UUID); if (!dev->control) goto drop; } control = dev->control; if (control->io) { error("Refusing unexpected connect from %s", address); goto drop; } avctp_set_state(control, AVCTP_STATE_CONNECTING); control->io = g_io_channel_ref(chan); if (audio_device_request_authorization(dev, AVRCP_TARGET_UUID, auth_cb, dev->control) < 0) goto drop; control->io_id = g_io_add_watch(chan, G_IO_ERR | G_IO_HUP | G_IO_NVAL, control_cb, control); return; drop: if (!control || !control->io) g_io_channel_shutdown(chan, TRUE, NULL); if (control) avctp_set_state(control, AVCTP_STATE_DISCONNECTED); } static GIOChannel *avctp_server_socket(const bdaddr_t *src, gboolean master) { GError *err = NULL; GIOChannel *io; io = bt_io_listen(BT_IO_L2CAP, NULL, avctp_confirm_cb, NULL, NULL, &err, BT_IO_OPT_SOURCE_BDADDR, src, BT_IO_OPT_PSM, AVCTP_PSM, BT_IO_OPT_SEC_LEVEL, BT_IO_SEC_MEDIUM, BT_IO_OPT_MASTER, master, BT_IO_OPT_INVALID); if (!io) { error("%s", err->message); g_error_free(err); } return io; } gboolean avrcp_connect(struct audio_device *dev) { struct control *control = dev->control; GError *err = NULL; GIOChannel *io; if (control->state > AVCTP_STATE_DISCONNECTED) return TRUE; avctp_set_state(control, AVCTP_STATE_CONNECTING); io = bt_io_connect(BT_IO_L2CAP, avctp_connect_cb, control, NULL, &err, BT_IO_OPT_SOURCE_BDADDR, &dev->src, BT_IO_OPT_DEST_BDADDR, &dev->dst, BT_IO_OPT_PSM, AVCTP_PSM, BT_IO_OPT_INVALID); if (err) { avctp_set_state(control, AVCTP_STATE_DISCONNECTED); error("%s", err->message); g_error_free(err); return FALSE; } control->io = io; return TRUE; } void avrcp_disconnect(struct audio_device *dev) { struct control *control = dev->control; if (!(control && control->io)) return; avctp_set_state(control, AVCTP_STATE_DISCONNECTED); } int avrcp_register(DBusConnection *conn, const bdaddr_t *src, GKeyFile *config) { sdp_record_t *record; gboolean tmp, master = TRUE; GError *err = NULL; struct avctp_server *server; if (config) { tmp = g_key_file_get_boolean(config, "General", "Master", &err); if (err) { DBG("audio.conf: %s", err->message); g_error_free(err); } else master = tmp; err = NULL; input_device_name = g_key_file_get_string(config, "AVRCP", "InputDeviceName", &err); if (err) { DBG("audio.conf: %s", err->message); input_device_name = NULL; g_error_free(err); } } server = g_new0(struct avctp_server, 1); if (!server) return -ENOMEM; if (!connection) connection = dbus_connection_ref(conn); record = avrcp_tg_record(); if (!record) { error("Unable to allocate new service record"); g_free(server); return -1; } if (add_record_to_server(src, record) < 0) { error("Unable to register AVRCP target service record"); g_free(server); sdp_record_free(record); return -1; } server->tg_record_id = record->handle; #ifndef ANDROID record = avrcp_ct_record(); if (!record) { error("Unable to allocate new service record"); g_free(server); return -1; } if (add_record_to_server(src, record) < 0) { error("Unable to register AVRCP controller service record"); sdp_record_free(record); g_free(server); return -1; } server->ct_record_id = record->handle; #endif server->io = avctp_server_socket(src, master); if (!server->io) { #ifndef ANDROID remove_record_from_server(server->ct_record_id); #endif remove_record_from_server(server->tg_record_id); g_free(server); return -1; } bacpy(&server->src, src); servers = g_slist_append(servers, server); return 0; } static struct avctp_server *find_server(GSList *list, const bdaddr_t *src) { for (; list; list = list->next) { struct avctp_server *server = list->data; if (bacmp(&server->src, src) == 0) return server; } return NULL; } void avrcp_unregister(const bdaddr_t *src) { struct avctp_server *server; server = find_server(servers, src); if (!server) return; servers = g_slist_remove(servers, server); #ifndef ANDROID remove_record_from_server(server->ct_record_id); #endif remove_record_from_server(server->tg_record_id); g_io_channel_shutdown(server->io, TRUE, NULL); g_io_channel_unref(server->io); g_free(server); if (servers) return; dbus_connection_unref(connection); connection = NULL; } static DBusMessage *control_is_connected(DBusConnection *conn, DBusMessage *msg, void *data) { struct audio_device *device = data; struct control *control = device->control; DBusMessage *reply; dbus_bool_t connected; reply = dbus_message_new_method_return(msg); if (!reply) return NULL; connected = (control->state == AVCTP_STATE_CONNECTED); dbus_message_append_args(reply, DBUS_TYPE_BOOLEAN, &connected, DBUS_TYPE_INVALID); return reply; } static int avctp_send_passthrough(struct control *control, uint8_t op) { unsigned char buf[AVCTP_HEADER_LENGTH + AVRCP_HEADER_LENGTH + 2]; struct avctp_header *avctp = (void *) buf; struct avrcp_header *avrcp = (void *) &buf[AVCTP_HEADER_LENGTH]; uint8_t *operands = &buf[AVCTP_HEADER_LENGTH + AVRCP_HEADER_LENGTH]; int sk = g_io_channel_unix_get_fd(control->io); static uint8_t transaction = 0; memset(buf, 0, sizeof(buf)); avctp->transaction = transaction++; avctp->packet_type = AVCTP_PACKET_SINGLE; avctp->cr = AVCTP_COMMAND; avctp->pid = htons(AV_REMOTE_SVCLASS_ID); avrcp->code = CTYPE_CONTROL; avrcp->subunit_type = SUBUNIT_PANEL; avrcp->opcode = OP_PASSTHROUGH; operands[0] = op & 0x7f; operands[1] = 0; if (write(sk, buf, sizeof(buf)) < 0) return -errno; /* Button release */ avctp->transaction = transaction++; operands[0] |= 0x80; if (write(sk, buf, sizeof(buf)) < 0) return -errno; return 0; } static DBusMessage *volume_up(DBusConnection *conn, DBusMessage *msg, void *data) { struct audio_device *device = data; struct control *control = device->control; DBusMessage *reply; int err; reply = dbus_message_new_method_return(msg); if (!reply) return NULL; if (control->state != AVCTP_STATE_CONNECTED) return btd_error_not_connected(msg); if (!control->target) return btd_error_not_supported(msg); err = avctp_send_passthrough(control, VOL_UP_OP); if (err < 0) return btd_error_failed(msg, strerror(-err)); return dbus_message_new_method_return(msg); } static DBusMessage *volume_down(DBusConnection *conn, DBusMessage *msg, void *data) { struct audio_device *device = data; struct control *control = device->control; DBusMessage *reply; int err; reply = dbus_message_new_method_return(msg); if (!reply) return NULL; if (control->state != AVCTP_STATE_CONNECTED) return btd_error_not_connected(msg); if (!control->target) return btd_error_not_supported(msg); err = avctp_send_passthrough(control, VOL_DOWN_OP); if (err < 0) return btd_error_failed(msg, strerror(-err)); return dbus_message_new_method_return(msg); } static DBusMessage *control_get_properties(DBusConnection *conn, DBusMessage *msg, void *data) { struct audio_device *device = data; DBusMessage *reply; DBusMessageIter iter; DBusMessageIter dict; gboolean value; reply = dbus_message_new_method_return(msg); if (!reply) return NULL; dbus_message_iter_init_append(reply, &iter); dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING DBUS_TYPE_STRING_AS_STRING DBUS_TYPE_VARIANT_AS_STRING DBUS_DICT_ENTRY_END_CHAR_AS_STRING, &dict); /* Connected */ value = (device->control->state == AVCTP_STATE_CONNECTED); dict_append_entry(&dict, "Connected", DBUS_TYPE_BOOLEAN, &value); dbus_message_iter_close_container(&iter, &dict); return reply; } static GDBusMethodTable control_methods[] = { { "IsConnected", "", "b", control_is_connected, G_DBUS_METHOD_FLAG_DEPRECATED }, { "GetProperties", "", "a{sv}",control_get_properties }, { "VolumeUp", "", "", volume_up }, { "VolumeDown", "", "", volume_down }, { NULL, NULL, NULL, NULL } }; static GDBusSignalTable control_signals[] = { { "Connected", "", G_DBUS_SIGNAL_FLAG_DEPRECATED}, { "Disconnected", "", G_DBUS_SIGNAL_FLAG_DEPRECATED}, { "PropertyChanged", "sv" }, { NULL, NULL } }; static void path_unregister(void *data) { struct audio_device *dev = data; struct control *control = dev->control; DBG("Unregistered interface %s on path %s", AUDIO_CONTROL_INTERFACE, dev->path); if (control->state != AVCTP_STATE_DISCONNECTED) avctp_disconnected(dev); g_free(control); dev->control = NULL; } void control_unregister(struct audio_device *dev) { g_dbus_unregister_interface(dev->conn, dev->path, AUDIO_CONTROL_INTERFACE); } void control_update(struct audio_device *dev, uint16_t uuid16) { struct control *control = dev->control; if (uuid16 == AV_REMOTE_TARGET_SVCLASS_ID) control->target = TRUE; } struct control *control_init(struct audio_device *dev, uint16_t uuid16) { struct control *control; if (!g_dbus_register_interface(dev->conn, dev->path, AUDIO_CONTROL_INTERFACE, control_methods, control_signals, NULL, dev, path_unregister)) return NULL; DBG("Registered interface %s on path %s", AUDIO_CONTROL_INTERFACE, dev->path); control = g_new0(struct control, 1); control->dev = dev; control->state = AVCTP_STATE_DISCONNECTED; control->uinput = -1; if (uuid16 == AV_REMOTE_TARGET_SVCLASS_ID) control->target = TRUE; return control; } gboolean control_is_active(struct audio_device *dev) { struct control *control = dev->control; if (control && control->state != AVCTP_STATE_DISCONNECTED) return TRUE; return FALSE; } unsigned int avctp_add_state_cb(avctp_state_cb cb, void *user_data) { struct avctp_state_callback *state_cb; static unsigned int id = 0; state_cb = g_new(struct avctp_state_callback, 1); state_cb->cb = cb; state_cb->user_data = user_data; state_cb->id = ++id; avctp_callbacks = g_slist_append(avctp_callbacks, state_cb); return state_cb->id; } gboolean avctp_remove_state_cb(unsigned int id) { GSList *l; for (l = avctp_callbacks; l != NULL; l = l->next) { struct avctp_state_callback *cb = l->data; if (cb && cb->id == id) { avctp_callbacks = g_slist_remove(avctp_callbacks, cb); g_free(cb); return TRUE; } } return FALSE; }
<filename>src/gate_visual.h /** * @file gate_visual.h * @date 08/2020 * @author <NAME> * @brief contains the parameters used to control a gate's visualization */ #ifndef QL_GATE_VISUAL_H #define QL_GATE_VISUAL_H namespace ql { enum NodeType {NONE, GATE, CONTROL, NOT, CROSS}; struct Node { NodeType type; unsigned int radius; std::string displayName; unsigned int fontHeight; std::array<unsigned char, 3> fontColor; std::array<unsigned char, 3> backgroundColor; std::array<unsigned char, 3> outlineColor; }; struct GateVisual { std::array<unsigned char, 3> connectionColor; std::vector<Node> nodes; }; } // ql #endif //QL_GATE_VISUAL_H
<reponame>hengxin/jepsen-in-cpp<filename>src/jepsen/generator/GeneratorFactory.h // // Created by Young on 2022/3/28. // #ifndef JEPSEN_IN_CPP_GENERATORFACTORY_H #define JEPSEN_IN_CPP_GENERATORFACTORY_H #include "Generator.h" namespace jepsen { namespace generator { class GeneratorFactory { public: static GeneratorPtr createNullptrGenerator() { return nullptr; } static OperationGeneratorPtr createGenerator(Operation op) { return std::make_shared<OperationGenerator>(OperationGenerator(op)); } static FunctionGeneratorPtr createGenerator( const std::function<Operation(Context)> func_with_context) { return std::make_shared<FunctionGenerator>(FunctionGenerator(func_with_context)); } static FunctionGeneratorPtr createGenerator(const std::function<Operation()>& func_base) { return std::make_shared<FunctionGenerator>(FunctionGenerator(std::move(func_base))); } static ListGeneratorPtr createGenerator(const std::list<Operation>& operations) { std::list<GeneratorPtr> generators; for (auto& op : operations) { generators.push_back(createGenerator(op)); } return std::make_shared<ListGenerator>(generators); } static ListGeneratorPtr createGenerator(const std::list<GeneratorPtr>& generators) { return std::make_shared<ListGenerator>(ListGenerator(generators)); } static ValidatePtr createValidate(GeneratorPtr gen) { return std::make_shared<Validate>(gen); } static OnThreadsPtr createOnThreads(GeneratorPtr gen, std::function<bool(int)> filter) { return std::make_shared<OnThreads>(gen, filter); } static TimeLimitPtr createTimeLimit(long dt, GeneratorPtr gen) { return std::make_shared<TimeLimit>(dt, gen); } static TimeLimitPtr createTimeLimit(long dt, long cutoff, GeneratorPtr gen) { return std::make_shared<TimeLimit>(dt, cutoff, gen); } static StaggerPtr createStagger(long dt, GeneratorPtr gen) { return std::make_shared<Stagger>(dt, gen); } static StaggerPtr createStagger(long dt, long next_time, GeneratorPtr gen) { return std::make_shared<Stagger>(dt, next_time, gen); } static MixPtr createMix(int idx, std::vector<GeneratorPtr> gens) { return std::make_shared<Mix>(idx, gens); } static AnyPtr createAny(std::vector<GeneratorPtr> gens) { return std::make_shared<Any>(gens); } }; } // namespace generator } // namespace jepsen #endif // JEPSEN_IN_CPP_GENERATORFACTORY_H
#pragma once #include <chrono> #include <fcntl.h> #include <unistd.h> #include <utility> #include "bdm/exception/bdm_system_exception.hxx" namespace bdm { class unique_fd { public: using fd_type = int; static constexpr fd_type invalid_fd = -1; static unique_fd open(const char* pathname, int flags); unique_fd(); explicit unique_fd(int); unique_fd(const unique_fd&) = delete; unique_fd(unique_fd&&) noexcept; unique_fd& operator=(const unique_fd&) = delete; unique_fd& operator=(unique_fd&&) noexcept; ~unique_fd(); explicit operator fd_type(); fd_type get(); explicit operator bool() const; private: fd_type _fd; }; inline unique_fd unique_fd::open(const char* pathname, int flags) { int fd = ::open(pathname, flags); if (fd == -1) { BDM_THROW_EXCEPTION(bdm::exception::bdm_system_exception(errno, std::system_category())); } return unique_fd(fd); } inline unique_fd::unique_fd() : _fd(invalid_fd) {} inline unique_fd::unique_fd(int fd) : _fd(fd) {} inline unique_fd::unique_fd(unique_fd&& fd) noexcept { *this = std::move(fd); } inline unique_fd& unique_fd::operator=(unique_fd&& another) noexcept { _fd = another._fd; another._fd = invalid_fd; return *this; } inline unique_fd::~unique_fd() { if (*this) { int result = close(_fd); (void) result; } } inline unique_fd::operator fd_type() { return _fd; } inline unique_fd::fd_type unique_fd::get() { return _fd; } inline unique_fd::operator bool() const { return _fd >= 0; } }
<filename>src/common/template/metann/policies/change_policy.h #pragma once #include <MetaNN/policies/policy_container.h> namespace MetaNN { template <typename TNewPolicy, typename TOriContainer> struct ChangePolicy_; template <typename TNewPolicy, typename... TPolicies> struct ChangePolicy_<TNewPolicy, PolicyContainer<TPolicies...>> { private: using newMajor = typename TNewPolicy::MajorClass; using newMinor = typename TNewPolicy::MinorClass; template <typename TPC, typename... TP> struct DropAppend_; template <typename... TFilteredPolicies> struct DropAppend_<PolicyContainer<TFilteredPolicies...>> { using type = PolicyContainer<TFilteredPolicies..., TNewPolicy>; }; template <typename... TFilteredPolicies, typename TCurPolicy, typename... TP> struct DropAppend_<PolicyContainer<TFilteredPolicies...>, TCurPolicy, TP...> { template <bool isArray, typename TDummy = void> struct ArrayBasedSwitch_ { template <typename TMajor, typename TMinor, typename TD = void> struct _impl { using type = PolicyContainer<TFilteredPolicies..., TCurPolicy>; }; template <typename TD> struct _impl<newMajor, newMinor, TD> { using type = PolicyContainer<TFilteredPolicies...>; }; using type = typename _impl<typename TCurPolicy::MajorClass, typename TCurPolicy::MinorClass>::type; }; template <typename TDummy> struct ArrayBasedSwitch_<true, TDummy> { using type = PolicyContainer<TFilteredPolicies..., TCurPolicy>; }; using t1 = typename ArrayBasedSwitch_<IsSubPolicyContainer<TCurPolicy>>::type; using type = typename DropAppend_<t1, TP...>::type; }; public: using type = typename DropAppend_<PolicyContainer<>, TPolicies...>::type; }; template <typename TNewPolicy, typename TOriContainer> using ChangePolicy = typename ChangePolicy_<TNewPolicy, TOriContainer>::type; }
<filename>aliyun-api-ram/2015-05-01/include/ali_ram_get_user_types.h #ifndef ALI_RAM_GET_USER_TYPESH #define ALI_RAM_GET_USER_TYPESH #include <stdio.h> #include <string> #include <vector> namespace aliyun { struct RamGetUserRequestType { std::string user_name; }; struct RamGetUserUserType { std::string user_id; std::string user_name; std::string display_name; std::string mobile_phone; std::string email; std::string comments; std::string create_date; std::string update_date; std::string last_login_date; }; struct RamGetUserResponseType { RamGetUserUserType user; }; } // end namespace #endif
<gh_stars>10-100 /* $NoKeywords: $ */ /* // // Copyright (c) 1993-2018 <NAME> & Associates. All rights reserved. // OpenNURBS, Rhinoceros, and Rhino3D are registered trademarks of Robert // McNeel & Associates. // // THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY. // ALL IMPLIED WARRANTIES OF FITNESS FOR ANY PARTICULAR PURPOSE AND OF // MERCHANTABILITY ARE HEREBY DISCLAIMED. // // For complete openNURBS copyright information see <http://www.opennurbs.org>. // //////////////////////////////////////////////////////////////// */ #if !defined(OPENNURBS_ATOMIC_OP_INC_) #define OPENNURBS_ATOMIC_OP_INC_ /* Description: Expert user tool to decrement the value of the parameter as an atomic operation. Parameters: ptr_int32 - [in] A non-null pointer to a signed 32-bit integer. Returns: Decremented value. Example: int i = 3; // j will be 2 int j = ON_AtomicDecrementInt32(&i); Remarks: Caller is responsible for insuring ptr_int32 is not nullptr. */ // ON_AtomicDecrementInt32(int* ptr_int32) /* Description: Expert user tool to increment the value of the parameter as an atomic operation. Parameters: ptr_int32 - [in] A non-null pointer to a signed 32-bit integer. Returns: Incremented value. Example: int i = 3; // j will be 4 int j = ON_AtomicIncrementInt32(&i); Remarks: Caller is responsible for insuring ptr_int32 points to a signed 32-bit integer. */ // ON_AtomicIncrementInt32(int* ptr_int32) #if defined(ON_RUNTIME_WIN) #define ON_AtomicDecrementInt32(ptr_int32) InterlockedDecrement((long*)(ptr_int32)) #define ON_AtomicIncrementInt32(ptr_int32) InterlockedIncrement((long*)(ptr_int32)) #elif defined(ON_RUNTIME_APPLE_MACOS) #include <libkern/OSAtomic.h> #define ON_AtomicDecrementInt32(ptr_int32) OSAtomicDecrement32((int*)(ptr_int32)) #define ON_AtomicIncrementInt32(ptr_int32) OSAtomicIncrement32((int*)(ptr_int32)) #else // NOT thread safe #define ON_AtomicDecrementInt32(ptr_int32) (--(*ptr_int32)) #define ON_AtomicIncrementInt32(ptr_int32) (++(*ptr_int32)) #endif #endif
/* * m_police.c Parse/print policing module options. * * This program is free software; you can u32istribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Authors: <NAME>, <<EMAIL>> * FIXES: 19990619 - <NAME> (<EMAIL>) * simple addattr packaging fix. * 2002: <NAME> - Add tc action extensions syntax * */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <syslog.h> #include <fcntl.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string.h> #include "utils.h" #include "tc_util.h" struct action_util police_action_util = { .id = "police", .parse_aopt = act_parse_police, .print_aopt = print_police, }; static void usage(void) { fprintf(stderr, "Usage: ... police rate BPS burst BYTES[/BYTES] [ mtu BYTES[/BYTES] ]\n"); fprintf(stderr, " [ peakrate BPS ] [ avrate BPS ]\n"); fprintf(stderr, " [ ACTIONTERM ]\n"); fprintf(stderr, "Old Syntax ACTIONTERM := action <EXCEEDACT>[/NOTEXCEEDACT] \n"); fprintf(stderr, "New Syntax ACTIONTERM := conform-exceed <EXCEEDACT>[/NOTEXCEEDACT] \n"); fprintf(stderr, "Where: *EXCEEDACT := pipe | ok | reclassify | drop | continue \n"); fprintf(stderr, "Where: pipe is only valid for new syntax \n"); exit(-1); } static void explain1(char *arg) { fprintf(stderr, "Illegal \"%s\"\n", arg); } char *police_action_n2a(int action, char *buf, int len) { switch (action) { case -1: return "continue"; break; case TC_POLICE_OK: return "pass"; break; case TC_POLICE_SHOT: return "drop"; break; case TC_POLICE_RECLASSIFY: return "reclassify"; case TC_POLICE_PIPE: return "pipe"; default: snprintf(buf, len, "%d", action); return buf; } } int police_action_a2n(char *arg, int *result) { int res; if (matches(arg, "continue") == 0) res = -1; else if (matches(arg, "drop") == 0) res = TC_POLICE_SHOT; else if (matches(arg, "shot") == 0) res = TC_POLICE_SHOT; else if (matches(arg, "pass") == 0) res = TC_POLICE_OK; else if (strcmp(arg, "ok") == 0) res = TC_POLICE_OK; else if (matches(arg, "reclassify") == 0) res = TC_POLICE_RECLASSIFY; else if (matches(arg, "pipe") == 0) res = TC_POLICE_PIPE; else { char dummy; if (sscanf(arg, "%d%c", &res, &dummy) != 1) return -1; } *result = res; return 0; } int get_police_result(int *action, int *result, char *arg) { char *p = strchr(arg, '/'); if (p) *p = 0; if (police_action_a2n(arg, action)) { if (p) *p = '/'; return -1; } if (p) { *p = '/'; if (police_action_a2n(p+1, result)) return -1; } return 0; } int act_parse_police(struct action_util *a,int *argc_p, char ***argv_p, int tca_id, struct nlmsghdr *n) { int argc = *argc_p; char **argv = *argv_p; int res = -1; int ok=0; struct tc_police p; __u32 rtab[256]; __u32 ptab[256]; __u32 avrate = 0; int presult = 0; unsigned buffer=0, mtu=0, mpu=0; int Rcell_log=-1, Pcell_log = -1; struct rtattr *tail; memset(&p, 0, sizeof(p)); p.action = TC_POLICE_RECLASSIFY; if (a) /* new way of doing things */ NEXT_ARG(); if (argc <= 0) return -1; while (argc > 0) { if (matches(*argv, "index") == 0) { NEXT_ARG(); if (get_u32(&p.index, *argv, 10)) { fprintf(stderr, "Illegal \"index\"\n"); return -1; } } else if (matches(*argv, "burst") == 0 || strcmp(*argv, "buffer") == 0 || strcmp(*argv, "maxburst") == 0) { NEXT_ARG(); if (buffer) { fprintf(stderr, "Double \"buffer/burst\" spec\n"); return -1; } if (get_size_and_cell(&buffer, &Rcell_log, *argv) < 0) { explain1("buffer"); return -1; } } else if (strcmp(*argv, "mtu") == 0 || strcmp(*argv, "minburst") == 0) { NEXT_ARG(); if (mtu) { fprintf(stderr, "Double \"mtu/minburst\" spec\n"); return -1; } if (get_size_and_cell(&mtu, &Pcell_log, *argv) < 0) { explain1("mtu"); return -1; } } else if (strcmp(*argv, "mpu") == 0) { NEXT_ARG(); if (mpu) { fprintf(stderr, "Double \"mpu\" spec\n"); return -1; } if (get_size(&mpu, *argv)) { explain1("mpu"); return -1; } } else if (strcmp(*argv, "rate") == 0) { NEXT_ARG(); if (p.rate.rate) { fprintf(stderr, "Double \"rate\" spec\n"); return -1; } if (get_rate(&p.rate.rate, *argv)) { explain1("rate"); return -1; } } else if (strcmp(*argv, "avrate") == 0) { NEXT_ARG(); if (avrate) { fprintf(stderr, "Double \"avrate\" spec\n"); return -1; } if (get_rate(&avrate, *argv)) { explain1("avrate"); return -1; } } else if (matches(*argv, "peakrate") == 0) { NEXT_ARG(); if (p.peakrate.rate) { fprintf(stderr, "Double \"peakrate\" spec\n"); return -1; } if (get_rate(&p.peakrate.rate, *argv)) { explain1("peakrate"); return -1; } } else if (matches(*argv, "reclassify") == 0) { p.action = TC_POLICE_RECLASSIFY; } else if (matches(*argv, "drop") == 0 || matches(*argv, "shot") == 0) { p.action = TC_POLICE_SHOT; } else if (matches(*argv, "continue") == 0) { p.action = TC_POLICE_UNSPEC; } else if (matches(*argv, "pass") == 0) { p.action = TC_POLICE_OK; } else if (matches(*argv, "pipe") == 0) { p.action = TC_POLICE_PIPE; } else if (strcmp(*argv, "conform-exceed") == 0) { NEXT_ARG(); if (get_police_result(&p.action, &presult, *argv)) { fprintf(stderr, "Illegal \"action\"\n"); return -1; } } else if (strcmp(*argv, "help") == 0) { usage(); } else { break; } ok++; argc--; argv++; } if (!ok) return -1; if (p.rate.rate && !buffer) { fprintf(stderr, "\"burst\" requires \"rate\".\n"); return -1; } if (p.peakrate.rate) { if (!p.rate.rate) { fprintf(stderr, "\"peakrate\" requires \"rate\".\n"); return -1; } if (!mtu) { fprintf(stderr, "\"mtu\" is required, if \"peakrate\" is requested.\n"); return -1; } } if (p.rate.rate) { if ((Rcell_log = tc_calc_rtable(p.rate.rate, rtab, Rcell_log, mtu, mpu)) < 0) { fprintf(stderr, "TBF: failed to calculate rate table.\n"); return -1; } p.burst = tc_calc_xmittime(p.rate.rate, buffer); p.rate.cell_log = Rcell_log; p.rate.mpu = mpu; } p.mtu = mtu; if (p.peakrate.rate) { if ((Pcell_log = tc_calc_rtable(p.peakrate.rate, ptab, Pcell_log, mtu, mpu)) < 0) { fprintf(stderr, "POLICE: failed to calculate peak rate table.\n"); return -1; } p.peakrate.cell_log = Pcell_log; p.peakrate.mpu = mpu; } tail = NLMSG_TAIL(n); addattr_l(n, MAX_MSG, tca_id, NULL, 0); addattr_l(n, MAX_MSG, TCA_POLICE_TBF, &p, sizeof(p)); if (p.rate.rate) addattr_l(n, MAX_MSG, TCA_POLICE_RATE, rtab, 1024); if (p.peakrate.rate) addattr_l(n, MAX_MSG, TCA_POLICE_PEAKRATE, ptab, 1024); if (avrate) addattr32(n, MAX_MSG, TCA_POLICE_AVRATE, avrate); if (presult) addattr32(n, MAX_MSG, TCA_POLICE_RESULT, presult); tail->rta_len = (void *) NLMSG_TAIL(n) - (void *) tail; res = 0; *argc_p = argc; *argv_p = argv; return res; } int parse_police(int *argc_p, char ***argv_p, int tca_id, struct nlmsghdr *n) { return act_parse_police(NULL,argc_p,argv_p,tca_id,n); } int print_police(struct action_util *a, FILE *f, struct rtattr *arg) { SPRINT_BUF(b1); struct tc_police *p; struct rtattr *tb[TCA_POLICE_MAX+1]; unsigned buffer; if (arg == NULL) return 0; parse_rtattr_nested(tb, TCA_POLICE_MAX, arg); if (tb[TCA_POLICE_TBF] == NULL) { fprintf(f, "[NULL police tbf]"); return 0; } #ifndef STOOPID_8BYTE if (RTA_PAYLOAD(tb[TCA_POLICE_TBF]) < sizeof(*p)) { fprintf(f, "[truncated police tbf]"); return -1; } #endif p = RTA_DATA(tb[TCA_POLICE_TBF]); fprintf(f, " police 0x%x ", p->index); fprintf(f, "rate %s ", sprint_rate(p->rate.rate, b1)); buffer = tc_calc_xmitsize(p->rate.rate, p->burst); fprintf(f, "burst %s ", sprint_size(buffer, b1)); fprintf(f, "mtu %s ", sprint_size(p->mtu, b1)); if (show_raw) fprintf(f, "[%08x] ", p->burst); if (p->peakrate.rate) fprintf(f, "peakrate %s ", sprint_rate(p->peakrate.rate, b1)); if (tb[TCA_POLICE_AVRATE]) fprintf(f, "avrate %s ", sprint_rate(*(__u32*)RTA_DATA(tb[TCA_POLICE_AVRATE]), b1)); fprintf(f, "action %s", police_action_n2a(p->action, b1, sizeof(b1))); if (tb[TCA_POLICE_RESULT]) { fprintf(f, "/%s ", police_action_n2a(*(int*)RTA_DATA(tb[TCA_POLICE_RESULT]), b1, sizeof(b1))); } else fprintf(f, " "); fprintf(f, "\nref %d bind %d\n",p->refcnt, p->bindcnt); return 0; } int tc_print_police(FILE *f, struct rtattr *arg) { return print_police(&police_action_util,f,arg); }
<reponame>ukos-git/arduino-reactor<gh_stars>0 #ifndef MKMODBUS_H #define MKMODBUS_H #include <Arduino.h> #include <SoftwareSerial.h> #define rxPinOven 8 #define txPinOven 9 #define MAX_BUFFER 64 class MKModbus { public: MKModbus(SoftwareSerial &SoftwareRS232) ; //Constructor ~MKModbus(); //Destructor void deliver(byte *message, byte sizeofMessage); void debug(HardwareSerial &Serial); void writeBuffer(byte *message, byte messageLength); void sendBuffer(); boolean wait(int timeout=1000); boolean sendMessage(int retryTimes=5); word readRegister(word input); boolean writeRegister(word address, word value); boolean test(); boolean loopback(byte address=1); private: void receiveBuffer(); boolean checkMessage(); word calcCRC(byte *message, byte messageLength); HardwareSerial* debugSerial; SoftwareSerial* mySerial; boolean verbose; long lastrun; //milliseconds on last run. byte outBuffer[MAX_BUFFER]; //This Array will store the message from master byte outBufferSize; //The current Size of the Filled buffer. byte inBuffer[MAX_BUFFER]; //This Array will receive the message from slave byte inBufferSize; //The current Size of the Filled buffer. }; #endif
<reponame>SNTSVV/FAQAS_MASS<gh_stars>1-10 double function() { return 10; }
<gh_stars>0 /* * Copyright (c) 2020 Yubico AB. All rights reserved. * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE file. */ #ifndef _DUMMY_H #define _DUMMY_H const char dummy_name[] = "finger1"; const char dummy_pin[] = "9}4gT:8d=A37Dh}U"; const char dummy_rp_id[] = "localhost"; const char dummy_rp_name[] = "sweet home localhost"; const char dummy_user_icon[] = "an icon"; const char dummy_user_name[] = "<NAME>"; const char dummy_user_nick[] = "jsmith"; const uint8_t dummy_id[] = { 0x5e, 0xd2 }; const char dummy_pin1[] = "skepp cg0u3;Y.."; const char dummy_pin2[] = "bastilha 6rJrfQZI."; const uint8_t dummy_user_id[] = { 0x78, 0x1c, 0x78, 0x60, 0xad, 0x88, 0xd2, 0x63, 0x32, 0x62, 0x2a, 0xf1, 0x74, 0x5d, 0xed, 0xb2, 0xe7, 0xa4, 0x2b, 0x44, 0x89, 0x29, 0x39, 0xc5, 0x56, 0x64, 0x01, 0x27, 0x0d, 0xbb, 0xc4, 0x49, }; const uint8_t dummy_cred_id[] = { 0x4f, 0x72, 0x98, 0x42, 0x4a, 0xe1, 0x17, 0xa5, 0x85, 0xa0, 0xef, 0x3b, 0x11, 0x24, 0x4a, 0x3d, }; const uint8_t dummy_cdh[] = { 0xec, 0x8d, 0x8f, 0x78, 0x42, 0x4a, 0x2b, 0xb7, 0x82, 0x34, 0xaa, 0xca, 0x07, 0xa1, 0xf6, 0x56, 0x42, 0x1c, 0xb6, 0xf6, 0xb3, 0x00, 0x86, 0x52, 0x35, 0x2d, 0xa2, 0x62, 0x4a, 0xbe, 0x89, 0x76, }; const uint8_t dummy_es256[] = { 0xcc, 0x1b, 0x50, 0xac, 0xc4, 0x19, 0xf8, 0x3a, 0xee, 0x0a, 0x77, 0xd6, 0xf3, 0x53, 0xdb, 0xef, 0xf2, 0xb9, 0x5c, 0x2d, 0x8b, 0x1e, 0x52, 0x58, 0x88, 0xf4, 0x0b, 0x85, 0x1f, 0x40, 0x6d, 0x18, 0x15, 0xb3, 0xcc, 0x25, 0x7c, 0x38, 0x3d, 0xec, 0xdf, 0xad, 0xbd, 0x46, 0x91, 0xc3, 0xac, 0x30, 0x94, 0x2a, 0xf7, 0x78, 0x35, 0x70, 0x59, 0x6f, 0x28, 0xcb, 0x8e, 0x07, 0x85, 0xb5, 0x91, 0x96, }; const uint8_t dummy_rs256[] = { 0xd2, 0xa8, 0xc0, 0x11, 0x82, 0x9e, 0x57, 0x2e, 0x60, 0xae, 0x8c, 0xb0, 0x09, 0xe1, 0x58, 0x2b, 0x99, 0xec, 0xc3, 0x11, 0x1b, 0xef, 0x81, 0x49, 0x34, 0x53, 0x6a, 0x01, 0x65, 0x2c, 0x24, 0x09, 0x30, 0x87, 0x98, 0x51, 0x6e, 0x30, 0x4f, 0x60, 0xbd, 0x54, 0xd2, 0x54, 0xbd, 0x94, 0x42, 0xdd, 0x63, 0xe5, 0x2c, 0xc6, 0x04, 0x32, 0xc0, 0x8f, 0x72, 0xd5, 0xb4, 0xf0, 0x4f, 0x42, 0xe5, 0xb0, 0xa2, 0x95, 0x11, 0xfe, 0xd8, 0xb0, 0x65, 0x34, 0xff, 0xfb, 0x44, 0x97, 0x52, 0xfc, 0x67, 0x23, 0x0b, 0xad, 0xf3, 0x3a, 0x82, 0xd4, 0x96, 0x10, 0x87, 0x6b, 0xfa, 0xd6, 0x51, 0x60, 0x3e, 0x1c, 0xae, 0x19, 0xb8, 0xce, 0x08, 0xae, 0x9a, 0xee, 0x78, 0x16, 0x22, 0xcc, 0x92, 0xcb, 0xa8, 0x95, 0x34, 0xe5, 0xb9, 0x42, 0x6a, 0xf0, 0x2e, 0x82, 0x1f, 0x4c, 0x7d, 0x84, 0x94, 0x68, 0x7b, 0x97, 0x2b, 0xf7, 0x7d, 0x67, 0x83, 0xbb, 0xc7, 0x8a, 0x31, 0x5a, 0xf3, 0x2a, 0x95, 0xdf, 0x63, 0xe7, 0x4e, 0xee, 0x26, 0xda, 0x87, 0x00, 0xe2, 0x23, 0x4a, 0x33, 0x9a, 0xa0, 0x1b, 0xce, 0x60, 0x1f, 0x98, 0xa1, 0xb0, 0xdb, 0xbf, 0x20, 0x59, 0x27, 0xf2, 0x06, 0xd9, 0xbe, 0x37, 0xa4, 0x03, 0x6b, 0x6a, 0x4e, 0xaf, 0x22, 0x68, 0xf3, 0xff, 0x28, 0x59, 0x05, 0xc9, 0xf1, 0x28, 0xf4, 0xbb, 0x35, 0xe0, 0xc2, 0x68, 0xc2, 0xaa, 0x54, 0xac, 0x8c, 0xc1, 0x69, 0x9e, 0x4b, 0x32, 0xfc, 0x53, 0x58, 0x85, 0x7d, 0x3f, 0x51, 0xd1, 0xc9, 0x03, 0x02, 0x13, 0x61, 0x62, 0xda, 0xf8, 0xfe, 0x3e, 0xc8, 0x95, 0x12, 0xfb, 0x0c, 0xdf, 0x06, 0x65, 0x6f, 0x23, 0xc7, 0x83, 0x7c, 0x50, 0x2d, 0x27, 0x25, 0x4d, 0xbf, 0x94, 0xf0, 0x89, 0x04, 0xb9, 0x2d, 0xc4, 0xa5, 0x32, 0xa9, 0x25, 0x0a, 0x99, 0x59, 0x01, 0x00, 0x01, }; const uint8_t dummy_eddsa[] = { 0xfe, 0x8b, 0x61, 0x50, 0x31, 0x7a, 0xe6, 0xdf, 0xb1, 0x04, 0x9d, 0x4d, 0xb5, 0x7a, 0x5e, 0x96, 0x4c, 0xb2, 0xf9, 0x5f, 0x72, 0x47, 0xb5, 0x18, 0xe2, 0x39, 0xdf, 0x2f, 0x87, 0x19, 0xb3, 0x02, }; #endif /* !_DUMMY_H */
<reponame>Goluck-Konuko/deep_animation_codec<filename>assets/hm_common/c++/source_common/tools.h #ifndef TOOLS_H #define TOOLS_H #include <fstream> #include <iostream> #include <map> #include <regex> /** @brief Checks whether the array is sorted in strictly ascending order. * * @param ptr_array Pointer to the array to be checked. * @param size_array Size of the array to be checked. * @param is_sorted_strictly_ascending True if the array is sorted in strictly * ascending order. * @return Error code. It is equal to -1 if an error occurs. Otherwise, it is equal to 0. * */ template <typename T> int check_array_sorted_strictly_ascending(const T* const ptr_array, const unsigned int& size_array, bool& is_sorted_strictly_ascending) { if (!ptr_array) { fprintf(stderr, "`ptr_array` is NULL."); return -1; } if (size_array == 1 || size_array == 0) { is_sorted_strictly_ascending = true; return 0; } if (ptr_array[size_array - 1] <= ptr_array[size_array - 2]) { is_sorted_strictly_ascending = false; return 0; } return check_array_sorted_strictly_ascending<T>(ptr_array, size_array - 1, is_sorted_strictly_ascending); } /** @brief Finds the position of a given value in the array. * * @param ptr_array Pointer to the array buffer. * @param size_array Number of elements in the array. * @param value Given value. * @return Position of the given value in the array. -1 is * returned if the given value is not in the array. */ template <typename T> int find_position_in_array(const T* const ptr_array, const unsigned int& size_array, const T& value) { if (!ptr_array) { std::cerr << "`ptr_array` is NULL." << std::endl; return -1; } for (unsigned int i(0); i < size_array; i++) { if (ptr_array[i] == value) { return i; } } return -1; } /** @brief Checks whether the given string only contains special characters. * * @param string_in Given string to be checked. * @return Does the given string contain special characters exclusively? * */ bool is_string_special_characters_exclusively(const std::string& string_in); /** @brief Parses the file in which each line contains one unsigned integer key and a string. * * @param map_storage Map associating each unsigned integer key to the string. * @param path_to_file Path to the file to be parsed. * @param delimiters Set of delimiters for delimiting a key and a string. * @return Error code. It is equal to -1 if an error occurs. Otherwise, it is equal to 0. * */ int parse_file_strings_one_key(std::map<unsigned int, std::string>& map_storage, const std::string& path_to_file, const std::string& delimiters); /** @brief Parses a file in which each line contains three keys and a string. * * @details The three keys are: an unsigned integer, a boolean and an unsigned integer. * They identify the string. * * @param map_false Map associating each pair of unsigned integer keys to the * string. The boolean key is false. * @param map_true Map associating each pair of unsigned integer keys to the * string. The boolean key is true. * @param path_to_file Path to the file to be parsed. * @param delimiters Set of delimiters for delimiting two keys or a key and a string. * @return Error code. It is equal to -1 if an error occurs. Otherwise, it is equal to 0. * */ int parse_file_strings_three_keys(std::map<std::pair<unsigned int, unsigned int>, std::string>& map_false, std::map<std::pair<unsigned int, unsigned int>, std::string>& map_true, const std::string& path_to_file, const std::string& delimiters); /** @brief Removes all the leading and trailing whitespaces from a string. * * @param string_to_be_modified String whose leading and trailing whitespaces * are to be removed. * */ void remove_leading_trailing_whitespaces(std::string& string_to_be_modified); /** @brief Replaces a value in an array by the value in another array at the same position. * * @param ptr_array_replacement Pointer to the array in which the value * is to be replaced. * @param ptr_array_reference Pointer to the reference array containing the * values for the replacement. * @param size_arrays Size of the two arrays. * @param value_replacement Value to be replaced. * @return Error code. It is equal to -1 if an error occurs. Otherwise, it is equal to 0. * */ template <typename T> int replace_in_array_by_value(T* const ptr_array_replacement, const T* const ptr_array_reference, const unsigned int& size_arrays, const T& value_replacement) { if (!ptr_array_replacement) { fprintf(stderr, "`ptr_array_replacement` is NULL.\n"); return -1; } if (!ptr_array_reference) { fprintf(stderr, "`ptr_array_reference` is NULL.\n"); return -1; } for (unsigned int i(0); i < size_arrays; i++) { if (ptr_array_replacement[i] == value_replacement) { ptr_array_replacement[i] = ptr_array_reference[i]; } } return 0; } /** @brief Splits a string into substrings using a given set of delimiters. * * @param vector_substrings Vector storing the substrings resulting from * the split. * @param input_string Input string to be split into substrings. * @param delimiters Set of delimiters. * */ void split_string(std::vector<std::string>& vector_substrings, const std::string& input_string, const std::string& delimiters); #endif
<reponame>EphTron/lamure<filename>provenance/include/lamure/prov/meta_data.h // Copyright (c) 2014-2018 Bauhaus-Universitaet Weimar // This Software is distributed under the Modified BSD License, see license.txt. // // Virtual Reality and Visualization Research Group // Faculty of Media, Bauhaus-Universitaet Weimar // http://www.uni-weimar.de/medien/vr #ifndef LAMURE_META_CONTAINER_H #define LAMURE_META_CONTAINER_H #include <lamure/prov/common.h> namespace lamure { namespace prov { class PROVENANCE_DLL MetaData { public: const vec<char> &get_metadata() const { return _metadata; } MetaData() {} ~MetaData() {} virtual void read_metadata(ifstream &is, uint32_t meta_data_length) { _metadata = vec<char>(meta_data_length, 0); is.read(&_metadata[0], meta_data_length); } protected: vec<char> _metadata; }; } } #endif // LAMURE_META_CONTAINER_H
#include "x68000/x68k_pcg.h" static uint16_t x68k_pcg_ctrl; static volatile uint16_t *x68k_pcg_ctrl_r = (volatile uint16_t *)PCG_BG_CTRL; static uint8_t s_spr_next = 0; static uint8_t s_spr_count_prev = 0; /* Control: 0xEB0808 ---- --9- ---- ---- D/C turn on PCG to allow PCG register access ---- ---- --54 ---- BG1 TXsel nametable mapping ---- ---- ---- 3--- BG1 ON ---- ---- ---- -21- BG0 TXsel nametable mapping ---- ---- ---- ---0 BG0 ON H-total: 0xEB080A ---- ---- 7654 3210 H total H-disp: 0xEB080C ---- ---- --54 3210 H disp V-disp: 0xEB080E ---- ---- 7654 3210 V disp Mode: 0xEB0810 ---- ---- ---4 ---- L/H 15KHz(0), 31Khz(1) ---- ---- ---- 32-- V-res ---- ---- ---- --10 H-res If nonzero, enables 16x16 tiles */ void x68k_pcg_init(const X68kPcgConfig *c) { volatile uint16_t *pcg_reg = (volatile uint16_t *)0xEB080A; pcg_reg[0] = c->htotal; pcg_reg[1] = c->hdisp; pcg_reg[2] = c->vdisp; pcg_reg[3] = c->flags; x68k_pcg_set_disp_en(0); x68k_pcg_set_bg0_txsel(0); x68k_pcg_set_bg1_txsel(1); x68k_pcg_set_bg0_enable(1); x68k_pcg_set_bg1_enable(1); x68k_pcg_set_bg0_xscroll(0); x68k_pcg_set_bg1_xscroll(0); x68k_pcg_set_bg0_yscroll(0); x68k_pcg_set_bg1_yscroll(0); x68k_pcg_clear_sprites(); x68k_pcg_set_disp_en(1); } // Set to CPU(1) or display(0) void x68k_pcg_set_disp_en(uint8_t en) { x68k_pcg_ctrl &= ~(0x0200); x68k_pcg_ctrl |= (en ? 0x0200 : 0x0000); *x68k_pcg_ctrl_r = x68k_pcg_ctrl; } // Change the mappings for BG1 and BG0 nametables void x68k_pcg_set_bg1_txsel(uint8_t t) { x68k_pcg_ctrl &= ~(0x0030); x68k_pcg_ctrl |= (t & 0x03) << 4; *x68k_pcg_ctrl_r = x68k_pcg_ctrl; } void x68k_pcg_set_bg0_txsel(uint8_t t) { x68k_pcg_ctrl &= ~(0x0030); x68k_pcg_ctrl |= (t & 0x03) << 1; *x68k_pcg_ctrl_r = x68k_pcg_ctrl; } // Enable or disable BG layer display void x68k_pcg_set_bg1_enable(uint8_t en) { x68k_pcg_ctrl &= ~(0x0008); x68k_pcg_ctrl |= (en ? 0x08 : 0x000); *x68k_pcg_ctrl_r = x68k_pcg_ctrl; } void x68k_pcg_set_bg0_enable(uint8_t en) { x68k_pcg_ctrl &= ~(0x0001); x68k_pcg_ctrl |= (en ? 0x001 : 0x000); *x68k_pcg_ctrl_r = x68k_pcg_ctrl; } void x68k_pcg_add_sprite(int16_t x, int16_t y, uint16_t attr, uint16_t prio) { while (s_spr_count_prev > 0) { s_spr_count_prev--; volatile X68kPcgSprite *spr = x68k_pcg_get_sprite(s_spr_count_prev); spr->x = 0; } if (s_spr_next >= 128) return; x68k_pcg_set_sprite(s_spr_next++, x, y, attr, prio); } void x68k_pcg_finish_sprites(void) { s_spr_count_prev = s_spr_next; s_spr_next = 0; }
<gh_stars>10-100 /*++ Copyright (c) 1994 Microsoft Corporation Module Name: debug.h Abstract: This file contains debugging macros for the DHCP server. Author: <NAME> (madana) 10-Sep-1993 <NAME> (mannyw) 10-Oct-1992 Environment: User Mode - Win32 Revision History: --*/ #define DEBUG_DIR L"\\debug" #define DEBUG_FILE L"\\dhcpssvc.log" #define DEBUG_BAK_FILE L"\\dhcpssvc.bak" // // LOW WORD bit mask (0x0000FFFF) for low frequency debug output. // #define DEBUG_ADDRESS 0x00000001 // subnet address #define DEBUG_CLIENT 0x00000002 // client API #define DEBUG_PARAMETERS 0x00000004 // dhcp server parameter #define DEBUG_OPTIONS 0x00000008 // dhcp option #define DEBUG_ERRORS 0x00000010 // hard error #define DEBUG_STOC 0x00000020 // protocol error #define DEBUG_INIT 0x00000040 // init error #define DEBUG_SCAVENGER 0x00000080 // sacvenger error #define DEBUG_TIMESTAMP 0x00000100 // debug message timing #define DEBUG_APIS 0x00000200 // Dhcp APIs #define DEBUG_REGISTRY 0x00000400 // Registry operation #define DEBUG_JET 0x00000800 // JET error #define DEBUG_THREADPOOL 0x00001000 // thread pool operation #define DEBUG_AUDITLOG 0x00002000 // audit log operation // unused flag. #define DEBUG_MISC 0x00008000 // misc info. // // HIGH WORD bit mask (0x0000FFFF) for high frequency debug output. // ie more verbose. // #define DEBUG_MESSAGE 0x00010000 // dhcp message output. #define DEBUG_API_VERBOSE 0x00020000 // Dhcp API verbose #define DEBUG_DNS 0x00040000 // Dns related messages #define DEBUG_MSTOC 0x00080000 // multicast stoc #define DEBUG_TRACK 0x00100000 // tracking specific problems #define DEBUG_ROGUE 0x00200000 // rogue stuff printed out #define DEBUG_PNP 0x00400000 // pnp interface stuff #define DEBUG_PERF 0x01000000 // Printfs for performance work. #define DEBUG_ALLOC 0x02000000 // Print allocations de-allocations.. #define DEBUG_PING 0x04000000 // Asynchronous ping details #define DEBUG_THREAD 0x08000000 // Thread.c stuff #define DEBUG_TRACE 0x10000000 // Printfs for tracing throug code. #define DEBUG_TRACE_CALLS 0x20000000 // Trace through piles of junk #define DEBUG_STARTUP_BRK 0x40000000 // breakin debugger during startup. #define DEBUG_LOG_IN_FILE 0x80000000 // log debug output in a file. VOID DhcpOpenDebugFile( IN BOOL ReopenFlag ); 
/* * ===================================================================================== * * Filename: etomc2_gt.c * * Description: cc gt * * Version: 1.0 * Created: 2020年05月27日 23时47分54秒 * Revision: none * Compiler: gcc * * Author: <EMAIL> (), <EMAIL> * Organization: etomc2.com * * ===================================================================================== */ #include "etomc2.h" /* * === FUNCTION * ====================================================================== * Name: ngx_cc_gt * Description: calc gt count * ===================================================================================== */ void ngx_cc_gt(ngx_http_request_t *r) { ngx_http_etomc2_loc_conf_t *lccf; ngx_slab_pool_t *shpool; Ngx_etomc2_shm_gt *cc_gt_ptr, *cc_new_ptr; ngx_shm_zone_t *shm_zone_cc_gt; time_t now; uint32_t hash_domain; lccf = ngx_http_get_module_loc_conf(r, ngx_http_etomc2_cc_module); if (!lccf) return; if (lccf->shm_zone_cc_gt == NULL) { NX_LOG("shm_zone_cc_ub is null"); return; } shm_zone_cc_gt = lccf->shm_zone_cc_gt; cc_gt_ptr = (Ngx_etomc2_shm_gt *)shm_zone_cc_gt->data; now = ngx_time(); hash_domain = to_hash((char *)r->headers_in.server.data, r->headers_in.server.len); int diff = now - cc_gt_ptr->now; while (cc_gt_ptr) { if (cc_gt_ptr->hash_domain == 0) { cc_gt_ptr->hash_domain = hash_domain; switch (lccf->cc_gt_level) { case 1: cc_gt_ptr->level = GTL_1; break; case 2: cc_gt_ptr->level = GTL_2; break; case 3: cc_gt_ptr->level = GTL_3; break; case 4: cc_gt_ptr->level = GTL_4; break; case 5: cc_gt_ptr->level = GTL_5; break; default: cc_gt_ptr->level = GTL_5; break; } /* ----- end switch ----- */ } if (cc_gt_ptr->hash_domain == hash_domain) { if (diff > SHM_GT_TIMEOUT) { cc_gt_ptr->count = 1; } else { cc_gt_ptr->count += 1; } cc_gt_ptr->now = now; return; } if (cc_gt_ptr->next == NULL) { shpool = (ngx_slab_pool_t *)shm_zone_cc_gt->shm.addr; // new cc_new_ptr = ngx_cc_gt_init(shpool); if (!cc_new_ptr) { return; } cc_new_ptr->hash_domain = hash_domain; cc_new_ptr->now = now; switch (lccf->cc_gt_level) { case 1: cc_new_ptr->level = GTL_1; break; case 2: cc_new_ptr->level = GTL_2; break; case 3: cc_new_ptr->level = GTL_3; break; case 4: cc_new_ptr->level = GTL_4; break; case 5: cc_new_ptr->level = GTL_5; break; default: cc_new_ptr->level = GTL_5; break; } /* ----- end switch ----- */ cc_gt_ptr->next = cc_new_ptr; return; } cc_gt_ptr = cc_gt_ptr->next; } } /* ----- end of function ngx_cc_gt ----- */ /* * === FUNCTION * ====================================================================== Name: * ngx_cc_gt_init Description: * ===================================================================================== */ Ngx_etomc2_shm_gt *ngx_cc_gt_init(ngx_slab_pool_t *shpool) { Ngx_etomc2_shm_gt *cc_new_ptr; // new cc_new_ptr = ngx_slab_alloc_locked(shpool, sizeof(Ngx_etomc2_shm_gt)); if (!cc_new_ptr) { return NULL; } cc_new_ptr->hash_domain = 0; cc_new_ptr->count = 1; cc_new_ptr->now = 0; /** cc_new_ptr->take = 0; */ memset(cc_new_ptr->uri_itemize, 0, (size_t)CC_GT_URI_MAX * sizeof(uint32_t)); cc_new_ptr->level = GTL_5; cc_new_ptr->next = NULL; return cc_new_ptr; } /* ----- end of function ngx_cc_gt_init ----- */ /* * === FUNCTION * ====================================================================== * Name: ngx_cc_gt_check * Description: * ===================================================================================== */ int ngx_cc_gt_check(ngx_http_request_t *r, uint32_t hash_uri) { Ngx_etomc2_shm_gt *cc_gt_ptr; int i; SHM_GT_LEVEL uri_level; cc_gt_ptr = NULL; ngx_cc_gt_search(r, &cc_gt_ptr); NX_DEBUG("[CC Attack check:%d level:%d]", cc_gt_ptr->count, cc_gt_ptr->level); if (cc_gt_ptr != NULL && cc_gt_ptr->count >= cc_gt_ptr->level) { for (i = 0; i < CC_GT_URI_MAX && cc_gt_ptr->uri_itemize[i] != 0; i++) { if (cc_gt_ptr->uri_itemize[i] == hash_uri) { uri_level = cc_gt_ptr->level; switch (uri_level) { case GTL_1: uri_level = GTL_2; break; case GTL_2: uri_level = GTL_3; break; case GTL_3: uri_level = GTL_4; break; case GTL_4: uri_level = GTL_5; break; default: uri_level = GTL_5; break; } /* ----- end switch ----- */ if (cc_gt_ptr->count >= uri_level) { return 0; } else { return -1; } } } return 0; } return -1; } /* ----- end of function ngx_cc_gt_check ----- */ /* * === FUNCTION * ====================================================================== Name: * ngx_cc_gt_search Description: * ===================================================================================== */ void ngx_cc_gt_search(ngx_http_request_t *r, Ngx_etomc2_shm_gt **gt_node_ptr) { ngx_http_etomc2_loc_conf_t *lccf; Ngx_etomc2_shm_gt *cc_gt_ptr; ngx_shm_zone_t *shm_zone_cc_gt; uint32_t hash_domain; /** ngx_str_t uri; */ lccf = ngx_http_get_module_loc_conf(r, ngx_http_etomc2_cc_module); if (!lccf) return; if (lccf->shm_zone_cc_gt == NULL) { NX_LOG("shm_zone_cc_ub is null"); return; } shm_zone_cc_gt = lccf->shm_zone_cc_gt; cc_gt_ptr = (Ngx_etomc2_shm_gt *)shm_zone_cc_gt->data; hash_domain = to_hash((char *)r->headers_in.server.data, r->headers_in.server.len); while (cc_gt_ptr) { if (cc_gt_ptr->hash_domain == hash_domain) { *gt_node_ptr = cc_gt_ptr; return; } cc_gt_ptr = cc_gt_ptr->next; } *gt_node_ptr = NULL; } /* ----- end of function ngx_cc_gt_search ----- */ /* * === FUNCTION * ====================================================================== * Name: gt_index * Description: * ===================================================================================== */ int gt_index(SHM_GT_LEVEL gt) { switch (gt) { case GTL_1: return 1; case GTL_2: return 2; case GTL_3: return 3; case GTL_4: return 4; default: return 5; } /* ----- end switch ----- */ } /* ----- end of function gt_index ----- */
<gh_stars>1000+ /*++ Copyright (c) 2006 Microsoft Corporation Module Name: inj_axiom.h Abstract: <abstract> Author: <NAME> (leonardo) 2008-06-23. Revision History: --*/ #pragma once #include "ast/ast.h" bool simplify_inj_axiom(ast_manager & m, quantifier * q, expr_ref & result);
#pragma once #include "../csgostructs.hpp" class CBoneCache { public: matrix3x4_t* m_pCachedBones; char pad[8]; unsigned int m_CachedBoneCount; };
/* * Copyright (C) 2016 Square, Inc. * * 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 DUKTAPE_ANDROID_STACK_CHECKER_H #define DUKTAPE_ANDROID_STACK_CHECKER_H #include "duktape/duktape.h" #include <string> #include <stdexcept> /** * Throws an exception and aborts the process if the Duktape stack has a different number of * elements at the end of the C++ scope than where the object was constructed. This will show a * trace and Duktape stack details in logcat when running in the debugger. Use CHECK_STACK() * below for a convenient way to add stack validation to debug builds only. */ class StackChecker { public: StackChecker(duk_context* ctx) : m_context(ctx) , m_top(duk_get_top(m_context)) { } ~StackChecker() { if (m_top == duk_get_top(m_context)) { return; } const auto actual = duk_get_top(m_context); duk_push_context_dump(m_context); throw stack_error(m_top, actual, duk_get_string(m_context, -1)); } private: struct stack_error : public std::runtime_error { stack_error(duk_idx_t expected, duk_idx_t actual, const std::string& stack) : std::runtime_error("expected " + std::to_string(expected) + ", actual " + std::to_string(actual) + " - stack " + stack) { } }; duk_context* m_context; const duk_idx_t m_top; }; #ifdef NDEBUG #define CHECK_STACK(ctx) ((void)0) #else #define CHECK_STACK(ctx) const StackChecker _(ctx) #endif #endif //DUKTAPE_ANDROID_STACK_CHECKER_H
#include <cgreen/cgreen.h> #include "integer_to_char.h" static void should_return_a_empty_string_with_base_less_than_two() { char *character = malloc(sizeof(100)); integer_to_char(10, character, 1); assert_string_equal("", character); } static void should_return_a_empty_string_with_base_greater_than_thirty_five() { char *character = malloc(sizeof(100)); integer_to_char(10, character, 36); assert_string_equal("", character); } static void should_convert_little_numbers_to_char() { char *character = malloc(sizeof(100)); integer_to_char(0, character, 10); assert_string_equal("0", character); integer_to_char(10, character, 10); assert_string_equal("10", character); integer_to_char(99, character, 10); assert_string_equal("99", character); } static void should_convert_high_numbers_to_char() { char *character = malloc(sizeof(10000)); integer_to_char(506978, character, 10); assert_string_equal("506978", character); integer_to_char(10000000, character, 10); assert_string_equal("10000000", character); integer_to_char(1000000000, character, 10); assert_string_equal("1000000000", character); integer_to_char(10000000000, character, 10); assert_string_equal("10000000000", character); } TestSuite *integer_to_char_suite() { TestSuite *suite = create_test_suite(); /* describe #integer_to_char */ add_test(suite, should_return_a_empty_string_with_base_less_than_two); add_test(suite, should_return_a_empty_string_with_base_greater_than_thirty_five); add_test(suite, should_convert_little_numbers_to_char); add_test(suite, should_convert_high_numbers_to_char); return suite; }
<reponame>GeekLee609/DesignPatterns_iOS<gh_stars>1-10 // // Mark.h // OC_DesignPatterns // // Created by polo on 2018/11/29. // Copyright © 2018年 GeekLee. All rights reserved. // 组合对象的父类协议 #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #import "MarkVisitor.h" @protocol Mark <NSObject> /// 颜色 @property (nonatomic, strong) UIColor *color; /// 尺寸 @property (nonatomic, assign) CGFloat size; /// 位置 @property (nonatomic, assign) CGPoint location; /// 子节点的个数 @property (nonatomic, assign, readonly) NSInteger count; /// 上一个节点 @property (nonatomic, readonly) id <Mark> lastChild; #pragma mark - 协议方法 /// 拷贝方法,原型模式,快速生成对象 - (id)copy; #pragma mark - 画图相关 /// 添加一个节点 - (void)addMark:(id <Mark>) mark; /// 删除一个节点 - (void)removeMark:(id <Mark>) mark; /// 获取指定索引的节点 - (id <Mark>)childMarkAtIndex:(NSInteger)index; /// 画图协议方法 - (void)drawWithContext:(CGContextRef)context; #pragma mark - 树的遍历迭代 /// 迭代器 - (NSEnumerator *)enumerator; /// 迭代器进行树的遍历 - (void)enumerateMarksUsingBlock:(void (^)(id <Mark>item, BOOL *stop))block; /// 访问者接口 - (void)acceptMarkVisitor:(id <MarkVisitor>)visitor; @end
<reponame>justacid/spaceclimber<gh_stars>0 #ifndef SCENE_GAME_OVER_H #define SCENE_GAME_OVER_H #include <SFML/Graphics.hpp> #include "Scene.h" #include "Camera.h" class GameOver : public Scene { public: GameOver(sf::RenderWindow& window, const std::string& id); void update() override; void draw() override; void pollEvents() override; void reset() override; void setScore(int score); private: Camera mCamera; sf::Sprite mBackground; sf::Sprite mTitle; sf::Sprite mContinue; sf::Sprite mCross; sf::Text mScoreText; }; #endif
<filename>ti/omap3/omx/audio/src/openmax_il/g722_enc/inc/OMX_G722Enc_Utils.h<gh_stars>1-10 /* * Copyright (C) Texas Instruments - http://www.ti.com/ * * 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. * * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* ============================================================================= * Texas Instruments OMAP (TM) Platform Software * (c) Copyright Texas Instruments, Incorporated. All Rights Reserved. * * Use of this software is controlled by the terms and conditions found * in the license agreement under which this software has been supplied. * =========================================================================== */ /** * @file OMX_G722Enc_Utils.h * * This header file contains data and function prototypes for G722 ENCODER OMX * * @path $(OMAPSW_MPU)\linux\audio\src\openmax_il\g722_enc\inc * * @rev 0.1 */ /* ----------------------------------------------------------------------------- *! *! Revision History *! =================================== *! Date Author(s) Version Description *! --------- ------------------- ------- --------------------------------- *! 08-Mar-2007 A.Donjon 0.1 Code update for G722 ENCODER *! *! * ================================================================================= */ #include <OMX_Component.h> #include "LCML_DspCodec.h" #include "OMX_G722Encoder.h" #define NEWSENDCOMMAND_MEMORY 123 /*#endif*/ #include <TIDspOmx.h> /* ComponentThread constant */ #define EXIT_COMPONENT_THRD 10 /* ======================================================================= */ /** * @def G722ENC_XXX_VER Component version */ /* ======================================================================= */ #define G722ENC_MAJOR_VER 1 #define G722ENC_MINOR_VER 1 /* ======================================================================= */ /** * @def NOT_USED Defines a value for "don't care" parameters */ /* ======================================================================= */ #define NOT_USED 10 /* ======================================================================= */ /** * @def NORMAL_BUFFER Defines the flag value with all flags turned off */ /* ======================================================================= */ #define NORMAL_BUFFER 0 /* ======================================================================= */ /** * @def OMX_G722ENC_DEFAULT_SEGMENT Default segment ID for the LCML */ /* ======================================================================= */ #define OMX_G722ENC_DEFAULT_SEGMENT (0) /* ======================================================================= */ /** * @def OMX_G722ENC_SN_TIMEOUT Timeout value for the socket node */ /* ======================================================================= */ #define OMX_G722ENC_SN_TIMEOUT (-1) /* ======================================================================= */ /** * @def OMX_G722ENC_SN_PRIORITY Priority for the socket node */ /* ======================================================================= */ #define OMX_G722ENC_SN_PRIORITY (10) /* ======================================================================= */ /** * @def G722ENC_TIMEOUT_MILLISECONDS Timeout value for the component thread */ /* ======================================================================= */ #define G722ENC_TIMEOUT_MILLISECONDS (1000) /* ======================================================================= */ /** * @def G722ENC_CACHE_ALIGN_MALLOC Value to add to the size needed to * malloc to ensure cache alignment */ /* ======================================================================= */ #define G722ENC_CACHE_ALIGN_MALLOC 256 /* ======================================================================= */ /** * @def G722ENC_CACHE_ALIGN_OFFSET Value to add to the pointer returned * by malloc to ensure cache alignment */ /* ======================================================================= */ #define G722ENC_CACHE_ALIGN_OFFSET 128 /* ======================================================================= */ /** * @def G722ENC_MAX_NUM_OF_BUFS Maximum number of buffers */ /* ======================================================================= */ #define G722ENC_MAX_NUM_OF_BUFS 10 /* ======================================================================= */ /** * @def USN_DLL_NAME Path to the USN */ /* ======================================================================= */ #ifdef UNDER_CE #define USN_DLL_NAME "\\windows\\usn.dll64P" #else #define USN_DLL_NAME "usn.dll64P" #endif /* ======================================================================= */ /** * @def G722ENC_DLL_NAME Path to the G722ENC SN */ /* ======================================================================= */ #ifdef UNDER_CE #define G722ENC_DLL_NAME "\\windows\\g722enc_sn.dll64P" #else #define G722ENC_DLL_NAME "g722enc_sn.dll64P" #endif /* ======================================================================= */ /** * @def DONT_CARE Don't care value for the LCML initialization params */ /* ======================================================================= */ #define DONT_CARE 0 /* ======================================================================= */ /** * @def G722ENC_DEBUG Turns debug messaging on and off */ /* ======================================================================= */ #undef G722ENC_DEBUG /*#define G722ENC_DEBUG*/ /* ======================================================================= */ /** * @def G722ENC_MEMCHECK Turns memory messaging on and off */ /* ======================================================================= */ #undef G722ENC_MEMCHECK /* try to avoid the time out due to print message */ /* ======================================================================= */ /** * @def G722ENC_DPRINT Debug print macro */ /* ======================================================================= */ #ifndef UNDER_CE /* Linux definitions */ #ifdef G722ENC_DEBUG #define G722ENC_DPRINT(...) fprintf(stdout,__VA_ARGS__) #else #define G722ENC_DPRINT(...) #endif #ifdef G722ENC_MEMCHECK #define G722ENC_MEMPRINT(...) fprintf(stdout,__VA_ARGS__) #else #define G722ENC_MEMPRINT(...) #endif #else #ifdef G722ENC_DEBUG #define G722ENC_DPRINT(STR, ARG...) printf() #else #endif /* ======================================================================= */ /** * @def G722ENC_MEMCHECK Memory print macro */ /* ======================================================================= */ #ifdef G722ENC_MEMCHECK #define G722ENC_MEMPRINT(STR, ARG...) printf() #else #endif #define G722ENC_DPRINT printf #define G722ENC_MEMPRINT printf #endif #ifdef UNDER_CE #ifdef DEBUG #define G722ENC_DPRINT printf #define G722ENC_MEMPRINT printf #else #define G722ENC_DPRINT #define G722ENC_MEMPRINT #endif #endif /* ======================================================================= */ /** * @def G722ENC_NUM_OF_PORTS Number of ports */ /* ======================================================================= */ #define G722ENC_NUM_OF_PORTS 2 /* ======================================================================= */ /** * @def G722ENC_NUM_STREAMS Number of streams */ /* ======================================================================= */ #define G722ENC_NUM_STREAMS 2 /* ======================================================================= */ /** * @def G722ENC_NUM_INPUT_DASF_BUFFERS Number of input buffers */ /* ======================================================================= */ #define G722ENC_NUM_INPUT_DASF_BUFFERS 2 /* ======================================================================= */ /** * @def G722ENC_AM_DEFAULT_RATE Default audio manager rate */ /* ======================================================================= */ #define G722ENC_AM_DEFAULT_RATE 48000 /* ======================================================================= */ /** * @def G722ENC_SAMPLE_RATE G722ENC SN sampling frequency */ /* ======================================================================= */ #define G722ENC_SAMPLE_RATE 16000 /* ======================================================================= */ /** * M A C R O S FOR MALLOC and MEMORY FREE and CLOSING PIPES */ /* ======================================================================= */ #define OMX_G722CONF_INIT_STRUCT(_s_, _name_) \ memset((_s_), 0x0, sizeof(_name_)); \ (_s_)->nSize = sizeof(_name_); \ (_s_)->nVersion.s.nVersionMajor = 0x1; \ (_s_)->nVersion.s.nVersionMinor = 0x1; \ (_s_)->nVersion.s.nRevision = 0x0; \ (_s_)->nVersion.s.nStep = 0x0 #define OMX_G722MEMFREE_STRUCT(_pStruct_) \ if(_pStruct_ != NULL) \ { \ G722ENC_MEMPRINT("%d :: [FREE] %p\n", __LINE__, _pStruct_); \ free(_pStruct_); \ _pStruct_ = NULL; \ } #define OMX_G722CLOSE_PIPE(_pStruct_,err) \ G722ENC_DPRINT("%d :: CLOSING PIPE \n", __LINE__); \ err = close (_pStruct_); \ if(0 != err && OMX_ErrorNone == eError) \ { \ eError = OMX_ErrorHardware; \ printf("%d :: Error while closing pipe\n", __LINE__); \ goto EXIT; \ } #define OMX_G722MALLOC_STRUCT(_pStruct_, _sName_) \ _pStruct_ = (_sName_*)malloc(sizeof(_sName_)); \ if(_pStruct_ == NULL) \ { \ printf("***********************************\n"); \ printf("%d :: Malloc Failed\n", __LINE__); \ printf("***********************************\n"); \ eError = OMX_ErrorInsufficientResources; \ goto EXIT; \ } \ memset(_pStruct_,0,sizeof(_sName_)); \ G722ENC_MEMPRINT("%d :: [ALLOC] %p\n", __LINE__, _pStruct_); /* ======================================================================= */ /** G722ENC_STREAM_TYPE Values for create phase params * * @param G722ENCSTREAMDMM Indicates DMM * * @param G722ENCSTREAMINPUT Sets input stream * * @param G722ENCSTREAMOUTPUT Sets output stream * */ /* ==================================================================== */ typedef enum { G722ENCSTREAMDMM, G722ENCSTREAMINPUT, G722ENCSTREAMOUTPUT } G722ENC_STREAM_TYPE; /* ======================================================================= */ /** IUALG_Cmd Values for create phase params * * @param IULAG_CMD_STOP Socket node stop command * * @param IULAG_CMD_PAUSE Socket node pause command * * @param IULAG_CMD_GETSTATUS Socket node get status command. * * @param IULAG_CMD_SETSTATUS Socket node set status command. * * @param IUALG_CMD_USERCMDSTART Socket node start command. * */ /* ==================================================================== */ typedef enum { IULAG_CMD_STOP = 0, IULAG_CMD_PAUSE = 1, IULAG_CMD_GETSTATUS = 2, IULAG_CMD_SETSTATUS = 3, IUALG_CMD_USERCMDSTART = 100 }IUALG_Cmd; /* ======================================================================= */ /** G722ENC_COMP_PORT_TYPE Port definition for component * * @param G722ENC_INPUT_PORT Index for input port * * @param G722ENC_OUTPUT_PORT Index for output port * */ /* ==================================================================== */ typedef enum G722ENC_COMP_PORT_TYPE { G722ENC_INPUT_PORT = 0, G722ENC_OUTPUT_PORT }G722ENC_COMP_PORT_TYPE; /* =================================================================================== */ /** * Socket node input buffer parameters. */ /* ================================================================================== */ typedef struct G722ENC_UAlgInBufParamStruct { unsigned long bLastBuffer; }G722ENC_UAlgInBufParamStruct; /* =================================================================================== */ /** * LCML data header. */ /* ================================================================================== */ typedef struct G722ENC_LCML_BUFHEADERTYPE { OMX_DIRTYPE eDir; OMX_BUFFERHEADERTYPE *pBufHdr; void *pOtherParams[10]; G722ENC_UAlgInBufParamStruct *pIpParam; /*G722ENC_UAlgOutBufParamStruct *pOpParam; */ }G722ENC_LCML_BUFHEADERTYPE; /* =================================================================================== */ /** * Socket node audio codec parameters */ /* ================================================================================== */ typedef struct G722ENC_AudioCodecParams { unsigned long iSamplingRate; unsigned long iStrmId; unsigned short iAudioFormat; }G722ENC_AudioCodecParams; /* =================================================================================== */ /** * Structure for buffer list */ /* ================================================================================== */ typedef struct _BUFFERLIST G722ENC_BUFFERLIST; struct _BUFFERLIST{ OMX_BUFFERHEADERTYPE *pBufHdr[G722ENC_MAX_NUM_OF_BUFS]; /* records buffer header send by client */ OMX_U32 bufferOwner[G722ENC_MAX_NUM_OF_BUFS]; OMX_U32 numBuffers; OMX_U32 bBufferPending[G722ENC_MAX_NUM_OF_BUFS]; }; /* =================================================================================== */ /** * Component private data */ /* ================================================================================== */ typedef struct G722ENC_COMPONENT_PRIVATE { /** Array of pointers to BUFFERHEADERTYPE structues This pBufHeader[G722ENC_INPUT_PORT] will point to all the BUFFERHEADERTYPE structures related to input port, not just one structure. Same is for output port also. */ OMX_BUFFERHEADERTYPE* pBufHeader[G722ENC_NUM_OF_PORTS]; /** Structure of callback pointers */ OMX_CALLBACKTYPE cbInfo; /** Handle for use with async callbacks */ OMX_PORT_PARAM_TYPE sPortParam; /** Input port parameters */ OMX_AUDIO_PARAM_PORTFORMATTYPE* pInPortFormat; /** Output port parameters */ OMX_AUDIO_PARAM_PORTFORMATTYPE* pOutPortFormat; /** Keeps track of whether a buffer is owned by the component or by the IL client */ OMX_U32 bIsBufferOwned[G722ENC_NUM_OF_PORTS]; /* Audio codec parameters structure */ G722ENC_AudioCodecParams *pParams; /** This will contain info like how many buffers are there for input/output ports, their size etc, but not BUFFERHEADERTYPE POINTERS. */ OMX_PARAM_PORTDEFINITIONTYPE* pPortDef[G722ENC_NUM_OF_PORTS]; OMX_AUDIO_PARAM_ADPCMTYPE* g722Params; OMX_AUDIO_PARAM_ADPCMTYPE* pcmParams; OMX_PRIORITYMGMTTYPE* sPriorityMgmt; /** This is component handle */ OMX_COMPONENTTYPE* pHandle; /** Current state of this component */ OMX_STATETYPE curState; /** The component thread handle */ pthread_t ComponentThread; /** The pipes for sending buffers to the thread */ int dataPipe[2]; /** The pipes for sending command data to the thread */ int cmdDataPipe[2]; /** The pipes for sending buffers to the thread */ int cmdPipe[2]; /** The pipes for sending buffers to the thread */ int lcml_Pipe[2]; /** Set to indicate component is stopping */ OMX_U32 bIsStopping; OMX_U32 bIsEOFSent; /** Count of number of buffers outstanding with bridge */ OMX_U32 lcml_nIpBuf; /** Count of number of buffers outstanding with bridge */ OMX_U32 lcml_nOpBuf; /** Count of buffers sent to the LCML */ OMX_U32 lcml_nCntIp; /** Count of buffers received from the LCML */ OMX_U32 lcml_nCntOpReceived; /** Count of buffers pending from the app */ OMX_U32 app_nBuf; /** Flag for DASF mode */ OMX_U32 dasfmode; /** Audio Stream ID */ OMX_U32 streamID; /** LCML Handle */ OMX_HANDLETYPE pLcmlHandle; /** LCML Buffer Header */ G722ENC_LCML_BUFHEADERTYPE *pLcmlBufHeader[2]; /** Tee Mode Flag */ OMX_U32 teemode; /** Flag set when port definitions are allocated */ OMX_U32 bPortDefsAllocated; /** Flag set when component thread is started */ OMX_U32 bCompThreadStarted; /** Mark data */ OMX_PTR pMarkData; /** Mark buffer */ OMX_MARKTYPE *pMarkBuf; /** Mark target component */ OMX_HANDLETYPE hMarkTargetComponent; /** Flag set when buffer should not be queued to the DSP */ OMX_U32 bBypassDSP; /** Create phase arguments */ OMX_U16 *pCreatePhaseArgs; /** Input buffer list */ G722ENC_BUFFERLIST *pInputBufferList; /** Output buffer list */ G722ENC_BUFFERLIST *pOutputBufferList; /** LCML stream attributes */ LCML_STRMATTR *strmAttr; /** Component version */ OMX_U32 nVersion; /** LCML Handle */ void *lcml_handle; /** Number of initialized input buffers */ int noInitInputBuf; /** Number of initialized output buffers */ int noInitOutputBuf; /** Flag set when LCML handle is opened */ int bLcmlHandleOpened; /** Flag set when initialization params are set */ OMX_U32 bInitParamsInitialized; /** Pipe write handle for audio manager */ int fdwrite; /** Pipe read handle for audio manager */ int fdread; /** Stores input buffers while paused */ OMX_BUFFERHEADERTYPE *pInputBufHdrPending[G722ENC_MAX_NUM_OF_BUFS]; /** Number of input buffers received while paused */ OMX_U32 nNumInputBufPending; /** Stores output buffers while paused */ OMX_BUFFERHEADERTYPE *pOutputBufHdrPending[G722ENC_MAX_NUM_OF_BUFS]; /** Number of output buffers received while paused */ OMX_U32 nNumOutputBufPending; /** Keeps track of the number of invalid frames that come from the LCML */ OMX_U32 nInvalidFrameCount; /** Flag set when a disable command is pending */ OMX_U32 bDisableCommandPending; /** Parameter for pending disable command */ OMX_U32 bDisableCommandParam; /** Flag to set when socket node stop callback should not transition component to OMX_StateIdle */ OMX_U32 bNoIdleOnStop; /** Flag set when idle command is pending */ OMX_U32 bIdleCommandPending; /** Flag set when socket node is stopped */ OMX_U32 bDspStoppedWhileExecuting; /** Number of outstanding FillBufferDone() calls */ OMX_U32 nOutStandingFillDones; /** Flag set when StrmCtrl has been called */ OMX_U32 bStreamCtrlCalled; OMX_PARAM_COMPONENTROLETYPE componentRole; OMX_STRING* sDeviceString; OMX_BOOL bLoadedCommandPending; /** Holds the value of RT Mixer mode */ OMX_U32 rtmx; TI_OMX_DSP_DEFINITION tiOmxDspDefinition; /* Removing sleep() calls. Definition. */ #ifndef UNDER_CE pthread_mutex_t AlloBuf_mutex; pthread_cond_t AlloBuf_threshold; OMX_U8 AlloBuf_waitingsignal; pthread_mutex_t InLoaded_mutex; pthread_cond_t InLoaded_threshold; OMX_U8 InLoaded_readytoidle; pthread_mutex_t InIdle_mutex; pthread_cond_t InIdle_threshold; OMX_U8 InIdle_goingtoloaded; #else OMX_Event AlloBuf_event; OMX_U8 AlloBuf_waitingsignal; OMX_Event InLoaded_event; OMX_U8 InLoaded_readytoidle; OMX_Event InIdle_event; OMX_U8 InIdle_goingtoloaded; #endif #ifdef __PERF_INSTRUMENTATION__ PERF_OBJHANDLE pPERF, pPERFcomp; OMX_U32 nLcml_nCntIp; OMX_U32 nLcml_nCntOpReceived; #endif /** Keep buffer timestamps **/ OMX_S64 arrTimestamp[G722ENC_MAX_NUM_OF_BUFS]; /** Keep buffer nTickCounts **/ OMX_S64 arrTickCount[G722ENC_MAX_NUM_OF_BUFS]; /** Index to arrTimestamp[], used for input buffer timestamps */ OMX_U8 IpBufindex; /** Index to arrTimestamp[], used for output buffer timestamps */ OMX_U8 OpBufindex; OMX_BOOL bPreempted; } G722ENC_COMPONENT_PRIVATE; /* =========================================================== */ /** * OMX_ComponentInit() Initializes component * * * @param hComp OMX Handle * * @return OMX_ErrorNone = Successful * Other error code = fail * */ /*================================================================== */ #ifndef UNDER_CE OMX_ERRORTYPE OMX_ComponentInit (OMX_HANDLETYPE hComp); #else /* WinCE Implicit Export Syntax */ #define OMX_EXPORT __declspec(dllexport) OMX_EXPORT OMX_ERRORTYPE OMX_ComponentInit (OMX_HANDLETYPE hComp); #endif /* =========================================================== */ /** * G722ENC_Fill_LCMLInitParams() Fills the parameters needed * to initialize the LCML * * @param pHandle OMX Handle * * @param plcml_Init LCML initialization parameters * * @return OMX_ErrorNone = Successful * Other error code = fail * */ /*================================================================== */ OMX_ERRORTYPE G722ENC_Fill_LCMLInitParams(OMX_HANDLETYPE pHandle, LCML_DSP *plcml_Init); /* =========================================================== */ /** * G722ENC_GetBufferDirection() Returns direction of pBufHeader * * @param pBufHeader Buffer header * * @param eDir Buffer direction * * @param pComponentPrivate Component private data * * @return OMX_ErrorNone = Successful * Other error code = fail */ /*================================================================== */ OMX_ERRORTYPE G722ENC_GetBufferDirection(OMX_BUFFERHEADERTYPE *pBufHeader, OMX_DIRTYPE *eDir, G722ENC_COMPONENT_PRIVATE *pComponentPrivate); /* =========================================================== */ /** * G722ENC_LCML_Callback() Callback from LCML * * @param event Codec Event * * @param args Arguments from LCML * * @return OMX_ErrorNone = Successful * Other error code = fail */ /*================================================================== */ OMX_ERRORTYPE G722ENC_LCML_Callback (TUsnCodecEvent event,void * args [10]); /* =========================================================== */ /** * G722ENC_HandleCommand() Handles commands sent via SendCommand() * * @param pComponentPrivate Component private data * * @return OMX_ErrorNone = Successful * Other error code = fail */ /*================================================================== */ OMX_U32 G722ENC_HandleCommand (G722ENC_COMPONENT_PRIVATE *pComponentPrivate); /* =========================================================== */ /** * G722ENC_HandleDataBuf_FromApp() Handles data buffers received * from application * * @param pBufHeader Buffer header * * @param pComponentPrivate Component private data * * @return OMX_ErrorNone = Successful * Other error code = fail */ /*================================================================== */ OMX_ERRORTYPE G722ENC_HandleDataBuf_FromApp(OMX_BUFFERHEADERTYPE *pBufHeader, G722ENC_COMPONENT_PRIVATE *pComponentPrivate); /* =========================================================== */ /** * G722ENC_HandleDataBuf_FromLCML() Handles data buffers received * from LCML * * @param pComponentPrivate Component private data * * @return OMX_ErrorNone = Successful * Other error code = fail */ /*================================================================== */ /***** NO LCML ******* OMX_ERRORTYPE G722ENC_HandleDataBuf_FromLCML(G722ENC_COMPONENT_PRIVATE* pComponentPrivate); **********************/ /* =========================================================== */ /** * GetLCMLHandle() * * @param * * @return * */ /*================================================================== */ OMX_HANDLETYPE GetLCMLHandle(); /* =========================================================== */ /** * G722ENC_GetCorresponding_LCMLHeader() Returns LCML header * that corresponds to the given buffer * * @param pComponentPrivate Component private data * * @return OMX_ErrorNone = Successful * Other error code = fail */ /*================================================================== */ OMX_ERRORTYPE G722ENC_GetCorresponding_LCMLHeader(OMX_U8 *pBuffer, OMX_DIRTYPE eDir, G722ENC_LCML_BUFHEADERTYPE **ppLcmlHdr); /* =========================================================== */ /** * G722Enc_FreeCompResources() Frees component resources * * @param pComponent OMX Handle * * @return OMX_ErrorNone = Successful * Other error code = fail */ /*================================================================== */ OMX_ERRORTYPE G722Enc_FreeCompResources(OMX_HANDLETYPE pComponent); /* =========================================================== */ /** * G722Enc_StartCompThread() Starts component thread * * @param pComponent OMX Handle * * @return OMX_ErrorNone = Successful * Other error code = fail */ /*================================================================== */ OMX_ERRORTYPE G722Enc_StartCompThread(OMX_HANDLETYPE pComponent); /* =========================================================== */ /** * G722ENC_GetLCMLHandle() Returns handle to the LCML * * * @return Handle to the LCML */ /*================================================================== */ OMX_HANDLETYPE G722ENC_GetLCMLHandle(); /* ========================================================================== */ /** * @G722ENC_StopComponentThread() This function is called by the component during * de-init to close component thread. * * @param pComponent handle for this instance of the component * * @pre * * @post * * @return none */ /* ========================================================================== */ OMX_ERRORTYPE G722ENC_StopComponentThread(OMX_HANDLETYPE pComponent); /* =========================================================== */ /** * G722ENC_FreeLCMLHandle() Frees the handle to the LCML * * * @return OMX_ErrorNone = Successful * Other error code = fail */ /*================================================================== */ OMX_ERRORTYPE G722ENC_FreeLCMLHandle(); /* =========================================================== */ /** * G722ENC_CleanupInitParams() Starts component thread * * @param pComponent OMX Handle * * @return OMX_ErrorNone = Successful * Other error code = fail */ /*================================================================== */ OMX_ERRORTYPE G722ENC_CleanupInitParams(OMX_HANDLETYPE pComponent); /* =========================================================== */ /** * G722ENC_CommandToIdle() Called when the component is commanded * to idle * * @param pComponentPrivate Component private data * * @return OMX_ErrorNone = Successful * Other error code = fail */ /*================================================================== */ OMX_ERRORTYPE G722ENC_CommandToIdle(G722ENC_COMPONENT_PRIVATE *pComponentPrivate); /* =========================================================== */ /** * G722ENC_CommandToIdle() Called when the component is commanded * to idle * * @param pComponentPrivate Component private data * * @return OMX_ErrorNone = Successful * Other error code = fail */ /*================================================================== */ OMX_ERRORTYPE G722ENC_CommandToLoaded(G722ENC_COMPONENT_PRIVATE *pComponentPrivate); /* =========================================================== */ /** * G722ENC_CommandToExecuting() Called when the component is commanded * to executing * * @param pComponentPrivate Component private data * * @return OMX_ErrorNone = Successful * Other error code = fail */ /*================================================================== */ OMX_ERRORTYPE G722ENC_CommandToExecuting(G722ENC_COMPONENT_PRIVATE *pComponentPrivate); /* =========================================================== */ /** * G722ENC_CommandToPause() Called when the component is commanded * to paused * * @param pComponentPrivate Component private data * * @return OMX_ErrorNone = Successful * Other error code = fail */ /*================================================================== */ OMX_ERRORTYPE G722ENC_CommandToPause(G722ENC_COMPONENT_PRIVATE *pComponentPrivate); /* =========================================================== */ /** * G722ENC_CommandToWaitForResources() Called when the component is commanded * to WaitForResources * * @param pComponentPrivate Component private data * * @return OMX_ErrorNone = Successful * Other error code = fail */ /*================================================================== */ OMX_ERRORTYPE G722ENC_CommandToWaitForResources(G722ENC_COMPONENT_PRIVATE *pComponentPrivate); /* =========================================================== */ /** * G722ENC_SetPending() Called when the component queues a buffer * to the LCML * * @param pComponentPrivate Component private data * * @param pBufHdr Buffer header * * @param eDir Direction of the buffer * * @return None */ /*================================================================== */ void G722ENC_SetPending(G722ENC_COMPONENT_PRIVATE *pComponentPrivate, OMX_BUFFERHEADERTYPE *pBufHdr, OMX_DIRTYPE eDir); /* =========================================================== */ /** * G722ENC_ClearPending() Called when a buffer is returned * from the LCML * * @param pComponentPrivate Component private data * * @param pBufHdr Buffer header * * @param eDir Direction of the buffer * * @return None */ /*================================================================== */ void G722ENC_ClearPending(G722ENC_COMPONENT_PRIVATE *pComponentPrivate, OMX_BUFFERHEADERTYPE *pBufHdr, OMX_DIRTYPE eDir) ; /* =========================================================== */ /** * G722ENC_IsPending() Returns the status of a buffer * * @param pComponentPrivate Component private data * * @param pBufHdr Buffer header * * @param eDir Direction of the buffer * * @return None */ /*================================================================== */ OMX_U32 G722ENC_IsPending(G722ENC_COMPONENT_PRIVATE *pComponentPrivate, OMX_BUFFERHEADERTYPE *pBufHdr, OMX_DIRTYPE eDir); /* =========================================================== */ /** * G722ENC_Fill_LCMLInitParamsEx() Fills the parameters needed * to initialize the LCML without recreating the socket node * * @param pComponent OMX Handle * * @return None */ /*================================================================== */ OMX_ERRORTYPE G722ENC_Fill_LCMLInitParamsEx(OMX_HANDLETYPE pComponent); /* =========================================================== */ /** * G722ENC_IsValid() Returns whether the buffer is a valid buffer * * @param pComponentPrivate Component private data * * @param pBuffer Buffer * * @param eDir Direction of the buffer * * @return None */ /*================================================================== */ OMX_U32 G722ENC_IsValid(G722ENC_COMPONENT_PRIVATE *pComponentPrivate, OMX_U8 *pBuffer, OMX_DIRTYPE eDir) ; /* =========================================================== */ /** * G722ENC_TransitionToIdle() Transitions component to idle * * * @param pComponentPrivate Component private data * * @return OMX_ErrorNone = No error * OMX Error code = Error */ /*================================================================== */ OMX_ERRORTYPE G722ENC_TransitionToIdle(G722ENC_COMPONENT_PRIVATE *pComponentPrivate); /*void printEmmEvent (TUsnCodecEvent event);*/
<gh_stars>0 #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <math.h> #include "QueueAndFunctions.h" #define BUFSIZE 1000 int main( int argc, char *argv[] ){ /* Assigning command line arguments to corresponding variables. */ int windowSize = atoi( argv[1] ); float dataSize = atoi( argv[2] ); float packetSize = atoi( argv[3] ); int timeOut = atoi( argv[4] ); int roundTripTime = atoi( argv[5] ); int numOfTotalPackets = ( dataSize + packetSize - 1 ) / packetSize; float dataSizeForPrint = dataSize; /* Creating packets. */ Queue *allPackets = createQueue(); int i; for ( i = 0; i < numOfTotalPackets; i++ ){ if ( dataSize >= packetSize ){ packet * currentPacket = newPacket( i, packetSize, false ); enQueue( allPackets, currentPacket ); dataSize = dataSize - packetSize; } else { packet * currentPacket = newPacket( i, dataSize, false ); enQueue( allPackets, currentPacket ); dataSize = 0; } } /* Determining packets which will be dropped.*/ FILE *f; f = fopen( argv[6], "r" ); char buff[BUFSIZE]; while ( fgets( buff, BUFSIZE - 1, f ) != NULL){ int a = atoi( buff ); packet * iter = allPackets->firstPacket; while ( iter->next != NULL ){ if ( iter->packetId == a ){ iter->ifDropped++; break; } else iter = iter->next; } } fclose(f); /* Creating WINDOW. */ Queue * window; window = createQueue(); int numOfDroppedPackets = 0; float sentDataSize = 0; int seconds = 0; int minutes = 0; int hours = 0; /* Starting simulation. */ simulationTimes( hours, minutes, seconds ); printf("<EVENTS>\n"); printf("- Data size sent so far is %4.2f Byte\n", sentDataSize); printQueue( *window ); seconds++; while ( allPackets->lastPacket != NULL || window->lastPacket != NULL ){ simulationTimes( hours, minutes, seconds ); printf("<EVENTS>\n"); if( window->queueSize < windowSize && allPackets->lastPacket != NULL ){ packet * currentPacket = dequeue(allPackets); enQueue( window, currentPacket ); printf("- A new data packet (id:%d) has now been sent!\n", currentPacket->packetId); printf("- Data size sent so far is %4.2f Byte\n", sentDataSize); window->queueSize++; counterForElapsedTime( window ,roundTripTime ); printQueue( *window ); } else { float ifDataACK = checkForACK( window, roundTripTime ); numOfDroppedPackets = checkForDroppedPacket( window, timeOut, numOfDroppedPackets ); checkForSentData( window, allPackets ); counterForElapsedTime( window ,roundTripTime ); if ( ifDataACK > 0) { sentDataSize += ifDataACK; printf("- Data size sent so far is %4.2f Byte\n", sentDataSize); } else printf("- Data size sent so far is %4.2f Byte\n", sentDataSize); printQueue( *window ); } seconds++; } /* Printing the transfer report. */ int totalTime = numOfTotalPackets * roundTripTime; totalTime = totalTime + numOfDroppedPackets * timeOut; float averageTime = (float)totalTime / (float)numOfTotalPackets; printf("***************************************************\n" "* TRANSFER REPORT *\n" "***************************************************\n" "Parameter Setting:\n" "---------------------------------------------------\n" "Window Size : %02d\n" "Timeout : %04d Sec.\n" "RTT : %04d Sec.\n" "Data Size : %4.2f Byte\n" "Packet Size : %4.2f Byte\n" "---------------------------------------------------\n" , windowSize, timeOut, roundTripTime, dataSizeForPrint, packetSize); printf("Results:\n" "---------------------------------------------------\n" "Number of packet to send the data : %04.0f\n" "Number of packet dropped : %04d\n" "Average time to send a single packet : %3.3f Sec.\n" "***************************************************", (float)numOfTotalPackets, numOfDroppedPackets, averageTime); /* Deallocate allocated memory */ free( window ); free( allPackets ); return 0; }
<gh_stars>100-1000 /* * @(#)graphics.c 1.2 01/03/85 * * Graphics routines for the SUN Gremlin picture editor. * * <NAME> (<EMAIL>) * */ #include <suntool/tool_hs.h> #include <vfont.h> #include "icondata.h" #include "gremlin.h" /* imports from main.c */ extern error(); extern struct pixwin *pix_pw; extern struct rect pix_size; extern struct pixrect *cset_pr; extern struct pixrect *scratch_pr; extern ELT *cset; extern Artmode; extern CSIZE; extern CFONT; extern CsetOn; extern SUN_XORIGIN; extern SUN_YORIGIN; /* imports from display.c */ extern minsunx, maxsunx, minsuny, maxsuny; /* imports from C */ extern char *malloc(); /* forward references */ extern char *GRReadFontFile(); /* symbolic font from text.c */ extern struct pixfont *text_pf; /* locally defined variables */ int charysizes[NFONTS][NSIZES]; /* Character y dimensions for each size */ int curve_set; /* TRUE if spline points pre-computed */ int linestyle; /* Current line style */ int linemod; /* Type of line (SOLID, DOTTED, ...) */ int linethickness; /* 1, 2, 3 */ char fontdir[128] = "/usr/lib/font/devsun/"; char stippledir[128] = "/usr/lib/font/devsun/"; char stippletype[32] = "cf"; char *font_types[NFONTS] = { "R", "I", "B", "S" }; int font_sizes[NSIZES] = { 7, 10, 14, 24 }; int stipple_index[NSTIPPLES] = { 1, 3, 12, 14, 16, 19, 21, 23 }; /* NOTE: all stipple fonts are expected to be 32 x 32 bit rasters */ /* pointers to the stipple pixrects (16 x 16 bits) in the menu ... */ struct pixrect *stipple_prs[NSTIPPLES] = { &stipple1_pr, &stipple2_pr, &stipple3_pr, &stipple4_pr, &stipple5_pr, &stipple6_pr, &stipple7_pr, &stipple8_pr }; /* ... and the corresponding images (32 x 32 bits) from the vfont file */ char stipple_patterns[NSTIPPLES][128]; /* data used in graphics2.c for drawing polygons */ int rasterlength; /* real # horizontal bits in scratch_pr */ int bytesperline; /* rasterlength / 8 */ int nlines; /* # horizontal bits defined by scratch_pr */ char *fill; /* pointer to scratch_pr image */ /* * This matrix points to the DISPATCH data for each font/size pair * if an unsuccesful attempt is made to open a particular font/size pair, * its entry in this table is marked as -1. */ char *font_info[NFONTS][NSIZES] = { { NULL, NULL, NULL, NULL }, { NULL, NULL, NULL, NULL }, { NULL, NULL, NULL, NULL }, { NULL, NULL, NULL, NULL }, }; struct pixrect *char_pr; /* Splines use these global arrays */ static float h[MAXPOINTS]; static float x[MAXPOINTS], dx[MAXPOINTS], d2x[MAXPOINTS], d3x[MAXPOINTS]; static float y[MAXPOINTS], dy[MAXPOINTS], d2y[MAXPOINTS], d3y[MAXPOINTS]; static numpoints; /* These are used as bit masks to create the right style lines. */ #define SOLID -1 #define DOTTED 002 #define DASHED 004 #define DOTDASHED 012 /* * This routine sets the current line style. */ GRSetLineStyle(style) int style; /* new stipple pattern for lines */ { switch (linestyle = style) { case 1: /* dotted */ linemod = DOTTED; linethickness = 1; break; case 2: /* broken */ linemod = DOTDASHED; linethickness = 1; break; case 3: /* thick */ linemod = SOLID; linethickness = 3; break; case 4: /* dashed */ linemod = DASHED; linethickness = 1; break; case 5: /* narrow */ linemod = SOLID; linethickness = 1; break; case 6: /* medium */ linemod = SOLID; linethickness = 2; break; } } /* * This routine returns the maximum vertical size (in bits) of a character * of the specified font/size. */ GRGetCharYSize(font, size) register font; /* character font (1 - 4) */ register size; /* character size (1 - 4) */ { return(charysizes[--font][--size]); } #define pi 3.14159265359 #define twopi 6.28318530718 #define log2_10 3.321915 /* * Draw arc - always to scratch_pr. * Note: must check for zero radius before calling. */ GRArc(center, cpoint, angle, style) register POINT *center, *cpoint; float angle; register style; { double radius, resolution, t1, fullcircle; double degreesperpoint; float xs, ys, epsilon; float x1, y1, x2, y2; register i, extent; xs = cpoint->x - center->x; ys = cpoint->y - center->y; /* calculate drawing parameters */ radius = sqrt((double) (xs * xs + ys * ys)); t1 = floor(log10(radius) * log2_10); resolution = pow(2.0, t1); epsilon = (float) 1.0 / resolution; fullcircle = ceil(twopi * resolution); degreesperpoint = 360.0 / fullcircle; extent = (angle == 0) ? fullcircle : angle/degreesperpoint; GRSetLineStyle(style); x1 = cpoint->x; y1 = cpoint->y; for (i=0; i<extent; ++i) { xs -= epsilon * ys; x2 = xs + center->x; ys += epsilon * xs; y2 = ys + center->y; GRVector(x1, y1, x2, y2); x1 = x2; y1 = y2; } } /* end GRArc */; /* This routine calculates parameteric values for use in calculating * curves. The values are an approximation of cumulative arc lengths * of the curve (uses cord * length). For additional information, * see paper cited below. */ static Paramaterize(x, y, h, n) float x[MAXPOINTS]; float y[MAXPOINTS]; float h[MAXPOINTS]; register n; { register i, j; float t1, t2; float u[MAXPOINTS]; n = numpoints; for (i=1; i<=n; ++i) { u[i] = 0.0; for (j=1; j<i; ++j) { t1 = x[j+1] - x[j]; t2 = y[j+1] - y[j]; u[i] += (float) sqrt((double) ((t1 * t1) + (t2 * t2))); } } for (i=1; i<n; ++i) h[i] = u[i+1] - u[i]; } /* end Paramaterize */ /* * This routine solves for the cubic polynomial to fit a spline * curve to the the points specified by the list of values. * The curve generated is periodic. The alogrithms for this * curve are from the "Spline Curve Techniques" paper cited below. */ static PeriodicSpline(h, z, dz, d2z, d3z, npoints) float h[MAXPOINTS]; /* paramaterization */ float z[MAXPOINTS]; /* point list */ float dz[MAXPOINTS]; /* to return the 1st derivative */ float d2z[MAXPOINTS]; /* 2nd derivative */ float d3z[MAXPOINTS]; /* and 3rd derivative */ register npoints; /* number of valid points */ { float a[MAXPOINTS]; float b[MAXPOINTS]; float c[MAXPOINTS]; float d[MAXPOINTS]; float deltaz[MAXPOINTS]; float r[MAXPOINTS]; float s[MAXPOINTS]; float ftmp; register i; /* step 1 */ for (i=1; i<npoints; ++i) { if (h[i] != 0) deltaz[i] = (z[i+1] - z[i]) / h[i]; else deltaz[i] = 0; } h[0] = h[npoints-1]; deltaz[0] = deltaz[npoints-1]; /* step 2 */ for (i=1; i<npoints-1; ++i) { d[i] = deltaz[i+1] - deltaz[i]; } d[0] = deltaz[1] - deltaz[0]; /* step 3a */ a[1] = 2 * (h[0] + h[1]); if (a[1] == 0) return(-1); /* 3 consecutive knots at same point */ b[1] = d[0]; c[1] = h[0]; for (i=2; i<npoints-1; ++i) { ftmp = h[i-1]; a[i] = ftmp + ftmp + h[i] + h[i] - (ftmp * ftmp)/a[i-1]; if (a[i] == 0) return(-1); /* 3 consec knots at same point */ b[i] = d[i-1] - ftmp * b[i-1]/a[i-1]; c[i] = -ftmp * c[i-1]/a[i-1]; } /* step 3b */ r[npoints-1] = 1; s[npoints-1] = 0; for (i=npoints-2; i>0; --i) { r[i] = -(h[i] * r[i+1] + c[i])/a[i]; s[i] = (6 * b[i] - h[i] * s[i+1])/a[i]; } /* step 4 */ d2z[npoints-1] = (6 * d[npoints-2] - h[0] * s[1] - h[npoints-1] * s[npoints-2]) / (h[0] * r[1] + h[npoints-1] * r[npoints-2] + 2 * (h[npoints-2] + h[0])); for (i=1; i<npoints-1; ++i) { d2z[i] = r[i] * d2z[npoints-1] + s[i]; } d2z[npoints] = d2z[1]; /* step 5 */ for (i=1; i<npoints; ++i) { dz[i] = deltaz[i] - h[i] * (2 * d2z[i] + d2z[i+1])/6; if (h[i] != 0) d3z[i] = (d2z[i+1] - d2z[i])/h[i]; else d3z[i] = 0; } return(0); } /* end PeriodicSpline */ /* * This routine solves for the cubic polynomial to fit a spline * curve from the points specified by the list of values. The alogrithms for * this curve are from the "Spline Curve Techniques" paper cited below. */ static NaturalEndSpline(h, z, dz, d2z, d3z, npoints) float h[MAXPOINTS]; /* paramaterization */ float z[MAXPOINTS]; /* point list */ float dz[MAXPOINTS]; /* to return the 1st derivative */ float d2z[MAXPOINTS]; /* 2nd derivative */ float d3z[MAXPOINTS]; /* and 3rd derivative */ register npoints; /* number of valid points */ { float a[MAXPOINTS]; float b[MAXPOINTS]; float d[MAXPOINTS]; float deltaz[MAXPOINTS]; float ftmp; register i; /* step 1 */ for (i=1; i<npoints; ++i) { if (h[i] != 0) deltaz[i] = (z[i+1] - z[i]) / h[i]; else deltaz[i] = 0; } deltaz[0] = deltaz[npoints-1]; /* step 2 */ for (i=1; i<npoints-1; ++i) { d[i] = deltaz[i+1] - deltaz[i]; } d[0] = deltaz[1] - deltaz[0]; /* step 3 */ a[0] = 2 * (h[2] + h[1]); if (a[0] == 0) /* 3 consec knots at same point */ return(-1); b[0] = d[1]; for (i=1; i<npoints-2; ++i) { ftmp = h[i+1]; a[i] = ftmp + ftmp + h[i+2] + h[i+2] - (ftmp * ftmp) / a[i-1]; if (a[i] == 0) /* 3 consec knots at same point */ return(-1); b[i] = d[i+1] - ftmp * b[i-1]/a[i-1]; } /* step 4 */ d2z[npoints] = d2z[1] = 0; for (i=npoints-1; i>1; --i) { d2z[i] = (6 * b[i-2] - h[i] *d2z[i+1])/a[i-2]; } /* step 5 */ for (i=1; i<npoints; ++i) { dz[i] = deltaz[i] - h[i] * (2 * d2z[i] + d2z[i+1])/6; if (h[i] != 0) d3z[i] = (d2z[i+1] - d2z[i])/h[i]; else d3z[i] = 0; } return(0); } /* end NaturalEndSpline */ #define PointsPerInterval 16 /* * This routine computes a smooth curve through a set of points. * Returns -1 if there are too many knots to draw the curve. * Use GRCurve AFTER this routine to actually draw the curve. * [Formerly the first half of GRCurve()] * * The method used is the parametric spline curve on unit knot mesh described * in "Spline Curve Techniques" by <NAME>, <NAME>, and * <NAME> -- Xerox Parc. */ GRSetCurve(pointlist) POINT *pointlist; { register POINT *ptr; register i, stat; /* Copy point list to array for easier access */ ptr = pointlist; for (i=1; (!Nullpoint(ptr)); ++i) { x[i] = ptr->x; y[i] = ptr->y; ptr = PTNextPoint(ptr); } /* Solve for derivatives of the curve at each point separately for x and y (parametric). */ numpoints = i - 1; /* set global numpoints */ Paramaterize(x, y, h, numpoints); stat = 0; if ((x[1] == x[numpoints]) && (y[1] == y[numpoints])) { /* closed curve */ stat |= PeriodicSpline(h, x, dx, d2x, d3x, numpoints); stat |= PeriodicSpline(h, y, dy, d2y, d3y, numpoints); } else { stat |= NaturalEndSpline(h, x, dx, d2x, d3x, numpoints); stat |= NaturalEndSpline(h, y, dy, d2y, d3y, numpoints); } curve_set = 1; /* indicates that paramterization is done */ return(stat); } /* * This routine displays a smooth curve through a set of points. The * method used is the parametric spline curve on unit knot mesh described * in "Spline Curve Techniques" by <NAME>, <NAME>, and * <NAME> -- <NAME>. * [formerly the second half of GRCurve()] * * Uses the data computed first by GRSetCurve(). * GRSetCurve() MUST be called before this routine and have returned a ZERO. */ GRCurve(style) int style; { float t, t2, t3, xinter, yinter; float x1, y1, x2, y2; register j, k; GRSetLineStyle(style); x1 = x[1]; y1 = y[1]; /* generate the curve using the information from GRSetCurve() and PointsPerInterval vectors between each specified knot. */ for (j=1; j<numpoints; ++j) { for (k=0; k<=PointsPerInterval; ++k) { t = (float) k * h[j] / (float) PointsPerInterval; t2 = t * t; t3 = t2 * t; x2 = x[j] + t * dx[j] + t2 * d2x[j]/2.0 + t3 * d3x[j]/6.0; y2 = y[j] + t * dy[j] + t2 * d2y[j]/2.0 + t3 * d3y[j]/6.0; GRVector(x1, y1, x2, y2); x1 = x2; y1 = y2; } } } /* end GRCurve */ /* * This routine clears the Gremlin pix subwindow or current set * pixrect image as specified in the mask. */ GRClear(mask) register mask; { if (mask & pixmask) pw_writebackground(pix_pw, 0, 0, 2000, 2000, PIX_SRC); if (mask & csetmask) pr_rop(cset_pr, 0, 0, 2000, 2000, PIX_SRC, NULL, 0, 0); } /* end GRClear */ /* * Display justification of TEXT element. */ GRDisplayJustify(elt) register ELT *elt; { register POINT *point; register x, y, length, ysize; ysize = GRGetCharYSize(elt->brushf, elt->size); length = GRFontStrlen(elt->textpt, elt->brushf, elt->size); point = PTNextPoint(elt->ptlist); /* lower left corner of text */ x = dbx_to_win(point->x); y = dby_to_win(point->y); switch (elt->type) { case TOPLEFT: y -= ysize; break; case TOPCENT: y -= ysize; x += (length >> 1); break; case TOPRIGHT: y -= ysize; x += length; break; case CENTLEFT: y -= (ysize >> 1); break; case CENTCENT: y -= (ysize >> 1); x += (length >> 1); break; case CENTRIGHT: y -= (ysize >> 1); x += length; break; case BOTLEFT: break; case BOTCENT: x += (length >> 1); break; case BOTRIGHT: x += length; break; } pw_write(pix_pw, x - 2, y - 2, 5, 5, PIX_SRC ^ PIX_DST, &dot_pr, 0, 0); pr_rop(cset_pr, x - 2, y - 2, 5, 5, PIX_SRC ^ PIX_DST, &dot_pr, 0, 0); } /* * This routine displays a point (layed down by the user) in the * pix subwindow. */ GRDisplayPoint(dbx, dby, number) float dbx, dby; /* data base coordinates */ register number; /* point number */ { register x, y; char numbuf[5]; x = dbx_to_win(dbx); y = dby_to_win(dby); if (Artmode) pw_write(pix_pw, x-1, y-1, 3, 3, PIX_SRC ^ PIX_DST, &littlepoint_pr, 3, 2); else { pw_write(pix_pw, x-3, y-3, 7, 7, PIX_SRC ^ PIX_DST, &littlepoint_pr, 1, 7); (void) sprintf(numbuf, "%d", number+1); pw_text(pix_pw, x+5, y+3, PIX_SRC^PIX_DST, text_pf, numbuf); } } /* end GRDisplayPoint */ /* * This routine erases the specified point. */ GRErasePoint(dbx, dby, number) float dbx, dby; register number; { GRDisplayPoint(dbx, dby, number); } /* end GRErasePoint */ /* * This routine clears all points in plist. */ GRBlankPoints(plist) register POINT *plist; { register i = 0; while (!Nullpoint(plist)) { GRErasePoint(plist->x, plist->y, i++); plist = PTNextPoint(plist); } } /* end GRBlankPoints */ /* * This routine displays the grid. */ GRDisplayGrid() { pw_replrop(pix_pw, 0, 0, 2000, 2000, PIX_SRC ^ PIX_DST, &replgrid32_pr, 0, 0); } /* end GRDisplayGrid */ /* * This routine erases the grid. */ GRBlankGrid() { GRDisplayGrid(); } /* end GRBlankGrid */ /* * Flash current set display. */ GRCurrentSet() { if (DBNullelt(cset)) return; pw_write(pix_pw, 0, 0, pix_size.r_width, pix_size.r_height, PIX_SRC ^ PIX_DST, cset_pr, 0, 0); CsetOn = !CsetOn; } /* * Make current set on. */ GRCurrentSetOn() { if (!CsetOn) GRCurrentSet(); } /* * Make current set off. */ GRCurrentSetOff() { if (CsetOn) GRCurrentSet(); } /* * Return TRUE if font file exists and is readable. */ GRfontfound(font, size) register font, size; { return(font_info[font-1][size-1] != (char *) -1); } /* * Open the default font file on startup. */ GRFontInit() { /* create memory pixrect template for displaying text with GRPutText() */ if ((char_pr = mem_create(1, 1, 1)) == NULL) { printf("GRFontInit: can't create char_pr\n"); exit(1); } GROpenFont(CFONT, CSIZE); GRStippleInit(); } /* end GRFontInit */ /* * Initialize stipple patterns from font file. * Big assumption: all stipples are defined by 32 x 32 bit patterns. * All fonts do not contain exactly 32 rows of 4 bytes - this is ok - * Fonts wider than 32 bits will be clipped. */ GRStippleInit() { register struct mpr_data *mpr_data; register char *from, *to; register char *fbase; register i, j, k; struct dispatch *dispatch, *dstart; int width, height, bytewidth; char *stipple_info; char name[128]; (void) sprintf(name, "%s%s.0", stippledir, stippletype); if ((stipple_info = GRReadFontFile(name)) == (char *) -1) { /* * use default stipple pixrects since we can't read the * user specified stipple font file. * copy stipple pixrects to stipple_patterns for display */ for (i=0; i<NSTIPPLES; i++) GRCopyStipple(i); return; } dstart = (struct dispatch *) (stipple_info + sizeof(struct header)); fbase = (char *) ((char *) dstart + NUM_DISPATCH * sizeof(struct dispatch)); for (i=0; i<NSTIPPLES; i++) { mpr_data = (struct mpr_data *) stipple_prs[i]->pr_data; dispatch = dstart + stipple_index[i]; if (dispatch->nbytes != 0) { width = dispatch->left + dispatch->right; height = dispatch->up + dispatch->down; bytewidth = (width + 7) >> 3; if (bytewidth > 4) /* force size constraint */ bytewidth = 4; /* pattern screwed up if ever > 4 */ from = (char *) ((char *) fbase + dispatch->addr); to = stipple_patterns[i]; for (j=1; j<=height; j++) { /* copy font entry to known location */ for (k=1; k<=bytewidth; k++) *to++ = *from++; for ( ;k<=4; k++) *to++ = '\0'; } for ( ; j<=32; j++) /* fix up any non- 32 x 32 font */ for (k=1; k<=4; k++) *to++ = '\0'; /* copy vfont stipple to stipple pixrect for menu display */ /* can only display a 16 x 16 menu icon */ from = stipple_patterns[i]; to = (char *) mpr_data->md_image; for (j=0; j<16; j++) { *to++ = *from++; *to++ = *from++; from += 2; } } else { (void) sprintf(name, "stipple index=%d not defined", stipple_index[i]); error(name); /* copy stipple pixrect to stipple_patterns for display */ GRCopyStipple(i); } } /* bit maps are all in core now */ free(stipple_info); /* set up parameters for drawing polygons */ mpr_data = (struct mpr_data *) scratch_pr->pr_data; bytesperline = mpr_data->md_linebytes; fill = (char *) mpr_data->md_image; rasterlength = bytesperline << 3; nlines = scratch_pr->pr_size.x; } /* end GRStippleInit */; /* * Copy the stipple bit map image as defined in the menu pixrect * to the bit maps used for drawing polygons. The pixrect bit map * is 16 x 16 bits and the target bit map is 32 x 32 bits. The * image is expanded appropriately. */ GRCopyStipple(index) int index; { register struct mpr_data *mpr_data; register char *from, *to; register i, j; mpr_data = (struct mpr_data *) stipple_prs[index]->pr_data; from = (char *) mpr_data->md_image; to = stipple_patterns[index]; for (i=0; i<16; i++) { j = i << 2; to[j] = to[j+2] = to[j+64] = to[j+66] = *from++; to[j+1] = to[j+3] = to[j+65] = to[j+67] = *from++; } } /* * Open a font file for use by first reading it into memory. * If the file is read successfully, the appropriate entry in * font_info[] is set to point to its memory image. If the * file cannot be opened or there is a error in reading the * file, set the font_info[] entry to -1. */ GROpenFont(font, size) register font; /* font is 1 to 4 */ register size; /* size is 1 to 4 */ { char name[128]; if (font_info[--font][--size] != NULL) /* already tried to open */ return; sprintf(name, "%s%s.%d", fontdir, font_types[font], font_sizes[size]); if ((font_info[font][size] = GRReadFontFile(name)) == (char *) -1) return; /* height of this font/size combination */ charysizes[font][size] = ((struct header *) font_info[font][size])->maxy; } /* end GROpenFont */ /* * Read a font file into memory and return a pointer to its * memory image, or -1 if any error occurs. */ char * GRReadFontFile(file) char *file; { char *image; /* pointer to font memory image */ char msg[128]; struct header header; int fd, filesize; if ((fd = open(file, 0)) < 0) { sprintf(msg, "can't open font file: %s", file); error(msg); return((char *) -1); } if (read(fd, &header, sizeof(struct header)) != sizeof(struct header)) { sprintf(msg, "can't read font header: %s\n", file); error(msg); return((char *) -1); } if (header.magic != VFONT_MAGIC) { sprintf(msg, "bad magic number %o in font file\n", header.magic); error(msg); return((char *) -1); } filesize = (sizeof(struct header) + sizeof(struct dispatch) * NUM_DISPATCH + header.size); if ((image = malloc(filesize)) == NULL) { error("not enough memory for font file"); return((char *) -1); } lseek(fd, (long) 0, 0); if (read(fd, image, filesize) != filesize) { error("can't read font file"); return((char *) -1); } close(fd); return(image); } /* end GRReadFontFile */ /* * Determine pixel length of string s in font and size. */ GRFontStrlen(text, font, size) char *text; int font; /* 1 - 4 */ int size; /* 1 - 4 */ { register struct dispatch *dispatch, *start; register length, spacewidth; if (*text == '\0') return(0); if (font_info[font-1][size-1] == NULL) /* not open yet */ GROpenFont(font, size); if (!GRfontfound(font, size)) /* unreadable font */ return(0); start = (struct dispatch *) (font_info[font-1][size-1] + sizeof(struct header)); spacewidth = font_sizes[size-1] * (120.0 / 216.0) + 0.5; length = 0; while (*text != '\0') { dispatch = start + (*text); if (*text == ' ') length += spacewidth; else if (dispatch->nbytes != 0) length += dispatch->width; text++; } return(length); } /* * Display text string of font/size at position pos. */ GRPutText(text, font, size, pos) char *text; int font, size; POINT *pos; { register struct dispatch *dispatch, *dstart; register struct mpr_data *mpr_data; register char *fbase; register width, height, spacewidth; int x, y; if (font_info[font-1][size-1] == NULL) GROpenFont(font, size); if (!GRfontfound(font, size)) return; dstart = (struct dispatch *) (font_info[font-1][size-1] + sizeof(struct header)); fbase = (char *) ((char *) dstart + NUM_DISPATCH * sizeof(struct dispatch)); x = dbx_to_win(pos->x); y = dby_to_win(pos->y); /* define region of screen to be drawn with text */ minsunx = x; maxsuny = y + 8; /* catch descenders */ minsuny = y - GRGetCharYSize(font, size); spacewidth = font_sizes[size-1] * (120.0 / 216.0) + 0.5; mpr_data = (struct mpr_data *) char_pr->pr_data; while (*text != '\0') { dispatch = dstart + (*text); if (*text == ' ') x += spacewidth; else if (dispatch->nbytes != 0) { mpr_data->md_image = (short *) ((char *) fbase + dispatch->addr); char_pr->pr_size.x = width = dispatch->left + dispatch->right; char_pr->pr_size.y = height = dispatch->up + dispatch->down; mpr_data->md_linebytes = ((width + 15) >> 3) & ~1; if (*text != ' ') pr_rop(scratch_pr, x - dispatch->left, y - dispatch->up, width, height, PIX_SRC ^ PIX_DST, char_pr, 0, 0); x += dispatch->width; } text++; } maxsunx = x; } /* end GRPutText */; /* * Set the actual positioning point for text with the justify, font, and * size attributes. Point is a pointer to the POINT layed down by the user. * Pos is a pointer to the returned positioning POINT used in a subsequent * call to GRPutText(). */ GRSetTextPos(text, justify, font, size, point, pos) char *text; int justify, font, size; POINT *point, *pos; { register length; register charysize; charysize = GRGetCharYSize(font, size); length = GRFontStrlen(text, font, size); switch (justify) { case BOTLEFT: pos->x = point->x; pos->y = point->y; break; case BOTCENT: pos->x = point->x - (length / 2); pos->y = point->y; break; case BOTRIGHT: pos->x = point->x - length; pos->y = point->y; break; case CENTLEFT: pos->x = point->x; pos->y = point->y - (charysize / 2); break; case CENTCENT: pos->x = point->x - (length / 2); pos->y = point->y - (charysize / 2); break; case CENTRIGHT: pos->x = point->x - length; pos->y = point->y - (charysize / 2); break; case TOPLEFT: pos->x = point->x; pos->y = point->y - charysize; break; case TOPCENT: pos->x = point->x - (length / 2); pos->y = point->y - charysize; break; case TOPRIGHT: pos->x = point->x - length; pos->y = point->y - charysize; break; } }
<filename>ios/dist/ViroRenderer/x86_64/ViroKit.framework/Headers/VROPhysicsWorld.h<gh_stars>0 // // VROPhysicsWorld.h // ViroRenderer // // Copyright © 2017 <NAME>. All rights reserved. // #ifndef VROPhysicsWorld_h #define VROPhysicsWorld_h #include <memory> #include "VROPhysicsBody.h" class btBulletDynamicsCommon; class btDiscreteDynamicsWorld; class btBroadphaseInterface; class btDefaultCollisionConfiguration; class btCollisionDispatcher; class btSequentialImpulseConstraintSolver; class VROPhysicsDebugDraw; class VRODriver; class VRORenderContext; /* VROPhysicsWorld is a simulated physics environment that contains and processes all acting forces and collisions on VROPhysicsBodies. It also contains both the physics properties of the simulated world (like gravity) and collision configuration parameters. */ class VROPhysicsWorld{ public: VROPhysicsWorld(); virtual ~VROPhysicsWorld(); /* Adds and removes a physics rigid body from the physics world. Also guards against adding or removing the same physics body from the world twice. */ void addPhysicsBody(std::shared_ptr<VROPhysicsBody> body); void removePhysicsBody(std::shared_ptr<VROPhysicsBody> body); /* When called, performs a timeStep of simulation / calculations for this physics world. */ void computePhysics(const VRORenderContext &context); /* Iterate through the dynamic world, identify collided object pairs and notify their corresponding physicsBodyDelegates regarding the collision event. */ void computeCollisions(); /* Sets the x,y,z gravity on this physics world. */ void setGravity(VROVector3f gravity); /* Projects a ray into the scene from the given start to end location and returns true if it has collided with any VROPhysics shape. If a collision occurred, the collided body's physics delegate will be notified as well. */ bool findCollisionsWithRay(VROVector3f from, VROVector3f to, bool returnClosest, std::string rayTag); /* Projects a shape into the scene from the given start to end location and returns true if it has collided with any VROPhysics shape. If a collision occurred, the collided body's physics delegate will be notified as well. Note: If checking along a path, only the first collided object is notified. Else, if checking at a point (where start and end VROVector3fs are the same), all collided objects intersecting the shape are notified. This is currently a Bullet limitation. */ bool findCollisionsWithShape(VROVector3f fromPos, VROVector3f toPos, std::shared_ptr<VROPhysicsShape> shape, std::string rayTag); /* If true, renders a set of lines representing the collision mesh of all physicsBodies within this world. */ void setDebugDrawVisible(bool isVisible); private: /* Represents the physicsBodies that have been added to and processed by this physics world. */ std::map<std::string, std::shared_ptr<VROPhysicsBody>> _activePhysicsBodies; /* Bullet's representation of the physics world. */ btDiscreteDynamicsWorld* _dynamicsWorld; /* Bullet Broadphase represents the collision algorithm used for quick, rough computations of collision pairs early on in the physics pipeline. */ btBroadphaseInterface* _broadphase; /* Configuration used for fine tuning collision algorithms. */ btDefaultCollisionConfiguration* _collisionConfiguration; /* Dispatcher is used for the notification of collisions. */ btCollisionDispatcher* _collisionDispatcher; /* Represents the constraints upon which the objects in this world will be resolved against. This takes into account things like gravity, collisions, and hinges. */ btSequentialImpulseConstraintSolver* _constraintSolver; /* Performs a collision shape test at the given location, returns true if it has collided with any VROPhysics shape, and notifies delegates along the way. */ bool collisionTestAtPoint(VROVector3f pos, std::shared_ptr<VROPhysicsShape> shape, std::string rayTag); /* Projects a shape into the scene from the given start to end location, returns true if it has collided with any VROPhysics shape. Only the closest VROPhysicsShape's delegate is notified. */ bool collisionTestAlongPath(VROVector3f fromPos, VROVector3f toPos, std::shared_ptr<VROPhysicsShape> shape, std::string rayTag); /* Used by Bullet to render all debug elements within the physics world. */ VROPhysicsDebugDraw* _debugDraw; bool _debugDrawVisible; }; #endif
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <math.h> #include <stdbool.h> #pragma warning(disable:4996) typedef uint16_t WORD; typedef uint32_t DWORD; typedef int32_t LONG; // https://docs.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-bitmapfileheader typedef struct tagBITMAPFILEHEADER { WORD bfType; DWORD bfSize; WORD bfReserved1; WORD bfReserved2; DWORD bfOffBits; } BITMAPFILEHEADER, * LPBITMAPFILEHEADER, * PBITMAPFILEHEADER; // https://docs.microsoft.com/pl-pl/previous-versions/dd183376(v=vs.85) typedef struct tagBITMAPINFOHEADER { DWORD biSize; LONG biWidth; LONG biHeight; WORD biPlanes; WORD biBitCount; DWORD biCompression; DWORD biSizeImage; LONG biXPelsPerMeter; LONG biYPelsPerMeter; DWORD biClrUsed; DWORD biClrImportant; } BITMAPINFOHEADER, * LPBITMAPINFOHEADER, * PBITMAPINFOHEADER; typedef struct COLORS { int* RED; int* GREEN; int* BLUE; } COLORS; void readfile(BITMAPFILEHEADER* fh, FILE* fp) { fread(&fh->bfType, sizeof fh->bfType, 1, fp); fread(&fh->bfSize, sizeof fh->bfSize, 1, fp); fread(&fh->bfReserved1, sizeof fh->bfReserved1, 1, fp); fread(&fh->bfReserved2, sizeof fh->bfReserved2, 1, fp); fread(&fh->bfOffBits, sizeof fh->bfOffBits, 1, fp); } void readinfo(BITMAPINFOHEADER* ih, FILE* fp) { fread(&ih->biSize, sizeof ih->biSize, 1, fp); fread(&ih->biWidth, sizeof ih->biWidth, 1, fp); fread(&ih->biHeight, sizeof ih->biHeight, 1, fp); fread(&ih->biPlanes, sizeof ih->biPlanes, 1, fp); fread(&ih->biBitCount, sizeof ih->biBitCount, 1, fp); fread(&ih->biCompression, sizeof ih->biCompression, 1, fp); fread(&ih->biSizeImage, sizeof ih->biSizeImage, 1, fp); fread(&ih->biXPelsPerMeter, sizeof ih->biXPelsPerMeter, 1, fp); fread(&ih->biYPelsPerMeter, sizeof ih->biYPelsPerMeter, 1, fp); fread(&ih->biClrUsed, sizeof ih->biClrUsed, 1, fp); fread(&ih->biClrImportant, sizeof ih->biClrImportant, 1, fp); } void print_all(BITMAPFILEHEADER fh, BITMAPINFOHEADER ih) { printf("BITMAPFILEHEADER\n"); printf("bfType: 0x%X\nbfSize: %u\nbfReserved1: 0x%X\nbfReserved2: 0x%X\nbfOffBits: %u\n", fh.bfType, fh.bfSize, fh.bfReserved1, fh.bfReserved2, fh.bfOffBits); printf("\nBITMAPINFOHEADER\n"); printf("biSize: %u\nbiWidth: %d\nbiHeight: %d\nbiPlanes: %u\nbiBitCount: %u\nbiCompression: %u\n", ih.biSize, ih.biWidth, ih.biHeight, ih.biPlanes, ih.biBitCount, ih.biCompression); printf("biSizeImage: %u\nbiXPelsPerMeter: %u\nbiYPelsPerMeter: %u\nbiClrUsed: %u\nbiClrImportant: %u\n", ih.biSizeImage, ih.biXPelsPerMeter, ih.biYPelsPerMeter, ih.biClrUsed, ih.biClrImportant); } void printhistogram(int* arr, float total) { for (int i = 0; i < 16; i++) printf("%u-%u: %.2f%%\n", i * 16, 16 * i + 15, arr[i] / total * 100); } void histogram(COLORS * ImgCol, FILE* fp, BITMAPFILEHEADER* fh, BITMAPINFOHEADER* ih, int rowlength) { if (ih->biCompression != 0 || ih->biBitCount != 24) { printf("\nhistogram calculation is unsupported"); return; } int red[16] = { 0 }; int green[16] = { 0 }; int blue[16] = { 0 }; uint8_t r; uint8_t g; uint8_t b; int k = 0; for (int j = 0; j < ih->biHeight; j++) { for (int i = 0; i < ih->biWidth; i++) { fread(&b, sizeof b, 1, fp); fread(&g, sizeof g, 1, fp); fread(&r, sizeof r, 1, fp); //printf("%u %u %u ", r, g, b); ImgCol->RED[k] = r; ImgCol->GREEN[k] = g; ImgCol->BLUE[k] = b; //printf("%d %d %d\n", r, g, b); //printf("%d %d %d\n", redB[k], greenB[k], blueB[k]); k++; red[r / 16]++; green[g / 16]++; blue[b / 16]++; } if (rowlength > ih->biWidth*3) { uint8_t temp; for (int x=0; x < rowlength - ih->biWidth*3; x++) fread(&temp, sizeof temp, 1, fp); } } printf("\nRED\n"); printhistogram(red, ih->biHeight * ih->biWidth); printf("\nGREEN\n"); printhistogram(green, ih->biHeight * ih->biWidth); printf("\nBLUE\n"); printhistogram(blue, ih->biHeight * ih->biWidth); } void tograyscale(COLORS * ImgCol, char* filename, BITMAPFILEHEADER* fh, BITMAPINFOHEADER* ih, int rowlength, uint8_t * offset) { FILE* fp = fopen(filename, "wb"); if (!fp) { perror("File opening failed"); return ; } fwrite(&fh->bfType, sizeof fh->bfType, 1, fp); fwrite(&fh->bfSize, sizeof fh->bfSize, 1, fp); fwrite(&fh->bfReserved1, sizeof fh->bfReserved1, 1, fp); fwrite(&fh->bfReserved2, sizeof fh->bfReserved2, 1, fp); fwrite(&fh->bfOffBits, sizeof fh->bfOffBits, 1, fp); fwrite(&ih->biSize, sizeof ih->biSize, 1, fp); fwrite(&ih->biWidth, sizeof ih->biWidth, 1, fp); fwrite(&ih->biHeight, sizeof ih->biHeight, 1, fp); fwrite(&ih->biPlanes, sizeof ih->biPlanes, 1, fp); fwrite(&ih->biBitCount, sizeof ih->biBitCount, 1, fp); fwrite(&ih->biCompression, sizeof ih->biCompression, 1, fp); fwrite(&ih->biSizeImage, sizeof ih->biSizeImage, 1, fp); fwrite(&ih->biXPelsPerMeter, sizeof ih->biXPelsPerMeter, 1, fp); fwrite(&ih->biYPelsPerMeter, sizeof ih->biYPelsPerMeter, 1, fp); fwrite(&ih->biClrUsed, sizeof ih->biClrUsed, 1, fp); fwrite(&ih->biClrImportant, sizeof ih->biClrImportant, 1, fp); fwrite(offset,sizeof(uint8_t),fh->bfOffBits-14-sizeof(BITMAPINFOHEADER), fp); uint8_t gray; int k = 0; for (int j = 0; j < ih->biHeight; j++) { for (int i = 0; i < ih->biWidth; i++) { gray = (ImgCol->RED[k] + ImgCol->GREEN[k] + ImgCol->BLUE[k]) / 3; //printf("%d %d %d %d\n", gray, redB[i], greenB[i], blueB[i]); fwrite(&gray, sizeof gray, 1, fp); fwrite(&gray, sizeof gray, 1, fp); fwrite(&gray, sizeof gray, 1, fp); k++; } if (rowlength > ih->biWidth*3) { uint8_t temp = 0; for (int x=0; x< rowlength - ih->biWidth*3; x++) fwrite(&temp, sizeof temp, 1, fp); } } fclose(fp); } char * string_to_binary(char* line) { if(line == NULL) return NULL; int len = strlen(line); char * binary = malloc(len*8 + 1); binary[0] = '\0'; for(int i = 0; i < len; i++) { int temp = (int)line[i]; for(int j = 0; j <8; j++){ if(temp%2==1) strcat(binary,"1"); else strcat(binary,"0"); temp/=2; } } return binary; } char * dec_bin (int x) { char * result = malloc(8 + 1); int counter = 0; result[0] = '\0'; while (x!=0) { if (x%2==0) strcat(result, "0"); else strcat(result, "1"); x/=2; counter++; } while (counter != 8) { strcat(result, "0"); counter++; } return result; } int bin_dec (char * s) { int x = 1; int res = 0; int temp = strlen(s); for (int i = 0; i < temp; i++) { res += (s[i]-'0')*x; x *= 2; } return res; } uint8_t eval_value (uint8_t color_value, uint8_t temp) { //if (color_value%2==0 && temp ==0); //nic nie robimy if (color_value%2==0 && temp == 1) color_value+=1; else if (color_value%2==1 && temp == 0) color_value-=1; //if (color_value%2==1 && temp == 1); //nic nie robimy return color_value; } void steganography(char * text, char * fileout, COLORS * ImgCol, BITMAPFILEHEADER * fh, BITMAPINFOHEADER * ih, int rowlength, uint8_t * offset) { int x = strlen(text); char * only_number = dec_bin(x); char * only_text = string_to_binary(text); char * bin_text = malloc((x*8+8+1)*sizeof(char)); bin_text[0]='\0'; strcat(bin_text,only_number); strcat(bin_text,only_text); int bin_len = strlen(bin_text); //printf("text: %s\n", text); //printf("binary string to encode:\n<%s>\n", bin_text); //printf("number of characters: %d\n", bin_len); FILE* fp = fopen(fileout, "wb"); if (!fp) { perror("File opening failed"); return ; } fwrite(&fh->bfType, sizeof fh->bfType, 1, fp); fwrite(&fh->bfSize, sizeof fh->bfSize, 1, fp); fwrite(&fh->bfReserved1, sizeof fh->bfReserved1, 1, fp); fwrite(&fh->bfReserved2, sizeof fh->bfReserved2, 1, fp); fwrite(&fh->bfOffBits, sizeof fh->bfOffBits, 1, fp); fwrite(&ih->biSize, sizeof ih->biSize, 1, fp); fwrite(&ih->biWidth, sizeof ih->biWidth, 1, fp); fwrite(&ih->biHeight, sizeof ih->biHeight, 1, fp); fwrite(&ih->biPlanes, sizeof ih->biPlanes, 1, fp); fwrite(&ih->biBitCount, sizeof ih->biBitCount, 1, fp); fwrite(&ih->biCompression, sizeof ih->biCompression, 1, fp); fwrite(&ih->biSizeImage, sizeof ih->biSizeImage, 1, fp); fwrite(&ih->biXPelsPerMeter, sizeof ih->biXPelsPerMeter, 1, fp); fwrite(&ih->biYPelsPerMeter, sizeof ih->biYPelsPerMeter, 1, fp); fwrite(&ih->biClrUsed, sizeof ih->biClrUsed, 1, fp); fwrite(&ih->biClrImportant, sizeof ih->biClrImportant, 1, fp); fwrite(offset,sizeof(uint8_t),fh->bfOffBits-14-sizeof(BITMAPINFOHEADER), fp); int k = 0; int encoded = 0; bool text_encoded = false; uint8_t temp; for (int j = 0; j < ih->biHeight; j++) { for (int i = 0; i < ih->biWidth; i++) { if (!text_encoded){ //BLUE temp = eval_value(ImgCol->BLUE[k], bin_text[encoded]-'0'); fwrite(&temp, sizeof (uint8_t), 1, fp); encoded++; //GREEN if (encoded != bin_len) { temp = eval_value(ImgCol->GREEN[k], bin_text[encoded]-'0'); fwrite(&temp, sizeof (uint8_t), 1, fp); encoded++; } else fwrite(&(ImgCol->GREEN[k]), sizeof (uint8_t), 1, fp); //RED if (encoded != bin_len) { temp = eval_value(ImgCol->RED[k], bin_text[encoded]-'0'); fwrite(&temp, sizeof (uint8_t), 1, fp); encoded++; } else fwrite(&(ImgCol->RED[k]), sizeof (uint8_t), 1, fp); if (encoded == bin_len) text_encoded = true; } else{ fwrite(&(ImgCol->BLUE[k]), sizeof (uint8_t), 1, fp); fwrite(&(ImgCol->GREEN[k]), sizeof (uint8_t), 1, fp); fwrite(&(ImgCol->RED[k]), sizeof (uint8_t), 1, fp); } k++; } if (rowlength > ih->biWidth*3) { uint8_t temp =0; for (int x=0; x< rowlength-ih->biWidth*3; x++) fwrite(&temp, sizeof temp, 1, fp); } } free(only_number); free(only_text); free(bin_text); fclose(fp); } void decode (char * filename) { FILE* fp = fopen(filename, "rb"); if (!fp) { perror("File opening failed"); return ; } BITMAPFILEHEADER fh; readfile(&fh, fp); BITMAPINFOHEADER ih; readinfo(&ih, fp); int offset_size = fh.bfOffBits-14-sizeof(BITMAPINFOHEADER); uint8_t * offset = (uint8_t *)calloc(offset_size, sizeof(uint8_t)); fread(offset,sizeof(uint8_t),offset_size,fp); free(offset); int rowlength = floor((ih.biBitCount * ih.biWidth + 31) / 32) * 4; uint8_t temp; char * bin_val = malloc(8+1); bin_val[0]='\0'; for (int x=0; x<8; x++) //reading how many chars will be to decode { fread(&temp, sizeof temp, 1, fp); if (temp%2==0) strcat(bin_val, "0"); else strcat(bin_val, "1"); } //printf("bin_val: %s\n", bin_val); int val = bin_dec(bin_val); //printf("val: %d\n", val); free(bin_val); char * text = malloc(val+1); text[0]='\0'; int counter = 8; for (int i=0; i<val; i++) { char * bin_ch = malloc(8+1); bin_ch[0]='\0'; for (int j=0; j<8; j++) { fread(&temp, sizeof temp, 1, fp); if (temp%2==0) strcat(bin_ch, "0"); else strcat(bin_ch, "1"); counter++; if (counter==ih.biWidth*3 && rowlength > ih.biWidth*3) { uint8_t pom; for (int x=0; x< rowlength - ih.biWidth*3; x++) fread(&pom, sizeof pom, 1, fp); counter=0; } } //printf("%s\n", bin_ch); text[i] = (char)(bin_dec(bin_ch)); free(bin_ch); } text[val]='\0'; printf("DECODED TEXT: %s\n", text); free(text); fclose(fp); }
/* * This header is generated by classdump-dyld 1.0 * on Tuesday, November 5, 2019 at 1:55:31 PM Mountain Standard Time * Operating System: Version 13.0 (Build 17J586) * Image Source: /Applications/Siri.app/Siri * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. */ @protocol SiriUIPresentationDataSource <NSObject> @optional -(id)siriEnabledAppListForSiriPresentation:(id)arg1; @required -(id)domainObjectStoreForSiriPresentation:(id)arg1; -(long long)siriStateForSiriPresentation:(id)arg1; -(id)conversationIdentifiersForSiriPresentation:(id)arg1; -(id)siriPresentation:(id)arg1 conversationWithIdentifier:(id)arg2; -(void)siriPresentation:(id)arg1 deleteConversationWithIdentifier:(id)arg2; -(void)siriPresentation:(id)arg1 activateConversationWithIdentifier:(id)arg2; -(id)startNewConversationForSiriPresentation:(id)arg1; -(id)sessionInfoForSiriPresentation:(id)arg1; -(id)siriPresentation:(id)arg1 domainObjectForIdentifier:(id)arg2; -(void)siriPresentation:(id)arg1 setDomainObject:(id)arg2 forIdentifier:(id)arg3; -(BOOL)siriPresentation:(id)arg1 itemAtIndexPathIsVirgin:(id)arg2; -(void)siriPresentation:(id)arg1 insertAceViews:(id)arg2 withDialogPhase:(id)arg3 asItemsAtIndexPaths:(id)arg4; -(void)siriPresentation:(id)arg1 removeItemsAtIndexPaths:(id)arg2; -(void)siriPresentation:(id)arg1 addSelectionResponse:(id)arg2; -(id)siriPresentation:(id)arg1 identifierOfItemAtIndexPath:(id)arg2; -(id)siriPresentation:(id)arg1 indexPathForItemWithIdentifier:(id)arg2; -(long long)siriPresentation:(id)arg1 typeOfItemAtIndexPath:(id)arg2; -(long long)siriPresentation:(id)arg1 numberOfChildrenForItemAtIndexPath:(id)arg2; -(id)siriPresentation:(id)arg1 dialogPhaseForItemAtIndexPath:(id)arg2; -(id)siriPresentation:(id)arg1 aceObjectForItemAtIndexPath:(id)arg2; -(id)siriPresentation:(id)arg1 aceCommandIdentifierForItemAtIndexPath:(id)arg2; -(long long)siriPresentation:(id)arg1 presentationStateForItemAtIndexPath:(id)arg2; @end
<reponame>The0x539/wasp<filename>libc/newlib/libc/sys/nautilus/syscall.h #ifndef __SYSCALL_H__ #define __SYSCALL_H__ #ifdef __NAUTILUS__ #include <nautilus/nautilus.h> #else #include <stdlib.h> #include <stdint.h> #include <sys/types.h> #ifndef NORETURN #define NORETURN __attribute__((noreturn)) #endif typedef unsigned int tid_t; #endif #ifdef __cplusplus extern "C" { #endif struct sem; typedef struct sem sem_t; typedef void (*signal_handler_t)(int); tid_t sys_getpid(void); int sys_fork(void); int sys_wait(int* status); int sys_execve(const char* name, char * const * argv, char * const * env); void NORETURN sys_exit(int arg); ssize_t sys_read(int fd, char* buf, size_t len); ssize_t sys_write(int fd, const char* buf, size_t len); ssize_t sys_sbrk(ssize_t incr); int sys_open(const char* name, int flags, int mode); int sys_close(int fd); int sys_clone(tid_t* id, void* ep, void* argv); off_t sys_lseek(int fd, off_t offset, int whence); void sys_yield(void); int sys_kill(tid_t dest, int signum); int sys_signal(signal_handler_t handler); int sys_stat(const char * file, struct stat * st); #define __NR_exit 0 #define __NR_write 1 #define __NR_open 2 #define __NR_close 3 #define __NR_read 4 #define __NR_lseek 5 #define __NR_unlink 6 #define __NR_getpid 7 #define __NR_kill 8 #define __NR_fstat 9 #define __NR_sbrk 10 #define __NR_fork 11 #define __NR_wait 12 #define __NR_execve 13 #define __NR_times 14 #define __NR_stat 15 #define __NR_dup 16 #define __NR_dup2 17 #define __NR_msleep 18 #define __NR_yield 19 #define __NR_sem_init 20 #define __NR_sem_destroy 21 #define __NR_sem_wait 22 #define __NR_sem_post 23 #define __NR_sem_timedwait 24 #define __NR_getprio 25 #define __NR_setprio 26 #define __NR_clone 27 #define __NR_sem_cancelablewait 28 #define __NR_get_ticks 29 #ifdef __cplusplus } #endif #endif
<reponame>wannyk/react-native-arkit<filename>ios/components/RCTARKitSpriteViewManager.h #import <React/RCTViewManager.h> @interface RCTARKitSpriteViewManager : RCTViewManager @end
<reponame>dingfude2008/LED_Zheng // // HelperConfig.h // 常用分类收集 // // Created by 丁付德 on 16/8/3. // Copyright © 2016年 dfd. All rights reserved. // #ifndef HelperMacro_h #define HelperMacro_h #ifdef __OBJC__ // OC 下的宏命令 #define APPID 1089456223 #ifndef __OPTIMIZE__ #define NSLog(...) NSLog(__VA_ARGS__) #else #define NSLog(...) {} #endif // ------- 本地存储 #define GetUserDefault(k) [[NSUserDefaults standardUserDefaults] objectForKey:k] #define SetUserDefault(k, v) [[NSUserDefaults standardUserDefaults] setObject:v forKey:k]; \ [[NSUserDefaults standardUserDefaults] synchronize]; #define RemoveUserDefault(k) [[NSUserDefaults standardUserDefaults] removeObjectForKey:k]; \ [[NSUserDefaults standardUserDefaults] synchronize]; // ------- 声明 #define DDWeakVV DDWeak(self) #define DDStrongVV DDStrong(self) #define DDWeak(type) __weak typeof(type) weak##type = type; #define DDStrong(type) __strong typeof(type) type = weak##type; // 系统相关 #define SystemVersion [[[UIDevice currentDevice] systemVersion] doubleValue] // 当前系统版本 #define IS_IPad [[UIDevice currentDevice].model rangeOfString:@"iPad"].length > 0// 是否是ipad // ------- 系统相关 #define IPhone4 (ScreenHeight == 480) #define IPhone5 (ScreenHeight == 568) #define IPhone6 (ScreenHeight == 667) #define IPhone6P (ScreenHeight == 736) #define SystemVersion [[[UIDevice currentDevice] systemVersion] doubleValue] // 当前系统版本 // 中英文 //#define kString(_S) NSLocalizedString(_S, @"") #define kString(key) [[NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:DFDLanguage]] ofType:@"lproj"]] localizedStringForKey:(key) value:nil table:@"Localizable"] #define St(_k) [@(_k) description] // ------- 宽高 #define ScreenHeight [[UIScreen mainScreen] bounds].size.height #define ScreenWidth [[UIScreen mainScreen] bounds].size.width #define StateBarHeight 20 #define NavBarHeight 64 #define BottomHeight 49 #define RealHeight(_k) ScreenHeight * (_k / 1334.0) #define RealWidth(_k) ScreenWidth * (_k / 750.0) #define ScreenRadio 0.562 // 屏幕宽高比 // ------- 显示 //#define MBShowAll [MBProgressHUD showHUDAddedTo:self.view animated:YES]; //#define MBHide [MBProgressHUD hideHUDForView:self.view animated:YES]; #define MBShowAll [MBProgressHUD showHUDAddedTo:[[UIApplication sharedApplication].delegate window] animated:YES]; #define MBShowAllText(_k) [MBProgressHUD showHUDAddedToWithText:_k view:[[UIApplication sharedApplication].delegate window] animated:YES]; #define MBHide [MBProgressHUD hideHUDForView:[[UIApplication sharedApplication].delegate window] animated:YES]; #define MBShow(_k) [MBProgressHUD show:kString(_k) toView:[[UIApplication sharedApplication].delegate window]]; #define DefaultUUIDString @"DefaultUUIDString" #define ListDataLocal @"ListDataLocal" // #define TESTACCOUNT @"<EMAIL>" // #define TESTPASSWORD @"<PASSWORD>" #define Border(_label, _color) _label.layer.borderWidth = 1; _label.layer.borderColor = _color.CGColor; // ------- 颜色 #define RGBA(_R,_G,_B,_A) [UIColor colorWithRed:_R / 255.0f green:_G / 255.0f blue:_B / 255.0f alpha:_A] #define RGB(_R,_G,_B) RGBA(_R,_G,_B,1) #define DWhite [UIColor whiteColor] #define DRed [UIColor redColor] #define DBlue [UIColor blueColor] #define DBlack [UIColor blackColor] #define DYellow [UIColor yellowColor] #define DBlack [UIColor blackColor] #define DClear [UIColor clearColor] #define DLightGray [UIColor lightGrayColor] #define DBackgroundColor [UIColor lightGrayColor] #define DWhiteA(_k) [[UIColor whiteColor] colorWithAlphaComponent:_k] #define DBlackA(_k) [[UIColor blackColor] colorWithAlphaComponent:_k] #define DBlackTextColor [UIColor cz_colorWithHex:0x333333] // 导航栏 标题 黑框按钮文字 #define DNormalTextColor [UIColor cz_colorWithHex:0x2A2A2A] // 正文文字 正在聊天 #define DTimeAndDistanceTextColor [UIColor cz_colorWithHex:0x949494] // 聊天列表时间数字 发现页距离 #define DMessageAndSexTextColor [UIColor cz_colorWithHex:0x737373] // 聊天列表文字内容 发现页性取向 #define DRequestTextColor [UIColor cz_colorWithHex:0x38a915] // 聊天列表互动请求 #define DSayHellowTextColor [UIColor cz_colorWithHex:0xeb8916] // 聊天列表打招呼 #define DTipsButtonSwithBackgroundColor [UIColor cz_colorWithHex:0xff3366] // 提示类文字 按钮颜色 开关 #define DTipsButtonDisEnableBackgroundColor [UIColor cz_colorWithHex:0xfba8b7] // 聊天消息的边框色 #define DChatBorderColor [UIColor cz_colorWithHex:0xe5e5e5] // 聊天消息的边框色 #define DFDLanguage @"DFDLanguage" #define DFDlanguageChanged @"DFDlanguageChanged" #endif #endif /* HelperConfig_h */
<gh_stars>0 int main( printf("e. That's all there is to it.") )
#include "quicksort.h" int main(void) { int a[N], i; srand(time(NULL)); for (i = 0; i < N; ++i) a[i] = rand() % 10000; quicksort(a, a + N - 1); /* // Check that the array a[] has been sorted // but do not print the array. We want to // profile the sorting, not the printing. */ for (i = 0; i < N - 1; ++i) { if (a[i] > a[i + 1]) { printf("SORTING ERROR - bye!\n"); exit(1); } } return 0; }
/** * @file Common.h * @author <NAME> (<EMAIL>) * @brief All headers of the Common Package * @version 1.0 * @date 2019-06-12 * * @copyright Copyright (c) 2020 * */ #ifndef __GAMESDK_COMMON_H__ #define __GAMESDK_COMMON_H__ #include <2DGameSDK/common/Constants.h> #include <2DGameSDK/common/Helpers.h> #include <2DGameSDK/common/graphics/GraphicTools.h> #include <2DGameSDK/common/types/ObjectType.h> // #include <2DGameSDK/common/types/Pose.h> #endif
#define Unrolling 1 //#define UseBebigokimisa //#define UseInterleaveTables //#define UseSchedule 3
#ifndef SNAKE_MACROS_H #define SNAKE_MACROS_H #ifdef __EMSCRIPTEN__ #define SNAKE_PATH_SEP "/" #else #ifdef WIN32 #define SNAKE_PATH_SEP "\\" #else #define SNAKE_PATH_SEP "/" #endif #endif #define STATUS_TEXT_FONT "edosz.ttf" #define INITIAL_SNAKE_SECONDS_PER_UPDATE 0.2F #define MINIMUM_SNAKE_SECONDS_PER_UPDATE 0.005F #define SNAKE_SECONDS_PER_UPDATE_INCREMENT 0.01F #endif
#ifndef STDARG_H #define STDARG_H typedef int jmp_buf; int setjmp(jmp_buf env); void longjmp(jmp_buf env, int val); #endif
<reponame>Wahno/PlantsVSZombies<gh_stars>1-10 #pragma once #include "TinyEngine\T_Graph.h" class GraphPlus : public T_Graph { public: GraphPlus(); ~GraphPlus(); static void PaintText(HDC hdc, RectF fontRect, wstring text, REAL fontSize, wstring fontName, Color fontColor = Color::White, FontStyle style = FontStyleBold, StringAlignment align = StringAlignmentCenter,int n = 10); };
<filename>aspect/src/AspectFunc.h /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ** ** Copyright (C) <NAME> 2011 ** ** <license> ** **~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ #ifndef __Compass_Aspect_AspectFunc_h__ #define __Compass_Aspect_AspectFunc_h__ /** Textual name of this class */ extern const char* coAspectFunc_type; #define __coAspectFunc \ __coObject \ \ void* funcPtr; /** The function pointer to the adviced function. */ \ char* fromFunc; /** The name of the function advicing. c-string that is copied & freed. */ \ coBool hasAspect; /** Whether the advice was with an aspectual object/ptr. */ \ void* fromAspect; /** The ascpectual object/ptr if provided. */ /** coAspectFunc class */ typedef struct _coAspectFunc { __coAspectFunc } coAspectFunc; /* Public member functions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ /** Create a new coAspectFunc. Note programmatically there's no reason to not allow a user to provide an aspect of * NULL, but we have to know when a user asks for an aspect when none is provided. For this reason we have to two styles * constructors. This one hasn't an aspect provided. */ coAspectFunc* coAspectFunc_new( const char* name, void* funcPtr, const char* fromFunc ); /** Create a new coAspectFunc. Note programmatically there's no reason to not allow a user to provide an aspect of * NULL, but we have to know when a user asks for an aspect when none is provided. For this reason we have to two styles * constructors. This one has an aspect provided. */ coAspectFunc* coAspectFunc_newWithAspect( const char* name, void* funcPtr, const char* fromFunc, void* fromAspect ); /* Private member functions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ /** Delete implementation */ void _coAspectFunc_delete( void* aspectFunc ); /** Print implementation */ void _coAspectFunc_print( void* aspectFunc, coStream* stream, coBool concise ); #endif /* __Compass_Aspect_AspectFunc_h__ */
#ifndef _NPY_NUMBER_H_ #define _NPY_NUMBER_H_ #include "npy_object.h" #include "npy_index.h" #if defined(__cplusplus) extern "C" { #endif struct NpyUFuncObject; struct NumericOps { struct NpyUFuncObject *add; struct NpyUFuncObject *subtract; struct NpyUFuncObject *multiply; struct NpyUFuncObject *divide; struct NpyUFuncObject *remainder; struct NpyUFuncObject *power; struct NpyUFuncObject *square; struct NpyUFuncObject *reciprocal; struct NpyUFuncObject *ones_like; struct NpyUFuncObject *sqrt; struct NpyUFuncObject *negative; struct NpyUFuncObject *absolute; struct NpyUFuncObject *invert; struct NpyUFuncObject *left_shift; struct NpyUFuncObject *right_shift; struct NpyUFuncObject *bitwise_and; struct NpyUFuncObject *bitwise_xor; struct NpyUFuncObject *bitwise_or; struct NpyUFuncObject *less; struct NpyUFuncObject *less_equal; struct NpyUFuncObject *equal; struct NpyUFuncObject *not_equal; struct NpyUFuncObject *greater; struct NpyUFuncObject *greater_equal; struct NpyUFuncObject *floor_divide; struct NpyUFuncObject *true_divide; struct NpyUFuncObject *logical_or; struct NpyUFuncObject *logical_and; struct NpyUFuncObject *floor; struct NpyUFuncObject *ceil; struct NpyUFuncObject *maximum; struct NpyUFuncObject *minimum; struct NpyUFuncObject *rint; struct NpyUFuncObject *conjugate; }; typedef struct NumericOps NumericOps; #if defined(__cplusplus) } #endif #endif
/* ** AcroColorExpT.h ** ** Types, macros, structures, etc. required to use the Acrobat Color Host Function Table. ** Copyright (C) 2002-2006 Adobe Systems Inc. All Rights Reserved. ** */ #ifndef _H_AcroColorExpT #define _H_AcroColorExpT //#include "Environ.h" /* This version # is used in AcroColorCalls.h for the definition/inclusion of the entry points. If missing, you don't get the right results. Clients should not have to explicitly specify this to get it to work. They will have to specify a later version number if they really want a later HFT version. */ #if PLUGIN #include "CoreExpT.h" #include "ASExpT.h" #include "PDExpT.h" #include "PEExpT.h" #endif /* PLUGIN */ #ifndef FOUR_CHAR_CODE #ifdef __SUNPRO_CC //SunStudio reads the byte in reverse order #define FOUR_CHAR_CODE(x) (((ASUns32)(x)>>24) + (((x)>>8)&0x0ff00) + (((x)<<8)&0x0ff0000) + ((x)<<24)) #else #define FOUR_CHAR_CODE(x) (x) #endif #endif #ifdef __cplusplus extern "C" { #endif #define AcroColorHFTNAME "AcroColorHFT" #ifdef __cplusplus /** A string value type for use with AcroColor functions. @see ACEngineInfo @see ACGetSettingsString @see ACMakeCalGray @see ACMakeCalLab @see ACMakeCalRGB @see ACMakeString @see ACPresetFileToName @see ACProfileDescription @see ACProfileFromDescription @see ACProfileListItemDescription @see ACStringASCII @see ACStringLocalized @see ACStringUnicode @see ACUnReferenceString */ class ACString; typedef ACString *AC_String; #else typedef struct ACString *AC_String; #endif #ifdef __cplusplus /** An opaque object representing a list of device color profiles. @see ACMakeProfileList @see ACProfileListCount @see ACProfileListItemCode @see ACProfileListItemDescription @see ACUnReferenceProfileList */ class ACProfileList; typedef ACProfileList *AC_ProfileList; #else typedef struct ACProfileList *AC_ProfileList; #endif #ifdef __cplusplus /** An opaque object representing a color tranformation. @see ACApplyTransform @see ACMakeColorTransform @see ACUnReferenceTranform */ class ACTransform; typedef ACTransform *AC_Transform; #else typedef struct ACTransform *AC_Transform; #endif #ifdef __cplusplus /** An opaque object representing the settings for the AcroColor engine (ACE). @see ACGetSettingsProfile @see ACGetSettingsString @see ACGetSettingsUnsigned32 @see ACLoadSettings @see ACMakeSettings @see ACUnReferenceSettings */ class ACSettings; typedef ACSettings *AC_Settings; #else typedef struct ACSettings *AC_Settings; #endif #ifdef __cplusplus /** An opaque object representing a device color profile. @see ACGetSettingsProfile @see ACGetWorkingSpaceProfile @see ACMakeBufferProfile @see ACMakeCalGray @see ACMakeCalLab @see ACMakeCalRGB @see ACMakeColorTransform @see ACMonitorProfile @see ACProfileColorSpace @see ACProfileData @see ACProfileDescription @see ACProfileFromCode @see ACProfileFromDescription @see ACProfileSize @see ACProfilesMatch @see ACUnReferenceProfile */ class ACProfile; typedef ACProfile *AC_Profile; #else typedef struct ACProfile *AC_Profile; #endif #ifdef __cplusplus /** An opaque object representing a preset list. A preset list is a list of predefined color settings that specify the source and destination working color profiles to be used for color conversion. @see ACMakePresetList @see ACPresetListCount @see ACPresetListItemFile @see ACUnReferencePresetList */ class ACPresetList; typedef ACPresetList *AC_PresetList; #else typedef struct ACPresetList *AC_PresetList; #endif /** Constants that specify the types of device profiles to include in a profile list. @see ACMakeProfileList */ typedef enum { /** Standard (recommended) RGB profiles. These profiles are always bidirectional. */ AC_Selector_RGB_Standard = FOUR_CHAR_CODE ('rStd'), /** RGB profiles that can be used as a source. These profiles may or may not be usable as a destination. This constant does not include profiles selected by AC_Selector_RGB_Standard. */ AC_Selector_RGB_OtherInputCapable = FOUR_CHAR_CODE ('rInp'), /** RGB profiles that can be used as a destination. These profiles are also usable as a source. This constant does not include profiles selected by AC_Selector_RGB_Standard. */ AC_Selector_RGB_OtherOutputCapable = FOUR_CHAR_CODE ('rOut'), /** Standard (recommended) CMYK profiles that can be used as a source. These profiles may or may not be usable as a destination. */ AC_Selector_CMYK_StandardInput = FOUR_CHAR_CODE ('cSIn'), /** Standard (recommended) CMYK profiles that can be used as a destination. These profiles are also usable as a source. */ AC_Selector_CMYK_StandardOutput = FOUR_CHAR_CODE ('cStd'), /** CMYK profiles that can be used as a source. These profiles may or may not be usable as a destination. This constant does not include profiles selected by AC_Selector_CMYK_StandardInput or AC_Selector_CMYK_StandardOutput. */ AC_Selector_CMYK_OtherInputCapable = FOUR_CHAR_CODE ('cInp'), /** CMYK profiles that can be used as a destination. These profiles are also usable as a source. This constant does not include profiles selected by AC_Selector_CMYK_StandardOutput. */ AC_Selector_CMYK_OtherOutputCapable = FOUR_CHAR_CODE ('cOut'), /** Standard (recommended) grayscale profiles. These profiles are always bidirectional. */ AC_Selector_Gray_Standard = FOUR_CHAR_CODE ('gStd'), /** Grayscale profiles that can be used as a source. These profiles may or may not be usable as a destination. This constant does not include profiles selected by AC_Selector_Gray_Standard. */ AC_Selector_Gray_OtherInputCapable = FOUR_CHAR_CODE ('gInp'), /** Grayscale profiles that can be used as a destination. These profiles are also usable as a source. This constant does not include profiles selected by AC_Selector_Gray_Standard. */ AC_Selector_Gray_OtherOutputCapable = FOUR_CHAR_CODE ('gOut'), /** Standard dot gain profiles. This constant is used by Photoshop to represent a single ink's dot gain curve, and is stored as an ICC gray output profile. */ AC_Selector_DotGain_Standard = FOUR_CHAR_CODE ('dStd'), /** Other grayscale printer profiles. This constant does not include profiles selected by AC_Selector_DotGain_Standard, and does not include grayscale display profiles. */ AC_Selector_DotGain_Other = FOUR_CHAR_CODE ('dOth'), /** PhotoYCC profiles that can be used as a source. */ AC_Selector_PhotoYCC_InputCapable = FOUR_CHAR_CODE ('iYCC'), /** This constant forces the enum to be 32 bits wide. */ AC_Selector_MaxEnum = 0xFFFFFFFFL } AC_SelectorCode; /** Error codes returned by AcroColor functions. */ typedef enum { /** No error. */ AC_Error_None = 0, /** Other error. */ AC_Error_General = FOUR_CHAR_CODE ('gen '), /** Bad parameters to an API call. */ AC_Error_Param = FOUR_CHAR_CODE ('parm'), /** Application and ACE library mismatch. */ AC_Error_Version = FOUR_CHAR_CODE ('ver '), /** The user aborted the operation. Returned by ACE when the client progress callback returns <code>false</code>. */ AC_Error_UserAbort = FOUR_CHAR_CODE ('abrt'), /** Out of memory. */ AC_Error_Memory = FOUR_CHAR_CODE ('memF'), /** Out of stack space. */ AC_Error_StackFull = FOUR_CHAR_CODE ('stkF'), /** Client callback ran out of scratch space. */ AC_Error_ScratchFull = FOUR_CHAR_CODE ('scrF'), /** String does not fit in supplied buffer. */ AC_Error_StringOverflow = FOUR_CHAR_CODE ('strO'), /** String does not contain ASCII data. */ AC_Error_NoASCII = FOUR_CHAR_CODE ('noA '), /** String does not contain Unicode data. */ AC_Error_NoUnicode = FOUR_CHAR_CODE ('noU '), /** String does not contain localized data. */ AC_Error_NoLocalized = FOUR_CHAR_CODE ('noL '), /** Data is not correctly byte aligned. */ AC_Error_BadAlignment = FOUR_CHAR_CODE ('alig'), /** Invalid profile description. */ AC_Error_BadDescription = FOUR_CHAR_CODE ('bDes'), /** Unable to concatenate transforms. */ AC_Error_BadConcat = FOUR_CHAR_CODE ('bCat'), /** Unable to merge transforms. */ AC_Error_BadMerge = FOUR_CHAR_CODE ('bMrg'), /** Invalid profile. */ AC_Error_BadProfile = FOUR_CHAR_CODE ('bPro'), /** Unsupported CMS. */ AC_Error_UnsupCMS = FOUR_CHAR_CODE ('uCMS'), /** Unsupported ACE option. */ AC_Error_UnsupOption = FOUR_CHAR_CODE ('uOpt'), /** Unsupported packing code. */ AC_Error_UnsupPacking = FOUR_CHAR_CODE ('uPac'), /** Unsupported profile version. */ AC_Error_UnsupProfile = FOUR_CHAR_CODE ('uPro'), /** Unsupported profile code. */ AC_Error_UnsupProfileCode = FOUR_CHAR_CODE ('uPrC'), /** Unsupported color space. */ AC_Error_UnsupSpace = FOUR_CHAR_CODE ('uSpc'), /** Unsupported query code. */ AC_Error_UnsupQuery = FOUR_CHAR_CODE ('uQry'), /** A profile was missing from the disk. */ AC_Error_MissingProfile = FOUR_CHAR_CODE ('misP'), /** The profile on disk has been modified. */ AC_Error_ModifiedProfile = FOUR_CHAR_CODE ('modP'), /** File is missing from disk. */ AC_Error_FileNotFound = FOUR_CHAR_CODE ('fnf '), /** End of file error. */ AC_Error_EOF = FOUR_CHAR_CODE ('eof '), /** File locked error. */ AC_Error_FileLocked = FOUR_CHAR_CODE ('flck'), /** Disk I/O error. */ AC_Error_DiskIO = FOUR_CHAR_CODE ('io '), /** A problem using ColorSync. */ AC_Error_ColorSync = FOUR_CHAR_CODE ('csE '), /** A problem using ICM. */ AC_Error_ICM = FOUR_CHAR_CODE ('icmE'), /** The color settings does not contain this key. */ AC_Error_MissingKey = FOUR_CHAR_CODE ('mKey'), /** The color settings file is invalid. */ AC_Error_InvalidSettings = FOUR_CHAR_CODE ('iSet'), /** The color settings file is an incompatible version. */ AC_Error_SettingsVersion = FOUR_CHAR_CODE ('vSet'), /** The function is not implemented (subsetted library). */ AC_Error_NotImplemented = FOUR_CHAR_CODE ('nImp'), /** This constant forces the <code>enum</code> to be 32 bits wide. */ AC_Error_MaxEnum = 0xFFFFFFFFL } AC_Error; /** Constants that describe the type of a device color profile. @see ACProfileFromCode @see ACProfileListItemCode */ typedef enum { /** A <code>NULL</code> result, indication that a profile is not a built-in profile. */ AC_Profile_Null = 0, /** Adobe's standard Lab profile. It has a white point of D50, and exactly matches the ICC's Lab PCS space. */ AC_Profile_Lab_D50 = FOUR_CHAR_CODE ('LD50'), /** An XYZ profile that exactly matches the ICC's XYZ PCS space. */ AC_Profile_PCS_XYZ = FOUR_CHAR_CODE ('pXYZ'), /** An XYZ profile with a flat white point encoding (<code>X = Y = Z = 1.0</code>). Photoshop uses this as an intermediate space in its display loop. */ AC_Profile_Flat_XYZ = FOUR_CHAR_CODE ('fXYZ'), /** HP's sRGB profile. The default Windows monitor profile. */ AC_Profile_sRGB = FOUR_CHAR_CODE ('sRGB'), /** Default RGB space using by Photoshop 4.0 and earlier. The default Mac OS monitor profile. */ AC_Profile_AppleRGB = FOUR_CHAR_CODE ('aRGB'), /** A wider gamut RGB space recommended by Adobe. */ AC_Profile_AdobeRGB1998 = FOUR_CHAR_CODE ('AS98'), /** A simplified version of Radius' ColorMatch RGB space, without Radius' non-zero black point. */ AC_Profile_ColorMatchRGB = FOUR_CHAR_CODE ('cmat'), /** Grayscale display profile with a gamma of 18. */ AC_Profile_Gamma18 = FOUR_CHAR_CODE ('GG18'), /** Grayscale display profile with a gamma of 22. */ AC_Profile_Gamma22 = FOUR_CHAR_CODE ('GG22'), /** Grayscale printer profile with a dot gain of 10. */ AC_Profile_DotGain10 = FOUR_CHAR_CODE ('DG10'), /** Grayscale printer profile with a dot gain of 15. */ AC_Profile_DotGain15 = FOUR_CHAR_CODE ('DG15'), /** Grayscale printer profile with a dot gain of 20. */ AC_Profile_DotGain20 = FOUR_CHAR_CODE ('DG20'), /** Grayscale printer profile with a dot gain of 25. */ AC_Profile_DotGain25 = FOUR_CHAR_CODE ('DG25'), /** Grayscale printer profile with a dot gain of 30. */ AC_Profile_DotGain30 = FOUR_CHAR_CODE ('DG30'), /** The system "Monitor RGB" profile, which is the same profile as that returned by AC_MainMonitorProfile. */ AC_Profile_MonitorRGB = FOUR_CHAR_CODE ('mRGB'), /** The system default profiles for RGB color space. (Currently a ColorSync 3.0 only feature.) */ AC_Profile_SystemRGB = FOUR_CHAR_CODE ('sysR'), /** The system default profiles for CMYK color space. (Currently a ColorSync 3.0 only feature.) */ AC_Profile_SystemCMYK = FOUR_CHAR_CODE ('sysC'), /** The system default profiles for Gray color space. (Currently a ColorSync 3.0 only feature.) */ AC_Profile_SystemGray = FOUR_CHAR_CODE ('sysG'), /** The system default profiles for input device type. (Currently a ColorSync 3.0 only feature.) */ AC_Profile_SystemInput = FOUR_CHAR_CODE ('sysI'), /** The system default profiles for output device type. (Currently a ColorSync 3.0 only feature.) */ AC_Profile_SystemOutput = FOUR_CHAR_CODE ('sysO'), /** The system default profiles for proofer device type. (Currently a ColorSync 3.0 only feature.) */ AC_Profile_SystemProofer = FOUR_CHAR_CODE ('sysP'), /** The application working (RGB) color space profiles. (For use as abstact values only, since ACE does not keep track of these profiles, and thus cannot make profiles from these codes.) */ AC_Profile_WorkingRGB = FOUR_CHAR_CODE ('wRGB'), /** The application working (CMYK) color space profiles. (For use as abstact values only, since ACE does not keep track of these profiles, and thus cannot make profiles from these codes.) */ AC_Profile_WorkingCMYK = FOUR_CHAR_CODE ('wCMY'), /** The application working (gray) color space profiles. (For use as abstact values only, since ACE does not keep track of these profiles, and thus cannot make profiles from these codes.) */ AC_Profile_WorkingGray = FOUR_CHAR_CODE ('wGry'), /** This constant forces the enum to be 32 bits wide. */ AC_Profile_MaxEnum = 0xFFFFFFFFL } AC_ProfileCode; /** Constants that specify the packing used in a color transformation. */ typedef enum { /** 8-bit RGB (or grayscale destination), with a leading pad byte. When grayscale is output in this format, the gray value is replicated into to the R, G, and B values. <p><code>R, G, B = 0</code> is black.</p> <p><code>R, G, B = 255</code> is white.</p> <p>Data must be 32-bit aligned.</p> */ AC_Packing_pRGB8 = FOUR_CHAR_CODE ('prgb'), /** Same as AC_Packing_pRGB8, without the leading pad byte. Data need only be 8-bit aligned. */ AC_Packing_RGB8 = FOUR_CHAR_CODE ('rgb '), /** 15+ bit RGB (or grayscale destination), with a leading pad word. When grayscale is output in this format, the gray value is replicated into to the R, G, and B values. <p><code>R, G, B = 0</code> is black.</p> <p><code>R, G, B = 32768</code> is white.</p> <p>Values greater than <code>32768</code> are invalid.</p> <p>Data must be 64-bit aligned.</p> */ AC_Packing_pRGB15 = FOUR_CHAR_CODE ('PRGB'), /** 8-bit CMYK. <p><code>C, M, Y, K = 0</code> is 100% ink.</p> <p><code>C, M, Y, K = 255</code> is 0% ink.</p> <p>Data must be 32-bit aligned.</p> */ AC_Packing_CMYK8_Black0 = FOUR_CHAR_CODE ('cmyk'), /** Same as AC_Packing_CMYK8_Black0 with inverse encoding. */ AC_Packing_CMYK8_White0 = FOUR_CHAR_CODE ('cmyw'), /** 15+ bit CMYK. <p><code>C, M, Y, K = 0</code> is 100% ink.</p> <p><code>C, M, Y, K = 32768</code> is 0% ink.</p> <p>Values greater than <code>32768</code> are invalid.</p> <p>Data must be 64-bit aligned.</p> */ AC_Packing_CMYK15_Black0 = FOUR_CHAR_CODE ('CMYK'), /** 8-bit LAB, with a leading pad byte. <p><code>L = 0</code> means <code>L* = 0.0</code></p> <p><code>L = 255</code> means <code>L* = 100.0</code></p> <p><code>a, b = 0</code> means <code>a*, b* = -128.0</code></p> <p><code>a, b = 128</code> means <code>a*, b* = 0.0</code></p> <p><code>a, b = 255</code> means <code>a*, b* = +127.0</code></p> <p>Data must be 32-bit aligned.</p> */ AC_Packing_pLab8 = FOUR_CHAR_CODE ('plab'), /** Same as AC_Packing_pLab8, without the leading pad byte. <p>Data need only be 8-bit aligned.</p> */ AC_Packing_Lab8 = FOUR_CHAR_CODE ('lab '), /** 15+ bit LAB, with a leading pad word. <p><code>L = 0</code> means <code>L* = 0.0</code></p> <p><code>L = 32768</code> means <code>L* = 100.0</code></p> <p><code>a, b = 0</code> means <code>a*, b* = -128.0</code></p> <p><code>a, b = 16384</code> means <code>a*, b* = 0.0</code></p> <p><code>a, b = 32768</code> means <code>a*, b* = +128.0</code></p> <p>Values greater than <code>32768</code> are invalid.</p> <p>Data must be 64-bit aligned.</p> */ AC_Packing_pLab15 = FOUR_CHAR_CODE ('PLAB'), /** 8-bit grayscale or gamut test results, no padding. <p><code>G = 0</code> is 100% ink or black or fully out of gamut.</p> <p><code>G = 255</code> is 0% ink or white or fully in gamut.</p> <p>When used for gamut test results, any value greater than or equal to <code>128</code> should be considered to be in gamut.</p> */ AC_Packing_Gray8_Black0 = FOUR_CHAR_CODE ('g8k0'), /** Same as AC_Packing_Gray8_Black0 with inverse encoding. */ AC_Packing_Gray8_White0 = FOUR_CHAR_CODE ('g8w0'), /** 15+ bit grayscale or gamut test results, no padding. <p><code>G = 0</code> is 100% ink or black or fully out of gamut.</p> <p><code>G = 32768</code> is 0% ink or white or fully in gamut.</p> <p>Values greater than <code>32768</code> are invalid.</p> <p>Data must be 16-bit aligned.</p> */ AC_Packing_Gray15_Black0 = FOUR_CHAR_CODE ('G15K'), /** 16-bit XYZ, with a leading pad word. <p><code>X, Y, Z = 0</code> means <code>X, Y, Z = 0.0</code></p> <p><code>X, Y, Z = 32768</code> means <code>X, Y, Z = 1.0</code></p> <p><code>X, Y, Z = 65535</code> means <code>X, Y, Z = 1.9999694824</code>.</p> <p>Data must be 64-bit aligned.</p> */ AC_Packing_pXYZ16 = FOUR_CHAR_CODE ('PXYZ'), /** Generic padded 3-component 8-bit packing. Data must be 32-bit aligned. */ AC_Packing_pABC8 = FOUR_CHAR_CODE ('pabc'), /** Same as AC_Packing_pABC8, without the leading pad byte. Data need only be 8-bit aligned. */ AC_Packing_ABC8 = FOUR_CHAR_CODE ('abc '), /** Generic padded 3-component 15+ bit packing. Data must be 64-bit aligned. */ AC_Packing_pABC15 = FOUR_CHAR_CODE ('pABC'), /** Generic 4-component 8-bit packing. Data must be 32-bit aligned. */ AC_Packing_ABCD8 = FOUR_CHAR_CODE ('abcd'), /** Generic 4-component 15+ bit packing. Data must be 64-bit aligned. */ AC_Packing_ABCD15 = FOUR_CHAR_CODE ('ABCD'), /** Packing codes for native 64-bit (gray) ColorSync formats (type "CMColor"). ICM2 also uses these packings formats (type "COLOR"). See the Apple ColorSync documentation for the details of these formats. These are mostly intended for internal use by ACE, and are not intended for use by most ACE clients. Data must be 16-bit aligned. */ AC_Packing_CS64_Gray = FOUR_CHAR_CODE ('CS01'), /** Packing codes for native 64-bit (RGB) ColorSync formats (type "CMColor"). ICM2 also uses these packings formats (type "COLOR"). See the Apple ColorSync documentation for the details of these formats. These are mostly intended for internal use by ACE, and are not intended for use by most ACE clients. Data must be 16-bit aligned. */ AC_Packing_CS64_RGB = FOUR_CHAR_CODE ('CS02'), /** Packing codes for native 64-bit (CMYK) ColorSync formats (type "CMColor"). ICM2 also uses these packings formats (type "COLOR"). See the Apple ColorSync documentation for the details of these formats. These are mostly intended for internal use by ACE, and are not intended for use by most ACE clients. Data must be 16-bit aligned. */ AC_Packing_CS64_CMYK = FOUR_CHAR_CODE ('CS03'), /** Packing codes for native 64-bit (Lab) ColorSync formats (type "CMColor"). ICM2 also uses these packings formats (type "COLOR"). See the Apple ColorSync documentation for the details of these formats. These are mostly intended for internal use by ACE, and are not intended for use by most ACE clients. Data must be 16-bit aligned. */ AC_Packing_CS64_Lab = FOUR_CHAR_CODE ('CS04'), /** Packing codes for native 64-bit (xyz) ColorSync formats (type "CMColor"). ICM2 also uses these packings formats (type "COLOR"). See the Apple ColorSync documentation for the details of these formats. These are mostly intended for internal use by ACE, and are not intended for use by most ACE clients. Data must be 16-bit aligned. */ AC_Packing_CS64_XYZ = FOUR_CHAR_CODE ('CS05'), /** Packing codes for native 64-bit (abc) ColorSync formats (type "CMColor"). ICM2 also uses these packings formats (type "COLOR"). See the Apple ColorSync documentation for the details of these formats. These are mostly intended for internal use by ACE, and are not intended for use by most ACE clients. Data must be 16-bit aligned. */ AC_Packing_CS64_ABC = FOUR_CHAR_CODE ('CS06'), /** Packing codes for native 64-bit (abcd)ColorSync formats (type "CMColor"). ICM2 also uses these packings formats (type "COLOR"). See the Apple ColorSync documentation for the details of these formats. These are mostly intended for internal use by ACE, and are not intended for use by most ACE clients. Data must be 16-bit aligned. */ AC_Packing_CS64_ABCD = FOUR_CHAR_CODE ('CS07'), /** <code>NULL</code> data, for use with data in AC_Space_Null. */ AC_Packing_Null = FOUR_CHAR_CODE ('null'), /** None of the above; use the general packing specification. */ AC_Packing_General = 0, /** This constant forces the <code>enum</code> to be 32 bits wide. */ AC_Packing_MaxEnum = 0xFFFFFFFFL } AC_PackingCode; /** Constants that specify a standard ICC rendering intent for a device color profile. The rendering intent specifies the color translation method for colors that are outside the gamut of the color profile. @see ACMakeCalGray @see ACMakeCalLab @see ACMakeCalRGB */ typedef enum { /** Tries to preserve the visual relationship between colors in a way that is perceived as natural to the human eye, although the color values themselves may change. This is the same as the Image intent in Adobe PageMaker and Illustrator. This option is suitable for photographic, continuous tone images. */ AC_Perceptual = 0, /** The same as absolute colorimetric, except that it compares the white point of the source color space to that of the destination color space and shifts all other colors accordingly, rather than comparing individual colors. */ AC_RelColorimetric = 1, /** Tries to create vivid color at the expense of accurate color. It scales the source gamut to the destination gamut, but preserves relative saturation instead of hue, so that when scaling to a smaller gamut, hues may shift. This is the same as the Graphics intent in Adobe PageMaker and Illustrator. This option is suitable for business graphics and charts, where the exact relationship between colors is not as important as having bright saturated colors. */ AC_Saturation = 2, /** Tries to maintain color accuracy at the expense of preserving relationships between colors. It leaves colors that fall inside the destination gamut unchanged. When translating to a smaller gamut, two colors that are distinct in the source space may be mapped to the same color in the destination space. This type of rendering can be more accurate than AC_RelColorimetric if the color profile of the image contains correct white point (extreme highlight) information. */ AC_AbsColorimetric = 3, /** Use the source profile's rendering intent. */ AC_UseProfileIntent = 0xFFFFFFFFL } AC_RenderIntent; #ifdef WIN_ENV #define kACMaxPathLength 260 #else #define kACMaxPathLength 256 #endif /** Contains a platform-specific version of a file specification. This is an FSSpec on Mac OS, or a full path name on other platforms. @see ACLoadSettings @see ACPresetFileToName @see ACPresetListItemFile */ typedef struct _t_AC_FileSpec { #ifdef MAC_ENV /** On Mac OS, use an FSSpec. */ FSSpec spec; #else /** Use a full path name when not using Mac OS. */ char path [kACMaxPathLength]; #endif } AC_FileSpec; /* color types */ /** Floating-point XYZ color. A pure black would be encoded as <code>0.0, 0.0, 0.0</code>, while a D50-based pure white would be encoded as <code>0.9642, 1.0, 0.8249</code>. @see ACCalCMYK @see ACCalGray @see ACCalLab @see ACCalRGB */ typedef struct _t_ACXYZColor { /** X-component of a floating-point XYZ color. */ double X; /** Y-component of a floating-point XYZ color. */ double Y; /** Z-component of a floating-point XYZ color. */ double Z; } AC_XYZColor; /******************************************************************************/ /** Floating-point xy chromaticity coordinate. These can be computed from XYZ colors using <code>x = X / (X + Y + Z)</code> and <code>y = Y / (X + Y + Z)</code>. */ typedef struct _t_ACXYColor { double x; double y; } AC_XYColor; /** A tone curve value for use in a calibrated CMYK color space specification. @see ACCalCMYK */ typedef struct _t_ACToneCurve { /** The number of bytes per value (1 or 2). */ ASUns32 bytesPerValue; /** Number of samples (often 256). */ ASUns32 count; /** A pointer to the samples. */ void *data; } AC_ToneCurve; /******************************************************************************/ /** <p>A simple 16-patch calibrated CMYK color space specification.</p> <p>The 16 <code>AC_XYZColor</code> values are the absolute XYZ values of all 16 CMYK ink combinations, including paper white. The illuminant is assumed to be D50.</p> <p>The <code>AC_ToneCurve</code> values represent the dot gain curves for each ink. Each one maps from ink percentage to the dot area percentage.</p> */ typedef struct _t_ACCalCMYK { /** Absolute XYZ value of a CMYK ink combination: paper white. */ AC_XYZColor w; /** Absolute XYZ value of a CMYK ink combination: K. */ AC_XYZColor k; /** Absolute XYZ value of a CMYK ink combination: C. */ AC_XYZColor c; /** Absolute XYZ value of a CMYK ink combination: M. */ AC_XYZColor m; /** Absolute XYZ value of a CMYK ink combination: Y. */ AC_XYZColor y; /** Absolute XYZ value of a CMYK ink combination: CM. */ AC_XYZColor cm; /** Absolute XYZ value of a CMYK ink combination: CY. */ AC_XYZColor cy; /** Absolute XYZ value of a CMYK ink combination: CK. */ AC_XYZColor ck; /** Absolute XYZ value of a CMYK ink combination: MY. */ AC_XYZColor my; /** Absolute XYZ value of a CMYK ink combination: MK. */ AC_XYZColor mk; /** Absolute XYZ value of a CMYK ink combination: YK. */ AC_XYZColor yk; /** Absolute XYZ value of a CMYK ink combination: CMY. */ AC_XYZColor cmy; /** Absolute XYZ value of a CMYK ink combination: CMK. */ AC_XYZColor cmk; /** Absolute XYZ value of a CMYK ink combination: CYK. */ AC_XYZColor cyk; /** Absolute XYZ value of a CMYK ink combination: MYK. */ AC_XYZColor myk; /** Absolute XYZ value of a CMYK ink combination: CMYK. */ AC_XYZColor cmyk; /** Dot gain curve for the cyan ink. */ AC_ToneCurve cTRC; /** Dot gain curve for the magenta ink. */ AC_ToneCurve mTRC; /** Dot gain curve for the yellow ink. */ AC_ToneCurve yTRC; /** Dot gain curve for the black ink. */ AC_ToneCurve kTRC; /** Adds a gamma curve to the output XYZ values, after the CLUT. This was used by old versions of Photoshop, and is now obsolete. It should always be set to <code>1.0</code>. */ double opticalGamma; /** The absolute XYZ value of paper white. It should be a duplicate of the <code>w</code> entry. */ AC_XYZColor white; /** The absolute XYZ value of a legal (within total ink limits) four-color CMYK black. It is currently ignored. */ AC_XYZColor black; } ACCalCMYK; /******************************************************************************/ /** Floating-point Lab color. Pure white is encoded as <code>100.0, 0.0, 0.0</code>. The usual <code>a</code> and <code>b</code> range is <code>-128.0</code> to <code>+127.0</code>, but this structure supports any <code>a</code> and <code>b</code> range. @see ACMakeCalLab */ typedef struct _t_AC_LabColor { double L; double a; double b; } AC_LabColor; /******************************************************************************/ /** A calibrated grayscale space specification. @see ACMakeCalGray */ typedef struct _t_ACCalGray { /** Gamma value. Normal values are greater than or equal to <code>1.0</code>. */ double gamma; /** Absolute XYZ value of a monitor white point (illuminant). The Y-value should be equal to <code>1.0</code>. */ AC_XYZColor white; /** Absolute XYZ value of a monitor black point. */ AC_XYZColor black; } ACCalGray; /******************************************************************************/ /** A calibrated RGB space specification. The <code>red</code>, <code>green</code>, and <code>blue</code> members represent columns of the matrix used to convert between RGB values and XYZ values. Normally, red + green + blue should exactly equal white (even if the monitor black point is non-zero). This means that, unless the monitor black point is zero, these entries are not equal to the absolute XYZ values of the pure RGB components (due to non-zero offsets in the other two components). This interpretation of these entries is used to maximize compatibility with the PDF <code>CalRGB</code> color space, which is defined using a matrix (rather than component XYZ values). @see ACMakeCalRGB */ typedef struct _t_ACCalRGB { /** Red gamma value for each component. Normal values are greater than or equal to <code>1.0</code>. */ double redGamma; /** Green gamma value for each component. Normal values are greater than or equal to <code>1.0</code>. */ double greenGamma; /** Blue gamma value for each component. Normal values are greater than or equal to <code>1.0</code>. */ double blueGamma; /** Red column of the matrix used to convert between RGB values and XYZ values. */ AC_XYZColor red; /** Green column of the matrix used to convert between RGB values and XYZ values. */ AC_XYZColor green; /** Blue column of the matrix used to convert between RGB values and XYZ values. */ AC_XYZColor blue; /** The absolute XYZ value of the monitor white point (illuminant). The Y-value shall be equal to <code>1.0</code>. See <i>CalRGB Color Spaces</i> in the <i>PDF Reference</i>. */ AC_XYZColor white; /** The absolute XYZ value of the monitor black point. */ AC_XYZColor black; } ACCalRGB; /******************************************************************************/ /** A calibrated Lab color space specification. The usual <code>min</code> and <code>max</code> values for <code>rangeA</code> and <code>rangeB</code> are <code>-128</code> and <code>+127</code>. @see ACMakeCalLab */ typedef struct _t_ACCalLab { /** Color space white point. The Y value should be equal to <code>1.0</code>. */ AC_XYZColor white; /** Color space black point. It is currently ignored by ACE when creating profiles, and is always set to zero when extracting from profiles. */ AC_XYZColor black; /** Range limits for the <code>a*</code> component. Values outside this range are clipped to this range. */ struct { /** The usual value is <code>-128</code>. */ ASInt32 min; /** The usual value <code>+127</code>. */ ASInt32 max; } rangeA; /** Range limits for the <code>b*</code> component. Values outside this range are clipped to this range. */ struct { /** The usual value is <code>-128</code>. */ ASInt32 min; /** The usual value <code>+127</code>. */ ASInt32 max; } rangeB; } ACCalLab; /** Constant key values for an <code>AC_Settings</code> object. @see ACGetSettingsProfile @see ACGetSettingsString @see ACGetSettingsUnsigned32 */ typedef enum { /** Settings file name string (if different than the file name). */ AC_Key_Name = FOUR_CHAR_CODE ('name'), /** Settings file description string. */ AC_Key_Description = FOUR_CHAR_CODE ('desc'), /** Name of application to write this settings file. */ AC_Key_WriterName = FOUR_CHAR_CODE ('wNam'), /** Working RGB profile. */ AC_Key_WorkingRGB = FOUR_CHAR_CODE ('wRGB'), /** Working CMYK profile. */ AC_Key_WorkingCMYK = FOUR_CHAR_CODE ('wCMY'), /** Working gray profile. */ AC_Key_WorkingGray = FOUR_CHAR_CODE ('wGry'), /** Working spot profile. */ AC_Key_WorkingSpot = FOUR_CHAR_CODE ('wSpt'), /** RGB color management policy (AC_Policy <code>enum</code>). */ AC_Key_PolicyRGB = FOUR_CHAR_CODE ('pRGB'), /** CMYK color management policy (AC_Policy <code>enum</code>). */ AC_Key_PolicyCMYK = FOUR_CHAR_CODE ('pCMY'), /** Gray color management policy (AC_Policy <code>enum</code>). */ AC_Key_PolicyGray = FOUR_CHAR_CODE ('pGry'), /** Ask about profile mismatches when opening (<code>0</code> = no, <code>1</code> = yes). */ AC_Key_MismatchAskOpening = FOUR_CHAR_CODE ('mAsk'), /** Ask about profile mismatches when pasting (<code>0</code> = no, <code>1</code> = yes). */ AC_Key_MismatchAskPasting = FOUR_CHAR_CODE ('pAsk'), /** Ask about missing profile when opening (<code>0</code> = no, <code>1</code> = yes). */ AC_Key_MissingAskOpening = FOUR_CHAR_CODE ('misA'), /** Conversion engine CMS code (4-char code, stored as <code>unsigned32</code>). */ AC_Key_EngineCMS = FOUR_CHAR_CODE ('eCMS'), /** Conversion engine CMM code (4-char code, stored as <code>unsigned32</code>). */ AC_Key_EngineCMM = FOUR_CHAR_CODE ('eCMM'), /** Conversion intent (standard ICC integer encoding). */ AC_Key_Intent = FOUR_CHAR_CODE ('cInt'), /** Conversion black point compensation (<code>0</code> = no, <code>1</code> = yes). */ AC_Key_KPC = FOUR_CHAR_CODE ('kpc '), /** Dither conversions between 8-bit color spaces (<code>0</code> = no, <code>1</code> = yes). */ AC_Key_Dither = FOUR_CHAR_CODE ('dith'), /** Enable or disable monitor compression (<code>0</code> = off, <code>1</code> = on). */ AC_Key_CompressionEnabled = FOUR_CHAR_CODE ('mce '), /** Monitor compression percent (in percent). */ AC_Key_CompressionPercent = FOUR_CHAR_CODE ('mcp '), /** Enable or disable RGB blending gamma (<code>0</code> = off, <code>1</code> = on). */ AC_Key_BlendGammaEnabled = FOUR_CHAR_CODE ('bge '), /** RGB blending gamma value (<code>100</code> = gamma 1.00). */ AC_Key_BlendGammaValue = FOUR_CHAR_CODE ('bgv '), /** Proof type (AC_ProofType <code>enum</code>). */ AC_Key_ProofType = FOUR_CHAR_CODE ('pTyp'), /** Proof profile. */ AC_Key_ProofProfile = FOUR_CHAR_CODE ('pPrf'), /** Display simulation (AC_Simulate <code>enum</code>). */ AC_Key_Simulate = FOUR_CHAR_CODE ('dSim'), /** This constant forces the <code>enum</code> to be 32 bits wide. */ AC_Key_MaxEnum = 0xFFFFFFFFL } AC_SettingsKey; /** Constant values that determine the type of an AC_Settings object. @see ACMakePresetList @see ACMakeSettings */ typedef enum { /** Used to hold global color settings, such as working spaces. */ AC_SettingsType_Color = FOUR_CHAR_CODE ('AsCs'), /** Used to specify the parameters for proofing a document. The Proof Setup Files generally control a per-window setting. */ AC_SettingsType_Proof = FOUR_CHAR_CODE ('AsPs'), /** This constant forces the <code>enum</code> to be 32 bits wide. */ AC_SettingsType_MaxEnum = 0xFFFFFFFFL } AC_SettingsType; /** Constant values for ICC color space signatures. @see ACProfileColorSpace */ typedef enum { /** @ingroup StdICCColorSpaceSignatures */ AC_Space_XYZ = FOUR_CHAR_CODE ('XYZ '), /** @ingroup StdICCColorSpaceSignatures */ AC_Space_Lab = FOUR_CHAR_CODE ('Lab '), /** @ingroup StdICCColorSpaceSignatures */ AC_Space_RGB = FOUR_CHAR_CODE ('RGB '), /** @ingroup StdICCColorSpaceSignatures */ AC_Space_Gray = FOUR_CHAR_CODE ('GRAY'), /** @ingroup StdICCColorSpaceSignatures */ AC_Space_CMYK = FOUR_CHAR_CODE ('CMYK'), /** @ingroup StdICCColorSpaceSignatures */ AC_Space_Luv = FOUR_CHAR_CODE ('Luv '), /** @ingroup StdICCColorSpaceSignatures */ AC_Space_YCbCr = FOUR_CHAR_CODE ('YCbr'), /** @ingroup StdICCColorSpaceSignatures */ AC_Space_HSV = FOUR_CHAR_CODE ('HSV '), /** @ingroup StdICCColorSpaceSignatures */ AC_Space_HLS = FOUR_CHAR_CODE ('HLS '), /** @ingroup StdICCColorSpaceSignatures */ AC_Space_CMY = FOUR_CHAR_CODE ('CMY '), /** @ingroup GenericICCColorSpaceSignatures */ AC_Space_2Component = FOUR_CHAR_CODE ('2CLR'), /** @ingroup GenericICCColorSpaceSignatures */ AC_Space_3Component = FOUR_CHAR_CODE ('3CLR'), /** @ingroup GenericICCColorSpaceSignatures */ AC_Space_4Component = FOUR_CHAR_CODE ('4CLR'), /** @ingroup GenericICCColorSpaceSignatures */ AC_Space_5Component = FOUR_CHAR_CODE ('5CLR'), /** @ingroup GenericICCColorSpaceSignatures */ AC_Space_6Component = FOUR_CHAR_CODE ('6CLR'), /** @ingroup GenericICCColorSpaceSignatures */ AC_Space_7Component = FOUR_CHAR_CODE ('7CLR'), /** @ingroup GenericICCColorSpaceSignatures */ AC_Space_8Component = FOUR_CHAR_CODE ('8CLR'), /** @ingroup GenericICCColorSpaceSignatures */ AC_Space_9Component = FOUR_CHAR_CODE ('9CLR'), /** @ingroup GenericICCColorSpaceSignatures */ AC_Space_10Component = FOUR_CHAR_CODE ('ACLR'), /** @ingroup GenericICCColorSpaceSignatures */ AC_Space_11Component = FOUR_CHAR_CODE ('BCLR'), /** @ingroup GenericICCColorSpaceSignatures */ AC_Space_12Component = FOUR_CHAR_CODE ('CCLR'), /** @ingroup GenericICCColorSpaceSignatures */ AC_Space_13Component = FOUR_CHAR_CODE ('DCLR'), /** @ingroup GenericICCColorSpaceSignatures */ AC_Space_14Component = FOUR_CHAR_CODE ('ECLR'), /** @ingroup GenericICCColorSpaceSignatures */ AC_Space_15Component = FOUR_CHAR_CODE ('FCLR'), /** Kodak's PhotoYCC space is stored as a generic 3-component space. @ingroup GenericICCColorSpaceSignatures */ AC_Space_PhotoYCC = AC_Space_3Component, /** A null color space. Used to represent spot-only color spaces. @ingroup GenericICCColorSpaceSignatures */ AC_Space_Null = 0, /** This constant forces the enum to be 32 bits wide. */ AC_Space_MaxEnum = 0xFFFFFFFFL } AC_ColorSpace; /** Constants that specify the color space of working profiles. This enumeration is added for the purpose of ACGetWorkingSpaceProfile(). The profile returned by this function must be unreferenced by the caller. @see ACGetWorkingSpaceProfile */ typedef enum { /** Grayscale profile. */ kACWorkingGray = 0, /** RGB profile. */ kACWorkingRGB = 1, /** CMYK profile. */ kACWorkingCMYK = 2, /** Working spaces. */ kACWorkingSpaces = 3 }ACWorkingSpace; #ifdef WIN_ENV #define kACEMaxPathLength 260 #else #define kACEMaxPathLength 256 #endif //typedef struct _t_PDColorConvertParamsRec *PDColorConvertParams; /* Object Attributes: these are arranged as a bitmap. In order to */ /* match, one must satisfy all ON bits. There are obviously combinations */ /* that are redundant or don't make sense. */ #define _FLG(n) (1 << n) /** Object attributes: these are arranged as a bitmap. */ typedef enum { /** Object is an image. */ kColorConvObj_Image = _FLG(0), /** Object is a JPEG image. */ kColorConvObj_JPEG = _FLG(1), /** Object is a JPEG2000 image. */ kColorConvObj_JPEG2000 = _FLG(2), /** Image is in a lossy space. */ kColorConvObj_Lossy = _FLG(3), /** Image is in a non-lossy space. */ kColorConvObj_Lossless = _FLG(4), /** Object is text. */ kColorConvObj_Text = _FLG(5), /** Object is line-art (fill, stroke). */ kColorConvObj_LineArt = _FLG(6), /** Object is a smooth shade. */ kColorConvObj_Shade = _FLG(7), /** Object is not opaque. */ kColorConvObj_Transparent = _FLG(8), /** Object overprints. */ kColorConvObj_Overprinting = _FLG(9), /** Overprint mode (OPM) is set to <code>1</code>. */ kColorConvObj_OverprintMode = _FLG(10), /** Any object. */ kColorConvObj_AnyObject = (_FLG(0)|_FLG(5)|_FLG(6)|_FLG(7)), /** Maximum enum value. */ kColorConvObj_MaxEnum = 0xFFFFFFFFL } PDColorConvertObjectAttributeFlags; typedef ASUns32 PDColorConvertObjectAttributes; /** Color Space attributes: these are arranged as a bitmap. */ typedef enum { /** Device color space. */ kColorConvDeviceSpace = _FLG(0), /** Calibrated color space. */ kColorConvCalibratedSpace = _FLG(1), /** Alternate color space. */ kColorConvAlternateSpace = _FLG(3), /* This is an alternate color space */ /** Base of an indexed space. */ kColorConvBaseSpace = _FLG(4), /* Base of an indexed space */ /** Indexed color space. */ kColorConvIndexedSpace = _FLG(5), /** Separation color space. */ kColorConvSeparationSpace = _FLG(6), /** DeviceN color space. */ kColorConvDeviceNSpace = _FLG(7), /** NChannel color space. */ kColorConvNChannelSpace = _FLG(8), /** RGB color space. This should only be set if either Device space (unless Lab) or Calibrated space is set. */ kColorConvRGBSpace = _FLG(9), /** CMYK color space. This should only be set if either Device space (unless Lab) or Calibrated space is set. */ kColorConvCMYKSpace = _FLG(10), /** Gray color space. This should only be set if either Device space (unless Lab) or Calibrated space is set. */ kColorConvGraySpace = _FLG(11), /** Lab color space. */ kColorConvLabSpace = _FLG(12), /** Any color space. */ kColorConvAnySpace = (_FLG(0)|_FLG(1)|_FLG(2)|_FLG(3)|_FLG(4)|_FLG(5)|_FLG(6)|_FLG(7)|_FLG(8)|_FLG(9)|_FLG(10)|_FLG(11)|_FLG(12)), /** Maximum enum value. */ kColorConvSpace_MaxEnum = 0xFFFFFFFFL } PDColorConvertSpaceTypeFlags; typedef ASUns32 PDColorConvertSpaceType; /** Action types: these specify what to do when an object is matched. */ typedef enum { /** Do nothing but handle ink aliases. */ kColorConvPreserve, /** Convert to target space. */ kColorConvConvert, /** Convert calibrated space to device space. */ kColorConvDecalibrate, /** Convert NChannel space to DeviceN space. */ kColorConvDownConvert, /** Maximum enum value. */ kColorConvMaxEnum = 0xFFFFFFFFL } PDColorConvertActionType; /** Defines a color conversion action for a combination of attributes, color space/family, and rendering intent. If all three match, the actions in the action list will be executed for any given object. */ typedef struct { /** Object attribute. The flags must all match for a match. */ PDColorConvertObjectAttributes mMatchAttributesAll; /** Object attribute. The flags will allow any match. */ PDColorConvertObjectAttributes mMatchAttributesAny; /** Type of color space. The flags must all match for a match. */ PDColorConvertSpaceType mMatchSpaceTypeAll; /** Type of color space. The flags will allow any match. */ PDColorConvertSpaceType mMatchSpaceTypeAny; /** The rendering intent of the object. If this is <code>AC_UseProfileIntent</code>, this action applies to any intent. */ AC_RenderIntent mMatchIntent; /** Defines the action, indicating what to do when an object matches this record. */ PDColorConvertActionType mAction; /** If converting, use this intent to override the object's intent for performing color conversion. <code>AC_UseProfileIntent</code> means that the intent of the object must not be overridden. */ AC_RenderIntent mConvertIntent; /** The target profile for the conversion. If the output intent is embedded, this should be the output intent profile. */ AC_Profile mConvertProfile; /** If <code>true</code>, embed the target profile. If <code>false</code> the resulting color is Device, if possible. */ ASBool mEmbed; /** If <code>true</code>, perform a black-preserving transform when converting. */ ASBool mPreserveBlack; /* (todo: perhaps there should be a "use current settings" option in */ /* addition to true/false) */ /** If <code>true</code>, turn on black point compensation for color conversions. */ ASBool mUseBlackPointCompensation; /** For ink actions (which describe a single colorant, whether used in Separation or DeviceN, and which are not matched using the above matching fields) this describes the colorant of the ink. */ ASAtom mColorantName; /** Ink alias; this only applies to ink actions. */ ASAtom mAlias; /** <code>true</code> if this ink is a process ink. */ ASBool mIsProcessColor; /** For internal use. */ void * mInternal; } PDColorConvertActionRec, *PDColorConvertAction; /** The list of actions in <code>PDColorConvertParams</code> is analogous to the list of filters in most email clients: each object is compared against the selection criteria for each of the actions, in order, until a matching action is found. The action is then executed on the object. Note that actions do not chain, except in the case of aliased ink definitions. */ typedef struct //_t_PDColorConvertParamsRec { /** The number of color conversion actions. */ ASInt32 mNumActions; /** The actions, arranged sequentially in memory. */ PDColorConvertAction mActions; /** The number of specific inks supplied. */ ASInt32 mNumInks; /** The list of ink actions, arranged sequentially in memory. */ PDColorConvertAction mInks; } PDColorConvertParamsRec, *PDColorConvertParams; /* Added min/max text size and promote gray to CMYK flag. */ /** Defines a color conversion action for a combination of attributes, color space/family, and rendering intent. If all three match, actions in the action list will be executed for any given object. */ typedef struct { /** The size (in bytes) of this structure. */ ASSize_t mSize; /** The object attributes. The flags must all match for a match. */ PDColorConvertObjectAttributes mMatchAttributesAll; /** The object attributes. The flags will allow any match. */ PDColorConvertObjectAttributes mMatchAttributesAny; /** The type of color space. The flags must all match for a match. */ PDColorConvertSpaceType mMatchSpaceTypeAll; /** The type of color space. The flags will allow any match. */ PDColorConvertSpaceType mMatchSpaceTypeAny; /** The rendering intent of the object. If this is <code>AC_UseProfileIntent</code>, this action applies to any intent. */ AC_RenderIntent mMatchIntent; /** The font size to match for text objects. */ double mMatchMinFontSize, mMatchMaxFontSize; /** Defines the action, specifying what to do when an object matches this record. */ PDColorConvertActionType mAction; /** If converting, use this intent to override the object's intent for performing color conversion. <code>AC_UseProfileIntent</code> means that the intent of the object must not be overridden. */ AC_RenderIntent mConvertIntent; /** The target profile for the conversion. If the output intent is embedded, this should be the output intent profile. */ AC_Profile mConvertProfile; /** If <code>true</code>, embed the target profile. If <code>false</code>, the resulting color is Device, if possible. */ ASBool mEmbed; /** If <code>true</code>, perform a black-preserving transform when converting. */ ASBool mPreserveBlack; /** If <code>true</code>, promote DeviceGray objects to DeviceCMYK with <code>K = 1.0 - gray value</code>. */ ASBool mPromoteGrayToCMYK; /* (todo: perhaps there should be a "use current settings" option in */ /* addition to true/false) */ /** If <code>true</code>, turn on black point compensation for color conversions. */ ASBool mUseBlackPointCompensation; /** For ink actions (which describe a single colorant, whether used in Separation or DeviceN, and which are not matched using the above matching fields) this describes the colorant of the ink. */ ASAtom mColorantName; /** Ink alias; this only applies to ink actions. */ ASAtom mAlias; /** <code>true</code> if this ink is a process ink. */ ASBool mIsProcessColor; /** If <code>true</code>, use a primary-preserving CMYK to CMYK transform. */ ASBool mPreserveCMYKPrimaries; /** For internal use. */ void * mInternal; } PDColorConvertActionRecEx, *PDColorConvertActionEx; /** The list of actions in <code>PDColorConvertParams</code> is analogous to the list of filters in most email clients: each object is compared against the selection criteria for each of the actions, in order, until a matching action is found. The action is then executed on the object. Note that actions do not chain, except in the case of aliased ink definitions. This is the <i>Extended</i> structure, which supports additional elements in the <code>PDColorConvertActionRecEx</code> action. */ typedef struct //_t_PDColorConvertParamsRecEx { /** The size of this data structure. */ ASSize_t mSize; /** The number of color conversion actions. */ ASInt32 mNumActions; /** The actions, arranged sequentially in memory. */ PDColorConvertActionEx mActions; /** The number of specific inks supplied. */ ASInt32 mNumInks; /** The list of ink actions, arranged sequentially in memory. */ PDColorConvertActionEx mInks; } PDColorConvertParamsRecEx, *PDColorConvertParamsEx; // Callback completion code /** Callback completion code. */ typedef enum { /** Success. */ PDCompletionSuccess, /** Continue. */ PDCompletionContinue, /** Abort. */ PDCompletionAbort } PDCompletionCode; /** Callback reason code. */ typedef enum { /** None. */ PDReasonNone, /** None implemented. */ PDReasonNotImplemented } PDReasonCode; /* Callback type for report proc */ typedef ACCBPROTO1 void (ACCBPROTO2 *PDColorConvertReportProc)( PDColorConvertObjectAttributes objectType, PDColorConvertSpaceType colorSpaceType, PDColorConvertActionType action, PDCompletionCode completionCode, PDReasonCode reasonCode, void *userData); /* Swatchbook API types */ /** Swatchbook database object. */ typedef void* ACSwatchBookDB; /** Swatchbook object. */ typedef void* ACSwatchBook; #ifdef __cplusplus } #endif #endif /* _H_AcroColorExpT */
/* ar-skbuff.c: socket buffer destruction handling * * Copyright (C) 2007 Red Hat, Inc. All Rights Reserved. * Written by <NAME> (<EMAIL>) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #include <linux/module.h> #include <linux/net.h> #include <linux/skbuff.h> #include <net/sock.h> #include <net/af_rxrpc.h> #include "ar-internal.h" /* * set up for the ACK at the end of the receive phase when we discard the final * receive phase data packet * - called with softirqs disabled */ static void rxrpc_request_final_ACK(struct rxrpc_call *call) { /* the call may be aborted before we have a chance to ACK it */ write_lock(&call->state_lock); switch (call->state) { case RXRPC_CALL_CLIENT_RECV_REPLY: call->state = RXRPC_CALL_CLIENT_FINAL_ACK; _debug("request final ACK"); /* get an extra ref on the call for the final-ACK generator to * release */ rxrpc_get_call(call); set_bit(RXRPC_CALL_ACK_FINAL, &call->events); if (try_to_del_timer_sync(&call->ack_timer) >= 0) rxrpc_queue_call(call); break; case RXRPC_CALL_SERVER_RECV_REQUEST: call->state = RXRPC_CALL_SERVER_ACK_REQUEST; default: break; } write_unlock(&call->state_lock); } /* * drop the bottom ACK off of the call ACK window and advance the window */ static void rxrpc_hard_ACK_data(struct rxrpc_call *call, struct rxrpc_skb_priv *sp) { int loop; u32 seq; spin_lock_bh(&call->lock); _debug("hard ACK #%u", ntohl(sp->hdr.seq)); for (loop = 0; loop < RXRPC_ACKR_WINDOW_ASZ; loop++) { call->ackr_window[loop] >>= 1; call->ackr_window[loop] |= call->ackr_window[loop + 1] << (BITS_PER_LONG - 1); } seq = ntohl(sp->hdr.seq); ASSERTCMP(seq, ==, call->rx_data_eaten + 1); call->rx_data_eaten = seq; if (call->ackr_win_top < UINT_MAX) call->ackr_win_top++; ASSERTIFCMP(call->state <= RXRPC_CALL_COMPLETE, call->rx_data_post, >=, call->rx_data_recv); ASSERTIFCMP(call->state <= RXRPC_CALL_COMPLETE, call->rx_data_recv, >=, call->rx_data_eaten); if (sp->hdr.flags & RXRPC_LAST_PACKET) { rxrpc_request_final_ACK(call); } else if (atomic_dec_and_test(&call->ackr_not_idle) && test_and_clear_bit(RXRPC_CALL_TX_SOFT_ACK, &call->flags)) { _debug("send Rx idle ACK"); __rxrpc_propose_ACK(call, RXRPC_ACK_IDLE, sp->hdr.serial, true); } spin_unlock_bh(&call->lock); } /* * destroy a packet that has an RxRPC control buffer * - advance the hard-ACK state of the parent call (done here in case something * in the kernel bypasses recvmsg() and steals the packet directly off of the * socket receive queue) */ void rxrpc_packet_destructor(struct sk_buff *skb) { struct rxrpc_skb_priv *sp = rxrpc_skb(skb); struct rxrpc_call *call = sp->call; _enter("%p{%p}", skb, call); if (call) { /* send the final ACK on a client call */ if (sp->hdr.type == RXRPC_PACKET_TYPE_DATA) rxrpc_hard_ACK_data(call, sp); rxrpc_put_call(call); sp->call = NULL; } if (skb->sk) sock_rfree(skb); _leave(""); } /** * rxrpc_kernel_free_skb - Free an RxRPC socket buffer * @skb: The socket buffer to be freed * * Let RxRPC free its own socket buffer, permitting it to maintain debug * accounting. */ void rxrpc_kernel_free_skb(struct sk_buff *skb) { rxrpc_free_skb(skb); } EXPORT_SYMBOL(rxrpc_kernel_free_skb);
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.md file in the project root for full license information. // #pragma once #include "stdafx.h" #include "CNTKLibrary.h" #define CNTK_ONNX_MODEL_VERSION 1 #define MACRO_TO_STRING(s) #s const std::string CNTK_ONNX_PRODUCER_NAME = "CNTK"; const std::string CNTK_ONNX_MODEL_DOMAIN = "ai.cntk"; #ifdef _WIN32 const std::string CNTK_ONNX_PRODUCER_VERSION = CNTK_VERSION; #else const std::string CNTK_ONNX_PRODUCER_VERSION = MACRO_TO_STRING(CNTK_VERSION); #endif namespace LotusIR { class Model; } namespace CNTK { class CNTKToONNX { public: static std::unique_ptr<LotusIR::Model> CreateModel(const FunctionPtr& src); }; }
#ifndef SAMPLES_BANK3_H_INCLUDE #define SAMPLES_BANK3_H_INCLUDE void play_sample2() __banked; #endif
/************************************************************ * Program to solve a finite difference * discretization of the screened Poisson equation: * (d2/dx2)u + (d2/dy2)u - alpha u = f * with zero Dirichlet boundary condition using the iterative * Jacobi method with overrelaxation. * * RHS (source) function * f(x,y) = -alpha*(1-x^2)(1-y^2)-2*[(1-x^2)+(1-y^2)] * * Analytical solution to the PDE * u(x,y) = (1-x^2)(1-y^2) * * Current Version: <NAME>, RWTH Aachen University * MPI C Version: <NAME>, RWTH Aachen University, 2006 * MPI Fortran Version: <NAME>, RWTH Aachen University, 1999 - 2005 * Modified: <NAME>, Kuck and Associates, Inc. (KAI), 1998 * Author: <NAME>, Kuck and Associates, Inc. (KAI), 1998 * * Input : n - grid dimension in x direction * m - grid dimension in y direction * alpha - constant (always greater than 0.0) * tol - error tolerance for the iterative solver * relax - Successice Overrelaxation parameter * mits - maximum iterations for the iterative solver * * On output * : u(n,m) - Dependent variable (solution) * : f(n,m,alpha) - Right hand side function * *************************************************************/ #include <stdio.h> #include <math.h> #include <stdlib.h> /************************************************************* * Performs one iteration of the Jacobi method and computes * the residual value. * * NOTE: u(0,*), u(maxXCount-1,*), u(*,0) and u(*,maxYCount-1) * are BOUNDARIES and therefore not part of the solution. *************************************************************/ double one_jacobi_iteration(double xStart, double yStart, int maxXCount, int maxYCount, double *src, double *dst, double deltaX, double deltaY, double alpha, double omega) { #define SRC(XX,YY) src[(YY)*maxXCount+(XX)] #define DST(XX,YY) dst[(YY)*maxXCount+(XX)] int x, y; double fX, fY; double error = 0.0; double updateVal; double f; // Coefficients double cx = 1.0/(deltaX*deltaX); double cy = 1.0/(deltaY*deltaY); double cc = -2.0*cx-2.0*cy-alpha; for (y = 1; y < (maxYCount-1); y++) { fY = yStart + (y-1)*deltaY; for (x = 1; x < (maxXCount-1); x++) { fX = xStart + (x-1)*deltaX; f = -alpha*(1.0-fX*fX)*(1.0-fY*fY)-2.0*(1.0-fX*fX)-2.0*(1.0-fY*fY); updateVal = ((SRC(x-1,y)+SRC(x+1,y))*cx + (SRC(x,y-1)+SRC(x,y+1))*cy + SRC(x,y)*cc - f)/cc; DST(x,y) = SRC(x,y) - omega*updateVal; error += updateVal*updateVal; } } return sqrt(error)/((maxXCount-2)*(maxYCount-2)); } /********************************************************** * Checks the error between numerical and exact solutions **********************************************************/ double checkSolution(double xStart, double yStart, int maxXCount, int maxYCount, double *u, double deltaX, double deltaY, double alpha) { #define U(XX,YY) u[(YY)*maxXCount+(XX)] int x, y; double fX, fY; double localError, error = 0.0; for (y = 1; y < (maxYCount-1); y++) { fY = yStart + (y-1)*deltaY; for (x = 1; x < (maxXCount-1); x++) { fX = xStart + (x-1)*deltaX; localError = U(x,y) - (1.0-fX*fX)*(1.0-fY*fY); error += localError*localError; } } return sqrt(error)/((maxXCount-2)*(maxYCount-2)); } int main(int argc, char **argv) { int n, m, mits; double alpha, tol, relax; double maxAcceptableError; double error; double *u, *u_old, *tmp; int allocCount; int iterationCount, maxIterationCount; printf("Input n,m - grid dimension in x,y direction:\n"); scanf("%d,%d", &n, &m); printf("Input alpha - Helmholtz constant:\n"); scanf("%lf", &alpha); printf("Input relax - successive over-relaxation parameter:\n"); scanf("%lf", &relax); printf("Input tol - error tolerance for the iterrative solver:\n"); scanf("%lf", &tol); printf("Input mits - maximum solver iterations:\n"); scanf("%d", &mits); printf("-> %d, %d, %g, %g, %g, %d\n", n, m, alpha, relax, tol, mits); allocCount = (n+2)*(m+2); // Those two calls also zero the boundary elements u = (double*)calloc(sizeof(double), allocCount); u_old = (double*)calloc(sizeof(double), allocCount); if (u == NULL || u_old == NULL) { fprintf(stderr, "Not enough memory for two %ix%i matrices\n", n+2, m+2); exit(1); } maxIterationCount = mits; maxAcceptableError = tol; // Solve in [-1, 1] x [-1, 1] double xLeft = -1.0, xRight = 1.0; double yBottom = -1.0, yUp = 1.0; double deltaX = (xRight-xLeft)/(n-1); double deltaY = (yUp-yBottom)/(m-1); iterationCount = 0; error = HUGE_VAL; /* Iterate as long as it takes to meet the convergence criterion */ while (iterationCount < maxIterationCount && error > maxAcceptableError) { printf("Iteration %i\n", iterationCount); error = one_jacobi_iteration(xLeft, yBottom, n+2, m+2, u_old, u, deltaX, deltaY, alpha, relax); printf("\tError %g\n", error); iterationCount++; // Swap the buffers tmp = u_old; u_old = u; u = tmp; } printf("Residual %g\n",error); // u_old holds the solution after the most recent buffers swap double absoluteError = checkSolution(xLeft, yBottom, n+2, m+2, u_old, deltaX, deltaY, alpha); printf("The error of the iterative solution is %g\n", absoluteError); return 0; }
<filename>source/pkgsrc/devel/tig/patches/patch-include_tig_tig.h $NetBSD: patch-include_tig_tig.h,v 1.1 2021/01/26 14:11:03 fcambus Exp $ Macro safety fix. --- include/tig/tig.h.orig 2020-04-08 16:17:38.000000000 +0000 +++ include/tig/tig.h @@ -119,7 +119,7 @@ #define MIN(x, y) ((x) < (y) ? (x) : (y)) #define MAX(x, y) ((x) > (y) ? (x) : (y)) -#define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0])) +#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) #define STRING_SIZE(x) (sizeof(x) - 1) #define SIZEOF_STR 1024 /* Default string size. */
/* ISC license. */ #ifndef MD5_INTERNAL_H #define MD5_INTERNAL_H #include <skalibs/uint32.h> #include <skalibs/md5.h> extern void md5_transform (uint32 * /* 4 uint32s */, uint32 const * /* 16 uint32s */) ; #endif
<filename>gcc-gcc-7_3_0-release/gcc/testsuite/c-c++-common/goacc/executeables-1.c /* { dg-do compile } */ void foo (void) { const int N = 32; float x[N], y[N]; int flag = 0; if (flag) #pragma acc update host (x[0:N]) /* { dg-error "may only be used in compound statements" } */ flag = 1; while (flag) #pragma acc update host (x[0:N]) /* { dg-error "may only be used in compound statements" } */ flag = 2; #pragma acc enter data create (x[0:N]) { if (flag) #pragma acc update host (x[0:N]) /* { dg-error "may only be used in compound statements" } */ flag = 1; } if (flag) while (flag) #pragma acc update host (x[0:N]) /* { dg-error "may only be used in compound statements" } */ flag = 2; if (flag) #pragma acc wait /* { dg-error "may only be used in compound statements" } */ flag = 1; while (flag) #pragma acc wait /* { dg-error "may only be used in compound statements" } */ flag = 2; #pragma acc enter data create (x[0:N]) { if (flag) #pragma acc wait /* { dg-error "may only be used in compound statements" } */ flag = 1; } if (flag) #pragma acc enter data create (x[0:N]) /* { dg-error "may only be used in compound statements" } */ flag = 1; while (flag) #pragma acc enter data create (x[0:N]) /* { dg-error "may only be used in compound statements" } */ flag = 2; #pragma acc enter data create (x[0:N]) { if (flag) #pragma acc enter data create (y[0:N]) /* { dg-error "may only be used in compound statements" } */ flag = 1; } if (flag) #pragma acc exit data delete (x[0:N]) /* { dg-error "may only be used in compound statements" } */ flag = 1; while (flag) #pragma acc exit data delete (x[0:N]) /* { dg-error "may only be used in compound statements" } */ flag = 2; #pragma acc enter data create (x[0:N]) { if (flag) #pragma acc exit data delete (x[0:N]) /* { dg-error "may only be used in compound statements" } */ flag = 1; } }
<reponame>aliakseis/grpcpp-pubsub-v2<gh_stars>0 #pragma once #include <string> #include <stdint.h> #define NOTIFICATION_X(macro) \ macro(uint64_t, index) \ macro(std::string, content) struct PlainNotification { #define DECL_MACRO(type, name) type name; NOTIFICATION_X(DECL_MACRO) #undef DECL_MACRO };
<filename>kernel/linux-4.13/arch/um/kernel/process.c /* * Copyright (C) 2015 <NAME> (<EMAIL>,kot-begem<EMAIL>}) * Copyright (C) 2015 <NAME> (<EMAIL>) * Copyright (C) 2000 - 2007 <NAME> (jdike@{addtoit,linux.intel}.com) * Copyright 2003 PathScale, Inc. * Licensed under the GPL */ #include <linux/stddef.h> #include <linux/err.h> #include <linux/hardirq.h> #include <linux/mm.h> #include <linux/module.h> #include <linux/personality.h> #include <linux/proc_fs.h> #include <linux/ptrace.h> #include <linux/random.h> #include <linux/slab.h> #include <linux/sched.h> #include <linux/sched/debug.h> #include <linux/sched/task.h> #include <linux/sched/task_stack.h> #include <linux/seq_file.h> #include <linux/tick.h> #include <linux/threads.h> #include <linux/tracehook.h> #include <asm/current.h> #include <asm/pgtable.h> #include <asm/mmu_context.h> #include <linux/uaccess.h> #include <as-layout.h> #include <kern_util.h> #include <os.h> #include <skas.h> #include <timer-internal.h> /* * This is a per-cpu array. A processor only modifies its entry and it only * cares about its entry, so it's OK if another processor is modifying its * entry. */ struct cpu_task cpu_tasks[NR_CPUS] = { [0 ... NR_CPUS - 1] = { -1, NULL } }; static inline int external_pid(void) { /* FIXME: Need to look up userspace_pid by cpu */ return userspace_pid[0]; } int pid_to_processor_id(int pid) { int i; for (i = 0; i < ncpus; i++) { if (cpu_tasks[i].pid == pid) return i; } return -1; } void free_stack(unsigned long stack, int order) { free_pages(stack, order); } unsigned long alloc_stack(int order, int atomic) { unsigned long page; gfp_t flags = GFP_KERNEL; if (atomic) flags = GFP_ATOMIC; page = __get_free_pages(flags, order); return page; } static inline void set_current(struct task_struct *task) { cpu_tasks[task_thread_info(task)->cpu] = ((struct cpu_task) { external_pid(), task }); } extern void arch_switch_to(struct task_struct *to); void *__switch_to(struct task_struct *from, struct task_struct *to) { to->thread.prev_sched = from; set_current(to); switch_threads(&from->thread.switch_buf, &to->thread.switch_buf); arch_switch_to(current); return current->thread.prev_sched; } void interrupt_end(void) { struct pt_regs *regs = &current->thread.regs; if (need_resched()) schedule(); if (test_thread_flag(TIF_SIGPENDING)) do_signal(regs); if (test_and_clear_thread_flag(TIF_NOTIFY_RESUME)) tracehook_notify_resume(regs); } int get_current_pid(void) { return task_pid_nr(current); } /* * This is called magically, by its address being stuffed in a jmp_buf * and being longjmp-d to. */ void new_thread_handler(void) { int (*fn)(void *), n; void *arg; if (current->thread.prev_sched != NULL) schedule_tail(current->thread.prev_sched); current->thread.prev_sched = NULL; fn = current->thread.request.u.thread.proc; arg = current->thread.request.u.thread.arg; /* * callback returns only if the kernel thread execs a process */ n = fn(arg); userspace(&current->thread.regs.regs); } /* Called magically, see new_thread_handler above */ void fork_handler(void) { force_flush_all(); schedule_tail(current->thread.prev_sched); /* * XXX: if interrupt_end() calls schedule, this call to * arch_switch_to isn't needed. We could want to apply this to * improve performance. -bb */ arch_switch_to(current); current->thread.prev_sched = NULL; userspace(&current->thread.regs.regs); } int copy_thread(unsigned long clone_flags, unsigned long sp, unsigned long arg, struct task_struct * p) { void (*handler)(void); int kthread = current->flags & PF_KTHREAD; int ret = 0; p->thread = (struct thread_struct) INIT_THREAD; if (!kthread) { memcpy(&p->thread.regs.regs, current_pt_regs(), sizeof(p->thread.regs.regs)); PT_REGS_SET_SYSCALL_RETURN(&p->thread.regs, 0); if (sp != 0) REGS_SP(p->thread.regs.regs.gp) = sp; handler = fork_handler; arch_copy_thread(&current->thread.arch, &p->thread.arch); } else { get_safe_registers(p->thread.regs.regs.gp, p->thread.regs.regs.fp); p->thread.request.u.thread.proc = (int (*)(void *))sp; p->thread.request.u.thread.arg = (void *)arg; handler = new_thread_handler; } new_thread(task_stack_page(p), &p->thread.switch_buf, handler); if (!kthread) { clear_flushed_tls(p); /* * Set a new TLS for the child thread? */ if (clone_flags & CLONE_SETTLS) ret = arch_copy_tls(p); } return ret; } void initial_thread_cb(void (*proc)(void *), void *arg) { int save_kmalloc_ok = kmalloc_ok; kmalloc_ok = 0; initial_thread_cb_skas(proc, arg); kmalloc_ok = save_kmalloc_ok; } void arch_cpu_idle(void) { cpu_tasks[current_thread_info()->cpu].pid = os_getpid(); os_idle_sleep(UM_NSEC_PER_SEC); local_irq_enable(); } int __cant_sleep(void) { return in_atomic() || irqs_disabled() || in_interrupt(); /* Is in_interrupt() really needed? */ } int user_context(unsigned long sp) { unsigned long stack; stack = sp & (PAGE_MASK << CONFIG_KERNEL_STACK_ORDER); return stack != (unsigned long) current_thread_info(); } extern exitcall_t __uml_exitcall_begin, __uml_exitcall_end; void do_uml_exitcalls(void) { exitcall_t *call; call = &__uml_exitcall_end; while (--call >= &__uml_exitcall_begin) (*call)(); } char *uml_strdup(const char *string) { return kstrdup(string, GFP_KERNEL); } EXPORT_SYMBOL(uml_strdup); int copy_to_user_proc(void __user *to, void *from, int size) { return copy_to_user(to, from, size); } int copy_from_user_proc(void *to, void __user *from, int size) { return copy_from_user(to, from, size); } int clear_user_proc(void __user *buf, int size) { return clear_user(buf, size); } int cpu(void) { return current_thread_info()->cpu; } static atomic_t using_sysemu = ATOMIC_INIT(0); int sysemu_supported; void set_using_sysemu(int value) { if (value > sysemu_supported) return; atomic_set(&using_sysemu, value); } int get_using_sysemu(void) { return atomic_read(&using_sysemu); } static int sysemu_proc_show(struct seq_file *m, void *v) { seq_printf(m, "%d\n", get_using_sysemu()); return 0; } static int sysemu_proc_open(struct inode *inode, struct file *file) { return single_open(file, sysemu_proc_show, NULL); } static ssize_t sysemu_proc_write(struct file *file, const char __user *buf, size_t count, loff_t *pos) { char tmp[2]; if (copy_from_user(tmp, buf, 1)) return -EFAULT; if (tmp[0] >= '0' && tmp[0] <= '2') set_using_sysemu(tmp[0] - '0'); /* We use the first char, but pretend to write everything */ return count; } static const struct file_operations sysemu_proc_fops = { .owner = THIS_MODULE, .open = sysemu_proc_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, .write = sysemu_proc_write, }; int __init make_proc_sysemu(void) { struct proc_dir_entry *ent; if (!sysemu_supported) return 0; ent = proc_create("sysemu", 0600, NULL, &sysemu_proc_fops); if (ent == NULL) { printk(KERN_WARNING "Failed to register /proc/sysemu\n"); return 0; } return 0; } late_initcall(make_proc_sysemu); int singlestepping(void * t) { struct task_struct *task = t ? t : current; if (!(task->ptrace & PT_DTRACE)) return 0; if (task->thread.singlestep_syscall) return 1; return 2; } /* * Only x86 and x86_64 have an arch_align_stack(). * All other arches have "#define arch_align_stack(x) (x)" * in their asm/exec.h * As this is included in UML from asm-um/system-generic.h, * we can use it to behave as the subarch does. */ #ifndef arch_align_stack unsigned long arch_align_stack(unsigned long sp) { if (!(current->personality & ADDR_NO_RANDOMIZE) && randomize_va_space) sp -= get_random_int() % 8192; return sp & ~0xf; } #endif unsigned long get_wchan(struct task_struct *p) { unsigned long stack_page, sp, ip; bool seen_sched = 0; if ((p == NULL) || (p == current) || (p->state == TASK_RUNNING)) return 0; stack_page = (unsigned long) task_stack_page(p); /* Bail if the process has no kernel stack for some reason */ if (stack_page == 0) return 0; sp = p->thread.switch_buf->JB_SP; /* * Bail if the stack pointer is below the bottom of the kernel * stack for some reason */ if (sp < stack_page) return 0; while (sp < stack_page + THREAD_SIZE) { ip = *((unsigned long *) sp); if (in_sched_functions(ip)) /* Ignore everything until we're above the scheduler */ seen_sched = 1; else if (kernel_text_address(ip) && seen_sched) return ip; sp += sizeof(unsigned long); } return 0; } int elf_core_copy_fpregs(struct task_struct *t, elf_fpregset_t *fpu) { int cpu = current_thread_info()->cpu; return save_i387_registers(userspace_pid[cpu], (unsigned long *) fpu); }
/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #ifndef QMITKUSCONTROLSDOPPLERWIDGET_H #define QMITKUSCONTROLSDOPPLERWIDGET_H #include <QWidget> #include "MitkUSUIExports.h" #include "mitkUSControlInterfaceDoppler.h" namespace Ui { class QmitkUSControlsDopplerWidget; } /** * \brief Widget for b mode controls of ultrasound devices. * This class handles the mitk::USControlInterfaceDoppler of mitk::USDevice * objects. */ class MITKUSUI_EXPORT QmitkUSControlsDopplerWidget : public QWidget { Q_OBJECT private slots: public: /** * A pointer to a concrete mitk::USControlInterfaceDoppler is needed to * construct a QmitkUSControlsBModeWidget. Widget is ready after * constructing; slots are connected to gui controls. * * If a null pointer is given for 'controlInterface' all gui control elements * will be disabled. */ explicit QmitkUSControlsDopplerWidget(mitk::USControlInterfaceDoppler::Pointer controlInterface, QWidget *parent = nullptr); ~QmitkUSControlsDopplerWidget() override; private: Ui::QmitkUSControlsDopplerWidget* ui; mitk::USControlInterfaceDoppler::Pointer m_ControlInterface; }; #endif // QMITKUSCONTROLSDOPPLERWIDGET_H
<reponame>rj011/Hacktoberfest2021-4 //For multiplication of two matrices. #include<stdio.h> #include<stdlib.h> int main() { int a[10][10],b[10][10],c[10][10], m,n,i,j,sum=0; printf("enter values for m and n:\t"); scanf("%d\t%d",&m,&n); printf("Enter first matrix elements\n"); for(i=0;i<m;i++) { for(j=0;j<n;j++) { scanf("%d" ,&a[i][j]); } } printf("Enter second matrix elements\n"); for(i=0;i<m;i++) { for(j=0;j<n;j++) { scanf("%d" ,&b[i][j]); } } for(i=0;i<m;i++) { for(j=0;j<n;j++) { c[i][j]=a[i][j]*b[i][j]; printf("sum of diagonal elements is:%d\t",sum); } } return 0; }
<filename>CreditChina/CreditChina/controls/WLTableViewCell/WLTFourItemsWithTitleCell.h // // WLTFourItemsWithTitleCell.h // CreditChina // // Created by 王磊 on 2019/2/2. // Copyright © 2019 wanglei. All rights reserved. // #import "WLBaseTableViewCell.h" NS_ASSUME_NONNULL_BEGIN @interface WLTFourItemsWithTitleCell : WLBaseTableViewCell @end NS_ASSUME_NONNULL_END
#ifndef OPTS_H #define OPTS_H // ------------- Struct for user-controllable FINUFFT options ----------------- // Deliberately a plain C struct, without special types. // See ../docs/devnotes.rst about what else to sync when you change this. typedef struct nufft_opts { // defaults see finufft.cpp:finufft_default_opts() // sphinx tag (don't remove): @opts_start // FINUFFT options: // data handling opts... int modeord; // (type 1,2 only): 0 CMCL-style increasing mode order // 1 FFT-style mode order int chkbnds; // 0 don't check NU pts in [-3pi,3pi), 1 do (<few % slower) // diagnostic opts... int debug; // 0 silent, 1 some timing/debug, or 2 more int spread_debug; // spreader: 0 silent, 1 some timing/debug, or 2 tonnes int showwarn; // 0 don't print warnings to stderr, 1 do // algorithm performance opts... int nthreads; // number of threads to use, or 0 uses all available int fftw; // plan flags to FFTW (FFTW_ESTIMATE=64, FFTW_MEASURE=0,...) int spread_sort; // spreader: 0 don't sort, 1 do, or 2 heuristic choice int spread_kerevalmeth; // spreader: 0 exp(sqrt()), 1 Horner piecewise poly (faster) int spread_kerpad; // (exp(sqrt()) only): 0 don't pad kernel to 4n, 1 do double upsampfac; // upsampling ratio sigma: 2.0 std, 1.25 small FFT, 0.0 auto int spread_thread; // (vectorized ntr>1 only): 0 auto, 1 seq multithreaded, // 2 parallel single-thread spread int maxbatchsize; // (vectorized ntr>1 only): max transform batch, 0 auto int spread_nthr_atomic; // if >=0, threads above which spreader OMP critical goes atomic int spread_max_sp_size; // if >0, overrides spreader (dir=1) max subproblem size // sphinx tag (don't remove): @opts_end } nufft_opts; // Those of the above of the form spread_* indicate pass through to spread_opts #endif // OPTS_H
#pragma once #include "Enemy.h" class ThrowingNinja : public Enemy { public: ThrowingNinja(); ~ThrowingNinja(); };
// Copyright 2022 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_HCI_FAKE_SCO_CONNECTION_H_ #define SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_HCI_FAKE_SCO_CONNECTION_H_ #include "src/connectivity/bluetooth/core/bt-host/hci/sco_connection.h" namespace bt::hci::testing { class FakeScoConnection final : public ScoConnection { public: FakeScoConnection(hci_spec::ConnectionHandle handle, const DeviceAddress& local_address, const DeviceAddress& peer_address, const fxl::WeakPtr<Transport>& hci); void TriggerPeerDisconnectCallback() { peer_disconnect_callback()(this, hci_spec::StatusCode::kRemoteUserTerminatedConnection); } // ScoConnection overrides: void Disconnect(hci_spec::StatusCode reason) override {} private: DISALLOW_COPY_AND_ASSIGN_ALLOW_MOVE(FakeScoConnection); }; } // namespace bt::hci::testing #endif // SRC_CONNECTIVITY_BLUETOOTH_CORE_BT_HOST_HCI_FAKE_SCO_CONNECTION_H_
#include <stdio.h> #include <time.h> enum {N = 1001}; int primes[N], cnt; int sieved[N]; void get_primes(int n); int main(int argc, char const *argv[]) { clock_t timer = clock(); get_primes(1000); int i; for (i = 0; i < cnt; ++ i) { printf("%d\t",primes[i]); } printf("\nTime:%dms\n",clock() - timer); system("pause"); return 0; } void get_primes(int n) { int i,j; for (i = 2; i <= n; i ++ ) { if (!sieved[i]) primes[cnt ++ ] = i; for (j = 0; primes[j] <= n / i; j ++ ) { sieved[primes[j] * i] = 1; if (i % primes[j] == 0) break; } } }
#ifndef SEQUENCE_INDEX_DATABASE_H_ #define SEQUENCE_INDEX_DATABASE_H_ #include <fstream> #include <iostream> #include <vector> #include <assert.h> #include <stdlib.h> #include <sstream> #include <algorithm> #include "Types.h" #include "DNASequence.h" #include "utils/StringUtils.h" #include <map> using namespace std; #define SEQUENCE_INDEX_DATABASE_MAGIC 1233211233 template<typename TSeq> class SequenceIndexDatabase { public: vector<DNALength> growableSeqStartPos; vector<string> growableName; DNALength *seqStartPos; bool deleteSeqStartPos; char **names; bool deleteNames; int *nameLengths; bool deleteNameLengths; int nSeqPos; bool deleteStructures; map<string, DNALength> startPos; map<string, DNALength> endPos; // // This is stored after reading in the sequence. // vector<string> md5; SequenceIndexDatabase(int final=0) { nSeqPos = 0; if (!final) { growableSeqStartPos.push_back(0); } names = NULL; deleteNames = false; nameLengths = NULL; deleteNameLengths = false; seqStartPos = NULL; deleteSeqStartPos = false; deleteStructures = false; } void BuildNameMaps() { int i; for (i = 0; i < nSeqPos-1; i++) { startPos[names[i]] = seqStartPos[i]; endPos[names[i]] = seqStartPos[i+1]-1; } } void GetBoundaries(string name, DNALength &queryStartPos, DNALength &queryEndPos) { if (startPos.find(name) != startPos.end()) { queryStartPos = startPos[name]; queryEndPos = endPos[name]; } else { queryStartPos = 0; queryEndPos = 0; } } DNALength GetLengthOfSeq(int seqIndex) { assert(seqIndex < nSeqPos-1); return seqStartPos[seqIndex+1] - seqStartPos[seqIndex] - 1; } // Return index of a reference sequence with name "seqName". int GetIndexOfSeqName(string seqName) { for(int i = 0; i < nSeqPos - 1; i++) { if (seqName == string(names[i])) { return i; } } return -1; } void GetName(int seqIndex, string &name) { assert(seqIndex < nSeqPos-1); name = names[seqIndex]; } void MakeSAMSQString(string &sqString) { stringstream st; int i; for (i = 0; i < nSeqPos-1; i++) { st << "@SQ\tSN:" << names[i] << "\tLN:" << GetLengthOfSeq(i); if (md5.size() == nSeqPos-1) { st << "\tM5:" << md5[i]; } st << endl; } sqString = st.str(); } DNALength ChromosomePositionToGenome(int chrom, DNALength chromPos) { assert(chrom < nSeqPos); return seqStartPos[chrom] + chromPos; } int SearchForIndex(DNALength pos) { // The default behavior for the case // that there is just one genome. if (nSeqPos == 1) { return 0; } DNALength* seqPosIt = upper_bound(seqStartPos+1, seqStartPos + nSeqPos, pos); return seqPosIt - seqStartPos - 1; } string GetSpaceDelimitedName(unsigned int index) { int pos; assert(index < nSeqPos); string name; for (pos = 0; pos < nameLengths[index]; pos++) { if (names[index][pos] == ' ' or names[index][pos] == '\t' or names[index][pos] == '\0') { break; } } name.assign(names[index], pos); return name; } int SearchForStartBoundary(DNALength pos) { int index = SearchForIndex(pos); if (index != -1) { return seqStartPos[index]; } else { return -1; } } int SearchForEndBoundary(DNALength pos) { int index = SearchForIndex(pos); if (index != -1) { return seqStartPos[index + 1]; } else { return -1; } } DNALength SearchForStartAndEnd(DNALength pos, DNALength &start, DNALength &end) { int index = SearchForIndex(pos); if (index != -1) { start = seqStartPos[index]; end = seqStartPos[index+1]; return 1; } else { start = end = -1; return 0; } } void WriteDatabase(ofstream &out) { int mn = SEQUENCE_INDEX_DATABASE_MAGIC; out.write((char*) &mn, sizeof(int)); out.write((char*) &nSeqPos, sizeof(int)); out.write((char*) seqStartPos, sizeof(DNALength) * nSeqPos); int nSeq = nSeqPos - 1; out.write((char*) nameLengths, sizeof(int) * nSeq); int i; // // The number of sequences is 1 less than the number of positions // since the positions include 0 as a boundary. // char nullchar = '\0'; for (i = 0; i < nSeq; i++) { // // nameLengths has space for the null char, so the length of the // name = nameLengths[i]-1. Write a nullchar to disk so that it // may be read in later with no work. // out.write((char*) names[i], sizeof(char) * (nameLengths[i]-1)); out.write((char*) &nullchar, sizeof(char)); } } void ReadDatabase(ifstream &in) { int mn; // Make sure this is a read database, since the binary input // is not syntax checked. in.read((char*) &mn, sizeof(int)); if (mn != SEQUENCE_INDEX_DATABASE_MAGIC) { cout << "ERROR: Sequence index database is corrupt!" << endl; exit(1); } // // Read in the boundaries of each sequence. // deleteStructures = true; in.read((char*) &nSeqPos, sizeof(int)); seqStartPos = new DNALength[nSeqPos]; deleteSeqStartPos = true; in.read((char*) seqStartPos, sizeof(DNALength) * nSeqPos); int nSeq = nSeqPos - 1; // Get the lengths of the strings to read. nameLengths = new int[nSeq]; deleteNameLengths = true; in.read((char*)nameLengths, sizeof(int) * nSeq); // Get the titles of the sequences. names = new char*[nSeq]; deleteNames = true; char *namePtr; int i; for (i = 0; i < nSeq; i++) { namePtr = new char[nameLengths[i]]; if (nameLengths[i] > 0) { in.read(namePtr, nameLengths[i]); } namePtr[nameLengths[i]-1] = '\0'; names[i] = namePtr; } } void SequenceTitleLinesToNames() { int seqIndex; vector<string> tmpNameArray; for (seqIndex = 0; seqIndex < nSeqPos-1; seqIndex++) { string tmpName; AssignUntilFirstSpace(names[seqIndex], nameLengths[seqIndex], tmpName); delete[] names[seqIndex]; names[seqIndex] = new char[tmpName.size()+1]; strcpy(names[seqIndex], tmpName.c_str()); names[seqIndex][tmpName.size()] = '\0'; nameLengths[seqIndex] = tmpName.size(); tmpNameArray.push_back(tmpName); } // Make sure that reference names are unique. sort(tmpNameArray.begin(), tmpNameArray.end()); for(int j = 0; j < tmpNameArray.size() - 1; j++) { if (tmpNameArray[j] == tmpNameArray[j+1]) { cout << "Error, reference with name \"" << tmpNameArray[j] << "\" in the reference genome is not unique"<<endl; exit(1); } } } VectorIndex AddSequence(TSeq &sequence) { int endPos = growableSeqStartPos[growableSeqStartPos.size() - 1]; int growableSize = growableSeqStartPos.size(); growableSeqStartPos.push_back(endPos + sequence.length + 1); string fastaTitle; sequence.GetFASTATitle(fastaTitle); growableName.push_back(fastaTitle); return growableName.size(); } void Finalize() { deleteStructures = true; seqStartPos = &growableSeqStartPos[0]; nSeqPos = growableSeqStartPos.size(); int nSeq = nSeqPos - 1; names = new char*[nSeq]; deleteNames = true; unsigned int i; nameLengths = new int[nSeq]; deleteNameLengths = true; for (i = 0; i < nSeq; i++) { names[i] = new char[growableName[i].size() + 1]; memcpy((char*) names[i], (char*) growableName[i].c_str(), growableName[i].size()); names[i][growableName[i].size()] = '\0'; nameLengths[i] = growableName[i].size() + 1; } } void FreeDatabase() { int i; if (deleteStructures == false) { return; } if (names != NULL and deleteNames) { int nSeq = nSeqPos - 1; for (i = 0; i < nSeq; i++ ){ delete[] names[i]; } delete[] names; } if (nameLengths != NULL) { delete[] nameLengths; } if (seqStartPos != NULL and deleteSeqStartPos) { delete[] seqStartPos; } } }; template< typename TSeq > class SeqBoundaryFtr { public: SequenceIndexDatabase<TSeq> *seqDB; SeqBoundaryFtr(SequenceIndexDatabase<TSeq> *_seqDB) { seqDB = _seqDB; } int GetIndex(DNALength pos) { return seqDB->SearchForIndex(pos); } int GetStartPos(int index) { assert(index < seqDB->nSeqPos); return seqDB->seqStartPos[index]; } void GetBoundaries(const char * name, DNALength &queryStart, DNALength &queryEnd) { seqDB->GetBoundaries(name, queryStart, queryEnd); } DNALength operator()(DNALength pos) { return seqDB->SearchForStartBoundary(pos); } // // This is misuse of a functor, but easier interface coding for now. DNALength Length(DNALength pos) { DNALength start, end; seqDB->SearchForStartAndEnd(pos, start, end); return end - start - 1; } }; #endif
#include <stdio.h> #include <stdlib.h> void modify(int *,int); int main() { int n[10],i; for (i=0;i<10;i++) { printf("Enter the %d no.: ",i+1); scanf("%d",&n[i]); } printf("\nThe numbers that you have entered are:\n\t"); for (i=0;i<10;i++) printf("%d ",n[i]); modify(n,10); printf("\nThe numbers that you have entered are multiplied by 3,new numbers are :\n\t"); for (i=0;i<10;i++) printf("%d ",n[i]); return 0; } void modify(int *num,int n) { int i; for (i=0;i<n;i++) num[i]=num[i]*3; }
#ifndef _H_EXTRACTTHREAD_ #define _H_EXTRACTTHREAD_ //#include <Qt/qthread.h> #include <QThread> #include "serviceDll.h" #include "AlgorithmInterface/AI_Maskman_Detect.h" class extractThread :public QThread{ Q_OBJECT public: void init(AI_Maskman_Detect* pAlInterface); bool getStatus() const; void setStatus(bool status); int getPercent() const; bool getImg(cv::Mat*&); std::string getEventInfo(); extractThread(QObject *parent); ~extractThread(); signals: void sendSliderVal(int); void threadStop(); void threadEnd(); void threadFail(); protected: void run(); private: ServiceDLL* serviceDll; AI_Maskman_Detect* pAI_md; }; #endif
#ifndef __MWOIBN__ROBOT_CLASS__ROBOT_POINTS__CENTER_OF_PRESSURE_H #define __MWOIBN__ROBOT_CLASS__ROBOT_POINTS__CENTER_OF_PRESSURE_H #include "mwoibn/robot_class/contacts_2.h" #include "mwoibn/robot_points/state.h" #include "mwoibn/robot_points/center_of_mass.h" #include "mwoibn/point_handling/raw_positions_handler.h" namespace mwoibn { namespace robot_points { class CenterOfPressure: public State { public: CenterOfPressure(RigidBodyDynamics::Model& model, const mwoibn::robot_class::State& state, mwoibn::robot_class::Contacts& contacts, mwoibn::robot_points::CenterOfMass& com); virtual ~CenterOfPressure() {} using Point::operator=; virtual void compute(); void computeJacobian() { _com.computeJacobian(); _jacobian = _com.getJacobian(); } virtual void update(bool jacobian = true); void init(); protected: mwoibn::robot_class::Contacts& _contacts; mwoibn::VectorN _forces; std::vector<mwoibn::Matrix3> _null_space; mwoibn::Vector3 _temp; point_handling::RawPositionsHandler _points; double _sum_force; mwoibn::robot_points::CenterOfMass& _com; }; } // namespace package } // namespace library #endif // CENTER_OF_MASS_H
<filename>DLLDiag/ResLineal/DVectorObj.h //****************************************************************** // // DVectorObj.h // // Define la clase vector de punteros a objeto // // fecha: 11/03/99 // // Modifications-----> // Date By Commets // //****************************************************************** #ifndef DVECTOROBJ_H #define DVECTOROBJ_H #include "Utilidades.h" class Ligadura; class Masa_Primaria; class Fuerza; class Vector_3D; class Vector_3D_Secundario; class Elemento; class Junta; template<class TYPE> class DVectorObj : public CObArray { int m_desplazamiento; int m_orden; public: DVectorObj(int orden = 1, int desplazamiento = 1); void SetSize (int orden); int GetSize (void) const; void SetDesplazamiento (int desplazamiento); int GetDesplazamiento (void) const; void SetAtributos (int orden, int desplazamiento); // Accessing elements TYPE GetAt(int indice) const { return (TYPE)CObArray::GetAt(indice - m_desplazamiento); } TYPE& ElementAt(int indice) { return (TYPE&)CObArray::ElementAt(indice - m_desplazamiento); } void SetAt(int indice, TYPE ptr) { CObArray::SetAt(indice - m_desplazamiento,(CObject*)ptr); } // Potentially growing the array void SetAtGrow(int indice, TYPE newElement) { CObArray::SetAtGrow(indice - m_desplazamiento,(CObject*) newElement); } int Add(TYPE newElement) { return CObArray::Add((CObject*)newElement); } int Append(const DVectorObj<TYPE>& src) { return (CObArray::Append(src)) + m_desplazamiento; } void Copy(const DVectorObj<TYPE>& src) { m_orden = src.m_orden; m_desplazamiento = src.m_desplazamiento; CObArray::Copy(src); } // Operations that move elements around void InsertAt(int indice, TYPE newElement, int nCount = 1) { CObArray::InsertAt(indice - m_desplazamiento,(CObject*) newElement, nCount); } void InsertAt(int nStartIndex, DVectorObj<TYPE>* pNewArray) { CObArray::InsertAt(nStartIndex - m_desplazamiento, pNewArray); } // overloaded operator helpers TYPE operator[](int indice) const { return (TYPE)CObArray::operator[](indice - m_desplazamiento); } TYPE& operator[](int indice) { return (TYPE&)CObArray::operator[](indice - m_desplazamiento); } void Serialize(CArchive &ar); }; #endif DVECTOROBJ_H
<reponame>NecroSig/DEVA2021EC<gh_stars>0 #ifndef HS_AFFICHAGE #define HS_AFFICHAGE void affichePionsJoueur(int*** tab); void affichePlateau(int **tab, int tj); void afficheInfosJeu(struct s_partie* p); #endif
<gh_stars>0 /* * This file is part of the GROMACS molecular simulation package. * * Copyright 2010- The GROMACS Authors * and the project initiators <NAME>, <NAME> and <NAME>. * Consult the AUTHORS/COPYING files and https://www.gromacs.org for details. * * GROMACS 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. * * GROMACS is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GROMACS; if not, see * https://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at https://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out https://www.gromacs.org. */ /*! \internal \file * \brief * Declares gmx::SelectionOptionStorage. * * \author <NAME> <<EMAIL>> * \ingroup module_selection */ #ifndef GMX_SELECTION_SELECTIONOPTIONSTORAGE_H #define GMX_SELECTION_SELECTIONOPTIONSTORAGE_H #include <string> #include "gromacs/options/optionstoragetemplate.h" #include "gromacs/selection/selection.h" #include "gromacs/selection/selectionoption.h" #include "selectionenums.h" namespace gmx { class SelectionOption; class SelectionOptionManager; /*! \internal \brief * Converts, validates, and stores selection values. * * \see SelectionOptionManager * * \ingroup module_selection */ class SelectionOptionStorage : public OptionStorageTemplate<Selection> { public: /*! \brief * Initializes the storage from option settings. * * \param[in] settings Storage settings. * \param manager Manager for this object. */ SelectionOptionStorage(const SelectionOption& settings, SelectionOptionManager* manager); OptionInfo& optionInfo() override { return info_; } std::string typeString() const override { return "selection"; } std::string formatSingleValue(const Selection& value) const override; std::vector<Any> normalizeValues(const std::vector<Any>& values) const override; /*! \brief * Adds selections to the storage. * * \param[in] selections List of selections to add. * \param[in] bFullValue If true, the provided selections are the full * value of the option, and additional checks are performed. * \throws std::bad_alloc if out of memory. * \throws InvalidInputError if * - There is an incorrect number of selections in \p selections. * - Any selection in \p selections is not allowed for this * option. * * This function is used to add selections from SelectionOptionManager. * It is called with \p bFullValue set to false from * SelectionOptionManager::convertOptionValue(), and \p bFullValue set * to true when parsing requested selections. */ void addSelections(const SelectionList& selections, bool bFullValue); // Required to access the number of values in selection requests. // See SelectionCollection::Impl. using MyBase::maxValueCount; //! Whether the option allows only atom-valued selections. bool allowsOnlyAtoms() const { return selectionFlags_.test(efSelection_OnlyAtoms); } //! \copydoc SelectionOptionInfo::setValueCount() void setAllowedValueCount(int count); /*! \brief * Alters flags for the selections created by this option. * * \param[in] flag Flag to change. * \param[in] bSet Whether to set or clear the flag. * \throws std::bad_alloc if out of memory. * \throws InvalidInputError if selections have already been * provided and conflict with the given flags. * * If selections have already been provided, it is checked that they * match the limitations enforced by the flags. Pending requests are * also affected. * * Strong exception safety guarantee. */ void setSelectionFlag(SelectionFlag flag, bool bSet); private: void convertValue(const Any& value) override; void processSetValues(ValueList* values) override; void processAll() override; SelectionOptionInfo info_; SelectionOptionManager& manager_; std::string defaultText_; SelectionFlags selectionFlags_; }; } // namespace gmx #endif
<gh_stars>0 #include "ofMain.h" #include "phonon.h" #include "ofxAudioFile.h" class ofxSteamAudioSoundSource { public: ofVec3f location; string soundName; IPLhandle* effect; int sampleStart; void setGain(float gain); float getGain(); void load(const std::string filepath, string sourceName); void destroy(); void play(); float getSample(int position); protected: ofxAudioFile _audioFile; float _gain = 1.0; };
/** * @file ZFIOBuffer.h * @brief util to hold and connect #ZFInput and #ZFOutput */ #ifndef _ZFI_ZFIOBuffer_h_ #define _ZFI_ZFIOBuffer_h_ #include "ZFObject.h" ZF_NAMESPACE_GLOBAL_BEGIN /** * @brief util to hold and connect #ZFInput and #ZFOutput * * usage: * @code * void outputFunc(ZF_IN const ZFOutput &callback) {...} * void inputFunc(ZF_IN const ZFInput &callback) {...} * * zfblockedAlloc(ZFIOBufferByXxx, io); * outputFunc(io->output()); // output data to io's internal buffer * inputFunc(io->input()); // input data from io's internal buffer * @endcode * * once created, the #ZFIOBuffer would be retained by the * returned #ZFInput/#ZFOutput by #ZFCallbackTagKeyword_ZFIOBuffer, * it's ensured safe to release the owner #ZFIOBuffer's reference */ zfabstract ZF_ENV_EXPORT ZFIOBuffer : zfextends ZFObject { ZFOBJECT_DECLARE_ABSTRACT(ZFIOBuffer, ZFObject) public: /** * @brief get input callback */ ZFMETHOD_DECLARE_0(ZFInput, input) /** * @brief get output callback */ ZFMETHOD_DECLARE_0(ZFOutput, output) /** * @brief remove all of contents, * so next output would write from beginning * and next input would read from beginning */ ZFMETHOD_DECLARE_0(void, removeAll) protected: /** @brief see #input */ virtual ZFInput implInput(void) zfpurevirtual; /** @brief see #output */ virtual ZFOutput implOutput(void) zfpurevirtual; /** @brief see #removeAll */ virtual void implRemoveAll(void) zfpurevirtual; }; /** * @brief store #ZFIOBuffer as #ZFCallback::callbackTag * for #ZFIOBuffer::input and #ZFIOBuffer::output */ #define ZFCallbackTagKeyword_ZFIOBuffer "ZFCallbackTagKeyword_ZFIOBuffer" ZF_NAMESPACE_GLOBAL_END #endif // #ifndef _ZFI_ZFIOBuffer_h_
// // FolderFactory.h // demo // // Created by Phil on 2019/8/2. // Copyright © 2019 Phil. All rights reserved. // #import <Foundation/Foundation.h> #import "Folder.h" NS_ASSUME_NONNULL_BEGIN @interface FolderFactory : NSObject + (Folder *)createFolderWithDetph:(int)detph; @end NS_ASSUME_NONNULL_END
<reponame>b19e93n/PLC-Pyramid /********Software Analysis - FY2013*************/ /* * File Name: invalid_extern.c * Defect Classification * --------------------- * Defect Type: Misc defects * Defect Sub-type: Bad extern type for global variable * Description: Defect Free Code to identify false positives during invalid extern declaration */ /* * Types of defects: external variable type mistake * Complexity: external variable type error * Note: the PolySpace compilation error handling * (variable has incompatible type with its ... The following) */ /* #if ! (defined(CHECKER_POLYSPACE) || defined(CHECKER_VARVEL)) */ #include "HeaderFile.h" extern int invalid_extern_001_glb_buf[5]; /*Tool should not detect this line as error*/ /*No ERROR:Bad extern type for global variable*/ extern float invalid_extern_001_glb_float[5] ; /*Tool should not detect this line as error*/ /*No ERROR:Bad extern type for global variable*/ extern float invalid_extern_001_glb_var3[5] ; /*Tool should not detect this line as error*/ /*No ERROR:Bad extern type for global variable*/ extern int invalid_extern_001_glb_var4 ; /*Tool should not detect this line as error*/ /*No ERROR:Bad extern type for global variable*/ extern float invalid_extern_001_glb_var5 ; /*Tool should not detect this line as error*/ /*No ERROR:Bad extern type for global variable*/ typedef struct { int csr; int data; }invalid_extern_001_glb_006_s_001; extern invalid_extern_001_glb_006_s_001 *invalid_extern_001_glb_006_str; void invalid_extern_001 () { invalid_extern_001_glb_buf[3] = 1; } void invalid_extern_002 () { invalid_extern_001_glb_float[3] = 1.0; } void invalid_extern_003 () { invalid_extern_001_glb_var3[3] = 1.0; } void invalid_extern_004 () { invalid_extern_001_glb_var4 = 1; } void invalid_extern_005 () { invalid_extern_001_glb_var5 = 1.0; } void invalid_extern_006 () { invalid_extern_001_glb_006_str = (invalid_extern_001_glb_006_s_001 *) malloc(1*sizeof(invalid_extern_001_glb_006_s_001)); invalid_extern_001_glb_006_str->csr = 10; } /* #endif ! (defined(CHECKER_POLYSPACE) || defined(CHECKER_VARVEL)) */ /* * Types of defects: external variable type mistake * Complexity: volatile */ extern volatile int vflag; void invalid_extern_main () { /*#if ! (defined(CHECKER_POLYSPACE) || defined(CHECKER_VARVEL))*/ if (vflag == 1 || vflag ==888) { invalid_extern_001(); } if (vflag == 2 || vflag ==888) { invalid_extern_002(); } if (vflag == 3 || vflag ==888) { invalid_extern_003(); } if (vflag == 4 || vflag ==888) { invalid_extern_004(); } if (vflag == 5 || vflag ==888) { invalid_extern_005(); } if (vflag == 6 || vflag ==888) { invalid_extern_006(); } /*#endif */ /* ! (defined(CHECKER_POLYSPACE) || defined(CHECKER_VARVEL)) */ }
// // Generated by classdumpios 1.0.1 (64 bit) (iOS port by DreamDevLost)(Debug version compiled Sep 26 2020 13:48:20). // // Copyright (C) 1997-2019 <NAME>. // #import <objc/NSObject.h> @class NSArray, NSMutableSet; __attribute__((visibility("hidden"))) @interface SHLLibraryChangeset : NSObject { NSMutableSet *_trackSetToAdd; // 8 = 0x8 NSMutableSet *_trackSetToDelete; // 16 = 0x10 NSMutableSet *_groupSetToAdd; // 24 = 0x18 NSMutableSet *_groupSetToDelete; // 32 = 0x20 } - (void).cxx_destruct; // IMP=0x0000000100017984 @property(retain, nonatomic) NSMutableSet *groupSetToDelete; // @synthesize groupSetToDelete=_groupSetToDelete; @property(retain, nonatomic) NSMutableSet *groupSetToAdd; // @synthesize groupSetToAdd=_groupSetToAdd; @property(retain, nonatomic) NSMutableSet *trackSetToDelete; // @synthesize trackSetToDelete=_trackSetToDelete; @property(retain, nonatomic) NSMutableSet *trackSetToAdd; // @synthesize trackSetToAdd=_trackSetToAdd; - (id)description; // IMP=0x00000001000177f8 - (void)mergeChangeset:(id)arg1; // IMP=0x00000001000176d8 - (void)deleteGroups:(id)arg1; // IMP=0x0000000100017578 - (void)addGroups:(id)arg1; // IMP=0x00000001000172b8 - (void)deleteTracks:(id)arg1; // IMP=0x0000000100017158 - (void)addTracks:(id)arg1; // IMP=0x0000000100016ff8 @property(readonly, nonatomic) NSArray *groupIDsToDelete; @property(readonly, nonatomic) NSArray *trackIDsToDelete; @property(readonly, nonatomic) NSArray *groupsToDelete; @property(readonly, nonatomic) NSArray *groupsToAdd; @property(readonly, nonatomic) NSArray *tracksToDelete; @property(readonly, nonatomic) NSArray *tracksToAdd; - (id)init; // IMP=0x0000000100016bec @end
<reponame>tactcomplabs/xbgas-bootstrap /* * _XBGAS-BOOTSTRAP_C_ * * Copyright (C) 2017-2018 Tactical Computing Laboratories, LLC * All Rights Reserved * <EMAIL> * * This file is a part of the XBGAS-RUNTIME package. For license * information, see the LICENSE file in the top level directory * of the distribution. * */ __attribute__ ((constructor(0))) __attribute((__section__(".init.text"))) static void __xbgas_ctor(); __attribute__ ((destructor(0))) __attribute((__section__(".exit.text"))) static void __xbgas_dtor(); #ifdef XBGAS_RV32 void __rv32_bootstrap(){ /* rv32 bootstrap code goes here */ } void __rv32_dtor(){ /* rv32 destructor code goes here */ } #else void __rv64_bootstrap(){ /* rv64 bootstrap code goes here */ } void __rv64_dtor(){ /* rv64 destructor code goes here */ } #endif static void __xbgas_ctor(){ #ifdef XBGAS_RV32 /* execute rv32 bootstrap code */ __rv32_bootstrap(); #else /* execute rv64 bootstrap code */ __rv64_bootstrap(); #endif } static void __xbgas_dtor(){ #ifdef XBGAS_RV32 /* execute rv32 destructor code */ __rv32_dtor(); #else /* execute rv64 destructor code */ __rv64_dtor(); #endif } /* EOF */
<gh_stars>1-10 #ifndef CHANNELRESULT_H #define CHANNELRESULT_H #include <QSharedData> #include <QList> #include <QString> #include <QDate> #include "transportableobject.h" #include "contactlogin.h" namespace MoodBox { class ChannelResultData : public QSharedData { public: ChannelResultData(); ChannelResultData(qint32 channelId, qint32 authorId, QString authorLogin, QDate creationDate, QString title, QString shortDescription, QString fullDescription, qint32 userCount, QString logoUrl, QList<ContactLogin> moderators); virtual ~ChannelResultData(); qint32 channelId; qint32 authorId; QString authorLogin; QDate creationDate; QString title; QString shortDescription; QString fullDescription; qint32 userCount; QString logoUrl; QList<ContactLogin> moderators; }; class ChannelResult : public TransportableObject { public: ChannelResult(); ChannelResult(qint32 channelId, qint32 authorId, QString authorLogin, QDate creationDate, QString title, QString shortDescription, QString fullDescription, qint32 userCount, QString logoUrl, QList<ContactLogin> moderators); virtual ~ChannelResult(); protected: ChannelResult(ChannelResultData* dataRef) { this->d = dataRef; } public: // never use ___new_ in your code!!! static ChannelResult* ___new_() { return new ChannelResult(new ChannelResultData()); } static ChannelResult empty() { return ChannelResult(new ChannelResultData()); } virtual bool isNull() const { return !d; } qint32 getChannelId() const; void setChannelId(qint32 value); qint32 getAuthorId() const; void setAuthorId(qint32 value); QString getAuthorLogin() const; void setAuthorLogin(QString value); QDate getCreationDate() const; void setCreationDate(QDate value); QString getTitle() const; void setTitle(QString value); QString getShortDescription() const; void setShortDescription(QString value); QString getFullDescription() const; void setFullDescription(QString value); qint32 getUserCount() const; void setUserCount(qint32 value); QString getLogoUrl() const; void setLogoUrl(QString value); QList<ContactLogin> getModerators() const; void setModerators(QList<ContactLogin> value); static qint32 getRepresentedTypeId(); virtual qint32 getTypeId() const; virtual void writeProperties(PropertyWriter *writer); virtual PropertyReadResult readProperty(qint32 propertyId, qint32 typeId, PropertyReader *reader); private: QExplicitlySharedDataPointer<ChannelResultData> d; }; } #endif // CHANNELRESULT_H
// -*- C++ -*- //============================================================================= /** * @file Svc_Conf_Lexer_Guard.h * * Svc_Conf_Lexer_Guard.h,v 4.2 2001/07/31 23:49:39 othman Exp * * @author <NAME> <<EMAIL>> */ //============================================================================= #ifndef ACE_SVC_CONF_LEXER_GUARD_H #define ACE_SVC_CONF_LEXER_GUARD_H #include "ace/pre.h" #include "ace/config-all.h" #if !defined (ACE_LACKS_PRAGMA_ONCE) # pragma once #endif /* ACE_LACKS_PRAGMA_ONCE */ /** * @class ACE_Svc_Conf_Lexer_Guard * * @brief "Guard" that ensures lexer buffer stack manipulation is * exception-safe. * * Buffers are allocated and deallocated when scanning a file or a * string. This class utilizes the "guard" idiom to perform stack * pushing and popping before and after parsing/scanning. * @par * The underlying stack allows nested scans to occur. For example, * while scanning a `svc.conf' file, a Service Object's init() method * could invoke a Service Configurator directive, which would require * "moving" the current lexer state out of the way (pushing it onto * the stack implementation). */ class ACE_Svc_Conf_Lexer_Guard { public: /// Constructor /** * Create a new buffer to be used when scanning a new Service * Configurator file, push it onto the underlying buffer stack, * and make it the current buffer. */ ACE_Svc_Conf_Lexer_Guard (FILE *file); /// Constructor /** * Create a new buffer to be used when scanning a new Service * Configurator directive, push it onto the underlying buffer stack, * and make it the current buffer. */ ACE_Svc_Conf_Lexer_Guard (const ACE_TCHAR *directive); /// Destructor /** * Pop the current buffer off of the underlying buffer stack, * and make the previous buffer (i.e. the one on the top of the * stack), the current buffer. */ ~ACE_Svc_Conf_Lexer_Guard (void); }; #include "ace/post.h" #endif /* ACE_SVC_CONF_LEXER_GUARD_H */
<reponame>ixiDev/iris<gh_stars>10-100 #include <iris/iris.h> #include <stdio.h> #include <stdlib.h> #include <malloc.h> size_t SIZE, UNIT; int VERBOSE; int TARGET; float *A, *B, *C; double t0, t1, t2, t3; void ijk() { for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { float sum = 0.0; for (int k = 0; k < SIZE; k++) { sum += A[i * SIZE + k] * B[k * SIZE + j]; } C[i * SIZE + j] = sum; } } } void kij() { for (int k = 0; k < SIZE; k++) { for (int i = 0; i < SIZE; i++) { float a = A[i * SIZE + k]; for (int j = 0; j < SIZE; j++) { C[i * SIZE + j] += a * B[k * SIZE + j]; } } } } int main(int argc, char** argv) { int ERROR = 0; iris_init(&argc, &argv, 1); iris_timer_now(&t0); SIZE = argc > 1 ? atol(argv[1]) : 64; TARGET = argc > 2 ? atoi(argv[2]) : 0; VERBOSE = argc > 3 ? atol(argv[3]) : 0; printf("SIZE[%d] MATRIX_SIZE[%u]MB VERBOSE[%d] TARGET[%d]\n", SIZE, SIZE * SIZE * sizeof(float) / 1024 / 1024, VERBOSE, TARGET); A = (float*) malloc(SIZE * SIZE * sizeof(float)); B = (float*) malloc(SIZE * SIZE * sizeof(float)); C = (float*) malloc(SIZE * SIZE * sizeof(float)); if (VERBOSE) { for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { A[i * SIZE + j] = i + j; B[i * SIZE + j] = i * j; C[i * SIZE + j] = 0.0; } } } iris_mem mem_A; iris_mem mem_B; iris_mem mem_C; iris_mem_create(SIZE * SIZE * sizeof(float), &mem_A); iris_mem_create(SIZE * SIZE * sizeof(float), &mem_B); iris_mem_create(SIZE * SIZE * sizeof(float), &mem_C); iris_timer_now(&t1); iris_task task; iris_task_create(&task); iris_task_h2d(task, mem_A, 0, SIZE * SIZE * sizeof(float), A); iris_task_h2d(task, mem_B, 0, SIZE * SIZE * sizeof(float), B); size_t ijk_idx[2] = { SIZE, SIZE }; size_t ijk_lws[2] = { 32, 32 }; void* params[3] = { mem_C, mem_A, mem_B }; int pinfo[3] = { iris_w, iris_r, iris_r }; iris_task_kernel(task, "ijk", 2, NULL, ijk_idx, ijk_lws, 3, params, pinfo); iris_task_d2h(task, mem_C, 0, SIZE * SIZE * sizeof(float), C); iris_task_submit(task, TARGET, NULL, 1); iris_timer_now(&t2); if (VERBOSE) { printf("[[ A ]]\n"); for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { printf("%5.0lf ", A[i * SIZE + j]); } printf("\n"); } printf("[[ B ]]\n"); for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { printf("%5.0lf ", B[i * SIZE + j]); } printf("\n"); } printf("[[ C ]]\n"); for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { printf("%5.0lf ", C[i * SIZE + j]); } printf("\n"); } printf("Checking errors\n"); for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { float sum = 0.0; for (int k = 0; k < SIZE; k++) { sum += A[i * SIZE + k] * B[k * SIZE + j]; } if (sum != C[i * SIZE + j]) ERROR++; } } } iris_timer_now(&t3); printf("ERROR[%d] TIME[%lf,%lf]\n", ERROR, t3 - t0, t2 - t1); iris_task_release(task); iris_mem_release(mem_A); iris_mem_release(mem_B); iris_mem_release(mem_C); free(A); free(B); free(C); iris_finalize(); return 0; }