blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
3042f568bd0b790e48d559955909163f04c7d076
0b358a0d64eb03655c030b36c0ae87880b153951
/mmcv-1.4.7/mmcv/ops/csrc/tensorrt/trt_roi_align.hpp
5677af90b062ab259f084511e49e2a562a2017bc
[ "Apache-2.0" ]
permissive
jshilong/DDQ
db05ff309d63316c62faa59b28c66d65eef973d1
de9331e4579aaafab4d69e3a9a3c6638efc5392c
refs/heads/main
2023-06-03T15:02:09.949907
2023-05-24T03:32:12
2023-05-24T03:32:12
498,974,099
199
6
Apache-2.0
2022-06-02T05:01:53
2022-06-02T03:10:25
null
UTF-8
C++
false
false
3,952
hpp
#ifndef TRT_ROI_ALIGN_HPP #define TRT_ROI_ALIGN_HPP #include <cublas_v2.h> #include <memory> #include <string> #include <vector> #include "trt_plugin_helper.hpp" class RoIAlignPluginDynamic : public nvinfer1::IPluginV2DynamicExt { public: RoIAlignPluginDynamic(const std::string &name, int outWidth, int outHeight, float spatialScale, int sampleRatio, int poolMode, bool aligned); RoIAlignPluginDynamic(const std::string name, const void *data, size_t length); RoIAlignPluginDynamic() = delete; // IPluginV2DynamicExt Methods nvinfer1::IPluginV2DynamicExt *clone() const override; nvinfer1::DimsExprs getOutputDimensions( int outputIndex, const nvinfer1::DimsExprs *inputs, int nbInputs, nvinfer1::IExprBuilder &exprBuilder) override; bool supportsFormatCombination(int pos, const nvinfer1::PluginTensorDesc *inOut, int nbInputs, int nbOutputs) override; void configurePlugin(const nvinfer1::DynamicPluginTensorDesc *in, int nbInputs, const nvinfer1::DynamicPluginTensorDesc *out, int nbOutputs) override; size_t getWorkspaceSize(const nvinfer1::PluginTensorDesc *inputs, int nbInputs, const nvinfer1::PluginTensorDesc *outputs, int nbOutputs) const override; int enqueue(const nvinfer1::PluginTensorDesc *inputDesc, const nvinfer1::PluginTensorDesc *outputDesc, const void *const *inputs, void *const *outputs, void *workspace, cudaStream_t stream) override; // IPluginV2Ext Methods nvinfer1::DataType getOutputDataType(int index, const nvinfer1::DataType *inputTypes, int nbInputs) const override; // IPluginV2 Methods const char *getPluginType() const override; const char *getPluginVersion() const override; int getNbOutputs() const override; int initialize() override; void terminate() override; size_t getSerializationSize() const override; void serialize(void *buffer) const override; void destroy() override; void setPluginNamespace(const char *pluginNamespace) override; const char *getPluginNamespace() const override; private: const std::string mLayerName; std::string mNamespace; int mOutWidth; int mOutHeight; float mSpatialScale; int mSampleRatio; int mPoolMode; // 1:avg 0:max bool mAligned; protected: // To prevent compiler warnings. using nvinfer1::IPluginV2DynamicExt::canBroadcastInputAcrossBatch; using nvinfer1::IPluginV2DynamicExt::configurePlugin; using nvinfer1::IPluginV2DynamicExt::enqueue; using nvinfer1::IPluginV2DynamicExt::getOutputDimensions; using nvinfer1::IPluginV2DynamicExt::getWorkspaceSize; using nvinfer1::IPluginV2DynamicExt::isOutputBroadcastAcrossBatch; using nvinfer1::IPluginV2DynamicExt::supportsFormat; }; class RoIAlignPluginDynamicCreator : public nvinfer1::IPluginCreator { public: RoIAlignPluginDynamicCreator(); const char *getPluginName() const override; const char *getPluginVersion() const override; const nvinfer1::PluginFieldCollection *getFieldNames() override; nvinfer1::IPluginV2 *createPlugin( const char *name, const nvinfer1::PluginFieldCollection *fc) override; nvinfer1::IPluginV2 *deserializePlugin(const char *name, const void *serialData, size_t serialLength) override; void setPluginNamespace(const char *pluginNamespace) override; const char *getPluginNamespace() const override; private: static nvinfer1::PluginFieldCollection mFC; static std::vector<nvinfer1::PluginField> mPluginAttributes; std::string mNamespace; }; #endif // TRT_ROI_ALIGN_HPP
[ "2392587229zsl@gmail.com" ]
2392587229zsl@gmail.com
64fdeb8ad125dd471236b99c8793b5607e59a3cf
99429b57b38ac1a6c78c276278fd45730b6b55a3
/main.h
5d037b4ac8f6256581165306c07e18608aa58e01
[]
no_license
wie-l/bomberman_v2
66d32232e74b8716edb5292de80621e04b429fd9
181c4a06bfb1c2daec30938dea9248c63498fc0c
refs/heads/main
2023-01-08T10:45:43.305633
2020-11-04T18:10:46
2020-11-04T18:10:46
310,028,336
0
0
null
null
null
null
UTF-8
C++
false
false
26
h
 #include <iostream>
[ "noreply@github.com" ]
noreply@github.com
e7323738d3e64a32bf63749dc458869fc08cbb75
667441fdca2e9accd1b59eccdb06be592db695ee
/src/hir_typeck/monomorph_state.hpp
f136139643d2af744c153e6dab683a97c3fefb46
[ "MIT" ]
permissive
arlosi/mrustc
6b398cbc551b5c5b3eb21561cfb813b4f4c96b1c
b151c9aaafcf476b85af7d96b50e3e2ac0df646e
refs/heads/master
2022-10-04T12:20:27.431675
2021-06-26T06:50:55
2021-06-26T06:50:55
222,812,916
0
0
MIT
2019-11-19T23:57:13
2019-11-19T23:57:12
null
UTF-8
C++
false
false
64
hpp
/// #pragma once #include <hir/type.hpp> #include <hir/path.hpp>
[ "tpg@mutabah.net" ]
tpg@mutabah.net
96c5fe9f7cdaf851add2c153c24a1e34fbf6e0f2
689f1162f3142717db2ffcc16f1ff69d6558790b
/TickTest_Overflow/TickTest_Overflow/StudyUnitClass.h
d60d051a51b929cb015e9653d686560e58b1ef09
[]
no_license
sed0h/cppExercise
e01d277be636b8b19db9f2e40c7131fcad11da8d
f3723be421331011441a735ad41432e23568d6d6
refs/heads/master
2023-06-05T16:47:48.902386
2021-06-25T15:17:14
2021-06-25T15:17:14
299,837,874
0
0
null
null
null
null
UTF-8
C++
false
false
82
h
#pragma once class StudyUnitClass { public: StudyUnitClass(); int OutPut(); };
[ "zhangguangtao@e-planet.cn" ]
zhangguangtao@e-planet.cn
c5b2cf99c670d88048cd92618736b36b2e85a12e
b7f3edb5b7c62174bed808079c3b21fb9ea51d52
/gpu/ipc/service/gpu_channel_test_common.h
504a47204577cefaa1dc0fda5531a84cb49f06e5
[ "BSD-3-Clause" ]
permissive
otcshare/chromium-src
26a7372773b53b236784c51677c566dc0ad839e4
64bee65c921db7e78e25d08f1e98da2668b57be5
refs/heads/webml
2023-03-21T03:20:15.377034
2020-11-16T01:40:14
2020-11-16T01:40:14
209,262,645
18
21
BSD-3-Clause
2023-03-23T06:20:07
2019-09-18T08:52:07
null
UTF-8
C++
false
false
2,484
h
// Copyright (c) 2015 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 GPU_IPC_SERVICE_GPU_CHANNEL_TEST_COMMON_H_ #define GPU_IPC_SERVICE_GPU_CHANNEL_TEST_COMMON_H_ #include <memory> #include <vector> #include "base/memory/ref_counted.h" #include "base/memory/unsafe_shared_memory_region.h" #include "ipc/ipc_test_sink.h" #include "testing/gtest/include/gtest/gtest.h" namespace base { class TestSimpleTaskRunner; namespace test { class ScopedFeatureList; } // namespace test namespace trace_event { class MemoryDumpManager; } // namespace trace_event } // namespace base namespace IPC { class Message; } // namespace IPC namespace gpu { class GpuChannel; class GpuChannelManager; class Scheduler; class SyncPointManager; class SharedImageManager; class TestGpuChannelManagerDelegate; class GpuChannelTestCommon : public testing::Test { public: explicit GpuChannelTestCommon(bool use_stub_bindings); // Constructor which allows a custom set of GPU driver bug workarounds. GpuChannelTestCommon(std::vector<int32_t> enabled_workarounds, bool use_stub_bindings); ~GpuChannelTestCommon() override; protected: Scheduler* scheduler() const { return scheduler_.get(); } GpuChannelManager* channel_manager() const { return channel_manager_.get(); } base::TestSimpleTaskRunner* task_runner() const { return task_runner_.get(); } base::TestSimpleTaskRunner* io_task_runner() const { return io_task_runner_.get(); } GpuChannel* CreateChannel(int32_t client_id, bool is_gpu_host); void HandleMessage(GpuChannel* channel, IPC::Message* msg); base::UnsafeSharedMemoryRegion GetSharedMemoryRegion(); private: std::unique_ptr<base::trace_event::MemoryDumpManager> memory_dump_manager_; IPC::TestSink sink_; scoped_refptr<base::TestSimpleTaskRunner> task_runner_; scoped_refptr<base::TestSimpleTaskRunner> io_task_runner_; std::unique_ptr<SyncPointManager> sync_point_manager_; std::unique_ptr<SharedImageManager> shared_image_manager_; std::unique_ptr<Scheduler> scheduler_; std::unique_ptr<TestGpuChannelManagerDelegate> channel_manager_delegate_; std::unique_ptr<base::test::ScopedFeatureList> scoped_feature_list_; std::unique_ptr<GpuChannelManager> channel_manager_; DISALLOW_COPY_AND_ASSIGN(GpuChannelTestCommon); }; } // namespace gpu #endif // GPU_IPC_SERVICE_GPU_CHANNEL_TEST_COMMON_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
cadbbfd0720c74c6dbd9fb7cd9b419a9f0c4fd89
1ea4ac794c9c52582f182d609194566472dac792
/src/plugins/anim/datatypes/constraints.cpp
f4100f8355daba103cd522e51f8286dc0b55dc8d
[ "MIT" ]
permissive
Pinyupen/possumwood
1b3a95b00c3fecca669645eeb8f63f71e9e57458
0ee3e0fe13ef27cf14795a79fb497e4d700bef63
refs/heads/master
2023-06-21T09:11:36.808752
2021-07-18T09:44:45
2021-07-18T09:44:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,413
cpp
#include "constraints.h" #include "animation.h" namespace anim { Constraints::Constraints(const anim::Animation& a) : m_anim(new anim::Animation(a)) { } Constraints::Constraints(const Constraints& c) { for(auto& val : c) { std::pair<std::string, constraints::Channel> value = std::make_pair(std::string(val.first), constraints::Channel(this)); std::map<std::string, constraints::Channel>::iterator it = m_channels.insert(value).first; it->second = val.second; } m_anim = c.m_anim; } const Constraints& Constraints::operator=(const Constraints& c) { m_channels.clear(); for(auto& val : c) { std::map<std::string, constraints::Channel>::iterator it = m_channels.insert(std::make_pair(val.first, constraints::Channel(this))).first; it->second = val.second; } m_anim = c.m_anim; return *this; } Constraints::const_iterator Constraints::begin() const { return m_channels.begin(); } Constraints::const_iterator Constraints::end() const { return m_channels.end(); } bool Constraints::operator==(const Constraints& c) const { return m_channels == c.m_channels; } bool Constraints::operator!=(const Constraints& c) const { return m_channels != c.m_channels; } bool Constraints::empty() const { return m_channels.empty(); } std::size_t Constraints::size() const { return m_channels.size(); } const anim::Animation& Constraints::anim() const { assert(m_anim != nullptr); return *m_anim; } namespace { anim::Transform average(const std::vector<constraints::Frame>& tr, std::size_t start, std::size_t end) { assert(start <= end); assert(end < tr.size()); Imath::V3f translation(0, 0, 0); Imath::Quatf rotation(0, 0, 0, 0); float norm = 0.0f; for(std::size_t i = start; i <= end; ++i) { assert(tr[i].value() <= 1.0f); const float weight = (1.0f - tr[i].value()); norm += weight; translation += tr[i].tr().translation * weight; if((rotation ^ tr[i].tr().rotation) > 0) rotation += tr[i].tr().rotation * weight; else rotation += -tr[i].tr().rotation * weight; } return anim::Transform(rotation.normalized(), translation / norm); } std::size_t findJointId(const std::string& name, const anim::Animation& anim) { assert(!anim.empty()); std::size_t jointId = std::numeric_limits<std::size_t>::max(); for(auto& j : anim.frame(0)) if(j.name() == name) jointId = j.index(); if(jointId == std::numeric_limits<std::size_t>::max()) throw std::runtime_error("Joint '" + name + "' not found in the animation data!"); return jointId; } } // namespace void Constraints::process(const std::string& jointName, std::function<void(constraints::Frames& fr)> fn) { if(m_anim == nullptr || m_anim->empty()) throw std::runtime_error("Cannot detect constraints - animation data is empty."); // find the joint ID const std::size_t jointId = findJointId(jointName, *m_anim); // get the frames of the constraint std::map<std::string, constraints::Channel>::iterator cit = m_channels.insert(std::make_pair(jointName, constraints::Channel(this))).first; constraints::Channel& channel = cit->second; // if empty, make a new array of world transforms constraints::Frames frames = channel.m_frames; if(frames.empty() || frames.size() != m_anim->size()) { frames.clear(); for(auto& fr : *m_anim) frames.m_frames.push_back(constraints::Frame(fr[jointId].world(), 0.0f)); } // process the frames fn(frames); // and create the constraints channel.m_frames = frames; channel.m_values.clear(); std::size_t begin = std::numeric_limits<std::size_t>::max(); std::size_t end = 0; for(std::size_t frameIndex = 0; frameIndex < frames.size(); ++frameIndex) { if(frames.m_frames[frameIndex].m_constraintValue < 1.0f) { if(begin > end) begin = frameIndex; end = frameIndex; } else { if(begin <= end) { channel.addConstraint(begin, end, average(frames.m_frames, begin, end)); begin = std::numeric_limits<std::size_t>::max(); } } } if(begin <= end) channel.addConstraint(begin, end, average(frames.m_frames, begin, end)); } std::ostream& operator<<(std::ostream& out, const Constraints& c) { out << "Constraints:" << std::endl; if(c.empty()) out << " (empty)" << std::endl; for(auto& i : c) { out << " " << i.first << " -"; for(auto& ci : i.second) out << " (" << ci.startFrame() << " - " << ci.endFrame() << ")"; out << std::endl; } return out; } } // namespace anim
[ "martin.prazak@gmail.com" ]
martin.prazak@gmail.com
64cde9fbd0e307873d6131fd9ca208ce4b80c651
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/wget/old_hunk_86.cpp
adf40dfb73b71bc99c6d6f1e8ad7351be9c175e1
[]
no_license
ccdxc/logSurvey
eaf28e9c2d6307140b17986d5c05106d1fd8e943
6b80226e1667c1e0760ab39160893ee19b0e9fb1
refs/heads/master
2022-01-07T21:31:55.446839
2018-04-21T14:12:43
2018-04-21T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
263
cpp
bhash = concat_strings (name, ".badhash", (char *)0); uname = unique_name (bhash, false); logprintf (LOG_VERBOSE, _("Renaming ‘%s’ to ‘%s’.\n"), name, uname); if (link (name, uname)) logprintf (LOG_NOTQUIET, "link: %s\n", strerror (errno));
[ "993273596@qq.com" ]
993273596@qq.com
977ca26c15345358172e5fcb9f47f169e41f6715
4967c207e5083e80a480d289ae18a37c9b738e4c
/Engine_AI.cpp
c9317a89a80f4e93dfb08fc8b104170619a0165c
[]
no_license
SaurabhGajula/Chess
b5afe63157f14e15d8c89b9ef2e7ab6768e2998b
a76deb765f7c6576ede934b58b7841ed2f86c687
refs/heads/master
2020-12-03T02:30:08.087944
2015-03-23T17:57:14
2015-03-23T17:57:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,525
cpp
#include "engine_ai.h" #include <windows.h> #include <ctime> const int values[] = { 0, 100, 300, 300, 500, 900, 100000}; const int mobility_value = 3; const int castle_value = 60; const int early_queen = 20; const int bishop_long_diagonal = 30; const int developed_knight = 35; const int double_bishop = 45; const int doubled_pawn = 10; const int pawn_forward_bonus = 5; moves EngineAI::GetBestMove(int level) { total_moves = 0; quies_extra_max = 0; moves result; this->level = level; int max_time; bool first_modified = false; //Game difficulty switch(level) { case AI_EASY: max_time = 1; break; case AI_MEDIUM: max_time = 4; break; case AI_HARD: max_time = 10; break; } //Decide game stage if(previous_moves.size()<20) { quies_factor = 0.5; stage = AI_OPENING; } else if(previous_moves.size()>50) { quies_factor = 0.25; stage = AI_END_GAME; } else { quies_factor = 0.25; stage = AI_MIDDLE_GAME; } HANDLE hThread = CreateThread(NULL, 0, AIThread, (void*)this, 0, 0); modified = false; max_d = 1; int init_time = time(NULL); while(true) { Sleep(5); if(modified) { first_modified=true; modified = false; max_d++; hThread = CreateThread(NULL, 0, AIThread, (void*)this, 0, 0); } if(first_modified && (time(NULL)-init_time>max_time)) { TerminateThread(hThread, 0); break; } } return best_move; } long unsigned int __stdcall EngineAI::AIThread(void *input) { EngineAI *engine_ai = (EngineAI*)input; engine_ai->best_move = engine_ai->minimax_base(engine_ai->max_d); engine_ai->modified = true; return 0; } void EngineAI::PrintInfo() { printf("AI level: "); switch(level) { case AI_EASY: printf("Easy\n"); break; case AI_MEDIUM: printf("Medium\n"); break; case AI_HARD: printf("Hard\n"); break; } printf("Game stage: "); switch(stage) { case AI_OPENING: printf("Opening\n"); break; case AI_MIDDLE_GAME: printf("Middle game\n"); break; case AI_END_GAME: printf("End game\n"); break; } printf("Base max depth: %u\n", (modified)? max_d-1 : max_d); printf("Total leaves evaluated: %u\n", total_moves); printf("Maximum extra moves for quiescence: %u\n", quies_extra_max); printf("\n"); } int EngineAI::EvaluateOpening() { int result = 0; //Relative piece values for(int i=1;i<=6;i++) result += values[i]*(pieces_lost1[i] - pieces_lost2[i]); //Add castling bonus if(castled1) result-=castle_value; if(castled2) result+=castle_value; //mobility result += mobility_value*(CountPossibleMoves(false) - CountPossibleMoves(true)); //Early Queen if(board_matrix[3][0]!=5) result+=early_queen; if(board_matrix[3][7]!=-5) result-=early_queen; //Doubled pawn for(int x=0;x<8;x++) { bool white_pawn = false; bool black_pawn = false; for(int y=0;y<8;y++) { if(board_matrix[x][y]==1) { if(white_pawn) result+=doubled_pawn; else white_pawn=true; } else if(board_matrix[x][y]==-1) { if(black_pawn) result-=doubled_pawn; else black_pawn=true; } } } //Developed knight if(board_matrix[1][0]!=3) result-=developed_knight; if(board_matrix[6][0]!=3) result-=developed_knight; if(board_matrix[1][7]!=-3) result+=developed_knight; if(board_matrix[6][7]!=-3) result+=developed_knight; return result; } int EngineAI::EvaluateMiddleGame() { int result = 0; for(int i=1;i<=6;i++) result += values[i]*(pieces_lost1[i] - pieces_lost2[i]); //Double bishop if(pieces_lost1[2]==1) result+=double_bishop; if(pieces_lost2[2]==1) result-=double_bishop; //Doubled pawn for(int x=0;x<8;x++) { bool white_pawn = false; bool black_pawn = false; for(int y=0;y<8;y++) { if(board_matrix[x][y]==1) { if(white_pawn) result+=doubled_pawn; else white_pawn=true; } else if(board_matrix[x][y]==-1) { if(black_pawn) result-=doubled_pawn; else black_pawn=true; } } } return result; } int EngineAI::EvaluateEndGame() { int result = 0; for(int i=1;i<=6;i++) result += values[i]*(pieces_lost1[i] - pieces_lost2[i]); //Doubled pawn for(int x=0;x<8;x++) { bool white_pawn = false; bool black_pawn = false; for(int y=0;y<8;y++) { if(board_matrix[x][y]==1) { if(white_pawn) result+=doubled_pawn; else white_pawn=true; } else if(board_matrix[x][y]==-1) { if(black_pawn) result-=doubled_pawn; else black_pawn=true; } } } //Favor pawn movement for(int x=0;x<8;x++) for(int y=0;y<8;y++) { if(board_matrix[x][y]==1) result-=pawn_forward_bonus*(y); if(board_matrix[x][y]==-1) result+=pawn_forward_bonus*(8-y); } return result; } int EngineAI::EvaluateFunction() { total_moves++; switch(stage) { case AI_OPENING: return EvaluateOpening(); case AI_MIDDLE_GAME: return EvaluateMiddleGame(); case AI_END_GAME: return EvaluateEndGame(); } } int EngineAI::CountPossibleMoves(bool player1) { int result = 0; for(int x0=0;x0<8;x0++) for(int y0=0;y0<8;y0++) { if((player1 && board_matrix[x0][y0]>0) || (!player1 && board_matrix[x0][y0]<0)) { for(int x1=0;x1<8;x1++) for(int y1=0;y1<8;y1++) if(IsValidMoveBase(x0, y0, x1, y1)) result++; } } return result; } int EngineAI::maximize(int depth, int max_depth, int alpha, int beta, int extra) { if(depth<=max_depth+extra) { if(IsCheckmate2()) { pieces_lost2[6]++; float result = EvaluateFunction(); pieces_lost2[6]--; return result; } else if(IsStalemate2()) { return EvaluateFunction(); } else { int max_here = -100000000; //Normal minimax with alpha - beta pruning for(int x0=0;x0<8;x0++) for(int y0=0;y0<8;y0++) for(int x1=0;x1<8;x1++) for(int y1=0;y1<8;y1++) if(board_matrix[x0][y0]<0) if(IsValidMove(x0,y0,x1,y1)) { //Do move int prev_0 = board_matrix[x0][y0]; int prev_1 = MakeMove(x0, y0, x1, y1); if(prev_1 >= 9) { pieces_lost1[5]++; pieces_lost1[prev_1 - 9]++; } else if(prev_1 == -7) castled2 = true; else if(prev_1 == -8) pieces_lost1[1]++; else pieces_lost1[prev_1]++; int value_evaluated = minimize(depth+1, max_depth, alpha, beta, extra); max_here = max(value_evaluated, max_here); alpha = max(max_here, alpha); //Undo move if(prev_1 >= 9) { pieces_lost1[5]--; pieces_lost1[prev_1-9]--; } else if(prev_1 == -7) castled2 = false; else if(prev_1 == -8) pieces_lost1[1]--; else pieces_lost1[prev_1]--; UndoMove(prev_0, prev_1, x0, y0, x1, y1); if(beta<=alpha) return max_here; } return max_here; } } //Quiescence int total_pieces_lost = 0; for(int i=1;i<=6;i++) total_pieces_lost+= pieces_lost1[i] + pieces_lost2[i]; extra = quies_factor*(float)total_pieces_lost; if(depth<=max_depth+extra) { quies_extra_max = max(extra, quies_extra_max); return maximize(depth, max_depth, alpha, beta, extra); } return EvaluateFunction(); } int EngineAI::minimize(int depth, int max_depth, int alpha, int beta, int extra) { if(depth<=max_depth+extra) { if(IsCheckmate1()) { pieces_lost1[6]++; int result = EvaluateFunction(); pieces_lost1[6]--; return result; } else if(IsStalemate1()) return EvaluateFunction(); else { int min_here = 100000000; for(int x0=0;x0<8;x0++) for(int y0=0;y0<8;y0++) for(int x1=0;x1<8;x1++) for(int y1=0;y1<8;y1++) if(board_matrix[x0][y0]>0) if(IsValidMove(x0,y0,x1,y1)) { //Do move int prev_0 = board_matrix[x0][y0]; int prev_1 = MakeMove(x0, y0, x1, y1); if(prev_1 <= -9) { pieces_lost2[5]++; pieces_lost2[-prev_1-9]++; } else if(prev_1 == 7) castled1 = true; else if(prev_1 == 8) pieces_lost2[1]++; else pieces_lost2[-prev_1]++; int value_evaluated = maximize(depth+1, max_depth, alpha, beta, extra); min_here = min(value_evaluated, min_here); beta = min(min_here, beta); //Undo move if(prev_1 <= -9) { pieces_lost2[5]--; pieces_lost2[-prev_1 - 9]--; } else if(prev_1 == 7) castled1 = false; else if(prev_1 == 8) pieces_lost2[1]--; else pieces_lost2[-prev_1]--; UndoMove(prev_0, prev_1, x0, y0, x1, y1); if(beta<=alpha) return min_here; } return min_here; } } //Quiescence int total_pieces_lost = 0; for(int i=1;i<=6;i++) total_pieces_lost+= pieces_lost1[i] + pieces_lost2[i]; extra = quies_factor*(float)total_pieces_lost; if(depth<=max_depth+extra) { quies_extra_max = max(extra, quies_extra_max); return minimize(depth, max_depth, alpha, beta, extra); } return EvaluateFunction(); } moves EngineAI::minimax_base(int max_depth, int alpha, int beta) { for(int i=0;i<7;i++) { pieces_lost1[i] = 0; pieces_lost2[i] = 0; } moves result{0,0,0,0}; if (!(IsCheckmate2()) && !(IsStalemate1())) { int max_here = -100000000; for(int x0=0;x0<8;x0++) for(int y0=0;y0<8;y0++) { for(int x1=0;x1<8;x1++) for(int y1=0;y1<8;y1++) if(board_matrix[x0][y0]<0) if(IsValidMove(x0,y0,x1,y1)) { //Do move int prev_0 = board_matrix[x0][y0]; int prev_1 = MakeMove(x0, y0, x1, y1); if(prev_1 >= 9) { pieces_lost1[5]++; pieces_lost1[prev_1-9]++; } else if(prev_1 == -7) castled2 = true; else if(prev_1 == -8) pieces_lost1[1]++; else pieces_lost1[prev_1]++; int value_evaluated = minimize(2, max_depth, alpha, beta, 0); if(value_evaluated > max_here) { max_here = value_evaluated; result.x0 = x0; result.y0 = y0; result.x1 = x1; result.y1 = y1; } alpha = max(max_here, alpha); //Undo move if(prev_1 >= 9) { pieces_lost1[5]--; pieces_lost1[prev_1 - 9]--; } else if(prev_1 == -7) castled2 = false; else if(prev_1 == -8) pieces_lost1[1]--; else pieces_lost1[prev_1]--; UndoMove(prev_0, prev_1, x0, y0, x1, y1); } } } return result; }
[ "rahulgovind517@gmail.com" ]
rahulgovind517@gmail.com
429875ee70c4df14986ec00e53be15364f041a8f
9a9fb43d866dc8fd829211d2b47328ef1f5ed428
/PI_ROS_WORKSPACES/test/devel_isolated/std_msgs/include/std_msgs/Float64.h
2ddfb654bc0b43b9193d3f1c31c6ba6b0cf1e25b
[]
no_license
droter/auto_mow
326df42a54676079cac61fe63c40d5d04beb049b
3742cb2ef78bc06d2771ac4c679e5110909774f8
refs/heads/master
2022-05-19T20:18:33.409777
2020-04-29T00:42:24
2020-04-29T00:42:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,524
h
// Generated by gencpp from file std_msgs/Float64.msg // DO NOT EDIT! #ifndef STD_MSGS_MESSAGE_FLOAT64_H #define STD_MSGS_MESSAGE_FLOAT64_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> namespace std_msgs { template <class ContainerAllocator> struct Float64_ { typedef Float64_<ContainerAllocator> Type; Float64_() : data(0.0) { } Float64_(const ContainerAllocator& _alloc) : data(0.0) { (void)_alloc; } typedef double _data_type; _data_type data; typedef boost::shared_ptr< ::std_msgs::Float64_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::std_msgs::Float64_<ContainerAllocator> const> ConstPtr; }; // struct Float64_ typedef ::std_msgs::Float64_<std::allocator<void> > Float64; typedef boost::shared_ptr< ::std_msgs::Float64 > Float64Ptr; typedef boost::shared_ptr< ::std_msgs::Float64 const> Float64ConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::std_msgs::Float64_<ContainerAllocator> & v) { ros::message_operations::Printer< ::std_msgs::Float64_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace std_msgs namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': True, 'IsMessage': True, 'HasHeader': False} // {'std_msgs': ['/home/pi/test/src/std_msgs/msg']} // !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types'] template <class ContainerAllocator> struct IsFixedSize< ::std_msgs::Float64_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsFixedSize< ::std_msgs::Float64_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::std_msgs::Float64_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::std_msgs::Float64_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::std_msgs::Float64_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::std_msgs::Float64_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::std_msgs::Float64_<ContainerAllocator> > { static const char* value() { return "fdb28210bfa9d7c91146260178d9a584"; } static const char* value(const ::std_msgs::Float64_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0xfdb28210bfa9d7c9ULL; static const uint64_t static_value2 = 0x1146260178d9a584ULL; }; template<class ContainerAllocator> struct DataType< ::std_msgs::Float64_<ContainerAllocator> > { static const char* value() { return "std_msgs/Float64"; } static const char* value(const ::std_msgs::Float64_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::std_msgs::Float64_<ContainerAllocator> > { static const char* value() { return "float64 data\n\ "; } static const char* value(const ::std_msgs::Float64_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::std_msgs::Float64_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.data); } ROS_DECLARE_ALLINONE_SERIALIZER }; // struct Float64_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::std_msgs::Float64_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::std_msgs::Float64_<ContainerAllocator>& v) { s << indent << "data: "; Printer<double>::stream(s, indent + " ", v.data); } }; } // namespace message_operations } // namespace ros #endif // STD_MSGS_MESSAGE_FLOAT64_H
[ "joshuatygert@gmail.com" ]
joshuatygert@gmail.com
2a071ebce3cc03231a1bd13322e5b369c11e6875
d62f900e93903225bc213c1e2b0439bdd9b3fb90
/src/base58.h
c7ba9af1765c6dd736de14ba00e7c9bb54323742
[ "MIT" ]
permissive
latiefwadasz/poins
91fc307a97298f67d81891a4f35d7fef07557f87
e0a706ab035536b03ac33e578032b2f1cbcebd24
refs/heads/master
2020-03-07T21:29:31.236869
2018-04-04T15:37:16
2018-04-04T15:37:16
127,727,717
0
0
null
null
null
null
UTF-8
C++
false
false
13,010
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // // Why base-58 instead of standard base-64 encoding? // - Don't want 0OIl characters that look the same in some fonts and // could be used to create visually identical looking account numbers. // - A string with non-alphanumeric characters is not as easily accepted as an account number. // - E-mail usually won't line-break if there's no punctuation to break at. // - Double-clicking selects the whole number as one word if it's all alphanumeric. // #ifndef BITCOIN_BASE58_H #define BITCOIN_BASE58_H #include <string> #include <vector> #include "bignum.h" #include "key.h" #include "script.h" #include "allocators.h" static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; // Encode a byte sequence as a base58-encoded string inline std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend) { CAutoBN_CTX pctx; CBigNum bn58 = 58; CBigNum bn0 = 0; // Convert big endian data to little endian // Extra zero at the end make sure bignum will interpret as a positive number std::vector<unsigned char> vchTmp(pend-pbegin+1, 0); reverse_copy(pbegin, pend, vchTmp.begin()); // Convert little endian data to bignum CBigNum bn; bn.setvch(vchTmp); // Convert bignum to std::string std::string str; // Expected size increase from base58 conversion is approximately 137% // use 138% to be safe str.reserve((pend - pbegin) * 138 / 100 + 1); CBigNum dv; CBigNum rem; while (bn > bn0) { if (!BN_div(&dv, &rem, &bn, &bn58, pctx)) throw bignum_error("EncodeBase58 : BN_div failed"); bn = dv; unsigned int c = rem.getulong(); str += pszBase58[c]; } // Leading zeroes encoded as base58 zeros for (const unsigned char* p = pbegin; p < pend && *p == 0; p++) str += pszBase58[0]; // Convert little endian std::string to big endian reverse(str.begin(), str.end()); return str; } // Encode a byte vector as a base58-encoded string inline std::string EncodeBase58(const std::vector<unsigned char>& vch) { return EncodeBase58(&vch[0], &vch[0] + vch.size()); } // Decode a base58-encoded string psz into byte vector vchRet // returns true if decoding is successful inline bool DecodeBase58(const char* psz, std::vector<unsigned char>& vchRet) { CAutoBN_CTX pctx; vchRet.clear(); CBigNum bn58 = 58; CBigNum bn = 0; CBigNum bnChar; while (isspace(*psz)) psz++; // Convert big endian string to bignum for (const char* p = psz; *p; p++) { const char* p1 = strchr(pszBase58, *p); if (p1 == NULL) { while (isspace(*p)) p++; if (*p != '\0') return false; break; } bnChar.setulong(p1 - pszBase58); if (!BN_mul(&bn, &bn, &bn58, pctx)) throw bignum_error("DecodeBase58 : BN_mul failed"); bn += bnChar; } // Get bignum as little endian data std::vector<unsigned char> vchTmp = bn.getvch(); // Trim off sign byte if present if (vchTmp.size() >= 2 && vchTmp.end()[-1] == 0 && vchTmp.end()[-2] >= 0x80) vchTmp.erase(vchTmp.end()-1); // Restore leading zeros int nLeadingZeros = 0; for (const char* p = psz; *p == pszBase58[0]; p++) nLeadingZeros++; vchRet.assign(nLeadingZeros + vchTmp.size(), 0); // Convert little endian data to big endian reverse_copy(vchTmp.begin(), vchTmp.end(), vchRet.end() - vchTmp.size()); return true; } // Decode a base58-encoded string str into byte vector vchRet // returns true if decoding is successful inline bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet) { return DecodeBase58(str.c_str(), vchRet); } // Encode a byte vector to a base58-encoded string, including checksum inline std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn) { // add 4-byte hash check to the end std::vector<unsigned char> vch(vchIn); uint256 hash = Hash(vch.begin(), vch.end()); vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4); return EncodeBase58(vch); } // Decode a base58-encoded string psz that includes a checksum, into byte vector vchRet // returns true if decoding is successful inline bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet) { if (!DecodeBase58(psz, vchRet)) return false; if (vchRet.size() < 4) { vchRet.clear(); return false; } uint256 hash = Hash(vchRet.begin(), vchRet.end()-4); if (memcmp(&hash, &vchRet.end()[-4], 4) != 0) { vchRet.clear(); return false; } vchRet.resize(vchRet.size()-4); return true; } // Decode a base58-encoded string str that includes a checksum, into byte vector vchRet // returns true if decoding is successful inline bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet) { return DecodeBase58Check(str.c_str(), vchRet); } /** Base class for all base58-encoded data */ class CBase58Data { protected: // the version byte unsigned char nVersion; // the actually encoded data typedef std::vector<unsigned char, zero_after_free_allocator<unsigned char> > vector_uchar; vector_uchar vchData; CBase58Data() { nVersion = 0; vchData.clear(); } void SetData(int nVersionIn, const void* pdata, size_t nSize) { nVersion = nVersionIn; vchData.resize(nSize); if (!vchData.empty()) memcpy(&vchData[0], pdata, nSize); } void SetData(int nVersionIn, const unsigned char *pbegin, const unsigned char *pend) { SetData(nVersionIn, (void*)pbegin, pend - pbegin); } public: bool SetString(const char* psz) { std::vector<unsigned char> vchTemp; DecodeBase58Check(psz, vchTemp); if (vchTemp.empty()) { vchData.clear(); nVersion = 0; return false; } nVersion = vchTemp[0]; vchData.resize(vchTemp.size() - 1); if (!vchData.empty()) memcpy(&vchData[0], &vchTemp[1], vchData.size()); OPENSSL_cleanse(&vchTemp[0], vchData.size()); return true; } bool SetString(const std::string& str) { return SetString(str.c_str()); } std::string ToString() const { std::vector<unsigned char> vch(1, nVersion); vch.insert(vch.end(), vchData.begin(), vchData.end()); return EncodeBase58Check(vch); } int CompareTo(const CBase58Data& b58) const { if (nVersion < b58.nVersion) return -1; if (nVersion > b58.nVersion) return 1; if (vchData < b58.vchData) return -1; if (vchData > b58.vchData) return 1; return 0; } bool operator==(const CBase58Data& b58) const { return CompareTo(b58) == 0; } bool operator<=(const CBase58Data& b58) const { return CompareTo(b58) <= 0; } bool operator>=(const CBase58Data& b58) const { return CompareTo(b58) >= 0; } bool operator< (const CBase58Data& b58) const { return CompareTo(b58) < 0; } bool operator> (const CBase58Data& b58) const { return CompareTo(b58) > 0; } }; /** base58-encoded Bitcoin addresses. * Public-key-hash-addresses have version 0 (or 111 testnet). * The data vector contains RIPEMD160(SHA256(pubkey)), where pubkey is the serialized public key. * Script-hash-addresses have version 5 (or 196 testnet). * The data vector contains RIPEMD160(SHA256(cscript)), where cscript is the serialized redemption script. */ class CBitcoinAddress; class CBitcoinAddressVisitor : public boost::static_visitor<bool> { private: CBitcoinAddress *addr; public: CBitcoinAddressVisitor(CBitcoinAddress *addrIn) : addr(addrIn) { } bool operator()(const CKeyID &id) const; bool operator()(const CScriptID &id) const; bool operator()(const CNoDestination &no) const; }; class CBitcoinAddress : public CBase58Data { public: enum { PUBKEY_ADDRESS = 48, // Poins addresses start with L SCRIPT_ADDRESS = 5, PUBKEY_ADDRESS_TEST = 111, SCRIPT_ADDRESS_TEST = 196, }; bool Set(const CKeyID &id) { SetData(fTestNet ? PUBKEY_ADDRESS_TEST : PUBKEY_ADDRESS, &id, 20); return true; } bool Set(const CScriptID &id) { SetData(fTestNet ? SCRIPT_ADDRESS_TEST : SCRIPT_ADDRESS, &id, 20); return true; } bool Set(const CTxDestination &dest) { return boost::apply_visitor(CBitcoinAddressVisitor(this), dest); } bool IsValid() const { unsigned int nExpectedSize = 20; bool fExpectTestNet = false; switch(nVersion) { case PUBKEY_ADDRESS: nExpectedSize = 20; // Hash of public key fExpectTestNet = false; break; case SCRIPT_ADDRESS: nExpectedSize = 20; // Hash of CScript fExpectTestNet = false; break; case PUBKEY_ADDRESS_TEST: nExpectedSize = 20; fExpectTestNet = true; break; case SCRIPT_ADDRESS_TEST: nExpectedSize = 20; fExpectTestNet = true; break; default: return false; } return fExpectTestNet == fTestNet && vchData.size() == nExpectedSize; } CBitcoinAddress() { } CBitcoinAddress(const CTxDestination &dest) { Set(dest); } CBitcoinAddress(const std::string& strAddress) { SetString(strAddress); } CBitcoinAddress(const char* pszAddress) { SetString(pszAddress); } CTxDestination Get() const { if (!IsValid()) return CNoDestination(); switch (nVersion) { case PUBKEY_ADDRESS: case PUBKEY_ADDRESS_TEST: { uint160 id; memcpy(&id, &vchData[0], 20); return CKeyID(id); } case SCRIPT_ADDRESS: case SCRIPT_ADDRESS_TEST: { uint160 id; memcpy(&id, &vchData[0], 20); return CScriptID(id); } } return CNoDestination(); } bool GetKeyID(CKeyID &keyID) const { if (!IsValid()) return false; switch (nVersion) { case PUBKEY_ADDRESS: case PUBKEY_ADDRESS_TEST: { uint160 id; memcpy(&id, &vchData[0], 20); keyID = CKeyID(id); return true; } default: return false; } } bool IsScript() const { if (!IsValid()) return false; switch (nVersion) { case SCRIPT_ADDRESS: case SCRIPT_ADDRESS_TEST: { return true; } default: return false; } } }; bool inline CBitcoinAddressVisitor::operator()(const CKeyID &id) const { return addr->Set(id); } bool inline CBitcoinAddressVisitor::operator()(const CScriptID &id) const { return addr->Set(id); } bool inline CBitcoinAddressVisitor::operator()(const CNoDestination &id) const { return false; } /** A base58-encoded secret key */ class CBitcoinSecret : public CBase58Data { public: enum { PRIVKEY_ADDRESS = CBitcoinAddress::PUBKEY_ADDRESS + 128, PRIVKEY_ADDRESS_TEST = CBitcoinAddress::PUBKEY_ADDRESS_TEST + 128, }; void SetKey(const CKey& vchSecret) { assert(vchSecret.IsValid()); SetData(fTestNet ? PRIVKEY_ADDRESS_TEST : PRIVKEY_ADDRESS, vchSecret.begin(), vchSecret.size()); if (vchSecret.IsCompressed()) vchData.push_back(1); } CKey GetKey() { CKey ret; ret.Set(&vchData[0], &vchData[32], vchData.size() > 32 && vchData[32] == 1); return ret; } bool IsValid() const { bool fExpectTestNet = false; switch(nVersion) { case PRIVKEY_ADDRESS: break; case PRIVKEY_ADDRESS_TEST: fExpectTestNet = true; break; default: return false; } return fExpectTestNet == fTestNet && (vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1)); } bool SetString(const char* pszSecret) { return CBase58Data::SetString(pszSecret) && IsValid(); } bool SetString(const std::string& strSecret) { return SetString(strSecret.c_str()); } CBitcoinSecret(const CKey& vchSecret) { SetKey(vchSecret); } CBitcoinSecret() { } }; #endif // BITCOIN_BASE58_H
[ "latiefmansyur@gmail.com" ]
latiefmansyur@gmail.com
05d5040b13b5d0531d36c43099769aed2194dc2a
809187e8943bb0420970b28ad8dbbb7e01c65650
/449/a.cpp
1842ae33940379f5b1e6c4d3954a7b66c213fa44
[]
no_license
pranxol/codeforces_solution
c718e7477e49d30f155909a9aa7cdfa6fa87fee4
b8b0fbf36214c7b448393b7f6ed52b59d8e23fcd
refs/heads/main
2022-12-19T00:02:43.778288
2020-10-05T15:04:03
2020-10-05T15:04:03
300,912,433
0
0
null
null
null
null
UTF-8
C++
false
false
750
cpp
#include<bits/stdc++.h> using namespace std; #define sf scanf #define pf printf #define pi acos(-1) #define ll long long #define pb push_back #define infinity 2147483647 #define pii pair<int,int> #define ff first #define ss second #define mx 1005 int main() { //freopen ("input.txt", "r", stdin); //freopen ("output.txt", "w", stdout); int n,m; sf("%d%d\n",&n,&m); char s[n+3]; for(int i=1;i<=n;i++) { sf("%c",&s[i]); } for(int i=1;i<=m;i++) { int l,r; char a,b; sf("%d%d %c %c",&l,&r,&a,&b); for(int j=l;j<=r;j++) { if(s[j]==a) s[j]=b; } } for(int i=1;i<=n;i++) { pf("%c",s[i]); } return 0; }
[ "pranxol@users.noreply.github.com" ]
pranxol@users.noreply.github.com
31dbdf5f8801756930bc10d32b083f8a2114ebfc
b367fe5f0c2c50846b002b59472c50453e1629bc
/xbox_leak_may_2020/xbox trunk/xbox/private/test/hvs/launcher/testconfigmenu.h
98469e7b1055a3fc486feb7205038e72fbbcf536
[]
no_license
sgzwiz/xbox_leak_may_2020
11b441502a659c8da8a1aa199f89f6236dd59325
fd00b4b3b2abb1ea6ef9ac64b755419741a3af00
refs/heads/master
2022-12-23T16:14:54.706755
2020-09-27T18:24:48
2020-09-27T18:24:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,366
h
/***************************************************** *** testconfigmenu.h *** *** Header file for our Test Config Menu class. *** This is a standard menu contains a list of menu *** items to be selected. *** *** by James N. Helm *** November 27th, 2001 *** *****************************************************/ #ifndef _TESTCONFIGMENU_H_ #define _TESTCONFIGMENU_H_ #include "menuscreen.h" #include "xbeinfo.h" const long gc_lTESTCONFIG_NUMBER_BUFZONE = 3500; const long gc_lTESTCONFIG_NUMBER_MAXSCALE = 100000; const long gc_lTESTCONFIG_NUMBER_MAXSCALE_DIVISOR = 15; enum TESTCONFMENU_ACTIONS { ENUM_TESTCONFMENU_NOACTION, ENUM_TESTCONFMENU_EDITSTRING2, ENUM_TESTCONFMENU_EDIT_NUMBERSTRING, ENUM_TESTCONFMENU_EDIT_NUMBER, ENUM_TESTCONFMENU_EDIT_RANGE1, ENUM_TESTCONFMENU_EDIT_RANGE2 }; class CTestConfigMenu : public CMenuScreen { public: // Constructors and Destructor CTestConfigMenu( void ); ~CTestConfigMenu( void ); // Public Methods HRESULT Init( XFONT* pMenuItemFont, // Initialize the Menu XFONT* pMenuTitleFont ); // Draws a menu on to the screen void Action( CUDTexture* pTexture ); // Renders to the texture and calls any per-frame processing void RenderScreenItems( CUDTexture* pTexture ); // Render the screen items properly on our menu void RenderMenuTitle( CUDTexture* pTexture ); // Render the menu title on to the menu void RenderMenuItems( CUDTexture* pTexture ); // Used to render the menu items on the screen void HandleInput( enum BUTTONS buttonPressed, // Handles input from the buttons BOOL bFirstPress ); void HandleInput( enum CONTROLS controlPressed, // Handle input (of the CONTROLS) for the current menu BOOL bFirstPress ); void HandleInput( enum JOYSTICK joystick, // Handle any requests for the joystick (thumb-pad) int nThumbY, int nThumbX, BOOL bFirstYPress, BOOL bFirstXPress ); void Enter( void ); // This should be called whenever the menu is entered or activated void SetXBEInfoPtr( CXBEInfo* pXBEInfo ); // Set the PTR to our active XBEInfo object void SetMultiConfigs( BOOL bConfigs ) // Set whether or not the XBE supports multiple configs { m_bMultiConfigs = bConfigs; }; private: CXBEInfo* m_pXBEInfo; enum TESTCONFMENU_ACTIONS m_eCurrentAction; // Used to track the current action of the user unsigned int m_uiSelectedConfigItem; // Used to track which config item is selected when using multiple menus long m_lNum1Val; // Used to store numbers if user is in manual edit mode BOOL m_bMultiConfigs; // Used to determine if the XBE supports multiple configs void Leave( CXItem* pItem ); // Should be called whenever user is leaving the menu void ProcessMenuActions( void ); // If the user is performing an action, this will handle it void GoToHelp( void ); // Sets up and goes to the help menu }; #endif // _TESTCONFIGMENU_H_
[ "benjamin.barratt@icloud.com" ]
benjamin.barratt@icloud.com
d4ecf82a69b5e3b527eb7de8cadde79223c055c6
f4dc1073def4c95a19d4183475405c439cfc0aff
/Include/Physics/Catmull-Rom3.h
9f8e4f87b0349475caab7b9cb83da9e7dd4d9e0c
[]
no_license
timi-liuliang/aresengine
9cf74e7137bb11cd8475852b8e4c9d51eda62505
efd39c6ef482b8d50a8eeaa5009cac5d5b9f41ee
refs/heads/master
2020-04-15T15:06:41.726469
2019-01-09T05:09:35
2019-01-09T05:09:35
164,779,995
1
0
null
null
null
null
GB18030
C++
false
false
1,264
h
#pragma once #include <Core/AresMath.h> namespace Ares { namespace Curves { //--------------------------------------------------------------- // Catmull_Rom3 2011-07-12 帝林 // 主要参考:<<game programming gems 1>> 3.4-A*审美优化 // // 说明: // Catmull-Rom样条可以使空间中的点序列变得平滑,它产生了一条 // 能够经过原始路径中所有控制点的曲线(不像Bezier曲线,虽然比较平 // 滑但是不能经过所有的控制点)。 // Catmull-Rom公式要求4个输入点,然后给出一条位于第2点和第3点 // 之间的光滑曲线。 // 为了得到第1个输入点和第二个输入点之间的点,你可以为这个函数 // 输入第1个点两次,接着输入第2点和第3点。为了获得第3点和第4点之间 // 的点,可以先为函数输入第2点和第3点,然后输入第4点两次。 // out 返回点 // v1,v2,v3,v4 控制点 // amount 控制量 Vector3 CatmullRom3( Vector3& out, const Vector3& v1, const Vector3& v2, const Vector3& v3, const Vector3& v4, float amount); // 求CatmullRom3 切线 Vector3 CatmullRom3Tangent( Vector3& out, const Vector3& v1, const Vector3& v2, const Vector3& v3, const Vector3& v4, float amount); } }
[ "qq79402005@gmail.com" ]
qq79402005@gmail.com
577bce4ddd9d02bf3cfe93847ba0c943d86873b5
d48531c367bc5df8cdd71e061f7999efb7c4ac66
/extractor/extractors/FFT.h
86fc17419e9d45ebf59a057a1df9327e18f8f991
[]
no_license
janisozaur/ro
2be69b87f5d6ff86e716919986df11f851f0926b
fb633a5d0c55641c891fa41f3517d56b96b27ff4
refs/heads/master
2021-01-01T19:11:04.315326
2012-01-23T08:46:58
2012-01-23T08:46:58
2,852,900
0
0
null
null
null
null
UTF-8
C++
false
false
918
h
#ifndef FFT_H #define FFT_H #include "../ExtractorInterface.h" #include "ComplexArray.h" class FFT : public ExtractorInterface { public: struct QImages { QImage phase, magnitude; }; FFT(); ~FFT(); virtual bool init(const QStringList &params); virtual QString name() const; void perform(ComplexArray *ca, bool inverse = false) const; QVector<float> extract(const QImage &image, const int &x, const int &y) const; int size() const; // const QImages complexToImages(const ComplexArray *ca, QImage::Format format) const; private: void rearrange(QVector<Complex> &elements) const; void transform(QVector<Complex> &elements, bool inverse) const; void oneDFftH(ComplexArray *ca, int idx1, int idx2, bool inverse) const; void oneDFftV(ComplexArray *ca, int idx1, int idx2, bool inverse) const; QSize mSize; QVector<float> mWindow; }; #endif // FFT_H
[ "janisozaur@gmail.com" ]
janisozaur@gmail.com
cc8458987655e15b168bd26e23a71ebafa0af3b5
e3c49316bc7b165d4bc40285ca23aad7673753e4
/sdd/order/strategies/force_hypergraph.hh
478fb90449c8ed270a13184380e661431ec54395
[ "BSD-2-Clause" ]
permissive
ahamez/proto-dd
557005b851f4adf0dd19d40e271a85befa1f63da
835535d8e8b53284b6228ef5679baa839e3134b3
refs/heads/master
2016-09-06T09:01:04.654079
2014-04-04T20:30:26
2014-04-04T20:30:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,809
hh
#ifndef _SDD_ORDER_STRATEGIES_FORCE_HYPERGRAPH_HH_ #define _SDD_ORDER_STRATEGIES_FORCE_HYPERGRAPH_HH_ #include <deque> #include <memory> // shared_ptr #include <unordered_map> #include <vector> #include "sdd/order/strategies/force_hyperedge.hh" #include "sdd/order/strategies/force_vertex.hh" namespace sdd { namespace force { /*------------------------------------------------------------------------------------------------*/ /// @brief Represent the connections between the identifiers. template <typename C> class hypergraph { public: /// @brief The user identifier type. using identifier_type = typename C::Identifier; private: /// @brief An hypergraph's vertex. using vertex_type = vertex<identifier_type>; /// @brief An hypergraph's hyperedge. using hyperedge_type = hyperedge<identifier_type>; /// @brief All the vertices of this hypergraph. /// /// A deque is used because insertions at the end don't invalid references. std::shared_ptr<std::deque<vertex_type>> vertices_ptr_; /// @brief All the hyperedges of this hypergraph. /// /// A deque is used because insertions at the end don't invalid references. std::shared_ptr<std::deque<hyperedge_type>> hyperedges_ptr_; /// @brief Map identifiers to vertices. /// /// Enable fast retrieval of a vertex's address. std::shared_ptr<std::unordered_map<identifier_type, vertex_type*>> id_to_vertex_ptr_; public: /// @brief Default constructor. template <typename InputIterator> hypergraph(InputIterator it, InputIterator end) : vertices_ptr_(std::make_shared<std::deque<vertex_type>>()) , hyperedges_ptr_(std::make_shared<std::deque<hyperedge_type>>()) , id_to_vertex_ptr_(std::make_shared<std::unordered_map<identifier_type, vertex_type*>>()) { static double location = 0; assert(it != end); for (; it != end; ++it) { vertices_ptr_->emplace_back(*it, location++); const auto insertion = id_to_vertex_ptr_->emplace(*it, &vertices_ptr_->back()); if (not insertion.second) { std::stringstream ss; ss << "Identifier " << *it << " appears twice."; throw std::runtime_error(ss.str()); } } assert(id_to_vertex_ptr_->size() != 0); } /// @brief Add a new hyperedge with a set of identifiers. template <typename InputIterator> void add_hyperedge(InputIterator it, InputIterator end) { if (it == end) { return; } // Create, if necessary all connected vertices. std::vector<vertex_type*> vertices; vertices.reserve(std::distance(it, end)); for (; it != end; ++it) { const auto search = id_to_vertex_ptr_->find(*it); assert(search != id_to_vertex_ptr_->end()); vertices.emplace_back(search->second); } assert(vertices.size() != 0); // Create the new hyperedge. hyperedges_ptr_->emplace_back(std::move(vertices)); // Update connected vertices. assert(hyperedges_ptr_->back().vertices().size() != 0); for (auto vertex_ptr : hyperedges_ptr_->back().vertices()) { assert(vertex_ptr != nullptr); vertex_ptr->hyperedges().emplace_back(&hyperedges_ptr_->back()); } } /// @internal std::deque<vertex_type>& vertices() noexcept { return *vertices_ptr_; } /// @internal const std::deque<vertex_type>& vertices() const noexcept { return *vertices_ptr_; } /// @internal std::deque<hyperedge_type>& hyperedges() noexcept { return *hyperedges_ptr_; } /// @internal const std::deque<hyperedge_type>& hyperedges() const noexcept { return *hyperedges_ptr_; } }; /*------------------------------------------------------------------------------------------------*/ }} // namespace sdd::force #endif // _SDD_ORDER_STRATEGIES_FORCE_HYPERGRAPH_HH_
[ "alexandre.hamez@gmail.com" ]
alexandre.hamez@gmail.com
9512fa5b82c84f907510b45988dd60732ff1639b
8abc7e35c37a3197cc2d0ec1f82d269f835294de
/testing/main.cpp
7bb09b1d5f8030c29ed9b8172c754961ab9c93c0
[]
no_license
jsren/osstdlib
8d46b05214f5a1c7b1fe6f3936e4484c4159b745
221ad786ec965d6492775dfa20f86efe657530a0
refs/heads/master
2021-07-14T08:41:15.167580
2021-07-05T21:29:47
2021-07-05T21:29:47
18,315,309
0
0
null
2017-07-24T19:10:48
2014-04-01T02:32:13
C++
UTF-8
C++
false
false
2,875
cpp
#if 1 #include <string> #include <tuple> #include <__platform> namespace std { } static auto print(const std::string& string) { __platform::size_t count; __platform::__write(__platform::__stdout, string.c_str(), string.size(), count); return count; } int main2() { char buffer[124]{}; (void)buffer; //auto count = __platform::__read(__platform::__stdin, buffer, sizeof(buffer)); /* __platform::__open_options opts{}; opts.read = true; opts.write = true; __platform::__file_acl mode{}; mode.userRead = true; mode.userWrite = true; mode.groupRead = true; mode.groupWrite = true; mode.othersRead = true; mode.othersWrite = true; auto handle = __platform::__open("test.txt", opts, __platform::__file_acl()); auto read1 = __platform::__read(handle, buffer, sizeof(buffer)); auto seek1 = __platform::__seek(handle, 0, __platform::__seek_whence::end); buffer[read1] = '1'; auto write2 = __platform::__write(handle, buffer, read1 + 1); __platform::__close(handle); std::string msg{"Handle 1: "}; msg += std::to_string(handle.value); msg += "\n"; std::string wmsg{"Wrote "}; wmsg += std::to_string(read1 + 1); wmsg += " bytes\n"; auto write3 = print(wmsg); msg += "\nRead 1: "; msg += std::to_string(read1); msg += "\nSeek 1: "; msg += std::to_string(seek1); msg += "\nWrite 2: "; msg += std::to_string(write2); msg += "\nWrite 3: "; msg += std::to_string(write3); msg += "\n"; print(msg);*/ print(std::to_string(0) += "\n"); print(std::to_string(1) += "\n"); print(std::to_string(9) += "\n"); print(std::to_string(10) += "\n"); print(std::to_string(11) += "\n"); print(std::to_string(99) += "\n"); print(std::to_string(100) += "\n"); print(std::to_string(101) += "\n"); print(std::to_string(109) += "\n"); print(std::to_string(110) += "\n"); print(std::to_string(111) += "\n"); print(std::to_string(999) += "\n"); print(std::to_string(1000) += "\n"); print(std::to_string(-0) += "\n"); print(std::to_string(-1) += "\n"); print(std::to_string(-9) += "\n"); print(std::to_string(-10) += "\n"); print(std::to_string(-11) += "\n"); print(std::to_string(-99) += "\n"); print(std::to_string(-100) += "\n"); print(std::to_string(-101) += "\n"); print(std::to_string(-109) += "\n"); print(std::to_string(-110) += "\n"); print(std::to_string(-111) += "\n"); print(std::to_string(-999) += "\n"); print(std::to_string(-1000) += "\n"); return 0; } #else #include <stdio.h> int main() { char buffer[125]; auto count = scanf("%s", buffer); buffer[count] = '\0'; printf("Hello, %s\n", buffer); return 0; } #endif
[ "jsrenwick3@gmail.com" ]
jsrenwick3@gmail.com
c92fa134218297f41cb268e680235045a03364ff
9fa2502e98b9779e16be62c65cca060ee4282061
/include/ui/RenderParam.h
eb671fc6debdbf878a9aa39f34e7aa76a2680e5e
[]
no_license
zjhlogo/spank_old
558d617c44e3f6b53bb4e26167f55d8cb7f5098c
8030f21d98ac743baf0681bbb626e76c489d8711
refs/heads/master
2021-01-23T13:48:16.189834
2012-12-16T03:45:40
2012-12-16T03:45:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
747
h
/*! * \file RenderParam.h * \date 8-25-2011 15:53:46 * * * \author zjhlogo (zjhlogo@gmail.com) */ #ifndef __RENDERPARAM_H__ #define __RENDERPARAM_H__ #include "../math/IMath.h" #include "BaseTypeUI.h" #include "UIRect.h" class RenderParam { public: RenderParam(); RenderParam(const Vector2& renderOffset, const UIRect& parentRect); RenderParam(const RenderParam& param); ~RenderParam(); RenderParam& operator=(const RenderParam& param); void SetRenderState(uint nMask, bool bEnable); bool CheckRenderState(uint nMask) const; void SetEnable(bool bEnable); bool IsEnable() const; public: Vector2 m_renderOffset; UIRect m_parentRect; uint m_nRenderState; }; #endif // __RENDERPARAM_H__
[ "zjhlogo@181a2263-6311-9be6-e15f-e484ee8db88e" ]
zjhlogo@181a2263-6311-9be6-e15f-e484ee8db88e
cebe763943a3371eb78063560367dfc1b172e2d0
8a5f01447a0cf775ebf2b11e15c903f2a4e9f7da
/src_single_thread_vll/backend/collapsed_versioned_storage.h
249a40d6af4a0612589e93185b4403ea13c6fcfb
[]
no_license
jingleyang/Calvin_mod
4c408464a80e83c0926db71e69a4d075a247bb69
e789c003d2675391c2b0f467c10e06bfe5f41de1
refs/heads/master
2021-01-10T09:11:12.710714
2016-03-03T15:35:08
2016-03-03T15:35:08
52,209,368
1
1
null
null
null
null
UTF-8
C++
false
false
2,818
h
// Author: Thaddeus Diamond (diamond@cs.yale.edu) // // This implements a simple collapsed storage that can be used in a versioned // deterministic database system. #ifndef _DB_BACKEND_COLLAPSED_VERSIONED_STORAGE_H_ #define _DB_BACKEND_COLLAPSED_VERSIONED_STORAGE_H_ #include <climits> #include <cstring> #include <tr1/unordered_map> #include "backend/versioned_storage.h" #define CHKPNTDIR "../db/checkpoints" using std::tr1::unordered_map; struct DataNode { int64 txn_id; Value* value; DataNode* next; }; class CollapsedVersionedStorage : public VersionedStorage { public: CollapsedVersionedStorage() { stable_ = 0; #ifdef TPCCHACK memset(&NewOrderStore, 0, sizeof(NewOrderStore)); memset(&OrderStore, 0, sizeof(OrderStore)); memset(&OrderLineStore, 0, sizeof(OrderLineStore)); memset(&HistoryStore, 0, sizeof(HistoryStore)); #endif } virtual ~CollapsedVersionedStorage() {} // TODO(Thad and Philip): How can we incorporate this type of versioned // storage into the work that you've been doing with prefetching? It seems // like we could do something optimistic with writing to disk and avoiding // having to checkpoint, but we should see. // Standard operators in the DB virtual Value* ReadObject(const Key& key, int64 txn_id = LLONG_MAX); virtual bool PutObject(const Key& key, Value* value, int64 txn_id); virtual bool DeleteObject(const Key& key, int64 txn_id); // Specify the overloaded parent functions we are using here using VersionedStorage::Prefetch; using VersionedStorage::Unfetch; // At a new versioned state, the version system is notified that the // previously stable values are no longer necessary. At this point in time, // the database can switch the labels as to what is stable (the previously // frozen values) to a new txn_id occurring in the future. virtual void PrepareForCheckpoint(int64 stable) { stable_ = stable; } virtual int Checkpoint(); // The capture checkpoint method is an internal method that allows us to // write out the stable checkpoint to disk. virtual void CaptureCheckpoint(); private: // We make a simple mapping of keys to a map of "versions" of our value. // The int64 represents a simple transaction id and the Value associated with // it is whatever value was written out at that time. unordered_map<Key, DataNode*> objects_; // The stable and frozen int64 represent which transaction ID's are stable // to write out to storage, and which should be the latest to be overwritten // in the current database execution cycle, respectively. int64 stable_; }; static inline void* RunCheckpointer(void* storage) { (reinterpret_cast<CollapsedVersionedStorage*>(storage))->CaptureCheckpoint(); return NULL; } #endif // _DB_BACKEND_COLLAPSED_VERSIONED_STORAGE_H_
[ "renkun.nwpu@gmail.com" ]
renkun.nwpu@gmail.com
4aa173954e27411df950f66b7820b2515bfa4cca
3a01d6f6e9f7db7428ae5dc286d6bc267c4ca13e
/unittests/libtests/bc/data/AbsorbingDampersDataHex8.hh
32e62ae38f906771d8e2bf86f9d50cf3aec33f21
[ "MIT" ]
permissive
youngsolar/pylith
1ee9f03c2b01560706b44b4ccae99c3fb6b9fdf4
62c07b91fa7581641c7b2a0f658bde288fa003de
refs/heads/master
2020-12-26T04:04:21.884785
2014-10-06T21:42:42
2014-10-06T21:42:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,863
hh
// -*- C++ -*- // // ====================================================================== // // Brad T. Aagaard, U.S. Geological Survey // Charles A. Williams, GNS Science // Matthew G. Knepley, University of Chicago // // This code was developed as part of the Computational Infrastructure // for Geodynamics (http://geodynamics.org). // // Copyright (c) 2010-2014 University of California, Davis // // See COPYING for license information. // // ====================================================================== // #if !defined(pylith_bc_absorbingdampersdatahex8_hh) #define pylith_bc_absorbingdampersdatahex8_hh #include "AbsorbingDampersData.hh" namespace pylith { namespace bc { class AbsorbingDampersDataHex8; } // pylith } // bc class pylith::bc::AbsorbingDampersDataHex8 : public AbsorbingDampersData { public: /// Constructor AbsorbingDampersDataHex8(void); /// Destructor ~AbsorbingDampersDataHex8(void); private: static const char* _meshFilename; static const int _numBasis; static const int _numQuadPts; static const PylithScalar _quadPts[]; static const PylithScalar _quadWts[]; static const PylithScalar _basis[]; static const PylithScalar _basisDerivRef[]; static const char* _spatialDBFilename; static const int _id; static const char* _label; static const PylithScalar _dt; static const PylithScalar _fieldTIncr[]; static const PylithScalar _fieldT[]; static const PylithScalar _fieldTmdt[]; static const int _spaceDim; static const int _cellDim; static const int _numVertices; static const int _numCells; static const int _numCorners; static const int _cells[]; static const PylithScalar _dampingConsts[]; static const PylithScalar _valsResidual[]; static const PylithScalar _valsJacobian[]; }; #endif // pylith_bc_absorbingdampersdatahex8_hh // End of file
[ "baagaard@usgs.gov" ]
baagaard@usgs.gov
9183c7bd9e435a804eeebf6fdef712c623a94390
def39f068050b234df9f6909d4277f96b740f11c
/E-olimp/85. Spiral .cpp
67844df93d4026e167e083a2746dd7f7773fd900
[]
no_license
azecoder/Problem-Solving
41a9a4302c48c8de59412ab9175b253df99f1f28
a920b7bac59830c7b798127f6eed0e2ab31a5fa2
refs/heads/master
2023-02-10T09:47:48.322849
2021-01-05T14:14:09
2021-01-05T14:14:09
157,236,604
5
1
null
null
null
null
UTF-8
C++
false
false
952
cpp
#include <stdio.h> #include <stdlib.h> int n, i, j, k, c=1; int a[101][101]; int main() { scanf("%d",&n); int x,v; scanf("%d %d",&x,&v); for(k=0;k<n/2;k++) { for(i=k;i<n-k;i++) { a[k][i]=c; c++; } for(i=k+1;i<=n-k-1;i++) { a[i][n-k-1]=c; c++; } for(i=n-k-1-1;i>=k;i--) { a[n-k-1][i]=c; c++; } for(i=n-k-1-1;i>k;i--) { a[i][k]=c; c++; } } if(n%2!=0) { a[(n/2)][(n/2)]=c; c++; } for(i=0;i<n;i++) { for(j=0;j<n;j++) { if(i==x-1 && j==v-1) break; } } printf("%d",a[x-1][v-1]); printf("\n"); return 0; }
[ "tabriz.haji@gmail.com" ]
tabriz.haji@gmail.com
53f082defff65b653cd2b26c4794fb92deaab9ce
fae5e7e614a55d024288f8d3d758b879a1000026
/Game/Star.h
18f221166f2edb163b14e1d6163607e56b823831
[]
no_license
SaikiRyuji/Game_alf
1a55686083517ef28c83c242d17aa4e1a4bda513
1e52aafd7aa7d9812a093426e560fb8b45f4f9ac
refs/heads/master
2020-04-04T02:58:08.971503
2019-03-04T02:17:58
2019-03-04T02:17:58
155,702,721
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
395
h
#pragma once class Star:public GameObject { public: Star(); ~Star(); bool Start(CVector3 pos, CQuaternion rot); void Update()override; //描画処理 void Render() override; //モデル座標を取得 CVector3 GetPosition() { return m_position; } void SetPosition(CVector3 pos) { m_position = pos; } private: SkinModel m_model; CVector3 m_position; CQuaternion m_rotation; };
[ "kbc17b12@stu.kawahara.ac.jp" ]
kbc17b12@stu.kawahara.ac.jp
565f3f7263b28151a500591d21995bfa1ee62ac7
3809e9f5122b7d82009c643ba236cf5d54eb349b
/src/qt/signverifymessagedialog.cpp
2842ed1846754f19e3a704289b4b28e87ae333fa
[ "MIT" ]
permissive
wincoinproject/wincoin
22aba9f845fd11099c31b630b9b0b82a48b4b525
6db2591255041afffdf9d52dd1d1ef3a50ec9110
refs/heads/master
2016-09-10T10:09:44.803592
2014-05-24T00:17:53
2014-05-24T00:17:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,695
cpp
#include "signverifymessagedialog.h" #include "ui_signverifymessagedialog.h" #include "addressbookpage.h" #include "base58.h" #include "guiutil.h" #include "init.h" #include "main.h" #include "optionsmodel.h" #include "walletmodel.h" #include "wallet.h" #include <string> #include <vector> #include <QClipboard> SignVerifyMessageDialog::SignVerifyMessageDialog(QWidget *parent) : QDialog(parent), ui(new Ui::SignVerifyMessageDialog), model(0) { ui->setupUi(this); #if (QT_VERSION >= 0x040700) /* Do not move this to the XML file, Qt before 4.7 will choke on it */ ui->addressIn_SM->setPlaceholderText(tr("Enter a WinCoin address")); ui->signatureOut_SM->setPlaceholderText(tr("Click \"Sign Message\" to generate signature")); ui->addressIn_VM->setPlaceholderText(tr("Enter a WinCoin address")); ui->signatureIn_VM->setPlaceholderText(tr("Enter WinCoin signature")); #endif GUIUtil::setupAddressWidget(ui->addressIn_SM, this); GUIUtil::setupAddressWidget(ui->addressIn_VM, this); ui->addressIn_SM->installEventFilter(this); ui->messageIn_SM->installEventFilter(this); ui->signatureOut_SM->installEventFilter(this); ui->addressIn_VM->installEventFilter(this); ui->messageIn_VM->installEventFilter(this); ui->signatureIn_VM->installEventFilter(this); ui->signatureOut_SM->setFont(GUIUtil::bitcoinAddressFont()); ui->signatureIn_VM->setFont(GUIUtil::bitcoinAddressFont()); } SignVerifyMessageDialog::~SignVerifyMessageDialog() { delete ui; } void SignVerifyMessageDialog::setModel(WalletModel *model) { this->model = model; } void SignVerifyMessageDialog::setAddress_SM(QString address) { ui->addressIn_SM->setText(address); ui->messageIn_SM->setFocus(); } void SignVerifyMessageDialog::setAddress_VM(QString address) { ui->addressIn_VM->setText(address); ui->messageIn_VM->setFocus(); } void SignVerifyMessageDialog::showTab_SM(bool fShow) { ui->tabWidget->setCurrentIndex(0); if (fShow) this->show(); } void SignVerifyMessageDialog::showTab_VM(bool fShow) { ui->tabWidget->setCurrentIndex(1); if (fShow) this->show(); } void SignVerifyMessageDialog::on_addressBookButton_SM_clicked() { if (model && model->getAddressTableModel()) { AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::ReceivingTab, this); dlg.setModel(model->getAddressTableModel()); if (dlg.exec()) { setAddress_SM(dlg.getReturnValue()); } } } void SignVerifyMessageDialog::on_pasteButton_SM_clicked() { setAddress_SM(QApplication::clipboard()->text()); } void SignVerifyMessageDialog::on_signMessageButton_SM_clicked() { /* Clear old signature to ensure users don't get confused on error with an old signature displayed */ ui->signatureOut_SM->clear(); CBitcoinAddress addr(ui->addressIn_SM->text().toStdString()); if (!addr.IsValid()) { ui->addressIn_SM->setValid(false); ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again.")); return; } CKeyID keyID; if (!addr.GetKeyID(keyID)) { ui->addressIn_SM->setValid(false); ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again.")); return; } WalletModel::UnlockContext ctx(model->requestUnlock()); if (!ctx.isValid()) { ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("Wallet unlock was cancelled.")); return; } CKey key; if (!pwalletMain->GetKey(keyID, key)) { ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("Private key for the entered address is not available.")); return; } CDataStream ss(SER_GETHASH, 0); ss << strMessageMagic; ss << ui->messageIn_SM->document()->toPlainText().toStdString(); std::vector<unsigned char> vchSig; if (!key.SignCompact(Hash(ss.begin(), ss.end()), vchSig)) { ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signing failed.") + QString("</nobr>")); return; } ui->statusLabel_SM->setStyleSheet("QLabel { color: green; }"); ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signed.") + QString("</nobr>")); ui->signatureOut_SM->setText(QString::fromStdString(EncodeBase64(&vchSig[0], vchSig.size()))); } void SignVerifyMessageDialog::on_copySignatureButton_SM_clicked() { QApplication::clipboard()->setText(ui->signatureOut_SM->text()); } void SignVerifyMessageDialog::on_clearButton_SM_clicked() { ui->addressIn_SM->clear(); ui->messageIn_SM->clear(); ui->signatureOut_SM->clear(); ui->statusLabel_SM->clear(); ui->addressIn_SM->setFocus(); } void SignVerifyMessageDialog::on_addressBookButton_VM_clicked() { if (model && model->getAddressTableModel()) { AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this); dlg.setModel(model->getAddressTableModel()); if (dlg.exec()) { setAddress_VM(dlg.getReturnValue()); } } } void SignVerifyMessageDialog::on_verifyMessageButton_VM_clicked() { CBitcoinAddress addr(ui->addressIn_VM->text().toStdString()); if (!addr.IsValid()) { ui->addressIn_VM->setValid(false); ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again.")); return; } CKeyID keyID; if (!addr.GetKeyID(keyID)) { ui->addressIn_VM->setValid(false); ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again.")); return; } bool fInvalid = false; std::vector<unsigned char> vchSig = DecodeBase64(ui->signatureIn_VM->text().toStdString().c_str(), &fInvalid); if (fInvalid) { ui->signatureIn_VM->setValid(false); ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(tr("The signature could not be decoded.") + QString(" ") + tr("Please check the signature and try again.")); return; } CDataStream ss(SER_GETHASH, 0); ss << strMessageMagic; ss << ui->messageIn_VM->document()->toPlainText().toStdString(); CKey key; if (!key.SetCompactSignature(Hash(ss.begin(), ss.end()), vchSig)) { ui->signatureIn_VM->setValid(false); ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(tr("The signature did not match the message digest.") + QString(" ") + tr("Please check the signature and try again.")); return; } if (!(CBitcoinAddress(key.GetPubKey().GetID()) == addr)) { ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verification failed.") + QString("</nobr>")); return; } ui->statusLabel_VM->setStyleSheet("QLabel { color: green; }"); ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verified.") + QString("</nobr>")); } void SignVerifyMessageDialog::on_clearButton_VM_clicked() { ui->addressIn_VM->clear(); ui->signatureIn_VM->clear(); ui->messageIn_VM->clear(); ui->statusLabel_VM->clear(); ui->addressIn_VM->setFocus(); } bool SignVerifyMessageDialog::eventFilter(QObject *object, QEvent *event) { if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::FocusIn) { if (ui->tabWidget->currentIndex() == 0) { /* Clear status message on focus change */ ui->statusLabel_SM->clear(); /* Select generated signature */ if (object == ui->signatureOut_SM) { ui->signatureOut_SM->selectAll(); return true; } } else if (ui->tabWidget->currentIndex() == 1) { /* Clear status message on focus change */ ui->statusLabel_VM->clear(); } } return QDialog::eventFilter(object, event); }
[ "wincoin29386593826@yahoo.com" ]
wincoin29386593826@yahoo.com
4a40a87cfcdefba6dd610f8aaf5038f1db6222b6
921282e89ffaafb41019b634391b608909779e29
/include/dr/shp/detail.hpp
72dd85d46ba645f02b6d78d3b59467e0ae68e8a0
[ "BSD-3-Clause" ]
permissive
kilobyte/distributed-ranges
1c9b198cc4fe1448d5246b927ecf0d94c734d79a
9271e7bbd18df1dcdda4761c5f1735937e093260
refs/heads/main
2023-07-21T09:29:39.951745
2023-05-09T13:21:40
2023-05-09T13:21:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,970
hpp
// SPDX-FileCopyrightText: Intel Corporation // // SPDX-License-Identifier: BSD-3-Clause #pragma once #include <dr/detail/ranges.hpp> #include <dr/shp/device_ptr.hpp> #include <dr/shp/init.hpp> #include <dr/shp/util/sycl_utils.hpp> #include <iterator> #include <sycl/sycl.hpp> namespace dr::shp { namespace __detail { inline constexpr auto local = dr::ranges::__detail::local; template <typename Src, typename Dest> concept is_syclmemcopyable = std::is_same_v<std::remove_const_t<Src>, Dest> && std::is_trivially_copyable_v<Dest>; template <std::contiguous_iterator Iter> sycl::usm::alloc get_pointer_type(Iter iter) { return sycl::get_pointer_type(std::to_address(iter), shp::context()); } template <typename T> sycl::usm::alloc get_pointer_type(shp::device_ptr<T> ptr) { return sycl::get_pointer_type(ptr.get_raw_pointer(), shp::context()); } template <std::contiguous_iterator Iter> sycl::device get_pointer_device(Iter iter) { return sycl::get_pointer_device(std::to_address(iter), shp::context()); } template <typename T> sycl::device get_pointer_device(shp::device_ptr<T> ptr) { return sycl::get_pointer_device(ptr.get_raw_pointer(), shp::context()); } template <typename InputIt> sycl::queue &get_queue_for_pointer(InputIt iter) { if (get_pointer_type(iter) == sycl::usm::alloc::device) { auto device = get_pointer_device(iter); return __detail::queue(device); } else { return default_queue(); } } template <typename InputIt, typename OutputIt> sycl::queue &get_queue_for_pointers(InputIt iter, OutputIt iter2) { if (get_pointer_type(iter) == sycl::usm::alloc::device) { auto device = get_pointer_device(iter); return __detail::queue(device); } else if (get_pointer_type(iter2) == sycl::usm::alloc::device) { auto device = get_pointer_device(iter2); return __detail::queue(device); } else { return default_queue(); } } } // namespace __detail } // namespace dr::shp
[ "noreply@github.com" ]
noreply@github.com
736e054cb88d1ce222ad9e2d3b5baebe350ea81e
4c88a8ffe438227c03139c2a7f1f30aff731bbf0
/src/ntp.cpp
7dd5e8f111da56eb6c2b0019cd6fa2a9d7792f2e
[ "MIT" ]
permissive
bankercoins/banker-coinsrc
ae9677a5be48bf959880d120954e7fca71f135de
d9c864185473d8eca4f392328a0dc467c2d56337
refs/heads/master
2021-05-08T07:47:04.107172
2017-10-13T11:20:18
2017-10-13T11:20:18
106,815,222
0
0
null
null
null
null
UTF-8
C++
false
false
14,647
cpp
#ifdef WIN32 #include <winsock2.h> #else #include <sys/socket.h> #include <sys/time.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #endif #ifndef WIN32 #include <unistd.h> #endif #include "netbase.h" #include "net.h" //#include "util.h" #include "ui_interface.h" extern int GetRandInt(int nMax); /* * NTP uses two fixed point formats. The first (l_fp) is the "long" * format and is 64 bits long with the decimal between bits 31 and 32. * This is used for time stamps in the NTP packet header (in network * byte order) and for internal computations of offsets (in local host * byte order). We use the same structure for both signed and unsigned * values, which is a big hack but saves rewriting all the operators * twice. Just to confuse this, we also sometimes just carry the * fractional part in calculations, in both signed and unsigned forms. * Anyway, an l_fp looks like: * * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Integral Part | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Fractional Part | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * REF http://www.eecis.udel.edu/~mills/database/rfc/rfc2030.txt */ typedef struct { union { uint32_t Xl_ui; int32_t Xl_i; } Ul_i; union { uint32_t Xl_uf; int32_t Xl_f; } Ul_f; } l_fp; inline void Ntp2Unix(const uint32_t &n, time_t &u) { // Ntp's time scale starts in 1900, Unix in 1970. u = n - 0x83aa7e80; // 2208988800 1970 - 1900 in seconds } inline void ntohl_fp(l_fp *n, l_fp *h) { (h)->Ul_i.Xl_ui = ntohl((n)->Ul_i.Xl_ui); (h)->Ul_f.Xl_uf = ntohl((n)->Ul_f.Xl_uf); } struct pkt { uint8_t li_vn_mode; /* leap indicator, version and mode */ uint8_t stratum; /* peer stratum */ uint8_t ppoll; /* peer poll interval */ int8_t precision; /* peer clock precision */ uint32_t rootdelay; /* distance to primary clock */ uint32_t rootdispersion; /* clock dispersion */ uint32_t refid; /* reference clock ID */ l_fp ref; /* time peer clock was last updated */ l_fp org; /* originate time stamp */ l_fp rec; /* receive time stamp */ l_fp xmt; /* transmit time stamp */ uint32_t exten[1]; /* misused */ uint8_t mac[5 * sizeof(uint32_t)]; /* mac */ }; const int nServersCount = 162; std::string NtpServers[162] = { // Microsoft "time.windows.com", // Google "time1.google.com", "time2.google.com", "time3.google.com", "time4.google.com", // Hurricane Electric "clock.sjc.he.net", "clock.nyc.he.net", // SixXS "ntp.sixxs.net", "ntp.eu.sixxs.net", "ntp.us.sixxs.net", "ntp.ap.sixxs.net", // Russian Federation "ntp.karelia.pro", "ntp.alpet.me", "aviel.alpet.me", "ntp.sampo.ru", "ntp.szt.ru", "ntp.ix.ru", "ntp1.stratum2.ru", "ntp2.stratum2.ru", "ntp3.stratum2.ru", "ntp4.stratum2.ru", "ntp5.stratum2.ru", "ntp6.stratum2.ru", "ntp7.stratum2.ru", "ntp1.stratum1.ru", "ntp2.stratum1.ru", "ntp3.stratum1.ru", "ntp4.stratum1.ru", "ntp1.vniiftri.ru", "ntp2.vniiftri.ru", "ntp3.vniiftri.ru", "ntp4.vniiftri.ru", "ntp21.vniiftri.ru", "ntp1.niiftri.irkutsk.ru", "ntp2.niiftri.irkutsk.ru", "vniiftri.khv.ru", "vniiftri2.khv.ru", "ntp0.zenon.net", "ntp.mobatime.ru", "0.ru.pool.ntp.org", "1.ru.pool.ntp.org", "2.ru.pool.ntp.org", "3.ru.pool.ntp.org", // United States "tock.cs.unlv.edu", "timex.cs.columbia.edu", "tick.cs.unlv.edu", "sundial.columbia.edu", "ntp-1.ece.cmu.edu", "ntp-2.ece.cmu.edu", "ntp1.cs.wisc.edu", "ntp2.cs.wisc.edu", "ntp3.cs.wisc.edu", "ntp-01.caltech.edu", "ntp-02.caltech.edu", "ntp-03.caltech.edu", "ntp-04.caltech.edu", "nist1-pa.ustiming.org", "time.nist.gov", "time-a.nist.gov", "time-b.nist.gov", "time-c.nist.gov", "time-d.nist.gov", "time-nw.nist.gov", "nist1-macon.macon.ga.us", "nist.netservicesgroup.com", "nisttime.carsoncity.k12.mi.us", "nist1-lnk.binary.net", "wwv.nist.gov", "time-a.timefreq.bldrdoc.gov", "time-b.timefreq.bldrdoc.gov", "time-c.timefreq.bldrdoc.gov", "utcnist.colorado.edu", "utcnist2.colorado.edu", "ntp-nist.ldsbc.net", "nist1-lv.ustiming.org", "time-nw.nist.gov", "nist-time-server.eoni.com", "nist-time-server.eoni.com", "ntp1.bu.edu", "ntp2.bu.edu", "ntp3.bu.edu", "0.us.pool.ntp.org", "1.us.pool.ntp.org", "2.us.pool.ntp.org", "3.us.pool.ntp.org", "wwv.otc.psu.edu", "otc1.psu.edu", "otc2.psu.edu", "now.okstate.edu", "ntp.colby.edu", "bonehed.lcs.mit.edu", "ntp-s1.cise.ufl.edu", // South Africa "ntp1.meraka.csir.co.za", "ntp.is.co.za", "ntp2.is.co.za", "igubu.saix.net", "ntp1.neology.co.za", "ntp2.neology.co.za", "tick.meraka.csir.co.za", "tock.meraka.csir.co.za", "ntp.time.org.za", "ntp1.meraka.csir.co.za", "ntp2.meraka.csir.co.za", "0.za.pool.ntp.org", "1.za.pool.ntp.org", "2.za.pool.ntp.org", "3.za.pool.ntp.org", // Italy "ntp0.ien.it", "ntp1.ien.it", "ntp2.ien.it", "ntp1.inrim.it", "ntp2.inrim.it", "0.it.pool.ntp.org", "1.it.pool.ntp.org", "2.it.pool.ntp.org", "3.it.pool.ntp.org", // Netherlands "ntp0.nl.net", "ntp1.nl.net", "ntp2.nl.net", "ntp.utwente.nl", "0.nl.pool.ntp.org", "1.nl.pool.ntp.org", "2.nl.pool.ntp.org", "3.nl.pool.ntp.org", // United Kingdom "ntp2d.mcc.ac.uk", "ntp2c.mcc.ac.uk", "ntp2b.mcc.ac.uk", "ntp.exnet.com", "ntp.cis.strath.ac.uk", "ntppub.le.ac.uk", "0.uk.pool.ntp.org", "1.uk.pool.ntp.org", "2.uk.pool.ntp.org", "3.uk.pool.ntp.org", // Canada "chime.utoronto.ca", "tick.utoronto.ca", "time.nrc.ca", "timelord.uregina.ca", "tock.utoronto.ca", "www1.cmc.ec.gc.ca", "www2.cmc.ec.gc.ca", "0.ca.pool.ntp.org", "1.ca.pool.ntp.org", "2.ca.pool.ntp.org", "3.ca.pool.ntp.org", // Japan "ntp.nict.jp", "0.jp.pool.ntp.org", "1.jp.pool.ntp.org", "2.jp.pool.ntp.org", "3.jp.pool.ntp.org", // Australia "ntp.cs.mu.oz.au", "augean.eleceng.adelaide.edu.au", "0.au.pool.ntp.org", "1.au.pool.ntp.org", "2.au.pool.ntp.org", "3.au.pool.ntp.org", // Slovenia "time.ijs.si", // Austria "0.at.pool.ntp.org", "1.at.pool.ntp.org", "2.at.pool.ntp.org", "3.at.pool.ntp.org", // ??? "clepsydra.dec.com", // ... To be continued }; bool InitWithHost(const std::string &strHostName, SOCKET &sockfd, socklen_t &servlen, struct sockaddr *pcliaddr) { sockfd = INVALID_SOCKET; std::vector<CNetAddr> vIP; bool fRet = LookupHost(strHostName.c_str(), vIP, 10, true); if (!fRet) { return false; } struct sockaddr_in servaddr; servaddr.sin_family = AF_INET; servaddr.sin_port = htons(123); bool found = false; for(unsigned int i = 0; i < vIP.size(); i++) { if ((found = vIP[i].GetInAddr(&servaddr.sin_addr)) != false) { break; } } if (!found) { return false; } sockfd = socket(AF_INET, SOCK_DGRAM, 0); if (sockfd == INVALID_SOCKET) return false; // socket initialization error if (connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) == -1 ) { return false; // "connection" error } *pcliaddr = *((struct sockaddr *) &servaddr); servlen = sizeof(servaddr); return true; } bool InitWithRandom(SOCKET &sockfd, socklen_t &servlen, struct sockaddr *pcliaddr) { for (int nAttempt = 0; nAttempt < nServersCount; nAttempt++) { int nServerNum = GetRandInt(nServersCount); if (InitWithHost(NtpServers[nServerNum], sockfd, servlen, pcliaddr)) { return true; } } return false; } int64_t DoReq(SOCKET sockfd, socklen_t servlen, struct sockaddr cliaddr) { #ifdef WIN32 u_long nOne = 1; if (ioctlsocket(sockfd, FIONBIO, &nOne) == SOCKET_ERROR) { printf("ConnectSocket() : ioctlsocket non-blocking setting failed, error %d\n", WSAGetLastError()); #else if (fcntl(sockfd, F_SETFL, O_NONBLOCK) == SOCKET_ERROR) { printf("ConnectSocket() : fcntl non-blocking setting failed, error %d\n", errno); #endif return -2; } struct timeval timeout = {10, 0}; struct pkt *msg = new pkt; struct pkt *prt = new pkt; time_t seconds_transmit; int len = 48; msg->li_vn_mode=227; msg->stratum=0; msg->ppoll=4; msg->precision=0; msg->rootdelay=0; msg->rootdispersion=0; msg->ref.Ul_i.Xl_i=0; msg->ref.Ul_f.Xl_f=0; msg->org.Ul_i.Xl_i=0; msg->org.Ul_f.Xl_f=0; msg->rec.Ul_i.Xl_i=0; msg->rec.Ul_f.Xl_f=0; msg->xmt.Ul_i.Xl_i=0; msg->xmt.Ul_f.Xl_f=0; int retcode = sendto(sockfd, (char *) msg, len, 0, &cliaddr, servlen); if (retcode < 0) { printf("sendto() failed: %d\n", retcode); seconds_transmit = -3; goto _end; } fd_set fdset; FD_ZERO(&fdset); FD_SET(sockfd, &fdset); retcode = select(sockfd + 1, &fdset, NULL, NULL, &timeout); if (retcode <= 0) { printf("recvfrom() error\n"); seconds_transmit = -4; goto _end; } recvfrom(sockfd, (char *) msg, len, 0, NULL, NULL); ntohl_fp(&msg->xmt, &prt->xmt); Ntp2Unix(prt->xmt.Ul_i.Xl_ui, seconds_transmit); _end: delete msg; delete prt; return seconds_transmit; } int64_t NtpGetTime(CNetAddr& ip) { struct sockaddr cliaddr; SOCKET sockfd; socklen_t servlen; if (!InitWithRandom(sockfd, servlen, &cliaddr)) return -1; ip = CNetAddr(((sockaddr_in *)&cliaddr)->sin_addr); int64_t nTime = DoReq(sockfd, servlen, cliaddr); closesocket(sockfd); return nTime; } int64_t NtpGetTime(const std::string &strHostName) { struct sockaddr cliaddr; SOCKET sockfd; socklen_t servlen; if (!InitWithHost(strHostName, sockfd, servlen, &cliaddr)) return -1; int64_t nTime = DoReq(sockfd, servlen, cliaddr); closesocket(sockfd); return nTime; } // NTP server, which we unconditionally trust. This may be your own installation of ntpd somewhere, for example. // "localhost" means "trust no one" std::string strTrustedUpstream = "localhost"; // Current offset int64_t nNtpOffset = INT64_MAX; int64_t GetNtpOffset() { return nNtpOffset; } void ThreadNtpSamples(void* parg) { const int64_t nMaxOffset = 86400; // Not a real limit, just sanity threshold. printf("Trying to find NTP server at localhost...\n"); std::string strLocalHost = "127.0.0.1"; if (NtpGetTime(strLocalHost) == GetTime()) { printf("There is NTP server active at localhost, we don't need NTP thread.\n"); nNtpOffset = 0; return; } printf("ThreadNtpSamples started\n"); vnThreadsRunning[THREAD_NTP]++; // Make this thread recognisable as time synchronization thread RenameThread("Bankercoin-ntp-samples"); CMedianFilter<int64_t> vTimeOffsets(200,0); while (!fShutdown) { if (strTrustedUpstream != "localhost") { // Trying to get new offset sample from trusted NTP server. int64_t nClockOffset = NtpGetTime(strTrustedUpstream) - GetTime(); if (abs64(nClockOffset) < nMaxOffset) { // Everything seems right, remember new trusted offset. printf("ThreadNtpSamples: new offset sample from %s, offset=%" PRId64 ".\n", strTrustedUpstream.c_str(), nClockOffset); nNtpOffset = nClockOffset; } else { // Something went wrong, disable trusted offset sampling. nNtpOffset = INT64_MAX; strTrustedUpstream = "localhost"; int nSleepMinutes = 1 + GetRandInt(9); // Sleep for 1-10 minutes. for (int i = 0; i < nSleepMinutes * 60 && !fShutdown; i++) Sleep(1000); continue; } } else { // Now, trying to get 2-4 samples from random NTP servers. int nSamplesCount = 2 + GetRandInt(2); for (int i = 0; i < nSamplesCount; i++) { CNetAddr ip; int64_t nClockOffset = NtpGetTime(ip) - GetTime(); if (abs64(nClockOffset) < nMaxOffset) { // Skip the deliberately wrong timestamps printf("ThreadNtpSamples: new offset sample from %s, offset=%" PRId64 ".\n", ip.ToString().c_str(), nClockOffset); vTimeOffsets.input(nClockOffset); } } if (vTimeOffsets.size() > 1) { nNtpOffset = vTimeOffsets.median(); } else { // Not enough offsets yet, try to collect additional samples later. nNtpOffset = INT64_MAX; int nSleepMinutes = 1 + GetRandInt(4); // Sleep for 1-5 minutes. for (int i = 0; i < nSleepMinutes * 60 && !fShutdown; i++) Sleep(1000); continue; } } if (GetNodesOffset() == INT_MAX && abs64(nNtpOffset) > 40 * 60) { // If there is not enough node offsets data and NTP time offset is greater than 40 minutes then give a warning. std::string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong Bankercoin will not work properly."); strMiscWarning = strMessage; printf("*** %s\n", strMessage.c_str()); uiInterface.ThreadSafeMessageBox(strMessage+" ", std::string("Bankercoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION); } printf("nNtpOffset = %+" PRId64 " (%+" PRId64 " minutes)\n", nNtpOffset, nNtpOffset/60); int nSleepHours = 1 + GetRandInt(5); // Sleep for 1-6 hours. for (int i = 0; i < nSleepHours * 3600 && !fShutdown; i++) Sleep(1000); } vnThreadsRunning[THREAD_NTP]--; printf("ThreadNtpSamples exited\n"); }
[ "bankercoins@gmail.com" ]
bankercoins@gmail.com
c2f19166493054a0247794d6210b86f4907e51cc
4b57a589522321be483f5d6ee355e461ef580cd7
/Course-Work/Course-Work/Jacobi.h
302c1c3ce5c28828c7889c4cc5379041a65d09b1
[ "MIT" ]
permissive
ALEXKIRNAS/Course-Work-OP
f05dc6f04169dbc389e03eec34e036cf2b1526f1
49ac2f2771dd9b8c29af457f0be885ec04e90b19
refs/heads/master
2021-01-18T15:04:00.469730
2016-06-16T18:04:12
2016-06-16T18:04:12
54,399,419
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
510
h
#pragma once #include "Utilities.h" using utilities::system; namespace Jacobi { double* Jacobi(utilities::system&); // Прототип функції рішення системи методом Якобі bool isSolved(utilities::system&); // Прототип функції перевірки на сходимість метода Якобі void nextSolution(utilities::system&, double*, double *); // Прототип функції знаходження наступного наближення };
[ "alexkirnas@ukr.net" ]
alexkirnas@ukr.net
1f3b55d00882c365afa5779fc1aa77074fab9b33
f588bd3b9a3f8233650c3ee6c253122af1a2d1ed
/cpp/defualtpara.cpp
5cd6b9ee31d2f73c2dca5ea60eb145c39e1b19ef
[]
no_license
Omarabdul3ziz/lowlvl
e9b100fcacfcb798e1a2358d5879a61853cee2d3
3613ebc31ecc7159e5b3d41a126e663354746413
refs/heads/master
2022-12-26T14:56:32.387125
2020-10-02T00:44:18
2020-10-02T00:44:18
300,027,872
0
0
null
null
null
null
UTF-8
C++
false
false
206
cpp
#include <iostream> using namespace std; void display (int n=3, char c='.') { for (int i=0; i<n; ++i) cout << c; cout << endl;} int main () { display(5,'*'); display(6); display(); return 0;}
[ "omarabdul3ziz@gmail.com" ]
omarabdul3ziz@gmail.com
b0c9c4e13e4e9c36a21a0bb537629326ccd53a75
78041dc623558078537cff39451ce3617ce30a83
/2017-10-10 Recursivitat 1/p3.cc
964a48763839a232b93e9c470eff5cd91dd70450
[]
no_license
alexjustbarcelona/ap1-codis-2017-2018
c8a6f5b9d762e37913bb07a9aea9688e870d14e7
296544c9cf12d7e5c1302790e2a8363d6cd0569a
refs/heads/master
2021-09-25T13:11:05.570835
2018-10-22T08:09:56
2018-10-22T08:09:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
229
cc
// Funció recursiva que calcula el màxim comú divisor de dos naturals int mcd(int a, int b) { if (a == 0) return b; return mcd(b%a, a); } // O també: int mcd(int a, int b) { return a == 0 ? b : mcd(b%a, a); }
[ "jordi.petit@gmail.com" ]
jordi.petit@gmail.com
4c06341779385caf4595f27d3641f475de8ac3c2
fa014d90469ec6045093fa53668f575c36db23b3
/lab5/src/type.h
d9f083e8e22ddb4d0138334a621e2465cfd56940
[]
no_license
suntianq/compiler
113eae53e39ffe9ee7ef5328f366fbf57740a97d
660b891fe5354d64323a82ee1aedab3e03cd02a3
refs/heads/master
2023-07-01T21:05:09.272651
2021-08-01T01:55:14
2021-08-01T01:55:14
317,736,341
0
0
null
null
null
null
UTF-8
C++
false
false
1,186
h
#ifndef TYPESYSTEM_H #define TYPESYSTEM_H #include "./pch.h" using namespace std; enum ValueType { VALUE_BOOL, VALUE_INT, VALUE_CHAR, VALUE_STRING, VALUE_DOUBLE, VALUE_VOID, VALUE_CITE, VALUE_POINT, COMPOSE_STRUCT, COMPOSE_UNION, COMPOSE_FUNCTION }; class Type { public: ValueType type; Type(ValueType valueType); public: /* 如果你要设计复杂类型系统的话,可以修改这一部分 */ ValueType* childType; // for union or struct ValueType* paramType, retType; // for function void addChild(Type* t); void addParam(Type* t); void addRet(Type* t); public: ValueType* sibling; public: string getTypeInfo(); }; // 设置几个常量Type,可以节省空间开销 static Type* TYPE_INT = new Type(VALUE_INT); static Type* TYPE_CHAR = new Type(VALUE_CHAR); static Type* TYPE_BOOL = new Type(VALUE_BOOL); static Type* TYPE_STRING = new Type(VALUE_STRING); static Type* TYPE_DOUBLE = new Type(VALUE_DOUBLE); static Type* TYPE_VOID = new Type(VALUE_VOID); static Type* TYPE_POINT = new Type(VALUE_POINT); static Type* TYPE_CITE = new Type(VALUE_CITE); int getSize(Type* type); #endif
[ "401159047@qq.com" ]
401159047@qq.com
42cd5b688c9af52dd73fb195334930e8c77c6229
0f4e9ebbff0fee56fc9fdb732a3e6cfabfc748fa
/implement/InitParser.cpp
c47d09e1798e159e1439daf8fe40256bbc81d44a
[]
no_license
Reisbey-1/EagCommon_6
779648409c529eb31d726ac6ba7b2539a5af1517
570eea5890b9c9129d3d4474692887c1713525e4
refs/heads/main
2023-06-25T02:46:31.473486
2021-07-18T20:32:46
2021-07-18T20:32:46
387,263,821
0
0
null
null
null
null
UTF-8
C++
false
false
1,637
cpp
// InitParser.cpp: Implementierung der Klasse CInitParser. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "InitParser.h" ////////////////////////////////////////////////////////////////////// // Konstruktion/Destruktion ////////////////////////////////////////////////////////////////////// namespace eag { CInitParser::CInitParser() { } CInitParser::~CInitParser() { } void CInitParser::GetNextToken(DString &r_dstrSource, CString &Key, CString &value, CString &trash) { int sizeofsource = r_dstrSource.laenge(); wchar_t *tmp = new wchar_t[sizeofsource+1]; do { _wcsnset(tmp,0,sizeofsource); r_dstrSource.get(tmp,sizeofsource,'<'); trash = tmp; r_dstrSource.get(tmp,2,'>'); _wcsnset(tmp,0,sizeofsource); r_dstrSource.get(tmp,sizeofsource,'>'); Key = tmp; r_dstrSource.get(tmp,2,' '); _wcsnset(tmp,0,sizeofsource); r_dstrSource.get(tmp,sizeofsource,'\n'); RemoveLastLF(tmp); value = tmp; r_dstrSource.get(tmp,2,' '); } while (Key.GetLength() ? (Key[0] == '*') : FALSE); delete tmp; value.TrimLeft(); value.TrimRight(); return ; } void CInitParser::RemoveLastLF(wchar_t *txt) { for (int i=0; txt[i] != 0; i++) if ( ((txt[i] == '\r') && (txt[i+1] == 0 )) || ((txt[i] == '\r') && (txt[i+1] == '\n')) || ((txt[i] == '\r') && (txt[i+1] == '\r')) || ((txt[i] == '\n') && (txt[i+1] == 0 )) || ((txt[i] == '\n') && (txt[i+1] == '\n')) || ((txt[i] == '\n') && (txt[i+1] == '\r')) ) txt[i] = 0; } } // end of namespace
[ "noreply@github.com" ]
noreply@github.com
3dcba254f067a991f91036b0bbbaf1e93f155aca
4d1170276bb928d1fa967a5cddac0210511d9282
/src/common/os/Condition.hxx
21f7a66f6a6953a3b9ac3ea617e69a1fa8f31fc2
[ "VSL-1.0" ]
permissive
resiprocate/msrp
de2fa2fb859a2609c760765f99d167929daf2cf1
44da1ee1f4cd1096f856d14578a460453b1c0d95
refs/heads/master
2016-09-10T11:17:36.498979
2005-06-13T23:28:48
2005-06-13T23:28:48
24,416,133
0
1
null
null
null
null
UTF-8
C++
false
false
4,116
hxx
#if !defined(MSRP_CONDITION_HXX) #define MSRP_CONDITION_HXX #if defined(WIN32) # include <windows.h> # include <winbase.h> #else # include <pthread.h> #endif // !kh! // Attempt to resolve POSIX behaviour conformance for win32 build. #define RESIP_CONDITION_WIN32_CONFORMANCE_TO_POSIX namespace msrp { class Mutex; class Condition { public: Condition(); virtual ~Condition(); void wait (Mutex& mtx); /** returns true if the condition was woken up by activity, false if timeout. * or interrupt. */ bool wait (Mutex& mutex, unsigned int ms); // !kh! // deprecate these? void wait (Mutex* mutex); bool wait (Mutex* mutex, unsigned int ms); /** Signal one waiting thread. * Returns 0, if successful, or an errorcode. */ void signal(); /** Signal all waiting threads. * Returns 0, if successful, or an errorcode. */ void broadcast(); private: // !kh! // no value sematics, therefore private and not implemented. Condition (const Condition&); Condition& operator= (const Condition&); private: #ifdef WIN32 # ifdef RESIP_CONDITION_WIN32_CONFORMANCE_TO_POSIX // !kh! // boost clone with modification // credit boost? void enterWait (); void* m_gate; void* m_queue; void* m_mutex; unsigned m_gone; // # threads that timed out and never made it to m_queue unsigned long m_blocked; // # threads blocked on the condition unsigned m_waiting; // # threads no longer waiting for the condition but // still waiting to be removed from m_queue # else HANDLE mId; # endif #else mutable pthread_cond_t mId; #endif }; } #endif /* ==================================================================== * The Vovida Software License, Version 1.0 * * Copyright (c) 2000 Vovida Networks, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 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 names "VOCAL", "Vovida Open Communication Application Library", * and "Vovida Open Communication Application Library (VOCAL)" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact vocal@vovida.org. * * 4. Products derived from this software may not be called "VOCAL", nor * may "VOCAL" appear in their name, without prior written * permission of Vovida Networks, Inc. * * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND * NON-INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL VOVIDA * NETWORKS, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT DAMAGES * IN EXCESS OF $1,000, NOR FOR ANY 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. * * ==================================================================== * * This software consists of voluntary contributions made by Vovida * Networks, Inc. and many individuals on behalf of Vovida Networks, * Inc. For more information on Vovida Networks, Inc., please see * <http://www.vovida.org/>. * */
[ "daniel@xten.com" ]
daniel@xten.com
e62d1e9059617f2fff566cb5d8d92b4775c327d6
73ee941896043f9b3e2ab40028d24ddd202f695f
/external/chromium_org/chrome/browser/chromeos/drive/file_cache_unittest.cc
34435064a01f83d655e2d2bcc4657c0e16d7925c
[ "BSD-3-Clause" ]
permissive
CyFI-Lab-Public/RetroScope
d441ea28b33aceeb9888c330a54b033cd7d48b05
276b5b03d63f49235db74f2c501057abb9e79d89
refs/heads/master
2022-04-08T23:11:44.482107
2016-09-22T20:15:43
2016-09-22T20:15:43
58,890,600
5
3
null
null
null
null
UTF-8
C++
false
false
36,473
cc
// Copyright (c) 2012 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. #include "chrome/browser/chromeos/drive/file_cache.h" #include <string> #include <vector> #include "base/file_util.h" #include "base/files/file_enumerator.h" #include "base/files/scoped_temp_dir.h" #include "base/md5.h" #include "base/run_loop.h" #include "base/threading/sequenced_worker_pool.h" #include "chrome/browser/chromeos/drive/drive.pb.h" #include "chrome/browser/chromeos/drive/fake_free_disk_space_getter.h" #include "chrome/browser/chromeos/drive/file_cache_metadata.h" #include "chrome/browser/chromeos/drive/file_system_util.h" #include "chrome/browser/chromeos/drive/resource_metadata_storage.h" #include "chrome/browser/chromeos/drive/test_util.h" #include "chrome/browser/google_apis/test_util.h" #include "content/public/browser/browser_thread.h" #include "content/public/test/test_browser_thread_bundle.h" #include "testing/gtest/include/gtest/gtest.h" namespace drive { namespace internal { namespace { // Bitmask of cache states in FileCacheEntry. enum TestFileCacheState { TEST_CACHE_STATE_NONE = 0, TEST_CACHE_STATE_PINNED = 1 << 0, TEST_CACHE_STATE_PRESENT = 1 << 1, TEST_CACHE_STATE_DIRTY = 1 << 2, }; // Copies results from Iterate(). void OnIterate(std::vector<std::string>* out_resource_ids, std::vector<FileCacheEntry>* out_cache_entries, const std::string& resource_id, const FileCacheEntry& cache_entry) { out_resource_ids->push_back(resource_id); out_cache_entries->push_back(cache_entry); } // Called upon completion of Iterate(). void OnIterateCompleted(bool* out_is_called) { *out_is_called = true; } } // namespace // Tests FileCache methods from UI thread. It internally uses a real blocking // pool and tests the interaction among threads. // TODO(hashimoto): remove this class. crbug.com/231221. class FileCacheTestOnUIThread : public testing::Test { protected: FileCacheTestOnUIThread() : expected_error_(FILE_ERROR_OK), expected_cache_state_(0) { } virtual void SetUp() OVERRIDE { ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); ASSERT_TRUE(file_util::CreateDirectory( temp_dir_.path().Append(util::kMetadataDirectory))); ASSERT_TRUE(file_util::CreateDirectory( temp_dir_.path().Append(util::kCacheFileDirectory))); ASSERT_TRUE(file_util::CreateTemporaryFileInDir(temp_dir_.path(), &dummy_file_path_)); fake_free_disk_space_getter_.reset(new FakeFreeDiskSpaceGetter); scoped_refptr<base::SequencedWorkerPool> pool = content::BrowserThread::GetBlockingPool(); blocking_task_runner_ = pool->GetSequencedTaskRunner(pool->GetSequenceToken()); metadata_storage_.reset(new ResourceMetadataStorage( temp_dir_.path(), blocking_task_runner_.get())); bool success = false; base::PostTaskAndReplyWithResult( blocking_task_runner_.get(), FROM_HERE, base::Bind(&ResourceMetadataStorage::Initialize, base::Unretained(metadata_storage_.get())), google_apis::test_util::CreateCopyResultCallback(&success)); test_util::RunBlockingPoolTask(); ASSERT_TRUE(success); cache_.reset(new FileCache( metadata_storage_.get(), temp_dir_.path().Append(util::kCacheFileDirectory), blocking_task_runner_.get(), fake_free_disk_space_getter_.get())); success = false; base::PostTaskAndReplyWithResult( blocking_task_runner_.get(), FROM_HERE, base::Bind(&FileCache::Initialize, base::Unretained(cache_.get())), google_apis::test_util::CreateCopyResultCallback(&success)); test_util::RunBlockingPoolTask(); ASSERT_TRUE(success); } void TestGetFile(const std::string& resource_id, FileError expected_error) { FileError error = FILE_ERROR_OK; base::FilePath cache_file_path; cache_->GetFileOnUIThread(resource_id, google_apis::test_util::CreateCopyResultCallback( &error, &cache_file_path)); test_util::RunBlockingPoolTask(); EXPECT_EQ(expected_error, error); if (error == FILE_ERROR_OK) { // Verify filename of |cache_file_path|. EXPECT_EQ(util::EscapeCacheFileName(resource_id), cache_file_path.BaseName().AsUTF8Unsafe()); } else { EXPECT_TRUE(cache_file_path.empty()); } } void TestStoreToCache(const std::string& resource_id, const std::string& md5, const base::FilePath& source_path, FileError expected_error, int expected_cache_state) { expected_error_ = expected_error; expected_cache_state_ = expected_cache_state; FileError error = FILE_ERROR_OK; cache_->StoreOnUIThread( resource_id, md5, source_path, FileCache::FILE_OPERATION_COPY, google_apis::test_util::CreateCopyResultCallback(&error)); test_util::RunBlockingPoolTask(); if (error == FILE_ERROR_OK) { FileCacheEntry cache_entry; EXPECT_TRUE(GetCacheEntryFromOriginThread(resource_id, &cache_entry)); EXPECT_EQ(md5, cache_entry.md5()); } VerifyCacheFileState(error, resource_id); } void TestRemoveFromCache(const std::string& resource_id, FileError expected_error) { expected_error_ = expected_error; FileError error = FILE_ERROR_OK; cache_->RemoveOnUIThread( resource_id, google_apis::test_util::CreateCopyResultCallback(&error)); test_util::RunBlockingPoolTask(); VerifyRemoveFromCache(error, resource_id); } void VerifyRemoveFromCache(FileError error, const std::string& resource_id) { EXPECT_EQ(expected_error_, error); FileCacheEntry cache_entry; if (!GetCacheEntryFromOriginThread(resource_id, &cache_entry)) { EXPECT_EQ(FILE_ERROR_OK, error); const base::FilePath path = cache_->GetCacheFilePath(resource_id); EXPECT_FALSE(base::PathExists(path)); } } void TestPin(const std::string& resource_id, FileError expected_error, int expected_cache_state) { expected_error_ = expected_error; expected_cache_state_ = expected_cache_state; FileError error = FILE_ERROR_OK; cache_->PinOnUIThread( resource_id, google_apis::test_util::CreateCopyResultCallback(&error)); test_util::RunBlockingPoolTask(); VerifyCacheFileState(error, resource_id); } void TestUnpin(const std::string& resource_id, FileError expected_error, int expected_cache_state) { expected_error_ = expected_error; expected_cache_state_ = expected_cache_state; FileError error = FILE_ERROR_OK; cache_->UnpinOnUIThread( resource_id, google_apis::test_util::CreateCopyResultCallback(&error)); test_util::RunBlockingPoolTask(); VerifyCacheFileState(error, resource_id); } void TestMarkDirty(const std::string& resource_id, FileError expected_error, int expected_cache_state) { expected_error_ = expected_error; expected_cache_state_ = expected_cache_state; FileError error = FILE_ERROR_OK; cache_->MarkDirtyOnUIThread( resource_id, google_apis::test_util::CreateCopyResultCallback(&error)); test_util::RunBlockingPoolTask(); VerifyCacheFileState(error, resource_id); // Verify filename. if (error == FILE_ERROR_OK) { base::FilePath cache_file_path; cache_->GetFileOnUIThread( resource_id, google_apis::test_util::CreateCopyResultCallback( &error, &cache_file_path)); test_util::RunBlockingPoolTask(); EXPECT_EQ(FILE_ERROR_OK, error); EXPECT_EQ(util::EscapeCacheFileName(resource_id), cache_file_path.BaseName().AsUTF8Unsafe()); } } void TestClearDirty(const std::string& resource_id, const std::string& md5, FileError expected_error, int expected_cache_state) { expected_error_ = expected_error; expected_cache_state_ = expected_cache_state; FileError error = FILE_ERROR_OK; PostTaskAndReplyWithResult( blocking_task_runner_.get(), FROM_HERE, base::Bind(&FileCache::ClearDirty, base::Unretained(cache_.get()), resource_id, md5), google_apis::test_util::CreateCopyResultCallback(&error)); test_util::RunBlockingPoolTask(); if (error == FILE_ERROR_OK) { FileCacheEntry cache_entry; EXPECT_TRUE(GetCacheEntryFromOriginThread(resource_id, &cache_entry)); EXPECT_EQ(md5, cache_entry.md5()); } VerifyCacheFileState(error, resource_id); } void TestMarkAsMounted(const std::string& resource_id, FileError expected_error, int expected_cache_state) { expected_error_ = expected_error; expected_cache_state_ = expected_cache_state; FileCacheEntry entry; EXPECT_TRUE(GetCacheEntryFromOriginThread(resource_id, &entry)); FileError error = FILE_ERROR_OK; base::FilePath cache_file_path; cache_->MarkAsMountedOnUIThread( resource_id, google_apis::test_util::CreateCopyResultCallback( &error, &cache_file_path)); test_util::RunBlockingPoolTask(); EXPECT_TRUE(base::PathExists(cache_file_path)); EXPECT_EQ(cache_file_path, cache_->GetCacheFilePath(resource_id)); } void TestMarkAsUnmounted(const std::string& resource_id, const base::FilePath& file_path, FileError expected_error, int expected_cache_state) { expected_error_ = expected_error; expected_cache_state_ = expected_cache_state; FileError error = FILE_ERROR_OK; cache_->MarkAsUnmountedOnUIThread( file_path, google_apis::test_util::CreateCopyResultCallback(&error)); test_util::RunBlockingPoolTask(); base::FilePath cache_file_path; cache_->GetFileOnUIThread( resource_id, google_apis::test_util::CreateCopyResultCallback( &error, &cache_file_path)); test_util::RunBlockingPoolTask(); EXPECT_EQ(FILE_ERROR_OK, error); EXPECT_TRUE(base::PathExists(cache_file_path)); EXPECT_EQ(cache_file_path, cache_->GetCacheFilePath(resource_id)); } void VerifyCacheFileState(FileError error, const std::string& resource_id) { EXPECT_EQ(expected_error_, error); // Verify cache map. FileCacheEntry cache_entry; const bool cache_entry_found = GetCacheEntryFromOriginThread(resource_id, &cache_entry); if ((expected_cache_state_ & TEST_CACHE_STATE_PRESENT) || (expected_cache_state_ & TEST_CACHE_STATE_PINNED)) { ASSERT_TRUE(cache_entry_found); EXPECT_EQ((expected_cache_state_ & TEST_CACHE_STATE_PINNED) != 0, cache_entry.is_pinned()); EXPECT_EQ((expected_cache_state_ & TEST_CACHE_STATE_PRESENT) != 0, cache_entry.is_present()); EXPECT_EQ((expected_cache_state_ & TEST_CACHE_STATE_DIRTY) != 0, cache_entry.is_dirty()); } else { EXPECT_FALSE(cache_entry_found); } // Verify actual cache file. base::FilePath dest_path = cache_->GetCacheFilePath(resource_id); EXPECT_EQ((expected_cache_state_ & TEST_CACHE_STATE_PRESENT) != 0, base::PathExists(dest_path)); } // Helper function to call GetCacheEntry from origin thread. bool GetCacheEntryFromOriginThread(const std::string& resource_id, FileCacheEntry* cache_entry) { bool result = false; cache_->GetCacheEntryOnUIThread( resource_id, google_apis::test_util::CreateCopyResultCallback(&result, cache_entry)); test_util::RunBlockingPoolTask(); return result; } // Returns true if the cache entry exists for the given resource ID. bool CacheEntryExists(const std::string& resource_id) { FileCacheEntry cache_entry; return GetCacheEntryFromOriginThread(resource_id, &cache_entry); } // Returns the number of the cache files with name <resource_id>, and Confirm // that they have the <md5>. This should return 1 or 0. size_t CountCacheFiles(const std::string& resource_id, const std::string& md5) { base::FilePath path = cache_->GetCacheFilePath(resource_id); base::FileEnumerator enumerator(path.DirName(), false, // recursive base::FileEnumerator::FILES, path.BaseName().value()); size_t num_files_found = 0; for (base::FilePath current = enumerator.Next(); !current.empty(); current = enumerator.Next()) { ++num_files_found; EXPECT_EQ(util::EscapeCacheFileName(resource_id), current.BaseName().AsUTF8Unsafe()); } return num_files_found; } content::TestBrowserThreadBundle thread_bundle_; scoped_refptr<base::SequencedTaskRunner> blocking_task_runner_; base::ScopedTempDir temp_dir_; base::FilePath dummy_file_path_; scoped_ptr<ResourceMetadataStorage, test_util::DestroyHelperForTests> metadata_storage_; scoped_ptr<FileCache, test_util::DestroyHelperForTests> cache_; scoped_ptr<FakeFreeDiskSpaceGetter> fake_free_disk_space_getter_; FileError expected_error_; int expected_cache_state_; std::string expected_file_extension_; }; TEST_F(FileCacheTestOnUIThread, StoreToCacheSimple) { std::string resource_id("pdf:1a2b"); std::string md5("abcdef0123456789"); // Store an existing file. TestStoreToCache(resource_id, md5, dummy_file_path_, FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT); // Store a non-existent file to the same |resource_id| and |md5|. TestStoreToCache(resource_id, md5, base::FilePath::FromUTF8Unsafe("non_existent_file"), FILE_ERROR_FAILED, TEST_CACHE_STATE_PRESENT); // Store a different existing file to the same |resource_id| but different // |md5|. md5 = "new_md5"; TestStoreToCache(resource_id, md5, dummy_file_path_, FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT); // Verify that there's only one file with name <resource_id>, i.e. previously // cached file with the different md5 should be deleted. EXPECT_EQ(1U, CountCacheFiles(resource_id, md5)); } TEST_F(FileCacheTestOnUIThread, GetFromCacheSimple) { std::string resource_id("pdf:1a2b"); std::string md5("abcdef0123456789"); // First store a file to cache. TestStoreToCache(resource_id, md5, dummy_file_path_, FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT); // Then try to get the existing file from cache. TestGetFile(resource_id, FILE_ERROR_OK); // Get file from cache with different resource id. resource_id = "document:1a2b"; TestGetFile(resource_id, FILE_ERROR_NOT_FOUND); } TEST_F(FileCacheTestOnUIThread, RemoveFromCacheSimple) { // Use alphanumeric characters for resource id. std::string resource_id("pdf:1a2b"); std::string md5("abcdef0123456789"); // First store a file to cache. TestStoreToCache(resource_id, md5, dummy_file_path_, FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT); // Then try to remove existing file from cache. TestRemoveFromCache(resource_id, FILE_ERROR_OK); // Repeat using non-alphanumeric characters for resource id, including '.' // which is an extension separator. resource_id = "pdf:`~!@#$%^&*()-_=+[{|]}\\;',<.>/?"; TestStoreToCache(resource_id, md5, dummy_file_path_, FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT); TestRemoveFromCache(resource_id, FILE_ERROR_OK); } TEST_F(FileCacheTestOnUIThread, PinAndUnpin) { std::string resource_id("pdf:1a2b"); std::string md5("abcdef0123456789"); // First store a file to cache. TestStoreToCache(resource_id, md5, dummy_file_path_, FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT); // Pin the existing file in cache. TestPin(resource_id, FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT | TEST_CACHE_STATE_PINNED); // Unpin the existing file in cache. TestUnpin(resource_id, FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT); // Pin back the same existing file in cache. TestPin(resource_id, FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT | TEST_CACHE_STATE_PINNED); // Pin a non-existent file in cache. resource_id = "document:1a2b"; TestPin(resource_id, FILE_ERROR_OK, TEST_CACHE_STATE_PINNED); // Unpin the previously pinned non-existent file in cache. TestUnpin(resource_id, FILE_ERROR_OK, TEST_CACHE_STATE_NONE); // Unpin a file that doesn't exist in cache and is not pinned, i.e. cache // has zero knowledge of the file. resource_id = "not-in-cache:1a2b"; TestUnpin(resource_id, FILE_ERROR_NOT_FOUND, TEST_CACHE_STATE_NONE); } TEST_F(FileCacheTestOnUIThread, StoreToCachePinned) { std::string resource_id("pdf:1a2b"); std::string md5("abcdef0123456789"); // Pin a non-existent file. TestPin(resource_id, FILE_ERROR_OK, TEST_CACHE_STATE_PINNED); // Store an existing file to a previously pinned file. TestStoreToCache(resource_id, md5, dummy_file_path_, FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT | TEST_CACHE_STATE_PINNED); // Store a non-existent file to a previously pinned and stored file. TestStoreToCache(resource_id, md5, base::FilePath::FromUTF8Unsafe("non_existent_file"), FILE_ERROR_FAILED, TEST_CACHE_STATE_PRESENT | TEST_CACHE_STATE_PINNED); } TEST_F(FileCacheTestOnUIThread, GetFromCachePinned) { std::string resource_id("pdf:1a2b"); std::string md5("abcdef0123456789"); // Pin a non-existent file. TestPin(resource_id, FILE_ERROR_OK, TEST_CACHE_STATE_PINNED); // Get the non-existent pinned file from cache. TestGetFile(resource_id, FILE_ERROR_NOT_FOUND); // Store an existing file to the previously pinned non-existent file. TestStoreToCache(resource_id, md5, dummy_file_path_, FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT | TEST_CACHE_STATE_PINNED); // Get the previously pinned and stored file from cache. TestGetFile(resource_id, FILE_ERROR_OK); } TEST_F(FileCacheTestOnUIThread, RemoveFromCachePinned) { // Use alphanumeric characters for resource_id. std::string resource_id("pdf:1a2b"); std::string md5("abcdef0123456789"); // Store a file to cache, and pin it. TestStoreToCache(resource_id, md5, dummy_file_path_, FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT); TestPin(resource_id, FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT | TEST_CACHE_STATE_PINNED); // Remove |resource_id| from cache. TestRemoveFromCache(resource_id, FILE_ERROR_OK); // Repeat using non-alphanumeric characters for resource id, including '.' // which is an extension separator. resource_id = "pdf:`~!@#$%^&*()-_=+[{|]}\\;',<.>/?"; TestStoreToCache(resource_id, md5, dummy_file_path_, FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT); TestPin(resource_id, FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT | TEST_CACHE_STATE_PINNED); TestRemoveFromCache(resource_id, FILE_ERROR_OK); } TEST_F(FileCacheTestOnUIThread, DirtyCacheSimple) { std::string resource_id("pdf:1a2b"); std::string md5("abcdef0123456789"); // First store a file to cache. TestStoreToCache(resource_id, md5, dummy_file_path_, FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT); // Mark the file dirty. TestMarkDirty(resource_id, FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT | TEST_CACHE_STATE_DIRTY); // Clear dirty state of the file. TestClearDirty(resource_id, md5, FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT); } TEST_F(FileCacheTestOnUIThread, DirtyCachePinned) { std::string resource_id("pdf:1a2b"); std::string md5("abcdef0123456789"); // First store a file to cache and pin it. TestStoreToCache(resource_id, md5, dummy_file_path_, FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT); TestPin(resource_id, FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT | TEST_CACHE_STATE_PINNED); // Mark the file dirty. TestMarkDirty(resource_id, FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT | TEST_CACHE_STATE_DIRTY | TEST_CACHE_STATE_PINNED); // Clear dirty state of the file. TestClearDirty(resource_id, md5, FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT | TEST_CACHE_STATE_PINNED); } TEST_F(FileCacheTestOnUIThread, PinAndUnpinDirtyCache) { std::string resource_id("pdf:1a2b"); std::string md5("abcdef0123456789"); // First store a file to cache and mark it as dirty. TestStoreToCache(resource_id, md5, dummy_file_path_, FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT); TestMarkDirty(resource_id, FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT | TEST_CACHE_STATE_DIRTY); // Verifies dirty file exists. base::FilePath dirty_path; FileError error = FILE_ERROR_FAILED; cache_->GetFileOnUIThread( resource_id, google_apis::test_util::CreateCopyResultCallback(&error, &dirty_path)); test_util::RunBlockingPoolTask(); EXPECT_EQ(FILE_ERROR_OK, error); EXPECT_TRUE(base::PathExists(dirty_path)); // Pin the dirty file. TestPin(resource_id, FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT | TEST_CACHE_STATE_DIRTY | TEST_CACHE_STATE_PINNED); // Verify dirty file still exist at the same pathname. EXPECT_TRUE(base::PathExists(dirty_path)); // Unpin the dirty file. TestUnpin(resource_id, FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT | TEST_CACHE_STATE_DIRTY); // Verify dirty file still exist at the same pathname. EXPECT_TRUE(base::PathExists(dirty_path)); } TEST_F(FileCacheTestOnUIThread, DirtyCacheRepetitive) { std::string resource_id("pdf:1a2b"); std::string md5("abcdef0123456789"); // First store a file to cache. TestStoreToCache(resource_id, md5, dummy_file_path_, FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT); // Mark the file dirty. TestMarkDirty(resource_id, FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT | TEST_CACHE_STATE_DIRTY); // Again, mark the file dirty. Nothing should change. TestMarkDirty(resource_id, FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT | TEST_CACHE_STATE_DIRTY); // Clear dirty state of the file. TestClearDirty(resource_id, md5, FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT); // Again, clear dirty state of the file, which is no longer dirty. TestClearDirty(resource_id, md5, FILE_ERROR_INVALID_OPERATION, TEST_CACHE_STATE_PRESENT); } TEST_F(FileCacheTestOnUIThread, DirtyCacheInvalid) { std::string resource_id("pdf:1a2b"); std::string md5("abcdef0123456789"); // Mark a non-existent file dirty. TestMarkDirty(resource_id, FILE_ERROR_NOT_FOUND, TEST_CACHE_STATE_NONE); // Clear dirty state of a non-existent file. TestClearDirty(resource_id, md5, FILE_ERROR_NOT_FOUND, TEST_CACHE_STATE_NONE); // Store a file to cache. TestStoreToCache(resource_id, md5, dummy_file_path_, FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT); // Clear dirty state of a non-dirty existing file. TestClearDirty(resource_id, md5, FILE_ERROR_INVALID_OPERATION, TEST_CACHE_STATE_PRESENT); // Mark an existing file dirty, then store a new file to the same resource id // but different md5, which should fail. TestMarkDirty(resource_id, FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT | TEST_CACHE_STATE_DIRTY); md5 = "new_md5"; TestStoreToCache(resource_id, md5, dummy_file_path_, FILE_ERROR_IN_USE, TEST_CACHE_STATE_PRESENT | TEST_CACHE_STATE_DIRTY); } TEST_F(FileCacheTestOnUIThread, RemoveFromDirtyCache) { std::string resource_id("pdf:1a2b"); std::string md5("abcdef0123456789"); // Store a file to cache, pin it, mark it dirty and commit it. TestStoreToCache(resource_id, md5, dummy_file_path_, FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT); TestPin(resource_id, FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT | TEST_CACHE_STATE_PINNED); TestMarkDirty(resource_id, FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT | TEST_CACHE_STATE_PINNED | TEST_CACHE_STATE_DIRTY); // Try to remove the file. Dirty caches can be removed at the level of // FileCache::Remove. Upper layer cache clearance functions like // FreeDiskSpaceIfNeededFor() and RemoveStaleCacheFiles() takes care of // securing dirty files. TestRemoveFromCache(resource_id, FILE_ERROR_OK); } TEST_F(FileCacheTestOnUIThread, MountUnmount) { std::string resource_id("pdf:1a2b"); std::string md5("abcdef0123456789"); // First store a file to cache. TestStoreToCache(resource_id, md5, dummy_file_path_, FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT); // Mark the file mounted. TestMarkAsMounted(resource_id, FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT); EXPECT_TRUE(CacheEntryExists(resource_id)); // Try to remove the file. TestRemoveFromCache(resource_id, FILE_ERROR_IN_USE); // Clear mounted state of the file. base::FilePath file_path; FileError error = FILE_ERROR_FAILED; cache_->GetFileOnUIThread( resource_id, google_apis::test_util::CreateCopyResultCallback(&error, &file_path)); test_util::RunBlockingPoolTask(); EXPECT_EQ(FILE_ERROR_OK, error); TestMarkAsUnmounted(resource_id, file_path, FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT); EXPECT_TRUE(CacheEntryExists(resource_id)); // Try to remove the file. TestRemoveFromCache(resource_id, FILE_ERROR_OK); } TEST_F(FileCacheTestOnUIThread, Iterate) { const std::vector<test_util::TestCacheResource> cache_resources( test_util::GetDefaultTestCacheResources()); ASSERT_TRUE(test_util::PrepareTestCacheResources(cache_.get(), cache_resources)); std::vector<std::string> resource_ids; std::vector<FileCacheEntry> cache_entries; bool completed = false; cache_->IterateOnUIThread( base::Bind(&OnIterate, &resource_ids, &cache_entries), base::Bind(&OnIterateCompleted, &completed)); test_util::RunBlockingPoolTask(); ASSERT_TRUE(completed); sort(resource_ids.begin(), resource_ids.end()); ASSERT_EQ(6U, resource_ids.size()); EXPECT_EQ("dirty:existing", resource_ids[0]); EXPECT_EQ("dirty_and_pinned:existing", resource_ids[1]); EXPECT_EQ("pinned:existing", resource_ids[2]); EXPECT_EQ("pinned:non-existent", resource_ids[3]); EXPECT_EQ("tmp:`~!@#$%^&*()-_=+[{|]}\\;',<.>/?", resource_ids[4]); EXPECT_EQ("tmp:resource_id", resource_ids[5]); ASSERT_EQ(6U, cache_entries.size()); } TEST_F(FileCacheTestOnUIThread, ClearAll) { std::string resource_id("pdf:1a2b"); std::string md5("abcdef0123456789"); // Store an existing file. TestStoreToCache(resource_id, md5, dummy_file_path_, FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT); // Verify that there's only one cached file. EXPECT_EQ(1U, CountCacheFiles(resource_id, md5)); // Clear cache. bool success = false; cache_->ClearAllOnUIThread( google_apis::test_util::CreateCopyResultCallback(&success)); test_util::RunBlockingPoolTask(); EXPECT_TRUE(success); // Verify that all the cache is removed. expected_error_ = FILE_ERROR_OK; VerifyRemoveFromCache(FILE_ERROR_OK, resource_id); EXPECT_EQ(0U, CountCacheFiles(resource_id, md5)); } TEST_F(FileCacheTestOnUIThread, StoreToCacheNoSpace) { fake_free_disk_space_getter_->set_default_value(0); std::string resource_id("pdf:1a2b"); std::string md5("abcdef0123456789"); // Try to store an existing file. TestStoreToCache(resource_id, md5, dummy_file_path_, FILE_ERROR_NO_LOCAL_SPACE, TEST_CACHE_STATE_NONE); // Verify that there's no files added. EXPECT_EQ(0U, CountCacheFiles(resource_id, md5)); } TEST_F(FileCacheTestOnUIThread, UpdatePinnedCache) { std::string resource_id("pdf:1a2b"); std::string md5("abcdef0123456789"); std::string md5_modified("aaaaaa0000000000"); // Store an existing file. TestStoreToCache(resource_id, md5, dummy_file_path_, FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT); // Pin the file. TestPin(resource_id, FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT | TEST_CACHE_STATE_PINNED); // Store the file with a modified content and md5. It should stay pinned. TestStoreToCache(resource_id, md5_modified, dummy_file_path_, FILE_ERROR_OK, TEST_CACHE_STATE_PRESENT | TEST_CACHE_STATE_PINNED); } // Tests FileCache methods working with the blocking task runner. class FileCacheTest : public testing::Test { protected: virtual void SetUp() OVERRIDE { ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); ASSERT_TRUE(file_util::CreateDirectory( temp_dir_.path().Append(util::kMetadataDirectory))); ASSERT_TRUE(file_util::CreateDirectory( temp_dir_.path().Append(util::kCacheFileDirectory))); fake_free_disk_space_getter_.reset(new FakeFreeDiskSpaceGetter); metadata_storage_.reset(new ResourceMetadataStorage( temp_dir_.path().Append(util::kMetadataDirectory), base::MessageLoopProxy::current().get())); ASSERT_TRUE(metadata_storage_->Initialize()); cache_.reset(new FileCache( metadata_storage_.get(), temp_dir_.path().Append(util::kCacheFileDirectory), base::MessageLoopProxy::current().get(), fake_free_disk_space_getter_.get())); ASSERT_TRUE(cache_->Initialize()); } static bool ImportOldDB(FileCache* cache, const base::FilePath& old_db_path) { return cache->ImportOldDB(old_db_path); } static void RenameCacheFilesToNewFormat(FileCache* cache) { cache->RenameCacheFilesToNewFormat(); } content::TestBrowserThreadBundle thread_bundle_; base::ScopedTempDir temp_dir_; scoped_ptr<ResourceMetadataStorage, test_util::DestroyHelperForTests> metadata_storage_; scoped_ptr<FileCache, test_util::DestroyHelperForTests> cache_; scoped_ptr<FakeFreeDiskSpaceGetter> fake_free_disk_space_getter_; }; TEST_F(FileCacheTest, ScanCacheFile) { // Set up files in the cache directory. const base::FilePath file_directory = temp_dir_.path().Append(util::kCacheFileDirectory); ASSERT_TRUE(google_apis::test_util::WriteStringToFile( file_directory.AppendASCII("id_foo"), "foo")); // Remove the existing DB. const base::FilePath metadata_directory = temp_dir_.path().Append(util::kMetadataDirectory); ASSERT_TRUE(base::DeleteFile(metadata_directory, true /* recursive */)); // Put an empty file with the same name as old DB. // This file cannot be opened by ImportOldDB() and will be dismissed. ASSERT_TRUE(file_util::CreateDirectory(metadata_directory)); ASSERT_TRUE(google_apis::test_util::WriteStringToFile( metadata_directory.Append(FileCache::kOldCacheMetadataDBName), "")); // Create a new cache and initialize it. metadata_storage_.reset(new ResourceMetadataStorage( metadata_directory, base::MessageLoopProxy::current().get())); ASSERT_TRUE(metadata_storage_->Initialize()); cache_.reset(new FileCache(metadata_storage_.get(), temp_dir_.path().Append(util::kCacheFileDirectory), base::MessageLoopProxy::current().get(), fake_free_disk_space_getter_.get())); ASSERT_TRUE(cache_->Initialize()); // Check contents of the cache. FileCacheEntry cache_entry; EXPECT_TRUE(cache_->GetCacheEntry("id_foo", &cache_entry)); EXPECT_TRUE(cache_entry.is_present()); EXPECT_EQ(base::MD5String("foo"), cache_entry.md5()); } TEST_F(FileCacheTest, FreeDiskSpaceIfNeededFor) { base::FilePath src_file; ASSERT_TRUE(file_util::CreateTemporaryFileInDir(temp_dir_.path(), &src_file)); // Store a file as a 'temporary' file and remember the path. const std::string resource_id_tmp = "id_tmp", md5_tmp = "md5_tmp"; ASSERT_EQ(FILE_ERROR_OK, cache_->Store(resource_id_tmp, md5_tmp, src_file, FileCache::FILE_OPERATION_COPY)); base::FilePath tmp_path; ASSERT_EQ(FILE_ERROR_OK, cache_->GetFile(resource_id_tmp, &tmp_path)); // Store a file as a pinned file and remember the path. const std::string resource_id_pinned = "id_pinned", md5_pinned = "md5_pinned"; ASSERT_EQ(FILE_ERROR_OK, cache_->Store(resource_id_pinned, md5_pinned, src_file, FileCache::FILE_OPERATION_COPY)); ASSERT_EQ(FILE_ERROR_OK, cache_->Pin(resource_id_pinned)); base::FilePath pinned_path; ASSERT_EQ(FILE_ERROR_OK, cache_->GetFile(resource_id_pinned, &pinned_path)); // Call FreeDiskSpaceIfNeededFor(). fake_free_disk_space_getter_->set_default_value(test_util::kLotsOfSpace); fake_free_disk_space_getter_->PushFakeValue(0); const int64 kNeededBytes = 1; EXPECT_TRUE(cache_->FreeDiskSpaceIfNeededFor(kNeededBytes)); // Only 'temporary' file gets removed. FileCacheEntry entry; EXPECT_FALSE(cache_->GetCacheEntry(resource_id_tmp, &entry)); EXPECT_FALSE(base::PathExists(tmp_path)); EXPECT_TRUE(cache_->GetCacheEntry(resource_id_pinned, &entry)); EXPECT_TRUE(base::PathExists(pinned_path)); // Returns false when disk space cannot be freed. fake_free_disk_space_getter_->set_default_value(0); EXPECT_FALSE(cache_->FreeDiskSpaceIfNeededFor(kNeededBytes)); } TEST_F(FileCacheTest, ImportOldDB) { const base::FilePath old_db_path = temp_dir_.path().AppendASCII("old_db.db"); const std::string key1 = "key1"; const std::string md5_1 = "md5_1"; const std::string key2 = "key2"; const std::string md5_2 = "md5_2"; // Set up data to be imported. { FileCacheMetadata old_metadata(NULL); ASSERT_TRUE(old_metadata.Initialize(old_db_path)); FileCacheEntry entry; entry.set_md5(md5_1); old_metadata.AddOrUpdateCacheEntry(key1, entry); entry.set_md5(md5_2); old_metadata.AddOrUpdateCacheEntry(key2, entry); } EXPECT_TRUE(base::PathExists(old_db_path)); // Do import. EXPECT_TRUE(ImportOldDB(cache_.get(), old_db_path)); // Old DB should be removed. EXPECT_FALSE(base::PathExists(old_db_path)); // Data is imported correctly. FileCacheEntry entry; EXPECT_TRUE(cache_->GetCacheEntry(key1, &entry)); EXPECT_EQ(md5_1, entry.md5()); EXPECT_TRUE(cache_->GetCacheEntry(key2, &entry)); EXPECT_EQ(md5_2, entry.md5()); } TEST_F(FileCacheTest, RenameCacheFilesToNewFormat) { const base::FilePath file_directory = temp_dir_.path().Append(util::kCacheFileDirectory); // File with an old style "<resource ID>.<MD5>" name. ASSERT_TRUE(google_apis::test_util::WriteStringToFile( file_directory.AppendASCII("id_koo.md5"), "koo")); // File with multiple extensions should be removed. ASSERT_TRUE(google_apis::test_util::WriteStringToFile( file_directory.AppendASCII("id_kyu.md5.mounted"), "kyu (mounted)")); ASSERT_TRUE(google_apis::test_util::WriteStringToFile( file_directory.AppendASCII("id_kyu.md5"), "kyu")); // Rename and verify the result. RenameCacheFilesToNewFormat(cache_.get()); std::string contents; EXPECT_TRUE(file_util::ReadFileToString(file_directory.AppendASCII("id_koo"), &contents)); EXPECT_EQ("koo", contents); contents.clear(); EXPECT_TRUE(file_util::ReadFileToString(file_directory.AppendASCII("id_kyu"), &contents)); EXPECT_EQ("kyu", contents); // Rename again. RenameCacheFilesToNewFormat(cache_.get()); // Files with new style names are not affected. contents.clear(); EXPECT_TRUE(file_util::ReadFileToString(file_directory.AppendASCII("id_koo"), &contents)); EXPECT_EQ("koo", contents); contents.clear(); EXPECT_TRUE(file_util::ReadFileToString(file_directory.AppendASCII("id_kyu"), &contents)); EXPECT_EQ("kyu", contents); } } // namespace internal } // namespace drive
[ "ProjectRetroScope@gmail.com" ]
ProjectRetroScope@gmail.com
4718d49eeed48c6e3cc54ef11a2a03d88002a0d7
6f4887d435b9420c7c1ac20c9b618bbdfe16464c
/also/Амантай/Syrym/obl2014E.cpp
fe6d4f4c62d96b47bcb3c5ee5eb6b9688d8cdb25
[]
no_license
beloofficial/Dev-C
4af8b69e58b07543a062360d9b17b0024759f0e2
64471bf2a2da7d3bf40f15445e397112648c189f
refs/heads/master
2022-01-10T22:36:33.601075
2019-05-04T09:18:59
2019-05-04T09:18:59
184,855,569
2
0
null
null
null
null
UTF-8
C++
false
false
688
cpp
#include <iostream> #include <cstdio> using namespace std; const int P = 1000000007; int n, a[1112]; int main() { freopen ("input.txt","r",stdin); freopen ("output.txt","w",stdout); cin >> n; for (int i = 1; i <= n; i++) { cin >> a[i]; } int m = n; for (int i = 1; i < n; i++) { if (i % 2 == 0) { for (int j = 1; j < m; j++) { a[j] = a[j]*a[j+1]; if (a[j] >= P) a[j] -= P; } } else { for (int j = 1; j < m; j++) { a[j] = a[j]+a[j+1]; a[j] %= P; } } m--; } cout << a[1]; return 0; }
[ "amantay.or@gmail.com" ]
amantay.or@gmail.com
75893a0bbe149fde38039ac2b6a76f21720dec8f
5af9479c6306a6a09234441a5aeeacdc3c6f4d1d
/mm-parser/ID3Lib/src/id3.cpp
10b53d710fdad76ab7b4a25f80d040670ebe1d6f
[]
no_license
zhaow123/android_vendor_qcom_proprietary-1
6193c67a2483e49cb690ceab0862451e826c8961
c6dd6f2a54c5e8c078271e0a221c4b622d2079bb
refs/heads/master
2022-03-21T20:57:51.156579
2017-01-19T18:45:25
2017-01-19T18:45:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
73,916
cpp
/* ======================================================================= ID3.cpp DESCRIPTION: Definitions for ID3 classes. This includes ID3v1 and ID3v2 and all constants and enums used by these classes and the callers of these classes Copyright (c) 2009-2013 Qualcomm Technologies, Inc. All Rights Reserved. Qualcomm Technologies Proprietary and Confidential. ========================================================================== */ /* ======================================================================= Edit History $Header: //source/qcom/qct/multimedia2/Video/Source/FileDemux/ID3Lib/main/latest/src/id3.cpp#31 $ $DateTime: 2013/10/21 02:25:48 $ $Change: 4628966 $ ========================================================================== */ //============================================================ // INCLUDES //============================================================ #include "id3.h" #include "oscl_file_io.h" //============================================================= // GLOBALS //============================================================= //============================================================= // MACROS //============================================================= #define ID3V2_IS_WFRAME(x) (((byte *)(x))[0] == 'W' ) #define ID3V2_IS_TFRAME(x) (((byte *)(x))[0] == 'T' ) // Condition to check for frame ID strings that should be handled as // generic frames and are NOT parsed individually // list more macros under this condition when required #define ID3V2_IS_FRAME_SUPPORTED(x) ((ID3V2_IS_WFRAME(x))\ ||(ID3V2_IS_TFRAME(x))) int GET_ID3V2_FRAME_ID_SIZE(int major) { if(major >=3 ) { return ID3V2_3_4_FRAME_ID_SIZE; } return ID3V2_2_BELOW_FRAME_ID_SIZE; } int GET_ID3V2_FRAME_LENGTH_SIZE(int major) { if(major >=3 ) { return ID3V2_3_4_FRAME_LENGTH_SIZE; } return ID3V2_2_BELOW_FRAME_LENGTH_SIZE; } int GET_ID3V2_FRAME_HDR_SIZE(int major) { if(major >=3 ) { return ID3V2_3_4_FRAME_HEADER_SIZE; } return ID3V2_2_BELOW_FRAME_HEADER_SIZE; } /* ============================================================================ @brief CalcStringLength @details Calculates string length. It varies based on coding type @param[in] pBuf Input buffer (string pointer) @param[in] bEncodingType Encoding type @param[in] ulBufSize Input Buffer Size @return String size. @note None. =============================================================================*/ uint32 CalcStringLength(const uint8 *pBuf, uint8 bEncodingType, uint32 ulBufSize) { //! Validate input parameters if ((NULL == pBuf) || (0 == ulBufSize)) { return 0; } /* ID3 tags has support for 4 types of Encodings. $00: ISO-8859-1 (LATIN-1, Identical to ASCII for values smaller than 0x80) $01: UCS-2 (UTF-16 encoded Unicode with BOM), in ID3v2.2 and ID3v2.3. $02: UTF-16BE encoded Unicode without BOM, in ID3v2.4. $03: UTF-8 encoded Unicode, in ID3v2.4. */ // ISO 8859-1 or UTF-8, calculate string size using normal strlen API if ((0x00 == bEncodingType) || (0x03 == bEncodingType)) { return std_strlen((const char *)pBuf) + 1; } // UTF-16 with and without BOM uint32 ulStrSize = 0; while (pBuf[ulStrSize] != '\0' || pBuf[ulStrSize + 1] != '\0') { //! Check if String length calculated is crossing the buffer Size or not if ((ulStrSize + sizeof(uint16)) > ulBufSize) { ulStrSize -= sizeof(uint16); break; } ulStrSize += sizeof(uint16); } // Add size of null termination. return ulStrSize + sizeof(uint16); } //============================================================= // CONSTANTS //============================================================= // Frame ID strings for known list of frame types which are handled /* *Caution: Do not change the following order. *If you have to change following order, make the same change in *enum ID3V2_FOUR_CHARS_TAG_ENUMS.The order of these two must match exactly. */ static const byte frame_identifiers[ID3V2_FOUR_CHARS_TAG_MAX][5] = { {0}, /* unknown frame type*/ "AENC",/*Audio encryption*/ "APIC",/*Attached picture*/ "COMM",/*Comments*/ "COMR",/*Commercial frame*/ "ENCR",/*Encryption method registration*/ "EQUA",/*Equalization*/ "ETCO",/*Event timing codes*/ "GEOB",/*General encapsulated object*/ "GRID",/*Group identification registration*/ "IPLS",/*Involved people list*/ "LINK",/*Linked information*/ "MCDI",/*Music CD identifier*/ "MLLT",/*MPEG location lookup table*/ "OWNE",/*Ownership frame*/ "PRIV",/*Private frame*/ "PCNT",/*Play counter*/ "POPM",/*Popularimeter*/ "POSS",/*Position synchronisation frame*/ "RBUF",/*Recommended buffer size*/ "RVAD",/*Relative volume adjustment*/ "RVRB",/*Reverb*/ "SYLT",/*Synchronized lyric/text*/ "SYTC",/*Synchronized tempo codes*/ "TALB",/*Album/Movie/Show title*/ "TBPM",/*BPM (beats per minute)*/ "TCOM",/*Composer*/ "TCON",/*Content type*/ "TCOP",/*Copyright message*/ "TDAT",/*Date*/ "TDLY",/*Playlist delay*/ "TENC",/*Encoded by*/ "TEXT",/*Lyricist/Text writer*/ "TFLT",/*File type*/ "TIME",/*Time*/ "TIT1",/*Content group description*/ "TIT2",/*Title/songname/content description*/ "TIT3",/*Subtitle/Description refinement*/ "TKEY",/*Initial key*/ "TLAN",/*Language(s)*/ "TLEN",/*Length*/ "TMED",/*Media type*/ "TOAL",/*Original album/movie/show title*/ "TOFN",/*Original filename*/ "TOLY",/*Original lyricist(s)/text writer(s)*/ "TOPE",/*Original artist(s)/performer(s)*/ "TORY",/*Original release year*/ "TOWN",/*File owner/licensee*/ "TPE1",/*Lead performer(s)/Soloist(s)*/ "TPE2",/*Band/orchestra/accompaniment*/ "TPE3",/*Conductor/performer refinement*/ "TPE4",/*Interpretedremixedor otherwise modified by*/ "TPOS",/*Part of a set*/ "TPUB",/*Publisher*/ "TRCK",/*Track number/Position in set*/ "TRDA",/*Recording dates*/ "TRSN",/*Internet radio station name*/ "TRSO",/*Internet radio station owner*/ "TSIZ",/*Size*/ "TSRC",/*ISRC (international standard recording code)*/ "TSSE",/*Software/Hardware and settings used for encoding*/ "TYER",/*Year*/ "TXXX",/*User defined text information frame*/ "UFID",/*Unique file identifier*/ "USER",/*Terms of use*/ "USLT",/*Unsychronized lyric/text transcription*/ "WCOM",/*Commercial information*/ "WCOP",/*Copyright/Legal information*/ "WOAF",/*Official audio file webpage*/ "WOAR",/*Official artist/performer webpage*/ "WOAS",/*Official audio source webpage*/ "WORS",/*Official internet radio station homepage*/ "WPAY",/*Payment*/ "WPUB",/*Publishers official webpage*/ "WXXX",/*User defined URL link frame*/ }; /* *Caution: Do not change the following order. *If you have to change following order, make the same change in *ID3V2_2_BELOW_TAG_ENUMS.The order of these two must match exactly. */ static const byte id3v2_2_below_frame_identifiers[ID3V2_THREE_CHARS_TAG_MAX][4] = { {0}, /*unknown frame type*/ "BUF", /*Recommended buffer size*/ "CNT", /*Play counter*/ "COM", /*Comments*/ "CRA", /*Audio encryption*/ "CRM", /*Encrypted meta frame*/ "ETC", /*Event timing codes*/ "EQU", /*Equalization*/ "GEO", /*General encapsulated object*/ "IPL", /*Involved people list*/ "LNK", /*Linked information*/ "MCI", /*Music CD Identifier*/ "MLL", /*MPEG location lookup table*/ "PIC", /*Attached picture*/ "POP", /*Popularimeter*/ "REV", /*Reverb*/ "RVA", /*Relative volume adjustment*/ "SLT", /*Synchronized lyric/text*/ "STC", /*Synced tempo codes*/ "TAL", /*Album/Movie/Show title*/ "TBP", /*BPM (Beats Per Minute)*/ "TCM", /*Composer*/ "TCO", /*Content type*/ "TCR", /*Copyright message*/ "TDA", /*Date*/ "TDY", /*Playlist delay*/ "TEN", /*Encoded by*/ "TFT", /*File type*/ "TIM", /*Time*/ "TKE", /*Initial key*/ "TLA", /*Language(s)*/ "TLE", /*Length*/ "TMT", /*Media type*/ "TOA", /*Original artist(s)/performer(s)*/ "TOF", /*Original filename*/ "TOL", /*Original Lyricist(s)/text writer(s)*/ "TOR", /*Original release year*/ "TOT", /*Original album/Movie/Show title*/ "TP1", /*Lead artist(s)/Lead performer(s)/Soloist(s)/Performing group*/ "TP2", /*Band/Orchestra/Accompaniment*/ "TP3", /*Conductor/Performer refinement*/ "TP4", /*Interpreted, remixed, or otherwise modified by*/ "TPA", /*Part of a set*/ "TPB", /*Publisher*/ "TRC", /*ISRC (International Standard Recording Code)*/ "TRD", /*Recording dates*/ "TRK", /*Track number/Position in set*/ "TSI", /*Size*/ "TSS", /*Software/hardware and settings used for encoding*/ "TT1", /*Content group description*/ "TT2", /*Title/Songname/Content description*/ "TT3", /*Subtitle/Description refinement*/ "TXT", /*Lyricist/text writer*/ "TXX", /*User defined text information frame*/ "TYE", /*Year*/ "UFI", /*Unique file identifier*/ "ULT", /*Unsychronized lyric/text transcription*/ "WAF", /*Official audio file webpage*/ "WAR", /*Official artist/performer webpage*/ "WAS", /*Official audio source webpage*/ "WCM", /*Commercial information*/ "WCP", /*Copyright/Legal information*/ "WPB", /*Publishers official webpage*/ "WXX", /*User defined URL link frame*/ }; //============================================================= // FUNCTION DEFINITONS //============================================================= // Simple file seek and read function PARSER_ERRORTYPE seekandreadfile(OSCL_FILE* fp_ID3FilePtr, uint32 length, uint64 position, byte *pbuffer); //============================================================= // Class ID3v1 //============================================================= //============================================================= //FUNCTION : Constructor // //DESCRIPTION // Constructor for ID3v1 // //PARAMETERS // None // //RETURN VALUE // void // //SIDE EFFECTS // None //============================================================= ID3v1::ID3v1( PARSER_ERRORTYPE &rnResult) { m_fileoffset =0; rnResult = PARSER_ErrorNone; } //============================================================= //FUNCTION : Destructor // //DESCRIPTION // Destructor for ID3v1 // //PARAMETERS // None // //RETURN VALUE // void // //SIDE EFFECTS // None //============================================================= ID3v1::~ID3v1() { m_fileoffset =0; } //============================================================= // FUNCTION : check_ID3v1_present // // DESCRIPTION // Static function that can be used to check the file to see if an ID3v1 // tag is present. Once the caller knows that and ID3v1 tag is present an // object of this class can be created to extract the tag information. // //PARAMETERS // file: IFilePort1 interface pointer to the audio file // nLength : total length of the input file in bytes // //RETURN VALUE // TRUE : ID3v1 tag is present in this file // FALSE : ID3v1 tag not present in this file // //SIDE EFFECTS // None //============================================================= bool ID3v1::check_ID3v1_present(OSCL_FILE* fp_ID3FilePtr, uint64 nLength) { byte tagheader[4] = {0}; PARSER_ERRORTYPE result = PARSER_ErrorNone; if(NULL == fp_ID3FilePtr || (MAX_FILE_SIZE == nLength)) { return FALSE; } if(nLength < 128) { return FALSE; } result = seekandreadfile(fp_ID3FilePtr, 3, (int64)(nLength-ID3v1_SIZE), tagheader); if(result) { return FALSE; } if(!std_memcmp("TAG",tagheader,std_strlen("TAG"))) { return TRUE; } return FALSE; } //============================================================= // FUNCTION : parse_ID3v1_tag // // DESCRIPTION // Parses and extracts all the info present in the ID3v1 tag // and populates this info into the metadata_id3v1_type struct // //PARAMETERS // file: IFilePort1 interface pointer to the audio file // nLength : total length of the input file in bytes // pstid3v1 : output param to be filled by this method // //RETURN VALUE // AEE_SUCCESS : Everything was done successfully // AEE_EFAILED : Could not execute this method successfully // //SIDE EFFECTS // None //============================================================= PARSER_ERRORTYPE ID3v1::parse_ID3v1_tag(OSCL_FILE* fp_ID3FilePtr, metadata_id3v1_type *pstid3v1, uint64 nLength) { if((NULL == fp_ID3FilePtr)||(NULL == pstid3v1)) { return PARSER_ErrorInvalidParam; } if(nLength < 10) { return PARSER_ErrorInvalidParam; } PARSER_ERRORTYPE result = PARSER_ErrorNone; byte buffer[128] ={0}; byte *bufferreadpos = buffer; m_fileoffset = nLength-ID3v1_SIZE; pstid3v1->file_position = m_fileoffset; result = seekandreadfile(fp_ID3FilePtr, ID3v1_SIZE, m_fileoffset, buffer); if(result) { return result; } // Skip 'TAG' id pstid3v1->size = ID3v1_SIZE; bufferreadpos += 3; // Copy Title (void) std_memmove(pstid3v1->title, bufferreadpos, ID3V1_TITLE_LENGTH); bufferreadpos += ID3V1_TITLE_LENGTH; // Copy artist (void) std_memmove(pstid3v1->artist, bufferreadpos, ID3V1_ARTIST_LENGTH); bufferreadpos += ID3V1_ARTIST_LENGTH; // Copy album (void) std_memmove(pstid3v1->album, bufferreadpos, ID3V1_ALBUM_LENGTH); bufferreadpos += ID3V1_ALBUM_LENGTH; // Copy year (void) std_memmove(pstid3v1->year, bufferreadpos, ID3V1_YEAR_LENGTH); bufferreadpos += ID3V1_YEAR_LENGTH; // Copy comment (void) std_memmove(pstid3v1->comment, bufferreadpos, ID3V1_COMMENT_LENGTH); bufferreadpos += ID3V1_COMMENT_LENGTH; // Copy track pstid3v1->track = *bufferreadpos; bufferreadpos++; // Copy genre pstid3v1->genre = *bufferreadpos; bufferreadpos++; return result; } //============================================================= // Class ID3v2 //============================================================= //============================================================= //FUNCTION : Constructor // //DESCRIPTION // Constructor for ID3v2 // //PARAMETERS // None // //RETURN VALUE // void // //SIDE EFFECTS // None //============================================================= ID3v2::ID3v2( PARSER_ERRORTYPE &rnResult) { init_ID3v2_params(); rnResult = PARSER_ErrorNone; } //============================================================= //FUNCTION : Destructor // //DESCRIPTION // Destructor for ID3v2 // //PARAMETERS // None // //RETURN VALUE // void // //SIDE EFFECTS // None //============================================================= ID3v2::~ID3v2() { m_pstid3v2 = NULL; } //============================================================= // FUNCTION : init_ID3v2_params // // DESCRIPTION // Initializes the member variables of this class used for parsing the tag // // PARAMETERS // None // //RETURN VALUE // void // //SIDE EFFECTS // None //============================================================= void ID3v2::init_ID3v2_params() { m_filereadoffset = 0; m_ID3v2startpos =0; m_size = 0; m_umajorversion = 0; m_uminorversion = 0; m_bunsncyhronisation = FALSE; m_bextendedheader = FALSE; m_bexperimentalheader = FALSE; m_bfooterpresent = FALSE; m_pstid3v2 = NULL; } //============================================================= // FUNCTION : check_ID3v2_present // // DESCRIPTION // static function that can be used to check the file to see if an ID3v2 tag // is present. Also sets a flag to inform the caller as to whether the tag // is appended at theof the file after the audio data or before the start of // audio data in the beginning of the file. Once the caller knows that and // ID3v2 tag is present an object of this class can be created to extract the // tag information. // // PARAMETERS // file: IFilePort1 interface pointer to the audio file // nLength : total length of the input file in bytes // pbID3v2postend : output param to be filled by this method // flag to show if ID3v2 tag is appended after // the end of audio data in the file. // //RETURN VALUE // TRUE : ID3v2 tag is present in this file // FALSE : ID3v2 tag not present in this file // //SIDE EFFECTS // None //============================================================= bool ID3v2::check_ID3v2_present(OSCL_FILE* fp_ID3FilePtr, uint64 nLength, uint64 nOffset, bool *pbID3v2postend) { PARSER_ERRORTYPE result = PARSER_ErrorNone; byte tagheader[4] = {0}; if((NULL == fp_ID3FilePtr)||(NULL == pbID3v2postend)) { return FALSE; } if(nLength < 10) { return FALSE; } // Check for Id3v2 tag at the given offset result = seekandreadfile(fp_ID3FilePtr,3,nOffset,tagheader); if(result) { return FALSE; } if(!std_memcmp("ID3",tagheader,std_strlen("ID3"))) { *pbID3v2postend = FALSE; return TRUE; } // Check for Id3v2 tag at the end of the file if file-size known // & there is no ID3 tag detected at beginning. if((nLength != MAX_FILE_SIZE) && (false == *pbID3v2postend)) { result = seekandreadfile(fp_ID3FilePtr,3,nLength-10,tagheader); if(result) { return FALSE; } if(!std_memcmp("3DI",tagheader,std_strlen("3DI"))) { *pbID3v2postend = TRUE; return TRUE; } } return FALSE; } //============================================================= // FUNCTION : parse_ID3v2_tag // // DESCRIPTION // Parses and extracts all the info present in the ID3v2 tag // and populates this info into the metadata_id3v2_type struct // //PARAMETERS // file: IFilePort1 interface pointer to the audio file // bID3v2postend : flag to show if ID3v2 tag is appended after // the end of audio data in the file // pstid3v2 : output param to be filled by this method // //RETURN VALUE // AEE_SUCCESS : Everything was done successfully // AEE_EFAILED : Could not execute this method successfully // //SIDE EFFECTS // None //============================================================= PARSER_ERRORTYPE ID3v2::parse_ID3v2_tag(OSCL_FILE* fp_ID3FilePtr, uint64 nOffset, metadata_id3v2_type *pstid3v2, bool bID3v2postend) { PARSER_ERRORTYPE result = PARSER_ErrorNone; if((NULL == fp_ID3FilePtr)||(NULL == pstid3v2)) { return PARSER_ErrorInvalidParam; } init_ID3v2_params(); (void) std_memset((void*)pstid3v2, 0, STD_SIZEOF(metadata_id3v2_type)); if(bID3v2postend) { result = parse_ID3v2_tag_postend(fp_ID3FilePtr,nOffset,pstid3v2, /*TBD*/ 50); } else { result = parse_ID3v2_tag_prepend(fp_ID3FilePtr,nOffset, pstid3v2, /*TBD*/ 50); } return result; } //============================================================= // FUNCTION : parse_ID3v2_tag_postend // // DESCRIPTION // Parses and extracts all the info present in the ID3v2 tag // and populates this info into the metadata_id3v2_type struct // when the tag is present after the end of audio data in the file // //PARAMETERS // file: IFilePort1 interface pointer to the audio file // pstid3v2 : output param to be filled by this method // nLength : total length of the input file in bytes // //RETURN VALUE // AEE_SUCCESS : Everything was done successfully // AEE_EFAILED : Could not execute this method successfully // //SIDE EFFECTS // None //============================================================= PARSER_ERRORTYPE ID3v2::parse_ID3v2_tag_postend(OSCL_FILE* fp_ID3FilePtr, uint64 nOffset, metadata_id3v2_type *pstid3v2, uint64 nLength) { PARSER_ERRORTYPE result = PARSER_ErrorNone; // Move m_filereadoffset to the beginning of the tag // TBD m_filereadoffset = nLength -10; result = parse_ID3v2_tag_header(fp_ID3FilePtr,nOffset, pstid3v2,nLength); return result; } //============================================================= // FUNCTION : parse_ID3v2_tag_prepend // // DESCRIPTION // Parses and extracts all the info present in the ID3v2 tag // and populates this info into the metadata_id3v2_type struct // when the tag is present before the start of audio data in the file // //PARAMETERS // file: IFilePort1 interface pointer to the audio file // pstid3v2 : output param to be filled by this method // nLength : total length of the input file in bytes // //RETURN VALUE //void // //SIDE EFFECTS // None //============================================================= // PARSER_ERRORTYPE ID3v2::parse_ID3v2_tag_prepend(OSCL_FILE* fp_ID3FilePtr, uint64 nOffset, metadata_id3v2_type *pstid3v2, uint64 nLength) { PARSER_ERRORTYPE result = PARSER_ErrorNone; m_filereadoffset = 0; result = parse_ID3v2_tag_header(fp_ID3FilePtr,nOffset, pstid3v2,nLength); if(result) { return result; } result = parse_ID3v2_frames(fp_ID3FilePtr,pstid3v2,nLength); return result; } //============================================================= // FUNCTION : parse_ID3v2_tag_header // // DESCRIPTION // Parses and extracts all the info present in the ID3v2 tag header // and populates this info into the metadata_id3v2_type struct // //PARAMETERS // file: IFilePort1 interface pointer to the audio file // pstid3v2 : output param to be filled by this method // nLength : total length of the input file in bytes // //RETURN VALUE // AEE_SUCCESS : Everything was done successfully // AEE_EFAILED : Could not execute this method successfully // //SIDE EFFECTS // None //============================================================= PARSER_ERRORTYPE ID3v2::parse_ID3v2_tag_header(OSCL_FILE* fp_ID3FilePtr, uint64 nOffset, metadata_id3v2_type *pstid3v2, uint64 nLength) { PARSER_ERRORTYPE result = PARSER_ErrorNone; uint64 offset = nOffset; byte buffer[4] ={0}; (void) nLength; pstid3v2->is_present = TRUE; m_ID3v2startpos = m_filereadoffset; pstid3v2->file_position = nOffset; // Skip the tag name offset += 3; result = seekandreadfile(fp_ID3FilePtr,2, offset,buffer); if(result) { //DBG(HIGH,"ID3v2::parse_ID3v2_tag_header : seekandreadfile failed"); return result; } offset += 2; m_umajorversion = buffer[0]; m_uminorversion = buffer[1]; uint8 flags = 0; result = seekandreadfile(fp_ID3FilePtr,1, offset,&flags); if(result) { //DBG(HIGH,"ID3v2::parse_ID3v2_tag_header : seekandreadfile failed"); return result; } offset += 1; m_bunsncyhronisation = (flags & 0x80)?TRUE:FALSE; m_bextendedheader = (flags & 0x40)?TRUE:FALSE; m_bexperimentalheader = (flags & 0x20)?TRUE:FALSE; m_bfooterpresent = (flags & 0x10)?TRUE:FALSE; result = seekandreadfile(fp_ID3FilePtr,4, offset,buffer); if(result) { //DBG(HIGH,"ID3v2::parse_ID3v2_tag_header : seekandreadfile failed"); return result; } offset += 4; // Convert the size value read from the tag to int m_size = getsyncsafeinteger(buffer,4) + ID3v2_HEADER_SIZE; pstid3v2->size = m_size; m_filereadoffset += ID3v2_HEADER_SIZE; m_filereadoffset+= nOffset; // If an extended header is present, skip it if(m_bextendedheader) { result = seekandreadfile(fp_ID3FilePtr,4, m_filereadoffset,buffer); if(result) { //DBG(HIGH,"ID3v2::parse_ID3v2_tag_header : seekandreadfile failed"); return result; } m_filereadoffset += 4; // Increment offset by size of the extended header uint32 exthdrsize = parse_ID3v2_uint(buffer, 4); result = seekandreadfile(fp_ID3FilePtr,1, m_filereadoffset,buffer); if(result) { //DBG(HIGH,"ID3v2::parse_ID3v2_tag_header : seekandreadfile failed"); return result; } //Increment offset by size of flags field(1 byte) + flags field(buffer[0]) m_filereadoffset += 1 + buffer[0]; // Skip the ext header field m_filereadoffset += exthdrsize; } return result; } //============================================================= // FUNCTION : parse_ID3v2_frames // // DESCRIPTION // Parses all frames in the ID3v2 tag one by one till the end of the tag // or till it encounters padding. // //PARAMETERS // file: IFilePort1 interface pointer to the audio file // pstid3v2 : output param to be filled by this method // nLength : total length of the input file in bytes // //RETURN VALUE // AEE_SUCCESS : Everything was done successfully // AEE_EFAILED : Could not execute this method successfully // //SIDE EFFECTS // None //============================================================= PARSER_ERRORTYPE ID3v2::parse_ID3v2_frames(OSCL_FILE* fp_ID3FilePtr, metadata_id3v2_type *pstid3v2, uint64 nLength) { PARSER_ERRORTYPE result = PARSER_ErrorNone; uint64 frame_length; ID3V2_FOUR_CHARS_FRAME_TYPES frame_type; ID3V2_THREE_CHARS_FRAME_TYPES id3v2_below_frame_type; uint64 tagsize = m_size; int hdrsize = GET_ID3V2_FRAME_HDR_SIZE(m_umajorversion) ; if(m_bfooterpresent) { tagsize -= hdrsize; } m_pstid3v2 = pstid3v2; m_pstid3v2->generic_frames = NULL; uint64 nendoffset = m_filereadoffset; if((m_filereadoffset + tagsize)> ID3v2_HEADER_SIZE) { nendoffset = m_filereadoffset + tagsize - ID3v2_HEADER_SIZE; } while(m_filereadoffset < nendoffset) { frame_length = 0; if(m_umajorversion >= 3) { frame_type = ID3V2_FOUR_CHARS_TAG_UNKN; result = get_next_frame(fp_ID3FilePtr,&frame_type,&frame_length); } else { id3v2_below_frame_type = ID3V2_THREE_CHARS_TAG_UNK; result = get_next_frame(fp_ID3FilePtr,&id3v2_below_frame_type,&frame_length); } if((result) || (frame_length == 0)) { break; } // As long as this frame completely exists, parse it even if its type // is unknown parse_ID3v2_frame will take care of hanlding the frame type if(m_filereadoffset + hdrsize + frame_length <= nendoffset) { if(m_umajorversion >= 3) { result = parse_ID3v2_frame(fp_ID3FilePtr,frame_type,frame_length); } else { result = parse_ID3v2_frame(fp_ID3FilePtr,id3v2_below_frame_type, frame_length); } if(result) { break; } } else { // Always make sure m_filereadoffset is updated with frame size to // avoid infinite loop m_filereadoffset+= (frame_length+hdrsize); } // When we encounter padding, we can stop parsing if(check_padding(fp_ID3FilePtr)) { break; } } return result; } //============================================================= // FUNCTION : parse_ID3v2_uint // // DESCRIPTION // Parses a single unit of an ID3v2 tag. This process is dependent on the // major version of the spec being used. A max of 4 bytes can be handled // at a time by this method. // //PARAMETERS // pInput : Input data (byte stream) // nbytes : number of bytes in the input data // //RETURN VALUE // uint32 : output data after parsing // //SIDE EFFECTS // None //============================================================= uint32 ID3v2::parse_ID3v2_uint(const uint8 *pInput, unsigned int nbytes) const { uint32 uoutputint = 0; if(4 == m_umajorversion) { return getsyncsafeinteger(pInput, nbytes); } for(;nbytes > 0;nbytes--,pInput++) { uoutputint = (uoutputint << 8) |*pInput; } return uoutputint; } //============================================================= // FUNCTION : parse_ID3v2_frame // // DESCRIPTION // This method handles the parsing of a single ID3v2 frame. // Respective handlers for frame types are called from this method // to handle the parsing of the frame. // //PARAMETERS // file: IFilePort1 interface pointer to the audio file // frame_type : type of the frame that needs to be parsed // nLength : total length of the input file in bytes // //RETURN VALUE // AEE_SUCCESS : Everything was done successfully // AEE_EFAILED : Could not execute this method successfully // //SIDE EFFECTS // None //============================================================= PARSER_ERRORTYPE ID3v2::parse_ID3v2_frame(OSCL_FILE* fp_ID3FilePtr, ID3V2_FOUR_CHARS_FRAME_TYPES frame_type, uint64 frame_length) { PARSER_ERRORTYPE result = PARSER_ErrorNone; if(frame_length ==0) { return PARSER_ErrorInvalidParam; } // If this is an unknown type, check if this frame type needs to be supported // if yes, then parse it as a generic frame if(frame_type == ID3V2_FOUR_CHARS_TAG_UNKN) { byte frame_id[ID3V2_3_4_FRAME_ID_SIZE] = {0}; result = seekandreadfile(fp_ID3FilePtr, ID3V2_3_4_FRAME_ID_SIZE, m_filereadoffset, frame_id); if(result) { //DBG(HIGH,"ID3v2::parse_ID3v2_frame: seekandreadfile failed"); return result; } if(ID3V2_IS_FRAME_SUPPORTED(frame_id)) { result = parse_ID3v2_frame_generic(fp_ID3FilePtr,frame_id,frame_length); } else { // Skip this frame's data // Move the file read offset to mark that this data is consumed m_filereadoffset += ID3V2_3_4_FRAME_HEADER_SIZE + frame_length; } return result; } text_frame* dataptr = NULL; private_tag_info* privTag = NULL; id3v2_pic_info* pict_tag = NULL; encoder_delay_tag_info* pEncTag = NULL; // Parse a known frame type switch(frame_type) { case ID3V2_FOUR_CHARS_TAG_IPLS: dataptr = &m_pstid3v2->involved_people_list; break; case ID3V2_FOUR_CHARS_TAG_TALB: dataptr = &m_pstid3v2->album; break; case ID3V2_FOUR_CHARS_TAG_TBPM: dataptr = &m_pstid3v2->beats_per_minute; break; case ID3V2_FOUR_CHARS_TAG_TCOM: dataptr = &m_pstid3v2->composer; break; case ID3V2_FOUR_CHARS_TAG_TCON: dataptr = &m_pstid3v2->genre; break; case ID3V2_FOUR_CHARS_TAG_TCOP: dataptr = &m_pstid3v2->copyright; break; case ID3V2_FOUR_CHARS_TAG_TDAT: dataptr = &m_pstid3v2->date; break; case ID3V2_FOUR_CHARS_TAG_TDLY: dataptr = &m_pstid3v2->playlist_delay; break; case ID3V2_FOUR_CHARS_TAG_TENC: dataptr = &m_pstid3v2->encoder; break; case ID3V2_FOUR_CHARS_TAG_TEXT: dataptr = &m_pstid3v2->lyricist; break; case ID3V2_FOUR_CHARS_TAG_TFLT: dataptr = &m_pstid3v2->file_type; break; case ID3V2_FOUR_CHARS_TAG_TIME: dataptr = &m_pstid3v2->time; break; case ID3V2_FOUR_CHARS_TAG_TIT1: dataptr = &m_pstid3v2->content_group_desc; break; case ID3V2_FOUR_CHARS_TAG_TIT2: dataptr = &m_pstid3v2->title; break; case ID3V2_FOUR_CHARS_TAG_TIT3: dataptr = &m_pstid3v2->subtitle; break; case ID3V2_FOUR_CHARS_TAG_TKEY: dataptr = &m_pstid3v2->init_key; break; case ID3V2_FOUR_CHARS_TAG_TLAN: dataptr = &m_pstid3v2->languages; break; case ID3V2_FOUR_CHARS_TAG_TLEN: dataptr = &m_pstid3v2->length; break; case ID3V2_FOUR_CHARS_TAG_TMED: dataptr = &m_pstid3v2->media_type; break; case ID3V2_FOUR_CHARS_TAG_TOAL: dataptr = &m_pstid3v2->original_title; break; case ID3V2_FOUR_CHARS_TAG_TOFN: dataptr = &m_pstid3v2->original_filename; break; case ID3V2_FOUR_CHARS_TAG_TOLY: dataptr = &m_pstid3v2->original_lyricists; break; case ID3V2_FOUR_CHARS_TAG_TOPE: dataptr = &m_pstid3v2->original_artist; break; case ID3V2_FOUR_CHARS_TAG_TORY: dataptr = &m_pstid3v2->original_release_year; break; case ID3V2_FOUR_CHARS_TAG_TOWN: dataptr = &m_pstid3v2->file_own_licensee; break; case ID3V2_FOUR_CHARS_TAG_TPE1: dataptr = &m_pstid3v2->album_artist; break; case ID3V2_FOUR_CHARS_TAG_TPE2: dataptr = &m_pstid3v2->orchestra; break; case ID3V2_FOUR_CHARS_TAG_TPE3: dataptr = &m_pstid3v2->conductor; break; case ID3V2_FOUR_CHARS_TAG_TPE4: dataptr = &m_pstid3v2->remix_mod_by; break; case ID3V2_FOUR_CHARS_TAG_TPOS: dataptr = &m_pstid3v2->part_of_set; break; case ID3V2_FOUR_CHARS_TAG_TPUB: dataptr = &m_pstid3v2->publisher; break; case ID3V2_FOUR_CHARS_TAG_TRCK: dataptr = &m_pstid3v2->track; break; case ID3V2_FOUR_CHARS_TAG_TRDA: dataptr = &m_pstid3v2->recording_dates; break; case ID3V2_FOUR_CHARS_TAG_TRSN: dataptr = &m_pstid3v2->internet_radio_stn_name; break; case ID3V2_FOUR_CHARS_TAG_TRSO: dataptr = &m_pstid3v2->internet_radio_stn_owner; break; case ID3V2_FOUR_CHARS_TAG_TSIZ: dataptr = &m_pstid3v2->size_in_bytes; break; case ID3V2_FOUR_CHARS_TAG_TSRC: dataptr = &m_pstid3v2->isrc_code; break; case ID3V2_FOUR_CHARS_TAG_TSSE: dataptr = &m_pstid3v2->sw_hw_enc_settings; break; case ID3V2_FOUR_CHARS_TAG_TYER: dataptr = &m_pstid3v2->year; break; case ID3V2_FOUR_CHARS_TAG_PRIV: privTag = &m_pstid3v2->private_tag; break; case ID3V2_FOUR_CHARS_TAG_APIC:/*custom frame*/ pict_tag = &m_pstid3v2->pic_info; break; case ID3V2_FOUR_CHARS_TAG_COMM:/*comment frame*/ pEncTag = &m_pstid3v2->encoder_delay_tag; break; //skip all custom and unknown frame types case ID3V2_FOUR_CHARS_TAG_AENC:/*custom frame*/ case ID3V2_FOUR_CHARS_TAG_COMR:/*custom frame*/ case ID3V2_FOUR_CHARS_TAG_ENCR:/*custom frame*/ case ID3V2_FOUR_CHARS_TAG_EQUA:/*custom frame*/ case ID3V2_FOUR_CHARS_TAG_ETCO:/*custom frame*/ case ID3V2_FOUR_CHARS_TAG_GEOB:/*custom frame*/ case ID3V2_FOUR_CHARS_TAG_GRID:/*custom frame*/ case ID3V2_FOUR_CHARS_TAG_LINK:/*custom frame*/ case ID3V2_FOUR_CHARS_TAG_MCDI:/*custom frame*/ case ID3V2_FOUR_CHARS_TAG_MLLT:/*custom frame*/ case ID3V2_FOUR_CHARS_TAG_OWNE:/*custom frame*/ case ID3V2_FOUR_CHARS_TAG_PCNT:/*custom frame*/ case ID3V2_FOUR_CHARS_TAG_POPM:/*custom frame*/ case ID3V2_FOUR_CHARS_TAG_POSS:/*custom frame*/ case ID3V2_FOUR_CHARS_TAG_RBUF:/*custom frame*/ case ID3V2_FOUR_CHARS_TAG_RVAD:/*custom frame*/ case ID3V2_FOUR_CHARS_TAG_RVRB:/*custom frame*/ case ID3V2_FOUR_CHARS_TAG_SYLT:/*custom frame*/ case ID3V2_FOUR_CHARS_TAG_SYTC:/*custom frame*/ case ID3V2_FOUR_CHARS_TAG_TXXX:/*user defined test frame*/ case ID3V2_FOUR_CHARS_TAG_UFID:/*custom frame*/ case ID3V2_FOUR_CHARS_TAG_USER:/*custom frame*/ case ID3V2_FOUR_CHARS_TAG_USLT:/*custom frame*/ case ID3V2_FOUR_CHARS_TAG_WCOM:/*user link frame*/ case ID3V2_FOUR_CHARS_TAG_WCOP:/*user link frame*/ case ID3V2_FOUR_CHARS_TAG_WOAF:/*user link frame*/ case ID3V2_FOUR_CHARS_TAG_WOAR:/*user link frame*/ case ID3V2_FOUR_CHARS_TAG_WOAS:/*user link frame*/ case ID3V2_FOUR_CHARS_TAG_WORS:/*user link frame*/ case ID3V2_FOUR_CHARS_TAG_WPAY:/*user link frame*/ case ID3V2_FOUR_CHARS_TAG_WPUB:/*user link frame*/ case ID3V2_FOUR_CHARS_TAG_WXXX:/*user defined url link frame*/ default: { result = PARSER_ErrorNone; } } if(dataptr) { result = parse_ID3v2_text_frame(fp_ID3FilePtr,dataptr,frame_length); } if(privTag) { result = parse_ID3v2_priv_frame(fp_ID3FilePtr,privTag,frame_length); } if(pict_tag) { result = parse_ID3v2_frame_APIC(fp_ID3FilePtr,pict_tag,frame_length); } else if (pEncTag) { result = parse_ID3v2_comment_frame(fp_ID3FilePtr, pEncTag, frame_length); } // Move the file read offset to mark that this data is consumed m_filereadoffset += ID3V2_3_4_FRAME_HEADER_SIZE + frame_length; return result; } //============================================================= // FUNCTION : parse_ID3v2_frame // // DESCRIPTION // This method handles the parsing of a single ID3v2 frame. // Respective handlers for frame types are called from this method // to handle the parsing of the frame. // //PARAMETERS // file: IFilePort1 interface pointer to the audio file // frame_type : type of the frame that needs to be parsed // nLength : total length of the input file in bytes // //RETURN VALUE // AEE_SUCCESS : Everything was done successfully // AEE_EFAILED : Could not execute this method successfully // //SIDE EFFECTS // None //============================================================= PARSER_ERRORTYPE ID3v2::parse_ID3v2_frame(OSCL_FILE* fp_ID3FilePtr, ID3V2_THREE_CHARS_FRAME_TYPES frame_type, uint64 frame_length) { PARSER_ERRORTYPE result = PARSER_ErrorNone; if(frame_length ==0) { return PARSER_ErrorInvalidParam; } // If this is an unknown type, skip the frame if(frame_type == ID3V2_THREE_CHARS_TAG_UNK) { m_filereadoffset += ID3V2_2_BELOW_FRAME_HEADER_SIZE + frame_length; return result; } text_frame* dataptr = NULL; encoder_delay_tag_info* pEncTag = NULL; // Parse a known frame type switch(frame_type) { case ID3V2_THREE_CHARS_TAG_IPL: dataptr = &m_pstid3v2->involved_people_list; break; case ID3V2_THREE_CHARS_TAG_TAL: dataptr = &m_pstid3v2->album; break; case ID3V2_THREE_CHARS_TAG_TBP: dataptr = &m_pstid3v2->beats_per_minute; break; case ID3V2_THREE_CHARS_TAG_TCM: dataptr = &m_pstid3v2->composer; break; case ID3V2_THREE_CHARS_TAG_TCO: dataptr = &m_pstid3v2->genre; break; case ID3V2_THREE_CHARS_TAG_TCR: dataptr = &m_pstid3v2->copyright; break; case ID3V2_THREE_CHARS_TAG_TDA: dataptr = &m_pstid3v2->date; break; case ID3V2_THREE_CHARS_TAG_TDY: dataptr = &m_pstid3v2->playlist_delay; break; case ID3V2_THREE_CHARS_TAG_TEN: dataptr = &m_pstid3v2->encoder; break; case ID3V2_THREE_CHARS_TAG_TFT: dataptr = &m_pstid3v2->file_type; break; case ID3V2_THREE_CHARS_TAG_TIM: dataptr = &m_pstid3v2->time; break; case ID3V2_THREE_CHARS_TAG_TKE: dataptr = &m_pstid3v2->init_key; break; case ID3V2_THREE_CHARS_TAG_TLA: dataptr = &m_pstid3v2->languages; break; case ID3V2_THREE_CHARS_TAG_TLE: dataptr = &m_pstid3v2->length; break; case ID3V2_THREE_CHARS_TAG_TMT: dataptr = &m_pstid3v2->media_type; break; case ID3V2_THREE_CHARS_TAG_TOA: dataptr = &m_pstid3v2->original_artist; break; case ID3V2_THREE_CHARS_TAG_TOF: dataptr = &m_pstid3v2->original_filename; break; case ID3V2_THREE_CHARS_TAG_TOL: dataptr = &m_pstid3v2->recomm_buff_size; break; case ID3V2_THREE_CHARS_TAG_TOR: dataptr = &m_pstid3v2->original_release_year; break; case ID3V2_THREE_CHARS_TAG_TOT: dataptr = &m_pstid3v2->original_title; break; case ID3V2_THREE_CHARS_TAG_TP1: dataptr = &m_pstid3v2->album_artist; break; case ID3V2_THREE_CHARS_TAG_TP2: dataptr = &m_pstid3v2->orchestra; break; case ID3V2_THREE_CHARS_TAG_TP3: dataptr = &m_pstid3v2->conductor; break; case ID3V2_THREE_CHARS_TAG_TP4: dataptr = &m_pstid3v2->remix_mod_by; break; case ID3V2_THREE_CHARS_TAG_TPA: dataptr = &m_pstid3v2->part_of_set; break; case ID3V2_THREE_CHARS_TAG_TPB: dataptr = &m_pstid3v2->publisher; break; case ID3V2_THREE_CHARS_TAG_TRC: dataptr = &m_pstid3v2->isrc_code; break; case ID3V2_THREE_CHARS_TAG_TRD: dataptr = &m_pstid3v2->recording_dates; break; case ID3V2_THREE_CHARS_TAG_TRK: dataptr = &m_pstid3v2->track; break; case ID3V2_THREE_CHARS_TAG_TSI: dataptr = &m_pstid3v2->size_in_bytes; break; case ID3V2_THREE_CHARS_TAG_TSS: dataptr = &m_pstid3v2->sw_hw_enc_settings; break; case ID3V2_THREE_CHARS_TAG_TT1: dataptr = &m_pstid3v2->content_group_desc; break; case ID3V2_THREE_CHARS_TAG_TT2: dataptr = &m_pstid3v2->title; break; case ID3V2_THREE_CHARS_TAG_TT3: dataptr = &m_pstid3v2->subtitle; break; case ID3V2_THREE_CHARS_TAG_TXT: dataptr = &m_pstid3v2->lyricist; break; case ID3V2_THREE_CHARS_TAG_TXX: dataptr = &m_pstid3v2->user_def_text_info; break; case ID3V2_THREE_CHARS_TAG_TYE: dataptr = &m_pstid3v2->year; break; case ID3V2_THREE_CHARS_TAG_COM://custom frame pEncTag = &m_pstid3v2->encoder_delay_tag; break; //skip all custom,unknown frames case ID3V2_THREE_CHARS_TAG_BUF://custom frame case ID3V2_THREE_CHARS_TAG_CNT://custom frame case ID3V2_THREE_CHARS_TAG_CRA://custom frame case ID3V2_THREE_CHARS_TAG_CRM://custom frame case ID3V2_THREE_CHARS_TAG_ETC://custom frame case ID3V2_THREE_CHARS_TAG_EQU://custom frame case ID3V2_THREE_CHARS_TAG_GEO://custom frame case ID3V2_THREE_CHARS_TAG_LNK://custom frame case ID3V2_THREE_CHARS_TAG_MCI://custom frame case ID3V2_THREE_CHARS_TAG_MLL://custom frame case ID3V2_THREE_CHARS_TAG_PIC://custom frame case ID3V2_THREE_CHARS_TAG_POP://custom frame case ID3V2_THREE_CHARS_TAG_REV://custom frame case ID3V2_THREE_CHARS_TAG_RVA://custom frame case ID3V2_THREE_CHARS_TAG_SLT://custom frame case ID3V2_THREE_CHARS_TAG_STC://custom frame case ID3V2_THREE_CHARS_TAG_UFI://custom frame case ID3V2_THREE_CHARS_TAG_ULT://custom frame case ID3V2_THREE_CHARS_TAG_WAF://user link frame case ID3V2_THREE_CHARS_TAG_WAR://user link frame case ID3V2_THREE_CHARS_TAG_WAS://user link frame case ID3V2_THREE_CHARS_TAG_WCM://user link frame case ID3V2_THREE_CHARS_TAG_WCP://user link frame case ID3V2_THREE_CHARS_TAG_WPB://user link frame case ID3V2_THREE_CHARS_TAG_WXX://user defined url link frame default: result = PARSER_ErrorNone; break; } if(dataptr) { result = parse_ID3v2_text_frame(fp_ID3FilePtr,dataptr,frame_length); } else if (pEncTag) { result = parse_ID3v2_comment_frame(fp_ID3FilePtr, pEncTag, frame_length); } // Move the file read offset to mark that this data is consumed m_filereadoffset += GET_ID3V2_FRAME_HDR_SIZE(m_umajorversion) + frame_length; return result; } //============================================================= // FUNCTION : parse_ID3v2_frame_generic // // DESCRIPTION // This method handles the parsing of generic frames. // These are frames that are classified as supported frame types but // do not have any specific handling for that frame type. // //PARAMETERS // file: IFilePort1 interface pointer to the audio file // pframe_id : 4 byte frame id for this frame // nLength : total length of the input file in bytes // //RETURN VALUE // AEE_SUCCESS : Everything was done successfully // AEE_EFAILED : Could not execute this method successfully // //SIDE EFFECTS // Allocates memory for a complete generic frame. // This memory has to be freed by the caller of the ID3 methods. //============================================================= PARSER_ERRORTYPE ID3v2::parse_ID3v2_frame_generic(OSCL_FILE* fp_ID3FilePtr, const byte *pframe_id, uint64 frame_length) { PARSER_ERRORTYPE result = PARSER_ErrorNone; id3v2_generic_frame_type *pgenframe = NULL; if(NULL == m_pstid3v2->generic_frames) { m_pstid3v2->generic_framesLen = 1; // This is the first generic frame // Allocate memory for reading data m_pstid3v2->generic_frames = (id3v2_generic_frame_type *) MM_Malloc(sizeof(id3v2_generic_frame_type)); if(m_pstid3v2->generic_frames) { memset(m_pstid3v2->generic_frames,0,sizeof(id3v2_generic_frame_type)); } } else { id3v2_generic_frame_type* pTemp = (id3v2_generic_frame_type *) MM_Realloc((void*)(m_pstid3v2->generic_frames), sizeof(id3v2_generic_frame_type)* (m_pstid3v2->generic_framesLen+1) ); if(pTemp) { m_pstid3v2->generic_framesLen++; memset(pTemp + (m_pstid3v2->generic_framesLen-1), 0, sizeof(id3v2_generic_frame_type)); m_pstid3v2->generic_frames = pTemp; } else { MM_MSG_PRIO(MM_FILE_OPS, MM_PRIO_FATAL, "parse_ID3v2_frame_generic ID3_INSUFFICIENT_BUFFER"); return PARSER_ErrorInsufficientBufSize; } } if(NULL == m_pstid3v2->generic_frames) { //DBG(HIGH,"ID3v2::parse_ID3v2_frame_generic: No memory"); return PARSER_ErrorInsufficientBufSize; } pgenframe = &(m_pstid3v2->generic_frames[m_pstid3v2->generic_framesLen -1]); // Set the frame ID (void) std_memmove(pgenframe->id,pframe_id,ID3V2_3_4_FRAME_ID_SIZE); byte ucflags[2] = {0}; m_filereadoffset += ID3V2_3_4_FRAME_ID_SIZE + ID3V2_3_4_FRAME_LENGTH_SIZE; // Get the 2 flag bytes result = seekandreadfile(fp_ID3FilePtr,2, m_filereadoffset,ucflags); if(result) { //DBG(HIGH,"ID3v2::parse_ID3v2_frame_generic: seekandreadfile failed"); return result; } m_filereadoffset += 2; pgenframe->flags = (ucflags[0]<<8)|ucflags[1]; pgenframe->in_memory = TRUE; pgenframe->contentLen = (int)frame_length; // Allocate memory for content pgenframe->content = MM_New_Array(byte,((int)frame_length)); if(NULL == pgenframe->content) { //DBG(HIGH,"ID3v2::parse_ID3v2_frame_generic: No memory"); return result; } // Read the content into this allocated memory result = seekandreadfile(fp_ID3FilePtr, (uint32)frame_length, m_filereadoffset, pgenframe->content); if(result) { //DBG(HIGH,"ID3v2::parse_ID3v2_frame_generic: seekandreadfile failed"); return result; } // Move the file read offset to mark that this data is consumed m_filereadoffset += frame_length; return result; } //============================================================= // FUNCTION : parse_ID3v2_frame_APIC // // DESCRIPTION // This method handles the parsing of an APIC frame. // //PARAMETERS // file: IFilePort1 interface pointer to the audio file // nLength : total length of the input file in bytes // //RETURN VALUE // AEE_SUCCESS : Everything was done successfully // AEE_EFAILED : Could not execute this method successfully // //SIDE EFFECTS // None //============================================================= PARSER_ERRORTYPE ID3v2::parse_ID3v2_frame_APIC(OSCL_FILE* fp_ID3FilePtr, id3v2_pic_info* pict_tag, uint64 frame_length) { uint8 *temp = NULL; uint32 buf_offset = 0; PARSER_ERRORTYPE result = PARSER_ErrorNone; if(frame_length && fp_ID3FilePtr && pict_tag) { temp = MM_New_Array(uint8,uint32(FIXED_APIC_FIELDS_LENGTH)); if(NULL == temp) { return PARSER_ErrorMemAllocFail; } uint64 offset; offset = m_filereadoffset + GET_ID3V2_FRAME_HDR_SIZE(m_umajorversion); // Read the fixed bytes of frame data into temp array result = seekandreadfile(fp_ID3FilePtr, FIXED_APIC_FIELDS_LENGTH, offset, temp); if(result) { //DBG(HIGH,"ID3v2::parse_ID3v2_APIC_frame: seekandreadfile failed"); return result; } pict_tag->text_enc = temp[buf_offset++]; if(!std_memcmp(temp + buf_offset, "image/jpeg", strlen("image/jpeg")) ) { pict_tag->img_format = IMG_JPG; memcpy(pict_tag->img_format_string, temp + buf_offset, strlen("image/jpeg") + 1); buf_offset += strlen("image/jpeg") + 1; } else if(!std_memcmp(temp + buf_offset, "image/png", strlen("image/png")) ) { pict_tag->img_format = IMG_PNG; memcpy(pict_tag->img_format_string, temp + buf_offset, strlen("image/png") + 1); buf_offset += strlen("image/png") + 1; } pict_tag->pict_type = (FS_PICTURE_TYPE)temp[buf_offset++]; //! Calculate Description string length uint32 ulDescStrLength = 0; ulDescStrLength = CalcStringLength(temp + buf_offset, pict_tag->text_enc, FIXED_APIC_FIELDS_LENGTH - buf_offset); //! Copy Description string data in structure //! MAX_DESC_LEN is the Description string size memcpy(pict_tag->desc, temp + buf_offset, FILESOURCE_MIN (ulDescStrLength, MAX_DESC_LEN)); buf_offset += ulDescStrLength; pict_tag->pic_data_len = uint32(frame_length - buf_offset); pict_tag->pic_data = (uint8*)MM_Malloc(pict_tag->pic_data_len); if(NULL == pict_tag->pic_data) { return PARSER_ErrorMemAllocFail; } // Read the main picture data bytes into output array result = seekandreadfile(fp_ID3FilePtr, pict_tag->pic_data_len, offset+buf_offset, pict_tag->pic_data); if(result) { //DBG(HIGH,"ID3v2::parse_ID3v2_APIC_frame: seekandreadfile failed"); return result; } /* Free the memory allocated to temp buffer */ MM_Delete_Array(temp); } return result; } //============================================================= // FUNCTION : parse_ID3v2_text_frame // // DESCRIPTION // This method handles the parsing of a text frame. The text data in the tag // is extracted and stored in the text frame structure. // //PARAMETERS // file: IFilePort1 interface pointer to the audio file // ptextframe : text frame location where this frame should be // parsed and stored // nLength : total length of the input file in bytes // //RETURN VALUE // AEE_SUCCESS : Everything was done successfully // AEE_EFAILED : Could not execute this method successfully // //SIDE EFFECTS // Memory for this is allocated here and has to be freed by the // caller of the ID3 methods. //============================================================= // PARSER_ERRORTYPE ID3v2::parse_ID3v2_text_frame(OSCL_FILE* fp_ID3FilePtr, text_frame *ptextframe, uint64 frame_length) { PARSER_ERRORTYPE result = PARSER_ErrorNone; ptextframe->text = NULL; // Since 1 byte is used to describe the encoding, the actual text len is //1 less than the frame's length. int textlen = (int)frame_length-1; if(textlen) { //As per ID3 specification, each text info should be NULL terminated, //however, there are few clips which are not following it. //Put explicit '\0' all the time. ptextframe->text = MM_New_Array(char,(textlen+1)); if(NULL == ptextframe->text) { return PARSER_ErrorMemAllocFail; } uint64 offset; offset = m_filereadoffset + GET_ID3V2_FRAME_HDR_SIZE(m_umajorversion); // Set encoding type result = seekandreadfile(fp_ID3FilePtr,1, offset,&ptextframe->encoding); if(result) { //DBG(HIGH,"ID3v2::parse_ID3v2_text_frame: seekandreadfile failed"); return result; } offset++; memset(ptextframe->text, 0, ptextframe->textLen + 1); // Read the content into this allocated memory result = seekandreadfile(fp_ID3FilePtr,textlen, offset, (byte*)ptextframe->text); if(result) { //DBG(HIGH,"ID3v2::parse_ID3v2_text_frame: seekandreadfile failed"); return result; } ptextframe->text[textlen] = '\0'; ptextframe->textLen = textlen+1; //! If encoding is UTF16 with Byte Order Marker, remove first two bytes if (ID3V2_FRAME_TEXT_ENCODING_UTF_16 == ptextframe->encoding) { uint16 *pStr = (uint16*)ptextframe->text; //! Check if the data is in Reverse Byte order if (BYTE_ORDER_MARKER_IN_BE == (uint16)pStr[0]) { ByteSwapString(ptextframe->text, ptextframe->textLen); } /* BOM data need not to be given to application, this helps to detect Endianness of the input string. So first two bytes can be skipped. */ if (BYTE_ORDER_MARKER_IN_LE == (uint16)pStr[0]) { memmove(ptextframe->text, ptextframe->text + 2, textlen - 2); ptextframe->textLen -= 2; textlen -= 2; ptextframe->text[textlen] = '\0'; ptextframe->text[textlen + 1] = '\0'; } } } return result; } //============================================================= // FUNCTION : parse_ID3v2_priv_frame // // DESCRIPTION // This method handles the parsing of a private tag. This tag is // used to store first frame's timestamp in case of live streaming. // This is extracted and stored in the private frame structure. //PARAMETERS // file: IFilePort1 interface pointer to the audio file // ptextframe : text frame location where this frame should be // parsed and stored // nLength : total length of the input file in bytes // //RETURN VALUE // AEE_SUCCESS : Everything was done successfully // AEE_EFAILED : Could not execute this method successfully // //SIDE EFFECTS // Memory for this is allocated here and has to be freed by the // caller of the ID3 methods. //============================================================= // PARSER_ERRORTYPE ID3v2::parse_ID3v2_priv_frame(OSCL_FILE* fp_ID3FilePtr, private_tag_info *priv_tag, uint64 frame_length) { uint8 *temp = 0; /* This is the string available as part of Owner identifier */ uint8 string[] = "com.apple.streaming.transportStreamTimestamp"; uint32 strLen = strlen((const char *)string); PARSER_ERRORTYPE result = PARSER_ErrorNone; if(frame_length && fp_ID3FilePtr && priv_tag) { temp = MM_New_Array(uint8,uint32(frame_length)); if(NULL == temp) { return PARSER_ErrorMemAllocFail; } uint64 offset; offset = m_filereadoffset + GET_ID3V2_FRAME_HDR_SIZE(m_umajorversion); // Read whole frame data into text array result = seekandreadfile(fp_ID3FilePtr,uint32(frame_length), offset,temp); if(result) { //DBG(HIGH,"ID3v2::parse_ID3v2_text_frame: seekandreadfile failed"); return result; } priv_tag->timeStamp = 0; priv_tag->isTsValid = false; /* Check whether this is matching with apple standard private tag or not*/ if(!std_memcmp(string, temp, strLen)) { priv_tag->isTsValid = true; uint32 TSFieldLen = 0; /* There is one NULL character after string before start of timestamp*/ strLen++; /* Conver big-endian eight-octet number number into little endian format*/ while(TSFieldLen < 8 && strLen < frame_length) { /* Right shift the timestamp field by 8 bits before copying the data*/ priv_tag->timeStamp <<= 8; priv_tag->timeStamp|= temp[strLen++]; TSFieldLen++; } /* Timestamp is stored as 33-bit MPEG-2 Program Elementary Stream. MPEG-2 stream timestamps are stored as units of 90khz. So, we need to divide with 90 to get accurate timestamp. */ priv_tag->timeStamp = priv_tag->timeStamp / 90; } /* Free the memory allocated to temp buffer */ if(temp) MM_Delete_Array(temp); } return result; } //============================================================= // FUNCTION : get_ID3v2_size // // DESCRIPTION // Called to get the complete size of the ID3v2 tag // the caller can call this API even before calling "parse_ID3v2_tag" // Calling this API after calling "parse_ID3v2_tag" is more efficient though. // //PARAMETERS // file: IFilePort1 interface pointer to the audio file // bID3v2postend : flag to show if ID3v2 tag is appended after // the end of audio data in the file // nLength : total length of the input file in bytes // size : o/p param: size of the complete ID3v2 tag in bytes // //RETURN VALUE // AEE_SUCCESS : Everything was done successfully // AEE_EFAILED : Could not execute this method successfully // //SIDE EFFECTS // None //============================================================= PARSER_ERRORTYPE ID3v2::get_ID3v2_size(OSCL_FILE* fp_ID3FilePtr,uint64 nLength, uint64 nOffset, bool bID3v2postend, uint64 *size) { PARSER_ERRORTYPE result = PARSER_ErrorNone; if((NULL == fp_ID3FilePtr)||(NULL == size)) { return PARSER_ErrorInvalidParam; } // check to see if we already have a valid size available if(m_size != 0) { // the tag has already been parsed // so, just return the size we have counted *size = m_size; return PARSER_ErrorNone; } // the tag has not been parsed yet. // get the tage info and parse the header // and then return the size value calculated if(bID3v2postend) { m_filereadoffset = nLength -10; } metadata_id3v2_type stid3v2; stid3v2.size =0; result = parse_ID3v2_tag_header(fp_ID3FilePtr,nOffset, &stid3v2,nLength); *size = (uint64)stid3v2.size; return result; } //============================================================= // FUNCTION : getsyncsafeinteger // // DESCRIPTION // Given an input byte stream of sync safe data, this method returns // a normal int. A max of 4 bytes can be handled at a time by this method. // // PARAMETERS // pInput : input data // nbytes : number of bytes in the input data // // RETURN VALUE // uint32 (integer) // // SIDE EFFECTS // None //============================================================= uint32 ID3v2::getsyncsafeinteger(const byte *pInput, int nbytes) const { uint32 uoutputint = 0; int n; for (n=0; n < nbytes; n++) { uoutputint = (uoutputint << 7) | (*(pInput)++ & 0x7F); } return uoutputint; } //============================================================= // FUNCTION : get_frame_id_type // // DESCRIPTION // Returns the ID3v2_frame_type enum given the 4 bytes frame ID if this // is a known frame type according to the list in enum ID3v2_frame_type // //PARAMETERS // frame_id: 4 byte frame ID // //RETURN VALUE // ID3v2_frame_type // //SIDE EFFECTS // None //============================================================= ID3V2_FOUR_CHARS_FRAME_TYPES ID3v2::get_frame_id_type(const byte* frame_id) const { int i; for(i=0; i< (int)ID3V2_FOUR_CHARS_TAG_MAX;i++) { if(!std_memcmp(frame_identifiers[i],frame_id,ID3V2_3_4_FRAME_ID_SIZE)) { return (ID3V2_FOUR_CHARS_FRAME_TYPES)i; } } return ID3V2_FOUR_CHARS_TAG_UNKN; } //============================================================= // FUNCTION : get_frame_id_type // // DESCRIPTION // Returns the ID3v2_frame_type enum given the 4 bytes frame ID if this // is a known frame type according to the list in enum ID3v2_frame_type // //PARAMETERS // frame_id: 4 byte frame ID // //RETURN VALUE // ID3v2_frame_type // //SIDE EFFECTS // None //============================================================= ID3V2_THREE_CHARS_FRAME_TYPES ID3v2::get_id3v2_2_below_frame_id_type (const byte* frame_id) const { for(int i=0; i< (int)ID3V2_THREE_CHARS_TAG_MAX;i++) { if(!std_memcmp(id3v2_2_below_frame_identifiers[i],frame_id, ID3V2_2_BELOW_FRAME_ID_SIZE)) { return (ID3V2_THREE_CHARS_FRAME_TYPES)i; } } return ID3V2_THREE_CHARS_TAG_UNK; } //============================================================= // FUNCTION : get_next_frame // // DESCRIPTION // reads the next frame header and returns the frame type and // frame length for the frame. // //PARAMETERS // file: IFilePort1 interface pointer to the audio file // pframe_type : output param to be filled by this method // gives the type of this frame // pframe_length : length of the frame in bytes // //RETURN VALUE // AEE_SUCCESS : Everything was done successfully // AEE_EFAILED : Could not execute this method successfully // //SIDE EFFECTS // None //============================================================= PARSER_ERRORTYPE ID3v2::get_next_frame(OSCL_FILE* fp_ID3FilePtr, ID3V2_FOUR_CHARS_FRAME_TYPES *pframe_type, uint64 *pframe_length) const { PARSER_ERRORTYPE result = PARSER_ErrorNone; uint64 offset = m_filereadoffset; byte frame_id[ID3V2_3_4_FRAME_ID_SIZE] = {0}; byte frame_length_buffer[ID3V2_3_4_FRAME_LENGTH_SIZE] = {0}; *pframe_type = ID3V2_FOUR_CHARS_TAG_UNKN; result = seekandreadfile(fp_ID3FilePtr,ID3V2_3_4_FRAME_ID_SIZE, offset,frame_id); if(result) { //DBG(HIGH,"ID3v2::get_next_frame: seekandreadfile failed"); return result; } offset+= ID3V2_3_4_FRAME_ID_SIZE; result = seekandreadfile(fp_ID3FilePtr, ID3V2_3_4_FRAME_ID_SIZE, offset, frame_length_buffer); if(result) { //DBG(HIGH,"ID3v2::get_next_frame: seekandreadfile failed"); return result; } offset += ID3V2_3_4_FRAME_LENGTH_SIZE; *pframe_type = get_frame_id_type(frame_id); // Check if the frame length is valid *pframe_length = parse_ID3v2_uint(frame_length_buffer, ID3V2_3_4_FRAME_LENGTH_SIZE); return result; } //============================================================= // FUNCTION : get_next_frame // // DESCRIPTION // reads the next frame header and returns the frame type and // frame length for the frame. // //PARAMETERS // file: IFilePort1 interface pointer to the audio file // pframe_type : output param to be filled by this method // gives the type of this frame // pframe_length : length of the frame in bytes // //RETURN VALUE // AEE_SUCCESS : Everything was done successfully // AEE_EFAILED : Could not execute this method successfully // //SIDE EFFECTS // None //============================================================= PARSER_ERRORTYPE ID3v2::get_next_frame(OSCL_FILE* fp_ID3FilePtr, ID3V2_THREE_CHARS_FRAME_TYPES *pframe_type, uint64 *pframe_length) const { PARSER_ERRORTYPE result = PARSER_ErrorNone; uint64 offset = m_filereadoffset; byte frame_id[ID3V2_2_BELOW_FRAME_ID_SIZE] = {0}; byte frame_length_buffer[ID3V2_2_BELOW_FRAME_LENGTH_SIZE] = {0}; *pframe_type = ID3V2_THREE_CHARS_TAG_UNK; result = seekandreadfile(fp_ID3FilePtr,ID3V2_2_BELOW_FRAME_ID_SIZE, offset,frame_id); if(result) { return result; } offset+= ID3V2_2_BELOW_FRAME_ID_SIZE; result = seekandreadfile(fp_ID3FilePtr,ID3V2_2_BELOW_FRAME_LENGTH_SIZE, offset,frame_length_buffer); if(result) { return result; } offset += ID3V2_2_BELOW_FRAME_LENGTH_SIZE; *pframe_type = get_id3v2_2_below_frame_id_type(frame_id); *pframe_length = parse_ID3v2_uint(frame_length_buffer, ID3V2_2_BELOW_FRAME_LENGTH_SIZE); return result; } //============================================================= // FUNCTION : check_padding // // DESCRIPTION // This method checks the current read position to see if we have hit padding yet. // If we have hit padding, it moves the read pointer to the end of the padding. // //PARAMETERS // file: IFilePort1 interface pointer to the audio file // //RETURN VALUE //void // //SIDE EFFECTS // None //============================================================= bool ID3v2::check_padding(OSCL_FILE* fp_ID3FilePtr) { uint8 i; uint32 result = PARSER_ErrorNone; bool bfoundpadding = FALSE; // Check if 4 bytes from current position are 0 // If yes, then we have found padding. byte buffer[ID3V2_3_4_FRAME_ID_SIZE] = {0}; byte null_buffer[ID3V2_3_4_FRAME_ID_SIZE] = {0}; result = seekandreadfile(fp_ID3FilePtr, ID3V2_3_4_FRAME_ID_SIZE, m_filereadoffset, buffer); if(result) { //DBG(HIGH,"ID3v2::check_padding: seekandreadfile failed"); return FALSE; } if(!std_memcmp(buffer, null_buffer, ID3V2_3_4_FRAME_ID_SIZE)) { // found padding bfoundpadding = TRUE; m_filereadoffset += ID3V2_3_4_FRAME_ID_SIZE; } else { return FALSE; } // Continue checking to find the end of padding while(bfoundpadding) { result = seekandreadfile(fp_ID3FilePtr ,ID3V2_3_4_FRAME_ID_SIZE, m_filereadoffset,buffer); /* If data read is failed because of some problem, then return False. */ if(result) { //DBG(HIGH,"ID3v2::check_padding: seekandreadfile failed"); return FALSE; } if(!std_memcmp(buffer, null_buffer, ID3V2_3_4_FRAME_ID_SIZE)) { // found padding m_filereadoffset += ID3V2_3_4_FRAME_ID_SIZE; } else { bfoundpadding = FALSE; for(i=0;i<ID3V2_3_4_FRAME_ID_SIZE;i++) { if(0 != buffer[i]) { break;} m_filereadoffset++; } } } return TRUE; } //============================================================= // FUNCTION : seekandreadfile // // DESCRIPTION // Seeks to the given position and then reads the desired number of bytes into the // buffer provided by the caller. A check is done to make sure that the bytes read // are as many as requested in the read. // // PARAMETERS // file : IFilePort1 interface pointer to the file // length : the no. of bytes required to be read // position : position to start reading in the file // pbuffer : pointer to the start of buffer for the data to be read into // // RETURN VALUE // AEE_SUCCESS : All worked well // AEE_EFAILED : Could not perform the operation as required // // SIDE EFFECTS // None //============================================================= PARSER_ERRORTYPE seekandreadfile (OSCL_FILE* fp_ID3FilePtr, uint32 length, uint64 position, uint8 *pbuffer) { PARSER_ERRORTYPE result = PARSER_ErrorNone; int bytes_read=0; MM_MSG_PRIO1(MM_FILE_OPS, MM_PRIO_MEDIUM, "seek position %lld",position); if(PARSER_ErrorNone != OSCL_FileSeek(fp_ID3FilePtr, position, SEEK_SET)) { //DBG(HIGH,"seekandreadfile: file seek failed"); MM_MSG_PRIO(MM_FILE_OPS, MM_PRIO_FATAL, "seek position fail"); result = PARSER_ErrorReadFail; return result; } // Verify enough data is read to parse the header bytes_read = OSCL_FileRead(pbuffer,length,1,fp_ID3FilePtr); // Verify enough data is available to contain the header if ((uint32)bytes_read != length) { result = PARSER_ErrorReadFail; return result; } return result; } /*============================================================= FUNCTION : parse_ID3v2_comment_frame DESCRIPTION This method handles the parsing of comment section in ID3 tags PARAMETERS fp_ID3FilePtr : IFilePort1 interface pointer to the file pEncTag : encoder tag pointer ullFrameLen : Comment frame size RETURN VALUE PARSER_ErrorNone if parsing is done successfully, else corresponding error will be reproted SIDE EFFECTS None =============================================================*/ PARSER_ERRORTYPE ID3v2::parse_ID3v2_comment_frame(OSCL_FILE* fp_ID3FilePtr, encoder_delay_tag_info* pEncTag, uint64 ullFrameLen) { uint32 ulBufOffset = 0; uint64 ullOffset = 0; uint8 *pucTempBuf = NULL; PARSER_ERRORTYPE result = PARSER_ErrorNone; if(ullFrameLen && fp_ID3FilePtr && pEncTag) { pucTempBuf = MM_New_Array(uint8,uint32(ullFrameLen)); if(NULL == pucTempBuf) { return PARSER_ErrorMemAllocFail; } ullOffset = m_filereadoffset + GET_ID3V2_FRAME_HDR_SIZE(m_umajorversion); // Read complete frame data into temp array result = seekandreadfile(fp_ID3FilePtr, (uint32)ullFrameLen, ullOffset, pucTempBuf); if(result) { //DBG(HIGH,"ID3v2::parse_ID3v2_comment_frame: seekandreadfile failed"); return result; } //First 4bytes are used to indicate data type and language code ulBufOffset = 4; if(!std_memcmp(pucTempBuf + ulBufOffset, "iTunSMPB", strlen("iTunSMPB")) ) { /* Metadata will be stored in following format: iTunSMPB<0><space><8bytes ZERO Padding><space><8bytes Encoder delay> <space><8Bytes Padding delay><space> */ //Metadata string length with NULL character ulBufOffset += strlen("iTunSMPB") + 1; //Every string starts with Space character and each field is of size //8bytes. 1st field is ZERO Padding field, Parser does not need this ulBufOffset += 9; //Skip additional Space character at the start of encoder delay field ulBufOffset++; memcpy(pEncTag->ucEncoderDelay, pucTempBuf + ulBufOffset, sizeof(uint64)); //Update Buffer offset to start of Padding delay filed. //1 Extra byte is required to skip space character at the start ulBufOffset += sizeof(uint64) + 1; memcpy(pEncTag->ucPaddingDelay, pucTempBuf + ulBufOffset, sizeof(uint64)); } /* Free the memory allocated to temp buffer */ MM_Delete_Array(pucTempBuf); } return result; } /*! ========================================================================= @brief Function to convert ISO-8859 standard string into UTF8 format @detail This is used to convert data into UTF8 string format. This function calculates the required string length for UTF8 format. It allocates memory to store string in UTF8 format. Frees the memory which is provided as input and updates the double pointer value with newly allocated memory. @param[in] dpStr : Input string which needs to be converted ulStrLen : String length @return PARSER_ErrorNone if successful, else corresponding error @note None. =============================================================================*/ PARSER_ERRORTYPE ID3v2::ConvertISO88591StrtoUTF8(char** dpStr, uint32* pulStrLen) { uint32 ulUTF8StrLen = 0; uint32 ulIndex = 0; uint32 ulUTF8Index = 0; uint8* pStr = (uint8*)*dpStr; uint8* pUTF8Str = NULL; //! Validate input param if ((!pStr) || (!pulStrLen) || (0 == *pulStrLen)) { return PARSER_ErrorInvalidParam; } /* ISO-8859-1 standard divides the characters into three sets. c0: Characters in the range of 0x00 to 0x80. These characters are directly used. c1: Characters in the range of 0x80 to 0xC0. These are named as set 1. These have start code 0xC2 followed by actual data byte. For eg: 0x80 is treated as 0x C2 80 in UTF8 format. c2: Characters in the range of 0xC0 to 0xFF. These are named as set 2. These have start code 0xC3 followed by modified data byte. For eg: 0xC0 is treated as 0x C3 80 in UTF8 format. It means we have to subtract 0xC0 with 0x40 value. The reason to use sync markers 0xC2 and 0xC3 is, 0xC1 has been already used in other standard ISO/IEC 2022 extension mechanism. */ //! Calculate output string length while(ulIndex < *pulStrLen) { //! If character value is beyond 0x80, it requires two bytes in UTF8 format if (pStr[ulIndex] < 0x80) { ulUTF8StrLen++; } else { ulUTF8StrLen += 2; } ulIndex++; } pUTF8Str = (uint8*)MM_Malloc(ulUTF8StrLen + 1); ulIndex = 0; if (!pUTF8Str) { return PARSER_ErrorMemAllocFail; } //! Update output string while(ulIndex < *pulStrLen) { if (pStr[ulIndex] < 0x80) { pUTF8Str[ulUTF8Index++] = pStr[ulIndex++]; } else if(pStr[ulIndex] < 0xC0) { pUTF8Str[ulUTF8Index++] = 0xC2; pUTF8Str[ulUTF8Index++] = pStr[ulIndex++]; } else { pUTF8Str[ulUTF8Index++] = 0xC3; pUTF8Str[ulUTF8Index++] = pStr[ulIndex++] - 0x40; } } pUTF8Str[ulUTF8Index] = '\0'; //! Free the input memory and update double pointer with new pointer value MM_Free(*dpStr); *dpStr = (char*)pUTF8Str; *pulStrLen = ulUTF8StrLen; return PARSER_ErrorNone; } /*! ========================================================================= @brief Function to reverse byte for UTF16 string @detail This is used to provide data in system expected Endian format @param[in] pStr : Input string which needs to be swapped ulStrLen : String length @return None @note None. =============================================================================*/ void ID3v2::ByteSwapString(char* pStr, uint32 ulStrLen) { uint32 ulIndex = 0; //! Validate input params if ((!pStr) || (0 == ulStrLen)) { return; } for (;(ulIndex + 1) < ulStrLen; ulIndex += 2) { char temp = pStr[ulIndex]; pStr[ulIndex] = pStr[ulIndex + 1]; pStr[ulIndex + 1] = temp; } return; }
[ "danile71@gmail.com" ]
danile71@gmail.com
6c1ec5348aca50f25cbc5c6366390ccc50f845d9
c393b1f402197dcee3d23a7980f671c0e1d762f6
/modelclass.h
1b2b0a12e408225ea47db7955c92d3eea9e53650
[]
no_license
cefecto/fffde
8be1f9c9b440eb7bfec93683a1d6f77a31406cb2
7094404f7a3374cee45368e752a44733ea088373
refs/heads/master
2021-01-18T14:28:52.403206
2011-11-24T19:36:29
2011-11-24T19:36:29
2,845,458
0
0
null
null
null
null
UTF-8
C++
false
false
1,178
h
//////////////////////////////////////////////////////////////////////////////// // Filename: modelclass.h //////////////////////////////////////////////////////////////////////////////// #ifndef _MODELCLASS_H_ #define _MODELCLASS_H_ ////////////// // INCLUDES // ////////////// #include <d3d11.h> #include <d3dx10math.h> #include "textureclass.h" //////////////////////////////////////////////////////////////////////////////// // Class name: ModelClass //////////////////////////////////////////////////////////////////////////////// class ModelClass { private: struct VertexType { D3DXVECTOR3 position; D3DXVECTOR2 texture; }; public: ModelClass(); ModelClass(const ModelClass&); ~ModelClass(); bool Initialize(ID3D11Device*); void Shutdown(); void Render(ID3D11DeviceContext*); int GetIndexCount(); ID3D11ShaderResourceView* GetTexture(); private: bool InitializeBuffers(ID3D11Device*); void ShutdownBuffers(); void RenderBuffers(ID3D11DeviceContext*); void LoadTexture(ID3D11Device*,WCHAR*); void ReleaseTexture(); private: ID3D11Buffer *m_vertexBuffer, *m_indexBuffer; int m_vertexCount, m_indexCount; TextureClass* m_Texture; }; #endif
[ "code.efecto@gmail.com" ]
code.efecto@gmail.com
e26618fb62419fd803c1597d707bec44f9598648
72eba01f118160c7bb7c5340d30b7dd403a2c978
/chrome/browser/page_load_metrics/observers/ukm_page_load_metrics_observer.cc
8211158ce2c4644642ef132f027322b693beb5c6
[ "BSD-3-Clause" ]
permissive
wbyche/chromium
117b7f9b7193d8347f241c53b6c3abc6c2caa740
62d77833a31b3ff9a06d4348f0dc35845d165086
refs/heads/master
2023-01-02T13:51:12.144463
2020-03-29T23:43:15
2020-03-29T23:43:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
30,730
cc
// Copyright 2017 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. #include "chrome/browser/page_load_metrics/observers/ukm_page_load_metrics_observer.h" #include <cmath> #include <memory> #include <vector> #include "base/feature_list.h" #include "base/trace_event/common/trace_event_common.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/content_settings/cookie_settings_factory.h" #include "chrome/browser/engagement/site_engagement_service.h" #include "chrome/browser/prerender/prerender_final_status.h" #include "chrome/browser/prerender/prerender_manager.h" #include "chrome/browser/prerender/prerender_manager_factory.h" #include "chrome/browser/prerender/prerender_origin.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/search_engines/template_url_service_factory.h" #include "chrome/common/pref_names.h" #include "components/content_settings/core/browser/cookie_settings.h" #include "components/content_settings/core/common/features.h" #include "components/content_settings/core/common/pref_names.h" #include "components/metrics/net/network_metrics_provider.h" #include "components/offline_pages/buildflags/buildflags.h" #include "components/page_load_metrics/browser/page_load_metrics_util.h" #include "components/page_load_metrics/browser/protocol_util.h" #include "components/prefs/pref_service.h" #include "components/search_engines/template_url_service.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/web_contents.h" #include "media/base/mime_util.h" #include "net/base/load_timing_info.h" #include "net/http/http_response_headers.h" #include "services/metrics/public/cpp/metrics_utils.h" #include "services/metrics/public/cpp/ukm_builders.h" #include "services/metrics/public/cpp/ukm_recorder.h" #include "services/network/public/cpp/network_quality_tracker.h" #include "third_party/blink/public/common/mime_util/mime_util.h" #include "third_party/metrics_proto/system_profile.pb.h" #include "ui/events/blink/blink_features.h" #if BUILDFLAG(ENABLE_OFFLINE_PAGES) #include "chrome/browser/offline_pages/offline_page_tab_helper.h" #endif namespace { const char kOfflinePreviewsMimeType[] = "multipart/related"; bool IsSupportedProtocol(page_load_metrics::NetworkProtocol protocol) { switch (protocol) { case page_load_metrics::NetworkProtocol::kHttp11: return true; case page_load_metrics::NetworkProtocol::kHttp2: return true; case page_load_metrics::NetworkProtocol::kQuic: return true; case page_load_metrics::NetworkProtocol::kOther: return false; } } int64_t LayoutShiftUkmValue(float shift_score) { // Report (shift_score * 100) as an int in the range [0, 1000]. return static_cast<int>(roundf(std::min(shift_score, 10.0f) * 100.0f)); } int32_t LayoutShiftUmaValue(float shift_score) { // Report (shift_score * 10) as an int in the range [0, 100]. return static_cast<int>(roundf(std::min(shift_score, 10.0f) * 10.0f)); } bool IsDefaultSearchEngine(content::BrowserContext* browser_context, const GURL& url) { if (!browser_context) return false; auto* template_service = TemplateURLServiceFactory::GetForProfile( Profile::FromBrowserContext(browser_context)); if (!template_service) return false; return template_service->IsSearchResultsPageFromDefaultSearchProvider(url); } bool IsUserHomePage(content::BrowserContext* browser_context, const GURL& url) { if (!browser_context) return false; return url.spec() == Profile::FromBrowserContext(browser_context) ->GetPrefs() ->GetString(prefs::kHomePage); } } // namespace // static std::unique_ptr<page_load_metrics::PageLoadMetricsObserver> UkmPageLoadMetricsObserver::CreateIfNeeded() { if (!ukm::UkmRecorder::Get()) { return nullptr; } return std::make_unique<UkmPageLoadMetricsObserver>( g_browser_process->network_quality_tracker()); } UkmPageLoadMetricsObserver::UkmPageLoadMetricsObserver( network::NetworkQualityTracker* network_quality_tracker) : network_quality_tracker_(network_quality_tracker), largest_contentful_paint_handler_() { DCHECK(network_quality_tracker_); } UkmPageLoadMetricsObserver::~UkmPageLoadMetricsObserver() = default; UkmPageLoadMetricsObserver::ObservePolicy UkmPageLoadMetricsObserver::OnStart( content::NavigationHandle* navigation_handle, const GURL& currently_committed_url, bool started_in_foreground) { browser_context_ = navigation_handle->GetWebContents()->GetBrowserContext(); start_url_is_default_search_ = IsDefaultSearchEngine(browser_context_, navigation_handle->GetURL()); start_url_is_home_page_ = IsUserHomePage(browser_context_, navigation_handle->GetURL()); if (!started_in_foreground) { was_hidden_ = true; return CONTINUE_OBSERVING; } // When OnStart is invoked, we don't yet know whether we're observing a web // page load, vs another kind of load (e.g. a download or a PDF). Thus, // metrics and source information should not be recorded here. Instead, we // store data we might want to persist in member variables below, and later // record UKM metrics for that data once we've confirmed that we're observing // a web page load. effective_connection_type_ = network_quality_tracker_->GetEffectiveConnectionType(); http_rtt_estimate_ = network_quality_tracker_->GetHttpRTT(); transport_rtt_estimate_ = network_quality_tracker_->GetTransportRTT(); downstream_kbps_estimate_ = network_quality_tracker_->GetDownstreamThroughputKbps(); page_transition_ = navigation_handle->GetPageTransition(); return CONTINUE_OBSERVING; } page_load_metrics::PageLoadMetricsObserver::ObservePolicy UkmPageLoadMetricsObserver::OnRedirect( content::NavigationHandle* navigation_handle) { main_frame_request_redirect_count_++; return CONTINUE_OBSERVING; } UkmPageLoadMetricsObserver::ObservePolicy UkmPageLoadMetricsObserver::ShouldObserveMimeType( const std::string& mime_type) const { if (PageLoadMetricsObserver::ShouldObserveMimeType(mime_type) == CONTINUE_OBSERVING || mime_type == kOfflinePreviewsMimeType) { return CONTINUE_OBSERVING; } return STOP_OBSERVING; } UkmPageLoadMetricsObserver::ObservePolicy UkmPageLoadMetricsObserver::OnCommit( content::NavigationHandle* navigation_handle, ukm::SourceId source_id) { if (navigation_handle->IsInMainFrame()) { largest_contentful_paint_handler_.RecordMainFrameTreeNodeId( navigation_handle->GetFrameTreeNodeId()); } if (navigation_handle->GetWebContents()->GetContentsMimeType() == kOfflinePreviewsMimeType) { if (!IsOfflinePreview(navigation_handle->GetWebContents())) return STOP_OBSERVING; } connection_info_ = navigation_handle->GetConnectionInfo(); const net::HttpResponseHeaders* response_headers = navigation_handle->GetResponseHeaders(); if (response_headers) http_response_code_ = response_headers->response_code(); // The PageTransition for the navigation may be updated on commit. page_transition_ = navigation_handle->GetPageTransition(); was_cached_ = navigation_handle->WasResponseCached(); is_signed_exchange_inner_response_ = navigation_handle->IsSignedExchangeInnerResponse(); RecordNoStatePrefetchMetrics(navigation_handle, source_id); RecordGeneratedNavigationUKM(source_id, navigation_handle->GetURL()); navigation_is_cross_process_ = !navigation_handle->IsSameProcess(); navigation_entry_offset_ = navigation_handle->GetNavigationEntryOffset(); main_document_sequence_number_ = navigation_handle->GetWebContents() ->GetController() .GetLastCommittedEntry() ->GetMainFrameDocumentSequenceNumber(); return CONTINUE_OBSERVING; } UkmPageLoadMetricsObserver::ObservePolicy UkmPageLoadMetricsObserver::FlushMetricsOnAppEnterBackground( const page_load_metrics::mojom::PageLoadTiming& timing) { if (!was_hidden_) { RecordPageLoadMetrics(base::TimeTicks::Now()); RecordTimingMetrics(timing); RecordInputTimingMetrics(); } ReportLayoutStability(); return STOP_OBSERVING; } UkmPageLoadMetricsObserver::ObservePolicy UkmPageLoadMetricsObserver::OnHidden( const page_load_metrics::mojom::PageLoadTiming& timing) { if (!was_hidden_) { RecordPageLoadMetrics(base::TimeTicks() /* no app_background_time */); RecordTimingMetrics(timing); RecordInputTimingMetrics(); was_hidden_ = true; } return CONTINUE_OBSERVING; } void UkmPageLoadMetricsObserver::OnFailedProvisionalLoad( const page_load_metrics::FailedProvisionalLoadInfo& failed_load_info) { if (was_hidden_) return; RecordPageLoadMetrics(base::TimeTicks() /* no app_background_time */); // Error codes have negative values, however we log net error code enum values // for UMA histograms using the equivalent positive value. For consistency in // UKM, we convert to a positive value here. int64_t net_error_code = static_cast<int64_t>(failed_load_info.error) * -1; DCHECK_GE(net_error_code, 0); ukm::builders::PageLoad(GetDelegate().GetSourceId()) .SetNet_ErrorCode_OnFailedProvisionalLoad(net_error_code) .SetPageTiming_NavigationToFailedProvisionalLoad( failed_load_info.time_to_failed_provisional_load.InMilliseconds()) .Record(ukm::UkmRecorder::Get()); } void UkmPageLoadMetricsObserver::OnComplete( const page_load_metrics::mojom::PageLoadTiming& timing) { if (!was_hidden_) { RecordPageLoadMetrics(base::TimeTicks() /* no app_background_time */); RecordTimingMetrics(timing); RecordInputTimingMetrics(); } ReportLayoutStability(); } void UkmPageLoadMetricsObserver::OnResourceDataUseObserved( content::RenderFrameHost* content, const std::vector<page_load_metrics::mojom::ResourceDataUpdatePtr>& resources) { if (was_hidden_) return; for (auto const& resource : resources) { network_bytes_ += resource->delta_bytes; if (blink::IsSupportedImageMimeType(resource->mime_type)) { image_total_bytes_ += resource->delta_bytes; if (!resource->is_main_frame_resource) image_subframe_bytes_ += resource->delta_bytes; } else if (media::IsSupportedMediaMimeType(resource->mime_type) || base::StartsWith(resource->mime_type, "audio/", base::CompareCase::SENSITIVE) || base::StartsWith(resource->mime_type, "video/", base::CompareCase::SENSITIVE)) { media_bytes_ += resource->delta_bytes; } // Only sum body lengths for completed resources. if (!resource->is_complete) continue; if (blink::IsSupportedJavascriptMimeType(resource->mime_type)) { js_decoded_bytes_ += resource->decoded_body_length; if (resource->decoded_body_length > js_max_decoded_bytes_) js_max_decoded_bytes_ = resource->decoded_body_length; } if (resource->cache_type != page_load_metrics::mojom::CacheType::kNotCached) { cache_bytes_ += resource->encoded_body_length; } } } void UkmPageLoadMetricsObserver::OnLoadedResource( const page_load_metrics::ExtraRequestCompleteInfo& extra_request_complete_info) { if (was_hidden_) return; if (extra_request_complete_info.request_destination == network::mojom::RequestDestination::kDocument) { DCHECK(!main_frame_timing_.has_value()); main_frame_timing_ = *extra_request_complete_info.load_timing_info; } } void UkmPageLoadMetricsObserver::RecordTimingMetrics( const page_load_metrics::mojom::PageLoadTiming& timing) { ukm::builders::PageLoad builder(GetDelegate().GetSourceId()); base::Optional<int64_t> rounded_site_engagement_score = GetRoundedSiteEngagementScore(); if (rounded_site_engagement_score) { builder.SetSiteEngagementScore(rounded_site_engagement_score.value()); } base::Optional<bool> third_party_cookie_blocking_enabled = GetThirdPartyCookieBlockingEnabled(); if (third_party_cookie_blocking_enabled) { builder.SetThirdPartyCookieBlockingEnabledForSite( third_party_cookie_blocking_enabled.value()); UMA_HISTOGRAM_BOOLEAN("Privacy.ThirdPartyCookieBlockingEnabledForSite", third_party_cookie_blocking_enabled.value()); } if (timing.input_to_navigation_start) { builder.SetExperimental_InputToNavigationStart( timing.input_to_navigation_start.value().InMilliseconds()); } if (timing.parse_timing->parse_start) { builder.SetParseTiming_NavigationToParseStart( timing.parse_timing->parse_start.value().InMilliseconds()); } if (timing.document_timing->dom_content_loaded_event_start) { builder.SetDocumentTiming_NavigationToDOMContentLoadedEventFired( timing.document_timing->dom_content_loaded_event_start.value() .InMilliseconds()); } if (timing.document_timing->load_event_start) { builder.SetDocumentTiming_NavigationToLoadEventFired( timing.document_timing->load_event_start.value().InMilliseconds()); } if (timing.paint_timing->first_paint) { builder.SetPaintTiming_NavigationToFirstPaint( timing.paint_timing->first_paint.value().InMilliseconds()); } if (timing.paint_timing->first_contentful_paint) { builder.SetPaintTiming_NavigationToFirstContentfulPaint( timing.paint_timing->first_contentful_paint.value().InMilliseconds()); } if (timing.paint_timing->first_meaningful_paint) { builder.SetExperimental_PaintTiming_NavigationToFirstMeaningfulPaint( timing.paint_timing->first_meaningful_paint.value().InMilliseconds()); } const page_load_metrics::ContentfulPaintTimingInfo& main_frame_largest_contentful_paint = largest_contentful_paint_handler_.MainFrameLargestContentfulPaint(); if (main_frame_largest_contentful_paint.ContainsValidTime() && WasStartedInForegroundOptionalEventInForeground( main_frame_largest_contentful_paint.Time(), GetDelegate())) { builder.SetPaintTiming_NavigationToLargestContentfulPaint_MainFrame( main_frame_largest_contentful_paint.Time().value().InMilliseconds()); } const page_load_metrics::ContentfulPaintTimingInfo& all_frames_largest_contentful_paint = largest_contentful_paint_handler_.MergeMainFrameAndSubframes(); if (all_frames_largest_contentful_paint.ContainsValidTime() && WasStartedInForegroundOptionalEventInForeground( all_frames_largest_contentful_paint.Time(), GetDelegate())) { builder.SetPaintTiming_NavigationToLargestContentfulPaint( all_frames_largest_contentful_paint.Time().value().InMilliseconds()); } if (timing.interactive_timing->first_input_delay) { base::TimeDelta first_input_delay = timing.interactive_timing->first_input_delay.value(); builder.SetInteractiveTiming_FirstInputDelay4( first_input_delay.InMilliseconds()); } if (timing.interactive_timing->first_input_timestamp) { base::TimeDelta first_input_timestamp = timing.interactive_timing->first_input_timestamp.value(); builder.SetInteractiveTiming_FirstInputTimestamp4( first_input_timestamp.InMilliseconds()); } if (timing.interactive_timing->longest_input_delay) { base::TimeDelta longest_input_delay = timing.interactive_timing->longest_input_delay.value(); builder.SetInteractiveTiming_LongestInputDelay4( longest_input_delay.InMilliseconds()); } if (timing.interactive_timing->longest_input_timestamp) { base::TimeDelta longest_input_timestamp = timing.interactive_timing->longest_input_timestamp.value(); builder.SetInteractiveTiming_LongestInputTimestamp4( longest_input_timestamp.InMilliseconds()); } builder.SetCpuTime(total_foreground_cpu_time_.InMilliseconds()); // Use a bucket spacing factor of 1.3 for bytes. builder.SetNet_CacheBytes2(ukm::GetExponentialBucketMin(cache_bytes_, 1.3)); builder.SetNet_NetworkBytes2( ukm::GetExponentialBucketMin(network_bytes_, 1.3)); // Use a bucket spacing factor of 10 for JS bytes. builder.SetNet_JavaScriptBytes( ukm::GetExponentialBucketMin(js_decoded_bytes_, 10)); builder.SetNet_JavaScriptMaxBytes( ukm::GetExponentialBucketMin(js_max_decoded_bytes_, 10)); builder.SetNet_ImageBytes( ukm::GetExponentialBucketMin(image_total_bytes_, 1.3)); builder.SetNet_ImageSubframeBytes( ukm::GetExponentialBucketMin(image_subframe_bytes_, 1.3)); builder.SetNet_MediaBytes(ukm::GetExponentialBucketMin(media_bytes_, 1.3)); if (main_frame_timing_) ReportMainResourceTimingMetrics(timing, &builder); builder.Record(ukm::UkmRecorder::Get()); } void UkmPageLoadMetricsObserver::RecordPageLoadMetrics( base::TimeTicks app_background_time) { ukm::builders::PageLoad builder(GetDelegate().GetSourceId()); base::Optional<base::TimeDelta> foreground_duration = page_load_metrics::GetInitialForegroundDuration(GetDelegate(), app_background_time); if (foreground_duration) { builder.SetPageTiming_ForegroundDuration( foreground_duration.value().InMilliseconds()); } bool is_user_initiated_navigation = // All browser initiated page loads are user-initiated. GetDelegate().GetUserInitiatedInfo().browser_initiated || // Renderer-initiated navigations are user-initiated if there is an // associated input event. GetDelegate().GetUserInitiatedInfo().user_input_event; builder.SetExperimental_Navigation_UserInitiated( is_user_initiated_navigation); // Convert to the EffectiveConnectionType as used in SystemProfileProto // before persisting the metric. metrics::SystemProfileProto::Network::EffectiveConnectionType proto_effective_connection_type = metrics::ConvertEffectiveConnectionType(effective_connection_type_); if (proto_effective_connection_type != metrics::SystemProfileProto::Network::EFFECTIVE_CONNECTION_TYPE_UNKNOWN) { builder.SetNet_EffectiveConnectionType2_OnNavigationStart( static_cast<int64_t>(proto_effective_connection_type)); } if (http_response_code_) { builder.SetNet_HttpResponseCode( static_cast<int64_t>(http_response_code_.value())); } if (http_rtt_estimate_) { builder.SetNet_HttpRttEstimate_OnNavigationStart( static_cast<int64_t>(http_rtt_estimate_.value().InMilliseconds())); } if (transport_rtt_estimate_) { builder.SetNet_TransportRttEstimate_OnNavigationStart( static_cast<int64_t>(transport_rtt_estimate_.value().InMilliseconds())); } if (downstream_kbps_estimate_) { builder.SetNet_DownstreamKbpsEstimate_OnNavigationStart( static_cast<int64_t>(downstream_kbps_estimate_.value())); } // page_transition_ fits in a uint32_t, so we can safely cast to int64_t. builder.SetNavigation_PageTransition(static_cast<int64_t>(page_transition_)); // GetDelegate().GetPageEndReason() fits in a uint32_t, so we can safely cast // to int64_t. builder.SetNavigation_PageEndReason( static_cast<int64_t>(GetDelegate().GetPageEndReason())); if (GetDelegate().DidCommit() && was_cached_) { builder.SetWasCached(1); } if (GetDelegate().DidCommit() && is_signed_exchange_inner_response_) { builder.SetIsSignedExchangeInnerResponse(1); } if (GetDelegate().DidCommit() && navigation_is_cross_process_) { builder.SetIsCrossProcessNavigation(navigation_is_cross_process_); } if (GetDelegate().DidCommit()) { builder.SetNavigationEntryOffset(navigation_entry_offset_); builder.SetMainDocumentSequenceNumber(main_document_sequence_number_); } builder.Record(ukm::UkmRecorder::Get()); } void UkmPageLoadMetricsObserver::ReportMainResourceTimingMetrics( const page_load_metrics::mojom::PageLoadTiming& timing, ukm::builders::PageLoad* builder) { DCHECK(main_frame_timing_.has_value()); builder->SetMainFrameResource_SocketReused(main_frame_timing_->socket_reused); int64_t dns_start_ms = main_frame_timing_->connect_timing.dns_start.since_origin() .InMilliseconds(); int64_t dns_end_ms = main_frame_timing_->connect_timing.dns_end.since_origin() .InMilliseconds(); int64_t connect_start_ms = main_frame_timing_->connect_timing.connect_start.since_origin() .InMilliseconds(); int64_t connect_end_ms = main_frame_timing_->connect_timing.connect_end.since_origin() .InMilliseconds(); int64_t request_start_ms = main_frame_timing_->request_start.since_origin().InMilliseconds(); int64_t send_start_ms = main_frame_timing_->send_start.since_origin().InMilliseconds(); int64_t receive_headers_end_ms = main_frame_timing_->receive_headers_end.since_origin().InMilliseconds(); DCHECK_LE(dns_start_ms, dns_end_ms); DCHECK_LE(dns_end_ms, connect_start_ms); DCHECK_LE(dns_start_ms, connect_start_ms); DCHECK_LE(connect_start_ms, connect_end_ms); int64_t dns_duration_ms = dns_end_ms - dns_start_ms; int64_t connect_duration_ms = connect_end_ms - connect_start_ms; int64_t request_start_to_send_start_ms = send_start_ms - request_start_ms; int64_t send_start_to_receive_headers_end_ms = receive_headers_end_ms - send_start_ms; int64_t request_start_to_receive_headers_end_ms = receive_headers_end_ms - request_start_ms; builder->SetMainFrameResource_DNSDelay(dns_duration_ms); builder->SetMainFrameResource_ConnectDelay(connect_duration_ms); if (request_start_to_send_start_ms >= 0) { builder->SetMainFrameResource_RequestStartToSendStart( request_start_to_send_start_ms); } if (send_start_to_receive_headers_end_ms >= 0) { builder->SetMainFrameResource_SendStartToReceiveHeadersEnd( send_start_to_receive_headers_end_ms); } builder->SetMainFrameResource_RequestStartToReceiveHeadersEnd( request_start_to_receive_headers_end_ms); if (!main_frame_timing_->request_start.is_null() && !GetDelegate().GetNavigationStart().is_null()) { base::TimeDelta navigation_start_to_request_start = main_frame_timing_->request_start - GetDelegate().GetNavigationStart(); builder->SetMainFrameResource_NavigationStartToRequestStart( navigation_start_to_request_start.InMilliseconds()); } if (!main_frame_timing_->receive_headers_start.is_null() && !GetDelegate().GetNavigationStart().is_null()) { base::TimeDelta navigation_start_to_receive_headers_start = main_frame_timing_->receive_headers_start - GetDelegate().GetNavigationStart(); builder->SetMainFrameResource_NavigationStartToReceiveHeadersStart( navigation_start_to_receive_headers_start.InMilliseconds()); } if (connection_info_.has_value()) { page_load_metrics::NetworkProtocol protocol = page_load_metrics::GetNetworkProtocol(*connection_info_); if (IsSupportedProtocol(protocol)) { builder->SetMainFrameResource_HttpProtocolScheme( static_cast<int>(protocol)); } } if (main_frame_request_redirect_count_ > 0) { builder->SetMainFrameResource_RedirectCount( main_frame_request_redirect_count_); } } void UkmPageLoadMetricsObserver::ReportLayoutStability() { ukm::builders::PageLoad(GetDelegate().GetSourceId()) .SetLayoutInstability_CumulativeShiftScore(LayoutShiftUkmValue( GetDelegate().GetPageRenderData().layout_shift_score)) .SetLayoutInstability_CumulativeShiftScore_MainFrame(LayoutShiftUkmValue( GetDelegate().GetMainFrameRenderData().layout_shift_score)) .SetLayoutInstability_CumulativeShiftScore_MainFrame_BeforeInputOrScroll( LayoutShiftUkmValue(GetDelegate() .GetMainFrameRenderData() .layout_shift_score_before_input_or_scroll)) .Record(ukm::UkmRecorder::Get()); UMA_HISTOGRAM_COUNTS_100( "PageLoad.LayoutInstability.CumulativeShiftScore", LayoutShiftUmaValue( GetDelegate().GetPageRenderData().layout_shift_score)); UMA_HISTOGRAM_COUNTS_100( "PageLoad.LayoutInstability.CumulativeShiftScore.MainFrame", LayoutShiftUmaValue( GetDelegate().GetMainFrameRenderData().layout_shift_score)); } void UkmPageLoadMetricsObserver::RecordInputTimingMetrics() { if (GetDelegate().GetPageInputTiming().num_input_events == 0) { return; } ukm::builders::PageLoad(GetDelegate().GetSourceId()) .SetInteractiveTiming_NumInputEvents( GetDelegate().GetPageInputTiming().num_input_events) .SetInteractiveTiming_TotalInputDelay( GetDelegate().GetPageInputTiming().total_input_delay.InMilliseconds()) .SetInteractiveTiming_TotalAdjustedInputDelay( GetDelegate() .GetPageInputTiming() .total_adjusted_input_delay.InMilliseconds()) .Record(ukm::UkmRecorder::Get()); } base::Optional<int64_t> UkmPageLoadMetricsObserver::GetRoundedSiteEngagementScore() const { if (!browser_context_) return base::nullopt; Profile* profile = Profile::FromBrowserContext(browser_context_); SiteEngagementService* engagement_service = SiteEngagementService::Get(profile); // UKM privacy requires the engagement score be rounded to nearest // value of 10. int64_t rounded_document_engagement_score = static_cast<int>(std::roundf( engagement_service->GetScore(GetDelegate().GetUrl()) / 10.0)) * 10; DCHECK(rounded_document_engagement_score >= 0 && rounded_document_engagement_score <= engagement_service->GetMaxPoints()); return rounded_document_engagement_score; } base::Optional<bool> UkmPageLoadMetricsObserver::GetThirdPartyCookieBlockingEnabled() const { if (!browser_context_) return base::nullopt; Profile* profile = Profile::FromBrowserContext(browser_context_); auto cookie_settings = CookieSettingsFactory::GetForProfile(profile); if (!cookie_settings->IsCookieControlsEnabled()) return base::nullopt; return !cookie_settings->IsThirdPartyAccessAllowed(GetDelegate().GetUrl(), nullptr /* source */); } void UkmPageLoadMetricsObserver::OnTimingUpdate( content::RenderFrameHost* subframe_rfh, const page_load_metrics::mojom::PageLoadTiming& timing) { largest_contentful_paint_handler_.RecordTiming(timing.paint_timing, subframe_rfh); bool loading_enabled; TRACE_EVENT_CATEGORY_GROUP_ENABLED("loading", &loading_enabled); if (!loading_enabled) return; const page_load_metrics::ContentfulPaintTimingInfo& paint = largest_contentful_paint_handler_.MergeMainFrameAndSubframes(); if (paint.ContainsValidTime()) { TRACE_EVENT_INSTANT2( "loading", "NavStartToLargestContentfulPaint::Candidate::AllFrames::UKM", TRACE_EVENT_SCOPE_THREAD, "data", paint.DataAsTraceValue(), "main_frame_tree_node_id", largest_contentful_paint_handler_.MainFrameTreeNodeId()); } else { TRACE_EVENT_INSTANT1( "loading", "NavStartToLargestContentfulPaint::" "Invalidate::AllFrames::UKM", TRACE_EVENT_SCOPE_THREAD, "main_frame_tree_node_id", largest_contentful_paint_handler_.MainFrameTreeNodeId()); } } void UkmPageLoadMetricsObserver::OnDidFinishSubFrameNavigation( content::NavigationHandle* navigation_handle) { largest_contentful_paint_handler_.OnDidFinishSubFrameNavigation( navigation_handle, GetDelegate()); } void UkmPageLoadMetricsObserver::OnCpuTimingUpdate( content::RenderFrameHost* subframe_rfh, const page_load_metrics::mojom::CpuTiming& timing) { if (GetDelegate().GetVisibilityTracker().currently_in_foreground()) total_foreground_cpu_time_ += timing.task_time; } void UkmPageLoadMetricsObserver::RecordNoStatePrefetchMetrics( content::NavigationHandle* navigation_handle, ukm::SourceId source_id) { prerender::PrerenderManager* const prerender_manager = prerender::PrerenderManagerFactory::GetForBrowserContext( navigation_handle->GetWebContents()->GetBrowserContext()); if (!prerender_manager) return; const std::vector<GURL>& redirects = navigation_handle->GetRedirectChain(); base::TimeDelta prefetch_age; prerender::FinalStatus final_status; prerender::Origin prefetch_origin; bool nostate_prefetch_entry_found = prerender_manager->GetPrefetchInformation( navigation_handle->GetURL(), &prefetch_age, &final_status, &prefetch_origin); // Try the URLs from the redirect chain. if (!nostate_prefetch_entry_found) { for (const auto& url : redirects) { nostate_prefetch_entry_found = prerender_manager->GetPrefetchInformation( url, &prefetch_age, &final_status, &prefetch_origin); if (nostate_prefetch_entry_found) break; } } if (!nostate_prefetch_entry_found) return; ukm::builders::NoStatePrefetch builder(source_id); builder.SetPrefetchedRecently_PrefetchAge( ukm::GetExponentialBucketMinForUserTiming(prefetch_age.InMilliseconds())); builder.SetPrefetchedRecently_FinalStatus(final_status); builder.SetPrefetchedRecently_Origin(prefetch_origin); builder.Record(ukm::UkmRecorder::Get()); } bool UkmPageLoadMetricsObserver::IsOfflinePreview( content::WebContents* web_contents) const { #if BUILDFLAG(ENABLE_OFFLINE_PAGES) offline_pages::OfflinePageTabHelper* tab_helper = offline_pages::OfflinePageTabHelper::FromWebContents(web_contents); return tab_helper && tab_helper->GetOfflinePreviewItem(); #else return false; #endif } void UkmPageLoadMetricsObserver::RecordGeneratedNavigationUKM( ukm::SourceId source_id, const GURL& committed_url) { bool final_url_is_home_page = IsUserHomePage(browser_context_, committed_url); bool final_url_is_default_search = IsDefaultSearchEngine(browser_context_, committed_url); if (!final_url_is_home_page && !final_url_is_default_search && !start_url_is_home_page_ && !start_url_is_default_search_) { return; } ukm::builders::GeneratedNavigation builder(source_id); builder.SetFinalURLIsHomePage(final_url_is_home_page); builder.SetFinalURLIsDefaultSearchEngine(final_url_is_default_search); builder.SetFirstURLIsHomePage(start_url_is_home_page_); builder.SetFirstURLIsDefaultSearchEngine(start_url_is_default_search_); builder.Record(ukm::UkmRecorder::Get()); }
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
b81e1e6e08239685610e0ba83a55f8783c2bfde4
3fc1ee94ebece7022c99d69cad39c3710487a74a
/chrome/browser/chromeos/policy/active_directory_policy_manager.cc
c9f968d3b6c3e385320d9a05de7e65f844b24487
[ "BSD-3-Clause" ]
permissive
vseal001/chromium
b78653699caa6d54f45401ad0d9e3e90c160b8fb
474eca05898d2524072c2e3d962a866ddcfe37fc
refs/heads/master
2023-01-15T05:05:41.728378
2018-08-07T12:38:42
2018-08-07T12:38:42
143,872,860
0
1
null
2018-08-07T12:52:25
2018-08-07T12:52:25
null
UTF-8
C++
false
false
14,246
cc
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/policy/active_directory_policy_manager.h" #include <string> #include <utility> #include "base/logging.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/net/system_network_context_manager.h" #include "chromeos/cryptohome/cryptohome_parameters.h" #include "chromeos/dbus/auth_policy_client.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/login_manager/policy_descriptor.pb.h" #include "chromeos/tools/variable_expander.h" #include "components/policy/core/common/cloud/cloud_external_data_manager.h" #include "components/policy/core/common/cloud/component_cloud_policy_store.h" #include "components/policy/core/common/policy_bundle.h" #include "components/policy/core/common/policy_namespace.h" #include "components/policy/core/common/policy_switches.h" #include "components/policy/policy_constants.h" #include "services/network/public/cpp/shared_url_loader_factory.h" namespace em = enterprise_management; namespace policy { namespace { // List of policies where variables like ${machine_name} should be expanded. constexpr const char* kPoliciesToExpand[] = {key::kNativePrinters}; // Fetch policy every 90 minutes which matches the Windows default: // https://technet.microsoft.com/en-us/library/cc940895.aspx constexpr base::TimeDelta kFetchInterval = base::TimeDelta::FromMinutes(90); void RunRefreshCallback(base::OnceCallback<void(bool success)> callback, authpolicy::ErrorType error) { std::move(callback).Run(error == authpolicy::ERROR_NONE); } // Gets the AuthPolicy D-Bus interface. chromeos::AuthPolicyClient* GetAuthPolicyClient() { chromeos::DBusThreadManager* thread_manager = chromeos::DBusThreadManager::Get(); DCHECK(thread_manager); chromeos::AuthPolicyClient* auth_policy_client = thread_manager->GetAuthPolicyClient(); DCHECK(auth_policy_client); return auth_policy_client; } bool IsComponentPolicyDisabled() { return base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableComponentCloudPolicy); } } // namespace ActiveDirectoryPolicyManager::~ActiveDirectoryPolicyManager() = default; void ActiveDirectoryPolicyManager::Init(SchemaRegistry* registry) { ConfigurationPolicyProvider::Init(registry); store_->AddObserver(this); if (!store_->is_initialized()) { store_->Load(); } // Does nothing if |store_| hasn't yet initialized. PublishPolicy(); scheduler_ = std::make_unique<PolicyScheduler>( base::BindRepeating(&ActiveDirectoryPolicyManager::DoPolicyFetch, weak_ptr_factory_.GetWeakPtr()), base::BindRepeating(&ActiveDirectoryPolicyManager::OnPolicyFetched, weak_ptr_factory_.GetWeakPtr()), kFetchInterval); if (external_data_manager_) { // Use the system network context here instead of a context derived from the // Profile because Connect() is called before the profile is fully // initialized (required so we can perform the initial policy load). // Note: The network context can be null for tests and for device policy. external_data_manager_->Connect( g_browser_process->system_network_context_manager() ? g_browser_process->system_network_context_manager() ->GetSharedURLLoaderFactory() : nullptr); } } void ActiveDirectoryPolicyManager::Shutdown() { if (external_data_manager_) external_data_manager_->Disconnect(); extension_policy_service_.reset(); store_->RemoveObserver(this); ConfigurationPolicyProvider::Shutdown(); } bool ActiveDirectoryPolicyManager::IsInitializationComplete( PolicyDomain domain) const { if (domain == POLICY_DOMAIN_CHROME) return store_->is_initialized(); if (domain == extension_policy_domain_ && !IsComponentPolicyDisabled()) { return extension_policy_service_ && extension_policy_service_->policy() != nullptr; } return true; } void ActiveDirectoryPolicyManager::RefreshPolicies() { scheduler_->ScheduleTaskNow(); } void ActiveDirectoryPolicyManager::OnStoreLoaded( CloudPolicyStore* cloud_policy_store) { DCHECK_EQ(store_.get(), cloud_policy_store); PublishPolicy(); if (fetch_ever_completed_) { // Policy is guaranteed to be up to date with the previous fetch result // because OnPolicyFetched() cancels any potentially running Load() // operations. CancelWaitForInitialPolicy(); } } void ActiveDirectoryPolicyManager::OnStoreError( CloudPolicyStore* cloud_policy_store) { DCHECK_EQ(store_.get(), cloud_policy_store); // Publish policy (even though it hasn't changed) in order to signal load // complete on the ConfigurationPolicyProvider interface. Technically, this is // only required on the first load, but doesn't hurt in any case. PublishPolicy(); if (fetch_ever_completed_) { CancelWaitForInitialPolicy(); } } ActiveDirectoryPolicyManager::ActiveDirectoryPolicyManager( std::unique_ptr<CloudPolicyStore> store, std::unique_ptr<CloudExternalDataManager> external_data_manager, PolicyDomain extension_policy_domain) : store_(std::move(store)), external_data_manager_(std::move(external_data_manager)), extension_policy_domain_(extension_policy_domain) { DCHECK(extension_policy_domain_ == POLICY_DOMAIN_EXTENSIONS || extension_policy_domain_ == POLICY_DOMAIN_SIGNIN_EXTENSIONS); } void ActiveDirectoryPolicyManager::OnComponentActiveDirectoryPolicyUpdated() { PublishPolicy(); } void ActiveDirectoryPolicyManager::PublishPolicy() { if (!store_->is_initialized()) { return; } std::unique_ptr<PolicyBundle> bundle = std::make_unique<PolicyBundle>(); PolicyMap& policy_map = bundle->Get(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string())); policy_map.CopyFrom(store_->policy_map()); if (extension_policy_service_ && extension_policy_service_->policy()) bundle->MergeFrom(*extension_policy_service_->policy()); // Overwrite the source which is POLICY_SOURCE_CLOUD by default. // TODO(tnagel): Rename CloudPolicyStore to PolicyStore and make the source // configurable, then drop PolicyMap::SetSourceForAll(). policy_map.SetSourceForAll(POLICY_SOURCE_ACTIVE_DIRECTORY); SetEnterpriseUsersDefaults(&policy_map); // Expand e.g. ${machine_name} for a selected set of policies. ExpandVariables(&policy_map); // Policy is ready, send it off. UpdatePolicy(std::move(bundle)); } void ActiveDirectoryPolicyManager::CreateExtensionPolicyService( PolicyScope scope, login_manager::PolicyAccountType account_type, const AccountId& account_id, SchemaRegistry* schema_registry) { if (IsComponentPolicyDisabled()) return; std::string cryptohome_id; if (!account_id.empty()) cryptohome_id = cryptohome::Identification(account_id).id(); // Create the service for sign-in extensions (device scope) or user profile // extensions (user scope). DCHECK(!extension_policy_service_); extension_policy_service_ = std::make_unique<ComponentActiveDirectoryPolicyService>( scope, extension_policy_domain_, account_type, cryptohome_id, this, schema_registry); } void ActiveDirectoryPolicyManager::OnPolicyFetched(bool success) { fetch_ever_completed_ = true; // In case of failure try to proceed with cached policy. if (!success && store()->is_initialized()) CancelWaitForInitialPolicy(); // Load/retrieve independently of success or failure to keep in sync with the // state in session manager. This cancels any potentially running Load() // operations thus it is guaranteed that at the next OnStoreLoaded() // invocation the policy is up-to-date with what was fetched. store_->Load(); if (extension_policy_service_) extension_policy_service_->RetrievePolicies(); } void ActiveDirectoryPolicyManager::ExpandVariables(PolicyMap* policy_map) { const em::PolicyData* policy = store_->policy(); if (!policy || policy_map->empty()) return; if (policy->machine_name().empty()) { LOG(ERROR) << "Cannot expand machine_name (empty string in policy)"; return; } chromeos::VariableExpander expander( {{"machine_name", policy->machine_name()}}); for (const char* policy_name : kPoliciesToExpand) { base::Value* value = policy_map->GetMutableValue(policy_name); if (value) { if (!expander.ExpandValue(value)) { LOG(ERROR) << "Failed to expand at least one variable in policy " << policy_name; } } } } UserActiveDirectoryPolicyManager::UserActiveDirectoryPolicyManager( const AccountId& account_id, bool policy_required, base::TimeDelta initial_policy_fetch_timeout, base::OnceClosure exit_session, std::unique_ptr<CloudPolicyStore> store, std::unique_ptr<CloudExternalDataManager> external_data_manager) : ActiveDirectoryPolicyManager( std::move(store), std::move(external_data_manager), POLICY_DOMAIN_EXTENSIONS /* extension_policy_domain */), account_id_(account_id), policy_required_(policy_required), waiting_for_initial_policy_fetch_( !initial_policy_fetch_timeout.is_zero()), exit_session_(std::move(exit_session)) { DCHECK(!initial_policy_fetch_timeout.is_max()); // Delaying initialization complete is intended for user policy only. if (waiting_for_initial_policy_fetch_) { initial_policy_timeout_.Start( FROM_HERE, initial_policy_fetch_timeout, base::Bind(&UserActiveDirectoryPolicyManager::OnBlockingFetchTimeout, weak_ptr_factory_.GetWeakPtr())); } } UserActiveDirectoryPolicyManager::~UserActiveDirectoryPolicyManager() = default; void UserActiveDirectoryPolicyManager::Init(SchemaRegistry* registry) { DCHECK(store()->is_initialized() || waiting_for_initial_policy_fetch_); if (store()->is_initialized() && !store()->has_policy() && policy_required_) { // Exit the session in case of immediate load if policy is required. LOG(ERROR) << "Policy from forced immediate load could not be obtained. " << "Aborting profile initialization"; if (exit_session_) std::move(exit_session_).Run(); } ActiveDirectoryPolicyManager::Init(registry); // Create the extension policy handler here. This is different from the device // policy manager, which can't do this in Init() because it needs to wait for // the sign-in profile's schema registry. CreateExtensionPolicyService(POLICY_SCOPE_USER, login_manager::ACCOUNT_TYPE_USER, account_id_, registry); } bool UserActiveDirectoryPolicyManager::IsInitializationComplete( PolicyDomain domain) const { if (waiting_for_initial_policy_fetch_) return false; return ActiveDirectoryPolicyManager::IsInitializationComplete(domain); } void UserActiveDirectoryPolicyManager::ForceTimeoutForTesting() { DCHECK(initial_policy_timeout_.IsRunning()); // Stop the timer to mimic what happens when a real timer fires, then invoke // the timer callback directly. initial_policy_timeout_.Stop(); OnBlockingFetchTimeout(); } void UserActiveDirectoryPolicyManager::DoPolicyFetch( PolicyScheduler::TaskCallback callback) { GetAuthPolicyClient()->RefreshUserPolicy( account_id_, base::BindOnce(&RunRefreshCallback, std::move(callback))); } void UserActiveDirectoryPolicyManager::CancelWaitForInitialPolicy() { if (!waiting_for_initial_policy_fetch_) return; initial_policy_timeout_.Stop(); // If the conditions to continue profile initialization are not met, the user // session is exited and initialization is not set as completed. if (!store()->has_policy() && policy_required_) { // If there's no policy at all (not even cached), but policy is required, // the user session must not continue. LOG(ERROR) << "Policy could not be obtained. " << "Aborting profile initialization"; if (exit_session_) std::move(exit_session_).Run(); return; } // Set initialization complete. waiting_for_initial_policy_fetch_ = false; // Publish policy (even though it hasn't changed) in order to signal load // complete on the ConfigurationPolicyProvider interface. PublishPolicy(); } void UserActiveDirectoryPolicyManager::OnBlockingFetchTimeout() { DCHECK(waiting_for_initial_policy_fetch_); LOG(WARNING) << "Timed out while waiting for the policy fetch. " << "The session will start with the cached policy."; if ((fetch_ever_completed_ && !store()->is_initialized()) || (!fetch_ever_completed_ && !store()->has_policy())) { // Waiting for store to load if policy was fetched. Or for policy fetch to // complete if there is no cached policy. return; } CancelWaitForInitialPolicy(); } DeviceActiveDirectoryPolicyManager::DeviceActiveDirectoryPolicyManager( std::unique_ptr<CloudPolicyStore> store) : ActiveDirectoryPolicyManager( std::move(store), nullptr /* external_data_manager */, POLICY_DOMAIN_SIGNIN_EXTENSIONS /* extension_policy_domain */) {} void DeviceActiveDirectoryPolicyManager::Shutdown() { ActiveDirectoryPolicyManager::Shutdown(); signin_profile_forwarding_schema_registry_.reset(); } void DeviceActiveDirectoryPolicyManager::SetSigninProfileSchemaRegistry( SchemaRegistry* schema_registry) { DCHECK(!signin_profile_forwarding_schema_registry_); signin_profile_forwarding_schema_registry_ = std::make_unique<ForwardingSchemaRegistry>(schema_registry); CreateExtensionPolicyService( POLICY_SCOPE_MACHINE, login_manager::ACCOUNT_TYPE_DEVICE, EmptyAccountId(), signin_profile_forwarding_schema_registry_.get()); } DeviceActiveDirectoryPolicyManager::~DeviceActiveDirectoryPolicyManager() = default; void DeviceActiveDirectoryPolicyManager::DoPolicyFetch( base::OnceCallback<void(bool success)> callback) { GetAuthPolicyClient()->RefreshDevicePolicy( base::BindOnce(&RunRefreshCallback, std::move(callback))); } } // namespace policy
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
942a81b45dffd1095d2040f53682e980469531bd
902a7285713ba08930ccc42205bfce6deef933a9
/Graph/ReBitmap.cpp
786a66b6d80f02148cb6f1e7f07b1ccbd300facc
[ "MIT" ]
permissive
neville1/Graph2D
cf66cd84ec3122e6c9b651f75bd464604d89bf64
646177e824098ad06c34bd28ae92f2840103ec50
refs/heads/master
2020-12-02T21:12:33.188434
2017-07-05T03:20:53
2017-07-05T03:20:53
96,272,163
1
1
null
null
null
null
UTF-8
C++
false
false
9,527
cpp
#include "StdAfx.h" #include "ReBitmap.h" #include "ReDraw.h" #include "Shape.h" #include "DIBSectionLite.h" CReBitmap::CReBitmap() : m_pData(0), m_hBmp(0), m_nBmpPitch(0) {} CReBitmap::CReBitmap(int nWidth, int nHeight) { m_pData = 0; m_hBmp = 0; m_szBmp.cx = nWidth; m_szBmp.cy = nHeight; m_nBmpPitch = m_szBmp.cx * 2; m_pData = new BYTE[nWidth * nHeight * 2]; } CReBitmap::CReBitmap(int nWidth, int nHeight, BYTE *pData) { m_hBmp = 0; m_szBmp.cx = nWidth; m_szBmp.cy = nHeight; m_nBmpPitch = m_szBmp.cx * 2; m_pData = pData; } CReBitmap::~CReBitmap() { if (m_hBmp) { ::DeleteObject(m_hBmp); } if (m_pData) { delete m_pData; } } void CReBitmap::ClearData() { if (m_pData) { delete m_pData; } m_pData = 0; } void CReBitmap::SetData(int nWidth,int nHeight) { if (m_pData) { delete m_pData; } m_szBmp.cx = nWidth; m_szBmp.cy = nHeight; m_nBmpPitch = m_szBmp.cx * 2; m_pData = new BYTE[nWidth * nHeight * 2]; } bool CReBitmap::LoadBmp(HINSTANCE hInstance, LPCWSTR lpBitmapName) { HBITMAP hBmp = ::LoadBitmap(hInstance, lpBitmapName); ASSERT(hBmp); return LoadBmp(hBmp); } bool CReBitmap::LoadBmp(LPCWSTR lpBitmapName) { CDIBSectionLite dib; if ( ! dib.Load(lpBitmapName) ) return false; HBITMAP hBmp = dib.GetSafeHandle(); if (!hBmp) { return false; } return LoadBmp(hBmp); } bool CReBitmap::LoadBmp(HBITMAP hBmp) { ASSERT(hBmp); if(m_pData) { delete m_pData; m_pData = 0; } if (m_hBmp) { ::DeleteObject(m_hBmp); m_hBmp = 0; } BITMAP Bitmap; GetObject( hBmp, sizeof(BITMAP), &Bitmap); BITMAPINFO dibInfo; dibInfo.bmiHeader.biBitCount = 24; dibInfo.bmiHeader.biClrImportant = 0; dibInfo.bmiHeader.biClrUsed = 0; dibInfo.bmiHeader.biCompression = BI_RGB; dibInfo.bmiHeader.biHeight = Bitmap.bmHeight; dibInfo.bmiHeader.biPlanes = 1; dibInfo.bmiHeader.biSize = sizeof( BITMAPINFOHEADER ); dibInfo.bmiHeader.biSizeImage = Bitmap.bmWidth * Bitmap.bmHeight * 3; dibInfo.bmiHeader.biWidth = Bitmap.bmWidth; dibInfo.bmiHeader.biXPelsPerMeter = 0; dibInfo.bmiHeader.biYPelsPerMeter = 0; dibInfo.bmiColors[0].rgbRed = 0; dibInfo.bmiColors[0].rgbGreen = 0; dibInfo.bmiColors[0].rgbBlue = 0; dibInfo.bmiColors[0].rgbReserved = 0; HDC hDC = ::GetDC(NULL); m_hBmp = CreateDIBSection(hDC, (const BITMAPINFO*)&dibInfo, DIB_RGB_COLORS, (void**)&m_pData, NULL, 0); ::ReleaseDC(NULL, hDC); HDC memDc = CreateCompatibleDC(NULL); if (!memDc) { DeleteObject( hBmp ); DeleteObject( m_hBmp ); m_hBmp = 0; return false; } HDC targetDc = CreateCompatibleDC(NULL); if (!targetDc) { DeleteDC( memDc ); DeleteObject( hBmp ); DeleteObject( m_hBmp ); m_hBmp = 0; return false; } HBITMAP hOldBitmap1 = (HBITMAP)::SelectObject( memDc, hBmp); HBITMAP hOldBitmap2 = (HBITMAP)::SelectObject( targetDc, m_hBmp ); ::BitBlt( targetDc, 0, 0, Bitmap.bmWidth, Bitmap.bmHeight, memDc, 0, 0, SRCCOPY ); m_szBmp.cx = Bitmap.bmWidth; m_szBmp.cy = Bitmap.bmHeight; int nBpp = 3; m_nBmpPitch = ((Bitmap.bmWidth * 3) + 3) & 0xfffc; ::SelectObject(memDc, hOldBitmap1); ::SelectObject(targetDc, hOldBitmap2); DeleteDC(memDc); DeleteDC(targetDc); DeleteObject(hBmp); BYTE *pByte = 0; UINT16 *pImage = new UINT16[m_szBmp.cx * m_szBmp.cy]; for (int nY = 0; nY < m_szBmp.cy; ++nY) { for (int nX = 0; nX < m_szBmp.cx; ++nX) { pByte = (m_pData + nY * m_nBmpPitch + nX * nBpp); COLORREF col(RGB(pByte[2], pByte[1], pByte[0])); pImage[nY * Bitmap.bmWidth + nX] = GetViewColor565(col); } } m_pData = (BYTE *) pImage; m_nBmpPitch = m_szBmp.cx * CReDraw::GetBpp(); if (m_szBmp.cx > 1000 || m_szBmp.cy > 1000) { AfxMessageBox(_T("Size Info Error")); } return true; } bool CReBitmap::BitBlt(int nX, int nY) { if (!m_pData) { return false; } RECT *pRect = CReDraw::GetDrawRect(); if (nX < pRect->left || nY < pRect->top || nX + m_szBmp.cx > (int) pRect->right || nY + m_szBmp.cy > (int) pRect->bottom) { return false; } UINT16 *pSrcData = 0; UINT16 nTempData; for (int y = 0; y < m_szBmp.cy; ++y) { pSrcData = (UINT16 *) (m_pData + (m_szBmp.cy - y - 1) * m_nBmpPitch); for (int x = 0; x < m_szBmp.cx; ++x) { if (CShape::s_BitCount == 15) { nTempData = ((pSrcData[x] >> 6) << 5) | (pSrcData[x] & 0x1F); DrawPixel(nX + x, nY + y, nTempData); } else { DrawPixel(nX + x, nY + y, pSrcData[x]); } } } return true; } bool CReBitmap::MaskBitBlt(int nX, int nY, COLORREF col) { if (!m_pData) { return false; } RECT *pRect = CReDraw::GetDrawRect(); if (nX < pRect->left || nY < pRect->top || nX + m_szBmp.cx > (int) pRect->right || nY + m_szBmp.cy > (int) pRect->bottom) { return false; } UINT16 colMask = GetViewColor(col); UINT16 *pSrcData = 0; UINT16 nTempData; for (int y = 0; y < m_szBmp.cy; ++y) { pSrcData =(UINT16 *) (m_pData + (m_szBmp.cy - y - 1) * m_nBmpPitch); for (int x = 0; x < m_szBmp.cx; ++x) { if (CShape::s_BitCount == 15) { nTempData = ((pSrcData[x] >> 6) << 5) | (pSrcData[x] & 0x1F); if(nTempData != colMask) { DrawPixel(nX + x, nY + y, nTempData); } }else { if(pSrcData[x] != colMask) { DrawPixel(nX + x, nY + y, pSrcData[x]); } } } } return true; } bool CReBitmap::MaskBitBlt(int nX, int nY) { if (!m_pData) { return false; } RECT *pRect = CReDraw::GetDrawRect(); if (nX < pRect->left || nY < pRect->top || nX + m_szBmp.cx > (int) pRect->right || nY + m_szBmp.cy > (int) pRect->bottom) { return false; } UINT16 colMask = static_cast<UINT16>(*m_pData); UINT16 *pSrcData = 0; for (int y = 0; y < m_szBmp.cy; ++y) { pSrcData =(UINT16 *) (m_pData + (m_szBmp.cy - y - 1) * m_nBmpPitch); for (int x = 0; x < m_szBmp.cx; ++x) { if(pSrcData[x] != colMask) { DrawPixel(nX + x, nY + y, pSrcData[x]); } } } return true; } bool CReBitmap::SplitBitBlt(int nX, int nY, int nOffset, COLORREF col) { if (!m_pData) { return false; } RECT *pRect = CReDraw::GetDrawRect(); if (nX < pRect->left || nY < pRect->top || nX + m_szBmp.cx > (int) pRect->right || nY + m_szBmp.cy > (int) pRect->bottom) { return false; } UINT16 colMask = GetViewColor(col); UINT16 *pSrcData = 0; UINT16 nTempData; for (int y = 0; y < m_szBmp.cy - nOffset; ++y) { pSrcData =(UINT16 *) (m_pData + (m_szBmp.cy - y - 1) * m_nBmpPitch); for (int x = 0; x < m_szBmp.cx - nOffset; ++x) { if (CShape::s_BitCount == 15) { nTempData = ((pSrcData[x] >> 6) << 5) | (pSrcData[x] & 0x1F); if(nTempData != colMask) { DrawPixel(nX + x, nY + y, nTempData); } }else { if(pSrcData[x] != colMask) { DrawPixel(nX + x, nY + y, pSrcData[x]); } } } } return true; } bool CReBitmap::TransparentBitBlt(int nX, int nY, float fAlpha) { if (!m_pData) { return false; } RECT *pRect = CReDraw::GetDrawRect(); if (nX < pRect->left || nY < pRect->top || nX + m_szBmp.cx > (int) pRect->right || nY + m_szBmp.cy > (int) pRect->bottom) { return false; } UINT16 *pSrcData = 0; UINT16 colAlpha = 0; UINT16 nTempData = 0; for (int y = 0; y < m_szBmp.cy; ++y) { pSrcData =(UINT16 *) (m_pData + (m_szBmp.cy - y - 1) * m_nBmpPitch); for (int x = 0; x < m_szBmp.cx; ++x) { if (CShape::s_BitCount == 15) { nTempData = ((pSrcData[x] >> 6) << 5) | (pSrcData[x] & 0x1F); colAlpha = GetAlphaColor(nX + x, nY + y, nTempData, fAlpha); } colAlpha = GetAlphaColor(nX + x, nY + y, pSrcData[x], fAlpha); DrawPixel(nX + x, nY + y, colAlpha); } } return true; } bool CReBitmap::TransparentMaskBitBlt(int nX, int nY, COLORREF col, float fAlpha) { if (!m_pData) { return false; } RECT *pRect = CReDraw::GetDrawRect(); if (nX < 0 || nY < 0 || nX + m_szBmp.cx > (int) pRect->right || nY + m_szBmp.cy > (int) pRect->bottom) { return false; } UINT16 colMask = GetViewColor(col); UINT16 *pSrcData = 0; UINT16 colAlpha = 0; UINT16 nTempData = 0; for (int y = 0; y < m_szBmp.cy; ++y) { pSrcData =(UINT16 *) (m_pData + (m_szBmp.cy - y - 1) * m_nBmpPitch); for (int x = 0; x < m_szBmp.cx; ++x) { if (CShape::s_BitCount == 15) { nTempData = ((pSrcData[x] >> 6) << 5) | (pSrcData[x] & 0x1F); } else { nTempData = pSrcData[x]; } if (nTempData != colMask) { colAlpha = GetAlphaColor(nX + x, nY + y, nTempData, fAlpha); DrawPixel(nX + x, nY + y, colAlpha); } } } return true; } bool CReBitmap::TransparentMask(int nX, int nY, COLORREF colMask, COLORREF col, float fAlpha) { if (!m_pData) { return false; } RECT *pRect = CReDraw::GetDrawRect(); if (nX < 0 || nY < 0 || nX + m_szBmp.cx > (int) pRect->right || nY + m_szBmp.cy > (int) pRect->bottom) { return false; } UINT16 colMask16 = GetViewColor(colMask); UINT16 colBK = GetViewColor(col); UINT16 *pSrcData = 0; UINT16 colAlpha = 0; UINT16 nTempData = 0; for (int y = 0; y < m_szBmp.cy; ++y) { pSrcData =(UINT16 *) (m_pData + (m_szBmp.cy - y - 1) * m_nBmpPitch); for (int x = 0; x < m_szBmp.cx; ++x) { if (CShape::s_BitCount == 15) { nTempData = ((pSrcData[x] >> 6) << 5) | (pSrcData[x] & 0x1F); } else { nTempData = pSrcData[x]; } if (nTempData != colMask16) { colAlpha = GetAlphaColor(nX + x, nY + y, colBK, fAlpha); DrawPixel(nX + x, nY + y, colAlpha); } } } return true; }
[ "nevillegee@sysgration.com" ]
nevillegee@sysgration.com
dea85977884d289c2087b2d047daa01475589946
19eb97436a3be9642517ea9c4095fe337fd58a00
/private/shell/cpls/inetcpl/clsutil.cpp
ef85621f73e46f13409c9c4cd81277d77b31d728
[]
no_license
oturan-boga/Windows2000
7d258fd0f42a225c2be72f2b762d799bd488de58
8b449d6659840b6ba19465100d21ca07a0e07236
refs/heads/main
2023-04-09T23:13:21.992398
2021-04-22T11:46:21
2021-04-22T11:46:21
360,495,781
2
0
null
null
null
null
UTF-8
C++
false
false
14,471
cpp
//********************************************************************* //* Microsoft Windows ** //* Copyright(c) Microsoft Corp., 1994-1995 ** //********************************************************************* // // CLSUTIL.C - some small, useful C++ classes to wrap memory allocation, // registry access, etc. // // HISTORY: // // 12/07/94 jeremys Borrowed from WNET common library // #include "inetcplp.h" BOOL BUFFER::Alloc( UINT cbBuffer ) { _lpBuffer = (LPTSTR)::GlobalAlloc(GPTR,cbBuffer); if (_lpBuffer != NULL) { _cb = cbBuffer; return TRUE; } return FALSE; } BOOL BUFFER::Realloc( UINT cbNew ) { LPVOID lpNew = ::GlobalReAlloc((HGLOBAL)_lpBuffer, cbNew, GMEM_MOVEABLE | GMEM_ZEROINIT); if (lpNew == NULL) return FALSE; _lpBuffer = (LPTSTR)lpNew; _cb = cbNew; return TRUE; } BUFFER::BUFFER( UINT cbInitial /* =0 */ ) : BUFFER_BASE(), _lpBuffer( NULL ) { if (cbInitial) Alloc( cbInitial ); } BUFFER::~BUFFER() { if (_lpBuffer != NULL) { GlobalFree((HGLOBAL) _lpBuffer); _lpBuffer = NULL; } } BOOL BUFFER::Resize( UINT cbNew ) { BOOL fSuccess; if (QuerySize() == 0) fSuccess = Alloc( cbNew ); else { fSuccess = Realloc( cbNew ); } if (fSuccess) _cb = cbNew; return fSuccess; } RegEntry::RegEntry(const TCHAR *pszSubKey, HKEY hkey, REGSAM regsam) { _error = RegCreateKeyEx(hkey, pszSubKey, 0, NULL, 0, regsam, NULL, &_hkey, NULL); if (_error) { bhkeyValid = FALSE; } else { bhkeyValid = TRUE; } } RegEntry::~RegEntry() { if (bhkeyValid) { RegCloseKey(_hkey); } } long RegEntry::SetValue(const TCHAR *pszValue, const TCHAR *string) { if (bhkeyValid) { _error = RegSetValueEx(_hkey, pszValue, 0, REG_SZ, (LPBYTE)string, (lstrlen(string)+1)*sizeof(TCHAR)); } return _error; } long RegEntry::SetValue(const TCHAR *pszValue, unsigned long dwNumber) { if (bhkeyValid) { _error = RegSetValueEx(_hkey, pszValue, 0, REG_BINARY, (LPBYTE)&dwNumber, sizeof(dwNumber)); } return _error; } long RegEntry::DeleteValue(const TCHAR *pszValue) { if (bhkeyValid) { _error = RegDeleteValue(_hkey, (LPTSTR) pszValue); } return _error; } TCHAR *RegEntry::GetString(const TCHAR *pszValue, TCHAR *string, unsigned long length) { DWORD dwType; if (bhkeyValid) { _error = RegQueryValueEx(_hkey, (LPTSTR) pszValue, 0, &dwType, (LPBYTE)string, &length); } if (_error) { *string = '\0'; return NULL; } return string; } long RegEntry::GetNumber(const TCHAR *pszValue, long dwDefault) { DWORD dwType; long dwNumber = 0L; DWORD dwSize = sizeof(dwNumber); if (bhkeyValid) { _error = RegQueryValueEx(_hkey, (LPTSTR) pszValue, 0, &dwType, (LPBYTE)&dwNumber, &dwSize); } if (_error) dwNumber = dwDefault; return dwNumber; } long RegEntry::MoveToSubKey(const TCHAR *pszSubKeyName) { HKEY _hNewKey; if (bhkeyValid) { _error = RegOpenKeyEx ( _hkey, pszSubKeyName, 0, KEY_READ|KEY_WRITE, &_hNewKey ); if (_error == ERROR_SUCCESS) { RegCloseKey(_hkey); _hkey = _hNewKey; } } return _error; } long RegEntry::FlushKey() { if (bhkeyValid) { _error = RegFlushKey(_hkey); } return _error; } RegEnumValues::RegEnumValues(RegEntry *pReqRegEntry) : pRegEntry(pReqRegEntry), iEnum(0), pchName(NULL), pbValue(NULL) { _error = pRegEntry->GetError(); if (_error == ERROR_SUCCESS) { _error = RegQueryInfoKey ( pRegEntry->GetKey(), // Key NULL, // Buffer for class string NULL, // Size of class string buffer NULL, // Reserved NULL, // Number of subkeys NULL, // Longest subkey name NULL, // Longest class string &cEntries, // Number of value entries &cMaxValueName, // Longest value name &cMaxData, // Longest value data NULL, // Security descriptor NULL ); // Last write time } if (_error == ERROR_SUCCESS) { if (cEntries != 0) { cMaxValueName = cMaxValueName + 1; // REG_SZ needs one more for null cMaxData = cMaxData + 1; // REG_SZ needs one more for null pchName = new TCHAR[cMaxValueName]; if (!pchName) { _error = ERROR_NOT_ENOUGH_MEMORY; } else { if (cMaxData) { pbValue = new BYTE[cMaxData]; if (!pbValue) { _error = ERROR_NOT_ENOUGH_MEMORY; } } } } } } RegEnumValues::~RegEnumValues() { delete pchName; delete pbValue; } long RegEnumValues::Next() { if (_error != ERROR_SUCCESS) { return _error; } if (cEntries == iEnum) { return ERROR_NO_MORE_ITEMS; } DWORD cchName = cMaxValueName; dwDataLength = cMaxData; _error = RegEnumValue ( pRegEntry->GetKey(), // Key iEnum, // Index of value pchName, // Address of buffer for value name &cchName, // Address for size of buffer NULL, // Reserved &dwType, // Data type pbValue, // Address of buffer for value data &dwDataLength ); // Address for size of data iEnum++; return _error; } int __cdecl _purecall(void) { return(0); } void * _cdecl operator new(size_t size) { return (void *)::GlobalAlloc(GPTR,size); } void _cdecl operator delete(void *ptr) { GlobalFree(ptr); } ////////////////////////////////////////////////////////////////////////////// // // CAccessibleWrapper implementation // ////////////////////////////////////////////////////////////////////////////// CAccessibleWrapper::CAccessibleWrapper( IAccessible * pAcc ) : m_ref( 1 ), m_pAcc( pAcc ), m_pEnumVar( NULL ), m_pOleWin( NULL ) { m_pAcc->AddRef(); } CAccessibleWrapper::~CAccessibleWrapper() { m_pAcc->Release(); if( m_pEnumVar ) m_pEnumVar->Release(); if( m_pOleWin ) m_pOleWin->Release(); } // IUnknown // Implement refcounting ourselves // Also implement QI ourselves, so that we return a ptr back to the wrapper. STDMETHODIMP CAccessibleWrapper::QueryInterface(REFIID riid, void** ppv) { HRESULT hr; *ppv = NULL; if ((riid == IID_IUnknown) || (riid == IID_IDispatch) || (riid == IID_IAccessible)) { *ppv = (IAccessible *) this; } else if( riid == IID_IEnumVARIANT ) { // Get the IEnumVariant from the object we are sub-classing so we can delegate // calls. if( ! m_pEnumVar ) { hr = m_pAcc->QueryInterface( IID_IEnumVARIANT, (void **) & m_pEnumVar ); if( FAILED( hr ) ) { m_pEnumVar = NULL; return hr; } // Paranoia (in case QI returns S_OK with NULL...) if( ! m_pEnumVar ) return E_NOINTERFACE; } *ppv = (IEnumVARIANT *) this; } else if( riid == IID_IOleWindow ) { // Get the IOleWindow from the object we are sub-classing so we can delegate // calls. if( ! m_pOleWin ) { hr = m_pAcc->QueryInterface( IID_IOleWindow, (void **) & m_pOleWin ); if( FAILED( hr ) ) { m_pOleWin = NULL; return hr; } // Paranoia (in case QI returns S_OK with NULL...) if( ! m_pOleWin ) return E_NOINTERFACE; } *ppv = (IOleWindow*) this; } else return(E_NOINTERFACE); AddRef(); return(NOERROR); } STDMETHODIMP_(ULONG) CAccessibleWrapper::AddRef() { return ++m_ref; } STDMETHODIMP_(ULONG) CAccessibleWrapper::Release() { ULONG ulRet = --m_ref; if( ulRet == 0 ) delete this; return ulRet; } // IDispatch // - pass all through m_pAcc STDMETHODIMP CAccessibleWrapper::GetTypeInfoCount(UINT* pctinfo) { return m_pAcc->GetTypeInfoCount(pctinfo); } STDMETHODIMP CAccessibleWrapper::GetTypeInfo(UINT itinfo, LCID lcid, ITypeInfo** pptinfo) { return m_pAcc->GetTypeInfo(itinfo, lcid, pptinfo); } STDMETHODIMP CAccessibleWrapper::GetIDsOfNames(REFIID riid, OLECHAR** rgszNames, UINT cNames, LCID lcid, DISPID* rgdispid) { return m_pAcc->GetIDsOfNames(riid, rgszNames, cNames, lcid, rgdispid); } STDMETHODIMP CAccessibleWrapper::Invoke(DISPID dispidMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS* pdispparams, VARIANT* pvarResult, EXCEPINFO* pexcepinfo, UINT* puArgErr) { return m_pAcc->Invoke(dispidMember, riid, lcid, wFlags, pdispparams, pvarResult, pexcepinfo, puArgErr); } // IAccessible // - pass all through m_pAcc STDMETHODIMP CAccessibleWrapper::get_accParent(IDispatch ** ppdispParent) { return m_pAcc->get_accParent(ppdispParent); } STDMETHODIMP CAccessibleWrapper::get_accChildCount(long* pChildCount) { return m_pAcc->get_accChildCount(pChildCount); } STDMETHODIMP CAccessibleWrapper::get_accChild(VARIANT varChild, IDispatch ** ppdispChild) { return m_pAcc->get_accChild(varChild, ppdispChild); } STDMETHODIMP CAccessibleWrapper::get_accName(VARIANT varChild, BSTR* pszName) { return m_pAcc->get_accName(varChild, pszName); } STDMETHODIMP CAccessibleWrapper::get_accValue(VARIANT varChild, BSTR* pszValue) { return m_pAcc->get_accValue(varChild, pszValue); } STDMETHODIMP CAccessibleWrapper::get_accDescription(VARIANT varChild, BSTR* pszDescription) { return m_pAcc->get_accDescription(varChild, pszDescription); } STDMETHODIMP CAccessibleWrapper::get_accRole(VARIANT varChild, VARIANT *pvarRole) { return m_pAcc->get_accRole(varChild, pvarRole); } STDMETHODIMP CAccessibleWrapper::get_accState(VARIANT varChild, VARIANT *pvarState) { return m_pAcc->get_accState(varChild, pvarState); } STDMETHODIMP CAccessibleWrapper::get_accHelp(VARIANT varChild, BSTR* pszHelp) { return m_pAcc->get_accHelp(varChild, pszHelp); } STDMETHODIMP CAccessibleWrapper::get_accHelpTopic(BSTR* pszHelpFile, VARIANT varChild, long* pidTopic) { return m_pAcc->get_accHelpTopic(pszHelpFile, varChild, pidTopic); } STDMETHODIMP CAccessibleWrapper::get_accKeyboardShortcut(VARIANT varChild, BSTR* pszKeyboardShortcut) { return m_pAcc->get_accKeyboardShortcut(varChild, pszKeyboardShortcut); } STDMETHODIMP CAccessibleWrapper::get_accFocus(VARIANT * pvarFocusChild) { return m_pAcc->get_accFocus(pvarFocusChild); } STDMETHODIMP CAccessibleWrapper::get_accSelection(VARIANT * pvarSelectedChildren) { return m_pAcc->get_accSelection(pvarSelectedChildren); } STDMETHODIMP CAccessibleWrapper::get_accDefaultAction(VARIANT varChild, BSTR* pszDefaultAction) { return m_pAcc->get_accDefaultAction(varChild, pszDefaultAction); } STDMETHODIMP CAccessibleWrapper::accSelect(long flagsSel, VARIANT varChild) { return m_pAcc->accSelect(flagsSel, varChild); } STDMETHODIMP CAccessibleWrapper::accLocation(long* pxLeft, long* pyTop, long* pcxWidth, long* pcyHeight, VARIANT varChild) { return m_pAcc->accLocation(pxLeft, pyTop, pcxWidth, pcyHeight, varChild); } STDMETHODIMP CAccessibleWrapper::accNavigate(long navDir, VARIANT varStart, VARIANT * pvarEndUpAt) { return m_pAcc->accNavigate(navDir, varStart, pvarEndUpAt); } STDMETHODIMP CAccessibleWrapper::accHitTest(long xLeft, long yTop, VARIANT * pvarChildAtPoint) { return m_pAcc->accHitTest(xLeft, yTop, pvarChildAtPoint); } STDMETHODIMP CAccessibleWrapper::accDoDefaultAction(VARIANT varChild) { return m_pAcc->accDoDefaultAction(varChild); } STDMETHODIMP CAccessibleWrapper::put_accName(VARIANT varChild, BSTR szName) { return m_pAcc->put_accName(varChild, szName); } STDMETHODIMP CAccessibleWrapper::put_accValue(VARIANT varChild, BSTR pszValue) { return m_pAcc->put_accValue(varChild, pszValue); } // IEnumVARIANT // - pass all through m_pEnumVar STDMETHODIMP CAccessibleWrapper::Next(ULONG celt, VARIANT* rgvar, ULONG * pceltFetched) { return m_pEnumVar->Next(celt, rgvar, pceltFetched); } STDMETHODIMP CAccessibleWrapper::Skip(ULONG celt) { return m_pEnumVar->Skip(celt); } STDMETHODIMP CAccessibleWrapper::Reset() { return m_pEnumVar->Reset(); } STDMETHODIMP CAccessibleWrapper::Clone(IEnumVARIANT ** ppenum) { return m_pEnumVar->Clone(ppenum); } // IOleWindow // - pass all through m_pOleWin STDMETHODIMP CAccessibleWrapper::GetWindow(HWND* phwnd) { return m_pOleWin->GetWindow(phwnd); } STDMETHODIMP CAccessibleWrapper::ContextSensitiveHelp(BOOL fEnterMode) { return m_pOleWin->ContextSensitiveHelp(fEnterMode); }
[ "mehmetyilmaz3371@gmail.com" ]
mehmetyilmaz3371@gmail.com
c8b79ec64d21deef7960047cb8ac2eeb88fc3fef
825f153b55bd9d06832be273e023eab1aa42bbdf
/learning/client_server_async/basic/server.cpp
44ea76e8f09159f66a70de3bfe0bd83384534d6b
[]
no_license
ddeka0/gemini
b1b54c28b9ea63e028ac93641772c1437098487a
7838c7ffdfb05b8c0f2cd21387de713017a3099e
refs/heads/master
2022-06-26T07:28:53.658316
2022-06-11T12:21:36
2022-06-11T12:21:36
217,849,701
0
0
null
2022-06-11T12:21:37
2019-10-27T12:11:07
C++
UTF-8
C++
false
false
13,897
cpp
/* * * Copyright 2015 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <bits/stdc++.h> #include <variant> #include <time.h> #include <sys/time.h> #include <thread> #include <chrono> #include <cmath> #include <iostream> #include <map> #include <functional> #include <future> #include <cmath> #include <thread> using namespace std; using namespace std::chrono; #include <memory> #include <iostream> #include <string> #include <thread> #include <grpcpp/grpcpp.h> #include <grpc/support/log.h> #ifdef BAZEL_BUILD #include "examples/protos/helloworld.grpc.pb.h" #else #include "helloworld.grpc.pb.h" #endif using grpc::Server; using grpc::ServerAsyncResponseWriter; using grpc::ServerBuilder; using grpc::ServerContext; using grpc::ServerCompletionQueue; using grpc::Status; using helloworld::HelloRequest; using helloworld::HelloReply; using helloworld::Greeter; /*============== Thread Pool code starts ============== */ #define THREAD_POOL_SIZE 4 std::map<thread::id,std::string> tidToTname; void delayMillis(int n) { /* used in test purpose */ struct timespec req = {0}; req.tv_sec = 0; req.tv_nsec = n * 1000000L; nanosleep(&req, (struct timespec *)NULL); } void delayNanos(int n) { /* used in test purpose */ struct timespec req = {0}; req.tv_sec = 0; req.tv_nsec = n; nanosleep(&req, (struct timespec *)NULL); } template<typename T> class threadSafeQueue { private: mutable std::mutex mut; std::queue<std::shared_ptr<T>> taskQueue; /* task as pushed here and task are processed in FIFO style */ std::condition_variable dataCond; /* used to protect the queue */ public: threadSafeQueue(){} void waitAndPop(T& value); /* wait untill task is not available in the queue */ std::shared_ptr<T> waitAndPop();/* same but returns a shared pointer */ bool tryPop(T& value); /* does not block */ std::shared_ptr<T> tryPop(); /* does not block and returns a pointer*/ void Push(T newData); bool IsEmpty() const; /* check if queue is empty or not */ void notifyAllThreads(); /* notify all the waiting threads used in Thpool decallocation */ int Size(); }; template<typename T> void threadSafeQueue<T>::notifyAllThreads() { dataCond.notify_all(); } template<typename T> void threadSafeQueue<T>::waitAndPop(T& value) { std::unique_lock<std::mutex> lk(mut); dataCond.wait(lk,[this](){return !taskQueue.empty();}); value = std::move(*taskQueue.front()); taskQueue.pop(); } template<typename T> std::shared_ptr<T> threadSafeQueue<T>::waitAndPop() { std::unique_lock<std::mutex> lk(mut); dataCond.wait(lk,[this](){return !taskQueue.empty();}); std::shared_ptr<T> res = taskQueue.front(); taskQueue.pop(); return res; } template<typename T> bool threadSafeQueue<T>::tryPop(T& value) { std::lock_guard<std::mutex> lk(mut); if(taskQueue.empty()) return false; value = std::move(*taskQueue.front()); taskQueue.pop(); return true; } template<typename T> std::shared_ptr<T> threadSafeQueue<T>::tryPop() { std::lock_guard<std::mutex> lk(mut); if(taskQueue.empty()) return std::shared_ptr<T>(); /* return nullptr */ std::shared_ptr<T> res = taskQueue.front(); taskQueue.pop(); return res; } template<typename T> void threadSafeQueue<T>::Push(T newData) { /* TODO: size check before pushing */ // std::shared_ptr<T> data(std::make_shared<T>(std::move(newData))); auto data = std::make_shared<T>(std::move(newData)); /* construct the object before lock*/ std::lock_guard<std::mutex> lk(mut); taskQueue.push(std::move(data)); dataCond.notify_one(); } template<typename T> bool threadSafeQueue<T>::IsEmpty() const { std::lock_guard<std::mutex> lk(mut); return taskQueue.empty(); } template<typename T> int threadSafeQueue<T>::Size() { std::lock_guard<std::mutex> lk(mut); return taskQueue.size(); } class threadJoiner { /* could be used to automatic thread deallocation not used for now, TODO use it in the exception case */ private: std::vector<std::thread> & threads; public: explicit threadJoiner(std::vector<std::thread>& thread_):threads(thread_){} ~threadJoiner() { for(unsigned long i = 0;i<threads.size();i++) { if(threads[i].joinable()) { threads[i].join(); } } } }; class TaskRPCB { /* Task RecvAndProcessCallbacks */ private: int len; uint fdId; int streamId; void* msgBlob; std::function<void(void*,int,uint,int)> func; public: TaskRPCB(std::function<void(void*,int,uint,int)>&f , void* msgBlob,int len, uint fdId, int streamId) { this->func = f; this->msgBlob = msgBlob; this->len = len; this->fdId = fdId; this->streamId = streamId; } void operator()() { func(msgBlob,len,fdId,streamId); } }; class TaskECB { /* Task eventCB */ private: std::function<void(void)> func; public: TaskECB(std::function<void(void)>&f) : func(f) {} void operator()() { func(); } }; class TaskTimer { /* Task timeEvent */ private: std::function<void(void)> func; public: TaskTimer(std::function<void(void)>&f) : func(f) {} void operator()() { func(); } }; class TaskProceed { private: std::function<void(void)> func; public: TaskProceed(std::function<void(void)>&f) : func(f) {} void operator()() { func(); } }; using TaskSet = std::variant<TaskECB,TaskRPCB,TaskTimer,TaskProceed>; struct executeTask { // TODO : replace this visit+lambda pattern later void operator()(TaskECB & task) { task(); } void operator()(TaskRPCB& task) { task(); } void operator()(TaskTimer& task) { task(); } void operator()(TaskProceed& task) { task(); } }; class Thpool { std::atomic_bool done; threadSafeQueue<TaskSet> workQ; std::vector<std::thread> threads; void workerThread() { while(!done) { auto task = workQ.waitAndPop(); if(task != nullptr and !done) { std::visit(executeTask(), (*task)); } } } public: Thpool(): done(false) /* ,joiner(threads) */ { unsigned const maxThreadCount = THREAD_POOL_SIZE; printf("ThreadPool Size = %u\n",maxThreadCount); try { for(unsigned int i = 0;i<maxThreadCount;i++) { threads.push_back(std::thread(&Thpool::workerThread,this)); } }catch(...) { done = true; throw; } } ~Thpool() { // done = true; } template<typename taskType> void submit(taskType task) { workQ.Push(task); } void deAllocatePool() { done = true; workQ.notifyAllThreads(); //unsigned const maxThreadCount = std::thread::hardware_concurrency(); unsigned const maxThreadCount = THREAD_POOL_SIZE; for(unsigned int i = 0;i<maxThreadCount;) { if(threads[i].joinable()) { threads[i].join(); i++; /* go for the next thread in the pool */ }else { /*did not wake up, do it again */ workQ.notifyAllThreads(); } } } int checkSize() { return workQ.Size(); } }; /*============== Thread Pool code ends ============== */ class ServerImpl final { public: ~ServerImpl() { server_->Shutdown(); // Always shutdown the completion queue after the server. cq_->Shutdown(); } // There is no shutdown handling in this code. void Run() { std::string server_address("0.0.0.0:50051"); ServerBuilder builder; // Listen on the given address without any authentication mechanism. builder.AddListeningPort(server_address, grpc::InsecureServerCredentials()); // Register "service_" as the instance through which we'll communicate with // clients. In this case it corresponds to an *asynchronous* service. builder.RegisterService(&service_); // Get hold of the completion queue used for the asynchronous communication // with the gRPC runtime. cq_ = builder.AddCompletionQueue(); // Finally assemble the server. server_ = builder.BuildAndStart(); std::cout << "Server listening on " << server_address << std::endl; // Proceed to the server's main loop. HandleRpcs(); } private: // Class encompasing the state and logic needed to serve a request. class CallData { public: // Take in the "service" instance (in this case representing an asynchronous // server) and the completion queue "cq" used for asynchronous communication // with the gRPC runtime. CallData(Greeter::AsyncService* service, ServerCompletionQueue* cq) : service_(service), cq_(cq), responder_(&ctx_), status_(CREATE) { // Invoke the serving logic right away. // std::cout <<"Constructor Called by TID = " << std::this_thread::get_id() << std::endl; Proceed(); } void Proceed() { if (status_ == CREATE) { // Make this instance progress to the PROCESS state. status_ = PROCESS; // As part of the initial CREATE state, we *request* that the system // start processing SayHello requests. In this request, "this" acts are // the tag uniquely identifying the request (so that different CallData // instances can serve different requests concurrently), in this case // the memory address of this CallData instance. service_->RequestSayHello(&ctx_, &request_, &responder_, cq_, cq_, this); // std::cout <<"RequestSayHello called by TID = " << std::this_thread::get_id() << std::endl; } else if (status_ == PROCESS) { // Spawn a new CallData instance to serve new clients while we process // the one for this CallData. The instance will deallocate itself as // part of its FINISH state. // std::cout << "new CallData Created! by TID = " << std::this_thread::get_id() <<std::endl; new CallData(service_, cq_); // The actual processing. std::string prefix("Hello "); { int x = 0; int y = 0; while(x++ <= 100000000 ) { // takes around 1 sec to complete y = y + 10; y = y - 10; } } reply_.set_message(prefix + request_.name()); // And we are done! Let the gRPC runtime know we've finished, using the // memory address of this instance as the uniquely identifying tag for // the event. status_ = FINISH; responder_.Finish(reply_, Status::OK, this); std::cout << "Replied by TID = " << std::this_thread::get_id() <<std::endl; } else { std::cout <<"deallocate done! by TID = "<< std::this_thread::get_id() << std::endl; GPR_ASSERT(status_ == FINISH); // Once in the FINISH state, deallocate ourselves (CallData). delete this; } } private: // The means of communication with the gRPC runtime for an asynchronous // server. Greeter::AsyncService* service_; // The producer-consumer queue where for asynchronous server notifications. ServerCompletionQueue* cq_; // Context for the rpc, allowing to tweak aspects of it such as the use // of compression, authentication, as well as to send metadata back to the // client. ServerContext ctx_; // What we get from the client. HelloRequest request_; // What we send back to the client. HelloReply reply_; // The means to get back to the client. ServerAsyncResponseWriter<HelloReply> responder_; // Let's implement a tiny state machine with the following states. enum CallStatus { CREATE, PROCESS, FINISH }; CallStatus status_; // The current serving state. }; // This can be run in multiple threads if needed. void HandleRpcs() { // Spawn a new CallData instance to serve new clients. auto x = new CallData(&service_, cq_.get()); Thpool pool; void* tag; // uniquely identifies a request. bool ok; int i = 0; while (true) { // Block waiting to read the next event from the completion queue. The // event is uniquely identified by its tag, which in this case is the // memory address of a CallData instance. // The return value of Next should always be checked. This return value // tells us whether there is any kind of event or cq_ is shutting down. GPR_ASSERT(cq_->Next(&tag, &ok)); GPR_ASSERT(ok); std::function<void(void)> func = std::bind(&CallData::Proceed, static_cast<CallData*>(tag)); TaskProceed task(func); pool.submit(task); std::cout <<"Proceed() done by TID = " << std::this_thread::get_id() << std::endl; i++; } } std::unique_ptr<ServerCompletionQueue> cq_; Greeter::AsyncService service_; std::unique_ptr<Server> server_; }; int main(int argc, char** argv) { ServerImpl server; server.Run(); return 0; }
[ "dekadebashish3@gmail.com" ]
dekadebashish3@gmail.com
88fe7db47170fe0ad398fa49a784b85ce8c83c6e
b8f67d61d62799db00542b7b3069da6fcdf10f85
/chrome/browser/ui/extensions/extension_action_view_controller_unittest.cc
423877d1c247717c3076a83c02b0c17dd70b1a09
[ "BSD-3-Clause" ]
permissive
fujunwei/chromium-src
535e4cc01dc2c96aac50671222a77de50d2616dc
57c7d5bbf24af7b342b330fb8775fc76c343ff69
refs/heads/webml
2022-12-30T07:55:11.938223
2018-08-28T07:07:52
2018-08-28T07:07:52
138,548,904
0
0
NOASSERTION
2019-03-22T01:51:37
2018-06-25T05:47:59
null
UTF-8
C++
false
false
14,379
cc
// Copyright 2015 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. #include "chrome/browser/ui/extensions/extension_action_view_controller.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/run_loop.h" #include "base/stl_util.h" #include "base/strings/stringprintf.h" #include "base/test/scoped_feature_list.h" #include "chrome/browser/extensions/extension_action.h" #include "chrome/browser/extensions/extension_action_manager.h" #include "chrome/browser/extensions/extension_action_runner.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/scripting_permissions_modifier.h" #include "chrome/browser/sessions/session_tab_helper.h" #include "chrome/browser/ui/extensions/icon_with_badge_image_source.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/ui/toolbar/toolbar_actions_bar.h" #include "chrome/browser/ui/toolbar/toolbar_actions_bar_unittest.h" #include "chrome/grit/chromium_strings.h" #include "chrome/grit/generated_resources.h" #include "extensions/browser/extension_system.h" #include "extensions/common/extension_builder.h" #include "extensions/common/extension_features.h" #include "extensions/common/user_script.h" #include "ui/base/l10n/l10n_util.h" // Tests the icon appearance of extension actions with the toolbar redesign. // Extensions that don't want to run should have their icons grayscaled. // Overflowed extensions that want to run should have an additional decoration. TEST_P(ToolbarActionsBarUnitTest, ExtensionActionWantsToRunAppearance) { CreateAndAddExtension("extension", extensions::ExtensionBuilder::ActionType::PAGE_ACTION); EXPECT_EQ(1u, toolbar_actions_bar()->GetIconCount()); EXPECT_EQ(0u, overflow_bar()->GetIconCount()); AddTab(browser(), GURL("chrome://newtab")); const gfx::Size size = toolbar_actions_bar()->GetViewSize(); content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); ExtensionActionViewController* action = static_cast<ExtensionActionViewController*>( toolbar_actions_bar()->GetActions()[0]); std::unique_ptr<IconWithBadgeImageSource> image_source = action->GetIconImageSourceForTesting(web_contents, size); EXPECT_TRUE(image_source->grayscale()); EXPECT_FALSE(image_source->paint_page_action_decoration()); EXPECT_FALSE(image_source->paint_blocked_actions_decoration()); SetActionWantsToRunOnTab(action->extension_action(), web_contents, true); image_source = action->GetIconImageSourceForTesting(web_contents, size); EXPECT_FALSE(image_source->grayscale()); EXPECT_FALSE(image_source->paint_page_action_decoration()); EXPECT_FALSE(image_source->paint_blocked_actions_decoration()); toolbar_model()->SetVisibleIconCount(0u); EXPECT_EQ(0u, toolbar_actions_bar()->GetIconCount()); EXPECT_EQ(1u, overflow_bar()->GetIconCount()); action = static_cast<ExtensionActionViewController*>( overflow_bar()->GetActions()[0]); image_source = action->GetIconImageSourceForTesting(web_contents, size); EXPECT_FALSE(image_source->grayscale()); EXPECT_TRUE(image_source->paint_page_action_decoration()); EXPECT_FALSE(image_source->paint_blocked_actions_decoration()); SetActionWantsToRunOnTab(action->extension_action(), web_contents, false); image_source = action->GetIconImageSourceForTesting(web_contents, size); EXPECT_TRUE(image_source->grayscale()); EXPECT_FALSE(image_source->paint_page_action_decoration()); EXPECT_FALSE(image_source->paint_blocked_actions_decoration()); } TEST_P(ToolbarActionsBarUnitTest, ExtensionActionBlockedActions) { // Blocked actions are only present with the runtime host permissions feature. base::test::ScopedFeatureList feature_list; feature_list.InitAndEnableFeature( extensions::features::kRuntimeHostPermissions); scoped_refptr<const extensions::Extension> browser_action_ext = CreateAndAddExtension( "browser action", extensions::ExtensionBuilder::ActionType::BROWSER_ACTION); ASSERT_EQ(1u, toolbar_actions_bar()->GetIconCount()); AddTab(browser(), GURL("https://www.google.com/")); ExtensionActionViewController* browser_action = static_cast<ExtensionActionViewController*>( toolbar_actions_bar()->GetActions()[0]); EXPECT_EQ(browser_action_ext.get(), browser_action->extension()); content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); ASSERT_TRUE(web_contents); const gfx::Size size = toolbar_actions_bar()->GetViewSize(); std::unique_ptr<IconWithBadgeImageSource> image_source = browser_action->GetIconImageSourceForTesting(web_contents, size); EXPECT_FALSE(image_source->grayscale()); EXPECT_FALSE(image_source->paint_page_action_decoration()); EXPECT_FALSE(image_source->paint_blocked_actions_decoration()); extensions::ExtensionActionRunner* action_runner = extensions::ExtensionActionRunner::GetForWebContents(web_contents); ASSERT_TRUE(action_runner); action_runner->RequestScriptInjectionForTesting( browser_action_ext.get(), extensions::UserScript::DOCUMENT_IDLE, base::DoNothing()); image_source = browser_action->GetIconImageSourceForTesting(web_contents, size); EXPECT_FALSE(image_source->grayscale()); EXPECT_FALSE(image_source->paint_page_action_decoration()); EXPECT_TRUE(image_source->paint_blocked_actions_decoration()); action_runner->RunBlockedActions(browser_action_ext.get()); image_source = browser_action->GetIconImageSourceForTesting(web_contents, size); EXPECT_FALSE(image_source->grayscale()); EXPECT_FALSE(image_source->paint_page_action_decoration()); EXPECT_FALSE(image_source->paint_blocked_actions_decoration()); scoped_refptr<const extensions::Extension> page_action_ext = CreateAndAddExtension( "page action", extensions::ExtensionBuilder::ActionType::PAGE_ACTION); ASSERT_EQ(2u, toolbar_actions_bar()->GetIconCount()); ExtensionActionViewController* page_action = static_cast<ExtensionActionViewController*>( toolbar_actions_bar()->GetActions()[1]); EXPECT_EQ(browser_action_ext.get(), browser_action->extension()); image_source = page_action->GetIconImageSourceForTesting(web_contents, size); EXPECT_TRUE(image_source->grayscale()); EXPECT_FALSE(image_source->paint_page_action_decoration()); EXPECT_FALSE(image_source->paint_blocked_actions_decoration()); action_runner->RequestScriptInjectionForTesting( page_action_ext.get(), extensions::UserScript::DOCUMENT_IDLE, base::DoNothing()); image_source = page_action->GetIconImageSourceForTesting(web_contents, size); EXPECT_FALSE(image_source->grayscale()); EXPECT_FALSE(image_source->paint_page_action_decoration()); EXPECT_TRUE(image_source->paint_blocked_actions_decoration()); // Overflow the page action and set the page action as wanting to run. We // shouldn't show the page action decoration because we are showing the // blocked action decoration (and should only show one at a time). toolbar_model()->SetVisibleIconCount(0u); EXPECT_EQ(0u, toolbar_actions_bar()->GetIconCount()); EXPECT_EQ(2u, overflow_bar()->GetIconCount()); ExtensionActionViewController* overflow_page_action = static_cast<ExtensionActionViewController*>( overflow_bar()->GetActions()[1]); SetActionWantsToRunOnTab(overflow_page_action->extension_action(), web_contents, true); image_source = overflow_page_action->GetIconImageSourceForTesting(web_contents, size); EXPECT_FALSE(image_source->grayscale()); EXPECT_FALSE(image_source->paint_page_action_decoration()); EXPECT_TRUE(image_source->paint_blocked_actions_decoration()); SetActionWantsToRunOnTab(overflow_page_action->extension_action(), web_contents, false); toolbar_model()->SetVisibleIconCount(2u); action_runner->RunBlockedActions(page_action_ext.get()); image_source = page_action->GetIconImageSourceForTesting(web_contents, size); EXPECT_TRUE(image_source->grayscale()); EXPECT_FALSE(image_source->paint_page_action_decoration()); EXPECT_FALSE(image_source->paint_blocked_actions_decoration()); } TEST_P(ToolbarActionsBarUnitTest, ExtensionActionContextMenu) { CreateAndAddExtension( "extension", extensions::ExtensionBuilder::ActionType::BROWSER_ACTION); EXPECT_EQ(1u, toolbar_actions_bar()->GetIconCount()); // Check that the context menu has the proper string for the action's position // (in the main toolbar, in the overflow container, or temporarily popped // out). auto check_visibility_string = [](ToolbarActionViewController* action, int expected_visibility_string) { ui::SimpleMenuModel* context_menu = static_cast<ui::SimpleMenuModel*>(action->GetContextMenu()); int visibility_index = context_menu->GetIndexOfCommandId( extensions::ExtensionContextMenuModel::TOGGLE_VISIBILITY); ASSERT_GE(visibility_index, 0); base::string16 visibility_label = context_menu->GetLabelAt(visibility_index); EXPECT_EQ(l10n_util::GetStringUTF16(expected_visibility_string), visibility_label); }; check_visibility_string(toolbar_actions_bar()->GetActions()[0], IDS_EXTENSIONS_HIDE_BUTTON_IN_MENU); toolbar_model()->SetVisibleIconCount(0u); check_visibility_string(overflow_bar()->GetActions()[0], IDS_EXTENSIONS_SHOW_BUTTON_IN_TOOLBAR); base::RunLoop run_loop; toolbar_actions_bar()->PopOutAction(toolbar_actions_bar()->GetActions()[0], false, run_loop.QuitClosure()); run_loop.Run(); check_visibility_string(toolbar_actions_bar()->GetActions()[0], IDS_EXTENSIONS_KEEP_BUTTON_IN_TOOLBAR); } // Tests the behavior for icon grayscaling with the runtime host permissions // feature enabled. TEST_P(ToolbarActionsBarUnitTest, GrayscaleIcon) { base::test::ScopedFeatureList feature_list; feature_list.InitAndEnableFeature( extensions::features::kRuntimeHostPermissions); scoped_refptr<const extensions::Extension> extension = extensions::ExtensionBuilder("extension") .SetAction(extensions::ExtensionBuilder::ActionType::BROWSER_ACTION) .SetLocation(extensions::Manifest::INTERNAL) .AddPermission("https://www.google.com/*") .Build(); extensions::ExtensionService* service = extensions::ExtensionSystem::Get(profile())->extension_service(); service->GrantPermissions(extension.get()); service->AddExtension(extension.get()); extensions::ScriptingPermissionsModifier permissions_modifier(profile(), extension); permissions_modifier.SetWithholdHostPermissions(true); ASSERT_EQ(1u, toolbar_actions_bar()->GetIconCount()); const GURL kUrl("https://www.google.com/"); AddTab(browser(), kUrl); enum class ActionState { kEnabled, kDisabled, }; enum class PageAccess { kGranted, kPending, kNone, }; enum class Opacity { kGrayscale, kFull, }; enum class BlockedActions { kPainted, kNotPainted, }; struct { ActionState action_state; PageAccess page_access; Opacity expected_opacity; BlockedActions expected_blocked_actions; } test_cases[] = { {ActionState::kEnabled, PageAccess::kNone, Opacity::kFull, BlockedActions::kNotPainted}, {ActionState::kEnabled, PageAccess::kPending, Opacity::kFull, BlockedActions::kPainted}, {ActionState::kEnabled, PageAccess::kGranted, Opacity::kFull, BlockedActions::kNotPainted}, {ActionState::kDisabled, PageAccess::kNone, Opacity::kGrayscale, BlockedActions::kNotPainted}, {ActionState::kDisabled, PageAccess::kPending, Opacity::kFull, BlockedActions::kPainted}, {ActionState::kDisabled, PageAccess::kGranted, Opacity::kFull, BlockedActions::kNotPainted}, }; auto* controller = static_cast<ExtensionActionViewController*>( toolbar_actions_bar()->GetActions()[0]); content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); ExtensionAction* extension_action = extensions::ExtensionActionManager::Get(profile())->GetExtensionAction( *extension); extensions::ExtensionActionRunner* action_runner = extensions::ExtensionActionRunner::GetForWebContents(web_contents); int tab_id = SessionTabHelper::IdForTab(web_contents).id(); const gfx::Size kSize = toolbar_actions_bar()->GetViewSize(); for (size_t i = 0; i < base::size(test_cases); ++i) { SCOPED_TRACE( base::StringPrintf("Running test case %d", static_cast<int>(i))); const auto& test_case = test_cases[i]; // Set up the proper state. extension_action->SetIsVisible( tab_id, test_case.action_state == ActionState::kEnabled); switch (test_case.page_access) { case PageAccess::kNone: // Page access should already be "none", but verify. EXPECT_EQ(extensions::PermissionsData::PageAccess::kWithheld, extension->permissions_data()->GetPageAccess( kUrl, tab_id, /*error=*/nullptr)); break; case PageAccess::kPending: action_runner->RequestScriptInjectionForTesting( extension.get(), extensions::UserScript::DOCUMENT_IDLE, base::DoNothing()); break; case PageAccess::kGranted: permissions_modifier.GrantHostPermission(kUrl); break; } std::unique_ptr<IconWithBadgeImageSource> image_source = controller->GetIconImageSourceForTesting(web_contents, kSize); EXPECT_EQ(test_case.expected_opacity == Opacity::kGrayscale, image_source->grayscale()); EXPECT_EQ(test_case.expected_blocked_actions == BlockedActions::kPainted, image_source->paint_blocked_actions_decoration()); // Clean up permissions state. if (test_case.page_access == PageAccess::kGranted) permissions_modifier.RemoveGrantedHostPermission(kUrl); action_runner->ClearInjectionsForTesting(*extension); } }
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
2276141521a77361ed38a0be9a50472e43619d34
d58f3a9e3891729578da9ea3ad64dc2b7e061c9b
/week-01/day-3/Hello-Others/main.cpp
806d94553b0e2cae7a17324ef766d2c5052c5785
[]
no_license
green-fox-academy/tothpeter1216
a116bd3df81dc3ff1201bd23aaf6e0cfc7c1e415
e10028fb1187eb2a29730cebbe35e0ef7ce35b5e
refs/heads/master
2020-06-10T22:52:06.047829
2019-09-23T07:24:09
2019-09-23T07:24:09
193,777,178
0
0
null
null
null
null
UTF-8
C++
false
false
189
cpp
#include <iostream> int main() { std::cout << "Hello, Bence!" << std::endl; std::cout << "Hello, Dani!" << std::endl; std::cout << "Hello, Gabor!" << std::endl; return 0; }
[ "tothpeter1216@gmail.com" ]
tothpeter1216@gmail.com
69b8eccb9fca8eaae917d5ea6f3e6333d14ef803
ad8499d1e1946b6efad64a1728f5fb5ce1c48eae
/Day4/printPrevSmaller.cpp
27b1494dd4841e615a89d6d41c40815ed9d67260
[]
no_license
Pal2000/CP_CipherSchools
011d1f52d55c43ad3c0e55cb285da9259636c0cc
9eb3d1d4aad592b0f0417ac18db9e0ff49df1957
refs/heads/main
2023-03-06T04:19:32.116016
2021-02-22T19:39:43
2021-02-22T19:39:43
338,570,398
0
0
null
null
null
null
UTF-8
C++
false
false
577
cpp
#include <bits/stdc++.h> using namespace std; vector<int> printPrevSmaller(int arr[], int n){ stack<int> s; vector<int> v; for(int i=0;i<n;i++){ while(!s.empty() && arr[i]<=s.top()) s.pop(); if(s.empty()) v.push_back(-1); else v.push_back(s.top()); s.push(arr[i]); } return v; } int main() { int n; cin>>n; int arr[n]; for(int i=0;i<n;i++) cin>>arr[i]; vector<int> res=printPrevSmaller(arr, n); for(auto x: res) cout<<x<<" "; return 0; }
[ "noreply@github.com" ]
noreply@github.com
44a5ef75c50d13eafe983bb5d8aa8daacd819441
d61c729c2d7ce6d3a7f72cc34c2e0b6db1651757
/drivers/soapysdr/soapyDriver.h
524cdde8e1c9df21f3a1125ca7d436697c6f62e3
[]
no_license
breynder/es-sensor
e2af2519ea46c861aa77665b41bf1cea8584492f
c6be3b3deee80749a3960ee940fa60efcfa01f5b
refs/heads/master
2020-03-31T14:42:39.605123
2018-10-09T19:36:36
2018-10-09T19:36:36
152,306,149
1
0
null
2018-10-09T19:05:12
2018-10-09T19:05:11
null
UTF-8
C++
false
false
2,520
h
/* * Copyright (C) 2018 by IMDEA Networks Institute * * This file is part of Electrosense. * * Electrosense 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. * * Electrosense 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 RTL-Spec. If not, see <http://www.gnu.org/licenses/>. * * Authors: * Roberto Calvo-Palomino <roberto.calvo@imdea.org> * */ #ifndef ES_SENSOR_RTLSDR_H #define ES_SENSOR_RTLSDR_H #include <iostream> #include <string> #include <SoapySDR/Device.hpp> #include <thread> #include <zconf.h> #include "../Driver.h" #include "../Component.h" #include "../Communication.h" #include "soapyDriver.h" #include "../../context/ElectrosenseContext.h" #include "../common/SequentialHopping.h" // Workaround issue #4 , complex.h breaks openssl's RSA library // include RSA before any mention to complex.h #include "../../types/SpectrumSegment.h" #include <complex.h> namespace electrosense { class soapyDriver: public Driver, public Component, public Communication<int, SpectrumSegment*> { public: soapyDriver(); ~soapyDriver(); // Open the device int open(std::string deviceId); // Close the device int close(); // Stop int stop(); // Running bool isRunning (); void SyncSampling(); ReaderWriterQueue<int>* getQueueIn() { return NULL; } void setQueueIn (ReaderWriterQueue<int>* QueueIn ) {}; ReaderWriterQueue<SpectrumSegment*>* getQueueOut() { return mQueueOut; }; void setQueueOut (ReaderWriterQueue<SpectrumSegment*>* QueueOut) {}; std::string getNameId () { return std::string("soapyDriver"); }; private: // Run the driver in the thread void run(); bool mRunning; int mDeviceId; SoapySDR::Device * mDevice; SoapySDR::Stream * mStream; SequentialHopping* mSeqHopping; ReaderWriterQueue<SpectrumSegment*>* mQueueOut; std::vector<std::complex<float>> m_capbuf_raw; }; } #endif //ES_SENSOR_RTLSDR_H
[ "brecht.reynders@esat.kuleuven.be" ]
brecht.reynders@esat.kuleuven.be
2601c5a183d1a44394128c5ff7480f0801ba8444
777be1b9f23abc39c56c3bc8b25c4119a7b2c6b1
/demo/ColorsEngineer.h
a6ce483a57d4c447795d69df87aee01983a20102
[]
no_license
shitianxing666/just_for_fun
284b463c0ee6362753e32f0318a4d5b1549ca056
c63059be8e87cc2b43ba498e23fbda57d1ce4239
refs/heads/master
2020-06-05T00:47:25.880848
2019-07-04T09:14:29
2019-07-04T09:14:29
192,256,286
2
0
null
null
null
null
UTF-8
C++
false
false
106
h
#pragma once #include <opencv2/opencv.hpp> class ColorsEngineer { public: void run(cv::Mat &frame); };
[ "461072496@qq.com" ]
461072496@qq.com
e95749b7c18a4e01b20246fe15d70b9391b1d26a
ef4a9e608602a5d9a9d26f7ff098e2bee719b620
/dev-c++写的代码/郝斌老师的代码/float会导致什么.cpp
052d753ea7025b5e674040e5be8fe1e1c7a9932d
[]
no_license
codeheng/freshman_code
19b0a812ba9ddabc768191951d67474fc3bfdf71
6a1fc87583a461eb751f51d68a0fc55751c67aba
refs/heads/master
2023-02-20T11:35:16.500000
2021-01-21T10:07:05
2021-01-21T10:13:23
294,962,445
0
0
null
null
null
null
GB18030
C++
false
false
305
cpp
/* 19.8.7 15点00分 当位数过多的时候会造成float的不准确!形成近似值 */ # include <stdio.h> int main(void) { float i; //i = 167416711;//瞎输的 i =0.8888888; printf("i = %f\n",i); //输出结果为167416704.000000 // 输出结果为0.888889 return 0; }
[ "1356410594@qq.com" ]
1356410594@qq.com
a33403e20c7a8f337f02921ede7e93e24dc2684e
2083dff37e6c666ca7caff6e062580f4a99f98fb
/source code/variable.h
941e1688a90e3a2db26106ad4da93d7b72f91696
[]
no_license
muhammed-kaya-2016400234/Automatic-Differentiation
0ff2f1dadfef98fb9d4ea3984282024e4dad3446
f142fee854770ea185fc42c8a5f05f83bb746133
refs/heads/master
2020-04-27T19:37:15.112443
2019-03-09T00:02:21
2019-03-09T00:02:21
174,626,478
0
0
null
null
null
null
UTF-8
C++
false
false
1,572
h
#ifndef VARIABLE_H #define VARIABLE_H #include <vector> #include <string> using namespace std; class Function; /* Node class is created in order to construct directed graph structure */ class Node{ public: // represents id of the node int id; // represents name of the node string name; // returns the incomming edges of the node virtual vector<Node *> getIncomings() = 0; // returns the outgoing edges of the node virtual vector<Node *> getOutgoings() = 0; // destructor ~Node(); }; /* Subclass of node class and represents the variables. Due to the different functionality, we have variable and function classes. */ class Variable : public Node{ public: // represents the value of the variable double value; // represents the partial derivative value of the variable // i.e. (d output/ d variable) double derivative; // represents that which function determines the variable // it will be null for inputs or constants Function *from; // represents the list of functions that takes the variable as input vector<Function *> to; Variable(); // default constructor Variable(int _id, string _name, double _value = 0); // custom constructor ~Variable(); // destructor // sets the from pointer void setFrom(Function *_from); // adds the given function to 'to' vector void addTo(Function *_to); // these functions are inherited features from node class vector<Node *> getIncomings(); vector<Node *> getOutgoings(); }; #endif // VARIABLE
[ "noreply@github.com" ]
noreply@github.com
62b9739183c2f0fb9cd9fe8825b4d8ad95e8d8f5
79f39f3063d4b143a2a59514a3552f42a7fd719c
/LinkedList.cpp
ac0b520d8d60f004fd898ea049b28c7b6043c0fa
[]
no_license
liuben10/cpp_practice
ca34b04ddd097bdf4455022e9cdbb8af4f86940b
6dd5ab1d9a84c7d95fdf5985f9caa21731f4514d
refs/heads/master
2020-03-08T13:48:58.943111
2018-05-12T22:34:19
2018-05-12T22:34:19
128,167,824
0
0
null
null
null
null
UTF-8
C++
false
false
2,215
cpp
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: LinkedList.cpp * Author: benja * * Created on April 2, 2018, 9:25 PM */ #include "LinkedList.h" #include <exception> #include <iostream> #include <sstream> #include <string.h> using namespace std; LinkedList::LinkedList() { this->head = shared_ptr<LLNode>(nullptr); } LinkedList::LinkedList(const LinkedList& orig) { shared_ptr<LLNode> iter(orig.head); while(iter != nullptr) { this->push(iter->val); iter = iter->next; } } LinkedList::~LinkedList() { } int LinkedList::pop() { if (this->head == nullptr) { throw runtime_error("Tried to pop from an empty list"); } int first = this->head->val; this->head = this->head->next; return first; } void LinkedList::push(int elem) { if (this->head == nullptr) { this->head = shared_ptr<LLNode>(new LLNode(elem)); return; } shared_ptr<LLNode> iter(this->head); while(iter->next != nullptr) { iter = iter->next; } iter->next = shared_ptr<LLNode>(new LLNode(elem)); } void LinkedList::reverse() { reverseHelper(this->head); cout << this->print(); } shared_ptr<LinkedList::LLNode> LinkedList::reverseHelper(shared_ptr<LinkedList::LLNode> ptr) { if (ptr->next == nullptr) { this->head = ptr; return ptr; } else { shared_ptr<LLNode> tmp = shared_ptr<LLNode>(ptr); shared_ptr<LLNode> reversed = reverseHelper(tmp->next); reversed->next = tmp; tmp->next = shared_ptr<LLNode>(nullptr); return tmp; } } string LinkedList::print() const { ostringstream output; if (this->head == nullptr) { output << "[]" << "\n"; return output.str(); } shared_ptr<LinkedList::LLNode> iter(this->head); while(iter != nullptr) { output << iter->val << "->"; iter = iter->next; } output << "[]" << "\n"; return output.str(); } ostream& operator<<(ostream& output, const LinkedList& ll) { output << ll.print(); return output; }
[ "benjamindliu@yahoo.com" ]
benjamindliu@yahoo.com
3c013612799e8c190c129ebf5392a0a95a80f094
5c3415f08a3a105e1fae4d9a6d73d13605e58fd4
/dds_utility.cpp
f9982bb2fc40914f0b9bff8ea67731a080b2a885
[ "MIT" ]
permissive
atharvdix/driver-drowsiness-sys
695d85f3def09f8f5e6e9639c0dc08b65842bd4c
1b8676e250bcfda6ca34acff34f17b6d7defc2ed
refs/heads/main
2023-06-21T03:09:54.054881
2021-07-22T21:00:44
2021-07-22T21:00:44
388,298,326
0
0
null
null
null
null
UTF-8
C++
false
false
1,096
cpp
#include "dds_utility.h" void calculate_ear(vector<Point>& eye, double* ear) { double A, B, C; double temp_x[6], temp_y[6]; for (int i = 0; i < 6; i++) { temp_x[i] = (double)eye[i].x; temp_y[i] = (double)eye[i].y; } A = (temp_x[5] - temp_x[1]) * (temp_x[5] - temp_x[1]); A = sqrt(A + ((temp_y[5] - temp_y[1]) * (temp_y[5] - temp_y[1]))); B = (temp_x[4] - temp_x[2]) * (temp_x[4] - temp_x[2]); B = sqrt(B + ((temp_y[4] - temp_y[2]) * (temp_y[4] - temp_y[2]))); C = (temp_x[3] - temp_x[0]) * (temp_x[3] - temp_x[0]); C = sqrt(C + ((temp_y[3] - temp_y[0]) * (temp_y[3] - temp_y[0]))); *ear = (A + B) / (2 * C); } void convert_rect_CV2DLIB(vector<Rect>& cv_rect, vector<dlib::rectangle>& dlib_rect, int pos) { Rect temp_cv; dlib::rectangle temp_dlib; temp_cv = cv_rect[pos]; temp_dlib.set_left((long)temp_cv.x); temp_dlib.set_top((long)temp_cv.y); temp_dlib.set_right((long)(temp_cv.x + temp_cv.width)); temp_dlib.set_bottom((long)(temp_cv.y + temp_cv.height)); dlib_rect.push_back(temp_dlib); }
[ "atharvdixit10@gmail.com" ]
atharvdixit10@gmail.com
29fd80670afec99b1ee0925a88b55c1350207a59
856bbf30c31bbb99a092ccbf9dd6391f144e8ce0
/qt-server/src/QuadTree/QuadTree.h
473577a91d83992ddc24a94739c0f4855e8d071f
[]
no_license
ryanbennettvoid/quad-tree-cpp
10e6457233a6cb6fb7efaf8cd13d97acb19523a2
89197961b6e93938bf2cb550ae368a9b3a1ac5ef
refs/heads/master
2020-03-14T04:38:29.700451
2018-05-04T22:57:07
2018-05-04T22:57:07
131,445,801
0
0
null
null
null
null
UTF-8
C++
false
false
741
h
#ifndef QUADTREE_H #define QUADTREE_H #include <string> #include <vector> #include "./BoundaryBox.h" #include "./Node.h" #include "../Misc/Printable.h" class QuadTree : Printable { private: static const unsigned int NODE_CAPACITY = 4; public: BoundaryBox mBoundaryBox; std::vector<Node> mNodes; QuadTree* mNorthWest; QuadTree* mNorthEast; QuadTree* mSouthWest; QuadTree* mSouthEast; // nw---ne // | | // | | // sw---se QuadTree( BoundaryBox boundaryBox ); ~QuadTree(); bool insert( Node node ); void subdivide(); // divide into 4 children std::vector<Node> queryRange( BoundaryBox boundaryBox ); // Printable std::string toString(); }; #endif
[ "ryanbennettvoid@gmail.com" ]
ryanbennettvoid@gmail.com
17faeb0544d1fda0e29c4d3a5020c78e48a87ffc
995391f7b0cb708b0e3609a260f3385f1ea49b0f
/stl/map/main.cpp
dcde5e957c4f15dfae9ba2511f94e773f9825dcc
[]
no_license
rkagrawal/Cplusplus
8ebf94ef5be043dc8fa848e7e3d0040c6e558ba7
53cd608e4defdd8784bb73d146d710ad17c21204
refs/heads/master
2023-04-09T13:59:42.483011
2023-03-28T01:06:57
2023-03-28T01:06:57
71,018,008
0
0
null
null
null
null
UTF-8
C++
false
false
1,993
cpp
#include <iostream> #include <map> #include <memory> #include <tuple> #include <utility> #include "emp.h" using namespace std; int main(int argc, char* argv[] ) { map<string, unique_ptr<emp> > empMap; unique_ptr<emp> up1 = make_unique<emp>( "Agrawal", "Rajesh", 52 ); unique_ptr<emp> up2 = make_unique<emp>( emp("Agrawal", "Suresh", 50 ) ); up1->print(cout); up2->print(cout); using mapiter = map<string, unique_ptr<emp>>::iterator; using mappair = pair<string, unique_ptr<emp>>; // map emplace takes a pair // move ctors are called.. pair<mapiter, bool> p = empMap.emplace( make_pair( "Dinesh", make_unique<emp>( "Agrawal", "Dinesh", 46 ))); p = empMap.emplace( make_pair( "Rajesh", make_unique<emp>( "Agrawal", "Rajesh", 52 ))); p = empMap.emplace( make_pair( "Suresh", make_unique<emp>( "Agrawal", "Suresh", 50 ))); // emplace in map can also take the variadic args like below // for it does not work as there is some problem with my understanding... // // piece wise construct cannot make shared ptr.. it can forward the tuple as args to the constructs. // Hence the below does not work /* pair<mapiter, bool> p = empMap.emplace( piecewise_construct, forward_as_tuple( "Dinesh" ), forward_as_tuple( "Agrawal", "Dinesh", 46 )); */ cout << "Printing Map\n"; for( auto& p : empMap ) p.second->print(cout); auto iter = empMap.find( "Rajesh" ) ; iter = empMap.erase( iter ); cout << "\nPrinting after removing Rajesh\n"; for( auto& p : empMap ) p.second->print(cout); empMap.insert( iter, make_pair( "Rajesh", make_unique<emp>( "Agrawal", "Mahesh", 48 ) ) ); cout << "\nPrinting after inserting Mahesh\n"; for( auto& p : empMap ) p.second->print(cout); }
[ "rkagrawal@gmail.com" ]
rkagrawal@gmail.com
2f47e2fce6a27bb6e182294e2d4e992e9661a353
54515418f497a5a61eed525d0d3e7953d52b39ff
/t2/src/Body.cpp
6e2d55b61dc042adc08980dadad3a55370d2d1b6
[]
no_license
jviriato/cg-elc1015
5834259b5502e19582a952ee2195f45f596a572b
490317a4f3e9521ac8eb2b3e83ec7f7a86ad8e9a
refs/heads/master
2020-04-28T16:45:58.252299
2019-09-13T02:54:06
2019-09-13T02:54:06
175,423,101
0
0
null
null
null
null
UTF-8
C++
false
false
385
cpp
#include "Body.h" Body::Body(double head_x, double head_y) { this->head_x = head_x; this->head_y = head_y; } void Body::render() { color(0, 0, 0); line(head_x, head_y, head_x - 5, head_y - 80); color(1, 0, 0); circleFill(head_x - 5, head_y - 80, 2, 5); color(0,0,0); line(head_x, head_y - 40, head_x + 60, head_y - 50); } Body::~Body() { }
[ "josevviriato@gmail.com" ]
josevviriato@gmail.com
c6cb1fc8b71cd7fab3cf403af1fa9250c390d93d
4d402199704e2c213d1074e79163106613d8db7c
/Assignment 7/CANDIDATE_HEADER.h
1e37e82328784084dfb3490ddaf1705a410dc490
[]
no_license
Kshumishyn/Cpp
9839c7de5f9cbc04a2115e6a99cce05e03858cbe
239cab8329b80a310c3c2be4efecb2576539231c
refs/heads/master
2021-09-05T06:36:35.790206
2018-01-24T21:41:20
2018-01-24T21:41:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,805
h
/**************************************************************************** * AUTHORS : KOSTYANTYN SHUMISHYN * STUDENT IDs : W7216875 * ASSIGNMENT #7 : MILITARY ACADEMY (OOP) * CLASS : CS 150 * DUE DATE : 5/03/2017 ***************************************************************************/ // This file is called GUEST_HEADER.h #ifndef CANDIDATE_HEADER_H_ #define CANDIDATE_HEADER_H_ // Preprocessor directives go here #include <string> using namespace std; class Candidate { public: Candidate (); // Default Constructor ~Candidate(); // Destructor Candidate ( string name, // Full Constructor int age, char gender, float height, int weight); Candidate ( string name, // Partial Constructor char gender); Candidate ( int age, // Partial Constructor float height, int weight); /** MUTATORS **/ void SetName (string candidName); // Set Candidate's name void SetAge (int candidAge); // Set Candidate's age (year) void SetGender(char candidGender); // Set Candidate's hender(f/m) void SetHeight(float candidHeight); // Set Candidate's height(in.) void SetWeight(int candidHeight); // Set Candidate's weight(lbs) void SetAll (string name, // Sets all of the above attributes int age, char gender, float height, int weight); void SetAll (string name, // Overloads SetAll char gender); void SetAll (int age, // Overloads SetAll float height, int weight); /** ACCESSORS **/ string GetName ()const; // Gets the Candidate's name int GetAge ()const; // Gets the Candidate's age (years) char GetGender()const; // Gets the Candidate's gender (f/m) float GetHeight()const; // Gets the Candidate's height (inches) int GetWeight()const; // Gets the Candidate's weight (lbs) private: string name; // IN/OUT - Candidate's Name int age; // IN/OUT - Candidate's Age (years) char gender; // IN/OUT - Candidate's Gender (f/m) float height; // IN/OUT - Candidate's Height (inches) int weight; // IN/OUT - Candidate's Weight (lbs) }; /**************************************************************************** * Candidate Class * This class represents a Candidate object. It manages 5 attributes, * name, age, gender, height and weight ***************************************************************************/ /****************************** ** CONSTRUCTORS & DESTRUCTOR** ******************************/ /**************************************************************************** * Candidate (); * Constructor: Initialized class attributes to default value * Parameters: none * Return: none ***************************************************************************/ /**************************************************************************** * ~Candidate (); * Destructor: Does not perform any specifc function * Parameters: none * Return: none ***************************************************************************/ /**************************************************************************** * Candidate (string name, int age, char gender, int height and int weight); * Destructor: Initializes all parameters to that of passed arguments * Parameters: name(string) // IN - Candidate name for new attribute age (integer) // IN - Candidate age for new attribute gender(character) // IN - Candidate gender for new attribute height(integer) // IN - Candidate height for new attribute weight(integer) // IN - Candidate weight for new attribute * Return: none ***************************************************************************/ /************** ** MUTATORS ** **************/ /**************************************************************************** * void SetName (string name); * * Mutator: This method will update the name attribute to the parameter * name value *--------------------------------------------------------------------------- * Parameters: name(string) // IN - Candidate name for a new attribute *--------------------------------------------------------------------------- * return: none ***************************************************************************/ /**************************************************************************** * void SetAge (int age); * * Mutator: This method will update the age attribute to the parameter * age's value *--------------------------------------------------------------------------- * Parameters: age (integer) // IN - Candidate age for a new attribute *--------------------------------------------------------------------------- * return: none ***************************************************************************/ /**************************************************************************** * void SetGender (char gender); * * Mutator: This method will update the gender attribute to the parameter * gender's character value *--------------------------------------------------------------------------- * Parameters: gender (character) // IN - Candidate's gender for a new * attribute *--------------------------------------------------------------------------- * return: none ***************************************************************************/ /**************************************************************************** * void SetHeight (int height); * * Mutator: This method will update the height attribute to the parameter * height's integer value *--------------------------------------------------------------------------- * Parameters: height (integer) // IN - Candidate's height for a new * attribute *--------------------------------------------------------------------------- * return: none ***************************************************************************/ /**************************************************************************** * void SetWeight (int weight); * * Mutator: This method will update the weight attribute to the parameter * weight's integer value *--------------------------------------------------------------------------- * Parameters: weight (integer) // IN - Candidate's weight for a new * attribute *--------------------------------------------------------------------------- * return: none ***************************************************************************/ /**************************************************************************** * void SetAll (string name, int age, char gender, int height & int weight); * * Mutator: This method will update all the attributes of the guest class to * the parameters' values. *--------------------------------------------------------------------------- * Parameters: name (string) // IN - Candidate's name for new attribute * age (integer) // IN - Candidate's age for new attribute * gender (character) // IN - Candidate gender for new attribute * height (integer) // IN - Candidate height for new attribute * weight (integer) // IN - Candidate weight for new attribute *--------------------------------------------------------------------------- * return: none ***************************************************************************/ /************** ** ACCESSORS ** **************/ /**************************************************************************** * string GetName ()const; * * Accessor: This method will return the name attribute *--------------------------------------------------------------------------- * Parameters: none *--------------------------------------------------------------------------- * return: name(string) ***************************************************************************/ /**************************************************************************** * int GetAge ()const; * * Accessor: This method will return the age attribute *--------------------------------------------------------------------------- * Parameters: none *--------------------------------------------------------------------------- * return: age(integer) ***************************************************************************/ /**************************************************************************** * char GetGender ()const; * * Accessor: This method will return the gender attribute *--------------------------------------------------------------------------- * Parameters: none *--------------------------------------------------------------------------- * return: gender(character) ***************************************************************************/ /**************************************************************************** * bool GetHeight ()const; * * Accessor: This method will return the height attribute *--------------------------------------------------------------------------- * Parameters: none *--------------------------------------------------------------------------- * return: height(integer) ***************************************************************************/ /**************************************************************************** * bool GetWeight ()const; * * Accessor: This method will return the weight attribute *--------------------------------------------------------------------------- * Parameters: none *--------------------------------------------------------------------------- * return: weight(integer) ***************************************************************************/ #endif /* CANDIDATE_HEADER_H_ */ // To include this file // #include "CANDIDATE_HEADER.h"
[ "Kshumishyn@gmail.com" ]
Kshumishyn@gmail.com
f33c9d20485825169f875e8ff02cb32649a0d10e
12ffa18e630162cfe0d7393e6436e84c2bec251e
/Main.cpp
459b652c7fe0156d6852c84fef54ed0d3fb6b8d1
[]
no_license
zachreitz878/MiningAdventure
07faebd4a8b99df4fa2c88c5b4698405a95bcd8c
80cbcc705e5fcde8ce084987b45b2a89c6b4aa29
refs/heads/master
2021-01-25T09:09:13.995844
2017-06-08T20:04:37
2017-06-08T20:04:37
93,786,866
0
0
null
null
null
null
UTF-8
C++
false
false
1,616
cpp
//Main file for game //keeps track of which state the game is in #include "Main.h" //Game States #define MAIN_MENU 0 #define LOAD_MENU 1 #define LOAD_GAME 2 #define GAME_LOOP 3 #define PAUSE_MENU 4 using namespace AGK; app App; World* World1; Menu* Menu1; int game_state = MAIN_MENU; //when game first loads void app::Begin ( void ) { Menu1 = new Menu(); World1 = new World(); } //Main Loop for screen update void app::Loop ( void ) { //Switch game_statement controls the flow of the game based on game_state variable switch(game_state) { //***************************MAIN_MENU_STATE****************************// case MAIN_MENU: Menu1->MainMenuUpdate(); if(Menu1->goToLoadGame) game_state = LOAD_MENU; if(Menu1->loading) game_state = LOAD_GAME; break; //***************************LOAD_MENU_STATE*****************************// case LOAD_MENU: Menu1->LoadMenuUpdate(); if (Menu1->loading) game_state = LOAD_GAME; if (Menu1->backToMain) game_state = MAIN_MENU; break; //****************************LOAD_GAME_STATE******************************// case LOAD_GAME: World1->LoadWorld(Menu1->SaveGame()); //initialize world game_state = GAME_LOOP; break; //****************************GAME_PLAY_LOOP*******************************// case GAME_LOOP: World1->Update(); //if(agk::GetRawKeyPressed(27)) //game_state = PAUSE_MENU; break; //****************************PAUSE_MENU_STATE*****************************// //case PAUSE_MENU: //break; }//END SWITCH agk::Sync ( ); //agk sync function } void app::End ( void ) { }
[ "zachreitz878@mail.fresnostate.edu" ]
zachreitz878@mail.fresnostate.edu
bdf4e72e90132b5381664eb4f82a2ab3b011dc8d
73e89812a3e4f979641c7d8765b46ed0226e3dd9
/Urasandesu.Swathe/Urasandesu/Swathe/Profiling/BaseClassPersistedHandler/BaseAppDomainProfilerPersistedHandlerFwd.h
50dcbe2734afeedc14132c4f08b9be6cfec9f011
[]
no_license
urasandesu/Swathe
c601244e7339c2d6fe5686a0ee2ca44732007d89
e086ede891a64d991f1f738b00eb158b44537d06
refs/heads/master
2021-01-19T00:52:31.845284
2017-03-17T11:32:51
2017-03-17T11:32:51
6,515,991
3
1
null
null
null
null
UTF-8
C++
false
false
2,410
h
/* * File: BaseAppDomainProfilerPersistedHandlerFwd.h * * Author: Akira Sugiura (urasandesu@gmail.com) * * * Copyright (c) 2014 Akira Sugiura * * This software is MIT License. * * 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. */ #pragma once #ifndef URASANDESU_SWATHE_PROFILING_BASECLASSPERSISTEDHANDLER_BASEAPPDOMAINPROFILERPERSISTEDHANDLERFWD_H #define URASANDESU_SWATHE_PROFILING_BASECLASSPERSISTEDHANDLER_BASEAPPDOMAINPROFILERPERSISTEDHANDLERFWD_H #ifndef URASANDESU_SWATHE_AUTOGEN_PROFILING_DEFAULTCLASSPERSISTEDHANDLERAPIHOLDER_DEFAULTAPPDOMAINPROFILERPERSISTEDHANDLERAPIHOLDERFWD_H #include <Urasandesu/Swathe/AutoGen/Profiling/DefaultClassPersistedHandlerApiHolder/DefaultAppDomainProfilerPersistedHandlerApiHolderFwd.h> #endif namespace Urasandesu { namespace Swathe { namespace Profiling { namespace BaseClassPersistedHandler { template< class ApiHolder = Urasandesu::Swathe::AutoGen::Profiling::DefaultClassPersistedHandlerApiHolder::DefaultAppDomainProfilerPersistedHandlerApiHolder > class BaseAppDomainProfilerPersistedHandler; }}}} // namespace Urasandesu { namespace Swathe { namespace Profiling { namespace BaseClassPersistedHandler { #endif // URASANDESU_SWATHE_PROFILING_BASECLASSPERSISTEDHANDLER_BASEAPPDOMAINPROFILERPERSISTEDHANDLERFWD_H
[ "urasandesu@gmail.com" ]
urasandesu@gmail.com
38b475de99639e5a5a3872ec5e8f4d6a7ef28520
2549401a7cfb7bdbda59855196f9946c7518c7b3
/interpreter/level3/ast.cc
af99b027ac36a1a05dd8a83654dae4c92dfa1d84
[]
no_license
Prithvirajbilla/compilers
cf45112f8b586bd6ed4ebaa92177c893e638edb5
ef3d226b30174ef5aef533dad4a04338af4c2e4f
refs/heads/master
2020-03-30T07:06:02.029226
2014-04-07T13:07:56
2014-04-07T13:07:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
17,313
cc
/********************************************************************************************* cfglp : A CFG Language Processor -------------------------------- About: Implemented by Tanu Kanvar (tanu@cse.iitb.ac.in) and Uday Khedker (http://www.cse.iitb.ac.in/~uday) for the courses cs302+cs306: Language Processors (theory and lab) at IIT Bombay. Release date Jan 15, 2013. Copyrights reserved by Uday Khedker. This implemenation has been made available purely for academic purposes without any warranty of any kind. Documentation (functionality, manual, and design) and related tools are available at http://www.cse.iitb.ac.in/~uday/cfglp ***********************************************************************************************/ #include<iostream> #include<fstream> #include <iomanip> using namespace std; #include"user-options.hh" #include"error-display.hh" #include"local-environment.hh" #include"symbol-table.hh" #include"ast.hh" #include"basic-block.hh" #include"procedure.hh" #include"program.hh" Ast::Ast() {} Ast::~Ast() {} bool Ast::check_ast(int line) { report_internal_error("Should not reach, Ast : check_ast"); } Data_Type Ast::get_data_type() { report_internal_error("Should not reach, Ast : get_data_type"); } void Ast::print_value(Local_Environment & eval_env, ostream & file_buffer) { report_internal_error("Should not reach, Ast : print_value"); } Eval_Result & Ast::get_value_of_evaluation(Local_Environment & eval_env) { report_internal_error("Should not reach, Ast : get_value_of_evaluation"); } void Ast::set_value_of_evaluation(Local_Environment & eval_env, Eval_Result & result) { report_internal_error("Should not reach, Ast : set_value_of_evaluation"); } void Ast::set_data_type(Data_Type value) { report_internal_error("Should not reach, Ast : set_data_type"); } //////////////////////////////////////////////////////////////// Assignment_Ast::Assignment_Ast(Ast * temp_lhs, Ast * temp_rhs) { lhs = temp_lhs; rhs = temp_rhs; } Assignment_Ast::~Assignment_Ast() { delete lhs; delete rhs; } Data_Type Assignment_Ast::get_data_type() { return node_data_type; } bool Assignment_Ast::check_ast(int line) { if (lhs->get_data_type() == rhs->get_data_type()) { node_data_type = lhs->get_data_type(); return true; } report_error("Assignment statement data type not compatible", line); } void Assignment_Ast::set_data_type(Data_Type value) { node_data_type=value; } void Assignment_Ast::print_ast(ostream & file_buffer) { file_buffer <<"\n"<< AST_SPACE << "Asgn:\n"; file_buffer << AST_NODE_SPACE"LHS ("; lhs->print_ast(file_buffer); file_buffer << ")\n"; file_buffer << AST_NODE_SPACE << "RHS ("; rhs->print_ast(file_buffer); file_buffer << ")\n"; } Eval_Result & Assignment_Ast::evaluate(Local_Environment & eval_env, ostream & file_buffer) { Eval_Result & result = rhs->evaluate(eval_env, file_buffer); if (result.is_variable_defined() == false) report_error("Variable should be defined to be on rhs", NOLINE); lhs->set_value_of_evaluation(eval_env, result); // Print the result print_ast(file_buffer); lhs->print_value(eval_env, file_buffer); return result; } ///////////////////////////////////////////////////////////////// Name_Ast::Name_Ast(string & name, Symbol_Table_Entry & var_entry) { variable_name = name; variable_symbol_entry = var_entry; } Name_Ast::~Name_Ast() {} Data_Type Name_Ast::get_data_type() { return variable_symbol_entry.get_data_type(); } void Name_Ast::print_ast(ostream & file_buffer) { file_buffer << "Name : " << variable_name; } void Name_Ast::set_data_type(Data_Type value) { node_data_type=value; } void Name_Ast::print_value(Local_Environment & eval_env, ostream & file_buffer) { Eval_Result_Value * loc_var_val = eval_env.get_variable_value(variable_name); Eval_Result_Value * glob_var_val = interpreter_global_table.get_variable_value(variable_name); file_buffer << "\n" << AST_SPACE << variable_name << " : "; if (!eval_env.is_variable_defined(variable_name) && !interpreter_global_table.is_variable_defined(variable_name)) file_buffer << "undefined"; else if (eval_env.is_variable_defined(variable_name) && loc_var_val != NULL) { if (loc_var_val->get_result_enum() == int_result) file_buffer << (int)loc_var_val->get_value() << "\n"; else if(loc_var_val->get_result_enum() == float_result) { file_buffer<< setiosflags(ios::fixed) << setprecision(2)<<loc_var_val->get_value() << "\n"; } else report_internal_error("Result type can only be int and float"); } else { if (glob_var_val->get_result_enum() == int_result) { if (glob_var_val == NULL) file_buffer << "0\n"; else file_buffer << (int)glob_var_val->get_value() << "\n"; } else if(glob_var_val->get_result_enum() == float_result) { if(glob_var_val == NULL) file_buffer << "0\n"; else file_buffer<< setiosflags(ios::fixed) << setprecision(2)<< glob_var_val->get_value() << "\n"; } else report_internal_error("Result type can only be int and float"); } file_buffer << "\n"; } Eval_Result & Name_Ast::get_value_of_evaluation(Local_Environment & eval_env) { if (eval_env.does_variable_exist(variable_name)) { Eval_Result * result = eval_env.get_variable_value(variable_name); return *result; } Eval_Result * result = interpreter_global_table.get_variable_value(variable_name); return *result; } void Name_Ast::set_value_of_evaluation(Local_Environment & eval_env, Eval_Result & result) { Eval_Result_Value * i; if (result.get_result_enum() == int_result) { i = new Eval_Result_Value_Int(); i->set_value(result.get_value()); } else if(result.get_result_enum() == float_result) { i = new Eval_Result_Value_Float(); i->set_value(result.get_value()); } if (eval_env.does_variable_exist(variable_name)) eval_env.put_variable_value(*i, variable_name); else interpreter_global_table.put_variable_value(*i, variable_name); } Eval_Result & Name_Ast::evaluate(Local_Environment & eval_env, ostream & file_buffer) { return get_value_of_evaluation(eval_env); } /////////////////////////////////////////////////////////////////////////////// template <class DATA_TYPE> Number_Ast<DATA_TYPE>::Number_Ast(DATA_TYPE number, Data_Type constant_data_type) { constant = number; node_data_type = constant_data_type; } template <class DATA_TYPE> Number_Ast<DATA_TYPE>::~Number_Ast() {} template <class DATA_TYPE> Data_Type Number_Ast<DATA_TYPE>::get_data_type() { return node_data_type; } template <class DATA_TYPE> void Number_Ast<DATA_TYPE>::set_data_type(Data_Type value) { node_data_type=value; } template <class DATA_TYPE> void Number_Ast<DATA_TYPE>::print_ast(ostream & file_buffer) { if(node_data_type == float_data_type) file_buffer << "Num : "<< setiosflags(ios::fixed) << setprecision(2)<< constant; else if(node_data_type == int_data_type) file_buffer << "Num : "<< (int)constant; } template <class DATA_TYPE> Eval_Result & Number_Ast<DATA_TYPE>::evaluate(Local_Environment & eval_env, ostream & file_buffer) { if (node_data_type == int_data_type) { Eval_Result & result = *new Eval_Result_Value_Int(); result.set_value(constant); return result; } else if(node_data_type == float_data_type) { Eval_Result & result = *new Eval_Result_Value_Float(); result.set_value(constant); return result; } } /////////////////////////////////////////////////////////////////////////////// Return_Ast::Return_Ast() { is_return = false; } Return_Ast::Return_Ast(Ast * l) { return_value = l; is_return = true; } Return_Ast::~Return_Ast() {} void Return_Ast::print_ast(ostream & file_buffer) { if(!is_return) file_buffer<<"\n\n"<< AST_SPACE << "RETURN <NOTHING>\n"; else { file_buffer<<"\n\n"<< AST_SPACE << "RETURN "; return_value->print_ast(file_buffer); file_buffer<<"\n\n"; } } void Return_Ast::set_data_type(Data_Type value) { node_data_type=value; } Eval_Result & Return_Ast::evaluate(Local_Environment & eval_env, ostream & file_buffer) { if(!is_return) { Eval_Result & result = *new Eval_Result_Value_Float(); print_ast(file_buffer); result.set_result_enum(void_result); return result; } else { Eval_Result & rr = return_value->evaluate(eval_env, file_buffer); Eval_Result & result = *new Eval_Result_Value_Float(); result.set_value(rr.get_value()); print_ast(file_buffer); result.set_result_enum(return_result); return result; } } template class Number_Ast<int>; template class Number_Ast<float>; //////////////////////////////////////////////////////////////// //int block_num; Goto_Ast::Goto_Ast(int a) { block_num = a; } void Goto_Ast::print_ast(ostream & file_buffer) { file_buffer << AST_SPACE << "Goto statement:\n"; file_buffer << AST_NODE_SPACE"Successor: "; file_buffer << block_num << "\n"; } int Goto_Ast::blocknum() { return block_num; } void Goto_Ast::set_data_type(Data_Type value) { node_data_type=value; } Eval_Result & Goto_Ast::evaluate(Local_Environment & eval_env, ostream & file_buffer) { Eval_Result & result = * new Eval_Result_Value_Int(); print_ast(file_buffer); file_buffer << AST_SPACE << "GOTO (BB "<<this->block_num<<")\n"; result.set_value(this->block_num); result.set_result_enum(block_result); return result; } ///////////////////////////////////////////////////////////////// Relational_Ast::Relational_Ast(Ast * temp_lhs, Ast * temp_rhs, rop oper) { lhs = temp_lhs; rhs = temp_rhs; rel_oper = oper; } Relational_Ast::~Relational_Ast() { delete lhs; delete rhs; } Data_Type Relational_Ast::get_data_type() { return node_data_type; } void Relational_Ast::set_data_type(Data_Type value) { node_data_type=value; } bool Relational_Ast::check_ast(int line) { if (lhs->get_data_type() == rhs->get_data_type()) { node_data_type = lhs->get_data_type(); return true; } else if(lhs->get_data_type() == float_data_type || rhs->get_data_type() == float_data_type) { node_data_type = float_data_type; return true; } report_error("Relational Expression lhs and rhs data types doesn't match", line); } void Relational_Ast::print_ast(ostream & file_buffer) { //LE, LT, GT, GE, NE, EE switch(rel_oper) { case 0: { file_buffer << "\n" << AST_SPACE << "Condition: "; file_buffer << "LE\n"; break; } case 1: { file_buffer << "\n" << AST_SPACE << "Condition: "; file_buffer << "LT\n"; break; } case 2: { file_buffer << "\n" << AST_SPACE << "Condition: "; file_buffer << "GT\n"; break; } case 3: { file_buffer << "\n" << AST_SPACE << "Condition: "; file_buffer << "GE\n"; break; } case 4: { file_buffer << "\n" << AST_SPACE << "Condition: "; file_buffer << "NE\n"; break; } case 5: { file_buffer << "\n" << AST_SPACE << "Condition: "; file_buffer << "EQ\n"; break; } case 6: { file_buffer << "\n" << AST_SPACE << "Arith: "; file_buffer<<"PLUS\n"; break; } case 7: { file_buffer << "\n" << AST_SPACE << "Arith: "; file_buffer<<"MINUS\n"; break; } case 8: { file_buffer << "\n" << AST_SPACE << "Arith: "; file_buffer<<"MULT\n"; break; } case 9: { file_buffer << "\n" << AST_SPACE << "Arith: "; file_buffer<<"DIV\n"; break; } case 10: { file_buffer << "\n" << AST_SPACE << "Arith: "; file_buffer<<"UMINUS\n"; file_buffer << "\n" << AST_NODE_SPACE << " LHS ("; rhs->print_ast(file_buffer); file_buffer << ")"; return ; } } file_buffer << "\n" << AST_NODE_SPACE << " LHS ("; lhs->print_ast(file_buffer); file_buffer << ")"; file_buffer << "\n" << AST_NODE_SPACE << " RHS ("; rhs->print_ast(file_buffer); file_buffer << ")"; } Eval_Result & Relational_Ast::evaluate(Local_Environment & eval_env, ostream & file_buffer) { float lhs_int = lhs->evaluate(eval_env,file_buffer).get_value(); float rhs_int = rhs->evaluate(eval_env,file_buffer).get_value(); float answer; switch(rel_oper) { case 0: { answer = (lhs_int <= rhs_int); break; } case 1: { answer = (lhs_int < rhs_int); break; } case 2: { answer = (lhs_int > rhs_int); break; } case 3: { answer = (lhs_int >= rhs_int); break; } case 4: { answer = (lhs_int != rhs_int); break; } case 5: { answer = (lhs_int == rhs_int); break; } case 6: { answer = (lhs_int + rhs_int); break; } case 7: { answer = (lhs_int - rhs_int); break; } case 8: { answer = (lhs_int * rhs_int); break; } case 9: { answer = (lhs_int/rhs_int); break; } case 10: { answer = -1*(lhs_int); break; } } if(node_data_type == float_data_type) { Eval_Result & result = * new Eval_Result_Value_Float(); result.set_value(answer); return result; } else if (node_data_type == int_data_type) { int k = (int) answer; Eval_Result & result = * new Eval_Result_Value_Int(); result.set_value(k); return result; } else { file_buffer<<" "<<node_data_type<<endl; Eval_Result & result = * new Eval_Result_Value_Float(); result.set_value(answer); return result; } } // ///////////////////////////////////////////////////////////////// // Goto_Ast * lhs; // Goto_Ast * rhs; // Relational_Ast * cond; IfCondition_Ast::IfCondition_Ast(Goto_Ast * temp_lhs, Goto_Ast * temp_rhs, Ast * relcond) { lhs = temp_lhs; rhs = temp_rhs; cond = relcond; } IfCondition_Ast::~IfCondition_Ast() { delete lhs; delete rhs; } void IfCondition_Ast::set_data_type(Data_Type value) { node_data_type=value; } Data_Type IfCondition_Ast::get_data_type() { return cond->get_data_type(); } bool IfCondition_Ast::check_ast(int line) { if (lhs->get_data_type() == rhs->get_data_type()) { node_data_type = lhs->get_data_type(); return true; } report_error("Conditional statement data type not compatible", line); } void IfCondition_Ast::print_ast(ostream & file_buffer) { file_buffer << AST_SPACE << "If_Else statement:"; cond->print_ast(file_buffer); file_buffer << "\n" << AST_NODE_SPACE <<"True Successor: "; file_buffer << lhs->blocknum()<<"\n"; file_buffer << AST_NODE_SPACE <<"False Successor: "; file_buffer << rhs->blocknum()<<"\n"; } Eval_Result & IfCondition_Ast::evaluate(Local_Environment & eval_env, ostream & file_buffer) { print_ast(file_buffer); Eval_Result& result = *new Eval_Result_Value_Int(); int condition = cond->evaluate(eval_env,file_buffer).get_value(); if(condition) { int bnum = lhs->blocknum(); file_buffer<<"\n"<<AST_SPACE<<"Condition True : "; file_buffer <<"Goto (BB "<<bnum<<")\n"; result.set_value(bnum); result.set_result_enum(block_result); } else { int bnum = rhs->blocknum(); file_buffer<<"\n"<<AST_SPACE<<"Condition False : "; file_buffer <<"Goto (BB "<<bnum<<")\n"; result.set_value(bnum); result.set_result_enum(block_result); } return result; } /////////////////////////////////////////// Typecast_Ast::Typecast_Ast(Ast * temp_lhs,Data_Type data_type) { typecast = temp_lhs; prev = node_data_type; node_data_type = data_type; } Typecast_Ast::~Typecast_Ast() { } bool Typecast_Ast::check_ast(int line) { return true; } void Typecast_Ast::set_data_type(Data_Type d) { node_data_type = d; } Data_Type Typecast_Ast::get_data_type() { return node_data_type; } void Typecast_Ast::print_ast(ostream & file_buffer) { typecast->print_ast(file_buffer); } Eval_Result & Typecast_Ast::evaluate(Local_Environment & eval_env, ostream & file_buffer) { float answer = typecast->evaluate(eval_env, file_buffer).get_value(); if(node_data_type == int_data_type) { int k = answer; Eval_Result & result = *new Eval_Result_Value_Int(); result.set_value(k); return result; } else if(node_data_type == float_data_type) { Eval_Result & result = *new Eval_Result_Value_Float(); result.set_value(answer); return result; } } ///////////////////////////////////////////// Procedurecall_Ast::Procedurecall_Ast(string& n,list<Ast *> & args) { name = n; arguments = args; } Procedurecall_Ast::~Procedurecall_Ast() { } bool Procedurecall_Ast::check_ast(int line) { return true; } void Procedurecall_Ast::set_data_type(Data_Type d) { node_data_type = d; } Data_Type Procedurecall_Ast::get_data_type() { return node_data_type; } void Procedurecall_Ast::print_ast(ostream & file_buffer) { Procedure * p; p = program_object.get_procedure(name); if (arguments.size() == 0) file_buffer<<"\n"<<AST_SPACE<<"FN CALL: "<<name<<"()"; else { file_buffer<<"\n"<<AST_SPACE<<"FN CALL: "<<name<<"("; list<Ast *> :: iterator it; for(it = arguments.begin();it!=arguments.end();it++) { file_buffer<<"\n"<<AST_NODE_SPACE; (*it)->print_ast(file_buffer); } file_buffer<<")"; } } Eval_Result & Procedurecall_Ast::evaluate(Local_Environment & eval_env, ostream & file_buffer) { Procedure * prod = program_object.get_procedure(name); list<Eval_Result * > eval_result; list<Ast *> :: iterator it; for(it = arguments.begin(); it != arguments.end();it++) { eval_result.push_back(&((*it)->evaluate(eval_env,file_buffer))); } return prod->evaluate(eval_result,file_buffer); } /////////////////////////////////////////////
[ "prithviraj.m.billa@gmail.com" ]
prithviraj.m.billa@gmail.com
5434e4287e456a2e1a4d86a517bd94a903526dfb
79e897a9e762282bc5a9795dc8378355dc827f1a
/Module-cpp-06/ex01/srcs/main.cpp
8e3ce8389ca313e328c2c2fbe1c7e30c49ff1d1b
[]
no_license
sphaxou/CPP-42
37a807c8c3799b93da681bec732ba0b6eab6777d
dee5653046d890737ffec93651696fb326a970aa
refs/heads/master
2023-01-13T19:40:32.988592
2020-11-19T16:28:17
2020-11-19T16:28:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,206
cpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: rchallie <rchallie@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/03/29 16:38:15 by rchallie #+# #+# */ /* Updated: 2020/10/16 23:23:59 by rchallie ### ########.fr */ /* */ /* ************************************************************************** */ # include "../incs/incs.hpp" int main() { void* raw = serialize(); Data* data = deserialize(raw); std::cout << "S1 = " << data->s1 << std::endl; std::cout << "N = " << data->n << std::endl; std::cout << "S2 = " << data->s2 << std::endl; delete reinterpret_cast<Data *>(raw); delete data; }
[ "unconfigured@null.spigotmc.org" ]
unconfigured@null.spigotmc.org
a917b5150a057fc10d18757a5074c68bda65d5a5
251413d8c6c34086debc828e5a56088c0f3cf4cf
/GgafDx/include/jp/ggaf/dx/model/MassSpriteModel.h
330b4ab688d8b1be47992f80e578ddf7b99e3355
[]
no_license
gecchi/MyMain01
a7311a3e4659a140dd1127b2ea592e7f1ed1a22b
31ada3d4a434bea4dcd42fc867a52378493b0853
refs/heads/master
2023-09-01T14:30:06.410655
2023-08-30T14:39:38
2023-08-30T14:39:38
13,404,587
19
0
null
null
null
null
SHIFT_JIS
C++
false
false
1,338
h
#ifndef GGAF_DX_MASSSPRITEMODEL_H_ #define GGAF_DX_MASSSPRITEMODEL_H_ #include "jp/ggaf/GgafDxCommonHeader.h" #include "jp/ggaf/dx/model/MassModel.h" #include "jp/ggaf/dx/model/interface/IPlaneModel.h" namespace GgafDx { /** * MassSpriteActor用モデルクラス. * @version 1.00 * @since 2016/02/25 * @author Masatoshi Tsuge */ class MassSpriteModel : public MassModel, public IPlaneModel { friend class ModelManager; public: struct VERTEX_model : public Model::VERTEX_POS_NOMAL { float tu, tv; // テクスチャ座標 }; VERTEX_model* _paVtxBuffer_data_model; WORD* _paIndexBuffer_data; float _model_half_width_px; float _model_half_height_px; public: /** * コンストラクタ<BR> * @param prm_model_id スプライト定義の識別名。".x"を追加すると定義Xファイル名になる。 */ MassSpriteModel(const char* prm_model_id); static void createVertexModel(void* prm, MassModel::VertexModelInfo* out_info); virtual HRESULT draw(FigureActor* prm_pActor_target, int prm_draw_set_num = 1, void* prm_pPrm = nullptr) override; virtual void restore() override; /** * デストラクタ<BR> */ virtual ~MassSpriteModel(); }; } #endif /*GGAF_DX_MASSSPRITEMODEL_H_*/
[ "gecchi@bochibochi.ddo.jp" ]
gecchi@bochibochi.ddo.jp
76c8b813010f802dca32ebe170de2bcdef0f74dc
16d0c669c3d5e99978925babbfb45c6dd6822a97
/hphp/runtime/base/member-lval.h
4e79d8faa71f5cf23ac0ad7f298ce36215930035
[ "PHP-3.01", "Zend-2.0", "BSD-3-Clause" ]
permissive
fabpot/hhvm
604ad1baefbea98b3616387340e78d7d0662f90e
989f3ea5cc733d2c082588d051e5d4a9da03366c
refs/heads/master
2021-01-21T19:27:28.317282
2017-05-22T23:55:13
2017-05-23T00:02:03
92,136,873
5
3
null
2017-05-23T06:21:30
2017-05-23T06:21:29
null
UTF-8
C++
false
false
3,053
h
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #ifndef incl_HPHP_MEMB_LVAL_H_ #define incl_HPHP_MEMB_LVAL_H_ #include "hphp/runtime/base/datatype.h" #include <cstddef> namespace HPHP { /////////////////////////////////////////////////////////////////////////////// struct ArrayData; struct HeapObject; struct TypedValue; union Value; /////////////////////////////////////////////////////////////////////////////// /* * Encapsulated minstr lval reference to a container and the value and type tag * of one of its members. */ struct member_lval { member_lval(); /* * Opaque union of element pointer types. */ union ptr_union { friend member_lval; ptr_union(TypedValue* tv) : tv{tv} {} ptr_union(Value* val) : val{val} {} ptr_union(std::nullptr_t) : tv{nullptr} {} private: TypedValue* tv; Value* val; }; member_lval(HeapObject* base, ptr_union ptr); member_lval(HeapObject* base, TypedValue* elem); /* * The base type which logically contains the referenced value and type. */ HeapObject* base() const; ArrayData* arr_base() const; /* * Whether this member_lval contains a valid reference to a value and type. */ bool has_ref() const; /* * References to the value and type. * * @requires: has_ref() */ const Value& val() const; Value& val(); const DataType& type() const; DataType& type(); /* * Get a pointer to the referenced TypedValue. * * The behavior is undefined if the base() does not actually store the value * and type as a TypedValue. Currently, this never happens. * * TODO(#9077255): Make it happen for monomorphic arrays. */ TypedValue* tv() const; /* * Opaque element pointer. * * This should only be used for constructing new member_lval objects from * existing ones. */ ptr_union elem() const; private: union { HeapObject* m_base; ArrayData* m_arr; }; ptr_union m_ptr; }; /////////////////////////////////////////////////////////////////////////////// } #include "hphp/runtime/base/member-lval-inl.h" #endif
[ "hhvm-bot@users.noreply.github.com" ]
hhvm-bot@users.noreply.github.com
2f76612dc4ac0d8a458ab1d20c32afe81ece05f5
3b9b4ce22b8c9cb2b24b358aabb45c57f3faca54
/test/yukicoder/4569.test.cpp
7f59211ada24d234fd59e8d9821e1b4a58d35abb
[]
no_license
beet-aizu/library
9a9f1b177236b36bf1ee8c2b3db0497d227745f0
4f26a088ff995dd9fc2612dbbafef9b56bdb0c61
refs/heads/master
2023-05-28T23:17:22.804903
2023-05-05T14:53:55
2023-05-05T14:53:55
62,494,730
157
49
null
2023-05-05T14:53:56
2016-07-03T12:05:57
C++
UTF-8
C++
false
false
602
cpp
// verification-helper: PROBLEM https://yukicoder.me/problems/4569 #include<bits/stdc++.h> using namespace std; #define call_from_test #include "../../io/single.cpp" #include "../../mod/rint.cpp" #undef call_from_test signed main(){ cin.tie(0); ios::sync_with_stdio(0); int p,n; cin>>p>>n; auto as=read(n); string s; cin>>s; using R = Rint<int>; R::set_mod(p); R ans(as[0]); for(int i=1;i<n;i++){ if(s[i-1]=='+') ans+=R(as[i]); if(s[i-1]=='-') ans-=R(as[i]); if(s[i-1]=='*') ans*=R(as[i]); if(s[i-1]=='/') ans/=R(as[i]); } cout<<ans<<endl; return 0; }
[ "20266375+beet-aizu@users.noreply.github.com" ]
20266375+beet-aizu@users.noreply.github.com
a0a33cd8d006d0c9f3b73d9b7df53e1f6e6b6398
c7feda8bb2b63bb0b1e346d9019f261e5e5a88e2
/leetcode/2.cpp
81cbf529a18cf7a5b63c6cf043da82a9512597a8
[]
no_license
EcutDavid/oj-practices
f6f05ee179b53fca436d6be33ef873033c72d895
831502fe83f7611d2031365663e8409919e2b0b0
refs/heads/master
2021-06-30T23:47:04.197213
2020-11-13T10:53:37
2020-11-13T10:53:37
152,569,918
1
0
null
null
null
null
UTF-8
C++
false
false
576
cpp
#include <bits/stdc++.h> struct ListNode { int val; ListNode* next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { auto ret = new ListNode(0); auto cur = ret; int acc = 0; while (l1 || l2) { int sum = acc + (l1 ? l1->val : 0) + (l2 ? l2->val : 0); cur->val = sum % 10; acc = sum / 10; if (l1) l1 = l1->next; if (l2) l2 = l2->next; if (l1 || l2 || acc) { cur = cur->next = new ListNode(acc); } } return ret; } };
[ "davidguandev@gmail.com" ]
davidguandev@gmail.com
8c2de2c008344db380a805534b21666b1225cff4
7d81512195811f6492b71d3645da811908e61a0c
/mymuduo/source/mymuduo/net/test/Reactor_test01.cc
156aaf8e0ee5786e09af7ec8fc3cc89b8fd6c9ff
[]
no_license
Kevin--Wu/learning-cpp-server
4a7f578f0f12060a4add988db9a98af9f234cc5f
27bdccffad985b53d1d779eeec52cac1a2e731ae
refs/heads/master
2023-03-11T14:13:52.146294
2021-02-21T04:33:05
2021-02-21T04:33:05
340,817,303
0
0
null
null
null
null
UTF-8
C++
false
false
463
cc
#include <mymuduo/net/EventLoop.h> #include <stdio.h> using namespace mymuduo; using namespace mymuduo::net; void threadFunc() { printf("threadFunc(): pid = %d, tid = %d\n", getpid(), CurrentThread::tid()); EventLoop loop; loop.loop(); } int main(void) { printf("main(): pid = %d, tid = %d\n", getpid(), CurrentThread::tid()); EventLoop loop; Thread t(threadFunc); t.start(); loop.loop(); t.join(); return 0; }
[ "wuhaoxuan1993@163.com" ]
wuhaoxuan1993@163.com
e2ee0b4a3bd92b556f2cc7590101d3917d42b512
deb3c10a3ecf2e1a41e47e5f6ef985b1f7561c72
/CarND-Unscented-Kalman-Filter-Project/src/ukf.h
fb361ffe9c1daa61673dd5801970c2f61bc39b4e
[ "MIT" ]
permissive
diegopdomingos/nanodegree
8b7a671df5dab73a2ea6b005701edaa83677095a
d93ff254d5de2ec46af033c474fb50fc6fd881d9
refs/heads/master
2021-09-10T16:26:12.134631
2018-03-28T00:34:48
2018-03-28T00:34:48
103,453,833
0
0
null
null
null
null
UTF-8
C++
false
false
2,739
h
#ifndef UKF_H #define UKF_H #include "measurement_package.h" #include "Eigen/Dense" #include <vector> #include <string> #include <fstream> using Eigen::MatrixXd; using Eigen::VectorXd; class UKF { public: ///* initially set to false, set to true in first call of ProcessMeasurement bool is_initialized_; ///* if this is false, laser measurements will be ignored (except for init) bool use_laser_; ///* if this is false, radar measurements will be ignored (except for init) bool use_radar_; ///* state vector: [pos1 pos2 vel_abs yaw_angle yaw_rate] in SI units and rad VectorXd x_; ///* state covariance matrix MatrixXd P_; ///* predicted sigma points matrix MatrixXd Xsig_pred_; ///* time when the state is true, in us long long time_us_; ///* Process noise standard deviation longitudinal acceleration in m/s^2 double std_a_; ///* Process noise standard deviation yaw acceleration in rad/s^2 double std_yawdd_; ///* Laser measurement noise standard deviation position1 in m double std_laspx_; ///* Laser measurement noise standard deviation position2 in m double std_laspy_; ///* Radar measurement noise standard deviation radius in m double std_radr_; ///* Radar measurement noise standard deviation angle in rad double std_radphi_; ///* Radar measurement noise standard deviation radius change in m/s double std_radrd_ ; ///* Weights of sigma points VectorXd weights_; // Xsig_pred MatrixXd Xsig_pred; ///* State dimension int n_x_; ///* Augmented state dimension int n_aug_; ///* Sigma point spreading parameter double lambda_; // Check if the system was initialized bool init; // Variables to store NIS double NIS_radar_; double NIS_laser_; /** * Constructor */ UKF(); /** * Destructor */ virtual ~UKF(); void AugmentedSigmaPoints(MatrixXd* Xsig_out); void UpdateUKF(MeasurementPackage meas_package, MatrixXd Zsig, int n_z); /** * ProcessMeasurement * @param meas_package The latest measurement data of either radar or laser */ void ProcessMeasurement(MeasurementPackage meas_package); /** * Prediction Predicts sigma points, the state, and the state covariance * matrix * @param delta_t Time between k and k+1 in s */ void Prediction(double delta_t); /** * Updates the state and the state covariance matrix using a laser measurement * @param meas_package The measurement at k+1 */ void UpdateLidar(MeasurementPackage meas_package); /** * Updates the state and the state covariance matrix using a radar measurement * @param meas_package The measurement at k+1 */ void UpdateRadar(MeasurementPackage meas_package); }; #endif /* UKF_H */
[ "diego.pdomingos@gmail.com" ]
diego.pdomingos@gmail.com
e6fde860ac3f1bc7e958e1cdbef043170f43ae10
1634d4f09e2db354cf9befa24e5340ff092fd9db
/Wonderland/Wonderland/Editor/Support/Math/Transform/WTransform3D.cpp
42873fa997fee0ee9e280a65a64f59f5cf2e81a3
[ "MIT" ]
permissive
RodrigoHolztrattner/Wonderland
cd5a977bec96fda1851119a8de47b40b74bd85b7
ffb71d47c1725e7cd537e2d1380962b5dfdc3d75
refs/heads/master
2021-01-10T15:29:21.940124
2017-10-01T17:12:57
2017-10-01T17:12:57
84,469,251
4
1
null
null
null
null
UTF-8
C++
false
false
986
cpp
/////////////////////////////////////////////////////////////////////////////// // Filename: WTransform3D.cpp /////////////////////////////////////////////////////////////////////////////// #include "WTransform3D.h" WTransform3D::WTransform3D() { } WTransform3D::WTransform3D(const WTransform3D& other) { } WTransform3D::~WTransform3D() { } void WTransform3D::SetPosition(float _x, float _y, float _z) { m_Position.x = _x; m_Position.y = _y; m_Position.z = _z; } void WTransform3D::SetPosition(Vector3 _position) { m_Position = _position; } void WTransform3D::SetSize(float _x, float _y, float _z) { m_Size.x = _x; m_Size.y = _y; m_Size.z = _z; } void WTransform3D::SetSize(Vector3 _size) { m_Size = _size; } void WTransform3D::SetRotation(WQuaternion _rotation) { m_Rotation = _rotation; } Vector3 WTransform3D::GetPosition() { return m_Position; } Vector3 WTransform3D::GetSize() { return m_Size; } WQuaternion WTransform3D::GetRotation() { return m_Rotation; }
[ "rodrigoholztrattner@gmail.com" ]
rodrigoholztrattner@gmail.com
8fe6865b9a1aa9fa38630d26f7a3b2bb339c00e3
d364b81e14ed538e7c9a21219b0f7c1a6e88a633
/demo/cse_168_hw3/Renderer.cpp
6d6c9ab0743d50f85c2108b2a2ce6858de61a235
[]
no_license
IngInx747/xtracing
fe623595ca466080030dd093990073a6c35eac6b
a4822e45881b3b59b0c47f04d8258d82730b4dd6
refs/heads/master
2023-08-01T06:18:18.954600
2021-09-11T01:01:50
2021-09-11T01:01:50
349,595,905
0
0
null
null
null
null
UTF-8
C++
false
false
1,900
cpp
#include "Renderer.h" #if defined(_OPENMP) #include <omp.h> #endif #include "util.h" vec3 Renderer::RenderPixel(const int2& index, const int2& dim, const Scene& scene) { vec3 result{0, 0, 0}; int spp = scene.nSamplePerPixel; #if defined(_OPENMP) int tid = omp_get_thread_num(); #else int tid = 0; #endif GetRandom(0.f, 1.f, tid); // set seed for (int i = 0; i < spp; ++i) { Payload payload; payload.done = false; payload.depth = 0; payload.weight = vec3{1, 1, 1}; payload.seed = tid; // ray 0 vec2 p = vec2{index.x, index.y}; if (i == 0) p += vec2{0.5f, 0.5f}; else p += vec2{GetRandom(), GetRandom()}; // jaggy vec2 d = p / vec2{dim.x, dim.y} * 2.0f - 1.0f; const CameraFrame& cam = scene.cameraFrame; payload.direction = normalize(d.x * cam.u + d.y * cam.v + cam.w); payload.origin = cam.o; do { Ray ray{payload.origin, payload.direction, kInfP, 0.001f}; // Ray 1 ~ n Trace(scene.root.get(), ray, payload, 0, false, scene.miss.get()); } while (!payload.done && payload.depth < scene.depth); result += payload.radiance; } return result / static_cast<float>(spp); } void Renderer::Render(std::vector<vec3>& buffer, const Scene& scene) { int width = scene.width; int height = scene.height; while (currentFrame < numMaxFrame) { #pragma omp parallel for// schedule(dynamic) for (int i = 0; i < height; ++i) { //printf("pixel(%d, :)\n", i); for (int j = 0; j < width; ++j) { //printf("pixel(%d, %d)\n", i, j); vec3 pixel = RenderPixel({j, i}, {width, height}, scene); buffer[i * width + j] = pixel; } } ++currentFrame; } }
[ "jingchun.wang@asml.com" ]
jingchun.wang@asml.com
2640a567cee3cdad8d676b439742c5993458677e
38c10c01007624cd2056884f25e0d6ab85442194
/content/common/indexed_db/indexed_db_param_traits.cc
9ca0ceceeaca9df4694c4fd11688f38f4091f7b9
[ "BSD-3-Clause" ]
permissive
zenoalbisser/chromium
6ecf37b6c030c84f1b26282bc4ef95769c62a9b2
e71f21b9b4b9b839f5093301974a45545dad2691
refs/heads/master
2022-12-25T14:23:18.568575
2016-07-14T21:49:52
2016-07-23T08:02:51
63,980,627
0
2
BSD-3-Clause
2022-12-12T12:43:41
2016-07-22T20:14:04
null
UTF-8
C++
false
false
7,032
cc
// Copyright (c) 2012 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. #include "content/common/indexed_db/indexed_db_param_traits.h" #include <string> #include <vector> #include "content/common/indexed_db/indexed_db_key.h" #include "content/common/indexed_db/indexed_db_key_path.h" #include "content/common/indexed_db/indexed_db_key_range.h" #include "ipc/ipc_message_utils.h" using content::IndexedDBKey; using content::IndexedDBKeyPath; using content::IndexedDBKeyRange; using blink::WebIDBKeyPathTypeArray; using blink::WebIDBKeyPathTypeNull; using blink::WebIDBKeyPathTypeString; using blink::WebIDBKeyType; using blink::WebIDBKeyTypeArray; using blink::WebIDBKeyTypeBinary; using blink::WebIDBKeyTypeDate; using blink::WebIDBKeyTypeInvalid; using blink::WebIDBKeyTypeMin; using blink::WebIDBKeyTypeNull; using blink::WebIDBKeyTypeNumber; using blink::WebIDBKeyTypeString; namespace IPC { void ParamTraits<IndexedDBKey>::Write(Message* m, const param_type& p) { WriteParam(m, static_cast<int>(p.type())); switch (p.type()) { case WebIDBKeyTypeArray: WriteParam(m, p.array()); return; case WebIDBKeyTypeBinary: WriteParam(m, p.binary()); return; case WebIDBKeyTypeString: WriteParam(m, p.string()); return; case WebIDBKeyTypeDate: WriteParam(m, p.date()); return; case WebIDBKeyTypeNumber: WriteParam(m, p.number()); return; case WebIDBKeyTypeInvalid: case WebIDBKeyTypeNull: return; case WebIDBKeyTypeMin: default: NOTREACHED(); return; } } bool ParamTraits<IndexedDBKey>::Read(const Message* m, base::PickleIterator* iter, param_type* r) { int type; if (!ReadParam(m, iter, &type)) return false; WebIDBKeyType web_type = static_cast<WebIDBKeyType>(type); switch (web_type) { case WebIDBKeyTypeArray: { std::vector<IndexedDBKey> array; if (!ReadParam(m, iter, &array)) return false; *r = IndexedDBKey(array); return true; } case WebIDBKeyTypeBinary: { std::string binary; if (!ReadParam(m, iter, &binary)) return false; *r = IndexedDBKey(binary); return true; } case WebIDBKeyTypeString: { base::string16 string; if (!ReadParam(m, iter, &string)) return false; *r = IndexedDBKey(string); return true; } case WebIDBKeyTypeDate: case WebIDBKeyTypeNumber: { double number; if (!ReadParam(m, iter, &number)) return false; *r = IndexedDBKey(number, web_type); return true; } case WebIDBKeyTypeInvalid: case WebIDBKeyTypeNull: *r = IndexedDBKey(web_type); return true; case WebIDBKeyTypeMin: default: NOTREACHED(); return false; } } void ParamTraits<IndexedDBKey>::Log(const param_type& p, std::string* l) { l->append("<IndexedDBKey>("); switch(p.type()) { case WebIDBKeyTypeArray: { l->append("array="); l->append("["); bool first = true; for (const IndexedDBKey& key : p.array()) { if (!first) l->append(", "); first = false; Log(key, l); } l->append("]"); break; } case WebIDBKeyTypeBinary: l->append("binary="); LogParam(p.binary(), l); break; case WebIDBKeyTypeString: l->append("string="); LogParam(p.string(), l); break; case WebIDBKeyTypeDate: l->append("date="); LogParam(p.date(), l); break; case WebIDBKeyTypeNumber: l->append("number="); LogParam(p.number(), l); break; case WebIDBKeyTypeInvalid: l->append("invalid"); break; case WebIDBKeyTypeNull: l->append("null"); break; case WebIDBKeyTypeMin: default: NOTREACHED(); break; } l->append(")"); } void ParamTraits<IndexedDBKeyPath>::Write(Message* m, const param_type& p) { WriteParam(m, static_cast<int>(p.type())); switch (p.type()) { case WebIDBKeyPathTypeArray: WriteParam(m, p.array()); return; case WebIDBKeyPathTypeString: WriteParam(m, p.string()); return; case WebIDBKeyPathTypeNull: return; default: NOTREACHED(); return; } } bool ParamTraits<IndexedDBKeyPath>::Read(const Message* m, base::PickleIterator* iter, param_type* r) { int type; if (!ReadParam(m, iter, &type)) return false; switch (type) { case WebIDBKeyPathTypeArray: { std::vector<base::string16> array; if (!ReadParam(m, iter, &array)) return false; *r = IndexedDBKeyPath(array); return true; } case WebIDBKeyPathTypeString: { base::string16 string; if (!ReadParam(m, iter, &string)) return false; *r = IndexedDBKeyPath(string); return true; } case WebIDBKeyPathTypeNull: *r = IndexedDBKeyPath(); return true; default: NOTREACHED(); return false; } } void ParamTraits<IndexedDBKeyPath>::Log(const param_type& p, std::string* l) { l->append("<IndexedDBKeyPath>("); switch (p.type()) { case WebIDBKeyPathTypeArray: { l->append("array=["); bool first = true; for (const base::string16& entry : p.array()) { if (!first) l->append(", "); first = false; LogParam(entry, l); } l->append("]"); break; } case WebIDBKeyPathTypeString: l->append("string="); LogParam(p.string(), l); break; case WebIDBKeyPathTypeNull: l->append("null"); break; default: NOTREACHED(); break; } l->append(")"); } void ParamTraits<IndexedDBKeyRange>::Write(Message* m, const param_type& p) { WriteParam(m, p.lower()); WriteParam(m, p.upper()); WriteParam(m, p.lower_open()); WriteParam(m, p.upper_open()); } bool ParamTraits<IndexedDBKeyRange>::Read(const Message* m, base::PickleIterator* iter, param_type* r) { IndexedDBKey lower; if (!ReadParam(m, iter, &lower)) return false; IndexedDBKey upper; if (!ReadParam(m, iter, &upper)) return false; bool lower_open; if (!ReadParam(m, iter, &lower_open)) return false; bool upper_open; if (!ReadParam(m, iter, &upper_open)) return false; *r = IndexedDBKeyRange(lower, upper, lower_open, upper_open); return true; } void ParamTraits<IndexedDBKeyRange>::Log(const param_type& p, std::string* l) { l->append("<IndexedDBKeyRange>(lower="); LogParam(p.lower(), l); l->append(", upper="); LogParam(p.upper(), l); l->append(", lower_open="); LogParam(p.lower_open(), l); l->append(", upper_open="); LogParam(p.upper_open(), l); l->append(")"); } } // namespace IPC
[ "zeno.albisser@hemispherian.com" ]
zeno.albisser@hemispherian.com
6392903d6942c50bee4c7cddb2789ef6e2beb7c9
96dae00de134c84e58ca7c3a5420313fc484da10
/ICPC_AlgorithmTemplete/数据结构/字符串与各种自动机/字符串匹配/kmp匹配.cpp
bab0c88a2ca8baa001f34223355e7c5c01728f3e
[]
no_license
meiyoumingzile/ICPC_AlgorithmTemplete
62758cde771667bf8602b6e625456a36c8525ab7
2bcabeadd94e83acaffa0b90365c93468a8f0004
refs/heads/master
2023-08-16T23:06:22.774993
2023-08-13T08:47:01
2023-08-13T08:47:01
159,670,934
7
2
null
null
null
null
GB18030
C++
false
false
3,712
cpp
#include<bits/stdc++.h> //#include<windows.h> using namespace std; #define ll long long #define inf 1e-5 const int INF=1<<30; const int MAX=10010; const int mod=1e9+7; char s1[MAX],s2[MAX]; int nex[MAX]; vector<int>ind; void getnext1(int *nex,char *s2){//原始next[0]=0数组 int j,k,len2=strlen(s2); nex[0]=0; for(j=1;j<len2;j++){ k=nex[j-1]; while(k>0&&s2[k]!=s2[j]){ k=nex[k-1]; } if(s2[k]!=s2[j]){ nex[j]=k; }else{ nex[j]=k+1; } } } void getnext1_1(int *nex,char *word){ int i,k,len=strlen(word);//模版字符串长度 nex[0] = 0; for(i=1,k=0;i<len;i++){ while(k&&word[i]!=word[k]) k=nex[k-1]; if(word[i]==word[k]){ k++; } nex[i] = k; } } void getnext2(int *nex,char *s2){//原始next[0]=-1数组 int j,k,len2=strlen(s2); nex[0]=-1; for(j=1;j<len2;j++){ k=nex[j-1]; while(k>-1&&s2[k]!=s2[j-1]){ k=nex[k]; } nex[j]=k+1; } } void getnext2_1(int *nex,char *word){ nex[0]=-1; int k=-1,j=0, num=(int)strlen(word); while(j<num){ if(k==-1||word[j]==word[k]){ j++;k++; nex[j]=k; }else k=nex[k]; } } void getnext3(int *nex,char *s2){//nextval数组 int j,k,len2=strlen(s2); nex[0]=-1;k=-1; for(j=1;j<len2;j++){ while(k>-1&&s2[k]!=s2[j-1]){ k=nex[k]; } k++; nex[j]=s2[k]==s2[j]?nex[k]:k; } } void getnext3_1(int *nex,char *word) { nex[0]=-1; int k=-1,j=0, num=(int)strlen(word); while(j<num){ if(k==-1||word[j]==word[k]){ j++;k++; if(word[j]!=word[k]) nex[j]=k; else nex[j]=nex[k]; }else k=nex[k]; } } int KMP1(char *s1,char *s2,int *nex){//在s1中找s2,找第一次出现位置,next[0]=-1可用 int i=0,j=0,len1=(int)strlen(s1),len2=(int)strlen(s2); while(i<len1&&j<len2){ if(j==-1||s1[i]==s2[j]){ i++; j++; }else{ j=nex[j]; } if(j==len2){ printf("%d\n",i-len2); return i-len2; } } return -1; } void KMP2(char *s1,char *s2,int *nex){//在s1中找s2,找全部出现位置,next[0]=-1可用 int i=0,j=0,len1=(int)strlen(s1),len2=(int)strlen(s2); while(i<len1&&j<len2){ if(j==-1||s1[i]==s2[j]){ i++; j++; }else{ j=nex[j]; } if(j==len2){ printf("%d\n",i-len2); j=nex[j]; } } } int KMP3(char *s1,char *s2,int *nex){//在s1中找s2,找第一次出现的位置,next[0]=0可用 int i=0,j=0,len1=(int)strlen(s1),len2=(int)strlen(s2); while(i<len1){ if(s1[i]==s2[j]){ i++; j++; }else{ if(j==0){ i++; }else{ j=nex[j-1]; } } if(j==len2) return i-j; } return -1; } bool vioMatch(char *s1,char *s2) {//暴力匹配 int len1=strlen(s1); int len2=strlen(s2); if(len1<len2){ swap(len1,len2); swap(s1,s2); } int i=0,j=0; while(i<len1){ printf("(%d %d)",i,j); if(s1[i]==s2[j]){ i++;j++; }else{ i-=j-1;//退回去 j=0; } if(j==len2) return i-j; } return 0; } int main(int argc,char *argv[]){ int i,len; while(~scanf("%s%s",s1,s2)){//查找s1中所有匹配的s2 getnext3(nex,s2); len=strlen(s2); for(i=0;i<len;i++){ printf("%d ",nex[i]); }printf("\n"); getnext2(nex,s2); for(i=0;i<len;i++){ printf("%d ",nex[i]); }printf("\n"); //printf("%d\n",KMP2(s1,s2,nex)); KMP2(s1,s2,nex); } return 0; }
[ "39816793+meiyoumingzile@users.noreply.github.com" ]
39816793+meiyoumingzile@users.noreply.github.com
37a31a5b039f1a3bb9869f59e22d7118539f46d0
3b77aa59eb39d62d06506520cf382cabadaebc39
/src/sdeventplus/exception.hpp
1303062a8abba2db311b3cd789dcef26b04a586e
[ "Apache-2.0" ]
permissive
wak-google/sdeventplus
a9577e862b3c661a8cdd851c50eb3ea92708f93f
3064849c13981864c4d85667659d502f0c3b5d9f
refs/heads/master
2020-05-17T18:44:57.220865
2019-06-02T09:05:03
2019-06-05T05:51:06
183,894,325
0
0
Apache-2.0
2019-04-28T10:37:02
2019-04-28T10:37:02
null
UTF-8
C++
false
false
506
hpp
#pragma once #include <system_error> namespace sdeventplus { /** @class SdEventError * @brief Holds information about underlying sd_event * issued errors */ class SdEventError final : public std::system_error { public: /** @brief Creates a new SdEventError from error data * * @param[in] r - The positive errno code * @param[in] prefix - The prefix string to display in the what() */ SdEventError(int r, const char* prefix); }; } // namespace sdeventplus
[ "wak@google.com" ]
wak@google.com
923274e9e6356a3a8b2aeb81d6fc1665690f1898
8675e2d47026f5b4fda8ed4b828f1dab06fbe9ce
/ecl_core/ecl_time/src/lib/sleep_win.cpp
57fb9d6e94d3833001182197408f9dc96e5397ee
[]
no_license
sergiodrm/Turtlebot2_UV
62e583bb8ccdd86b503b5c9ac54906b086d561bc
f68a2ca25b7e27f07c7433d7b0da20a07ff34d81
refs/heads/master
2022-11-13T06:43:42.879290
2020-07-03T11:09:59
2020-07-03T11:09:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,350
cpp
/** * @file /src/lib/sleep_win.cpp * * @brief Implementation of the sleep classes. * * @date April 2013 **/ /***************************************************************************** ** Platform Check *****************************************************************************/ #include <ecl/config.hpp> #if defined(ECL_IS_WIN32) /***************************************************************************** ** Includes *****************************************************************************/ #include <ecl/errors/macros.hpp> #include "../../include/ecl/time/duration.hpp" #include "../../include/ecl/time/sleep_win.hpp" #include <iostream> #include <ecl/time_lite/functions.hpp> /***************************************************************************** ** Namespaces *****************************************************************************/ namespace ecl { /***************************************************************************** ** Implementation [Sleep] *****************************************************************************/ Sleep::Sleep(const Duration &duration) { required.tv_sec = duration.sec(); required.tv_nsec = duration.nsec(); } Sleep::Sleep(const unsigned long &seconds) { required.tv_sec = seconds; required.tv_nsec = 0; } void Sleep::operator ()() { TimeError result = sleep(required); ecl_assert_throw( result == TimeError(NoError), time::throwSleepException(LOC) ); } void Sleep::operator ()(const Duration &duration) { required.tv_sec = duration.sec(); required.tv_nsec = duration.nsec(); TimeError result = sleep(required); ecl_assert_throw( result == TimeError(NoError), time::throwSleepException(LOC) ); } void Sleep::operator ()(const unsigned long &seconds) { required.tv_sec = seconds; required.tv_nsec = 0; TimeError result = sleep(required); ecl_assert_throw( result == TimeError(NoError), time::throwSleepException(LOC) ); } /***************************************************************************** ** Implementation [MilliSleep] *****************************************************************************/ MilliSleep::MilliSleep(const unsigned long &milliseconds) { required.tv_sec = milliseconds/1000; // integer division required.tv_nsec = (milliseconds%1000)*1000000; } void MilliSleep::operator ()() { TimeError result = sleep(required); ecl_assert_throw( result == TimeError(NoError), time::throwSleepException(LOC) ); } void MilliSleep::operator ()(const unsigned long &milliseconds) { required.tv_sec = milliseconds/1000; // integer division required.tv_nsec = (milliseconds%1000)*1000000; // required.tv_nsec = 1000000*milli_seconds; TimeError result = sleep(required); ecl_assert_throw( result == TimeError(NoError), time::throwSleepException(LOC) ); } /***************************************************************************** ** Implementation [MicroSleep] *****************************************************************************/ MicroSleep::MicroSleep(const unsigned long &microseconds) { required.tv_sec = microseconds/1000000; // integer division required.tv_nsec = (microseconds%1000000)*1000; } void MicroSleep::operator ()() { TimeError result = sleep(required); ecl_assert_throw( result == TimeError(NoError), time::throwSleepException(LOC) ); } void MicroSleep::operator ()(const unsigned long &micro_seconds) { required.tv_nsec = 1000*micro_seconds; TimeError result = sleep(required); ecl_assert_throw( result == TimeError(NoError), time::throwSleepException(LOC) ); } /***************************************************************************** ** Implementation [NanoSleep] *****************************************************************************/ NanoSleep::NanoSleep(const unsigned long &nanoseconds) { required.tv_sec = nanoseconds/1000000000; // integer division required.tv_nsec = nanoseconds%1000000000; } void NanoSleep::operator ()() { TimeError result = sleep(required); ecl_assert_throw( result == TimeError(NoError), time::throwSleepException(LOC) ); } void NanoSleep::operator ()(const unsigned long &nanoseconds) { required.tv_nsec = nanoseconds; TimeError result = sleep(required); ecl_assert_throw( result == TimeError(NoError), time::throwSleepException(LOC) ); } } // namespace ecl #endif /* ECL_IS_WIN32 */
[ "theverbat@gmail.com" ]
theverbat@gmail.com
e58d29a7d11d6ac4198deebc2934c1d0352c9c0f
d5f68f68ba46df63b20c1c5c7f020136cbc31647
/Error-Game/Source/BitmapFont.h
21e182b2675341f09807206146cf079d8bb381d1
[]
no_license
ianalcid08/FinalProject
088f8bf035543b55243c20be274538552d58c384
a41c87a85d130e3c3021d24d53df4ffa2a80d67f
refs/heads/master
2021-01-23T08:15:25.394104
2014-02-25T01:29:40
2014-02-25T01:29:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,851
h
#ifndef CBITMAPFONT_H_ #define CBITMAPFONT_H_ /*********************************************** * Filename: BitmapFont.h * Date: 2/12/2013 * Mod. Date: 3/7/2013 * Mod. Initials: IA * Author: Ian Alcid * Purpose: Bitmap Font for screen ************************************************/ #include "Renderer.h" class CGame; class CAssetManager; class CBitmapFont { private: CBitmapFont(void); ~CBitmapFont(void); static CBitmapFont m_Instance; CAssetManager *m_pAM; CRenderer *m_pRenderer; IDirect3DTexture9 *m_d3dFontSheet; //Cell Algorithm int m_nChar_Width; int m_nChar_Height; int m_nNumCols; int m_nNumRows; char m_cFirstChar; // First character in the image bool m_bOnlyUppercase; // Only uppercase letters in the image public: static CBitmapFont* GetInstance(); /***************************************************************** * void InitFont(): Loads the bitmap font sheet * * Ins: void * * Outs: void * * Returns: void * * Mod. Date: 03/8/2013 * Mod. Initials: IA *****************************************************************/ void InitFont(); /***************************************************************** * void PrintBF(): Draws strings to screen using the bitmap sheet * * Ins: const char* szText int nX int nY float fScale DWORD dwColor = D3DCOLOR_XRGB(255,255,255) * * Outs: void * * Returns: void * * Mod. Date: 03/8/2013 * Mod. Initials: IA *****************************************************************/ void PrintBF( const char* szText , int nX, int nY, float fScale, DWORD dwColor = D3DCOLOR_XRGB(255,255,255)); /***************************************************************** * void CellAlgorithm(): Based on char finds desired rect on bitmap sheet * * Ins: unsigned int id * * Outs: void * * Returns: void * * Mod. Date: 03/8/2013 * Mod. Initials: IA *****************************************************************/ RECT CellAlgorithm ( unsigned int id); /***************************************************************** * void DrawTexture(): Draws per character * * Ins: IDirect3DTexture9* backgroundBMP int nX, int nY, float fScaleX, float fScaleY, RECT* pSection = NULL, float fRotCenterX = 0.0f, float fRotCenterY = 0.0f, float fRotation = 0.0f, DWORD dwColor = 0xFFFFFFFF); * * Outs: void * * Returns: void * * Mod. Date: 03/8/2013 * Mod. Initials: IA *****************************************************************/ void DrawTexture(IDirect3DTexture9* backgroundBMP, int nX, int nY, float fScaleX, float fScaleY, RECT* pSection = NULL, float fRotCenterX = 0.0f, float fRotCenterY = 0.0f, float fRotation = 0.0f, DWORD dwColor = 0xFFFFFFFF); }; #endif
[ "ian.alcid08@gmail.com" ]
ian.alcid08@gmail.com
0d11462c47de153c25080e71e5f122e8bab9b9a3
e2bd7bf66a01a835a87ee43773d40d6c9a88d96c
/source/digits_hits/src/GateBenchmarkActor.cc
5189d66e4783099f3df33cd5b80a81b2af76d8a1
[]
no_license
sansiri20/opengate-public
900136e98ce6e324819d944474b12e3c6da8e668
06d46c29e8c78d7b0fc81052cfb44cf002c60bd0
refs/heads/master
2021-05-26T17:27:53.975226
2013-05-21T12:56:53
2013-05-21T12:56:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,583
cc
/*---------------------- GATE version name: gate_v6 Copyright (C): OpenGATE Collaboration This software is distributed under the terms of the GNU Lesser General Public Licence (LGPL) See GATE/LICENSE.txt for further details ----------------------*/ #include "GateBenchmarkActor.hh" #ifdef G4ANALYSIS_USE_ROOT #include <G4VProcess.hh> #include "GateBenchmarkActorMessenger.hh" GateBenchmarkActor::GateBenchmarkActor(G4String name, G4int depth) : GateVActor(name,depth) { pMessenger = new GateBenchmarkActorMessenger(this); } GateBenchmarkActor::~GateBenchmarkActor() { delete pMessenger; } void GateBenchmarkActor::Construct() { const int nbins = 1024; const G4double max_fly_distance = 15*mm; const G4double max_energy = 10*MeV; GateVActor::Construct(); EnableBeginOfRunAction(false); EnableBeginOfEventAction(false); EnableEndOfEventAction(true); // for save every n EnablePreUserTrackingAction(true); EnablePostUserTrackingAction(true); EnableUserSteppingAction(true); pTfile = new TFile(mSaveFilename,"RECREATE"); histoEFreePath = new TH2D("EFreePath","Free path", nbins, 0, max_energy/MeV, nbins, 0, max_fly_distance/mm); histoEFreePath->SetXTitle("Energy [MeV]"); histoEFreePath->SetYTitle("Distance [mm]"); histoEDeltaE = new TH2D("EDeltaE","Energy loss", nbins, 0, max_energy/MeV, nbins, 0, 2); histoEDeltaE->SetXTitle("Energy [MeV]"); histoEDeltaE->SetYTitle("Energy loss [MeV]"); histoEPrimaryDeviation = new TH2D("EPrimaryDeviation","Primary deviation angle", nbins, 0, max_energy/MeV, nbins, 0, 2); histoEPrimaryDeviation->SetXTitle("Energy [MeV]"); histoEPrimaryDeviation->SetYTitle("Deviation angle [deg]"); histoESecondaryDeviation = new TH2D("ESecondaryDeviation","Secondary deviation angle", nbins, 0, max_energy/MeV, nbins, 40, 90); histoESecondaryDeviation->SetXTitle("Energy [MeV]"); histoESecondaryDeviation->SetYTitle("Deviation angle [deg]"); histoFlyDistance = new TH1D("FlyDistance","Fly distance per track", nbins, 0, max_fly_distance/mm); histoFlyDistance->SetXTitle("Distance [mm]"); histoSumFreePath = new TH1D("SumFreePath","Sum of free path per track", nbins, 0, max_fly_distance/mm); histoSumFreePath->SetXTitle("Distance [mm]"); ResetData(); } void GateBenchmarkActor::SaveData() { pTfile->Write(); } void GateBenchmarkActor::ResetData() { histoEFreePath->Reset(); histoEDeltaE->Reset(); histoEPrimaryDeviation->Reset(); histoESecondaryDeviation->Reset(); histoFlyDistance->Reset(); histoSumFreePath->Reset(); } void GateBenchmarkActor::BeginOfRunAction(const G4Run*) { GateDebugMessage("Actor", 3, "GateBenchmarkActor -- Begin of Run" << G4endl); } void GateBenchmarkActor::BeginOfEventAction(const G4Event*) { GateDebugMessage("Actor", 3, "GateBenchmarkActor -- Begin of Event" << G4endl); } void GateBenchmarkActor::EndOfEventAction(const G4Event*) { GateDebugMessage("Actor", 3, "GateBenchmarkActor -- End of Event" << G4endl); } void GateBenchmarkActor::PreUserTrackingAction(const GateVVolume*, const G4Track* track) { const G4String name = track->GetDefinition()->GetParticleName(); const G4ThreeVector position = track->GetPosition(); //const G4double energy = track->GetKineticEnergy(); //G4cout << "begin track for " << name << " position = " << position/mm << " energy = " << energy/MeV << G4endl; positionInitial = position; sumFreePath = 0; currentSecondary = 0; } G4double deviationAngle(const G4ThreeVector& dir_orig, const G4ThreeVector& dir_final) { G4double dot_product = dir_orig.dot(dir_final); if (dot_product > 1) dot_product = 1; if (dot_product < -1) dot_product = -1; return acos(dot_product)*rad; } void GateBenchmarkActor::UserSteppingAction(const GateVVolume*, const G4Step* step) { const G4double weight = step->GetTrack()->GetWeight(); const G4ThreeVector position_pre = step->GetPreStepPoint()->GetPosition(); const G4ThreeVector position_post = step->GetPostStepPoint()->GetPosition(); const G4double free_path = step->GetStepLength(); const G4double energy_pre = step->GetPreStepPoint()->GetKineticEnergy(); const G4double energy_post = step->GetPostStepPoint()->GetKineticEnergy(); const G4double energy_delta = energy_pre-energy_post; const G4ThreeVector direction_pre = step->GetPostStepPoint()->GetMomentumDirection(); const G4ThreeVector direction_post = step->GetPostStepPoint()->GetMomentumDirection(); const G4double deviation = deviationAngle(direction_post,direction_pre); const G4VProcess* process = step->GetPostStepPoint()->GetProcessDefinedStep(); G4String process_name = "unknown"; if (process) process_name = process->GetProcessName(); sumFreePath += free_path; //G4cout << "step position_pre = " << position_pre/mm << " position_post = " << position_post/mm << " free_path = " << free_path/mm << G4endl; //G4cout << " energy_pre = " << energy_pre/MeV << " energy_post = " << energy_post/MeV << " delta = " << energy_delta/MeV << G4endl; //G4cout << " direction_pre = " << direction_pre << " direction_post = " << direction_post << " deviation = " << deviation/deg << G4endl; //G4cout << " process = " << process_name << G4endl; histoEFreePath->Fill(energy_pre/MeV,free_path/mm,weight); histoEDeltaE->Fill(energy_pre/MeV,energy_delta/MeV,weight); if (deviation) histoEPrimaryDeviation->Fill(energy_pre/MeV,deviation/MeV,weight); //G4cout << " nsec = " << step->GetSecondary()->size() << G4endl; while (currentSecondary < step->GetSecondary()->size()) { const G4Track* track_secondary = (*step->GetSecondary())[currentSecondary]; const G4ThreeVector direction_secondary = track_secondary->GetMomentumDirection(); const G4double deviation_secondary = deviationAngle(direction_secondary,direction_pre); //G4cout << " currentSecondary = " << currentSecondary << " direction_pre = " << direction_pre << " direction_sec = " << direction_secondary << " deviation = " << deviation_secondary/deg << G4endl; if (deviation_secondary) histoESecondaryDeviation->Fill(energy_pre/MeV,deviation_secondary/deg,weight); currentSecondary++; } } void GateBenchmarkActor::PostUserTrackingAction(const GateVVolume*, const G4Track* track) { const G4ThreeVector position = track->GetPosition(); const G4double fly_distance = (position-positionInitial).mag(); const G4double weight = track->GetWeight(); //G4cout << "end track position = " << position/mm << " flyDistance = " << fly_distance/mm << " sumFreePath = " << sumFreePath/mm << G4endl; histoFlyDistance->Fill(fly_distance/mm,weight); histoSumFreePath->Fill(sumFreePath/mm,weight); } #endif
[ "pierre.gueth@creatis.insa-lyon.fr" ]
pierre.gueth@creatis.insa-lyon.fr
7620e7b6a9347cba64d6e34cc7c2fe5d31d416b2
7ac7712fac59af460af20144f7ae452f5db5321c
/automata.h
4df1ecfa5aeee30da884afab05de8ee8b00f9327
[]
no_license
TinyYan/Z3-str-replaceAll
f0e22598b276ae1f6db58d7de08a13f3c1d6c983
0ae49c35e994fb5dec2648c2cb8ad613ca5e5c06
refs/heads/master
2020-03-12T13:33:13.120181
2018-04-24T08:03:12
2018-04-24T08:03:12
130,644,899
7
0
null
null
null
null
UTF-8
C++
false
false
6,831
h
#ifndef automata_h #define automata_h #include<set> #include<map> #include<unordered_map> #include<unordered_set> #include<algorithm> extern char emptyChar; extern std::unordered_set<char> faCharSet; class DFAState; class NFAState; class DFA; class NFA; class FA; typedef std::unordered_map<char, std::unordered_set<NFAState*> > NFATransMap; typedef std::unordered_map<char, DFAState*> DFATransMap; typedef std::unordered_set<NFAState*> NFAStateSet; typedef std::unordered_set<DFAState*> DFAStateSet; struct InformationForStr { DFAState* state; std::unordered_map<DFAState*, DFAState*> mapping; friend bool operator== (const InformationForStr& info1,const InformationForStr& info2) { if (info1.state == info2.state && info1.mapping == info2.mapping) return true; else return false; } }; struct InformationForReg { DFAStateSet preStates; DFAStateSet noFinalStates; friend bool operator== (const InformationForReg& info1, const InformationForReg& info2) { if (info1.noFinalStates == info2.noFinalStates && info1.preStates == info2.preStates) return true; else return false; } }; //------------------------------------------------- class State { public: virtual bool isEnd() = 0; virtual void setEnd(bool e) = 0; virtual ~State() {} }; class NFAState : public State { private: unsigned long long id; static unsigned long long size; bool end; NFATransMap transMap; public: friend class NFA; NFAState():id(size++),end(false) {} void setEnd(bool e) { end = e; } bool isEnd() { return end; } void addTrans(char c, NFAState* s) { transMap[c].insert(s); } NFATransMap& getTransMap() { return transMap; } bool hasTrans(char c) { if (transMap.count(c) != 0) return true; else return false; } NFAStateSet getStates(char c); virtual void* getInformation() { return (void*)&id; }; virtual ~NFAState() {} }; class DFAState : public State { private: unsigned long long id; static unsigned long long size; bool end; DFATransMap transMap; public: friend class DFA; DFAState():id(size++),end(false) {} void setEnd(bool e) { end = e; } bool isEnd() { return end; } void addTrans(char c, DFAState* s) { if (transMap.count(c) == 1) { fprintf(stdout, "> Error: DFA state can only have one %c-transition.\n", c); fflush(stdout); } else { transMap[c] = s; } } DFATransMap& getTransMap() { return transMap; } bool hasTrans(char c) { if (transMap.count(c) != 0) return true; else return false; } DFAState* getState(char c) { if (transMap.count(c) == 0) { return NULL; } else { return transMap[c]; } } virtual void* getInformation() { return (void*)&id; }; virtual ~DFAState() {} }; class FA { public: static void setFACharSet() { for (int i = 0; i < 127; ++i) { faCharSet.insert(static_cast<char>(i)); } } virtual std::string getWord(bool &succ) = 0; virtual bool isEmpty() = 0; virtual bool accept(std::string &s) = 0; virtual void clear() = 0; virtual bool isDeterministic() = 0; virtual ~FA() {} }; class NFA : public FA { private: NFAState* startState; NFAStateSet finalStates; NFAStateSet allStates; public: NFA(): startState(NULL) {}; NFA(NFA &nfa); NFA(NFA *nfaP); NFA(DFA &dfa); NFA(DFA *dfaP); NFA(std::string regex); NFA(NFA *nfaP, std::unordered_map<NFAState*,NFAState*> &sMap); NFAStateSet &getFinalStates() { return finalStates; } NFAStateSet &getAllStates() { return allStates; } NFAState *getStartState() { return startState; } void setStartState(NFAState* const s) { startState = s; addState(startState); } void addFinalState(NFAState *s) { finalStates.insert(s); s->setEnd(true); } void removeFinalState(NFAState *s) { finalStates.erase(s); s->setEnd(false); } void addState(NFAState *s) {allStates.insert(s);} NFAState *mkNewState() { NFAState *newState = new NFAState(); addState(newState); return newState; } NFAState *mkNewFinalState() { NFAState *newFinalState = mkNewState(); addFinalState(newFinalState); return newFinalState; } std::string getWord(NFAState *s, bool &succ); std::string getWord(bool &succ); bool isEmpty(); bool accept(std::string &s); void clear(); bool isDeterministic() {return false;} DFA* determine(); //static NFA* intersection(NFA& fa1, NFA& fa2); ~NFA(); }; class DFA : public FA { private: DFAState* startState; DFAStateSet finalStates; DFAStateSet allStates; public: DFA(): startState(NULL) {}; DFA(DFA *dfaP); DFA(DFA &dfa); DFA(std::string regex); DFA(DFA* dfaP, std::unordered_map<DFAState*, DFAState*>& sMap); DFAStateSet &getFinalStates() { return finalStates; } DFAStateSet &getAllStates() { return allStates; } DFAState *getStartState() { return startState; } void setStartState(DFAState *s) { startState = s; addState(startState);} void addFinalState(DFAState *s) { finalStates.insert(s); s->setEnd(true); } void removeFinalState(DFAState* s) { finalStates.erase(s); s->setEnd(false); } void addState(DFAState *s) { allStates.insert(s); } DFAState *mkNewState() { DFAState *newState = new DFAState(); addState(newState); return newState; } DFAState *mkNewFinalState() { DFAState *newFinalState = mkNewState(); addFinalState(newFinalState); return newFinalState; } std::string getWord(DFAState *s, bool &succ); std::string getWord(bool &succ); bool isEmpty(); bool accept(std::string &s); void clear(); bool isDeterministic() {return true;} static DFA* intersection(DFA& fa1, DFA& fa2); ~DFA(); }; //---------------------------------------------------- class AggregateStateForStr :public DFAState { private: InformationForStr* info; public: AggregateStateForStr() {} AggregateStateForStr(InformationForStr *i) { info = i; } virtual void* getInformation() { return reinterpret_cast<void*>(info); } virtual ~AggregateStateForStr() { delete info; } }; class AggregateStateForReg :public NFAState { private: InformationForReg* info; public: AggregateStateForReg() {} AggregateStateForReg(InformationForReg* i) { info = i; } virtual void* getInformation() { return reinterpret_cast<void*>(info); } virtual ~AggregateStateForReg() { delete info; } }; #endif
[ "chenyan@chenyandeMacBook-Pro.local" ]
chenyan@chenyandeMacBook-Pro.local
b16381118474ad1fbf45a8c281c9d5ddd4c1731d
66ce4862f1de35f0da2cf4c83048859486432cf0
/EditorAPI/TESObject.h
413272700ff4e4d828adbf17f1148c61eade19d3
[]
no_license
stavrossk/Construction-Set-Extender
4e8483d9dd99593d794fef7bf81e4a7695c9aa50
aab85ad206b47e76729939f98428fa927417c1f1
refs/heads/master
2021-01-15T23:58:20.148989
2014-07-23T11:44:41
2014-07-23T11:44:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,490
h
#pragma once #include "TESForm.h" // EditorAPI: TESObject class and its derivatives. // A number of class definitions are directly derived from the COEF API; Credit to JRoush for his comprehensive decoding /* TESObject is the parent for all placeable form classes. Most(all?) TESObjects are connected in a doubly-linked list, maintained by the global data handler. TESObject maintains info on the number of TESObjectREFR that use a form, and a list of cells in which those refs appear. This complements the the normal Cross-Referencing of base forms in the CS. TESBoundObject is a subclass, used for (I think) all objects that can be independently rendered. */ class TESObject; class TESObjectCELL; class TESObjectREFR; // control structure for object list. Seems to be BoundObjects in game, but includes static objects in CS. // 10 class TESObjectListHead { public: // members /*00*/ UInt32 objectCount; /*04*/ TESObject* first; /*08*/ TESObject* last; /*0C*/ UInt32 unkC; // methods void AddObject(TESObject* Object); }; STATIC_ASSERT(sizeof(TESObjectListHead) == 0x10); // 34 class TESObject : public TESForm { public: // members /*24*/ TESObjectListHead* head; /*28*/ void* unkObj28; // for ref counting of loaded models (?) // struct {void* reflist; UInt32 modelUseCount?; BSSimpleList<UInt32> unk; ...?} /*2C*/ TESObject* prev; /*30*/ TESObject* next; }; STATIC_ASSERT(sizeof(TESObject) == 0x34); // size may be as large as 20, but probably is no larger than 08 // 08 ? class TESCellUseList { public: struct CellUseInfo { TESObjectCELL* cell; UInt32 count; }; typedef tList<CellUseInfo> CellUseInfoListT; // members /*00*/ CellUseInfoListT cellUses; }; STATIC_ASSERT(sizeof(TESCellUseList) == 0x08); // 58 class TESBoundObject : public TESObject, public TESCellUseList { public: // members // /*00*/ TESObject // /*34*/ TESCellUseList /*3C*/ Vector3 center; // filled in as requested /*48*/ Vector3 extents; // filled in as requested /*54*/ UInt32 objectRefrCount; // count of TESObjectREFR using this form }; STATIC_ASSERT(sizeof(TESBoundObject) == 0x58); // 58 class TESBoundAnimObject : public TESBoundObject { public: // no additional members }; STATIC_ASSERT(sizeof(TESBoundAnimObject) == 0x58); // 58 class TESBoundTreeObject : public TESBoundObject { public: // no additional members }; STATIC_ASSERT(sizeof(TESBoundTreeObject) == 0x58);
[ "thechaosfactory@gmail.com" ]
thechaosfactory@gmail.com
f8872b5fa58a89960fc7a104ed0199cd2fc88318
d6632e7e34a64247268a8715c873b8d4b0166dab
/sketch_jan20b/sketch_jan20b.ino
2b3fbec3a8f91b89bcbc24a8621e769744322bc5
[]
no_license
urvishajain/Aurdino
150f368a3100a560ae93f49d4b0bff9638aecc71
e9744c5398a948bfe6e7fa96132cdec09ba15ac7
refs/heads/main
2023-02-27T18:57:48.397992
2021-02-04T07:54:36
2021-02-04T07:54:36
335,862,178
0
0
null
null
null
null
UTF-8
C++
false
false
533
ino
int trigpin=8; int echopin=9; long duration,distance; int m1=3,m2=10,m3=6,m4=11; int dly=200; void setup() { pinMode(m1,OUTPUT); pinMode(m2,OUTPUT); pinMode(m3,OUTPUT); pinMode(m4,OUTPUT); Serial.begin(9600); pinMode(trigpin,OUTPUT); pinMode(echopin,INPUT); } void loop() { analogWrite(m1,100); analogWrite(m2,0); analogWrite(m3,120); analogWrite(m4,0); delay(2000); analogWrite(m1,0); analogWrite(m2,120); analogWrite(m3,0); analogWrite(m4,120); delay(2000); }
[ "noreply@github.com" ]
noreply@github.com
0dfa3b82b527d179bb8f6ca96194818aa302e562
4a36e8a7f598bb910a1cef0732702828106d98ca
/Dragon/src/operators/norm/group_norm.cc
8ddded375da17fec488d16b92232e2c1a2498443
[ "BSD-2-Clause" ]
permissive
awesome-archive/Dragon
d5a5e737d63f71ba8b73306051aa9960d48e7447
b35f9320909d07d138c2f6b345a4c24911f7c521
refs/heads/master
2023-08-21T09:07:58.238769
2019-03-20T09:01:37
2019-03-20T09:01:37
177,972,970
0
0
BSD-2-Clause
2020-01-13T03:40:54
2019-03-27T10:41:13
C++
UTF-8
C++
false
false
5,902
cc
#include "core/workspace.h" #include "utils/filler.h" #include "utils/op_kernel.h" #include "utils/math_functions.h" #include "operators/norm/group_norm_op.h" namespace dragon { template <class Context> template <typename Tx, typename Tp> void GroupNormOp<Context>::RunWithType() { TENSOR_FILL_WITH_TYPE(Input(1), vector<int64_t>({ C }), Tp); TENSOR_FILL_WITH_TYPE(Input(2), vector<int64_t>({ C }), Tp); auto* x = Input(0).template data<Tx, Context>(); auto* gamma = Input(1).template data<Tp, Context>(); auto* beta = Input(2).template data<Tp, Context>(); auto* mu = mean->template mutable_data<Tp, Context>(); auto* rsig = var->template mutable_data<Tp, Context>(); auto* s = scale.template mutable_data<Tp, Context>(); auto* b = bias.template mutable_data<Tp, Context>(); auto* y = Output(0)->template mutable_data<Tx, Context>(); // Compute the moments if (data_format == "NCHW") { vector<int> dims = { (int)(N * G), (int)(D * S) }; vector<int> axes = { 1 }; kernel::Moments( 2, dims.data(), 1, axes.data(), x, mu, rsig, ctx()); } else if (data_format == "NHWC") { vector<int> dims = { (int)N, (int)S, (int)G, (int)D }; vector<int> axes = { 1, 3 }; kernel::Moments( 4, dims.data(), 2, axes.data(), x, mu, rsig, ctx()); } math::InvStd(N * G, eps, rsig, rsig, ctx()); kernel::GroupNormForward(N, G, D, S, data_format, x, mu, rsig, gamma, beta, s, b, y, ctx()); } template <class Context> void GroupNormOp<Context>::Reshape() { // Determine the data format int64_t channel_axis = axis; data_format = "NCHW"; if (channel_axis == -1) channel_axis += Input(0).ndim(); if (channel_axis + 1 == Input(0).ndim()) data_format = "NHWC"; if (Input(0).ndim() == 2) data_format = "NCHW"; N = Input(0).dim(0); C = Input(0).dim(channel_axis); S = Input(0).count() / N / C; // InstanceNorm, LayerNorm or GroupNorm ? G = group > 0 ? group : C; D = C / G; // Check the channels and groups CHECK_EQ(C % G, 0) << "\nThe " << C << " channels " << "can not be split into " << G << " groups."; if (G == C && Input(0).ndim() == 2) LOG(WARNING) << "The 2d input will output all zeros."; // Create the shared resources mean = ws()->CreateTensor(mount_name( "gn/mu"))->Reshape({ N * G }); var = ws()->CreateTensor(mount_name( "gn/rsig"))->Reshape({ N * G }); // Reshape scale.Reshape({ N * C }); bias.Reshape({ N * C }); Output(0)->ReshapeLike(Input(0)); } template <class Context> void GroupNormOp<Context>::RunOnDevice() { Reshape(); if (XIsType(Input(0), float)) RunWithType<float, float>(); else if (XIsType(Input(0), float16)) RunWithType<float16, float>(); else LOG(FATAL) << DTypeHelper(Input(0), { "float32", "float16" }); } DEPLOY_CPU(GroupNorm); #ifdef WITH_CUDA DEPLOY_CUDA(GroupNorm); #endif OPERATOR_SCHEMA(GroupNorm) .NumInputs(3).NumOutputs(1); template <class Context> template <typename Tx, typename Tp> void GroupNormGradientOp<Context>::RunWithType() { auto* x = Input(0).template data<Tx, Context>(); auto* mu = mean->template data<Tp, Context>(); auto* rsig = var->template data<Tp, Context>(); auto* gamma = Input(1).template data<Tp, Context>(); auto* dy = Input(-1).template data<Tx, Context>(); auto* ds = dscale.template mutable_data<Tp, Context>(); auto* db = dbias.template mutable_data<Tp, Context>(); auto* dx = Output(0)->template mutable_data<Tx, Context>(); auto* dgamma = Output(1)->template mutable_data<Tp, Context>(); auto* dbeta = Output(2)->template mutable_data<Tp, Context>(); kernel::GroupNormBackward( N, G, D, S, data_format, x, mu, rsig, gamma, dy, ds, db, dx, dgamma, dbeta, ctx()); } template <class Context> void GroupNormGradientOp<Context>::Reshape() { // Determine the data format int64_t channel_axis = axis; data_format = "NCHW"; if (channel_axis == -1) channel_axis += Input(0).ndim(); if (channel_axis + 1 == Input(0).ndim()) data_format = "NHWC"; if (Input(0).ndim() == 2) data_format = "NCHW"; N = Input(0).dim(0); C = Input(0).dim(channel_axis); S = Input(0).count() / N / C; // InstanceNorm, LayerNorm or GroupNorm ? G = group > 0 ? group : C; D = C / G; // Check the channels and groups CHECK_EQ(C % G, 0) << "\nThe " << C << " channels " << "can not be split into " << G << " groups."; if (G == C && Input(0).ndim() == 2) LOG(WARNING) << "The 2d input will output all zeros."; // Get the shared resources mean = ws()->GetTensor(mount_name("gn/mu")); var = ws()->GetTensor(mount_name("gn/rsig")); // Reshape dscale.Reshape({ N * G }); dbias.Reshape({ N * G }); Output(0)->ReshapeLike(Input(0)); // dx Output(1)->Reshape({ C }); // dgamma Output(2)->Reshape({ C }); // dbeta } template <class Context> void GroupNormGradientOp<Context>::RunOnDevice() { Reshape(); if (XIsType(Input(0), float)) RunWithType<float, float>(); else if (XIsType(Input(0), float16)) RunWithType<float16, float>(); else LOG(FATAL) << DTypeHelper(Input(0), { "float32", "float16" }); } DEPLOY_CPU(GroupNormGradient); #ifdef WITH_CUDA DEPLOY_CUDA(GroupNormGradient); #endif OPERATOR_SCHEMA(GroupNormGradient) .NumInputs(3).NumOutputs(3); class GetGroupNormGradient final : public GradientMakerBase { public: GRADIENT_MAKER_CTOR(GetGroupNormGradient); vector<OperatorDef> MakeDefs() override { return SingleDef(def.type() + "Gradient", "", vector<string>({ I(0), I(1), GO(0) }), vector<string>({ GI(0), GI(1), GI(2) })); } }; REGISTER_GRADIENT(GroupNorm, GetGroupNormGradient); } // namespace dragon
[ "ting.pan@seetatech.com" ]
ting.pan@seetatech.com
661cd09b76c1339e81b230ced6942f454a22afcb
2dadfe24e51d3a8ceb94a71cc1f48de4ed0e4b30
/ss/test1/Q_Charprint.cpp
5cdc4340c600b1995fb0e5118c136ecdb50e55d0
[]
no_license
Wasrek/POSN15
12e1ee582e04b21580e230325cc6288e93ae5a04
8fe2999ab0bc3f9b54c485b4643d8630cbb878a8
refs/heads/master
2020-09-06T23:44:11.761136
2020-02-27T08:11:23
2020-02-27T08:11:23
220,591,575
0
0
null
2020-02-27T08:11:24
2019-11-09T04:34:10
C++
UTF-8
C++
false
false
1,323
cpp
/* TASK:Q_Charprint LANG: CPP AUTHOR: Wichada SCHOOL: RYW */ #include<bits/stdc++.h> using namespace std; vector<long long> a[30]; long long ar[30],cnt[30]; char s[300010],ask[300010]; long long fw[300010]; int query(long long a){ long long sum=0,i; for(i=a;i>0;i-=(i&-i)) sum+=fw[i]; return sum; } void update(long long a){ for(int i=a;i<=300000;i+=(i&-i)){ fw[i]++; } } int main() { long long opr,i,len,lena,j,ans=0,ch=0; scanf("%lld",&opr); scanf(" %s",s+1); scanf(" %s",ask+1); len = strlen(s+1); lena = strlen(ask+1); for(i=1;i<=len;i++){ a[s[i]-'a'].push_back(i); } for(i=1;i<=lena;i++){ ar[ask[i]-'a']++; } for(i=0;i<='z'-'a';i++){ if(ar[i]==0)continue; if(a[i].size()<ar[i]){ch=1;break;} for(j=0;j<ar[i];j++){ ans+=a[i][j]; } } if(ch){printf("-1\n");return 0;} if(opr==0){printf("%lld\n",ans);return 0;} for(i=1;i<=lena;i++){ cnt[ask[i]-'a']++; // printf("%d\n",cnt[ask[i]-'a']); ans-=query(a[ask[i]-'a'][cnt[ask[i]-'a']-1]); update(a[ask[i]-'a'][cnt[ask[i]-'a']-1]); } printf("%lld\n",ans); return 0; } /* 1 aabceddectfghaat catbat */
[ "noreply@github.com" ]
noreply@github.com
c5f6305189d4cc1b306f253415236c4e2df945bc
20922b88278cbc3595ee9e748858e7f5177917f8
/Teclado_numerico/GeneratedFiles/Debug/moc_teclado_numerico.cpp
9133181b5e93904bd383555d882744b6c79e011f
[]
no_license
Griman87/Teclado_Numerico
d4168f82d7cb010df311376d3d0e506b84ffb463
0c4f750ca6ab98568bd83f96f21473bf07315655
refs/heads/master
2020-06-18T19:03:01.439469
2019-07-11T14:35:10
2019-07-11T14:35:10
196,411,375
0
0
null
null
null
null
UTF-8
C++
false
false
2,950
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'teclado_numerico.h' ** ** Created: Thu 27. Mar 16:29:02 2014 ** by: The Qt Meta Object Compiler version 63 (Qt 4.8.4) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "StdAfx.h" #include "../../teclado_numerico.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'teclado_numerico.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 63 #error "This file was generated using the moc from 4.8.4. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_Teclado_numerico[] = { // content: 6, // revision 0, // classname 0, 0, // classinfo 1, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: signature, parameters, type, tag, flags 18, 17, 17, 17, 0x0a, 0 // eod }; static const char qt_meta_stringdata_Teclado_numerico[] = { "Teclado_numerico\0\0on_Boton_clicked()\0" }; void Teclado_numerico::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { Q_ASSERT(staticMetaObject.cast(_o)); Teclado_numerico *_t = static_cast<Teclado_numerico *>(_o); switch (_id) { case 0: _t->on_Boton_clicked(); break; default: ; } } Q_UNUSED(_a); } const QMetaObjectExtraData Teclado_numerico::staticMetaObjectExtraData = { 0, qt_static_metacall }; const QMetaObject Teclado_numerico::staticMetaObject = { { &QMainWindow::staticMetaObject, qt_meta_stringdata_Teclado_numerico, qt_meta_data_Teclado_numerico, &staticMetaObjectExtraData } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &Teclado_numerico::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *Teclado_numerico::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *Teclado_numerico::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_Teclado_numerico)) return static_cast<void*>(const_cast< Teclado_numerico*>(this)); return QMainWindow::qt_metacast(_clname); } int Teclado_numerico::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QMainWindow::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 1) qt_static_metacall(this, _c, _id, _a); _id -= 1; } return _id; } QT_END_MOC_NAMESPACE
[ "gorka.talleda@elytt.com" ]
gorka.talleda@elytt.com
b6bcc3d814c3f983f858d1138c3d71e59afcd5ce
452e86d97c6ad352cc559d2abe5106f65faa60d6
/c/src/judge.cpp
4860c13ab3411643973154b501b4d92877263390
[]
no_license
BiwefC/FastGomoku
ecc94a3677a9e524cfca43b0db73fa63342e537c
3e0adccaa1c339e73419e6442edbe4524c66dcd7
refs/heads/master
2020-04-10T03:34:50.605540
2018-12-20T09:27:09
2018-12-20T09:27:09
160,774,161
0
1
null
null
null
null
UTF-8
C++
false
false
21,526
cpp
#include "judge.hpp" using namespace gomoku; Judge::Judge() {} Color Judge::do_judge(Board &table, int x, int y) { Color color_last = table[x][y]; if (color_last == COLOR_WHITE){ if (fivelink(table, COLOR_WHITE)) { // 白棋五连 return COLOR_WHITE; } } else if (color_last == COLOR_BLACK) { if (longlink(table)) { // 黑棋长连禁手 return COLOR_WHITE; } else if (fivelink(table, COLOR_BLACK)) { // 黑棋五连 return COLOR_BLACK; } else if (huosan(table, x, y) > 1) { // 黑棋33禁手 return COLOR_WHITE; } else if (si(table, x, y) > 1) { // 黑棋44禁手 return COLOR_WHITE; } } return COLOR_NONE; } // 判断长连 bool Judge::longlink(Board &table) { int i, j ; for( i = 0 ; i < 15 ; i++ ){ //判断黑棋横向长连 for( j = 0 ; j < 10 ; j++ ){ if( table[i][j] == COLOR_BLACK && table[i][j+1] == COLOR_BLACK && table[i][j+2] == COLOR_BLACK && table[i][j+3] == COLOR_BLACK && table[i][j+4] == COLOR_BLACK && table[i][j+5] == COLOR_BLACK){ return 1 ; } } } for( i = 0 ; i < 10 ; i++ ){ //判断黑棋纵向长连 for( j = 0 ; j < 15 ; j++ ){ if( table[i][j] == COLOR_BLACK && table[i+1][j] == COLOR_BLACK && table[i+2][j] == COLOR_BLACK && table[i+3][j] == COLOR_BLACK && table[i+4][j] == COLOR_BLACK && table[i+5][j] == COLOR_BLACK){ return 1 ; } } } for( i = 0 ; i < 10 ; i++ ){ //判断黑棋“\”向长连 for( j = 0 ; j < 10 ; j++ ){ if( table[i][j] == COLOR_BLACK && table[i+1][j+1] == COLOR_BLACK && table[i+2][j+2] == COLOR_BLACK && table[i+3][j+3] == COLOR_BLACK && table[i+4][j+4] == COLOR_BLACK && table[i+5][j+5] == COLOR_BLACK){ return 1 ; } } } for( i = 0 ; i < 10 ; i++ ){ //判断黑棋“/”向长连 for( j = 5 ; j < 15 ; j++ ){ if( table[i][j] == COLOR_BLACK && table[i+1][j-1] == COLOR_BLACK && table[i+2][j-2] == COLOR_BLACK && table[i+3][j-3] == COLOR_BLACK && table[i+4][j-4] == COLOR_BLACK && table[i+5][j-5] == COLOR_BLACK){ return 1 ; } } } return 0 ; } // 判断五连 int Judge::fivelink(Board &table, Color color) { int i, j ; //判断横向五连 for( i = 0 ; i < 15 ; i++ ){ for( j = 0 ; j < 11 ; j++ ){ if( table[i][j] == color && table[i][j+1] == color && table[i][j+2] == color && table[i][j+3] == color && table[i][j+4] == color){ return 1 ; } } } //判断纵向五连 for( i = 0 ; i < 11 ; i++ ){ for( j = 0 ; j < 15 ; j++ ){ if( table[i][j] == color && table[i+1][j] == color && table[i+2][j] == color && table[i+3][j] == color && table[i+4][j] == color){ return 1 ; } } } //判断“\”向五连 for( i = 0 ; i < 11 ; i++ ){ for( j = 0 ; j < 11 ; j++ ){ if( table[i][j] == color && table[i+1][j+1] == color && table[i+2][j+2] == color && table[i+3][j+3] == color && table[i+4][j+4] == color){ return 1 ; } } } //判断“/”向五连 for( i = 0 ; i < 11 ; i++ ){ for( j = 4 ; j < 15 ; j++ ){ if( table[i][j] == color && table[i+1][j-1] == color && table[i+2][j-2] == color && table[i+3][j-3] == color && table[i+4][j-4] == color){ return 1 ; } } } return 0 ; } // 判断四(包括冲四、活四),并返回棋盘中“四”的个数 int Judge::si(Board &table, char line, char column) { siArr1.clear(); siArr2.clear(); siArr3.clear(); siArr4.clear(); int i , j , pi = 22 , pj = 22 , count = 0 ; for( i = 0 ; i < 15 ; i++ ){ //判断横向四 for( j = 0 ; j < 11 ; j++ ){ if((i != pi || j != pj+1 ) && table[i][j] != COLOR_WHITE && table[i][j+1] != COLOR_WHITE && table[i][j+2] != COLOR_WHITE && table[i][j+3] != COLOR_WHITE && table[i][j+4] != COLOR_WHITE && ( table[i][j] + table[i][j+1] + table[i][j+2] + table[i][j+3] + table[i][j+4] ) == 4*COLOR_BLACK ){ //count ++ ; pi = i ; pj = j ; //cout << "i j " << i << " " << j << endl; static p_tmp temp = { 22, 22 }; p_tmp p1 = { i, j }; p_tmp p2 = { i, j + 1 }; p_tmp p3 = { i, j + 2 }; p_tmp p4 = { i, j + 3 }; p_tmp p5 = { i, j + 4 }; //if (temp.i != p1.i && temp.j != p1.j) if (1) { if (table[i][j] != 0) siArr1.push_back(p1); if (table[i][j + 1] != 0) siArr1.push_back(p2); if (table[i][j + 2] != 0) siArr1.push_back(p3); if (table[i][j + 3] != 0) siArr1.push_back(p4); if (table[i][j + 4] != 0) siArr1.push_back(p5); } temp = p1; } } } //test for (unsigned int i = 0; i < siArr1.size(); i++) { //cout << "Si Arr1 " << siArr1[i].i << " " << siArr1[i].j << endl; } //----------------------------------------------------------------------------------- pi = 22 ; pj = 22 ; for( i = 0 ; i < 11 ; i++ ){ //判断纵向四 for( j = 0 ; j < 15 ; j++ ){ if((i != pi+1 || j != pj ) && table[i][j] != COLOR_WHITE && table[i+1][j] != COLOR_WHITE && table[i+2][j] != COLOR_WHITE && table[i+3][j] != COLOR_WHITE && table[i+4][j] != COLOR_WHITE && ( table[i][j] + table[i+1][j] + table[i+2][j] + table[i+3][j] + table[i+4][j] ) == 4*COLOR_BLACK ){ //count ++ ; pi = i ; pj = j ; static p_tmp temp = { 22, 22 }; p_tmp p1 = { i , j }; p_tmp p2 = { i + 1, j }; p_tmp p3 = { i + 2, j }; p_tmp p4 = { i + 3, j }; p_tmp p5 = { i + 4, j }; //if (temp.i != p1.i && temp.j != p1.j) if (1) { if (table[i][j] != 0) siArr2.push_back(p1); if (table[i + 1][j] != 0) siArr2.push_back(p2); if (table[i + 2][j] != 0) siArr2.push_back(p3); if (table[i + 3][j] != 0) siArr2.push_back(p4); if (table[i + 4][j] != 0) siArr2.push_back(p5); } temp = p1; } } } //test for (unsigned int i = 0; i < siArr2.size(); i++) { //cout << "Si Arr2 " << siArr2[i].i << " " << siArr2[i].j << endl; } //----------------------------------------------------------------------------------- pi = 22 ; pj = 22 ; for( i = 0 ; i < 11 ; i++ ){ //判断“\”向四 for( j = 0 ; j < 11 ; j++ ){ if((i != pi+1 || j != pj+1 ) && table[i][j] != COLOR_WHITE && table[i+1][j+1] != COLOR_WHITE && table[i+2][j+2] != COLOR_WHITE && table[i+3][j+3] != COLOR_WHITE && table[i+4][j+4] != COLOR_WHITE && ( table[i][j] + table[i+1][j+1] + table[i+2][j+2] + table[i+3][j+3] + table[i+4][j+4] ) == 4*COLOR_BLACK ){ //count ++ ; pi = i ; pj = j ; static p_tmp temp = { 22, 22 }; p_tmp p1 = { i + 0, j + 0 }; p_tmp p2 = { i + 1, j + 1 }; p_tmp p3 = { i + 2, j + 2 }; p_tmp p4 = { i + 3, j + 3 }; p_tmp p5 = { i + 4, j + 4 }; //if (temp.i != p1.i && temp.j != p1.j) if (1) { if (table[i + 0][j + 0] != 0) siArr3.push_back(p1); if (table[i + 1][j + 1] != 0) siArr3.push_back(p2); if (table[i + 2][j + 2] != 0) siArr3.push_back(p3); if (table[i + 3][j + 3] != 0) siArr3.push_back(p4); if (table[i + 4][j + 4] != 0) siArr3.push_back(p5); } temp = p1; } } } //test for (unsigned int i = 0; i < siArr3.size(); i++) { //cout << "Si Arr3 " << siArr3[i].i << " " << siArr3[i].j << endl; } //----------------------------------------------------------------------------------- pi = 22 ; pj = 22 ; for( i = 0 ; i < 11 ; i++ ){ //判断“/”向四 for( j = 4 ; j < 15 ; j++ ){ if((i != pi+1 || j != pj-1 ) && table[i][j] != COLOR_WHITE && table[i+1][j-1] != COLOR_WHITE && table[i+2][j-2] != COLOR_WHITE && table[i+3][j-3] != COLOR_WHITE && table[i+4][j-4] != COLOR_WHITE && ( table[i][j] + table[i+1][j-1] + table[i+2][j-2] + table[i+3][j-3] + table[i+4][j-4] ) == 4*COLOR_BLACK ){ //count ++ ; pi = i ; pj = j ; static p_tmp temp = { 22, 22 }; p_tmp p1 = { i + 0, j - 0 }; p_tmp p2 = { i + 1, j - 1 }; p_tmp p3 = { i + 2, j - 2 }; p_tmp p4 = { i + 3, j - 3 }; p_tmp p5 = { i + 4, j - 4 }; //if (temp.i != p1.i && temp.j != p1.j) if (1) { if (table[i + 0][j - 0] != 0) siArr4.push_back(p1); if (table[i + 1][j - 1] != 0) siArr4.push_back(p2); if (table[i + 2][j - 2] != 0) siArr4.push_back(p3); if (table[i + 3][j - 3] != 0) siArr4.push_back(p4); if (table[i + 4][j - 4] != 0) siArr4.push_back(p5); } temp = p1; } } } //test for (unsigned int i = 0; i < siArr4.size(); i++) { //cout << "Si Arr4 " << siArr4[i].i << " " << siArr4[i].j << endl; } //----------------------------------------------------------------------------------- //judge four four forbidden for (unsigned int i = 0; i < siArr1.size(); i++) { p_tmp compare_elem = siArr1[i]; for (unsigned int j = 0; j < siArr2.size(); j++) { if (compare_elem.i == siArr2[j].i && compare_elem.j == siArr2[j].j) if (compare_elem.i == line && compare_elem.j == column) return 2; } for (unsigned int j = 0; j < siArr3.size(); j++) { if (compare_elem.i == siArr3[j].i && compare_elem.j == siArr3[j].j) if (compare_elem.i == line && compare_elem.j == column) return 2; } for (unsigned int j = 0; j < siArr4.size(); j++) { if (compare_elem.i == siArr4[j].i && compare_elem.j == siArr4[j].j) if (compare_elem.i == line && compare_elem.j == column) return 2; } } for (unsigned int i = 0; i < siArr2.size(); i++) { p_tmp compare_elem = siArr2[i]; for (unsigned int j = 0; j < siArr3.size(); j++) { if (compare_elem.i == siArr3[j].i && compare_elem.j == siArr3[j].j) if (compare_elem.i == line && compare_elem.j == column) return 2; } for (unsigned int j = 0; j < siArr4.size(); j++) { if (compare_elem.i == siArr4[j].i && compare_elem.j == siArr4[j].j) if (compare_elem.i == line && compare_elem.j == column) return 2; } } for (unsigned int i = 0; i < siArr3.size(); i++) { p_tmp compare_elem = siArr3[i]; for (unsigned int j = 0; j < siArr4.size(); j++) { if (compare_elem.i == siArr4[j].i && compare_elem.j == siArr4[j].j) if (compare_elem.i == line && compare_elem.j == column) return 2; } } count = 0; return count ; } // 判断“活三”,并返回棋盘中“活三”的个数 int Judge::huosan(Board &table, char line, char column) { sanArr1.clear(); sanArr2.clear(); sanArr3.clear(); sanArr4.clear(); int i, j , pi=22 , pj=22 , count = 0 ; for( i = 0 ; i < 15 ; i++ ){ //判断横向“活三” for( j = 0 ; j < 10 ; j++ ){ if ((i != pi || j != pj + 1) && table[i][j] == 0 && table[i][j + 1] != COLOR_WHITE && table[i][j + 2] != COLOR_WHITE && table[i][j + 3] != COLOR_WHITE && table[i][j + 4] != COLOR_WHITE && table[i][j + 5] == 0 && (table[i][j + 1] + table[i][j + 2] + table[i][j + 3] + table[i][j + 4]) == 3 * COLOR_BLACK){ //count ++ ; pi = i ; pj = j ; static p_tmp temp = { 22, 22 }; p_tmp p1 = { i, j + 1}; p_tmp p2 = { i, j + 2}; p_tmp p3 = { i, j + 3}; p_tmp p4 = { i, j + 4}; //if (temp.i != p1.i && temp.j != p1.j) if (1) { if (table[i][j + 1] != 0) //忽略[0] 和 [5] ,因为必须是0 sanArr1.push_back(p1); if (table[i][j + 2] != 0) sanArr1.push_back(p2); if (table[i][j + 3] != 0) sanArr1.push_back(p3); if (table[i][j + 4] != 0) sanArr1.push_back(p4); } temp = p1; } } } //test for (unsigned int i = 0; i < sanArr1.size(); i++) { //cout << "San Arr1 " << sanArr1[i].i << " " << sanArr1[i].j << endl; } //----------------------------------------------------------------------------------- pi = 22 ; pj = 22 ; for( i = 0 ; i < 10 ; i++ ){ //判断纵向“活三” for( j = 0 ; j < 15 ; j++ ){ if ((i != pi + 1 || j != pj) && table[i][j] == 0 && table[i + 1][j] != COLOR_WHITE && table[i + 2][j] != COLOR_WHITE && table[i + 3][j] != COLOR_WHITE && table[i + 4][j] != COLOR_WHITE && table[i + 5][j] == 0 && (table[i + 1][j] + table[i + 2][j] + table[i + 3][j] + table[i + 4][j]) == 3 * COLOR_BLACK){ //count ++ ; pi = i ; pj = j ; static p_tmp temp = { 22, 22 }; p_tmp p1 = { i + 1, j }; p_tmp p2 = { i + 2, j }; p_tmp p3 = { i + 3, j }; p_tmp p4 = { i + 4, j }; //if (temp.i != p1.i && temp.j != p1.j) if (1) { if (table[i + 1][j] != 0) sanArr2.push_back(p1); if (table[i + 2][j] != 0) sanArr2.push_back(p2); if (table[i + 3][j] != 0) sanArr2.push_back(p3); if (table[i + 4][j] != 0) sanArr2.push_back(p4); } temp = p1; } } } //test for (unsigned int i = 0; i < sanArr2.size(); i++) { //cout << "San Arr2 " << sanArr2[i].i << " " << sanArr2[i].j << endl; } //----------------------------------------------------------------------------------- pi = 22 ; pj = 22 ; for( i = 0 ; i < 10 ; i++ ){ //判断“\”向“活三” for( j = 0 ; j < 10 ; j++ ){ if ((i != pi + 1 || j != pj + 1) && table[i][j] == 0 && table[i + 1][j + 1] != COLOR_WHITE && table[i + 2][j + 2] != COLOR_WHITE && table[i + 3][j + 3] != COLOR_WHITE && table[i + 4][j + 4] != COLOR_WHITE && table[i + 5][j + 5] == 0 && (table[i + 1][j + 1] + table[i + 2][j + 2] + table[i + 3][j + 3] + table[i + 4][j + 4]) == 3 * COLOR_BLACK){ //count ++ ; pi = i ; pj = j ; static p_tmp temp = { 22, 22 }; p_tmp p1 = { i + 1, j + 1}; p_tmp p2 = { i + 2, j + 2}; p_tmp p3 = { i + 3, j + 3}; p_tmp p4 = { i + 4, j + 4}; //if (temp.i != p1.i && temp.j != p1.j) if (1) { if (table[i + 1][j + 1] != 0) sanArr3.push_back(p1); if (table[i + 2][j + 2] != 0) sanArr3.push_back(p2); if (table[i + 3][j + 3] != 0) sanArr3.push_back(p3); if (table[i + 4][j + 4] != 0) sanArr3.push_back(p4); } temp = p1; } } } //test for (unsigned int i = 0; i < sanArr3.size(); i++) { //cout << "San Arr3 " << sanArr3[i].i << " " << sanArr3[i].j << endl; } //----------------------------------------------------------------------------------- pi = 22 ; pj = 22 ; for( i = 0 ; i < 10 ; i++ ){ //判断“/”向“活三” for( j = 5 ; j < 15 ; j++ ){ if ((i != pi + 1 || j != pj - 1) && table[i][j] == 0 && table[i + 1][j - 1] != COLOR_WHITE && table[i + 2][j - 2] != COLOR_WHITE && table[i + 3][j - 3] != COLOR_WHITE && table[i + 4][j - 4] != COLOR_WHITE && table[i + 5][j - 5] == 0 && (table[i + 1][j - 1] + table[i + 2][j - 2] + table[i + 3][j - 3] + table[i + 4][j - 4]) == 3 * COLOR_BLACK){ //count ++ ; pi = i ; pj = j ; static p_tmp temp = { 22, 22 }; p_tmp p1 = { i + 1, j - 1 }; p_tmp p2 = { i + 2, j - 2 }; p_tmp p3 = { i + 3, j - 3 }; p_tmp p4 = { i + 4, j - 4 }; //if (temp.i != p1.i && temp.j != p1.j) if (1) { if (table[i + 1][j - 1] != 0) sanArr4.push_back(p1); if (table[i + 2][j - 2] != 0) sanArr4.push_back(p2); if (table[i + 3][j - 3] != 0) sanArr4.push_back(p3); if (table[i + 4][j - 4] != 0) sanArr4.push_back(p4); } temp = p1; } } } //test for (unsigned int i = 0; i < sanArr4.size(); i++) { //cout << "San Arr4 " << sanArr4[i].i << " " << sanArr4[i].j << endl; } //----------------------------------------------------------------------------------- //judge three three forbidden for (unsigned int i = 0; i < sanArr1.size(); i++) { p_tmp compare_elem = sanArr1[i]; for (unsigned int j = 0; j < sanArr2.size(); j++) { if (compare_elem.i == sanArr2[j].i && compare_elem.j == sanArr2[j].j) if (compare_elem.i == line && compare_elem.j == column) return 2; } for (unsigned int j = 0; j < sanArr3.size(); j++) { if (compare_elem.i == sanArr3[j].i && compare_elem.j == sanArr3[j].j) if (compare_elem.i == line && compare_elem.j == column) return 2; } for (unsigned int j = 0; j < sanArr4.size(); j++) { if (compare_elem.i == sanArr4[j].i && compare_elem.j == sanArr4[j].j) if (compare_elem.i == line && compare_elem.j == column) return 2; } } for (unsigned int i = 0; i < sanArr2.size(); i++) { p_tmp compare_elem = sanArr2[i]; for (unsigned int j = 0; j < sanArr3.size(); j++) { if (compare_elem.i == sanArr3[j].i && compare_elem.j == sanArr3[j].j) if (compare_elem.i == line && compare_elem.j == column) return 2; } for (unsigned int j = 0; j < sanArr4.size(); j++) { if (compare_elem.i == sanArr4[j].i && compare_elem.j == sanArr4[j].j) if (compare_elem.i == line && compare_elem.j == column) return 2; } } for (unsigned int i = 0; i < sanArr3.size(); i++) { p_tmp compare_elem = sanArr3[i]; for (unsigned int j = 0; j < sanArr4.size(); j++) { if (compare_elem.i == sanArr4[j].i && compare_elem.j == sanArr4[j].j) if (compare_elem.i == line && compare_elem.j == column) return 2; } } count = 0; return count ; }
[ "chw1996019@163.com" ]
chw1996019@163.com
3f25b79c4a0358a2309d24ee81a0204f66975248
ec7002ba79e9f38ab71ba19b5a3e1503a61d91d6
/include/godot_cpp/PackedDataContainerRef.hpp
5670e671cd7f44a92b62f4784e8275be5e2f9cf3
[]
no_license
triptych/Godot-Webrtc-test-project
a7e2615e098d6c1f329ed16c3b0c6414b0cb6070
0a7aa5e8b386a1a397ecde23689ad8ce7d87ae5c
refs/heads/master
2020-05-02T09:17:45.170566
2018-08-07T06:49:23
2018-08-07T06:49:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
656
hpp
#ifndef PACKEDDATACONTAINERREF_H #define PACKEDDATACONTAINERREF_H #if defined(_WIN32) && defined(_GD_CPP_BINDING_IMPL) # define GD_CPP_BINDING_API __declspec(dllexport) #elif defined(_WIN32) # define GD_CPP_BINDING_API __declspec(dllimport) #else # define GD_CPP_BINDING_API #endif #include "core/CoreTypes.hpp" #include <godot.h> #include "Reference.hpp" namespace godot { class GD_CPP_BINDING_API PackedDataContainerRef : public Reference { public: void _init(); int size() const; void _iter_init(const Array arg0); void _iter_get(const Variant arg0); void _iter_next(const Array arg0); bool _is_dictionary() const; }; } #endif
[ "bmicmak@gmail.com" ]
bmicmak@gmail.com
d48d0e4afddb1d46565e42ee4aa795db19525f07
e76e4b2855e9d0cd8b71e04a979bb6118f465d3f
/lib/tanklib/tanklib/TankGame.h
9d5b60c838858e5923c3119be940c4a9c6633780
[]
no_license
fcoulombe/tank
92de0969e62d9604cc4b2fee7d75d14e0c70c325
f0c7edbe40899dba4a7ea9f2f14d0af492424104
refs/heads/master
2020-12-24T13:28:32.668557
2012-10-26T20:11:02
2012-10-26T20:11:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,954
h
/* * Copyright (C) 2011 by Francois Coulombe * * 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. */ #pragma once #include "tanklib/BaseApplication.h" #include "tanklib/Actor.h" #include "tanklib/SkyBox.h" #include "tanklib/Terrain.h" namespace tank { class TankGame : public BaseApplication { public: virtual ~TankGame(void); TankGame(void); protected: virtual void createScene(void); virtual void createFrameListener(void); virtual bool frameRenderingQueued(const Ogre::FrameEvent &evt); // OIS::KeyListener virtual bool keyPressed( const OIS::KeyEvent &arg ); virtual bool keyReleased( const OIS::KeyEvent &arg ); // OIS::MouseListener /*virtual bool mouseMoved( const OIS::MouseEvent &arg ); virtual bool mousePressed( const OIS::MouseEvent &arg, OIS::MouseButtonID id ); virtual bool mouseReleased( const OIS::MouseEvent &arg, OIS::MouseButtonID id ); */ Actor *mActor; Terrain *mTerrain; SkyBox *mSkyBox; }; }
[ "fcoulombe@silentfalls.org" ]
fcoulombe@silentfalls.org
1df5747de66f3473a65ffc0dd9d98ec669f2a31f
49a814e0a2a5aa3f91936e946c2029575aa975f2
/EP/HybridInheritance.cpp
0e723dec09904a6bb868a8acb8231b36a109495c
[]
no_license
krishna-somwanshi/CPP
77ed18a1898b8197982bd9541788f3047a378e5b
c7fca6ab331298b8163f5090c9d58b751f84d183
refs/heads/main
2023-02-15T01:07:30.444082
2021-01-14T18:06:31
2021-01-14T18:06:31
329,632,542
0
0
null
null
null
null
UTF-8
C++
false
false
400
cpp
#include<iostream> using namespace std; class base1 { public: int a; }; class drv1:virtual public base1 { public: int b; }; class drv2:virtual public base1 { public: int c; }; class drv3:public drv1, public drv2 { public: int d; }; int main() { drv3 obj; obj.a=10; obj.c=20; obj.d=30; cout<<obj.a; cout<<obj.c; cout<<obj.d; return 0; }
[ "noreply@github.com" ]
noreply@github.com
f08e83670dd7b4b0fc450e2e798fea67d38f3569
41a12517775c8b1688ae817381eb217063446202
/Toph/correct_the_sieve.cpp
81fe28b007fed4e323afc14132877d5da33d4335
[]
no_license
AbdulHamidRumman/Problem-Solving
d5319d72151b77164ae4e69c08f1830fd063cb21
47608d33ace31b9982f21595eb8031a5cb00b654
refs/heads/master
2021-05-23T17:11:51.132540
2020-04-06T06:37:54
2020-04-06T06:37:54
253,394,274
0
0
null
null
null
null
UTF-8
C++
false
false
761
cpp
#include <bits/stdc++.h> using namespace std; bool mark[1000005]; void sieve() { int i,j,limit = sqrt(1000000*1.0)+1; mark[0] = true; mark[1] = true; for(i=4;i<= 1000000;i+=2) mark[i] = true; for(i=3;(i*i)<= 1000000;i+=2) { if(!mark[i]) { if(i<=limit) { for(j=(i*i);j<= 1000000;j+=i+i) mark[j] = true; } } } return; } int main() { sieve(); int N,x; scanf(" %d",&N); while(N--) { scanf("%d",&x); if(!mark[x]) printf("%d is a prime number.\n",x); else printf("%d is not a prime number.\n",x); } return 0; }
[ "noreply@github.com" ]
noreply@github.com
644c3752af3db05d7ef123bb79b93990cc5cccc8
3fa089d3acc366d13d7d548d5bc83607cd0f9f59
/src/leveldb/util/hash.h
7ab3ae7cb3d6fac996f6398e3236869c74595243
[ "MIT", "BSD-3-Clause", "LicenseRef-scancode-generic-cla" ]
permissive
graventi/Seci
4a3d03981bed98e89528a45e6aebe7cd0066fc89
2266e4a3d7c810a576aba63d0a756621537a9ef0
refs/heads/master
2020-03-30T02:59:14.758201
2018-08-22T03:26:57
2018-08-22T03:26:57
150,662,069
0
0
NOASSERTION
2018-09-28T00:12:57
2018-09-28T00:12:56
null
UTF-8
C++
false
false
525
h
// Copyright (c) 2011 The LevelDB Authors. All rights reserved. // Use of this source code is governed by a SECI-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. // // Simple hash function used for internal data structures #ifndef STORAGE_LEVELDB_UTIL_HASH_H_ #define STORAGE_LEVELDB_UTIL_HASH_H_ #include <stddef.h> #include <stdint.h> namespace leveldb { extern uint32_t Hash(const char* data, size_t n, uint32_t seed); } #endif // STORAGE_LEVELDB_UTIL_HASH_H_
[ "37882828+Hamrex@users.noreply.github.com" ]
37882828+Hamrex@users.noreply.github.com
fa68e0cf8f5f90a8bfe0ad3911e5829dcf54ac2a
df6950c85e2a204cd5284e716352000b9b3cffe3
/Mazegame++/main.cpp
2e442ce56ee5cd728f07e1d9b4cad6566cbd05f5
[]
no_license
peteksu/internshipHomeworks
fbe9833105bde6dbda4f8792cfbb1baa548d3102
4533689acf796c8d89d882e3731a007f6d6eda2a
refs/heads/main
2023-07-09T13:05:52.860806
2021-08-12T12:50:13
2021-08-12T12:50:13
395,313,005
0
0
null
null
null
null
UTF-8
C++
false
false
8,225
cpp
#include <iostream> #include <conio.h> #include <stdlib.h> #include <process.h> #include <windows.h> #include <fstream> #define KEY_UP 72 #define KEY_DOWN 80 #define KEY_LEFT 75 #define KEY_RIGHT 77 using namespace std; const char wall = '#'; const char path = ' '; const char start = 'S'; const char finish = 'F'; const char maze[20][20]={{wall,start,wall,wall,wall,wall,wall,wall,wall,wall,wall,wall,wall,wall,wall,wall,wall,wall,wall,wall}, {wall,path,path,path,path,path,path,path,path,wall,wall,path,path,path,path,path,path,path,path,wall}, {wall,wall,path,wall,wall,path,wall,wall,path,wall,wall,path,wall,wall,wall,path,wall,wall,path,wall}, {wall,wall,path,path,wall,path,wall,wall,path,wall,wall,path,wall,wall,wall,path,wall,wall,path,wall}, {wall,wall,wall,path,wall,path,wall,wall,path,path,path,path,path,path,path,path,wall,wall,path,wall}, {wall,wall,wall,path,path,path,path,path,path,wall,wall,wall,wall,path,wall,path,wall,wall,path,wall}, {wall,wall,wall,path,wall,wall,wall,wall,path,wall,wall,wall,wall,path,wall,path,wall,wall,path,wall}, {wall,wall,wall,path,wall,wall,wall,wall,path,wall,wall,wall,wall,path,wall,path,wall,wall,path,wall}, {wall,path,path,path,path,path,path,path,path,path,path,path,path,path,wall,path,wall,wall,path,wall}, {wall,wall,wall,path,wall,wall,wall,wall,wall,wall,wall,path,wall,path,path,path,path,path,path,wall}, {wall,wall,wall,path,wall,wall,wall,wall,path,wall,wall,path,wall,wall,path,wall,wall,path,wall,wall}, {wall,wall,wall,path,wall,wall,wall,wall,path,wall,wall,path,wall,wall,path,wall,wall,path,wall,wall}, {wall,path,path,path,path,path,path,path,path,path,path,path,path,path,path,wall,wall,path,wall,wall}, {wall,path,wall,path,wall,wall,path,wall,wall,wall,wall,path,wall,wall,path,wall,wall,path,wall,wall}, {wall,path,wall,path,wall,wall,path,wall,wall,wall,wall,path,wall,wall,path,wall,wall,path,wall,wall}, {wall,path,wall,wall,wall,wall,path,wall,wall,wall,wall,path,wall,wall,path,wall,wall,path,wall,wall}, {wall,path,wall,path,path,path,path,path,path,path,path,path,path,path,path,path,path,path,path,wall}, {wall,path,wall,path,wall,wall,wall,path,wall,wall,path,wall,wall,path,wall,wall,path,wall,wall,wall}, {wall,path,path,path,wall,wall,wall,path,path,path,path,wall,wall,path,wall,wall,path,path,path,finish}, {wall,wall,wall,wall,wall,wall,wall,wall,wall,wall,wall,wall,wall,wall,wall,wall,wall,wall,wall,wall} }; void ClearConsole(){ system("CLS"); } void PlayersInputHandle(char moveInput, char up, char down, char right, char left, int &positionX, int &positionY){ int mazeSize = sizeof(maze)/sizeof(maze[0]); moveInput=getch(); if(moveInput == up || moveInput == KEY_UP){ if( positionY-1 >= 0 ){ if(maze[positionY-1][positionX] != wall){ positionY--; } } } if(moveInput == down || moveInput == KEY_DOWN){ if( positionY+1 <= mazeSize-1 ){ if(maze[positionY+1][positionX] != wall){ positionY++; } } } if(moveInput == right || moveInput == KEY_RIGHT){ if( positionX+1 <= mazeSize-1 ){ if(maze[positionY][positionX+1] != wall){ positionX++; } } } if(moveInput == left || moveInput == KEY_LEFT){ if( positionX-1 >= 0 ){ if(maze[positionY][positionX-1] != wall){ positionX--; } } } } void DisplayMaze(int &positionX, int &positionY){ char Player = 'P'; int mazeSize = sizeof(maze)/sizeof(maze[0]); for(int i=0;i<mazeSize;i++){ for(int j=0;j<mazeSize;j++){ if(j==positionX && i==positionY){ cout<<Player<<" "; continue; } cout<<maze[i][j]<<" "; } cout<<"\n"; } } bool isGameFinish(int &positionX, int &positionY){ if(positionX==19 && positionY ==18){ return true; } return false; } char settings(char &upKey, char &downKey, char &rightKey, char &leftKey ){ cout<<"Choose a key to move up:\n"; cin>>upKey; cout<<"Choose a key to move down:\n"; cin>>downKey; cout<<"Choose a key to move right:\n"; cin>>rightKey; cout<<"Choose a key to move left:\n"; cin>>leftKey; return upKey, downKey, rightKey, leftKey; } void gameInformation(){ cout<<"Hello player! This is a maze game.\n"; cout<<" S: Start Point\n #: Wall\n F: Finish Point\n P: Player\n"; cout<<"You can use the arrow keys or the arrow keys of your choice on the keyboard to move the player.\n"; cout<<"You can set the keys you want to use from the settings option.\n"; cout<<"You must remember that the player cannot pass through walls!\n"; cout<<"If you can reach the finish point, you will have finished the game.\n"; cout<<"Don't forget, if your number of moves exceeds 45, you will lose the game!GOOD LUCK!\n\n"; } void menu(int &selection){ cout<<"------------MENU------------\n"; cout<<"Press 1 for settings.\n"; cout<<"Press 2 for information about the game.\n"; cout<<"Press 3 to play the game.\n"; cout<<"Press 4 to go back to menu.\n"; cout<<"Press 5 to see last scores.\n"; cout<<"Press 0 to exit!\n"; cout<<"-----------------------------\n"; cin>>selection; } void saveScoreToFile(int score){ FILE *targetFile = fopen("score.txt", "a"); fprintf(targetFile, "%d \n", score ); fclose(targetFile); } void readScoreFromFile(){ int line; FILE *targetFile = fopen("score.txt", "r+"); if(targetFile == NULL) return; int counter; for(counter = 0; counter<100; counter++){ fscanf(targetFile, "%d \n", &line); if(line>=45){ printf("\n->%d -> BAD SCORE-LOST THE GAME\n",line ); }else{ printf("\n->%d -> GOOD SCORE-WIN THE GAME\n",line ); } if(feof(targetFile)) break; } fclose(targetFile); } int main(){ system("color 3"); int playerPosX=1; int playerPosY=0; int selectionOfPlayer; char movement; char up; char down; char right; char left; int moveCounter=0; cout<<" WELCOME TO MAZE GAME!\n\n\n"; while(true){ menu(selectionOfPlayer); ClearConsole(); if(selectionOfPlayer == 1){ settings(up,down,right,left); cout<<"\nSETTINGS SAVED!\n"; Sleep(1200); ClearConsole(); }else if (selectionOfPlayer == 2){ gameInformation(); }else if (selectionOfPlayer == 3){ while(!isGameFinish(playerPosX,playerPosY)){//if player is not in the finish, loop DisplayMaze(playerPosX, playerPosY);//Show current maze PlayersInputHandle(movement, up, down, right, left, playerPosX, playerPosY);//take input ClearConsole();//Clear the console moveCounter=moveCounter+1; } if(moveCounter >= 45){ cout<<"Your score : "<<moveCounter; cout<<"\n\nYour number of moves has exceeded 45! YOU LOST THE GAME!\n\n\n"; }else{ cout<<"Your score : "<<moveCounter; cout<<"\n\nCONGRATULATIONS! YOU HAVE SUCCESSFULLY FINISHED THE MAZE GAME!\n\n\n"; } saveScoreToFile(moveCounter); }else if(selectionOfPlayer == 4){ menu(selectionOfPlayer); break; }else if(selectionOfPlayer == 5){ cout<<"Your past scores are as follows:"; readScoreFromFile(); }else{ exit(0); } } }
[ "peteksukarpuz@icloud.com" ]
peteksukarpuz@icloud.com
6415e424d0b921e1b035de258c4e781e74b4a851
93e99cf7c6d77fa92595d8385fbecdc30b29e5fa
/main.cpp
6d9a37054db3ac1ab3d1bef518116d21302c3fb1
[]
no_license
ratish1112/Vector-and-Smart-Pointers
f5eb65cb46079414c7d482df2000229ff82f4fb5
7d2c23dda272c3e8bc7726455faf3d5efd941d92
refs/heads/master
2022-12-09T02:01:39.959408
2020-09-05T16:21:52
2020-09-05T16:21:52
292,676,312
0
0
null
null
null
null
UTF-8
C++
false
false
1,825
cpp
#include <iostream> #include <memory> #include <vector> using namespace std; class Test { private: int data; public: Test():data{0} { cout<< "\tTest Constructor (" << data << ")" << endl; } Test(int data):data{data} { cout<< "\tTest Constructor (" << data << ")" << endl; } int get_data() const {return data;} ~Test() {cout<< "\tTest Destructor (" << data << ")" << endl;} }; // Function Prototypes unique_ptr <vector <shared_ptr <Test>>> make(); // can also write auto make(); // this way the compiler figures out the return type void fill (vector <shared_ptr<Test>> &vec, int num); void display (const vector <shared_ptr<Test>> &vec); int main() { unique_ptr <vector <shared_ptr <Test>>> vec_ptr; vec_ptr = make(); int num {0}; cout << "How many data points do you want to enter? "; cin >> num; fill (*vec_ptr,num); display (*vec_ptr); return 0; } unique_ptr <vector <shared_ptr <Test>>> make() { vector <shared_ptr <Test>> v; unique_ptr <vector <shared_ptr <Test>>> vec_ptr = make_unique <vector <shared_ptr <Test>>> (v); return vec_ptr; } void fill (vector <shared_ptr<Test>> &vec, int num) { int temp {0}; for (int i {1}; i <= num; ++i) { cout << "Enter data point [" << i << "]:"; cin >> temp; shared_ptr<Test> p1 = make_shared <Test> (temp); // Putting pointer on heap vec.push_back(p1); // Adding pointer to the back of the vector } } void display (const vector <shared_ptr<Test>> &vec) { cout << "\nDisplaying Vector Data: " << endl << "==========================" << endl; for (const auto &v:vec) { cout << v -> get_data() << endl; // Can also use (*v).get_data() } }
[ "noreply@github.com" ]
noreply@github.com
0c838ca9f761fe2e18da977bade88360367bf04d
21bdc29f49bbdaac196bde6426f21f1a88628411
/source/syscall.cpp
fcfcc9884f075c45485008aab8e019bbd50b9d4d
[]
no_license
Lorinet/NeutrinoOS
2d6502049a2abca21094be3ab0d03e1fdcc03530
7e56ede3845b0edcd078c9e4cfcb73f5348f4a11
refs/heads/master
2022-08-24T08:37:15.089657
2022-07-29T07:58:35
2022-07-29T07:58:35
252,728,898
0
0
null
null
null
null
UTF-8
C++
false
false
11,763
cpp
#include "syscall.h" #include "nvm.h" #include "vt.h" #include "event.h" #include "lvmgr.h" #include "vmmgr.h" #include "input.h" #include "sysinfo.h" #include "ntime.h" #include "timer.h" #include "components.h" #include "kernlog.h" #include "filesystem.h" string syscall::filename, syscall::files, syscall::folders, syscall::txt, syscall::txt1, syscall::txt2; Array<byte> syscall::contents, syscall::msg; unsigned int syscall::n; int syscall::proc, syscall::id, syscall::id2; byte syscall::c; bool syscall::bl; vt syscall::vi, syscall::vo; interrupts syscall::syscll; IntMap<iapi*> syscall::interfaces; Array<byte> syscall::data; mutex syscall::syscallMutex; Array<byte> syscall::systemCall(byte* indata, int datasize, nvm* v) { lock_guard<mutex> lock(syscallMutex); syscll = (interrupts)indata[0]; data.clear(); eventid eid; for (unsigned int i = 1; i < datasize; i++) data.push(indata[i]); #if defined(__SDL) SDL_Color sc; #endif switch (syscll) { case interrupts::PRINT: v->outterm->write(data); break; case interrupts::NEWLN: v->outterm->write("\n"); break; case interrupts::GETNOMSG: return bitconverter::toArray(v->messages.size); break; case interrupts::FGETS: filename = lvmgr::formatPath(bitconverter::tostring(data)); if(file::fileExists(filename)) { return file::readAllBytes(filename); } else { vmmgr::vmmerror("File not found: " + bitconverter::tostring(data), v->processid); } break; case interrupts::FPUTS: filename = ""; n = 0; while (data[n] != 0) { filename += (char)data[n]; n += 1; } n += 4; contents = Array<byte>(data.size - filename.size() - 4); while (n < data.size) { contents[n - filename.size() - 4] = data[n]; n += 1; } filename = lvmgr::formatPath(filename); if(file::fileExists(filename)) { file::writeAllBytes(filename, contents); } else { vmmgr::vmmerror("File not found: " + bitconverter::tostring(data), v->processid); } break; case interrupts::FDELETE: filename = lvmgr::formatPath(bitconverter::tostring(data)); if(file::fileExists(filename)) { file::deleteFile(filename); } else { vmmgr::vmmerror("File not found: " + bitconverter::tostring(data), v->processid); } break; case interrupts::FCREATE: filename = lvmgr::formatPath(bitconverter::tostring(data)); if(!file::fileExists(filename)) { file::createFile(filename); } break; case interrupts::DDELETE: filename = lvmgr::formatPath(bitconverter::tostring(data)); if(file::directoryExists(filename)) { file::deleteDirectory(filename); } else { vmmgr::vmmerror("Folder not found: " + bitconverter::tostring(data), v->processid); } break; case interrupts::DCREATE: filename = lvmgr::formatPath(bitconverter::tostring(data)); if(!file::directoryExists(filename)) { file::createDirectory(filename); } break; case interrupts::CGETS: v->awaitin = true; case interrupts::CSCAN: break; case interrupts::CGETK: break; case interrupts::START_PROCESS: proc = bitconverter::toint32(data, 0); if(vmmgr::getProcess(proc) == NULL) { vmmgr::vmmerror("Can't find PID " + proc, v->processid); } else { vmmgr::getProcess(proc)->suspended = false; } break; case interrupts::GETFILES: id = 0; while (v->arrays.find(id) != v->arrays.end()) { id++; } v->arrays.insert({ id, arrayobj() }); filename = lvmgr::formatPath(bitconverter::tostring(data)); if(file::directoryExists(filename)) { vector<string> fls = file::getFiles(filename); for (string s : fls) v->arrays[id].data.push(bitconverter::toArray(s)); return bitconverter::toArray(id); } else { vmmgr::vmmerror("Folder not found: " + bitconverter::tostring(data), v->processid); } break; case interrupts::GETDIRECTORIES: id = 0; while (v->arrays.find(id) != v->arrays.end()) { id++; } v->arrays.insert({ id, arrayobj() }); filename = lvmgr::formatPath(bitconverter::tostring(data)); if(file::directoryExists(filename)) { for (string s : file::getDirectories(filename)) v->arrays[id].data.push(bitconverter::toArray(s)); return bitconverter::toArray(id); } else { vmmgr::vmmerror("Folder not found: " + bitconverter::tostring(data), v->processid); } break; case interrupts::FILE_EXISTS: return bitconverter::toArray(file::fileExists(lvmgr::formatPath(bitconverter::tostring(data)))); case interrupts::FOLDER_EXISTS: return bitconverter::toArray(file::directoryExists(lvmgr::formatPath(bitconverter::tostring(data)))); case interrupts::POWER: switch (data[0]) { case 0x00: #ifdef __ESP32 esp_restart(); #endif break; case 0x01: #if defined(COMPONENT_EFFIGY) WindowManager::Stop(); #endif #if defined(__UNIX) vmmgr::shutdown(); #endif exit(0); break; case 0x02: break; case 0x03: break; } break; case interrupts::GETFIRSTMSG: if (v->messages.size > 0) { msg = v->messages[0]; v->messages.removeAt(0); return msg; } break; case interrupts::CREATE_PROCESS: filename = lvmgr::formatPath(bitconverter::tostring(data)); if(file::fileExists(filename)) { return bitconverter::toArray(vmmgr::createProcess(filename)); } else { vmmgr::vmmerror("Can't find file " + bitconverter::tostring(data), v->processid); } break; case interrupts::CREATE_BACKGROUND_PROCESS: break; case interrupts::KILL_PROCESS: proc = bitconverter::toint32(data, 0); if(vmmgr::getProcess(proc) == NULL) { vmmgr::vmmerror("Can't find PID " + proc, v->processid); } else { vmmgr::terminateProcess(proc); } break; case interrupts::GET_PROCESSID: return bitconverter::toArray(v->processid); case interrupts::SHUTDOWN_PROCESS: v->running = false; break; case interrupts::FORK_PROCESS: vmmgr::createProcess(v->fileName); break; case interrupts::RESTORE_SCREEN: break; case interrupts::CPRINTEDIT: break; case interrupts::CREATE_PROCESS_EX: c = data[0]; data.removeAt(0); switch (c) { case procexih::STDIN_MSGOUT: vi = vt(0, v->processid, vtype::StandardInput); vo = vt(0, v->processid, vtype::MessageOut); break; case procexih::MSGIN_MSGOUT: vi = vt(0, v->processid, vtype::MessageIn); vo = vt(0, v->processid, vtype::MessageOut); break; case procexih::STDIN_STDOUT: vi = vt(0, v->processid, vtype::StandardInput); vo = vt(0, v->processid, vtype::StandardOutput); break; case procexih::MSGIN_STDOUT: vi = vt(0, v->processid, vtype::MessageIn); vo = vt(0, v->processid, vtype::StandardOutput); break; } filename = lvmgr::formatPath(bitconverter::tostring(data)); if(file::fileExists(filename)) { return bitconverter::toArray(vmmgr::createProcessEx(filename, vi, vo)); } else { vmmgr::vmmerror("Can't find file " + bitconverter::tostring(data), v->processid); } break; case interrupts::SEND_PROC_INPUT: proc = bitconverter::toint32(data, 0); msg = Array<byte>(); for (n = 4; n < data.size; n++) msg.push(data[n]); msg.push('\n'); if(vmmgr::getProcess(proc) == NULL) { vmmgr::vmmerror("Can't find PID " + proc, v->processid); } else { vmmgr::sendInput(proc, msg); } break; case interrupts::GETMSG: if (v->messages.size > 0) { msg = v->messages.getTop(); v->messages.pop(); return msg; } break; case interrupts::SENDMSG: proc = bitconverter::toint32(data, 0); msg = Array<byte>(); for (n = 4; n < data.size; n++) msg.push(data[n]); if(vmmgr::getProcess(proc) == NULL) { vmmgr::vmmerror("Can't find PID " + proc, v->processid); } else { vmmgr::sendMessage(proc, msg); } break; case interrupts::AWAITMSG: v->awaitmsg = true; break; case interrupts::THROWERR: vmmgr::vmmerror(bitconverter::tostring(data), v->processid); break; case interrupts::WAIT_FOR_PROC_REQUEST_INPUT: proc = bitconverter::toint32(data, 0); if(vmmgr::getProcess(proc) == NULL) { vmmgr::vmmerror("Can't find PID " + proc, v->processid); } else { v->waitForProcInput = proc; } break; case interrupts::SUSPEND_PROCESS_EX: proc = bitconverter::toint32(data, 0); if(vmmgr::getProcess(proc) == NULL) { vmmgr::vmmerror("Can't find PID " + proc, v->processid); } else { vmmgr::getProcess(proc)->suspended = true; } break; case interrupts::GETINFOSTRING: switch (data[0]) { case 0x00: return bitconverter::toArray(neutrinoOSVersion); case 0x01: return bitconverter::toArray(aboutNeutrino); case 0x02: return bitconverter::toArray(neutrinoDeviceType); case 0x03: return bitconverter::toArray(neutrinoOSVersion); case 0x04: return bitconverter::toArray(neutrinoBuildDate); case 0x05: return bitconverter::toArray(neutrinoBuildNumber); case 0x06: return bitconverter::toArray(platformArch); } break; case interrupts::ATTACH_EVENT_HANDLER: eid = (eventid)data[0]; proc = bitconverter::toint32(data, 1); v->eventHandlers.insert({ eid, proc }); break; case interrupts::DETACH_EVENT_HANDLER: eid = (eventid)data[0]; if (v->eventHandlers.count(eid)) v->eventHandlers.erase(eid); break; case interrupts::ENABLE_EVENTS: v->eventsenabled = true; break; case interrupts::DISABLE_EVENTS: v->eventsenabled = false; break; case interrupts::SUSPEND: v->suspended = true; break; case interrupts::WAKE: v->suspended = false; break; case interrupts::GETTIME: switch (data[0]) { case timesel::TIME_HM: return bitconverter::toArray(ntime::getTimeS()); break; case timesel::TIME_HMS: return bitconverter::toArray(ntime::getTimeWithSeconds()); break; case timesel::DATETIME: return bitconverter::toArray(ntime::getDateTime()); break; case timesel::HOUR: return bitconverter::toArray(ntime::getHour()); break; case timesel::MINUTE: return bitconverter::toArray(ntime::getMinute()); break; case timesel::SECOND: return bitconverter::toArray(ntime::getSecond()); break; case timesel::YEAR: return bitconverter::toArray(ntime::getYear()); break; case timesel::MONTH: return bitconverter::toArray(ntime::getMonth()); break; case timesel::DAY: return bitconverter::toArray(ntime::getDay()); break; } break; case interrupts::SETTIMEZONE: ntime::setTimeZone(bitconverter::toint32(data, 0)); if (ntime::getDST()) ntime::timeZone += 1; break; case interrupts::TIMERINT: switch (data[0]) { case timercmd::CREATE_TIMER: id = 0; while (v->timers.find(id) != v->timers.end()) id += 1; v->timers.insert({ id, timerevt(bitconverter::toint32(data, 1), bitconverter::toint32(data, 5)) }); return bitconverter::toArray(id); break; case timercmd::DESTROY_TIMER: id = bitconverter::toint32(data, 1); if (v->timers.find(id) != v->timers.end()) v->timers.erase(v->timers.find(id)); break; case timercmd::LOOP: id = bitconverter::toint32(data, 1); if (v->timers.find(id) != v->timers.end()) v->timers[id].loop = true; break; case timercmd::ONCE: id = bitconverter::toint32(data, 1); if (v->timers.find(id) != v->timers.end()) v->timers[id].loop = false; break; case timercmd::START_TIMER: id = bitconverter::toint32(data, 1); if (v->timers.find(id) != v->timers.end()) { v->timers[id].startTime = ntime::getMillis(); v->timers[id].running = true; } break; case timercmd::STOP_TIMER: id = bitconverter::toint32(data, 1); if (v->timers.find(id) != v->timers.end()) v->timers[id].running = false; break; } break; case interrupts::COMPONENT_CALL: msg = Array<byte>(data); msg.removeAt(0); contents = interfaces[data[0]]->message(msg, v); if (contents.size > 0) return Array<byte>(contents); break; default: break; } return Array<byte>(); }
[ "lorinet3@gmail.com" ]
lorinet3@gmail.com
657bbdaac89037093a8b0be4304ead7deb379fc4
0b51cc2091e61302194d58ec1b6244892b57d039
/algo_3_snake_190620.cpp
8e9d32edff6765d109bf2e3bc7752e8349459ef8
[]
no_license
lyg726016/algorithm
9e44e1da2b77d151089d1bd2f8441a5e46fc7fab
9c9fd27b1528f50857ebd9713f9f8c3db8453048
refs/heads/master
2020-06-17T23:51:49.845257
2019-10-22T03:06:10
2019-10-22T03:06:10
196,102,773
1
0
null
null
null
null
UTF-8
C++
false
false
1,561
cpp
#include <iostream> #include <vector> #include <queue> #include <Windows.h> using namespace std; #define MAX_SIZE 100 + 1 #define MAX_X 10000 + 1 #define EMPTY 0 #define SNAKE 1 #define APPLE 2 #define U 0 #define R 1 #define D 2 #define L 3 int N, K, M; int map[MAX_SIZE][MAX_SIZE] = { 0, }; char turn[MAX_X] = { 0, }; queue<pair<int, int>> snake; void show() { Sleep(1000); system("cls"); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { printf("%d ", map[i][j]); } printf("\n"); } printf("\n"); } int main() { scanf_s("%d", &N); scanf_s("%d", &K); int x, y; for (int i = 0; i < K; i++) { scanf_s("%d %d", &y, &x); map[y - 1][x - 1] = APPLE; } //apple scanf_s("%d", &M); for (int i = 0; i < M; i++) { int X; char C; scanf_s("%d %c", &X, &C); turn[X] = C; //printf("%c\n",turn[X]); } int second = 0; int T = R; y = 0; x = 0; snake.push(make_pair(y, x)); map[y][x] = SNAKE; while (1) { show(); int bfr_y = y; int bfr_x = x; if (T == U) y--; if (T == R) x++; if (T == D) y++; if (T == L) x--; if (x < 0 || x >= N || y < 0 || y >= N || map[y][x] == 1) { //printf("%d %d %d %d",bfr_y,bfr_x,y,x); break; } if (map[y][x] != APPLE) { pair<int, int> p = snake.front(); snake.pop(); map[p.first][p.second] = EMPTY; } snake.push(make_pair(y, x)); map[y][x] = SNAKE; second++; if (turn[second] == 'L') T--; if (turn[second] == 'D') T++; if (T < 0) T = L; if (T > 3) T = U; } printf("%d", second + 1); scanf_s("%d", &second); return 0; }
[ "lyg2717@mwstory.com" ]
lyg2717@mwstory.com
2277cabb09adb6587d309532afce61b032d0d0b7
a5a99f646e371b45974a6fb6ccc06b0a674818f2
/RecoLocalTracker/SiStripClusterizer/plugins/ChannelLocsGPU.h
343d5a536f0357d36f596c10dd91777427bb3ac4
[ "Apache-2.0" ]
permissive
cms-sw/cmssw
4ecd2c1105d59c66d385551230542c6615b9ab58
19c178740257eb48367778593da55dcad08b7a4f
refs/heads/master
2023-08-23T21:57:42.491143
2023-08-22T20:22:40
2023-08-22T20:22:40
10,969,551
1,006
3,696
Apache-2.0
2023-09-14T19:14:28
2013-06-26T14:09:07
C++
UTF-8
C++
false
false
5,167
h
#ifndef RecoLocalTracker_SiStripClusterizer_plugins_ChannelLocsGPU_h #define RecoLocalTracker_SiStripClusterizer_plugins_ChannelLocsGPU_h #include <memory> #include <vector> #include <cuda_runtime.h> #include "HeterogeneousCore/CUDAUtilities/interface/device_unique_ptr.h" #include "HeterogeneousCore/CUDAUtilities/interface/host_unique_ptr.h" #include "DataFormats/SiStripCluster/interface/SiStripTypes.h" class ChannelLocsGPU; template <template <typename> class T> class ChannelLocsBase { public: ChannelLocsBase(size_t size) : size_(size) {} virtual ~ChannelLocsBase() = default; ChannelLocsBase(ChannelLocsBase&& arg) : input_(std::move(arg.input_)), inoff_(std::move(arg.inoff_)), offset_(std::move(arg.offset_)), length_(std::move(arg.length_)), fedID_(std::move(arg.fedID_)), fedCh_(std::move(arg.fedCh_)), detID_(std::move(arg.detID_)), size_(arg.size_) {} void setChannelLoc(uint32_t index, const uint8_t* input, size_t inoff, size_t offset, uint16_t length, stripgpu::fedId_t fedID, stripgpu::fedCh_t fedCh, stripgpu::detId_t detID) { input_[index] = input; inoff_[index] = inoff; offset_[index] = offset; length_[index] = length; fedID_[index] = fedID; fedCh_[index] = fedCh; detID_[index] = detID; } size_t size() const { return size_; } const uint8_t* input(uint32_t index) const { return input_[index]; } size_t inoff(uint32_t index) const { return inoff_[index]; } size_t offset(uint32_t index) const { return offset_[index]; } uint16_t length(uint32_t index) const { return length_[index]; } stripgpu::fedId_t fedID(uint32_t index) const { return fedID_[index]; } stripgpu::fedCh_t fedCh(uint32_t index) const { return fedCh_[index]; } stripgpu::detId_t detID(uint32_t index) const { return detID_[index]; } const uint8_t* const* input() const { return input_.get(); } size_t* inoff() const { return inoff_.get(); } size_t* offset() const { return offset_.get(); } uint16_t* length() const { return length_.get(); } stripgpu::fedId_t* fedID() const { return fedID_.get(); } stripgpu::fedCh_t* fedCh() const { return fedCh_.get(); } stripgpu::detId_t* detID() const { return detID_.get(); } protected: T<const uint8_t*[]> input_; // input raw data for channel T<size_t[]> inoff_; // offset in input raw data T<size_t[]> offset_; // global offset in alldata T<uint16_t[]> length_; // length of channel data T<stripgpu::fedId_t[]> fedID_; T<stripgpu::fedCh_t[]> fedCh_; T<stripgpu::detId_t[]> detID_; size_t size_ = 0; }; class ChannelLocs : public ChannelLocsBase<cms::cuda::host::unique_ptr> { friend class ChannelLocsGPU; public: ChannelLocs(size_t size, cudaStream_t stream); ChannelLocs(ChannelLocs&& arg) : ChannelLocsBase(std::move(arg)) {} ChannelLocs(ChannelLocs&) = delete; ChannelLocs(const ChannelLocs&) = delete; ChannelLocs& operator=(const ChannelLocs&) = delete; ChannelLocs& operator=(ChannelLocs&&) = delete; ~ChannelLocs() override = default; }; class ChannelLocsView { public: void fill(const ChannelLocsGPU& c); __device__ size_t size() const { return size_; } __device__ const uint8_t* input(uint32_t index) const { return input_[index]; } __device__ size_t inoff(uint32_t index) const { return inoff_[index]; } __device__ size_t offset(uint32_t index) const { return offset_[index]; } __device__ uint16_t length(uint32_t index) const { return length_[index]; } __device__ stripgpu::fedId_t fedID(uint32_t index) const { return fedID_[index]; } __device__ stripgpu::fedCh_t fedCh(uint32_t index) const { return fedCh_[index]; } __device__ stripgpu::detId_t detID(uint32_t index) const { return detID_[index]; } private: const uint8_t* const* input_; // input raw data for channel size_t* inoff_; // offset in input raw data size_t* offset_; // global offset in alldata uint16_t* length_; // length of channel data stripgpu::fedId_t* fedID_; stripgpu::fedCh_t* fedCh_; stripgpu::detId_t* detID_; size_t size_; }; class ChannelLocsGPU : public ChannelLocsBase<cms::cuda::device::unique_ptr> { public: //using Base = ChannelLocsBase<cms::cuda::device::unique_ptr>; ChannelLocsGPU(size_t size, cudaStream_t stream); ChannelLocsGPU(ChannelLocsGPU&& arg) : ChannelLocsBase(std::move(arg)), channelLocsViewGPU_(std::move(arg.channelLocsViewGPU_)) {} ChannelLocsGPU(ChannelLocsGPU&) = delete; ChannelLocsGPU(const ChannelLocsGPU&) = delete; ChannelLocsGPU& operator=(const ChannelLocsGPU&) = delete; ChannelLocsGPU& operator=(ChannelLocsGPU&&) = delete; ~ChannelLocsGPU() override = default; void setVals(const ChannelLocs* c, cms::cuda::host::unique_ptr<const uint8_t*[]> inputGPU, cudaStream_t stream); const ChannelLocsView* channelLocsView() const { return channelLocsViewGPU_.get(); } private: cms::cuda::device::unique_ptr<ChannelLocsView> channelLocsViewGPU_; }; #endif
[ "Daniel.Riley@cornell.edu" ]
Daniel.Riley@cornell.edu
2b5684047973522d664eeb46f8ec30d0e211a8d2
7c0149fbd18e1eb8f7a941aaecf2af49e7865047
/SPC-source/players-editors/spctool/src/A2Reg.cpp
dfb3d95e5ce5f8a3e6c31a245ab3a5b3167387f9
[]
no_license
navjack/phalanx-snes-remastered
4812cb7f266ba57d23a3148b835d5881646f0ee3
f29144f8e23f29a25a2f50e89c388c0a835b89f0
refs/heads/master
2022-12-12T12:30:27.883042
2020-08-30T19:11:17
2020-08-30T19:11:17
291,532,785
0
0
null
null
null
null
UTF-8
C++
false
false
4,577
cpp
/*************************************************************************************************** * Windows Registry Class * * Copyright (C)2004 Alpha-II Productions * ***************************************************************************************************/ #include <windows.h> #include "Types.h" #include "A2Reg.h" //************************************************************************************************** A2Reg::A2Reg() { hkey = NULL; } A2Reg::~A2Reg() { Close(); } //************************************************************************************************** b8 __fastcall A2Reg::Open(s8 *key) { Close(); return !RegOpenKeyEx(HKEY_CURRENT_USER, key, 0, KEY_QUERY_VALUE, &hkey); } b8 __fastcall A2Reg::Create(s8 *key) { Close(); if (!RegOpenKeyEx(HKEY_CURRENT_USER, key, 0, KEY_WRITE, &hkey)) return 1; return !RegCreateKeyEx(HKEY_CURRENT_USER, key, 0, NULL, 0, KEY_WRITE, NULL, &hkey, NULL); } b8 __fastcall A2Reg::Remove(s8 *key) { return !RegDeleteKey(HKEY_CURRENT_USER, key); } void __fastcall A2Reg::Close() { if (hkey) { RegCloseKey(hkey); hkey = NULL; } } //************************************************************************************************** b8 __fastcall A2Reg::Get(s8 *val, b8 def) { DWORD data,size; data = 0; size = 4; if (RegQueryValueEx(hkey, val, NULL, NULL, (u8*)&data, &size)) return def; return data != 0; } s32 __fastcall A2Reg::Get(s8 *val, s32 def, s32 min, s32 max) { s32 data; DWORD size; data = 0; size = 4; if (RegQueryValueEx(hkey, val, NULL, NULL, (u8*)&data, &size) || size != 4) return def; if (min != max) { if (data < min) return min; if (data > max) return max; } return data; } u32 __fastcall A2Reg::Get(s8 *val, u32 def, u32 min, u32 max) { u32 data; DWORD size; size = 4; if (RegQueryValueEx(hkey, val, NULL, NULL, (u8*)&data, &size) || size != 4) return def; if (min != max) { if (data < min) return min; if (data > max) return max; } return data; } f32 __fastcall A2Reg::Get(s8 *val, f32 def, f32 min, f32 max) { f32 data; DWORD size; size = 4; if (RegQueryValueEx(hkey, val, NULL, NULL, (u8*)&data, &size) || size != 4) return def; if (*(u32*)&min == *(u32*)&max) return data; switch ((u8)(*(u32*)&data >> 23)) { case(0): //Check for denormalized numbers case(255): // or NaNs if (*(u32*)&data & 0x7FFFFF) return def; } if (data < min) return min; if (data > max) return max; return data; } f64 __fastcall A2Reg::Get(s8 *val, f64 def, f64 min, f64 max) { f64 data; DWORD size; size = 8; if (RegQueryValueEx(hkey, val, NULL, NULL, (u8*)&data, &size) || size != 8) return def; if (*(u64*)&min == *(u64*)&max) return data; switch ((((u32*)&data)[1] >> 20) & 0x7FF) { case(0): //Check for denormalized numbers case(2047): // or NaNs if (((u32*)&data)[0] | ((u32*)&data)[1] & 0xFFFFF) return def; } if (data < min) return min; if (data > max) return max; return data; } u32 __fastcall A2Reg::Get(s8 *val, s8 *str, u32 size, s8 *def) { size++; if (RegQueryValueEx(hkey, val, NULL, NULL, (u8*)str, (DWORD*)&size)) { strcpy(str, def); return 0; } return size; } u32 __fastcall A2Reg::Get(s8 *val, void *pData, u32 size) { return RegQueryValueEx(hkey, val, NULL, NULL, (u8*)pData, (DWORD*)&size) ? 0 : size; } //************************************************************************************************** void __fastcall A2Reg::Set(s8 *val, b8 data) { u32 d = (data != 0); RegSetValueEx(hkey, val, 0, REG_DWORD, (u8*)&d, 4); } void __fastcall A2Reg::Set(s8 *val, s32 data) { RegSetValueEx(hkey, val, 0, REG_DWORD, (u8*)&data, 4); } void __fastcall A2Reg::Set(s8 *val, u32 data) { RegSetValueEx(hkey, val, 0, REG_DWORD, (u8*)&data, 4); } void __fastcall A2Reg::Set(s8 *val, f32 data) { RegSetValueEx(hkey, val, 0, REG_DWORD, (u8*)&data, 4); } void __fastcall A2Reg::Set(s8 *val, f64 data) { RegSetValueEx(hkey, val, 0, REG_QWORD, (u8*)&data, 8); } void __fastcall A2Reg::Set(s8 *val, s8 *str) { RegSetValueEx(hkey, val, 0, REG_SZ, (u8*)str, strlen(str) + 1); } void __fastcall A2Reg::Set(s8 *val, void *pData, u32 size) { RegSetValueEx(hkey, val, 0, REG_BINARY, (u8*)pData, size); } //************************************************************************************************** b8 __fastcall A2Reg::Delete(s8 *val) { return !RegDeleteValue(hkey, val); }
[ "jack.mangano@gmail.com" ]
jack.mangano@gmail.com
f3f961f98d3cfe9f717a73607c294c71d4f701af
b8f2800536c293a52e274986534e1c0d9ea33a5e
/SimpleEx/SimpleEx/SimpleEx.cpp
9dc5ab82d2949cb2ac32c6df78152d6b5692af12
[]
no_license
hksuh/SimpleEx
6dfb0375ac1471a5fcf176567e2eddaea70cb1ea
ec312cc2aa79fef2a80feb41380dac5d9e6a5f00
refs/heads/master
2021-01-10T10:04:51.849595
2016-03-15T13:51:30
2016-03-15T13:51:30
53,815,678
0
0
null
2016-03-15T14:18:44
2016-03-14T00:36:50
Mathematica
UTF-8
C++
false
false
4,501
cpp
// SimpleEx.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "fIO.h" #include "iostream" int superSimple(){ const int len = 4; vector<> for (int i = 0; i<len; i++){ being[i].getScore(layer, trainInput); cout << i << "score: " << being[i].score << endl; } int alter = 100; int from, to; double foot = 0.5; while (alter>0){ for (int i = 0; i<len; i++){ being[i].copy(nbeing[i]); } while (alter > 0){ alter--; if (alter % 100 == 0){ cout << ">>>>>>>>>>>>>>>>>" << (alter / 100) << endl; } for (int i = 0; i < len; i++){ nbeing[i].perturb(foot); nbeing[i].getScore(layer, trainInput); if (nbeing[i].score < being[i].score){ nbeing[i].copy(being[i]); cout << i << "score: " << being[i].score << endl; } } } for (int i = 0; i < len; i++){ nbeing[i].perturb(foot); nbeing[i].getScore(layer, trainInput); if (nbeing[i].score < being[i].score){ nbeing[i].copy(being[i]); cout << i << "score: " << being[i].score << endl; } } cout << "step number: "; cin >> alter; if (alter == -5){ cout << "=========copy_mode=========" << endl; cout << "from:"; cin >> from; cout << "to:"; cin >> to; being[from].copy(being[to]); cout << "step number: "; cin >> alter; } cout << "foot size: "; cin >> foot; } txtOut("out.txt", being, len); return 0; } int test(){ /* mat4 qwer(2, mat3(2, mat2(2, mat1(2, 1.)))); mat2 asdf(2, mat1(2, 1.)); mat2 as(2, mat1(2, 1.)); product(qwer, asdf,as); showMat(as); */ /* time measure kit clock_t time_a = clock(); clock_t time_b = clock(); cout << "a to b: " << ((double)(time_b - time_a)) / CLOCKS_PER_SEC << endl; cout << "b to c: " << ((double)(time_c - time_b)) / CLOCKS_PER_SEC << endl; */ srand((unsigned int)time(NULL)); vector<mat2> layer; layer.reserve(6); //layer.push_back(mat2(8, mat1(8, 0.))); //layer.push_back(mat2(16, mat1(16, 0.))); //layer.push_back(mat2(16, mat1(16, 0.))); layer.push_back(mat2(8, mat1(8, 0.))); layer.push_back(mat2(8, mat1(8, 0.))); layer.push_back(mat2(4, mat1(4, 0.))); layer.push_back(mat2(4, mat1(4, 0.))); layer.push_back(mat2(2, mat1(2, 0.))); layer.push_back(mat2(2, mat1(2, 0.))); layer.push_back(mat2(1, mat1(1, 0.))); mat3 trainInput=txtIn("TrainingList.txt"); int v; indiv being = indiv(); for (int aw = 0; aw < 10; aw++){ being.newRand(); // being.show(); for (int rai = 0; rai < 99; rai++){ layer[0] = trainInput[rai]; being.propagate(layer); } showMat(layer[6]); //cin>>v; } //clock_t time_c = clock(); //showMat(being.thsd[0]); return 0; } int _tmain(int argc, _TCHAR* argv[]){ srand((unsigned int)time(NULL)); return 0; vector<mat2> layer; layer.reserve(7); //layer.push_back(mat2(8, mat1(8, 0.))); //layer.push_back(mat2(16, mat1(16, 0.))); //layer.push_back(mat2(16, mat1(16, 0.))); layer.push_back(mat2(8, mat1(8, 0.))); layer.push_back(mat2(8, mat1(8, 0.))); layer.push_back(mat2(4, mat1(4, 0.))); layer.push_back(mat2(4, mat1(4, 0.))); layer.push_back(mat2(2, mat1(2, 0.))); layer.push_back(mat2(2, mat1(2, 0.))); layer.push_back(mat2(1, mat1(1, 0.))); mat3 trainInput = txtIn("TrainingList.txt"); const int len = 16; indiv being[len]; indiv nbeing[len]; for (int i = 0; i<len; i++){ being[i].getScore(layer,trainInput); cout << i << "score: " << being[i].score << endl; } int alter=100; int from, to; double foot = 0.5; while (alter>0){ for (int i = 0; i<len; i++){ being[i].copy(nbeing[i]); } while (alter > 0){ alter--; if (alter % 100 == 0){ cout <<">>>>>>>>>>>>>>>>>"<< (alter / 100)<<endl; } for (int i = 0; i < len; i++){ nbeing[i].perturb(foot); nbeing[i].getScore(layer, trainInput); if (nbeing[i].score < being[i].score){ nbeing[i].copy(being[i]); cout << i << "score: " << being[i].score << endl; } } } for (int i = 0; i < len; i++){ nbeing[i].perturb(foot); nbeing[i].getScore(layer, trainInput); if (nbeing[i].score < being[i].score){ nbeing[i].copy(being[i]); cout << i << "score: " << being[i].score << endl; } } cout << "step number: "; cin >> alter; if (alter == -5){ cout << "=========copy_mode=========" << endl; cout << "from:"; cin >> from; cout << "to:"; cin >> to; being[from].copy(being[to]); cout << "step number: "; cin >> alter; } cout << "foot size: "; cin >> foot; } txtOut("out.txt", being, len); return 0; }
[ "hksuh@kaist.ac.kr" ]
hksuh@kaist.ac.kr
9ce0dac6174c29131ff4e338ad746925a223fdbe
c43f9c8ae0731c59ec4ec9dfdaa9a6a916828082
/src/MemManager/ProcessManager.cpp
cccfeb70cee0dc2a1064223894345243079c7d81
[]
no_license
roccosec/Anti-VAC
a055922842447e5fae461830b4f8cba327c722b4
80d19b9dd7b475916e78e1cb2236c3097c594ccd
refs/heads/master
2021-04-09T10:09:38.112869
2020-03-19T01:40:21
2020-03-19T01:40:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,302
cpp
// // Created by itayb on 3/16/2020. // #include "ProcessManager.h" #include <windows.h> ProcessManager::ProcessManager(const char * name): name(name), id(0), handle(INVALID_HANDLE_VALUE), attached(false) {} ProcessManager::~ProcessManager() { this->detach(); } void ProcessManager::read(uintptr_t add, void *buff,size_t size) { ReadProcessMemory(handle,(void*)add,buff,size,nullptr); } void ProcessManager::write(uintptr_t add, void *buff,size_t size) { WriteProcessMemory(handle,(void*)add,buff,size,nullptr); } bool ProcessManager::wait() { while(!isRunning()){ Sleep(500);//Wait half a second before checking for program again } return attach(); } bool ProcessManager::isRunning() { if(attached){ DWORD exitCode; GetExitCodeProcess(handle,&exitCode); return exitCode == STILL_ACTIVE; }else return findProcess(); } bool ProcessManager::attach() { if(!attached){ if(id == 0) isRunning(); handle = OpenProcess(PROCESS_ALL_ACCESS,FALSE,id); if(handle == NULL){ puts("ERROR: Bad Process ID"); exit(2); } attached = true; return true; }else{ puts("ERROR: Process is already attached"); return false; } } bool ProcessManager::detach() { if (attached) { CloseHandle(handle); attached = false; return true; } else { puts("ERROR: Process is already detached!"); return false; } } uintptr_t ProcessManager::getModule(const char *modName) { MODULEENTRY32 modEntry; if(findModule(modName,&modEntry)){ return (uintptr_t)modEntry.modBaseAddr; } return 0; } uintptr_t ProcessManager::waitModule(const char *modName) { uintptr_t mod = 0; while(!(mod = getModule(modName))){ Sleep(1000); } return mod; } bool ProcessManager::findProcess() { PROCESSENTRY32 pEntry; ZeroMemory(&pEntry,sizeof(pEntry)); pEntry.dwSize = sizeof(PROCESSENTRY32); //Get a snapshot of all processes and loop through the entries to find //a process with a matching name and return its id HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0); if(hSnap && Process32Next(hSnap,&pEntry)){ do{ if(strcmp(pEntry.szExeFile,this->name.c_str()) == 0){ this->id = pEntry.th32ProcessID; CloseHandle(hSnap); return true; } }while(Process32Next(hSnap,&pEntry)); } return false; } bool ProcessManager::findModule(const char * modName, MODULEENTRY32 * modEntry) { MODULEENTRY32 mEntry; ZeroMemory(&mEntry, sizeof(mEntry)); mEntry.dwSize = sizeof(MODULEENTRY32); //Get Snapshot of all modules in a process and loop through entries to find // a module with a matching name and return the Module Struct HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, this->id); if (hSnap && Module32Next(hSnap, &mEntry)) { do { if (strcmp(mEntry.szModule, modName) == 0) { modEntry = &mEntry; CloseHandle(hSnap); return true; } } while (Module32Next(hSnap, &mEntry)); } return false; }
[ "itay.bachar01@gmail.com" ]
itay.bachar01@gmail.com
2a5061c0bd1a1c1a798de3938a3c4e7c5c56b926
3cf9e141cc8fee9d490224741297d3eca3f5feff
/C++ Benchmark Programs/Benchmark Files 1/classtester/autogen-sources/source-4942.cpp
9dfc0af97a1477deebdda9672ee8e480d9b1bcad
[]
no_license
TeamVault/tauCFI
e0ac60b8106fc1bb9874adc515fc01672b775123
e677d8cc7acd0b1dd0ac0212ff8362fcd4178c10
refs/heads/master
2023-05-30T20:57:13.450360
2021-06-14T09:10:24
2021-06-14T09:10:24
154,563,655
0
1
null
null
null
null
UTF-8
C++
false
false
2,496
cpp
struct c0; void __attribute__ ((noinline)) tester0(c0* p); struct c0 { bool active0; c0() : active0(true) {} virtual ~c0() { tester0(this); active0 = false; } virtual void f0(){} }; void __attribute__ ((noinline)) tester0(c0* p) { p->f0(); } struct c1; void __attribute__ ((noinline)) tester1(c1* p); struct c1 { bool active1; c1() : active1(true) {} virtual ~c1() { tester1(this); active1 = false; } virtual void f1(){} }; void __attribute__ ((noinline)) tester1(c1* p) { p->f1(); } struct c2; void __attribute__ ((noinline)) tester2(c2* p); struct c2 : c0, c1 { bool active2; c2() : active2(true) {} virtual ~c2() { tester2(this); c0 *p0_0 = (c0*)(c2*)(this); tester0(p0_0); c1 *p1_0 = (c1*)(c2*)(this); tester1(p1_0); active2 = false; } virtual void f2(){} }; void __attribute__ ((noinline)) tester2(c2* p) { p->f2(); if (p->active0) p->f0(); if (p->active1) p->f1(); } struct c3; void __attribute__ ((noinline)) tester3(c3* p); struct c3 : c0, c1 { bool active3; c3() : active3(true) {} virtual ~c3() { tester3(this); c0 *p0_0 = (c0*)(c3*)(this); tester0(p0_0); c1 *p1_0 = (c1*)(c3*)(this); tester1(p1_0); active3 = false; } virtual void f3(){} }; void __attribute__ ((noinline)) tester3(c3* p) { p->f3(); if (p->active0) p->f0(); if (p->active1) p->f1(); } struct c4; void __attribute__ ((noinline)) tester4(c4* p); struct c4 : virtual c0, virtual c1 { bool active4; c4() : active4(true) {} virtual ~c4() { tester4(this); c0 *p0_0 = (c0*)(c4*)(this); tester0(p0_0); c1 *p1_0 = (c1*)(c4*)(this); tester1(p1_0); active4 = false; } virtual void f4(){} }; void __attribute__ ((noinline)) tester4(c4* p) { p->f4(); if (p->active0) p->f0(); if (p->active1) p->f1(); } int __attribute__ ((noinline)) inc(int v) {return ++v;} int main() { c0* ptrs0[25]; ptrs0[0] = (c0*)(new c0()); ptrs0[1] = (c0*)(c2*)(new c2()); ptrs0[2] = (c0*)(c3*)(new c3()); ptrs0[3] = (c0*)(c4*)(new c4()); for (int i=0;i<4;i=inc(i)) { tester0(ptrs0[i]); delete ptrs0[i]; } c1* ptrs1[25]; ptrs1[0] = (c1*)(new c1()); ptrs1[1] = (c1*)(c2*)(new c2()); ptrs1[2] = (c1*)(c3*)(new c3()); ptrs1[3] = (c1*)(c4*)(new c4()); for (int i=0;i<4;i=inc(i)) { tester1(ptrs1[i]); delete ptrs1[i]; } c2* ptrs2[25]; ptrs2[0] = (c2*)(new c2()); for (int i=0;i<1;i=inc(i)) { tester2(ptrs2[i]); delete ptrs2[i]; } c3* ptrs3[25]; ptrs3[0] = (c3*)(new c3()); for (int i=0;i<1;i=inc(i)) { tester3(ptrs3[i]); delete ptrs3[i]; } c4* ptrs4[25]; ptrs4[0] = (c4*)(new c4()); for (int i=0;i<1;i=inc(i)) { tester4(ptrs4[i]); delete ptrs4[i]; } return 0; }
[ "ga72foq@mytum.de" ]
ga72foq@mytum.de
8ac43eb846e10025c4de57287bd87f4efa7d0ea1
e6da789ca138a46058210e14d4dc4b1e001eef22
/Code/FingerprintRobotLocalControl/lib/VNH5019Driver/VNH5019Driver.cpp
3f56b1aaf6f20bec82fa4d6ea0016dfdd7be7a9e
[ "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
usnistgov/FingerprintScannerRobot
39e23254b84eb86e5119e858c7da02aebf898f69
6b70fd22e7c799d0be8e7170e529c071b1371abc
refs/heads/master
2021-05-03T14:04:30.432053
2016-09-30T19:11:58
2016-09-30T19:11:58
63,962,904
4
0
null
null
null
null
UTF-8
C++
false
false
1,766
cpp
/* * VNH5019Driver.cpp * * Created on: Jun 23, 2015 * Author: jacob */ #include <Arduino.h> #include <VNH5019Driver.h> namespace VNH5019DriverLib { #define BRAKE_VCC 3 //0b11 #define CLOCKWISE 2 //0b10 #define COUNTERCLOCKWISE 1 //0b01 #define BRAKE_GND 0 // 0b00 VNH5019Driver::VNH5019Driver(int INA, int INB, int PWM, int parity) { this->INA = INA; this->INB = INB; this->PWM = PWM; this->parity = parity; pinMode(INA, OUTPUT); pinMode(INB, OUTPUT); pinMode(PWM, OUTPUT); } /** * Sets the speed of the motor. Takes a speed in the range [-255,255]. A positive speed will set INA to 0 and INB to 1, putting the chip into counterclockwise mode. A negative speed will set INA to 1 and INB to 0, putting the chip into clockwise mode. A speed of zero will also put the chip into counterclockwise mode, but will not cause the motor to spin. */ void VNH5019Driver::setSpeed(int speed) { speed *= parity; setControlPins(speed >= 0 ? COUNTERCLOCKWISE : CLOCKWISE); //Serial.println(abs(speed)); analogWrite(PWM, abs(speed)); //Serial.print("PWM: "); //Serial.println(PWM); } /** * Not really sure what this does, but it sets INA and INB to HIGH. */ void VNH5019Driver::brakeToVCC() { analogWrite(PWM, abs(0)); setControlPins(BRAKE_VCC); } /** * Not really sure what this does, but it sets INA and INB to LOW. */ void VNH5019Driver::brakeToGround() { analogWrite(PWM, abs(0)); setControlPins(BRAKE_GND); } void VNH5019Driver::setControlPins(int state) { //Serial.print("INA: "); uint8_t INAState = (state & 2) >> 1; uint8_t INBState = state & 1; //Serial.println(INAState); //Serial.print("INB: "); //Serial.println(INBState); digitalWrite(INA, INAState); digitalWrite(INB, INBState); } } /* namespace VNH5019DriverLib */
[ "jacob.glueck@nist.gov" ]
jacob.glueck@nist.gov
774b0e0748d59c25dd771acc2daca9e2dde54fef
4dc8470e8de1ab1a701ea77d1f58ed6e78f65e02
/external/playground/include/pf/simplehttp.h
634abc1be77c5afa5cc4f23bff8104ff1543c3aa
[]
no_license
ForestMan/DefenceGarden
51c94f1b69d7a5e0bc634e672051fc043cb2b1b2
5467ceb4fc35736e25dc74a0c57329b8f2c82fbb
refs/heads/master
2020-05-31T17:47:56.509231
2009-10-08T05:57:26
2009-10-08T05:57:26
258,647
1
0
null
null
null
null
UTF-8
C++
false
false
4,108
h
//------------------------------------------------------------------ // Copyright (c) 2004-2008 PlayFirst, Inc. All rights reserved. // Part of the Playground SDK(tm). // // This file contains proprietary information of PlayFirst, Inc. // It is provided subject to a license agreement. It may not be // reproduced, used, disclosed, sold or transferred without the // prior written consent of PlayFirst, Inc. //------------------------------------------------------------------ #ifndef SIMPLEHTTP_H_INCLUDED #define SIMPLEHTTP_H_INCLUDED #if !defined(PFCONFIG_H_INCLUDED) #include "pfconfig.h" #endif //------------------------------------------------------------------ #include "str.h" //------------------------------------------------------------------ class THttpData; /** * The TSimpleHttp class implements a basic HTTP connection. */ class PFLIB_API TSimpleHttp { public: /** * Construction. */ TSimpleHttp(); /** * Destruction. */ virtual ~TSimpleHttp(); /** * Initialize TSimpleHttp. * * @param url The URL to connect with. The underlying library * will not accept extremely long URLs, so * use POST requests if the request will be more * than about 800 characters long. * @param bPost True for a POST request; otherwise GET. * @param path Specify path name to download to; otherwise the * data is kept in an internal buffer and retrieved * using TSimpleHttp::GetContents(). */ void Init(const char* url, bool bPost = false, const char* path = NULL); /** * Add a POST or GET argument to the query. * * @param name Name of argument. * @param value Value of argument. */ void AddArg(const char* name, const char* value); /** * Add a POST or GET argument to the query. * * @param name Name of argument. * @param value Value of argument. */ void AddArg(const char* name, int32_t value); /** * HTTP cleanup. * * @param unsafeString * String to clean. * * @return Newly cleaned string. */ static str HttpSafeString(const char *unsafeString); /// Request modifiers. enum ERequestFlags { /// No modifier. eNoFlag = 0x00000000, /// Do not write the request to the cache. eDoNotWriteCache = 0x00000001, /// Ignore an invalid certificate. eIgnoreCNInvalid = 0x00000002 }; /** * Start the request. * * @param flags One or more ERequestFlags bitwise-ORed together. */ void DoRequest(int32_t flags); /** * Status enumeration. */ enum EStatus { /// Waiting for a reply. eNetWait, /// Reply complete and successful. eNetDone, /// Error communicating with server. eNetError, /// Error writing file. eFileError }; /** * Get the current status. * * @return The status. */ EStatus GetStatus(); /** * Returns the "content-length" field of the HTTP header, if * available. * * This value is the expected total download size. * * @return Expected size of the content. * * @see GetBytesReceived() */ unsigned long GetContentLengthHeader(); /** * Get the total number of bytes received. If the download is * complete, this is the same as GetContentLengthHeader(); if * the download is still in progress, this will be a lower * number that you can use to display a progress bar. * * @return Bytes received. * * @see GetContentLengthHeader() */ unsigned long GetBytesReceived(); /// Get the content of the reply. /// /// Available only if downloading to memory: Will fail until status is eNetDone. char* GetContents(); private: str mUrl; str mArgs; str mPath; str mPostStr; bool mbFirst; bool mbPost; THttpData* mData; }; //------------------------------------------------------------------ #endif // SIMPLEHTTP_H_INCLUDED
[ "denis.kozhushenko@gmail.com" ]
denis.kozhushenko@gmail.com
f74de368b14e1a5501cc3104d98206b1adb9ba99
3400bd103952373e2f8715f72734440e5e894734
/2201.cpp
b6a20a6c2206cf924437e9796652fd27346fb915
[]
no_license
immortalmin/ZOJ
264f0ad94c054043eba0bf90c87b7419e67cb29e
acf5ee8e684ee1db41f68409b19fd1d0570007f4
refs/heads/master
2020-05-31T21:36:02.643235
2019-06-11T05:43:15
2019-06-11T05:43:15
190,501,369
0
0
null
null
null
null
UTF-8
C++
false
false
220
cpp
#include<iostream> using namespace std; int main() { int n; cin>>n; for(int ii=0;ii<n;ii++) { int a,b; cin>>a>>b; if(a>=b) cout<<"MMM BRAINS"<<endl; else cout<<"NO BRAINS"<<endl; } return 0; }
[ "1608725226@qq.com" ]
1608725226@qq.com
54cfabe51451eab0d4e049dde0bc857f51bd616a
2cf838b54b556987cfc49f42935f8aa7563ea1f4
/aws-cpp-sdk-macie2/include/aws/macie2/model/GetFindingsPublicationConfigurationRequest.h
580f02544c8222627a721c2627d4bfd20e82f9b2
[ "MIT", "Apache-2.0", "JSON" ]
permissive
QPC-database/aws-sdk-cpp
d11e9f0ff6958c64e793c87a49f1e034813dac32
9f83105f7e07fe04380232981ab073c247d6fc85
refs/heads/main
2023-06-14T17:41:04.817304
2021-07-09T20:28:20
2021-07-09T20:28:20
384,714,703
1
0
Apache-2.0
2021-07-10T14:16:41
2021-07-10T14:16:41
null
UTF-8
C++
false
false
1,021
h
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/macie2/Macie2_EXPORTS.h> #include <aws/macie2/Macie2Request.h> namespace Aws { namespace Macie2 { namespace Model { /** */ class AWS_MACIE2_API GetFindingsPublicationConfigurationRequest : public Macie2Request { public: GetFindingsPublicationConfigurationRequest(); // Service request name is the Operation name which will send this request out, // each operation should has unique request name, so that we can get operation's name from this request. // Note: this is not true for response, multiple operations may have the same response name, // so we can not get operation's name from response. inline virtual const char* GetServiceRequestName() const override { return "GetFindingsPublicationConfiguration"; } Aws::String SerializePayload() const override; }; } // namespace Model } // namespace Macie2 } // namespace Aws
[ "aws-sdk-cpp-automation@github.com" ]
aws-sdk-cpp-automation@github.com
3a7f2cc6588f83ca66c7ec7204d653470ca6351d
412c9fc6bfe858cd9c618a8ebb371b079b1f3c64
/l2.h
9a4b523890152f22f49487e578965e90012939e8
[]
no_license
Kevin0901881/Quadris
ca92fe432719cbfa61fd5ec5f346678a9c4b4806
81a3a16d91debbf0208662cc18f21f21cb5a0fb3
refs/heads/master
2021-03-24T10:27:09.861819
2018-02-28T03:45:26
2018-02-28T03:45:26
112,525,361
0
0
null
null
null
null
UTF-8
C++
false
false
355
h
#ifndef L2_H #define L2_H #include <memory> #include <cstdlib> #include "level.h" class L2 : public Level { int prob; bool isSeedAvailable; public: L2(unsigned int seed); // constructor with seed L2(); // constructor no seed std::unique_ptr<Block> createBlock(Grid* grid, int id, bool onBoard, std::string s); // creates a new block }; #endif
[ "kevin0901881@gmail.com" ]
kevin0901881@gmail.com
f153936e8c919d7624573b58edc83b23116dae79
2dba1dc8e5c62631ad9801222d8a34b72b8a5635
/UVa Online Judge/volume002/213 Message Decoding/program.cpp
9f059ceca4905d4e04a33a6d8cdf609c2e371823
[]
no_license
dingswork/Code
f9e875417238efd04294b86c0b4261b4da867923
669139b70d0dbc8eae238d52aa7b8c0782fb9003
refs/heads/master
2021-01-24T16:52:10.703835
2018-02-27T14:07:25
2018-02-27T14:07:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,290
cpp
// Message Decoding // UVa ID: 213 // Verdict: Accepted // Submission Date: 2016-04-28 // UVa Run Time: 0.010s // // 版权所有(C)2016,邱秋。metaphysis # yeah dot net #include <iostream> #include <map> #include <bitset> using namespace std; map<string, int> indexer; int main(int argc, char *argv[]) { for (int i = 2, idx = 0, length = 1; length < 8; i *= 2, length++) for (int j = 0; j < (i - 1); j++) { bitset<8> n(j); indexer[n.to_string().substr(8 - length, length)] = idx++; } string line, head, buffer; bool headReaded = false; bool segmentEnded = false, segmentStartReaded = false; int keyLength; while (getline(cin, line)) { if (!headReaded) { head = line; headReaded = true; } else { buffer += line; nextReading: if (!segmentStartReaded) { if (buffer.length() >= 3) { keyLength = stoi(buffer.substr(0, 3), NULL, 2); if (keyLength == 0) { headReaded = false; segmentStartReaded = false; buffer.clear(); cout << "\n"; } else { buffer.erase(0, 3); segmentStartReaded = true; segmentEnded = false; } } } if (!segmentEnded) { while (buffer.length() >= keyLength) { string key = buffer.substr(0, keyLength); if (key == string(keyLength, '1')) { segmentEnded = true; segmentStartReaded = false; buffer.erase(0, keyLength); goto nextReading; } else { cout << head[indexer[key]]; buffer.erase(0, keyLength); } } } } } return 0; }
[ "metaphysis@yeah.net" ]
metaphysis@yeah.net
ccd50436eb1e31572ff1244532fb8ac184c8e79a
d75db18f0dcf48ee78a8a3e66c6e889af77dd7ee
/src/Special/Output.cpp
54314187e3103e8107ce98a50be8749591e92dcb
[]
no_license
ThomasMarches/NanoTekSpice
1e25583d8c48992f106e9de5974817e94b9d648e
cbed2141d2c5e73c522cff59f42dc4624e86d917
refs/heads/master
2023-05-27T04:24:56.435904
2021-06-02T08:00:58
2021-06-02T08:00:58
351,381,175
0
0
null
null
null
null
UTF-8
C++
false
false
301
cpp
#include "Output.hpp" #include "Exceptions/InvalidPin.hpp" namespace nts { Output::Output() : AComponent(1) { } Output::~Output() { } void Output::dump() const { std::cout << getName() << ": " << TristateToString(m_vValues[0]) << std::endl; } }
[ "56929277+ThomasMarches@users.noreply.github.com" ]
56929277+ThomasMarches@users.noreply.github.com
faf98ffd95cc989960e436ad821aeb29d66bd9a4
0f0b2c5e9095ba273992ab0b74a82f986b4f941e
/services/inputflinger/reader/mapper/InputMapper.cpp
a8fe39aa101d1527a4b82119afd188cd27e6dadb
[ "LicenseRef-scancode-unicode", "Apache-2.0" ]
permissive
LineageOS/android_frameworks_native
28274a8a6a3d2b16150702e0a34434bc45090b9a
c25b27db855a0a6d749bfd45d05322939d2ad39a
refs/heads/lineage-18.1
2023-08-04T11:18:47.942921
2023-05-05T12:54:26
2023-05-05T12:54:26
75,639,913
21
626
NOASSERTION
2021-06-11T19:11:21
2016-12-05T15:41:33
C++
UTF-8
C++
false
false
3,256
cpp
/* * Copyright (C) 2019 The Android Open Source Project * * 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 "../Macros.h" #include "InputMapper.h" #include "InputDevice.h" namespace android { InputMapper::InputMapper(InputDeviceContext& deviceContext) : mDeviceContext(deviceContext) {} InputMapper::~InputMapper() {} void InputMapper::populateDeviceInfo(InputDeviceInfo* info) { info->addSource(getSources()); } void InputMapper::dump(std::string& dump) {} void InputMapper::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) {} void InputMapper::reset(nsecs_t when) {} void InputMapper::timeoutExpired(nsecs_t when) {} int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) { return AKEY_STATE_UNKNOWN; } int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) { return AKEY_STATE_UNKNOWN; } int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) { return AKEY_STATE_UNKNOWN; } bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) { return false; } void InputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat, int32_t token) {} void InputMapper::cancelVibrate(int32_t token) {} void InputMapper::cancelTouch(nsecs_t when) {} int32_t InputMapper::getMetaState() { return 0; } void InputMapper::updateMetaState(int32_t keyCode) {} void InputMapper::updateExternalStylusState(const StylusState& state) {} status_t InputMapper::getAbsoluteAxisInfo(int32_t axis, RawAbsoluteAxisInfo* axisInfo) { return getDeviceContext().getAbsoluteAxisInfo(axis, axisInfo); } void InputMapper::bumpGeneration() { getDeviceContext().bumpGeneration(); } void InputMapper::dumpRawAbsoluteAxisInfo(std::string& dump, const RawAbsoluteAxisInfo& axis, const char* name) { if (axis.valid) { dump += StringPrintf(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d, resolution=%d\n", name, axis.minValue, axis.maxValue, axis.flat, axis.fuzz, axis.resolution); } else { dump += StringPrintf(INDENT4 "%s: unknown range\n", name); } } void InputMapper::dumpStylusState(std::string& dump, const StylusState& state) { dump += StringPrintf(INDENT4 "When: %" PRId64 "\n", state.when); dump += StringPrintf(INDENT4 "Pressure: %f\n", state.pressure); dump += StringPrintf(INDENT4 "Button State: 0x%08x\n", state.buttons); dump += StringPrintf(INDENT4 "Tool Type: %" PRId32 "\n", state.toolType); } } // namespace android
[ "prabirmsp@google.com" ]
prabirmsp@google.com
4c91793a25451eb45047ef4e4f943b7a8dd68ac7
467894d8fca451d8041ef82b6aa153f9bd38675b
/the-cursed-room/main.cpp
07ab4cd3c013ce1ccb380709d310f639ea8d491c
[]
no_license
w-k-s/ProgrammingPuzzles
19bfdeea1f15fd00a237fe24f9bcc27c7c7bc7a4
131c055e8d42c52becc82b32a6c7d2e6b531a631
refs/heads/master
2022-10-11T09:20:46.162093
2022-10-04T19:21:36
2022-10-04T19:21:36
158,879,006
0
1
null
null
null
null
UTF-8
C++
false
false
2,937
cpp
#include <iostream> #include <fstream> #include <sstream> #include <vector> #include <set> #include <map> #include <algorithm> #define INDEX(bedNumber) (bedNumber - 1) int main() { std::ifstream inputFile("input", std::ios_base::in); int lineNumber; std::set<int> assignedBedrooms; std::map<int, std::vector<int> > studentNumberToRequestedBedroomsMap; std::vector<int> bedroomDemand; if (inputFile.is_open()) { for (std::string line;getline(inputFile, line);) { ++lineNumber; std::stringstream lineStream(line); if (lineNumber == 1) { continue; } if (bedroomDemand.empty()) { int numberOfStudents; lineStream >> numberOfStudents; int numberOfBeds; lineStream >> numberOfBeds; bedroomDemand.resize(numberOfBeds); std::fill(bedroomDemand.begin(), bedroomDemand.end(), 0); // initialize studentNumberToRequestedBedroomsMap for (int i = 1; i <= numberOfStudents; i++) { studentNumberToRequestedBedroomsMap[i] = std::vector<int>(); } continue; } int bedroomNumber; lineStream >> bedroomNumber; int studentNumber; lineStream >> studentNumber; if (studentNumber != 0) { studentNumberToRequestedBedroomsMap[studentNumber].push_back(bedroomNumber); bedroomDemand[INDEX(bedroomNumber)]++; } else { // End of test case // Sort bedRequested in order of least in-demand to most in-demand for (auto& item : studentNumberToRequestedBedroomsMap) { std::sort( item.second.begin(), item.second.end(), [&bedroomDemand](int bedroomNumberLeft, int bedroomNumberRight) { return bedroomDemand[INDEX(bedroomNumberLeft)] < bedroomDemand[INDEX(bedroomNumberRight)]; }); } // Start assigning rooms to students starting with the least in-demand // room requested. for (auto item : studentNumberToRequestedBedroomsMap) { for (auto bedroomNumber : item.second) { auto result = assignedBedrooms.insert(bedroomNumber); if (result.second) { break; } } } std::cout << assignedBedrooms.size() << std::endl; assignedBedrooms.clear(); studentNumberToRequestedBedroomsMap.clear(); bedroomDemand.clear(); } } inputFile.close(); } }
[ "waqqas.abdulkareem@gmail.com" ]
waqqas.abdulkareem@gmail.com