hexsha
stringlengths
40
40
size
int64
5
1.05M
ext
stringclasses
588 values
lang
stringclasses
305 values
max_stars_repo_path
stringlengths
3
363
max_stars_repo_name
stringlengths
5
118
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
10
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringdate
2015-01-01 00:00:35
2022-03-31 23:43:49
max_stars_repo_stars_event_max_datetime
stringdate
2015-01-01 12:37:38
2022-03-31 23:59:52
max_issues_repo_path
stringlengths
3
363
max_issues_repo_name
stringlengths
5
118
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
10
max_issues_count
float64
1
134k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
363
max_forks_repo_name
stringlengths
5
135
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
10
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringdate
2015-01-01 00:01:02
2022-03-31 23:27:27
max_forks_repo_forks_event_max_datetime
stringdate
2015-01-03 08:55:07
2022-03-31 23:59:24
content
stringlengths
5
1.05M
avg_line_length
float64
1.13
1.04M
max_line_length
int64
1
1.05M
alphanum_fraction
float64
0
1
d0b04097a98df1661916747fae49ea6c9464f1e1
973
c
C
ternary.c
SaadMeftah/c-example-code
6206be05a2f837e85a0ed2450d2dc5ea33109913
[ "MIT" ]
16
2021-10-06T17:58:35.000Z
2022-03-30T04:31:16.000Z
ternary.c
SaadMeftah/c-example-code
6206be05a2f837e85a0ed2450d2dc5ea33109913
[ "MIT" ]
1
2022-03-19T21:19:49.000Z
2022-03-20T03:35:13.000Z
ternary.c
SaadMeftah/c-example-code
6206be05a2f837e85a0ed2450d2dc5ea33109913
[ "MIT" ]
13
2021-12-22T21:42:38.000Z
2022-03-29T18:43:56.000Z
/******************************************************************************* * * Program: Ternary operator example * * Description: Examples of how to use the ternary operator in C. * * YouTube Lesson: https://www.youtube.com/watch?v=nWvk4fPJu1U * * Author: Kevin Browne @ https://portfoliocourses.com * *******************************************************************************/ #include <stdio.h> int main(void) { int a = 5; int b = 5; int c = 0; // we could use an if-else to determine what assignment to make // if (a == b) c = 10; // else c = 5; // or we could use a ternary operator, which checks the boolean expression // preceeding the ? and then returns 5 if it is true and 10 if it is false c = ( a == b ) ? 5 : 10; printf("c: %d\n", c); int result = 0; // We can use a ternary operator in the middle of an expression such as this! result = 10 * ((a == c) ? 2 : 1); printf("result: %d\n", result); return 0; }
23.731707
80
0.520041
45a750ec81ba36b9acc656791593ec902443a871
2,000
c
C
tests/actions/action-sound.c
pwmt/libzathura
25ef21efbc5a7bf26d6dedbf5bc7b91a8eea350b
[ "Zlib" ]
1
2022-03-18T02:22:40.000Z
2022-03-18T02:22:40.000Z
tests/actions/action-sound.c
pwmt/libzathura
25ef21efbc5a7bf26d6dedbf5bc7b91a8eea350b
[ "Zlib" ]
null
null
null
tests/actions/action-sound.c
pwmt/libzathura
25ef21efbc5a7bf26d6dedbf5bc7b91a8eea350b
[ "Zlib" ]
null
null
null
/* See LICENSE file for license and copyright information */ #include <check.h> #include <libzathura/action.h> static void setup_action_sound(void) { fail_unless(zathura_action_new(&action, ZATHURA_ACTION_SOUND) == ZATHURA_ERROR_OK); fail_unless(action != NULL); } START_TEST(test_action_sound_new) { } END_TEST START_TEST(test_action_sound_get_type) { zathura_action_type_t type; fail_unless(zathura_action_get_type(action, &type) == ZATHURA_ERROR_OK); fail_unless(type == ZATHURA_ACTION_SOUND); } END_TEST START_TEST(test_action_sound_init) { /* invalid arguments */ fail_unless(zathura_action_sound_init(NULL) == ZATHURA_ERROR_INVALID_ARGUMENTS); zathura_action_t* action_unknown; fail_unless(zathura_action_new(&action_unknown, ZATHURA_ACTION_UNKNOWN) == ZATHURA_ERROR_OK); fail_unless(action_unknown != NULL); fail_unless(zathura_action_sound_init(action_unknown) == ZATHURA_ERROR_ACTION_INVALID_TYPE); fail_unless(zathura_action_free(action_unknown) == ZATHURA_ERROR_OK); /* valid arguments */ fail_unless(zathura_action_sound_init(action) == ZATHURA_ERROR_OK); // double initialization /* fault injection */ #ifdef WITH_LIBFIU fiu_enable("libc/mm/calloc", 1, NULL, 0); fail_unless(zathura_action_sound_init(action) == ZATHURA_ERROR_OUT_OF_MEMORY); // double initialization fiu_disable("libc/mm/calloc"); #endif } END_TEST START_TEST(test_action_sound_clear) { /* invalid arguments */ fail_unless(zathura_action_sound_clear(NULL) == ZATHURA_ERROR_INVALID_ARGUMENTS); zathura_action_t* action_unknown; fail_unless(zathura_action_new(&action_unknown, ZATHURA_ACTION_UNKNOWN) == ZATHURA_ERROR_OK); fail_unless(action_unknown != NULL); fail_unless(zathura_action_sound_clear(action_unknown) == ZATHURA_ERROR_ACTION_INVALID_TYPE); fail_unless(zathura_action_free(action_unknown) == ZATHURA_ERROR_OK); /* valid arguments */ fail_unless(zathura_action_sound_clear(action) == ZATHURA_ERROR_OK); } END_TEST
33.333333
95
0.787
a9ca0117a56197b2492f7611f1ac39d4250427c1
101
h
C
app/src/main/cpp/kiss_fft/test/pstats.h
nickjingyuli/ECE420-final-project
cce482224cb54d60d406b55b12e5a7e4f1535f89
[ "Apache-2.0" ]
4
2016-01-28T10:20:23.000Z
2021-06-19T21:11:44.000Z
app/src/main/cpp/kiss_fft/test/pstats.h
nickjingyuli/ECE420-final-project
cce482224cb54d60d406b55b12e5a7e4f1535f89
[ "Apache-2.0" ]
null
null
null
app/src/main/cpp/kiss_fft/test/pstats.h
nickjingyuli/ECE420-final-project
cce482224cb54d60d406b55b12e5a7e4f1535f89
[ "Apache-2.0" ]
3
2019-12-31T15:56:34.000Z
2021-06-19T21:11:33.000Z
#ifndef PSTATS_H #define PSTATS_H void pstats_init(void); void pstats_report(void); #endif
12.625
26
0.722772
a9d80c9b3e14e7ce49f6908eb49dd53148752006
229
h
C
songs/model/ZDProject+Factory.h
jjorgemoura/songs
de2cec9b9ab5b702b31220c4082da9a87249f17a
[ "MIT" ]
null
null
null
songs/model/ZDProject+Factory.h
jjorgemoura/songs
de2cec9b9ab5b702b31220c4082da9a87249f17a
[ "MIT" ]
null
null
null
songs/model/ZDProject+Factory.h
jjorgemoura/songs
de2cec9b9ab5b702b31220c4082da9a87249f17a
[ "MIT" ]
null
null
null
// // ZDProject+Factory.h // songs // // Created by Jorge Moura on 09/07/14. // Copyright (c) 2014 Jorge Moura. All rights reserved. // #import "ZDProject.h" @interface ZDProject (Factory) + (NSString *)entityName; @end
13.470588
56
0.663755
e73768bec2f4c2942bc38731493179f0ac4a9a55
2,194
h
C
gdal/ogr/ogrsf_frmts/mvt/mvtutils.h
vincentsarago/gdal
a04093a73abc2060c0c46f5f03f5940867a1f65d
[ "MIT" ]
1
2021-04-10T21:03:13.000Z
2021-04-10T21:03:13.000Z
gdal/ogr/ogrsf_frmts/mvt/mvtutils.h
vincentsarago/gdal
a04093a73abc2060c0c46f5f03f5940867a1f65d
[ "MIT" ]
null
null
null
gdal/ogr/ogrsf_frmts/mvt/mvtutils.h
vincentsarago/gdal
a04093a73abc2060c0c46f5f03f5940867a1f65d
[ "MIT" ]
null
null
null
/****************************************************************************** * * Project: MVT Translator * Purpose: MapBox Vector Tile decoder * Author: Even Rouault, Even Rouault <even dot rouault at spatialys dot com> * ****************************************************************************** * Copyright (c) 2018, Even Rouault <even dot rouault at spatialys dot com> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef MVTUTILS_H #define MVTUTILS_H #include "cpl_json.h" #include "ogrsf_frmts.h" void OGRMVTInitFields(OGRFeatureDefn* poFeatureDefn, const CPLJSONObject& oFields); OGRwkbGeometryType OGRMVTFindGeomTypeFromTileStat( const CPLJSONArray& oTileStatLayers, const char* pszLayerName); OGRFeature* OGRMVTCreateFeatureFrom(OGRFeature* poSrcFeature, OGRFeatureDefn* poTargetFeatureDefn, bool bJsonField, OGRSpatialReference* poSRS); #endif // MVTUTILS_H
45.708333
79
0.625342
43dbaa2a6826663789204239aa43c7f1dcd57cc1
16,209
h
C
src/bringup/bin/netsvc/test/paver-test-common.h
csrpi/fuchsia
2f015594dcb4c13aa51eee305ad561078f1f9b7f
[ "BSD-2-Clause" ]
null
null
null
src/bringup/bin/netsvc/test/paver-test-common.h
csrpi/fuchsia
2f015594dcb4c13aa51eee305ad561078f1f9b7f
[ "BSD-2-Clause" ]
null
null
null
src/bringup/bin/netsvc/test/paver-test-common.h
csrpi/fuchsia
2f015594dcb4c13aa51eee305ad561078f1f9b7f
[ "BSD-2-Clause" ]
null
null
null
// Copyright 2020 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_BRINGUP_BIN_NETSVC_TEST_PAVER_TEST_COMMON_H_ #define SRC_BRINGUP_BIN_NETSVC_TEST_PAVER_TEST_COMMON_H_ #include <fuchsia/device/llcpp/fidl.h> #include <fuchsia/paver/llcpp/fidl.h> #include <lib/async-loop/cpp/loop.h> #include <lib/async-loop/default.h> #include <lib/async/dispatcher.h> #include <lib/driver-integration-test/fixture.h> #include <lib/fidl-async/cpp/bind.h> #include <lib/sync/completion.h> #include <lib/zircon-internal/thread_annotations.h> #include <lib/zx/channel.h> #include <lib/zx/time.h> #include <threads.h> #include <zircon/boot/netboot.h> #include <zircon/errors.h> #include <zircon/time.h> #include <algorithm> #include <memory> #include <vector> #include <fbl/auto_lock.h> #include <fbl/mutex.h> #include <ramdevice-client/ramdisk.h> #include <zxtest/zxtest.h> #include "src/bringup/bin/netsvc/paver.h" #include "src/lib/storage/vfs/cpp/pseudo_dir.h" #include "src/lib/storage/vfs/cpp/service.h" #include "src/lib/storage/vfs/cpp/synchronous_vfs.h" enum class Command { kUnknown, kInitializeAbr, kQueryCurrentConfiguration, kQueryActiveConfiguration, kQueryConfigurationStatus, kSetConfigurationActive, kSetConfigurationUnbootable, kSetConfigurationHealthy, kReadAsset, kWriteAsset, kWriteFirmware, kWriteVolumes, kWriteBootloader, kWriteDataFile, kWipeVolume, kInitPartitionTables, kWipePartitionTables, kDataSinkFlush, kBootManagerFlush, }; struct AbrSlotData { bool unbootable; bool active; }; struct AbrData { AbrSlotData slot_a; AbrSlotData slot_b; }; constexpr AbrData kInitAbrData = { .slot_a = { .unbootable = false, .active = false, }, .slot_b = { .unbootable = false, .active = false, }, }; class FakePaver : public fidl::WireRawChannelInterface<fuchsia_paver::Paver>, public fidl::WireInterface<fuchsia_paver::BootManager>, public fidl::WireRawChannelInterface<fuchsia_paver::DynamicDataSink> { public: zx_status_t Connect(async_dispatcher_t* dispatcher, zx::channel request) { dispatcher_ = dispatcher; return fidl::BindSingleInFlightOnly<fidl::WireRawChannelInterface<fuchsia_paver::Paver>>( dispatcher, std::move(request), this); } void FindDataSink(zx::channel data_sink, FindDataSinkCompleter::Sync& _completer) override { fidl::BindSingleInFlightOnly<fidl::WireRawChannelInterface<fuchsia_paver::DynamicDataSink>>( dispatcher_, std::move(data_sink), this); } void UseBlockDevice(zx::channel block_device, zx::channel dynamic_data_sink, UseBlockDeviceCompleter::Sync& _completer) override { auto result = fidl::WireCall<fuchsia_device::Controller>(zx::unowned(block_device)).GetTopologicalPath(); if (!result.ok() || result->result.is_err()) { return; } const auto& path = result->result.response().path; { fbl::AutoLock al(&lock_); if (std::string(path.data(), path.size()) != expected_block_device_) { return; } } fidl::BindSingleInFlightOnly<fidl::WireRawChannelInterface<fuchsia_paver::DynamicDataSink>>( dispatcher_, std::move(dynamic_data_sink), this); } void FindBootManager(zx::channel boot_manager, FindBootManagerCompleter::Sync& _completer) override { fbl::AutoLock al(&lock_); AppendCommand(Command::kInitializeAbr); if (abr_supported_) { fidl::BindSingleInFlightOnly<fidl::WireInterface<fuchsia_paver::BootManager>>( dispatcher_, std::move(boot_manager), this); } } void QueryCurrentConfiguration(QueryCurrentConfigurationCompleter::Sync& completer) override { fbl::AutoLock al(&lock_); AppendCommand(Command::kQueryCurrentConfiguration); completer.ReplySuccess(fuchsia_paver::wire::Configuration::A); } void FindSysconfig(zx::channel sysconfig, FindSysconfigCompleter::Sync& _completer) override {} void QueryActiveConfiguration(QueryActiveConfigurationCompleter::Sync& completer) override { fbl::AutoLock al(&lock_); AppendCommand(Command::kQueryActiveConfiguration); completer.ReplySuccess(fuchsia_paver::wire::Configuration::A); } void QueryConfigurationStatus(fuchsia_paver::wire::Configuration configuration, QueryConfigurationStatusCompleter::Sync& completer) override { fbl::AutoLock al(&lock_); AppendCommand(Command::kQueryConfigurationStatus); completer.ReplySuccess(fuchsia_paver::wire::ConfigurationStatus::HEALTHY); } void SetConfigurationActive(fuchsia_paver::wire::Configuration configuration, SetConfigurationActiveCompleter::Sync& completer) override { fbl::AutoLock al(&lock_); AppendCommand(Command::kSetConfigurationActive); zx_status_t status; switch (configuration) { case fuchsia_paver::wire::Configuration::A: abr_data_.slot_a.active = true; abr_data_.slot_a.unbootable = false; status = ZX_OK; break; case fuchsia_paver::wire::Configuration::B: abr_data_.slot_b.active = true; abr_data_.slot_b.unbootable = false; status = ZX_OK; break; case fuchsia_paver::wire::Configuration::RECOVERY: status = ZX_ERR_INVALID_ARGS; break; } completer.Reply(status); } void SetConfigurationUnbootable(fuchsia_paver::wire::Configuration configuration, SetConfigurationUnbootableCompleter::Sync& completer) override { fbl::AutoLock al(&lock_); AppendCommand(Command::kSetConfigurationUnbootable); zx_status_t status; switch (configuration) { case fuchsia_paver::wire::Configuration::A: abr_data_.slot_a.unbootable = true; status = ZX_OK; break; case fuchsia_paver::wire::Configuration::B: abr_data_.slot_b.unbootable = true; status = ZX_OK; break; case fuchsia_paver::wire::Configuration::RECOVERY: status = ZX_ERR_INVALID_ARGS; break; } completer.Reply(status); } void SetConfigurationHealthy(fuchsia_paver::wire::Configuration configuration, SetConfigurationHealthyCompleter::Sync& completer) override { fbl::AutoLock al(&lock_); AppendCommand(Command::kSetConfigurationHealthy); completer.Reply(ZX_OK); } void Flush(fidl::WireRawChannelInterface<fuchsia_paver::DynamicDataSink>::FlushCompleter::Sync& completer) override { fbl::AutoLock al(&lock_); AppendCommand(Command::kDataSinkFlush); completer.Reply(ZX_OK); } void Flush( fidl::WireInterface<fuchsia_paver::BootManager>::FlushCompleter::Sync& completer) override { fbl::AutoLock al(&lock_); AppendCommand(Command::kBootManagerFlush); completer.Reply(ZX_OK); } void ReadAsset(fuchsia_paver::wire::Configuration configuration, fuchsia_paver::wire::Asset asset, ReadAssetCompleter::Sync& completer) override { fbl::AutoLock al(&lock_); AppendCommand(Command::kReadAsset); completer.ReplyError(ZX_ERR_NOT_SUPPORTED); } void WriteAsset(fuchsia_paver::wire::Configuration configuration, fuchsia_paver::wire::Asset asset, fuchsia_mem::wire::Buffer payload, WriteAssetCompleter::Sync& completer) override { fbl::AutoLock al(&lock_); AppendCommand(Command::kWriteAsset); auto status = payload.size == expected_payload_size_ ? ZX_OK : ZX_ERR_INVALID_ARGS; completer.Reply(status); } void WriteFirmware(fuchsia_paver::wire::Configuration configuration, fidl::StringView type, fuchsia_mem::wire::Buffer payload, WriteFirmwareCompleter::Sync& completer) override { using fuchsia_paver::wire::WriteFirmwareResult; fbl::AutoLock al(&lock_); AppendCommand(Command::kWriteFirmware); last_firmware_type_ = std::string(type.data(), type.size()); // Reply varies depending on whether we support |type| or not. if (supported_firmware_type_ == std::string_view(type.data(), type.size())) { auto status = payload.size == expected_payload_size_ ? ZX_OK : ZX_ERR_INVALID_ARGS; completer.Reply( WriteFirmwareResult::WithStatus(fidl::ObjectView<zx_status_t>::FromExternal(&status))); } else { bool unsupported = true; completer.Reply( WriteFirmwareResult::WithUnsupported(fidl::ObjectView<bool>::FromExternal(&unsupported))); } } void WriteVolumes(zx::channel payload_stream, WriteVolumesCompleter::Sync& completer) override { { fbl::AutoLock al(&lock_); AppendCommand(Command::kWriteVolumes); } // Register VMO. zx::vmo vmo; auto status = zx::vmo::create(1024, 0, &vmo); if (status != ZX_OK) { completer.Reply(status); return; } fidl::WireSyncClient<fuchsia_paver::PayloadStream> stream(std::move(payload_stream)); auto result = stream.RegisterVmo(std::move(vmo)); status = result.ok() ? result.value().status : result.status(); if (status != ZX_OK) { completer.Reply(status); return; } // Stream until EOF. status = [&]() { size_t data_transferred = 0; for (;;) { { fbl::AutoLock al(&lock_); if (wait_for_start_signal_) { al.release(); sync_completion_wait(&start_signal_, ZX_TIME_INFINITE); sync_completion_reset(&start_signal_); } else { signal_size_ = expected_payload_size_ + 1; } } while (data_transferred < signal_size_) { auto result = stream.ReadData(); if (!result.ok()) { return result.status(); } const auto& response = result.value(); switch (response.result.which()) { case fuchsia_paver::wire::ReadResult::Tag::kErr: return response.result.err(); case fuchsia_paver::wire::ReadResult::Tag::kEof: return data_transferred == expected_payload_size_ ? ZX_OK : ZX_ERR_INVALID_ARGS; case fuchsia_paver::wire::ReadResult::Tag::kInfo: data_transferred += response.result.info().size; continue; default: return ZX_ERR_INTERNAL; } } sync_completion_signal(&done_signal_); } }(); sync_completion_signal(&done_signal_); completer.Reply(status); } void WriteBootloader(fuchsia_mem::wire::Buffer payload, WriteBootloaderCompleter::Sync& completer) override { fbl::AutoLock al(&lock_); AppendCommand(Command::kWriteBootloader); auto status = payload.size == expected_payload_size_ ? ZX_OK : ZX_ERR_INVALID_ARGS; completer.Reply(status); } void WriteDataFile(fidl::StringView filename, fuchsia_mem::wire::Buffer payload, WriteDataFileCompleter::Sync& completer) override { fbl::AutoLock al(&lock_); AppendCommand(Command::kWriteDataFile); auto status = payload.size == expected_payload_size_ ? ZX_OK : ZX_ERR_INVALID_ARGS; completer.Reply(status); } void WipeVolume(WipeVolumeCompleter::Sync& completer) override { fbl::AutoLock al(&lock_); AppendCommand(Command::kWipeVolume); completer.ReplySuccess({}); } void InitializePartitionTables(InitializePartitionTablesCompleter::Sync& completer) override { fbl::AutoLock al(&lock_); AppendCommand(Command::kInitPartitionTables); completer.Reply(ZX_OK); } void WipePartitionTables(WipePartitionTablesCompleter::Sync& completer) override { fbl::AutoLock al(&lock_); AppendCommand(Command::kWipePartitionTables); completer.Reply(ZX_OK); } void WaitForWritten(size_t size) { signal_size_ = size; sync_completion_signal(&start_signal_); sync_completion_wait(&done_signal_, ZX_TIME_INFINITE); sync_completion_reset(&done_signal_); } const std::vector<Command> GetCommandTrace() { fbl::AutoLock al(&lock_); return command_trace_; } std::string last_firmware_type() const { fbl::AutoLock al(&lock_); return last_firmware_type_; } void set_expected_payload_size(size_t size) { expected_payload_size_ = size; } void set_supported_firmware_type(std::string type) { fbl::AutoLock al(&lock_); supported_firmware_type_ = type; } void set_abr_supported(bool supported) { abr_supported_ = supported; } void set_wait_for_start_signal(bool wait) { wait_for_start_signal_ = wait; } void set_expected_device(std::string expected) { fbl::AutoLock al(&lock_); expected_block_device_ = expected; } const AbrData abr_data() { fbl::AutoLock al(&lock_); return abr_data_; } private: std::atomic<bool> wait_for_start_signal_ = false; sync_completion_t start_signal_; sync_completion_t done_signal_; std::atomic<size_t> signal_size_; mutable fbl::Mutex lock_; std::string last_firmware_type_ TA_GUARDED(lock_); std::atomic<size_t> expected_payload_size_ = 0; std::string expected_block_device_ TA_GUARDED(lock_); std::string supported_firmware_type_ TA_GUARDED(lock_); std::atomic<bool> abr_supported_ = false; AbrData abr_data_ TA_GUARDED(lock_) = kInitAbrData; std::atomic<async_dispatcher_t*> dispatcher_ = nullptr; std::vector<Command> command_trace_ TA_GUARDED(lock_); void AppendCommand(Command cmd) TA_REQ(lock_) { command_trace_.push_back(cmd); } }; class FakeSvc { public: explicit FakeSvc(async_dispatcher_t* dispatcher) : dispatcher_(dispatcher), vfs_(dispatcher) { auto root_dir = fbl::MakeRefCounted<fs::PseudoDir>(); root_dir->AddEntry(fuchsia_paver::Paver::Name, fbl::MakeRefCounted<fs::Service>([this](zx::channel request) { return fake_paver_.Connect(dispatcher_, std::move(request)); })); zx::channel svc_remote; ASSERT_OK(zx::channel::create(0, &svc_local_, &svc_remote)); vfs_.ServeDirectory(root_dir, std::move(svc_remote)); } FakePaver& fake_paver() { return fake_paver_; } zx::channel& svc_chan() { return svc_local_; } private: async_dispatcher_t* dispatcher_; fs::SynchronousVfs vfs_; FakePaver fake_paver_; zx::channel svc_local_; }; class FakeDev { public: FakeDev() { driver_integration_test::IsolatedDevmgr::Args args; args.driver_search_paths.push_back("/boot/driver"); ASSERT_OK(driver_integration_test::IsolatedDevmgr::Create(&args, &devmgr_)); fbl::unique_fd fd; ASSERT_OK( devmgr_integration_test::RecursiveWaitForFile(devmgr_.devfs_root(), "sys/platform", &fd)); } driver_integration_test::IsolatedDevmgr devmgr_; }; class PaverTest : public zxtest::Test { protected: PaverTest() : loop_(&kAsyncLoopConfigNoAttachToCurrentThread), fake_svc_(loop_.dispatcher()), paver_(std::move(fake_svc_.svc_chan()), fake_dev_.devmgr_.devfs_root().duplicate()) { paver_.set_timeout(zx::msec(500)); loop_.StartThread("paver-test-loop"); } ~PaverTest() { // Need to make sure paver thread exits. Wait(); if (ramdisk_ != nullptr) { ramdisk_destroy(ramdisk_); ramdisk_ = nullptr; } loop_.Shutdown(); } void Wait() { while (paver_.InProgress()) continue; } void SpawnBlockDevice() { fbl::unique_fd fd; ASSERT_OK(devmgr_integration_test::RecursiveWaitForFile(fake_dev_.devmgr_.devfs_root(), "misc/ramctl", &fd)); ASSERT_OK(ramdisk_create_at(fake_dev_.devmgr_.devfs_root().get(), zx_system_get_page_size(), 100, &ramdisk_)); std::string expected = std::string("/dev/") + ramdisk_get_path(ramdisk_); fake_svc_.fake_paver().set_expected_device(expected); } async::Loop loop_; ramdisk_client_t* ramdisk_ = nullptr; FakeSvc fake_svc_; FakeDev fake_dev_; netsvc::Paver paver_; }; #endif // SRC_BRINGUP_BIN_NETSVC_TEST_PAVER_TEST_COMMON_H_
33.489669
100
0.687087
a2b68823717bc7269e4de9e8e9cef2df57743312
10,440
h
C
kernel/linux-5.4/include/linux/coresight.h
josehu07/SplitFS
d7442fa67a17de7057664f91defbfdbf10dd7f4a
[ "Apache-2.0" ]
27
2021-10-04T18:56:52.000Z
2022-03-28T08:23:06.000Z
kernel/linux-5.4/include/linux/coresight.h
josehu07/SplitFS
d7442fa67a17de7057664f91defbfdbf10dd7f4a
[ "Apache-2.0" ]
1
2022-01-12T04:05:36.000Z
2022-01-16T15:48:42.000Z
kernel/linux-5.4/include/linux/coresight.h
josehu07/SplitFS
d7442fa67a17de7057664f91defbfdbf10dd7f4a
[ "Apache-2.0" ]
6
2021-11-02T10:56:19.000Z
2022-03-06T11:58:20.000Z
/* SPDX-License-Identifier: GPL-2.0 */ /* * Copyright (c) 2012, The Linux Foundation. All rights reserved. */ #ifndef _LINUX_CORESIGHT_H #define _LINUX_CORESIGHT_H #include <linux/device.h> #include <linux/perf_event.h> #include <linux/sched.h> /* Peripheral id registers (0xFD0-0xFEC) */ #define CORESIGHT_PERIPHIDR4 0xfd0 #define CORESIGHT_PERIPHIDR5 0xfd4 #define CORESIGHT_PERIPHIDR6 0xfd8 #define CORESIGHT_PERIPHIDR7 0xfdC #define CORESIGHT_PERIPHIDR0 0xfe0 #define CORESIGHT_PERIPHIDR1 0xfe4 #define CORESIGHT_PERIPHIDR2 0xfe8 #define CORESIGHT_PERIPHIDR3 0xfeC /* Component id registers (0xFF0-0xFFC) */ #define CORESIGHT_COMPIDR0 0xff0 #define CORESIGHT_COMPIDR1 0xff4 #define CORESIGHT_COMPIDR2 0xff8 #define CORESIGHT_COMPIDR3 0xffC #define ETM_ARCH_V3_3 0x23 #define ETM_ARCH_V3_5 0x25 #define PFT_ARCH_V1_0 0x30 #define PFT_ARCH_V1_1 0x31 #define CORESIGHT_UNLOCK 0xc5acce55 extern struct bus_type coresight_bustype; enum coresight_dev_type { CORESIGHT_DEV_TYPE_NONE, CORESIGHT_DEV_TYPE_SINK, CORESIGHT_DEV_TYPE_LINK, CORESIGHT_DEV_TYPE_LINKSINK, CORESIGHT_DEV_TYPE_SOURCE, CORESIGHT_DEV_TYPE_HELPER, }; enum coresight_dev_subtype_sink { CORESIGHT_DEV_SUBTYPE_SINK_NONE, CORESIGHT_DEV_SUBTYPE_SINK_PORT, CORESIGHT_DEV_SUBTYPE_SINK_BUFFER, }; enum coresight_dev_subtype_link { CORESIGHT_DEV_SUBTYPE_LINK_NONE, CORESIGHT_DEV_SUBTYPE_LINK_MERG, CORESIGHT_DEV_SUBTYPE_LINK_SPLIT, CORESIGHT_DEV_SUBTYPE_LINK_FIFO, }; enum coresight_dev_subtype_source { CORESIGHT_DEV_SUBTYPE_SOURCE_NONE, CORESIGHT_DEV_SUBTYPE_SOURCE_PROC, CORESIGHT_DEV_SUBTYPE_SOURCE_BUS, CORESIGHT_DEV_SUBTYPE_SOURCE_SOFTWARE, }; enum coresight_dev_subtype_helper { CORESIGHT_DEV_SUBTYPE_HELPER_NONE, CORESIGHT_DEV_SUBTYPE_HELPER_CATU, }; /** * union coresight_dev_subtype - further characterisation of a type * @sink_subtype: type of sink this component is, as defined * by @coresight_dev_subtype_sink. * @link_subtype: type of link this component is, as defined * by @coresight_dev_subtype_link. * @source_subtype: type of source this component is, as defined * by @coresight_dev_subtype_source. * @helper_subtype: type of helper this component is, as defined * by @coresight_dev_subtype_helper. */ union coresight_dev_subtype { /* We have some devices which acts as LINK and SINK */ struct { enum coresight_dev_subtype_sink sink_subtype; enum coresight_dev_subtype_link link_subtype; }; enum coresight_dev_subtype_source source_subtype; enum coresight_dev_subtype_helper helper_subtype; }; /** * struct coresight_platform_data - data harvested from the DT specification * @nr_inport: number of input ports for this component. * @nr_outport: number of output ports for this component. * @conns: Array of nr_outport connections from this component */ struct coresight_platform_data { int nr_inport; int nr_outport; struct coresight_connection *conns; }; /** * struct coresight_desc - description of a component required from drivers * @type: as defined by @coresight_dev_type. * @subtype: as defined by @coresight_dev_subtype. * @ops: generic operations for this component, as defined * by @coresight_ops. * @pdata: platform data collected from DT. * @dev: The device entity associated to this component. * @groups: operations specific to this component. These will end up * in the component's sysfs sub-directory. * @name: name for the coresight device, also shown under sysfs. */ struct coresight_desc { enum coresight_dev_type type; union coresight_dev_subtype subtype; const struct coresight_ops *ops; struct coresight_platform_data *pdata; struct device *dev; const struct attribute_group **groups; const char *name; }; /** * struct coresight_connection - representation of a single connection * @outport: a connection's output port number. * @child_port: remote component's port number @output is connected to. * @chid_fwnode: remote component's fwnode handle. * @child_dev: a @coresight_device representation of the component connected to @outport. */ struct coresight_connection { int outport; int child_port; struct fwnode_handle *child_fwnode; struct coresight_device *child_dev; }; /** * struct coresight_device - representation of a device as used by the framework * @pdata: Platform data with device connections associated to this device. * @type: as defined by @coresight_dev_type. * @subtype: as defined by @coresight_dev_subtype. * @ops: generic operations for this component, as defined by @coresight_ops. * @dev: The device entity associated to this component. * @refcnt: keep track of what is in use. * @orphan: true if the component has connections that haven't been linked. * @enable: 'true' if component is currently part of an active path. * @activated: 'true' only if a _sink_ has been activated. A sink can be * activated but not yet enabled. Enabling for a _sink_ * appens when a source has been selected for that it. * @ea: Device attribute for sink representation under PMU directory. */ struct coresight_device { struct coresight_platform_data *pdata; enum coresight_dev_type type; union coresight_dev_subtype subtype; const struct coresight_ops *ops; struct device dev; atomic_t *refcnt; bool orphan; bool enable; /* true only if configured as part of a path */ /* sink specific fields */ bool activated; /* true only if a sink is part of a path */ struct dev_ext_attribute *ea; }; /* * coresight_dev_list - Mapping for devices to "name" index for device * names. * * @nr_idx: Number of entries already allocated. * @pfx: Prefix pattern for device name. * @fwnode_list: Array of fwnode_handles associated with each allocated * index, upto nr_idx entries. */ struct coresight_dev_list { int nr_idx; const char *pfx; struct fwnode_handle **fwnode_list; }; #define DEFINE_CORESIGHT_DEVLIST(var, dev_pfx) \ static struct coresight_dev_list (var) = { \ .pfx = dev_pfx, \ .nr_idx = 0, \ .fwnode_list = NULL, \ } #define to_coresight_device(d) container_of(d, struct coresight_device, dev) #define source_ops(csdev) csdev->ops->source_ops #define sink_ops(csdev) csdev->ops->sink_ops #define link_ops(csdev) csdev->ops->link_ops #define helper_ops(csdev) csdev->ops->helper_ops /** * struct coresight_ops_sink - basic operations for a sink * Operations available for sinks * @enable: enables the sink. * @disable: disables the sink. * @alloc_buffer: initialises perf's ring buffer for trace collection. * @free_buffer: release memory allocated in @get_config. * @update_buffer: update buffer pointers after a trace session. */ struct coresight_ops_sink { int (*enable)(struct coresight_device *csdev, u32 mode, void *data); int (*disable)(struct coresight_device *csdev); void *(*alloc_buffer)(struct coresight_device *csdev, struct perf_event *event, void **pages, int nr_pages, bool overwrite); void (*free_buffer)(void *config); unsigned long (*update_buffer)(struct coresight_device *csdev, struct perf_output_handle *handle, void *sink_config); }; /** * struct coresight_ops_link - basic operations for a link * Operations available for links. * @enable: enables flow between iport and oport. * @disable: disables flow between iport and oport. */ struct coresight_ops_link { int (*enable)(struct coresight_device *csdev, int iport, int oport); void (*disable)(struct coresight_device *csdev, int iport, int oport); }; /** * struct coresight_ops_source - basic operations for a source * Operations available for sources. * @cpu_id: returns the value of the CPU number this component * is associated to. * @trace_id: returns the value of the component's trace ID as known * to the HW. * @enable: enables tracing for a source. * @disable: disables tracing for a source. */ struct coresight_ops_source { int (*cpu_id)(struct coresight_device *csdev); int (*trace_id)(struct coresight_device *csdev); int (*enable)(struct coresight_device *csdev, struct perf_event *event, u32 mode); void (*disable)(struct coresight_device *csdev, struct perf_event *event); }; /** * struct coresight_ops_helper - Operations for a helper device. * * All operations could pass in a device specific data, which could * help the helper device to determine what to do. * * @enable : Enable the device * @disable : Disable the device */ struct coresight_ops_helper { int (*enable)(struct coresight_device *csdev, void *data); int (*disable)(struct coresight_device *csdev, void *data); }; struct coresight_ops { const struct coresight_ops_sink *sink_ops; const struct coresight_ops_link *link_ops; const struct coresight_ops_source *source_ops; const struct coresight_ops_helper *helper_ops; }; #ifdef CONFIG_CORESIGHT extern struct coresight_device * coresight_register(struct coresight_desc *desc); extern void coresight_unregister(struct coresight_device *csdev); extern int coresight_enable(struct coresight_device *csdev); extern void coresight_disable(struct coresight_device *csdev); extern int coresight_timeout(void __iomem *addr, u32 offset, int position, int value); extern int coresight_claim_device(void __iomem *base); extern int coresight_claim_device_unlocked(void __iomem *base); extern void coresight_disclaim_device(void __iomem *base); extern void coresight_disclaim_device_unlocked(void __iomem *base); extern char *coresight_alloc_device_name(struct coresight_dev_list *devs, struct device *dev); #else static inline struct coresight_device * coresight_register(struct coresight_desc *desc) { return NULL; } static inline void coresight_unregister(struct coresight_device *csdev) {} static inline int coresight_enable(struct coresight_device *csdev) { return -ENOSYS; } static inline void coresight_disable(struct coresight_device *csdev) {} static inline int coresight_timeout(void __iomem *addr, u32 offset, int position, int value) { return 1; } static inline int coresight_claim_device_unlocked(void __iomem *base) { return -EINVAL; } static inline int coresight_claim_device(void __iomem *base) { return -EINVAL; } static inline void coresight_disclaim_device(void __iomem *base) {} static inline void coresight_disclaim_device_unlocked(void __iomem *base) {} #endif extern int coresight_get_cpu(struct device *dev); struct coresight_platform_data *coresight_get_platform_data(struct device *dev); #endif
32.933754
80
0.774617
bdb7140d5a323977c167a61c6ec31a9f3b03f248
2,389
c
C
2AHME/ue11_ Koerperberechnung mit Menuefunktion/main.c
kosphm18/aiit
1ac9a6253ee7af8191f8d709bc6ddce82f7e3336
[ "MIT" ]
null
null
null
2AHME/ue11_ Koerperberechnung mit Menuefunktion/main.c
kosphm18/aiit
1ac9a6253ee7af8191f8d709bc6ddce82f7e3336
[ "MIT" ]
null
null
null
2AHME/ue11_ Koerperberechnung mit Menuefunktion/main.c
kosphm18/aiit
1ac9a6253ee7af8191f8d709bc6ddce82f7e3336
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <math.h> double getInputIntegerValue (char text[]) { char s[100]; int rv; int n; do { printf("%s", text); fgets(s, 100, stdin); n = sscanf(s, "%d", &rv); } while (n != 1); return rv; } double getInputDoubleValue (char text[]) { char s[100]; int rv; double n; do { printf("%s", text); fgets(s, 100, stdin); n = sscanf(s, "%d", &rv); } while (n != 1); return rv; } double getSelectedMenu() { int rv; do{ printf("--------------------------------------\n"); printf("1 ... Wuerfel\n"); printf("2 ... Quder\n"); printf("3 ... Kugel\n"); printf("4 ... Programm beenden\n"); rv = getInputIntegerValue("\n Auswahl (1-4): "); } while ( rv != 1 && rv != 2 && rv != 3 && rv != 4); return rv; } void calcCube() { double h; double f; double v; printf("Wuerfel: "); do{ h = getInputDoubleValue("Laenge: "); } while (h > 0); f = 6 * (h * h); v = h * h * h; printf("Oberflaeche: %.2lf\n", f); printf("Volumen: %.2lf\n", v); } void calcCuboid() { double l, b, h; printf("Quader: "); do{ l = getInputDoubleValue("Laenge: "); b = getInputDoubleValue("Breite: "); h = getInputDoubleValue("Hoehe: "); } while (l < 0 || b < 0 || h < 0); double v = l * b * h; double f = 2 * l * b + 2 * l * h + 2 * b * h; printf("Volumen: %.2lf\n", v); printf("Oberflaeche: %.2lf", f); } double calcSphere() { double d; printf("Kugel"); do{ d = getInputDoubleValue("Durchmesser: "); }while (d < 0); double r = d / 2; double v = (4 / 3) * M_PI * r * r * r; double f = 4 * M_PI * r * r; printf("Volumen: %.2lf\n", v); printf("Flaeche: %.2lf\n", f); return 0; } int main() { int wahl; wahl = getSelectedMenu(); while (1){ switch(wahl) { case 1: { calcCube(); break; } case 2: { calcCuboid(); break; } case 3: { calcSphere(); break; } case 4: { return 0; } } return 0; } }
16.251701
60
0.421097
ecd9bad9ea1932002ef7d14e07de53c293121743
1,772
h
C
roo_material_icons/sharp/36/toggle.h
dejwk/roo_material_icons
f559ce25b6ee2fdf67ed4f8b0bedfce2aaefb885
[ "MIT" ]
null
null
null
roo_material_icons/sharp/36/toggle.h
dejwk/roo_material_icons
f559ce25b6ee2fdf67ed4f8b0bedfce2aaefb885
[ "MIT" ]
null
null
null
roo_material_icons/sharp/36/toggle.h
dejwk/roo_material_icons
f559ce25b6ee2fdf67ed4f8b0bedfce2aaefb885
[ "MIT" ]
null
null
null
#include "roo_display/image/image.h" const ::roo_display::RleImage4bppxBiased<::roo_display::Alpha4, ::roo_display::PrgMemResource>& ic_sharp_36_toggle_check_box_outline_blank(); const ::roo_display::RleImage4bppxBiased<::roo_display::Alpha4, ::roo_display::PrgMemResource>& ic_sharp_36_toggle_check_box(); const ::roo_display::RleImage4bppxBiased<::roo_display::Alpha4, ::roo_display::PrgMemResource>& ic_sharp_36_toggle_indeterminate_check_box(); const ::roo_display::RleImage4bppxBiased<::roo_display::Alpha4, ::roo_display::PrgMemResource>& ic_sharp_36_toggle_radio_button_checked(); const ::roo_display::RleImage4bppxBiased<::roo_display::Alpha4, ::roo_display::PrgMemResource>& ic_sharp_36_toggle_radio_button_unchecked(); const ::roo_display::RleImage4bppxBiased<::roo_display::Alpha4, ::roo_display::PrgMemResource>& ic_sharp_36_toggle_star_border(); const ::roo_display::RleImage4bppxBiased<::roo_display::Alpha4, ::roo_display::PrgMemResource>& ic_sharp_36_toggle_star_border_purple500(); const ::roo_display::RleImage4bppxBiased<::roo_display::Alpha4, ::roo_display::PrgMemResource>& ic_sharp_36_toggle_star_half(); const ::roo_display::RleImage4bppxBiased<::roo_display::Alpha4, ::roo_display::PrgMemResource>& ic_sharp_36_toggle_star_outline(); const ::roo_display::RleImage4bppxBiased<::roo_display::Alpha4, ::roo_display::PrgMemResource>& ic_sharp_36_toggle_star(); const ::roo_display::RleImage4bppxBiased<::roo_display::Alpha4, ::roo_display::PrgMemResource>& ic_sharp_36_toggle_star_purple500(); const ::roo_display::RleImage4bppxBiased<::roo_display::Alpha4, ::roo_display::PrgMemResource>& ic_sharp_36_toggle_toggle_off(); const ::roo_display::RleImage4bppxBiased<::roo_display::Alpha4, ::roo_display::PrgMemResource>& ic_sharp_36_toggle_toggle_on();
110.75
141
0.826185
0c1bd6f93cffe0a7d952c68b1f1aa367c12e39d1
938
h
C
Standard/Limits.h
CarysT/medusa
8e79f7738534d8cf60577ec42ed86621533ac269
[ "MIT" ]
32
2016-05-22T23:09:19.000Z
2022-03-13T03:32:27.000Z
Standard/Limits.h
CarysT/medusa
8e79f7738534d8cf60577ec42ed86621533ac269
[ "MIT" ]
2
2016-05-30T19:45:58.000Z
2018-01-24T22:29:51.000Z
Standard/Limits.h
CarysT/medusa
8e79f7738534d8cf60577ec42ed86621533ac269
[ "MIT" ]
17
2016-05-27T11:01:42.000Z
2022-03-13T03:32:30.000Z
/* Limits.h (c)2005 Palestar, Richard Lyle */ #ifndef LIMITS_H #define LIMITS_H //---------------------------------------------------------------------------- template<class T> const T & Max( const T &a, const T &b) { return( a > b ? a : b ); } template<class T> const T & Min( const T &a, const T &b) { return( a > b ? b : a ); } template<class T> inline T ClampMax( T value, T max ) { return( value > max ? max : value ); } template<class T> inline T ClampMin( T value, T min ) { return( value < min ? min : value ); } template<class T> const T & Clamp( const T &value, const T &min, const T &max) { return( value < max ? value > min ? value : min : max ); } template<class T> void Swap( T & v1, T & v2 ) { T swap = v1; v1 = v2; v2 = swap; } //---------------------------------------------------------------------------- #endif //---------------------------------------------------------------------------- // EOF
16.75
78
0.442431
312305bd633dd420f4962065e40fe13c56b451f9
22,850
h
C
src/vw/Math/Functors.h
maxerbubba/visionworkbench
b06ba0597cd3864bb44ca52671966ca580c02af1
[ "Apache-2.0" ]
318
2015-01-02T16:37:34.000Z
2022-03-17T07:12:20.000Z
src/vw/Math/Functors.h
maxerbubba/visionworkbench
b06ba0597cd3864bb44ca52671966ca580c02af1
[ "Apache-2.0" ]
39
2015-07-30T22:22:42.000Z
2021-03-23T16:11:55.000Z
src/vw/Math/Functors.h
maxerbubba/visionworkbench
b06ba0597cd3864bb44ca52671966ca580c02af1
[ "Apache-2.0" ]
135
2015-01-19T00:57:20.000Z
2022-03-18T13:51:40.000Z
// __BEGIN_LICENSE__ // Copyright (c) 2006-2013, United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. All // rights reserved. // // The NASA Vision Workbench is 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. // __END_LICENSE__ /// \file Math/Functors.h /// /// Mathematical functors. /// /// This file provides polymorphic functor versions of the standard /// mathematical functions defined in e.g. math.h. /// #ifndef __VW_MATH_FUNCTORS_H__ #define __VW_MATH_FUNCTORS_H__ #include <cstdlib> #include <limits> #include <complex> #include <vector> #include <algorithm> #include <vw/config.h> #include <vw/Core/CompoundTypes.h> #include <vw/Core/TypeDeduction.h> #include <vw/Core/Functors.h> #include <vw/Core/Exception.h> #include <vw/config.h> #include <queue> // The math.h header in FreeBSD (and possibly other platforms) does not // include routines for manipulating long doubles. We disable long // double VW math routines here for certain platforms. #if defined(__FreeBSD__) || defined(_WIN32) #define __VW_MATH_DISABLE_LONG_DOUBLE_ARITHMETIC #endif namespace vw { namespace math { template <class T> struct StdMathType { typedef double type; }; template <> struct StdMathType<float > { typedef float type; }; template <> struct StdMathType<long double> { typedef long double type; }; template <class T1, class T2> struct StdMathType2 { typedef typename StdMathType<typename PromoteType<T1,T2>::type>::type type; }; template <class FuncT, class ArgT, bool ArgIsCompound> struct ArgUnaryFunctorTypeHelper : public StdMathType<ArgT> {}; template <class FuncT, class ArgT> struct ArgUnaryFunctorTypeHelper<FuncT,ArgT,true> { typedef typename CompoundChannelType<ArgT>::type channel_type; typedef typename ArgUnaryFunctorTypeHelper<FuncT,channel_type,IsCompound<channel_type>::value>::type result_channel_type; typedef typename CompoundChannelCast<ArgT,result_channel_type>::type type; }; template <class F, class T> struct ArgUnaryFunctorType : public ArgUnaryFunctorTypeHelper<F,T,IsCompound<T>::value> {}; template <class FuncT, class Arg1T, class Arg2T, bool Arg1IsCompound, bool Arg2IsCompound> struct BinaryFunctorTypeHelper : public StdMathType2<Arg1T,Arg2T> {}; template <class FuncT, class Arg1T, class Arg2T> struct BinaryFunctorTypeHelper<FuncT,Arg1T,Arg2T,true,false> { typedef typename CompoundChannelType<Arg1T>::type channel_type; typedef typename BinaryFunctorTypeHelper<FuncT,channel_type,Arg2T,IsCompound<channel_type>::value,false>::type result_channel_type; typedef typename CompoundChannelCast<Arg1T,result_channel_type>::type type; }; template <class FuncT, class Arg1T, class Arg2T> struct BinaryFunctorTypeHelper<FuncT,Arg1T,Arg2T,false,true> { typedef typename CompoundChannelType<Arg2T>::type channel_type; typedef typename BinaryFunctorTypeHelper<FuncT,Arg1T,channel_type,false,IsCompound<channel_type>::value>::type result_channel_type; typedef typename CompoundChannelCast<Arg2T,result_channel_type>::type type; }; template <class FuncT, class Arg1T, class Arg2T> struct BinaryFunctorTypeHelper<FuncT,Arg1T,Arg2T,true,true> { typedef typename CompoundChannelType<Arg1T>::type channel1_type; typedef typename CompoundChannelType<Arg2T>::type channel2_type; typedef typename BinaryFunctorTypeHelper<FuncT,channel1_type,channel2_type,IsCompound<channel1_type>::value,IsCompound<channel2_type>::value>::type result_channel_type; typedef typename boost::mpl::if_<CompoundIsCompatible<Arg1T,Arg2T>, typename CompoundChannelCast<Arg1T,result_channel_type>::type, TypeDeductionError<BinaryFunctorTypeHelper> >::type type; }; template <class FuncT, class Arg1T, class Arg2T> struct BinaryFunctorType : public BinaryFunctorTypeHelper<FuncT,Arg1T,Arg2T,IsCompound<Arg1T>::value,IsCompound<Arg2T>::value> {}; // ******************************************************************** // Standard Mathematical Functors // ******************************************************************** #if !defined(__VW_MATH_DISABLE_LONG_DOUBLE_ARITHMETIC) // This will actually create a specialization for long doubles #define __VW_MATH_UNARY_LONG_DOUBLE_IMPL(func) \ long double operator()( long double arg ) const { \ return func##l(arg); \ } #define __VW_MATH_BINARY_LONG_DOUBLE_IMPL(func) \ long double operator()( long double arg1, long double arg2 ) const { \ return func##l(arg1,arg2); \ } #else // This is basically a no-op #define __VW_MATH_UNARY_LONG_DOUBLE_IMPL(func) #define __VW_MATH_BINARY_LONG_DOUBLE_IMPL(func) #endif // Macros to easily create functors with a certain interface #define __VW_UNARY_MATH_FUNCTOR(name,func) \ struct Arg##name##Functor \ : UnaryReturnBinaryTemplateBind1st<ArgUnaryFunctorType,Arg##name##Functor> { \ template <class ValT> \ typename ArgUnaryFunctorType<Arg##name##Functor,ValT>::type \ operator()( ValT arg ) const { \ return func(arg); \ } \ float operator()( float arg ) const { \ return func##f(arg); \ } \ __VW_MATH_UNARY_LONG_DOUBLE_IMPL(func) \ }; \ using ::func; // END __VW_UNARY_MATH_FUNCTOR #define __VW_BINARY_MATH_FUNCTOR(name,func) \ struct ArgArg##name##Functor \ : BinaryReturnTernaryTemplateBind1st<BinaryFunctorType,ArgArg##name##Functor> { \ float operator()( float arg1, float arg2 ) const { \ return func##f(arg1,arg2); \ } \ __VW_MATH_BINARY_LONG_DOUBLE_IMPL(func) \ template <class Arg1T, class Arg2T> \ typename BinaryFunctorType<ArgArg##name##Functor,Arg1T,Arg2T>::type \ inline operator()( Arg1T const& arg1, Arg2T const& arg2 ) const { \ return func( arg1, arg2 ); \ } \ }; \ template <class ValT> \ struct ArgVal##name##Functor \ : UnaryReturnTernaryTemplateBind1st3rd<BinaryFunctorType,ArgArg##name##Functor,ValT> { \ ValT m_val; \ ArgVal##name##Functor(ValT val) : m_val(val) {} \ template <class ArgT> \ typename BinaryFunctorType<ArgArg##name##Functor,ArgT,ValT>::type \ inline operator()( ArgT const& arg ) const { \ return ArgArg##name##Functor()( arg, m_val ); \ } \ }; \ template <class ValT> \ struct ValArg##name##Functor \ : UnaryReturnTernaryTemplateBind1st2nd<BinaryFunctorType,ArgArg##name##Functor,ValT> { \ ValT m_val; \ ValArg##name##Functor(ValT val) : m_val(val) {} \ template <class ArgT> \ typename BinaryFunctorType<ArgArg##name##Functor,ValT,ArgT>::type \ inline operator()( ArgT const& arg ) const { \ return ArgArg##name##Functor()( m_val, arg ); \ } \ }; \ using ::func; // END __VW_BINARY_MATH_FUNCTOR __VW_UNARY_MATH_FUNCTOR( Fabs, fabs ) __VW_UNARY_MATH_FUNCTOR( Acos, acos ) __VW_UNARY_MATH_FUNCTOR( Asin, asin ) __VW_UNARY_MATH_FUNCTOR( Atan, atan ) __VW_UNARY_MATH_FUNCTOR( Cos, cos ) __VW_UNARY_MATH_FUNCTOR( Sin, sin ) __VW_UNARY_MATH_FUNCTOR( Tan, tan ) __VW_UNARY_MATH_FUNCTOR( Cosh, cosh ) __VW_UNARY_MATH_FUNCTOR( Sinh, sinh ) __VW_UNARY_MATH_FUNCTOR( Tanh, tanh ) __VW_UNARY_MATH_FUNCTOR( Exp, exp ) __VW_UNARY_MATH_FUNCTOR( Log, log ) __VW_UNARY_MATH_FUNCTOR( Log10, log10 ) __VW_UNARY_MATH_FUNCTOR( Sqrt, sqrt ) __VW_UNARY_MATH_FUNCTOR( Ceil, ceil ) __VW_UNARY_MATH_FUNCTOR( Floor, floor ) __VW_BINARY_MATH_FUNCTOR( Atan2, atan2 ) __VW_BINARY_MATH_FUNCTOR( Pow, pow ) __VW_BINARY_MATH_FUNCTOR( Hypot, hypot ) #ifndef WIN32 __VW_UNARY_MATH_FUNCTOR( Acosh, acosh ) __VW_UNARY_MATH_FUNCTOR( Asinh, asinh ) __VW_UNARY_MATH_FUNCTOR( Atanh, atanh ) #ifdef VW_HAVE_EXP2 __VW_UNARY_MATH_FUNCTOR( Exp2, exp2 ) #endif #ifdef VW_HAVE_LOG2 __VW_UNARY_MATH_FUNCTOR( Log2, log2 ) #endif #ifdef VW_HAVE_TGAMMA __VW_UNARY_MATH_FUNCTOR( Tgamma, tgamma ) #endif __VW_UNARY_MATH_FUNCTOR( Lgamma, lgamma ) __VW_UNARY_MATH_FUNCTOR( Expm1, expm1 ) __VW_UNARY_MATH_FUNCTOR( Log1p, log1p ) __VW_UNARY_MATH_FUNCTOR( Cbrt, cbrt ) __VW_UNARY_MATH_FUNCTOR( Erf, erf ) __VW_UNARY_MATH_FUNCTOR( Erfc, erfc ) __VW_UNARY_MATH_FUNCTOR( Round, round ) __VW_UNARY_MATH_FUNCTOR( Trunc, trunc ) __VW_BINARY_MATH_FUNCTOR( Copysign, copysign ) __VW_BINARY_MATH_FUNCTOR( Fdim, fdim ) #endif // Clean up the macros we are finished using #undef __VW_UNARY_MATH_FUNCTOR #undef __VW_BINARY_MATH_FUNCTOR // Real part functor struct ArgRealFunctor : UnaryReturnTemplateType<MakeReal> { template <class ValT> ValT operator()( ValT const& val ) const { return val; } template <class ValT> ValT operator()( std::complex<ValT> const& val ) const { return std::real(val); } }; // Imaginary part functor struct ArgImagFunctor : UnaryReturnTemplateType<MakeReal> { template <class ValT> ValT operator()( ValT const& /*val*/ ) const { return ValT(); } template <class ValT> ValT operator()( std::complex<ValT> const& val ) const { return std::imag(val); } }; // Absolute value functor // This one's tricky because we have a bunch of distinct cases // for integer types, floating-point types, and complex types. /// \cond INTERNAL // This is outside ArgAbsFunctor because explicit template // specialization doesn't work at class scope. template <bool IntegralN> struct DefaultAbsBehavior { template <class ValT> static inline int apply( ValT val ) { return std::abs(val); } }; template <> struct DefaultAbsBehavior<false> { template <class ValT> static inline double apply( ValT val ) { return fabs(val); } }; /// \endcond struct ArgAbsFunctor { template <class Args> struct result; template <class FuncT, class ValT> struct result<FuncT(ValT)> { typedef typename boost::mpl::if_c<std::numeric_limits<ValT>::is_integer, int, double>::type type; }; template <class FuncT> struct result<FuncT(float)> { typedef float type; }; template <class FuncT> struct result<FuncT(long double)> { typedef long double type; }; template <class FuncT> struct result<FuncT(int32)> { typedef int32 type; }; template <class FuncT> struct result<FuncT(int64)> { typedef int64 type; }; template <class FuncT, class ValT> struct result<FuncT(std::complex<ValT>)> { typedef ValT type; }; template <class ValT> typename result<ArgAbsFunctor(ValT)>::type inline operator()( ValT val ) const { return DefaultAbsBehavior<std::numeric_limits<ValT>::is_integer>::apply(val); } inline float operator()( float val ) const { return ::fabsf(val); } inline long operator()( long val ) const { return std::labs(val); } #ifdef VW_HAVE_FABSL inline long double operator()( long double val ) const { return ::fabsl(val); } #endif #ifdef VW_HAVE_LLABS inline long long operator()( long long val ) const { return ::llabs(val); } #endif template <class ValT> inline ValT operator()( std::complex<ValT> const& val ) const { return std::abs(val); } }; // Complex conjugation functor struct ArgConjFunctor : UnaryReturnSameType { template <class ValT> ValT operator()( ValT const& val ) const { return val; } template <class ValT> std::complex<ValT> operator()( std::complex<ValT> const& val ) const { return std::conj(val); } }; // Square Functor (so we don't have to always invoke POW) struct ArgSquareFunctor : UnaryReturnSameType { template <class ValT> ValT operator()( ValT const& val ) const { return val*val; } }; // General-purpose accumulation functor template <class AccumT, class FuncT = ArgArgInPlaceSumFunctor> struct Accumulator : ReturnFixedType<AccumT const&> { private: AccumT m_accum; FuncT m_func; public: typedef AccumT value_type; Accumulator() : m_accum(), m_func() {} Accumulator( FuncT const& func ) : m_accum(), m_func(func) {} Accumulator( AccumT const& accum ) : m_accum(accum), m_func() {} Accumulator( AccumT const& accum, FuncT const& func ) : m_accum(accum), m_func(func) {} template <class ArgT> inline AccumT const& operator()( ArgT const& arg ) { m_func(m_accum, arg); return m_accum; } inline AccumT const& value() const { return m_accum; } void reset( AccumT const& accum = AccumT() ) { m_accum = accum; } }; /// Computes minimum and maximum values template <class ValT> class MinMaxAccumulator : public ReturnFixedType<void> { ValT m_minval, m_maxval; bool m_valid; public: typedef std::pair<ValT,ValT> value_type; MinMaxAccumulator() : m_minval(0), m_maxval(0), m_valid(false) {} void operator()( ValT const& arg ) { if ( ! m_valid ) { m_minval = m_maxval = arg; m_valid = true; } else { if( arg < m_minval ) m_minval = arg; if( m_maxval < arg ) m_maxval = arg; } } ValT minimum() const { VW_ASSERT(m_valid, ArgumentErr() << "MinMaxAccumulator: no valid samples"); return m_minval; } ValT maximum() const { VW_ASSERT(m_valid, ArgumentErr() << "MinMaxAccumulator: no valid samples"); return m_maxval; } std::pair<ValT,ValT> value() const { VW_ASSERT(m_valid, ArgumentErr() << "MinMaxAccumulator: no valid samples"); return std::make_pair(m_minval,m_maxval); } }; // Note: This function modifies the input! template <class T> T destructive_median(std::vector<T> & vec){ int len = vec.size(); VW_ASSERT(len, ArgumentErr() << "median: no valid samples."); std::sort(vec.begin(), vec.end()); return len%2 ? vec[len/2] : (vec[len/2 - 1] + vec[len/2]) / 2; } // Computes the median of the values to which it is applied. template <class ValT> class MedianAccumulator : public ReturnFixedType<void> { std::vector<ValT> m_values; public: typedef ValT value_type; void operator()( ValT const& value ) { m_values.push_back( value ); } // This is to check if there are any values size_t size() { return m_values.size(); } ValT value() { return destructive_median(m_values); } }; // Compute the normalized median absolute deviation: // nmad = 1.4826 * median(abs(X - median(X))) // Note: This function modifies the input! template <class T> T destructive_nmad(std::vector<T> & vec){ int len = vec.size(); VW_ASSERT(len, ArgumentErr() << "nmad: no valid samples."); // Find the median. This sorts the vector, but that is not a problem. T median = destructive_median(vec); for (size_t it = 0; it < vec.size(); it++) vec[it] = std::abs(vec[it] - median); median = destructive_median(vec); median *= 1.4826; return median; } // Compute the percentile using // https://en.wikipedia.org/wiki/Percentile#The_nearest-rank_method // Note: This function modifies the input! template <class T> T destructive_percentile(std::vector<T> & vec, double percentile){ int len = vec.size(); VW_ASSERT(len > 0, ArgumentErr() << "percentile: no valid samples."); VW_ASSERT(percentile >= 0 && percentile <= 100.0, ArgumentErr() << "Percentile must be between 0 and 100."); // Sorting is vital std::sort(vec.begin(), vec.end()); int index = ceil((percentile/100.0) * double(len)); // Account for the fact that in C++ indices start from 0 index--; if (index < 0) index = 0; if (index >= len) index = len-1; return vec[index]; } /// Computes the mean of the values to which it is applied. template <class ValT> class MeanAccumulator : public ReturnFixedType<void> { typedef typename CompoundChannelCast<ValT,double>::type accum_type; accum_type m_accum; double m_count; public: typedef accum_type value_type; MeanAccumulator() : m_accum(), m_count() {} void operator()( ValT const& value ) { m_accum += value; m_count += 1.0; } value_type value() const { VW_ASSERT(m_count, ArgumentErr() << "MeanAccumulator: no valid samples"); return m_accum / m_count; } }; /// Computes the standard deviation of the values to which it is applied. /// - This implementation normalizes by num_samples, not num_samples - 1. template <class ValT> class StdDevAccumulator : public ReturnFixedType<void> { typedef typename CompoundChannelCast<ValT,double>::type accum_type; accum_type mom1_accum, mom2_accum; double num_samples; public: typedef accum_type value_type; StdDevAccumulator() : mom1_accum(), mom2_accum(), num_samples() {} void operator()( ValT const& arg ) { mom1_accum += arg; mom2_accum += (accum_type) arg * arg; num_samples += 1.0; } /// Return the standard deviation value_type value() const { VW_ASSERT(num_samples, ArgumentErr() << "StdDevAccumulator(): no valid samples."); return sqrt(mom2_accum/num_samples - (mom1_accum/num_samples)*(mom1_accum/num_samples)); } /// Return the mean value_type mean() const { VW_ASSERT(num_samples, ArgumentErr() << "StdDevAccumulator(): no valid samples."); return mom1_accum / num_samples; } }; /// Compute the standard deviation of values in a fixed size list. /// - When a new value is added, the oldest value is removed from the statistics. /// - This implementation normalizes by num_samples, not num_samples - 1. class StdDevSlidingFunctor { public: /// Constructor set with the sliding window size. StdDevSlidingFunctor(const size_t max_size) : m_max_size(max_size), m_mean(0), m_squared(0) {} /// Implement push with the standard functor interface void operator()(double new_val) { push(new_val); } /// Add a new value and eject the oldest value. void push(double new_val) { // If we grew larger than the size limit remove the oldest value if (m_values.size() >= m_max_size) pop(); // Now incorporate the newest value m_values.push(new_val); // Record the new value double count = static_cast<double>(m_values.size()); // Update the statistics to add in the new value double delta = new_val - m_mean; m_mean += delta/count; double delta2 = new_val - m_mean; m_squared += delta*delta2; } /// Remove the oldest value void pop() { if (m_values.empty()) // Handle empty case return; double old_val = m_values.front(); double count = static_cast<double>(m_values.size()); m_values.pop(); // Update the statistics to account for removing the old value double shrunk_count = count - 1.0; double new_mean = (count*m_mean - old_val)/shrunk_count; m_squared -= (old_val - m_mean) * (old_val - new_mean); m_mean = new_mean; }; /// Compute the standard deviation of all current values. double get_std_dev() { double count = static_cast<double>(m_values.size()); if (count < 2.0) return 0; return sqrt(m_squared/count); } private: size_t m_max_size; ///< Max number of values to store. std::queue<double> m_values; ///< Store current values double m_mean; ///< Store the mean double m_squared; ///< Store sum of differences squared }; // End class StdDevSlidingFunctor } // namespace math // I'm not even really sure why the math namespace exists anymore.... -MDH using math::Accumulator; using math::MinMaxAccumulator; using math::MedianAccumulator; using math::MeanAccumulator; using math::StdDevAccumulator; using math::StdDevSlidingFunctor; } // namespace vw #endif // __VW_MATH_FUNCTORS_H__
38.146912
194
0.608665
0301c92e849653d52ad47dff88d36c09553e00ba
40
c
C
c-tools/io.c
iBug/USTC-RV-Chisel
e6c3b67c5d756a50903a80000276001acaa7fffe
[ "MIT" ]
8
2019-04-12T16:48:05.000Z
2022-01-07T15:45:49.000Z
c-tools/io.c
iBug/USTC-RV-Chisel
e6c3b67c5d756a50903a80000276001acaa7fffe
[ "MIT" ]
null
null
null
c-tools/io.c
iBug/USTC-RV-Chisel
e6c3b67c5d756a50903a80000276001acaa7fffe
[ "MIT" ]
1
2019-10-11T11:04:04.000Z
2019-10-11T11:04:04.000Z
#include "io.h" volatile struct IO io;
10
22
0.7
26db1e595c2831c77879af3b33e0ef33988245b8
750
h
C
NextEngine/include/graphics/rhi/rhi.h
CompilerLuke/NextEngine
aa1a8e9d9370bce004dba00854701597cab74989
[ "MIT" ]
1
2021-09-10T18:19:16.000Z
2021-09-10T18:19:16.000Z
NextEngine/include/graphics/rhi/rhi.h
CompilerLuke/NextEngine
aa1a8e9d9370bce004dba00854701597cab74989
[ "MIT" ]
null
null
null
NextEngine/include/graphics/rhi/rhi.h
CompilerLuke/NextEngine
aa1a8e9d9370bce004dba00854701597cab74989
[ "MIT" ]
2
2020-04-02T06:46:56.000Z
2021-06-17T16:47:57.000Z
#pragma once #include "device.h" #include "buffer.h" #include "frame_buffer.h" #include "pipeline.h" #include "primitives.h" struct RHI; struct BufferAllocator; struct AppInfo { const char* app_name; const char* engine_name; }; struct DeviceFeatures { bool sampler_anistropy = true; bool multi_draw_indirect = true; }; ENGINE_API void make_RHI(AppInfo& info, DeviceFeatures&); ENGINE_API void begin_gpu_upload(); ENGINE_API void end_gpu_upload(); ENGINE_API void queue_for_destruction(void*, void(*)(void*)); //may be worth using std::function instead ENGINE_API uint get_frame_index(); template<typename T> void queue_t_for_destruction(T data, void(*func)(T)) { queue_for_destruction(data, (void(*)(void*))func); } void destroy_RHI();
20.833333
104
0.757333
1856fba7e69e6928ad2ac60014faa6eacae8c2d0
11,897
h
C
generated/niscope/niscope_library_interface.h
amstewart/grpc-device
7afa3b171576a988d47f512f5b50556364c729f2
[ "MIT" ]
24
2021-03-25T18:37:59.000Z
2022-03-03T16:33:56.000Z
generated/niscope/niscope_library_interface.h
amstewart/grpc-device
7afa3b171576a988d47f512f5b50556364c729f2
[ "MIT" ]
129
2021-04-03T15:16:04.000Z
2022-03-25T21:48:18.000Z
generated/niscope/niscope_library_interface.h
amstewart/grpc-device
7afa3b171576a988d47f512f5b50556364c729f2
[ "MIT" ]
24
2021-03-31T12:36:14.000Z
2022-02-25T03:01:25.000Z
//--------------------------------------------------------------------- // This file is automatically generated. All manual edits will be lost. //--------------------------------------------------------------------- // Library wrapper for implementing interactions with NI-SCOPE //--------------------------------------------------------------------- #ifndef NISCOPE_GRPC_LIBRARY_WRAPPER_H #define NISCOPE_GRPC_LIBRARY_WRAPPER_H #include <grpcpp/grpcpp.h> #include <niScope.h> namespace niscope_grpc { class NiScopeLibraryInterface { public: virtual ~NiScopeLibraryInterface() {} virtual ViStatus Abort(ViSession vi) = 0; virtual ViStatus AcquisitionStatus(ViSession vi, ViInt32* acquisitionStatus) = 0; virtual ViStatus ActualMeasWfmSize(ViSession vi, ViInt32 arrayMeasFunction, ViInt32* measWaveformSize) = 0; virtual ViStatus ActualNumWfms(ViSession vi, ViConstString channelList, ViInt32* numWfms) = 0; virtual ViStatus ActualRecordLength(ViSession vi, ViInt32* recordLength) = 0; virtual ViStatus AddWaveformProcessing(ViSession vi, ViConstString channelList, ViInt32 measFunction) = 0; virtual ViStatus AdjustSampleClockRelativeDelay(ViSession vi, ViReal64 delay) = 0; virtual ViStatus AutoSetup(ViSession vi) = 0; virtual ViStatus CableSenseSignalStart(ViSession vi) = 0; virtual ViStatus CableSenseSignalStop(ViSession vi) = 0; virtual ViStatus CalSelfCalibrate(ViSession vi, ViConstString channelList, ViInt32 option) = 0; virtual ViStatus CheckAttributeViBoolean(ViSession vi, ViConstString channelList, ViAttr attributeId, ViBoolean value) = 0; virtual ViStatus CheckAttributeViInt32(ViSession vi, ViConstString channelList, ViAttr attributeId, ViInt32 value) = 0; virtual ViStatus CheckAttributeViInt64(ViSession vi, ViConstString channelList, ViAttr attributeId, ViInt64 value) = 0; virtual ViStatus CheckAttributeViReal64(ViSession vi, ViConstString channelList, ViAttr attributeId, ViReal64 value) = 0; virtual ViStatus CheckAttributeViSession(ViSession vi, ViConstString channelList, ViAttr attributeId, ViSession value) = 0; virtual ViStatus CheckAttributeViString(ViSession vi, ViConstString channelList, ViAttr attributeId, ViConstString value) = 0; virtual ViStatus ClearWaveformMeasurementStats(ViSession vi, ViConstString channelList, ViInt32 clearableMeasurementFunction) = 0; virtual ViStatus ClearWaveformProcessing(ViSession vi, ViConstString channelList) = 0; virtual ViStatus Close(ViSession vi) = 0; virtual ViStatus Commit(ViSession vi) = 0; virtual ViStatus ConfigureAcquisition(ViSession vi, ViInt32 acquisitionType) = 0; virtual ViStatus ConfigureChanCharacteristics(ViSession vi, ViConstString channelList, ViReal64 inputImpedance, ViReal64 maxInputFrequency) = 0; virtual ViStatus ConfigureClock(ViSession vi, ViConstString inputClockSource, ViConstString outputClockSource, ViConstString clockSyncPulseSource, ViBoolean masterEnabled) = 0; virtual ViStatus ConfigureEqualizationFilterCoefficients(ViSession vi, ViConstString channelList, ViInt32 numberOfCoefficients, ViReal64 coefficients[]) = 0; virtual ViStatus ConfigureHorizontalTiming(ViSession vi, ViReal64 minSampleRate, ViInt32 minNumPts, ViReal64 refPosition, ViInt32 numRecords, ViBoolean enforceRealtime) = 0; virtual ViStatus ConfigureTriggerDigital(ViSession vi, ViConstString triggerSource, ViInt32 slope, ViReal64 holdoff, ViReal64 delay) = 0; virtual ViStatus ConfigureTriggerEdge(ViSession vi, ViConstString triggerSource, ViReal64 level, ViInt32 slope, ViInt32 triggerCoupling, ViReal64 holdoff, ViReal64 delay) = 0; virtual ViStatus ConfigureTriggerGlitch(ViSession vi, ViConstString triggerSource, ViReal64 level, ViReal64 width, ViInt32 polarity, ViInt32 glitchCondition, ViInt32 triggerCoupling, ViReal64 holdoff, ViReal64 delay) = 0; virtual ViStatus ConfigureTriggerHysteresis(ViSession vi, ViConstString triggerSource, ViReal64 level, ViReal64 hysteresis, ViInt32 slope, ViInt32 triggerCoupling, ViReal64 holdoff, ViReal64 delay) = 0; virtual ViStatus ConfigureTriggerImmediate(ViSession vi) = 0; virtual ViStatus ConfigureTriggerRunt(ViSession vi, ViConstString triggerSource, ViReal64 lowThreshold, ViReal64 highThreshold, ViInt32 polarity, ViInt32 triggerCoupling, ViReal64 holdoff, ViReal64 delay) = 0; virtual ViStatus ConfigureTriggerSoftware(ViSession vi, ViReal64 holdoff, ViReal64 delay) = 0; virtual ViStatus ConfigureTriggerVideo(ViSession vi, ViConstString triggerSource, ViBoolean enableDcRestore, ViInt32 signalFormat, ViInt32 eventParameter, ViInt32 lineNumber, ViInt32 polarity, ViInt32 triggerCoupling, ViReal64 holdoff, ViReal64 delay) = 0; virtual ViStatus ConfigureTriggerWidth(ViSession vi, ViConstString triggerSource, ViReal64 level, ViReal64 lowThreshold, ViReal64 highThreshold, ViInt32 polarity, ViInt32 condition, ViInt32 triggerCoupling, ViReal64 holdoff, ViReal64 delay) = 0; virtual ViStatus ConfigureTriggerWindow(ViSession vi, ViConstString triggerSource, ViReal64 lowLevel, ViReal64 highLevel, ViInt32 windowMode, ViInt32 triggerCoupling, ViReal64 holdoff, ViReal64 delay) = 0; virtual ViStatus ConfigureVertical(ViSession vi, ViConstString channelList, ViReal64 range, ViReal64 offset, ViInt32 coupling, ViReal64 probeAttenuation, ViBoolean enabled) = 0; virtual ViStatus Disable(ViSession vi) = 0; virtual ViStatus ErrorHandler(ViSession vi, ViStatus errorCode, ViChar errorSource[642], ViChar errorDescription[642]) = 0; virtual ViStatus ExportAttributeConfigurationBuffer(ViSession vi, ViInt32 sizeInBytes, ViInt8 configuration[]) = 0; virtual ViStatus ExportAttributeConfigurationFile(ViSession vi, ViConstString filePath) = 0; virtual ViStatus ExportSignal(ViSession vi, ViInt32 signal, ViConstString signalIdentifier, ViConstString outputTerminal) = 0; virtual ViStatus Fetch(ViSession vi, ViConstString channelList, ViReal64 timeout, ViInt32 numSamples, ViReal64 waveform[], niScope_wfmInfo wfmInfo[]) = 0; virtual ViStatus FetchArrayMeasurement(ViSession vi, ViConstString channelList, ViReal64 timeout, ViInt32 arrayMeasFunction, ViInt32 measurementWaveformSize, ViReal64 measWfm[], niScope_wfmInfo wfmInfo[]) = 0; virtual ViStatus FetchBinary16(ViSession vi, ViConstString channelList, ViReal64 timeout, ViInt32 numSamples, ViInt16 waveform[], niScope_wfmInfo wfmInfo[]) = 0; virtual ViStatus FetchBinary32(ViSession vi, ViConstString channelList, ViReal64 timeout, ViInt32 numSamples, ViInt32 waveform[], niScope_wfmInfo wfmInfo[]) = 0; virtual ViStatus FetchBinary8(ViSession vi, ViConstString channelList, ViReal64 timeout, ViInt32 numSamples, ViInt8 waveform[], niScope_wfmInfo wfmInfo[]) = 0; virtual ViStatus FetchComplex(ViSession vi, ViConstString channelList, ViReal64 timeout, ViInt32 numSamples, NIComplexNumber_struct wfm[], niScope_wfmInfo wfmInfo[]) = 0; virtual ViStatus FetchComplexBinary16(ViSession vi, ViConstString channelList, ViReal64 timeout, ViInt32 numSamples, NIComplexI16_struct wfm[], niScope_wfmInfo wfmInfo[]) = 0; virtual ViStatus FetchMeasurement(ViSession vi, ViConstString channelList, ViReal64 timeout, ViInt32 scalarMeasFunction, ViReal64 result[]) = 0; virtual ViStatus FetchMeasurementStats(ViSession vi, ViConstString channelList, ViReal64 timeout, ViInt32 scalarMeasFunction, ViReal64 result[], ViReal64 mean[], ViReal64 stdev[], ViReal64 min[], ViReal64 max[], ViInt32 numInStats[]) = 0; virtual ViStatus GetAttributeViBoolean(ViSession vi, ViConstString channelList, ViAttr attributeId, ViBoolean* value) = 0; virtual ViStatus GetAttributeViInt32(ViSession vi, ViConstString channelList, ViAttr attributeId, ViInt32* value) = 0; virtual ViStatus GetAttributeViInt64(ViSession vi, ViConstString channelList, ViAttr attributeId, ViInt64* value) = 0; virtual ViStatus GetAttributeViReal64(ViSession vi, ViConstString channelList, ViAttr attributeId, ViReal64* value) = 0; virtual ViStatus GetAttributeViSession(ViSession vi, ViConstString channelList, ViAttr attributeId, ViSession* value) = 0; virtual ViStatus GetAttributeViString(ViSession vi, ViConstString channelList, ViAttr attributeId, ViInt32 bufSize, ViChar value[]) = 0; virtual ViStatus GetChannelName(ViSession vi, ViInt32 index, ViInt32 bufferSize, ViChar channelString[]) = 0; virtual ViStatus GetChannelNameFromString(ViSession vi, ViConstString index, ViInt32 bufferSize, ViChar name[]) = 0; virtual ViStatus GetEqualizationFilterCoefficients(ViSession vi, ViConstString channel, ViInt32 numberOfCoefficients, ViReal64 coefficients[]) = 0; virtual ViStatus GetError(ViSession vi, ViStatus* errorCode, ViInt32 bufferSize, ViChar description[]) = 0; virtual ViStatus GetErrorMessage(ViSession vi, ViStatus errorCode, ViInt32 bufferSize, ViChar errorMessage[]) = 0; virtual ViStatus GetFrequencyResponse(ViSession vi, ViConstString channel, ViInt32 bufferSize, ViReal64 frequencies[], ViReal64 amplitudes[], ViReal64 phases[], ViInt32* numberOfFrequencies) = 0; virtual ViStatus GetNormalizationCoefficients(ViSession vi, ViConstString channelList, ViInt32 bufferSize, niScope_coefficientInfo coefficientInfo[], ViInt32* numberOfCoefficientSets) = 0; virtual ViStatus GetScalingCoefficients(ViSession vi, ViConstString channelList, ViInt32 bufferSize, niScope_coefficientInfo coefficientInfo[], ViInt32* numberOfCoefficientSets) = 0; virtual ViStatus GetStreamEndpointHandle(ViSession vi, ViConstString streamName, ViUInt32* writerHandle) = 0; virtual ViStatus ImportAttributeConfigurationBuffer(ViSession vi, ViInt32 sizeInBytes, ViInt8 configuration[]) = 0; virtual ViStatus ImportAttributeConfigurationFile(ViSession vi, ViConstString filePath) = 0; virtual ViStatus Init(ViRsrc resourceName, ViBoolean idQuery, ViBoolean resetDevice, ViSession* vi) = 0; virtual ViStatus InitWithOptions(ViRsrc resourceName, ViBoolean idQuery, ViBoolean resetDevice, ViConstString optionString, ViSession* vi) = 0; virtual ViStatus InitiateAcquisition(ViSession vi) = 0; virtual ViStatus LockSession(ViSession vi, ViBoolean* callerHasLock) = 0; virtual ViStatus ProbeCompensationSignalStart(ViSession vi) = 0; virtual ViStatus ProbeCompensationSignalStop(ViSession vi) = 0; virtual ViStatus Read(ViSession vi, ViConstString channelList, ViReal64 timeout, ViInt32 numSamples, ViReal64 waveform[], niScope_wfmInfo wfmInfo[]) = 0; virtual ViStatus ReadMeasurement(ViSession vi, ViConstString channelList, ViReal64 timeout, ViInt32 scalarMeasFunction, ViReal64 result[]) = 0; virtual ViStatus Reset(ViSession vi) = 0; virtual ViStatus ResetDevice(ViSession vi) = 0; virtual ViStatus RevisionQuery(ViSession vi, ViChar driverRevision[256], ViChar firmwareRevision[256]) = 0; virtual ViStatus SampleMode(ViSession vi, ViInt32* sampleMode) = 0; virtual ViStatus SampleRate(ViSession vi, ViReal64* sampleRate) = 0; virtual ViStatus SelfTest(ViSession vi, ViInt16* selfTestResult, ViChar selfTestMessage[256]) = 0; virtual ViStatus SendSoftwareTriggerEdge(ViSession vi, ViInt32 whichTrigger) = 0; virtual ViStatus SetAttributeViBoolean(ViSession vi, ViConstString channelList, ViAttr attributeId, ViBoolean value) = 0; virtual ViStatus SetAttributeViInt32(ViSession vi, ViConstString channelList, ViAttr attributeId, ViInt32 value) = 0; virtual ViStatus SetAttributeViInt64(ViSession vi, ViConstString channelList, ViAttr attributeId, ViInt64 value) = 0; virtual ViStatus SetAttributeViReal64(ViSession vi, ViConstString channelList, ViAttr attributeId, ViReal64 value) = 0; virtual ViStatus SetAttributeViSession(ViSession vi, ViConstString channelList, ViAttr attributeId, ViSession value) = 0; virtual ViStatus SetAttributeViString(ViSession vi, ViConstString channelList, ViAttr attributeId, ViConstString value) = 0; virtual ViStatus UnlockSession(ViSession vi, ViBoolean* callerHasLock) = 0; }; } // namespace niscope_grpc #endif // NISCOPE_GRPC_LIBRARY_WRAPPER_H
106.223214
258
0.807178
185f868d71dc002818bf5f3c91451de64f7938a3
1,925
h
C
openvsx/libcommonutil/include/commonutil.h
openvcx/openvcx
cf6e6ba25b5d879943e993e415507650c7e30bc1
[ "Apache-2.0" ]
63
2015-06-25T00:53:12.000Z
2021-11-14T19:44:40.000Z
openvsx/libcommonutil/include/commonutil.h
ahmadmysra/openvcx
cf6e6ba25b5d879943e993e415507650c7e30bc1
[ "Apache-2.0" ]
3
2018-07-29T05:21:01.000Z
2019-10-25T06:37:01.000Z
openvsx/libcommonutil/include/commonutil.h
ahmadmysra/openvcx
cf6e6ba25b5d879943e993e415507650c7e30bc1
[ "Apache-2.0" ]
41
2015-09-02T12:15:43.000Z
2022-03-17T05:21:28.000Z
/** <!-- * * Copyright (C) 2014 OpenVCX openvcx@gmail.com * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * If you would like this software to be made available to you under an * alternate license please email openvcx@gmail.com for more information. * * --> */ #ifndef __COMMON_H__ #define __COMMON_H__ #include <stdlib.h> #include "logutil.h" #define CHAR_PRINTABLE(c) ((c) >= 32 && (c) < 127) #define CHAR_NUMERIC(c) ((c) >= '0' && (c) <= '9') int avc_istextchar(const unsigned char c); // replacement for isascii int avc_strip_nl(char *str, size_t sz, int stripws); char *avc_dequote(const char *p, char *buf, unsigned int szbuf); void *avc_calloc(size_t count, size_t size); void *avc_realloc(void *porig, size_t size); void *avc_recalloc(void *porig, size_t size, size_t size_orig); void avc_free(void **pp); void avc_dumpHex(void *fp, const unsigned char *buf, unsigned int len, int ascii); const char *avc_getPrintableDuration(unsigned long long duration, unsigned int timescale); const unsigned char *avc_binstrstr(const unsigned char *buf, unsigned int len, const unsigned char *needle, unsigned int lenneedle); int avc_isnumeric(const char *s); #endif // __COMMON_H__
37.019231
90
0.697143
6392073cb2ecb19129a73dda4902caf9f2629a94
32,588
h
C
mplayer/src/alsa-lib-1.1.9/src/pcm/plugin_ops.h
Minaduki-Shigure/BeagleBone_Proj
f6f66a4758f64515dcfd4f8d6cd02d02a5a0b35b
[ "MIT" ]
null
null
null
mplayer/src/alsa-lib-1.1.9/src/pcm/plugin_ops.h
Minaduki-Shigure/BeagleBone_Proj
f6f66a4758f64515dcfd4f8d6cd02d02a5a0b35b
[ "MIT" ]
1
2018-11-13T22:48:18.000Z
2018-11-13T22:48:18.000Z
mplayer/src/alsa-lib-1.1.9/src/pcm/plugin_ops.h
Minaduki-Shigure/BeagleBone_Proj
f6f66a4758f64515dcfd4f8d6cd02d02a5a0b35b
[ "MIT" ]
null
null
null
/* * Plugin sample operators with fast switch * Copyright (c) 2000 by Jaroslav Kysela <perex@perex.cz> * * * 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 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 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 * */ #ifndef SX_INLINES #define SX_INLINES static inline uint32_t sx20(uint32_t x) { if(x&0x00080000) return x|0xFFF00000; return x&0x000FFFFF; } static inline uint32_t sx24(uint32_t x) { if(x&0x00800000) return x|0xFF000000; return x&0x00FFFFFF; } static inline uint32_t sx24s(uint32_t x) { if(x&0x00008000) return x|0x000000FF; return x&0xFFFFFF00; } #endif #define as_u8(ptr) (*(uint8_t*)(ptr)) #define as_u16(ptr) (*(uint16_t*)(ptr)) #define as_u32(ptr) (*(uint32_t*)(ptr)) #define as_u64(ptr) (*(uint64_t*)(ptr)) #define as_s8(ptr) (*(int8_t*)(ptr)) #define as_s16(ptr) (*(int16_t*)(ptr)) #define as_s32(ptr) (*(int32_t*)(ptr)) #define as_s64(ptr) (*(int64_t*)(ptr)) #define as_float(ptr) (*(float_t*)(ptr)) #define as_double(ptr) (*(double_t*)(ptr)) #define as_u8c(ptr) (*(const uint8_t*)(ptr)) #define as_u16c(ptr) (*(const uint16_t*)(ptr)) #define as_u32c(ptr) (*(const uint32_t*)(ptr)) #define as_u64c(ptr) (*(const uint64_t*)(ptr)) #define as_s8c(ptr) (*(const int8_t*)(ptr)) #define as_s16c(ptr) (*(const int16_t*)(ptr)) #define as_s32c(ptr) (*(const int32_t*)(ptr)) #define as_s64c(ptr) (*(const int64_t*)(ptr)) #define as_floatc(ptr) (*(const float_t*)(ptr)) #define as_doublec(ptr) (*(const double_t*)(ptr)) #define _get_triple_le(ptr) (*(uint8_t*)(ptr) | (uint32_t)*((uint8_t*)(ptr) + 1) << 8 | (uint32_t)*((uint8_t*)(ptr) + 2) << 16) #define _get_triple_be(ptr) ((uint32_t)*(uint8_t*)(ptr) << 16 | (uint32_t)*((uint8_t*)(ptr) + 1) << 8 | *((uint8_t*)(ptr) + 2)) #define _put_triple_le(ptr,val) do { \ uint8_t *_tmp = (uint8_t *)(ptr); \ uint32_t _val = (val); \ _tmp[0] = _val; \ _tmp[1] = _val >> 8; \ _tmp[2] = _val >> 16; \ } while(0) #define _put_triple_be(ptr,val) do { \ uint8_t *_tmp = (uint8_t *)(ptr); \ uint32_t _val = (val); \ _tmp[0] = _val >> 16; \ _tmp[1] = _val >> 8; \ _tmp[2] = _val; \ } while(0) #ifdef SNDRV_LITTLE_ENDIAN #define _get_triple(ptr) _get_triple_le(ptr) #define _get_triple_s(ptr) _get_triple_be(ptr) #define _put_triple(ptr,val) _put_triple_le(ptr,val) #define _put_triple_s(ptr,val) _put_triple_be(ptr,val) #else #define _get_triple(ptr) _get_triple_be(ptr) #define _get_triple_s(ptr) _get_triple_le(ptr) #define _put_triple(ptr,val) _put_triple_be(ptr,val) #define _put_triple_s(ptr,val) _put_triple_le(ptr,val) #endif #ifdef CONV_LABELS /* src_wid src_endswap sign_toggle dst_wid dst_endswap */ static void *const conv_labels[4 * 2 * 2 * 4 * 2] = { &&conv_xxx1_xxx1, /* 8h -> 8h */ &&conv_xxx1_xxx1, /* 8h -> 8s */ &&conv_xxx1_xx10, /* 8h -> 16h */ &&conv_xxx1_xx01, /* 8h -> 16s */ &&conv_xxx1_x100, /* 8h -> 24h */ &&conv_xxx1_001x, /* 8h -> 24s */ &&conv_xxx1_1000, /* 8h -> 32h */ &&conv_xxx1_0001, /* 8h -> 32s */ &&conv_xxx1_xxx9, /* 8h ^> 8h */ &&conv_xxx1_xxx9, /* 8h ^> 8s */ &&conv_xxx1_xx90, /* 8h ^> 16h */ &&conv_xxx1_xx09, /* 8h ^> 16s */ &&conv_xxx1_x900, /* 8h ^> 24h */ &&conv_xxx1_009x, /* 8h ^> 24s */ &&conv_xxx1_9000, /* 8h ^> 32h */ &&conv_xxx1_0009, /* 8h ^> 32s */ &&conv_xxx1_xxx1, /* 8s -> 8h */ &&conv_xxx1_xxx1, /* 8s -> 8s */ &&conv_xxx1_xx10, /* 8s -> 16h */ &&conv_xxx1_xx01, /* 8s -> 16s */ &&conv_xxx1_x100, /* 8s -> 24h */ &&conv_xxx1_001x, /* 8s -> 24s */ &&conv_xxx1_1000, /* 8s -> 32h */ &&conv_xxx1_0001, /* 8s -> 32s */ &&conv_xxx1_xxx9, /* 8s ^> 8h */ &&conv_xxx1_xxx9, /* 8s ^> 8s */ &&conv_xxx1_xx90, /* 8s ^> 16h */ &&conv_xxx1_xx09, /* 8s ^> 16s */ &&conv_xxx1_x900, /* 8s ^> 24h */ &&conv_xxx1_009x, /* 8s ^> 24s */ &&conv_xxx1_9000, /* 8s ^> 32h */ &&conv_xxx1_0009, /* 8s ^> 32s */ &&conv_xx12_xxx1, /* 16h -> 8h */ &&conv_xx12_xxx1, /* 16h -> 8s */ &&conv_xx12_xx12, /* 16h -> 16h */ &&conv_xx12_xx21, /* 16h -> 16s */ &&conv_xx12_x120, /* 16h -> 24h */ &&conv_xx12_021x, /* 16h -> 24s */ &&conv_xx12_1200, /* 16h -> 32h */ &&conv_xx12_0021, /* 16h -> 32s */ &&conv_xx12_xxx9, /* 16h ^> 8h */ &&conv_xx12_xxx9, /* 16h ^> 8s */ &&conv_xx12_xx92, /* 16h ^> 16h */ &&conv_xx12_xx29, /* 16h ^> 16s */ &&conv_xx12_x920, /* 16h ^> 24h */ &&conv_xx12_029x, /* 16h ^> 24s */ &&conv_xx12_9200, /* 16h ^> 32h */ &&conv_xx12_0029, /* 16h ^> 32s */ &&conv_xx12_xxx2, /* 16s -> 8h */ &&conv_xx12_xxx2, /* 16s -> 8s */ &&conv_xx12_xx21, /* 16s -> 16h */ &&conv_xx12_xx12, /* 16s -> 16s */ &&conv_xx12_x210, /* 16s -> 24h */ &&conv_xx12_012x, /* 16s -> 24s */ &&conv_xx12_2100, /* 16s -> 32h */ &&conv_xx12_0012, /* 16s -> 32s */ &&conv_xx12_xxxA, /* 16s ^> 8h */ &&conv_xx12_xxxA, /* 16s ^> 8s */ &&conv_xx12_xxA1, /* 16s ^> 16h */ &&conv_xx12_xx1A, /* 16s ^> 16s */ &&conv_xx12_xA10, /* 16s ^> 24h */ &&conv_xx12_01Ax, /* 16s ^> 24s */ &&conv_xx12_A100, /* 16s ^> 32h */ &&conv_xx12_001A, /* 16s ^> 32s */ &&conv_x123_xxx1, /* 24h -> 8h */ &&conv_x123_xxx1, /* 24h -> 8s */ &&conv_x123_xx12, /* 24h -> 16h */ &&conv_x123_xx21, /* 24h -> 16s */ &&conv_x123_x123, /* 24h -> 24h */ &&conv_x123_321x, /* 24h -> 24s */ &&conv_x123_1230, /* 24h -> 32h */ &&conv_x123_0321, /* 24h -> 32s */ &&conv_x123_xxx9, /* 24h ^> 8h */ &&conv_x123_xxx9, /* 24h ^> 8s */ &&conv_x123_xx92, /* 24h ^> 16h */ &&conv_x123_xx29, /* 24h ^> 16s */ &&conv_x123_x923, /* 24h ^> 24h */ &&conv_x123_329x, /* 24h ^> 24s */ &&conv_x123_9230, /* 24h ^> 32h */ &&conv_x123_0329, /* 24h ^> 32s */ &&conv_123x_xxx3, /* 24s -> 8h */ &&conv_123x_xxx3, /* 24s -> 8s */ &&conv_123x_xx32, /* 24s -> 16h */ &&conv_123x_xx23, /* 24s -> 16s */ &&conv_123x_x321, /* 24s -> 24h */ &&conv_123x_123x, /* 24s -> 24s */ &&conv_123x_3210, /* 24s -> 32h */ &&conv_123x_0123, /* 24s -> 32s */ &&conv_123x_xxxB, /* 24s ^> 8h */ &&conv_123x_xxxB, /* 24s ^> 8s */ &&conv_123x_xxB2, /* 24s ^> 16h */ &&conv_123x_xx2B, /* 24s ^> 16s */ &&conv_123x_xB21, /* 24s ^> 24h */ &&conv_123x_12Bx, /* 24s ^> 24s */ &&conv_123x_B210, /* 24s ^> 32h */ &&conv_123x_012B, /* 24s ^> 32s */ &&conv_1234_xxx1, /* 32h -> 8h */ &&conv_1234_xxx1, /* 32h -> 8s */ &&conv_1234_xx12, /* 32h -> 16h */ &&conv_1234_xx21, /* 32h -> 16s */ &&conv_1234_x123, /* 32h -> 24h */ &&conv_1234_321x, /* 32h -> 24s */ &&conv_1234_1234, /* 32h -> 32h */ &&conv_1234_4321, /* 32h -> 32s */ &&conv_1234_xxx9, /* 32h ^> 8h */ &&conv_1234_xxx9, /* 32h ^> 8s */ &&conv_1234_xx92, /* 32h ^> 16h */ &&conv_1234_xx29, /* 32h ^> 16s */ &&conv_1234_x923, /* 32h ^> 24h */ &&conv_1234_329x, /* 32h ^> 24s */ &&conv_1234_9234, /* 32h ^> 32h */ &&conv_1234_4329, /* 32h ^> 32s */ &&conv_1234_xxx4, /* 32s -> 8h */ &&conv_1234_xxx4, /* 32s -> 8s */ &&conv_1234_xx43, /* 32s -> 16h */ &&conv_1234_xx34, /* 32s -> 16s */ &&conv_1234_x432, /* 32s -> 24h */ &&conv_1234_234x, /* 32s -> 24s */ &&conv_1234_4321, /* 32s -> 32h */ &&conv_1234_1234, /* 32s -> 32s */ &&conv_1234_xxxC, /* 32s ^> 8h */ &&conv_1234_xxxC, /* 32s ^> 8s */ &&conv_1234_xxC3, /* 32s ^> 16h */ &&conv_1234_xx3C, /* 32s ^> 16s */ &&conv_1234_xC32, /* 32s ^> 24h */ &&conv_1234_23Cx, /* 32s ^> 24s */ &&conv_1234_C321, /* 32s ^> 32h */ &&conv_1234_123C, /* 32s ^> 32s */ }; #endif #ifdef CONV_END while(0) { conv_xxx1_xxx1: as_u8(dst) = as_u8c(src); goto CONV_END; conv_xxx1_xx10: as_u16(dst) = (uint16_t)as_u8c(src) << 8; goto CONV_END; conv_xxx1_xx01: as_u16(dst) = (uint16_t)as_u8c(src); goto CONV_END; conv_xxx1_x100: as_u32(dst) = sx24((uint32_t)as_u8c(src) << 16); goto CONV_END; conv_xxx1_001x: as_u32(dst) = sx24s((uint32_t)as_u8c(src) << 8); goto CONV_END; conv_xxx1_1000: as_u32(dst) = (uint32_t)as_u8c(src) << 24; goto CONV_END; conv_xxx1_0001: as_u32(dst) = (uint32_t)as_u8c(src); goto CONV_END; conv_xxx1_xxx9: as_u8(dst) = as_u8c(src) ^ 0x80; goto CONV_END; conv_xxx1_xx90: as_u16(dst) = (uint16_t)(as_u8c(src) ^ 0x80) << 8; goto CONV_END; conv_xxx1_xx09: as_u16(dst) = (uint16_t)(as_u8c(src) ^ 0x80); goto CONV_END; conv_xxx1_x900: as_u32(dst) = sx24((uint32_t)(as_u8c(src) ^ 0x80) << 16); goto CONV_END; conv_xxx1_009x: as_u32(dst) = sx24s((uint32_t)(as_u8c(src) ^ 0x80) << 8); goto CONV_END; conv_xxx1_9000: as_u32(dst) = (uint32_t)(as_u8c(src) ^ 0x80) << 24; goto CONV_END; conv_xxx1_0009: as_u32(dst) = (uint32_t)(as_u8c(src) ^ 0x80); goto CONV_END; conv_xx12_xxx1: as_u8(dst) = as_u16c(src) >> 8; goto CONV_END; conv_xx12_xx12: as_u16(dst) = as_u16c(src); goto CONV_END; conv_xx12_xx21: as_u16(dst) = bswap_16(as_u16c(src)); goto CONV_END; conv_xx12_x120: as_u32(dst) = sx24((uint32_t)as_u16c(src) << 8); goto CONV_END; conv_xx12_021x: as_u32(dst) = sx24s((uint32_t)bswap_16(as_u16c(src)) << 8); goto CONV_END; conv_xx12_1200: as_u32(dst) = (uint32_t)as_u16c(src) << 16; goto CONV_END; conv_xx12_0021: as_u32(dst) = (uint32_t)bswap_16(as_u16c(src)); goto CONV_END; conv_xx12_xxx9: as_u8(dst) = (as_u16c(src) >> 8) ^ 0x80; goto CONV_END; conv_xx12_xx92: as_u16(dst) = as_u16c(src) ^ 0x8000; goto CONV_END; conv_xx12_xx29: as_u16(dst) = bswap_16(as_u16c(src)) ^ 0x80; goto CONV_END; conv_xx12_x920: as_u32(dst) = sx24((uint32_t)(as_u16c(src) ^ 0x8000) << 8); goto CONV_END; conv_xx12_029x: as_u32(dst) = sx24s((uint32_t)(bswap_16(as_u16c(src)) ^ 0x80) << 8); goto CONV_END; conv_xx12_9200: as_u32(dst) = (uint32_t)(as_u16c(src) ^ 0x8000) << 16; goto CONV_END; conv_xx12_0029: as_u32(dst) = (uint32_t)(bswap_16(as_u16c(src)) ^ 0x80); goto CONV_END; conv_xx12_xxx2: as_u8(dst) = as_u16c(src) & 0xff; goto CONV_END; conv_xx12_x210: as_u32(dst) = sx24((uint32_t)bswap_16(as_u16c(src)) << 8); goto CONV_END; conv_xx12_012x: as_u32(dst) = sx24s((uint32_t)as_u16c(src) << 8); goto CONV_END; conv_xx12_2100: as_u32(dst) = (uint32_t)bswap_16(as_u16c(src)) << 16; goto CONV_END; conv_xx12_0012: as_u32(dst) = (uint32_t)as_u16c(src); goto CONV_END; conv_xx12_xxxA: as_u8(dst) = (as_u16c(src) ^ 0x80) & 0xff; goto CONV_END; conv_xx12_xxA1: as_u16(dst) = bswap_16(as_u16c(src) ^ 0x80); goto CONV_END; conv_xx12_xx1A: as_u16(dst) = as_u16c(src) ^ 0x80; goto CONV_END; conv_xx12_xA10: as_u32(dst) = sx24((uint32_t)bswap_16(as_u16c(src) ^ 0x80) << 8); goto CONV_END; conv_xx12_01Ax: as_u32(dst) = sx24s((uint32_t)(as_u16c(src) ^ 0x80) << 8); goto CONV_END; conv_xx12_A100: as_u32(dst) = (uint32_t)bswap_16(as_u16c(src) ^ 0x80) << 16; goto CONV_END; conv_xx12_001A: as_u32(dst) = (uint32_t)(as_u16c(src) ^ 0x80); goto CONV_END; conv_x123_xxx1: as_u8(dst) = as_u32c(src) >> 16; goto CONV_END; conv_x123_xx12: as_u16(dst) = as_u32c(src) >> 8; goto CONV_END; conv_x123_xx21: as_u16(dst) = bswap_16(as_u32c(src) >> 8); goto CONV_END; conv_x123_x123: as_u32(dst) = sx24(as_u32c(src)); goto CONV_END; conv_x123_321x: as_u32(dst) = sx24s(bswap_32(as_u32c(src))); goto CONV_END; conv_x123_1230: as_u32(dst) = as_u32c(src) << 8; goto CONV_END; conv_x123_0321: as_u32(dst) = bswap_32(as_u32c(src)) >> 8; goto CONV_END; conv_x123_xxx9: as_u8(dst) = (as_u32c(src) >> 16) ^ 0x80; goto CONV_END; conv_x123_xx92: as_u16(dst) = (as_u32c(src) >> 8) ^ 0x8000; goto CONV_END; conv_x123_xx29: as_u16(dst) = bswap_16(as_u32c(src) >> 8) ^ 0x80; goto CONV_END; conv_x123_x923: as_u32(dst) = sx24(as_u32c(src) ^ 0x800000); goto CONV_END; conv_x123_329x: as_u32(dst) = sx24s(bswap_32(as_u32c(src)) ^ 0x8000); goto CONV_END; conv_x123_9230: as_u32(dst) = (as_u32c(src) ^ 0x800000) << 8; goto CONV_END; conv_x123_0329: as_u32(dst) = (bswap_32(as_u32c(src)) >> 8) ^ 0x80; goto CONV_END; conv_123x_xxx3: as_u8(dst) = (as_u32c(src) >> 8) & 0xff; goto CONV_END; conv_123x_xx32: as_u16(dst) = bswap_16(as_u32c(src) >> 8); goto CONV_END; conv_123x_xx23: as_u16(dst) = (as_u32c(src) >> 8) & 0xffff; goto CONV_END; conv_123x_x321: as_u32(dst) = sx24(bswap_32(as_u32c(src))); goto CONV_END; conv_123x_123x: as_u32(dst) = sx24s(as_u32c(src)); goto CONV_END; conv_123x_3210: as_u32(dst) = bswap_32(as_u32c(src)) << 8; goto CONV_END; conv_123x_0123: as_u32(dst) = as_u32c(src) >> 8; goto CONV_END; conv_123x_xxxB: as_u8(dst) = ((as_u32c(src) >> 8) & 0xff) ^ 0x80; goto CONV_END; conv_123x_xxB2: as_u16(dst) = bswap_16((as_u32c(src) >> 8) ^ 0x80); goto CONV_END; conv_123x_xx2B: as_u16(dst) = ((as_u32c(src) >> 8) & 0xffff) ^ 0x80; goto CONV_END; conv_123x_xB21: as_u32(dst) = sx24(bswap_32(as_u32c(src)) ^ 0x800000); goto CONV_END; conv_123x_12Bx: as_u32(dst) = sx24s(as_u32c(src) ^ 0x8000); goto CONV_END; conv_123x_B210: as_u32(dst) = bswap_32(as_u32c(src) ^ 0x8000) << 8; goto CONV_END; conv_123x_012B: as_u32(dst) = (as_u32c(src) >> 8) ^ 0x80; goto CONV_END; conv_1234_xxx1: as_u8(dst) = as_u32c(src) >> 24; goto CONV_END; conv_1234_xx12: as_u16(dst) = as_u32c(src) >> 16; goto CONV_END; conv_1234_xx21: as_u16(dst) = bswap_16(as_u32c(src) >> 16); goto CONV_END; conv_1234_x123: as_u32(dst) = sx24(as_u32c(src) >> 8); goto CONV_END; conv_1234_321x: as_u32(dst) = sx24s(bswap_32(as_u32c(src)) << 8); goto CONV_END; conv_1234_1234: as_u32(dst) = as_u32c(src); goto CONV_END; conv_1234_4321: as_u32(dst) = bswap_32(as_u32c(src)); goto CONV_END; conv_1234_xxx9: as_u8(dst) = (as_u32c(src) >> 24) ^ 0x80; goto CONV_END; conv_1234_xx92: as_u16(dst) = (as_u32c(src) >> 16) ^ 0x8000; goto CONV_END; conv_1234_xx29: as_u16(dst) = bswap_16(as_u32c(src) >> 16) ^ 0x80; goto CONV_END; conv_1234_x923: as_u32(dst) = sx24((as_u32c(src) >> 8) ^ 0x800000); goto CONV_END; conv_1234_329x: as_u32(dst) = sx24s((bswap_32(as_u32c(src)) ^ 0x80) << 8); goto CONV_END; conv_1234_9234: as_u32(dst) = as_u32c(src) ^ 0x80000000; goto CONV_END; conv_1234_4329: as_u32(dst) = bswap_32(as_u32c(src)) ^ 0x80; goto CONV_END; conv_1234_xxx4: as_u8(dst) = as_u32c(src) & 0xff; goto CONV_END; conv_1234_xx43: as_u16(dst) = bswap_16(as_u32c(src)); goto CONV_END; conv_1234_xx34: as_u16(dst) = as_u32c(src) & 0xffff; goto CONV_END; conv_1234_x432: as_u32(dst) = sx24(bswap_32(as_u32c(src)) >> 8); goto CONV_END; conv_1234_234x: as_u32(dst) = sx24s(as_u32c(src) << 8); goto CONV_END; conv_1234_xxxC: as_u8(dst) = (as_u32c(src) & 0xff) ^ 0x80; goto CONV_END; conv_1234_xxC3: as_u16(dst) = bswap_16(as_u32c(src) ^ 0x80); goto CONV_END; conv_1234_xx3C: as_u16(dst) = (as_u32c(src) & 0xffff) ^ 0x80; goto CONV_END; conv_1234_xC32: as_u32(dst) = sx24((bswap_32(as_u32c(src)) >> 8) ^ 0x800000); goto CONV_END; conv_1234_23Cx: as_u32(dst) = sx24s((as_u32c(src) ^ 0x80) << 8); goto CONV_END; conv_1234_C321: as_u32(dst) = bswap_32(as_u32c(src) ^ 0x80); goto CONV_END; conv_1234_123C: as_u32(dst) = as_u32c(src) ^ 0x80; goto CONV_END; } #endif #ifdef GET16_LABELS /* src_wid src_endswap sign_toggle */ static void *const get16_labels[5 * 2 * 2 + 4 * 3] = { &&get16_1_10, /* 8h -> 16h */ &&get16_1_90, /* 8h ^> 16h */ &&get16_1_10, /* 8s -> 16h */ &&get16_1_90, /* 8s ^> 16h */ &&get16_12_12, /* 16h -> 16h */ &&get16_12_92, /* 16h ^> 16h */ &&get16_12_21, /* 16s -> 16h */ &&get16_12_A1, /* 16s ^> 16h */ /* 4 byte formats */ &&get16_0123_12, /* 24h -> 16h */ &&get16_0123_92, /* 24h ^> 16h */ &&get16_1230_32, /* 24s -> 16h */ &&get16_1230_B2, /* 24s ^> 16h */ &&get16_1234_12, /* 32h -> 16h */ &&get16_1234_92, /* 32h ^> 16h */ &&get16_1234_43, /* 32s -> 16h */ &&get16_1234_C3, /* 32s ^> 16h */ &&get16_0123_12_20, /* 20h -> 16h */ &&get16_0123_92_20, /* 20h ^> 16h */ &&get16_1230_32_20, /* 20s -> 16h */ &&get16_1230_B2_20, /* 20s ^> 16h */ /* 3bytes format */ &&get16_123_12, /* 24h -> 16h */ &&get16_123_92, /* 24h ^> 16h */ &&get16_123_32, /* 24s -> 16h */ &&get16_123_B2, /* 24s ^> 16h */ &&get16_123_12_20, /* 20h -> 16h */ &&get16_123_92_20, /* 20h ^> 16h */ &&get16_123_32_20, /* 20s -> 16h */ &&get16_123_B2_20, /* 20s ^> 16h */ &&get16_123_12_18, /* 18h -> 16h */ &&get16_123_92_18, /* 18h ^> 16h */ &&get16_123_32_18, /* 18s -> 16h */ &&get16_123_B2_18, /* 18s ^> 16h */ }; #endif #ifdef GET16_END while(0) { get16_1_10: sample = (uint16_t)as_u8c(src) << 8; goto GET16_END; get16_1_90: sample = (uint16_t)(as_u8c(src) ^ 0x80) << 8; goto GET16_END; get16_12_12: sample = as_u16c(src); goto GET16_END; get16_12_92: sample = as_u16c(src) ^ 0x8000; goto GET16_END; get16_12_21: sample = bswap_16(as_u16c(src)); goto GET16_END; get16_12_A1: sample = bswap_16(as_u16c(src) ^ 0x80); goto GET16_END; get16_0123_12: sample = as_u32c(src) >> 8; goto GET16_END; get16_0123_92: sample = (as_u32c(src) >> 8) ^ 0x8000; goto GET16_END; get16_1230_32: sample = bswap_16(as_u32c(src) >> 8); goto GET16_END; get16_1230_B2: sample = bswap_16((as_u32c(src) >> 8) ^ 0x80); goto GET16_END; get16_1234_12: sample = as_u32c(src) >> 16; goto GET16_END; get16_1234_92: sample = (as_u32c(src) >> 16) ^ 0x8000; goto GET16_END; get16_1234_43: sample = bswap_16(as_u32c(src)); goto GET16_END; get16_1234_C3: sample = bswap_16(as_u32c(src) ^ 0x80); goto GET16_END; get16_0123_12_20: sample = as_u32c(src) >> 4; goto GET16_END; get16_0123_92_20: sample = (as_u32c(src) >> 4) ^ 0x8000; goto GET16_END; get16_1230_32_20: sample = bswap_32(as_u32c(src)) >> 4; goto GET16_END; get16_1230_B2_20: sample = (bswap_32(as_u32c(src)) >> 4) ^ 0x8000; goto GET16_END; get16_123_12: sample = _get_triple(src) >> 8; goto GET16_END; get16_123_92: sample = (_get_triple(src) >> 8) ^ 0x8000; goto GET16_END; get16_123_32: sample = _get_triple_s(src) >> 8; goto GET16_END; get16_123_B2: sample = (_get_triple_s(src) >> 8) ^ 0x8000; goto GET16_END; get16_123_12_20: sample = _get_triple(src) >> 4; goto GET16_END; get16_123_92_20: sample = (_get_triple(src) >> 4) ^ 0x8000; goto GET16_END; get16_123_32_20: sample = _get_triple_s(src) >> 4; goto GET16_END; get16_123_B2_20: sample = (_get_triple_s(src) >> 4) ^ 0x8000; goto GET16_END; get16_123_12_18: sample = _get_triple(src) >> 2; goto GET16_END; get16_123_92_18: sample = (_get_triple(src) >> 2) ^ 0x8000; goto GET16_END; get16_123_32_18: sample = _get_triple_s(src) >> 2; goto GET16_END; get16_123_B2_18: sample = (_get_triple_s(src) >> 2) ^ 0x8000; goto GET16_END; } #endif #ifdef PUT16_LABELS /* dst_wid dst_endswap sign_toggle */ static void *const put16_labels[5 * 2 * 2 + 4 * 3] = { &&put16_12_1, /* 16h -> 8h */ &&put16_12_9, /* 16h ^> 8h */ &&put16_12_1, /* 16h -> 8s */ &&put16_12_9, /* 16h ^> 8s */ &&put16_12_12, /* 16h -> 16h */ &&put16_12_92, /* 16h ^> 16h */ &&put16_12_21, /* 16h -> 16s */ &&put16_12_29, /* 16h ^> 16s */ /* 4 byte formats */ &&put16_12_0120, /* 16h -> 24h */ &&put16_12_0920, /* 16h ^> 24h */ &&put16_12_0210, /* 16h -> 24s */ &&put16_12_0290, /* 16h ^> 24s */ &&put16_12_1200, /* 16h -> 32h */ &&put16_12_9200, /* 16h ^> 32h */ &&put16_12_0021, /* 16h -> 32s */ &&put16_12_0029, /* 16h ^> 32s */ &&put16_12_0120_20, /* 16h -> 20h */ &&put16_12_0920_20, /* 16h ^> 20h */ &&put16_12_0210_20, /* 16h -> 20s */ &&put16_12_0290_20, /* 16h ^> 20s */ /* 3bytes format */ &&put16_12_120, /* 16h -> 24h */ &&put16_12_920, /* 16h ^> 24h */ &&put16_12_021, /* 16h -> 24s */ &&put16_12_029, /* 16h ^> 24s */ &&put16_12_120_20, /* 16h -> 20h */ &&put16_12_920_20, /* 16h ^> 20h */ &&put16_12_021_20, /* 16h -> 20s */ &&put16_12_029_20, /* 16h ^> 20s */ &&put16_12_120_18, /* 16h -> 18h */ &&put16_12_920_18, /* 16h ^> 18h */ &&put16_12_021_18, /* 16h -> 18s */ &&put16_12_029_18, /* 16h ^> 18s */ }; #endif #ifdef PUT16_END while (0) { put16_12_1: as_u8(dst) = sample >> 8; goto PUT16_END; put16_12_9: as_u8(dst) = (sample >> 8) ^ 0x80; goto PUT16_END; put16_12_12: as_u16(dst) = sample; goto PUT16_END; put16_12_92: as_u16(dst) = sample ^ 0x8000; goto PUT16_END; put16_12_21: as_u16(dst) = bswap_16(sample); goto PUT16_END; put16_12_29: as_u16(dst) = bswap_16(sample) ^ 0x80; goto PUT16_END; put16_12_0120: as_u32(dst) = sx24((uint32_t)sample << 8); goto PUT16_END; put16_12_0920: as_u32(dst) = sx24((uint32_t)(sample ^ 0x8000) << 8); goto PUT16_END; put16_12_0210: as_u32(dst) = sx24s((uint32_t)bswap_16(sample) << 8); goto PUT16_END; put16_12_0290: as_u32(dst) = sx24s((uint32_t)(bswap_16(sample) ^ 0x80) << 8); goto PUT16_END; put16_12_1200: as_u32(dst) = (uint32_t)sample << 16; goto PUT16_END; put16_12_9200: as_u32(dst) = (uint32_t)(sample ^ 0x8000) << 16; goto PUT16_END; put16_12_0021: as_u32(dst) = (uint32_t)bswap_16(sample); goto PUT16_END; put16_12_0029: as_u32(dst) = (uint32_t)bswap_16(sample) ^ 0x80; goto PUT16_END; put16_12_0120_20: as_u32(dst) = sx20((uint32_t)sample << 4); goto PUT16_END; put16_12_0920_20: as_u32(dst) = sx20((uint32_t)(sample ^ 0x8000) << 4); goto PUT16_END; put16_12_0210_20: as_u32(dst) = bswap_32(sx20((uint32_t)sample << 4)); goto PUT16_END; put16_12_0290_20: as_u32(dst) = bswap_32(sx20((uint32_t)(sample ^ 0x8000) << 4)); goto PUT16_END; put16_12_120: _put_triple(dst, (uint32_t)sample << 8); goto PUT16_END; put16_12_920: _put_triple(dst, (uint32_t)(sample ^ 0x8000) << 8); goto PUT16_END; put16_12_021: _put_triple_s(dst, (uint32_t)sample << 8); goto PUT16_END; put16_12_029: _put_triple_s(dst, (uint32_t)(sample ^ 0x8000) << 8); goto PUT16_END; put16_12_120_20: _put_triple(dst, (uint32_t)sample << 4); goto PUT16_END; put16_12_920_20: _put_triple(dst, (uint32_t)(sample ^ 0x8000) << 4); goto PUT16_END; put16_12_021_20: _put_triple_s(dst, (uint32_t)sample << 4); goto PUT16_END; put16_12_029_20: _put_triple_s(dst, (uint32_t)(sample ^ 0x8000) << 4); goto PUT16_END; put16_12_120_18: _put_triple(dst, (uint32_t)sample << 2); goto PUT16_END; put16_12_920_18: _put_triple(dst, (uint32_t)(sample ^ 0x8000) << 2); goto PUT16_END; put16_12_021_18: _put_triple_s(dst, (uint32_t)sample << 2); goto PUT16_END; put16_12_029_18: _put_triple_s(dst, (uint32_t)(sample ^ 0x8000) << 2); goto PUT16_END; } #endif #ifdef CONV24_LABELS #define GET32_LABELS #define PUT32_LABELS #endif #ifdef GET32_LABELS /* src_wid src_endswap sign_toggle */ static void *const get32_labels[5 * 2 * 2 + 4 * 3] = { &&get32_1_1000, /* 8h -> 32h */ &&get32_1_9000, /* 8h ^> 32h */ &&get32_1_1000, /* 8s -> 32h */ &&get32_1_9000, /* 8s ^> 32h */ &&get32_12_1200, /* 16h -> 32h */ &&get32_12_9200, /* 16h ^> 32h */ &&get32_12_2100, /* 16s -> 32h */ &&get32_12_A100, /* 16s ^> 32h */ /* 4 byte formats */ &&get32_0123_1230, /* 24h -> 32h */ &&get32_0123_9230, /* 24h ^> 32h */ &&get32_1230_3210, /* 24s -> 32h */ &&get32_1230_B210, /* 24s ^> 32h */ &&get32_1234_1234, /* 32h -> 32h */ &&get32_1234_9234, /* 32h ^> 32h */ &&get32_1234_4321, /* 32s -> 32h */ &&get32_1234_C321, /* 32s ^> 32h */ &&get32_0123_1230_20, /* 20h -> 32h */ &&get32_0123_9230_20, /* 20h ^> 32h */ &&get32_1230_3210_20, /* 20s -> 32h */ &&get32_1230_B210_20, /* 20s ^> 32h */ /* 3bytes format */ &&get32_123_1230, /* 24h -> 32h */ &&get32_123_9230, /* 24h ^> 32h */ &&get32_123_3210, /* 24s -> 32h */ &&get32_123_B210, /* 24s ^> 32h */ &&get32_123_1230_20, /* 20h -> 32h */ &&get32_123_9230_20, /* 20h ^> 32h */ &&get32_123_3210_20, /* 20s -> 32h */ &&get32_123_B210_20, /* 20s ^> 32h */ &&get32_123_1230_18, /* 18h -> 32h */ &&get32_123_9230_18, /* 18h ^> 32h */ &&get32_123_3210_18, /* 18s -> 32h */ &&get32_123_B210_18, /* 18s ^> 32h */ }; #endif #ifdef CONV24_END #define GET32_END __conv24_get #endif #ifdef GET32_END while (0) { get32_1_1000: sample = (uint32_t)as_u8c(src) << 24; goto GET32_END; get32_1_9000: sample = (uint32_t)(as_u8c(src) ^ 0x80) << 24; goto GET32_END; get32_12_1200: sample = (uint32_t)as_u16c(src) << 16; goto GET32_END; get32_12_9200: sample = (uint32_t)(as_u16c(src) ^ 0x8000) << 16; goto GET32_END; get32_12_2100: sample = (uint32_t)bswap_16(as_u16c(src)) << 16; goto GET32_END; get32_12_A100: sample = (uint32_t)bswap_16(as_u16c(src) ^ 0x80) << 16; goto GET32_END; get32_0123_1230: sample = as_u32c(src) << 8; goto GET32_END; get32_0123_9230: sample = (as_u32c(src) << 8) ^ 0x80000000; goto GET32_END; get32_1230_3210: sample = bswap_32(as_u32c(src) >> 8); goto GET32_END; get32_1230_B210: sample = bswap_32((as_u32c(src) >> 8) ^ 0x80); goto GET32_END; get32_1234_1234: sample = as_u32c(src); goto GET32_END; get32_1234_9234: sample = as_u32c(src) ^ 0x80000000; goto GET32_END; get32_1234_4321: sample = bswap_32(as_u32c(src)); goto GET32_END; get32_1234_C321: sample = bswap_32(as_u32c(src) ^ 0x80); goto GET32_END; get32_0123_1230_20: sample = as_u32c(src) << 12; goto GET32_END; get32_0123_9230_20: sample = (as_u32c(src) << 12) ^ 0x80000000; goto GET32_END; get32_1230_3210_20: sample = bswap_32(as_u32c(src)) << 12; goto GET32_END; get32_1230_B210_20: sample = (bswap_32(as_u32c(src)) << 12) ^ 0x80000000; goto GET32_END; get32_123_1230: sample = _get_triple(src) << 8; goto GET32_END; get32_123_9230: sample = (_get_triple(src) << 8) ^ 0x80000000; goto GET32_END; get32_123_3210: sample = _get_triple_s(src) << 8; goto GET32_END; get32_123_B210: sample = (_get_triple_s(src) << 8) ^ 0x80000000; goto GET32_END; get32_123_1230_20: sample = _get_triple(src) << 12; goto GET32_END; get32_123_9230_20: sample = (_get_triple(src) << 12) ^ 0x80000000; goto GET32_END; get32_123_3210_20: sample = _get_triple_s(src) << 12; goto GET32_END; get32_123_B210_20: sample = (_get_triple_s(src) << 12) ^ 0x80000000; goto GET32_END; get32_123_1230_18: sample = _get_triple(src) << 14; goto GET32_END; get32_123_9230_18: sample = (_get_triple(src) << 14) ^ 0x80000000; goto GET32_END; get32_123_3210_18: sample = _get_triple_s(src) << 14; goto GET32_END; get32_123_B210_18: sample = (_get_triple_s(src) << 14) ^ 0x80000000; goto GET32_END; } #endif #ifdef CONV24_END __conv24_get: goto *put; #define PUT32_END CONV24_END #endif #ifdef PUT32_LABELS /* dst_wid dst_endswap sign_toggle */ static void *const put32_labels[5 * 2 * 2 + 4 * 3] = { &&put32_1234_1, /* 32h -> 8h */ &&put32_1234_9, /* 32h ^> 8h */ &&put32_1234_1, /* 32h -> 8s */ &&put32_1234_9, /* 32h ^> 8s */ &&put32_1234_12, /* 32h -> 16h */ &&put32_1234_92, /* 32h ^> 16h */ &&put32_1234_21, /* 32h -> 16s */ &&put32_1234_29, /* 32h ^> 16s */ /* 4 byte formats */ &&put32_1234_0123, /* 32h -> 24h */ &&put32_1234_0923, /* 32h ^> 24h */ &&put32_1234_3210, /* 32h -> 24s */ &&put32_1234_3290, /* 32h ^> 24s */ &&put32_1234_1234, /* 32h -> 32h */ &&put32_1234_9234, /* 32h ^> 32h */ &&put32_1234_4321, /* 32h -> 32s */ &&put32_1234_4329, /* 32h ^> 32s */ &&put32_1234_0123_20, /* 32h -> 20h */ &&put32_1234_0923_20, /* 32h ^> 20h */ &&put32_1234_3210_20, /* 32h -> 20s */ &&put32_1234_3290_20, /* 32h ^> 20s */ /* 3bytes format */ &&put32_1234_123, /* 32h -> 24h */ &&put32_1234_923, /* 32h ^> 24h */ &&put32_1234_321, /* 32h -> 24s */ &&put32_1234_329, /* 32h ^> 24s */ &&put32_1234_123_20, /* 32h -> 20h */ &&put32_1234_923_20, /* 32h ^> 20h */ &&put32_1234_321_20, /* 32h -> 20s */ &&put32_1234_329_20, /* 32h ^> 20s */ &&put32_1234_123_18, /* 32h -> 18h */ &&put32_1234_923_18, /* 32h ^> 18h */ &&put32_1234_321_18, /* 32h -> 18s */ &&put32_1234_329_18, /* 32h ^> 18s */ }; #endif #ifdef CONV24_LABELS #undef GET32_LABELS #undef PUT32_LABELS #endif #ifdef PUT32_END while (0) { put32_1234_1: as_u8(dst) = sample >> 24; goto PUT32_END; put32_1234_9: as_u8(dst) = (sample >> 24) ^ 0x80; goto PUT32_END; put32_1234_12: as_u16(dst) = sample >> 16; goto PUT32_END; put32_1234_92: as_u16(dst) = (sample >> 16) ^ 0x8000; goto PUT32_END; put32_1234_21: as_u16(dst) = bswap_16(sample >> 16); goto PUT32_END; put32_1234_29: as_u16(dst) = bswap_16(sample >> 16) ^ 0x80; goto PUT32_END; put32_1234_0123: as_u32(dst) = sx24(sample >> 8); goto PUT32_END; put32_1234_0923: as_u32(dst) = sx24((sample >> 8) ^ 0x800000); goto PUT32_END; put32_1234_3210: as_u32(dst) = sx24s(bswap_32(sample) << 8); goto PUT32_END; put32_1234_3290: as_u32(dst) = sx24s((bswap_32(sample) ^ 0x80) << 8); goto PUT32_END; put32_1234_1234: as_u32(dst) = sample; goto PUT32_END; put32_1234_9234: as_u32(dst) = sample ^ 0x80000000; goto PUT32_END; put32_1234_4321: as_u32(dst) = bswap_32(sample); goto PUT32_END; put32_1234_4329: as_u32(dst) = bswap_32(sample) ^ 0x80; goto PUT32_END; put32_1234_0123_20: as_u32(dst) = sx20(sample >> 12); goto PUT32_END; put32_1234_0923_20: as_u32(dst) = sx20((sample ^ 0x80000000) >> 12); goto PUT32_END; put32_1234_3210_20: as_u32(dst) = bswap_32(sx20(sample >> 12)); goto PUT32_END; put32_1234_3290_20: as_u32(dst) = bswap_32(sx20((sample ^ 0x80000000) >> 12)); goto PUT32_END; put32_1234_123: _put_triple(dst, sample >> 8); goto PUT32_END; put32_1234_923: _put_triple(dst, (sample ^ 0x80000000) >> 8); goto PUT32_END; put32_1234_321: _put_triple_s(dst, sample >> 8); goto PUT32_END; put32_1234_329: _put_triple_s(dst, (sample ^ 0x80000000) >> 8); goto PUT32_END; put32_1234_123_20: _put_triple(dst, sample >> 12); goto PUT32_END; put32_1234_923_20: _put_triple(dst, (sample ^ 0x80000000) >> 12); goto PUT32_END; put32_1234_321_20: _put_triple_s(dst, sample >> 12); goto PUT32_END; put32_1234_329_20: _put_triple_s(dst, (sample ^ 0x80000000) >> 12); goto PUT32_END; put32_1234_123_18: _put_triple(dst, sample >> 14); goto PUT32_END; put32_1234_923_18: _put_triple(dst, (sample ^ 0x80000000) >> 14); goto PUT32_END; put32_1234_321_18: _put_triple_s(dst, sample >> 14); goto PUT32_END; put32_1234_329_18: _put_triple_s(dst, (sample ^ 0x80000000) >> 14); goto PUT32_END; } #endif #ifdef CONV24_END #undef GET32_END #undef PUT32_END #endif #ifdef PUT32F_LABELS /* type (0 = float, 1 = float64), endswap */ static void *const put32float_labels[2 * 2] = { &&put32f_1234_1234F, /* 32h -> (float)h */ &&put32f_1234_4321F, /* 32h -> (float)s */ &&put32f_1234_1234D, /* 32h -> (float64)h */ &&put32f_1234_4321D, /* 32h -> (float64)s */ }; #endif #ifdef PUT32F_END put32f_1234_1234F: as_float(dst) = (float_t)((int32_t)sample) / (float_t)0x80000000UL; goto PUT32F_END; put32f_1234_4321F: tmp_float.f = (float_t)((int32_t)sample) / (float_t)0x80000000UL; as_u32(dst) = bswap_32(tmp_float.i); goto PUT32F_END; put32f_1234_1234D: as_double(dst) = (double_t)((int32_t)sample) / (double_t)0x80000000UL; goto PUT32F_END; put32f_1234_4321D: tmp_double.d = (double_t)((int32_t)sample) / (double_t)0x80000000UL; as_u64(dst) = bswap_64(tmp_double.l); goto PUT32F_END; #endif #ifdef GET32F_LABELS /* type (0 = float, 1 = float64), endswap */ static void *const get32float_labels[2 * 2] = { &&get32f_1234F_1234, /* (float)h -> 32h */ &&get32f_4321F_1234, /* (float)s -> 32h */ &&get32f_1234D_1234, /* (float64)h -> 32h */ &&get32f_4321D_1234, /* (float64)s -> 32h */ }; #endif #ifdef GET32F_END get32f_1234F_1234: tmp_float.f = as_floatc(src); if (tmp_float.f >= 1.0) sample = 0x7fffffff; else if (tmp_float.f <= -1.0) sample = 0x80000000; else sample = (int32_t)(tmp_float.f * (float_t)0x80000000UL); goto GET32F_END; get32f_4321F_1234: tmp_float.i = bswap_32(as_u32c(src)); if (tmp_float.f >= 1.0) sample = 0x7fffffff; else if (tmp_float.f <= -1.0) sample = 0x80000000; else sample = (int32_t)(tmp_float.f * (float_t)0x80000000UL); goto GET32F_END; get32f_1234D_1234: tmp_double.d = as_doublec(src); if (tmp_double.d >= 1.0) sample = 0x7fffffff; else if (tmp_double.d <= -1.0) sample = 0x80000000; else sample = (int32_t)(tmp_double.d * (double_t)0x80000000UL); goto GET32F_END; get32f_4321D_1234: tmp_double.l = bswap_64(as_u64c(src)); if (tmp_double.d >= 1.0) sample = 0x7fffffff; else if (tmp_double.d <= -1.0) sample = 0x80000000; else sample = (int32_t)(tmp_double.d * (double_t)0x80000000UL); goto GET32F_END; #endif #undef as_u8 #undef as_u16 #undef as_u32 #undef as_s8 #undef as_s16 #undef as_s32 #undef as_float #undef as_double #undef as_u8c #undef as_u16c #undef as_u32c #undef as_s8c #undef as_s16c #undef as_s32c #undef as_floatc #undef as_doublec #undef _get_triple #undef _get_triple_s #undef _get_triple_le #undef _get_triple_be #undef _put_triple #undef _put_triple_s #undef _put_triple_le #undef _put_triple_be
43.860027
127
0.665767
e4677ad9b154d6c881d5d05ba8914cafa12137b8
2,876
h
C
samplecode/StrokeFilter/Source/StrokeFilterFlashController.h
shivendra14/AI_CC_2017_SDK_Win
e921f93bef0d73aa809bcda1bd6bbe2c0a4d28b2
[ "X11" ]
null
null
null
samplecode/StrokeFilter/Source/StrokeFilterFlashController.h
shivendra14/AI_CC_2017_SDK_Win
e921f93bef0d73aa809bcda1bd6bbe2c0a4d28b2
[ "X11" ]
null
null
null
samplecode/StrokeFilter/Source/StrokeFilterFlashController.h
shivendra14/AI_CC_2017_SDK_Win
e921f93bef0d73aa809bcda1bd6bbe2c0a4d28b2
[ "X11" ]
null
null
null
//======================================================================================== // // $File: //ai/ai15/devtech/sdk/public/samplecode/StrokeFilter/Source/StrokeFilterFlashController.h $ // // $Revision: #1 $ // // Copyright 2010 Adobe Systems Incorporated. All rights reserved. // // NOTICE: Adobe permits you to use, modify, and distribute this file in accordance // with the terms of the Adobe license agreement accompanying it. If you have received // this file from a source other than Adobe, then your use, modification, or // distribution of it requires the prior written permission of Adobe. // //======================================================================================== #ifndef __StrokeFilterFlashController_H__ #define __StrokeFilterFlashController_H__ #include "SDKPlugPlug.h" #include "StrokeFilters.h" #include "StrokeFileterParams.h" #include "FlashUIController.h" #include "StrokeFilterPlugin.h" /** StrokeFilterFlashController Controls data passing between the flash panel and StrokeFilter plug-in. */ extern StrokeFilterPlugin *gPlugin; class StrokeFilterFlashController : public FlashUIController { public: enum FilterType { kDashStroke = 0, kWaveStroke = 1 }; public: StrokeFilterFlashController(); /** Load the extension which opens the stroke filter flash panel dialog. */ AIErr DoFlashExtension(AIFilterMessage* pb, FilterType filter); /** Registers the events this plug-in will listen for with PlugPlug. @return error code if error found, or success otherwise. */ csxs::event::EventErrorCode RegisterCSXSEventListeners(); /** Removes the previously added event listeners from PlugPlug. @return error code if error found, or success otherwise. */ csxs::event::EventErrorCode RemoveEventListeners(); /** Send the current frame label values to the flash panel - values will either initialize the flash panel or populate it with values from current item, used by InitializeDialogFields. Data is constructed as an XML string before being sent. */ ASErr SendWaveData(); /** Send the current frame label values to the flash panel - values will either initialize the flash panel or populate it with values from current item, used by InitializeDialogFields. Data is constructed as an XML string before being sent. */ ASErr SendDashData(); void ParseDashData(const char* eventData); void ParseWaveData(const char* eventData); FilterType GetFilterType(); StrokeFileterParamsDash GetDashParams(); StrokeFileterParamsWave GetWaveParams(); ASErr SendData(){return kNoErr;}; void ParseData(const char* eventData){return ;}; private: FilterType filterType; // Dash variables StrokeFileterParamsDash dashParms; // Wave variables StrokeFileterParamsWave waveParms; StrokeFilters strokeFilters; }; #endif
29.346939
102
0.706885
e4afce3ab5bbdedd81a6add80facf2adedcea5c1
622
h
C
PrivateFrameworks/FMCore.framework/FMNanoIDSRequest.h
shaojiankui/iOS10-Runtime-Headers
6b0d842bed0c52c2a7c1464087b3081af7e10c43
[ "MIT" ]
36
2016-04-20T04:19:04.000Z
2018-10-08T04:12:25.000Z
PrivateFrameworks/FMCore.framework/FMNanoIDSRequest.h
shaojiankui/iOS10-Runtime-Headers
6b0d842bed0c52c2a7c1464087b3081af7e10c43
[ "MIT" ]
null
null
null
PrivateFrameworks/FMCore.framework/FMNanoIDSRequest.h
shaojiankui/iOS10-Runtime-Headers
6b0d842bed0c52c2a7c1464087b3081af7e10c43
[ "MIT" ]
10
2016-06-16T02:40:44.000Z
2019-01-15T03:31:45.000Z
/* Generated by RuntimeBrowser Image: /System/Library/PrivateFrameworks/FMCore.framework/FMCore */ @interface FMNanoIDSRequest : NSObject { NSString * _idsMessageID; id /* block */ _responseHandler; FMDispatchTimer * _timer; } @property (nonatomic, retain) NSString *idsMessageID; @property (nonatomic, copy) id /* block */ responseHandler; @property (nonatomic, retain) FMDispatchTimer *timer; - (void).cxx_destruct; - (id)idsMessageID; - (id /* block */)responseHandler; - (void)setIdsMessageID:(id)arg1; - (void)setResponseHandler:(id /* block */)arg1; - (void)setTimer:(id)arg1; - (id)timer; @end
25.916667
67
0.717042
a5ece05885182b106729192aefe9a43c47190e48
208
h
C
src/native/tch_include/TchTypedef.h
dudes-come/tchapp
24844869813edafff277e8c0ca6126d195423134
[ "MIT" ]
8
2016-11-08T08:56:58.000Z
2017-03-30T02:34:00.000Z
src/native/tch_include/TchTypedef.h
dudes-come/tchapp
24844869813edafff277e8c0ca6126d195423134
[ "MIT" ]
32
2016-11-08T10:22:08.000Z
2016-12-19T07:51:55.000Z
src/native/tch_include/TchTypedef.h
dudes-come/tchapp
24844869813edafff277e8c0ca6126d195423134
[ "MIT" ]
5
2016-11-08T08:57:02.000Z
2022-01-29T09:22:46.000Z
namespace Tnelab{ enum TchAppStartPosition { Manual, CenterScreen }; typedef struct { char* Url; TchAppStartPosition StartPosition; int X; int Y; int Width; int Height; }TchAppStartSettings; }
17.333333
51
0.730769
4f9b9b7e38b74c20ec396f38d3402e9c3a07cf36
964
c
C
C_course/Extra/structureFormulario.c
aMurryFly/Old_Courses
d5d105cbdcd3c4a35bf38fc60acfe76ce403bed3
[ "MIT" ]
null
null
null
C_course/Extra/structureFormulario.c
aMurryFly/Old_Courses
d5d105cbdcd3c4a35bf38fc60acfe76ce403bed3
[ "MIT" ]
null
null
null
C_course/Extra/structureFormulario.c
aMurryFly/Old_Courses
d5d105cbdcd3c4a35bf38fc60acfe76ce403bed3
[ "MIT" ]
null
null
null
#include<stdio.h> typedef struct//Agurpar muchas variables de diferentes tipos { char nombre[50]; char empleo[50]; int edad; }formulario; int main() { formulario f1, f2; printf("Introduce informaci%cn para el formulario 1: \n",162); printf("Introduzca su nombre: \n"); scanf(" %[^\n]",&f1.nombre); printf("Introduzca su empleo: \n"); scanf(" %[^\n]",&f1.empleo); printf("Introduzca su edad: \n"); scanf("%d",&f1.edad); printf("Introduce informaci%cn para el formulario 2: \n",162); printf("Introduzca su nombre: \n"); scanf(" %[^\n]",&f2.nombre); printf("Introduzca su empleo: \n"); scanf(" %[^\n]",&f2.empleo); printf("Introduzca su edad: \n"); scanf("%d",&f2.edad); printf("Formulario 1:\n"); printf("Nombre%s\nEmpleo:%s\nEdad:%d\n",f1.nombre,f1.empleo,f1.edad); printf("Formulario 2:\n"); printf("Nombre%s\nEmpleo:%s\nEdad:%d\n",f2.nombre,f2.empleo,f2.edad); getchar(); getchar(); return 0; }
26.054054
71
0.626556
4fac7ca72c6c231e6f3785aaae12c49e62dcd9c9
508
h
C
ConvenienceKitHaris/Classes/NSString+Attributed.h
haijun-suyan/ConvenienceKitHaris
3249814fc8b54d75758c094abada4a13130b9ea5
[ "MIT" ]
9
2020-12-11T02:19:59.000Z
2020-12-24T03:54:48.000Z
ConvenienceKitHaris/Classes/NSString+Attributed.h
haijun-suyan/ConvenienceKitHaris
3249814fc8b54d75758c094abada4a13130b9ea5
[ "MIT" ]
null
null
null
ConvenienceKitHaris/Classes/NSString+Attributed.h
haijun-suyan/ConvenienceKitHaris
3249814fc8b54d75758c094abada4a13130b9ea5
[ "MIT" ]
null
null
null
// // NSString+Attributed.h // SRCBBank // // Created by haijunyan on 2020/12/8. // Copyright © 2020 李培辉. All rights reserved. // #import <Foundation/Foundation.h> @interface NSString (Attributed) /** * 特征字符串 * * @return 返回特征字符串 */ + (NSAttributedString *)getAttributeWith:(id)sender string:(NSString *)string orginFont:(CGFloat)orginFont orginColor:(UIColor *)orginColor attributeFont:(CGFloat)attributeFont attributeColor:(UIColor *)attributeColor; @end
21.166667
67
0.677165
c49ba671c6ee98e0e2e1ac0072b0980ac6c234e4
2,614
c
C
src/main/osx_pthread_barrier.c
kyle-singer/aerospike-benchmark
5ac1c08d68a2d7883a9e831cd9fb264c4314bc04
[ "Apache-2.0" ]
9
2020-11-26T05:10:40.000Z
2022-03-09T15:57:42.000Z
src/main/osx_pthread_barrier.c
kyle-singer/aerospike-benchmark
5ac1c08d68a2d7883a9e831cd9fb264c4314bc04
[ "Apache-2.0" ]
26
2020-12-02T04:28:38.000Z
2021-12-08T20:17:25.000Z
src/main/osx_pthread_barrier.c
kyle-singer/aerospike-benchmark
5ac1c08d68a2d7883a9e831cd9fb264c4314bc04
[ "Apache-2.0" ]
8
2020-11-26T03:01:30.000Z
2022-01-06T22:40:28.000Z
#ifdef __APPLE__ #include <assert.h> #include <errno.h> #include <pthread.h> #include <osx_pthread_barrier.h> #define BARRIER_IN_THRESHOLD ((2147483647 * 2U + 1U) / 2) int32_t pthread_barrier_init(pthread_barrier_t* barrier, void* attr, uint32_t count) { // attr is not implemented assert(attr == NULL); if (count == 0 || count > BARRIER_IN_THRESHOLD) { return EINVAL; } pthread_cond_init(&barrier->cond, NULL); pthread_mutex_init(&barrier->lock, NULL); barrier->count = count; barrier->in = 0; barrier->current_round = 0; return 0; } int32_t pthread_barrier_destroy(pthread_barrier_t* barrier) { pthread_cond_destroy(&barrier->cond); pthread_mutex_destroy(&barrier->lock); return 0; } int32_t pthread_barrier_wait(pthread_barrier_t* barrier) { // read the current round before incrementing the in variable, since we // require that current round be correct, and incrementing in before reading // current_round would induce a race uint32_t round = __atomic_load_n(&barrier->current_round, __ATOMIC_ACQUIRE); // increment the in variable with relaxed memory ordering since this is the // only modification we've made to memory uint32_t i = __atomic_add_fetch(&barrier->in, 1, __ATOMIC_RELAXED); uint32_t count = barrier->count; if (i < count) { // acquire the condition lock before reading cur_round, since we don't // want the broadcast signal to be sent before waiting on the condition // variable pthread_mutex_lock(&barrier->lock); // read the current round before waiting on the condition variable uint32_t cur_round = __atomic_load_n(&barrier->current_round, __ATOMIC_ACQUIRE); while (cur_round == round) { pthread_cond_wait(&barrier->cond, &barrier->lock); cur_round = __atomic_load_n(&barrier->current_round, __ATOMIC_ACQUIRE); } pthread_mutex_unlock(&barrier->lock); } else { // reset the in-thread count to zero, preventing any of the other // threads at the barrier from leaving before the round is incremented __atomic_store_n(&barrier->in, 0, __ATOMIC_RELAXED); // go to the next round, allowing all other threads waiting at the // barrier to leave. At this point, the state of the barrier is // completely reset __atomic_store_n(&barrier->current_round, round + 1, __ATOMIC_RELEASE); // acquire the condition lock so no thread can wait after checking the // condition and after the broadcast wakeup is executed pthread_mutex_lock(&barrier->lock); pthread_cond_broadcast(&barrier->cond); pthread_mutex_unlock(&barrier->lock); return PTHREAD_BARRIER_SERIAL_THREAD; } return 0; } #endif /* __APPLE__ */
28.725275
77
0.748279
8f7f8636e5ae8adde897f49077ccd98cb20e8891
6,500
h
C
include/dai/hak.h
hyunsukimsokcho/libdai
52c0b51823724f02c7a268e6af6db72dc3324385
[ "BSD-2-Clause" ]
11
2018-01-31T16:14:28.000Z
2021-06-22T03:45:11.000Z
include/dai/hak.h
flurischt/libDAI
20683a222e2ef307209290f79081fe428d9c5050
[ "BSD-2-Clause" ]
1
2019-05-25T08:20:58.000Z
2020-02-17T10:58:55.000Z
include/dai/hak.h
flurischt/libDAI
20683a222e2ef307209290f79081fe428d9c5050
[ "BSD-2-Clause" ]
3
2018-12-13T11:49:22.000Z
2021-12-31T03:19:26.000Z
/* This file is part of libDAI - http://www.libdai.org/ * * Copyright (c) 2006-2011, The libDAI authors. All rights reserved. * * Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ /// \file /// \brief Defines class HAK, which implements a variant of Generalized Belief Propagation. /// \idea Implement more general region graphs and corresponding Generalized Belief Propagation updates as described in [\ref YFW05]. /// \todo Use ClusterGraph instead of a vector<VarSet> for speed. /// \todo Optimize this code for large factor graphs. /// \todo Implement GBP parent-child algorithm. #include <dai/dai_config.h> #ifdef DAI_WITH_HAK #ifndef __defined_libdai_hak_h #define __defined_libdai_hak_h #include <string> #include <dai/daialg.h> #include <dai/regiongraph.h> #include <dai/enum.h> #include <dai/properties.h> namespace dai { /// Approximate inference algorithm: implementation of single-loop ("Generalized Belief Propagation") and double-loop algorithms by Heskes, Albers and Kappen [\ref HAK03] class HAK : public DAIAlgRG { private: /// Outer region beliefs std::vector<Factor> _Qa; /// Inner region beliefs std::vector<Factor> _Qb; /// Messages from outer to inner regions std::vector<std::vector<Factor> > _muab; /// Messages from inner to outer regions std::vector<std::vector<Factor> > _muba; /// Maximum difference encountered so far Real _maxdiff; /// Number of iterations needed size_t _iters; public: /// Parameters for HAK struct Properties { /// Enumeration of possible cluster choices /** The following cluster choices are defined: * - MIN minimal clusters, i.e., one outer region for each maximal factor * - DELTA one outer region for each variable and its Markov blanket * - LOOP one cluster for each loop of length at most \a Properties::loopdepth, and in addition one cluster for each maximal factor * - BETHE Bethe approximation (one outer region for each maximal factor, inner regions are single variables) */ DAI_ENUM(ClustersType,MIN,BETHE,DELTA,LOOP); /// Enumeration of possible message initializations DAI_ENUM(InitType,UNIFORM,RANDOM); /// Verbosity (amount of output sent to stderr) size_t verbose; /// Maximum number of iterations size_t maxiter; /// Maximum time (in seconds) double maxtime; /// Tolerance for convergence test Real tol; /// Damping constant (0.0 means no damping, 1.0 is maximum damping) Real damping; /// How to choose the outer regions ClustersType clusters; /// How to initialize the messages InitType init; /// Use single-loop (GBP) or double-loop (HAK) bool doubleloop; /// Depth of loops (only relevant for \a clusters == \c ClustersType::LOOP) size_t loopdepth; } props; public: /// \name Constructors/destructors //@{ /// Default constructor HAK() : DAIAlgRG(), _Qa(), _Qb(), _muab(), _muba(), _maxdiff(0.0), _iters(0U), props() {} /// Construct from FactorGraph \a fg and PropertySet \a opts /** \param fg Factor graph. * \param opts Parameters @see Properties */ HAK( const FactorGraph &fg, const PropertySet &opts ); /// Construct from RegionGraph \a rg and PropertySet \a opts HAK( const RegionGraph &rg, const PropertySet &opts ); //@} /// \name General InfAlg interface //@{ virtual HAK* clone() const { return new HAK(*this); } virtual HAK* construct( const FactorGraph &fg, const PropertySet &opts ) const { return new HAK( fg, opts ); } virtual std::string name() const { return "HAK"; } virtual Factor belief( const VarSet &vs ) const; virtual std::vector<Factor> beliefs() const; virtual Real logZ() const; virtual void init(); virtual void init( const VarSet &vs ); virtual Real run(); virtual Real maxDiff() const { return _maxdiff; } virtual size_t Iterations() const { return _iters; } virtual void setMaxIter( size_t maxiter ) { props.maxiter = maxiter; } virtual void setProperties( const PropertySet &opts ); virtual PropertySet getProperties() const; virtual std::string printProperties() const; //@} /// \name Additional interface specific for HAK //@{ /// Returns reference to message from outer region \a alpha to its \a _beta 'th neighboring inner region Factor & muab( size_t alpha, size_t _beta ) { return _muab[alpha][_beta]; } /// Returns reference to message the \a _beta 'th neighboring inner region of outer region \a alpha to that outer region Factor & muba( size_t alpha, size_t _beta ) { return _muba[alpha][_beta]; } /// Returns belief of outer region \a alpha const Factor& Qa( size_t alpha ) const { return _Qa[alpha]; }; /// Returns belief of inner region \a beta const Factor& Qb( size_t beta ) const { return _Qb[beta]; }; /// Runs single-loop algorithm (algorithm 1 in [\ref HAK03]) Real doGBP(); /// Runs double-loop algorithm (as described in section 4.2 of [\ref HAK03]), which always convergences Real doDoubleLoop(); //@} private: /// Helper function for constructors void construct(); /// Recursive procedure for finding clusters of variables containing loops of length at most \a length /** \param fg the factor graph * \param allcl the clusters found so far * \param newcl partial candidate cluster * \param root start (and end) point of the loop * \param length number of variables that may be added to \a newcl * \param vars neighboring variables of \a newcl * \return allcl all clusters of variables with loops of length at most \a length passing through root */ void findLoopClusters( const FactorGraph &fg, std::set<VarSet> &allcl, VarSet newcl, const Var & root, size_t length, VarSet vars ); }; } // end of namespace dai #endif #endif
38.011696
170
0.629231
8f8f865cd2da7caae300408401ecc0be713bb7e9
8,139
h
C
include/ossim/support_data/ossimSrcRecord.h
vladislav-horbatiuk/ossim
82417ad868fac022672335e1684bdd91d662c18c
[ "MIT" ]
251
2015-10-20T09:08:11.000Z
2022-03-22T18:16:38.000Z
include/ossim/support_data/ossimSrcRecord.h
vladislav-horbatiuk/ossim
82417ad868fac022672335e1684bdd91d662c18c
[ "MIT" ]
73
2015-11-02T17:12:36.000Z
2021-11-15T17:41:47.000Z
include/ossim/support_data/ossimSrcRecord.h
vladislav-horbatiuk/ossim
82417ad868fac022672335e1684bdd91d662c18c
[ "MIT" ]
146
2015-10-15T16:00:15.000Z
2022-03-22T12:37:14.000Z
//************************************************************************************************* // OSSIM -- Open Source Software Image Map // // LICENSE: See top level LICENSE.txt file. // AUTHOR: Oscar Kramer // //************************************************************************************************* // $Id: ossimSrcRecord.h 2788 2011-06-29 13:20:37Z oscar.kramer $ #ifndef ossimSrcRecord_HEADER #define ossimSrcRecord_HEADER #include <ossim/base/ossimConstants.h> #include <ossim/base/ossimCommon.h> #include <ossim/base/ossimString.h> #include <ossim/base/ossimFilename.h> #include <ossim/base/ossimKeywordlist.h> #include <vector> //************************************************************************************************* // CLASS DESCRIPTION: //! Class used for parsing the command line *.src files. This is a scheme for providing input //! file information to am ossim app such as ossim-orthoigen. //! //! The following keywords with image prefixes as shown are considered: //! //! image0.file: <image_filename> //! image0.entry: <image_index_in_multi_image_file> (unsigned integer) //! image0.ovr: <full/path/to/overview_file.ovr> //! image0.hist: <full/path/to/histogram.his> //! image0.hist-op: auto-minmax | std-stretch N (N=1|2|3) //! image0.support: <path_to_support_files> //! image0.rgb: R,G,B (unsigned integers starting with 1) //! image0.mask: <filename> //! image0.opacity: <double> //! image0.replacement_mode: <REPLACE_BAND_IF_TARGET | //! REPLACE_BAND_IF_PARTIAL_TARGET | //! REPLACE_ALL_BANDS_IF_ANY_TARGET | //! REPLACE_ALL_BANDS_IF_PARTIAL_TARGET | //! REPLACE_ONLY_FULL_TARGETS> //! image0.clamp.min: <double> //! image0.clamp.max: <double> //! image0.clip.min: <double> //! image0.clip.max: <double> //! //! vector0.file: <image_filename> //! vector0.entry: <image_index_in_multi_image_file> (unsigned integer) //! vector0.query: <select query> //! vector0.line.color: <R, G, B> (255,255,255) //! vector0.line.width: <line width> (unsigned integer) //! vector0.fill.color: <R, G, B> (255,0,0) //! vector0.fill.opacity: <opacity> (unsigned integer) //! //! //! The "support" keyword can be specified in lieu of "ovr" and "hist" when the latter reside in //! the same external directory. This directory can also contain external image geometry files. //! If a support dir is provided without an ovr or hist specification, then default filenames are //! derived from the image filename, but with the support dir as the path. //! //! Multiple files can be specified by incrementing the prefix image index. //! //************************************************************************************************* class OSSIM_DLL ossimSrcRecord { public: struct PixelFlipParams { public: PixelFlipParams() : replacementMode(""), clampMin(ossim::nan()), clampMax(ossim::nan()), clipMin(ossim::nan()), clipMax(ossim::nan()) {} ossimString replacementMode; double clampMin; double clampMax; double clipMin; double clipMax; }; ossimSrcRecord(); //! Constructs given an in-memory KWL and record index. ossimSrcRecord(const ossimKeywordlist& kwl, ossim_uint32 index=0, ossimString prefix_str="image"); //! @brief Initializes record from an in-memory KWL and prefix. //! //! "prefix.file" e.g. "image0.file" is required. All other data members will be cleared //! if their keword is not present. // //! @param kwl Keyword list containing one or more records. //! @param prefix Like "image0." //! @return true on success, false if required keyword is not set. bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); //! Returns TRUE if record is valid. bool valid() const { return !m_filename.empty(); } const ossimFilename& getFilename() const { return m_filename; } ossim_int32 getEntryIndex() const { return m_entryIndex; } const ossimFilename& getSupportDir() const { return m_supportDir;} const ossimString& getHistogramOp() const { return m_histogramOp;} const std::vector<ossim_uint32>& getBands() const { return m_bandList; } const double& getWeight() const { return m_weight; } const double& getGamma() const { return m_gamma; } const double& getAutoMinMaxBiasFactory() const { return m_autoMinMaxBiasFactor; } const PixelFlipParams& getPixelFlipParams() const { return m_pixelFlipParams; } //! See note below on these data members. const ossimFilename& getOverviewPath() const { return m_overviewPath; } const ossimFilename& getHistogramPath() const { return m_histogramPath; } const ossimFilename& getMaskPath() const { return m_maskPath; } const ossimFilename& getGeomPath() const { return m_geomPath; } void setFilename(const ossimFilename& f); void setEntryIndex(ossim_int32 i); void setOverview(const ossimFilename& f); void setMask(const ossimFilename& f) { m_maskPath = f; } void setHistogram(const ossimFilename& f) { m_histogramPath = f; } void setHistogramOp(const ossimString& s) { m_histogramOp = s; } void setGeom(const ossimFilename& f); void setBands(const std::vector<ossim_uint32>& v) { m_bandList = v; } void setWeight(const double& weight) { m_weight = weight; } void setRgbDataBool(bool isRgbData) { m_isRgbData = isRgbData; } void setGamma(const double& gamma) { m_gamma = gamma; } void getAutoMinMaxBiasFactory(const double& autoMinMaxBiasFactor) { m_autoMinMaxBiasFactor = autoMinMaxBiasFactor; } //! Sets supplementary data files dir. If the OVR and/or hist dirs are undefined, they are also //! set to this path. void setSupportDir(const ossimFilename& f); //! Returns TRUE if the record represents a vector data set: bool isVectorData() const { return m_isVectorData; } //! Returns TRUE if the record represents an rgb data set: bool isRgbData() const { return m_isRgbData; } ossimFilename getRgbFilename (int band) const { return m_rgbFilenames[band]; } ossimFilename getRgbHistogramPath(int band) const { return m_rgbHistogramPaths[band]; } ossimString getRgbHistogramOp (int band) const { return m_rgbHistogramOps[band]; } ossimFilename getRgbOverviewPath (int band) const { return m_rgbOverviewPaths[band]; } //! Returns the KWL containing the desired vector representation properties. In the future we //! should stuff many of the members in ossimSrcRecord in a KWL (similar to what is currently //! done with vector properties) so that the handler is initialized via loadState() instead of //! individual calls to set methods. OLK 10/10 const ossimKeywordlist& getAttributesKwl() const { return m_attributesKwl; } private: ossimFilename m_filename; ossim_int32 m_entryIndex; ossimFilename m_supportDir; std::vector<ossim_uint32> m_bandList; ossimString m_histogramOp; double m_autoMinMaxBiasFactor; double m_weight; //! The following data members are usually just a copy of m_supportDir, but are provided in //! order to support legacy systems where paths to OVR, thumbnails and histogram files ossimFilename m_overviewPath; ossimFilename m_histogramPath; ossimFilename m_maskPath; ossimFilename m_geomPath; //! The following data members allow users to render vector data bool m_isVectorData; ossimKeywordlist m_attributesKwl; std::vector<ossimString> m_rgbFilenames; std::vector<ossimString> m_rgbHistogramPaths; std::vector<ossimString> m_rgbHistogramOps; std::vector<ossimString> m_rgbOverviewPaths; bool m_isRgbData; PixelFlipParams m_pixelFlipParams; double m_gamma; }; #endif
45.983051
119
0.647991
eb412138e41ea156f4416b001fed192f8a5a7ba7
540
h
C
CodeInputView/CodeInputView.h
eastsss/CodeInputView
2956c036417c895a12ba6db9021de7d715a6e004
[ "MIT" ]
1
2018-01-01T17:00:11.000Z
2018-01-01T17:00:11.000Z
CodeInputView/CodeInputView.h
eastsss/CodeInputView
2956c036417c895a12ba6db9021de7d715a6e004
[ "MIT" ]
null
null
null
CodeInputView/CodeInputView.h
eastsss/CodeInputView
2956c036417c895a12ba6db9021de7d715a6e004
[ "MIT" ]
null
null
null
// // CodeInputView.h // CodeInputView // // Created by Anatoliy Radchenko on 26/07/2017. // Copyright © 2017 Anatoliy Radchenko. All rights reserved. // #import <UIKit/UIKit.h> //! Project version number for CodeInputView. FOUNDATION_EXPORT double CodeInputViewVersionNumber; //! Project version string for CodeInputView. FOUNDATION_EXPORT const unsigned char CodeInputViewVersionString[]; // In this header, you should import all the public headers of your framework using statements like #import <CodeInputView/PublicHeader.h>
27
138
0.777778
ac216d42943be2e692fa8b6a8282242e13be1510
711
h
C
Utilities/GameUtils/GameUtils.h
mym2o/HavokDemos
1235b96b93e256de50bc36c229439a334410fd77
[ "MIT" ]
1
2017-08-14T10:23:45.000Z
2017-08-14T10:23:45.000Z
Utilities/GameUtils/GameUtils.h
mym2o/HavokDemos
1235b96b93e256de50bc36c229439a334410fd77
[ "MIT" ]
null
null
null
Utilities/GameUtils/GameUtils.h
mym2o/HavokDemos
1235b96b93e256de50bc36c229439a334410fd77
[ "MIT" ]
2
2016-06-22T02:22:32.000Z
2019-11-21T19:49:41.000Z
#pragma once #include <Common\Base\hkBase.h> #include <Physics2012\Dynamics\World\hkpWorld.h> #include <Physics2012\Dynamics\Entity\hkpRigidBody.h> #include <Physics2012\Collide\Shape\Convex\Box\hkpBoxShape.h> #include <Physics2012\Utilities\Dynamics\Inertia\hkpInertiaTensorComputer.h> class GameUtils { public: //Create a fixed rigid body made with a hkpBoxShape static void createStaticBox(hkpWorld* world, float centerX, float centerY, float centerZ, float radiusX, float radiusY, float radiusZ); //This is just a user function to help create a box in one line static hkpRigidBody* createBox(const hkVector4& size, const hkReal mass, const hkVector4& position, hkReal radius = 0.0); };
44.4375
137
0.776371
16753480a19f52d9e6543ca8783cbf2ad453b48c
484
h
C
Development/Games/Test_Game1/PrintRoutine.h
AaronAppel/QwerkE_Engine
662a4386b5068066b9139ea24e3c7fb14ed3177d
[ "BSD-3-Clause" ]
1
2018-03-31T18:16:43.000Z
2018-03-31T18:16:43.000Z
Development/Games/Test_Game1/PrintRoutine.h
AaronAppel/QwerkE_Engine
662a4386b5068066b9139ea24e3c7fb14ed3177d
[ "BSD-3-Clause" ]
null
null
null
Development/Games/Test_Game1/PrintRoutine.h
AaronAppel/QwerkE_Engine
662a4386b5068066b9139ea24e3c7fb14ed3177d
[ "BSD-3-Clause" ]
null
null
null
#ifndef _PrintRoutine_H_ #define _PrintRoutine_H_ #include "../../../QwerkE_Framework/Source/Core/Scenes/Entities/Routines/Routine.h" #include "PrintComponent.h" class PrintComponent; class PrintRoutine : Routine { public: PrintRoutine(); ~PrintRoutine(); void Initialize(); void Update(double a_Deltatime); private: float m_PrintPeriod = 3.0f; float m_TimePassed = m_PrintPeriod; PrintComponent* m_pPrint = nullptr; }; #endif // !_PrintRoutine_H_
17.925926
83
0.725207
757334b3dbfd870f772dd1fbff96a3059cde344c
4,422
h
C
archive_widget.h
horsicq/archive_widget
4baa1e715600e8213c4cc7bc81c233e2a0597985
[ "MIT" ]
null
null
null
archive_widget.h
horsicq/archive_widget
4baa1e715600e8213c4cc7bc81c233e2a0597985
[ "MIT" ]
null
null
null
archive_widget.h
horsicq/archive_widget
4baa1e715600e8213c4cc7bc81c233e2a0597985
[ "MIT" ]
null
null
null
/* Copyright (c) 2020-2021 hors<horsicq@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef ARCHIVE_WIDGET_H #define ARCHIVE_WIDGET_H #include "dialogcreateviewmodel.h" #include "dialogdex.h" #include "dialogelf.h" #include "dialogentropy.h" #include "dialoghash.h" #include "dialoghexview.h" #include "dialogle.h" #include "dialogmach.h" #include "dialogmsdos.h" #include "dialogne.h" #include "dialogpe.h" #include "dialogsearchstrings.h" #include "dialogshowimage.h" #include "dialogshowtext.h" #include "dialogstaticscan.h" #include "dialogunpackfile.h" #include "xandroidbinary.h" #include "xarchives.h" namespace Ui { class Archive_widget; } class Archive_widget : public XShortcutsWidget { Q_OBJECT enum ACTION { ACTION_OPEN=0, ACTION_SCAN, ACTION_HEX, ACTION_STRINGS, ACTION_ENTROPY, ACTION_HASH, ACTION_COPYFILENAME, ACTION_DUMP // TODO more }; public: explicit Archive_widget(QWidget *pParent=nullptr); ~Archive_widget(); // TODO setOptions void setFileName(QString sFileName,FW_DEF::OPTIONS options,QSet<XBinary::FT> stAvailableOpenFileTypes,QWidget *pParent=nullptr); // TODO options for Viewers TODO Device void setDirectoryName(QString sDirectoryName,FW_DEF::OPTIONS options,QSet<XBinary::FT> stAvailableOpenFileTypes,QWidget *pParent=nullptr); void setData(CreateViewModelProcess::TYPE type,QString sName,FW_DEF::OPTIONS options,QSet<XBinary::FT> stAvailableOpenFileTypes,QWidget *pParent=nullptr); QString getCurrentRecordFileName(); public slots: void openRecord(); private slots: void on_treeViewArchive_customContextMenuRequested(const QPoint &pos); void on_tableViewArchive_customContextMenuRequested(const QPoint &pos); void showContext(QString sRecordFileName,bool bIsRoot,QPoint point); bool isOpenAvailable(QString sRecordFileName,bool bIsRoot); void scanRecord(); void hexRecord(); void stringsRecord(); void entropyRecord(); void hashRecord(); void copyFileName(); void dumpRecord(); void handleAction(ACTION action); void _handleActionDevice(ACTION action,QIODevice *pDevice); void _handleActionOpenFile(QString sFileName,QString sTitle,bool bReadWrite); void on_comboBoxType_currentIndexChanged(int nIndex); void on_lineEditFilter_textChanged(const QString &sString); void on_treeViewArchive_doubleClicked(const QModelIndex &index); void on_tableViewArchive_doubleClicked(const QModelIndex &index); void onTreeElement_selected(const QItemSelection &selected,const QItemSelection &prev); // TrackSelection void onTableElement_selected(const QItemSelection &selected,const QItemSelection &prev); // TrackSelection protected: virtual void registerShortcuts(bool bState); signals: void openAvailable(bool bState); private: Ui::Archive_widget *ui; CreateViewModelProcess::TYPE g_type; QString g_sName; FW_DEF::OPTIONS g_options; QList<XArchive::RECORD> g_listRecords; QSortFilterProxyModel *g_pFilterTable; QSet<XBinary::FT> g_stAvailableOpenFileTypes; qint64 g_nCurrentFileSize; bool g_bCurrentFileIsRoot; QString g_sCurrentRecordFileName; }; #endif // ARCHIVE_WIDGET_H
36.545455
173
0.740389
3df422a3a0d112dd15c5f880267638ec016585d7
422
h
C
PrivateFrameworks/TVRemoteCore/TVRCVoiceRecorder.h
phatblat/macOSPrivateFrameworks
9047371eb80f925642c8a7c4f1e00095aec66044
[ "MIT" ]
17
2018-11-13T04:02:58.000Z
2022-01-20T09:27:13.000Z
PrivateFrameworks/TVRemoteCore/TVRCVoiceRecorder.h
phatblat/macOSPrivateFrameworks
9047371eb80f925642c8a7c4f1e00095aec66044
[ "MIT" ]
3
2018-04-06T02:02:27.000Z
2018-10-02T01:12:10.000Z
PrivateFrameworks/TVRemoteCore/TVRCVoiceRecorder.h
phatblat/macOSPrivateFrameworks
9047371eb80f925642c8a7c4f1e00095aec66044
[ "MIT" ]
1
2018-09-28T13:54:23.000Z
2018-09-28T13:54:23.000Z
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard. // #import "NSObject.h" @class TVRCDevice; @interface TVRCVoiceRecorder : NSObject { TVRCDevice *_device; BOOL _recordsAutomatically; } - (void).cxx_destruct; - (void)stop; - (void)start; @property(nonatomic) BOOL recordsAutomatically; - (id)_initWithDevice:(id)arg1; @end
16.88
83
0.689573
35e16f7ec16dcef9afca8f3723815bfc4f46e044
3,476
h
C
RayTracing/Middleware/Qt/include/QtQuick/5.3.1/QtQuick/private/qquickrepeater_p.h
DarriusWrightGD/realtimeraytracing
1b1117858dcd8880ed88b59ce0388cfb39fc1d96
[ "MIT" ]
3
2015-03-18T03:12:27.000Z
2020-11-19T10:40:12.000Z
RayTracing/Middleware/Qt/include/QtQuick/5.3.1/QtQuick/private/qquickrepeater_p.h
DarriusWrightGD/RealtimeRaytracing
1b1117858dcd8880ed88b59ce0388cfb39fc1d96
[ "MIT" ]
2
2017-03-23T17:28:37.000Z
2018-06-07T06:38:08.000Z
RayTracing/Middleware/Qt/include/QtQuick/5.3.1/QtQuick/private/qquickrepeater_p.h
DarriusWrightGD/RealtimeRaytracing
1b1117858dcd8880ed88b59ce0388cfb39fc1d96
[ "MIT" ]
3
2016-06-22T11:11:16.000Z
2019-10-25T15:09:46.000Z
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtQuick module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QQUICKREPEATER_P_H #define QQUICKREPEATER_P_H #include "qquickitem.h" QT_BEGIN_NAMESPACE class QQmlChangeSet; class QQuickRepeaterPrivate; class Q_AUTOTEST_EXPORT QQuickRepeater : public QQuickItem { Q_OBJECT Q_PROPERTY(QVariant model READ model WRITE setModel NOTIFY modelChanged) Q_PROPERTY(QQmlComponent *delegate READ delegate WRITE setDelegate NOTIFY delegateChanged) Q_PROPERTY(int count READ count NOTIFY countChanged) Q_CLASSINFO("DefaultProperty", "delegate") public: QQuickRepeater(QQuickItem *parent=0); virtual ~QQuickRepeater(); QVariant model() const; void setModel(const QVariant &); QQmlComponent *delegate() const; void setDelegate(QQmlComponent *); int count() const; Q_INVOKABLE QQuickItem *itemAt(int index) const; Q_SIGNALS: void modelChanged(); void delegateChanged(); void countChanged(); void itemAdded(int index, QQuickItem *item); void itemRemoved(int index, QQuickItem *item); private: void clear(); void regenerate(); protected: virtual void componentComplete(); void itemChange(ItemChange change, const ItemChangeData &value); private Q_SLOTS: void createdItem(int index, QObject *item); void initItem(int, QObject *item); void modelUpdated(const QQmlChangeSet &changeSet, bool reset); private: Q_DISABLE_COPY(QQuickRepeater) Q_DECLARE_PRIVATE(QQuickRepeater) }; QT_END_NAMESPACE QML_DECLARE_TYPE(QQuickRepeater) #endif // QQUICKREPEATER_P_H
32.792453
94
0.721807
0d66c1a3198cda29a2f19ecde5459155d4d8b479
615
h
C
DeviceManagement.framework/DMFFetchProfilesRequest.h
reels-research/iOS-Private-Frameworks
9a4f4534939310a51fdbf5a439dd22487efb0f01
[ "MIT" ]
4
2021-10-06T12:15:26.000Z
2022-02-21T02:26:00.000Z
DeviceManagement.framework/DMFFetchProfilesRequest.h
reels-research/iOS-Private-Frameworks
9a4f4534939310a51fdbf5a439dd22487efb0f01
[ "MIT" ]
null
null
null
DeviceManagement.framework/DMFFetchProfilesRequest.h
reels-research/iOS-Private-Frameworks
9a4f4534939310a51fdbf5a439dd22487efb0f01
[ "MIT" ]
1
2021-10-08T07:40:53.000Z
2021-10-08T07:40:53.000Z
/* Generated by RuntimeBrowser Image: /System/Library/PrivateFrameworks/DeviceManagement.framework/DeviceManagement */ @interface DMFFetchProfilesRequest : DMFTaskRequest { unsigned long long _filterFlags; } @property (nonatomic) unsigned long long filterFlags; + (bool)isPermittedOnSystemConnection; + (bool)isPermittedOnUserConnection; + (id)permittedPlatforms; + (bool)supportsSecureCoding; + (Class)whitelistedClassForResultObject; - (void)encodeWithCoder:(id)arg1; - (unsigned long long)filterFlags; - (id)init; - (id)initWithCoder:(id)arg1; - (void)setFilterFlags:(unsigned long long)arg1; @end
25.625
87
0.785366
e4c65ab2c876d78101696bb20c550904a86abcfc
596
c
C
Atividade02/ex03.c
vncenturion/Tec-Desenv-Alg
d796f663f9495f1ce55a9fb3ff375c0d7cd9f5b8
[ "MIT" ]
null
null
null
Atividade02/ex03.c
vncenturion/Tec-Desenv-Alg
d796f663f9495f1ce55a9fb3ff375c0d7cd9f5b8
[ "MIT" ]
null
null
null
Atividade02/ex03.c
vncenturion/Tec-Desenv-Alg
d796f663f9495f1ce55a9fb3ff375c0d7cd9f5b8
[ "MIT" ]
null
null
null
#include <stdio.h> int main(void) { unsigned long int fatorial = 1; int num, i; // adota-se unsigned long int em razao do crescimento da funcao printf("Digite um numero inteiro qualquer: "); scanf("%d", &num); for (i=1; i<=num; i++) { fatorial=fatorial*i; //para conferir: printf("i: %d, fatorial: %lu\n",i,fatorial); } printf("fatorial de %d vale %lu", num, fatorial); /* adota-se a definicao de 0!=1 do ensino medio; ressalta-se no entando que a integral da funcao gama que define a funcao fatorial so é convergente para num>0. */ return 0; }
22.923077
112
0.637584
7c0efb9a6da867417e6c0c9f795b17d6f9b3254d
204
h
C
slycore/include/sly/gfx/enums/polygonfillmode.h
Gibbeon/sly
9216cf04a78f1d41af01186489ba6680b9641229
[ "MIT" ]
null
null
null
slycore/include/sly/gfx/enums/polygonfillmode.h
Gibbeon/sly
9216cf04a78f1d41af01186489ba6680b9641229
[ "MIT" ]
null
null
null
slycore/include/sly/gfx/enums/polygonfillmode.h
Gibbeon/sly
9216cf04a78f1d41af01186489ba6680b9641229
[ "MIT" ]
null
null
null
#pragma once #include "sly/global.h" namespace sly { namespace gfx { ENUM_DECL(ePolygonFillMode, ePolygonFillMode_Wireframe, ePolygonFillMode_Solid ); } }
17
39
0.607843
8ea316d4f8640adbd944fe9282175b2aeeb2b789
605
h
C
PrivateFrameworks/CoreCDP/CDPAccount.h
phatblat/macOSPrivateFrameworks
9047371eb80f925642c8a7c4f1e00095aec66044
[ "MIT" ]
17
2018-11-13T04:02:58.000Z
2022-01-20T09:27:13.000Z
PrivateFrameworks/CoreCDP/CDPAccount.h
phatblat/macOSPrivateFrameworks
9047371eb80f925642c8a7c4f1e00095aec66044
[ "MIT" ]
3
2018-04-06T02:02:27.000Z
2018-10-02T01:12:10.000Z
PrivateFrameworks/CoreCDP/CDPAccount.h
phatblat/macOSPrivateFrameworks
9047371eb80f925642c8a7c4f1e00095aec66044
[ "MIT" ]
1
2018-09-28T13:54:23.000Z
2018-09-28T13:54:23.000Z
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard. // #import "NSObject.h" @interface CDPAccount : NSObject { } + (id)sharedInstance; + (BOOL)isICDPEnabledForDSID:(id)arg1 checkWithServer:(BOOL)arg2; + (BOOL)isICDPEnabledForDSID:(id)arg1; - (id)primaryAppleAccount; - (id)sharedAccountStore; - (id)contextForPrimaryAccount; - (id)iCloudEnv; - (id)escrowURL; - (id)authToken; - (unsigned long long)primaryAccountSecurityLevel; - (id)primaryAccountAltDSID; - (id)primaryAccountDSID; - (id)primaryAccountUsername; @end
20.862069
83
0.72562
11ac7f41e7925e5740479744969eef57a53d43ec
784
c
C
Strange_numbers/C/Strange/Source.c
ncoe/rosetta
15c2302a247dfbcea694ff095238a525c60226d4
[ "MIT" ]
3
2018-02-26T18:12:31.000Z
2019-08-26T06:47:30.000Z
Strange_numbers/C/Strange/Source.c
ncoe/rosetta
15c2302a247dfbcea694ff095238a525c60226d4
[ "MIT" ]
null
null
null
Strange_numbers/C/Strange/Source.c
ncoe/rosetta
15c2302a247dfbcea694ff095238a525c60226d4
[ "MIT" ]
null
null
null
#include <stdbool.h> #include <stdio.h> bool isPrime(int n) { if (n < 0) { n = -n; } return n == 2 || n == 3 || n == 5 || n == 7; } int main() { int count = 0; int i, j; int d[3]; int dptr; printf("Strange numbers in the open interval (100, 500) are:\n"); for (i = 101; i < 500; i++) { dptr = 0; j = i; while (j > 0) { d[dptr++] = j % 10; j /= 10; } if (isPrime(d[0] - d[1]) && isPrime(d[1] - d[2])) { printf("%d ", i); count++; if (count % 10 == 0) { printf("\n"); } } } if (count % 10 != 0) { printf("\n"); } printf("\n%d strange numbers in all.\n", count); return 0; }
19.6
69
0.371173
11b7d6da0e68a19716d4b4e9f4dc0abfffb097c3
1,736
h
C
Reloaded/trunk/src/mame/video/kan_pand.h
lofunz/mieme
4226c2960b46121ec44fa8eab9717d2d644bff04
[ "Unlicense" ]
51
2015-11-22T14:53:28.000Z
2021-12-14T07:17:42.000Z
Reloaded/trunk/src/mame/video/kan_pand.h
lofunz/mieme
4226c2960b46121ec44fa8eab9717d2d644bff04
[ "Unlicense" ]
8
2018-01-14T07:19:06.000Z
2021-08-22T15:29:59.000Z
Reloaded/trunk/src/mame/video/kan_pand.h
lofunz/mieme
4226c2960b46121ec44fa8eab9717d2d644bff04
[ "Unlicense" ]
35
2017-02-15T09:39:00.000Z
2021-12-14T07:17:43.000Z
/************************************************************************* kan_pand.h Implementation of Kaneko Pandora sprite chip **************************************************************************/ #ifndef __KAN_PAND_H__ #define __KAN_PAND_H__ #include "devlegcy.h" /*************************************************************************** TYPE DEFINITIONS ***************************************************************************/ typedef struct _kaneko_pandora_interface kaneko_pandora_interface; struct _kaneko_pandora_interface { const char *screen; UINT8 gfx_region; int x; int y; }; DECLARE_LEGACY_DEVICE(KANEKO_PANDORA, kaneko_pandora); /*************************************************************************** DEVICE CONFIGURATION MACROS ***************************************************************************/ #define MDRV_KANEKO_PANDORA_ADD(_tag, _interface) \ MDRV_DEVICE_ADD(_tag, KANEKO_PANDORA, 0) \ MDRV_DEVICE_CONFIG(_interface) /*************************************************************************** DEVICE I/O FUNCTIONS ***************************************************************************/ void pandora_update(running_device *device, bitmap_t *bitmap, const rectangle *cliprect); void pandora_eof(running_device *device); void pandora_set_clear_bitmap(running_device *device, int clear); void pandora_set_bg_pen( running_device *device, int pen ); WRITE8_DEVICE_HANDLER ( pandora_spriteram_w ); READ8_DEVICE_HANDLER( pandora_spriteram_r ); WRITE16_DEVICE_HANDLER( pandora_spriteram_LSB_w ); READ16_DEVICE_HANDLER( pandora_spriteram_LSB_r ); #endif /* __KAN_PAND_H__ */
31.563636
90
0.487327
69a74971b7aae818e24ec0d987be451d8f7aae06
645
h
C
include/server/tcp.h
RickySu/respondphp
9316f019356afeab25bfe073b6a01dfc6da75ef8
[ "MIT" ]
null
null
null
include/server/tcp.h
RickySu/respondphp
9316f019356afeab25bfe073b6a01dfc6da75ef8
[ "MIT" ]
null
null
null
include/server/tcp.h
RickySu/respondphp
9316f019356afeab25bfe073b6a01dfc6da75ef8
[ "MIT" ]
null
null
null
#ifndef _RP_SERVER_TCP_H #define _RP_SERVER_TCP_H #include "internal/event_emitter.h" CLASS_ENTRY_FUNCTION_D(respond_server_tcp); ZEND_BEGIN_ARG_INFO(ARGINFO(respond_server_tcp, __construct), 0) ZEND_ARG_TYPE_INFO(0, port, IS_LONG, 0) ZEND_ARG_TYPE_INFO(0, host, IS_STRING, 0) ZEND_END_ARG_INFO() typedef struct { uint flag; rp_reactor_t *reactor; event_hook_t event_hook; zend_object zo; } rp_server_tcp_ext_t; PHP_METHOD(respond_server_tcp, close); PHP_METHOD(respond_server_tcp, __construct); TRAIT_PHP_METHOD(respond_server_tcp, event_emitter); TRAIT_FUNCTION_ARG_INFO(respond_server_tcp, event_emitter); #endif
25.8
64
0.809302
dae435d12839012b0d44e99932bfefdda9eba2f5
592
c
C
media.c
dudusapio/ProjetosCpublico
665ee46355bc9bd377575bf8862bb4b5573010c3
[ "MIT" ]
null
null
null
media.c
dudusapio/ProjetosCpublico
665ee46355bc9bd377575bf8862bb4b5573010c3
[ "MIT" ]
null
null
null
media.c
dudusapio/ProjetosCpublico
665ee46355bc9bd377575bf8862bb4b5573010c3
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> int main (void){ float salario[50], sal,media=0,salmedio=0; int i,n ; printf("Escreva o seu salario:"); scanf("%f",&sal); for(i = 0; i < 50 && sal > 0; i++ ){ salario[i] = sal; media = media + sal; printf("Escreva o seu salario: "); scanf("%f",&sal); } media = media/i; printf("Digite o limite de salario:"); scanf("%f",&salmedio); for(n = 0; n < i; n++){ if(salario[n] <= salmedio){ printf("O trabalhador %d recebe: %.2f\n",n,salario[n]); } } }
22.769231
67
0.496622
d34a8ea4d7ac8eb149fa9f372588ac314ca7296d
3,055
c
C
lzjwm_compress.c
johnmeacham/lzjwm
a7da642f1fe4639ea83bb36535466e6a4c6cf6aa
[ "BSD-2-Clause" ]
6
2020-11-11T16:55:45.000Z
2021-11-09T09:41:07.000Z
lzjwm_compress.c
johnmeacham/lzjwm
a7da642f1fe4639ea83bb36535466e6a4c6cf6aa
[ "BSD-2-Clause" ]
null
null
null
lzjwm_compress.c
johnmeacham/lzjwm
a7da642f1fe4639ea83bb36535466e6a4c6cf6aa
[ "BSD-2-Clause" ]
1
2020-11-04T14:07:23.000Z
2020-11-04T14:07:23.000Z
/* simple encoder in C, the python lzjwm.py is more featureful. */ #include "lzjwm.h" #include <stdint.h> #include <assert.h> #define NDEBUG static char mk_ptr(uint8_t count, uint8_t offset) { assert(count >= 2); assert(offset >= 0); assert(offset < LOOKBACK); if (ZERO_BITS && offset == 0) //return 0xf0 | (count - 2); return ~((1 << (COUNT_BITS + ZERO_BITS)) - 1) | (count - 2); return 0x80 | ((offset - (ZERO_BITS ? 1 : 0)) << COUNT_BITS) | (count - 2); } static int match(const char *data, int x, int y, int max, int max_match) { assert(x != y); assert(x <= max); assert(y <= max); int result = 0; int mresult = x > y ? max - x : max - y; if (mresult > max_match) mresult = max_match; while (result < mresult && data[x + result] == data[y + result]) result++; return result; } /* out must be at lesat as big as in. */ ssize_t lzjwm_compress(const char *in, size_t isize, char *out) { struct { int next, from; uint8_t count; } *as; as = malloc(isize * sizeof(*as)); for (int i = 0; i < isize; i++) { if (in[i] & 0x80) { free(as); return -1; } as[i].next = i + 1; as[i].count = 1; as[i].from = 0; } as[isize - 1].next = -1; for (int dptr = 0; dptr != -1; dptr = as[dptr].next) { int cl = dptr; for (int i = 0; i < LOOKBACK; i++) { cl = as[cl].next; if (cl < 0) break; int m = match(in, dptr, cl, isize, i ? MAX_MATCH : MAX_ZERO_MATCH); if (m >= 2) { int nn = cl; int d = 0, j = 0; for (; nn != -1; d++) { int c = as[nn].count; if (j + c > m) break; j += c; nn = as[nn].next; } if (d >= 2) { as[cl].next = nn; as[cl].count = j; as[cl].from = dptr; } } } } int optr = 0; for (int i = 0; i != -1; i = as[i].next) { if (as[i].count < 2) out[optr] = in[i] & 0x7f; else { out[optr] = mk_ptr(as[i].count, optr - as[as[i].from].from - 1); } as[i].from = optr++; } free(as); return optr; }
33.571429
91
0.341408
1c1b0f9242e84b91910ad3fda93da62d54651d67
4,463
h
C
src/ismrmrd_wrapper.h
brknowles/ISMRMRD.jl
2330aecd80a2664b4b2ecb6ba45be09b140a85b8
[ "MIT" ]
1
2021-07-02T02:18:41.000Z
2021-07-02T02:18:41.000Z
src/ismrmrd_wrapper.h
brknowles/ISMRMRD.jl
2330aecd80a2664b4b2ecb6ba45be09b140a85b8
[ "MIT" ]
null
null
null
src/ismrmrd_wrapper.h
brknowles/ISMRMRD.jl
2330aecd80a2664b4b2ecb6ba45be09b140a85b8
[ "MIT" ]
null
null
null
#ifndef _GDCM_WRAPPER_ #define _GDCM_WRAPPER_ 1 #include "ismrmrd/ismrmrd.h" #ifdef __cplusplus extern "C" { #endif /* * * ISMRMRD::Dataset interface * */ /* Inputs: filename, groupname, 0=read,1=write */ void* jl_ismrmrd_create_dataset(const char*, const char*, int ); void jl_ismrmrd_delete_dataset(void* ); /*int jl_ismrmrd_is_dataset_open(void *);*/ int jl_ismrmrd_read_header(void*, char* ); /*void* jl_ismrmrd_deserialize_header(const char* );*/ void jl_ismrmrd_write_header(void*, const char* ); void jl_ismrmrd_append_acquisition(void*, void *); void* jl_ismrmrd_read_acquisition(void*, int32_t); int jl_ismrmrd_get_number_of_acquisitions(void* ); /* arguments: dataset,groupname,image idx */ void* jl_ismrmrd_read_image(void*, const char*, int32_t); /* * * ISMRMRD::Image interface * */ void* jl_ismrmrd_create_image(void); void jl_ismrmrd_delete_image(void*); int jl_ismrmrd_get_image_data_type(void*); uint16_t* jl_ismrmrd_get_image_dims(void*); uint16_t* jl_ismrmrd_get_ushort_data(void *); int16_t* jl_ismrmrd_get_short_data(void *); uint32_t* jl_ismrmrd_get_uint_data(void *); int32_t* jl_ismrmrd_get_int_data(void *); float* jl_ismrmrd_get_float_data(void *); double* jl_ismrmrd_get_double_data(void *); complex_float_t* jl_ismrmrd_get_complex_float_data(void *); complex_double_t* jl_ismrmrd_get_complex_double_data(void *); /* * * ISMRMRD::Acquisition interface * */ void* jl_ismrmrd_create_acquisition(void ); void* jl_ismrmrd_setup_acquisition(int ,int, int); void* jl_ismrmrd_copy_acquisition_copy(void* ); void jl_ismrmrd_delete_acquisition(void *); /* * Accessors */ uint64_t jl_ismrmrd_header_version(void*); uint64_t jl_ismrmrd_header_flags(void*); uint32_t jl_ismrmrd_header_measurement_uid(void*); uint32_t jl_ismrmrd_header_scan_counter(void*); uint32_t jl_ismrmrd_header_acquisition_time_stamp(void*); uint32_t jl_ismrmrd_header_physiology_time_stamp(void*, int ); const uint16_t jl_ismrmrd_header_number_of_samples(void*); uint16_t jl_ismrmrd_header_available_channels(void*); const uint16_t jl_ismrmrd_header_active_channels(void*); const uint64_t jl_ismrmrd_header_channel_mask(void*, int ); uint16_t jl_ismrmrd_header_discard_pre(void*); uint16_t jl_ismrmrd_header_discard_post(void*); uint16_t jl_ismrmrd_header_center_sample(void*); uint16_t jl_ismrmrd_header_encoding_space_ref(void*); const uint16_t jl_ismrmrd_header_trajectory_dimensions(void*); float jl_ismrmrd_header_sample_time_us(void*); float jl_ismrmrd_header_position(void*, int ); float jl_ismrmrd_header_read_dir(void*, int ); float jl_ismrmrd_header_phase_dir(void*, int ); float jl_ismrmrd_header_slice_dir(void*, int ); float jl_ismrmrd_header_patient_table_position(void*, int ); /*void* jl_ismrmrd_header_idx(void*);*/ int jl_ismrmrd_header_user_int(void*, int ); float jl_ismrmrd_header_user_float(void*, int ); /* * EncodingCounter */ uint16_t jl_ismrmrd_get_ec_kspace_encode_step_1(void *); uint16_t jl_ismrmrd_get_ec_kspace_encode_step_2(void *); uint16_t jl_ismrmrd_get_ec_average(void *); uint16_t jl_ismrmrd_get_ec_slice(void *); uint16_t jl_ismrmrd_get_ec_contrast(void *); uint16_t jl_ismrmrd_get_ec_phase(void *); uint16_t jl_ismrmrd_get_ec_repetition(void *); uint16_t jl_ismrmrd_get_ec_set(void *); uint16_t jl_ismrmrd_get_ec_segment(void *); uint16_t jl_ismrmrd_get_ec_user(void *, int); /* * sizes */ void jl_ismrmrd_resize(void*, uint16_t, uint16_t, uint16_t); size_t jl_ismrmrd_get_number_of_data_elements(void* ); size_t jl_ismrmrd_get_number_of_traj_elements(void* ); size_t jl_ismrmrd_get_data_size(void *); size_t jl_ismrmrd_get_traj_size(void *); /* * data/traj accessors */ /* ISMRMRD_AcquisitionHeader jl_ismrmrd_get_head(void *); void jl_ismrmrd_set_head(void*, ISMRMRD_AcquisitionHeader ); */ complex_float_t* jl_ismrmrd_get_data_pointer(void* ); float* jl_ismrmrd_get_traj_pointer(void* ); /* * flags */ int jl_ismrmrd_is_flag_set(void*, const uint16_t ); void jl_ismrmrd_set_flag(void*, const uint16_t ); void jl_ismrmrd_clear_flag(void*, const uint16_t); void jl_ismrmrd_clear_all_flags(void*); /* * channels */ int jl_ismrmrd_is_channel_active(void*, uint16_t ); void jl_ismrmrd_set_channel_active(void*, uint16_t ); void jl_ismrmrd_set_channel_not_active(void*, uint16_t); void jl_ismrmrd_set_all_channels_not_active(void*); #ifdef __cplusplus } #endif #endif
31.429577
66
0.784898
bce6768eba0901c6599bc39156a3f2aa0491871d
4,267
h
C
src/nibble.h
adrianlizarraga/nibble
4909038d697b56c6251dca4c9788412446c87789
[ "MIT" ]
3
2021-04-20T00:30:43.000Z
2021-05-18T06:58:36.000Z
src/nibble.h
adrianlizarraga/nibble
4909038d697b56c6251dca4c9788412446c87789
[ "MIT" ]
1
2021-06-20T08:43:49.000Z
2021-06-20T08:43:49.000Z
src/nibble.h
adrianlizarraga/nibble
4909038d697b56c6251dca4c9788412446c87789
[ "MIT" ]
null
null
null
#ifndef NIBBLE_H #define NIBBLE_H #include <stddef.h> #include <stdint.h> #include <stdbool.h> #include "allocator.h" #include "hash_map.h" #include "stream.h" #define MAX_ERROR_LEN 256 #define ARRAY_LEN(a) (sizeof(a) / sizeof((a)[0])) #define ALIGN_UP(p, a) (((p) + (a)-1) & ~((a)-1)) #define BITS(x) (sizeof(x) * 8) #if defined(_WIN32) || defined(_WIN64) #define NIBBLE_HOST_WINDOWS #elif defined(__linux__) #define NIBBLE_HOST_LINUX #else #error "This operating system is not yet supported!" #endif typedef enum OS { OS_INVALID, OS_LINUX, OS_WIN32, OS_OSX, NUM_OS, } OS; typedef enum Arch { ARCH_INVALID, ARCH_X64, ARCH_X86, NUM_ARCH, } Arch; extern const char* os_names[NUM_OS]; extern const char* arch_names[NUM_ARCH]; typedef uint32_t ProgPos; typedef struct ProgRange { ProgPos start; ProgPos end; } ProgRange; typedef struct StringView { const char* str; size_t len; } StringView; #define string_view_lit(cstr_lit) \ { \ .str = cstr_lit, .len = sizeof(cstr_lit) - 1 \ } typedef uint8_t u8; typedef int8_t s8; typedef uint16_t u16; typedef int16_t s16; typedef uint32_t u32; typedef int32_t s32; typedef uint64_t u64; typedef int64_t s64; typedef float f32; typedef double f64; typedef enum FloatKind { FLOAT_F64, FLOAT_F32, } FloatKind; typedef struct Float { union { f64 _f64; f32 _f32; }; } Float; typedef enum IntegerKind { INTEGER_U8, INTEGER_S8, INTEGER_U16, INTEGER_S16, INTEGER_U32, INTEGER_S32, INTEGER_U64, INTEGER_S64, } IntegerKind; typedef struct Integer { union { u8 _u8; s8 _s8; u16 _u16; s16 _s16; u32 _u32; s32 _s32; u64 _u64; s64 _s64; }; } Integer; typedef struct Scalar { union { Float as_float; Integer as_int; void* as_ptr; }; } Scalar; typedef struct TypeCache { HMap ptrs; HMap arrays; HMap procs; } TypeCache; typedef enum Keyword { KW_VAR = 0, KW_CONST, KW_ENUM, KW_UNION, KW_STRUCT, KW_PROC, KW_TYPEDEF, KW_SIZEOF, KW_TYPEOF, KW_STATIC_ASSERT, KW_EXPORT, KW_IMPORT, KW_FROM, KW_AS, KW_INCLUDE, KW_LABEL, KW_GOTO, KW_BREAK, KW_CONTINUE, KW_RETURN, KW_IF, KW_ELSE, KW_WHILE, KW_DO, KW_FOR, KW_SWITCH, KW_CASE, KW_UNDERSCORE, KW_COUNT, } Keyword; typedef enum Annotation { ANNOTATION_CUSTOM = 0, ANNOTATION_EXPORTED, ANNOTATION_FOREIGN, ANNOTATION_PACKED, ANNOTATION_COUNT, } Annotation; typedef enum Intrinsic { INTRINSIC_READIN, INTRINSIC_WRITEOUT, INTRINSIC_COUNT, } Intrinsic; typedef struct StrLit { struct StrLit* next; size_t id; size_t len; char str[]; } StrLit; typedef enum IdentifierKind { IDENTIFIER_NAME, IDENTIFIER_KEYWORD, IDENTIFIER_INTRINSIC, } IdentifierKind; typedef struct Identifier { struct Identifier* next; IdentifierKind kind; union { Keyword kw; Intrinsic intrinsic; }; size_t len; char str[]; } Identifier; extern const char* keyword_names[KW_COUNT]; extern const char* annotation_names[ANNOTATION_COUNT]; extern const char* intrinsic_names[INTRINSIC_COUNT]; extern Identifier* main_proc_ident; StrLit* intern_str_lit(const char* str, size_t len); Identifier* intern_ident(const char* str, size_t len); bool slurp_file(StringView* contents, Allocator* allocator, const char* filename); typedef struct Error Error; typedef struct ErrorStream ErrorStream; struct Error { Error* next; ProgRange range; size_t size; char msg[]; }; struct ErrorStream { Error* first; Error* last; size_t count; Allocator* allocator; }; void error_stream_init(ErrorStream* stream, Allocator* allocator); void error_stream_free(ErrorStream* stream); void error_stream_add(ErrorStream* stream, ProgRange range, const char* buf, size_t size); void report_error(ProgRange range, const char* format, ...); #define NIBBLE_FATAL_EXIT(f, ...) nibble_fatal_exit((f), ##__VA_ARGS__) void nibble_fatal_exit(const char* format, ...); #endif
18.471861
90
0.662292
efe533c7d964293fe70864ec0187dd6af6940371
581
h
C
Sail/src/API/VULKAN/shader/SVkPipelineStateObject.h
Piratkopia13/Sail
c428024967cd7aa75e45d5fe9418a1d565881279
[ "MIT" ]
9
2019-03-18T18:35:29.000Z
2020-10-26T06:30:18.000Z
Sail/src/API/VULKAN/shader/SVkPipelineStateObject.h
Piratkopia13/Sail
c428024967cd7aa75e45d5fe9418a1d565881279
[ "MIT" ]
11
2019-06-10T19:54:11.000Z
2020-04-14T08:50:47.000Z
Sail/src/API/VULKAN/shader/SVkPipelineStateObject.h
Piratkopia13/Sail
c428024967cd7aa75e45d5fe9418a1d565881279
[ "MIT" ]
5
2019-06-16T20:24:50.000Z
2020-03-03T09:27:18.000Z
#pragma once #include "../SVkAPI.h" #include "Sail/api/shader/PipelineStateObject.h" class SVkShader; class SVkPipelineStateObject : public PipelineStateObject { public: SVkPipelineStateObject(Shader* shader, unsigned int attributesHash); ~SVkPipelineStateObject(); virtual bool bind(void* cmdList) override; const VkDescriptorSet& getDescriptorSet() const; private: void createGraphicsPipelineState(); void createComputePipelineState(); private: SVkAPI* m_context; SVkShader* m_vkShader; VkPipeline m_pipeline; std::vector<VkDescriptorSet> m_descriptorSets; };
20.75
69
0.79346
3c907e2ad60ca3b3c001ac904fc149fe48e12ee2
33,795
c
C
sdl2/grafX2/src/shade.c
pdpdds/SDL_YUZA
8299672a70005a1b702cc7e3577aad4f8b31bec2
[ "BSD-2-Clause" ]
null
null
null
sdl2/grafX2/src/shade.c
pdpdds/SDL_YUZA
8299672a70005a1b702cc7e3577aad4f8b31bec2
[ "BSD-2-Clause" ]
null
null
null
sdl2/grafX2/src/shade.c
pdpdds/SDL_YUZA
8299672a70005a1b702cc7e3577aad4f8b31bec2
[ "BSD-2-Clause" ]
null
null
null
/* vim:expandtab:ts=2 sw=2: */ /* Grafx2 - The Ultimate 256-color bitmap paint program Copyright owned by various GrafX2 authors, see COPYRIGHT.txt for details. Grafx2 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; version 2 of the License. Grafx2 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 Grafx2; if not, see <http://www.gnu.org/licenses/> */ #include <string.h> #include <stdlib.h> #include "global.h" #include "graph.h" #include "engine.h" #include "errors.h" #include "misc.h" #include "readline.h" #include "help.h" #include "screen.h" #include "windows.h" #include "input.h" #include "shade.h" #include "keycodes.h" void Button_Shade_mode(void) { if (Shade_mode) Effect_function=No_effect; else { Effect_function=Effect_shade; Quick_shade_mode=0; Colorize_mode=0; Smooth_mode=0; Tiling_mode=0; Smear_mode=0; } Shade_mode=!Shade_mode; } void Button_Quick_shade_mode(void) { if (Quick_shade_mode) Effect_function=No_effect; else { Effect_function=Effect_quick_shade; Shade_mode=0; Colorize_mode=0; Smooth_mode=0; Tiling_mode=0; Smear_mode=0; } Quick_shade_mode=!Quick_shade_mode; } void Shade_draw_grad_ranges(void) { word cursor=0; word nb_shades=0; short shade_processed,shade_processed_old; word shade_size=0; word start_shade=0; short x_pos,y_pos; short x_size,y_size; short start_x,start_y,end_x,end_y; // On commence par compter le nombre de shades while (cursor<512) { while ((cursor<512) && (Shade_list[Shade_current].List[cursor]&0xFF00)) cursor++; if (cursor<512) { nb_shades++; while ( (cursor<512) && (!(Shade_list[Shade_current].List[cursor]&0xFF00)) ) cursor++; } } // Maintenant qu'on sait combien il y en a, on les affiche: if (nb_shades) { x_size=Menu_factor_X<<6; y_size=Menu_factor_Y*48; start_x=Window_pos_X+(Menu_factor_X*224); start_y=Window_pos_Y+(Menu_factor_Y*35); end_x=start_x+x_size; end_y=start_y+y_size; cursor=0; shade_processed_old=-1; for (y_pos=start_y;y_pos<end_y;y_pos++) { // On regarde quel shade on va afficher en preview shade_processed=((y_pos-start_y)*nb_shades)/y_size; // Si ce n'est pas le shade précédemment traité on calcule ses infos if (shade_processed>shade_processed_old) { // On commence par sauter tous les vides jusqu'au prochain shade while ((cursor<512) && (Shade_list[Shade_current].List[cursor]&0xFF00)) cursor++; start_shade=cursor; // puis regarde sa taille while ((cursor<512) && (!(Shade_list[Shade_current].List[cursor]&0xFF00))) cursor++; shade_size=cursor-start_shade; shade_processed_old=shade_processed; } for (x_pos=start_x;x_pos<end_x;x_pos++) { Pixel(x_pos,y_pos,Shade_list[Shade_current].List [(((x_pos-start_x)*shade_size)/x_size)+start_shade]); } } } else { Window_display_frame_out(224,35,64,48); Window_rectangle(225,36,62,46,MC_Light); } Update_window_area(224,35,64,48); } void Tag_shades(word selection_start,word selection_end) { word line, column; word position; word x_pos, y_pos; if (selection_end<selection_start) { position =selection_end; selection_end =selection_start; selection_start=position; } for (line=0; line<8; line++) for (column=0; column<64; column++) { position=(line<<6)+column; x_pos=Window_pos_X+(Menu_factor_X*((column<<2)+8)); y_pos=Window_pos_Y+(Menu_factor_Y*((line*7)+131)); // On regarde si la case est "disablée" if (Shade_list[Shade_current].List[position]&0x8000) { if ((position>=selection_start) && (position<=selection_end)) { Block(x_pos,y_pos,Menu_factor_X<<2,Menu_factor_Y,MC_White); Block(x_pos,y_pos+Menu_factor_Y,Menu_factor_X<<2,Menu_factor_Y,MC_Black); } else Block(x_pos,y_pos,Menu_factor_X<<2,Menu_factor_Y<<1,MC_White); } else // "enablée" { if ((position>=selection_start) && (position<=selection_end)) Block(x_pos,y_pos,Menu_factor_X<<2,Menu_factor_Y<<1,MC_Black); else Block(x_pos,y_pos,Menu_factor_X<<2,Menu_factor_Y<<1,MC_Light); } } Update_window_area(8,131,64<<2,8<<3); } void Display_selected_cell_color(word selection_start,word selection_end) { char str[4]; if ((selection_start!=selection_end) || (Shade_list[Shade_current].List[selection_start]&0x0100)) strcpy(str," "); else Num2str(Shade_list[Shade_current].List[selection_start]&0xFF,str,3); Print_in_window(213,115,str,MC_Black,MC_Light); } void Display_selected_color(word selection_start,word selection_end) { char str[4]; if (selection_start!=selection_end) strcpy(str," "); else Num2str(selection_start,str,3); Print_in_window(213,106,str,MC_Black,MC_Light); } void Display_shade_mode(short x,short y,byte mode) { char str[7]; switch (mode) { case SHADE_MODE_NORMAL : strcpy(str,"Normal"); break; case SHADE_MODE_LOOP : strcpy(str," Loop "); break; default : // SHADE_MODE_NOSAT strcpy(str,"No sat"); } Print_in_window(x,y,str,MC_Black,MC_Light); } void Display_all_shade(word selection_start1,word selection_end1, word selection_start2,word selection_end2) { word line, column; word position; for (line=0; line<8; line++) for (column=0; column<64; column++) { position=(line<<6)+column; // On regarde si c'est une couleur ou un bloc vide if (Shade_list[Shade_current].List[position]&0x0100) // Vide { Window_display_frame_out((column<<2)+8,(line*7)+127,4,4); Window_rectangle((column<<2)+9, (line*7)+128, 2,2,MC_Light); } else // color Window_rectangle((column<<2)+8, (line*7)+127, 4,4, Shade_list[Shade_current].List[position]&0xFF); } Update_window_area(7,126,(64<<2)+2,(8<<2)+2); Tag_shades(selection_start2,selection_end2); Shade_draw_grad_ranges(); Display_selected_cell_color(selection_start2,selection_end2); Display_selected_color(selection_start1,selection_end1); Display_shade_mode(250,110,Shade_list[Shade_current].Mode); } void Remove_shade(word selection_start,word selection_end) { word temp; if (selection_end<selection_start) { temp =selection_end; selection_end =selection_start; selection_start=temp; } for (selection_end++;selection_end<512;selection_start++,selection_end++) Shade_list[Shade_current].List[selection_start]=Shade_list[Shade_current].List[selection_end]; for (;selection_start<512;selection_start++) Shade_list[Shade_current].List[selection_start]=0x0100; } void Insert_shade(byte first_color, byte last_color, word selection_start) { word cursor,limit; word temp; if (last_color<first_color) { temp =last_color; last_color=first_color; first_color=temp; } // Avant d'insérer quoi que ce soit, on efface les éventuelles couleurs que // l'on va réinsérer: limit=512-selection_start; for (cursor=0; cursor<512; cursor++) { if (!(Shade_list[Shade_current].List[cursor]&0x0100)) for (temp=first_color; temp<=last_color; temp++) if ( (temp-first_color<limit) && ((Shade_list[Shade_current].List[cursor]&0xFF)==temp) ) Shade_list[Shade_current].List[cursor]=(Shade_list[Shade_current].List[cursor]&0x8000)|0x0100; } // Voilà... Maintenant on peut y aller peinard. temp=1+last_color-first_color; limit=selection_start+temp; if (limit>=512) temp=512-selection_start; for (cursor=511;cursor>=limit;cursor--) Shade_list[Shade_current].List[cursor]=Shade_list[Shade_current].List[cursor-temp]; for (cursor=selection_start+temp;selection_start<cursor;selection_start++,first_color++) Shade_list[Shade_current].List[selection_start]=first_color; } void Insert_empty_cell_in_shade(word position) { word cursor; if (position>=512) return; for (cursor=511;cursor>position;cursor--) Shade_list[Shade_current].List[cursor]=Shade_list[Shade_current].List[cursor-1]; Shade_list[Shade_current].List[position]=0x0100; } short Wait_click_in_shade_table() { short selected_cell=-1; byte old_hide_cursor; Hide_cursor(); old_hide_cursor=Cursor_hidden; Cursor_hidden=0; Cursor_shape=CURSOR_SHAPE_TARGET; Display_cursor(); while (selected_cell<0) { Get_input(20); if ( (Mouse_K==LEFT_SIDE) && ( ( (Window_click_in_rectangle(8,127,263,179)) && (((((Mouse_Y-Window_pos_Y)/Menu_factor_Y)-127)%7)<4) ) || ( (Mouse_X<Window_pos_X) || (Mouse_Y<Window_pos_Y) || (Mouse_X>=Window_pos_X+(Window_width*Menu_factor_X)) || (Mouse_Y>=Window_pos_Y+(Window_height*Menu_factor_Y)) ) ) ) selected_cell=(((((Mouse_Y-Window_pos_Y)/Menu_factor_Y)-127)/7)<<6)+ ((((Mouse_X-Window_pos_X)/Menu_factor_X)-8 )>>2); if ((Mouse_K==RIGHT_SIDE) || (Key==KEY_ESC)) selected_cell=512; // valeur indiquant que l'on n'a rien choisi } Hide_cursor(); Cursor_shape=CURSOR_SHAPE_ARROW; Cursor_hidden=old_hide_cursor; Display_cursor(); return selected_cell; } void Swap_shade(short block_1_start,short block_2_start,short block_size) { short pos_1; short pos_2; short end_1; short end_2; word temp; word * temp_shade; // On fait une copie de la liste temp_shade=(word *)malloc(512*sizeof(word)); memcpy(temp_shade,Shade_list[Shade_current].List,512*sizeof(word)); // On calcul les dernières couleurs de chaque bloc. end_1=block_1_start+block_size-1; end_2=block_2_start+block_size-1; if ((block_2_start>=block_1_start) && (block_2_start<=end_1)) { // Le bloc destination commence dans le bloc source. for (pos_1=block_1_start,pos_2=end_1+1;pos_1<=end_2;pos_1++) { // Il faut transformer la case pos_1 en pos_2: Shade_list[Shade_current].List[pos_1]=temp_shade[pos_2]; // On gère la mise à jour de pos_2 if (pos_2==end_2) pos_2=block_1_start; else pos_2++; } } else if ((block_2_start<block_1_start) && (end_2>=block_1_start)) { // Le bloc destination déborde dans le bloc source. for (pos_1=block_2_start,pos_2=block_1_start;pos_1<=end_1;pos_1++) { // Il faut transformer la couleur pos_1 en pos_2: Shade_list[Shade_current].List[pos_1]=temp_shade[pos_2]; // On gère la mise à jour de pos_2 if (pos_2==end_1) pos_2=block_2_start; else pos_2++; } } else { // Le bloc source et le bloc destination sont distincts. for (pos_1=block_1_start,pos_2=block_2_start;pos_1<=end_1;pos_1++,pos_2++) { // On échange les cases temp =Shade_list[Shade_current].List[pos_1]; Shade_list[Shade_current].List[pos_1]=Shade_list[Shade_current].List[pos_2]; Shade_list[Shade_current].List[pos_2]=temp; } } free(temp_shade); } int Menu_shade(void) { short clicked_button; // Numéro du bouton sur lequel l'utilisateur a clické char str[4]; // str d'affichage du n° de shade actif et du Pas word old_mouse_x, old_mouse_x2; // Mémo. de l'ancienne pos. du curseur word old_mouse_y, old_mouse_y2; byte old_mouse_k, old_mouse_k2; byte temp_color; // Variables de gestion des clicks dans la palette byte first_color = Fore_color; byte last_color = Fore_color; word selection_start = 0; word selection_end = 0; T_Special_button * input_button; short temp, temp2; word temp_cell; word * buffer; // buffer du Copy/Paste word * undo_buffer; // buffer du Undo word * temp_ptr; byte color; byte click; buffer =(word *)malloc(512*sizeof(word)); undo_buffer =(word *)malloc(512*sizeof(word)); temp_ptr=(word *)malloc(512*sizeof(word)); // Ouverture de la fenêtre du menu Open_window(310,190,"Shade"); // Déclaration & tracé du bouton de palette Window_set_palette_button(5,16); // 1 // Déclaration & tracé du scroller de sélection du n° de dégradé Window_set_scroller_button(192,17,84,8,1,Shade_current); // 2 // Déclaration & tracé de la zone de définition des dégradés Window_set_special_button(8,127,256,53,0); // 3 // Déclaration & tracé des boutons de sortie Window_set_normal_button(207,17,51,14,"Cancel",0,1,KEY_ESC); // 4 Window_set_normal_button(261,17,43,14,"OK" ,0,1,KEY_RETURN); // 5 // Déclaration & tracé des boutons de copie de shade Window_set_normal_button(206,87,27,14,"Cpy" ,1,1,KEY_c); // 6 Window_set_normal_button(234,87,43,14,"Paste" ,1,1,KEY_p); // 7 // On tagge le bloc Tag_color_range(Fore_color,Fore_color); // Tracé d'un cadre creux autour du bloc dégradé Window_display_frame_in(171,26,18,66); Window_rectangle(172,27,16,64,MC_Black); // Tracé d'un cadre creux autour de tous les dégradés Window_display_frame_in(223,34,66,50); Shade_draw_grad_ranges(); // Tracé d'un cadre autour de la zone de définition de dégradés Window_display_frame(5,124,262,61); Display_all_shade(first_color,last_color,selection_start,selection_end); // Déclaration & tracé des boutons d'édition de shade Window_set_normal_button( 6,107,27,14,"Ins" ,0,1,KEY_INSERT); // 8 Window_set_normal_button( 38,107,27,14,"Del" ,0,1,KEY_DELETE); // 9 Window_set_normal_button( 66,107,43,14,"Blank",1,1,KEY_b); // 10 Window_set_normal_button(110,107,27,14,"Inv" ,1,1,KEY_i); // 11 Window_set_normal_button(138,107,27,14,"Swp" ,1,1,KEY_s); // 12 // Déclaration & tracé des boutons de taggage Print_in_window(268,123,"Disbl"/*"Dsabl"*/,MC_Dark,MC_Light); Window_set_normal_button(274,133,27,14,"Set" ,0,1,KEY_F1); // 13 Window_set_normal_button(274,148,27,14,"Clr" ,0,1,KEY_F2); // 14 // Déclaration & tracé de la zone de saisie du pas Print_in_window(272,165,"Step",MC_Dark,MC_Light); input_button = Window_set_input_button(274,174,3); // 15 Num2str(Shade_list[Shade_current].Step,str,3); Window_input_content(input_button,str); // Button Undo Window_set_normal_button(170,107,35,14,"Undo",1,1,KEY_u); // 16 // Button Clear Window_set_normal_button(278,87,27,14,"Clr",0,1,KEY_BACKSPACE); // 17 // Button Mode Window_set_normal_button(244,107,60,14,"",0,1,KEY_TAB); // 18 // Affichage du n° de shade actif Num2str(Shade_current+1,str,1); Print_in_window(210,55,str,MC_Black,MC_Light); memcpy(buffer ,Shade_list[Shade_current].List,512*sizeof(word)); memcpy(undo_buffer,Shade_list[Shade_current].List,512*sizeof(word)); Update_window_area(0,0,310,190); Display_cursor(); do { old_mouse_x=old_mouse_x2=Mouse_X; old_mouse_y=old_mouse_y2=Mouse_Y; old_mouse_k=old_mouse_k2=Mouse_K; clicked_button=Window_clicked_button(); switch (clicked_button) { case 0 : break; case -1 : case 1 : // Gestion de la palette if ( (Mouse_X!=old_mouse_x) || (Mouse_Y!=old_mouse_y) || (Mouse_K!=old_mouse_k) ) { Hide_cursor(); temp_color=(clicked_button==1) ? Window_attribute2 : Read_pixel(Mouse_X,Mouse_Y); if (!old_mouse_k) { // On vient de clicker // On met à jour l'intervalle du Shade first_color=last_color=temp_color; // On tagge le bloc Tag_color_range(first_color,last_color); // Tracé du bloc dégradé: Display_grad_block_in_window(172,27,16,64,first_color,last_color); } else { // On maintient le click, on va donc tester si le curseur bouge if (temp_color!=last_color) { last_color=temp_color; // On tagge le bloc if (first_color<=temp_color) { Tag_color_range(first_color,last_color); Display_grad_block_in_window(172,27,16,64,first_color,last_color); } else { Tag_color_range(last_color,first_color); Display_grad_block_in_window(172,27,16,64,last_color,first_color); } } } // On affiche le numéro de la couleur sélectionnée Display_selected_color(first_color,last_color); Display_cursor(); } break; case 2 : // Gestion du changement de Shade (scroller) Hide_cursor(); Shade_current=Window_attribute2; // Affichade du n° de shade actif Num2str(Shade_current+1,str,1); Print_in_window(210,55,str,MC_Black,MC_Light); // Affichade du Pas Num2str(Shade_list[Shade_current].Step,str,3); Print_in_window(276,176,str,MC_Black,MC_Light); // Tracé du bloc dégradé: Display_all_shade(first_color,last_color,selection_start,selection_end); Display_cursor(); // On place le nouveau shade dans le buffer du Undo memcpy(undo_buffer,Shade_list[Shade_current].List,512*sizeof(word)); break; case 3 : // Gestion de la zone de définition de shades if (((((Mouse_Y-Window_pos_Y)/Menu_factor_Y)-127)%7)<4) if ( (Mouse_X!=old_mouse_x2) || (Mouse_Y!=old_mouse_y2) || (Mouse_K!=old_mouse_k2) ) { Hide_cursor(); selection_end=(((((Mouse_Y-Window_pos_Y)/Menu_factor_Y)-127)/7)<<6)+ ((((Mouse_X-Window_pos_X)/Menu_factor_X)-8 )>>2); if (!old_mouse_k2) // On vient de clicker selection_start=selection_end; Tag_shades(selection_start,selection_end); Display_selected_cell_color(selection_start,selection_end); Display_cursor(); } break; case 5: // Ok if (selection_start == selection_end && Shade_list[Shade_current].List[selection_start] > 0) Set_fore_color(Shade_list[Shade_current].List[selection_start]); else if (first_color == last_color) Set_fore_color(first_color); break; case 6 : // Copy memcpy(buffer,Shade_list[Shade_current].List,512*sizeof(word)); break; case 7 : // Paste // On place le shade dans le buffer du Undo memcpy(undo_buffer,Shade_list[Shade_current].List,512*sizeof(word)); // Et on le modifie memcpy(Shade_list[Shade_current].List,buffer,512*sizeof(word)); Hide_cursor(); Display_all_shade(first_color,last_color,selection_start,selection_end); Display_cursor(); break; case 8 : // Insert // On place le shade dans le buffer du Undo memcpy(undo_buffer,Shade_list[Shade_current].List,512*sizeof(word)); // Et on le modifie if (first_color<=last_color) temp=last_color-first_color; else temp=first_color-last_color; if (selection_start==selection_end) // Une couleur sélectionnée { if (Window_attribute1==2) Remove_shade(selection_start,selection_start+temp); } else // Un bloc sélectionné { Remove_shade(selection_start,selection_end); if (first_color<=last_color) temp=last_color-first_color; else temp=first_color-last_color; if (selection_start<selection_end) selection_end=selection_start+temp; else { selection_start=selection_end; selection_end+=temp; } } if (selection_start<selection_end) selection_end=selection_start+temp; else { selection_start=selection_end; selection_end+=temp; } Insert_shade(first_color,last_color,selection_start); // On sélectionne la position juste après ce qu'on vient d'insérer selection_start+=temp+1; if (selection_start>=512) selection_start=511; selection_end=selection_start; Hide_cursor(); Display_all_shade(first_color,last_color,selection_start,selection_end); Display_cursor(); break; case 9 : // Delete // On place le shade dans le buffer du Undo memcpy(undo_buffer,Shade_list[Shade_current].List,512*sizeof(word)); // Et on le modifie Remove_shade(selection_start,selection_end); if (selection_start<=selection_end) selection_end=selection_start; else selection_start=selection_end; Hide_cursor(); Display_all_shade(first_color,last_color,selection_start,selection_end); Display_cursor(); break; case 10 : // Blank // On place le shade dans le buffer du Undo memcpy(undo_buffer,Shade_list[Shade_current].List,512*sizeof(word)); // Et on le modifie if (Window_attribute1==RIGHT_SIDE) // Click droit { if (selection_start!=selection_end) { if (selection_start<=selection_end) { Insert_empty_cell_in_shade(selection_start); Insert_empty_cell_in_shade(selection_end+2); } else { Insert_empty_cell_in_shade(selection_end); Insert_empty_cell_in_shade(selection_start+2); } } else Insert_empty_cell_in_shade(selection_start); if (selection_start<511) selection_start++; if (selection_end<511) selection_end++; } else // Click gauche { if (selection_start<=selection_end) { temp=selection_start; temp2=selection_end; } else { temp=selection_end; temp2=selection_start; } while (temp<=temp2) Shade_list[Shade_current].List[temp++]=0x0100; } Hide_cursor(); Display_all_shade(first_color,last_color,selection_start,selection_end); Display_cursor(); break; case 11 : // Invert // On place le shade dans le buffer du Undo memcpy(undo_buffer,Shade_list[Shade_current].List,512*sizeof(word)); // Et on le modifie if (selection_start<=selection_end) { temp=selection_start; temp2=selection_end; } else { temp=selection_end; temp2=selection_start; } for (;temp<temp2;temp++,temp2--) { temp_cell=Shade_list[Shade_current].List[temp]; Shade_list[Shade_current].List[temp]=Shade_list[Shade_current].List[temp2]; Shade_list[Shade_current].List[temp2]=temp_cell; } Hide_cursor(); Display_all_shade(first_color,last_color,selection_start,selection_end); Display_cursor(); break; case 12 : // Swap temp_cell=Wait_click_in_shade_table(); if (temp_cell<512) { // On place le shade dans le buffer du Undo memcpy(undo_buffer,Shade_list[Shade_current].List,512*sizeof(word)); // Et on le modifie // On échange le bloc avec sa destination if (selection_start<=selection_end) { temp=(temp_cell+selection_end-selection_start<512)?selection_end+1-selection_start:512-temp_cell; Swap_shade(selection_start,temp_cell,temp); } else { temp=(temp_cell+selection_start-selection_end<512)?selection_start+1-selection_end:512-temp_cell; Swap_shade(selection_end,temp_cell,temp); } // On place la sélection sur la nouvelle position du bloc selection_start=temp_cell; selection_end=selection_start+temp-1; // Et on raffiche tout Hide_cursor(); Display_all_shade(first_color,last_color,selection_start,selection_end); Display_cursor(); } Wait_end_of_click(); break; case 13 : // Set (disable) case 14 : // Clear (enable) // On place le shade dans le buffer du Undo memcpy(undo_buffer,Shade_list[Shade_current].List,512*sizeof(word)); // Et on le modifie if (selection_start<selection_end) { temp=selection_start; temp2=selection_end; } else { temp=selection_end; temp2=selection_start; } if (clicked_button==13) for (;temp<=temp2;temp++) Shade_list[Shade_current].List[temp]|=0x8000; else for (;temp<=temp2;temp++) Shade_list[Shade_current].List[temp]&=0x7FFF; Hide_cursor(); Tag_shades(selection_start,selection_end); Shade_draw_grad_ranges(); Display_cursor(); break; case 15 : // Saisie du pas Num2str(Shade_list[Shade_current].Step,str,3); Readline(276,176,str,3,INPUT_TYPE_INTEGER); temp=atoi(str); // On corrige le pas if (!temp) { temp=1; Num2str(temp,str,3); Window_input_content(input_button,str); } else if (temp>255) { temp=255; Num2str(temp,str,3); Window_input_content(input_button,str); } Shade_list[Shade_current].Step=temp; Display_cursor(); break; case 16 : // Undo memcpy(temp_ptr,undo_buffer,512*sizeof(word)); memcpy(undo_buffer,Shade_list[Shade_current].List,512*sizeof(word)); memcpy(Shade_list[Shade_current].List,temp_ptr,512*sizeof(word)); Hide_cursor(); Display_all_shade(first_color,last_color,selection_start,selection_end); Display_cursor(); break; case 17 : // Clear memcpy(undo_buffer,Shade_list[Shade_current].List,512*sizeof(word)); for (temp=0;temp<512;temp++) Shade_list[Shade_current].List[temp]=0x0100; Hide_cursor(); Display_all_shade(first_color,last_color,selection_start,selection_end); Display_cursor(); break; case 18 : // Mode Shade_list[Shade_current].Mode=(Shade_list[Shade_current].Mode+1)%3; Hide_cursor(); Display_shade_mode(250,110,Shade_list[Shade_current].Mode); Display_cursor(); } if (!Mouse_K) switch (Key) { case KEY_LEFTBRACKET : // Décaler couleur dans palette vers la gauche case KEY_RIGHTBRACKET : // Décaler couleur dans palette vers la droite if (first_color==last_color) { if (Key==KEY_LEFTBRACKET) { first_color--; last_color--; } else { first_color++; last_color++; } Hide_cursor(); Tag_color_range(first_color,first_color); Block(Window_pos_X+(Menu_factor_X*172), Window_pos_Y+(Menu_factor_Y*27), Menu_factor_X<<4,Menu_factor_Y*64,first_color); // On affiche le numéro de la couleur sélectionnée Display_selected_color(first_color,last_color); Display_cursor(); } Key=0; break; case KEY_UP : // Select Haut case KEY_DOWN : // Select Bas case KEY_LEFT : // Select Gauche case KEY_RIGHT : // Select Droite if (selection_start==selection_end) { switch (Key) { case KEY_UP : // Select Haut if (selection_start>=64) { selection_start-=64; selection_end-=64; } else selection_start=selection_end=0; break; case KEY_DOWN : // Select Bas if (selection_start<448) { selection_start+=64; selection_end+=64; } else selection_start=selection_end=511; break; case KEY_LEFT : // Select Gauche if (selection_start>0) { selection_start--; selection_end--; } break; default : // Select Droite if (selection_start<511) { selection_start++; selection_end++; } } Hide_cursor(); Tag_shades(selection_start,selection_start); Display_selected_cell_color(selection_start,selection_start); Display_cursor(); } Key=0; break; case KEY_BACKQUOTE : // Récupération d'une couleur derrière le menu case KEY_COMMA : Get_color_behind_window(&color,&click); if (click) { Hide_cursor(); temp_color=color; // On met à jour l'intervalle du Shade first_color=last_color=temp_color; // On tagge le bloc Tag_color_range(first_color,last_color); // Tracé du bloc dégradé: Display_grad_block_in_window(172,27,16,64,first_color,last_color); // On affiche le numéro de la couleur sélectionnée Display_selected_color(first_color,last_color); Display_cursor(); Wait_end_of_click(); } Key=0; break; default: if (Is_shortcut(Key,0x100+BUTTON_HELP)) { Key=0; Window_help(BUTTON_EFFECTS, "SHADE"); } else if (Is_shortcut(Key,SPECIAL_SHADE_MENU)) clicked_button=5; } } while ((clicked_button!=4) && (clicked_button!=5)); Close_window(); free(undo_buffer); free(buffer); free(temp_ptr); return (clicked_button==5); } /// Handles the screen with Shade settings. /// @return true if user clicked ok, false if he cancelled int Shade_settings_menu(void) { T_Shade * initial_shade_list; // Anciennes données des shades byte old_shade; // old n° de shade actif int return_code; // Backup des anciennes données initial_shade_list=(T_Shade *)malloc(sizeof(Shade_list)); memcpy(initial_shade_list,Shade_list,sizeof(Shade_list)); old_shade=Shade_current; return_code = Menu_shade(); if (!return_code) // Cancel { memcpy(Shade_list,initial_shade_list,sizeof(Shade_list)); Shade_current=old_shade; } else // OK { Shade_list_to_lookup_tables(Shade_list[Shade_current].List, Shade_list[Shade_current].Step, Shade_list[Shade_current].Mode, Shade_table_left,Shade_table_right); } free(initial_shade_list); Display_cursor(); return return_code; } void Button_Shade_menu(void) { if (Shade_settings_menu()) { // If user clicked OK while in the menu, activate Shade mode. if (!Shade_mode) Button_Shade_mode(); } } void Button_Quick_shade_menu(void) { short clicked_button; int temp; char str[4]; byte step_backup=Quick_shade_step; // Backup des byte loop_backup=Quick_shade_loop; // anciennes données T_Special_button * step_button; Open_window(142,56,"Quick-shade"); Window_set_normal_button(76,36,60,14,"OK",0,1,KEY_RETURN); // 1 Window_set_normal_button( 6,36,60,14,"Cancel",0,1,KEY_ESC); // 2 Window_set_normal_button(76,18,60,14,"",0,1,KEY_TAB); // 3 Display_shade_mode(83,21,Quick_shade_loop); // Déclaration & tracé de la zone de saisie du pas Print_in_window(5,21,"Step",MC_Dark,MC_Light); step_button = Window_set_input_button(40,19,3); // 4 Num2str(Quick_shade_step,str,3); Window_input_content(step_button,str); Update_window_area(0,0,142,56); Display_cursor(); do { clicked_button=Window_clicked_button(); switch (clicked_button) { case 3 : // Mode Quick_shade_loop=(Quick_shade_loop+1)%3; Hide_cursor(); Display_shade_mode(83,21,Quick_shade_loop); Display_cursor(); break; case 4 : // Saisie du pas Num2str(Quick_shade_step,str,3); Readline(42,21,str,3,INPUT_TYPE_INTEGER); temp=atoi(str); // On corrige le pas if (!temp) { temp=1; Num2str(temp,str,3); Window_input_content(step_button,str); } else if (temp>255) { temp=255; Num2str(temp,str,3); Window_input_content(step_button,str); } Quick_shade_step=temp; Display_cursor(); } if (Is_shortcut(Key,0x100+BUTTON_HELP)) Window_help(BUTTON_EFFECTS, "QUICK SHADE"); else if (Is_shortcut(Key,SPECIAL_QUICK_SHADE_MENU)) clicked_button=1; } while ((clicked_button!=1) && (clicked_button!=2)); Close_window(); if (clicked_button==2) // Cancel { Quick_shade_step=step_backup; Quick_shade_loop=loop_backup; } else // OK { // Si avant de rentrer dans le menu on n'était pas en mode Quick-Shade if (!Quick_shade_mode) Button_Quick_shade_mode(); // => On y passe (cool!) } Display_cursor(); }
29.880637
113
0.631099
4c6b51e2c19350f47a8003e976ce86ad1f7d1245
948
h
C
AEAssistant/Classes/AEAssistant_Category/UIKit/UIDevice/UIDevice+IdentifierAddition.h
AltairEven/AEAssistantPod
a3f0ab0555a337ce71758ee4f5fdea1d8d0790a9
[ "MIT" ]
1
2017-12-27T13:27:20.000Z
2017-12-27T13:27:20.000Z
AEAssistant/Classes/AEAssistant_Category/UIKit/UIDevice/UIDevice+IdentifierAddition.h
AltairEven/AEAssistantPod
a3f0ab0555a337ce71758ee4f5fdea1d8d0790a9
[ "MIT" ]
null
null
null
AEAssistant/Classes/AEAssistant_Category/UIKit/UIDevice/UIDevice+IdentifierAddition.h
AltairEven/AEAssistantPod
a3f0ab0555a337ce71758ee4f5fdea1d8d0790a9
[ "MIT" ]
null
null
null
/* * Copyright (c) 2012,腾讯科技有限公司 * All rights reserved. * * 文件名称:UIDevice+IdentifierAddition.h * 文件标识: * 摘 要: * * 当前版本:1.0 * 作 者:tomtctang * 完成日期:2012年9月18日 */ #import <UIKit/UIKit.h> @interface UIDevice (IdentifierAddition) /* * @method uniqueDeviceIdentifier * @description use this method when you need a unique identifier in one app. * It generates a hash from the MAC-address in combination with the bundle identifier * of your app. */ - (NSString *) uniqueDeviceIdentifier; /* * @method uniqueGlobalDeviceIdentifier * @description use this method when you need a unique global identifier to track a device * with multiple apps. as example a advertising network will use this method to track the device * from different apps. * It generates a hash from the MAC-address only. */ - (NSString *) uniqueGlobalDeviceIdentifier; - (NSString *) vendorIdentifier:(NSString**)oldUdid; - (NSString *) platformString; @end
22.571429
96
0.729958
98042ae1572a41748f9a3b334c487a956878300a
2,971
h
C
engine/include/Scene/components.h
mrcoalp/dempsta-engine
5f60094c0f9eb2bc4541dcd96cdab3f0eafb7346
[ "MIT" ]
1
2020-12-08T17:15:46.000Z
2020-12-08T17:15:46.000Z
engine/include/Scene/components.h
mrcoalp/dempsta-engine
5f60094c0f9eb2bc4541dcd96cdab3f0eafb7346
[ "MIT" ]
null
null
null
engine/include/Scene/components.h
mrcoalp/dempsta-engine
5f60094c0f9eb2bc4541dcd96cdab3f0eafb7346
[ "MIT" ]
null
null
null
#pragma once #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <utility> #include "Core/core.h" #include "Core/uuid.h" #include "Renderer/label.h" #include "Renderer/subtexture.h" #include "Scene/scenecamera.h" #include "Scripting/scriptentity.h" #include "Sound/sound.h" namespace de { struct IDComponent { UUID uuid; }; struct NameComponent { std::string name; NameComponent() = default; explicit NameComponent(std::string name) : name(std::move(name)) {} explicit operator const std::string &() const noexcept { return name; } explicit operator const char*() const noexcept { return name.c_str(); } }; struct TransformComponent { glm::vec3 translation{0.f, 0.f, 0.f}; glm::vec3 rotation{0.f, 0.f, 0.f}; glm::vec3 scale{1.f, 1.f, 1.f}; [[nodiscard]] glm::mat4 GetTransform() const { auto rotationX = glm::rotate(glm::mat4(1.f), rotation.x, {1.f, 0.f, 0.f}); auto rotationY = glm::rotate(glm::mat4(1.f), rotation.y, {0.f, 1.f, 0.f}); auto rotationZ = glm::rotate(glm::mat4(1.f), rotation.z, {0.f, 0.f, 1.f}); return glm::translate(glm::mat4(1.f), translation) * rotationX * rotationY * rotationZ * glm::scale(glm::mat4(1.f), scale); } explicit operator glm::mat4() const noexcept { return GetTransform(); } TransformComponent() = default; explicit TransformComponent(const glm::vec3& translation) : translation(translation) {} }; struct SpriteComponent { glm::vec4 color{glm::vec4(1.0f)}; glm::vec2 anchor{glm::vec2(0.f)}; std::string asset; Ref<SubTexture2D> sprite; SpriteComponent() = default; explicit SpriteComponent(std::string asset) : asset(std::move(asset)) {} }; struct ScriptComponent { std::string asset; Scope<lua::ScriptEntity> instance; ScriptComponent() = default; explicit ScriptComponent(std::string asset) : asset(std::move(asset)) {} }; struct NativeScriptComponent { NativeScriptEntity* instance = nullptr; NativeScriptEntity* (*Create)(); void (*Destroy)(NativeScriptComponent*); template <class Script> void Bind() { Create = []() { return dynamic_cast<NativeScriptEntity*>(new Script()); }; Destroy = [](NativeScriptComponent* nsc) { delete nsc->instance; nsc->instance = nullptr; }; } NativeScriptComponent() = default; }; struct CameraComponent { SceneCamera camera; bool primary = false; bool fixedAspectRatio = false; CameraComponent() = default; }; struct LabelComponent { std::string asset; Ref<Label> label; glm::vec4 color = glm::vec4(1.0f); LabelComponent() = default; explicit LabelComponent(std::string asset) : asset(std::move(asset)) {} }; struct SoundComponent { std::string asset; Ref<SoundInstance> sound; SoundComponent() = default; explicit SoundComponent(std::string asset) : asset(std::move(asset)) {} }; } // namespace de
27.256881
131
0.655335
bca54dc709db7b836ee153e2434a68432187a823
3,821
h
C
_Coridium/MiClib/lpc12xx_gpio.h
TodWulff/MegaHurtz_ARMbasic_Repo
6ac16a87aae43376c4f7e475ccfbc75d09f05a9b
[ "Unlicense" ]
1
2018-11-19T06:08:47.000Z
2018-11-19T06:08:47.000Z
_Coridium/MiClib/lpc12xx_gpio.h
TodWulff/ARMbasic_Repo
6ac16a87aae43376c4f7e475ccfbc75d09f05a9b
[ "Unlicense" ]
null
null
null
_Coridium/MiClib/lpc12xx_gpio.h
TodWulff/ARMbasic_Repo
6ac16a87aae43376c4f7e475ccfbc75d09f05a9b
[ "Unlicense" ]
null
null
null
/**************************************************************************//** * $Id: lpc12xx_gpio.h 5070 2010-09-29 05:56:16Z cnh20509 $ * * @file lpc12xx_gpio.h * @brief Contains all macro definitions and function prototypes * support for GPIO firmware library on lpc12xx. * @version 1.0 * @date 26. Sep. 2010 * @author NXP MCU Team * * @note * Copyright (C) 2010 NXP Semiconductors(NXP). All rights reserved. * * @par * Software that is described herein is for illustrative purposes only * which provides customers with programming information regarding the * products. This software is supplied "AS IS" without any warranties. * NXP Semiconductors assumes no responsibility or liability for the * use of the software, conveys no license or title under any patent, * copyright, or mask work right to the product. NXP Semiconductors * reserves the right to make changes in the software without * notification. NXP Semiconductors also make no representation or * warranty that such application will be suitable for the specified * use without further testing or modification. ******************************************************************************/ /* Peripheral group ----------------------------------------------------------- */ /** @defgroup GPIO * @ingroup LPC1200CMSIS_FwLib_Drivers * @{ */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __LPC12xx_GPIO_H #define __LPC12xx_GPIO_H /* Includes ------------------------------------------------------------------- */ #include "lpc12xx.h" #include "lpc_types.h" #ifdef __cplusplus extern "C" { #endif /* Public Macros --------------------------------------------------------------- */ /** @defgroup GPIO_Public_Types * @{ */ /** @defgroup GPIO_interrupt_type * @{ */ #define GPIO_INTERRUPT_FALLING ((uint8_t)(0)) #define GPIO_INTERRUPT_RISING ((uint8_t)(1)) #define GPIO_INTERRUPT_BOTH_EDGES ((uint8_t)(2)) #define GPIO_INTERRUPT_LOW ((uint8_t)(3)) #define GPIO_INTERRUPT_HIGH ((uint8_t)(4)) #define PARAM_GPIO_INTERRUPT(TYPE) (( TYPE == GPIO_INTERRUPT_FALLING) || \ ( TYPE == GPIO_INTERRUPT_RISING) || \ ( TYPE == GPIO_INTERRUPT_BOTH_EDGES)|| \ ( TYPE == GPIO_INTERRUPT_LOW) || \ ( TYPE == GPIO_INTERRUPT_HIGH)) /** * @} */ /** * @} */ /* Public Functions ----------------------------------------------------------- */ /** @defgroup GPIO_Public_Functions * @{ */ void GPIO_SetMask(LPC_GPIO_TypeDef* pGPIO, uint8_t bitPosi, uint32_t mask); uint32_t GPIO_GetPinValue( LPC_GPIO_TypeDef* pGPIO, uint8_t bitPosi); void GPIO_SetOutValue(LPC_GPIO_TypeDef* pGPIO, uint32_t value); void GPIO_SetHighLevel(LPC_GPIO_TypeDef* pGPIO, uint8_t bitPosi, uint32_t value); void GPIO_SetLowLevel(LPC_GPIO_TypeDef* pGPIO, uint8_t bitPosi, uint32_t value); void GPIO_SetInvert(LPC_GPIO_TypeDef* pGPIO, uint8_t bitPosi, uint32_t value); void GPIO_SetDir(LPC_GPIO_TypeDef* pGPIO, uint8_t bitPosi, uint32_t value); uint32_t GPIO_GetDir( LPC_GPIO_TypeDef* pGPIO, uint8_t bitPosi); #ifdef _GPIO_INT void GPIO_IntSetType(LPC_GPIO_TypeDef* pGPIO, uint8_t bitPosi, uint8_t type ); uint32_t GPIO_IntGetRawStatus( LPC_GPIO_TypeDef* pGPIO, uint8_t bitPosi ); void GPIO_IntSetMask(LPC_GPIO_TypeDef* pGPIO, uint8_t bitPosi, uint32_t mask); uint32_t GPIO_IntGetMaskStatus( LPC_GPIO_TypeDef* pGPIO, uint8_t bitPosi ); void GPIO_IntClear(LPC_GPIO_TypeDef* pGPIO, uint8_t bitPosi, uint32_t value); #endif /** * @} */ #ifdef __cplusplus } #endif #endif /* __LPC12xx_GPIO_H */ /** * @} */ /* --------------------------------- End Of File ------------------------------ */
34.116071
83
0.604815
ad34184860c3e97c8b01e5771765d1aee8a7ae11
353
c
C
test/races/src/RaceTest19.c
mutilin/cpachecker-ldv
e57bec78f72d408abb4a6812044972324df298d4
[ "ECL-2.0", "Apache-2.0" ]
1
2017-03-10T07:42:29.000Z
2017-03-10T07:42:29.000Z
test/races/src/RaceTest19.c
mutilin/cpachecker-ldv
e57bec78f72d408abb4a6812044972324df298d4
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
test/races/src/RaceTest19.c
mutilin/cpachecker-ldv
e57bec78f72d408abb4a6812044972324df298d4
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* This test is similar to RaceTest18.c, but it has two usages with two locks */ int unsafe; int global; int f() { intLock(); g(); intUnlock(); return (0); } int g() { unsafe = 0; } int ldv_main() { int t; if (t) { splbio(); } else { kernDispatchDisable(); } f(); splx(); kernDispatchEnable(); }
11.766667
77
0.526912
21377287be92fad238f92e896c4d7c083b1bba4f
1,940
h
C
torch/csrc/lazy/core/shape.h
stungkit/pytorch
0f05e398705bf15406bce79f7ee57d3935ad2abd
[ "Intel" ]
2
2020-03-13T06:57:49.000Z
2020-05-17T04:18:14.000Z
torch/csrc/lazy/core/shape.h
stungkit/pytorch
0f05e398705bf15406bce79f7ee57d3935ad2abd
[ "Intel" ]
1
2022-01-10T18:39:28.000Z
2022-01-10T19:15:57.000Z
torch/csrc/lazy/core/shape.h
stungkit/pytorch
0f05e398705bf15406bce79f7ee57d3935ad2abd
[ "Intel" ]
1
2022-03-26T14:42:50.000Z
2022-03-26T14:42:50.000Z
#pragma once #include <ostream> #include <vector> #include <c10/core/Scalar.h> #include <torch/csrc/jit/passes/symbolic_shape_analysis.h> #include <torch/csrc/lazy/core/hash.h> C10_DECLARE_bool(ltc_enable_symbolic_shapes); namespace torch { namespace lazy { class TORCH_API Shape { public: Shape() = default; Shape(at::ScalarType scalar_type, c10::ArrayRef<int64_t> sizes); std::string to_string() const; c10::ScalarType scalar_type() const { return scalar_type_; } void set_scalar_type(at::ScalarType value) { scalar_type_ = value; } int64_t dim() const { return sizes_.size(); } c10::ArrayRef<int64_t> sizes() const { return sizes_; } int64_t size(int64_t dim) const { return sizes_.at(dim); } void set_size(int64_t dim, int64_t size) { sizes_.at(dim) = size; } const c10::optional<std::vector<bool>>& is_symbolic() const { return is_symbolic_; } // Makes a copy with symbolic dims applied Shape with_symbolic_dims( c10::optional<std::vector<bool>> symbolic_dims) const; size_t numel() const; hash_t hash(bool bakeInSizes) const; bool operator==(const Shape& other) const; private: c10::ScalarType scalar_type_{c10::ScalarType::Undefined}; // Stores which dimmensions are symbolic // If nullopt, either it hasn't been initialized or the symbolic // dimmensions are not calculatable c10::optional<std::vector<bool>> is_symbolic_ = c10::nullopt; // Sizes are the upper bound sizes for a tensor, used by XLA. std::vector<int64_t> sizes_; }; TORCH_API std::ostream& operator<<(std::ostream& out, const Shape& shape); TORCH_API bool symbolicShapeEnabled(); // Calculate and applies symbolic shapes onto the // Shape objects passed to result_shapes TORCH_API void applySymbolicShapesOnLT( const char* schema_str, std::vector<c10::IValue> args, std::vector<Shape>& result_shapes); } // namespace lazy } // namespace torch
24.871795
74
0.715464
42985879268efbf9d621b5eb47b72b07df898a8e
616
h
C
ios/Pods/Valet/Valet/VALSecureEnclaveValet_Protected.h
VMadalin/react-native-uport-signer
22ef440e07ccb1b0cc679d6730bc391484d57eb5
[ "Apache-2.0" ]
247
2015-12-07T10:32:19.000Z
2019-05-05T15:33:50.000Z
ios/Pods/Valet/Valet/VALSecureEnclaveValet_Protected.h
VMadalin/react-native-uport-signer
22ef440e07ccb1b0cc679d6730bc391484d57eb5
[ "Apache-2.0" ]
21
2018-06-19T23:02:19.000Z
2021-02-04T17:16:02.000Z
ios/Pods/Valet/Valet/VALSecureEnclaveValet_Protected.h
VMadalin/react-native-uport-signer
22ef440e07ccb1b0cc679d6730bc391484d57eb5
[ "Apache-2.0" ]
53
2015-12-14T12:35:31.000Z
2017-12-21T09:21:07.000Z
// // VALSecureEnclaveValet_Protected.h // Valet // // Created by Dan Federman on 1/23/17. // Copyright © 2017 Square, Inc. All rights reserved. // #import <Valet/VALValet.h> @interface VALSecureEnclaveValet () - (nullable NSData *)objectForKey:(nonnull NSString *)key userPrompt:(nullable NSString *)userPrompt userCancelled:(nullable inout BOOL *)userCancelled options:(nullable NSDictionary *)options; - (nullable NSString *)stringForKey:(nonnull NSString *)key userPrompt:(nullable NSString *)userPrompt userCancelled:(nullable inout BOOL *)userCancelled options:(nullable NSDictionary *)options; @end
32.421053
195
0.766234
5527f02e25d597cabacf1a27b13465407310b998
3,691
h
C
include/PossibleChar.h
zoumson/zoumson-Parking_Lot_License_Plate_Detection_Opencv
9fa2de14de713a13ef13ea70f2bb55f27ec66aef
[ "MIT", "Unlicense" ]
null
null
null
include/PossibleChar.h
zoumson/zoumson-Parking_Lot_License_Plate_Detection_Opencv
9fa2de14de713a13ef13ea70f2bb55f27ec66aef
[ "MIT", "Unlicense" ]
null
null
null
include/PossibleChar.h
zoumson/zoumson-Parking_Lot_License_Plate_Detection_Opencv
9fa2de14de713a13ef13ea70f2bb55f27ec66aef
[ "MIT", "Unlicense" ]
null
null
null
/* * License plate detection * See COPYRIGHT file at the top of the source tree. * * This product includes software developed by the * STARGUE Project (http://www.stargue.org/). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the STARGUE License Statement and * the GNU General Public License along with this program. If not, * see <http://www.lsstcorp.org/LegalNotices/>. */ /** * @file PossibleChar.h * * @brief Return all possible plates in a image. * * @author Adama Zouma * * @Contact: stargue49@gmail.com * */ // PossibleChar.h #ifndef POSSIBLE_CHAR_H #define POSSIBLE_CHAR_H #include<opencv2/core/core.hpp> #include<opencv2/imgproc/imgproc.hpp> namespace za { /** * Implementation of a Possible character for retrieving character * * A character is delimited by a rectangular area * the area itself has a center defined by a coordinate (x,y) * the rectangle diagonal length and aspect ratio are used to * check whether the possible character is a real character or not * */ class PossibleChar { public: /* ============================================================================ * Data Memeber Declaration * ============================================================================ */ std::vector<cv::Point> contour; cv::Rect boundingRect; int intCenterX; int intCenterY; double dblDiagonalSize; double dblAspectRatio; /* ============================================================================ * Member Function Declaration * ============================================================================ */ /** * \brief Custom constructor. * * \details Custom constructor. * * \param _contour [in] contour of an area, type is vector of opencv Point. * * * \return #void * * \attention * */ PossibleChar(std::vector<cv::Point> _contour); /** * \brief sort characters from left to right. * * \details Get 4 vertices of a plate, then the rectangle with specified color. * * \param pcLeft first compared possible characters, type is PossibleChar. * \param pcRight second compared possible characters, type is PossibleChar. * * \return #void * * \attention * */ static bool sortCharsLeftToRight(const PossibleChar &pcLeft, const PossibleChar & pcRight); /** * \brief Check if two Possible characters are equal. * * \details Check if two Possible characters are equal. * * \param otherPossibleChar [in] compared possible characters, type is PossibleChar. * * \return # type is bool. * * \attention * */ bool operator == (const PossibleChar& otherPossibleChar) const; /** * \brief Check if two Possible characters are different. * * \details Check if two Possible characters are different. * * \param otherPossibleChar [in] compared possible characters, type is PossibleChar. * * \return # type is bool. * * \attention * */ bool operator != (const PossibleChar& otherPossibleChar) const; }; } #endif // POSSIBLE_CHAR_H
26.941606
96
0.607965
05ec9e21d201857de0ee34d3caed78bdfbd3ef9a
1,424
h
C
WVideoPlayer/Classes/WVideoManager.h
zzttwzq/WVideoPlayer
e9d0a8df016de340f5cd13c331e7cae7fcc1d7ca
[ "MIT" ]
2
2019-01-15T08:16:52.000Z
2019-01-15T09:19:07.000Z
WVideoPlayer/Classes/WVideoManager.h
zzttwzq/WVideoPlayer
e9d0a8df016de340f5cd13c331e7cae7fcc1d7ca
[ "MIT" ]
null
null
null
WVideoPlayer/Classes/WVideoManager.h
zzttwzq/WVideoPlayer
e9d0a8df016de340f5cd13c331e7cae7fcc1d7ca
[ "MIT" ]
null
null
null
// // WVideoManager.h // Pods // // Created by 吴志强 on 2018/7/18. // #import <Foundation/Foundation.h> #import "WVideoPlayItem.h" typedef NS_ENUM(NSInteger,WPlayState) { WPlayState_PrepareToPlay, WPlayState_isPlaying, WPlayState_Paused, WPlayState_Stoped, WPlayState_Finished, WPlayState_Seeking, WPlayState_Failed, WPlayState_UnKown, }; @class WVideoManager; @protocol WPlayManagerDelegate <NSObject> - (void) playStateChanged:(WPlayState)playState manager:(WVideoManager *)manager; - (void) totalTimeChanged:(NSString *)totalTimeString totalTime:(NSTimeInterval)totalTime playItem:(WVideoPlayItem *)playItem; - (void) scheduleTimeChanged:(NSString *)scheduleTimeString currentTime:(NSTimeInterval)currentTime playItem:(WVideoPlayItem *)playItem; - (void) bufferTimeChanged:(NSTimeInterval)bufferTime playItem:(WVideoPlayItem *)playItem; @end @interface WVideoManager : NSObject @property (nonatomic,weak) id<WPlayManagerDelegate> delegate; /** 自动重新播放 */ @property (nonatomic,assign) BOOL autoReplay; /** 播放图层 */ @property (nonatomic,strong) AVPlayerLayer *layer; /** 设置播放源 */ @property (nonatomic,strong) WVideoPlayItem *item; /** 播放状态 */ @property (nonatomic,assign) WPlayState playState; /** 进度条正在被拖拽 */ @property (nonatomic,assign) BOOL isSliding; /** 播放到当前时间 @param timeinterval 播放时间 */ - (void) playWithTimeInterval:(NSTimeInterval)timeinterval; @end
19.777778
136
0.753511
e2fa65a05fa749231113449c0a9ed47298deb842
712
h
C
src/OSSupport/Event.h
planetx/MCServer
4e119b522409af682e62ed38f4d22ddd9da40170
[ "Apache-2.0" ]
null
null
null
src/OSSupport/Event.h
planetx/MCServer
4e119b522409af682e62ed38f4d22ddd9da40170
[ "Apache-2.0" ]
null
null
null
src/OSSupport/Event.h
planetx/MCServer
4e119b522409af682e62ed38f4d22ddd9da40170
[ "Apache-2.0" ]
null
null
null
// Event.h // Interfaces to the cEvent object representing an OS-specific synchronization primitive that can be waited-for // Implemented as an Event on Win and as a 1-semaphore on *nix #pragma once #ifndef CEVENT_H_INCLUDED #define CEVENT_H_INCLUDED class cEvent { public: cEvent(void); ~cEvent(); void Wait(void); void Set (void); /** Waits for the event until either it is signalled, or the (relative) timeout is passed. Returns true if the event was signalled, false if the timeout was hit or there was an error. */ bool Wait(int a_TimeoutMSec); private: #ifdef _WIN32 HANDLE m_Event; #else sem_t * m_Event; bool m_bIsNamed; #endif } ; #endif // CEVENT_H_INCLUDED
13.692308
111
0.716292
824b3bec892e9bdc966f2ff07413ae09c81e9d68
11,376
h
C
externals/lcm/lcm-1.0.0/lcm/lcm_coretypes.h
ericmanzi/double_pendulum_lqr
76bba3091295abb7d412c4a3156258918f280c96
[ "BSD-3-Clause" ]
null
null
null
externals/lcm/lcm-1.0.0/lcm/lcm_coretypes.h
ericmanzi/double_pendulum_lqr
76bba3091295abb7d412c4a3156258918f280c96
[ "BSD-3-Clause" ]
null
null
null
externals/lcm/lcm-1.0.0/lcm/lcm_coretypes.h
ericmanzi/double_pendulum_lqr
76bba3091295abb7d412c4a3156258918f280c96
[ "BSD-3-Clause" ]
null
null
null
#ifndef _LCM_LIB_INLINE_H #define _LCM_LIB_INLINE_H #include <stdio.h> #include <stdint.h> #include <string.h> #include <stdlib.h> #ifdef __cplusplus extern "C" { #endif union float_uint32 { float f; uint32_t i; }; union double_uint64 { double f; uint64_t i; }; typedef struct ___lcm_hash_ptr __lcm_hash_ptr; struct ___lcm_hash_ptr { const __lcm_hash_ptr *parent; void *v; }; /** * BOOLEAN */ #define __boolean_hash_recursive __int8_t_hash_recursive #define __boolean_decode_array_cleanup __int8_t_decode_array_cleanup #define __boolean_encoded_array_size __int8_t_encoded_array_size #define __boolean_encode_array __int8_t_encode_array #define __boolean_decode_array __int8_t_decode_array #define __boolean_clone_array __int8_t_clone_array #define boolean_encoded_size int8_t_encoded_size /** * BYTE */ #define __byte_hash_recursive(p) 0 #define __byte_decode_array_cleanup(p, sz) {} #define byte_encoded_size(p) ( sizeof(int64_t) + sizeof(uint8_t) ) static inline int __byte_encoded_array_size(const uint8_t *p, int elements) { (void)p; return sizeof(uint8_t) * elements; } static inline int __byte_encode_array(void *_buf, int offset, int maxlen, const uint8_t *p, int elements) { if (maxlen < elements) return -1; uint8_t *buf = (uint8_t*) _buf; memcpy(&buf[offset], p, elements); return elements; } static inline int __byte_decode_array(const void *_buf, int offset, int maxlen, uint8_t *p, int elements) { if (maxlen < elements) return -1; uint8_t *buf = (uint8_t*) _buf; memcpy(p, &buf[offset], elements); return elements; } static inline int __byte_clone_array(const uint8_t *p, uint8_t *q, int elements) { memcpy(q, p, elements * sizeof(uint8_t)); return 0; } /** * INT8_T */ #define __int8_t_hash_recursive(p) 0 #define __int8_t_decode_array_cleanup(p, sz) {} #define int8_t_encoded_size(p) ( sizeof(int64_t) + sizeof(int8_t) ) static inline int __int8_t_encoded_array_size(const int8_t *p, int elements) { (void)p; return sizeof(int8_t) * elements; } static inline int __int8_t_encode_array(void *_buf, int offset, int maxlen, const int8_t *p, int elements) { if (maxlen < elements) return -1; int8_t *buf = (int8_t*) _buf; memcpy(&buf[offset], p, elements); return elements; } static inline int __int8_t_decode_array(const void *_buf, int offset, int maxlen, int8_t *p, int elements) { if (maxlen < elements) return -1; int8_t *buf = (int8_t*) _buf; memcpy(p, &buf[offset], elements); return elements; } static inline int __int8_t_clone_array(const int8_t *p, int8_t *q, int elements) { memcpy(q, p, elements * sizeof(int8_t)); return 0; } /** * INT16_T */ #define __int16_t_hash_recursive(p) 0 #define __int16_t_decode_array_cleanup(p, sz) {} #define int16_t_encoded_size(p) ( sizeof(int64_t) + sizeof(int16_t) ) static inline int __int16_t_encoded_array_size(const int16_t *p, int elements) { (void)p; return sizeof(int16_t) * elements; } static inline int __int16_t_encode_array(void *_buf, int offset, int maxlen, const int16_t *p, int elements) { int total_size = sizeof(int16_t) * elements; uint8_t *buf = (uint8_t*) _buf; int pos = offset; int element; if (maxlen < total_size) return -1; for (element = 0; element < elements; element++) { int16_t v = p[element]; buf[pos++] = (v>>8) & 0xff; buf[pos++] = (v & 0xff); } return total_size; } static inline int __int16_t_decode_array(const void *_buf, int offset, int maxlen, int16_t *p, int elements) { int total_size = sizeof(int16_t) * elements; uint8_t *buf = (uint8_t*) _buf; int pos = offset; int element; if (maxlen < total_size) return -1; for (element = 0; element < elements; element++) { p[element] = (buf[pos]<<8) + buf[pos+1]; pos+=2; } return total_size; } static inline int __int16_t_clone_array(const int16_t *p, int16_t *q, int elements) { memcpy(q, p, elements * sizeof(int16_t)); return 0; } /** * INT32_T */ #define __int32_t_hash_recursive(p) 0 #define __int32_t_decode_array_cleanup(p, sz) {} #define int32_t_encoded_size(p) ( sizeof(int64_t) + sizeof(int32_t) ) static inline int __int32_t_encoded_array_size(const int32_t *p, int elements) { (void)p; return sizeof(int32_t) * elements; } static inline int __int32_t_encode_array(void *_buf, int offset, int maxlen, const int32_t *p, int elements) { int total_size = sizeof(int32_t) * elements; uint8_t *buf = (uint8_t*) _buf; int pos = offset; int element; if (maxlen < total_size) return -1; for (element = 0; element < elements; element++) { int32_t v = p[element]; buf[pos++] = (v>>24)&0xff; buf[pos++] = (v>>16)&0xff; buf[pos++] = (v>>8)&0xff; buf[pos++] = (v & 0xff); } return total_size; } static inline int __int32_t_decode_array(const void *_buf, int offset, int maxlen, int32_t *p, int elements) { int total_size = sizeof(int32_t) * elements; uint8_t *buf = (uint8_t*) _buf; int pos = offset; int element; if (maxlen < total_size) return -1; for (element = 0; element < elements; element++) { p[element] = (buf[pos+0]<<24) + (buf[pos+1]<<16) + (buf[pos+2]<<8) + buf[pos+3]; pos+=4; } return total_size; } static inline int __int32_t_clone_array(const int32_t *p, int32_t *q, int elements) { memcpy(q, p, elements * sizeof(int32_t)); return 0; } /** * INT64_T */ #define __int64_t_hash_recursive(p) 0 #define __int64_t_decode_array_cleanup(p, sz) {} #define int64_t_encoded_size(p) ( sizeof(int64_t) + sizeof(int64_t) ) static inline int __int64_t_encoded_array_size(const int64_t *p, int elements) { (void)p; return sizeof(int64_t) * elements; } static inline int __int64_t_encode_array(void *_buf, int offset, int maxlen, const int64_t *p, int elements) { int total_size = sizeof(int64_t) * elements; uint8_t *buf = (uint8_t*) _buf; int pos = offset; int element; if (maxlen < total_size) return -1; for (element = 0; element < elements; element++) { int64_t v = p[element]; buf[pos++] = (v>>56)&0xff; buf[pos++] = (v>>48)&0xff; buf[pos++] = (v>>40)&0xff; buf[pos++] = (v>>32)&0xff; buf[pos++] = (v>>24)&0xff; buf[pos++] = (v>>16)&0xff; buf[pos++] = (v>>8)&0xff; buf[pos++] = (v & 0xff); } return total_size; } static inline int __int64_t_decode_array(const void *_buf, int offset, int maxlen, int64_t *p, int elements) { int total_size = sizeof(int64_t) * elements; uint8_t *buf = (uint8_t*) _buf; int pos = offset; int element; if (maxlen < total_size) return -1; for (element = 0; element < elements; element++) { int64_t a = (buf[pos+0]<<24) + (buf[pos+1]<<16) + (buf[pos+2]<<8) + buf[pos+3]; pos+=4; int64_t b = (buf[pos+0]<<24) + (buf[pos+1]<<16) + (buf[pos+2]<<8) + buf[pos+3]; pos+=4; p[element] = (a<<32) + (b&0xffffffff); } return total_size; } static inline int __int64_t_clone_array(const int64_t *p, int64_t *q, int elements) { memcpy(q, p, elements * sizeof(int64_t)); return 0; } /** * FLOAT */ #define __float_hash_recursive(p) 0 #define __float_decode_array_cleanup(p, sz) {} #define float_encoded_size(p) ( sizeof(int64_t) + sizeof(float) ) static inline int __float_encoded_array_size(const float *p, int elements) { (void)p; return sizeof(float) * elements; } static inline int __float_encode_array(void *_buf, int offset, int maxlen, const float *p, int elements) { return __int32_t_encode_array(_buf, offset, maxlen, (int32_t*) p, elements); } static inline int __float_decode_array(const void *_buf, int offset, int maxlen, float *p, int elements) { return __int32_t_decode_array(_buf, offset, maxlen, (int32_t*) p, elements); } static inline int __float_clone_array(const float *p, float *q, int elements) { memcpy(q, p, elements * sizeof(float)); return 0; } /** * DOUBLE */ #define __double_hash_recursive(p) 0 #define __double_decode_array_cleanup(p, sz) {} #define double_encoded_size(p) ( sizeof(int64_t) + sizeof(double) ) static inline int __double_encoded_array_size(const double *p, int elements) { (void)p; return sizeof(double) * elements; } static inline int __double_encode_array(void *_buf, int offset, int maxlen, const double *p, int elements) { return __int64_t_encode_array(_buf, offset, maxlen, (int64_t*) p, elements); } static inline int __double_decode_array(const void *_buf, int offset, int maxlen, double *p, int elements) { return __int64_t_decode_array(_buf, offset, maxlen, (int64_t*) p, elements); } static inline int __double_clone_array(const double *p, double *q, int elements) { memcpy(q, p, elements * sizeof(double)); return 0; } /** * STRING */ #define __string_hash_recursive(p) 0 static inline int __string_decode_array_cleanup(char **s, int elements) { int element; for (element = 0; element < elements; element++) free(s[element]); return 0; } static inline int __string_encoded_array_size(char * const *s, int elements) { int size = 0; int element; for (element = 0; element < elements; element++) size += 4 + strlen(s[element]) + 1; return size; } static inline int __string_encoded_size(char * const *s) { return sizeof(int64_t) + __string_encoded_array_size(s, 1); } static inline int __string_encode_array(void *_buf, int offset, int maxlen, char * const *p, int elements) { int pos = 0, thislen; int element; for (element = 0; element < elements; element++) { int length = strlen(p[element]) + 1; // length includes \0 thislen = __int32_t_encode_array(_buf, offset + pos, maxlen - pos, &length, 1); if (thislen < 0) return thislen; else pos += thislen; thislen = __int8_t_encode_array(_buf, offset + pos, maxlen - pos, (int8_t*) p[element], length); if (thislen < 0) return thislen; else pos += thislen; } return pos; } static inline int __string_decode_array(const void *_buf, int offset, int maxlen, char **p, int elements) { int pos = 0, thislen; int element; for (element = 0; element < elements; element++) { int length; // read length including \0 thislen = __int32_t_decode_array(_buf, offset + pos, maxlen - pos, &length, 1); if (thislen < 0) return thislen; else pos += thislen; p[element] = (char*) malloc(length); thislen = __int8_t_decode_array(_buf, offset + pos, maxlen - pos, (int8_t*) p[element], length); if (thislen < 0) return thislen; else pos += thislen; } return pos; } static inline int __string_clone_array(char * const *p, char **q, int elements) { int element; for (element = 0; element < elements; element++) { // because strdup is not C99 size_t len = strlen(p[element]) + 1; q[element] = (char*) malloc (len); memcpy (q[element], p[element], len); } return 0; } static inline void *lcm_malloc(size_t sz) { if (sz) return malloc(sz); return NULL; } #ifdef __cplusplus } #endif #endif
25.223947
108
0.65814
5ea74bc65c56dfb93a2d1a2226977c30bbc24934
4,634
c
C
includes/drivers/events/quick_start_interrupt_hook/qs_events_interrupt_hook.c
LordSpacehog/samd21-baremetal-template
6235d3cade90fb7e1db5b779021d3585e06575ea
[ "Unlicense" ]
null
null
null
includes/drivers/events/quick_start_interrupt_hook/qs_events_interrupt_hook.c
LordSpacehog/samd21-baremetal-template
6235d3cade90fb7e1db5b779021d3585e06575ea
[ "Unlicense" ]
null
null
null
includes/drivers/events/quick_start_interrupt_hook/qs_events_interrupt_hook.c
LordSpacehog/samd21-baremetal-template
6235d3cade90fb7e1db5b779021d3585e06575ea
[ "Unlicense" ]
1
2020-03-08T01:50:58.000Z
2020-03-08T01:50:58.000Z
/** * \file * * \brief SAM Event System Driver Quick Start * * Copyright (C) 2014-2015 Atmel Corporation. All rights reserved. * * \asf_license_start * * \page License * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name of Atmel may not be used to endorse or promote products derived * from this software without specific prior written permission. * * 4. This software may only be redistributed and used in connection with an * Atmel microcontroller product. * * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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. * * \asf_license_stop * */ /* * Support and FAQ: visit <a href="http://www.atmel.com/design-support/">Atmel Support</a> */ #include <asf.h> #include "conf_qs_events_interrupt_hook.h" //! [setup] static volatile uint32_t event_count = 0; void event_counter(struct events_resource *resource); static void configure_event_channel(struct events_resource *resource) { //! [setup_1] struct events_config config; //! [setup_1] //! [setup_2] events_get_config_defaults(&config); //! [setup_2] //! [setup_3] config.generator = CONF_EVENT_GENERATOR; config.edge_detect = EVENTS_EDGE_DETECT_RISING; config.path = EVENTS_PATH_SYNCHRONOUS; config.clock_source = GCLK_GENERATOR_0; //! [setup_3] //! [setup_4] events_allocate(resource, &config); //! [setup_4] } static void configure_event_user(struct events_resource *resource) { //! [setup_5] events_attach_user(resource, CONF_EVENT_USER); //! [setup_5] } static void configure_tc(struct tc_module *tc_instance) { //! [setup_6] struct tc_config config_tc; struct tc_events config_events; //! [setup_6] //! [setup_7] tc_get_config_defaults(&config_tc); //! [setup_7] //! [setup_8] config_tc.counter_size = TC_COUNTER_SIZE_8BIT; config_tc.wave_generation = TC_WAVE_GENERATION_NORMAL_FREQ; config_tc.clock_source = GCLK_GENERATOR_1; config_tc.clock_prescaler = TC_CLOCK_PRESCALER_DIV64; //! [setup_8] //! [setup_9] tc_init(tc_instance, CONF_TC_MODULE, &config_tc); //! [setup_9] //! [setup_10] config_events.generate_event_on_overflow = true; tc_enable_events(tc_instance, &config_events); //! [setup_10] //! [setup_11] tc_enable(tc_instance); //! [setup_11] } static void configure_event_interrupt(struct events_resource *resource, struct events_hook *hook) { //! [setup_12] events_create_hook(hook, event_counter); //! [setup_12] //! [setup_13] events_add_hook(resource, hook); events_enable_interrupt_source(resource, EVENTS_INTERRUPT_DETECT); //! [setup_13] } //! [setup_14] void event_counter(struct events_resource *resource) { if(events_is_interrupt_set(resource, EVENTS_INTERRUPT_DETECT)) { port_pin_toggle_output_level(LED_0_PIN); event_count++; events_ack_interrupt(resource, EVENTS_INTERRUPT_DETECT); } } //! [setup_14] //! [setup] int main(void) { //! [setup_init] struct tc_module tc_instance; struct events_resource example_event; struct events_hook hook; system_init(); system_interrupt_enable_global(); configure_event_channel(&example_event); configure_event_user(&example_event); configure_event_interrupt(&example_event, &hook); configure_tc(&tc_instance); //! [setup_init] //! [main] //! [main_1] while (events_is_busy(&example_event)) { /* Wait for channel */ }; //! [main_1] //! [main_2] tc_start_counter(&tc_instance); //! [main_2] while (true) { /* Nothing to do */ } //! [main] }
25.461538
90
0.734786
c3c8a20c43ce074fd8ff5199aef29294110ce712
10,046
c
C
Nexus Game Builder/code/ai/ai_logic.c
3RUN/Retro-FPS
638a2dc5555c864a58aca5f1ae05d8fad9909791
[ "MIT" ]
6
2019-08-02T20:23:34.000Z
2022-01-20T05:33:45.000Z
code/ai/ai_logic.c
3RUN/Retro-FPS
638a2dc5555c864a58aca5f1ae05d8fad9909791
[ "MIT" ]
1
2021-02-11T16:55:59.000Z
2021-02-11T16:55:59.000Z
code/ai/ai_logic.c
3RUN/Retro-FPS
638a2dc5555c864a58aca5f1ae05d8fad9909791
[ "MIT" ]
1
2019-08-04T13:07:00.000Z
2019-08-04T13:07:00.000Z
// detect near by enemies void npc_detect_enemies(ENTITY *ent, NPC *npc) { c_ignore(SWITCH_ITEM_GROUP, PROJECTILE_GROUP, NPC_GROUP, SHOOT_THROUGH_GROUP, OBSTACLE_GROUP, 0); ent_scan(ent, &ent->x, &ent->pan, vector(360, 0, npc->scan_range), MOVE_FLAGS | SCAN_ENTS | SCAN_FLAG2); } // alert other npcs near by void npc_alert_friends(ENTITY *ent, NPC *npc) { c_ignore(SWITCH_ITEM_GROUP, PROJECTILE_GROUP, PLAYER_GROUP, SHOOT_THROUGH_GROUP, OBSTACLE_GROUP, 0); ent_scan(ent, &ent->x, &ent->pan, vector(360, 0, npc->scan_range), MOVE_FLAGS | SCAN_ENTS | SCAN_FLAG2); } // checks if you entity is visible or not // this function is called from event function only! var npc_is_you_visible(ENTITY *my_ent, NPC *npc, ENTITY *you_ent) { if (!my_ent || !you_ent) { error("No valid my or you pointers in is_you_visible funciton!"); return; } ENTITY *temp_my = my_ent; ENTITY *temp_you = you_ent; wait(1); // because we are calling this in event function c_ignore(SWITCH_ITEM_GROUP, PROJECTILE_GROUP, PLAYER_GROUP, NPC_GROUP, SHOOT_THROUGH_GROUP, 0); c_trace(&temp_my->x, &temp_you->x, TRACE_FLAGS); if (HIT_TARGET) { return false; } // if you is player if (temp_you->OBJ_TYPE == TYPE_PLAYER) { npc->target_ent = temp_you; npc->is_triggered = true; } else if (temp_you->OBJ_TYPE == TYPE_NPC) { if (npc->target_ent) { NPC *friendly_npc = get_npc(temp_you); friendly_npc->is_triggered = true; friendly_npc->target_ent = npc->target_ent; NPC *friendly_npc = NULL; } } temp_my = NULL; temp_you = NULL; return true; } // check if npc can see it's target var npc_is_target_visible(ENTITY *ent, NPC *npc) { if (!npc->target_ent) { diag("\nERROR! No visibility check for npc, target ent it doesn't exist!"); return false; } c_ignore(SWITCH_ITEM_GROUP, PROJECTILE_GROUP, PLAYER_GROUP, SHOOT_THROUGH_GROUP, 0); var trace_res = ent_trace(ent, &ent->x, &npc->target_ent->x, TRACE_FLAGS); if (trace_res > 0) { return false; } return true; } // simple obstacle avoidance void npc_obstacle_avoidance(ENTITY *ent, NPC *npc) { vec_set(&npc->sensor_right, vector(npc->sensor_distance, -npc->sensor_width, 0)); vec_rotate(&npc->sensor_right, vector(npc->cct.rotaton_pan, 0, 0)); vec_add(&npc->sensor_right, &ent->x); c_ignore(SWITCH_ITEM_GROUP, PROJECTILE_GROUP, 0); ent_trace(ent, &ent->x, &npc->sensor_right, TRACE_FLAGS); npc->sensor_hit_right = false; if (HIT_TARGET) { npc->sensor_hit_right = true; npc->route_timer = 0; npc->route_find = true; } vec_set(&npc->sensor_left, vector(npc->sensor_distance, npc->sensor_width, 0)); vec_rotate(&npc->sensor_left, vector(npc->cct.rotaton_pan, 0, 0)); vec_add(&npc->sensor_left, &ent->x); c_ignore(SWITCH_ITEM_GROUP, PROJECTILE_GROUP, 0); ent_trace(ent, &ent->x, &npc->sensor_left, TRACE_FLAGS); npc->sensor_hit_left = false; if (HIT_TARGET) { npc->sensor_hit_left = true; npc->route_timer = 0; npc->route_find = true; } if (npc->sensor_hit_right == true && npc->sensor_hit_left == true) { npc->cct.rotaton_pan += (180 + (random(90) - random(90))); } else if (npc->sensor_hit_right == true) { npc->cct.rotaton_pan += 45 + random(45); } else if (npc->sensor_hit_left == true) { npc->cct.rotaton_pan -= 45 + random(45); } // intaraction trace vec_set(&npc->sensor_ahead, vector(npc->sensor_distance + 4, 0, 0)); vec_rotate(&npc->sensor_ahead, vector(npc->cct.rotaton_pan, 0, 0)); vec_add(&npc->sensor_ahead, &ent->x); c_ignore(SWITCH_ITEM_GROUP, PROJECTILE_GROUP, PLAYER_GROUP, NPC_GROUP, SHOOT_THROUGH_GROUP, 0); npc->sensor_hit_ahead = ent_trace(ent, &ent->x, &npc->sensor_ahead, TRACE_FLAGS | ACTIVATE_SHOOT); #ifdef AI_SHOW_SENSORS draw_point3d(&npc->sensor_right, COLOR_WHITE, 100, 1); draw_point3d(&npc->sensor_left, COLOR_WHITE, 100, 1); draw_point3d(&npc->sensor_ahead, COLOR_RED, 100, 1); #endif } // rotate npc to the given target void npc_rotate_to(ENTITY *ent, NPC *npc, VECTOR *pos) { if (!ent || !npc) { error("Can't rotate npc to target, entity or it's structure doesn't exist!"); return; } ANGLE temp_angle; vec_to_angle(&temp_angle, vec_diff(NULL, pos, &ent->x)); npc->cct.rotaton_pan = temp_angle.pan; } // rotate to something using obstacle avoidance void npc_rotate_to_with_avoidance(ENTITY *ent, NPC *npc, VECTOR *pos) { // if we aren't looking for a new route // then we can look at the player ! if (npc->route_find == false) { npc_rotate_to(ent, npc, pos); } else { // this is executed each half of a second // since fps_max is limited to 60 if ((total_frames % 30) == 1) { // if we can see player, while finding new route // then we can chase him directly if (npc_is_target_visible(ent, npc) == true) { npc->route_timer = npc->route_def_time; } } // well.. it we are looking for a new route // then do that for a specific amount of time only ! // then rotate back to player and try to rich him npc->route_timer += time_frame / 16; if (npc->route_timer >= npc->route_def_time) { npc->route_find = false; npc->route_timer -= npc->route_def_time; } } } // detect walls on explosions void npc_check_walls(ENTITY *ent, VECTOR *from, VECTOR *to, var dmg) { // save input VECTOR you_pos; VECTOR my_pos; vec_set(&you_pos, from); vec_set(&my_pos, to); var temp_damage = dmg; wait(1); // because in called in event function ! // if we are close enough ? if (vec_dist(&you_pos, &my_pos) > explo_default_range) { return; } c_ignore(SWITCH_ITEM_GROUP, PROJECTILE_GROUP, PLAYER_GROUP, NPC_GROUP, SHOOT_THROUGH_GROUP, 0); if (c_trace(&you_pos, &my_pos, TRACE_FLAGS)) { return; } // calculate damage // 128 quants (by default), because it's the closes range var damage = (1 - (vec_dist(&you_pos, &my_pos) / explo_default_range)) * temp_damage; ent->OBJ_HEALTH -= damage + 32; // to make sure, that you will die, if very close // if your health is too low, then you need to spawn gibs if (ent->OBJ_HEALTH <= -20) { ent->OBJ_DEATH_TYPE = TYPE_SMASHED; } // push away VECTOR push_vec; vec_diff(&push_vec, &my_pos, &you_pos); vec_normalize(&push_vec, damage * 0.25); NPC *npc = get_npc(ent); vec_set(&npc->cct.abs_force, &push_vec); npc_go_to_state(my, npc, AI_PAIN_STATE); } // event function for all npcs void npc_event_function() { if (event_type == EVENT_PUSH) { // smashed by props ? if (you->OBJ_TYPE == TYPE_PROPS_SECRET) { // get props structure PROPS *props = get_props(you); NPC *npc = get_npc(my); // push us away vec_set(&npc->cct.push_force, vector(props->diff.x, props->diff.y, 0)); // if we can perform check ? // means that door is almost closed (f.e.) if (you->OBJ_CHECK == true) { // check if we were smashed or not if (props_vs_npc_check(you, my, my->scale_x) == true) { my->OBJ_HEALTH = -999; my->OBJ_DEATH_TYPE = TYPE_SMASHED; } } } } if (event_type == EVENT_SHOOT) { // take damage from projectiles if (you->OBJ_TYPE == TYPE_PLAYER_MELEE || you->OBJ_TYPE == TYPE_PLAYER_BULLET) { my->OBJ_HEALTH -= you->OBJ_TAKE_DAMAGE; NPC *npc = get_npc(my); npc_go_to_state(my, npc, AI_PAIN_STATE); if (npc->is_triggered == false) { npc->target_ent = you; npc->is_triggered = true; } } #ifdef FRIENDLY_FIRE // take damage from projectiles if (you->OBJ_TYPE == TYPE_NPC_MELEE || you->OBJ_TYPE == TYPE_NPC_BULLET) { my->OBJ_HEALTH -= you->OBJ_TAKE_DAMAGE; NPC *npc = get_npc(my); npc_go_to_state(my, npc, AI_PAIN_STATE); } #endif // if hit by rocket ? // explode right now ! if (you->OBJ_TYPE == TYPE_PLAYER_ROCKET) { my->OBJ_HEALTH = -999; } } if (event_type == EVENT_SCAN) { // if scan from any type of explosions if (you->OBJ_TYPE == TYPE_PLAYER_EXPLOSION || you->OBJ_TYPE == TYPE_PROPS_EXPLOSION) { // check for walls, push away from explosion etc npc_check_walls(my, &you->x, &my->x, you->OBJ_EXPLO_DAMAGE); } #ifdef FRIENDLY_FIRE if (you->OBJ_TYPE == TYPE_NPC_EXPLOSION) { // check for walls, push away from explosion etc npc_check_walls(my, &you->x, &my->x, you->OBJ_EXPLO_DAMAGE); } #endif } if (event_type == EVENT_DETECT) { NPC *npc = get_npc(my); // player ? if (you->OBJ_TYPE == TYPE_PLAYER && ent_is_alive(you) == true) { if (npc->is_triggered == false) { npc_is_you_visible(my, npc, you); } } // if we detect an npc near by and we are already trying to kill player if (you->OBJ_TYPE == TYPE_NPC) { if (npc->is_triggered == true) { NPC *friendly_npc = get_npc(you); if (friendly_npc->is_triggered == false) { npc_is_you_visible(my, npc, you); } } } } }
29.721893
108
0.588692
66cfa6f7a07049794064bd10362ea8468e43932a
362
h
C
src/sig/dilithium/pqclean_dilithium4_clean/rounding.h
MicrohexHQ/liboqs
6340a0ba71f66ad494ede00d38f358b2a4546164
[ "MIT" ]
5
2020-11-19T07:56:02.000Z
2021-10-04T03:38:55.000Z
src/sig/dilithium/pqclean_dilithium4_clean/rounding.h
MicrohexHQ/liboqs
6340a0ba71f66ad494ede00d38f358b2a4546164
[ "MIT" ]
1
2018-07-09T13:12:01.000Z
2018-07-19T15:03:08.000Z
src/sig/dilithium/pqclean_dilithium4_clean/rounding.h
MicrohexHQ/liboqs
6340a0ba71f66ad494ede00d38f358b2a4546164
[ "MIT" ]
1
2020-12-12T19:37:45.000Z
2020-12-12T19:37:45.000Z
#ifndef ROUNDING_H #define ROUNDING_H #include <stdint.h> uint32_t PQCLEAN_DILITHIUM4_CLEAN_power2round(uint32_t a, uint32_t *a0); uint32_t PQCLEAN_DILITHIUM4_CLEAN_decompose(uint32_t a, uint32_t *a0); unsigned int PQCLEAN_DILITHIUM4_CLEAN_make_hint(uint32_t a0, uint32_t a1); uint32_t PQCLEAN_DILITHIUM4_CLEAN_use_hint(uint32_t a, unsigned int hint); #endif
30.166667
74
0.842541
c94de6e81f2f0ed5b770e5651b070abb77adcca9
818
h
C
Lab04/GDI/GDI.h
TrumpZuo/WindowsProgrammingUsingMFCAndSDK
17280991c6f01bf89c1e01ef92efd85f81fa8941
[ "Apache-2.0" ]
2
2022-01-12T12:21:16.000Z
2022-01-15T01:38:37.000Z
Lab04/GDI/GDI.h
TrumpZuo/WindowsProgrammingUsingMFCAndSDK
17280991c6f01bf89c1e01ef92efd85f81fa8941
[ "Apache-2.0" ]
null
null
null
Lab04/GDI/GDI.h
TrumpZuo/WindowsProgrammingUsingMFCAndSDK
17280991c6f01bf89c1e01ef92efd85f81fa8941
[ "Apache-2.0" ]
null
null
null
#pragma once #define IDM_FILE_EXIT 1001 #define IDM_FUNC_LINETO 2001 #define IDM_FUNC_POLYLINE 2002 #define IDM_FUNC_ARC 2003 #define IDM_FUNC_RECTANGLE 2004 #define IDM_FUNC_ELLIPSE 2005 #define IDM_FUNC_ROUNDRECT 2006 #define IDM_FUNC_CHORD 2007 #define IDM_FUNC_PIE 2008 #define IDM_FUNC_POLYGON 2009 #define IDM_PEN_BLACK 3001 #define IDM_PEN_REDDASHDOT 3002 #define IDM_PEN_BLUESOLID 3003 #define IDM_BRUSH_WHITE 4001 #define IDM_BRUSH_LTGRAY 4002 #define IDM_BRUSH_COLORSOLID 4003 #define IDM_BRUSH_CROSS 4004 #define IDM_ABOUT 5001
31.461538
43
0.567237
c9dbfd6bdfd5d05330c6f731501865d3059c44db
1,726
h
C
Unreal/PocoSDK/Source/PocoSDK/Private/Misc/TickableObject.h
mtzhanglei/Poco-SDK
9f82581b779d180c068cae73f8a11e575d1eca0b
[ "Apache-2.0" ]
221
2018-01-25T09:00:08.000Z
2022-03-24T02:57:19.000Z
Unreal/PocoSDK/Source/PocoSDK/Private/Misc/TickableObject.h
mtzhanglei/Poco-SDK
9f82581b779d180c068cae73f8a11e575d1eca0b
[ "Apache-2.0" ]
93
2018-03-26T07:49:58.000Z
2021-12-20T12:31:19.000Z
Unreal/PocoSDK/Source/PocoSDK/Private/Misc/TickableObject.h
mtzhanglei/Poco-SDK
9f82581b779d180c068cae73f8a11e575d1eca0b
[ "Apache-2.0" ]
119
2018-02-26T22:27:51.000Z
2022-02-22T08:43:45.000Z
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "Tickable.h" namespace Poco { class FPocoManager; /** * Implements a tickable object that listens for incoming TCP connections. */ class FTickableObject : FTickableGameObject { public: /** * Creates and initializes a new instance from the owner. * * @param Parent The parent class that owns this tickable object. */ FTickableObject(FPocoManager* Manager) :Parent(Manager) {} /** * Overrides the Tick() method in the base class FTickableObjectBase. * * @param DeltaTime Game time passed since the last call. */ virtual void Tick(float DeltaTime) override; /** * Used to determine whether an object is ready to be ticked. * * @return true if object is ready to be ticked, false otherwise. */ virtual bool IsTickable() const override { return true; } /** * Used to determine if an object should be ticked when the game is paused. * * @return true if it should be ticked when paused, false otherwise. */ virtual bool IsTickableWhenPaused() const override { return true; } /** * Used to determine whether the object should be ticked in the editor. * * @return true if this tickable object can be ticked in the editor. */ virtual bool IsTickableInEditor() const override { return true; } /** * Returns the stat id to use for this tickable. * * @return The stat id to use for this tickable. **/ virtual TStatId GetStatId() const override { RETURN_QUICK_DECLARE_CYCLE_STAT(FPocoManager, STATGROUP_Tickables); } private: /** Holds the owner of this tickable object. */ FPocoManager* Parent; }; }
24.309859
77
0.693511
68a02c72514ffaace0f5ee31827fd9b85ba036b0
219
c
C
src/examples/echo/main/main.c
NDHANA94/rosserial_esp32
78e82edd2e1b0bbf1a65fa7a12042e2e111c8770
[ "BSD-2-Clause" ]
29
2019-07-14T00:06:12.000Z
2022-03-29T11:13:19.000Z
src/examples/echo/main/main.c
NDHANA94/rosserial_esp32
78e82edd2e1b0bbf1a65fa7a12042e2e111c8770
[ "BSD-2-Clause" ]
5
2020-02-05T17:48:42.000Z
2022-03-04T16:19:51.000Z
src/examples/echo/main/main.c
NDHANA94/rosserial_esp32
78e82edd2e1b0bbf1a65fa7a12042e2e111c8770
[ "BSD-2-Clause" ]
16
2019-09-19T18:06:59.000Z
2022-01-09T19:02:09.000Z
#include "stdio.h" #include "esp_echo.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" int app_main() { rosserial_setup(); while(1) { rosserial_spinonce(); vTaskDelay(100); } }
14.6
30
0.621005
c516f923614f11a62880b1b0fec81ec6516c1eeb
555
c
C
lldb/packages/Python/lldbsuite/test/python_api/hello_world/main.c
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
2,338
2018-06-19T17:34:51.000Z
2022-03-31T11:00:37.000Z
packages/Python/lldbsuite/test/python_api/hello_world/main.c
DalavanCloud/lldb
e913eaf2468290fb94c767d474d611b41a84dd69
[ "Apache-2.0" ]
3,740
2019-01-23T15:36:48.000Z
2022-03-31T22:01:13.000Z
packages/Python/lldbsuite/test/python_api/hello_world/main.c
DalavanCloud/lldb
e913eaf2468290fb94c767d474d611b41a84dd69
[ "Apache-2.0" ]
500
2019-01-23T07:49:22.000Z
2022-03-30T02:59:37.000Z
#include <stdio.h> #ifdef _MSC_VER #include <windows.h> #define sleep(x) Sleep((x) * 1000) #else #include <unistd.h> #endif int main(int argc, char const *argv[]) { lldb_enable_attach(); printf("Hello world.\n"); // Set break point at this line. if (argc == 1) return 1; // Create the synchronization token. FILE *f; if (f = fopen(argv[1], "wx")) { fputs("\n", f); fflush(f); fclose(f); } else return 1; // Waiting to be attached by the debugger, otherwise. while (1) sleep(1); // Waiting to be attached... }
18.5
60
0.609009
02a29a5cf2b97b21a5e71cfd57ad41a36137428a
2,494
h
C
Silicon/NXP/Drivers/I2cDxe/I2cDxe.h
jwang36/edk2-platforms
28d572fb96cd2697d903f6a3af94f6cb76948869
[ "Python-2.0", "Zlib", "BSD-2-Clause", "MIT", "BSD-2-Clause-Patent", "BSD-3-Clause" ]
1
2021-03-29T18:18:27.000Z
2021-03-29T18:18:27.000Z
Silicon/NXP/Drivers/I2cDxe/I2cDxe.h
jwang36/edk2-platforms
28d572fb96cd2697d903f6a3af94f6cb76948869
[ "Python-2.0", "Zlib", "BSD-2-Clause", "MIT", "BSD-2-Clause-Patent", "BSD-3-Clause" ]
null
null
null
Silicon/NXP/Drivers/I2cDxe/I2cDxe.h
jwang36/edk2-platforms
28d572fb96cd2697d903f6a3af94f6cb76948869
[ "Python-2.0", "Zlib", "BSD-2-Clause", "MIT", "BSD-2-Clause-Patent", "BSD-3-Clause" ]
null
null
null
/** I2cDxe.h Header defining the constant, base address amd function for I2C controller Copyright 2017-2019 NXP SPDX-License-Identifier: BSD-2-Clause-Patent **/ #ifndef I2C_DXE_H_ #define I2C_DXE_H_ #include <Library/UefiLib.h> #include <Uefi.h> #include <Protocol/I2cMaster.h> #include <Protocol/NonDiscoverableDevice.h> #define I2C_CR_IIEN (1 << 6) #define I2C_CR_MSTA (1 << 5) #define I2C_CR_MTX (1 << 4) #define I2C_CR_TX_NO_AK (1 << 3) #define I2C_CR_RSTA (1 << 2) #define I2C_SR_ICF (1 << 7) #define I2C_SR_IBB (1 << 5) #define I2C_SR_IAL (1 << 4) #define I2C_SR_IIF (1 << 1) #define I2C_SR_RX_NO_AK (1 << 0) #define I2C_CR_IEN (0 << 7) #define I2C_CR_IDIS (1 << 7) #define I2C_SR_IIF_CLEAR (1 << 1) #define BUS_IDLE (0 | (I2C_SR_IBB << 8)) #define BUS_BUSY (I2C_SR_IBB | (I2C_SR_IBB << 8)) #define IIF (I2C_SR_IIF | (I2C_SR_IIF << 8)) #define I2C_FLAG_WRITE 0x0 #define I2C_STATE_RETRIES 50000 #define RETRY_COUNT 3 #define NXP_I2C_SIGNATURE SIGNATURE_32 ('N', 'I', '2', 'C') #define NXP_I2C_FROM_THIS(a) CR ((a), NXP_I2C_MASTER, \ I2cMaster, NXP_I2C_SIGNATURE) extern EFI_COMPONENT_NAME2_PROTOCOL gNxpI2cDriverComponentName2; #pragma pack(1) typedef struct { VENDOR_DEVICE_PATH Vendor; UINT64 MmioBase; EFI_DEVICE_PATH_PROTOCOL End; } NXP_I2C_DEVICE_PATH; #pragma pack() typedef struct { UINT32 Signature; EFI_I2C_MASTER_PROTOCOL I2cMaster; NXP_I2C_DEVICE_PATH DevicePath; NON_DISCOVERABLE_DEVICE *Dev; } NXP_I2C_MASTER; /** Record defining i2c registers **/ typedef struct { UINT8 I2cAdr; UINT8 I2cFdr; UINT8 I2cCr; UINT8 I2cSr; UINT8 I2cDr; } I2C_REGS; typedef struct { UINT16 SCLDivider; UINT16 BusClockRate; } CLK_DIV; extern UINT64 GetBusFrequency ( VOID ); EFI_STATUS NxpI2cInit ( IN EFI_HANDLE DriverBindingHandle, IN EFI_HANDLE ControllerHandle ); EFI_STATUS NxpI2cRelease ( IN EFI_HANDLE DriverBindingHandle, IN EFI_HANDLE ControllerHandle ); #endif //I2C_DXE_H_
24.693069
77
0.578589
461e9eb17dec159f3e7f488a672cd974fc98c579
1,478
c
C
c/input/keyboard/capture_keyboard.c
vgonisanz/piperobashscripts
176d1efa4e04e2504e5df9e0025fb4a2634b9223
[ "MIT" ]
2
2016-09-27T11:14:49.000Z
2016-11-08T12:46:06.000Z
c/input/keyboard/capture_keyboard.c
vgonisanz/piperobashscripts
176d1efa4e04e2504e5df9e0025fb4a2634b9223
[ "MIT" ]
null
null
null
c/input/keyboard/capture_keyboard.c
vgonisanz/piperobashscripts
176d1efa4e04e2504e5df9e0025fb4a2634b9223
[ "MIT" ]
1
2020-05-22T12:28:00.000Z
2020-05-22T12:28:00.000Z
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <fcntl.h> #include <dirent.h> #include <linux/input.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/select.h> #include <sys/time.h> #include <termios.h> #include <signal.h> void handler (int sig) { printf ("Exiting... signal received: (%d)\n", sig); exit (0); } void perror_exit (char *error) { perror (error); handler (9); } int main (int argc, char *argv[]) { struct input_event ev[64]; int fd, rd, value, size = sizeof (struct input_event); char name[256] = "Unknown"; char *device = NULL; //Setup check if (argv[1] == NULL) { printf("Bad usage, Specified the path to the dev event interface\n"); printf("Sample /dev/input/event5\n"); exit (0); } if ((getuid ()) != 0) printf ("You are not root!\n"); if (argc > 1) device = argv[1]; //Open Device if ((fd = open (device, O_RDONLY)) == -1) printf ("Device: %s is not a valid device.\n", device); //Print Device Name ioctl (fd, EVIOCGNAME (sizeof (name)), name); printf ("Reading From : %s (%s), forever...\n", device, name); while (1) { if ((rd = read (fd, ev, size * 64)) < size) perror_exit ("read()\n"); value = ev[0].value; if (value != ' ' && ev[1].value == 1 && ev[1].type == 1){ // Only read the key press event printf (" Code[%d] received. \n", (ev[1].code)); } } return 0; }
20.816901
96
0.582544
01206102a5d3b245ec403554415ed0d1db44ceab
332
h
C
include/Operations.h
alexreinking/verify-bounds
2b01f0ef8512d7189cea184ed15f9f23a4249dd5
[ "MIT" ]
null
null
null
include/Operations.h
alexreinking/verify-bounds
2b01f0ef8512d7189cea184ed15f9f23a4249dd5
[ "MIT" ]
null
null
null
include/Operations.h
alexreinking/verify-bounds
2b01f0ef8512d7189cea184ed15f9f23a4249dd5
[ "MIT" ]
null
null
null
#pragma once #include "z3++.h" #include <string> enum Operation { Add = 0, Sub, Div, Mul }; std::string OpToString(Operation op); z3::expr generate_op(z3::context &context, Operation op, z3::expr &i, z3::expr &j); // i / j in Halide semantics z3::expr halide_div(z3::context &context, z3::expr &i, z3::expr &j);
18.444444
83
0.638554
935bb4d06df368661666fa9eec6b7d8d98d05b8c
382
h
C
include/ppr/preprocessing/build_routing_graph.h
zieglerdo/ppr
3ba2d675ee80a723a4e83b0e9249bb546e2a1489
[ "MIT" ]
1
2020-08-05T08:37:43.000Z
2020-08-05T08:37:43.000Z
include/ppr/preprocessing/build_routing_graph.h
zieglerdo/ppr
3ba2d675ee80a723a4e83b0e9249bb546e2a1489
[ "MIT" ]
null
null
null
include/ppr/preprocessing/build_routing_graph.h
zieglerdo/ppr
3ba2d675ee80a723a4e83b0e9249bb546e2a1489
[ "MIT" ]
1
2022-03-31T06:14:04.000Z
2022-03-31T06:14:04.000Z
#pragma once #include <string> #include "ppr/common/routing_graph.h" #include "ppr/preprocessing/logging.h" #include "ppr/preprocessing/options.h" #include "ppr/preprocessing/statistics.h" namespace ppr::preprocessing { routing_graph build_routing_graph(options const& opt, logging& log, statistics& stats); } // namespace ppr::preprocessing
23.875
67
0.709424
9e39a3038fb273e088981ef90a4e4f74cd0cc74b
437
h
C
JBCustomSafeKeyboard/CharsAndSymbolsKeyboard/JBCharsKeyboard.h
ThaiLanKing/zSafeKeyboard
621c3f9e5ba459a42c0b7b4ce60c7b5226fb8e58
[ "MIT" ]
4
2020-08-21T05:19:27.000Z
2021-12-13T08:30:07.000Z
JBCustomSafeKeyboard/CharsAndSymbolsKeyboard/JBCharsKeyboard.h
ThaiLanKing/zSafeKeyboard
621c3f9e5ba459a42c0b7b4ce60c7b5226fb8e58
[ "MIT" ]
null
null
null
JBCustomSafeKeyboard/CharsAndSymbolsKeyboard/JBCharsKeyboard.h
ThaiLanKing/zSafeKeyboard
621c3f9e5ba459a42c0b7b4ce60c7b5226fb8e58
[ "MIT" ]
1
2021-12-13T08:30:10.000Z
2021-12-13T08:30:10.000Z
// // JBCharsKeyboard.h // JamBoHealth // // Created by ZhangYaoHua on 2019/11/4. // Copyright © 2019 zyh. All rights reserved. // #import <UIKit/UIKit.h> @class JBKeyboardButton; NS_ASSUME_NONNULL_BEGIN @interface JBCharsKeyboard : UIView @property (nonatomic, strong, readonly) NSArray<JBKeyboardButton *> *allCharBtns; @property (nonatomic, assign) BOOL safeKeyboard; - (void)reloadRandomKeys; @end NS_ASSUME_NONNULL_END
16.807692
81
0.750572
9ecf3dc0d7f82919e3e75a39c3eb9adb3312cb70
3,774
h
C
Source/Core/IdNameMap.h
ohois/libRocket
f51879cdb42beeda28a47d55f2c2a76417ac9fbc
[ "MIT" ]
3
2020-03-25T06:05:09.000Z
2021-04-15T09:16:47.000Z
Source/Core/IdNameMap.h
ohois/libRocket
f51879cdb42beeda28a47d55f2c2a76417ac9fbc
[ "MIT" ]
2
2022-02-17T19:53:56.000Z
2022-02-19T00:20:18.000Z
Source/Core/IdNameMap.h
ohois/libRocket
f51879cdb42beeda28a47d55f2c2a76417ac9fbc
[ "MIT" ]
1
2022-02-18T17:42:51.000Z
2022-02-18T17:42:51.000Z
/* * This source file is part of RmlUi, the HTML/CSS Interface Middleware * * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd * Copyright (c) 2019 The RmlUi Team, and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ #ifndef RMLUICOREIDNAMEMAP_H #define RMLUICOREIDNAMEMAP_H #include "../../Include/RmlUi/Core/Header.h" #include "../../Include/RmlUi/Core/Types.h" #include <algorithm> namespace Rml { namespace Core { template <typename ID> class IdNameMap { std::vector<String> name_map; // IDs are indices into the name_map UnorderedMap<String, ID> reverse_map; protected: IdNameMap(size_t num_ids_to_reserve) { static_assert((int)ID::Invalid == 0, "Invalid id must be zero"); name_map.reserve(num_ids_to_reserve); reverse_map.reserve(num_ids_to_reserve); AddPair(ID::Invalid, "invalid"); } public: void AddPair(ID id, const String& name) { // Should only be used for defined IDs if ((size_t)id >= name_map.size()) name_map.resize(1 + (size_t)id); name_map[(size_t)id] = name; bool inserted = reverse_map.emplace(name, id).second; RMLUI_ASSERT(inserted); (void)inserted; } void AssertAllInserted(ID number_of_defined_ids) const { std::ptrdiff_t cnt = std::count_if(name_map.begin(), name_map.end(), [](const String& name) { return !name.empty(); }); RMLUI_ASSERT(cnt == (std::ptrdiff_t)number_of_defined_ids && reverse_map.size() == (size_t)number_of_defined_ids); (void)cnt; } ID GetId(const String& name) const { auto it = reverse_map.find(name); if (it != reverse_map.end()) return it->second; return ID::Invalid; } const String& GetName(ID id) const { if (static_cast<size_t>(id) < name_map.size()) return name_map[static_cast<size_t>(id)]; return name_map[static_cast<size_t>(ID::Invalid)]; } ID GetOrCreateId(const String& name) { // All predefined properties must be set before possibly adding custom properties here RMLUI_ASSERT(name_map.size() == reverse_map.size()); ID next_id = static_cast<ID>(name_map.size()); // Only insert if not already in list auto pair = reverse_map.emplace(name, next_id); const auto& it = pair.first; bool inserted = pair.second; if (inserted) name_map.push_back(name); // Return the property id that already existed, or the new one if inserted return it->second; } }; class PropertyIdNameMap : public IdNameMap<PropertyId> { public: PropertyIdNameMap(size_t reserve_num_properties) : IdNameMap(reserve_num_properties) {} }; class ShorthandIdNameMap : public IdNameMap<ShorthandId> { public: ShorthandIdNameMap(size_t reserve_num_shorthands) : IdNameMap(reserve_num_shorthands) {} }; } } #endif
31.714286
121
0.736619
7f3ae3e8fb34fcdcde193bce0167c0cca4584486
5,755
h
C
ash/wm/overview/window_selector_item.h
sunjc53yy/chromium
049b380040949089c2a6e447b0cd0ac3c4ece38e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
ash/wm/overview/window_selector_item.h
sunjc53yy/chromium
049b380040949089c2a6e447b0cd0ac3c4ece38e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
ash/wm/overview/window_selector_item.h
sunjc53yy/chromium
049b380040949089c2a6e447b0cd0ac3c4ece38e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 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 ASH_WM_OVERVIEW_WINDOW_SELECTOR_ITEM_H_ #define ASH_WM_OVERVIEW_WINDOW_SELECTOR_ITEM_H_ #include "base/compiler_specific.h" #include "base/memory/scoped_ptr.h" #include "ui/aura/window_observer.h" #include "ui/gfx/rect.h" #include "ui/views/controls/button/button.h" namespace aura { class Window; } namespace views { class Label; class Widget; } namespace ash { class TransparentActivateWindowButton; // This class represents an item in overview mode. An item can have one or more // windows, of which only one can be activated by keyboard (i.e. alt+tab) but // any can be selected with a pointer (touch or mouse). class WindowSelectorItem : public views::ButtonListener, public aura::WindowObserver { public: WindowSelectorItem(); ~WindowSelectorItem() override; // The time for the close buttons and labels to fade in when initially shown // on entering overview mode. static const int kFadeInMilliseconds; // Returns the root window on which this item is shown. virtual aura::Window* GetRootWindow() = 0; // Returns true if the window selector item has |window| as a selectable // window. virtual bool HasSelectableWindow(const aura::Window* window) = 0; // Returns true if |target| is contained in this WindowSelectorItem. virtual bool Contains(const aura::Window* target) = 0; // Restores |window| on exiting window overview rather than returning it // to its previous state. virtual void RestoreWindowOnExit(aura::Window* window) = 0; // Returns the |window| to activate on selecting of this item. virtual aura::Window* SelectionWindow() = 0; // Removes |window| from this item. Check empty() after calling this to see // if the entire item is now empty. virtual void RemoveWindow(const aura::Window* window); // Returns true if this item has no more selectable windows (i.e. after // calling RemoveWindow for the last contained window). virtual bool empty() const = 0; // Dispatched before beginning window overview. This will do any necessary // one time actions such as restoring minimized windows. virtual void PrepareForOverview() = 0; // Sets the bounds of this window selector item to |target_bounds| in the // |root_window| root window. void SetBounds(aura::Window* root_window, const gfx::Rect& target_bounds, bool animate); // Recomputes the positions for the windows in this selection item. This is // dispatched when the bounds of a window change. void RecomputeWindowTransforms(); // Sends an a11y focus alert so that, if chromevox is enabled, the window // label is read. void SendFocusAlert() const; // Sets if the item is dimmed in the overview. Changing the value will also // change the visibility of the transform windows. virtual void SetDimmed(bool dimmed); bool dimmed() const { return dimmed_; } const gfx::Rect& bounds() const { return bounds_; } const gfx::Rect& target_bounds() const { return target_bounds_; } // views::ButtonListener: void ButtonPressed(views::Button* sender, const ui::Event& event) override; // aura::WindowObserver: void OnWindowTitleChanged(aura::Window* window) override; protected: // Sets the bounds of this selector's items to |target_bounds| in // |root_window|. If |animate| the windows are animated from their current // location. virtual void SetItemBounds(aura::Window* root_window, const gfx::Rect& target_bounds, bool animate) = 0; // Sets the bounds used by the selector item's windows. void set_bounds(const gfx::Rect& bounds) { bounds_ = bounds; } // Changes the opacity of all the windows the item owns. virtual void SetOpacity(float opacity); // True if the item is being shown in the overview, false if it's being // filtered. bool dimmed_; private: friend class WindowSelectorTest; // Creates |close_button_| if it does not exist and updates the bounds based // on GetCloseButtonTargetBounds() void UpdateCloseButtonBounds(aura::Window* root_window, bool animate); // Creates a label to display under the window selector item. void UpdateWindowLabels(const gfx::Rect& target_bounds, aura::Window* root_window, bool animate); // Initializes window_label_. void CreateWindowLabel(const base::string16& title); // The root window this item is being displayed on. aura::Window* root_window_; // The target bounds this selector item is fit within. gfx::Rect target_bounds_; // The actual bounds of the window(s) for this item. The aspect ratio of // window(s) are maintained so they may not fill the target_bounds_. gfx::Rect bounds_; // True if running SetItemBounds. This prevents recursive calls resulting from // the bounds update when calling ::wm::RecreateWindowLayers to copy // a window layer for display on another monitor. bool in_bounds_update_; // Label under the window displaying its active tab name. scoped_ptr<views::Widget> window_label_; // View for the label under the window. views::Label* window_label_view_; // An easy to access close button for the window in this item. scoped_ptr<views::Widget> close_button_; // Transparent window on top of the real windows in the overview that // activates them on click or tap. scoped_ptr<TransparentActivateWindowButton> activate_window_button_; DISALLOW_COPY_AND_ASSIGN(WindowSelectorItem); }; } // namespace ash #endif // ASH_WM_OVERVIEW_WINDOW_SELECTOR_ITEM_H_
35.306748
80
0.724761
3659742d20018af2cd5c4980fd83deb1b65455ad
534
h
C
BasicBitcoinWallet/BasicBitcoinWallet/Others/AddressDetail/LXHAddressDetailView.h
lianxianghui/BasicBitcoinWallet-iOS
4866d1461129aa15ba5fb66ea3e62deb53c1a350
[ "MIT" ]
12
2020-08-13T08:57:17.000Z
2022-01-10T04:05:22.000Z
BasicBitcoinWallet/BasicBitcoinWallet/Others/AddressDetail/LXHAddressDetailView.h
lianxianghui/BasicBitcoinWallet-iOS
4866d1461129aa15ba5fb66ea3e62deb53c1a350
[ "MIT" ]
1
2021-05-04T23:27:56.000Z
2021-05-04T23:27:56.000Z
BasicBitcoinWallet/BasicBitcoinWallet/Others/AddressDetail/LXHAddressDetailView.h
lianxianghui/BasicBitcoinWallet-iOS
4866d1461129aa15ba5fb66ea3e62deb53c1a350
[ "MIT" ]
2
2020-08-13T11:20:35.000Z
2021-10-08T02:46:56.000Z
// LXHAddressDetailView.h // BasicWallet // // Created by lianxianghui on 19-09-16 // Copyright © 2019年 lianxianghui. All rights reserved. #import <UIKit/UIKit.h> @interface LXHAddressDetailView : UIView @property (nonatomic) UITableView *listView; @property (nonatomic) UIView *customNavigationBar; @property (nonatomic) UIView *bottomLine; @property (nonatomic) UILabel *title; @property (nonatomic) UIButton *leftImageButton; @property (nonatomic) UILabel *leftText; @property (nonatomic) UIImageView *leftBarItemImage; @end
26.7
56
0.777154
36bd55f3fc6ef1957f444431cdd5edbc44032717
1,446
h
C
release/src-rt-6.x.4708/linux/linux-2.6.36/arch/arm/mach-at91/include/mach/irqs.h
afeng11/tomato-arm
1ca18a88480b34fd495e683d849f46c2d47bb572
[ "FSFAP" ]
55
2015-01-20T00:09:45.000Z
2021-08-19T05:40:27.000Z
linux-3.0/arch/arm/mach-at91/include/mach/irqs.h
spartan263/vizio_oss
74270002d874391148119b48882db6816e7deedc
[ "Linux-OpenIB" ]
1
2018-08-21T03:43:09.000Z
2018-08-21T03:43:09.000Z
linux-3.0/arch/arm/mach-at91/include/mach/irqs.h
spartan263/vizio_oss
74270002d874391148119b48882db6816e7deedc
[ "Linux-OpenIB" ]
36
2015-02-13T00:58:22.000Z
2021-08-19T08:08:07.000Z
/* * arch/arm/mach-at91/include/mach/irqs.h * * Copyright (C) 2004 SAN People * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef __ASM_ARCH_IRQS_H #define __ASM_ARCH_IRQS_H #include <linux/io.h> #include <mach/at91_aic.h> #define NR_AIC_IRQS 32 /* * Acknowledge interrupt with AIC after interrupt has been handled. * (by kernel/irq.c) */ #define irq_finish(irq) do { at91_sys_write(AT91_AIC_EOICR, 0); } while (0) /* * IRQ interrupt symbols are the AT91xxx_ID_* symbols * for IRQs handled directly through the AIC, or else the AT91_PIN_* * symbols in gpio.h for ones handled indirectly as GPIOs. * We make provision for 5 banks of GPIO. */ #define NR_IRQS (NR_AIC_IRQS + (5 * 32)) /* FIQ is AIC source 0. */ #define FIQ_START AT91_ID_FIQ #endif
29.510204
76
0.732365
d21cf523730b0666472b37fe70a31e4a05ad2869
6,471
h
C
include/i2s.h
marangisto/HAL
fa56b539f64b277fa122a010e4ee643463f58498
[ "MIT" ]
2
2019-09-12T04:12:16.000Z
2020-09-23T19:13:06.000Z
include/i2s.h
marangisto/HAL
fa56b539f64b277fa122a010e4ee643463f58498
[ "MIT" ]
2
2019-09-10T13:47:50.000Z
2020-02-24T03:27:47.000Z
include/i2s.h
marangisto/HAL
fa56b539f64b277fa122a010e4ee643463f58498
[ "MIT" ]
3
2019-08-31T12:58:28.000Z
2020-03-26T22:56:34.000Z
#pragma once #include <gpio.h> #include "dma.h" namespace hal { namespace i2s { using namespace device; using namespace gpio; enum i2s_standard_t { philips_i2s = 0x0 , left_justified = 0x1 , right_justified = 0x2 , pcm_standard = 0x3 }; enum i2s_clock_polarity_t { low_level, high_level }; enum i2s_format_t { format_16_16 = 0x0 , format_16_32 = 0x4 , format_24_32 = 0x1 , format_32_32 = 0x2 }; template<int NO> struct i2s_traits {}; #if !defined(STM32G431) template<> struct i2s_traits<1> { typedef spi1_t T; static inline T& I2S() { return SPI1; } static const gpio::internal::alternate_function_t ck = gpio::internal::I2S1_CK; static const gpio::internal::alternate_function_t mck = gpio::internal::I2S1_MCK; static const gpio::internal::alternate_function_t sd = gpio::internal::I2S1_SD; static const gpio::internal::alternate_function_t ws = gpio::internal::I2S1_WS; static const dma::resource_t tx_request = dma::SPI1_TX; }; #endif template<> struct i2s_traits<2> { typedef spi2_t T; static inline T& I2S() { return SPI2; } static const gpio::internal::alternate_function_t ck = gpio::internal::I2S2_CK; static const gpio::internal::alternate_function_t mck = gpio::internal::I2S2_MCK; static const gpio::internal::alternate_function_t sd = gpio::internal::I2S2_SD; static const gpio::internal::alternate_function_t ws = gpio::internal::I2S2_WS; static const dma::resource_t tx_request = dma::SPI2_TX; }; template<> struct i2s_traits<3> { typedef spi3_t T; static inline T& I2S() { return SPI3; } static const gpio::internal::alternate_function_t ck = gpio::internal::I2S3_CK; static const gpio::internal::alternate_function_t mck = gpio::internal::I2S3_MCK; static const gpio::internal::alternate_function_t sd = gpio::internal::I2S3_SD; static const gpio::internal::alternate_function_t ws = gpio::internal::I2S3_WS; static const dma::resource_t tx_request = dma::SPI3_TX; }; template<int NO, gpio_pin_t CK, gpio_pin_t SD, gpio_pin_t WS> struct i2s_t { private: typedef typename i2s_traits<NO>::T _; public: template < i2s_standard_t standard , i2s_clock_polarity_t polarity , i2s_format_t format , uint8_t divider , output_speed_t speed = high_speed > static inline void setup() { using namespace gpio::internal; alternate_t<SD, i2s_traits<NO>::sd>::template setup<speed>(); alternate_t<WS, i2s_traits<NO>::ws>::template setup<speed>(); alternate_t<CK, i2s_traits<NO>::ck>::template setup<speed>(); peripheral_traits<_>::enable(); // enable i2s clock I2S().CR1 = _::CR1_RESET_VALUE; // reset control register 1 I2S().CR2 = _::CR2_RESET_VALUE; // reset control register 2 I2S().I2SCFGR = _::I2SCFGR_RESET_VALUE // reset i2s configuration register | _::I2SCFGR_I2SMOD // enable i2s mode | _::template I2SCFGR_I2SCFG<0x2> // master transmit | _::template I2SCFGR_I2SSTD<standard> // standard selection | (polarity == high_level ? _::I2SCFGR_CKPOL : 0) // enable i2s mode | _::template I2SCFGR_DATLEN<format & 0x3> // data length | ((format & 0x4) ? _::I2SCFGR_CHLEN : 0) // 32-bit channel width ; static_assert(divider > 3, "I2S clock division must be strictly larger than 3"); I2S().I2SPR = _::template I2SPR_I2SDIV<(divider >> 1)> // linear prescaler | ((divider & 0x1) ? _::I2SPR_ODD : 0) // odd prescaler ; // FIXME: master clock output enable option I2S().I2SCFGR |= _::I2SCFGR_I2SE; // enable i2s peripheral // note dma and interrupt enable flags are in CR2 } template<typename DMA, uint8_t DMACH, typename T> static inline void enable_dma(const T *source, uint16_t nelem) { I2S().CR2 |= _::CR2_TXDMAEN // enable dma transmission ; DMA::template disable<DMACH>(); // disable dma channel DMA::template mem_to_periph<DMACH>(source, nelem, &I2S().DR); // configure dma from memory DMA::template enable<DMACH>(); // enable dma channel #if defined(STM32G431) dma::dmamux_traits<DMA::INST, DMACH>::CCR() = device::dmamux_t::C0CR_DMAREQ_ID<i2s_traits<NO>::tx_request>; #endif } __attribute__((always_inline)) static inline void write16(uint16_t x) { while (!(I2S().SR & _::SR_TXE)); // wait until tx buffer is empty I2S().DR = x; } __attribute__((always_inline)) static inline void write24(uint32_t x) { while (!(I2S().SR & _::SR_TXE)); // wait until tx buffer is empty I2S().DR = x >> 8; while (!(I2S().SR & _::SR_TXE)); // wait until tx buffer is empty I2S().DR = (x & 0xffff) << 8; } __attribute__((always_inline)) static inline void write32(uint32_t x) { while (!(I2S().SR & _::SR_TXE)); // wait until tx buffer is empty I2S().DR = x & 0xffff; while (!(I2S().SR & _::SR_TXE)); // wait until tx buffer is empty I2S().DR = x >> 16; } __attribute__((always_inline)) static inline bool busy() { return I2S().SR & _::SR_BSY; } __attribute__((always_inline)) static inline void wait_idle() { while ((I2S().SR & (_::SR_BSY | _::SR_TXE)) != _::SR_TXE); } enum interrupt_t { err_interrupt = _::CR2_ERRIE , rx_interrupt = _::CR2_RXNEIE , tx_interrupt = _::CR2_TXEIE }; static inline void interrupt_enable(uint32_t flags) { static const uint32_t mask = err_interrupt | rx_interrupt | tx_interrupt; I2S().CR2 &= ~mask; I2S().CR2 |= flags & mask; } private: static inline typename i2s_traits<NO>::T& I2S() { return i2s_traits<NO>::I2S(); } }; } }
34.978378
115
0.58229
cfe7ceaeb25ebd11bd1ae14aa1c405f6ca64601d
2,948
c
C
src/sema_parse.c
YutaNagaoka/9cc
5ead462c9cefc7a9522ae2455e5fdb07a480d3cb
[ "MIT" ]
5
2020-01-16T09:50:46.000Z
2021-01-28T15:59:48.000Z
src/sema_parse.c
YutaNagaoka/9cc
5ead462c9cefc7a9522ae2455e5fdb07a480d3cb
[ "MIT" ]
27
2019-07-10T14:28:45.000Z
2019-11-18T03:46:03.000Z
src/sema_parse.c
YutaNagaoka/9cc
5ead462c9cefc7a9522ae2455e5fdb07a480d3cb
[ "MIT" ]
1
2021-03-19T16:36:31.000Z
2021-03-19T16:36:31.000Z
#include "ycc.h" void sema_parse(Node *node) { if (!node || (node->c_type && node->node_type != ND_DEF_FUNC)) return; sema_parse(node->lhs); sema_parse(node->rhs); sema_parse(node->condition); sema_parse(node->then); sema_parse(node->els); sema_parse(node->init); sema_parse(node->inc); sema_parse(node->body); if (node->args != NULL) { for (int i = 0; node->args->data[i]; i++) { sema_parse(node->args->data[i]); } } if (node->params != NULL) { for (int i = 0; node->params->data[i]; i++) { sema_parse(node->params->data[i]); } } if (node->stmts_in_block != NULL) { for (int i = 0; node->stmts_in_block->data[i]; i++) { sema_parse(node->stmts_in_block->data[i]); } } switch (node->node_type) { case ND_FUNCCALL: node->c_type = new_type(TY_FUNC, 1, NULL); case ND_AND: case ND_OR: case ND_EQ: case ND_NE: case ND_LESS: case ND_LE: case ND_MUL: case ND_DIV: case ND_NOT: node->c_type = new_type(TY_INT, 4, NULL); break; case ND_ASSIGN: case ND_ADDR: node->c_type = node->lhs->c_type; break; case ND_DEREF: if (node->lhs->c_type->type == TY_ARRAY) node->c_type = node->lhs->c_type->array_of; else node->c_type = node->lhs->c_type->ptr_to; break; case ND_ADD: // Convert 'num + ptr' to 'ptr + num' if (node->rhs->c_type->type == TY_PTR) { Node *tmp = node->lhs; node->lhs = node->rhs; node->rhs = tmp; } // 'ptr + ptr' is invalid, and its rhs is still 'ptr' after swapping if (node->rhs->c_type->type == TY_PTR) ERROR("Invalid operands to binary expression ('int *' and 'int *')\n"); if (node->lhs->c_type->type == TY_ARRAY && node->rhs->c_type->type == TY_PTR) ERROR("Invalid operands to binary expression ('int *' and 'int *')\n"); node->c_type = node->lhs->c_type; break; case ND_SUB: if (node->lhs->c_type->type == TY_PTR) { if (node->rhs->c_type->type == TY_PTR) node->c_type->type = TY_INT; } else if (node->rhs->c_type->type == TY_PTR) ERROR("Invalid operands to binary expression ('int' and 'int *')\n"); if (node->lhs->c_type->type == TY_ARRAY && node->rhs->c_type->type == TY_PTR) ERROR("Invalid operands to binary expression ('int *' and 'int *')\n"); node->c_type = node->lhs->c_type; break; case ND_SIZEOF: node->c_type = new_type(TY_INT, 4, NULL); case ND_NUM: node->c_type = new_type(TY_INT, 4, NULL); break; default: break; } } void sema_parse_nodes(Vector *nodes) { for (int i = 0; nodes->data[i]; i++) { sema_parse(nodes->data[i]); } }
30.708333
85
0.533582
3c08901d717466820fe1328eb0ef127709b33a51
7,230
h
C
modules/platforms/cpp/thin-client/include/ignite/impl/thin/cache/query/query_fields_row_impl.h
vvteplygin/ignite
876a2ca190dbd88f42bc7acecff8b7783ce7ce54
[ "Apache-2.0" ]
4,339
2015-08-21T21:13:25.000Z
2022-03-30T09:56:44.000Z
modules/platforms/cpp/thin-client/include/ignite/impl/thin/cache/query/query_fields_row_impl.h
vvteplygin/ignite
876a2ca190dbd88f42bc7acecff8b7783ce7ce54
[ "Apache-2.0" ]
1,933
2015-08-24T11:37:40.000Z
2022-03-31T08:37:08.000Z
modules/platforms/cpp/thin-client/include/ignite/impl/thin/cache/query/query_fields_row_impl.h
vvteplygin/ignite
876a2ca190dbd88f42bc7acecff8b7783ce7ce54
[ "Apache-2.0" ]
2,140
2015-08-21T22:09:00.000Z
2022-03-25T07:57:34.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 _IGNITE_IMPL_CACHE_QUERY_CACHE_QUERY_FIELDS_ROW_IMPL #define _IGNITE_IMPL_CACHE_QUERY_CACHE_QUERY_FIELDS_ROW_IMPL #include <ignite/common/concurrent.h> #include <ignite/ignite_error.h> namespace ignite { namespace impl { namespace cache { namespace query { /** * Query fields cursor implementation. */ class IGNITE_IMPORT_EXPORT QueryFieldsRowImpl { public: typedef common::concurrent::SharedPointer<interop::InteropMemory> SP_InteropMemory; /** * Constructor. * * @param mem Memory containig row data. */ QueryFieldsRowImpl(SP_InteropMemory mem, int32_t rowBegin, int32_t columnNum) : mem(mem), stream(mem.Get()), reader(&stream), columnNum(columnNum), processed(0) { stream.Position(rowBegin); } /** * Check whether next entry exists. * * @return True if next entry exists. */ bool HasNext() { IgniteError err; bool res = HasNext(err); IgniteError::ThrowIfNeeded(err); return res; } /** * Check whether next entry exists. * * @param err Error. * @return True if next entry exists. */ bool HasNext(IgniteError& err) { if (IsValid()) return processed < columnNum; else { err = IgniteError(IgniteError::IGNITE_ERR_GENERIC, "Instance is not usable (did you check for error?)."); return false; } } /** * Get next entry. * * @return Next entry. */ template<typename T> T GetNext() { IgniteError err; QueryFieldsRowImpl res = GetNext<T>(err); IgniteError::ThrowIfNeeded(err); return res; } /** * Get next entry. * * @param err Error. * @return Next entry. */ template<typename T> T GetNext(IgniteError& err) { if (IsValid()) { ++processed; return reader.ReadTopObject<T>(); } else { err = IgniteError(IgniteError::IGNITE_ERR_GENERIC, "Instance is not usable (did you check for error?)."); return T(); } } /** * Get next entry assuming it's an array of 8-byte signed * integers. Maps to "byte[]" type in Java. * * @param dst Array to store data to. * @param len Expected length of array. * @return Actual amount of elements read. If "len" argument is less than actual * array size or resulting array is set to null, nothing will be written * to resulting array and returned value will contain required array length. * -1 will be returned in case array in stream was null. */ int32_t GetNextInt8Array(int8_t* dst, int32_t len) { if (IsValid()) { int32_t actualLen = reader.ReadInt8Array(dst, len); if (actualLen == 0 || (dst && len >= actualLen)) ++processed; return actualLen; } else { throw IgniteError(IgniteError::IGNITE_ERR_GENERIC, "Instance is not usable (did you check for error?)."); } } /** * Check if the instance is valid. * * Invalid instance can be returned if some of the previous * operations have resulted in a failure. For example invalid * instance can be returned by not-throwing version of method * in case of error. Invalid instances also often can be * created using default constructor. * * @return True if the instance is valid and can be used. */ bool IsValid() { return mem.Get() != 0; } private: /** Row memory. */ SP_InteropMemory mem; /** Row data stream. */ interop::InteropInputStream stream; /** Row data reader. */ binary::BinaryReaderImpl reader; /** Number of elements in a row. */ int32_t columnNum; /** Number of elements that have been read by now. */ int32_t processed; IGNITE_NO_COPY_ASSIGNMENT(QueryFieldsRowImpl); }; } } } } #endif //_IGNITE_IMPL_CACHE_QUERY_CACHE_QUERY_FIELDS_ROW_IMPL
36.515152
103
0.425173
19088cb5be98daff037ebcaf940f998e71ed3949
14,043
h
C
windows/RNFetchBlob/Generated Files/winrt/impl/Windows.Security.DataProtection.0.h
vladimixz/rn-fetch-blob
77005dfc75f3975d41c195b1d8754f270d28d95a
[ "MIT" ]
null
null
null
windows/RNFetchBlob/Generated Files/winrt/impl/Windows.Security.DataProtection.0.h
vladimixz/rn-fetch-blob
77005dfc75f3975d41c195b1d8754f270d28d95a
[ "MIT" ]
null
null
null
windows/RNFetchBlob/Generated Files/winrt/impl/Windows.Security.DataProtection.0.h
vladimixz/rn-fetch-blob
77005dfc75f3975d41c195b1d8754f270d28d95a
[ "MIT" ]
null
null
null
// WARNING: Please don't edit this file. It was generated by C++/WinRT v2.0.200615.7 #ifndef WINRT_Windows_Security_DataProtection_0_H #define WINRT_Windows_Security_DataProtection_0_H WINRT_EXPORT namespace winrt::Windows::Foundation { struct Deferral; struct EventRegistrationToken; template <typename TResult> struct __declspec(empty_bases) IAsyncOperation; template <typename TSender, typename TResult> struct __declspec(empty_bases) TypedEventHandler; } WINRT_EXPORT namespace winrt::Windows::Storage { struct IStorageItem; } WINRT_EXPORT namespace winrt::Windows::Storage::Streams { struct IBuffer; } WINRT_EXPORT namespace winrt::Windows::System { struct User; } WINRT_EXPORT namespace winrt::Windows::Security::DataProtection { enum class UserDataAvailability : int32_t { Always = 0, AfterFirstUnlock = 1, WhileUnlocked = 2, }; enum class UserDataBufferUnprotectStatus : int32_t { Succeeded = 0, Unavailable = 1, }; enum class UserDataStorageItemProtectionStatus : int32_t { Succeeded = 0, NotProtectable = 1, DataUnavailable = 2, }; struct IUserDataAvailabilityStateChangedEventArgs; struct IUserDataBufferUnprotectResult; struct IUserDataProtectionManager; struct IUserDataProtectionManagerStatics; struct IUserDataStorageItemProtectionInfo; struct UserDataAvailabilityStateChangedEventArgs; struct UserDataBufferUnprotectResult; struct UserDataProtectionManager; struct UserDataStorageItemProtectionInfo; } namespace winrt::impl { template <> struct category<Windows::Security::DataProtection::IUserDataAvailabilityStateChangedEventArgs>{ using type = interface_category; }; template <> struct category<Windows::Security::DataProtection::IUserDataBufferUnprotectResult>{ using type = interface_category; }; template <> struct category<Windows::Security::DataProtection::IUserDataProtectionManager>{ using type = interface_category; }; template <> struct category<Windows::Security::DataProtection::IUserDataProtectionManagerStatics>{ using type = interface_category; }; template <> struct category<Windows::Security::DataProtection::IUserDataStorageItemProtectionInfo>{ using type = interface_category; }; template <> struct category<Windows::Security::DataProtection::UserDataAvailabilityStateChangedEventArgs>{ using type = class_category; }; template <> struct category<Windows::Security::DataProtection::UserDataBufferUnprotectResult>{ using type = class_category; }; template <> struct category<Windows::Security::DataProtection::UserDataProtectionManager>{ using type = class_category; }; template <> struct category<Windows::Security::DataProtection::UserDataStorageItemProtectionInfo>{ using type = class_category; }; template <> struct category<Windows::Security::DataProtection::UserDataAvailability>{ using type = enum_category; }; template <> struct category<Windows::Security::DataProtection::UserDataBufferUnprotectStatus>{ using type = enum_category; }; template <> struct category<Windows::Security::DataProtection::UserDataStorageItemProtectionStatus>{ using type = enum_category; }; template <> inline constexpr auto& name_v<Windows::Security::DataProtection::UserDataAvailabilityStateChangedEventArgs> = L"Windows.Security.DataProtection.UserDataAvailabilityStateChangedEventArgs"; template <> inline constexpr auto& name_v<Windows::Security::DataProtection::UserDataBufferUnprotectResult> = L"Windows.Security.DataProtection.UserDataBufferUnprotectResult"; template <> inline constexpr auto& name_v<Windows::Security::DataProtection::UserDataProtectionManager> = L"Windows.Security.DataProtection.UserDataProtectionManager"; template <> inline constexpr auto& name_v<Windows::Security::DataProtection::UserDataStorageItemProtectionInfo> = L"Windows.Security.DataProtection.UserDataStorageItemProtectionInfo"; template <> inline constexpr auto& name_v<Windows::Security::DataProtection::UserDataAvailability> = L"Windows.Security.DataProtection.UserDataAvailability"; template <> inline constexpr auto& name_v<Windows::Security::DataProtection::UserDataBufferUnprotectStatus> = L"Windows.Security.DataProtection.UserDataBufferUnprotectStatus"; template <> inline constexpr auto& name_v<Windows::Security::DataProtection::UserDataStorageItemProtectionStatus> = L"Windows.Security.DataProtection.UserDataStorageItemProtectionStatus"; template <> inline constexpr auto& name_v<Windows::Security::DataProtection::IUserDataAvailabilityStateChangedEventArgs> = L"Windows.Security.DataProtection.IUserDataAvailabilityStateChangedEventArgs"; template <> inline constexpr auto& name_v<Windows::Security::DataProtection::IUserDataBufferUnprotectResult> = L"Windows.Security.DataProtection.IUserDataBufferUnprotectResult"; template <> inline constexpr auto& name_v<Windows::Security::DataProtection::IUserDataProtectionManager> = L"Windows.Security.DataProtection.IUserDataProtectionManager"; template <> inline constexpr auto& name_v<Windows::Security::DataProtection::IUserDataProtectionManagerStatics> = L"Windows.Security.DataProtection.IUserDataProtectionManagerStatics"; template <> inline constexpr auto& name_v<Windows::Security::DataProtection::IUserDataStorageItemProtectionInfo> = L"Windows.Security.DataProtection.IUserDataStorageItemProtectionInfo"; template <> inline constexpr guid guid_v<Windows::Security::DataProtection::IUserDataAvailabilityStateChangedEventArgs>{ 0xA76582C9,0x06A2,0x4273,{ 0xA8,0x03,0x83,0x4C,0x9F,0x87,0xFB,0xEB } }; // A76582C9-06A2-4273-A803-834C9F87FBEB template <> inline constexpr guid guid_v<Windows::Security::DataProtection::IUserDataBufferUnprotectResult>{ 0x8EFD0E90,0xFA9A,0x46A4,{ 0xA3,0x77,0x01,0xCE,0xBF,0x1E,0x74,0xD8 } }; // 8EFD0E90-FA9A-46A4-A377-01CEBF1E74D8 template <> inline constexpr guid guid_v<Windows::Security::DataProtection::IUserDataProtectionManager>{ 0x1F13237D,0xB42E,0x4A88,{ 0x94,0x80,0x0F,0x24,0x09,0x24,0xC8,0x76 } }; // 1F13237D-B42E-4A88-9480-0F240924C876 template <> inline constexpr guid guid_v<Windows::Security::DataProtection::IUserDataProtectionManagerStatics>{ 0x977780E8,0x6DCE,0x4FAE,{ 0xAF,0x85,0x78,0x2A,0xC2,0xCF,0x45,0x72 } }; // 977780E8-6DCE-4FAE-AF85-782AC2CF4572 template <> inline constexpr guid guid_v<Windows::Security::DataProtection::IUserDataStorageItemProtectionInfo>{ 0x5B6680F6,0xE87F,0x40A1,{ 0xB1,0x9D,0xA6,0x18,0x7A,0x0C,0x66,0x2F } }; // 5B6680F6-E87F-40A1-B19D-A6187A0C662F template <> struct default_interface<Windows::Security::DataProtection::UserDataAvailabilityStateChangedEventArgs>{ using type = Windows::Security::DataProtection::IUserDataAvailabilityStateChangedEventArgs; }; template <> struct default_interface<Windows::Security::DataProtection::UserDataBufferUnprotectResult>{ using type = Windows::Security::DataProtection::IUserDataBufferUnprotectResult; }; template <> struct default_interface<Windows::Security::DataProtection::UserDataProtectionManager>{ using type = Windows::Security::DataProtection::IUserDataProtectionManager; }; template <> struct default_interface<Windows::Security::DataProtection::UserDataStorageItemProtectionInfo>{ using type = Windows::Security::DataProtection::IUserDataStorageItemProtectionInfo; }; template <> struct abi<Windows::Security::DataProtection::IUserDataAvailabilityStateChangedEventArgs> { struct __declspec(novtable) type : inspectable_abi { virtual int32_t __stdcall GetDeferral(void**) noexcept = 0; }; }; template <> struct abi<Windows::Security::DataProtection::IUserDataBufferUnprotectResult> { struct __declspec(novtable) type : inspectable_abi { virtual int32_t __stdcall get_Status(int32_t*) noexcept = 0; virtual int32_t __stdcall get_UnprotectedBuffer(void**) noexcept = 0; }; }; template <> struct abi<Windows::Security::DataProtection::IUserDataProtectionManager> { struct __declspec(novtable) type : inspectable_abi { virtual int32_t __stdcall ProtectStorageItemAsync(void*, int32_t, void**) noexcept = 0; virtual int32_t __stdcall GetStorageItemProtectionInfoAsync(void*, void**) noexcept = 0; virtual int32_t __stdcall ProtectBufferAsync(void*, int32_t, void**) noexcept = 0; virtual int32_t __stdcall UnprotectBufferAsync(void*, void**) noexcept = 0; virtual int32_t __stdcall IsContinuedDataAvailabilityExpected(int32_t, bool*) noexcept = 0; virtual int32_t __stdcall add_DataAvailabilityStateChanged(void*, winrt::event_token*) noexcept = 0; virtual int32_t __stdcall remove_DataAvailabilityStateChanged(winrt::event_token) noexcept = 0; }; }; template <> struct abi<Windows::Security::DataProtection::IUserDataProtectionManagerStatics> { struct __declspec(novtable) type : inspectable_abi { virtual int32_t __stdcall TryGetDefault(void**) noexcept = 0; virtual int32_t __stdcall TryGetForUser(void*, void**) noexcept = 0; }; }; template <> struct abi<Windows::Security::DataProtection::IUserDataStorageItemProtectionInfo> { struct __declspec(novtable) type : inspectable_abi { virtual int32_t __stdcall get_Availability(int32_t*) noexcept = 0; }; }; template <typename D> struct consume_Windows_Security_DataProtection_IUserDataAvailabilityStateChangedEventArgs { WINRT_IMPL_AUTO(Windows::Foundation::Deferral) GetDeferral() const; }; template <> struct consume<Windows::Security::DataProtection::IUserDataAvailabilityStateChangedEventArgs> { template <typename D> using type = consume_Windows_Security_DataProtection_IUserDataAvailabilityStateChangedEventArgs<D>; }; template <typename D> struct consume_Windows_Security_DataProtection_IUserDataBufferUnprotectResult { [[nodiscard]] WINRT_IMPL_AUTO(Windows::Security::DataProtection::UserDataBufferUnprotectStatus) Status() const; [[nodiscard]] WINRT_IMPL_AUTO(Windows::Storage::Streams::IBuffer) UnprotectedBuffer() const; }; template <> struct consume<Windows::Security::DataProtection::IUserDataBufferUnprotectResult> { template <typename D> using type = consume_Windows_Security_DataProtection_IUserDataBufferUnprotectResult<D>; }; template <typename D> struct consume_Windows_Security_DataProtection_IUserDataProtectionManager { WINRT_IMPL_AUTO(Windows::Foundation::IAsyncOperation<Windows::Security::DataProtection::UserDataStorageItemProtectionStatus>) ProtectStorageItemAsync(Windows::Storage::IStorageItem const& storageItem, Windows::Security::DataProtection::UserDataAvailability const& availability) const; WINRT_IMPL_AUTO(Windows::Foundation::IAsyncOperation<Windows::Security::DataProtection::UserDataStorageItemProtectionInfo>) GetStorageItemProtectionInfoAsync(Windows::Storage::IStorageItem const& storageItem) const; WINRT_IMPL_AUTO(Windows::Foundation::IAsyncOperation<Windows::Storage::Streams::IBuffer>) ProtectBufferAsync(Windows::Storage::Streams::IBuffer const& unprotectedBuffer, Windows::Security::DataProtection::UserDataAvailability const& availability) const; WINRT_IMPL_AUTO(Windows::Foundation::IAsyncOperation<Windows::Security::DataProtection::UserDataBufferUnprotectResult>) UnprotectBufferAsync(Windows::Storage::Streams::IBuffer const& protectedBuffer) const; WINRT_IMPL_AUTO(bool) IsContinuedDataAvailabilityExpected(Windows::Security::DataProtection::UserDataAvailability const& availability) const; WINRT_IMPL_AUTO(winrt::event_token) DataAvailabilityStateChanged(Windows::Foundation::TypedEventHandler<Windows::Security::DataProtection::UserDataProtectionManager, Windows::Security::DataProtection::UserDataAvailabilityStateChangedEventArgs> const& handler) const; using DataAvailabilityStateChanged_revoker = impl::event_revoker<Windows::Security::DataProtection::IUserDataProtectionManager, &impl::abi_t<Windows::Security::DataProtection::IUserDataProtectionManager>::remove_DataAvailabilityStateChanged>; [[nodiscard]] DataAvailabilityStateChanged_revoker DataAvailabilityStateChanged(auto_revoke_t, Windows::Foundation::TypedEventHandler<Windows::Security::DataProtection::UserDataProtectionManager, Windows::Security::DataProtection::UserDataAvailabilityStateChangedEventArgs> const& handler) const; WINRT_IMPL_AUTO(void) DataAvailabilityStateChanged(winrt::event_token const& token) const noexcept; }; template <> struct consume<Windows::Security::DataProtection::IUserDataProtectionManager> { template <typename D> using type = consume_Windows_Security_DataProtection_IUserDataProtectionManager<D>; }; template <typename D> struct consume_Windows_Security_DataProtection_IUserDataProtectionManagerStatics { WINRT_IMPL_AUTO(Windows::Security::DataProtection::UserDataProtectionManager) TryGetDefault() const; WINRT_IMPL_AUTO(Windows::Security::DataProtection::UserDataProtectionManager) TryGetForUser(Windows::System::User const& user) const; }; template <> struct consume<Windows::Security::DataProtection::IUserDataProtectionManagerStatics> { template <typename D> using type = consume_Windows_Security_DataProtection_IUserDataProtectionManagerStatics<D>; }; template <typename D> struct consume_Windows_Security_DataProtection_IUserDataStorageItemProtectionInfo { [[nodiscard]] WINRT_IMPL_AUTO(Windows::Security::DataProtection::UserDataAvailability) Availability() const; }; template <> struct consume<Windows::Security::DataProtection::IUserDataStorageItemProtectionInfo> { template <typename D> using type = consume_Windows_Security_DataProtection_IUserDataStorageItemProtectionInfo<D>; }; } #endif
74.696809
304
0.783024
d2c311bd37802b1058c2c7b46b9fdff57c0aa477
1,020
h
C
ion/TrafficZoomPage.h
dtylman/ion
219a84761ff9213a53c79d3447b03ae620711024
[ "MIT" ]
2
2018-01-15T12:22:31.000Z
2018-03-16T12:43:32.000Z
ion/TrafficZoomPage.h
dtylman/ion
219a84761ff9213a53c79d3447b03ae620711024
[ "MIT" ]
null
null
null
ion/TrafficZoomPage.h
dtylman/ion
219a84761ff9213a53c79d3447b03ae620711024
[ "MIT" ]
null
null
null
/* * File: TrafficZoomPage.h * Author: danny * * Created on March 18, 2015, 2:41 PM */ #ifndef TRAFFICZOOMPAGE_H #define TRAFFICZOOMPAGE_H #include "PageRequestHandler.h" #include <Poco/Data/RecordSet.h> #include <string> class TrafficZoomPage : public PageRequestHandler { public: static const std::string Title; static const std::string Link; TrafficZoomPage(); virtual ~TrafficZoomPage(); protected: virtual std::string title() const; virtual std::string subtitle() const; virtual void renderScripts(std::ostream& output); virtual void renderPanelBody(std::ostream& output, Poco::Net::HTTPServerRequest& request); virtual void renderButtons(std::ostream& output); virtual bool handleForm(Poco::Net::HTMLForm& form, Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response); private: void renderRow(std::ostream& output, Poco::Data::RecordSet& rs); private: std::string _field; std::string _value; }; #endif /* TRAFFICZOOMPAGE_H */
26.842105
135
0.722549
cf27ed9ec385b965b4a051f446a64eff896c54f3
629
c
C
libtommath/bn_mp_shrink.c
myarchsource/tcl
e78010cecf89dad7a3377643b2038660ccaf0e76
[ "TCL" ]
770
2015-02-22T03:16:17.000Z
2022-03-25T03:08:08.000Z
libtommath/bn_mp_shrink.c
myarchsource/tcl
e78010cecf89dad7a3377643b2038660ccaf0e76
[ "TCL" ]
475
2015-07-24T21:41:40.000Z
2022-02-21T20:49:11.000Z
libtommath/bn_mp_shrink.c
myarchsource/tcl
e78010cecf89dad7a3377643b2038660ccaf0e76
[ "TCL" ]
180
2015-03-15T20:11:26.000Z
2022-03-27T17:33:40.000Z
#include "tommath_private.h" #ifdef BN_MP_SHRINK_C /* LibTomMath, multiple-precision integer library -- Tom St Denis */ /* SPDX-License-Identifier: Unlicense */ /* shrink a bignum */ mp_err mp_shrink(mp_int *a) { mp_digit *tmp; int alloc = MP_MAX(MP_MIN_PREC, a->used); if (a->alloc != alloc) { if ((tmp = (mp_digit *) MP_REALLOC(a->dp, (size_t)a->alloc * sizeof(mp_digit), (size_t)alloc * sizeof(mp_digit))) == NULL) { return MP_MEM; } a->dp = tmp; a->alloc = alloc; } return MP_OKAY; } #endif
27.347826
86
0.540541
652505a98524cca7dc5ecd2119046553af2cf1ca
16,530
c
C
firmware/bsl/lib-qpc/examples/arm-cm/vanilla/gnu/lwip_ek-lm3s6965/bsp.c
AmuletGroup/amulet-project
b37bc1a66ea084f6ef1e9e727043aa6416d781a6
[ "BSD-Source-Code" ]
20
2016-09-01T15:07:35.000Z
2022-02-10T15:47:39.000Z
firmware/bsl/lib-qpc/examples/arm-cm/vanilla/iar/lwip_ek-lm3s6965/bsp.c
AmuletGroup/amulet-project
b37bc1a66ea084f6ef1e9e727043aa6416d781a6
[ "BSD-Source-Code" ]
null
null
null
firmware/bsl/lib-qpc/examples/arm-cm/vanilla/iar/lwip_ek-lm3s6965/bsp.c
AmuletGroup/amulet-project
b37bc1a66ea084f6ef1e9e727043aa6416d781a6
[ "BSD-Source-Code" ]
4
2016-10-29T20:34:33.000Z
2022-02-10T15:45:40.000Z
/***************************************************************************** * Product: DPP with lwIP application, cooperative Vanilla kernel * Last Updated for Version: 5.2.0 * Date of the Last Update: Dec 17, 2013 * * Q u a n t u m L e a P s * --------------------------- * innovating embedded systems * * Copyright (C) 2002-2013 Quantum Leaps, LLC. All rights reserved. * * This program is open source software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Alternatively, this program may be distributed and modified under the * terms of Quantum Leaps commercial licenses, which expressly supersede * the GNU General Public License and are specifically designed for * licensees interested in retaining the proprietary status of their code. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contact information: * Quantum Leaps Web sites: http://www.quantum-leaps.com * http://www.state-machine.com * e-mail: info@quantum-leaps.com *****************************************************************************/ #include "qp_port.h" /* QP port header file */ #include "dpp.h" /* application events and active objects */ #include "bsp.h" /* Board Support Package header file */ #include "lm3s_cmsis.h" Q_DEFINE_THIS_FILE /*!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! CAUTION !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! * Assign a priority to EVERY ISR explicitly by calling NVIC_SetPriority(). * DO NOT LEAVE THE ISR PRIORITIES AT THE DEFAULT VALUE! */ enum KernelUnawareISRs { /* see NOTE00 */ /* ... */ MAX_KERNEL_UNAWARE_CMSIS_PRI /* keep always last */ }; /* "kernel-unaware" interrupts can't overlap "kernel-aware" interrupts */ Q_ASSERT_COMPILE(MAX_KERNEL_UNAWARE_CMSIS_PRI <= QF_AWARE_ISR_CMSIS_PRI); enum KernelAwareISRs { ETHERNET_PRIO = QF_AWARE_ISR_CMSIS_PRI, /* see NOTE00 */ SYSTICK_PRIO, /* ... */ MAX_KERNEL_AWARE_CMSIS_PRI /* keep always last */ }; /* "kernel-aware" interrupts should not overlap the PendSV priority */ Q_ASSERT_COMPILE(MAX_KERNEL_AWARE_CMSIS_PRI <= (0xFF >>(8-__NVIC_PRIO_BITS))); /* ISRs defined in this BSP ------------------------------------------------*/ void SysTick_Handler(void); /* Local-scope objects -----------------------------------------------------*/ #define USER_LED (1 << 0) #define USER_BTN (1 << 1) #define ETH0_LED (1 << 3) #define ETH1_LED (1 << 2) static uint32_t l_nTicks; #ifdef Q_SPY QSTimeCtr QS_tickTime_; QSTimeCtr QS_tickPeriod_; static uint8_t l_SysTick_Handler; #define UART_BAUD_RATE 115200 #define UART_TXFIFO_DEPTH 16 #define UART_FR_TXFE (1 << 7) #endif /*..........................................................................*/ void SysTick_Handler(void) { static uint32_t btn_debounced = 0; static uint8_t debounce_state = 0; uint32_t volatile tmp; ++l_nTicks; /* count the number of clock ticks */ #ifdef Q_SPY tmp = SysTick->CTRL; /* clear SysTick_CTRL_COUNTFLAG */ QS_tickTime_ += QS_tickPeriod_; /* account for the clock rollover */ #endif QF_TICK_X(0U, &l_SysTick_Handler); /* process all time events at rate 0 */ tmp = GPIOF->DATA_Bits[USER_BTN]; /* read the User Button */ switch (debounce_state) { case 0: if (tmp != btn_debounced) { debounce_state = 1; /* transition to the next state */ } break; case 1: if (tmp != btn_debounced) { debounce_state = 2; /* transition to the next state */ } else { debounce_state = 0; /* transition back to state 0 */ } break; case 2: if (tmp != btn_debounced) { debounce_state = 3; /* transition to the next state */ } else { debounce_state = 0; /* transition back to state 0 */ } break; case 3: if (tmp != btn_debounced) { btn_debounced = tmp; /* save the debounced button value */ if (tmp == 0) { /* is the button depressed? */ static QEvt const bd = { BTN_DOWN_SIG, 0 }; QF_PUBLISH(&bd, &l_SysTick_Handler); } else { static QEvt const bu = { BTN_UP_SIG, 0 }; QF_PUBLISH(&bu, &l_SysTick_Handler); } } debounce_state = 0; /* transition back to state 0 */ break; } } /*..........................................................................*/ void BSP_init(void) { /* set the system clock as specified in lm3s_config.h (20MHz from PLL) */ SystemInit(); SYSCTL->RCGC2 |= (1 << 5); /* enable clock to GPIOF (User and Eth LEDs)*/ __NOP(); __NOP(); /* configure the pin driving the Ethernet LED */ GPIOF->DIR &= ~(ETH0_LED | ETH1_LED); /* set direction: hardware */ GPIOF->AFSEL |= (ETH0_LED | ETH1_LED); GPIOF->DR2R |= (ETH0_LED | ETH1_LED); GPIOF->ODR &= ~(ETH0_LED | ETH1_LED); GPIOF->PUR |= (ETH0_LED | ETH1_LED); GPIOF->PDR &= ~(ETH0_LED | ETH1_LED); GPIOF->DEN |= (ETH0_LED | ETH1_LED); GPIOF->AMSEL &= ~(ETH0_LED | ETH1_LED); /* configure the pin driving the User LED */ GPIOF->DIR |= USER_LED; /* set direction: output */ GPIOF->DR2R |= USER_LED; GPIOF->DEN |= USER_LED; GPIOF->AMSEL &= ~USER_LED; GPIOF->DATA_Bits[USER_LED] = 0; /* turn the LED off */ /* configure the pin connected to the Buttons */ GPIOF->DIR &= ~USER_BTN; /* set direction: input */ GPIOF->DR2R |= USER_BTN; GPIOF->ODR &= ~USER_BTN; GPIOF->PUR |= USER_BTN; GPIOF->PDR &= ~USER_BTN; GPIOF->DEN |= USER_BTN; GPIOF->AMSEL &= ~USER_BTN; if (QS_INIT((void *)0) == 0) { /* initialize the QS software tracing */ Q_ERROR(); } QS_OBJ_DICTIONARY(&l_SysTick_Handler); } /*..........................................................................*/ void QF_onStartup(void) { /* set up the SysTick timer to fire at BSP_TICKS_PER_SEC rate */ SysTick_Config(SystemFrequency / BSP_TICKS_PER_SEC); /* assing all priority bits for preemption-prio. and none to sub-prio. */ NVIC_SetPriorityGrouping(0U); /* set priorities of ALL ISRs used in the system, see NOTE00 * * !!!!!!!!!!!!!!!!!!!!!!!!!!!! CAUTION !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! * Assign a priority to EVERY ISR explicitly by calling NVIC_SetPriority(). * DO NOT LEAVE THE ISR PRIORITIES AT THE DEFAULT VALUE! */ NVIC_SetPriority(SysTick_IRQn, SYSTICK_PRIO); NVIC_SetPriority(Ethernet_IRQn, ETHERNET_PRIO); /* ... */ NVIC_EnableIRQ(Ethernet_IRQn); /* enable the Ethernet Interrupt */ } /*..........................................................................*/ void QF_onCleanup(void) { } /*..........................................................................*/ void QF_onIdle(void) { /* called with interrupts disabled, see NOTE01 */ /* toggle the User LED on and then off, see NOTE02 */ GPIOF->DATA_Bits[USER_LED] = USER_LED; /* turn the User LED on */ GPIOF->DATA_Bits[USER_LED] = 0; /* turn the User LED off */ #ifdef Q_SPY QF_INT_ENABLE(); if ((UART0->FR & UART_FR_TXFE) != 0) { /* TX done? */ uint16_t fifo = UART_TXFIFO_DEPTH; /* max bytes we can accept */ uint8_t const *block; QF_INT_DISABLE(); block = QS_getBlock(&fifo); /* try to get next block to transmit */ QF_INT_ENABLE(); while (fifo-- != 0) { /* any bytes in the block? */ UART0->DR = *block++; /* put into the FIFO */ } } #elif defined NDEBUG /* Put the CPU and peripherals to the low-power mode. * you might need to customize the clock management for your application, * see the datasheet for your particular Cortex-M MCU. */ QF_CPU_SLEEP(); /* atomically go to sleep and enable interrupts */ #else QF_INT_ENABLE(); /* just enable interrupts */ #endif } /*..........................................................................*/ void Q_onAssert(char const Q_ROM * const file, int_t line) { assert_failed(file, line); } /*..........................................................................*/ /* error routine that is called if the CMSIS library encounters an error */ void assert_failed(char const *file, int line) { (void)file; /* avoid compiler warning */ (void)line; /* avoid compiler warning */ QF_INT_DISABLE(); /* make sure that all interrupts are disabled */ NVIC_SystemReset(); /* perform system reset */ } /*..........................................................................*/ /* sys_now() is used in the lwIP stack */ uint32_t sys_now(void) { return l_nTicks * (1000 / BSP_TICKS_PER_SEC); } /*--------------------------------------------------------------------------*/ #ifdef Q_SPY /*..........................................................................*/ uint8_t QS_onStartup(void const *arg) { static uint8_t qsBuf[6*256]; /* buffer for Quantum Spy */ uint32_t tmp; QS_initBuf(qsBuf, sizeof(qsBuf)); /* enable the peripherals used by the UART0 */ SYSCTL->RCGC1 |= (1 << 0); /* enable clock to UART0 */ SYSCTL->RCGC2 |= (1 << 0); /* enable clock to GPIOA */ __NOP(); /* wait after enabling clocks */ __NOP(); __NOP(); /* configure UART0 pins for UART operation */ tmp = (1 << 0) | (1 << 1); GPIOA->DIR &= ~tmp; GPIOA->AFSEL |= tmp; GPIOA->DR2R |= tmp; /* set 2mA drive, DR4R and DR8R are cleared */ GPIOA->SLR &= ~tmp; GPIOA->ODR &= ~tmp; GPIOA->PUR &= ~tmp; GPIOA->PDR &= ~tmp; GPIOA->DEN |= tmp; GPIOA->AMSEL &= ~tmp; /* configure the UART for the desired baud rate, 8-N-1 operation */ tmp = (((SystemFrequency * 8) / UART_BAUD_RATE) + 1) / 2; UART0->IBRD = tmp / 64; UART0->FBRD = tmp % 64; UART0->LCRH = 0x60; /* configure 8-bit operation */ UART0->LCRH |= 0x10; /* enable FIFOs */ UART0->CTL |= (1 << 0) | (1 << 8) | (1 << 9); QS_tickPeriod_ = SystemFrequency / BSP_TICKS_PER_SEC; QS_tickTime_ = QS_tickPeriod_; /* to start the timestamp at zero */ /* setup the QS filters... */ QS_FILTER_ON(QS_ALL_RECORDS); // QS_FILTER_OFF(QS_QEP_STATE_ENTRY); // QS_FILTER_OFF(QS_QEP_STATE_EXIT); // QS_FILTER_OFF(QS_QEP_STATE_INIT); // QS_FILTER_OFF(QS_QEP_TRAN_HIST); // QS_FILTER_OFF(QS_QEP_INTERN_TRAN); // QS_FILTER_OFF(QS_QEP_TRAN); // QS_FILTER_OFF(QS_QEP_IGNORED); QS_FILTER_OFF(QS_QF_ACTIVE_ADD); QS_FILTER_OFF(QS_QF_ACTIVE_REMOVE); QS_FILTER_OFF(QS_QF_ACTIVE_SUBSCRIBE); QS_FILTER_OFF(QS_QF_ACTIVE_UNSUBSCRIBE); QS_FILTER_OFF(QS_QF_ACTIVE_POST_FIFO); QS_FILTER_OFF(QS_QF_ACTIVE_POST_LIFO); QS_FILTER_OFF(QS_QF_ACTIVE_GET); QS_FILTER_OFF(QS_QF_ACTIVE_GET_LAST); QS_FILTER_OFF(QS_QF_EQUEUE_INIT); QS_FILTER_OFF(QS_QF_EQUEUE_POST_FIFO); QS_FILTER_OFF(QS_QF_EQUEUE_POST_LIFO); QS_FILTER_OFF(QS_QF_EQUEUE_GET); QS_FILTER_OFF(QS_QF_EQUEUE_GET_LAST); QS_FILTER_OFF(QS_QF_MPOOL_INIT); QS_FILTER_OFF(QS_QF_MPOOL_GET); QS_FILTER_OFF(QS_QF_MPOOL_PUT); QS_FILTER_OFF(QS_QF_PUBLISH); QS_FILTER_OFF(QS_QF_NEW); QS_FILTER_OFF(QS_QF_GC_ATTEMPT); QS_FILTER_OFF(QS_QF_GC); // QS_FILTER_OFF(QS_QF_TICK); QS_FILTER_OFF(QS_QF_TIMEEVT_ARM); QS_FILTER_OFF(QS_QF_TIMEEVT_AUTO_DISARM); QS_FILTER_OFF(QS_QF_TIMEEVT_DISARM_ATTEMPT); QS_FILTER_OFF(QS_QF_TIMEEVT_DISARM); QS_FILTER_OFF(QS_QF_TIMEEVT_REARM); QS_FILTER_OFF(QS_QF_TIMEEVT_POST); QS_FILTER_OFF(QS_QF_CRIT_ENTRY); QS_FILTER_OFF(QS_QF_CRIT_EXIT); QS_FILTER_OFF(QS_QF_ISR_ENTRY); QS_FILTER_OFF(QS_QF_ISR_EXIT); return (uint8_t)1; /* return success */ } /*..........................................................................*/ void QS_onCleanup(void) { } /*..........................................................................*/ QSTimeCtr QS_onGetTime(void) { /* invoked with interrupts locked */ if ((SysTick->CTRL & SysTick_CTRL_COUNTFLAG_Msk) == 0) { /* not set? */ return QS_tickTime_ - (QSTimeCtr)SysTick->VAL; } else { /* the rollover occured, but the SysTick_ISR did not run yet */ return QS_tickTime_ + QS_tickPeriod_ - (QSTimeCtr)SysTick->VAL; } } /*..........................................................................*/ void QS_onFlush(void) { uint16_t fifo = UART_TXFIFO_DEPTH; /* Tx FIFO depth */ uint8_t const *block; QF_INT_DISABLE(); while ((block = QS_getBlock(&fifo)) != (uint8_t *)0) { QF_INT_ENABLE(); /* busy-wait until TX FIFO empty */ while ((UART0->FR & UART_FR_TXFE) == 0) { } while (fifo-- != 0) { /* any bytes in the block? */ UART0->DR = *block++; /* put into the TX FIFO */ } fifo = UART_TXFIFO_DEPTH; /* re-load the Tx FIFO depth */ QF_INT_DISABLE(); } QF_INT_ENABLE(); } #endif /* Q_SPY */ /*--------------------------------------------------------------------------*/ /***************************************************************************** * NOTE00: * The QF_AWARE_ISR_CMSIS_PRI constant from the QF port specifies the highest * ISR priority that is disabled by the QF framework. The value is suitable * for the NVIC_SetPriority() CMSIS function. * * Only ISRs prioritized at or below the QF_AWARE_ISR_CMSIS_PRI level (i.e., * with the numerical values of priorities equal or higher than * QF_AWARE_ISR_CMSIS_PRI) are allowed to call any QF services. These ISRs * are "QF-aware". * * Conversely, any ISRs prioritized above the QF_AWARE_ISR_CMSIS_PRI priority * level (i.e., with the numerical values of priorities less than * QF_AWARE_ISR_CMSIS_PRI) are never disabled and are not aware of the kernel. * Such "QF-unaware" ISRs cannot call any QF services. The only mechanism * by which a "QF-unaware" ISR can communicate with the QF framework is by * triggering a "QF-aware" ISR, which can post/publish events. * * NOTE01: * The QF_onIdle() callback is called with interrupts disabled, because the * determination of the idle condition might change by any interrupt posting * an event. QF::onIdle() must internally enable interrupts, ideally * atomically with putting the CPU to the power-saving mode. * * NOTE02: * The User LED is used to visualize the idle loop activity. The brightness * of the LED is proportional to the frequency of invcations of the idle loop. * Please note that the LED is toggled with interrupts locked, so no interrupt * execution time contributes to the brightness of the User LED. */
41.01737
78
0.539988
65300053aba65822ae01f202b15ede6a639ab759
5,518
h
C
tools/TweeboParser/TBParser/src/tagger/SequencePart.h
unititled99/Bella
6ec5ec84ef1cf89a5e99c6a5a3ccc7972d77e023
[ "MIT" ]
1
2021-03-24T20:51:23.000Z
2021-03-24T20:51:23.000Z
Source/TurboParser2.1.0/src/tagger/SequencePart.h
DKlaper/gsw-DepParser
f8938ca0a368c9416919326a50765afeb13197ea
[ "Apache-2.0", "BSD-3-Clause" ]
10
2020-01-28T22:16:20.000Z
2022-02-09T23:32:01.000Z
Source/TurboParser2.1.0/src/tagger/SequencePart.h
DKlaper/gsw-DepParser
f8938ca0a368c9416919326a50765afeb13197ea
[ "Apache-2.0", "BSD-3-Clause" ]
1
2018-08-11T14:12:47.000Z
2018-08-11T14:12:47.000Z
// Copyright (c) 2012-2013 Andre Martins // All Rights Reserved. // // This file is part of TurboParser 2.1. // // TurboParser 2.1 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 3 of the License, or // (at your option) any later version. // // TurboParser 2.1 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 TurboParser 2.1. If not, see <http://www.gnu.org/licenses/>. #ifndef SEQUENCEPART_H_ #define SEQUENCEPART_H_ #include <stdio.h> #include <vector> #include "Part.h" using namespace std; enum { SEQUENCEPART_UNIGRAM = 0, SEQUENCEPART_BIGRAM, SEQUENCEPART_TRIGRAM, NUM_SEQUENCEPARTS }; class SequencePartUnigram : public Part { public: SequencePartUnigram() { position_ = tag_ = -1; }; SequencePartUnigram(int position, int tag) : position_(position), tag_(tag) {}; virtual ~SequencePartUnigram() {}; public: int position() { return position_; }; int tag() { return tag_; }; public: int type() { return SEQUENCEPART_UNIGRAM; }; private: int position_; // Word position. int tag_; // Tag ID. }; class SequencePartBigram : public Part { public: SequencePartBigram() { position_ = tag_ = tag_left_ = -1; }; SequencePartBigram(int position, int tag, int tag_left) : position_(position), tag_(tag), tag_left_(tag_left) {}; virtual ~SequencePartBigram() {}; public: int position() { return position_; }; int tag() { return tag_; }; int tag_left() { return tag_left_; }; public: int type() { return SEQUENCEPART_BIGRAM; }; private: int position_; // Word position. int tag_; // Tag ID. int tag_left_; // Left tag ID }; class SequencePartTrigram : public Part { public: SequencePartTrigram() { position_ = tag_ = tag_left_ = tag_left_left_ = -1; }; SequencePartTrigram(int position, int tag, int tag_left, int tag_left_left) : position_(position), tag_(tag), tag_left_(tag_left), tag_left_left_(tag_left_left) {}; virtual ~SequencePartTrigram() {}; public: int position() { return position_; }; int tag() { return tag_; }; int tag_left() { return tag_left_; }; int tag_left_left() { return tag_left_left_; }; public: int type() { return SEQUENCEPART_TRIGRAM; }; private: int position_; // Word position. int tag_; // Tag ID. int tag_left_; // Left tag ID int tag_left_left_; // Tag ID two words on the left. }; class SequenceParts : public Parts { public: SequenceParts() {}; virtual ~SequenceParts() { DeleteAll(); }; void Initialize() { DeleteAll(); for (int i = 0; i < NUM_SEQUENCEPARTS; ++i) { offsets_[i] = -1; } }; Part *CreatePartUnigram(int position, int tag) { return new SequencePartUnigram(position, tag); } Part *CreatePartBigram(int position, int tag, int tag_left) { return new SequencePartBigram(position, tag, tag_left); } Part *CreatePartTrigram(int position, int tag, int tag_left, int tag_left_left) { return new SequencePartTrigram(position, tag, tag_left, tag_left_left); } public: void DeleteAll(); public: void BuildUnigramIndices(int sentence_length); void BuildBigramIndices(int sentence_length); void BuildTrigramIndices(int sentence_length); void BuildIndices(int sentence_length); void DeleteUnigramIndices(); void DeleteBigramIndices(); void DeleteTrigramIndices(); void DeleteIndices(); const vector<int> &FindUnigramParts(int position) { return index_[position]; } const vector<int> &FindBigramParts(int position) { return index_bigrams_[position]; } const vector<int> &FindTrigramParts(int position) { return index_trigrams_[position]; } // Set/Get offsets: void BuildOffsets() { for (int i = NUM_SEQUENCEPARTS - 1; i >= 0; --i) { if (offsets_[i] < 0) { offsets_[i] = (i == NUM_SEQUENCEPARTS - 1)? size() : offsets_[i + 1]; } } }; void SetOffsetUnigram(int offset, int size) { SetOffset(SEQUENCEPART_UNIGRAM, offset, size); }; void SetOffsetBigram(int offset, int size) { SetOffset(SEQUENCEPART_BIGRAM, offset, size); }; void SetOffsetTrigram(int offset, int size) { SetOffset(SEQUENCEPART_TRIGRAM, offset, size); }; void GetOffsetUnigram(int *offset, int *size) const { GetOffset(SEQUENCEPART_UNIGRAM, offset, size); }; void GetOffsetBigram(int *offset, int *size) const { GetOffset(SEQUENCEPART_BIGRAM, offset, size); }; void GetOffsetTrigram(int *offset, int *size) const { GetOffset(SEQUENCEPART_TRIGRAM, offset, size); }; private: // Get offset from part index. void GetOffset(int i, int *offset, int *size) const { *offset = offsets_[i]; *size = (i < NUM_SEQUENCEPARTS - 1)? offsets_[i + 1] - (*offset) : SequenceParts::size() - (*offset); } // Set offset from part index. void SetOffset(int i, int offset, int size) { offsets_[i] = offset; if (i < NUM_SEQUENCEPARTS - 1) offsets_[i + 1] = offset + size; } private: vector<vector<int> > index_; vector<vector<int> > index_bigrams_; vector<vector<int> > index_trigrams_; int offsets_[NUM_SEQUENCEPARTS]; }; #endif /* SEQUENCEPART_H_ */
28.153061
79
0.686662
658798478618ace05a45def0cb72616c9b185a27
1,837
h
C
System/Library/Frameworks/MediaToolbox.framework/MediaToolbox.h
lechium/tvOS130Headers
6b47cdcd4a6f453b399aa9d742b5d0f7e3f732fd
[ "MIT" ]
11
2019-11-06T04:48:48.000Z
2022-02-09T17:48:15.000Z
System/Library/Frameworks/MediaToolbox.framework/MediaToolbox.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
1
2020-07-26T20:45:31.000Z
2020-08-09T09:30:46.000Z
System/Library/Frameworks/MediaToolbox.framework/MediaToolbox.h
lechium/tvOS135Headers
46cd30d3f0f7962eaa0c3f925cd71f414c65e2ac
[ "MIT" ]
3
2019-12-22T20:17:53.000Z
2021-01-25T09:47:49.000Z
#import <MediaToolbox/FigCaptionBackdropLayer.h> #import <MediaToolbox/FigCaptionLayerPrivate.h> #import <MediaToolbox/FigCaptionLayer.h> #import <MediaToolbox/FigCaptionRowLayer.h> #import <MediaToolbox/FigScreenCaptureController.h> #import <MediaToolbox/FPSupport_PowerStateSingleton.h> #import <MediaToolbox/FPSupport_VideoRangeSingleton.h> #import <MediaToolbox/FigSubtitleBackdropCALayerContentLayer.h> #import <MediaToolbox/FigSubtitleBackdropCALayer.h> #import <MediaToolbox/FigSubtitleWebVTTRegionCALayer.h> #import <MediaToolbox/fmpcDummyThreadInvoker.h> #import <MediaToolbox/FigDisplayMirroringChangeObserver.h> #import <MediaToolbox/FigCDSCALayer.h> #import <MediaToolbox/FigCDSCALayerOutputNodeContentLayer.h> #import <MediaToolbox/FigCDSCALayerOutputNodeLayer.h> #import <MediaToolbox/FigVideoContainerLayer.h> #import <MediaToolbox/FigPlayablePattern.h> #import <MediaToolbox/FigSubtitleCALayer.h> #import <MediaToolbox/FigFCRCALayer.h> #import <MediaToolbox/FigHTTPRequestSessionDataDelegate.h> #import <MediaToolbox/FigBaseCALayer.h> #import <MediaToolbox/FigBaseCALayerHost.h> #import <MediaToolbox/FigDisplaySleepAssertion.h> #import <MediaToolbox/FigSubtitleWebVTTCueCALayer.h> #import <MediaToolbox/FigNSURLSession.h> #import <MediaToolbox/FigNSURLSessionRegistry.h> #import <MediaToolbox/FigVideoLayerInternal.h> #import <MediaToolbox/FigVideoLayer.h> #import <MediaToolbox/FigFCRCALayerOutputNodeContentLayer.h> #import <MediaToolbox/FigFCRCALayerOutputNodeLayer.h> #import <MediaToolbox/CMNetworkActivityObserver.h> #import <MediaToolbox/CMNetworkActivityMonitor.h> #import <MediaToolbox/FigNeroLayer.h> #import <MediaToolbox/FigHUDGraphLayer.h> #import <MediaToolbox/FigHUDLayer.h> #import <MediaToolbox/FigPhotoTile.h> #import <MediaToolbox/FigPhotoTiledLayer.h> #import <MediaToolbox/FigCPEFPAirPlaySession.h>
47.102564
63
0.855199
aa3301fc6cd748723cb787387fe7223f98964e2e
57,713
c
C
cngram2vec.c
ysenarath/wang2vec
28ab4875540d123466dbe6a060cc00c99563948d
[ "Apache-2.0" ]
null
null
null
cngram2vec.c
ysenarath/wang2vec
28ab4875540d123466dbe6a060cc00c99563948d
[ "Apache-2.0" ]
null
null
null
cngram2vec.c
ysenarath/wang2vec
28ab4875540d123466dbe6a060cc00c99563948d
[ "Apache-2.0" ]
null
null
null
// Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <pthread.h> #include <time.h> #include <windows.h> #define MAX_STRING 100 #define EXP_TABLE_SIZE 1000 #define MAX_EXP 6 #define MAX_SENTENCE_LENGTH 1000 #define MAX_CODE_LENGTH 40 #define posix_memalign(p, a, s) (((*(p)) = _aligned_malloc((s), (a))), *(p) ?0 :errno) const int vocab_hash_size = 30000000; // Maximum 30 * 0.7 = 21M words in the vocabulary typedef float real; // Precision of float numbers struct vocab_word { long long cn; int *point; char *word, *code, codelen; }; char train_file[MAX_STRING], output_file[MAX_STRING]; char save_vocab_file[MAX_STRING], read_vocab_file[MAX_STRING]; struct vocab_word *vocab; int binary = 0, type = 1, debug_mode = 2, window = 5, min_count = 5, num_threads = 12, min_reduce = 1; int *vocab_hash; long long vocab_max_size = 1000, vocab_size = 0, layer1_size = 100; long long train_words = 0, word_count_actual = 0, iter = 5, file_size = 0, classes = 0; real alpha = 0.025, starting_alpha, sample = 1e-3; real *syn0, *syn1, *syn1neg, *syn1nce, *expTable; clock_t start; real *syn1_window, *syn1neg_window, *syn1nce_window; int w_offset, window_layer_size; int window_hidden_size = 500; real *syn_window_hidden, *syn_hidden_word, *syn_hidden_word_neg, *syn_hidden_word_nce; int hs = 0, negative = 5; const int table_size = 1e8; int *table; //constrastive negative sampling char negative_classes_file[MAX_STRING]; int *word_to_group; int *group_to_table; //group_size*table_size int class_number; //nce real* noise_distribution; int nce = 10; //param caps real CAP_VALUE = 50; int cap = 0; // char models char boundToken = 'Z'; char *unkNgramToken = "ZZZ"; int cngram_size = 6; real *syn0_cngram; long long cngram_vocab_size = 0; struct vocab_word *cngram_vocab; int *cngram_vocab_hash; long long cngram_vocab_max_size = 1000; char extra_vocab_file[MAX_STRING]; long long maxNgramSize = 1000000; // Returns hash value of a word int GetWordHash(char *word) { unsigned long long a, hash = 0; for (a = 0; a < strlen(word); a++) hash = hash * 257 + word[a]; hash = hash % vocab_hash_size; return hash; } // Search int SearchCNgramVocab(char *ngram) { unsigned int hash = GetWordHash(ngram); while (1) { if (cngram_vocab_hash[hash] == -1) return -1; if (!strcmp(ngram, cngram_vocab[cngram_vocab_hash[hash]].word)) return cngram_vocab_hash[hash]; hash = (hash + 1) % vocab_hash_size; } return -1; } // char functions void ForwardCNgramWordNgram(real *output, char *ngram){ long long a; int index = SearchCNgramVocab(ngram); if (index == -1) {index = SearchCNgramVocab(unkNgramToken);} long long startIndex = layer1_size * index; for (a = 0; a < layer1_size; a++){ output[a] += syn0_cngram[startIndex + a]; } } void ForwardCNgramWordRepresentation(real *output, char *word){ int length = strlen(word); int start; int cur_len; char *ngram; char tmp[cngram_size+1]; tmp[cngram_size] = '\0'; int ngrams = 0; for(start = 0; start < length-cngram_size+1; start++){ ngram = word + start; strncpy(tmp, ngram, cngram_size); ForwardCNgramWordNgram(output, tmp); ngrams++; } for(cur_len = 0; cur_len < cngram_size-1; cur_len++) tmp[cur_len] = boundToken; strncpy(tmp+1, word, cur_len); ForwardCNgramWordNgram(output, tmp); for(cur_len = 0; cur_len < cngram_size-1; cur_len++) tmp[cngram_size-cur_len-1] = boundToken; cur_len = cngram_size - 1; if(length < cur_len){ cur_len = length; } ngram = word + length - cur_len; strncpy(tmp, ngram, cur_len); tmp[cur_len] = 'Z'; tmp[cur_len + 1] = '\0'; ForwardCNgramWordNgram(output, tmp); for(start = 0; start < layer1_size; start++){ output[start] /= ngrams+2; } } void BackwardCNgramWordNgram(real *output, char *ngram, real *output_err){ long long a; int index = SearchCNgramVocab(ngram); if (index == -1) index = SearchCNgramVocab(unkNgramToken); long long startIndex = layer1_size * index; for (a = 0; a < layer1_size; a++){ syn0_cngram[startIndex + a] += output_err[a]; } } void BackwardCNgramWordRepresentation(real *output, char *word, real *output_err){ int length = strlen(word); int start; int cur_len; char *ngram; char tmp[cngram_size+1]; tmp[cngram_size] = '\0'; for(start = 0; start < length-cngram_size+1; start++){ ngram = word + start; strncpy(tmp, ngram, cngram_size); BackwardCNgramWordNgram(output, tmp, output_err); } for(cur_len = 0; cur_len < cngram_size-1; cur_len++) tmp[cur_len] = boundToken; strncpy(tmp+1, word, cur_len); BackwardCNgramWordNgram(output, tmp, output_err); for(cur_len = 0; cur_len < cngram_size-1; cur_len++) tmp[cngram_size-cur_len-1] = boundToken; cur_len = cngram_size - 1; if(length < cur_len){ cur_len = length; } ngram = word + length - cur_len; strncpy(tmp, ngram, cur_len); tmp[cur_len] = 'Z'; tmp[cur_len + 1] = '\0'; BackwardCNgramWordNgram(output, tmp, output_err); } void AddWordNgramToVocab(char *ngram, int count){ int index = SearchCNgramVocab(ngram); if(index != -1){ cngram_vocab[index].cn+=count; return; } unsigned int hash, length = strlen(ngram) + 1; if (length > MAX_STRING) length = MAX_STRING; cngram_vocab[cngram_vocab_size].word = (char *)calloc(length, sizeof(char)); strcpy(cngram_vocab[cngram_vocab_size].word, ngram); cngram_vocab[cngram_vocab_size].cn = count; cngram_vocab_size++; // Reallocate memory if needed if (cngram_vocab_size + 2 >= cngram_vocab_max_size) { cngram_vocab_max_size += 1000; cngram_vocab = (struct vocab_word *)realloc(cngram_vocab, cngram_vocab_max_size * sizeof(struct vocab_word)); } hash = GetWordHash(ngram); while (cngram_vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size; cngram_vocab_hash[hash] = cngram_vocab_size - 1; } void AddAllWordNgramToVocab(char *word, int count){ int length = strlen(word); int start; int cur_len; char *ngram; char tmp[cngram_size+1]; tmp[cngram_size] = '\0'; for(start = 0; start < length-cngram_size+1; start++){ ngram = word + start; strncpy(tmp, ngram, cngram_size); AddWordNgramToVocab(tmp, count); } for(cur_len = 0; cur_len < cngram_size-1; cur_len++) tmp[cur_len] = boundToken; strncpy(tmp+1, word, cur_len); AddWordNgramToVocab(tmp, count); for(cur_len = 0; cur_len < cngram_size-1; cur_len++) tmp[cngram_size-cur_len-1] = boundToken; cur_len = cngram_size - 1; if(length < cur_len){ cur_len = length; } ngram = word + length - cur_len; strncpy(tmp, ngram, cur_len); tmp[cur_len] = 'Z'; tmp[cur_len + 1] = '\0'; AddWordNgramToVocab(tmp, count); } void capParam(real* array, int index){ if(array[index] > CAP_VALUE) array[index] = CAP_VALUE; else if(array[index] < -CAP_VALUE) array[index] = -CAP_VALUE; } real hardTanh(real x){ if(x>=1){ return 1; } else if(x<=-1){ return -1; } else{ return x; } } real dHardTanh(real x, real g){ if(x > 1 && g > 0){ return 0; } if(x < -1 && g < 0){ return 0; } return 1; } void InitUnigramTable() { int a, i; long long train_words_pow = 0; real d1, power = 0.75; table = (int *)malloc(table_size * sizeof(int)); for (a = 0; a < vocab_size; a++) train_words_pow += pow(vocab[a].cn, power); i = 0; d1 = pow(vocab[i].cn, power) / (real)train_words_pow; for (a = 0; a < table_size; a++) { table[a] = i; if (a / (real)table_size > d1) { i++; d1 += pow(vocab[i].cn, power) / (real)train_words_pow; } if (i >= vocab_size) i = vocab_size - 1; } noise_distribution = (real *)calloc(vocab_size, sizeof(real)); for (a = 0; a < vocab_size; a++) noise_distribution[a] = pow(vocab[a].cn, power)/(real)train_words_pow; } // Reads a single word from a file, assuming space + tab + EOL to be word boundaries void ReadWord(char *word, FILE *fin) { int a = 0, ch; while (!feof(fin)) { ch = fgetc(fin); if (ch == 13) continue; if ((ch == ' ') || (ch == '\t') || (ch == '\n')) { if (a > 0) { if (ch == '\n') ungetc(ch, fin); break; } if (ch == '\n') { strcpy(word, (char *)"</s>"); return; } else continue; } word[a] = ch; a++; if (a >= MAX_STRING - 1) a--; // Truncate too long words } word[a] = 0; } // Returns position of a word in the vocabulary; if the word is not found, returns -1 int SearchVocab(char *word) { unsigned int hash = GetWordHash(word); while (1) { if (vocab_hash[hash] == -1) return -1; if (!strcmp(word, vocab[vocab_hash[hash]].word)) return vocab_hash[hash]; hash = (hash + 1) % vocab_hash_size; } return -1; } // Reads a word and returns its index in the vocabulary int ReadWordIndex(FILE *fin) { char word[MAX_STRING]; ReadWord(word, fin); if (feof(fin)) return -1; return SearchVocab(word); } // Adds a word to the vocabulary int AddWordToVocab(char *word) { unsigned int hash, length = strlen(word) + 1; if (length > MAX_STRING) length = MAX_STRING; vocab[vocab_size].word = (char *)calloc(length, sizeof(char)); strcpy(vocab[vocab_size].word, word); vocab[vocab_size].cn = 0; vocab_size++; // Reallocate memory if needed if (vocab_size + 2 >= vocab_max_size) { vocab_max_size += 1000; vocab = (struct vocab_word *)realloc(vocab, vocab_max_size * sizeof(struct vocab_word)); } hash = GetWordHash(word); while (vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size; vocab_hash[hash] = vocab_size - 1; return vocab_size - 1; } // Used later for sorting by word counts int VocabCompare(const void *a, const void *b) { return ((struct vocab_word *)b)->cn - ((struct vocab_word *)a)->cn; } // Sorts the vocabulary by frequency using word counts void SortVocab() { int a, size; unsigned int hash; // Sort the vocabulary and keep </s> at the first position qsort(&vocab[1], vocab_size - 1, sizeof(struct vocab_word), VocabCompare); for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1; size = vocab_size; train_words = 0; for (a = 0; a < size; a++) { // Words occuring less than min_count times will be discarded from the vocab if ((vocab[a].cn < min_count) && (a != 0)) { vocab_size--; free(vocab[a].word); } else { // Hash will be re-computed, as after the sorting it is not actual hash=GetWordHash(vocab[a].word); while (vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size; vocab_hash[hash] = a; train_words += vocab[a].cn; } } vocab = (struct vocab_word *)realloc(vocab, (vocab_size + 1) * sizeof(struct vocab_word)); // Allocate memory for the binary tree construction for (a = 0; a < vocab_size; a++) { vocab[a].code = (char *)calloc(MAX_CODE_LENGTH, sizeof(char)); vocab[a].point = (int *)calloc(MAX_CODE_LENGTH, sizeof(int)); } } // Reduces the vocabulary by removing infrequent tokens void ReduceVocab() { int a, b = 0; unsigned int hash; for (a = 0; a < vocab_size; a++) if (vocab[a].cn > min_reduce) { vocab[b].cn = vocab[a].cn; vocab[b].word = vocab[a].word; b++; } else free(vocab[a].word); vocab_size = b; for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1; for (a = 0; a < vocab_size; a++) { // Hash will be re-computed, as it is not actual hash = GetWordHash(vocab[a].word); while (vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size; vocab_hash[hash] = a; } fflush(stdout); min_reduce++; } // Create binary Huffman tree using the word counts // Frequent words will have short uniqe binary codes void CreateBinaryTree() { long long a, b, i, min1i, min2i, pos1, pos2, point[MAX_CODE_LENGTH]; char code[MAX_CODE_LENGTH]; long long *count = (long long *)calloc(vocab_size * 2 + 1, sizeof(long long)); long long *binary = (long long *)calloc(vocab_size * 2 + 1, sizeof(long long)); long long *parent_node = (long long *)calloc(vocab_size * 2 + 1, sizeof(long long)); for (a = 0; a < vocab_size; a++) count[a] = vocab[a].cn; for (a = vocab_size; a < vocab_size * 2; a++) count[a] = 1e15; pos1 = vocab_size - 1; pos2 = vocab_size; // Following algorithm constructs the Huffman tree by adding one node at a time for (a = 0; a < vocab_size - 1; a++) { // First, find two smallest nodes 'min1, min2' if (pos1 >= 0) { if (count[pos1] < count[pos2]) { min1i = pos1; pos1--; } else { min1i = pos2; pos2++; } } else { min1i = pos2; pos2++; } if (pos1 >= 0) { if (count[pos1] < count[pos2]) { min2i = pos1; pos1--; } else { min2i = pos2; pos2++; } } else { min2i = pos2; pos2++; } count[vocab_size + a] = count[min1i] + count[min2i]; parent_node[min1i] = vocab_size + a; parent_node[min2i] = vocab_size + a; binary[min2i] = 1; } // Now assign binary code to each vocabulary word for (a = 0; a < vocab_size; a++) { b = a; i = 0; while (1) { code[i] = binary[b]; point[i] = b; i++; b = parent_node[b]; if (b == vocab_size * 2 - 2) break; } vocab[a].codelen = i; vocab[a].point[0] = vocab_size - 2; for (b = 0; b < i; b++) { vocab[a].code[i - b - 1] = code[b]; vocab[a].point[i - b] = point[b] - vocab_size; } } free(count); free(binary); free(parent_node); } void LearnVocabFromTrainFile() { char word[MAX_STRING]; FILE *fin; long long a, i; for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1; for (a = 0; a < vocab_hash_size; a++) cngram_vocab_hash[a] = -1; fin = fopen(train_file, "rb"); if (fin == NULL) { printf("ERROR: training data file not found!\n"); exit(1); } vocab_size = 0; AddWordToVocab((char *)"</s>"); AddWordNgramToVocab(unkNgramToken,1000000); while (1) { ReadWord(word, fin); if (feof(fin)) break; train_words++; if ((debug_mode > 1) && (train_words % 100000 == 0)) { printf("%lldK%c", train_words / 1000, 13); fflush(stdout); } i = SearchVocab(word); if (i == -1) { a = AddWordToVocab(word); vocab[a].cn = 1; } else vocab[i].cn++; if (vocab_size > vocab_hash_size * 0.7) ReduceVocab(); } SortVocab(); for (a = 0; a < vocab_size; a++){ AddAllWordNgramToVocab(vocab[a].word, vocab[a].cn); } if (debug_mode > 0) { printf("Vocab size: %lld\n", vocab_size); printf("Ngrams size: %lld\n", cngram_vocab_size); printf("Words in train file: %lld\n", train_words); } file_size = ftell(fin); fclose(fin); } void SaveVocab() { long long i; FILE *fo = fopen(save_vocab_file, "wb"); for (i = 0; i < vocab_size; i++) fprintf(fo, "%s %lld\n", vocab[i].word, vocab[i].cn); fclose(fo); } void ReadVocab() { long long a, i = 0; char c; char word[MAX_STRING]; FILE *fin = fopen(read_vocab_file, "rb"); if (fin == NULL) { printf("Vocabulary file not found\n"); exit(1); } for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1; vocab_size = 0; while (1) { ReadWord(word, fin); if (feof(fin)) break; a = AddWordToVocab(word); fscanf(fin, "%lld%c", &vocab[a].cn, &c); i++; } SortVocab(); if (debug_mode > 0) { printf("Vocab size: %lld\n", vocab_size); printf("Words in train file: %lld\n", train_words); } fin = fopen(train_file, "rb"); if (fin == NULL) { printf("ERROR: training data file not found!\n"); exit(1); } fseek(fin, 0, SEEK_END); file_size = ftell(fin); fclose(fin); } void InitClassUnigramTable() { long long a,c; printf("loading class unigrams \n"); FILE *fin = fopen(negative_classes_file, "rb"); if (fin == NULL) { printf("ERROR: class file not found!\n"); exit(1); } word_to_group = (int *)malloc(vocab_size * sizeof(int)); for(a = 0; a < vocab_size; a++) word_to_group[a] = -1; char class[MAX_STRING]; char prev_class[MAX_STRING]; prev_class[0] = 0; char word[MAX_STRING]; class_number = -1; while (1) { if (feof(fin)) break; ReadWord(class, fin); ReadWord(word, fin); int word_index = SearchVocab(word); if (word_index != -1){ if(strcmp(class, prev_class) != 0){ class_number++; strcpy(prev_class, class); } word_to_group[word_index] = class_number; } ReadWord(word, fin); } class_number++; fclose(fin); group_to_table = (int *)malloc(table_size * class_number * sizeof(int)); long long train_words_pow = 0; real d1, power = 0.75; for(c = 0; c < class_number; c++){ long long offset = c * table_size; train_words_pow = 0; for (a = 0; a < vocab_size; a++) if(word_to_group[a] == c) train_words_pow += pow(vocab[a].cn, power); int i = 0; while(word_to_group[i]!=c && i < vocab_size) i++; d1 = pow(vocab[i].cn, power) / (real)train_words_pow; for (a = 0; a < table_size; a++) { //printf("index %lld , word %d\n", a, i); group_to_table[offset + a] = i; if (a / (real)table_size > d1) { i++; while(word_to_group[i]!=c && i < vocab_size) i++; d1 += pow(vocab[i].cn, power) / (real)train_words_pow; } if (i >= vocab_size) while(word_to_group[i]!=c && i >= 0) i--; } } } void InitNet() { long long a, b; unsigned long long next_random = 1; window_layer_size = layer1_size*window*2; a = posix_memalign((void **)&syn0, 128, (long long)vocab_size * layer1_size * sizeof(real)); if (syn0 == NULL) {printf("Memory allocation failed\n"); exit(1);} a = posix_memalign((void **)&syn0_cngram, 128, (long long)vocab_size * layer1_size * sizeof(real)); if (syn0_cngram == NULL) {printf("Memory allocation failed\n"); exit(1);} if (hs) { a = posix_memalign((void **)&syn1, 128, (long long)vocab_size * layer1_size * sizeof(real)); if (syn1 == NULL) {printf("Memory allocation failed\n"); exit(1);} a = posix_memalign((void **)&syn1_window, 128, (long long)vocab_size * window_layer_size * sizeof(real)); if (syn1_window == NULL) {printf("Memory allocation failed\n"); exit(1);} a = posix_memalign((void **)&syn_hidden_word, 128, (long long)vocab_size * window_hidden_size * sizeof(real)); if (syn_hidden_word == NULL) {printf("Memory allocation failed\n"); exit(1);} for (a = 0; a < vocab_size; a++) for (b = 0; b < layer1_size; b++) syn1[a * layer1_size + b] = 0; for (a = 0; a < vocab_size; a++) for (b = 0; b < window_layer_size; b++) syn1_window[a * window_layer_size + b] = 0; for (a = 0; a < vocab_size; a++) for (b = 0; b < window_hidden_size; b++) syn_hidden_word[a * window_hidden_size + b] = 0; } if (negative>0) { a = posix_memalign((void **)&syn1neg, 128, (long long)vocab_size * layer1_size * sizeof(real)); if (syn1neg == NULL) {printf("Memory allocation failed\n"); exit(1);} a = posix_memalign((void **)&syn1neg_window, 128, (long long)vocab_size * window_layer_size * sizeof(real)); if (syn1neg_window == NULL) {printf("Memory allocation failed\n"); exit(1);} a = posix_memalign((void **)&syn_hidden_word_neg, 128, (long long)vocab_size * window_hidden_size * sizeof(real)); if (syn_hidden_word_neg == NULL) {printf("Memory allocation failed\n"); exit(1);} for (a = 0; a < vocab_size; a++) for (b = 0; b < layer1_size; b++) syn1neg[a * layer1_size + b] = 0; for (a = 0; a < vocab_size; a++) for (b = 0; b < window_layer_size; b++) syn1neg_window[a * window_layer_size + b] = 0; for (a = 0; a < vocab_size; a++) for (b = 0; b < window_hidden_size; b++) syn_hidden_word_neg[a * window_hidden_size + b] = 0; } if (nce>0) { a = posix_memalign((void **)&syn1nce, 128, (long long)vocab_size * layer1_size * sizeof(real)); if (syn1nce == NULL) {printf("Memory allocation failed\n"); exit(1);} a = posix_memalign((void **)&syn1nce_window, 128, (long long)vocab_size * window_layer_size * sizeof(real)); if (syn1nce_window == NULL) {printf("Memory allocation failed\n"); exit(1);} a = posix_memalign((void **)&syn_hidden_word_nce, 128, (long long)vocab_size * window_hidden_size * sizeof(real)); if (syn_hidden_word_nce == NULL) {printf("Memory allocation failed\n"); exit(1);} for (a = 0; a < vocab_size; a++) for (b = 0; b < layer1_size; b++) syn1nce[a * layer1_size + b] = 0; for (a = 0; a < vocab_size; a++) for (b = 0; b < window_layer_size; b++) syn1nce_window[a * window_layer_size + b] = 0; for (a = 0; a < vocab_size; a++) for (b = 0; b < window_hidden_size; b++) syn_hidden_word_nce[a * window_hidden_size + b] = 0; } for (a = 0; a < vocab_size; a++) for (b = 0; b < layer1_size; b++) { next_random = next_random * (unsigned long long)25214903917 + 11; syn0[a * layer1_size + b] = (((next_random & 0xFFFF) / (real)65536) - 0.5) / layer1_size; } for (a = 0; a < cngram_vocab_size; a++) for (b = 0; b < layer1_size; b++){ next_random = next_random * (unsigned long long)25214903917 + 11; syn0_cngram[a * layer1_size + b] = (((next_random & 0xFFFF) / (real)65536) - 0.5) / layer1_size; } a = posix_memalign((void **)&syn_window_hidden, 128, window_hidden_size * window_layer_size * sizeof(real)); if (syn_window_hidden == NULL) {printf("Memory allocation failed\n"); exit(1);} for (a = 0; a < window_hidden_size * window_layer_size; a++){ next_random = next_random * (unsigned long long)25214903917 + 11; syn_window_hidden[a] = (((next_random & 0xFFFF) / (real)65536) - 0.5) / (window_hidden_size*window_layer_size); } CreateBinaryTree(); } void *TrainModelThread(void *id) { long long a, b, d, cw, word, last_word, sentence_length = 0, sentence_position = 0; long long word_count = 0, last_word_count = 0, sen[MAX_SENTENCE_LENGTH + 1]; long long l1, l2, c, target, label, local_iter = iter; unsigned long long next_random = (long long)id; real f, g; clock_t now; int input_len_1 = layer1_size; int window_offset = -1; if(type == 2 || type == 4){ input_len_1=window_layer_size; } real *neu1 = (real *)calloc(input_len_1, sizeof(real)); real *neu1e = (real *)calloc(input_len_1, sizeof(real)); int input_len_2 = 0; if(type == 4){ input_len_2 = window_hidden_size; } real *neu2 = (real *)calloc(input_len_2, sizeof(real)); real *neu2e = (real *)calloc(input_len_2, sizeof(real)); FILE *fi = fopen(train_file, "rb"); fseek(fi, file_size / (long long)num_threads * (long long)id, SEEK_SET); while (1) { if (word_count - last_word_count > 10000) { word_count_actual += word_count - last_word_count; last_word_count = word_count; if ((debug_mode > 1)) { now=clock(); printf("%cAlpha: %f Progress: %.2f%% Words/thread/sec: %.2fk ", 13, alpha, word_count_actual / (real)(iter * train_words + 1) * 100, word_count_actual / ((real)(now - start + 1) / (real)CLOCKS_PER_SEC * 1000)); fflush(stdout); } alpha = starting_alpha * (1 - word_count_actual / (real)(iter * train_words + 1)); if (alpha < starting_alpha * 0.0001) alpha = starting_alpha * 0.0001; } if (sentence_length == 0) { while (1) { word = ReadWordIndex(fi); if (feof(fi)) break; if (word == -1) continue; word_count++; if (word == 0) break; // The subsampling randomly discards frequent words while keeping the ranking same if (sample > 0) { real ran = (sqrt(vocab[word].cn / (sample * train_words)) + 1) * (sample * train_words) / vocab[word].cn; next_random = next_random * (unsigned long long)25214903917 + 11; if (ran < (next_random & 0xFFFF) / (real)65536) continue; } sen[sentence_length] = word; sentence_length++; if (sentence_length >= MAX_SENTENCE_LENGTH) break; } sentence_position = 0; } if (feof(fi) || (word_count > train_words / num_threads)) { word_count_actual += word_count - last_word_count; local_iter--; if (local_iter == 0) break; word_count = 0; last_word_count = 0; sentence_length = 0; fseek(fi, file_size / (long long)num_threads * (long long)id, SEEK_SET); continue; } word = sen[sentence_position]; if (word == -1) continue; for (c = 0; c < input_len_1; c++) neu1[c] = 0; for (c = 0; c < input_len_1; c++) neu1e[c] = 0; for (c = 0; c < input_len_2; c++) neu2[c] = 0; for (c = 0; c < input_len_2; c++) neu2e[c] = 0; next_random = next_random * (unsigned long long)25214903917 + 11; b = next_random % window; if (type == 0) { //train the cbow architecture // in -> hidden cw = 0; for (a = b; a < window * 2 + 1 - b; a++) if (a != window) { c = sentence_position - window + a; if (c < 0) continue; if (c >= sentence_length) continue; last_word = sen[c]; if (last_word == -1) continue; ForwardCNgramWordRepresentation(neu1, vocab[last_word].word); cw++; } if (cw) { for (c = 0; c < layer1_size; c++) neu1[c] /= cw; if (hs) for (d = 0; d < vocab[word].codelen; d++) { f = 0; l2 = vocab[word].point[d] * layer1_size; // Propagate hidden -> output for (c = 0; c < layer1_size; c++) f += neu1[c] * syn1[c + l2]; if (f <= -MAX_EXP) continue; else if (f >= MAX_EXP) continue; else f = expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]; // 'g' is the gradient multiplied by the learning rate g = (1 - vocab[word].code[d] - f) * alpha; // Propagate errors output -> hidden for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1[c + l2]; // Learn weights hidden -> output for (c = 0; c < layer1_size; c++) syn1[c + l2] += g * neu1[c]; if(cap == 1) for (c = 0; c < layer1_size; c++) capParam(syn1, c + l2); } // NEGATIVE SAMPLING if (negative > 0) for (d = 0; d < negative + 1; d++) { if (d == 0) { target = word; label = 1; } else { next_random = next_random * (unsigned long long)25214903917 + 11; if(word_to_group != NULL && word_to_group[word] != -1){ target = word; while(target == word) { target = group_to_table[word_to_group[word]*table_size + (next_random >> 16) % table_size]; next_random = next_random * (unsigned long long)25214903917 + 11; } //printf("negative sampling %lld for word %s returned %s\n", d, vocab[word].word, vocab[target].word); } else{ target = table[(next_random >> 16) % table_size]; } if (target == 0) target = next_random % (vocab_size - 1) + 1; if (target == word) continue; label = 0; } l2 = target * layer1_size; f = 0; for (c = 0; c < layer1_size; c++) f += neu1[c] * syn1neg[c + l2]; if (f > MAX_EXP) g = (label - 1) * alpha; else if (f < -MAX_EXP) g = (label - 0) * alpha; else g = (label - expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]) * alpha; for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1neg[c + l2]; for (c = 0; c < layer1_size; c++) syn1neg[c + l2] += g * neu1[c]; if (cap == 1) for (c = 0; c < layer1_size; c++) capParam(syn1neg, c + l2); } // Noise Contrastive Estimation if (nce > 0) for (d = 0; d < nce + 1; d++) { if (d == 0) { target = word; label = 1; } else { next_random = next_random * (unsigned long long)25214903917 + 11; if(word_to_group != NULL && word_to_group[word] != -1){ target = word; while(target == word) { target = group_to_table[word_to_group[word]*table_size + (next_random >> 16) % table_size]; next_random = next_random * (unsigned long long)25214903917 + 11; } } else{ target = table[(next_random >> 16) % table_size]; } if (target == 0) target = next_random % (vocab_size - 1) + 1; if (target == word) continue; label = 0; } l2 = target * layer1_size; f = 0; for (c = 0; c < layer1_size; c++) f += neu1[c] * syn1nce[c + l2]; if (f > MAX_EXP) g = (label - 1) * alpha; else if (f < -MAX_EXP) g = (label - 0) * alpha; else { f = exp(f); g = (label - f/(noise_distribution[target]*nce + f)) * alpha; } for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1nce[c + l2]; for (c = 0; c < layer1_size; c++) syn1nce[c + l2] += g * neu1[c]; if(cap == 1) for (c = 0; c < layer1_size; c++) capParam(syn1nce,c + l2); } // hidden -> in for (a = b; a < window * 2 + 1 - b; a++) if (a != window) { c = sentence_position - window + a; if (c < 0) continue; if (c >= sentence_length) continue; last_word = sen[c]; if (last_word == -1) continue; BackwardCNgramWordRepresentation(neu1, vocab[last_word].word, neu1e); } } } else if(type==1) { //train skip-gram for (a = b; a < window * 2 + 1 - b; a++) if (a != window) { c = sentence_position - window + a; if (c < 0) continue; if (c >= sentence_length) continue; last_word = sen[c]; if (last_word == -1) continue; l1 = last_word * layer1_size; ForwardCNgramWordRepresentation(neu1, vocab[last_word].word); for (c = 0; c < layer1_size; c++) neu1e[c] = 0; // HIERARCHICAL SOFTMAX if (hs) for (d = 0; d < vocab[word].codelen; d++) { f = 0; l2 = vocab[word].point[d] * layer1_size; // Propagate hidden -> output for (c = 0; c < layer1_size; c++) f += neu1[c] * syn1[c + l2]; if (f <= -MAX_EXP) continue; else if (f >= MAX_EXP) continue; else f = expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]; // 'g' is the gradient multiplied by the learning rate g = (1 - vocab[word].code[d] - f) * alpha; // Propagate errors output -> hidden for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1[c + l2]; // Learn weights hidden -> output for (c = 0; c < layer1_size; c++) syn1[c + l2] += g * neu1[c]; if (cap == 1) for (c = 0; c < layer1_size; c++) capParam(syn1, c + l2); } // NEGATIVE SAMPLING if (negative > 0) for (d = 0; d < negative + 1; d++) { if (d == 0) { target = word; label = 1; } else { next_random = next_random * (unsigned long long)25214903917 + 11; if(word_to_group != NULL && word_to_group[word] != -1){ target = word; while(target == word) { target = group_to_table[word_to_group[word]*table_size + (next_random >> 16) % table_size]; next_random = next_random * (unsigned long long)25214903917 + 11; } //printf("negative sampling %lld for word %s returned %s\n", d, vocab[word].word, vocab[target].word); } else{ target = table[(next_random >> 16) % table_size]; } if (target == 0) target = next_random % (vocab_size - 1) + 1; if (target == word) continue; label = 0; } l2 = target * layer1_size; f = 0; for (c = 0; c < layer1_size; c++) f += neu1[c] * syn1neg[c + l2]; if (f > MAX_EXP) g = (label - 1) * alpha; else if (f < -MAX_EXP) g = (label - 0) * alpha; else g = (label - expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]) * alpha; for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1neg[c + l2]; for (c = 0; c < layer1_size; c++) syn1neg[c + l2] += g * neu1[c]; if (cap == 1) for (c = 0; c < layer1_size; c++) capParam(syn1neg, c + l2); } //Noise Contrastive Estimation if (nce > 0) for (d = 0; d < nce + 1; d++) { if (d == 0) { target = word; label = 1; } else { next_random = next_random * (unsigned long long)25214903917 + 11; if(word_to_group != NULL && word_to_group[word] != -1){ target = word; while(target == word) { target = group_to_table[word_to_group[word]*table_size + (next_random >> 16) % table_size]; next_random = next_random * (unsigned long long)25214903917 + 11; } //printf("negative sampling %lld for word %s returned %s\n", d, vocab[word].word, vocab[target].word); } else{ target = table[(next_random >> 16) % table_size]; } if (target == 0) target = next_random % (vocab_size - 1) + 1; if (target == word) continue; label = 0; } l2 = target * layer1_size; f = 0; for (c = 0; c < layer1_size; c++) f += neu1[c] * syn1nce[c + l2]; if (f > MAX_EXP) g = (label - 1) * alpha; else if (f < -MAX_EXP) g = (label - 0) * alpha; else { f = exp(f); g = (label - f/(noise_distribution[target]*nce + f)) * alpha; } for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1nce[c + l2]; for (c = 0; c < layer1_size; c++) syn1nce[c + l2] += g * neu1[c]; if (cap == 1) for (c = 0; c < layer1_size; c++) capParam(syn1nce, c + l2); } // Learn weights input -> hidden BackwardCNgramWordRepresentation(neu1, vocab[last_word].word, neu1e); } } else if(type == 2){ //train the cwindow architecture // in -> hidden cw = 0; for (a = 0; a < window * 2 + 1; a++) if (a != window) { c = sentence_position - window + a; if (c < 0) continue; if (c >= sentence_length) continue; last_word = sen[c]; if (last_word == -1) continue; window_offset = a*layer1_size; if (a > window) window_offset-=layer1_size; ForwardCNgramWordRepresentation(&neu1[window_offset], vocab[last_word].word); cw++; } if (cw) { if (hs) for (d = 0; d < vocab[word].codelen; d++) { f = 0; l2 = vocab[word].point[d] * window_layer_size; // Propagate hidden -> output for (c = 0; c < window_layer_size; c++) f += neu1[c] * syn1_window[c + l2]; if (f <= -MAX_EXP) continue; else if (f >= MAX_EXP) continue; else f = expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]; // 'g' is the gradient multiplied by the learning rate g = (1 - vocab[word].code[d] - f) * alpha; // Propagate errors output -> hidden for (c = 0; c < window_layer_size; c++) neu1e[c] += g * syn1_window[c + l2]; // Learn weights hidden -> output for (c = 0; c < window_layer_size; c++) syn1_window[c + l2] += g * neu1[c]; if (cap == 1) for (c = 0; c < window_layer_size; c++) capParam(syn1_window, c + l2); } // NEGATIVE SAMPLING if (negative > 0) for (d = 0; d < negative + 1; d++) { if (d == 0) { target = word; label = 1; } else { next_random = next_random * (unsigned long long)25214903917 + 11; if(word_to_group != NULL && word_to_group[word] != -1){ target = word; while(target == word) { target = group_to_table[word_to_group[word]*table_size + (next_random >> 16) % table_size]; next_random = next_random * (unsigned long long)25214903917 + 11; } //printf("negative sampling %lld for word %s returned %s\n", d, vocab[word].word, vocab[target].word); } else{ target = table[(next_random >> 16) % table_size]; } if (target == 0) target = next_random % (vocab_size - 1) + 1; if (target == word) continue; label = 0; } l2 = target * window_layer_size; f = 0; for (c = 0; c < window_layer_size; c++) f += neu1[c] * syn1neg_window[c + l2]; if (f > MAX_EXP) g = (label - 1) * alpha; else if (f < -MAX_EXP) g = (label - 0) * alpha; else g = (label - expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]) * alpha; for (c = 0; c < window_layer_size; c++) neu1e[c] += g * syn1neg_window[c + l2]; for (c = 0; c < window_layer_size; c++) syn1neg_window[c + l2] += g * neu1[c]; if(cap == 1) for (c = 0; c < window_layer_size; c++) capParam(syn1neg_window, c + l2); } // Noise Contrastive Estimation if (nce > 0) for (d = 0; d < nce + 1; d++) { if (d == 0) { target = word; label = 1; } else { next_random = next_random * (unsigned long long)25214903917 + 11; if(word_to_group != NULL && word_to_group[word] != -1){ target = word; while(target == word) { target = group_to_table[word_to_group[word]*table_size + (next_random >> 16) % table_size]; next_random = next_random * (unsigned long long)25214903917 + 11; } //printf("negative sampling %lld for word %s returned %s\n", d, vocab[word].word, vocab[target].word); } else{ target = table[(next_random >> 16) % table_size]; } if (target == 0) target = next_random % (vocab_size - 1) + 1; if (target == word) continue; label = 0; } l2 = target * window_layer_size; f = 0; for (c = 0; c < window_layer_size; c++) f += neu1[c] * syn1nce_window[c + l2]; if (f > MAX_EXP) g = (label - 1) * alpha; else if (f < -MAX_EXP) g = (label - 0) * alpha; else { f = exp(f); g = (label - f/(noise_distribution[target]*nce + f)) * alpha; } for (c = 0; c < window_layer_size; c++) neu1e[c] += g * syn1nce_window[c + l2]; for (c = 0; c < window_layer_size; c++) syn1nce_window[c + l2] += g * neu1[c]; if(cap == 1) for (c = 0; c < window_layer_size; c++) capParam(syn1nce_window, c + l2); } // hidden -> in for (a = 0; a < window * 2 + 1; a++) if (a != window) { c = sentence_position - window + a; if (c < 0) continue; if (c >= sentence_length) continue; last_word = sen[c]; if (last_word == -1) continue; window_offset = a * layer1_size; if(a > window) window_offset -= layer1_size; BackwardCNgramWordRepresentation(&neu1[window_offset], vocab[last_word].word, &neu1e[window_offset]); } } } else if (type == 3){ //train structured skip-gram for (a = 0; a < window * 2 + 1; a++) if (a != window) { c = sentence_position - window + a; if (c < 0) continue; if (c >= sentence_length) continue; last_word = sen[c]; if (last_word == -1) continue; l1 = last_word * layer1_size; window_offset = a * layer1_size; if(a > window) window_offset -= layer1_size; ForwardCNgramWordRepresentation(neu1, vocab[last_word].word); for (c = 0; c < layer1_size; c++) neu1e[c] = 0; // HIERARCHICAL SOFTMAX if (hs) for (d = 0; d < vocab[word].codelen; d++) { f = 0; l2 = vocab[word].point[d] * window_layer_size; // Propagate hidden -> output for (c = 0; c < layer1_size; c++) f += neu1[c] * syn1_window[c + l2 + window_offset]; if (f <= -MAX_EXP) continue; else if (f >= MAX_EXP) continue; else f = expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]; // 'g' is the gradient multiplied by the learning rate g = (1 - vocab[word].code[d] - f) * alpha; // Propagate errors output -> hidden for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1_window[c + l2 + window_offset]; // Learn weights hidden -> output for (c = 0; c < layer1_size; c++) syn1[c + l2 + window_offset] += g * neu1[c]; if(cap == 1) for (c = 0; c < layer1_size; c++) capParam(syn1, c + l2 + window_offset); } // NEGATIVE SAMPLING if (negative > 0) for (d = 0; d < negative + 1; d++) { if (d == 0) { target = word; label = 1; } else { next_random = next_random * (unsigned long long)25214903917 + 11; if(word_to_group != NULL && word_to_group[word] != -1){ target = word; while(target == word) { target = group_to_table[word_to_group[word]*table_size + (next_random >> 16) % table_size]; next_random = next_random * (unsigned long long)25214903917 + 11; } //printf("negative sampling %lld for word %s returned %s\n", d, vocab[word].word, vocab[target].word); } else{ target = table[(next_random >> 16) % table_size]; } if (target == 0) target = next_random % (vocab_size - 1) + 1; if (target == word) continue; label = 0; } l2 = target * window_layer_size; f = 0; for (c = 0; c < layer1_size; c++) f += neu1[c] * syn1neg_window[c + l2 + window_offset]; if (f > MAX_EXP) g = (label - 1) * alpha; else if (f < -MAX_EXP) g = (label - 0) * alpha; else g = (label - expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]) * alpha; for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1neg_window[c + l2 + window_offset]; for (c = 0; c < layer1_size; c++) syn1neg_window[c + l2 + window_offset] += g * neu1[c]; if(cap == 1) for (c = 0; c < layer1_size; c++) capParam(syn1neg_window, c + l2 + window_offset); } // Noise Constrastive Estimation if (nce > 0) for (d = 0; d < nce + 1; d++) { if (d == 0) { target = word; label = 1; } else { next_random = next_random * (unsigned long long)25214903917 + 11; if(word_to_group != NULL && word_to_group[word] != -1){ target = word; while(target == word) { target = group_to_table[word_to_group[word]*table_size + (next_random >> 16) % table_size]; next_random = next_random * (unsigned long long)25214903917 + 11; } //printf("negative sampling %lld for word %s returned %s\n", d, vocab[word].word, vocab[target].word); } else{ target = table[(next_random >> 16) % table_size]; } if (target == 0) target = next_random % (vocab_size - 1) + 1; if (target == word) continue; label = 0; } l2 = target * window_layer_size; f = 0; for (c = 0; c < layer1_size; c++) f += neu1[c] * syn1nce_window[c + l2 + window_offset]; if (f > MAX_EXP) g = (label - 1) * alpha; else if (f < -MAX_EXP) g = (label - 0) * alpha; else { f = exp(f); g = (label - f/(noise_distribution[target]*nce + f)) * alpha; } for (c = 0; c < layer1_size; c++) neu1e[c] += g * syn1nce_window[c + l2 + window_offset]; for (c = 0; c < layer1_size; c++) syn1nce_window[c + l2 + window_offset] += g * neu1[c]; if (cap == 1) for (c = 0; c < layer1_size; c++) capParam(syn1nce_window, c + l2 + window_offset); } // Learn weights input -> hidden BackwardCNgramWordRepresentation(neu1, vocab[last_word].word, neu1e); } } else if(type == 4){ //training senna // in -> hidden cw = 0; for (a = 0; a < window * 2 + 1; a++) if (a != window) { c = sentence_position - window + a; if (c < 0) continue; if (c >= sentence_length) continue; last_word = sen[c]; if (last_word == -1) continue; window_offset = a*layer1_size; if (a > window) window_offset-=layer1_size; for (c = 0; c < layer1_size; c++) neu1[c+window_offset] += syn0[c + last_word * layer1_size]; cw++; } if (cw) { for (a = 0; a < window_hidden_size; a++){ c = a*window_layer_size; for(b = 0; b < window_layer_size; b++){ neu2[a] += syn_window_hidden[c + b] * neu1[b]; } } if (hs) for (d = 0; d < vocab[word].codelen; d++) { f = 0; l2 = vocab[word].point[d] * window_hidden_size; // Propagate hidden -> output for (c = 0; c < window_hidden_size; c++) f += hardTanh(neu2[c]) * syn_hidden_word[c + l2]; if (f <= -MAX_EXP) continue; else if (f >= MAX_EXP) continue; else f = expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]; // 'g' is the gradient multiplied by the learning rate g = (1 - vocab[word].code[d] - f) * alpha; // Propagate errors output -> hidden for (c = 0; c < window_hidden_size; c++) neu2e[c] += dHardTanh(neu2[c],g) * g * syn_hidden_word[c + l2]; // Learn weights hidden -> output for (c = 0; c < window_hidden_size; c++) syn_hidden_word[c + l2] += dHardTanh(neu2[c],g) * g * neu2[c]; } // NEGATIVE SAMPLING if (negative > 0) for (d = 0; d < negative + 1; d++) { if (d == 0) { target = word; label = 1; } else { next_random = next_random * (unsigned long long)25214903917 + 11; if(word_to_group != NULL && word_to_group[word] != -1){ target = word; while(target == word) { target = group_to_table[word_to_group[word]*table_size + (next_random >> 16) % table_size]; next_random = next_random * (unsigned long long)25214903917 + 11; } //printf("negative sampling %lld for word %s returned %s\n", d, vocab[word].word, vocab[target].word); } else{ target = table[(next_random >> 16) % table_size]; } if (target == 0) target = next_random % (vocab_size - 1) + 1; if (target == word) continue; label = 0; } l2 = target * window_hidden_size; f = 0; for (c = 0; c < window_hidden_size; c++) f += hardTanh(neu2[c]) * syn_hidden_word_neg[c + l2]; if (f > MAX_EXP) g = (label - 1) * alpha / negative; else if (f < -MAX_EXP) g = (label - 0) * alpha / negative; else g = (label - expTable[(int)((f + MAX_EXP) * (EXP_TABLE_SIZE / MAX_EXP / 2))]) * alpha / negative; for (c = 0; c < window_hidden_size; c++) neu2e[c] += dHardTanh(neu2[c],g) * g * syn_hidden_word_neg[c + l2]; for (c = 0; c < window_hidden_size; c++) syn_hidden_word_neg[c + l2] += dHardTanh(neu2[c],g) * g * neu2[c]; } for (a = 0; a < window_hidden_size; a++) for(b = 0; b < window_layer_size; b++) neu1e[b] += neu2e[a] * syn_window_hidden[a*window_layer_size + b]; for (a = 0; a < window_hidden_size; a++) for(b = 0; b < window_layer_size; b++) syn_window_hidden[a*window_layer_size + b] += neu2e[a] * neu1[b]; // hidden -> in for (a = 0; a < window * 2 + 1; a++) if (a != window) { c = sentence_position - window + a; if (c < 0) continue; if (c >= sentence_length) continue; last_word = sen[c]; if (last_word == -1) continue; window_offset = a * layer1_size; if(a > window) window_offset -= layer1_size; for (c = 0; c < layer1_size; c++) syn0[c + last_word * layer1_size] += neu1e[c + window_offset]; } } } else{ printf("unknown type %i", type); exit(0); } sentence_position++; if (sentence_position >= sentence_length) { sentence_length = 0; continue; } } fclose(fi); free(neu1); free(neu1e); pthread_exit(NULL); } void TrainModel() { long a, b; long extra_words; FILE *fo; FILE *fi; pthread_t *pt = (pthread_t *)malloc(num_threads * sizeof(pthread_t)); printf("Starting training using file %s\n", train_file); starting_alpha = alpha; if (read_vocab_file[0] != 0) ReadVocab(); else LearnVocabFromTrainFile(); if (save_vocab_file[0] != 0) SaveVocab(); if (output_file[0] == 0) return; InitNet(); if (negative > 0 || nce > 0) InitUnigramTable(); if (negative_classes_file[0] != 0) InitClassUnigramTable(); start = clock(); for (a = 0; a < num_threads; a++) pthread_create(&pt[a], NULL, TrainModelThread, (void *)a); for (a = 0; a < num_threads; a++) pthread_join(pt[a], NULL); fo = fopen(output_file, "wb"); if (classes == 0) { // Save the word vectors real neu1[layer1_size]; // count extra words extra_words = 0; fi = fopen(extra_vocab_file, "rb"); if (fi != NULL) { char word[MAX_STRING]; while(1){ ReadWord(word, fi); if(feof(fi)) break; extra_words++; ReadWord(word, fi); } } fclose(fi); fprintf(fo, "%lld %lld\n", vocab_size + extra_words, layer1_size); for (a = 0; a < vocab_size; a++) { fprintf(fo, "%s ", vocab[a].word); for (b = 0; b < layer1_size; b++) neu1[b] = 0; ForwardCNgramWordRepresentation(neu1, vocab[a].word); if (binary) for (b = 0; b < layer1_size; b++) fwrite(&neu1[b], sizeof(real), 1, fo); else for (b = 0; b < layer1_size; b++) fprintf(fo, "%lf ", neu1[b]); fprintf(fo, "\n"); } fi = fopen(extra_vocab_file, "rb"); if (fi != NULL) { char word[MAX_STRING]; while(1){ ReadWord(word, fi); if(feof(fi)) break; for (b = 0; b < layer1_size; b++) neu1[b] = 0; fprintf(fo, "%s ", word); ForwardCNgramWordRepresentation(neu1, word); if (binary) for (b = 0; b < layer1_size; b++) fwrite(&neu1[b], sizeof(real), 1, fo); else for (b = 0; b < layer1_size; b++) fprintf(fo, "%lf ", neu1[b]); fprintf(fo, "\n"); ReadWord(word, fi); } } fclose(fi); } fclose(fo); } int ArgPos(char *str, int argc, char **argv) { int a; for (a = 1; a < argc; a++) if (!strcmp(str, argv[a])) { if (a == argc - 1) { printf("Argument missing for %s\n", str); exit(1); } return a; } return -1; } int main(int argc, char **argv) { int i; if (argc == 1) { printf("WORD VECTOR estimation toolkit v 0.1c\n\n"); printf("Options:\n"); printf("Parameters for training:\n"); printf("\t-train <file>\n"); printf("\t\tUse text data from <file> to train the model\n"); printf("\t-output <file>\n"); printf("\t\tUse <file> to save the resulting word vectors / word clusters\n"); printf("\t-size <int>\n"); printf("\t\tSet size of word vectors; default is 100\n"); printf("\t-window <int>\n"); printf("\t\tSet max skip length between words; default is 5\n"); printf("\t-sample <float>\n"); printf("\t\tSet threshold for occurrence of words. Those that appear with higher frequency in the training data\n"); printf("\t\twill be randomly down-sampled; default is 1e-3, useful range is (0, 1e-5)\n"); printf("\t-hs <int>\n"); printf("\t\tUse Hierarchical Softmax; default is 0 (not used)\n"); printf("\t-negative <int>\n"); printf("\t\tNumber of negative examples; default is 5, common values are 3 - 10 (0 = not used)\n"); printf("\t-negative-classes <file>\n"); printf("\t\tNegative classes to sample from\n"); printf("\t-nce <int>\n"); printf("\t\tNumber of negative examples for nce; default is 5, common values are 3 - 10 (0 = not used)\n"); printf("\t-threads <int>\n"); printf("\t\tUse <int> threads (default 12)\n"); printf("\t-iter <int>\n"); printf("\t\tRun more training iterations (default 5)\n"); printf("\t-cngram-size <int>\n"); printf("\t\tUse <int> size of the character ngrams (default 4)\n"); printf("\t-extra_vocab_file <file>\n"); printf("\t\tUse <file> file with extra words (one per line)\n"); printf("\t-min-count <int>\n"); printf("\t\tThis will discard words that appear less than <int> times; default is 5\n"); printf("\t-alpha <float>\n"); printf("\t\tSet the starting learning rate; default is 0.025 for skip-gram and 0.05 for CBOW\n"); printf("\t-classes <int>\n"); printf("\t\tOutput word classes rather than word vectors; default number of classes is 0 (vectors are written)\n"); printf("\t-debug <int>\n"); printf("\t\tSet the debug mode (default = 2 = more info during training)\n"); printf("\t-binary <int>\n"); printf("\t\tSave the resulting vectors in binary moded; default is 0 (off)\n"); printf("\t-save-vocab <file>\n"); printf("\t\tThe vocabulary will be saved to <file>\n"); printf("\t-read-vocab <file>\n"); printf("\t\tThe vocabulary will be read from <file>, not constructed from the training data\n"); printf("\t-type <int>\n"); printf("\t\tType of embeddings (0 for cbow, 1 for skipngram, 2 for cwindow, 3 for structured skipngram, 4 for senna type)\n"); printf("\t-cap <int>\n"); printf("\t\tlimit the parameter values to the range [-50, 50]; default is 0 (off)\n"); printf("\nExamples:\n"); printf("./word2vec -train data.txt -output vec.txt -size 200 -window 5 -sample 1e-4 -negative 5 -hs 0 -binary 0 -type 1 -iter 3 -cngram-size 4 -extra_vocab_file extra.txt \n\n"); return 0; } output_file[0] = 0; save_vocab_file[0] = 0; read_vocab_file[0] = 0; negative_classes_file[0] = 0; if ((i = ArgPos((char *)"-size", argc, argv)) > 0) layer1_size = atoi(argv[i + 1]); if ((i = ArgPos((char *)"-train", argc, argv)) > 0) strcpy(train_file, argv[i + 1]); if ((i = ArgPos((char *)"-save-vocab", argc, argv)) > 0) strcpy(save_vocab_file, argv[i + 1]); if ((i = ArgPos((char *)"-read-vocab", argc, argv)) > 0) strcpy(read_vocab_file, argv[i + 1]); if ((i = ArgPos((char *)"-debug", argc, argv)) > 0) debug_mode = atoi(argv[i + 1]); if ((i = ArgPos((char *)"-binary", argc, argv)) > 0) binary = atoi(argv[i + 1]); if ((i = ArgPos((char *)"-type", argc, argv)) > 0) type = atoi(argv[i + 1]); if ((i = ArgPos((char *)"-output", argc, argv)) > 0) strcpy(output_file, argv[i + 1]); if ((i = ArgPos((char *)"-window", argc, argv)) > 0) window = atoi(argv[i + 1]); if ((i = ArgPos((char *)"-sample", argc, argv)) > 0) sample = atof(argv[i + 1]); if ((i = ArgPos((char *)"-hs", argc, argv)) > 0) hs = atoi(argv[i + 1]); if ((i = ArgPos((char *)"-negative", argc, argv)) > 0) negative = atoi(argv[i + 1]); if ((i = ArgPos((char *)"-negative-classes", argc, argv)) > 0) strcpy(negative_classes_file, argv[i + 1]); if ((i = ArgPos((char *)"-nce", argc, argv)) > 0) nce = atoi(argv[i + 1]); if ((i = ArgPos((char *)"-threads", argc, argv)) > 0) num_threads = atoi(argv[i + 1]); if ((i = ArgPos((char *)"-iter", argc, argv)) > 0) iter = atoi(argv[i + 1]); if ((i = ArgPos((char *)"-min-count", argc, argv)) > 0) min_count = atoi(argv[i + 1]); if ((i = ArgPos((char *)"-classes", argc, argv)) > 0) classes = atoi(argv[i + 1]); if ((i = ArgPos((char *)"-cap", argc, argv)) > 0) cap = atoi(argv[i + 1]); if ((i = ArgPos((char *)"-cngram-size", argc, argv)) > 0) cngram_size = atoi(argv[i + 1]); if ((i = ArgPos((char *)"-extra_vocab_file", argc, argv)) > 0) strcpy(extra_vocab_file, argv[i + 1]); if (type==0 || type==2 || type==4) alpha = 0.05; if ((i = ArgPos((char *)"-alpha", argc, argv)) > 0) alpha = atof(argv[i + 1]); vocab = (struct vocab_word *)calloc(vocab_max_size, sizeof(struct vocab_word)); vocab_hash = (int *)calloc(vocab_hash_size, sizeof(int)); cngram_vocab = (struct vocab_word *)calloc(cngram_vocab_max_size, sizeof(struct vocab_word)); cngram_vocab_hash = (int *)calloc(vocab_hash_size, sizeof(int)); expTable = (real *)malloc((EXP_TABLE_SIZE + 1) * sizeof(real)); for (i = 0; i < EXP_TABLE_SIZE; i++) { expTable[i] = exp((i / (real)EXP_TABLE_SIZE * 2 - 1) * MAX_EXP); // Precompute the exp() table expTable[i] = expTable[i] / (expTable[i] + 1); // Precompute f(x) = x / (x + 1) } TrainModel(); return 0; }
39.884589
182
0.567775
a632b5fbef79c30bd38db872fae9d2f27de92c4d
2,905
h
C
dir600b_v2.03/tools/sqlzma-3.4/lzma-457/CPP/7zip/Compress/Branch/x86_2.h
ghsecuritylab/DIR600B2
78510ce13e037c430c84b4cdc7f49939481fe894
[ "BSD-2-Clause" ]
1
2019-07-21T01:58:19.000Z
2019-07-21T01:58:19.000Z
dir600b_v2.03/tools/sqlzma-3.4/lzma-457/CPP/7zip/Compress/Branch/x86_2.h
ghsecuritylab/DIR600B2
78510ce13e037c430c84b4cdc7f49939481fe894
[ "BSD-2-Clause" ]
null
null
null
dir600b_v2.03/tools/sqlzma-3.4/lzma-457/CPP/7zip/Compress/Branch/x86_2.h
ghsecuritylab/DIR600B2
78510ce13e037c430c84b4cdc7f49939481fe894
[ "BSD-2-Clause" ]
2
2020-03-06T22:45:39.000Z
2021-12-23T13:58:14.000Z
// x86_2.h #ifndef __BRANCH_X86_2_H #define __BRANCH_X86_2_H #include "../../../Common/MyCom.h" #include "../RangeCoder/RangeCoderBit.h" #include "../../ICoder.h" namespace NCompress { namespace NBcj2 { const int kNumMoveBits = 5; #ifndef EXTRACT_ONLY class CEncoder: public ICompressCoder2, public CMyUnknownImp { Byte *_buffer; public: CEncoder(): _buffer(0) {}; ~CEncoder(); bool Create(); COutBuffer _mainStream; COutBuffer _callStream; COutBuffer _jumpStream; NCompress::NRangeCoder::CEncoder _rangeEncoder; NCompress::NRangeCoder::CBitEncoder<kNumMoveBits> _statusEncoder[256 + 2]; HRESULT Flush(); void ReleaseStreams() { _mainStream.ReleaseStream(); _callStream.ReleaseStream(); _jumpStream.ReleaseStream(); _rangeEncoder.ReleaseStream(); } class CCoderReleaser { CEncoder *_coder; public: CCoderReleaser(CEncoder *coder): _coder(coder) {} ~CCoderReleaser() { _coder->ReleaseStreams(); } }; public: MY_UNKNOWN_IMP HRESULT CodeReal(ISequentialInStream **inStreams, const UInt64 **inSizes, UInt32 numInStreams, ISequentialOutStream **outStreams, const UInt64 **outSizes, UInt32 numOutStreams, ICompressProgressInfo *progress); STDMETHOD(Code)(ISequentialInStream **inStreams, const UInt64 **inSizes, UInt32 numInStreams, ISequentialOutStream **outStreams, const UInt64 **outSizes, UInt32 numOutStreams, ICompressProgressInfo *progress); }; #endif class CDecoder: public ICompressCoder2, public CMyUnknownImp { public: CInBuffer _mainInStream; CInBuffer _callStream; CInBuffer _jumpStream; NCompress::NRangeCoder::CDecoder _rangeDecoder; NCompress::NRangeCoder::CBitDecoder<kNumMoveBits> _statusDecoder[256 + 2]; COutBuffer _outStream; void ReleaseStreams() { _mainInStream.ReleaseStream(); _callStream.ReleaseStream(); _jumpStream.ReleaseStream(); _rangeDecoder.ReleaseStream(); _outStream.ReleaseStream(); } HRESULT Flush() { return _outStream.Flush(); } class CCoderReleaser { CDecoder *_coder; public: CCoderReleaser(CDecoder *coder): _coder(coder) {} ~CCoderReleaser() { _coder->ReleaseStreams(); } }; public: MY_UNKNOWN_IMP HRESULT CodeReal(ISequentialInStream **inStreams, const UInt64 **inSizes, UInt32 numInStreams, ISequentialOutStream **outStreams, const UInt64 **outSizes, UInt32 numOutStreams, ICompressProgressInfo *progress); STDMETHOD(Code)(ISequentialInStream **inStreams, const UInt64 **inSizes, UInt32 numInStreams, ISequentialOutStream **outStreams, const UInt64 **outSizes, UInt32 numOutStreams, ICompressProgressInfo *progress); }; }} #endif
23.427419
77
0.678485
10d4b3acdd41862d0d7b797e40dd5f8bc443e62b
1,448
h
C
src/dpdk/lib/librte_gso/gso_tcp4.h
timgates42/trex-core
efe94752fcb2d0734c83d4877afe92a3dbf8eccd
[ "Apache-2.0" ]
956
2015-06-24T15:04:55.000Z
2022-03-30T06:25:04.000Z
src/dpdk/lib/librte_gso/gso_tcp4.h
angelyouyou/trex-core
fddf78584cae285d9298ef23f9f5c8725e16911e
[ "Apache-2.0" ]
782
2015-09-20T15:19:00.000Z
2022-03-31T23:52:05.000Z
src/dpdk/lib/librte_gso/gso_tcp4.h
angelyouyou/trex-core
fddf78584cae285d9298ef23f9f5c8725e16911e
[ "Apache-2.0" ]
429
2015-06-27T19:34:21.000Z
2022-03-23T11:02:51.000Z
/* SPDX-License-Identifier: BSD-3-Clause * Copyright(c) 2017 Intel Corporation */ #ifndef _GSO_TCP4_H_ #define _GSO_TCP4_H_ #include <stdint.h> #include <rte_mbuf.h> /** * Segment an IPv4/TCP packet. This function doesn't check if the input * packet has correct checksums, and doesn't update checksums for output * GSO segments. Furthermore, it doesn't process IP fragment packets. * * @param pkt * The packet mbuf to segment. * @param gso_size * The max length of a GSO segment, measured in bytes. * @param ipid_delta * The increasing unit of IP ids. * @param direct_pool * MBUF pool used for allocating direct buffers for output segments. * @param indirect_pool * MBUF pool used for allocating indirect buffers for output segments. * @param pkts_out * Pointer array used to store the MBUF addresses of output GSO * segments, when the function succeeds. If the memory space in * pkts_out is insufficient, it fails and returns -EINVAL. * @param nb_pkts_out * The max number of items that 'pkts_out' can keep. * * @return * - The number of GSO segments filled in pkts_out on success. * - Return -ENOMEM if run out of memory in MBUF pools. * - Return -EINVAL for invalid parameters. */ int gso_tcp4_segment(struct rte_mbuf *pkt, uint16_t gso_size, uint8_t ip_delta, struct rte_mempool *direct_pool, struct rte_mempool *indirect_pool, struct rte_mbuf **pkts_out, uint16_t nb_pkts_out); #endif
31.478261
72
0.737569
e75b6473e0b85ce707e90cdf05145b8331fe7e0e
5,608
c
C
Ch14/Exercises/Exer_14_9.c
kilinchange/C_Primer_Plus
8782c6af62e24be9507e3c85411174592d0e4f4d
[ "MIT" ]
null
null
null
Ch14/Exercises/Exer_14_9.c
kilinchange/C_Primer_Plus
8782c6af62e24be9507e3c85411174592d0e4f4d
[ "MIT" ]
null
null
null
Ch14/Exercises/Exer_14_9.c
kilinchange/C_Primer_Plus
8782c6af62e24be9507e3c85411174592d0e4f4d
[ "MIT" ]
null
null
null
#include <stdio.h> #include <string.h> #include <stdbool.h> #include <ctype.h> #include <stdlib.h> #define STRLEN 20 #define SEAT_NUMBER 12 #define FLIGHT_NUMBER 4 struct seat_s { int seat_id; bool is_ordered; bool is_confirmed; char firstname[STRLEN]; char lastname[STRLEN]; }; struct flight_s { struct seat_s seats[SEAT_NUMBER]; int flight_id; }; int compare_two_seats_by_name(const void *a, const void* b); int main(void) { struct flight_s flights[FLIGHT_NUMBER]; int seat_id; char firstname[STRLEN], lastname[STRLEN], buffer[1024]; flights[0].flight_id = 102; flights[1].flight_id = 311; flights[2].flight_id = 444; flights[3].flight_id = 519; for (int j = 0; j < FLIGHT_NUMBER; j++) { for (int i = 0; i < SEAT_NUMBER; i++) { flights[j].seats[i].seat_id = i + 1; flights[j].seats[i].is_ordered = false; flights[j].seats[i].is_confirmed = true; flights[j].seats[i].firstname[0] = '\0'; flights[j].seats[i].lastname[0] = '\0'; } } while (true) { puts("To choose a flight, enter its label:"); puts("0) 102"); puts("1) 311"); puts("2) 444"); puts("3) 519"); puts("4) Quit"); putchar('\n'); struct flight_s *flight; int temp; scanf("%d", &temp); if (temp == 4) break; flight = &(flights[temp]); struct flight_s flight_buffer; memcpy(&flight_buffer, flight, sizeof flight_buffer); gets(buffer); while (true) { printf("%d flight\n", flight->flight_id); puts("To choose a function, enter its letter label:"); puts("a) Show number of empty seats"); puts("b) Show list of empty"); puts("c) Show alphabetical list of seats"); puts("d) Assign a customer to a seat assignment"); puts("e) Delete a seat assignment"); puts("f) Confirm"); puts("g) Quit"); putchar('\n'); char choice = tolower(getchar()); gets(buffer); if (choice == 'g') break; if (choice == 'a') { int count = 0; for (int i = 0; i < SEAT_NUMBER; i++) if (!flight->seats[i].is_ordered) count++; printf("The number of empty seats is %d.\n", count); } else if (choice == 'b') { printf("The list of empty seats:\n"); for (int i = 0; i < SEAT_NUMBER; i++) if (!flight->seats[i].is_ordered) printf("%d ", flight->seats[i].seat_id); } else if (choice == 'c') { struct seat_s temp[SEAT_NUMBER]; memcpy(temp, flight->seats, sizeof temp); qsort(temp, SEAT_NUMBER, sizeof *temp, compare_two_seats_by_name); for (int i = 0; i < SEAT_NUMBER; i++) printf("%02d(%c): %s %s\t is confirmed: %s", temp[i].seat_id, temp[i].is_ordered ? 'x' : 'o', temp[i].firstname, temp[i].lastname, temp[i].is_confirmed ? "Yes" : "No"); } else if (choice == 'd') { printf("Please enter the seat id and the customer's name: "); scanf("%d %s %s", &seat_id, firstname, lastname); int status = 0; for (int i = 0; i < SEAT_NUMBER; i++) if (flight_buffer.seats[i].seat_id == seat_id) { if (flight_buffer.seats[i].is_ordered) status = 1; else { status = 2; flight_buffer.seats[i].is_ordered = true; strcpy(flight_buffer.seats[i].firstname, firstname); strcpy(flight_buffer.seats[i].lastname, lastname); flight_buffer.seats[i].is_confirmed = false; } break; } if (status == 0) puts("No such seat id!"); else if (status == 1) puts("Selected seat ordered!"); else if (status == 2) puts("Seat successfully assigned."); } else if (choice == 'e') { printf("Please enter the seat id of assignment to be deleted: "); scanf("%d", &seat_id); bool found = false; for (int i = 0; i < SEAT_NUMBER; i++) if (flight_buffer.seats[i].seat_id == seat_id) { flight_buffer.seats[i].is_ordered = false; flight_buffer.seats[i].firstname[0] = '\0'; flight_buffer.seats[i].lastname[0] = '\0'; found = true; break; } if (found) puts("Assignment found and deleted."); else puts("Sorry, assignment not found!"); } else if (choice == 'f') { memcpy(flight, &flight_buffer, sizeof flight_buffer); printf("Successfully confirmed!"); } else puts("Invalid choice!"); putchar('\n'); } } puts("Done!"); return 0; } int compare_two_seats_by_name(const void *a, const void *b) { struct seat_s *pa = (struct seat_s *)a, *pb = (struct seat_s*)b; int cmp_firstname = strcmp(pa->firstname, pb->firstname), cmp_lastname = strcmp(pa->lastname, pb->lastname); return cmp_firstname != 0 ? cmp_firstname : cmp_lastname; }
38.675862
188
0.498039
e7944ea573f304e6341ea8d976c6293332667793
1,107
h
C
include/quipper/huge_page_deducer.h
jackanth/quipper
c7d0fb8582757e344a18f1870503b4ad1b51d318
[ "BSD-3-Clause" ]
1
2018-06-13T08:53:36.000Z
2018-06-13T08:53:36.000Z
include/quipper/huge_page_deducer.h
jackanth/quipper
c7d0fb8582757e344a18f1870503b4ad1b51d318
[ "BSD-3-Clause" ]
null
null
null
include/quipper/huge_page_deducer.h
jackanth/quipper
c7d0fb8582757e344a18f1870503b4ad1b51d318
[ "BSD-3-Clause" ]
null
null
null
#ifndef PERF_DATA_CONVERTER_SRC_QUIPPER_HUGE_PAGE_DEDUCER_H_ #define PERF_DATA_CONVERTER_SRC_QUIPPER_HUGE_PAGE_DEDUCER_H_ #include "quipper/compat/proto.h" namespace quipper { // Walks through all the perf events in |*events| and deduces correct |pgoff| // and |filename| values for MMAP events. // // This may not correctly handle perf data that has been processed to remove // MMAPs that contain no sample events, since one or more of the mappings // necessary to resolve the huge pages mapping could have been discarded. The // result would be that the huge pages mapping would remain as "//anon" and the // other mappings would remain unchanged. void DeduceHugePages(RepeatedPtrField<PerfDataProto::PerfEvent>* events); // Walks through all the perf events in |*events| and searches for split // mappings. Combines these split mappings into one and replaces the split // mapping events. Modifies the events vector stored in |*events|. void CombineMappings(RepeatedPtrField<PerfDataProto::PerfEvent>* events); } // namespace quipper #endif // PERF_DATA_CONVERTER_SRC_QUIPPER_HUGE_PAGE_DEDUCER_H_
42.576923
79
0.796748
3140259d52f0ee8592addeabb5858bff9772f970
11,114
h
C
3rdparty/mshadow/mshadow/tensor_gpu-inl.h
pioy/incubator-mxnet
9d432079f489327ec6daab61326a3e4f3c7cb8b3
[ "Apache-2.0" ]
211
2016-06-06T08:32:36.000Z
2021-07-03T16:50:16.000Z
3rdparty/mshadow/mshadow/tensor_gpu-inl.h
pioy/incubator-mxnet
9d432079f489327ec6daab61326a3e4f3c7cb8b3
[ "Apache-2.0" ]
42
2017-01-05T02:45:13.000Z
2020-08-11T23:45:27.000Z
3rdparty/mshadow/mshadow/tensor_gpu-inl.h
pioy/incubator-mxnet
9d432079f489327ec6daab61326a3e4f3c7cb8b3
[ "Apache-2.0" ]
58
2016-10-27T07:37:08.000Z
2021-07-03T16:50:17.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ /*! * Copyright (c) 2014 by Contributors * \file tensor_gpu-inl.h * \brief implementation of GPU host code * \author Bing Xu, Tianqi Chen */ #ifndef MSHADOW_TENSOR_GPU_INL_H_ #define MSHADOW_TENSOR_GPU_INL_H_ #include "./base.h" #include "./tensor.h" namespace mshadow { #if MSHADOW_USE_CUDA template<> inline void InitTensorEngine<gpu>(int dev_id) { cudaDeviceProp prop; int device_id = 0; int device_count = 0; cudaGetDeviceCount(&device_count); CHECK_GT(device_count, 0) << "Cannot find CUDA device. Please check CUDA-Configuration"; if (dev_id < 0) { device_id = 0; } else { device_id = dev_id; } CHECK_LT(device_id, device_count) << "Incorrect Device ID"; MSHADOW_CUDA_CALL(cudaSetDevice(device_id)); MSHADOW_CUDA_CALL(cudaGetDeviceProperties(&prop, device_id)); } template<> inline void ShutdownTensorEngine<gpu>(void) { } template<> inline void SetDevice<gpu>(int devid) { MSHADOW_CUDA_CALL(cudaSetDevice(devid)); } template<int dim, typename DType> inline void AllocSpace(Tensor<gpu, dim, DType> *obj, bool pad) { size_t pitch; // common choice for cuda mem align unit is 32 if (pad && obj->size(dim - 1) >= MSHADOW_MIN_PAD_RATIO * 32) { MSHADOW_CUDA_CALL(cudaMallocPitch(reinterpret_cast<void**>(&(obj->dptr_)), &pitch, obj->size(dim - 1) * sizeof(DType), obj->shape_.FlatTo2D()[0])); obj->stride_ = static_cast<index_t>(pitch / sizeof(DType)); } else { obj->stride_ = obj->size(dim - 1); MSHADOW_CUDA_CALL(cudaMallocPitch(reinterpret_cast<void**>(&(obj->dptr_)), &pitch, obj->shape_.Size() * sizeof(DType), 1)); } } template<int dim, typename DType> inline void FreeSpace(Tensor<gpu, dim, DType> *obj) { MSHADOW_CUDA_CALL(cudaFree(obj->dptr_)); obj->dptr_ = NULL; } template<typename A, typename B, int dim, typename DType> inline void Copy(Tensor<A, dim, DType> _dst, Tensor<B, dim, DType> _src, cudaMemcpyKind kind, Stream<gpu> *stream) { CHECK_EQ(_dst.shape_, _src.shape_) << "Copy:shape mismatch"; Tensor<A, 2, DType> dst = _dst.FlatTo2D(); Tensor<B, 2, DType> src = _src.FlatTo2D(); MSHADOW_CUDA_CALL(cudaMemcpy2DAsync(dst.dptr_, dst.stride_ * sizeof(DType), src.dptr_, src.stride_ * sizeof(DType), dst.size(1) * sizeof(DType), dst.size(0), kind, Stream<gpu>::GetStream(stream))); // use synchronize call behavior for zero stream if (stream == NULL) { MSHADOW_CUDA_CALL(cudaStreamSynchronize(0)); } } template<int dim, typename DType> inline void Copy(Tensor<cpu, dim, DType> dst, const Tensor<gpu, dim, DType> &src, Stream<gpu> *stream) { Copy(dst, src, cudaMemcpyDeviceToHost, stream); } template<int dim, typename DType> inline void Copy(Tensor<gpu, dim, DType> dst, const Tensor<gpu, dim, DType> &src, Stream<gpu> *stream) { Copy(dst, src, cudaMemcpyDeviceToDevice, stream); } template<int dim, typename DType> inline void Copy(Tensor<gpu, dim, DType> dst, const Tensor<cpu, dim, DType> &src, Stream<gpu> *stream) { Copy(dst, src, cudaMemcpyHostToDevice, stream); } #endif // MSHADOW_USE_CUDA } // namespace mshadow // the following part is included only if compiler is nvcc #ifdef __CUDACC__ #include "./cuda/tensor_gpu-inl.cuh" namespace mshadow { template<typename Saver, typename R, int dim, typename DType, typename E, int etype> inline void MapExp(TRValue<R, gpu, dim, DType> *dst, const expr::Exp<E, DType, etype> &exp) { expr::TypeCheckPass<expr::TypeCheck<gpu, dim, DType, E>::kMapPass> ::Error_All_Tensor_in_Exp_Must_Have_Same_Type(); Shape<dim> eshape = expr::ShapeCheck<dim, E>::Check(exp.self()); Shape<dim> dshape = expr::ShapeCheck<dim, R>::Check(dst->self()); CHECK(eshape[0] == 0 || eshape == dshape) << "Assignment: Shape of Tensors are not consistent with target, " << "eshape: " << eshape << " dshape:" << dshape; cuda::MapPlan<Saver>(MakePlan(dst->self()), MakePlan(exp.self()), dshape.FlatTo2D(), Stream<gpu>::GetStream(expr::StreamInfo<gpu, R>::Get(dst->self()))); } template<typename Saver, typename Reducer, typename R, typename DType, typename E, int etype> inline void MapReduceKeepLowest(TRValue<R, gpu, 1, DType> *dst, const expr::Exp<E, DType, etype> &exp, DType scale) { expr::TypeCheckPass<expr::TypeCheck<gpu, 1, DType, E>::kRedPass> ::Error_TypeCheck_Not_Pass_For_Reduce_Exp(); Shape<2> eshape = expr::ShapeCheck<expr::ExpInfo<E>::kDim, E> ::Check(exp.self()).FlatTo2D(); Shape<1> dshape = expr::ShapeCheck<1, R>::Check(dst->self()); CHECK_EQ(eshape[1], dshape[0]) << "MapReduceKeepLowest::reduction dimension do not match"; CHECK_NE(eshape[0], 0U) << "can not reduce over empty tensor"; cuda::MapReduceKeepLowest<Saver, Reducer> (MakePlan(dst->self()), MakePlan(exp.self()), scale, eshape, Stream<gpu>::GetStream(expr::StreamInfo<gpu, R>::Get(dst->self()))); } template<typename Saver, typename Reducer, int dimkeep, typename R, typename DType, typename E, int etype> inline void MapReduceKeepHighDim(TRValue<R, gpu, 1, DType> *dst, const expr::Exp<E, DType, etype> &exp, DType scale) { expr::TypeCheckPass<expr::TypeCheck<gpu, dimkeep, DType, E>::kRedPass> ::Error_TypeCheck_Not_Pass_For_Reduce_Exp(); typedef Shape<expr::ExpInfo<E>::kDim> EShape; EShape eshape = expr::ShapeCheck<expr::ExpInfo<E>::kDim, E> ::Check(exp.self()); Shape<1> dshape = expr::ShapeCheck<1, R>::Check(dst->self()); CHECK_EQ(eshape[dimkeep], dshape[0]) << "MapReduceKeepHighDim::reduction dimension do not match"; // use equvalent form Shape<4> pshape = Shape4(eshape.ProdShape(0, dimkeep), eshape[dimkeep], eshape.ProdShape(dimkeep + 1, EShape::kSubdim), eshape[EShape::kSubdim]); // call equavalent map red dim 2 cuda::MapReduceKeepDim1<Saver, Reducer> (MakePlan(dst->self()), MakePlan(exp.self()), scale, pshape, Stream<gpu>::GetStream(expr::StreamInfo<gpu, R>::Get(dst->self()))); } template<typename DType> inline void Softmax(Tensor<gpu, 2, DType> dst, const Tensor<gpu, 2, DType>& src) { cuda::Softmax(dst, src); } template<typename DType> inline void Softmax(Tensor<gpu, 3, DType> dst, const Tensor<gpu, 3, DType>& src) { cuda::Softmax(dst, src); } template<typename DType> inline void SoftmaxGrad(const Tensor<gpu, 2, DType> &dst, const Tensor<gpu, 2, DType> &src, const Tensor<gpu, 1, DType> &label) { cuda::SoftmaxGrad(dst, src, label); } template<typename DType> inline void SmoothSoftmaxGrad(const Tensor<gpu, 2, DType> &dst, const Tensor<gpu, 2, DType> &src, const Tensor<gpu, 1, DType> &label, const float alpha) { cuda::SmoothSoftmaxGrad(dst, src, label, alpha); } template<typename DType> inline void SoftmaxGrad(const Tensor<gpu, 2, DType> &dst, const Tensor<gpu, 2, DType> &src, const Tensor<gpu, 1, DType> &label, const DType &ignore_label) { cuda::SoftmaxGrad(dst, src, label, ignore_label); } template<typename DType> inline void SmoothSoftmaxGrad(const Tensor<gpu, 2, DType> &dst, const Tensor<gpu, 2, DType> &src, const Tensor<gpu, 1, DType> &label, const DType &ignore_label, const float alpha) { cuda::SmoothSoftmaxGrad(dst, src, label, ignore_label, alpha); } template<typename DType> inline void SoftmaxGrad(const Tensor<gpu, 3, DType> &dst, const Tensor<gpu, 3, DType> &src, const Tensor<gpu, 2, DType> &label) { cuda::SoftmaxGrad(dst, src, label); } template<typename DType> inline void SoftmaxGrad(const Tensor<gpu, 3, DType> &dst, const Tensor<gpu, 3, DType> &src, const Tensor<gpu, 2, DType> &label, const DType &ignore_label) { cuda::SoftmaxGrad(dst, src, label, ignore_label); } template<bool clip, typename IndexType, typename DType> inline void AddTakeGrad(Tensor<gpu, 2, DType> dst, const Tensor<gpu, 1, IndexType>& index, const Tensor<gpu, 2, DType> &src) { cuda::AddTakeGrad<clip, IndexType, DType>(dst, index, src); } template<bool clip, typename IndexType, typename DType, typename AType> inline void AddTakeGrad(Tensor<gpu, 2, DType> dst, Tensor<gpu, 2, AType> temp, const Tensor<gpu, 1, IndexType>& index, const Tensor<gpu, 2, DType> &src) { cuda::AddTakeGrad<clip, IndexType, DType>(dst, temp, index, src); } template<typename IndexType, typename DType> inline void AddTakeGradLargeBatch(Tensor<gpu, 2, DType> dst, const Tensor<gpu, 1, IndexType>& sorted, const Tensor<gpu, 1, IndexType>& index, const Tensor<gpu, 2, DType> &src) { cuda::AddTakeGradLargeBatch(dst, sorted, index, src); } template<typename KDType, typename VDType> inline void SortByKey(Tensor<gpu, 1, KDType> keys, Tensor<gpu, 1, VDType> values, bool is_ascend) { cuda::SortByKey(keys, values, is_ascend); } template<typename IndexType, typename DType> inline void IndexFill(Tensor<gpu, 2, DType> dst, const Tensor<gpu, 1, IndexType>& index, const Tensor<gpu, 2, DType> &src) { cuda::IndexFill(dst, index, src); } } // namespace mshadow #endif // __CUDACC__ #endif // MSHADOW_TENSOR_GPU_INL_H_
40.710623
99
0.618229
2e8a42ccf176e5fd92402184a2e6ec44b70a3129
3,293
h
C
android/app/src/cpp/src/backend/opencl/cl/rx/randomx_constants_arqma.h
FlameSalamander/react-native-xmrig
6a6e3b301bd78b88459989f334d759f65e434082
[ "MIT" ]
28
2021-05-11T03:28:57.000Z
2022-03-09T14:34:57.000Z
android/app/src/cpp/src/backend/opencl/cl/rx/randomx_constants_arqma.h
FlameSalamander/react-native-xmrig
6a6e3b301bd78b88459989f334d759f65e434082
[ "MIT" ]
10
2021-05-16T19:50:31.000Z
2022-01-30T03:56:45.000Z
android/app/src/cpp/src/backend/opencl/cl/rx/randomx_constants_arqma.h
FlameSalamander/react-native-xmrig
6a6e3b301bd78b88459989f334d759f65e434082
[ "MIT" ]
12
2021-07-19T22:14:58.000Z
2022-02-08T02:24:05.000Z
/* Copyright (c) 2019 SChernykh This file is part of RandomX OpenCL. RandomX OpenCL is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. RandomX OpenCL 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 RandomX OpenCL. If not, see <http://www.gnu.org/licenses/>. */ //Dataset base size in bytes. Must be a power of 2. #define RANDOMX_DATASET_BASE_SIZE 2147483648 //Dataset extra size. Must be divisible by 64. #define RANDOMX_DATASET_EXTRA_SIZE 33554368 //Scratchpad L3 size in bytes. Must be a power of 2. #define RANDOMX_SCRATCHPAD_L3 262144 //Scratchpad L2 size in bytes. Must be a power of two and less than or equal to RANDOMX_SCRATCHPAD_L3. #define RANDOMX_SCRATCHPAD_L2 131072 //Scratchpad L1 size in bytes. Must be a power of two (minimum 64) and less than or equal to RANDOMX_SCRATCHPAD_L2. #define RANDOMX_SCRATCHPAD_L1 16384 //Jump condition mask size in bits. #define RANDOMX_JUMP_BITS 8 //Jump condition mask offset in bits. The sum of RANDOMX_JUMP_BITS and RANDOMX_JUMP_OFFSET must not exceed 16. #define RANDOMX_JUMP_OFFSET 8 //Integer instructions #define RANDOMX_FREQ_IADD_RS 16 #define RANDOMX_FREQ_IADD_M 7 #define RANDOMX_FREQ_ISUB_R 16 #define RANDOMX_FREQ_ISUB_M 7 #define RANDOMX_FREQ_IMUL_R 16 #define RANDOMX_FREQ_IMUL_M 4 #define RANDOMX_FREQ_IMULH_R 4 #define RANDOMX_FREQ_IMULH_M 1 #define RANDOMX_FREQ_ISMULH_R 4 #define RANDOMX_FREQ_ISMULH_M 1 #define RANDOMX_FREQ_IMUL_RCP 8 #define RANDOMX_FREQ_INEG_R 2 #define RANDOMX_FREQ_IXOR_R 15 #define RANDOMX_FREQ_IXOR_M 5 #define RANDOMX_FREQ_IROR_R 8 #define RANDOMX_FREQ_IROL_R 2 #define RANDOMX_FREQ_ISWAP_R 4 //Floating point instructions #define RANDOMX_FREQ_FSWAP_R 4 #define RANDOMX_FREQ_FADD_R 16 #define RANDOMX_FREQ_FADD_M 5 #define RANDOMX_FREQ_FSUB_R 16 #define RANDOMX_FREQ_FSUB_M 5 #define RANDOMX_FREQ_FSCAL_R 6 #define RANDOMX_FREQ_FMUL_R 32 #define RANDOMX_FREQ_FDIV_M 4 #define RANDOMX_FREQ_FSQRT_R 6 //Control instructions #define RANDOMX_FREQ_CBRANCH 25 #define RANDOMX_FREQ_CFROUND 1 //Store instruction #define RANDOMX_FREQ_ISTORE 16 //No-op instruction #define RANDOMX_FREQ_NOP 0 #define RANDOMX_DATASET_ITEM_SIZE 64 #define RANDOMX_PROGRAM_SIZE 256 #define HASH_SIZE 64 #define ENTROPY_SIZE (128 + RANDOMX_PROGRAM_SIZE * 8) #define REGISTERS_SIZE 256 #define IMM_BUF_SIZE (RANDOMX_PROGRAM_SIZE * 4 - REGISTERS_SIZE) #define IMM_INDEX_COUNT ((IMM_BUF_SIZE / 4) - 2) #define VM_STATE_SIZE (REGISTERS_SIZE + IMM_BUF_SIZE + RANDOMX_PROGRAM_SIZE * 4) #define ROUNDING_MODE (RANDOMX_FREQ_CFROUND ? -1 : 0) // Scratchpad L1/L2/L3 bits #define LOC_L1 (32 - 14) #define LOC_L2 (32 - 17) #define LOC_L3 (32 - 18)
33.948454
115
0.751291
bdf1d9540f03681b829639c02a694c414ee7f552
982
h
C
vital/applets/applet_config.h
Purg/kwiver-v2-exp
bc811128853517e5e3679c9bcbb8905fdb0c0baa
[ "BSD-3-Clause" ]
null
null
null
vital/applets/applet_config.h
Purg/kwiver-v2-exp
bc811128853517e5e3679c9bcbb8905fdb0c0baa
[ "BSD-3-Clause" ]
null
null
null
vital/applets/applet_config.h
Purg/kwiver-v2-exp
bc811128853517e5e3679c9bcbb8905fdb0c0baa
[ "BSD-3-Clause" ]
null
null
null
// This file is part of KWIVER, and is distributed under the // OSI-approved BSD 3-Clause License. See top-level LICENSE file or // https://github.com/Kitware/kwiver/blob/master/LICENSE for details. #ifndef KWIVER_TOOLS_APPLET_CONFIG_H #define KWIVER_TOOLS_APPLET_CONFIG_H #include <kwiversys/SystemTools.hxx> #include <vital/applets/kwiver_applet.h> #include <vital/config/config_block.h> namespace kwiver { namespace tools { /// Load and merge the appropriate default video configuration based on filename /// TODO: This needs a better location... inline kwiver::vital::config_block_sptr load_default_video_input_config(std::string const& video_file_name) { typedef kwiversys::SystemTools ST; typedef kwiver::tools::kwiver_applet kvt; if (ST::GetFilenameLastExtension(video_file_name) == ".txt") { return kvt::find_configuration("core_image_list_video_input.conf"); } return kvt::find_configuration("ffmpeg_video_input.conf"); } } } // end namespace #endif
29.757576
80
0.778004
ecc38cd5962db3f815403e213e57249f727d25f5
4,662
h
C
opal/mca/shmem/base/base.h
abouteiller/ompi-aurelien
3fedbf777c4864c9c4f864228d787b27fadf0f74
[ "BSD-3-Clause-Open-MPI" ]
1,585
2015-01-03T04:10:59.000Z
2022-03-31T19:48:54.000Z
opal/mca/shmem/base/base.h
abouteiller/ompi-aurelien
3fedbf777c4864c9c4f864228d787b27fadf0f74
[ "BSD-3-Clause-Open-MPI" ]
7,655
2015-01-04T14:42:56.000Z
2022-03-31T22:51:57.000Z
opal/mca/shmem/base/base.h
abouteiller/ompi-aurelien
3fedbf777c4864c9c4f864228d787b27fadf0f74
[ "BSD-3-Clause-Open-MPI" ]
846
2015-01-20T15:01:44.000Z
2022-03-27T13:06:07.000Z
/* * Copyright (c) 2004-2005 The Trustees of Indiana University and Indiana * University Research and Technology * Corporation. All rights reserved. * Copyright (c) 2004-2006 The University of Tennessee and The University * of Tennessee Research Foundation. All rights * reserved. * Copyright (c) 2004-2005 High Performance Computing Center Stuttgart, * University of Stuttgart. All rights reserved. * Copyright (c) 2004-2005 The Regents of the University of California. * All rights reserved. * Copyright (c) 2007-2015 Cisco Systems, Inc. All rights reserved. * Copyright (c) 2010-2011 Los Alamos National Security, LLC. * All rights reserved. * $COPYRIGHT$ * * Additional copyrights may follow * * $HEADER$ */ #ifndef OPAL_SHMEM_BASE_H #define OPAL_SHMEM_BASE_H #include "opal_config.h" #include "opal/mca/base/mca_base_framework.h" #include "opal/mca/shmem/shmem.h" BEGIN_C_DECLS /* ////////////////////////////////////////////////////////////////////////// */ /* Public API for the shmem framework */ /* ////////////////////////////////////////////////////////////////////////// */ OPAL_DECLSPEC int opal_shmem_segment_create(opal_shmem_ds_t *ds_buf, const char *file_name, size_t size); OPAL_DECLSPEC int opal_shmem_ds_copy(const opal_shmem_ds_t *from, opal_shmem_ds_t *to); OPAL_DECLSPEC void *opal_shmem_segment_attach(opal_shmem_ds_t *ds_buf); OPAL_DECLSPEC int opal_shmem_segment_detach(opal_shmem_ds_t *ds_buf); OPAL_DECLSPEC int opal_shmem_unlink(opal_shmem_ds_t *ds_buf); /* ////////////////////////////////////////////////////////////////////////// */ /* End Public API for the shmem framework */ /* ////////////////////////////////////////////////////////////////////////// */ /* * Global functions for MCA overall shmem open and close */ /** * returns the name of the best, runnable shmem component. the caller is * responsible for freeing returned resources. * * @retval name of best component. NULL if no component is found. * * see: 3rd-party/prrte/src/mca/odls/base/odls_base_default_fns.c */ OPAL_DECLSPEC char *opal_shmem_base_best_runnable_component_name(void); /** * Select an available component. * * @return OPAL_SUCCESS Upon success. * @return OPAL_NOT_FOUND If no component can be selected. * @return OPAL_ERROR Upon other failure. * * This function invokes the selection process for shmem components, * which works as follows: * * - If the \em shmem MCA parameter is not specified, the * selection set is all available shmem components. * - If the \em shmem MCA parameter is specified, the * selection set is just that component. * - All components in the selection set are queried to see if * they want to run. All components that want to run are ranked * by their priority and the highest priority component is * selected. All non-selected components have their "close" * function invoked to let them know that they were not selected. * - The selected component will have its "init" function invoked to * let it know that it was selected. * * If we fall through this entire process and no component is * selected, then return OPAL_NOT_FOUND (this is not a fatal * error). * * At the end of this process, we'll either have a single * component that is selected and initialized, or no component was * selected. If no component was selected, subsequent invocation * of the shmem wrapper functions will return an error. */ OPAL_DECLSPEC int opal_shmem_base_select(void); /** * Shut down the shmem MCA framework. * * @retval OPAL_SUCCESS Always * * This function shuts down everything in the shmem MCA * framework, and is called during opal_finalize(). * * It must be the last function invoked on the shmem MCA * framework. */ OPAL_DECLSPEC int opal_shmem_base_close(void); /** * Indication of whether a component was successfully selected or * not */ OPAL_DECLSPEC extern bool opal_shmem_base_selected; /** * Global component struct for the selected component */ OPAL_DECLSPEC extern opal_shmem_base_component_t *opal_shmem_base_component; /** * Global module struct for the selected module */ OPAL_DECLSPEC extern opal_shmem_base_module_t *opal_shmem_base_module; /** * Runtime hint */ OPAL_DECLSPEC extern char *opal_shmem_base_RUNTIME_QUERY_hint; /** * Framework structure declaration */ OPAL_DECLSPEC extern mca_base_framework_t opal_shmem_base_framework; END_C_DECLS #endif /* OPAL_BASE_SHMEM_H */
34.029197
91
0.675032
aeb9eb9cbe01653fe914cd300a13f8c82372dff6
290
h
C
JDDetail/SearchViewController/JDDataModel.h
Jiaguanglei0418/iOS-UIDemo
08f38bb229071f3a1bfaca7876b85177e0fa9c4a
[ "MIT" ]
null
null
null
JDDetail/SearchViewController/JDDataModel.h
Jiaguanglei0418/iOS-UIDemo
08f38bb229071f3a1bfaca7876b85177e0fa9c4a
[ "MIT" ]
null
null
null
JDDetail/SearchViewController/JDDataModel.h
Jiaguanglei0418/iOS-UIDemo
08f38bb229071f3a1bfaca7876b85177e0fa9c4a
[ "MIT" ]
null
null
null
// // JDDataModel.h // JDDetail // // Created by Guangleijia on 2018/7/24. // Copyright © 2018年 Reboot. All rights reserved. // #import <Foundation/Foundation.h> @interface JDDataModel : NSObject @property(nonatomic, strong) NSArray *dataArr; + (instancetype)sharedDataModel; @end
16.111111
50
0.717241
6487428411608b09835630de590a51d5816ae67e
15,980
c
C
test_suite/trie_array/TestTrieArray.c
noizu/trie_gen
f414696f67ca7a7f762f5f8d6647825ef7ba6708
[ "MIT" ]
null
null
null
test_suite/trie_array/TestTrieArray.c
noizu/trie_gen
f414696f67ca7a7f762f5f8d6647825ef7ba6708
[ "MIT" ]
null
null
null
test_suite/trie_array/TestTrieArray.c
noizu/trie_gen
f414696f67ca7a7f762f5f8d6647825ef7ba6708
[ "MIT" ]
null
null
null
#include "unity.h" #include "unity_fixture.h" #include "support/trie_test_fixture.h" TEST_GROUP(TrieArray); TRIE_TOKEN array_test_sentinel(TRIE_TOKEN advance_flag, struct noizu_trie_state* state, struct noizu_trie_definition* definition) { struct noizu_trie__array__definition* a_trie = (struct noizu_trie__array__definition*)definition->type_definition; TRIE_TOKEN t = a_trie->trie[state->position][TRIE_A_TOKEN]; if (t == ARRAY_JK_CONTENTS) { state->token = t; state->token_index = state->position; state->match_type = TRIE_MATCH; return ARRAY_SENTINEL_HALT_ON_CONTENTS; } if (t == ARRAY_JV_DEGREES_CELSIUS) { state->initialized = FALSE; state->position = 1; } return 0; } TEST_SETUP(TrieArray) { } TEST_TEAR_DOWN(TrieArray) { } TEST(TrieArray, UnitTest_ParseToDelim_KL1_EB0) { struct noizu_trie_options options = { 0, .delimiter = '+', .keep_last_token = 1 }; offset_buffer* req = calloc(1, sizeof(offset_buffer)); req->buffer = calloc(256, sizeof(uint8_t)); req->buffer_size = sprintf_s(req->buffer, 256, "degrees_celsius+++"); struct noizu_trie_state state = { 0 }; noizu_trie__init(req, &array_test_trie, options, &state); TRIE_TOKEN o = noizu_trie__tokenize(&state, &array_test_trie, NULL); TEST_ASSERT_TOKENIZER_STATE(o, &state, TRIE_DELIM_EXIT, TRIE_MATCH, ARRAY_JV_DEGREES_CELSIUS, 0, 0, '+'); } TEST(TrieArray, UnitTest_ParseToDelim_KL0_EB1) { struct noizu_trie_options options = { 0, .delimiter = '+', .end_of_buffer_token = 1 }; offset_buffer* req = calloc(1, sizeof(offset_buffer)); req->buffer = calloc(256, sizeof(uint8_t)); req->buffer_size = sprintf_s(req->buffer, 256, "degrees_celsius+++"); struct noizu_trie_state state = { 0 }; noizu_trie__init(req, &array_test_trie, options, &state); TRIE_TOKEN o = noizu_trie__tokenize(&state, &array_test_trie, NULL); TEST_ASSERT_TOKENIZER_STATE(o, &state, TRIE_DELIM_EXIT, TRIE_MATCH, ARRAY_JV_DEGREES_CELSIUS, 0, 0, '+'); } TEST(TrieArray, UnitTest_ParseToDelim_KL0_EB0) { struct noizu_trie_options options = { 0, .delimiter = '+' }; offset_buffer* req = calloc(1, sizeof(offset_buffer)); req->buffer = calloc(256, sizeof(uint8_t)); req->buffer_size = sprintf_s(req->buffer, 256, "degrees_celsius+++"); struct noizu_trie_state state = { 0 }; noizu_trie__init(req, &array_test_trie, options, &state); TRIE_TOKEN o = noizu_trie__tokenize(&state, &array_test_trie, NULL); TEST_ASSERT_TOKENIZER_STATE(o, &state, TRIE_DELIM_EXIT, TRIE_MATCH, ARRAY_JV_DEGREES_CELSIUS, 0, 0, '+'); } TEST(TrieArray, UnitTest_ParseToDelim_KL1_EB1) { struct noizu_trie_options options = { 0, .delimiter = '+', .keep_last_token = 1, .end_of_buffer_token = 1 }; offset_buffer* req = calloc(1, sizeof(offset_buffer)); req->buffer = calloc(256, sizeof(uint8_t)); req->buffer_size = sprintf_s(req->buffer, 256, "degrees_celsius+++"); struct noizu_trie_state state = { 0 }; noizu_trie__init(req, &array_test_trie, options, &state); TRIE_TOKEN o = noizu_trie__tokenize(&state, &array_test_trie, NULL); TEST_ASSERT_TOKENIZER_STATE(o, &state, TRIE_DELIM_EXIT, TRIE_MATCH, ARRAY_JV_DEGREES_CELSIUS, 0, 0, '+'); } TEST(TrieArray, UnitTest_ParseToEnd_KL1_EB0) { struct noizu_trie_options options = { 0, .delimiter = '+', .keep_last_token = 1 }; offset_buffer* req = calloc(1, sizeof(offset_buffer)); req->buffer = calloc(256, sizeof(uint8_t)); req->buffer_size = sprintf_s(req->buffer, 256, "degrees_celsius") + 10; struct noizu_trie_state state = { 0 }; noizu_trie__init(req, &array_test_trie, options, &state); TRIE_TOKEN o = noizu_trie__tokenize(&state, &array_test_trie, NULL); TEST_ASSERT_TOKENIZER_STATE(o, &state, TRIE_END_INPUT_EXIT, TRIE_MATCH, ARRAY_JV_DEGREES_CELSIUS, 0, 0, '\0'); } TEST(TrieArray, UnitTest_ParseToEnd_KL0_EB1) { struct noizu_trie_options options = { 0, .delimiter = '+', .end_of_buffer_token = 1 }; offset_buffer* req = calloc(1, sizeof(offset_buffer)); req->buffer = calloc(256, sizeof(uint8_t)); req->buffer_size = sprintf_s(req->buffer, 256, "degrees_celsius") + 10; struct noizu_trie_state state = { 0 }; noizu_trie__init(req, &array_test_trie, options, &state); TRIE_TOKEN o = noizu_trie__tokenize(&state, &array_test_trie, NULL); TEST_ASSERT_TOKENIZER_STATE(o, &state, TRIE_END_INPUT_EXIT, TRIE_MATCH, ARRAY_JV_DEGREES_CELSIUS, 0, 0, '\0'); } TEST(TrieArray, UnitTest_ParseToEnd_KL0_EB0) { struct noizu_trie_options options = { 0, .delimiter = '+' }; offset_buffer* req = calloc(1, sizeof(offset_buffer)); req->buffer = calloc(256, sizeof(uint8_t)); req->buffer_size = sprintf_s(req->buffer, 256, "degrees_celsius") + 10; struct noizu_trie_state state = { 0 }; noizu_trie__init(req, &array_test_trie, options, &state); TRIE_TOKEN o = noizu_trie__tokenize(&state, &array_test_trie, NULL); TEST_ASSERT_TOKENIZER_STATE(o, &state, TRIE_END_INPUT_EXIT, TRIE_MATCH, ARRAY_JV_DEGREES_CELSIUS, 0, 0, '\0'); } TEST(TrieArray, UnitTest_ParseToEnd_KL1_EB1) { struct noizu_trie_options options = { 0, .delimiter = '+', .keep_last_token = 1, .end_of_buffer_token = 1, }; offset_buffer* req = calloc(1, sizeof(offset_buffer)); req->buffer = calloc(256, sizeof(uint8_t)); req->buffer_size = sprintf_s(req->buffer, 256, "degrees_celsius") + 10; struct noizu_trie_state state = { 0 }; noizu_trie__init(req, &array_test_trie, options, &state); TRIE_TOKEN o = noizu_trie__tokenize(&state, &array_test_trie, NULL); TEST_ASSERT_TOKENIZER_STATE(o, &state, TRIE_END_INPUT_EXIT, TRIE_MATCH, ARRAY_JV_DEGREES_CELSIUS, 0, 0, '\0'); } TEST(TrieArray, UnitTest_Partial_KL1_EB0) { struct noizu_trie_options options = { 0, .delimiter = '+', .keep_last_token = 1 }; offset_buffer* req = calloc(1, sizeof(offset_buffer)); req->buffer = calloc(256, sizeof(uint8_t)); req->buffer_size = sprintf_s(req->buffer, 256, "degrees_celsiusc_degreg+++"); struct noizu_trie_state state = { 0 }; noizu_trie__init(req, &array_test_trie, options, &state); TRIE_TOKEN o = noizu_trie__tokenize(&state, &array_test_trie, NULL); TEST_ASSERT_TOKENIZER_STATE(o, &state, TRIE_END_PARSE_EXIT, TRIE_PARTIAL_MATCH, ARRAY_JV_DEGREES_CELSIUS, 0, 0, 'c'); } TEST(TrieArray, UnitTest_Partial_KL0_EB0) { struct noizu_trie_options options = { 0, .delimiter = '+' }; offset_buffer* req = calloc(1, sizeof(offset_buffer)); req->buffer = calloc(256, sizeof(uint8_t)); req->buffer_size = sprintf_s(req->buffer, 256, "degrees_celsiusc_degreg+++"); struct noizu_trie_state state = { 0 }; noizu_trie__init(req, &array_test_trie, options, &state); TRIE_TOKEN o = noizu_trie__tokenize(&state, &array_test_trie, NULL); TEST_ASSERT_TOKENIZER_STATE(o, &state, TRIE_END_PARSE_EXIT, TRIE_LAST_MATCH, ARRAY_JV_DEGREES_CELSIUS, 0, 0, 'c'); } TEST(TrieArray, UnitTest_BuffEnd_KL0_EB1) { struct noizu_trie_options options = { 0, .delimiter = '+', .end_of_buffer_token = 1 }; offset_buffer* req = calloc(1, sizeof(offset_buffer)); req->buffer = calloc(256, sizeof(uint8_t)); sprintf_s(req->buffer, 256, "beforefor+++degrees_celsius_degreg+++"); req->buffer_pos = 12; req->buffer_size = 27; struct noizu_trie_state state = { 0 }; noizu_trie__init(req, &array_test_trie, options, &state); TRIE_TOKEN o = noizu_trie__tokenize(&state, &array_test_trie, NULL); TEST_ASSERT_TOKENIZER_STATE(o, &state, TRIE_BUFFER_END, TRIE_LAST_MATCH, ARRAY_JV_DEGREES_CELSIUS, 0, 1, '\0'); } TEST(TrieArray, UnitTest_BuffEnd_KL0_EB0) { struct noizu_trie_options options = { 0, .delimiter = '+' }; offset_buffer* req = calloc(1, sizeof(offset_buffer)); req->buffer = calloc(256, sizeof(uint8_t)); sprintf_s(req->buffer, 256, "beforefor+++degrees_celsius_degreg+++"); req->buffer_pos = 12; req->buffer_size = 27; struct noizu_trie_state state = { 0 }; noizu_trie__init(req, &array_test_trie, options, &state); TRIE_TOKEN o = noizu_trie__tokenize(&state, &array_test_trie, NULL); TEST_ASSERT_TOKENIZER_STATE(o, &state, TRIE_BUFFER_END, TRIE_NO_MATCH, 0, 0, 1, '\0'); } TEST(TrieArray, UnitTest_BuffEarlyEnd_KL0_EB1) { struct noizu_trie_options options = { 0, .delimiter = '+', .end_of_buffer_token = 1 }; offset_buffer* req = calloc(1, sizeof(offset_buffer)); req->buffer = calloc(256, sizeof(uint8_t)); sprintf_s(req->buffer, 256, "beforefor+++degrees_celsius_degreg+++"); req->buffer_pos = 12; req->buffer_size = 20; struct noizu_trie_state state = { 0 }; noizu_trie__init(req, &array_test_trie, options, &state); TRIE_TOKEN o = noizu_trie__tokenize(&state, &array_test_trie, NULL); TEST_ASSERT_TOKENIZER_STATE(o, &state, TRIE_BUFFER_END, TRIE_NO_MATCH, 0, 0, 1, '\0'); } TEST(TrieArray, UnitTest_BuffEarlyEnd_KL0_EB0) { struct noizu_trie_options options = { 0, .delimiter = '+' }; offset_buffer* req = calloc(1, sizeof(offset_buffer)); req->buffer = calloc(256, sizeof(uint8_t)); sprintf_s(req->buffer, 256, "beforefor+++degrees_celsius_degreg+++"); req->buffer_pos = 12; req->buffer_size = 20; struct noizu_trie_state state = { 0 }; noizu_trie__init(req, &array_test_trie, options, &state); TRIE_TOKEN o = noizu_trie__tokenize(&state, &array_test_trie, NULL); TEST_ASSERT_TOKENIZER_STATE(o, &state, TRIE_BUFFER_END, TRIE_NO_MATCH, 0, 0, 1, '\0'); } TEST(TrieArray, UnitTest_Sentinel_On) { struct noizu_trie_options options = { 0, .delimiter = '+', .keep_last_token = 1 }; offset_buffer* req = calloc(1, sizeof(offset_buffer)); req->buffer = calloc(256, sizeof(uint8_t)); req->buffer_size = sprintf_s(req->buffer, 256, "degrees_celsiuscontentsrelative_humiditydegrees_celsius"); req->buffer_pos = 0; struct noizu_trie_state state = { 0 }; noizu_trie__init(req, &array_test_trie, options, &state); TRIE_TOKEN o = noizu_trie__tokenize(&state, &array_test_trie, array_test_sentinel); TEST_ASSERT_TOKENIZER_STATE(o, &state, TRIE_PARTIAL_SENTINEL_EXIT, TRIE_MATCH, ARRAY_JK_CONTENTS, ARRAY_JV_DEGREES_CELSIUS, 0, '\0'); TEST_ASSERT_EQUAL(state.sentinel_exit_code, ARRAY_SENTINEL_HALT_ON_CONTENTS); } TEST(TrieArray, UnitTest_Sentinel_Off) { struct noizu_trie_options options = { 0, .delimiter = '+', .keep_last_token = 1 }; offset_buffer* req = calloc(1, sizeof(offset_buffer)); req->buffer = calloc(256, sizeof(uint8_t)); req->buffer_size = sprintf_s(req->buffer, 256, "degrees_celsiuscontentsrelative_humiditydegrees_celsius"); req->buffer_pos = 0; struct noizu_trie_state state = { 0 }; noizu_trie__init(req, &array_test_trie, options, &state); TRIE_TOKEN o = noizu_trie__tokenize(&state, &array_test_trie, NULL); TEST_ASSERT_TOKENIZER_STATE(o, &state, TRIE_END_PARSE_EXIT, TRIE_PARTIAL_MATCH, ARRAY_JV_DEGREES_CELSIUS, 0, 0, 'c'); TEST_ASSERT_EQUAL(state.sentinel_exit_code, 0); } TEST(TrieArray, UnitTest_RunOn) { struct noizu_trie_options options = { 0, .delimiter = '+', .keep_last_token = 1 }; offset_buffer* req = calloc(1, sizeof(offset_buffer)); req->buffer = calloc(256, sizeof(uint8_t)); req->buffer_size = sprintf_s(req->buffer, 256, "degrees_celsius_contents+relative_humiditydegrees_celsius"); req->buffer_pos = 0; struct noizu_trie_state state = { 0 }; noizu_trie__init(req, &array_test_trie, options, &state); TRIE_TOKEN o = noizu_trie__tokenize(&state, &array_test_trie, NULL); TEST_ASSERT_TOKENIZER_STATE(o, &state, TRIE_DELIM_EXIT, TRIE_MATCH, ARRAY_JV_DEGREES_CELSIUS_CONTENTS, ARRAY_JV_DEGREES_CELSIUS, 0, '+'); } TEST(TrieArray, UnitTest_HardDelim_On) { struct noizu_trie_options options = { 0, .delimiter = '+', .keep_last_token = 1,.hard_delim = 1 }; offset_buffer* req = calloc(1, sizeof(offset_buffer)); req->buffer = calloc(256, sizeof(uint8_t)); req->buffer_size = sprintf_s(req->buffer, 256, "hello+hello+world"); req->buffer_pos = 0; struct noizu_trie_state state = { 0 }; noizu_trie__init(req, &array_test_trie, options, &state); TRIE_TOKEN o = noizu_trie__tokenize(&state, &array_test_trie, NULL); TEST_ASSERT_TOKENIZER_STATE(o, &state, TRIE_DELIM_EXIT, TRIE_MATCH, ARRAY_HELLO, 0, 0, '+'); } TEST(TrieArray, UnitTest_HardDelim_Off) { struct noizu_trie_options options = { 0, .delimiter = '+', .keep_last_token = 1,.hard_delim = 0 }; offset_buffer* req = calloc(1, sizeof(offset_buffer)); req->buffer = calloc(256, sizeof(uint8_t)); req->buffer_size = sprintf_s(req->buffer, 256, "hello+hello+world"); req->buffer_pos = 0; struct noizu_trie_state state = { 0 }; noizu_trie__init(req, &array_test_trie, options, &state); TRIE_TOKEN o = noizu_trie__tokenize(&state, &array_test_trie, NULL); TEST_ASSERT_TOKENIZER_STATE(o, &state, TRIE_DELIM_EXIT, TRIE_MATCH, ARRAY_HELLO_HELLO, ARRAY_HELLO, 0, '+'); } TEST(TrieArray, UnitTest_JsonDelim_KL0) { struct noizu_trie_options options = { 0, .delimiter = '+', .keep_last_token = 0,.hard_delim = 0, .json_delim = 1 }; offset_buffer* req = calloc(1, sizeof(offset_buffer)); req->buffer = calloc(256, sizeof(uint8_t)); req->buffer_size = sprintf_s(req->buffer, 256, "\"hello+hello\": 1234"); req->buffer_pos = 1; struct noizu_trie_state state = { 0 }; noizu_trie__init(req, &array_test_trie, options, &state); TRIE_TOKEN o = noizu_trie__tokenize(&state, &array_test_trie, NULL); TEST_ASSERT_TOKENIZER_STATE(o, &state, TRIE_DELIM_EXIT, TRIE_MATCH, ARRAY_HELLO_HELLO, 0, 0, '"'); } TEST(TrieArray, UnitTest_JsonDelim_KL1) { struct noizu_trie_options options = { 0, .delimiter = '+', .keep_last_token = 1,.hard_delim = 0, .json_delim = 1}; offset_buffer* req = calloc(1, sizeof(offset_buffer)); req->buffer = calloc(256, sizeof(uint8_t)); req->buffer_size = sprintf_s(req->buffer, 256, "\"hello+hello\": 1234"); req->buffer_pos = 1; struct noizu_trie_state state = { 0 }; noizu_trie__init(req, &array_test_trie, options, &state); TRIE_TOKEN o = noizu_trie__tokenize(&state, &array_test_trie, NULL); TEST_ASSERT_TOKENIZER_STATE(o, &state, TRIE_DELIM_EXIT, TRIE_MATCH, ARRAY_HELLO_HELLO, ARRAY_HELLO, 0, '"'); } TEST(TrieArray, UnitTest_Escape_E1) { struct noizu_trie_options options = { 0, .delimiter = '+', .keep_last_token = 0,.hard_delim = 0, .json_delim = 1, .escape_chars = 1}; offset_buffer* req = calloc(1, sizeof(offset_buffer)); req->buffer = calloc(256, sizeof(uint8_t)); req->buffer_size = sprintf_s(req->buffer, 256, "\"escaped\\\"char\": 1234"); req->buffer_pos = 1; struct noizu_trie_state state = { 0 }; noizu_trie__init(req, &array_test_trie, options, &state); TRIE_TOKEN o = noizu_trie__tokenize(&state, &array_test_trie, NULL); TEST_ASSERT_TOKENIZER_STATE(o, &state, TRIE_DELIM_EXIT, TRIE_MATCH, ARRAY_JV_ESCAPE, 0, 0, '"'); } TEST(TrieArray, UnitTest_Escape_E0) { struct noizu_trie_options options = { 0, .delimiter = '+', .keep_last_token = 0,.hard_delim = 0, .json_delim = 1, .escape_chars = 0 }; offset_buffer* req = calloc(1, sizeof(offset_buffer)); req->buffer = calloc(256, sizeof(uint8_t)); req->buffer_size = sprintf_s(req->buffer, 256, "\"escaped\\\"char\": 1234"); req->buffer_pos = 1; struct noizu_trie_state state = { 0 }; noizu_trie__init(req, &array_test_trie, options, &state); TRIE_TOKEN o = noizu_trie__tokenize(&state, &array_test_trie, NULL); TEST_ASSERT_TOKENIZER_STATE(o, &state, TRIE_END_PARSE_EXIT, TRIE_NO_MATCH, 0, 0, 0, '\\'); }
42.387268
142
0.697121
2fe7edb291ad8158b4ae06a6dc61bb4ff34def8f
1,905
h
C
UNFLoader/main.h
anacierdem/N64-UNFLoader
89ea5dad435bbf9b71bda3f797e1db504c61a41a
[ "WTFPL" ]
46
2020-07-28T20:40:18.000Z
2022-03-04T09:30:19.000Z
UNFLoader/main.h
anacierdem/N64-UNFLoader
89ea5dad435bbf9b71bda3f797e1db504c61a41a
[ "WTFPL" ]
60
2020-07-30T23:43:02.000Z
2022-02-27T23:30:01.000Z
UNFLoader/main.h
anacierdem/N64-UNFLoader
89ea5dad435bbf9b71bda3f797e1db504c61a41a
[ "WTFPL" ]
16
2020-07-28T22:16:02.000Z
2022-01-12T23:58:00.000Z
#ifndef __MAIN_HEADER #define __MAIN_HEADER #pragma warning(push, 0) #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <ctype.h> #ifndef LINUX #include <windows.h> // Needed to prevent a macro redefinition due to curses.h #else #include <unistd.h> #endif #ifndef LINUX #include "Include/curses.h" #include "Include/curspriv.h" #include "Include/panel.h" #else #include <locale.h> #include <curses.h> #endif #include "Include/ftd2xx.h" #pragma warning(pop) /********************************* Macros *********************************/ #define false 0 #define true 1 #define CH_ESCAPE 27 #define CH_ENTER '\n' #define CH_BACKSPACE '\b' /********************************* Typedefs *********************************/ typedef unsigned char u8; typedef unsigned short u16; typedef unsigned int u32; typedef char s8; typedef short s16; typedef int s32; /********************************* Globals *********************************/ extern bool global_usecolors; extern int global_cictype; extern u32 global_savetype; extern bool global_listenmode; extern bool global_debugmode; extern bool global_z64; extern char* global_debugout; extern FILE* global_debugoutptr; extern char* global_exportpath; extern time_t global_timeout; extern time_t global_timeouttime; extern bool global_closefail; extern char* global_filename; extern WINDOW* global_window; #endif
26.830986
91
0.487664
d96dd206fbd4fc55dd92a1e73977e92b14c747c1
6,454
h
C
targets/TARGET_RENESAS/TARGET_RZ_A2XX/TARGET_GR_MANGO/device/inc/iodefine/iodefines/scifa_iodefine.h
thl-mot/mbed-os
d03d4a7ee066957a4015deb28281a0d726752e45
[ "Apache-2.0" ]
3,897
2015-09-04T13:42:23.000Z
2022-03-30T16:53:07.000Z
targets/TARGET_RENESAS/TARGET_RZ_A2XX/TARGET_GR_MANGO/device/inc/iodefine/iodefines/scifa_iodefine.h
thl-mot/mbed-os
d03d4a7ee066957a4015deb28281a0d726752e45
[ "Apache-2.0" ]
13,030
2015-09-17T10:30:05.000Z
2022-03-31T13:36:44.000Z
targets/TARGET_RENESAS/TARGET_RZ_A2XX/TARGET_GR_MANGO/device/inc/iodefine/iodefines/scifa_iodefine.h
thl-mot/mbed-os
d03d4a7ee066957a4015deb28281a0d726752e45
[ "Apache-2.0" ]
2,950
2015-09-08T19:07:05.000Z
2022-03-31T13:37:23.000Z
/******************************************************************************* * DISCLAIMER * This software is supplied by Renesas Electronics Corporation and is only * intended for use with Renesas products. No other uses are authorized. This * software is owned by Renesas Electronics Corporation and is protected under * all applicable laws, including copyright laws. * THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING * THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT * LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE * AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. * TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS * ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE * FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR * ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE * BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * Renesas reserves the right, without notice, to make changes to this software * and to discontinue the availability of this software. By using this software, * you agree to the additional terms and conditions found by accessing the * following link: * http://www.renesas.com/disclaimer * Copyright (C) 2019 Renesas Electronics Corporation. All rights reserved. *******************************************************************************/ /* Copyright (c) 2019-2020 Renesas Electronics Corporation. * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /******************************************************************************* * Rev: 3.01 * Description : IO define header *******************************************************************************/ #ifndef SCIFA_IODEFINE_H #define SCIFA_IODEFINE_H struct st_scifa { union { unsigned short WORD; struct { unsigned short CKS: 2; unsigned short : 1; unsigned short STOP: 1; unsigned short PM: 1; unsigned short PE: 1; unsigned short CHR: 1; unsigned short CM: 1; unsigned short : 8; } BIT; } SMR; union { union { unsigned char BYTE; struct { unsigned char MDDR: 8; } BIT; } MDDR; union { unsigned char BYTE; struct { unsigned char BRR: 8; } BIT; } BRR; } BRR_MDDR; char wk0[1]; union { unsigned short WORD; struct { unsigned short CKE: 2; unsigned short TEIE: 1; unsigned short REIE: 1; unsigned short RE: 1; unsigned short TE: 1; unsigned short RIE: 1; unsigned short TIE: 1; unsigned short : 8; } BIT; } SCR; union { unsigned char BYTE; struct { unsigned char FTDR: 8; } BIT; } FTDR; char wk1[1]; union { unsigned short WORD; struct { unsigned short DR: 1; unsigned short RDF: 1; unsigned short PER: 1; unsigned short FER: 1; unsigned short BRK: 1; unsigned short TDFE: 1; unsigned short TEND: 1; unsigned short ER: 1; unsigned short : 8; } BIT; } FSR; union { unsigned char BYTE; struct { unsigned char FRDR: 8; } BIT; } FRDR; char wk2[1]; union { unsigned short WORD; struct { unsigned short LOOP: 1; unsigned short RFRST: 1; unsigned short TFRST: 1; unsigned short MCE: 1; unsigned short TTRG: 2; unsigned short RTRG: 2; unsigned short RSTRG: 3; unsigned short : 5; } BIT; } FCR; union { unsigned short WORD; struct { unsigned short R: 5; unsigned short : 3; unsigned short T: 5; unsigned short : 3; } BIT; } FDR; union { unsigned short WORD; struct { unsigned short SPB2DT: 1; unsigned short SPB2IO: 1; unsigned short SCKDT: 1; unsigned short SCKIO: 1; unsigned short CTS2DT: 1; unsigned short CTS2IO: 1; unsigned short RTS2DT: 1; unsigned short RTS2IO: 1; unsigned short : 8; } BIT; } SPTR; union { unsigned short WORD; struct { unsigned short ORER: 1; unsigned short : 1; unsigned short FER: 4; unsigned short : 2; unsigned short PER: 4; unsigned short : 4; } BIT; } LSR; union { unsigned char BYTE; struct { unsigned char ABCS0: 1; unsigned char : 1; unsigned char NFEN: 1; unsigned char DIR: 1; unsigned char MDDRS: 1; unsigned char BRME: 1; unsigned char : 1; unsigned char BGDM: 1; } BIT; } SEMR; char wk3[1]; union { unsigned short WORD; struct { unsigned short TFTC: 5; unsigned short : 2; unsigned short TTRGS: 1; unsigned short RFTC: 5; unsigned short : 2; unsigned short RTRGS: 1; } BIT; } FTCR; }; #define SCIFA0 (*(volatile struct st_scifa *)0xE8007000) #define SCIFA1 (*(volatile struct st_scifa *)0xE8007800) #define SCIFA2 (*(volatile struct st_scifa *)0xE8008000) #define SCIFA3 (*(volatile struct st_scifa *)0xE8008800) #define SCIFA4 (*(volatile struct st_scifa *)0xE8009000) #endif
32.761421
80
0.545863
afd9938f9071185a32a1ab6725fe6c3f9e9001cd
129
h
C
OpenIDConnectSwift/AppAuth-Bridging-Header.h
jmelberg-okta/okta-openidconnect-appauth-sample-swift
283d51898538e6deb863a2848364113c674c45d0
[ "Apache-2.0" ]
7
2016-10-26T22:53:40.000Z
2019-10-04T20:34:04.000Z
OpenIDConnectSwift/AppAuth-Bridging-Header.h
jmelberg-okta/okta-openidconnect-appauth-sample-swift
283d51898538e6deb863a2848364113c674c45d0
[ "Apache-2.0" ]
4
2017-01-12T21:39:17.000Z
2017-12-04T22:08:47.000Z
OpenIDConnectSwift/AppAuth-Bridging-Header.h
jmelberg-okta/okta-openidconnect-appauth-sample-swift
283d51898538e6deb863a2848364113c674c45d0
[ "Apache-2.0" ]
5
2016-11-10T00:21:29.000Z
2019-03-07T08:27:09.000Z
#ifndef AppAuth_Bridging_Header_h #define AppAuth_Bridging_Header_h #import "AppAuth.h" #endif /* AppAuth_Bridging_Header_h */
18.428571
38
0.821705
8c0bfc51865f8bd74a2fcc20aeebb291be96567a
6,692
h
C
src/Ch376msc.h
djuseeq/Ch376msc
a0eff22b460f0230723fb709b81ec9c19ad71b2b
[ "MIT" ]
49
2019-04-23T08:40:19.000Z
2022-03-26T11:30:22.000Z
src/Ch376msc.h
n6il/Ch376msc
a0eff22b460f0230723fb709b81ec9c19ad71b2b
[ "MIT" ]
53
2019-05-08T02:54:20.000Z
2022-03-19T00:49:23.000Z
src/Ch376msc.h
n6il/Ch376msc
a0eff22b460f0230723fb709b81ec9c19ad71b2b
[ "MIT" ]
17
2019-04-05T06:24:28.000Z
2022-02-18T09:58:20.000Z
/* * Ch376msc.h * * Created on: Feb 25, 2019 * Author: György Kovács * Copyright (c) 2019, György Kovács * The MIT License (MIT) * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ #ifndef Ch376msc_H_ #define Ch376msc_H_ #include <Arduino.h> #include "CommDef.h" #include <Stream.h> #include <SPI.h> #if defined(__STM32F1__) #include "itoa.h" #endif #if defined(ARDUINO_ARCH_SAM) || defined(ARDUINO_ARCH_SAMD) #include "avr/dtostrf.h" #endif #define ANSWTIMEOUT 1000 // waiting for data from CH #define MAXDIRDEPTH 3 // 3 = /subdir1/subdir2/subdir3 class Ch376msc { public: /////////////Constructors//////////////////////// Ch376msc(HardwareSerial &usb, uint32_t speed);//HW serial Ch376msc(Stream &sUsb);// SW serial //Ch376msc(uint8_t spiSelect, uint8_t intPin, uint32_t speed = SPI_SCK_KHZ(125)); //Ch376msc(uint8_t spiSelect, uint32_t speed = SPI_SCK_KHZ(125));//SPI with MISO as Interrupt pin Ch376msc(uint8_t spiSelect, uint8_t intPin, SPISettings speed = SPI_SCK_KHZ(125)); Ch376msc(uint8_t spiSelect, SPISettings speed = SPI_SCK_KHZ(125));//SPI with MISO as Interrupt pin virtual ~Ch376msc();//destructor //////////////////////////////////////////////// void init(); uint8_t saveFileAttrb(); uint8_t openFile(); uint8_t closeFile(); uint8_t moveCursor(uint32_t position); uint8_t deleteFile(); uint8_t deleteDir(); uint8_t pingDevice(); uint8_t listDir(const char* filename = "*"); uint8_t readFile(char* buffer, uint8_t b_size); uint8_t readRaw(uint8_t* buffer, uint8_t b_size); int32_t readLong(char trmChar = '\n'); uint32_t readULong(char trmChar = '\n'); double readDouble(char trmChar = '\n'); uint8_t writeChar(char trmChar); uint8_t writeFile(char* buffer, uint8_t b_size); uint8_t writeRaw(uint8_t* buffer, uint8_t b_size); uint8_t writeNum(uint8_t buffer); uint8_t writeNum(int8_t buffer); uint8_t writeNum(uint16_t buffer); uint8_t writeNum(int16_t buffer); uint8_t writeNum(uint32_t buffer); uint8_t writeNum(int32_t buffer); uint8_t writeNum(double buffer); uint8_t writeNumln(uint8_t buffer); uint8_t writeNumln(int8_t buffer); uint8_t writeNumln(uint16_t buffer); uint8_t writeNumln(int16_t buffer); uint8_t writeNumln(uint32_t buffer); uint8_t writeNumln(int32_t buffer); uint8_t writeNumln(double buffer); uint8_t cd(const char* dirPath, bool mkDir); bool readFileUntil(char trmChar, char* buffer, uint8_t b_size); bool checkIntMessage(); // check is it any interrupt message came from CH(drive attach/detach) bool driveReady(); // call before file operation to check thumb drive or SD card are present void resetFileList(); //set/get uint32_t getFreeSectors(); uint32_t getTotalSectors(); uint32_t getFileSize(); uint32_t getCursorPos(); uint16_t getYear(); uint16_t getMonth(); uint16_t getDay(); uint16_t getHour(); uint16_t getMinute(); uint16_t getSecond(); uint8_t getStreamLen(); uint8_t getStatus(); uint8_t getFileSystem(); uint8_t getFileAttrb(); uint8_t getSource(); uint8_t getError(); uint8_t getChipVer(); char* getFileName(); char* getFileSizeStr(); bool getDeviceStatus(); // usb device mounted, unmounted bool getCHpresence(); bool getEOF(); void setFileName(const char* filename = ""); void setYear(uint16_t year); void setMonth(uint16_t month); void setDay(uint16_t day); void setHour(uint16_t hour); void setMinute(uint16_t minute); void setSecond(uint16_t second); void setSource(uint8_t inpSource); private: void write(uint8_t data); void print(const char str[]); void spiBeginTransfer(); void spiEndTransfer(); void driveAttach(); void driveDetach(); uint8_t spiWaitInterrupt(); uint8_t spiReadData(); uint8_t mount(); uint8_t getInterrupt(); uint8_t fileEnumGo(); uint8_t byteRdGo(); uint8_t fileCreate(); uint8_t byteWrGo(); uint8_t reqByteRead(uint8_t a); uint8_t reqByteWrite(uint8_t a); uint8_t readSerDataUSB(); uint8_t writeMachine(uint8_t* buffer, uint8_t b_size); uint8_t writeDataFromBuff(uint8_t* buffer); uint8_t readDataToBuff(uint8_t* buffer, uint8_t siz); uint8_t readMachine(uint8_t* buffer, uint8_t b_size); uint8_t dirInfoRead(); uint8_t setMode(uint8_t mode); uint8_t dirCreate(); void rdFatInfo(); void setSpeed(); void setError(uint8_t errCode); void clearError(); void sendCommand(uint8_t b_parancs); void sendFilename(); void writeFatData(); void constructDate(uint16_t value, uint8_t ymd); void constructTime(uint16_t value, uint8_t hms); void rdDiskInfo(); void rstFileContainer(); void rstDriveContainer(); ///////Global Variables/////////////////////////////// bool _deviceAttached = false; //false USB detached, true attached bool _controllerReady = false; // ha sikeres a kommunikacio bool _hwSerial; uint8_t _streamLength = 0; uint8_t _fileWrite = 0; // read or write mode, needed for close operation uint8_t _dirDepth = 0;// Don't check SD card if it's in subdir uint8_t _byteCounter = 0; //vital variable for proper reading,writing uint8_t _answer = 0; //a CH jelenlegi statusza INTERRUPT uint8_t _driveSource = 0;//0 = USB, 1 = SD uint8_t _spiChipSelect; // chip select pin SPI uint8_t _intPin; // interrupt pin uint8_t _errorCode = 0; // Store the last error code(see datasheet or CommDef.h) uint16_t _sectorCounter = 0;// variable for proper reading uint32_t _speed ; // Serial communication speed fSizeContainer _cursorPos; //unsigned long union char _filename[12]; HardwareSerial* _comPortHW; // Serial interface Stream* _comPort; SPISettings _spiSpeed; commInterface _interface; fileProcessENUM fileProcesSTM = REQUEST; fatFileInfo _fileData; diskInfo _diskData; };//end class #endif /* Ch376msc_H_ */
32.019139
99
0.742678
f030972db7cd0f8df6eeb3c9aa7d5c1ccdaf15a6
61,883
c
C
windows/core/ntgdi/fondrv/tt/scaler/scentry.c
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
windows/core/ntgdi/fondrv/tt/scaler/scentry.c
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
windows/core/ntgdi/fondrv/tt/scaler/scentry.c
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/********************************************************************* scentry.c -- New Scan Converter NewScan Module (c) Copyright 1992-1997 Microsoft Corp. All rights reserved. 10/14/97 claudebe accessing unitialized memory 1/31/95 deanb added fsc_GetCoords function 8/04/94 deanb State initialized to more it out of bss 8/24/93 deanb flatcount fix to reversal detection 8/10/93 deanb gray scale support routines added 6/22/93 deanb all black bounding box, (0,0) for null glyph 6/11/93 gregh Removed ONCURVE definition 6/11/93 deanb if HiBand <= LoBand do entire bitmap 6/10/93 deanb fsc_Initialize added, stdio & assert gone 4/06/92 deanb CheckContour removed 3/19/92 deanb ScanArrays rather than lists 12/22/92 deanb MultDivide -> LongMulDiv; Rectangle -> Rect 12/21/92 deanb interface types aligned with rasterizer 12/11/92 deanb fserror.h imported, new error codes 11/30/92 deanb WorkSpace renamed WorkScan 11/04/92 deanb remove duplicate points function added 10/28/92 deanb memory requirement calculation reworked 10/19/92 deanb bad contours ignored rather than error'd 10/16/92 deanb first contour point off curve fix 10/13/92 deanb rect.bounds correction 10/12/92 deanb reentrant State implemented 10/08/92 deanb reworked for split workspace 10/05/92 deanb global ListMemory replace with stListSize 9/25/92 deanb scankind included in line/spline/endpoint calls 9/10/92 deanb dropout coding begun 9/08/92 deanb MAXSPLINELENGTH now imported from scspline.h 8/18/92 deanb New i/f for dropout control, contour elems 7/28/92 deanb Recursive calls for up/down & left/right 7/23/92 deanb EvaluateSpline included 7/17/92 deanb Included EvaluateLine 7/13/92 deanb Start/End point made SHORT 6/01/92 deanb fsc_FillBitMap debug switch added 5/08/92 deanb reordered includes for precompiled headers 4/27/92 deanb Splines coded 4/09/92 deanb New types 4/06/92 deanb rectBounds calc corrected 3/30/92 deanb MinMax calc added to MeasureContour 3/24/92 deanb GetWorkspaceSize coded 3/23/92 deanb First cut **********************************************************************/ /*********************************************************************/ /* Imports */ /*********************************************************************/ #define FSCFG_INTERNAL #include "fscdefs.h" /* shared data types */ #include "fserror.h" /* error codes */ #include "fontmath.h" /* for LongMulDiv */ #include "scglobal.h" /* structures & constants */ #include "scgray.h" /* gray scale param block */ #include "scspline.h" /* spline evaluation */ #include "scline.h" /* line evaluation */ #include "scendpt.h" /* for init and contour list */ #include "scanlist.h" /* for init and bitmap */ #include "scmemory.h" /* for setup mem */ #include "scentry.h" /* for own function prototypes */ /*********************************************************************/ /* Global state structure */ /*********************************************************************/ #ifndef FSCFG_REENTRANT FS_PUBLIC StateVars State = {0}; /* global static: available to all */ #endif /*********************************************************************/ /* Local Prototypes */ /*********************************************************************/ FS_PRIVATE int32 FindExtrema(ContourList*, GlyphBitMap*); FS_PRIVATE int32 EvaluateSpline(PSTATE F26Dot6, F26Dot6, F26Dot6, F26Dot6, F26Dot6, F26Dot6, uint16 ); /*********************************************************************/ /* Function Exports */ /*********************************************************************/ /* Initialization Functions */ /*********************************************************************/ FS_PUBLIC void fsc_Initialize() { fsc_InitializeScanlist(); /* scanlist calls to bitmap */ } /*********************************************************************/ /* Remove duplicated points from contour data */ /* This was previously done in sc_FindExtrema of sc.c, */ /* but was pulled out to avoid having fsc_MeasureGlyph */ /* make changes to the contour list data structure. */ /*********************************************************************/ FS_PUBLIC int32 fsc_RemoveDups( ContourList* pclContour ) /* glyph outline */ { uint16 usContour; /* contour limit */ int16 sStartPt, sEndPt; /* coutour index limits */ int16 sPt; /* point index */ int16 s; /* index for list collapse */ F26Dot6 *pfxX1, *pfxY1; /* leading point */ F26Dot6 fxX2, fxY2; /* trailing point */ for (usContour = 0; usContour < pclContour->usContourCount; usContour++) { sStartPt = pclContour->asStartPoint[usContour]; sEndPt = pclContour->asEndPoint[usContour]; pfxX1 = &(pclContour->afxXCoord[sStartPt]); pfxY1 = &(pclContour->afxYCoord[sStartPt]); for (sPt = sStartPt; sPt < sEndPt; ++sPt) { fxX2 = *pfxX1; /* check next pair */ pfxX1++; fxY2 = *pfxY1; pfxY1++; if ((*pfxX1 == fxX2) && (*pfxY1 == fxY2)) /* if duplicate */ { for(s = sPt; s > sStartPt; s--) /* s = index of point to be removed */ { pclContour->afxXCoord[s] = pclContour->afxXCoord[s - 1]; pclContour->afxYCoord[s] = pclContour->afxYCoord[s - 1]; pclContour->abyOnCurve[s] = pclContour->abyOnCurve[s - 1]; } sStartPt++; /* advance start past dup */ pclContour->asStartPoint[usContour] = sStartPt; pclContour->abyOnCurve[sPt + 1] |= ONCURVE; /* dup'd pt must be on curve */ } } /* now pfxX1 and pfxY1 point to end point coordinates */ if (sStartPt != sEndPt) /* finished if single point */ { fxX2 = pclContour->afxXCoord[sStartPt]; fxY2 = pclContour->afxYCoord[sStartPt]; if ((*pfxX1 == fxX2) && (*pfxY1 == fxY2)) /* if start = end */ { pclContour->asStartPoint[usContour]++; pclContour->abyOnCurve[sEndPt] |= ONCURVE; /* dup'd pt must be on curve */ } } } return NO_ERR; } /*********************************************************************/ /* Calculate the amount of workspace needed to scan convert */ /* a given glyph into a given bitmap. Get per intersection and */ /* per scanline size info from ScanList module. */ /*********************************************************************/ FS_PRIVATE int32 fsc_CheckYReversal ( PRevRoot prrRoots, F26Dot6 fxY1, F26Dot6 fxY2, int16 *sDir, int16 *sOrgDir, int16 *sFlatCount) { int32 lErrCode; if (*sDir == 0) { if (fxY2 > fxY1) /* find first up or down */ { *sDir = 1; *sOrgDir = *sDir; /* save original ep check */ } else if (fxY2 < fxY1) { *sDir = -1; *sOrgDir = *sDir; /* save original ep check */ } else { (*sFlatCount)++; /* countour starts flat */ } } else if (*sDir == 1) { if (fxY2 <= fxY1) /* = is for endpoint cases */ { lErrCode = fsc_AddYReversal (prrRoots, fxY1, 1); if (lErrCode != NO_ERR) return lErrCode; *sDir = -1; } } else /* if sDir == -1 */ { if (fxY2 >= fxY1) /* = is for endpoint cases */ { lErrCode = fsc_AddYReversal (prrRoots, fxY1, -1); if (lErrCode != NO_ERR) return lErrCode; *sDir = 1; } } return NO_ERR; } FS_PRIVATE int32 fsc_CheckYReversalInSpline( PRevRoot prrRoots, int16 *sDir, int16 *sOrgDir, int16 *sFlatCount, F26Dot6 fxX1, /* start point x coordinate */ F26Dot6 fxY1, /* start point y coordinate */ F26Dot6 fxX2, /* control point x coordinate */ F26Dot6 fxY2, /* control point y coordinate */ F26Dot6 fxX3, /* ending x coordinate */ F26Dot6 fxY3 /* ending y coordinate */ ) { /* subset of EvaluateSpline, must cut spline the same way in regrads to Y direction reversal */ int32 lErrCode; F26Dot6 fxDX21, fxDX32; /* delta x's */ F26Dot6 fxDY21, fxDY32; /* delta y's */ F26Dot6 fxDenom; /* ratio denominator */ F26Dot6 fxX4, fxY4; /* first mid point */ F26Dot6 fxX5, fxY5; /* mid mid point */ F26Dot6 fxX6, fxY6; /* second mid point */ F26Dot6 fxX456, fxY456; /* for monotonic subdivision */ fxDX21 = fxX2 - fxX1; /* get all four deltas */ fxDX32 = fxX3 - fxX2; fxDY21 = fxY2 - fxY1; fxDY32 = fxY3 - fxY2; /* If spline goes up and down, then subdivide it */ if (((fxDY21 > 0L) && (fxDY32 < 0L)) || ((fxDY21 < 0L) && (fxDY32 > 0L))) { fxDenom = fxDY21 - fxDY32; /* total y span */ if(fxDenom == 0) return SPLINE_SUBDIVISION_ERR; fxX4 = fxX1 + LongMulDiv(fxDX21, fxDY21, fxDenom); fxX6 = fxX2 + LongMulDiv(fxDX32, fxDY21, fxDenom); fxX5 = fxX4 + LongMulDiv(fxX6 - fxX4, fxDY21, fxDenom); fxY456 = fxY1 + LongMulDiv(fxDY21, fxDY21, fxDenom); lErrCode = fsc_CheckYReversalInSpline(prrRoots, sDir, sOrgDir, sFlatCount, fxX1, fxY1, fxX4, fxY456, fxX5, fxY456); if (lErrCode != NO_ERR) return lErrCode; return fsc_CheckYReversalInSpline(prrRoots, sDir, sOrgDir, sFlatCount, fxX5, fxY456, fxX6, fxY456, fxX3, fxY3); } /* If spline goes left and right, then subdivide it */ if (((fxDX21 > 0L) && (fxDX32 < 0L)) || ((fxDX21 < 0L) && (fxDX32 > 0L))) { fxDenom = fxDX21 - fxDX32; /* total x span */ if(fxDenom == 0) return SPLINE_SUBDIVISION_ERR; fxY4 = fxY1 + LongMulDiv(fxDY21, fxDX21, fxDenom); fxY6 = fxY2 + LongMulDiv(fxDY32, fxDX21, fxDenom); fxY5 = fxY4 + LongMulDiv(fxY6 - fxY4, fxDX21, fxDenom); fxX456 = fxX1 + LongMulDiv(fxDX21, fxDX21, fxDenom); lErrCode = fsc_CheckYReversalInSpline(prrRoots, sDir, sOrgDir, sFlatCount, fxX1, fxY1, fxX456, fxY4, fxX456, fxY5); if (lErrCode != NO_ERR) return lErrCode; return fsc_CheckYReversalInSpline(prrRoots, sDir, sOrgDir, sFlatCount, fxX456, fxY5, fxX456, fxY6, fxX3, fxY3); } /* By now the spline must be monotonic */ return fsc_CheckYReversal(prrRoots, fxY1, fxY3, sDir, sOrgDir, sFlatCount); } FS_PUBLIC int32 fsc_MeasureGlyph( ContourList* pclContour, /* glyph outline */ GlyphBitMap* pbmpBitMap, /* to return bounds */ WorkScan * pwsWork, /* to return values */ uint16 usScanKind, /* dropout control value */ uint16 usRoundXMin, /* for gray scale alignment */ int16 sBitmapEmboldeningHorExtra, int16 sBitmapEmboldeningVertExtra ) { uint16 usCont; /* contour index */ int16 sPt; /* point index */ int16 sStart, sEnd; /* start and end point of contours */ int16 sOrgDir; /* original contour direction */ int16 sDir; /* current contour direction */ int16 sFlatCount; /* for contours starting flat */ int32 lVScanCount; /* total vertical scan lines */ int32 lHScanCount; /* total horizontal scan lines */ int32 lTotalHIx; int32 lTotalVIx; int32 lElementCount; /* total element point estimate */ int32 lDivide; /* spline element point counter */ int32 lErrCode; F26Dot6 fxX1, fxX2, fxX3; /* x coord endpoints */ F26Dot6 fxY1, fxY2, fxY3; /* y coord endpoints */ F26Dot6 *pfxXCoord, *pfxYCoord, *pfxXStop; /* for fast point array access */ F26Dot6 fxAbsDelta; /* for element count check */ uint8 byF1, byF2; /* oncurve flag values */ uint8 *pbyFlags; /* for element count check */ PRevRoot prrRoots; /* reversal list roots structure */ lErrCode = FindExtrema(pclContour, pbmpBitMap); /* calc bounding box */ if (lErrCode != NO_ERR) return lErrCode; pbmpBitMap->rectBounds.left &= -((int32)usRoundXMin); /* mask off low n bits */ /* bitmap emboldening by 2% + 1 pixel horizontally, 2% vertically */ if ((pbmpBitMap->rectBounds.top != pbmpBitMap->rectBounds.bottom) && (pbmpBitMap->rectBounds.left != pbmpBitMap->rectBounds.right)) { // we don't want to increase the size of the bitmap on a empty glyph if (sBitmapEmboldeningHorExtra > 0) { pbmpBitMap->rectBounds.right += sBitmapEmboldeningHorExtra; } else { pbmpBitMap->rectBounds.left += sBitmapEmboldeningHorExtra; } if (sBitmapEmboldeningVertExtra > 0) { pbmpBitMap->rectBounds.bottom -= (sBitmapEmboldeningVertExtra); } else { pbmpBitMap->rectBounds.top -= (sBitmapEmboldeningVertExtra); } } prrRoots = fsc_SetupRevRoots(pwsWork->pchRBuffer, pwsWork->lRMemSize); lElementCount = 0; /* smart point counter */ for (usCont = 0; usCont < pclContour->usContourCount; usCont++) { sStart = pclContour->asStartPoint[usCont]; sEnd = pclContour->asEndPoint[usCont]; if (sStart == sEnd) { continue; /* for anchor points */ } /* check contour Y values for direction reversals */ /* in order to get correct value here and avoid overflow later, we need to cut splines is subsplines the same way as it's done in fsc_FillGlyph */ pfxXCoord = &pclContour->afxXCoord[sStart]; pfxYCoord = &pclContour->afxYCoord[sStart]; pbyFlags = &pclContour->abyOnCurve[sStart]; pfxXStop = &pclContour->afxXCoord[sEnd]; if (pclContour->abyOnCurve[sEnd] & ONCURVE) /* if endpoint oncurve */ { fxX1 = pclContour->afxXCoord[sEnd]; fxY1 = pclContour->afxYCoord[sEnd]; fxX2 = *pfxXCoord; fxY2 = *pfxYCoord; byF1 = *pbyFlags; /* 1st pt might be off */ pfxXStop++; /* stops at endpoint */ } else /* if endpoint offcurve */ { fxX1 = pclContour->afxXCoord[sEnd - 1]; fxY1 = pclContour->afxYCoord[sEnd - 1]; fxX2 = pclContour->afxXCoord[sEnd]; fxY2 = pclContour->afxYCoord[sEnd]; if ((pclContour->abyOnCurve[sEnd - 1] & ONCURVE) == 0) { fxX1 = (fxX1 + fxX2 + 1) >> 1; /* offcurve midpoint */ fxY1 = (fxY1 + fxY2 + 1) >> 1; } byF1 = 0; pfxXCoord--; /* pre decrement */ pfxYCoord--; pbyFlags--; } /* At this point, (x1,y1) is the last oncurve point; (x2,y2) is the next point (on or off); and the pointers are ready to be incremented to the point following (x2,y2). Throughout this loop (x1,y1) is always an oncurve point (it may be the midpoint between two offcurve points). If (x2,y2) is oncurve, then we have a line; if offcurve, we have a spline, and (x3,y3) will be the next oncurve point. */ sDir = 0; /* starting dir unknown */ sFlatCount = 0; sOrgDir = 1; /* default direction if everything is flat */ while (pfxXCoord < pfxXStop) { if (byF1 & ONCURVE) /* if next point oncurve */ { lErrCode = fsc_CheckYReversal(prrRoots, fxY1, fxY2, &sDir, &sOrgDir, &sFlatCount); if (lErrCode != NO_ERR) return lErrCode; fxX1 = fxX2; /* next oncurve point */ fxY1 = fxY2; pfxXCoord++; pfxYCoord++; pbyFlags++; } else { pfxXCoord++; /* check next point */ fxX3 = *pfxXCoord; pfxYCoord++; fxY3 = *pfxYCoord; pbyFlags++; if (*pbyFlags & ONCURVE) /* if it's on, use it */ { pfxXCoord++; pfxYCoord++; pbyFlags++; } else /* if not, calc next on */ { fxX3 = (fxX2 + fxX3 + 1) >> 1; /* offcurve midpoint */ fxY3 = (fxY2 + fxY3 + 1) >> 1; } lErrCode = fsc_CheckYReversalInSpline(prrRoots, &sDir, &sOrgDir, &sFlatCount,fxX1, fxY1, fxX2, fxY2, fxX3, fxY3); if (lErrCode != NO_ERR) return lErrCode; fxX1 = fxX3; /* next oncurve point */ fxY1 = fxY3; } /* test to avoid reading past the end of memory on the last line */ if (pfxXCoord != pfxXStop) { fxX2 = *pfxXCoord; /* next contour point */ fxY2 = *pfxYCoord; byF1 = *pbyFlags; } } while (sFlatCount > 0) /* if contour started flat */ { if (sDir == 0) /* if completely flat */ { sDir = 1; /* then pick a direction */ } lErrCode = fsc_AddYReversal (prrRoots, fxY1, sDir); /* add one per point */ if (lErrCode != NO_ERR) return lErrCode; sDir = -sDir; sFlatCount--; } if (sOrgDir != sDir) /* if endpoint reverses */ { lErrCode = fsc_AddYReversal (prrRoots, fxY1, sDir); /* then balance up/down */ if (lErrCode != NO_ERR) return lErrCode; } /* if doing dropout control, check contour X values for direction reversals */ if (!(usScanKind & SK_NODROPOUT)) /* if any kind of dropout */ { fxX1 = pclContour->afxXCoord[sEnd]; /* start by closing */ pfxXCoord = &pclContour->afxXCoord[sStart]; sPt = sStart; sDir = 0; /* starting dir unknown */ sFlatCount = 0; while ((sDir == 0) && (sPt <= sEnd)) { fxX2 = *pfxXCoord++; if (fxX2 > fxX1) /* find first up or down */ { sDir = 1; } else if (fxX2 < fxX1) { sDir = -1; } else { sFlatCount++; /* countour starts flat */ } fxX1 = fxX2; sPt++; } sOrgDir = sDir; /* save original ep check */ while (sPt <= sEnd) { fxX2 = *pfxXCoord++; if (sDir == 1) { if (fxX2 <= fxX1) /* = is for endpoint cases */ { lErrCode = fsc_AddXReversal (prrRoots, fxX1, 1); if (lErrCode != NO_ERR) return lErrCode; sDir = -1; } } else /* if sDir == -1 */ { if (fxX2 >= fxX1) /* = is for endpoint cases */ { lErrCode = fsc_AddXReversal (prrRoots, fxX1, -1); if (lErrCode != NO_ERR) return lErrCode; sDir = 1; } } fxX1 = fxX2; /* next segment */ sPt++; } while (sFlatCount > 0) /* if contour started flat */ { if (sDir == 0) /* if completely flat */ { sDir = 1; /* then pick a direction */ sOrgDir = 1; } lErrCode = fsc_AddXReversal (prrRoots, fxX1, sDir); /* add one per point */ if (lErrCode != NO_ERR) return lErrCode; sDir = -sDir; sFlatCount--; } if (sOrgDir != sDir) /* if endpoint reverses */ { lErrCode = fsc_AddXReversal (prrRoots, fxX1, sDir); /* then balance up/down */ if (lErrCode != NO_ERR) return lErrCode; } if (usScanKind & SK_SMART) /* if smart dropout control */ { /* estimate the elem point count */ fxX1 = pclContour->afxXCoord[sEnd]; fxY1 = pclContour->afxYCoord[sEnd]; byF1 = pclContour->abyOnCurve[sEnd]; pfxXCoord = &pclContour->afxXCoord[sStart]; pfxYCoord = &pclContour->afxYCoord[sStart]; pbyFlags = &pclContour->abyOnCurve[sStart]; lElementCount += (uint32)(sEnd - sStart) + 2L; /* 1/pt + 1/contour */ for (sPt = sStart; sPt <= sEnd; sPt++) { fxX2 = *pfxXCoord++; fxY2 = *pfxYCoord++; byF2 = *pbyFlags++; if (((byF1 & byF2) & ONCURVE) == 0) /* if this is a spline */ { if (((byF1 | byF2) & ONCURVE) == 0) { lElementCount++; /* +1 for midpoint */ } if (FXABS(fxX2 - fxX1) > FXABS(fxY2 - fxY1)) { fxAbsDelta = FXABS(fxX2 - fxX1); } else { fxAbsDelta = FXABS(fxY2 - fxY1); } lDivide = 0; while (fxAbsDelta > (MAXSPLINELENGTH / 2)) { lDivide++; lDivide <<= 1; fxAbsDelta >>= 1; } lElementCount += lDivide; /* for subdivision */ } fxX1 = fxX2; fxY1 = fxY2; byF1 = byF2; } } } } if (!(usScanKind & SK_NODROPOUT) && (usScanKind & SK_SMART)) /* if smart dropout */ { lElementCount += fsc_GetReversalCount(prrRoots) << 1; /* add in 2 * reversals */ if (lElementCount > (0xFFFF >> SC_CODESHFT)) { return SMART_DROP_OVERFLOW_ERR; } } /* set horiz workspace return values */ lHScanCount = (int32)(pbmpBitMap->rectBounds.top - pbmpBitMap->rectBounds.bottom); lVScanCount = (int32)(pbmpBitMap->rectBounds.right - pbmpBitMap->rectBounds.left); pbmpBitMap->sRowBytes = (int16)ROWBYTESLONG(lVScanCount); pbmpBitMap->lMMemSize = (lHScanCount * (int32)pbmpBitMap->sRowBytes); lTotalHIx = fsc_GetHIxEstimate(prrRoots); /* intersection count */ pwsWork->lHMemSize = fsc_GetScanHMem(usScanKind, lHScanCount, lTotalHIx); /* set vertical workspace return values */ if (usScanKind & SK_NODROPOUT) /* if no dropout */ { pwsWork->lVMemSize = 0L; lTotalVIx = 0; } else { lTotalVIx = fsc_GetVIxEstimate(prrRoots); /* estimate intersection count */ pwsWork->lVMemSize = fsc_GetScanVMem(usScanKind, lVScanCount, lTotalVIx, lElementCount); } pwsWork->lHInterCount = lTotalHIx; /* save for SetupScan */ pwsWork->lVInterCount = lTotalVIx; pwsWork->lElementCount = lElementCount; pwsWork->lRMemSize = fsc_GetRevMemSize(prrRoots); #ifdef FSCFG_REENTRANT pwsWork->lHMemSize += sizeof(StateVars); /* reentrant state space */ #endif return NO_ERR; } /*********************************************************************/ /* Calculate the amount of workspace needed to scan convert */ /* a given band into a given bitmap. Get per intersection and */ /* per scanline size info from ScanList module. */ /*********************************************************************/ FS_PUBLIC int32 fsc_MeasureBand( GlyphBitMap* pbmpBitMap, /* computed by MeasureGlyph */ WorkScan* pwsWork, /* to return new values */ uint16 usBandType, /* small or fast */ uint16 usBandWidth, /* scanline count */ uint16 usScanKind ) /* dropout control value */ { int32 lBandWidth; /* max scanline count */ int32 lTotalHIx; /* est of horiz intersections in band */ int32 lVScanCount; /* total vertical scan lines */ int32 lHScanCount; /* total horizontal scan lines */ lBandWidth = (int32)usBandWidth; pbmpBitMap->lMMemSize = (lBandWidth * (int32)pbmpBitMap->sRowBytes); if (usBandType == FS_BANDINGSMALL) { lTotalHIx = fsc_GetHIxBandEst((PRevRoot)pwsWork->pchRBuffer, &pbmpBitMap->rectBounds, lBandWidth); pwsWork->lHInterCount = lTotalHIx; /* save for SetupScan */ pwsWork->lHMemSize = fsc_GetScanHMem(usScanKind, lBandWidth, lTotalHIx); pwsWork->lVMemSize = 0L; /* force dropout control off */ } else if (usBandType == FS_BANDINGFAST) { lTotalHIx = fsc_GetHIxEstimate((PRevRoot)pwsWork->pchRBuffer); /* intersection count */ pwsWork->lHInterCount = lTotalHIx; /* save for SetupScan */ lHScanCount = (int32)(pbmpBitMap->rectBounds.top - pbmpBitMap->rectBounds.bottom); pwsWork->lHMemSize = fsc_GetScanHMem(usScanKind, lHScanCount, lTotalHIx); if (usScanKind & SK_NODROPOUT) /* if no dropout */ { pwsWork->lVMemSize = 0L; } else /* if any kind of dropout */ { pbmpBitMap->lMMemSize += (int32)pbmpBitMap->sRowBytes; /* to save below row */ lVScanCount = (int32)(pbmpBitMap->rectBounds.right - pbmpBitMap->rectBounds.left); pwsWork->lVMemSize = fsc_GetScanVMem(usScanKind, lVScanCount, pwsWork->lVInterCount, pwsWork->lElementCount); pwsWork->lVMemSize += (int32)pbmpBitMap->sRowBytes; /* to save above row */ ALIGN(voidPtr, pwsWork->lVMemSize ); } } #ifdef FSCFG_REENTRANT pwsWork->lHMemSize += sizeof(StateVars); /* reentrant state space */ #endif return NO_ERR; } /*********************************************************************/ /* Scan Conversion Routine */ /* Trace the contour, passing out lines and splines, */ /* then call ScanList to fill the bitmap */ /*********************************************************************/ FS_PUBLIC int32 fsc_FillGlyph( ContourList* pclContour, /* glyph outline */ GlyphBitMap* pgbBitMap, /* target */ WorkScan* pwsWork, /* for scan array */ uint16 usBandType, /* old, small, fast or faster */ uint16 usScanKind ) /* dropout control value */ { uint16 usCont; /* contour index */ int16 sStart, sEnd; /* start and end point of contours */ int32 lStateSpace; /* HMem used by state structure */ int32 lErrCode; /* function return code */ F26Dot6 *pfxXCoord; /* next x coord ptr */ F26Dot6 *pfxYCoord; /* next y coord ptr */ uint8 *pbyOnCurve; /* next flag ptr */ F26Dot6 *pfxXStop; /* contour trace end condition */ F26Dot6 fxX1, fxX2, fxX3; /* x coord endpoints */ F26Dot6 fxY1, fxY2, fxY3; /* y coord endpoints */ uint8 byOnCurve; /* point 2 flag variable */ int32 lHiScanBand; /* top scan limit */ int32 lLoScanBand; /* bottom scan limit */ int32 lHiBitBand; /* top bitmap limit */ int32 lLoBitBand; /* bottom bitmap limit */ int32 lOrgLoBand; /* save for overscan fill check */ F26Dot6 fxYHiBand, fxYLoBand; /* limits in f26.6 */ boolean bSaveRow; /* for dropout over scanning */ boolean bBandCheck; /* eliminate out of band elements */ #ifdef FSCFG_REENTRANT StateVars *pState; /* reentrant State is accessed via pointer */ pState = (StateVars*)pwsWork->pchHBuffer; /* and lives in HMem (memoryBase[6]) */ lStateSpace = sizeof(StateVars); #else lStateSpace = 0L; /* no HMem needed if not reentrant */ #endif if (pgbBitMap->rectBounds.top <= pgbBitMap->rectBounds.bottom) { return NO_ERR; /* quick out for null glyph */ } if (pgbBitMap->bZeroDimension) /* if no height or width */ { usScanKind &= (~SK_STUBS); /* force no-stub dropout */ } lHiBitBand = (int32)pgbBitMap->sHiBand, lLoBitBand = (int32)pgbBitMap->sLoBand; lOrgLoBand = lLoBitBand; /* save for fill call */ Assert (lHiBitBand > lLoBitBand); /* should be handled above */ if (!(usScanKind & SK_NODROPOUT)) /* if any kind of dropout */ { lLoBitBand--; /* leave room below line */ } if (lHiBitBand > pgbBitMap->rectBounds.top) { lHiBitBand = pgbBitMap->rectBounds.top; /* clip to top */ } if (lLoBitBand < pgbBitMap->rectBounds.bottom) { lLoBitBand = pgbBitMap->rectBounds.bottom; /* clip to bottom */ } if (usBandType == FS_BANDINGFAST) /* if fast banding */ { lHiScanBand = pgbBitMap->rectBounds.top; /* render everything */ lLoScanBand = pgbBitMap->rectBounds.bottom; bSaveRow = TRUE; /* keep last row for dropout */ } else /* if old or small banding */ { lHiScanBand = lHiBitBand; /* just take the band */ lLoScanBand = lLoBitBand; bSaveRow = FALSE; /* last row not needed */ } /* if fast banding has already renderend elements, skip to FillBitMap */ if (usBandType != FS_BANDINGFASTER) /* if rendering required */ { fsc_SetupMem(ASTATE /* init workspace */ pwsWork->pchHBuffer + lStateSpace, pwsWork->lHMemSize - lStateSpace, pwsWork->pchVBuffer, pwsWork->lVMemSize); fsc_SetupLine(ASTATE0); /* passes line callback to scanlist */ fsc_SetupSpline(ASTATE0); /* passes spline callback to scanlist */ fsc_SetupEndPt(ASTATE0); /* passes endpoint callback to scanlist */ /* Eliminate out of band lines and splines, unless fast banding */ bBandCheck = ((lHiScanBand < pgbBitMap->rectBounds.top) || (lLoScanBand > pgbBitMap->rectBounds.bottom)); fxYHiBand = (F26Dot6)((lHiScanBand << SUBSHFT) - SUBHALF); /* may be too wide */ fxYLoBand = (F26Dot6)((lLoScanBand << SUBSHFT) + SUBHALF); lErrCode = fsc_SetupScan(ASTATE &(pgbBitMap->rectBounds), usScanKind, lHiScanBand, lLoScanBand, bSaveRow, (int32)pgbBitMap->sRowBytes, pwsWork->lHInterCount, pwsWork->lVInterCount, pwsWork->lElementCount, (PRevRoot)pwsWork->pchRBuffer ); if (lErrCode != NO_ERR) return lErrCode; for (usCont = 0; usCont < pclContour->usContourCount; usCont++) { sStart = pclContour->asStartPoint[usCont]; sEnd = pclContour->asEndPoint[usCont]; if (sStart == sEnd) { continue; /* for compatibilty */ } /* For efficiency in tracing the contour, we start by assigning (x1,y1) to the last oncurve point. This is found by starting with the End point and backing up if necessary. The pfxCoord pointers can then be used to trace the entire contour without being reset across the Start/End gap. */ pfxXCoord = &pclContour->afxXCoord[sStart]; pfxYCoord = &pclContour->afxYCoord[sStart]; pbyOnCurve = &pclContour->abyOnCurve[sStart]; pfxXStop = &pclContour->afxXCoord[sEnd]; if (pclContour->abyOnCurve[sEnd] & ONCURVE) /* if endpoint oncurve */ { fxX1 = pclContour->afxXCoord[sEnd]; fxY1 = pclContour->afxYCoord[sEnd]; fxX2 = *pfxXCoord; fxY2 = *pfxYCoord; byOnCurve = *pbyOnCurve; /* 1st pt might be off */ pfxXStop++; /* stops at endpoint */ } else /* if endpoint offcurve */ { fxX1 = pclContour->afxXCoord[sEnd - 1]; fxY1 = pclContour->afxYCoord[sEnd - 1]; fxX2 = pclContour->afxXCoord[sEnd]; fxY2 = pclContour->afxYCoord[sEnd]; if ((pclContour->abyOnCurve[sEnd - 1] & ONCURVE) == 0) { fxX1 = (fxX1 + fxX2 + 1) >> 1; /* offcurve midpoint */ fxY1 = (fxY1 + fxY2 + 1) >> 1; } byOnCurve = 0; pfxXCoord--; /* pre decrement */ pfxYCoord--; pbyOnCurve--; } fsc_BeginContourEndpoint(ASTATE fxX1, fxY1); /* 1st oncurve pt -> ep module */ lErrCode = fsc_BeginContourScan(ASTATE usScanKind, fxX1, fxY1); /* to scanlist module too */ if (lErrCode != NO_ERR) return lErrCode; /* At this point, (x1,y1) is the last oncurve point; (x2,y2) is the next point (on or off); and the pointers are ready to be incremented to the point following (x2,y2). Throughout this loop (x1,y1) is always an oncurve point (it may be the midpoint between two offcurve points). If (x2,y2) is oncurve, then we have a line; if offcurve, we have a spline, and (x3,y3) will be the next oncurve point. */ if (!bBandCheck) { while (pfxXCoord < pfxXStop) { if (byOnCurve & ONCURVE) /* if next point oncurve */ { lErrCode = fsc_CheckEndPoint(ASTATE fxX2, fxY2, usScanKind); if (lErrCode != NO_ERR) return lErrCode; lErrCode = fsc_CalcLine(ASTATE fxX1, fxY1, fxX2, fxY2, usScanKind); if (lErrCode != NO_ERR) return lErrCode; fxX1 = fxX2; /* next oncurve point */ fxY1 = fxY2; pfxXCoord++; pfxYCoord++; pbyOnCurve++; } else { pfxXCoord++; /* check next point */ fxX3 = *pfxXCoord; pfxYCoord++; fxY3 = *pfxYCoord; pbyOnCurve++; if (*pbyOnCurve & ONCURVE) /* if it's on, use it */ { pfxXCoord++; pfxYCoord++; pbyOnCurve++; } else /* if not, calc next on */ { fxX3 = (fxX2 + fxX3 + 1) >> 1; /* offcurve midpoint */ fxY3 = (fxY2 + fxY3 + 1) >> 1; } lErrCode = EvaluateSpline(ASTATE fxX1, fxY1, fxX2, fxY2, fxX3, fxY3, usScanKind); if (lErrCode != NO_ERR) return lErrCode; fxX1 = fxX3; /* next oncurve point */ fxY1 = fxY3; } /* test to avoid reading past the end of memory on the last line */ if (pfxXCoord != pfxXStop) { fxX2 = *pfxXCoord; /* next contour point */ fxY2 = *pfxYCoord; byOnCurve = *pbyOnCurve; } } } else /* if band checking */ { while (pfxXCoord < pfxXStop) { if (byOnCurve & ONCURVE) /* if next point oncurve */ { lErrCode = fsc_CheckEndPoint(ASTATE fxX2, fxY2, usScanKind); if (lErrCode != NO_ERR) return lErrCode; if (!(((fxY1 > fxYHiBand) && (fxY2 > fxYHiBand)) || ((fxY1 < fxYLoBand) && (fxY2 < fxYLoBand)))) { lErrCode = fsc_CalcLine(ASTATE fxX1, fxY1, fxX2, fxY2, usScanKind); if (lErrCode != NO_ERR) return lErrCode; } fxX1 = fxX2; /* next oncurve point */ fxY1 = fxY2; pfxXCoord++; pfxYCoord++; pbyOnCurve++; } else { pfxXCoord++; /* check next point */ fxX3 = *pfxXCoord; pfxYCoord++; fxY3 = *pfxYCoord; pbyOnCurve++; if (*pbyOnCurve & ONCURVE) /* if it's on, use it */ { pfxXCoord++; pfxYCoord++; pbyOnCurve++; } else /* if not, calc next on */ { fxX3 = (fxX2 + fxX3 + 1) >> 1; /* offcurve midpoint */ fxY3 = (fxY2 + fxY3 + 1) >> 1; } if (!(((fxY1 > fxYHiBand) && (fxY2 > fxYHiBand) && (fxY3 > fxYHiBand)) || ((fxY1 < fxYLoBand) && (fxY2 < fxYLoBand) && (fxY3 < fxYLoBand)))) { lErrCode = EvaluateSpline(ASTATE fxX1, fxY1, fxX2, fxY2, fxX3, fxY3, usScanKind); if (lErrCode != NO_ERR) return lErrCode; } else /* if entirely outside of the band */ { lErrCode = fsc_CheckEndPoint(ASTATE fxX3, fxY3, usScanKind); if (lErrCode != NO_ERR) return lErrCode; } fxX1 = fxX3; /* next oncurve point */ fxY1 = fxY3; } /* test to avoid reading past the end of memory on the last line */ if (pfxXCoord != pfxXStop) { fxX2 = *pfxXCoord; /* next contour point */ fxY2 = *pfxYCoord; byOnCurve = *pbyOnCurve; } } } lErrCode = fsc_EndContourEndpoint(ASTATE usScanKind); if (lErrCode != NO_ERR) return lErrCode; } } lErrCode = fsc_FillBitMap( ASTATE pgbBitMap->pchBitMap, lHiBitBand, lLoBitBand, (int32)pgbBitMap->sRowBytes, lOrgLoBand, usScanKind ); if (lErrCode != NO_ERR) return lErrCode; return NO_ERR; } #ifndef FSCFG_DISABLE_GRAYSCALE /*********************************************************************/ /* This routine scales up an outline for gray scale scan conversion */ /*********************************************************************/ FS_PUBLIC int32 fsc_OverScaleOutline( ContourList* pclContour, /* glyph outline */ uint16 usOverScale /* over scale factor */ ) { uint16 usCont; /* contour index */ int16 sPt; /* point index */ int16 sStart, sEnd; /* start and end point of contours */ int16 sShift; /* for power of two multiply */ F26Dot6 *pfxXCoord, *pfxYCoord; /* for fast point array access */ switch (usOverScale) /* look for power of two */ { case 1: sShift = 0; break; case 2: sShift = 1; break; case 4: sShift = 2; break; case 8: sShift = 3; break; default: sShift = -1; break; } for (usCont = 0; usCont < pclContour->usContourCount; usCont++) { sStart = pclContour->asStartPoint[usCont]; sEnd = pclContour->asEndPoint[usCont]; pfxXCoord = &pclContour->afxXCoord[sStart]; pfxYCoord = &pclContour->afxYCoord[sStart]; if (sShift >= 0) /* if power of two */ { for (sPt = sStart; sPt <= sEnd; sPt++) { *pfxXCoord <<= sShift; pfxXCoord++; *pfxYCoord <<= sShift; pfxYCoord++; } } else /* if not a power of two */ { for (sPt = sStart; sPt <= sEnd; sPt++) { *pfxXCoord *= (int32)usOverScale; pfxXCoord++; *pfxYCoord *= (int32)usOverScale; pfxYCoord++; } } } return NO_ERR; } /*********************************************************************/ /* Gray scale bitmap calculation */ /* Count over scale pixels into gray scale byte array */ /* Be sure that Hi/LoBand are set correctly for both Over & Gray! */ /*********************************************************************/ FS_PUBLIC int32 fsc_CalcGrayMap( GlyphBitMap* pOverGBMap, /* over scaled source */ GlyphBitMap* pGrayGBMap, /* gray scale target */ uint16 usOverScale /* over scale factor */ ) { char *pchOverRow; /* over scaled bitmap row pointer */ char *pchGrayRow; /* gray scale bitmap row pointer */ int16 sVOffset; /* over scaled rows to skip */ int16 sRightPix; /* right edge of used over pix's */ int16 sGrayRow; /* gray scale row loop counter */ uint16 usOverRowCount; /* over scaled row loop counter */ int16 sTotalRowCount; /* over scaled whole band counter */ uint32 ulBytes; /* gray scale count for clear */ int32 lErrCode; /* function return code */ GrayScaleParam GSP; /* param block for CalcGrayRow */ /* checked above */ Assert ((usOverScale == 1) || (usOverScale == 2) || (usOverScale == 4) || (usOverScale == 8)); ulBytes = (uint32)pGrayGBMap->sRowBytes * (uint32)(pGrayGBMap->sHiBand - pGrayGBMap->sLoBand); Assert(((ulBytes >> 2) << 2) == ulBytes); fsc_ScanClearBitMap (ulBytes >> 2, (uint32*)pGrayGBMap->pchBitMap); GSP.usOverScale = usOverScale; GSP.pchOverLo = pOverGBMap->pchBitMap; /* set pointer limits */ GSP.pchOverHi = pOverGBMap->pchBitMap + pOverGBMap->lMMemSize; GSP.pchGrayLo = pGrayGBMap->pchBitMap; /* set pointer limits */ GSP.pchGrayHi = pGrayGBMap->pchBitMap + pGrayGBMap->lMMemSize; pchOverRow = pOverGBMap->pchBitMap; usOverRowCount = usOverScale; sTotalRowCount = pOverGBMap->sHiBand - pOverGBMap->sLoBand; sVOffset = pOverGBMap->sHiBand - usOverScale * pGrayGBMap->sHiBand; if (sVOffset < 0) /* if mapped above over's bitmap */ { usOverRowCount -= (uint16)(-sVOffset); /* correct first band count */ } else { pchOverRow += sVOffset * pOverGBMap->sRowBytes; /* point into bitmap */ sTotalRowCount -= sVOffset; /* adjust for skipped rows */ } sRightPix = pGrayGBMap->rectBounds.right * (int16)usOverScale - pOverGBMap->rectBounds.left; pchOverRow += (sRightPix - 1) >> 3; GSP.usFirstShift = (uint16)(7 - ((sRightPix-1) & 0x0007)); GSP.sGrayCol = pGrayGBMap->rectBounds.right - pGrayGBMap->rectBounds.left; pchGrayRow = pGrayGBMap->pchBitMap + (GSP.sGrayCol - 1); for (sGrayRow = pGrayGBMap->sHiBand - 1; sGrayRow >= pGrayGBMap->sLoBand; sGrayRow--) { GSP.pchGray = pchGrayRow; while ((usOverRowCount > 0) && (sTotalRowCount > 0)) { GSP.pchOver = pchOverRow; lErrCode = fsc_ScanCalcGrayRow( &GSP ); if (lErrCode != NO_ERR) return lErrCode; pchOverRow += pOverGBMap->sRowBytes; usOverRowCount--; sTotalRowCount--; } pchGrayRow += pGrayGBMap->sRowBytes; usOverRowCount = usOverScale; } return NO_ERR; } #else /* if grayscale is disabled */ FS_PUBLIC int32 fsc_OverScaleOutline( ContourList* pclContour, /* glyph outline */ uint16 usOverScale /* over scale factor */ ) { FS_UNUSED_PARAMETER(pclContour); FS_UNUSED_PARAMETER(usOverScale); return BAD_GRAY_LEVEL_ERR; } FS_PUBLIC int32 fsc_CalcGrayMap( GlyphBitMap* pOverGBMap, /* over scaled source */ GlyphBitMap* pGrayGBMap, /* gray scale target */ uint16 usOverScale /* over scale factor */ ) { FS_UNUSED_PARAMETER(pOverGBMap); FS_UNUSED_PARAMETER(pGrayGBMap); FS_UNUSED_PARAMETER(usOverScale); return BAD_GRAY_LEVEL_ERR; } #endif /*********************************************************************/ /* Local Functions */ /*********************************************************************/ /*********************************************************************/ /* This routine examines a glyph contour by contour and calculates */ /* its bounding box. */ /*********************************************************************/ FS_PRIVATE int32 FindExtrema( ContourList* pclContour, /* glyph outline */ GlyphBitMap* pbmpBitMap /* to return bounds */ ) { uint16 usCont; /* contour index */ int16 sPt; /* point index */ int16 sStart, sEnd; /* start and end point of contours */ int32 lMaxX, lMinX; /* for bounding box left, right */ int32 lMaxY, lMinY; /* for bounding box top, bottom */ F26Dot6 *pfxXCoord, *pfxYCoord; /* for fast point array access */ F26Dot6 fxMaxX, fxMinX; /* for bounding box left, right */ F26Dot6 fxMaxY, fxMinY; /* for bounding box top, bottom */ boolean bFirstContour; /* set false after min/max set */ fxMaxX = 0L; /* default bounds limits */ fxMinX = 0L; fxMaxY = 0L; fxMinY = 0L; bFirstContour = TRUE; /* first time only */ for (usCont = 0; usCont < pclContour->usContourCount; usCont++) { sStart = pclContour->asStartPoint[usCont]; sEnd = pclContour->asEndPoint[usCont]; if (sStart == sEnd) { continue; /* for anchor points */ } pfxXCoord = &pclContour->afxXCoord[sStart]; pfxYCoord = &pclContour->afxYCoord[sStart]; if (bFirstContour) { fxMaxX = *pfxXCoord; /* init bounds limits */ fxMinX = *pfxXCoord; fxMaxY = *pfxYCoord; fxMinY = *pfxYCoord; bFirstContour = FALSE; /* just once */ } for (sPt = sStart; sPt <= sEnd; sPt++) /* find the min & max */ { if (*pfxXCoord > fxMaxX) fxMaxX = *pfxXCoord; if (*pfxXCoord < fxMinX) fxMinX = *pfxXCoord; if (*pfxYCoord > fxMaxY) fxMaxY = *pfxYCoord; if (*pfxYCoord < fxMinY) fxMinY = *pfxYCoord; pfxXCoord++; pfxYCoord++; } } pbmpBitMap->fxMinX = fxMinX; /* save full precision bounds */ pbmpBitMap->fxMinY = fxMinY; pbmpBitMap->fxMaxX = fxMaxX; /* save full precision bounds */ pbmpBitMap->fxMaxY = fxMaxY; lMinX = (fxMinX + SUBHALF - 1) >> SUBSHFT; /* pixel black box */ lMinY = (fxMinY + SUBHALF - 1) >> SUBSHFT; lMaxX = (fxMaxX + SUBHALF) >> SUBSHFT; lMaxY = (fxMaxY + SUBHALF) >> SUBSHFT; if ((F26Dot6)(int16)lMinX != lMinX || /* check overflow */ (F26Dot6)(int16)lMinY != lMinY || (F26Dot6)(int16)lMaxX != lMaxX || (F26Dot6)(int16)lMaxY != lMaxY ) { return POINT_MIGRATION_ERR; } pbmpBitMap->bZeroDimension = FALSE; /* assume some size */ if (bFirstContour == FALSE) /* if contours present */ { /* then force a non-zero bitmap */ if (lMinX == lMaxX) { lMaxX++; /* force 1 pixel wide */ pbmpBitMap->bZeroDimension = TRUE; /* flag for filling */ } if (lMinY == lMaxY) { lMaxY++; /* force 1 pixel high */ pbmpBitMap->bZeroDimension = TRUE; /* flag for filling */ } } /* set bitmap structure return values */ pbmpBitMap->rectBounds.left = (int16)lMinX; pbmpBitMap->rectBounds.right = (int16)lMaxX; pbmpBitMap->rectBounds.bottom = (int16)lMinY; pbmpBitMap->rectBounds.top = (int16)lMaxY; return NO_ERR; } /*********************************************************************/ /* This recursive routine subdivides splines that are non-monotonic or */ /* too big into splines that fsc_CalcSpline can handle. It also */ /* filters out degenerate (linear) splines, passing off to fsc_CalcLine. */ FS_PRIVATE int32 EvaluateSpline( PSTATE /* pointer to state vars */ F26Dot6 fxX1, /* start point x coordinate */ F26Dot6 fxY1, /* start point y coordinate */ F26Dot6 fxX2, /* control point x coordinate */ F26Dot6 fxY2, /* control point y coordinate */ F26Dot6 fxX3, /* ending x coordinate */ F26Dot6 fxY3, /* ending y coordinate */ uint16 usScanKind /* scan control type */ ) { F26Dot6 fxDX21, fxDX32, fxDX31; /* delta x's */ F26Dot6 fxDY21, fxDY32, fxDY31; /* delta y's */ F26Dot6 fxDenom; /* ratio denominator */ F26Dot6 fxX4, fxY4; /* first mid point */ F26Dot6 fxX5, fxY5; /* mid mid point */ F26Dot6 fxX6, fxY6; /* second mid point */ F26Dot6 fxX456, fxY456; /* for monotonic subdivision */ F26Dot6 fxAbsDX, fxAbsDY; /* abs of DX31, DY31 */ int32 lErrCode; fxDX21 = fxX2 - fxX1; /* get all four deltas */ fxDX32 = fxX3 - fxX2; fxDY21 = fxY2 - fxY1; fxDY32 = fxY3 - fxY2; /* If spline goes up and down, then subdivide it */ if (((fxDY21 > 0L) && (fxDY32 < 0L)) || ((fxDY21 < 0L) && (fxDY32 > 0L))) { fxDenom = fxDY21 - fxDY32; /* total y span */ fxX4 = fxX1 + LongMulDiv(fxDX21, fxDY21, fxDenom); fxX6 = fxX2 + LongMulDiv(fxDX32, fxDY21, fxDenom); fxX5 = fxX4 + LongMulDiv(fxX6 - fxX4, fxDY21, fxDenom); fxY456 = fxY1 + LongMulDiv(fxDY21, fxDY21, fxDenom); lErrCode = EvaluateSpline(ASTATE fxX1, fxY1, fxX4, fxY456, fxX5, fxY456, usScanKind); if (lErrCode != NO_ERR) return lErrCode; return EvaluateSpline(ASTATE fxX5, fxY456, fxX6, fxY456, fxX3, fxY3, usScanKind); } /* If spline goes left and right, then subdivide it */ if (((fxDX21 > 0L) && (fxDX32 < 0L)) || ((fxDX21 < 0L) && (fxDX32 > 0L))) { fxDenom = fxDX21 - fxDX32; /* total x span */ fxY4 = fxY1 + LongMulDiv(fxDY21, fxDX21, fxDenom); fxY6 = fxY2 + LongMulDiv(fxDY32, fxDX21, fxDenom); fxY5 = fxY4 + LongMulDiv(fxY6 - fxY4, fxDX21, fxDenom); fxX456 = fxX1 + LongMulDiv(fxDX21, fxDX21, fxDenom); lErrCode = EvaluateSpline(ASTATE fxX1, fxY1, fxX456, fxY4, fxX456, fxY5, usScanKind); if (lErrCode != NO_ERR) return lErrCode; return EvaluateSpline(ASTATE fxX456, fxY5, fxX456, fxY6, fxX3, fxY3, usScanKind); } /* By now the spline must be monotonic */ fxDX31 = fxX3 - fxX1; /* check overall size */ fxDY31 = fxY3 - fxY1; fxAbsDX = FXABS(fxDX31); fxAbsDY = FXABS(fxDY31); /* If spline is too big to calculate, then subdivide it */ if ((fxAbsDX > MAXSPLINELENGTH) || (fxAbsDY > MAXSPLINELENGTH)) { fxX4 = (fxX1 + fxX2) >> 1; /* first segment mid point */ fxY4 = (fxY1 + fxY2) >> 1; fxX6 = (fxX2 + fxX3) >> 1; /* second segment mid point */ fxY6 = (fxY2 + fxY3) >> 1; fxX5 = (fxX4 + fxX6) >> 1; /* mid segment mid point */ fxY5 = (fxY4 + fxY6) >> 1; lErrCode = EvaluateSpline(ASTATE fxX1, fxY1, fxX4, fxY4, fxX5, fxY5, usScanKind); if (lErrCode != NO_ERR) return lErrCode; return EvaluateSpline(ASTATE fxX5, fxY5, fxX6, fxY6, fxX3, fxY3, usScanKind); } /* The spline is now montonic and small enough */ lErrCode = fsc_CheckEndPoint(ASTATE fxX3, fxY3, usScanKind); /* first check endpoint */ if (lErrCode != NO_ERR) return lErrCode; if (fxDX21 * fxDY32 == fxDY21 * fxDX32) /* if spline is degenerate (linear) */ { /* treat as a line */ return fsc_CalcLine(ASTATE fxX1, fxY1, fxX3, fxY3, usScanKind); } else { return fsc_CalcSpline(ASTATE fxX1, fxY1, fxX2, fxY2, fxX3, fxY3, usScanKind); } } /*********************************************************************/ /* Return an array of coordinates for outline points */ FS_PUBLIC int32 fsc_GetCoords( ContourList* pclContour, /* glyph outline */ uint16 usPointCount, /* point count */ uint16* pusPointIndex, /* point indices */ PixCoord* ppcCoordinate /* point coordinates */ ) { uint16 usMaxIndex; /* last defined point */ int32 lX; /* integer x coord */ int32 lY; /* integer y coord */ if (pclContour->usContourCount == 0) { return BAD_POINT_INDEX_ERR; /* can't have a point without a contour */ } usMaxIndex = pclContour->asEndPoint[pclContour->usContourCount - 1] + 2; /* allow 2 phantoms */ while (usPointCount > 0) { if (*pusPointIndex > usMaxIndex) { return BAD_POINT_INDEX_ERR; /* beyond the last contour */ } lX = (pclContour->afxXCoord[*pusPointIndex] + SUBHALF) >> SUBSHFT; lY = (pclContour->afxYCoord[*pusPointIndex] + SUBHALF) >> SUBSHFT; if ( ((int32)(int16)lX != lX) || ((int32)(int16)lY != lY) ) { return POINT_MIGRATION_ERR; /* catch overflow */ } ppcCoordinate->x = (int16)lX; ppcCoordinate->y = (int16)lY; pusPointIndex++; ppcCoordinate++; usPointCount--; /* loop through all points */ } return NO_ERR; } /*********************************************************************/
40.873844
136
0.45683
37ca1e74c285afd58469acde12c9a7e680a88ead
48
c
C
test/testFolder/test.c
yanfrimmel/Formattier
69a897baae3ffe8c735f9df9b45ff9c332223e1e
[ "MIT" ]
1
2019-06-28T14:33:49.000Z
2019-06-28T14:33:49.000Z
test/testFolder/test.c
yanfrimmel/CStyler
69a897baae3ffe8c735f9df9b45ff9c332223e1e
[ "MIT" ]
null
null
null
test/testFolder/test.c
yanfrimmel/CStyler
69a897baae3ffe8c735f9df9b45ff9c332223e1e
[ "MIT" ]
null
null
null
#include "game.h" int initialize_sdl(void) { }
9.6
26
0.6875
9b73d4ea8439a80c7b6cb41a3f2c02e59dda9a3b
3,251
c
C
tools/gap8-openocd/src/target/arm_jtag.c
knmcguire/gap_sdk
7b0a09a353ab6f0550793d40bd46e98051f4a3d7
[ "Apache-2.0" ]
2
2021-05-28T08:25:33.000Z
2021-11-17T02:58:50.000Z
tools/gap8-openocd/src/target/arm_jtag.c
knmcguire/gap_sdk
7b0a09a353ab6f0550793d40bd46e98051f4a3d7
[ "Apache-2.0" ]
null
null
null
tools/gap8-openocd/src/target/arm_jtag.c
knmcguire/gap_sdk
7b0a09a353ab6f0550793d40bd46e98051f4a3d7
[ "Apache-2.0" ]
5
2018-05-23T02:56:10.000Z
2021-01-02T16:44:09.000Z
/*************************************************************************** * Copyright (C) 2005 by Dominic Rath * * Dominic.Rath@gmx.de * * * * Copyright (C) 2007,2008 Øyvind Harboe * * oyvind.harboe@zylin.com * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ***************************************************************************/ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "arm_jtag.h" #if 0 #define _ARM_JTAG_SCAN_N_CHECK_ #endif int arm_jtag_set_instr_inner(struct jtag_tap *tap, uint32_t new_instr, void *no_verify_capture, tap_state_t end_state) { struct scan_field field; uint8_t t[4]; field.num_bits = tap->ir_length; field.out_value = t; buf_set_u32(t, 0, field.num_bits, new_instr); field.in_value = NULL; if (no_verify_capture == NULL) jtag_add_ir_scan(tap, &field, end_state); else { /* FIX!!!! this is a kludge!!! arm926ejs.c should reimplement this arm_jtag_set_instr to * have special verification code. */ jtag_add_ir_scan_noverify(tap, &field, end_state); } return ERROR_OK; } int arm_jtag_scann_inner(struct arm_jtag *jtag_info, uint32_t new_scan_chain, tap_state_t end_state) { int retval = ERROR_OK; uint8_t out_value[4]; buf_set_u32(out_value, 0, jtag_info->scann_size, new_scan_chain); struct scan_field field = { .num_bits = jtag_info->scann_size, .out_value = out_value, }; retval = arm_jtag_set_instr(jtag_info->tap, jtag_info->scann_instr, NULL, end_state); if (retval != ERROR_OK) return retval; jtag_add_dr_scan(jtag_info->tap, 1, &field, end_state); jtag_info->cur_scan_chain = new_scan_chain; return retval; } static int arm_jtag_reset_callback(enum jtag_event event, void *priv) { struct arm_jtag *jtag_info = priv; if (event == JTAG_TRST_ASSERTED) jtag_info->cur_scan_chain = 0; return ERROR_OK; } int arm_jtag_setup_connection(struct arm_jtag *jtag_info) { jtag_info->scann_instr = 0x2; jtag_info->cur_scan_chain = 0; jtag_info->intest_instr = 0xc; return jtag_register_event_callback(arm_jtag_reset_callback, jtag_info); }
34.221053
100
0.575515
171b2cb33002c21b2b26bcdc3f3a812ba085580a
2,773
h
C
test/testCommon.h
MarcoCallari/gba-mu
f888884c7abafd6fa35e027be334a6ba36783f5f
[ "MIT" ]
47
2021-12-23T05:22:03.000Z
2022-01-11T10:55:39.000Z
test/testCommon.h
MarcoCallari/gba-mu
f888884c7abafd6fa35e027be334a6ba36783f5f
[ "MIT" ]
5
2021-12-26T10:17:24.000Z
2022-01-01T21:45:42.000Z
test/testCommon.h
MarcoCallari/gba-mu
f888884c7abafd6fa35e027be334a6ba36783f5f
[ "MIT" ]
2
2021-12-26T09:48:49.000Z
2021-12-28T14:08:44.000Z
#include <cstdint> #include <fstream> #include <iostream> #include <iterator> #include <vector> #include <bitset> #include <assert.h> #define ASSERT_EQUAL(message, expected, actual) \ if (expected != actual) { \ DEBUG("ASSERTION FAILED: " << message << \ " expected: " << expected << " != actual: " << actual << \ "\n"); assert(false); } typedef struct cpu_log { uint32_t address; uint32_t instruction; uint32_t cpsr; uint32_t r[16]; uint32_t cycles; } cpu_log_t; std::vector<cpu_log> getLogs(std::string path) { std::ifstream logFile; logFile.open(path); std::string line; std::vector<cpu_log> logs; std::string delimiter = ","; while (std::getline(logFile, line)) { // std::cout << line << std::endl; int currentPos = 0; int nextPos = (line.find(delimiter, currentPos) == std::string::npos) ? line.size() : line.find(delimiter, currentPos); std::string value; cpu_log log; value = line.substr(currentPos, nextPos - currentPos); log.address = std::stoul(value, nullptr, 16); currentPos = nextPos + 1; nextPos = (line.find(delimiter, currentPos) == std::string::npos) ? line.size() : line.find(delimiter, currentPos); value = line.substr(currentPos, nextPos - currentPos); log.instruction = std::stoul(value, nullptr, 16); currentPos = nextPos + 1; nextPos = (line.find(delimiter, currentPos) == std::string::npos) ? line.size() : line.find(delimiter, currentPos); value = line.substr(currentPos, nextPos - currentPos); log.cpsr = std::stoul(value, nullptr, 16); currentPos = nextPos + 1; nextPos = (line.find(delimiter, currentPos) == std::string::npos) ? line.size() : line.find(delimiter, currentPos); for (int i = 0; i < 16; i++) { value = line.substr(currentPos, nextPos - currentPos); log.r[i] = std::stoul(value, nullptr, 16); currentPos = nextPos + 1; nextPos = (line.find(delimiter, currentPos) == std::string::npos) ? line.size() : line.find(delimiter, currentPos); } value = line.substr(currentPos, nextPos - currentPos); log.cycles = std::stoul(value, nullptr, 10); currentPos = nextPos + 1; nextPos = (line.find(delimiter, currentPos) == std::string::npos) ? line.size() : line.find(delimiter, currentPos); logs.push_back(log); } return logs; };
33.817073
77
0.544537
a57c3af765a8369d32901a146dcd1f9b8baf27fc
3,134
h
C
src/server/io_worker.h
ut-osa/nightcore
f041db04bd369d9bd7a617b48892338fc11c090c
[ "Apache-2.0" ]
34
2021-01-18T17:19:11.000Z
2022-03-31T06:48:49.000Z
src/server/io_worker.h
ut-osa/nightcore
f041db04bd369d9bd7a617b48892338fc11c090c
[ "Apache-2.0" ]
5
2021-04-16T05:08:10.000Z
2021-11-15T17:41:01.000Z
src/server/io_worker.h
ut-osa/nightcore
f041db04bd369d9bd7a617b48892338fc11c090c
[ "Apache-2.0" ]
7
2021-01-28T02:16:25.000Z
2022-01-23T00:37:50.000Z
#pragma once #include "base/common.h" #include "base/thread.h" #include "common/uv.h" #include "common/stat.h" #include "utils/buffer_pool.h" #include "utils/object_pool.h" #include "server/connection_base.h" namespace faas { namespace server { class IOWorker final : public uv::Base { public: IOWorker(std::string_view worker_name, size_t read_buffer_size, size_t write_buffer_size); ~IOWorker(); std::string_view worker_name() const { return worker_name_; } // Return current IOWorker within event loop thread static IOWorker* current() { return current_; } void Start(int pipe_to_server_fd); void ScheduleStop(); void WaitForFinish(); // Called by Connection for ONLY once void OnConnectionClose(ConnectionBase* connection); // Can only be called from uv_loop_ void NewReadBuffer(size_t suggested_size, uv_buf_t* buf); void ReturnReadBuffer(const uv_buf_t* buf); void NewWriteBuffer(uv_buf_t* buf); void ReturnWriteBuffer(char* buf); uv_write_t* NewWriteRequest(); void ReturnWriteRequest(uv_write_t* write_req); // Pick a connection of given type managed by this IOWorker ConnectionBase* PickConnection(int type); // Schedule a function to run on this IO worker's event loop // thread. It can be called safely from other threads. // When the function is ready to run, IO worker will check if its // owner connection is still active, and will not run the function // if it is closed. void ScheduleFunction(ConnectionBase* owner, std::function<void()> fn); private: enum State { kCreated, kRunning, kStopping, kStopped }; std::string worker_name_; std::atomic<State> state_; static thread_local IOWorker* current_; std::string log_header_; uv_loop_t uv_loop_; uv_async_t stop_event_; uv_pipe_t pipe_to_server_; uv_async_t run_fn_event_; base::Thread event_loop_thread_; absl::flat_hash_map</* id */ int, ConnectionBase*> connections_; absl::flat_hash_map</* type */ int, absl::flat_hash_set</* id */ int>> connections_by_type_; absl::flat_hash_map</* type */ int, std::vector<ConnectionBase*>> connections_for_pick_; absl::flat_hash_map</* type */ int, size_t> connections_for_pick_rr_; utils::BufferPool read_buffer_pool_; utils::BufferPool write_buffer_pool_; utils::SimpleObjectPool<uv_write_t> write_req_pool_; int connections_on_closing_; struct ScheduledFunction { int owner_id; std::function<void()> fn; }; absl::Mutex scheduled_function_mu_; absl::InlinedVector<std::unique_ptr<ScheduledFunction>, 16> scheduled_functions_ ABSL_GUARDED_BY(scheduled_function_mu_); std::atomic<int64_t> async_event_recv_timestamp_; stat::StatisticsCollector<int32_t> uv_async_delay_stat_; void EventLoopThreadMain(); DECLARE_UV_ASYNC_CB_FOR_CLASS(Stop); DECLARE_UV_READ_CB_FOR_CLASS(NewConnection); DECLARE_UV_WRITE_CB_FOR_CLASS(PipeWrite); DECLARE_UV_ASYNC_CB_FOR_CLASS(RunScheduledFunctions); DISALLOW_COPY_AND_ASSIGN(IOWorker); }; } // namespace server } // namespace faas
32.989474
96
0.73261
cbeb874e392659ce0b0e0748d2be4668e52fe1f0
4,534
h
C
src/analyzer/protocol/login/Rlogin.h
hugolin615/zeek-4.0.0-ele420520-spring2021
258e9b2ee1f2a4bd45c6332a75304793b7d44d40
[ "Apache-2.0" ]
null
null
null
src/analyzer/protocol/login/Rlogin.h
hugolin615/zeek-4.0.0-ele420520-spring2021
258e9b2ee1f2a4bd45c6332a75304793b7d44d40
[ "Apache-2.0" ]
null
null
null
src/analyzer/protocol/login/Rlogin.h
hugolin615/zeek-4.0.0-ele420520-spring2021
258e9b2ee1f2a4bd45c6332a75304793b7d44d40
[ "Apache-2.0" ]
null
null
null
// See the file "COPYING" in the main distribution directory for copyright. #pragma once #include "zeek/analyzer/protocol/login/Login.h" #include "zeek/analyzer/protocol/tcp/ContentLine.h" ZEEK_FORWARD_DECLARE_NAMESPACED(Rlogin_Analyzer, zeek, analyzer::login); namespace zeek::analyzer::login { enum rlogin_state { RLOGIN_FIRST_NULL, // waiting to see first NUL RLOGIN_CLIENT_USER_NAME, // scanning client user name up to NUL RLOGIN_SERVER_USER_NAME, // scanning server user name up to NUL RLOGIN_TERMINAL_TYPE, // scanning terminal type & speed RLOGIN_SERVER_ACK, // waiting to see NUL from server to ack client RLOGIN_IN_BAND_CONTROL_FF2, // waiting to see the second FF RLOGIN_WINDOW_CHANGE_S1, // waiting to see the first 's' RLOGIN_WINDOW_CHANGE_S2, // waiting to see the second 's' RLOGIN_WINDOW_CHANGE_REMAINDER, // remaining "bytes_to_scan" bytes RLOGIN_LINE_MODE, // switch to line-oriented processing RLOGIN_PRESUMED_REJECTED, // apparently server said No Way RLOGIN_UNKNOWN, // we don't know what state we're in }; class Contents_Rlogin_Analyzer final : public analyzer::tcp::ContentLine_Analyzer { public: Contents_Rlogin_Analyzer(Connection* conn, bool orig, Rlogin_Analyzer* analyzer); ~Contents_Rlogin_Analyzer() override; void SetPeer(Contents_Rlogin_Analyzer* arg_peer) { peer = arg_peer; } rlogin_state RloginState() const { return state; } protected: void DoDeliver(int len, const u_char* data) override; void BadProlog(); rlogin_state state, save_state; int num_bytes_to_scan; Contents_Rlogin_Analyzer* peer; Rlogin_Analyzer* analyzer; }; class Rlogin_Analyzer final : public Login_Analyzer { public: explicit Rlogin_Analyzer(Connection* conn); void ClientUserName(const char* s); void ServerUserName(const char* s); void TerminalType(const char* s); static analyzer::Analyzer* Instantiate(Connection* conn) { return new Rlogin_Analyzer(conn); } }; } // namespace zeek::analyzer::login namespace analyzer::login { using rlogin_state [[deprecated("Remove in v4.1. Use zeek::analyzer::login::rlogin_state.")]] = zeek::analyzer::login::rlogin_state; constexpr auto RLOGIN_FIRST_NULL [[deprecated("Remove in v4.1. Use zeek::analyzer::login::RLOGIN_FIRST_NULL.")]] = zeek::analyzer::login::RLOGIN_FIRST_NULL; constexpr auto RLOGIN_CLIENT_USER_NAME [[deprecated("Remove in v4.1. Use zeek::analyzer::login::RLOGIN_CLIENT_USER_NAME.")]] = zeek::analyzer::login::RLOGIN_CLIENT_USER_NAME; constexpr auto RLOGIN_SERVER_USER_NAME [[deprecated("Remove in v4.1. Use zeek::analyzer::login::RLOGIN_SERVER_USER_NAME.")]] = zeek::analyzer::login::RLOGIN_SERVER_USER_NAME; constexpr auto RLOGIN_TERMINAL_TYPE [[deprecated("Remove in v4.1. Use zeek::analyzer::login::RLOGIN_TERMINAL_TYPE.")]] = zeek::analyzer::login::RLOGIN_TERMINAL_TYPE; constexpr auto RLOGIN_SERVER_ACK [[deprecated("Remove in v4.1. Use zeek::analyzer::login::RLOGIN_SERVER_ACK.")]] = zeek::analyzer::login::RLOGIN_SERVER_ACK; constexpr auto RLOGIN_IN_BAND_CONTROL_FF2 [[deprecated("Remove in v4.1. Use zeek::analyzer::login::RLOGIN_IN_BAND_CONTROL_FF2.")]] = zeek::analyzer::login::RLOGIN_IN_BAND_CONTROL_FF2; constexpr auto RLOGIN_WINDOW_CHANGE_S1 [[deprecated("Remove in v4.1. Use zeek::analyzer::login::RLOGIN_WINDOW_CHANGE_S1.")]] = zeek::analyzer::login::RLOGIN_WINDOW_CHANGE_S1; constexpr auto RLOGIN_WINDOW_CHANGE_S2 [[deprecated("Remove in v4.1. Use zeek::analyzer::login::RLOGIN_WINDOW_CHANGE_S2.")]] = zeek::analyzer::login::RLOGIN_WINDOW_CHANGE_S2; constexpr auto RLOGIN_WINDOW_CHANGE_REMAINDER [[deprecated("Remove in v4.1. Use zeek::analyzer::login::RLOGIN_WINDOW_CHANGE_REMAINDER.")]] = zeek::analyzer::login::RLOGIN_WINDOW_CHANGE_REMAINDER; constexpr auto RLOGIN_LINE_MODE [[deprecated("Remove in v4.1. Use zeek::analyzer::login::RLOGIN_LINE_MODE.")]] = zeek::analyzer::login::RLOGIN_LINE_MODE; constexpr auto RLOGIN_PRESUMED_REJECTED [[deprecated("Remove in v4.1. Use zeek::analyzer::login::RLOGIN_PRESUMED_REJECTED.")]] = zeek::analyzer::login::RLOGIN_PRESUMED_REJECTED; constexpr auto RLOGIN_UNKNOWN [[deprecated("Remove in v4.1. Use zeek::analyzer::login::RLOGIN_UNKNOWN.")]] = zeek::analyzer::login::RLOGIN_UNKNOWN; using Contents_Rlogin_Analyzer [[deprecated("Remove in v4.1. Use zeek::analyzer::login::Contents_Rlogin_Analyzer.")]] = zeek::analyzer::login::Contents_Rlogin_Analyzer; using Rlogin_Analyzer [[deprecated("Remove in v4.1. Use zeek::analyzer::login::Rlogin_Analyzer.")]] = zeek::analyzer::login::Rlogin_Analyzer; } // namespace analyzer::login
50.377778
195
0.779224
48c43416bdfa2ea1833d44cd0e120d08603791fb
14,632
c
C
pg_reset_page_lsn.c
mikecaat/pg_reset_page_lsn
b9389a3478af5cd2a5feea6ecc9b73ac018b95cf
[ "PostgreSQL", "MIT" ]
null
null
null
pg_reset_page_lsn.c
mikecaat/pg_reset_page_lsn
b9389a3478af5cd2a5feea6ecc9b73ac018b95cf
[ "PostgreSQL", "MIT" ]
null
null
null
pg_reset_page_lsn.c
mikecaat/pg_reset_page_lsn
b9389a3478af5cd2a5feea6ecc9b73ac018b95cf
[ "PostgreSQL", "MIT" ]
1
2021-03-20T16:44:47.000Z
2021-03-20T16:44:47.000Z
#include "postgres_fe.h" #include <dirent.h> #include <sys/stat.h> #include <time.h> #include "access/xlog_internal.h" #include "common/file_utils.h" #include "common/logging.h" #include "getopt_long.h" #include "storage/bufpage.h" #include "storage/checksum.h" #include "storage/checksum_impl.h" static const char *progname; static XLogRecPtr lsn = InvalidXLogRecPtr; static bool data_checksums = false; static bool do_sync = true; static bool showprogress = false; static int64 files = 0; static int64 blocks = 0; /* database cluster is specified as a target directory to scan? */ static bool pgdata_mode = false; static XLogRecPtr pg_lsn_in_internal(const char *str, bool *have_error); static int64 scan_directory(const char *basedir, const char *subdir, bool sizeonly); static void scan_file(const char *fn, BlockNumber segmentno); static int64 scan_pgdata(const char *basedir, bool sizeonly); static void validate_datadir(const char *datadir); static bool skipfile(const char *fn); static void progress_report(bool finished); /* * Progress status information. */ int64 total_size = 0; int64 current_size = 0; static pg_time_t last_progress_report = 0; static void usage(void) { printf(_("%s resets LSN of every pages in relation files.\n\n"), progname); printf(_("Usage:\n")); printf(_(" %s [OPTION]...\n"), progname); printf(_("\nOptions:\n")); printf(_(" -D, --directory=DIR database directory to find relation files\n")); printf(_(" -l, --lsn=LSN reset LSN in relation pages\n")); printf(_(" -k, --data-checksums update checksums in relation pages\n")); printf(_(" -N, --no-sync do not wait for changes to be written safely to disk\n")); printf(_(" -P, --progress show progress information\n")); printf(_(" -V, --version output version information, then exit\n")); printf(_(" -?, --help show this help, then exit\n")); } /* * Copy-and-paste from src/backend/utils/adt/pg_lsn.c */ static XLogRecPtr pg_lsn_in_internal(const char *str, bool *have_error) { #define MAXPG_LSNCOMPONENT 8 int len1, len2; uint32 id, off; XLogRecPtr result; Assert(have_error != NULL); *have_error = false; /* Sanity check input format. */ len1 = strspn(str, "0123456789abcdefABCDEF"); if (len1 < 1 || len1 > MAXPG_LSNCOMPONENT || str[len1] != '/') { *have_error = true; return InvalidXLogRecPtr; } len2 = strspn(str + len1 + 1, "0123456789abcdefABCDEF"); if (len2 < 1 || len2 > MAXPG_LSNCOMPONENT || str[len1 + 1 + len2] != '\0') { *have_error = true; return InvalidXLogRecPtr; } /* Decode result. */ id = (uint32) strtoul(str, NULL, 16); off = (uint32) strtoul(str + len1 + 1, NULL, 16); result = ((uint64) id << 32) | off; return result; } static int64 scan_directory(const char *basedir, const char *subdir, bool sizeonly) { /* Copy and paste from src/include/storage/fd.h */ #define PG_TEMP_FILES_DIR "pgsql_tmp" #define PG_TEMP_FILE_PREFIX "pgsql_tmp" int64 dirsize = 0; char path[MAXPGPATH]; bool path_is_symlink = false; DIR *dir; struct dirent *de; struct stat st; if (subdir == NULL) strncpy(path, basedir, sizeof(path)); else snprintf(path, sizeof(path), "%s/%s", basedir, subdir); /* Check if the current path indicates a symlink or not */ #ifndef WIN32 if (lstat(path, &st) < 0) { pg_log_error("could not stat directory \"%s\": %m", path); exit(1); } else if (S_ISLNK(st.st_mode)) path_is_symlink = true; #else if (pgwin32_is_junction(path)) path_is_symlink = true; #endif dir = opendir(path); if (!dir) { pg_log_error("could not open directory \"%s\": %m", path); exit(1); } while ((de = readdir(dir)) != NULL) { char fn[MAXPGPATH]; if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0) continue; /* Skip temporary files */ if (strncmp(de->d_name, PG_TEMP_FILE_PREFIX, strlen(PG_TEMP_FILE_PREFIX)) == 0) continue; /* Skip temporary folders */ if (strncmp(de->d_name, PG_TEMP_FILES_DIR, strlen(PG_TEMP_FILES_DIR)) == 0) continue; snprintf(fn, sizeof(fn), "%s/%s", path, de->d_name); if (lstat(fn, &st) < 0) { pg_log_error("could not stat file \"%s\": %m", fn); exit(1); } if (S_ISREG(st.st_mode)) { char fnonly[MAXPGPATH]; char *segmentpath; BlockNumber segmentno = 0; if (skipfile(de->d_name)) continue; /* * Cut off at the segment boundary (".") to get the segment number * in order to mix it into the checksum. */ if (data_checksums) { strlcpy(fnonly, de->d_name, sizeof(fnonly)); segmentpath = strchr(fnonly, '.'); if (segmentpath != NULL) { *segmentpath++ = '\0'; segmentno = atoi(segmentpath); if (segmentno == 0) { pg_log_error("invalid segment number %d in file name \"%s\"", segmentno, fn); exit(1); } } } dirsize += st.st_size; /* * No need to work on the file when calculating only the size of * the items in the data folder. */ if (!sizeonly) scan_file(fn, segmentno); } #ifndef WIN32 else if (S_ISDIR(st.st_mode) || S_ISLNK(st.st_mode)) #else else if (S_ISDIR(st.st_mode) || pgwin32_is_junction(fn)) #endif { /* * If going through the entries of pg_tblspc, we assume to operate * on tablespace locations where only TABLESPACE_VERSION_DIRECTORY * is valid, resolving the linked locations and dive into them * directly. */ if (subdir != NULL && strncmp("pg_tblspc", subdir, strlen("pg_tblspc")) == 0) { char tblspc_path[MAXPGPATH]; struct stat tblspc_st; /* * Resolve tablespace location path and check whether * TABLESPACE_VERSION_DIRECTORY exists. Not finding a valid * location is unexpected, since there should be no orphaned * links and no links pointing to something else than a * directory. */ snprintf(tblspc_path, sizeof(tblspc_path), "%s/%s/%s", path, de->d_name, TABLESPACE_VERSION_DIRECTORY); if (lstat(tblspc_path, &tblspc_st) < 0) { pg_log_error("could not stat file \"%s\": %m", tblspc_path); exit(1); } /* Looks like a valid tablespace location */ dirsize += scan_directory(fn, TABLESPACE_VERSION_DIRECTORY, sizeonly); /* * Issue fsync recursively on the tablespace location and * all its contents if requested. This is required here * because fsync_dir_recurse() that will be called at the end * of this program skips symlinks. But we don't need to do * that if we're scanning database cluster because * fsync_pgdata() will be called later. */ if (do_sync && path_is_symlink && !pgdata_mode) fsync_dir_recurse(tblspc_path); } else { dirsize += scan_directory(path, de->d_name, sizeonly); if (do_sync && path_is_symlink && !pgdata_mode) fsync_dir_recurse(fn); } } } closedir(dir); return dirsize; } static void scan_file(const char *fn, BlockNumber segmentno) { PGAlignedBlock buf; PageHeader header = (PageHeader) buf.data; int f; BlockNumber blockno; f = open(fn, PG_BINARY | O_RDWR, 0); if (f < 0) { pg_log_error("could not open file \"%s\": %m", fn); exit(1); } files++; for (blockno = 0;; blockno++) { int r = read(f, buf.data, BLCKSZ); int w; if (r == 0) break; if (r != BLCKSZ) { if (r < 0) pg_log_error("could not read block %u in file \"%s\": %m", blockno, fn); else pg_log_error("could not read block %u in file \"%s\": read %d of %d", blockno, fn, r, BLCKSZ); exit(1); } current_size += r; blocks++; /* New pages have no page lsn yet */ if (PageIsNew(header)) continue; /* Set page LSN in page header */ PageSetLSN(buf.data, lsn); /* Set checksum in page header if requested */ if (data_checksums) { header->pd_checksum = pg_checksum_page(buf.data, blockno + segmentno * RELSEG_SIZE); } /* Seek back to beginning of block */ if (lseek(f, -BLCKSZ, SEEK_CUR) < 0) { pg_log_error("seek failed for block %u in file \"%s\": %m", blockno, fn); exit(1); } /* Write block with new LSN */ w = write(f, buf.data, BLCKSZ); if (w != BLCKSZ) { if (w < 0) pg_log_error("could not write block %u in file \"%s\": %m", blockno, fn); else pg_log_error("could not write block %u in file \"%s\": wrote %d of %d", blockno, fn, w, BLCKSZ); exit(1); } if (showprogress) progress_report(false); } close(f); } /* Subdirectories under PGDATA to scan */ static const char *const pgdata_subdirs[] = {"base", "global", "pg_tblspc"}; static int64 scan_pgdata(const char *basedir, bool sizeonly) { int64 dirsize = 0; int i; for (i = 0; i < lengthof(pgdata_subdirs); i++) dirsize += scan_directory(basedir, pgdata_subdirs[i], sizeonly); return dirsize; } static void validate_datadir(const char *datadir) { struct stat st; int i; /* Does the database directory to scan exist? */ if (lstat(datadir, &st) < 0) { if (errno == ENOENT) pg_log_error("directory \"%s\" does not exist", datadir); else pg_log_error("could not stat directory \"%s\": %m", datadir); exit(1); } /* Check whether database directory to scan is database cluster */ pgdata_mode = true; for (i = 0; i < lengthof(pgdata_subdirs); i++) { char path[MAXPGPATH]; snprintf(path, sizeof(path), "%s/%s", datadir, pgdata_subdirs[i]); if (lstat(path, &st) < 0) { pgdata_mode = false; break; } } } /* Copy and paste from src/bin/pg_checksums/pg_checksums.c */ struct exclude_list_item { const char *name; bool match_prefix; }; static const struct exclude_list_item skip[] = { {"pg_control", false}, {"pg_filenode.map", false}, {"pg_internal.init", true}, {"PG_VERSION", false}, #ifdef EXEC_BACKEND {"config_exec_params", true}, #endif {NULL, false} }; static bool skipfile(const char *fn) { int excludeIdx; for (excludeIdx = 0; skip[excludeIdx].name != NULL; excludeIdx++) { int cmplen = strlen(skip[excludeIdx].name); if (!skip[excludeIdx].match_prefix) cmplen++; if (strncmp(skip[excludeIdx].name, fn, cmplen) == 0) return true; } return false; } /* * Report current progress status. * Copy and paste from src/bin/pg_checksums/pg_checksums.c. */ static void progress_report(bool finished) { int percent; char total_size_str[32]; char current_size_str[32]; pg_time_t now; Assert(showprogress); now = time(NULL); if (now == last_progress_report && !finished) return; /* Max once per second */ /* Save current time */ last_progress_report = now; /* Adjust total size if current_size is larger */ if (current_size > total_size) total_size = current_size; /* Calculate current percentage of size done */ percent = total_size ? (int) ((current_size) * 100 / total_size) : 0; /* * Separate step to keep platform-dependent format code out of * translatable strings. And we only test for INT64_FORMAT availability * in snprintf, not fprintf. */ snprintf(total_size_str, sizeof(total_size_str), INT64_FORMAT, total_size / (1024 * 1024)); snprintf(current_size_str, sizeof(current_size_str), INT64_FORMAT, current_size / (1024 * 1024)); fprintf(stderr, _("%*s/%s MB (%d%%) computed"), (int) strlen(current_size_str), current_size_str, total_size_str, percent); /* * Stay on the same line if reporting to a terminal and we're not done * yet. */ fputc((!finished && isatty(fileno(stderr))) ? '\r' : '\n', stderr); } int main(int argc, char *argv[]) { static struct option long_options[] = { {"directory", required_argument, NULL, 'D'}, {"lsn", required_argument, NULL, 'l'}, {"data-checksums", no_argument, NULL, 'k'}, {"no-sync", no_argument, NULL, 'N'}, {"progress", no_argument, NULL, 'P'}, {NULL, 0, NULL, 0} }; int c; int option_index; char *datadir = NULL; char *lsn_str = NULL; bool have_error = false; pg_logging_init(argv[0]); set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_reset_page_lsn")); progname = get_progname(argv[0]); if (argc > 1) { if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0) { usage(); exit(0); } if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0) { puts("pg_reset_page_lsn (PostgreSQL) " PG_VERSION); exit(0); } } while ((c = getopt_long(argc, argv, "D:l:kNP", long_options, &option_index)) != -1) { switch (c) { case 'D': datadir = pg_strdup(optarg); break; case 'l': lsn_str = pg_strdup(optarg); break; case 'k': data_checksums = true; break; case 'N': do_sync = false; break; case 'P': showprogress = true; break; default: fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname); exit(1); } } /* Complain if any arguments remain */ if (optind < argc) { pg_log_error("too many command-line arguments (first is \"%s\")", argv[optind]); fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname); exit(1); } /* * Required arguments */ if (datadir == NULL) { pg_log_error("no database directory specified"); fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname); exit(1); } if (lsn_str == NULL) { pg_log_error("no LSN specified"); fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname); exit(1); } /* Validate input LSN */ lsn = pg_lsn_in_internal(lsn_str, &have_error); if (have_error) { pg_log_error("invalid argument for option %s", "-l"); fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname); exit(1); } canonicalize_path(datadir); validate_datadir(datadir); /* * If progress status information is requested, we need to scan the * directory tree twice: once to know how much total data needs to be * processed and once to do the real work. */ if (pgdata_mode) { if (showprogress) total_size = scan_pgdata(datadir, true); (void) scan_pgdata(datadir, false); } else { if (showprogress) total_size = scan_directory(datadir, NULL, true); (void) scan_directory(datadir, NULL, false); } if (showprogress) progress_report(true); /* Make the data durable on disk */ if (do_sync) { if (pgdata_mode) fsync_pgdata(datadir, PG_VERSION_NUM); else fsync_dir_recurse(datadir); } printf(_("Operation completed\n")); printf(_("Files scanned: %s\n"), psprintf(INT64_FORMAT, files)); printf(_("Blocks scanned: %s\n"), psprintf(INT64_FORMAT, blocks)); return 0; }
23.638126
96
0.644478