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
7a55ddc8bd88bb10cba386099a1d1abcbff6d069
ee8101887e8fe39af5993c1a4f370a7163689ab1
/1114.cpp
a6e03a02841642e4c96bf68516837ffc1aff029f
[]
no_license
fanxingzju/PAT_advanced
23f0ff9f35e7e9f111651bed048451fbd709eada
b6187a98b6970fd35ccefc7c323c8677564940e2
refs/heads/master
2021-01-10T12:14:06.442386
2016-04-07T13:12:10
2016-04-07T13:12:10
55,694,296
2
0
null
null
null
null
GB18030
C++
false
false
2,780
cpp
/* 这个题目最困难的地方是确定哪些人在同一个家庭, 将族谱作为一张图来考虑, 父母和子女间有连通路径, 利用DFS可以确定图的连通区域, 一块连通区域即为一个家庭*/ #include <iostream> #include <set> #include <vector> #include <algorithm> #include <cstdio> using namespace std; const int MAXNODE = 10010; /* 为了优化效率,用邻接表的方式存储图*/ class node { public: node(): adj(), visited(true), M_estate(0), Area(0){} set<int> adj; bool visited; float M_estate; float Area; }; int N; node inputs[MAXNODE]; class elem { public: elem():ID(0), M(0), total_sets(0), total_area(0){} bool operator<(const elem& target) { if (AVG_area == target.AVG_area) { return ID < target.ID; } return AVG_area > target.AVG_area; } void clear() { ID = 0; M = 0; total_area = 0; total_sets = 0; } void compute_AVG() { AVG_sets = total_sets/M; AVG_area = total_area/M; } int ID; int M; float total_sets; float total_area; float AVG_sets; float AVG_area; }; vector<elem> res; void dfs(int index, set<int> &family) { int ni; family.insert(index); inputs[index].visited = true; for (set<int>::iterator iter = inputs[index].adj.begin(); iter != inputs[index].adj.end(); ++iter) { ni = *iter; if (!inputs[ni].visited) { dfs(ni, family); } } } int main() { int ID, father, mother, k, temp; set<int> family; elem tmpres; cin >> N; for (int i = 0; i != N; ++i) { cin >> ID; inputs[ID].visited = false; cin >> father >> mother >> k; if (-1 != mother) { inputs[ID].adj.insert(mother); inputs[mother].adj.insert(ID); inputs[mother].visited = false; } if (-1 != father) { inputs[ID].adj.insert(father); inputs[father].adj.insert(ID); inputs[father].visited = false; } for (int j = 0; j != k; ++j) { cin >> temp; inputs[ID].adj.insert(temp); inputs[temp].visited = false; inputs[temp].adj.insert(ID); } cin >> inputs[ID].M_estate; cin >> inputs[ID].Area; /* 建立图, 只有题目输入中涉及到的ID需要全部访问, 因此只将它们的visited位置为false*/ } for (int i = 0; i != MAXNODE; ++i) { if (!inputs[i].visited) { family.clear(); tmpres.clear(); dfs(i, family); tmpres.ID = *family.begin(); for (set<int>::iterator iter = family.begin(); iter != family.end(); ++iter) { ++tmpres.M; tmpres.total_area += inputs[*iter].Area; tmpres.total_sets += inputs[*iter].M_estate; } tmpres.compute_AVG(); res.push_back(tmpres); } } sort(res.begin(), res.end()); cout << res.size() << endl; for (int i = 0; i != res.size(); ++i) { printf("%04d %d %0.03f %0.03f\n", res[i].ID, res[i].M, res[i].AVG_sets, res[i].AVG_area); } return 0; }
[ "fanzhaonan@zju.edu.cn" ]
fanzhaonan@zju.edu.cn
6ac1aead8bf5b40b6541a4f61a0e444fca4dc09a
0d6ce1920a597e6c706d5cdc0876ab5f1f56ead0
/xcore/cl_tonemapping_handler.cpp
27b3221f7b771373f79a94579eb2e67f97773780
[ "Apache-2.0" ]
permissive
mohendra/libxcam
f5e731ca9b94c14d4e6ccdf07ce51f812f6e48e8
a6580237a0b4194f10d3f5777b1f47c9f93d26f8
refs/heads/master
2021-01-20T15:59:11.467017
2015-10-08T08:51:28
2015-10-09T11:28:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,447
cpp
/* * cl_tonemapping_handler.cpp - CL tonemapping handler * * Copyright (c) 2015 Intel Corporation * * 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. * * Author: Yao Wang <yao.y.wang@intel.com> */ #include "xcam_utils.h" #include "cl_tonemapping_handler.h" namespace XCam { CLTonemappingImageKernel::CLTonemappingImageKernel (SmartPtr<CLContext> &context, const char *name) : CLImageKernel (context, name), _initial_color_bits (12) { } void CLTonemappingImageKernel::set_initial_color_bits(uint32_t color_bits) { _initial_color_bits = color_bits; } XCamReturn CLTonemappingImageKernel::prepare_arguments ( SmartPtr<DrmBoBuffer> &input, SmartPtr<DrmBoBuffer> &output, CLArgument args[], uint32_t &arg_count, CLWorkSize &work_size) { SmartPtr<CLContext> context = get_context (); _image_in = new CLVaImage (context, input); _image_out = new CLVaImage (context, output); XCAM_ASSERT (_image_in->is_valid () && _image_out->is_valid ()); XCAM_FAIL_RETURN ( WARNING, _image_in->is_valid () && _image_out->is_valid (), XCAM_RETURN_ERROR_MEM, "cl image kernel(%s) in/out memory not available", get_kernel_name ()); //XCAM_LOG_INFO ("IN tonemapping color bits = %d\n",_initial_color_bits); //set args; args[0].arg_adress = &_image_in->get_mem_id (); args[0].arg_size = sizeof (cl_mem); args[1].arg_adress = &_image_out->get_mem_id (); args[1].arg_size = sizeof (cl_mem); args[2].arg_adress = &_initial_color_bits; args[2].arg_size = sizeof (_initial_color_bits); arg_count = 3; const CLImageDesc out_info = _image_out->get_image_desc (); work_size.dim = XCAM_DEFAULT_IMAGE_DIM; work_size.global[0] = out_info.width; work_size.global[1] = out_info.height; work_size.local[0] = 8; work_size.local[1] = 4; return XCAM_RETURN_NO_ERROR; } CLTonemappingImageHandler::CLTonemappingImageHandler (const char *name) : CLImageHandler (name) , _output_format (V4L2_PIX_FMT_RGBA32) { } bool CLTonemappingImageHandler::set_tonemapping_kernel(SmartPtr<CLTonemappingImageKernel> &kernel) { SmartPtr<CLImageKernel> image_kernel = kernel; add_kernel (image_kernel); _tonemapping_kernel = kernel; return true; } void CLTonemappingImageHandler::set_initial_color_bits(uint32_t color_bits) { _tonemapping_kernel->set_initial_color_bits(color_bits); } XCamReturn CLTonemappingImageHandler::prepare_buffer_pool_video_info ( const VideoBufferInfo &input, VideoBufferInfo &output) { bool format_inited = output.init (_output_format, input.width, input.height); XCAM_FAIL_RETURN ( WARNING, format_inited, XCAM_RETURN_ERROR_PARAM, "CL image handler(%s) ouput format(%s) unsupported", get_name (), xcam_fourcc_to_string (_output_format)); return XCAM_RETURN_NO_ERROR; } SmartPtr<CLImageHandler> create_cl_tonemapping_image_handler (SmartPtr<CLContext> &context) { SmartPtr<CLTonemappingImageHandler> tonemapping_handler; SmartPtr<CLTonemappingImageKernel> tonemapping_kernel; XCamReturn ret = XCAM_RETURN_NO_ERROR; tonemapping_kernel = new CLTonemappingImageKernel (context, "kernel_tonemapping"); { XCAM_CL_KERNEL_FUNC_SOURCE_BEGIN(kernel_tonemapping) #include "kernel_tonemapping.clx" XCAM_CL_KERNEL_FUNC_END; ret = tonemapping_kernel->load_from_source (kernel_tonemapping_body, strlen (kernel_tonemapping_body)); XCAM_FAIL_RETURN ( WARNING, ret == XCAM_RETURN_NO_ERROR, NULL, "CL image handler(%s) load source failed", tonemapping_kernel->get_kernel_name()); } XCAM_ASSERT (tonemapping_kernel->is_valid ()); tonemapping_handler = new CLTonemappingImageHandler("cl_handler_tonemapping"); tonemapping_handler->set_tonemapping_kernel(tonemapping_kernel); return tonemapping_handler; } };
[ "feng.yuan@intel.com" ]
feng.yuan@intel.com
c65f7550e4a2f63ce8791e0525afdc7f40633644
7b47a48d74d21a0caa0a4f382b53765582f1e3cf
/shared/cs488-framework/MeshConsolidator.hpp
31e21975701f95799f93fe72458713da99f655b4
[]
no_license
dearonesama/cs488
a3513ed38d8459c26b050549b6d40b1ce180a380
2b70667b27c994c73288231ce297661bf15ac8da
refs/heads/master
2022-03-06T00:41:25.051184
2017-09-21T05:28:12
2017-09-21T05:28:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,305
hpp
#pragma once #include "cs488-framework/BatchInfo.hpp" #include <glm/glm.hpp> #include <initializer_list> #include <vector> #include <unordered_map> #include <string> // String identifier for a mesh. typedef std::string MeshId; // File path to a .obj file. typedef std::string ObjFilePath; // BatchInfoMap is an associative container that maps a unique MeshId to a BatchInfo // object. Each BatchInfo object contains an index offset and the number of indices // required to render the mesh with identifier MeshId. typedef std::unordered_map<MeshId, BatchInfo> BatchInfoMap; /* * Class for consolidating all vertex data within a list of .obj files. */ class MeshConsolidator { public: MeshConsolidator(); MeshConsolidator(std::initializer_list<ObjFilePath> objFileList); ~MeshConsolidator(); const float * getVertexPositionDataPtr() const; const float * getVertexNormalDataPtr() const; const float * getUVDataPtr() const; size_t getNumVertexPositionBytes() const; size_t getNumVertexNormalBytes() const; size_t getNumUVBytes() const; void getBatchInfoMap(BatchInfoMap & batchInfoMap) const; private: std::vector<glm::vec3> m_vertexPositionData; std::vector<glm::vec3> m_vertexNormalData; std::vector<glm::vec2> m_uvData; BatchInfoMap m_batchInfoMap; };
[ "ramanpreet.nara@gmail.com" ]
ramanpreet.nara@gmail.com
532a0ef167f3cc00f297609308576df5aa00bf26
93c9499a60687ca615bda7469f18480a1480763a
/1463/solve.cpp
1a48744e8d0b0600f26a63a9093ab7e71146ec6c
[]
no_license
chin0/everydayalgo
93257812a758fbdf4bd02d121a9057166e6a3bca
f6d2b5e58f15b1f2c7e41d1a2b5cf4051b6d2bc8
refs/heads/master
2022-09-26T23:14:21.566812
2022-08-25T09:15:17
2022-08-25T09:15:17
96,144,716
3
0
null
null
null
null
UTF-8
C++
false
false
525
cpp
#include <iostream> #include <algorithm> #include <vector> using namespace std; int dp[1000001]; int solve(int n) { dp[0] = 0; dp[1] = 0; dp[2] = 1; dp[3] = 1; for(int i = 4; i <= n; i++) { dp[i] = dp[i-1]; if(i % 3 == 0) dp[i] = min(dp[i],dp[i/3]); if(i % 2 == 0) dp[i] = min(dp[i],dp[i/2]); dp[i] += 1; } return dp[n]; } int main(void) { int n; cin >> n; ios_base::sync_with_stdio(false); cout << solve(n) << endl; }
[ "pypi1103@gmail.com" ]
pypi1103@gmail.com
70f10639435a775e26d3678ecb2ef4e3bc260186
c79d0b76b076dc7c6db5c20b422d17ee4bffa863
/src/gb_cpu.cc
2ad386d3873e83741fe94a3f1a9878c77ca31aac
[ "MIT" ]
permissive
0ctobyte/goodboy
58dde63752e768e8c22dd46073a81cecd826ac21
3f2cda52dc24be34badea12645a1e3baa66a1250
refs/heads/master
2022-02-06T21:36:44.243593
2022-01-12T20:02:57
2022-01-12T20:02:57
173,666,947
1
1
null
null
null
null
UTF-8
C++
false
false
31,542
cc
/* * Copyright (c) 2019 Sekhar Bhattacharya * * SPDX-License-Identifier: MIT */ #include "gb_logger.h" #include "gb_memory_map.h" #include "gb_cpu.h" #include "gb_cpu_instructions.h" #include "gb_cpu_cb_instructions.h" #define FLAGS_IS_SET(flags) ((m_registers.f & (flags)) != 0) #define FLAGS_IS_CLEAR(flags) ((m_registers.f & (flags)) == 0) #define FLAGS_SET(flags) { m_registers.f |= (flags); } #define FLAGS_CLEAR(flags) { m_registers.f &= ~(flags); } #define FLAGS_TOGGLE(flags) { m_registers.f ^= (flags); } #define FLAGS_SET_IF_Z(x) { if (static_cast<uint8_t>((x)) == 0) FLAGS_SET(FLAGS_Z); } #define FLAGS_SET_IF_H(x,y) { if ((((x) & 0x0f) + ((y) & 0x0f)) & 0xf0) FLAGS_SET(FLAGS_H); } #define FLAGS_SET_IF_C(x) { if ((x) & 0xff00) FLAGS_SET(FLAGS_C); } #define FLAGS_SET_IF_H_16(x,y) { if ((((x) & 0xfff) + ((y) & 0xfff)) & 0xf000) FLAGS_SET(FLAGS_H); } #define FLAGS_SET_IF_C_16(x) { if ((x) & 0xffff0000) FLAGS_SET(FLAGS_C); } #define FLAGS_SET_IF_H_BORROW(x,y) { if (((x) & 0x0f) > ((y) & 0x0f)) FLAGS_SET(FLAGS_H); } #define FLAGS_SET_IF_C_BORROW(x,y) { if ((x) > (y)) FLAGS_SET(FLAGS_C); } gb_cpu::gb_cpu(gb_memory_map& memory_map) : m_instructions(INSTRUCTIONS_INIT), m_cb_instructions(CB_INSTRUCTIONS_INIT), m_memory_map(memory_map), m_eidi_flag(EIDI_NONE), m_interrupt_enable(true), m_halted(false), m_bp_enabled(false), m_wp_enabled(false), m_bp(), m_wp() { m_registers.af = 0x01b0; m_registers.bc = 0x0013; m_registers.de = 0x00d8; m_registers.hl = 0x014d; m_registers.sp = 0xfffe; m_registers.pc = 0x0000; } gb_cpu::~gb_cpu() { } void gb_cpu::dump_registers() const { char buf[256]; snprintf(buf, 256, "AF: 0x%02x.%02x BC: 0x%02x.%02x DE: 0x%02x.%02x HL: 0x%02x.%02x SP: 0x%04x PC: 0x%04x FLAGS: %c%c%c%c", m_registers.a, m_registers.f, m_registers.b, m_registers.c, m_registers.d, m_registers.e, m_registers.h, m_registers.l, m_registers.sp, m_registers.pc, FLAGS_IS_SET(FLAGS_Z) ? 'Z' : '-', FLAGS_IS_SET(FLAGS_N) ? 'N' : '-', FLAGS_IS_SET(FLAGS_H) ? 'H' : '-', FLAGS_IS_SET(FLAGS_C) ? 'C' : '-'); GB_LOGGER(GB_LOG_TRACE) << buf << std::endl; } uint16_t gb_cpu::get_pc() const { return m_registers.pc; } void gb_cpu::set_pc(uint16_t pc) { m_registers.pc = pc; } bool gb_cpu::handle_interrupt(uint16_t jump_address) { // Always break out of halted mode if an interrupt occurs m_halted = false; if (!m_interrupt_enable) return false; // Disable interrupts m_interrupt_enable = false; // Push current PC onto the stack _operand_set_mem_sp_16(0, m_registers.pc); // Jump to interrupt address m_registers.pc = jump_address; return true; } int gb_cpu::step() { // Check if in halted mode, do nothing and return 4 CPU clock cycles (i.e. 1 system clock cycle) if (m_halted) return 4; uint8_t opcode = m_memory_map.read_byte(m_registers.pc); const instruction_t& instruction = m_instructions[opcode]; if (instruction.op_exec == nullptr) { std::string unknown_str ("UNKNOWN"); _op_print_type0(unknown_str, m_registers.pc, 0, 0); m_registers.pc++; return 0; } // Enabling or disabling the interrupt flags are delayed by one cycles // The eidi_flag is set by the EI and DI instructions and checked the next cycle here if (m_eidi_flag == EIDI_IENABLE) m_interrupt_enable = true; if (m_eidi_flag == EIDI_IDISABLE) m_interrupt_enable = false; m_eidi_flag = EIDI_NONE; // Execute instruction and catch any watchpoint exceptions int cycles = 0; gb_cpu::registers_t saved_registers = m_registers; try { cycles = instruction.op_exec(instruction); } catch (const gb_watchpoint_exception& wp) { // Rollback register state m_registers = saved_registers; // Throw watchpoint exception with custom message throw gb_watchpoint_exception("Watchpoing hit:", wp.get_val()); } // Check for breakpoints if (m_bp_enabled) m_bp.match(m_registers.pc, cycles); return cycles; } int gb_cpu::_op_exec_cb(const instruction_t& instruction) { uint8_t cb_opcode = m_memory_map.read_byte(m_registers.pc+1); const instruction_t& cb_instruction = m_cb_instructions[cb_opcode]; if (cb_instruction.op_exec == nullptr) { std::string unknown_str ("UNKNOWN CB"); _op_print_type0(unknown_str, m_registers.pc, 0, 0); m_registers.pc += 2; return 0; } int cycles = cb_instruction.op_exec(cb_instruction); m_registers.pc++; return cycles; } int gb_cpu::_op_exec_nop(const instruction_t& instruction) { uint16_t pc = m_registers.pc++; instruction.op_print(instruction.disassembly, pc, 0, 0); return instruction.cycles_hi; } int gb_cpu::_op_exec_stop(const instruction_t& instruction) { uint16_t pc = m_registers.pc++; // TODO: Implement stop instruction.op_print(instruction.disassembly, pc, 0, 0); return instruction.cycles_hi; } int gb_cpu::_op_exec_halt(const instruction_t& instruction) { uint16_t pc = m_registers.pc++; m_halted = true; instruction.op_print(instruction.disassembly, pc, 0, 0); return instruction.cycles_hi; } int gb_cpu::_op_exec_ld(const instruction_t& instruction) { uint16_t pc = m_registers.pc++; uint16_t data = instruction.get_operand1(); uint16_t addr = instruction.get_operand2 == nullptr ? 0 : instruction.get_operand2(); instruction.set_operand(addr, data); instruction.op_print(instruction.disassembly, pc, data, addr); return instruction.cycles_hi; } int gb_cpu::_op_exec_add8(const instruction_t& instruction) { uint16_t pc = m_registers.pc++; uint16_t a1 = instruction.get_operand1(); uint16_t a2 = instruction.get_operand2(); uint16_t sum = a1 + a2; FLAGS_CLEAR(FLAGS_Z | FLAGS_N | FLAGS_H | FLAGS_C); FLAGS_SET_IF_Z(sum); FLAGS_SET_IF_H(a1, a2); FLAGS_SET_IF_C(sum); instruction.set_operand(0, sum); instruction.op_print(instruction.disassembly, pc, a1, a2); return instruction.cycles_hi; } int gb_cpu::_op_exec_add16(const instruction_t& instruction) { uint16_t pc = m_registers.pc++; uint32_t a1 = instruction.get_operand1(); uint32_t a2 = instruction.get_operand2(); uint32_t sum = a1 + a2; FLAGS_CLEAR(FLAGS_N | FLAGS_H | FLAGS_C); FLAGS_SET_IF_H_16(a1, a2); FLAGS_SET_IF_C_16(sum); instruction.set_operand(0, static_cast<uint16_t>(sum)); instruction.op_print(instruction.disassembly, pc, static_cast<uint16_t>(a1), static_cast<uint16_t>(a2)); return instruction.cycles_hi; } int gb_cpu::_op_exec_addsp(const instruction_t& instruction) { uint16_t pc = m_registers.pc++; int32_t a1 = static_cast<int32_t>(static_cast<int8_t>(instruction.get_operand1())); int32_t a2 = static_cast<int32_t>(instruction.get_operand2()); int32_t sum = a1 + a2; FLAGS_CLEAR(FLAGS_Z | FLAGS_N | FLAGS_H | FLAGS_C); FLAGS_SET_IF_H(a1, a2); FLAGS_SET_IF_C((a1 & 0xff) + (a2 & 0xff)); instruction.set_operand(0, static_cast<uint16_t>(sum)); instruction.op_print(instruction.disassembly, pc, static_cast<uint16_t>(a1), static_cast<uint16_t>(a2)); return instruction.cycles_hi; } int gb_cpu::_op_exec_adc(const instruction_t& instruction) { uint16_t pc = m_registers.pc++; uint8_t carry = FLAGS_IS_SET(FLAGS_C) ? 1 : 0; uint16_t a1 = instruction.get_operand1(); uint16_t a2 = instruction.get_operand2(); uint16_t sum = a1 + a2 + carry; FLAGS_CLEAR(FLAGS_Z | FLAGS_N | FLAGS_H | FLAGS_C); FLAGS_SET_IF_Z(sum); FLAGS_SET_IF_C(sum); if (((a1 & 0x0f) + (a2 & 0x0f) + carry) & 0xf0) FLAGS_SET(FLAGS_H); instruction.set_operand(0, sum); instruction.op_print(instruction.disassembly, pc, a1, a2); return instruction.cycles_hi; } int gb_cpu::_op_exec_sub(const instruction_t& instruction) { uint16_t pc = m_registers.pc++; uint16_t a1 = instruction.get_operand1(); uint16_t a2 = instruction.get_operand2(); uint16_t sum = a2 - a1; FLAGS_CLEAR(FLAGS_Z | FLAGS_N | FLAGS_H | FLAGS_C); FLAGS_SET_IF_Z(sum); FLAGS_SET(FLAGS_N); FLAGS_SET_IF_H_BORROW(a1, a2); FLAGS_SET_IF_C_BORROW(a1, a2); if (instruction.set_operand != nullptr) { instruction.set_operand(0, sum); } instruction.op_print(instruction.disassembly, pc, a1, a2); return instruction.cycles_hi; } int gb_cpu::_op_exec_sbc(const instruction_t& instruction) { uint16_t pc = m_registers.pc++; uint16_t carry = FLAGS_IS_SET(FLAGS_C) ? 1 : 0; uint16_t a1 = instruction.get_operand1(); uint16_t a2 = instruction.get_operand2(); uint16_t sum = a2 - (a1 + carry); FLAGS_CLEAR(FLAGS_Z | FLAGS_N | FLAGS_H | FLAGS_C); FLAGS_SET_IF_Z(sum); FLAGS_SET(FLAGS_N); if (((a1 & 0x0f) + carry) > (a2 & 0x0f)) FLAGS_SET(FLAGS_H); if ((a1 + carry) > a2) FLAGS_SET(FLAGS_C); instruction.set_operand(0, sum); instruction.op_print(instruction.disassembly, pc, a1, a2); return instruction.cycles_hi; } int gb_cpu::_op_exec_jr(const instruction_t& instruction) { uint16_t pc = m_registers.pc++; int cycles = instruction.cycles_lo; int16_t offset = static_cast<int8_t>(instruction.get_operand1()); uint16_t jump_pc = static_cast<uint16_t>(static_cast<int16_t>(m_registers.pc) + offset); uint16_t do_jump = instruction.get_operand2 == nullptr ? 1 : instruction.get_operand2(); if (do_jump != 0) { instruction.set_operand(0, jump_pc); cycles = instruction.cycles_hi; } instruction.op_print(instruction.disassembly, pc, jump_pc, 0); return cycles; } int gb_cpu::_op_exec_jp(const instruction_t& instruction) { uint16_t pc = m_registers.pc++; int cycles = instruction.cycles_lo; uint16_t jump_pc = instruction.get_operand1(); uint16_t do_jump = instruction.get_operand2 == nullptr ? 1 : instruction.get_operand2(); if (do_jump != 0) { instruction.set_operand(0, jump_pc); cycles = instruction.cycles_hi; } instruction.op_print(instruction.disassembly, pc, jump_pc, 0); return cycles; } int gb_cpu::_op_exec_call(const instruction_t& instruction) { uint16_t pc = m_registers.pc++; int cycles = instruction.cycles_lo; uint16_t jump_pc = instruction.get_operand1(); uint16_t do_jump = instruction.get_operand2 == nullptr ? 1 : instruction.get_operand2(); if (do_jump != 0) { instruction.set_operand(0, m_registers.pc); m_registers.pc = jump_pc; cycles = instruction.cycles_hi; } instruction.op_print(instruction.disassembly, pc, jump_pc, 0); return cycles; } int gb_cpu::_op_exec_ret(const instruction_t& instruction) { uint16_t pc = m_registers.pc++; int cycles = instruction.cycles_lo; uint16_t do_jump = instruction.get_operand2 == nullptr ? 1 : instruction.get_operand2(); if (do_jump != 0) { uint16_t jump_pc = instruction.get_operand1(); instruction.set_operand(0, jump_pc); cycles = instruction.cycles_hi; } instruction.op_print(instruction.disassembly, pc, 0, 0); return cycles; } int gb_cpu::_op_exec_reti(const instruction_t& instruction) { m_interrupt_enable = true; return gb_cpu::_op_exec_ret(instruction); } int gb_cpu::_op_exec_rst(const instruction_t& instruction) { uint16_t pc = m_registers.pc++; uint16_t jump_pc = instruction.get_operand1(); instruction.set_operand(0, m_registers.pc); m_registers.pc = jump_pc; instruction.op_print(instruction.disassembly, pc, jump_pc, 0); return instruction.cycles_hi; } int gb_cpu::_op_exec_da(const instruction_t& instruction) { uint16_t pc = m_registers.pc++; uint16_t a = instruction.get_operand1(); // Good explanation for this instruction here: https://ehaskins.com/2018-01-30%20Z80%20DAA/ if (FLAGS_IS_SET(FLAGS_N)) { // Subtraction case; adjust top nibble if C flag is set // adjust bottom nibble if H flag is set. Adjustment is done by subtracting 0x6. if (FLAGS_IS_SET(FLAGS_H)) a = (a - 0x06) & 0xff; if (FLAGS_IS_SET(FLAGS_C)) a -= 0x60; } else { // Addition case; adjust top nibble if C flag is set or result is > 0x99 // which is the largest # that can be represented by 8-bit BCD. // Adjust bottom nibble if H flag is set or if > 0x9. 0x9 is the largest each nibble // can represent. if (FLAGS_IS_SET(FLAGS_H) || (a & 0x0f) > 0x09) a += 0x06; if (FLAGS_IS_SET(FLAGS_C) || a > 0x9F) a += 0x60; } FLAGS_CLEAR(FLAGS_Z | FLAGS_H); FLAGS_SET_IF_Z(a); FLAGS_SET_IF_C(a); instruction.set_operand(0, a); instruction.op_print(instruction.disassembly, pc, a, 0); return instruction.cycles_hi; } int gb_cpu::_op_exec_rlc(const instruction_t& instruction) { uint16_t pc = m_registers.pc++; uint16_t val = static_cast<uint16_t>(instruction.get_operand1() << 1); uint16_t addr = instruction.get_operand2 == nullptr ? 0 : instruction.get_operand2(); val |= ((val >> 8) & 0x1); FLAGS_CLEAR(FLAGS_Z | FLAGS_N | FLAGS_H | FLAGS_C); FLAGS_SET_IF_Z(val); FLAGS_SET_IF_C(val); instruction.set_operand(addr, val); instruction.op_print(instruction.disassembly, pc, val, 0); return instruction.cycles_hi; } int gb_cpu::_op_exec_rlca(const instruction_t& instruction) { int cycles = _op_exec_rlc(instruction); FLAGS_CLEAR(FLAGS_Z); return cycles; } int gb_cpu::_op_exec_rl(const instruction_t& instruction) { uint16_t pc = m_registers.pc++; uint16_t val = static_cast<uint16_t>(instruction.get_operand1() << 1); uint16_t addr = instruction.get_operand2 == nullptr ? 0 : instruction.get_operand2(); int carry = FLAGS_IS_SET(FLAGS_C) ? 1 : 0; val |= carry; FLAGS_CLEAR(FLAGS_Z | FLAGS_N | FLAGS_H | FLAGS_C); FLAGS_SET_IF_Z(val); FLAGS_SET_IF_C(val); instruction.set_operand(addr, val); instruction.op_print(instruction.disassembly, pc, val, 0); return instruction.cycles_hi; } int gb_cpu::_op_exec_rla(const instruction_t& instruction) { int cycles = _op_exec_rl(instruction); FLAGS_CLEAR(FLAGS_Z); return cycles; } int gb_cpu::_op_exec_rrc(const instruction_t& instruction) { uint16_t pc = m_registers.pc++; uint16_t val = instruction.get_operand1(); uint16_t addr = instruction.get_operand2 == nullptr ? 0 : instruction.get_operand2(); int bit1 = val & 0x1; val = static_cast<uint16_t>((val >> 1) | (bit1 << 7)); FLAGS_CLEAR(FLAGS_Z | FLAGS_N | FLAGS_H | FLAGS_C); FLAGS_SET_IF_Z(val); FLAGS_SET_IF_C(bit1 << 8); instruction.set_operand(addr, val); instruction.op_print(instruction.disassembly, pc, val, 0); return instruction.cycles_hi; } int gb_cpu::_op_exec_rrca(const instruction_t& instruction) { int cycles = _op_exec_rrc(instruction); FLAGS_CLEAR(FLAGS_Z); return cycles; } int gb_cpu::_op_exec_rr(const instruction_t& instruction) { uint16_t pc = m_registers.pc++; uint16_t val = instruction.get_operand1(); uint16_t addr = instruction.get_operand2 == nullptr ? 0 : instruction.get_operand2(); int bit1 = val & 0x1; int carry = FLAGS_IS_SET(FLAGS_C) ? 1 : 0; val = static_cast<uint16_t>((val >> 1) | (carry << 0x7)); FLAGS_CLEAR(FLAGS_Z | FLAGS_N | FLAGS_H | FLAGS_C); FLAGS_SET_IF_Z(val); FLAGS_SET_IF_C(bit1 << 8); instruction.set_operand(addr, val); instruction.op_print(instruction.disassembly, pc, val, 0); return instruction.cycles_hi; } int gb_cpu::_op_exec_rra(const instruction_t& instruction) { int cycles = _op_exec_rr(instruction); FLAGS_CLEAR(FLAGS_Z); return cycles; } int gb_cpu::_op_exec_sla(const instruction_t& instruction) { uint16_t pc = m_registers.pc++; uint16_t val = static_cast<uint16_t>(instruction.get_operand1() << 1); uint16_t addr = instruction.get_operand2 == nullptr ? 0 : instruction.get_operand2(); FLAGS_CLEAR(FLAGS_Z | FLAGS_N | FLAGS_H | FLAGS_C); FLAGS_SET_IF_Z(val); FLAGS_SET_IF_C(val); instruction.set_operand(addr, val); instruction.op_print(instruction.disassembly, pc, val, 0); return instruction.cycles_hi; } int gb_cpu::_op_exec_sra(const instruction_t& instruction) { uint16_t pc = m_registers.pc++; uint16_t val = instruction.get_operand1(); uint16_t addr = instruction.get_operand2 == nullptr ? 0 : instruction.get_operand2(); int bit0 = val & 0x1; int bit7 = val & 0x80; val = static_cast<uint16_t>((val >> 1) | bit7); FLAGS_CLEAR(FLAGS_Z | FLAGS_N | FLAGS_H | FLAGS_C); FLAGS_SET_IF_Z(val); FLAGS_SET_IF_C(bit0 << 0x8); instruction.set_operand(addr, val); instruction.op_print(instruction.disassembly, pc, val, 0); return instruction.cycles_hi; } int gb_cpu::_op_exec_srl(const instruction_t& instruction) { uint16_t pc = m_registers.pc++; uint16_t val = instruction.get_operand1(); uint16_t addr = instruction.get_operand2 == nullptr ? 0 : instruction.get_operand2(); int bit0 = val & 0x1; val = val >> 1; FLAGS_CLEAR(FLAGS_Z | FLAGS_N | FLAGS_H | FLAGS_C); FLAGS_SET_IF_Z(val); FLAGS_SET_IF_C(bit0 << 0x8); instruction.set_operand(addr, val); instruction.op_print(instruction.disassembly, pc, val, 0); return instruction.cycles_hi; } int gb_cpu::_op_exec_swap(const instruction_t& instruction) { uint16_t pc = m_registers.pc++; uint16_t val = instruction.get_operand1(); uint16_t addr = instruction.get_operand2 == nullptr ? 0 : instruction.get_operand2(); val = static_cast<uint16_t>((val << 4) | (val >> 4)); FLAGS_CLEAR(FLAGS_Z | FLAGS_N | FLAGS_H | FLAGS_C); FLAGS_SET_IF_Z(val); instruction.set_operand(addr, val); instruction.op_print(instruction.disassembly, pc, val, 0); return instruction.cycles_hi; } int gb_cpu::_op_exec_cpl(const instruction_t& instruction) { uint16_t pc = m_registers.pc++; uint16_t val = instruction.get_operand1(); FLAGS_SET(FLAGS_N | FLAGS_H); instruction.set_operand(0, ~val); instruction.op_print(instruction.disassembly, pc, val, 0); return instruction.cycles_hi; } int gb_cpu::_op_exec_inc(const instruction_t& instruction) { uint16_t pc = m_registers.pc++; uint16_t val = instruction.get_operand1(); instruction.set_operand(0, ++val); instruction.op_print(instruction.disassembly, pc, val, 0); return instruction.cycles_hi; } int gb_cpu::_op_exec_dec(const instruction_t& instruction) { uint16_t pc = m_registers.pc++; uint16_t val = instruction.get_operand1(); instruction.set_operand(0, --val); instruction.op_print(instruction.disassembly, pc, val, 0); return instruction.cycles_hi; } int gb_cpu::_op_exec_incf(const instruction_t& instruction) { uint16_t pc = m_registers.pc++; uint16_t val = instruction.get_operand1(); uint16_t addr = instruction.get_operand2 == nullptr ? 0 : instruction.get_operand2(); uint16_t vali = val + 1; FLAGS_CLEAR(FLAGS_Z | FLAGS_N | FLAGS_H); FLAGS_SET_IF_Z(vali); FLAGS_SET_IF_H(val, 1); instruction.set_operand(addr, vali); instruction.op_print(instruction.disassembly, pc, val, 0); return instruction.cycles_hi; } int gb_cpu::_op_exec_decf(const instruction_t& instruction) { uint16_t pc = m_registers.pc++; uint16_t val = instruction.get_operand1(); uint16_t addr = instruction.get_operand2 == nullptr ? 0 : instruction.get_operand2(); uint16_t vald = val - 1; FLAGS_CLEAR(FLAGS_Z | FLAGS_N | FLAGS_H); FLAGS_SET_IF_Z(vald); FLAGS_SET(FLAGS_N); FLAGS_SET_IF_H_BORROW(1, val); instruction.set_operand(addr, vald); instruction.op_print(instruction.disassembly, pc, val, 0); return instruction.cycles_hi; } int gb_cpu::_op_exec_scf(const instruction_t& instruction) { uint16_t pc = m_registers.pc++; FLAGS_CLEAR(FLAGS_N | FLAGS_H); FLAGS_SET(FLAGS_C); instruction.op_print(instruction.disassembly, pc, 0, 0); return instruction.cycles_hi; } int gb_cpu::_op_exec_ccf(const instruction_t& instruction) { uint16_t pc = m_registers.pc++; FLAGS_CLEAR(FLAGS_N | FLAGS_H); FLAGS_TOGGLE(FLAGS_C); instruction.op_print(instruction.disassembly, pc, 0, 0); return instruction.cycles_hi; } int gb_cpu::_op_exec_and(const instruction_t& instruction) { uint16_t pc = m_registers.pc++; uint16_t a1 = instruction.get_operand1(); uint16_t a2 = instruction.get_operand2(); uint16_t result = a1 & a2; FLAGS_CLEAR(FLAGS_Z | FLAGS_N | FLAGS_H | FLAGS_C); FLAGS_SET_IF_Z(result); FLAGS_SET(FLAGS_H); instruction.set_operand(0, result); instruction.op_print(instruction.disassembly, pc, a1, a2); return instruction.cycles_hi; } int gb_cpu::_op_exec_xor(const instruction_t& instruction) { uint16_t pc = m_registers.pc++; uint16_t a1 = instruction.get_operand1(); uint16_t a2 = instruction.get_operand2(); uint16_t result = a1 ^ a2; FLAGS_CLEAR(FLAGS_Z | FLAGS_N | FLAGS_H | FLAGS_C); FLAGS_SET_IF_Z(result); instruction.set_operand(0, result); instruction.op_print(instruction.disassembly, pc, a1, a2); return instruction.cycles_hi; } int gb_cpu::_op_exec_or(const instruction_t& instruction) { uint16_t pc = m_registers.pc++; uint16_t a1 = instruction.get_operand1(); uint16_t a2 = instruction.get_operand2(); uint16_t result = a1 | a2; FLAGS_CLEAR(FLAGS_Z | FLAGS_N | FLAGS_H | FLAGS_C); FLAGS_SET_IF_Z(result); instruction.set_operand(0, result); instruction.op_print(instruction.disassembly, pc, a1, a1); return instruction.cycles_hi; } int gb_cpu::_op_exec_bit(const instruction_t& instruction) { uint16_t pc = m_registers.pc++; uint16_t a1 = instruction.get_operand1(); uint16_t bit = instruction.get_operand2(); uint16_t result = a1 & (1 << bit); FLAGS_CLEAR(FLAGS_Z | FLAGS_N | FLAGS_H); FLAGS_SET_IF_Z(result); FLAGS_SET(FLAGS_H); instruction.op_print(instruction.disassembly, pc, a1, bit); return instruction.cycles_hi; } int gb_cpu::_op_exec_set(const instruction_t& instruction) { uint16_t pc = m_registers.pc++; uint16_t a1 = instruction.get_operand1(); uint16_t bit = instruction.get_operand2(); uint16_t result = static_cast<uint16_t>(a1 | (1 << bit)); instruction.set_operand(0, result); instruction.op_print(instruction.disassembly, pc, a1, bit); return instruction.cycles_hi; } int gb_cpu::_op_exec_res(const instruction_t& instruction) { uint16_t pc = m_registers.pc++; uint16_t a1 = instruction.get_operand1(); uint16_t bit = instruction.get_operand2(); uint16_t result = a1 & ~(1 << bit); instruction.set_operand(0, result); instruction.op_print(instruction.disassembly, pc, a1, bit); return instruction.cycles_hi; } int gb_cpu::_op_exec_di(const instruction_t& instruction) { uint16_t pc = m_registers.pc++; m_eidi_flag = EIDI_IDISABLE; instruction.op_print(instruction.disassembly, pc, 0, 0); return instruction.cycles_hi; } int gb_cpu::_op_exec_ei(const instruction_t& instruction) { uint16_t pc = m_registers.pc++; m_eidi_flag = EIDI_IENABLE; instruction.op_print(instruction.disassembly, pc, 0, 0); return instruction.cycles_hi; } uint8_t gb_cpu::_read_byte(uint16_t addr) { // Check for watchpoints if (m_wp_enabled) m_wp.match(addr); return m_memory_map.read_byte(addr); } void gb_cpu::_write_byte(uint16_t addr, uint8_t val) { // Check for watchpoints if (m_wp_enabled) m_wp.match(addr); m_memory_map.write_byte(addr, val); } uint16_t gb_cpu::_operand_get_register_a() { return m_registers.a; } uint16_t gb_cpu::_operand_get_register_f() { return m_registers.f; } uint16_t gb_cpu::_operand_get_register_af() { return m_registers.af; } uint16_t gb_cpu::_operand_get_register_b() { return m_registers.b; } uint16_t gb_cpu::_operand_get_register_c() { return m_registers.c; } uint16_t gb_cpu::_operand_get_register_bc() { return m_registers.bc; } uint16_t gb_cpu::_operand_get_register_d() { return m_registers.d; } uint16_t gb_cpu::_operand_get_register_e() { return m_registers.e; } uint16_t gb_cpu::_operand_get_register_de() { return m_registers.de; } uint16_t gb_cpu::_operand_get_register_h() { return m_registers.h; } uint16_t gb_cpu::_operand_get_register_l() { return m_registers.l; } uint16_t gb_cpu::_operand_get_register_hl() { return m_registers.hl; } uint16_t gb_cpu::_operand_get_register_sp() { return m_registers.sp; } uint16_t gb_cpu::_operand_get_register_pc() { return m_registers.pc; } uint16_t gb_cpu::_operand_get_register_hl_plus() { uint16_t hl = m_registers.hl; m_registers.hl++; return hl; } uint16_t gb_cpu::_operand_get_register_hl_minus() { uint16_t hl = m_registers.hl; m_registers.hl--; return hl; } uint16_t gb_cpu::_operand_get_mem_8() { return m_memory_map.read_byte(m_registers.pc++); } uint16_t gb_cpu::_operand_get_mem_16() { uint16_t byte_lo = m_memory_map.read_byte(m_registers.pc++); uint16_t byte_hi = m_memory_map.read_byte(m_registers.pc++); return static_cast<uint16_t>((byte_hi << 8) | byte_lo); } uint16_t gb_cpu::_operand_get_mem_8_plus_io_base() { uint16_t offset = _operand_get_mem_8(); return (offset + GB_MEMORY_MAP_IO_BASE); } uint16_t gb_cpu::_operand_get_register_c_plus_io_base() { uint16_t offset = _operand_get_register_c(); return (offset + GB_MEMORY_MAP_IO_BASE); } uint16_t gb_cpu::_operand_get_register_c_plus_io_base_mem() { uint16_t addr = _operand_get_register_c_plus_io_base(); return _read_byte(addr); } uint16_t gb_cpu::_operand_get_mem_16_mem() { uint16_t addr = _operand_get_mem_16(); return _read_byte(addr); } uint16_t gb_cpu::_operand_get_mem_bc() { return _read_byte(m_registers.bc); } uint16_t gb_cpu::_operand_get_mem_de() { return _read_byte(m_registers.de); } uint16_t gb_cpu::_operand_get_mem_hl() { return _read_byte(m_registers.hl); } uint16_t gb_cpu::_operand_get_mem_sp_8() { return _read_byte(m_registers.sp++); } uint16_t gb_cpu::_operand_get_mem_sp_16() { uint16_t byte_lo = _read_byte(m_registers.sp++); uint16_t byte_hi = _read_byte(m_registers.sp++); return static_cast<uint16_t>((byte_hi << 8) | byte_lo); } uint16_t gb_cpu::_operand_get_flags_is_nz() { return FLAGS_IS_CLEAR(FLAGS_Z); } uint16_t gb_cpu::_operand_get_flags_is_z() { return FLAGS_IS_SET(FLAGS_Z); } uint16_t gb_cpu::_operand_get_flags_is_nc() { return FLAGS_IS_CLEAR(FLAGS_C); } uint16_t gb_cpu::_operand_get_flags_is_c() { return FLAGS_IS_SET(FLAGS_C); } uint16_t gb_cpu::_operand_get_rst_00() { return 0x0; } uint16_t gb_cpu::_operand_get_rst_08() { return 0x8; } uint16_t gb_cpu::_operand_get_rst_10() { return 0x10; } uint16_t gb_cpu::_operand_get_rst_18() { return 0x18; } uint16_t gb_cpu::_operand_get_rst_20() { return 0x20; } uint16_t gb_cpu::_operand_get_rst_28() { return 0x28; } uint16_t gb_cpu::_operand_get_rst_30() { return 0x30; } uint16_t gb_cpu::_operand_get_rst_38() { return 0x38; } uint16_t gb_cpu::_operand_get_imm_0() { return 0x0; } uint16_t gb_cpu::_operand_get_imm_1() { return 0x1; } uint16_t gb_cpu::_operand_get_imm_2() { return 0x2; } uint16_t gb_cpu::_operand_get_imm_3() { return 0x3; } uint16_t gb_cpu::_operand_get_imm_4() { return 0x4; } uint16_t gb_cpu::_operand_get_imm_5() { return 0x5; } uint16_t gb_cpu::_operand_get_imm_6() { return 0x6; } uint16_t gb_cpu::_operand_get_imm_7() { return 0x7; } void gb_cpu::_operand_set_register_a(uint16_t addr, uint16_t val) { m_registers.a = static_cast<uint8_t>(val); } void gb_cpu::_operand_set_register_f(uint16_t addr, uint16_t val) { m_registers.f = (static_cast<uint8_t>(val) & 0xF0); } void gb_cpu::_operand_set_register_af(uint16_t addr, uint16_t val) { m_registers.af = (val & 0xFFF0); } void gb_cpu::_operand_set_register_b(uint16_t addr, uint16_t val) { m_registers.b = static_cast<uint8_t>(val); } void gb_cpu::_operand_set_register_c(uint16_t addr, uint16_t val) { m_registers.c = static_cast<uint8_t>(val); } void gb_cpu::_operand_set_register_bc(uint16_t addr, uint16_t val) { m_registers.bc = val; } void gb_cpu::_operand_set_register_d(uint16_t addr, uint16_t val) { m_registers.d = static_cast<uint8_t>(val); } void gb_cpu::_operand_set_register_e(uint16_t addr, uint16_t val) { m_registers.e = static_cast<uint8_t>(val); } void gb_cpu::_operand_set_register_de(uint16_t addr, uint16_t val) { m_registers.de = val; } void gb_cpu::_operand_set_register_h(uint16_t addr, uint16_t val) { m_registers.h = static_cast<uint8_t>(val); } void gb_cpu::_operand_set_register_l(uint16_t addr, uint16_t val) { m_registers.l = static_cast<uint8_t>(val); } void gb_cpu::_operand_set_register_hl(uint16_t addr, uint16_t val) { m_registers.hl = val; } void gb_cpu::_operand_set_register_sp(uint16_t addr, uint16_t val) { m_registers.sp = val; } void gb_cpu::_operand_set_register_pc(uint16_t addr, uint16_t val) { m_registers.pc = val; } void gb_cpu::_operand_set_register_a_mem(uint16_t addr, uint16_t val) { m_registers.a = static_cast<uint8_t>(_read_byte(val)); } void gb_cpu::_operand_set_mem_8(uint16_t addr, uint16_t val) { _write_byte(addr, static_cast<uint8_t>(val)); } void gb_cpu::_operand_set_mem_16(uint16_t addr, uint16_t val) { _operand_set_mem_8(addr, static_cast<uint8_t>(val & 0xff)); _operand_set_mem_8(addr+1, static_cast<uint8_t>(val >> 8)); } void gb_cpu::_operand_set_mem_hl_8(uint16_t addr, uint16_t val) { _operand_set_mem_8(_operand_get_register_hl(), val); } void gb_cpu::_operand_set_mem_sp_16(uint16_t addr, uint16_t val) { _write_byte(--m_registers.sp, static_cast<uint8_t>(val >> 8)); _write_byte(--m_registers.sp, static_cast<uint8_t>(val)); } void gb_cpu::_op_print_type0(const std::string& disassembly, uint16_t pc, uint16_t operand1, uint16_t operand2) const { char out[256]; snprintf(out, 256, "%04x: %s", pc, disassembly.c_str()); std::string fmt = out; GB_LOGGER(GB_LOG_TRACE) << fmt << std::endl; } void gb_cpu::_op_print_type1(const std::string& disassembly, uint16_t pc, uint16_t operand1, uint16_t operand2) const { char buf[256], out[256]; snprintf(buf, 256, disassembly.c_str(), operand1); snprintf(out, 256, "%04x: %s", pc, buf); std::string fmt = out; GB_LOGGER(GB_LOG_TRACE) << fmt << std::endl; } void gb_cpu::_op_print_type2(const std::string& disassembly, uint16_t pc, uint16_t operand1, uint16_t operand2) const { _op_print_type1(disassembly, pc, static_cast<uint8_t>(operand1), static_cast<uint8_t>(operand2)); } void gb_cpu::_op_print_type3(const std::string& disassembly, uint16_t pc, uint16_t operand1, uint16_t operand2) const { char buf[256], out[256]; snprintf(buf, 256, disassembly.c_str(), operand2); snprintf(out, 256, "%04x: %s", pc, buf); std::string fmt = out; GB_LOGGER(GB_LOG_TRACE) << fmt << std::endl; } void gb_cpu::_op_print_type4(const std::string& disassembly, uint16_t pc, uint16_t operand1, uint16_t operand2) const { _op_print_type3(disassembly, pc, static_cast<uint8_t>(operand1), static_cast<uint8_t>(operand2)); }
[ "sekhar.bx@gmail.com" ]
sekhar.bx@gmail.com
215405f575bfa9cdb0c74b57e049209bf4b16b0f
8ae1361ca290cc4a9f8535b89bf4315203c3b552
/software/old/tinybld/firmware/icdpictypes.inc
d1397fee25dbb9344899dfc0600a4483062de4f3
[]
no_license
GBert/EasyCAN
e9232ccaaf876017bd6478d4072d0c0eb34c36c1
0a382b3a9a484f9f415d9f06ae92aa9af49ba99f
refs/heads/master
2021-01-17T07:43:33.705419
2017-10-24T17:40:20
2017-10-24T17:40:20
16,690,146
12
2
null
null
null
null
UTF-8
C++
false
false
6,179
inc
;IdTypePIC ;bits 7 6 5 4 3 2 1 0 ;meaning: type16/18/ds | model_nr ; ; ;If you want to work with another model that is not on the list ;find one model that is similar to yours and has THE SAME amount ;of flash and replace its "IFDEF __XXXXXX" and ;"#include "ZZZZZZZZZ.inc"", but the ID must remain. ;Each IdTypePIC has one corespondent in the PC application, ;if you add new ones they will not be recognized. IdTypePIC SET 0 IFDEF __16F876A #include "p16f876a.inc" IdTypePIC = 0x31 #define max_flash 0x2000 ENDIF IFDEF __16F877A #include "p16f877a.inc" IdTypePIC = 0x31 #define max_flash 0x2000 ENDIF IFDEF __16F873A #include "p16f873a.inc" IdTypePIC = 0x32 #define max_flash 0x1000 ENDIF IFDEF __16F874A #include "p16f874a.inc" IdTypePIC = 0x32 #define max_flash 0x1000 ENDIF IFDEF __16F87 #include "p16f87.inc" IdTypePIC = 0x33 #define max_flash 0x1000 ENDIF IFDEF __16F88 #include "p16f88.inc" IdTypePIC = 0x33 #define max_flash 0x1000 ENDIF IFDEF __16F886 #include "p16f886.inc" IdTypePIC = 0x36 #define max_flash 0x2000 ENDIF IFDEF __16F887 #include "p16f887.inc" IdTypePIC = 0x36 #define max_flash 0x2000 ENDIF ;---------- 18F ------------- ; 28/40pin IFDEF __18F252 #include "p18f252.inc" IdTypePIC = 0x41 #define max_flash 0x8000 ENDIF IFDEF __18F452 #include "p18f452.inc" IdTypePIC = 0x41 #define max_flash 0x8000 ENDIF IFDEF __18F242 #include "p18f242.inc" IdTypePIC = 0x42 #define max_flash 0x4000 ENDIF IFDEF __18F442 #include "p18f442.inc" IdTypePIC = 0x42 #define max_flash 0x4000 ENDIF IFDEF __18F2520 #include "p18f2520.inc" IdTypePIC = 0x41 #define max_flash 0x8000 ENDIF IFDEF __18F4520 #include "p18f4520.inc" IdTypePIC = 0x41 #define max_flash 0x8000 ENDIF IFDEF __18F2420 #include "p18f2420.inc" IdTypePIC = 0x42 #define max_flash 0x4000 ENDIF IFDEF __18F4420 #include "p18f4420.inc" IdTypePIC = 0x42 #define max_flash 0x4000 ENDIF IFDEF __18F4431 #include "p18f4431.inc" IdTypePIC = 0x42 #define max_flash 0x4000 ENDIF ; 28/40pin can2.0 IFDEF __18F258 #include <p18f258.inc> IdTypePIC = 0x43 #define max_flash 0x8000 ENDIF IFDEF __18F2580 #include <p18f2580.inc> IdTypePIC = 0x43 #define max_flash 0x8000 ENDIF IFDEF __18F458 #include <p18f458.inc> IdTypePIC = 0x43 #define max_flash 0x8000 ENDIF IFDEF __18F4580 #include <p18f4580.inc> IdTypePIC = 0x43 #define max_flash 0x8000 ENDIF IFDEF __18F248 #include <p18f248.inc> IdTypePIC = 0x44 #define max_flash 0x4000 ENDIF IFDEF __18F2480 #include <p18f2480.inc> IdTypePIC = 0x44 #define max_flash 0x4000 ENDIF IFDEF __18F448 #include <p18f448.inc> IdTypePIC = 0x44 #define max_flash 0x4000 ENDIF IFDEF __18F4480 #include <p18f4480.inc> IdTypePIC = 0x44 #define max_flash 0x4000 ENDIF ; 18/28pin 6pwm (some:I2C/SPI) IFDEF __18F1320 #include <p18f1320.inc> IdTypePIC = 0x45 #define max_flash 0x2000 ENDIF IFDEF __18F2320 #include <p18f2320.inc> IdTypePIC = 0x45 #define max_flash 0x2000 ENDIF IFDEF __18F2331 #include <p18f2331.inc> IdTypePIC = 0x45 #define max_flash 0x2000 ENDIF IFDEF __18F1220 #include <p18f1220.inc> IdTypePIC = 0x46 #define max_flash 0x1000 ENDIF IFDEF __18F2220 #include <p18f2220.inc> IdTypePIC = 0x46 #define max_flash 0x1000 ENDIF ; 40pin 6pwm IFDEF __18F4320 #include <p18f4320.inc> IdTypePIC = 0x47 #define max_flash 0x2000 ENDIF IFDEF __18F4331 #include <p18f4331.inc> IdTypePIC = 0x47 #define max_flash 0x2000 ENDIF IFDEF __18F4220 #include <p18f4220.inc> IdTypePIC = 0x48 #define max_flash 0x1000 ENDIF ; 64/80pin TQFP 2usart IFDEF __18F6720 #include <p18f6720.inc> IdTypePIC = 0x4A #define max_flash 0x20000 ENDIF IFDEF __18F8720 #include <p18f8720.inc> IdTypePIC = 0x4A #define max_flash 0x20000 ENDIF IFDEF __18F6620 #include <p18f6620.inc> IdTypePIC = 0x4B #define max_flash 0x10000 ENDIF IFDEF __18F8620 #include <p18f8620.inc> IdTypePIC = 0x4B #define max_flash 0x10000 ENDIF IFDEF __18F6520 #include <p18f6520.inc> IdTypePIC = 0x4C #define max_flash 0x8000 ENDIF IFDEF __18F8520 #include <p18f8520.inc> IdTypePIC = 0x4C #define max_flash 0x8000 ENDIF IFDEF __18F8680 #include <p18f8680.inc> IdTypePIC = 0x4D #define max_flash 0x10000 ENDIF ;PIC18F 2525/2620/4525/4620 EA-USART, nanoWatt, intOSC IFDEF __18F2525 #include "p18f2525.inc" IdTypePIC = 0x4E #define max_flash 0xC000 ENDIF IFDEF __18F2585 #include "p18f2585.inc" IdTypePIC = 0x4E #define max_flash 0xC000 ENDIF IFDEF __18F4525 #include "p18f4525.inc" IdTypePIC = 0x4E #define max_flash 0xC000 ENDIF IFDEF __18F4585 #include "p18f4585.inc" IdTypePIC = 0x4E #define max_flash 0xC000 ENDIF IFDEF __18F2620 #include "p18f2620.inc" IdTypePIC = 0x4F #define max_flash 0x10000 ENDIF IFDEF __18F2680 #include "p18f2680.inc" IdTypePIC = 0x4F #define max_flash 0x10000 ENDIF IFDEF __18F4620 #include "p18f4620.inc" IdTypePIC = 0x4F #define max_flash 0x10000 ENDIF IFDEF __18F4680 #include "p18f4680.inc" IdTypePIC = 0x4F #define max_flash 0x10000 ENDIF IFDEF __18F46K80 #include "p18f46k80.inc" IdTypePIC = 0x50 #define max_flash 0x10000 ENDIF IFDEF __18F26K80 #include "p18f26k80.inc" IdTypePIC = 0x50 #define max_flash 0x10000 ENDIF ;---------------- USB ------------------------------ IFDEF __18F2550 #include "p18f2550.inc" IdTypePIC = 0x55 #define max_flash 0x8000 ENDIF IFDEF __18F2553 #include "p18f2553.inc" IdTypePIC = 0x55 #define max_flash 0x8000 ENDIF IFDEF __18F4550 #include "p18f4550.inc" IdTypePIC = 0x55 #define max_flash 0x8000 ENDIF IFDEF __18F2455 #include "p18f2455.inc" IdTypePIC = 0x56 #define max_flash 0x6000 ENDIF IFDEF __18F4455 #include "p18f4455.inc" IdTypePIC = 0x56 #define max_flash 0x6000 ENDIF IFDEF __18F4685 #include "p18f4685.inc" IdTypePIC = 0x57 #define max_flash 0x18000 ENDIF IFDEF __18F2685 #include <p18f2685.inc> IdTypePIC = 0x57 #define max_flash 0x18000 ; 18000 ENDIF if IdTypePIC==0 error "Pic not yet implemeted" endif
[ "info@gerhard-bertelsmann.de" ]
info@gerhard-bertelsmann.de
10abd6a8cc7156742f2209c8697d4833279b751b
d5b29a08c4d981815f807b3ab50474a751ad1ba8
/renderer/mediarendererdevice.h
1521f2c4ee5983a6adc8c30b3053962b3ab261a6
[]
no_license
dirkvdb/doozy
42a03bae5b0664df12485e40511de4a65d27749a
6cf51bd80e1d9d0aa5bbc724f4c70e1675768c7c
refs/heads/master
2020-05-21T20:23:30.515496
2014-12-08T19:23:58
2014-12-08T19:23:58
27,730,604
0
1
null
null
null
null
UTF-8
C++
false
false
4,264
h
// Copyright (C) 2012 Dirk Vanden Boer <dirk.vdb@gmail.com> // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #ifndef MEDIA_RENDERER_DEVICE_H #define MEDIA_RENDERER_DEVICE_H #include <memory> #include "utils/workerthread.h" #include "upnp/upnprootdevice.h" #include "upnp/upnpdeviceservice.h" #include "upnp/upnpactionresponse.h" #include "upnp/upnprenderingcontrolservice.h" #include "upnp/upnpavtransportservice.h" #include "upnp/upnpconnectionmanagerservice.h" #include "audio/audioplaybackinterface.h" #include "playqueue.h" namespace upnp { class WebServer; } namespace doozy { class MediaRendererDevice : public upnp::IConnectionManager , public upnp::IRenderingControl , public upnp::IAVTransport { public: MediaRendererDevice(const std::string& udn, const std::string& descriptionXml, int32_t advertiseIntervalInSeconds, const std::string& audioOutput, const std::string& audioDevice, upnp::WebServer& webServer); MediaRendererDevice(const MediaRendererDevice&) = delete; void start(); void stop(); // IConnectionManager virtual void prepareForConnection(const upnp::ProtocolInfo& protocolInfo, upnp::ConnectionManager::ConnectionInfo& info); virtual void connectionComplete(int32_t connectionId); virtual upnp::ConnectionManager::ConnectionInfo getCurrentConnectionInfo(int32_t connectionId); // IRenderingControl virtual void selectPreset(uint32_t instanceId, const std::string& name); virtual void setVolume(uint32_t instanceId, upnp::RenderingControl::Channel channel, uint16_t value); virtual void setMute(uint32_t instanceId, upnp::RenderingControl::Channel channel, bool enabled); //IAVTransport virtual void setAVTransportURI(uint32_t instanceId, const std::string& uri, const std::string& metaData); virtual void setNextAVTransportURI(uint32_t instanceId, const std::string& uri, const std::string& metaData); virtual void stop(uint32_t instanceId); virtual void play(uint32_t instanceId, const std::string& speed); virtual void seek(uint32_t instanceId, upnp::AVTransport::SeekMode mode, const std::string& target); virtual void next(uint32_t instanceId); virtual void previous(uint32_t instanceId); virtual void pause(uint32_t instanceId); private: void setInitialValues(); void setTransportVariable(uint32_t instanceId, upnp::AVTransport::Variable var, const std::string& value); void onEventSubscriptionRequest(Upnp_Subscription_Request* pRequest); void onControlActionRequest(Upnp_Action_Request* pRequest); bool supportsProtocol(const upnp::ProtocolInfo& info) const; void addAlbumArtToWebServer(const PlayQueueItemPtr& item); void throwOnBadInstanceId(uint32_t id) const; mutable std::mutex m_Mutex; PlayQueue m_Queue; std::unique_ptr<audio::IPlayback> m_Playback; upnp::RootDevice m_RootDevice; upnp::ConnectionManager::Service m_ConnectionManager; upnp::RenderingControl::Service m_RenderingControl; upnp::AVTransport::Service m_AVTransport; upnp::WebServer& m_WebServer; std::vector<upnp::ProtocolInfo> m_SupportedProtocols; upnp::ConnectionManager::ConnectionInfo m_CurrentConnectionInfo; utils::WorkerThread m_Thread; }; } #endif
[ "dirk.vdb@gmail.com" ]
dirk.vdb@gmail.com
acde4b3e16918994a87e01b02fc107bb5f1440e8
22e9144e9ca00d73e9a9d9e958fe1f04f511f9dd
/test/src/conv_dbn.cpp
840ed05c98549005c458fcafd241694df5223c35
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
acknowledge/dll
e378c8d960df36e27b0f50a0d261bc6469cb80ad
6ab90077bbfc93a4089c5a906dda039575fcc446
refs/heads/master
2021-01-12T05:34:23.360832
2016-12-22T09:58:06
2016-12-22T09:58:06
77,131,064
0
0
null
2016-12-22T09:22:35
2016-12-22T09:22:35
null
UTF-8
C++
false
false
3,902
cpp
//======================================================================= // Copyright (c) 2014-2016 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include "catch.hpp" #define DLL_SVM_SUPPORT #include "dll/rbm/conv_rbm.hpp" #include "dll/dbn.hpp" #include "mnist/mnist_reader.hpp" #include "mnist/mnist_utils.hpp" TEST_CASE("conv_dbn/mnist_1", "conv_dbn::simple") { typedef dll::dbn_desc< dll::dbn_layers< dll::conv_rbm_desc_square<1, 28, 40, 12, dll::momentum, dll::batch_size<25>>::layer_t, dll::conv_rbm_desc_square<40, 12, 20, 10, dll::momentum, dll::batch_size<25>>::layer_t, dll::conv_rbm_desc_square<20, 10, 50, 6, dll::momentum, dll::batch_size<25>>::layer_t>>::dbn_t dbn_t; auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<double, 1, 28, 28>>(100); REQUIRE(!dataset.training_images.empty()); mnist::binarize_dataset(dataset); auto dbn = std::make_unique<dbn_t>(); dbn->pretrain(dataset.training_images, 5); } TEST_CASE("conv_dbn/mnist_2", "conv_dbn::svm_simple") { typedef dll::dbn_desc< dll::dbn_layers< dll::conv_rbm_desc_square<1, 28, 40, 12, dll::momentum, dll::batch_size<25>>::layer_t, dll::conv_rbm_desc_square<40, 12, 40, 10, dll::momentum, dll::batch_size<25>>::layer_t>>::dbn_t dbn_t; auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<double, 1, 28, 28>>(200); REQUIRE(!dataset.training_images.empty()); mnist::binarize_dataset(dataset); auto dbn = std::make_unique<dbn_t>(); dbn->pretrain(dataset.training_images, 20); auto result = dbn->svm_train(dataset.training_images, dataset.training_labels); REQUIRE(result); auto test_error = dll::test_set(dbn, dataset.training_images, dataset.training_labels, dll::svm_predictor()); std::cout << "test_error:" << test_error << std::endl; REQUIRE(test_error < 0.1); } TEST_CASE("conv_dbn/mnist_3", "conv_dbn::svm_concatenate") { typedef dll::dbn_desc< dll::dbn_layers< dll::conv_rbm_desc_square<1, 28, 40, 12, dll::momentum, dll::batch_size<25>>::layer_t, dll::conv_rbm_desc_square<40, 12, 40, 10, dll::momentum, dll::batch_size<25>>::layer_t>, dll::svm_concatenate>::dbn_t dbn_t; auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<double, 1, 28, 28>>(200); REQUIRE(!dataset.training_images.empty()); mnist::binarize_dataset(dataset); auto dbn = std::make_unique<dbn_t>(); dbn->pretrain(dataset.training_images, 20); auto result = dbn->svm_train(dataset.training_images, dataset.training_labels); REQUIRE(result); auto test_error = dll::test_set(dbn, dataset.training_images, dataset.training_labels, dll::svm_predictor()); std::cout << "test_error:" << test_error << std::endl; REQUIRE(test_error < 0.1); } TEST_CASE("conv_dbn/mnist_4", "conv_dbn::svm_simple") { typedef dll::dbn_desc< dll::dbn_layers< dll::conv_rbm_desc_square<1, 28, 40, 12, dll::momentum, dll::batch_size<25>>::layer_t>>::dbn_t dbn_t; auto dataset = mnist::read_dataset_direct<std::vector, etl::fast_dyn_matrix<double, 1, 28, 28>>(200); REQUIRE(!dataset.training_images.empty()); mnist::binarize_dataset(dataset); auto dbn = std::make_unique<dbn_t>(); dbn->pretrain(dataset.training_images, 20); auto result = dbn->svm_train(dataset.training_images, dataset.training_labels); REQUIRE(result); auto test_error = dll::test_set(dbn, dataset.training_images, dataset.training_labels, dll::svm_predictor()); std::cout << "test_error:" << test_error << std::endl; REQUIRE(test_error < 0.1); }
[ "baptiste.wicht@gmail.com" ]
baptiste.wicht@gmail.com
e023126c2db9f4b11723a2d0042125effe819e9a
ba98197d69bb4b9390a94750556d0bc07c163eae
/Source/Engine/Animators/Nodes/ParticleVelocityNode.h
396e10393025e229659a6c0e5d33455770aea01a
[ "MIT" ]
permissive
daiwei1999/AwayCPP
a229389369e01e1b80a27ff684723d234dbba030
095a994bdd85982ffffd99a9461cbefb57499ccb
refs/heads/master
2023-07-20T19:42:32.741480
2023-07-05T09:10:26
2023-07-05T09:10:26
36,792,672
12
6
null
null
null
null
UTF-8
C++
false
false
732
h
#pragma once #include "Common.h" #include "ParticleNodeBase.h" AWAY_NAMESPACE_BEGIN /** * A particle animation node used to set the starting velocity of a particle. */ class ParticleVelocityNode : public ParticleNodeBase { public: ParticleVelocityNode(ParticlePropertiesMode mode, Vector3D* velocity = nullptr); void getAGALVertexCode(ShaderChunk& code, AnimationRegisterCache* regCache) override; AnimationStateBase* createAnimationState(IAnimator* animator) override; void generatePropertyOfOneParticle(ParticleProperties& param) override; public: static const int VELOCITY_INDEX; static const std::string VELOCITY_VECTOR3D; friend class ParticleVelocityState; private: Vector3D* m_velocity; }; AWAY_NAMESPACE_END
[ "daiwei_1999_82@163.com" ]
daiwei_1999_82@163.com
e4f03785a87dd046cbba9613efabdb7b80f2a9e2
765eacfebcb5cc4d06359ca55b4a47768d4c8d24
/utils/level_face_traversal.hpp
d9899133d3a097b3ad52e378ce8a503eda216716
[]
no_license
MikolajTwarog/Technika-Baker
98f96d5aa09d2d1eeb320cea6ea4bca010db4340
054f837a867ece3f5fea9580a7b81227060e29c2
refs/heads/main
2023-06-17T21:22:22.487818
2021-06-23T12:47:58
2021-06-23T12:47:58
319,667,728
1
0
null
null
null
null
UTF-8
C++
false
false
3,478
hpp
// // Created by mikolajtwarog on 2021-02-04. // #ifndef TECHNIKA_BAKER_LEVEL_FACE_TRAVERSAL_HPP #define TECHNIKA_BAKER_LEVEL_FACE_TRAVERSAL_HPP #include <vector> #include <set> #include <map> #include <boost/next_prior.hpp> #include <boost/graph/graph_traits.hpp> #include <boost/graph/properties.hpp> template < typename Graph, typename Visitor , typename Container> inline void level_face_traversal(Container& embedding, Visitor& visitor) { typedef typename boost::graph_traits<Graph>::vertex_descriptor vertex_t; typedef typename boost::graph_traits<Graph>::edge_descriptor edge_t; using h = std::hash<int>; auto hash = [](const edge_t& n){return ((17 * 31 + h()(n.m_source)) * 31 + h()(n.m_target)) * 31;}; auto equal = [](const edge_t & l, const edge_t& r){return l.m_source == r.m_source && l.m_target == r.m_target && l.m_eproperty == r.m_eproperty;}; std::map<edge_t, std::map<vertex_t, edge_t> > next_edge; std::map<edge_t, std::set<vertex_t> > visited; visitor.begin_traversal(); std::vector<edge_t> edges_cache; for (int v = 0; v < embedding.size(); v++) { auto& edges = embedding[v]; for (int i = 0; i < edges.size(); i++) { edge_t e = edges[i]; edges_cache.push_back(e); next_edge[e][v] = edges[(i+1)%edges.size()]; } } std::vector<vertex_t> vertices_in_edge; for (auto e : edges_cache) { vertices_in_edge.clear(); vertices_in_edge.push_back(e.m_source); vertices_in_edge.push_back(e.m_target); for (auto v : vertices_in_edge) { std::set<vertex_t>& e_visited = visited[e]; typename std::set<vertex_t>::iterator e_visited_found = e_visited.find(v); if (e_visited_found == visited[e].end()) visitor.begin_face(); while (visited[e].find(v) == visited[e].end()) { visitor.next_vertex(v); visitor.next_edge(e); visited[e].insert(v); v = e.m_source == v ? e.m_target : e.m_source; e = next_edge[e][v]; } if (e_visited_found == e_visited.end()) visitor.end_face(); } } } template<typename Graph> bool check_for_edge(int x, int y, Graph& g, std::set<std::pair<int, int> >& added_edges) { if (x == y) { return false; } std::pair<int, int> e(x, y); bool res = false; typename graph_traits<Graph>::out_edge_iterator ei, ei_end; for(boost::tie(ei, ei_end) = out_edges(x, g); ei != ei_end; ++ei) { if (ei->m_source == y || ei->m_target == y) { res = true; break; } } if (!res || added_edges.find(e) != added_edges.end()) { return false; } std::swap(e.first, e.second); return added_edges.find(e) == added_edges.end(); } int get_edge_it(int v, int w, PlanarEmbedding& embedding) { for (int i = 0; i < embedding[v].size(); i++) { if ((embedding[v][i].m_source == v && embedding[v][i].m_target == w) || (embedding[v][i].m_source == w && embedding[v][i].m_target == v)) { return i; } } return -1; } int get_edge_it(Edge e, int v, PlanarEmbedding& embedding) { int w = e.m_source == v ? e.m_target : e.m_source; return get_edge_it(v, w, embedding); } #endif //TECHNIKA_BAKER_LEVEL_FACE_TRAVERSAL_HPP
[ "mikolajtwarog@gmail.com" ]
mikolajtwarog@gmail.com
a1b38a909e51a48fb47456cda04123886d5a4c59
01374f1ee782b39c9a9289eed40cc60deeac8535
/ContactListener.h
52182d0f3964aa387e389804e711e567b7e9efec
[]
no_license
Redbassist/FYP-Server
bf98b7921fadabb36a9c1662de8fb7e2844f23ae
9f9e73fee04c1e0e61457a356f44d8aed8dfd3e6
refs/heads/master
2021-01-01T05:19:38.637308
2016-04-20T22:48:01
2016-04-20T22:48:01
56,725,785
0
0
null
null
null
null
UTF-8
C++
false
false
8,480
h
#ifndef CONTACTLISTENER_H #define CONTACTLISTENER_H #include "stdafx.h" #include "Player.h" #include "Item.h" #include "Container.h" #include "Stalker.h" #include "Door.h" class ContactListener : public b2ContactListener { public: void BeginContact(b2Contact* contact) { void* fixAType = contact->GetFixtureA()->GetUserData(); void* fixBType = contact->GetFixtureB()->GetUserData(); if (fixAType == "Player" && fixBType == "Item" || fixAType == "Item" && fixBType == "Player") { if (fixAType == "Player") { void* bodyUserData1 = contact->GetFixtureA()->GetBody()->GetUserData(); void* bodyUserData2 = contact->GetFixtureB()->GetBody()->GetUserData(); static_cast<Player*>(bodyUserData1)->TouchingItem(static_cast<Item*>(bodyUserData2)); } else if (fixBType == "Player") { void* bodyUserData1 = contact->GetFixtureB()->GetBody()->GetUserData(); void* bodyUserData2 = contact->GetFixtureA()->GetBody()->GetUserData(); static_cast<Player*>(bodyUserData1)->TouchingItem(static_cast<Item*>(bodyUserData2)); } } else if (fixAType == "Player" && fixBType == "Container" || fixAType == "Container" && fixBType == "Player") { if (fixAType == "Player") { void* bodyUserData1 = contact->GetFixtureA()->GetBody()->GetUserData(); void* bodyUserData2 = contact->GetFixtureB()->GetBody()->GetUserData(); static_cast<Player*>(bodyUserData1)->TouchingContainer(static_cast<Container*>(bodyUserData2)); } else if (fixBType == "Player") { void* bodyUserData1 = contact->GetFixtureB()->GetBody()->GetUserData(); void* bodyUserData2 = contact->GetFixtureA()->GetBody()->GetUserData(); static_cast<Player*>(bodyUserData1)->TouchingContainer(static_cast<Container*>(bodyUserData2)); } } else if (fixAType == "Player" && fixBType == "Door" || fixAType == "Door" && fixBType == "Player") { if (fixAType == "Player") { void* bodyUserData1 = contact->GetFixtureA()->GetBody()->GetUserData(); void* bodyUserData2 = contact->GetFixtureB()->GetBody()->GetUserData(); static_cast<Player*>(bodyUserData1)->TouchingDoor(static_cast<Door*>(bodyUserData2)); } else if (fixBType == "Player") { void* bodyUserData1 = contact->GetFixtureB()->GetBody()->GetUserData(); void* bodyUserData2 = contact->GetFixtureA()->GetBody()->GetUserData(); static_cast<Player*>(bodyUserData1)->TouchingDoor(static_cast<Door*>(bodyUserData2)); } } else if (fixAType == "Player" && fixBType == "EnemyPunch" || fixAType == "EnemyPunch" && fixBType == "Player") { if (fixAType == "Player") { void* bodyUserData1 = contact->GetFixtureA()->GetBody()->GetUserData(); void* bodyUserData2 = contact->GetFixtureB()->GetBody()->GetUserData(); if (static_cast<Stalker*>(bodyUserData2)->HitPlayer()) { static_cast<Player*>(bodyUserData1)->TakeDamage(0); } } else if (fixBType == "Player") { void* bodyUserData1 = contact->GetFixtureB()->GetBody()->GetUserData(); void* bodyUserData2 = contact->GetFixtureA()->GetBody()->GetUserData(); if (static_cast<Stalker*>(bodyUserData2)->HitPlayer()) { static_cast<Player*>(bodyUserData1)->TakeDamage(0); } } } else if (fixAType == "EnemyHit" && fixBType == "Punch" || fixAType == "Punch" && fixBType == "EnemyHit") { if (fixAType == "EnemyHit") { void* bodyUserData1 = contact->GetFixtureA()->GetBody()->GetUserData(); void* bodyUserData2 = contact->GetFixtureB()->GetBody()->GetUserData(); if (static_cast<Player*>(bodyUserData2)->doingPunchDamage) { static_cast<Player*>(bodyUserData2)->doingPunchDamage = false; static_cast<Enemy*>(bodyUserData1)->DropHealth(10); } } else if (fixBType == "EnemyHit") { void* bodyUserData1 = contact->GetFixtureB()->GetBody()->GetUserData(); void* bodyUserData2 = contact->GetFixtureA()->GetBody()->GetUserData(); if (static_cast<Player*>(bodyUserData2)->doingPunchDamage) { static_cast<Player*>(bodyUserData2)->doingPunchDamage = false; static_cast<Enemy*>(bodyUserData1)->DropHealth(10); } } } else if (fixAType == "EnemyHit" && fixBType == "MeleeWeapon" || fixAType == "MeleeWeapon" && fixBType == "EnemyHit") { if (fixAType == "EnemyHit") { void* bodyUserData1 = contact->GetFixtureA()->GetBody()->GetUserData(); void* bodyUserData2 = contact->GetFixtureB()->GetBody()->GetUserData(); if (static_cast<Player*>(bodyUserData2)->doingMeleeDamage) { static_cast<Player*>(bodyUserData2)->doingMeleeDamage = false; static_cast<Enemy*>(bodyUserData1)->DropHealth(40); } } else if (fixBType == "EnemyHit") { void* bodyUserData1 = contact->GetFixtureB()->GetBody()->GetUserData(); void* bodyUserData2 = contact->GetFixtureA()->GetBody()->GetUserData(); if (static_cast<Player*>(bodyUserData2)->doingMeleeDamage) { static_cast<Player*>(bodyUserData2)->doingMeleeDamage = false; static_cast<Enemy*>(bodyUserData1)->DropHealth(40); } } } else if (fixAType == "EnemyHit" && fixBType == "Door" || fixAType == "Door" && fixBType == "EnemyHit") { if (fixAType == "Door") { void* bodyUserData1 = contact->GetFixtureA()->GetBody()->GetUserData(); void* bodyUserData2 = contact->GetFixtureB()->GetBody()->GetUserData(); static_cast<Door*>(bodyUserData1)->Open(); } else if (fixBType == "Door") { void* bodyUserData1 = contact->GetFixtureB()->GetBody()->GetUserData(); void* bodyUserData2 = contact->GetFixtureA()->GetBody()->GetUserData(); static_cast<Door*>(bodyUserData1)->Open(); } } else if (fixAType == "Punch" && fixBType == "Door" || fixAType == "Door" && fixBType == "Punch") { if (fixAType == "Door") { void* bodyUserData1 = contact->GetFixtureA()->GetBody()->GetUserData(); void* bodyUserData2 = contact->GetFixtureB()->GetBody()->GetUserData(); if (static_cast<Player*>(bodyUserData2)->doingPunchDamage) static_cast<Door*>(bodyUserData1)->Knock(); } else if (fixBType == "Door") { void* bodyUserData1 = contact->GetFixtureB()->GetBody()->GetUserData(); void* bodyUserData2 = contact->GetFixtureA()->GetBody()->GetUserData(); if (static_cast<Player*>(bodyUserData2)->doingPunchDamage) static_cast<Door*>(bodyUserData1)->Knock(); } } } void EndContact(b2Contact* contact) { void* fixAType = contact->GetFixtureA()->GetUserData(); void* fixBType = contact->GetFixtureB()->GetUserData(); if (fixAType == "Player" && fixBType == "Item" || fixAType == "Item" && fixBType == "Player") { if (fixAType == "Player") { void* bodyUserData1 = contact->GetFixtureA()->GetBody()->GetUserData(); void* bodyUserData2 = contact->GetFixtureB()->GetBody()->GetUserData(); static_cast<Player*>(bodyUserData1)->NotTouchingItem(static_cast<Item*>(bodyUserData2)); } else if (fixBType == "Player") { void* bodyUserData1 = contact->GetFixtureB()->GetBody()->GetUserData(); void* bodyUserData2 = contact->GetFixtureA()->GetBody()->GetUserData(); static_cast<Player*>(bodyUserData1)->NotTouchingItem(static_cast<Item*>(bodyUserData2)); } } else if (fixAType == "Player" && fixBType == "Container" || fixAType == "Container" && fixBType == "Player") { if (fixAType == "Player") { void* bodyUserData1 = contact->GetFixtureA()->GetBody()->GetUserData(); void* bodyUserData2 = contact->GetFixtureB()->GetBody()->GetUserData(); static_cast<Player*>(bodyUserData1)->NotTouchingContainer(); static_cast<Container*>(bodyUserData2)->Close(); } else if (fixBType == "Player") { void* bodyUserData1 = contact->GetFixtureB()->GetBody()->GetUserData(); void* bodyUserData2 = contact->GetFixtureA()->GetBody()->GetUserData(); static_cast<Player*>(bodyUserData1)->NotTouchingContainer(); static_cast<Container*>(bodyUserData2)->Close(); } } else if (fixAType == "Player" && fixBType == "Door" || fixAType == "Door" && fixBType == "Player") { if (fixAType == "Player") { void* bodyUserData1 = contact->GetFixtureA()->GetBody()->GetUserData(); void* bodyUserData2 = contact->GetFixtureB()->GetBody()->GetUserData(); static_cast<Player*>(bodyUserData1)->NotTouchingDoor(); } else if (fixBType == "Player") { void* bodyUserData1 = contact->GetFixtureB()->GetBody()->GetUserData(); void* bodyUserData2 = contact->GetFixtureA()->GetBody()->GetUserData(); static_cast<Player*>(bodyUserData1)->NotTouchingDoor(); } } } }; #endif
[ "mattgerig@gmail.com" ]
mattgerig@gmail.com
3667572f09dc1d96b834b0250be8513116c49a2f
ecaca679938c7d6b0bc6ca835981e7cc2a0330d8
/DSClient/dsClient.cpp
0fa24362912e3a117ce84d6c85ff2a950e7feacc
[]
no_license
amitprat/IMSDEV
df187a105859dacd53f818fea18ae40c5ab1e162
568880e6242eeb01ca4ebd46c3e63029009f5374
refs/heads/master
2021-01-01T19:24:53.037674
2014-12-20T18:34:23
2014-12-20T18:34:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,202
cpp
#include "gprot.h" #include "OpenDSInterface.h" #include "DSClient.h" dsClient::dsClient() { availableIndex = 1; //first index allocated to DS Node targetTime = presentTime = 0.0; periodicTimer = false; timeInterval = 0.0; firstMsg = true; portNo = IMS_PORT; sockId = socket(FAMILY,STREAM,FLAG); FD_ZERO(&read_fds); FD_SET(sockId,&read_fds); fd_max = sockId; memset( &tv,0,sizeof(struct timeval) ); tvptr = NULL; ERROR(sockId == -1,__FILE__,__LINE__); setsockopt(sockId, SOL_SOCKET, SO_REUSEADDR, NULL, NULL); bzero((char *) &svrAdd, sizeof(svrAdd)); server = gethostbyname(DEFAULT_IMS); ERROR(server==NULL,__FILE__,__LINE__); nodes = NULL; } void dsClient::clientSetup() { svrAdd.sin_family = FAMILY; bcopy((char *) server -> h_addr, (char *) &svrAdd.sin_addr.s_addr,server -> h_length); svrAdd.sin_port = htons(portNo); result = connect(sockId, (struct sockaddr *) &svrAdd, sizeof(svrAdd)); ERROR(result==-1,__FILE__,__LINE__); PRINTF( INFO ,"DS : Client setup done, connection established\n" ); } void dsClient :: startConnection() { while(true) { FD_ZERO(&master); master = read_fds; result = select( fd_max+1, &master, NULL, NULL, tvptr); ERROR(result==-1,__FILE__,__LINE__); if( FD_ISSET( sockId, & master) ) { recvMsg(); processMsg(); } else if(periodicTimer == true) { tv.tv_sec = 0; tv.tv_usec = timeInterval*1000; tvptr = &tv; makeSendMsg(); targetTime += timeInterval; presentTime += timeInterval; } else { PRINTF(ERROR,"DS : Not Handled : Error \n"); } } close(sockId); } void dsClient :: makeSendMsg() { PRINTF( INFO ,"DS : DS Update Notify update sent\n" ); outMsg.reset(); outMsg.writeByte(23); outMsg.writeChar(CMD_DS_UPDATE); interface.getUpdatedPos(nodes[0].speed,nodes[0].X,nodes[0].Y,nodes[0].Z); outMsg.writeInt(nodes[0].nodeId); outMsg.writeDouble(targetTime); outMsg.writeByte(POSITION_2D); outMsg.writeFloat(nodes[0].X); outMsg.writeFloat(nodes[0].Y); PRINTF( VERBOSE,"DS: Node Position , nodes[0].X : %f, nodes[0].Y : %f\n", nodes[0].X, nodes[0].Y ); sendMsg(); } void dsClient :: sendMsg() { len = static_cast<int>(outMsg.size()); lengthStorage.reset(); lengthStorage.writeInt(len + 4); outPacket.clear(); outPacket.insert(outPacket.end(), lengthStorage.begin(), lengthStorage.end()); outPacket.insert(outPacket.end(), outMsg.begin(), outMsg.end()); numbytes = outPacket.size(); buffer = new unsigned char[numbytes]; memset(buffer,0,numbytes); unsigned char *ptr = buffer; for(size_t i = 0; i < numbytes; i++) { buffer[i] = outPacket[i]; } result = send( sockId,buffer,numbytes, 0 ); delete[] ptr; } void dsClient :: recvMsg(){ inMsg.reset(); buffer = new unsigned char[BUF_SIZE]; memset(buffer,0,BUF_SIZE); recv( sockId, buffer, BUF_SIZE, 0 ); len = length(); unsigned char* buf = new unsigned char[len]; memset(buf,0,len); memcpy(buf,buffer+4,len); inMsg.writePacket(buf,len); delete[] buf; delete[] buffer; } int dsClient :: length() { unsigned char* bufLength = new unsigned char[4]; memset(bufLength,0,4); memcpy(bufLength,buffer,4); Storage length_storage(bufLength,4); int NN = length_storage.readInt() - 4; delete bufLength; return NN; } void dsClient :: processMsg() { if(inMsg.readByte()==11) { } char commandType = inMsg.readChar(); switch(commandType) { case CMD_ACK: PRINTF( INFO, "DS : Command Ack Recieved\n" ); break; case CMD_HBW: PRINTF( INFO, "DS : Warning Message Recieved\n" ); break; case CMD_SETMAXSPEED: PRINTF( INFO, "DS : Set Max Speed Cmd Recieved\n" ); break; case CMD_DS_NOTIFY_REQ: PRINTF( INFO, "DS : DS Update Notify request recievd\n" ); timeInterval = inMsg.readDouble(); tv.tv_sec = 0; tv.tv_usec = timeInterval*1000; targetTime += timeInterval; periodicTimer = true; tvptr = &tv; break; case CMD_TS_CONN_REM: //TS closes the connection, reset present and target time and stop sending update //after every disconnection start simulation from scratch, node pos back to zero presentTime = targetTime = 0; tv.tv_sec = 0; tvptr = NULL; periodicTimer = false; timeInterval = 0.0; PRINTF( INFO, "DS : TS is dead, stop sending update and reset timer\n" ); break; case CMD_SIMSTEP_DS: updateTSNode(); PRINTF( INFO, "DS : TS nodes update recieved from TS\n" ); break; default: PRINTF( ERROR, "No handler written still...!!\n" ); } } void dsClient::updateTSNode() { char status = inMsg.readChar(); string desc = inMsg.readString(); ERROR(status != RTYPE_OK || desc != "OK",__FILE__,__LINE__); if(firstMsg) { firstMsg = false; return; } while (!firstMsg && inMsg.valid_pos()) { int len = inMsg.readByte(); char commType = inMsg.readChar(); if(len != 23 || commType != CMD_MOVENODE) { //ERROR(false,__FILE__,__LINE__); //PRINTF("DS : Error reading TS nodes position"); //break; } int TSID = inMsg.readInt(); if( tsIndexMap.find(TSID) == tsIndexMap.end() ) { tsIndexMap[TSID] = availableIndex++; } int index = tsIndexMap[TSID]; nodes[index].nodeId = TSID; nodes[index].targetTime = inMsg.readDouble(); nodes[index].posType = inMsg.readByte(); nodes[index].X = inMsg.readFloat(); nodes[index].Y = inMsg.readFloat(); } displayStats(); interface.sendTSNodeUpdate(nodes,availableIndex); } void dsClient :: displayStats() { for(int i=0;i<availableIndex;i++) { PRINTF( VERBOSE, "DS: Node Position\n"); PRINTF( VERBOSE, "DS : %d , %f, %d, %f , %f\n", nodes[i].nodeId, nodes[i].targetTime, nodes[i].posType, nodes[i].X, nodes[i].Y ); } } void dsClient :: simCar(float speed,float &X, float &Y){ PRINTF( VERBOSE, "DS , target time : %f, present_time : %f\n",targetTime, presentTime ); time_t time = (targetTime - presentTime)/1000; X += ( (float)(speed*time)); Y += ( (float)(speed*time)); } void *func(void *arg) { OpenDSInterface *obj = (OpenDSInterface *)arg; obj->startConnection(); return NULL; } int main(int argc, char* argv[]) { pthread_t pid; dsClient client; createConfig(client.nodes,client.indexMap,NUM_NODES); readConfig(client.nodes,NUM_NODES); client.clientSetup(); pthread_create(&pid,NULL,func,(void *)&client.interface); client.startConnection(); writeConfig(client.nodes,NUM_NODES,client.indexMap); pthread_join(pid,NULL); destroyNodes(client.nodes); return 0; }
[ "amitprat@buffalo.edu" ]
amitprat@buffalo.edu
a5e82f5e73b49f8fd0f55228d11b556a00b11b49
050ebbbc7d5f89d340fd9f2aa534eac42d9babb7
/grupa1/lfilipiuk/p2/kol.cpp
c7a9e1fa2f10d0a162860e61acc30787ec48302f
[]
no_license
anagorko/zpk2015
83461a25831fa4358366ec15ab915a0d9b6acdf5
0553ec55d2617f7bea588d650b94828b5f434915
refs/heads/master
2020-04-05T23:47:55.299547
2016-09-14T11:01:46
2016-09-14T11:01:46
52,429,626
0
13
null
2016-03-22T09:35:25
2016-02-24T09:19:07
C++
UTF-8
C++
false
false
188
cpp
#include <iostream> #include <cmath> #include <iomanip> using namespace std; int main(){ double r; cin >> r; cout << setprecision(3) << fixed << M_PI*r*r << "\n" << 2*M_PI*r << endl; }
[ "lukasz.filipiuk@student.uw.edu.pl" ]
lukasz.filipiuk@student.uw.edu.pl
968912a7ba66d452750a959b0aea71d5a00e8507
a7757ba650122f0540cc2980fd08f191c4744866
/src/irc.cpp
5201168e0a9edd267561ad80fbdaded9fecf6a0d
[ "MIT" ]
permissive
doriancoin/doriancoin-v3
77473eb3e95b8a49b5061b3e7d7bda63cab3667e
7c52fd1ac94b431fea11eb6522c9b278bd084ea6
refs/heads/master
2021-03-12T19:56:03.693580
2014-03-08T11:41:20
2014-03-08T11:41:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,516
cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Copyright (c) 2011-2012 Litecoin Developers // Copyright (c) 2013 doriancoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "irc.h" #include "net.h" #include "strlcpy.h" #include "base58.h" using namespace std; using namespace boost; int nGotIRCAddresses = 0; void ThreadIRCSeed2(void* parg); #pragma pack(push, 1) struct ircaddr { struct in_addr ip; short port; }; #pragma pack(pop) string EncodeAddress(const CService& addr) { struct ircaddr tmp; if (addr.GetInAddr(&tmp.ip)) { tmp.port = htons(addr.GetPort()); vector<unsigned char> vch(UBEGIN(tmp), UEND(tmp)); return string("u") + EncodeBase58Check(vch); } return ""; } bool DecodeAddress(string str, CService& addr) { vector<unsigned char> vch; if (!DecodeBase58Check(str.substr(1), vch)) return false; struct ircaddr tmp; if (vch.size() != sizeof(tmp)) return false; memcpy(&tmp, &vch[0], sizeof(tmp)); addr = CService(tmp.ip, ntohs(tmp.port)); return true; } static bool Send(SOCKET hSocket, const char* pszSend) { if (strstr(pszSend, "PONG") != pszSend) printf("IRC SENDING: %s\n", pszSend); const char* psz = pszSend; const char* pszEnd = psz + strlen(psz); while (psz < pszEnd) { int ret = send(hSocket, psz, pszEnd - psz, MSG_NOSIGNAL); if (ret < 0) return false; psz += ret; } return true; } bool RecvLineIRC(SOCKET hSocket, string& strLine) { loop { bool fRet = RecvLine(hSocket, strLine); if (fRet) { if (fShutdown) return false; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() >= 1 && vWords[0] == "PING") { strLine[1] = 'O'; strLine += '\r'; Send(hSocket, strLine.c_str()); continue; } } return fRet; } } int RecvUntil(SOCKET hSocket, const char* psz1, const char* psz2=NULL, const char* psz3=NULL, const char* psz4=NULL) { loop { string strLine; strLine.reserve(10000); if (!RecvLineIRC(hSocket, strLine)) return 0; printf("IRC %s\n", strLine.c_str()); if (psz1 && strLine.find(psz1) != string::npos) return 1; if (psz2 && strLine.find(psz2) != string::npos) return 2; if (psz3 && strLine.find(psz3) != string::npos) return 3; if (psz4 && strLine.find(psz4) != string::npos) return 4; } } bool Wait(int nSeconds) { if (fShutdown) return false; printf("IRC waiting %d seconds to reconnect\n", nSeconds); for (int i = 0; i < nSeconds; i++) { if (fShutdown) return false; Sleep(1000); } return true; } bool RecvCodeLine(SOCKET hSocket, const char* psz1, string& strRet) { strRet.clear(); loop { string strLine; if (!RecvLineIRC(hSocket, strLine)) return false; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() < 2) continue; if (vWords[1] == psz1) { printf("IRC %s\n", strLine.c_str()); strRet = strLine; return true; } } } bool GetIPFromIRC(SOCKET hSocket, string strMyName, CNetAddr& ipRet) { Send(hSocket, strprintf("USERHOST %s\r", strMyName.c_str()).c_str()); string strLine; if (!RecvCodeLine(hSocket, "302", strLine)) return false; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() < 4) return false; string str = vWords[3]; if (str.rfind("@") == string::npos) return false; string strHost = str.substr(str.rfind("@")+1); // Hybrid IRC used by lfnet always returns IP when you userhost yourself, // but in case another IRC is ever used this should work. printf("GetIPFromIRC() got userhost %s\n", strHost.c_str()); CNetAddr addr(strHost, true); if (!addr.IsValid()) return false; ipRet = addr; return true; } void ThreadIRCSeed(void* parg) { IMPLEMENT_RANDOMIZE_STACK(ThreadIRCSeed(parg)); // Make this thread recognisable as the IRC seeding thread RenameThread("bitcoin-ircseed"); try { ThreadIRCSeed2(parg); } catch (std::exception& e) { PrintExceptionContinue(&e, "ThreadIRCSeed()"); } catch (...) { PrintExceptionContinue(NULL, "ThreadIRCSeed()"); } printf("ThreadIRCSeed exited\n"); } void ThreadIRCSeed2(void* parg) { /* Dont advertise on IRC if we don't allow incoming connections */ if (mapArgs.count("-connect") || fNoListen) return; if (!GetBoolArg("-irc", false)) return; printf("ThreadIRCSeed started\n"); int nErrorWait = 10; int nRetryWait = 10; while (!fShutdown) { CService addrConnect("irc.lfnet.org", 6667, true); SOCKET hSocket; if (!ConnectSocket(addrConnect, hSocket)) { addrConnect = CService("pelican.heliacal.net", 6667, true); if (!ConnectSocket(addrConnect, hSocket)) { printf("IRC connect failed\n"); nErrorWait = nErrorWait * 11 / 10; if (Wait(nErrorWait += 60)) continue; else return; } } if (!RecvUntil(hSocket, "Found your hostname", "using your IP address instead", "Couldn't look up your hostname", "ignoring hostname")) { closesocket(hSocket); hSocket = INVALID_SOCKET; nErrorWait = nErrorWait * 11 / 10; if (Wait(nErrorWait += 60)) continue; else return; } CNetAddr addrIPv4("1.2.3.4"); // arbitrary IPv4 address to make GetLocal prefer IPv4 addresses CService addrLocal; string strMyName; if (GetLocal(addrLocal, &addrIPv4)) strMyName = EncodeAddress(GetLocalAddress(&addrConnect)); if (strMyName == "") strMyName = strprintf("x%u", GetRand(1000000000)); Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str()); Send(hSocket, strprintf("USER %s 8 * : %s\r", strMyName.c_str(), strMyName.c_str()).c_str()); int nRet = RecvUntil(hSocket, " 004 ", " 433 "); if (nRet != 1) { closesocket(hSocket); hSocket = INVALID_SOCKET; if (nRet == 2) { printf("IRC name already in use\n"); Wait(10); continue; } nErrorWait = nErrorWait * 11 / 10; if (Wait(nErrorWait += 60)) continue; else return; } Sleep(500); // Get our external IP from the IRC server and re-nick before joining the channel CNetAddr addrFromIRC; if (GetIPFromIRC(hSocket, strMyName, addrFromIRC)) { printf("GetIPFromIRC() returned %s\n", addrFromIRC.ToString().c_str()); if (addrFromIRC.IsRoutable()) { // IRC lets you to re-nick AddLocal(addrFromIRC, LOCAL_IRC); strMyName = EncodeAddress(GetLocalAddress(&addrConnect)); Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str()); } } if (fTestNet) { Send(hSocket, "JOIN #doriancoinTEST3\r"); Send(hSocket, "WHO #doriancoinTEST3\r"); } else { // randomly join #doriancoin00-#doriancoin99 int channel_number = GetRandInt(100); channel_number = 0; // doriancoin: for now, just use one channel Send(hSocket, strprintf("JOIN #doriancoin%02d\r", channel_number).c_str()); Send(hSocket, strprintf("WHO #doriancoin%02d\r", channel_number).c_str()); } int64 nStart = GetTime(); string strLine; strLine.reserve(10000); while (!fShutdown && RecvLineIRC(hSocket, strLine)) { if (strLine.empty() || strLine.size() > 900 || strLine[0] != ':') continue; vector<string> vWords; ParseString(strLine, ' ', vWords); if (vWords.size() < 2) continue; char pszName[10000]; pszName[0] = '\0'; if (vWords[1] == "352" && vWords.size() >= 8) { // index 7 is limited to 16 characters // could get full length name at index 10, but would be different from join messages strlcpy(pszName, vWords[7].c_str(), sizeof(pszName)); printf("IRC got who\n"); } if (vWords[1] == "JOIN" && vWords[0].size() > 1) { // :username!username@50000007.F000000B.90000002.IP JOIN :#channelname strlcpy(pszName, vWords[0].c_str() + 1, sizeof(pszName)); if (strchr(pszName, '!')) *strchr(pszName, '!') = '\0'; printf("IRC got join\n"); } if (pszName[0] == 'u') { CAddress addr; if (DecodeAddress(pszName, addr)) { addr.nTime = GetAdjustedTime(); if (addrman.Add(addr, addrConnect, 51 * 60)) printf("IRC got new address: %s\n", addr.ToString().c_str()); nGotIRCAddresses++; } else { printf("IRC decode failed\n"); } } } closesocket(hSocket); hSocket = INVALID_SOCKET; if (GetTime() - nStart > 20 * 60) { nErrorWait /= 3; nRetryWait /= 3; } nRetryWait = nRetryWait * 11 / 10; if (!Wait(nRetryWait += 60)) return; } } #ifdef TEST int main(int argc, char *argv[]) { WSADATA wsadata; if (WSAStartup(MAKEWORD(2,2), &wsadata) != NO_ERROR) { printf("Error at WSAStartup()\n"); return false; } ThreadIRCSeed(NULL); WSACleanup(); return 0; } #endif
[ "x21coin@outlook.com" ]
x21coin@outlook.com
614b83e699a46856e7deff02610db0c59886af2f
8bb13df66047ee25f55fb7f428b5b5d313705926
/Hashcionary/JanelaElimina.h
596c78e57ffae0fc672f5b79c6c6121eb8310b7b
[]
no_license
thiagoarmede/HashcionaryFinal
ca6964a218222818baccada74031873c57e0d9f2
960a76a8a76ce33de5c2e64fa571ebc6c97cbfdc
refs/heads/master
2021-07-18T22:16:21.752135
2017-10-27T05:03:11
2017-10-27T05:03:11
107,429,898
0
0
null
null
null
null
UTF-8
C++
false
false
338
h
#pragma once #include <QWidget> #include "ui_JanelaElimina.h" #include "Hashing.h" #include "popup1.h" class JanelaElimina : public QWidget { Q_OBJECT public: JanelaElimina(QWidget *parent = Q_NULLPTR); ~JanelaElimina(); popup1 *popup; void popupEliminou(); public slots: void eliminaPalavra(); private: Ui::JanelaElimina ui; };
[ "thiagoarmede@gmail.com" ]
thiagoarmede@gmail.com
d08c51903e26c165395c58853d836c5a21dfa851
a02d6d6c8db6a94156113f592dfe7f4698d97092
/Chapter_4/explicit_return_type_3.cpp
d57bf3b07bb00c064e4cca50e556f94e44d31af0
[ "MIT" ]
permissive
wagnerhsu/packt-CPP-Templates-Up-and-Running
0e884dcefca1fd954877ceb7a1d8af187eaf65ed
2dcede8bb155d609a1b8d9765bfd4167e3a57289
refs/heads/main
2023-06-23T14:02:55.872749
2021-07-10T12:45:06
2021-07-10T12:45:06
383,464,461
0
0
null
null
null
null
UTF-8
C++
false
false
395
cpp
#include <iostream> template<typename T, typename U> U get_coef(T type) { std::cout << type << std::endl; U ret; switch(type) { case 1: ret = 20.5; break; case 2: ret = 100.5; break; default: ret = 10.4; } return ret; } int main() { int type = 2; std::cout << get_coef<double>(type) << std::endl; return 0; }
[ "vivek.bhadra@gmail.com" ]
vivek.bhadra@gmail.com
54e49d985052622ae19c00be63d78bcb733e524f
da3215baf37d257d5814f165e98b4b19dee9cb05
/SDK/FN_RadialPicker_parameters.hpp
acc9f78361b7afc54f203ffa5b11768a750c068a
[]
no_license
Griizz/Fortnite-Hack
d37a6eea3502bf1b7c78be26a2206c8bc70f6fa5
5b80d585065372a4fb57839b8022dc522fe4110b
refs/heads/Griizz_Version
2022-04-01T22:10:36.081573
2019-05-21T19:28:30
2019-05-21T19:28:30
106,034,464
115
85
null
2020-02-06T04:00:07
2017-10-06T17:55:47
C++
UTF-8
C++
false
false
5,633
hpp
#pragma once // Fortnite SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "../SDK.hpp" namespace SDK { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function RadialPicker.RadialPicker_C.SetShowMouseCursor struct URadialPicker_C_SetShowMouseCursor_Params { bool InShowMouseCursor; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData) }; // Function RadialPicker.RadialPicker_C.SetPointerDirection struct URadialPicker_C_SetPointerDirection_Params { }; // Function RadialPicker.RadialPicker_C.IsGamepadInPickerDeadZone struct URadialPicker_C_IsGamepadInPickerDeadZone_Params { bool bIsInDeadZone; // (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_IsPlainOldData) }; // Function RadialPicker.RadialPicker_C.MoveActiveOption struct URadialPicker_C_MoveActiveOption_Params { int MoveOptionDirection; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData) }; // Function RadialPicker.RadialPicker_C.ResetInput struct URadialPicker_C_ResetInput_Params { }; // Function RadialPicker.RadialPicker_C.CanConfirm struct URadialPicker_C_CanConfirm_Params { bool CanAccept; // (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_IsPlainOldData) }; // Function RadialPicker.RadialPicker_C.SetInputMode struct URadialPicker_C_SetInputMode_Params { }; // Function RadialPicker.RadialPicker_C.SetActiveOption struct URadialPicker_C_SetActiveOption_Params { int Option; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData) }; // Function RadialPicker.RadialPicker_C.ClearActiveOption struct URadialPicker_C_ClearActiveOption_Params { }; // Function RadialPicker.RadialPicker_C.GetOptionAngle struct URadialPicker_C_GetOptionAngle_Params { int Option; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData) float Angle; // (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_IsPlainOldData) }; // Function RadialPicker.RadialPicker_C.GetAngleDifference struct URadialPicker_C_GetAngleDifference_Params { float AngleA; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData) float AngleB; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData) float Difference; // (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_IsPlainOldData) }; // Function RadialPicker.RadialPicker_C.GetOptionPosition struct URadialPicker_C_GetOptionPosition_Params { int Option; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData) struct FVector2D Position; // (CPF_Parm, CPF_OutParm, CPF_IsPlainOldData) }; // Function RadialPicker.RadialPicker_C.InitializePicker struct URadialPicker_C_InitializePicker_Params { EFortPickerMode PickerMode; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData) int InitialOption; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData) }; // Function RadialPicker.RadialPicker_C.Tick struct URadialPicker_C_Tick_Params { struct FGeometry* MyGeometry; // (CPF_Parm, CPF_IsPlainOldData) float* InDeltaTime; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData) }; // Function RadialPicker.RadialPicker_C.Construct struct URadialPicker_C_Construct_Params { }; // Function RadialPicker.RadialPicker_C.Event AcceptOption struct URadialPicker_C_Event_AcceptOption_Params { }; // Function RadialPicker.RadialPicker_C.Event CancelPicker struct URadialPicker_C_Event_CancelPicker_Params { }; // Function RadialPicker.RadialPicker_C.ClosePicker struct URadialPicker_C_ClosePicker_Params { }; // Function RadialPicker.RadialPicker_C.AcceptChosenOption struct URadialPicker_C_AcceptChosenOption_Params { int PickerOption; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData) }; // Function RadialPicker.RadialPicker_C.OnPickerRefreshItems struct URadialPicker_C_OnPickerRefreshItems_Params { }; // Function RadialPicker.RadialPicker_C.ExecuteUbergraph_RadialPicker struct URadialPicker_C_ExecuteUbergraph_RadialPicker_Params { int EntryPoint; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "sinbadhacks@gmail.com" ]
sinbadhacks@gmail.com
4c0a59dcb2fa0b49a5f7abdeec7f446c33368450
43d318ff49c6ee368db1274d55b3bbf66a9a9461
/HorrorPrototype/AI/Services/BTS_CheckPatrolTime.h
fe528c26a279fc1c1eb0654c0421129f1c19b656
[]
no_license
dyg006/FPSHorrorPrototype
cc1accdbb2502d9526b3f4fca63b42178e72f489
41b01e6888a51fd1c96728d24c327a7ee32d7458
refs/heads/master
2022-12-08T04:39:42.921332
2020-07-28T21:19:13
2020-07-28T21:19:13
283,244,388
0
0
null
null
null
null
UTF-8
C++
false
false
671
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "BehaviorTree/BTService.h" #include "BTS_CheckPatrolTime.generated.h" /** * */ UCLASS() class HORRORPROTOTYPE_API UBTS_CheckPatrolTime : public UBTService { GENERATED_BODY() public: UBTS_CheckPatrolTime(); /// <summary> /// Ticks the node. /// </summary> /// <param name="OwnerComp">The owner comp.</param> /// <param name="NodeMemory">The node memory.</param> /// <param name="DeltaSeconds">The delta seconds.</param> virtual void TickNode(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory, float DeltaSeconds) override; };
[ "diego_yguay2@hotmail.com" ]
diego_yguay2@hotmail.com
d269df889e54e60b1f616408eda439d51cb2346b
685e13ac69e688f7221e2adf0ba9fa8ec6b32660
/03/ex02/FragTrap.hpp
230688ac1497c59b17d9d5a999516a5c73d826a9
[]
no_license
vrdbettoni/piscine_cpp
2000e53d99c02f7f84ccb731861b68a7e5969d70
30dc11fa207ea66d1c86125ddc61d08eb7415ac3
refs/heads/master
2023-03-14T18:04:39.459266
2021-03-17T14:35:12
2021-03-17T14:35:12
332,657,558
0
0
null
null
null
null
UTF-8
C++
false
false
425
hpp
#ifndef FRAGTRAP_HPP # define FRAGTRAP_HPP #include <iostream> #include <cstdlib> #include "ClapTrap.hpp" class FragTrap : public ClapTrap { public: FragTrap(); FragTrap(std::string name); ~FragTrap(); FragTrap(const FragTrap&); FragTrap& operator=(const FragTrap&); void vaulthunter_dot_exe(std::string const &target); private: void setStats(); }; #endif
[ "vroth-di@student.42lyon.fr" ]
vroth-di@student.42lyon.fr
02f5669d1da4655750c4f1f3e6c00418019ccfe5
7f8fb92af3bae8c60b5886cc12d4d7da31f470a7
/helper_methods.cpp
d0be7962a5e3267db6368be95d6f269e24f9b70d
[]
no_license
DiboraHaile/wumpus
6dea4c8fa57823e59f90688509ef768615f5474a
258b9b9ff3e6da68918cce3dc29c4001df22ba58
refs/heads/master
2022-06-07T00:19:56.859887
2020-05-02T12:40:51
2020-05-02T12:40:51
255,151,213
0
0
null
null
null
null
UTF-8
C++
false
false
809
cpp
#include <iostream> #include <string> #include "helper_methods.hpp" bool helper_methods::Not(bool a){ int operand_no = 1; return !a; } bool helper_methods::And(bool a, bool b){ int operand_no = 2; if (a and b) return true; else return false; } bool helper_methods::Or(bool a, bool b){ int operand_no = 2; if (a or b) return true; else return false; } bool helper_methods::Imp(bool a, bool b){ int operand_no = 2; if (!a or b) return true; else return false; } bool helper_methods::Bimp(bool a, bool b){ int operand_no = 2; if ((a and b) or (!a and !b)) return true; else return false; }
[ "deborahaile3@gmail.com" ]
deborahaile3@gmail.com
d0f96d97034dbf97137c2faed6f9062cd3c574ec
f89d365228e236cb9875114524c9460360234676
/Week-05/Day-02/GreenFoxExercise/sponsor.h
4b90cd398bacc873e380c61ea2c090ef263e2cf5
[]
no_license
green-fox-academy/Dextyh
8c08afc3318df61b99029c8a3c821c8eed21da0b
2da333d385526aeda779605f129e35e70b266034
refs/heads/master
2020-04-02T17:22:06.014213
2019-01-30T11:36:03
2019-01-30T11:36:03
154,655,041
0
0
null
null
null
null
UTF-8
C++
false
false
402
h
#ifndef GREENFOXEXERCISE_SPONSOR_H #define GREENFOXEXERCISE_SPONSOR_H #include <iostream> #include "person.h" class Sponsor : public Person { public: Sponsor(std::string name, int age, Gender gender, std::string company); Sponsor(); void introduce() override; void hire(); void getGoal() override; protected: std::string _company; int _hiredStudents; }; #endif
[ "tmark.boy001@gmail.com" ]
tmark.boy001@gmail.com
0dfb99bc3a748bf5847455d2716cabcf61c9cd75
b3cec46417829c50c9860c82d157a286c2ccd624
/modified_files_in_caffe/layers/Berhu_loss_layer.hpp
6d385aded019ad3a685c86e28411953749b2cba9
[]
no_license
dkanou/tsrenet
cfd62a7ba793174627492b84a04b9b7605695cde
575c7851c9e65c9b7977d00531e3bd4f3da8e118
refs/heads/master
2020-03-24T07:38:02.229141
2018-09-21T16:26:44
2018-09-21T16:26:44
142,570,275
1
1
null
null
null
null
UTF-8
C++
false
false
4,106
hpp
#ifndef CAFFE_BERHU_LOSS_LAYER_HPP_ #define CAFFE_BERHU_LOSS_LAYER_HPP_ #include <vector> #include "caffe/blob.hpp" #include "caffe/layer.hpp" #include "caffe/proto/caffe.pb.h" #include "caffe/layers/loss_layer.hpp" namespace caffe { /** * @brief Computes the Berhu (L1 or L2) loss * C is @f$ 0.2* abs(\left| \left| \hat{y}_n - y_n \right| \right|) @f$ * if @f$ abs (\left| \left| \hat{y}_n - y_n \right| \right|) <= C @f$ * @f$ E = \sum\limits_{n=1}^N \left| \left| \hat{y}_n - y_n @f$ * else * @f$ E = \frac{1}{2C} \sum\limits_{n=1}^N \left| \left| \hat{y}_n - y_n * \right| \right|_2^2 + C^2 @f$ for real-valued regression tasks. * * @param bottom input Blob vector (length 2) * -# @f$ (N \times C \times H \times W) @f$ * the predictions @f$ \hat{y} \in [-\infty, +\infty]@f$ * -# @f$ (N \times C \times H \times W) @f$ * the targets @f$ y \in [-\infty, +\infty]@f$ * @param top output Blob vector (length 1) * -# @f$ (1 \times 1 \times 1 \times 1) @f$ * * This can be used for regression tasks. Proved to work better for heavy tailed distribution. */ template <typename Dtype> class BerhuLossLayer : public LossLayer<Dtype> { public: explicit BerhuLossLayer(const LayerParameter& param) : LossLayer<Dtype>(param), diff_() {} virtual void Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual inline const char* type() const { return "BerhuLoss"; } /** * Unlike most loss layers, in the BerhuLossLayer we can backpropagate * to both inputs -- override to return true and always allow force_backward. */ virtual inline bool AllowForceBackward(const int bottom_index) const { return true; } protected: /// @copydoc BerhuLossLayer virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); /** * @brief Computes the Berhu error gradient w.r.t. the inputs. (modified according to C) * * Unlike other children of LossLayer, BerhuLossLayer \b can compute * gradients with respect to the label inputs bottom[1] (but still only will * if propagate_down[1] is set, due to being produced by learnable parameters * or if force_backward is set). In fact, this layer is "commutative" -- the * result is the same regardless of the order of the two bottoms. * * @param top output Blob vector (length 1), providing the error gradient with * respect to the outputs * -# @f$ (1 \times 1 \times 1 \times 1) @f$ * This Blob's diff will simply contain the loss_weight* @f$ \lambda @f$, * as @f$ \lambda @f$ is the coefficient of this layer's output * @f$\ell_i@f$ in the overall Net loss * @f$ E = \lambda_i \ell_i + \mbox{other loss terms}@f$; hence * @f$ \frac{\partial E}{\partial \ell_i} = \lambda_i @f$. * (*Assuming that this top Blob is not used as a bottom (input) by any * other layer of the Net.) * @param propagate_down see Layer::Backward. * @param bottom input Blob vector (length 2) * -# @f$ (N \times C \times H \times W) @f$ * the predictions @f$\hat{y}@f$; Backward fills their diff with * gradients @f$ * \frac{\partial E}{\partial \hat{y}} = * \frac{1}{n} \sum\limits_{n=1}^N (\hat{y}_n - y_n) * @f$ if propagate_down[0] * -# @f$ (N \times C \times H \times W) @f$ * the targets @f$y@f$; Backward fills their diff with gradients * @f$ \frac{\partial E}{\partial y} = * \frac{1}{n} \sum\limits_{n=1}^N (y_n - \hat{y}_n) * @f$ if propagate_down[1] */ virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); Blob<Dtype> diff_; }; } // namespace caffe #endif // CAFFE_BERHU_LOSS_LAYER_HPP_
[ "vivek.sury28@gmail.com" ]
vivek.sury28@gmail.com
2ea3525182a484b5a661a82ea2f50a96fc75f069
9a410544d62fe7df68e8fa9b62badcc04bab0fb8
/drewTe/drewTe/drewTeDoc.cpp
1afad6ab1dcec3ab477015c2ec2cc9fa1b4f8eee
[]
no_license
rayAthavtis/VisualHK
4c67a5cbc194bc903d2ce67ca78bc93d98dd812d
cbacbdb23e4abf96102dcc9b1eba6d919c9e0917
refs/heads/master
2022-04-24T11:03:23.152766
2020-04-29T04:41:17
2020-04-29T04:41:17
259,825,801
0
0
null
null
null
null
GB18030
C++
false
false
2,770
cpp
// drewTeDoc.cpp : CdrewTeDoc 类的实现 // #include "stdafx.h" // SHARED_HANDLERS 可以在实现预览、缩略图和搜索筛选器句柄的 // ATL 项目中进行定义,并允许与该项目共享文档代码。 #ifndef SHARED_HANDLERS #include "drewTe.h" #endif #include "drewTeDoc.h" #include <propkey.h> #ifdef _DEBUG #define new DEBUG_NEW #endif // CdrewTeDoc IMPLEMENT_DYNCREATE(CdrewTeDoc, CDocument) BEGIN_MESSAGE_MAP(CdrewTeDoc, CDocument) END_MESSAGE_MAP() // CdrewTeDoc 构造/析构 CdrewTeDoc::CdrewTeDoc() { // TODO: 在此添加一次性构造代码 m_str.Empty(); m_point=CPoint(0,0); } CdrewTeDoc::~CdrewTeDoc() { } BOOL CdrewTeDoc::OnNewDocument() { if (!CDocument::OnNewDocument()) return FALSE; // TODO: 在此添加重新初始化代码 // (SDI 文档将重用该文档) return TRUE; } // CdrewTeDoc 序列化 void CdrewTeDoc::Serialize(CArchive& ar) { if (ar.IsStoring()) { ar<<m_str<<m_point; // TODO: 在此添加存储代码 } else { ar>>m_str>>m_point; // TODO: 在此添加加载代码 } } void CdrewTeDoc::Set(CString &str,CPoint &point){ m_str=str; m_point=point; } void CdrewTeDoc::Get(CString &str,CPoint &point){ str=m_str; point=m_point; } #ifdef SHARED_HANDLERS // 缩略图的支持 void CdrewTeDoc::OnDrawThumbnail(CDC& dc, LPRECT lprcBounds) { // 修改此代码以绘制文档数据 dc.FillSolidRect(lprcBounds, RGB(255, 255, 255)); CString strText = _T("TODO: implement thumbnail drawing here"); LOGFONT lf; CFont* pDefaultGUIFont = CFont::FromHandle((HFONT) GetStockObject(DEFAULT_GUI_FONT)); pDefaultGUIFont->GetLogFont(&lf); lf.lfHeight = 36; CFont fontDraw; fontDraw.CreateFontIndirect(&lf); CFont* pOldFont = dc.SelectObject(&fontDraw); dc.DrawText(strText, lprcBounds, DT_CENTER | DT_WORDBREAK); dc.SelectObject(pOldFont); } // 搜索处理程序的支持 void CdrewTeDoc::InitializeSearchContent() { CString strSearchContent; // 从文档数据设置搜索内容。 // 内容部分应由“;”分隔 // 例如: strSearchContent = _T("point;rectangle;circle;ole object;"); SetSearchContent(strSearchContent); } void CdrewTeDoc::SetSearchContent(const CString& value) { if (value.IsEmpty()) { RemoveChunk(PKEY_Search_Contents.fmtid, PKEY_Search_Contents.pid); } else { CMFCFilterChunkValueImpl *pChunk = NULL; ATLTRY(pChunk = new CMFCFilterChunkValueImpl); if (pChunk != NULL) { pChunk->SetTextValue(PKEY_Search_Contents, value, CHUNK_TEXT); SetChunkValue(pChunk); } } } #endif // SHARED_HANDLERS // CdrewTeDoc 诊断 #ifdef _DEBUG void CdrewTeDoc::AssertValid() const { CDocument::AssertValid(); } void CdrewTeDoc::Dump(CDumpContext& dc) const { CDocument::Dump(dc); } #endif //_DEBUG // CdrewTeDoc 命令
[ "861322624@qq.com" ]
861322624@qq.com
7805f27d349ee9bc22928298543093aefa2433b5
01ee682e4ca1d3b6c5d40bbb77a6be42a9fe66c4
/src/arm_rrt/test_dynamic_rrt.cpp
9a27c430a5945d639bbc1fc87ef9bd5f2ac910d7
[]
no_license
Greattc/schunk_rrt
1e1da1cd531edd98672c89b6113d46a19ee51e8c
d42875b0572c3c90c00cd56a042543d546ea80f1
refs/heads/master
2021-01-22T02:34:40.366938
2015-01-08T06:04:28
2015-01-08T06:04:28
28,951,580
1
0
null
null
null
null
UTF-8
C++
false
false
1,924
cpp
#include "schunk_rrt/dynamic_rrt.h" #include <boost/shared_ptr.hpp> #include <ros/callback_queue.h> #include "schunk_kinematics/arm_kinematics.h" using namespace fcl; using Eigen::VectorXd; using Eigen::MatrixXd; using std::cout; using std::endl; int main(int argc, char **argv) { ros::init(argc, argv, "dynamicRRT"); std::vector<double> init_vec(7, 0.0); std::vector<double> goal_vec(7, 1.0); // std::vector<double> goal_vec(7, 0.5); VectorXd IK(7), linkLen(7), IK0(7); MatrixXd Goal(4,4); Goal<< 0.0, -1.0, 0.0,-0.4,\ 0.0, 0.0, 1.0, 0.6,\ -1.0, 0.0, 0.0, 0.3,\ 0.0, 0.0, 0.0, 1.0; linkLen<<0.3,0.0,0.328,0.0,0.276,0.0,0.1785; //Grasp Link IK0 << 0.8407, 1.2096, 0.0, 0.635, 0.0, 0.0, 0.0; IK << 2.168, 1.2096, 0.0, 0.6350, 0.0, -0.2268, 0.0; inverse_kinematics(IK, linkLen, Goal, false, 0); minimum_energy(IK, IK0); // cout << forward_kinematics(IK, linkLen) << endl; // cout << forward_kinematics(IK0, linkLen) << endl; for(int i=0; i<7; ++i) { init_vec[i] = IK0(i); goal_vec[i] = IK(i); } NodePtr start(new Node(init_vec)); NodePtr goal(new Node(goal_vec)); ros::NodeHandle nh1; //second nodehandle and service queue for working in second thread ros::NodeHandle nh2(nh1); ros::CallbackQueue service_queue(true); nh2.setCallbackQueue(&service_queue); DynamicRRT rrt(start, goal, nh1, nh2); boost::shared_ptr<Sphere> box(new Sphere(0.1)); Transform3f tf1; tf1.setIdentity(); tf1.setTranslation(Vec3f(0.0, 1.0, 0.5)); rrt.rrt->addObstacle(box, tf1); ros::Rate r(2); ros::AsyncSpinner spinner2(1,&service_queue); spinner2.start(); ros::AsyncSpinner spinner(1); spinner.start(); ros::waitForShutdown(); /* while (ros::ok()) { ros::spinOnce(); r.sleep(); } */ return 0; }
[ "robot.myth2014@gmail.com" ]
robot.myth2014@gmail.com
25397a79071479a9f45c36bf10305026488fa8a9
95513dd56f370a48cc684aedb3965cc9e85ab957
/message_widget.cpp
69a7bc180afd40c579062112cb800b6c9c0bb45c
[]
no_license
shashwb/VTDraw
6dd66b6c665164f9b32ea57e8ba98240e675f33d
916866bb8bd75fb6d114575171b09302029c679e
refs/heads/master
2021-03-16T05:13:06.052200
2017-07-05T20:32:17
2017-07-05T20:32:17
91,541,694
0
0
null
null
null
null
UTF-8
C++
false
false
1,027
cpp
#include "message_widget.hpp" #include "repl_widget.hpp" #include "qt_interpreter.hpp" #include <QLineEdit> #include <QKeyEvent> #include <QString> #include <QLayout> MessageWidget::MessageWidget (QWidget * parent) : QWidget (parent) { message_box = new QLineEdit(); QBoxLayout *horizontal_layout = new QHBoxLayout; QLabel *message = new QLabel("Message:"); horizontal_layout->addWidget(message); horizontal_layout->addWidget(message_box); this->setLayout(horizontal_layout); message_box->setReadOnly(true); } void MessageWidget::error(QString message) { QPalette *palette = new QPalette(); palette->setColor(QPalette::Highlight,Qt::red); palette->setColor(QPalette::Text,Qt::black); message_box->setPalette(*palette); message_box->setText(message); message_box->selectAll(); } void MessageWidget::info(QString message) { QPalette *palette = new QPalette(); palette->setColor(QPalette::Text,Qt::black); message_box->setPalette(*palette); message_box->setText(message); }
[ "shashwb@vt.edu" ]
shashwb@vt.edu
b1e092bae396e38ac6c3de17d132bbab5637d371
73c236437958c9fde595609a0ce8d24823e46071
/auto_dirvers_mobile/main.cpp
83b4d1a7f8f9f12ecf0192f0e06686ce46c7c9cb
[]
no_license
blacksjt/autobots
f7f4bd4e870066a44ad83f86020aeb3e580a523c
0b92d832afa6b3afcbc49b677c1489029227fae0
refs/heads/master
2020-04-16T02:11:56.871238
2017-06-27T12:01:18
2017-06-27T12:01:18
63,883,688
1
0
null
null
null
null
UTF-8
C++
false
false
196
cpp
#include "auto_dirvers_mobile.h" #include <QtWidgets/QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); auto_dirvers_fatie w; w.show(); return a.exec(); }
[ "Administrator@USER-20170110ZO" ]
Administrator@USER-20170110ZO
d04b088d6c5078620d49c7dcf614fb1033708510
67099389ed791705d9c20889e2065b0227a4db27
/server/master/master/FileTransfer.cpp
bc5856b4a3509e5b07ba57b4af9d196d50c30d83
[]
no_license
shennong/trochilus1
b6a626913c0bab0f66672c9b2ae2145cf80ff39a
8bb0de53e81263ec1cb2130934142b23dce0dca6
refs/heads/master
2021-01-24T23:34:39.294082
2015-07-01T14:52:52
2015-07-01T14:52:52
null
0
0
null
null
null
null
GB18030
C++
false
false
7,240
cpp
#include "StdAfx.h" #include "FileTransfer.h" #include "CommManager.h" CFileTransfer::CFileTransfer() { } CFileTransfer::~CFileTransfer() { } BOOL CFileTransfer::Init() { CommManager::GetInstanceRef().RegisterMsgHandler(MSGID_GET_FILE, MsgHandler_GetFile, this); CommManager::GetInstanceRef().RegisterMsgHandler(MSGID_PUT_FILE, MsgHandler_PutFile, this); return TRUE; } BOOL CFileTransfer::MsgHandler_GetFile( MSGID msgid, const CommData& commData, LPVOID lpParameter ) { CFileTransfer* lpClass = (CFileTransfer*)lpParameter; return lpClass->MsgHandler_GetFile_Proc(msgid,commData); } BOOL CFileTransfer::MsgHandler_GetFile_Proc(MSGID msgid, const CommData& commData) { DECLARE_STR_PARAM(serverpath) DECLARE_STR_PARAM(clientpath) DECLARE_STR_PARAM(md5) DECLARE_UINT64_PARAM(size) DECLARE_UINT64_PARAM(offset) DECLARE_UINT64_PARAM(total) MyFile file; BOOL ret = file.Open(serverpath.c_str(),GENERIC_READ); if (!ret) return FALSE; int FileSize = GetFileSize(file,0); file.Close(); do { TRANS_STATUS status; ByteBuffer buffer; int nReaded = 0xffffffff; if (FileSize != offset) nReaded = CFileParser::GetInstanceRef().Read(serverpath.c_str(),offset,size,md5,buffer); if (!nReaded) break; status.isDown = FALSE; status.nCurPos = offset; status.nTotal = FileSize; lstrcpy(status.strSPath,serverpath.c_str()); lstrcpy(status.strCPath,clientpath.c_str()); UpdateTransferList(commData.GetClientID(),status); //下载完成则停止请求 if (offset == FileSize) break; CommData sendData; sendData.SetMsgID(MSGID_PUT_FILE); sendData.SetData(_T("serverpath"), serverpath.c_str()); sendData.SetData(_T("clientpath"), clientpath.c_str()); sendData.SetData(_T("size"), nReaded); sendData.SetData(_T("total"),FileSize); sendData.SetData(_T("md5"), md5.c_str()); sendData.SetByteData(buffer,buffer.Size()); DWORD serialID = CommManager::GetInstanceRef().AddToSendMessage(commData.GetClientID(), sendData); if (INVALID_MSGSERIALID == serialID) { errorLog(_T("add to send msg failed")); break; } } while (FALSE); return TRUE; } BOOL CFileTransfer::MsgHandler_PutFile( MSGID msgid, const CommData& commData, LPVOID lpParameter ) { CFileTransfer* lpClass = (CFileTransfer*)lpParameter; return lpClass->MsgHandler_PutFile_Proc(msgid,commData); } BOOL CFileTransfer::MsgHandler_PutFile_Proc(MSGID msgid, const CommData& commData) { DECLARE_STR_PARAM(serverpath) DECLARE_STR_PARAM(clientpath) DECLARE_STR_PARAM(md5) DECLARE_UINT64_PARAM(size) DECLARE_UINT64_PARAM(total) ByteBuffer buffer = commData.GetByteData(); do { CFileParser& parser = CFileParser::GetInstanceRef(); if (!parser.IsFileExist(CString(serverpath.c_str())+OPTIONS_EXT)) { DeleteFile(serverpath.c_str()); parser.CreateFileStatus(serverpath.c_str(),md5.c_str(),total); } BOOL ret = CFileParser::GetInstanceRef().Write(serverpath.c_str(),size,md5.c_str(),buffer); FILE_OPTIONS options; TRANS_STATUS status; options.nTotalSize = total; lstrcpyA(options.szMD5,t2a(md5.c_str())); ret = CFileParser::GetInstanceRef().GetFileCurStatus(serverpath.c_str(),options); if (!ret) break; status.isDown = TRUE; status.nCurPos = options.nCurSel; status.nTotal = options.nTotalSize; lstrcpy(status.strSPath,serverpath.c_str()); lstrcpy(status.strCPath,clientpath.c_str()); UpdateTransferList(commData.GetClientID(),status); ret = IsHasStop(serverpath.c_str()); if (!ret && (status.nCurPos != status.nTotal)) RequestGetFile(commData.GetClientID(),clientpath.c_str(),serverpath.c_str()); if ((status.nCurPos == status.nTotal)) { DeleteFile(CString(status.strSPath)+OPTIONS_EXT); } } while (FALSE); return TRUE; } BOOL CFileTransfer::RequestPutFile( LPCTSTR clientid,LPCTSTR clientpath,LPCTSTR serverpath ) { CommData sendData; sendData.SetMsgID(MSGID_REQUESTPUT_FILE); sendData.SetData(_T("serverpath"), serverpath); sendData.SetData(_T("clientpath"), clientpath); DWORD serialID = CommManager::GetInstanceRef().AddToSendMessage(clientid,sendData); if (INVALID_MSGSERIALID == serialID) { errorLog(_T("add to send msg failed")); return FALSE; } return TRUE; } BOOL CFileTransfer::RequestGetFile( LPCTSTR clientid,LPCTSTR clientpath,LPCTSTR serverpath ) { FILE_OPTIONS options; BOOL ret = CFileParser::GetInstanceRef().GetFileCurStatus(serverpath,options); if (!ret) return FALSE; CommData sendData; sendData.SetMsgID(MSGID_GET_FILE); sendData.SetData(_T("serverpath"), serverpath); sendData.SetData(_T("clientpath"), clientpath); sendData.SetData(_T("size"), MAX_BLOCK_SIZE); sendData.SetData(_T("offset"), options.nCurSel); DWORD serialID = CommManager::GetInstanceRef().AddToSendMessage(clientid,sendData); if (INVALID_MSGSERIALID == serialID) { errorLog(_T("add to send msg failed")); return FALSE; } return TRUE; } BOOL CFileTransfer::AddStopList( LPCTSTR serverpath ) { DeleteStopList(serverpath); m_csStopMap.Enter(); { m_stopList.push_back(serverpath); } m_csStopMap.Leave(); return TRUE; } BOOL CFileTransfer::DeleteStopList( LPCTSTR serverpath ) { m_csStopMap.Enter(); { TransStopList::iterator it = m_stopList.begin(); for (; it != m_stopList.end(); it++) { if (*it == serverpath) { m_stopList.erase(it); break; } } } m_csStopMap.Leave(); return TRUE; } BOOL CFileTransfer::IsHasStop(LPCTSTR serverpath) { BOOL ret = FALSE; m_csStopMap.Enter(); { TransStopList::iterator it = m_stopList.begin(); for (; it != m_stopList.end(); it++) { if (*it == serverpath) { ret = TRUE; break; } } } m_csStopMap.Leave(); return ret; } void CFileTransfer::GetTransferList( LPCTSTR clientid,TransStatusVector* list ) { m_csProcessMap.Enter(); { ProcessMap::iterator it = m_processMap.find(clientid); if (it != m_processMap.end()) { TransStatusVector::iterator it2 = it->second.begin(); for (; it2 != it->second.end();it2++) { list->push_back(*it2); } } } m_csProcessMap.Leave(); } BOOL CFileTransfer::GetStatusByPath(LPCTSTR clientid,CString strSPath,TRANS_STATUS& status) { TransStatusVector list; GetTransferList(clientid,&list);; TransStatusVector::iterator it = list.begin(); for(; it != list.end(); it++) { if (CString(it->strSPath) == strSPath) { status = *it; return TRUE; } } return FALSE; } void CFileTransfer::UpdateTransferList( LPCTSTR clientid,TRANS_STATUS& status ) { m_csProcessMap.Enter(); { do { ProcessMap::iterator it1 = m_processMap.find(clientid); TransStatusVector *list; //查找是否存在对应ID的list if (it1 != m_processMap.end()) { list = &m_processMap[clientid]; } //如果list不存在,则添加 else { TransStatusVector newlist; newlist.push_back(status); m_processMap[clientid] = newlist; break; } //迭代查找符合条件的 TransStatusVector::iterator it2 = list->begin(); for (; it2 != list->end(); it2++) { if (CString(it2->strSPath) == CString(status.strSPath)) { *it2 = status; break; } } if (it2 == list->end()) { list->push_back(status); } } while (FALSE); } m_csProcessMap.Leave(); }
[ "floyd419@foxmail.com" ]
floyd419@foxmail.com
f4884f22b9f2e5d32bed6750a91278033d7bde0b
00eaeacedc909bf421474eb6bb3c84ed370258aa
/matrixchainmulti.cpp
5bc4f13e18a4ade4296b7613cf403c89013c5539
[]
no_license
kibo27/coding
232e51a96214b4bc0db12dd7ec8f8e2cddc7bba4
4bf5d21048e399fdb2cf0f6dc7ad4df573ad70e5
refs/heads/master
2020-12-28T16:35:18.168628
2020-03-07T04:16:38
2020-03-07T04:16:38
238,406,767
0
0
null
null
null
null
UTF-8
C++
false
false
807
cpp
//matrix chain multiplication #include<bits/stdc++.h> using namespace std; void solve() { int n; cin>>n; int a[n]; for(int i=0;i<n;i++) { cin>>a[i]; } vector<vector<int>> dp(n,vector<int>(n,0)); for(int l=2;l<n;l++) { for(int i=1;i<n-l+1;i++) { int j=i+l-1; dp[i][j]=INT_MAX; for(int k=i;k<j;k++) { dp[i][j]=min(dp[i][j],dp[i][k]+dp[k+1][j]+a[i-1]*a[k]*a[j]); } } } for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { cout<<dp[i][j]<<" "; } cout<<"\n"; } cout<<dp[1][n-1]<<"\n"; } int main() { ios::sync_with_stdio(false); int t; cin>>t; while(t--) { solve(); } }
[ "anprest149@gmail.com" ]
anprest149@gmail.com
25f4cae9efca1c315087f40c0dd3792b602a00a1
b4c1fbe077a1a630da528963179b27ac044701f8
/glibc-atexit.cpp
fde4cb9c78e1bcec6dfc7deeced453113a99a89e
[]
no_license
giraldeau/test-glibc
5f0aca4fa847f557d83df692563a1dc776c823ee
8bd3799e10814f44e340d39b08f9225b4ce7be07
refs/heads/master
2022-12-19T21:29:09.512059
2020-09-29T20:11:58
2020-09-29T20:11:58
299,727,213
0
0
null
null
null
null
UTF-8
C++
false
false
395
cpp
#ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include <thread> #include <cstdio> #include <cstdlib> #include <dlfcn.h> #ifndef _GLIBCXX_HAVE___CXA_THREAD_ATEXIT_IMPL #error __cxa_thread_atexit_impl not supported #endif int main() { void *addr = dlsym(RTLD_DEFAULT, "__cxa_thread_atexit_impl"); Dl_info info; dladdr(addr, &info); printf("%p %s\n", addr, info.dli_fname); return 0; }
[ "francis.giraldeau@gmail.com" ]
francis.giraldeau@gmail.com
79205347a326791d87ca2c5aabbdf9702a7e18e2
65c414a91ff3615b86b169e0bb486aa59f4ef0bb
/ConsoleApplication1.cpp
217b6c0c8564b34bb8c2cf3eb394896fa0cbb5fe
[]
no_license
yar-yasenkov/Algorythm
8536829ec938e952dfc18b3e031a695aad5ddfa6
e16a1c97658d9d2e8ed2c392940c8741ad2a8e7f
refs/heads/master
2021-06-26T22:19:28.216322
2017-09-15T07:26:22
2017-09-15T07:26:22
103,627,490
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
795
cpp
// ConsoleApplication1.cpp : Defines the entry point for the console application. // #include "stdafx.h" //возвращает n-е число Фибоначчи int fib(int n) { int a = 1, ta, b = 1, tb, c = 1, rc = 0, tc, d = 0, rd = 1; while (n) { if (n & 1) // Если степень нечетная { // Умножаем вектор R на матрицу A tc = rc; rc = rc*a + rd*c; rd = tc*b + rd*d; } // Умножаем матрицу A на саму себя ta = a; tb = b; tc = c; a = a*a + b*c; b = ta*b + b*d; c = c*ta + d*c; d = tc*tb + d*d; n >>= 1; // Уменьшаем степень вдвое } return rc; } int main() { int a; a = fib(4); printf("%d", a); return 0; }
[ "noreply@github.com" ]
noreply@github.com
6664fe66807851ed0408e2d4836b0f97ef6c41e3
38a4b208f5c75f1c74accc64d813ead668937dca
/MixHit/cCocktailMixer.h
5baa7fa9a49f3a54523955c807d9c2990e4c18c6
[]
no_license
DrStealth126/MixHit_Webserver_neu
fca98543f0fea0954ac81cf17fe6f2e0229a0954
fd5f1dc64e1cc81feb8b4aeeb812370c0306ef8c
refs/heads/master
2020-04-07T18:25:11.468527
2018-11-27T14:02:35
2018-11-27T14:02:35
158,609,254
0
0
null
null
null
null
ISO-8859-1
C++
false
false
4,319
h
#ifndef _CCOCKTAILMIXER_H_ #define _CCOCKTAILMIXER_H_ #include "cIngredient.h" #include "Configuration.h" #include "cScale.h" #include "cRotateTable.h" #include "cGlasses.h" #include "cGlass.h" #include "cCocktail.h" #include "cQueueOfOrders.h" #include "cValveControl.h" #include "cReservoir.h" #include "cOrder.h" #include "MyMath.h" #include "cServoMotor.h" #define mixNextCocktail_OK 0 #define mixNextCocktail_OK_WarteschlangeLeer 1 #define mixCocktail_OK 0 #define ERROR_mixCocktail_KeinGlasGefunden -2 #define INIT_Zutaten_OK 0 #define ERROR_INIT_PositionNichtGefunden -1 #define ERROR_INIT_KeinGlasGefunden -2 #define ERROR_INIT_VorratLeer -3 #define findEmptyGlass_OK 0 #define ERROR_findEmptyGlass_PositionNichtGefunden -1 #define ERROR_findEmptyGlass_KeinGlasGefunden -2 class cCocktailMixer { public: cCocktailMixer(); // Standartkonstruktor int addOrderToQueue(cOrder pBestellung); // Fügt eine Bestellung der entspraecheden Warteschlange hinzu. int getNumberOfOrdersInQueue(int pPrio); // Gibt die Anzahl an Cocktails aus, welche aktuell vor einer Bestellung mit angegebener Prio gemixt werden würden. int getNumberOfOrdersBeforeOrderNumber(int pOrderNumber); // Gibt die ANzahl an COcktails aus, welche vor der angegebenen Bestellnummer ausgeschenkt werden. int mixNextCocktail(); // Holt den naechsten Cocktail aus der Warteschlange (unter beruecksichtigung der Prioritaeten) und gibt ihn an "mixCocktail(...); int mixCocktail(cOrder pOrder); // Mixt einen Cocktail (Prüft nach ob ein leeres Glas vorhanden ist). int mixCocktail_TEST(cCocktail pCocktail); // Mixt einen Cocktail ungeachtet aller Sensorwerte (z.B. auch wenn kein Glas unter dem Ausschank steht. int InitIngredients(); // Initialisiert alle Zutaten (siehe InitIngredient(...); int InitIngredient(int pIndex); // Initielisiert den angegebenen Zutatenvorrat (fuer die Werte zur Umrechnugn von Menge zu Zeit) int findEmptyGlass(int& pSlotNumber, int& pGlasIndex); // Sucht nach einem Leeren Glas. int getSlotnummer(int pOrderNumber); // Gibt die aktuelle Bestellnummer zurueck welche sich in dem Slot befindet. int getSlotBestellnummer(int pSlotNumber); // Gibt die aktuelle Bestellnummer zurueck welche sich in dem Slot befindet. String getSlotCocktailName(int pSlotNumber); // Gibt den aktuellen Cocktailnamen zurueck welcher sich in dem Slot befindet. int getNumberOfServedCocktails(); // Gibt die anzahl an gemixten COcktails seit Programmstart zurueck. int getNextOrderNumber(); // Gibt die naechste moegliche freie Bestellnummer zurueck. int getCurrentOrderNumber(); // Gibt die Bestellnummer zurueck, welche zuletzt gemixt wurde. cValveControl mValveControl; // Steuerung der Ventile. cRotateTable mRotateTable; // Drehteller zum rotieren der Glaeser. cReservoir mReservoir; // Informationen zu den Vorraetigen Zutaten. cGlasses mGlasses; // Liste an bekannten Glaeser. cScale mScale; // Waage fuer die Glaserkennung cServoMotor mServo; // Servomotor fuer den Abtropfschutz private: //int getNumberOfOrdersBefore(int pPrio, int pPlace); int mSlotOrderNumber[NumberOfSlotsRotateTable]; // Zuweisen einer Bestellnummer zu einem Slot (Damit man weis, welcher bestellte Cocktail in welchem Slot im Drehteller steht). String mSlotCocktailName[NumberOfSlotsRotateTable ]; // Zuweisen einer Bestellnummer zu einem Slot (Damit man weis, welcher bestellte Cocktail in welchem Slot im Drehteller steht). int mAmountOfMixedCocktails; // Anzahl an gemixten COcktails (seit dem letzten Neustart). byte mQueueSelectCounter; // Wird benoetigt, um zu entscheiden aus welcher Warteschlange eine Bestellung geholt wird (zwischen Prio 0 und Prio 1, da diese sich ggf. abwechseln (Prio 1 3x oefters als Prio 0). cQueueOfOrders mQueue[3]; // Drei Warteschlangen fuer drei Prioritaeten (Prio 2 > Prio 1 > Prio 0) int mNextOrderNumber; // Naechste moegliche freie Bestellnummer. int mCurrentOrderNumber; // Zuletzt gemixte Bestellnummer. void WaitMillis(unsigned long pTime); // Wartet die angegebene Zeit in Millisekunden. Bricht ab, sobald der Betriebsmodus verlassen wird. }; extern cCocktailMixer gCocktailMixer; #endif
[ "43671054+DrStealth126@users.noreply.github.com" ]
43671054+DrStealth126@users.noreply.github.com
4ff50ed3cf490cce4fe17707dfe6d7deded505d9
3b219b05e85c4ba74170e41078c2fe80f5ee0b4d
/src/editor/ScintillaQt.h
2cb01025029ef6513a3dc76685b0c9a18ed1e910
[ "MIT" ]
permissive
shane-gramlich/gitahead
9727ae57ff1841dd3b31953a83ae9a7b4369a551
17796287d99a7fb438b5c38b02429fd9168b4e3e
refs/heads/master
2020-10-02T03:34:29.835909
2019-12-17T19:42:03
2019-12-17T19:42:03
227,692,266
0
0
MIT
2019-12-12T20:38:37
2019-12-12T20:38:35
null
UTF-8
C++
false
false
6,091
h
// // Copyright (c) 2016, Scientific Toolworks, Inc. // // This software is licensed under the MIT License. The LICENSE.md file // describes the conditions under which this software may be distributed. // // Author: Jason Haslam // #ifndef SCINTILLAQT_H #define SCINTILLAQT_H #include <stdlib.h> #include <string.h> #include <stdio.h> #include <assert.h> #include <ctype.h> #include <time.h> #include <cmath> #include <stdexcept> #include <string> #include <vector> #include <map> #include <algorithm> #include <memory> #include "Scintilla.h" #include "Platform.h" #include "ILexer.h" #include "Position.h" #include "SplitVector.h" #include "Partitioning.h" #include "RunStyles.h" #include "ContractionState.h" #include "CellBuffer.h" #include "CallTip.h" #include "KeyMap.h" #include "Indicator.h" #include "XPM.h" #include "LineMarker.h" #include "Style.h" #include "AutoComplete.h" #include "UniqueString.h" #include "ViewStyle.h" #include "CharClassify.h" #include "Decoration.h" #include "CaseFolder.h" #include "ILoader.h" #include "CharacterCategory.h" #include "Document.h" #include "Selection.h" #include "PositionCache.h" #include "EditModel.h" #include "MarginView.h" #include "EditView.h" #include "Editor.h" #include "ScintillaBase.h" #include "CaseConvert.h" #ifdef SCI_LEXER #include "SciLexer.h" #include "PropSetSimple.h" #endif #include <QAbstractScrollArea> #include <QAction> #include <QClipboard> #include <QPaintEvent> #include <QTime> #ifdef SCI_NAMESPACE namespace Scintilla { #endif class ScintillaQt : public QAbstractScrollArea, public ScintillaBase { Q_OBJECT public: ScintillaQt(QWidget *parent = nullptr); virtual ~ScintillaQt(); sptr_t send( unsigned int iMessage, uptr_t wParam = 0, sptr_t lParam = 0) const; signals: // Clients can use this hook to add additional // formats (e.g. rich text) to the MIME data. void aboutToCopy(QMimeData *data); // Scintilla Notifications void linesAdded(int linesAdded); void styleNeeded(int position); void charAdded(int ch); void savePointChanged(bool dirty); void modifyAttemptReadOnly(); void key(int key); void doubleClick(int position, int line); void updateUi(); void modified( int type, int position, int length, int linesAdded, const QByteArray &text, int line, int foldNow, int foldPrev); void macroRecord(int message, uptr_t wParam, sptr_t lParam); void marginClicked(int position, int modifiers, int margin); void textAreaClicked(int line, int modifiers); void needShown(int position, int length); void painted(); void userListSelection(); // Wants some args. void uriDropped(); // Wants some args. void dwellStart(int x, int y); void dwellEnd(int x, int y); void zoom(int zoom); void hotSpotClick(int position, int modifiers); void hotSpotDoubleClick(int position, int modifiers); void callTipClick(); void autoCompleteSelection(int position, const QString &text); void autoCompleteCancelled(); protected: bool event(QEvent *event) override; void timerEvent(QTimerEvent *event) override; void paintEvent(QPaintEvent *event) override; void wheelEvent(QWheelEvent *event) override; void focusInEvent(QFocusEvent *event) override; void focusOutEvent(QFocusEvent *event) override; void resizeEvent(QResizeEvent *event) override; void keyPressEvent(QKeyEvent *event) override; void mousePressEvent(QMouseEvent *event) override; void mouseReleaseEvent(QMouseEvent *event) override; void mouseDoubleClickEvent(QMouseEvent *event) override; void mouseMoveEvent(QMouseEvent *event) override; void contextMenuEvent(QContextMenuEvent *event) override; void dragEnterEvent(QDragEnterEvent *event) override; void dragLeaveEvent(QDragLeaveEvent *event) override; void dragMoveEvent(QDragMoveEvent *event) override; void dropEvent(QDropEvent *event) override; void inputMethodEvent(QInputMethodEvent *event) override; QVariant inputMethodQuery(Qt::InputMethodQuery query) const override; void scrollContentsBy(int dx, int dy) override {} private: void PasteFromMode(QClipboard::Mode); void CopyToModeClipboard(const SelectionText &, QClipboard::Mode); void MoveImeCarets(int offset); void DrawImeIndicator(int indicator, int len); void Initialise() override; void Finalise() override; bool DragThreshold(Point ptStart, Point ptNow) override; bool ValidCodePage(int codePage) const override; void ScrollText(Sci::Line linesToMove) override; void SetVerticalScrollPos() override; void SetHorizontalScrollPos() override; bool ModifyScrollBars(Sci::Line nMax, Sci::Line nPage) override; void ReconfigureScrollBars() override; void Copy() override; void CopyToClipboard(const SelectionText &selectedText) override; void Paste() override; void ClaimSelection() override; void NotifyChange() override; void NotifyParent(SCNotification scn) override; bool FineTickerRunning(TickReason reason) override; void FineTickerStart(TickReason reason, int millis, int tolerance) override; void FineTickerCancel(TickReason reason) override; bool SetIdle(bool on) override; void SetMouseCapture(bool on) override; bool HaveMouseCapture() override; void StartDrag() override; CaseFolder *CaseFolderForEncoding() override; std::string CaseMapString(const std::string &s, int caseMapping) override; void CreateCallTipWindow(PRectangle rc) override; void AddToPopUp(const char *label, int cmd = 0, bool enabled = true) override; sptr_t WndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) override; sptr_t DefWndProc(unsigned int iMessage, uptr_t wParam, sptr_t lParam) override; static sptr_t DirectFunction( sptr_t ptr, unsigned int iMessage, uptr_t wParam, sptr_t lParam); private: QTime time; int preeditPos = -1; QString preeditString; int timers[tickDwell + 1]; int vMax = 0, hMax = 0; // Scroll bar maximums. int vPage = 0, hPage = 0; // Scroll bar page sizes. bool haveMouseCapture = false; friend class ScintillaEditBase; }; #ifdef SCI_NAMESPACE } #endif #endif // SCINTILLAQT_H
[ "jason@scitools.com" ]
jason@scitools.com
58715726633c1d19312c60498e1fae6ea555d593
51973d4f0b22d6b82416ab4c8e36ebf79d5efede
/hpctoolkit/src/lib/prof/Metric-IData.hpp
a7707b3393bdc05cd22a878d2c1eb3526af90305
[]
no_license
proywm/ccprof_hpctoolkit_deps
a18df3c3701c41216d74dca54f957e634ac7c2ed
62d86832ecbe41b5d7a9fb5254eb2b202982b4ed
refs/heads/master
2023-03-29T21:41:21.412066
2021-04-08T17:11:19
2021-04-08T17:11:19
355,986,924
0
1
null
null
null
null
UTF-8
C++
false
false
7,166
hpp
// -*-Mode: C++;-*- // * BeginRiceCopyright ***************************************************** // // $HeadURL$ // $Id$ // // -------------------------------------------------------------------------- // Part of HPCToolkit (hpctoolkit.org) // // Information about sources of support for research and development of // HPCToolkit is at 'hpctoolkit.org' and in 'README.Acknowledgments'. // -------------------------------------------------------------------------- // // Copyright ((c)) 2002-2017, Rice University // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Rice University (RICE) nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // This software is provided by RICE and contributors "as is" and any // express or implied warranties, including, but not limited to, the // implied warranties of merchantability and fitness for a particular // purpose are disclaimed. In no event shall RICE or contributors be // liable for any direct, indirect, incidental, special, exemplary, or // consequential damages (including, but not limited to, procurement of // substitute goods or services; loss of use, data, or profits; or // business interruption) however caused and on any theory of liability, // whether in contract, strict liability, or tort (including negligence // or otherwise) arising in any way out of the use of this software, even // if advised of the possibility of such damage. // // ******************************************************* EndRiceCopyright * //*************************************************************************** // // File: // $HeadURL$ // // Purpose: // [The purpose of this file] // // Description: // [The set of functions, macros, etc. defined in the file] // //*************************************************************************** #ifndef prof_Prof_Metric_IData_hpp #define prof_Prof_Metric_IData_hpp //************************* System Include Files **************************** #include <iostream> #include <string> #include <vector> #include <typeinfo> #include <algorithm> #include <climits> //*************************** User Include Files **************************** #include <include/uint.h> #include <lib/support/diagnostics.h> //*************************** Forward Declarations ************************** //*************************************************************************** namespace Prof { namespace Metric { //*************************************************************************** // IData // // Interface/Mixin for metric data // // Optimized for the two expected common cases: // 1. no metrics (hpcstruct's using Prof::Struct::Tree) // 2. a known number of metrics (which may then be expanded) //*************************************************************************** class IData { public: typedef std::vector<double> MetricVec; public: // -------------------------------------------------------- // Create/Destroy // -------------------------------------------------------- IData(size_t size = 0) : m_metrics(NULL) { if (size != 0) { ensureMetricsSize(size); } } virtual ~IData() { delete m_metrics; } IData(const IData& x) : m_metrics(NULL) { if (x.m_metrics) { m_metrics = new MetricVec(*(x.m_metrics)); } } IData& operator=(const IData& x) { if (this != &x) { clearMetrics(); if (x.m_metrics) { m_metrics = new MetricVec(*(x.m_metrics)); } } return *this; } // -------------------------------------------------------- // Metrics // -------------------------------------------------------- static const uint npos = UINT_MAX; bool hasMetrics(uint mBegId = Metric::IData::npos, uint mEndId = Metric::IData::npos) const { if (mBegId == IData::npos) { mBegId = 0; } mEndId = std::min(numMetrics(), mEndId); for (uint i = mBegId; i < mEndId; ++i) { if (hasMetric(i)) { return true; } } return false; } bool hasMetric(size_t mId) const { return ((*m_metrics)[mId] != 0.0); } bool hasMetricSlow(size_t mId) const { return (m_metrics && mId < m_metrics->size() && hasMetric(mId)); } double metric(size_t mId) const { return (*m_metrics)[mId]; } double& metric(size_t mId) { return (*m_metrics)[mId]; } double demandMetric(size_t mId, size_t size = 0) const { size_t sz = std::max(size, mId+1); ensureMetricsSize(sz); return metric(mId); } double& demandMetric(size_t mId, size_t size = 0) { size_t sz = std::max(size, mId+1); ensureMetricsSize(sz); return metric(mId); } // zeroMetrics: takes bounds of the form [mBegId, mEndId) // N.B.: does not have demandZeroMetrics() semantics void zeroMetrics(uint mBegId, uint mEndId) { for (uint i = mBegId; i < mEndId; ++i) { metric(i) = 0.0; } } void clearMetrics() { delete m_metrics; m_metrics = NULL; } // -------------------------------------------------------- // // -------------------------------------------------------- // ensureMetricsSize: ensures a vector of the requested size exists void ensureMetricsSize(size_t size) const { if (!m_metrics) { m_metrics = new MetricVec(size, 0.0 /*value*/); } else if (size > m_metrics->size()) { m_metrics->resize(size, 0.0 /*value*/); // inserts at end } } void insertMetricsBefore(size_t numMetrics) { if (numMetrics > 0 && !m_metrics) { m_metrics = new MetricVec(); } for (uint i = 0; i < numMetrics; ++i) { m_metrics->insert(m_metrics->begin(), 0.0); } } uint numMetrics() const { return (m_metrics) ? m_metrics->size() : 0; } // -------------------------------------------------------- // // -------------------------------------------------------- std::string toStringMetrics(int oFlags = 0, const char* pfx = "") const; // [mBegId, mEndId) std::ostream& writeMetricsXML(std::ostream& os, uint mBegId = Metric::IData::npos, uint mEndId = Metric::IData::npos, int oFlags = 0, const char* pfx = "") const; std::ostream& dumpMetrics(std::ostream& os = std::cerr, int oFlags = 0, const char* pfx = "") const; void ddumpMetrics() const; private: mutable MetricVec* m_metrics; // 'mutable' for ensureMetricsSize() }; //*************************************************************************** } // namespace Metric } // namespace Prof #endif /* prof_Prof_Metric_IData_hpp */
[ "proy@email.wm.edu" ]
proy@email.wm.edu
ba819bb7a3da24a566fa32f80d913028d1612f61
4384c42810ec6e9091b06578a4377344b0e33daf
/ROBOTIS-THORMANG-MPC/thormang3_manager/src/thormang3_manager.cpp
d29fc2aa190865f63cdbac7faf7a3dca6f7ec1e0
[ "BSD-3-Clause" ]
permissive
khaleddallah/ExoBrainTon
a6a0812aaa6260729f46f78933644a6b35eaf751
4ce85fb42a5f696cffacb3d0400dea04616f42e1
refs/heads/master
2020-03-31T17:09:49.988586
2018-10-15T08:55:27
2018-10-15T08:55:27
152,409,668
0
0
null
null
null
null
UTF-8
C++
false
false
4,550
cpp
/******************************************************************************* * Copyright (c) 2016, ROBOTIS CO., LTD. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of ROBOTIS nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *******************************************************************************/ /* * thormang3_manager.cpp * * Created on: 2016. 1. 21. * Author: zerom */ #include "robotis_controller/robotis_controller.h" /* Sensor Module Header */ #include "thormang3_feet_ft_module/feet_force_torque_sensor_module.h" /* Motion Module Header */ #include "thormang3_base_module/base_module.h" #include "thormang3_action_module/action_module.h" #include "thormang3_head_control_module/head_control_module.h" #include "thormang3_manipulation_module/manipulation_module.h" #include "thormang3_walking_module/walking_module.h" #include "thormang3_gripper_module/gripper_module.h" #include "changer/changer.h" using namespace thormang3; int main(int argc, char **argv) { ros::init(argc, argv, "THORMANG3_Manager"); ros::NodeHandle nh; ROS_INFO("manager->init"); robotis_framework::RobotisController *controller = robotis_framework::RobotisController::getInstance(); /* Load ROS Parameter */ std::string offset_file = nh.param<std::string>("offset_file_path", ""); std::string robot_file = nh.param<std::string>("robot_file_path", ""); std::string init_file = nh.param<std::string>("init_file_path", ""); /* gazebo simulation */ controller->gazebo_mode_ = nh.param<bool>("gazebo", false); if(controller->gazebo_mode_ == true) { ROS_WARN("SET TO GAZEBO MODE!"); std::string robot_name = nh.param<std::string>("gazebo_robot_name", ""); if(robot_name != "") controller->gazebo_robot_name_ = robot_name; } if(robot_file == "") { ROS_ERROR("NO robot file path in the ROS parameters."); return -1; } if(controller->initialize(robot_file, init_file) == false) { ROS_ERROR("ROBOTIS Controller Initialize Fail!"); return -1; } if(offset_file != "") controller->loadOffset(offset_file); sleep(1); /* Add Sensor Module */ controller->addSensorModule((robotis_framework::SensorModule*)FeetForceTorqueSensor::getInstance()); /* Add Motion Module */ controller->addMotionModule((robotis_framework::MotionModule*)BaseModule::getInstance()); controller->addMotionModule((robotis_framework::MotionModule*)ActionModule::getInstance()); controller->addMotionModule((robotis_framework::MotionModule*)ManipulationModule::getInstance()); controller->addMotionModule((robotis_framework::MotionModule*)GripperModule::getInstance()); controller->addMotionModule((robotis_framework::MotionModule*)HeadControlModule::getInstance()); controller->addMotionModule((robotis_framework::MotionModule*)OnlineWalkingModule::getInstance()); controller->addMotionModule((robotis_framework::MotionModule*)changerM::getInstance()); controller->startTimer(); while(ros::ok()) { usleep(1000*1000); } return 0; }
[ "qs@COR" ]
qs@COR
f22817fbe8fbea945aa74d9ce79bc8a76d4b8504
b4ebcf9a7e4753221b4393ee40f3e3d82f6137ea
/final.ino
43cf1b087ec7826df4b5c8df1993bb76cf36b092
[]
no_license
unstoppable14/ourcode14
a2fe5e979ffbd392f4ed668fecbb351bc509a12c
0bf127d60f41bbda4231bbedf271c11436a97325
refs/heads/master
2020-04-27T00:40:44.510803
2014-04-29T22:11:28
2014-04-29T22:11:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,251
ino
#include <HUBeeBMDWheel.h> HUBeeBMDWheel leftWheel; HUBeeBMDWheel rightWheel; unsigned long previousMillis = 0; long interval = 88000; int leftSpeed = 250, rightSpeed = 250; volatile int count = 0; int leftQeiAPin = 2; //external interrupt 0 int leftQeiBPin = 4; int rightQeiAPin = 3; //external interrupt 1 int rightQeiBPin = 7; volatile int leftQeiCounts = 0; volatile int rightQeiCounts = 0; int leftElapsedTime = 0, rightElapsedTime = 0; int leftOldElapsedTime = 0, rightOldElapsedTime = 0; int serialTimer = 0; int travel = 0; void setup() { pinMode(leftQeiAPin, INPUT_PULLUP); pinMode(rightQeiAPin, INPUT_PULLUP); pinMode(leftQeiBPin, INPUT_PULLUP); pinMode(rightQeiBPin, INPUT_PULLUP); leftWheel.setupPins(8, 11, 9); //setup using pins 12 and 2 for direction control, and 3 for PWM speed control rightWheel.setupPins(12, 13, 10); //setup using pins 13 and 4 for direction control, and 11 for PWM speed control leftWheel.setDirectionMode(0); //Set the direction mode to 1 rightWheel.setDirectionMode(1); //set the direction mode to 1 /* The counter for each wheel (leftQeiCounts and rightQeiCounts) will go up when the motor direction is set to 1 and motor power is positive It will go down when motor power is negative The leftElapsedTime and rightElapsedTime will give you an indication of speed - The bigger the number the lower the speed BE WARNED - The speed variables will give innacurate readings at low speed because the values get too big */ attachInterrupt(0, QEI_LeftWheel, CHANGE); attachInterrupt(1, QEI_RightWheel, CHANGE); Serial.begin(9600); //start the wheels } void loop() { //do this forever - spin the wheels and reverse direction when the count gets to + or - 64 // There are 64 'ticks' per revolution unsigned long currentMillis = millis(); if (currentMillis <interval) { goforward(800); gobackward(400); goleft(80); goforward(300); } } void QEI_LeftWheel() { //work out the elapsed time since the last interrupt leftElapsedTime = micros() - leftOldElapsedTime; leftOldElapsedTime = micros(); //ChA has changed state //Check the state of ChA if (digitalRead(leftQeiAPin)) { //pin has gone high //check chanel B if (digitalRead(leftQeiBPin)) { //both are high leftQeiCounts++; return; } //ChB is low leftQeiCounts--; return; } //if you get here then ChA has gone low, check ChB if (digitalRead(leftQeiBPin)) { //ChB is high leftQeiCounts--; return; } //if you get here then A has gone low and B is low leftQeiCounts++; } //Left Wheel pin interrupt function void QEI_RightWheel() { if (digitalRead(rightQeiAPin)) { //pin has gone high //check chanel B if (digitalRead(rightQeiBPin)) { //both are high rightQeiCounts--; return; } //ChB is low rightQeiCounts++; return; } if (digitalRead(rightQeiBPin)) { rightQeiCounts++; return; } rightQeiCounts--; } void goforward (int distance_mm) { int start_left_counts = leftQeiCounts; int start_right_counts = rightQeiCounts; leftWheel.setMotorPower(leftSpeed); rightWheel.setMotorPower(rightSpeed); int distance_ticks = (int) distance_mm * 64.0 / 188.5; while ((leftQeiCounts < (distance_ticks + start_left_counts)) && (rightQeiCounts < (distance_ticks + start_right_counts))) { int right_sensor= analogRead(A0); if (A0 > 550){ obstructionDetected(); leftWheel.setMotorPower(leftSpeed); rightWheel.setMotorPower(-rightSpeed); } } leftWheel.stopMotor(); rightWheel.stopMotor(); } void gobackward(int distance_mm) { int start_left_counts = leftQeiCounts; int start_right_counts = rightQeiCounts; leftWheel.setMotorPower(-leftSpeed); rightWheel.setMotorPower(-rightSpeed); int distance_ticks = (int) distance_mm * 64.0 / 188.5; while ((leftQeiCounts > (start_left_counts - distance_ticks)) && (rightQeiCounts > (start_right_counts - distance_ticks))) { } leftWheel.stopMotor(); rightWheel.stopMotor(); } void goright(int angle_degrees) { int start_left_counts = leftQeiCounts; int start_right_counts = rightQeiCounts; leftWheel.setMotorPower(leftSpeed); rightWheel.setMotorPower(-rightSpeed); int distance_mm = 3.14 * 115 * angle_degrees / 360 ; int distance_ticks = (int) distance_mm * 64.0 / 188.5; while ((leftQeiCounts > (start_left_counts - distance_ticks)) && (rightQeiCounts < (distance_ticks + start_right_counts))) { } leftWheel.stopMotor(); rightWheel.stopMotor(); } void goleft(int angle_degrees) { int start_left_counts = leftQeiCounts; int start_right_counts = rightQeiCounts; leftWheel.setMotorPower(-leftSpeed); rightWheel.setMotorPower(rightSpeed); int distance_mm = 3.14 * 115 * angle_degrees / 360 ; int distance_ticks = (int) distance_mm * 64.0 / 188.5; while ((leftQeiCounts < (start_left_counts + distance_ticks)) && (rightQeiCounts > (start_right_counts- distance_ticks ))) { } leftWheel.stopMotor(); rightWheel.stopMotor(); } void obstructionDetected(){ leftWheel.stopMotor(); rightWheel.stopMotor(); //wait for obstruction to move while(analogRead(A0>140)) { } }
[ "karimala10@hotmail.fr" ]
karimala10@hotmail.fr
1975aebfc166e6e739d700fc2c0bc6fc4c407ae7
fdeca1313be23ba40a255e0a46856d427987a8ca
/external/boost_1_54_0_arm/boost/date_time/local_time/local_date_time.hpp
214cf7c666cbc295b8691e5ae7136ab45af83f73
[ "BSL-1.0" ]
permissive
petiaccja/raspberry-rc
ee42f0bf265bd4e1ab6fde4a31d015dcdfdea155
aa0f1cb18be2f6aad6fd5799ab79904fc64a4b24
refs/heads/master
2016-09-06T00:09:10.647868
2015-01-28T22:21:34
2015-01-28T22:21:34
23,356,436
0
0
null
null
null
null
UTF-8
C++
false
false
19,830
hpp
#ifndef LOCAL_TIME_LOCAL_DATE_TIME_HPP__ #define LOCAL_TIME_LOCAL_DATE_TIME_HPP__ /* Copyright (c) 2003-2005 CrystalClear Software, Inc. * Subject to the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) * Author: Jeff Garland, Bart Garst * $Date: 2012-08-15 19:06:56 +0200 (sze, 15 aug 2012) $ */ #include <string> #include <iomanip> #include <sstream> #include <stdexcept> #include <boost/shared_ptr.hpp> #include <boost/throw_exception.hpp> #include <boost/date_time/time.hpp> #include <boost/date_time/posix_time/posix_time.hpp> //todo remove? #include <boost/date_time/dst_rules.hpp> #include <boost/date_time/time_zone_base.hpp> #include <boost/date_time/special_defs.hpp> #include <boost/date_time/time_resolution_traits.hpp> // absolute_value namespace boost { namespace local_time { //! simple exception for reporting when STD or DST cannot be determined struct ambiguous_result : public std::logic_error { ambiguous_result (std::string const& msg = std::string()) : std::logic_error(std::string("Daylight Savings Results are ambiguous: " + msg)) {} }; //! simple exception for when time label given cannot exist struct time_label_invalid : public std::logic_error { time_label_invalid (std::string const& msg = std::string()) : std::logic_error(std::string("Time label given is invalid: " + msg)) {} }; struct dst_not_valid: public std::logic_error { dst_not_valid(std::string const& msg = std::string()) : std::logic_error(std::string("is_dst flag does not match resulting dst for time label given: " + msg)) {} }; //TODO: I think these should be in local_date_time_base and not // necessarily brought into the namespace using date_time::time_is_dst_result; using date_time::is_in_dst; using date_time::is_not_in_dst; using date_time::ambiguous; using date_time::invalid_time_label; //! Representation of "wall-clock" time in a particular time zone /*! Representation of "wall-clock" time in a particular time zone * Local_date_time_base holds a time value (date and time offset from 00:00) * along with a time zone. The time value is stored as UTC and conversions * to wall clock time are made as needed. This approach allows for * operations between wall-clock times in different time zones, and * daylight savings time considerations, to be made. Time zones are * required to be in the form of a boost::shared_ptr<time_zone_base>. */ template<class utc_time_=posix_time::ptime, class tz_type=date_time::time_zone_base<utc_time_,char> > class local_date_time_base : public date_time::base_time<utc_time_, boost::posix_time::posix_time_system> { public: typedef utc_time_ utc_time_type; typedef typename utc_time_type::time_duration_type time_duration_type; typedef typename utc_time_type::date_type date_type; typedef typename date_type::duration_type date_duration_type; typedef typename utc_time_type::time_system_type time_system_type; /*! This constructor interprets the passed time as a UTC time. * So, for example, if the passed timezone is UTC-5 then the * time will be adjusted back 5 hours. The time zone allows for * automatic calculation of whether the particular time is adjusted for * daylight savings, etc. * If the time zone shared pointer is null then time stays unadjusted. *@param t A UTC time *@param tz Timezone for to adjust the UTC time to. */ local_date_time_base(utc_time_type t, boost::shared_ptr<tz_type> tz) : date_time::base_time<utc_time_type, time_system_type>(t), zone_(tz) { // param was already utc so nothing more to do } /*! This constructs a local time -- the passed time information * understood to be in the passed tz. The DST flag must be passed * to indicate whether the time is in daylight savings or not. * @throws -- time_label_invalid if the time passed does not exist in * the given locale. The non-existent case occurs typically * during the shift-back from daylight savings time. When * the clock is shifted forward a range of times * (2 am to 3 am in the US) is skipped and hence is invalid. * @throws -- dst_not_valid if the DST flag is passed for a period * where DST is not active. */ local_date_time_base(date_type d, time_duration_type td, boost::shared_ptr<tz_type> tz, bool dst_flag) : //necessary for constr_adj() date_time::base_time<utc_time_type,time_system_type>(construction_adjustment(utc_time_type(d, td), tz, dst_flag)), zone_(tz) { if(tz != boost::shared_ptr<tz_type>() && tz->has_dst()){ // d & td are already local so we use them time_is_dst_result result = check_dst(d, td, tz); bool in_dst = (result == is_in_dst); // less processing than is_dst() // ambig occurs at end, invalid at start if(result == invalid_time_label){ // Ex: 2:15am local on trans-in day in nyc, dst_flag irrelevant std::ostringstream ss; ss << "time given: " << d << ' ' << td; boost::throw_exception(time_label_invalid(ss.str())); } else if(result != ambiguous && in_dst != dst_flag){ // is dst_flag accurate? // Ex: false flag in NYC in June std::ostringstream ss; ss.setf(std::ios_base::boolalpha); ss << "flag given: dst=" << dst_flag << ", dst calculated: dst=" << in_dst; boost::throw_exception(dst_not_valid(ss.str())); } // everything checks out and conversion to utc already done } } //TODO maybe not the right set...Ignore the last 2 for now... enum DST_CALC_OPTIONS { EXCEPTION_ON_ERROR, NOT_DATE_TIME_ON_ERROR }; //ASSUME_DST_ON_ERROR, ASSUME_NOT_DST_ON_ERROR }; /*! This constructs a local time -- the passed time information * understood to be in the passed tz. The DST flag is calculated * according to the specified rule. */ local_date_time_base(date_type d, time_duration_type td, boost::shared_ptr<tz_type> tz, DST_CALC_OPTIONS calc_option) : // dummy value - time_ is set in constructor code date_time::base_time<utc_time_type,time_system_type>(utc_time_type(d,td)), zone_(tz) { time_is_dst_result result = check_dst(d, td, tz); if(result == ambiguous) { if(calc_option == EXCEPTION_ON_ERROR){ std::ostringstream ss; ss << "time given: " << d << ' ' << td; boost::throw_exception(ambiguous_result(ss.str())); } else{ // NADT on error this->time_ = posix_time::posix_time_system::get_time_rep(date_type(date_time::not_a_date_time), time_duration_type(date_time::not_a_date_time)); } } else if(result == invalid_time_label){ if(calc_option == EXCEPTION_ON_ERROR){ std::ostringstream ss; ss << "time given: " << d << ' ' << td; boost::throw_exception(time_label_invalid(ss.str())); } else{ // NADT on error this->time_ = posix_time::posix_time_system::get_time_rep(date_type(date_time::not_a_date_time), time_duration_type(date_time::not_a_date_time)); } } else if(result == is_in_dst){ utc_time_type t = construction_adjustment(utc_time_type(d, td), tz, true); this->time_ = posix_time::posix_time_system::get_time_rep(t.date(), t.time_of_day()); } else{ utc_time_type t = construction_adjustment(utc_time_type(d, td), tz, false); this->time_ = posix_time::posix_time_system::get_time_rep(t.date(), t.time_of_day()); } } //! Determines if given time label is in daylight savings for given zone /*! Determines if given time label is in daylight savings for given zone. * Takes a date and time_duration representing a local time, along * with time zone, and returns a time_is_dst_result object as result. */ static time_is_dst_result check_dst(date_type d, time_duration_type td, boost::shared_ptr<tz_type> tz) { if(tz != boost::shared_ptr<tz_type>() && tz->has_dst()) { typedef typename date_time::dst_calculator<date_type, time_duration_type> dst_calculator; return dst_calculator::local_is_dst( d, td, tz->dst_local_start_time(d.year()).date(), tz->dst_local_start_time(d.year()).time_of_day(), tz->dst_local_end_time(d.year()).date(), tz->dst_local_end_time(d.year()).time_of_day(), tz->dst_offset() ); } else{ return is_not_in_dst; } } //! Simple destructor, releases time zone if last referrer ~local_date_time_base() {} //! Copy constructor local_date_time_base(const local_date_time_base& rhs) : date_time::base_time<utc_time_type, time_system_type>(rhs), zone_(rhs.zone_) {} //! Special values constructor explicit local_date_time_base(const boost::date_time::special_values sv, boost::shared_ptr<tz_type> tz = boost::shared_ptr<tz_type>()) : date_time::base_time<utc_time_type, time_system_type>(utc_time_type(sv)), zone_(tz) {} //! returns time zone associated with calling instance boost::shared_ptr<tz_type> zone() const { return zone_; } //! returns false is time_zone is NULL and if time value is a special_value bool is_dst() const { if(zone_ != boost::shared_ptr<tz_type>() && zone_->has_dst() && !this->is_special()) { // check_dst takes a local time, *this is utc utc_time_type lt(this->time_); lt += zone_->base_utc_offset(); // dst_offset only needs to be considered with ambiguous time labels // make that adjustment there switch(check_dst(lt.date(), lt.time_of_day(), zone_)){ case is_not_in_dst: return false; case is_in_dst: return true; case ambiguous: if(lt + zone_->dst_offset() < zone_->dst_local_end_time(lt.date().year())) { return true; } break; case invalid_time_label: if(lt >= zone_->dst_local_start_time(lt.date().year())) { return true; } break; } } return false; } //! Returns object's time value as a utc representation utc_time_type utc_time() const { return utc_time_type(this->time_); } //! Returns object's time value as a local representation utc_time_type local_time() const { if(zone_ != boost::shared_ptr<tz_type>()){ utc_time_type lt = this->utc_time() + zone_->base_utc_offset(); if (is_dst()) { lt += zone_->dst_offset(); } return lt; } return utc_time_type(this->time_); } //! Returns string in the form "2003-Aug-20 05:00:00 EDT" /*! Returns string in the form "2003-Aug-20 05:00:00 EDT". If * time_zone is NULL the time zone abbreviation will be "UTC". The time * zone abbrev will not be included if calling object is a special_value*/ std::string to_string() const { //TODO is this a temporary function ??? std::ostringstream ss; if(this->is_special()){ ss << utc_time(); return ss.str(); } if(zone_ == boost::shared_ptr<tz_type>()) { ss << utc_time() << " UTC"; return ss.str(); } bool is_dst_ = is_dst(); utc_time_type lt = this->utc_time() + zone_->base_utc_offset(); if (is_dst_) { lt += zone_->dst_offset(); } ss << local_time() << " "; if (is_dst()) { ss << zone_->dst_zone_abbrev(); } else { ss << zone_->std_zone_abbrev(); } return ss.str(); } /*! returns a local_date_time_base in the given time zone with the * optional time_duration added. */ local_date_time_base local_time_in(boost::shared_ptr<tz_type> new_tz, time_duration_type td=time_duration_type(0,0,0)) const { return local_date_time_base(utc_time_type(this->time_) + td, new_tz); } //! Returns name of associated time zone or "Coordinated Universal Time". /*! Optional bool parameter will return time zone as an offset * (ie "+07:00" extended iso format). Empty string is returned for * classes that do not use a time_zone */ std::string zone_name(bool as_offset=false) const { if(zone_ == boost::shared_ptr<tz_type>()) { if(as_offset) { return std::string("Z"); } else { return std::string("Coordinated Universal Time"); } } if (is_dst()) { if(as_offset) { time_duration_type td = zone_->base_utc_offset(); td += zone_->dst_offset(); return zone_as_offset(td, ":"); } else { return zone_->dst_zone_name(); } } else { if(as_offset) { time_duration_type td = zone_->base_utc_offset(); return zone_as_offset(td, ":"); } else { return zone_->std_zone_name(); } } } //! Returns abbreviation of associated time zone or "UTC". /*! Optional bool parameter will return time zone as an offset * (ie "+0700" iso format). Empty string is returned for classes * that do not use a time_zone */ std::string zone_abbrev(bool as_offset=false) const { if(zone_ == boost::shared_ptr<tz_type>()) { if(as_offset) { return std::string("Z"); } else { return std::string("UTC"); } } if (is_dst()) { if(as_offset) { time_duration_type td = zone_->base_utc_offset(); td += zone_->dst_offset(); return zone_as_offset(td, ""); } else { return zone_->dst_zone_abbrev(); } } else { if(as_offset) { time_duration_type td = zone_->base_utc_offset(); return zone_as_offset(td, ""); } else { return zone_->std_zone_abbrev(); } } } //! returns a posix_time_zone string for the associated time_zone. If no time_zone, "UTC+00" is returned. std::string zone_as_posix_string() const { if(zone_ == shared_ptr<tz_type>()) { return std::string("UTC+00"); } return zone_->to_posix_string(); } //! Equality comparison operator /*bool operator==(const date_time::base_time<boost::posix_time::ptime,boost::posix_time::posix_time_system>& rhs) const { // fails due to rhs.time_ being protected return date_time::base_time<boost::posix_time::ptime,boost::posix_time::posix_time_system>::operator==(rhs); //return this->time_ == rhs.time_; }*/ //! Equality comparison operator bool operator==(const local_date_time_base& rhs) const { return time_system_type::is_equal(this->time_, rhs.time_); } //! Non-Equality comparison operator bool operator!=(const local_date_time_base& rhs) const { return !(*this == rhs); } //! Less than comparison operator bool operator<(const local_date_time_base& rhs) const { return time_system_type::is_less(this->time_, rhs.time_); } //! Less than or equal to comparison operator bool operator<=(const local_date_time_base& rhs) const { return (*this < rhs || *this == rhs); } //! Greater than comparison operator bool operator>(const local_date_time_base& rhs) const { return !(*this <= rhs); } //! Greater than or equal to comparison operator bool operator>=(const local_date_time_base& rhs) const { return (*this > rhs || *this == rhs); } //! Local_date_time + date_duration local_date_time_base operator+(const date_duration_type& dd) const { return local_date_time_base(time_system_type::add_days(this->time_,dd), zone_); } //! Local_date_time += date_duration local_date_time_base operator+=(const date_duration_type& dd) { this->time_ = time_system_type::add_days(this->time_,dd); return *this; } //! Local_date_time - date_duration local_date_time_base operator-(const date_duration_type& dd) const { return local_date_time_base(time_system_type::subtract_days(this->time_,dd), zone_); } //! Local_date_time -= date_duration local_date_time_base operator-=(const date_duration_type& dd) { this->time_ = time_system_type::subtract_days(this->time_,dd); return *this; } //! Local_date_time + time_duration local_date_time_base operator+(const time_duration_type& td) const { return local_date_time_base(time_system_type::add_time_duration(this->time_,td), zone_); } //! Local_date_time += time_duration local_date_time_base operator+=(const time_duration_type& td) { this->time_ = time_system_type::add_time_duration(this->time_,td); return *this; } //! Local_date_time - time_duration local_date_time_base operator-(const time_duration_type& td) const { return local_date_time_base(time_system_type::subtract_time_duration(this->time_,td), zone_); } //! Local_date_time -= time_duration local_date_time_base operator-=(const time_duration_type& td) { this->time_ = time_system_type::subtract_time_duration(this->time_,td); return *this; } //! local_date_time -= local_date_time --> time_duration_type time_duration_type operator-(const local_date_time_base& rhs) const { return utc_time_type(this->time_) - utc_time_type(rhs.time_); } private: boost::shared_ptr<tz_type> zone_; //bool is_dst_; /*! Adjust the passed in time to UTC? */ utc_time_type construction_adjustment(utc_time_type t, boost::shared_ptr<tz_type> z, bool dst_flag) { if(z != boost::shared_ptr<tz_type>()) { if(dst_flag && z->has_dst()) { t -= z->dst_offset(); } // else no adjust t -= z->base_utc_offset(); } return t; } /*! Simple formatting code -- todo remove this? */ std::string zone_as_offset(const time_duration_type& td, const std::string& separator) const { std::ostringstream ss; if(td.is_negative()) { // a negative duration is represented as "-[h]h:mm" // we require two digits for the hour. A positive duration // with the %H flag will always give two digits ss << "-"; } else { ss << "+"; } ss << std::setw(2) << std::setfill('0') << date_time::absolute_value(td.hours()) << separator << std::setw(2) << std::setfill('0') << date_time::absolute_value(td.minutes()); return ss.str(); } }; //!Use the default parameters to define local_date_time typedef local_date_time_base<> local_date_time; } } #endif
[ "kardospeter1994@hotmail.com" ]
kardospeter1994@hotmail.com
8d4dcd5b1d4d405586d00aed24c99878efd35d74
65553f43ab9632154321269862acc5467aeabb02
/GravityFalls/Address.cpp
842d724613ef1965c712ffc2ecdd0e506d8f8365
[]
no_license
adratkovskiy/GravityFalls
fd427b8303419820b0254de91846a3c6b972bd70
1f4645676dc9f6db5955605b6e5efd70208cb5db
refs/heads/master
2020-07-02T06:31:38.351697
2019-10-04T14:16:59
2019-10-04T14:16:59
201,440,475
0
0
null
null
null
null
UTF-8
C++
false
false
806
cpp
#include "Address.h" Address::Address() { address = 0; port = 0; } Address::Address(unsigned char a, unsigned char b, unsigned char c, unsigned char d, unsigned short port) { this->address = (a << 24) | (b << 16) | (c << 8) | d; this->port = port; } Address::Address(unsigned int address, unsigned short port) { this->address = address; this->port = port; } unsigned int Address::GetAddress() const { return address; } unsigned char Address::GetA() const { return (unsigned char)(address >> 24); } unsigned char Address::GetB() const { return (unsigned char)(address >> 16); } unsigned char Address::GetC() const { return (unsigned char)(address >> 8); } unsigned char Address::GetD() const { return (unsigned char)(address); } unsigned short Address::GetPort() const { return port; }
[ "79095647794@ya.ru" ]
79095647794@ya.ru
297e820057a5f05a80d5eeadf2c0e2debecb7406
0002ff30413d89f321e2a3ac49bcddcb7bf05526
/bluetoothleinterface.cpp
234732229031a6b3247276a98e2ce0fd32f81bc8
[]
no_license
piggz/bletest
e52da50fcc268e53740072b3765dfc50ccc9000b
88069381b6ee403fd2f91b753888c3e841eb2a36
refs/heads/master
2020-03-07T18:58:43.452456
2018-04-02T12:37:08
2018-04-02T12:37:08
127,658,384
6
0
null
null
null
null
UTF-8
C++
false
false
11,308
cpp
#include "bluetoothleinterface.h" #include <QLowEnergyCharacteristic> #include "qaesencryption.h" BluetoothLEInterface::BluetoothLEInterface() { m_deviceDiscoveryAgent = new QBluetoothDeviceDiscoveryAgent(this); m_deviceDiscoveryAgent->setLowEnergyDiscoveryTimeout(60000); connect(m_deviceDiscoveryAgent, &QBluetoothDeviceDiscoveryAgent::deviceDiscovered, this, &BluetoothLEInterface::addDevice); connect(m_deviceDiscoveryAgent, static_cast<void (QBluetoothDeviceDiscoveryAgent::*)(QBluetoothDeviceDiscoveryAgent::Error)>(&QBluetoothDeviceDiscoveryAgent::error), this, &BluetoothLEInterface::scanError); connect(m_deviceDiscoveryAgent, &QBluetoothDeviceDiscoveryAgent::finished, this, &BluetoothLEInterface::scanFinished); connect(m_deviceDiscoveryAgent, &QBluetoothDeviceDiscoveryAgent::canceled, this, &BluetoothLEInterface::scanFinished); } void BluetoothLEInterface::startScan() { m_deviceDiscoveryAgent->start(QBluetoothDeviceDiscoveryAgent::LowEnergyMethod); } void BluetoothLEInterface::scanError() { qDebug() << "Scan Error"; } void BluetoothLEInterface::scanFinished() { qDebug() << "Scan Finished"; } void BluetoothLEInterface::connectToDevice(const QString &address) { } void BluetoothLEInterface::addDevice(const QBluetoothDeviceInfo &device) { qDebug() << "Found" << device.address() << device.name(); // If device is LowEnergy-device, add it to the list if (device.coreConfigurations() & QBluetoothDeviceInfo::LowEnergyCoreConfiguration) { m_devices.append(device); qDebug() << "Low Energy device found. Scanning more..."; if (device.name().toLower().contains("amazfit")) { qDebug() << "Found an amazfit, scanning services"; m_control = new QLowEnergyController(device, this); connect(m_control, &QLowEnergyController::serviceDiscovered, this, &BluetoothLEInterface::serviceDiscovered); connect(m_control, &QLowEnergyController::discoveryFinished, this, [this] { qDebug() << "Service scan done."; }); connect(m_control, static_cast<void (QLowEnergyController::*)(QLowEnergyController::Error)>(&QLowEnergyController::error), this, [this](QLowEnergyController::Error error) { Q_UNUSED(error); qDebug() << "Cannot connect to remote device."; }); connect(m_control, &QLowEnergyController::connected, this, [this]() { qDebug() << "Controller connected. Search services..."; m_control->discoverServices(); }); connect(m_control, &QLowEnergyController::disconnected, this, [this]() { qDebug() << "LowEnergy controller disconnected"; }); // Connect m_control->connectToDevice(); m_control->discoverServices(); } } } void BluetoothLEInterface::serviceDiscovered(const QBluetoothUuid &gatt) { qDebug() << "Service discovered:" << gatt.toString(); if (gatt == QBluetoothUuid(UUID_SERVICE_BIP_AUTH)) { qDebug() << "Creating service object"; m_service = m_control->createServiceObject(QBluetoothUuid(UUID_SERVICE_BIP_AUTH), this); qDebug() << m_service->serviceName(); if (m_service) { connect(m_service, &QLowEnergyService::stateChanged, this, &BluetoothLEInterface::serviceStateChanged); connect(m_service, &QLowEnergyService::characteristicChanged, this, &BluetoothLEInterface::authCharacteristicChanged); //connect(m_service, &QLowEnergyService::descriptorWritten, this, &DeviceHandler::confirmedDescriptorWrite); m_service->discoverDetails(); } else { qDebug() << "Service not found"; } } } void BluetoothLEInterface::characteristicChanged(const QLowEnergyCharacteristic &characteristic, const QByteArray &newValue) { qDebug() << "Changed:" << characteristic.uuid() << "(" << characteristic.name() << "):" << newValue; } void BluetoothLEInterface::serviceStateChanged(QLowEnergyService::ServiceState s) { switch (s) { case QLowEnergyService::DiscoveringServices: qDebug() << "xDiscovering services..."; break; case QLowEnergyService::ServiceDiscovered: { qDebug() << "xService discovered."; Q_FOREACH(QLowEnergyCharacteristic c, m_service->characteristics()) { qDebug() << "Characteristic:" << c.uuid() << c.name(); } qDebug() << "Getting the auth characteristic"; m_authChar = m_service->characteristic(QBluetoothUuid(UUID_CHARACTERISTEC_AUTH)); if (!m_authChar.isValid()) { qDebug() << "Auth service not found."; break; } qDebug() << "Registering for notifications on the auth service"; m_notificationDesc = m_authChar.descriptor(QBluetoothUuid::ClientCharacteristicConfiguration); if (m_notificationDesc.isValid()) m_service->writeDescriptor(m_notificationDesc, QByteArray::fromHex("0100")); qDebug() << "Writing special value to trigger pair dialog"; m_service->writeCharacteristic(m_authChar, QByteArray(&AUTH_SEND_KEY, 1) + QByteArray(&AUTH_BYTE, 1) + AUTH_SECRET_KEY); break; } default: //nothing for now break; } } void BluetoothLEInterface::authCharacteristicChanged(const QLowEnergyCharacteristic &c, const QByteArray &value) { // ignore any other characteristic change -> shouldn't really happen though if (c.uuid() != QBluetoothUuid(UUID_CHARACTERISTEC_AUTH)) { qDebug() << "Expecting auth UUID but got" << c.uuid(); return; } qDebug() << "Received data:" << value.size() << value.toHex(); if (value.size() < 3) { return; } if (value[0] == AUTH_RESPONSE && value[1] == AUTH_SEND_KEY && value[2] == AUTH_SUCCESS) { qDebug() << "Received initial auth success, requesting random auth number"; m_service->writeCharacteristic(m_authChar, QByteArray(&AUTH_REQUEST_RANDOM_AUTH_NUMBER, 1) + QByteArray(&AUTH_BYTE, 1)); } else if (value[0] == AUTH_RESPONSE && value[1] == AUTH_REQUEST_RANDOM_AUTH_NUMBER && value[2] == AUTH_SUCCESS) { qDebug() << "Received random auth number, sending encrypted auth number"; m_service->writeCharacteristic(m_authChar, QByteArray(&AUTH_SEND_ENCRYPTED_AUTH_NUMBER, 1) + QByteArray(&AUTH_BYTE, 1) + handleAesAuth(value.mid(3, 17), AUTH_SECRET_KEY)); } else if (value[0] == AUTH_RESPONSE && value[1] == AUTH_SEND_ENCRYPTED_AUTH_NUMBER && value[2] == AUTH_SUCCESS) { qDebug() << "Authenticated, go read the device information!"; } else { qDebug() << "Unexpected data"; } } QByteArray BluetoothLEInterface::handleAesAuth(QByteArray data, QByteArray secretKey) { return QAESEncryption::Crypt(QAESEncryption::AES_128, QAESEncryption::ECB, data, secretKey, QByteArray(), QAESEncryption::ZERO); } void BluetoothLEInterface::requestDeviceInfo() { m_infoService = m_control->createServiceObject(QBluetoothUuid::DeviceInformation, this); if (m_infoService) { qDebug() << m_infoService->serviceName(); connect(m_infoService, &QLowEnergyService::stateChanged, this, &BluetoothLEInterface::infoServiceStateChanged); connect(m_infoService, &QLowEnergyService::characteristicRead, this, &BluetoothLEInterface::characteristicRead); m_infoService->discoverDetails(); } else { qDebug() << "Service not found"; } } void BluetoothLEInterface::characteristicRead(const QLowEnergyCharacteristic &characteristic, const QByteArray &value) { qDebug() << "Read:" << characteristic.uuid() << "(" << characteristic.name() << "):" << value; } void BluetoothLEInterface::characteristicWritten(const QLowEnergyCharacteristic &characteristic, const QByteArray &value) { qDebug() << "Written:" << characteristic.uuid() << "(" << characteristic.name() << "):" << value; } void BluetoothLEInterface::infoServiceStateChanged(QLowEnergyService::ServiceState s) { switch (s) { case QLowEnergyService::DiscoveringServices: qDebug() << "Discovering services..."; break; case QLowEnergyService::ServiceDiscovered: { qDebug() << "Service discovered."; Q_FOREACH(QLowEnergyCharacteristic c, m_infoService->characteristics()) { qDebug() << "Characteristic:" << c.uuid() << c.name(); } QLowEnergyCharacteristic c = m_infoService->characteristic(QBluetoothUuid(UUID_CHARACTERISTIC_INFO_SERIAL_NO)); m_infoService->readCharacteristic(c); c = m_infoService->characteristic(QBluetoothUuid(UUID_CHARACTERISTIC_INFO_HARDWARE_REV)); m_infoService->readCharacteristic(c); c = m_infoService->characteristic(QBluetoothUuid(UUID_CHARACTERISTIC_INFO_SOFTWARE_REV)); m_infoService->readCharacteristic(c); c = m_infoService->characteristic(QBluetoothUuid(UUID_CHARACTERISTIC_INFO_SYSTEM_ID)); m_infoService->readCharacteristic(c); c = m_infoService->characteristic(QBluetoothUuid(UUID_CHARACTERISTIC_INFO_PNP_ID)); m_infoService->readCharacteristic(c); break; } default: //nothing for now break; } } void BluetoothLEInterface::alertServiceStateChanged(QLowEnergyService::ServiceState s) { switch (s) { case QLowEnergyService::DiscoveringServices: qDebug() << "Discovering services..."; break; case QLowEnergyService::ServiceDiscovered: { qDebug() << "Service discovered."; Q_FOREACH(QLowEnergyCharacteristic c, m_alertService->characteristics()) { qDebug() << "Characteristic:" << c.uuid() << c.name(); } QLowEnergyCharacteristic control = m_alertService->characteristic(QBluetoothUuid(UUID_CHARACTERISTIC_ALERT_CONTROL)); m_alertService->writeCharacteristic(control, QByteArray::fromHex("0000")); QLowEnergyCharacteristic c = m_alertService->characteristic(QBluetoothUuid(UUID_CHARACTERISTIC_NEW_ALERT)); m_alertService->writeCharacteristic(c, QByteArray::fromHex("01") + QByteArray::fromHex("01") + "TEST\nThis is a long message hope it displays ok"); break; } default: //nothing for now break; } } void BluetoothLEInterface::sendMessage() { m_alertService = m_control->createServiceObject(QBluetoothUuid(UUID_SERVICE_ALERT_NOTIFICATION), this); if (m_alertService) { qDebug() << m_alertService->serviceName(); connect(m_alertService, &QLowEnergyService::stateChanged, this, &BluetoothLEInterface::alertServiceStateChanged); connect(m_alertService, &QLowEnergyService::characteristicRead, this, &BluetoothLEInterface::characteristicRead); connect(m_alertService, &QLowEnergyService::characteristicWritten, this, &BluetoothLEInterface::characteristicWritten); //connect(m_alertService, &QLowEnergyService::error, this, &BluetoothLEInterface::error); m_alertService->discoverDetails(); } else { qDebug() << "Service not found"; } } void BluetoothLEInterface::error(QLowEnergyService::ServiceError newError) { qDebug() << "Error" << newError; }
[ "adam@piggz.co.uk" ]
adam@piggz.co.uk
f488e2a2c13c1275ac652cee242eb58d528015b2
14840363a4541be3a2393e6973559bb7dbb4b7c7
/controller/src/vnsw/agent/oper/vn.h
10fb554255ed71e2ee0c1f33d13aebfa01940681
[]
no_license
forsakening/test-ipv6
792abd067266483b5969637cca42d93617d53411
b7be1f268b50cf8b4c8ac33793df1f2c8c6d9737
refs/heads/master
2020-04-08T11:54:04.654282
2018-11-27T11:33:49
2018-11-27T11:33:49
159,324,883
0
1
null
2018-12-04T02:07:07
2018-11-27T11:28:57
C++
UTF-8
C++
false
false
16,824
h
/* * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved. */ #ifndef vnsw_agent_vn_hpp #define vnsw_agent_vn_hpp #include <cmn/agent_cmn.h> #include <cmn/agent.h> #include <oper/agent_types.h> #include <oper/oper_db.h> #include <oper/oper_dhcp_options.h> #include <oper/agent_route_walker.h> using namespace boost::uuids; using namespace std; class AgentRouteResync; namespace autogen { class NetworkIpam; class VirtualDns; struct IpamType; struct VirtualDnsType; } bool IsVRFServiceChainingInstance(const std::string &vn_name, const std::string &vrf_name); class VmInterface; struct VnIpam { IpAddress ip_prefix; uint32_t plen; IpAddress default_gw; // In case of TSN, we could have different addresses for default_gw & dns IpAddress dns_server; bool installed; // is the route to send pkts to host installed bool dhcp_enable; std::string ipam_name; OperDhcpOptions oper_dhcp_options; uint32_t alloc_unit; VnIpam(const std::string& ip, uint32_t len, const std::string& gw, const std::string& dns, bool dhcp, const std::string &name, const std::vector<autogen::DhcpOptionType> &dhcp_options, const std::vector<autogen::RouteType> &host_routes, uint32_t alloc); bool IsV4() const { return ip_prefix.is_v4(); } bool IsV6() const { return ip_prefix.is_v6(); } bool operator<(const VnIpam &rhs) const { if (ip_prefix != rhs.ip_prefix) return ip_prefix < rhs.ip_prefix; return (plen < rhs.plen); } Ip4Address GetBroadcastAddress() const; Ip4Address GetSubnetAddress() const; Ip6Address GetV6SubnetAddress() const; bool IsSubnetMember(const IpAddress &ip) const; }; struct VnStaticRoute { IpAddress ip_prefix; uint32_t plen; IpAddress gw; std::vector<std::string> route_target; CommunityList community; VnStaticRoute(const IpAddress& ip, uint32_t len, const IpAddress& nh); bool IsV4() const { return ip_prefix.is_v4(); } bool IsV6() const { return ip_prefix.is_v6(); } bool operator<(const VnStaticRoute &rhs) const { if (ip_prefix != rhs.ip_prefix) return ip_prefix < rhs.ip_prefix; return (plen < rhs.plen); } Ip4Address GetBroadcastAddress() const; Ip4Address GetSubnetAddress() const; Ip6Address GetV6SubnetAddress() const; bool IsSubnetMember(const IpAddress &ip) const; }; // Per IPAM data of the VN struct VnIpamLinkData { OperDhcpOptions oper_dhcp_options_; bool operator==(const VnIpamLinkData &rhs) const { if (oper_dhcp_options_.host_routes() == rhs.oper_dhcp_options_.host_routes()) return true; return false; } }; struct VnKey : public AgentOperDBKey { VnKey(const boost::uuids::uuid &id) : AgentOperDBKey(), uuid_(id) { } virtual ~VnKey() { } boost::uuids::uuid uuid_; }; struct VnData : public AgentOperDBData { typedef std::map<std::string, VnIpamLinkData> VnIpamDataMap; typedef std::pair<std::string, VnIpamLinkData> VnIpamDataPair; VnData(const Agent *agent, IFMapNode *node, const string &name, const uuid &acl_id, const string &vrf_name, const uuid &mirror_acl_id, const uuid &mc_acl_id, const std::vector<VnIpam> &ipam, const VnIpamDataMap &vn_ipam_data, int vxlan_id, int vnid, bool admin_state, bool enable_rpf, bool flood_unknown_unicast, Agent::ForwardingMode forwarding_mode, const boost::uuids::uuid &qos_config_uuid, bool mirror_destination, bool pbb_etree_enable, bool pbb_evpn_enable, bool layer2_control_word, UuidList slo_list) : AgentOperDBData(agent, node), name_(name), vrf_name_(vrf_name), acl_id_(acl_id), mirror_acl_id_(mirror_acl_id), mirror_cfg_acl_id_(mc_acl_id), ipam_(ipam), vn_ipam_data_(vn_ipam_data), vxlan_id_(vxlan_id), vnid_(vnid), admin_state_(admin_state), enable_rpf_(enable_rpf), flood_unknown_unicast_(flood_unknown_unicast), forwarding_mode_(forwarding_mode), qos_config_uuid_(qos_config_uuid), mirror_destination_(mirror_destination), pbb_etree_enable_(pbb_etree_enable), pbb_evpn_enable_(pbb_evpn_enable), layer2_control_word_(layer2_control_word), slo_list_(slo_list) { }; VnData(const Agent *agent, IFMapNode *node, const string &name, const uuid &acl_id, const string &vrf_name, const uuid &mirror_acl_id, const uuid &mc_acl_id, const std::vector<VnIpam> &ipam, const VnIpamDataMap &vn_ipam_data, const std::vector<VnStaticRoute> &static_route, int vxlan_id, int vnid, bool admin_state, bool enable_rpf, bool flood_unknown_unicast, Agent::ForwardingMode forwarding_mode, const boost::uuids::uuid &qos_config_uuid, bool mirror_destination, bool pbb_etree_enable, bool pbb_evpn_enable, bool layer2_control_word, UuidList slo_list) : AgentOperDBData(agent, node), name_(name), vrf_name_(vrf_name), acl_id_(acl_id), mirror_acl_id_(mirror_acl_id), mirror_cfg_acl_id_(mc_acl_id), ipam_(ipam), vn_ipam_data_(vn_ipam_data), static_route_(static_route), vxlan_id_(vxlan_id), vnid_(vnid), admin_state_(admin_state), enable_rpf_(enable_rpf), flood_unknown_unicast_(flood_unknown_unicast), forwarding_mode_(forwarding_mode), qos_config_uuid_(qos_config_uuid), mirror_destination_(mirror_destination), pbb_etree_enable_(pbb_etree_enable), pbb_evpn_enable_(pbb_evpn_enable), layer2_control_word_(layer2_control_word), slo_list_(slo_list) { }; virtual ~VnData() { } string name_; string vrf_name_; uuid acl_id_; uuid mirror_acl_id_; uuid mirror_cfg_acl_id_; std::vector<VnIpam> ipam_; VnIpamDataMap vn_ipam_data_; std::vector<VnStaticRoute> static_route_; int vxlan_id_; int vnid_; bool admin_state_; bool enable_rpf_; bool flood_unknown_unicast_; Agent::ForwardingMode forwarding_mode_; boost::uuids::uuid qos_config_uuid_; bool mirror_destination_; bool pbb_etree_enable_; bool pbb_evpn_enable_; bool layer2_control_word_; UuidList slo_list_; }; class VnEntry : AgentRefCount<VnEntry>, public AgentOperDBEntry { public: VnEntry(Agent *agent, uuid id); virtual ~VnEntry(); virtual bool IsLess(const DBEntry &rhs) const; virtual KeyPtr GetDBRequestKey() const; virtual void SetKey(const DBRequestKey *key); virtual string ToString() const; const uuid &GetUuid() const {return uuid_;}; const string &GetName() const {return name_;}; bool IsAclSet() const { return ((acl_.get() != NULL) || (mirror_acl_.get() != NULL) || (mirror_cfg_acl_.get() != NULL)); } const AclDBEntry *GetAcl() const {return acl_.get();} const AclDBEntry *GetMirrorAcl() const {return mirror_acl_.get();} const AclDBEntry *GetMirrorCfgAcl() const {return mirror_cfg_acl_.get();} VrfEntry *GetVrf() const {return vrf_.get();} const std::vector<VnIpam> &GetVnIpam() const { return ipam_; } const VnIpam *GetIpam(const IpAddress &ip) const; IpAddress GetGatewayFromIpam(const IpAddress &ip) const; IpAddress GetDnsFromIpam(const IpAddress &ip) const; IpAddress GetDefaultRouteFromVnHostRoutes() const; IpAddress GetL3VxlanRouteGateway() const; bool GetL3VxlanRouteDestByGateway(IpAddress *prefix_addr, uint32_t *plen, IpAddress gw) const; uint32_t GetAllocUnitFromIpam(const IpAddress &ip) const; bool GetVnHostRoutes(const std::string &ipam, std::vector<OperDhcpOptions::HostRoute> *routes) const; bool GetIpamName(const IpAddress &vm_addr, std::string *ipam_name) const; bool GetIpamData(const IpAddress &vm_addr, std::string *ipam_name, autogen::IpamType *ipam_type) const; bool GetIpamVdnsData(const IpAddress &vm_addr, autogen::IpamType *ipam_type, autogen::VirtualDnsType *vdns_type) const; bool GetPrefix(const Ip6Address &ip, Ip6Address *prefix, uint8_t *plen) const; std::string GetProject() const; int GetVxLanId() const; const VxLanId *vxlan_id_ref() const {return vxlan_id_ref_.get();} void set_bridging(bool bridging) {bridging_ = bridging;} bool bridging() const {return bridging_;}; bool layer3_forwarding() const {return layer3_forwarding_;}; void set_layer3_forwarding(bool layer3_forwarding) {layer3_forwarding_ = layer3_forwarding;} Agent::ForwardingMode forwarding_mode() const {return forwarding_mode_;} bool admin_state() const {return admin_state_;} bool enable_rpf() const {return enable_rpf_;} bool flood_unknown_unicast() const {return flood_unknown_unicast_;} const AgentQosConfig* qos_config() const { return qos_config_.get(); } const bool mirror_destination() const { return mirror_destination_; } int vnid() const {return vnid_;} bool pbb_etree_enable() const { return pbb_etree_enable_; } bool pbb_evpn_enable() const { return pbb_evpn_enable_; } bool layer2_control_word() const { return layer2_control_word_; } const UuidList &slo_list() const { return slo_list_; } uint32_t GetRefCount() const { return AgentRefCount<VnEntry>::GetRefCount(); } bool DBEntrySandesh(Sandesh *sresp, std::string &name) const; void SendObjectLog(AgentLogEvent::type event) const; bool IdentifyBgpRoutersServiceIp(const IpAddress &ip_address, bool *is_dns, bool *is_gateway) const; void AllocWalker(); void ReleaseWalker(); private: friend class VnTable; bool Resync(Agent *agent); bool ChangeHandler(Agent *agent, const DBRequest *req); bool UpdateVxlan(Agent *agent, bool op_del); void ResyncRoutes(); bool UpdateForwardingMode(Agent *agent); bool ApplyAllIpam(Agent *agent, VrfEntry *old_vrf, bool del); bool ApplyIpam(Agent *agent, VnIpam *ipam, VrfEntry *old_vrf, bool del); bool CanInstallIpam(const VnIpam *ipam); bool UpdateIpam(Agent *agent, std::vector<VnIpam> &new_ipam); bool HandleIpamChange(Agent *agent, VnIpam *old_ipam, VnIpam *new_ipam); void UpdateHostRoute(Agent *agent, const IpAddress &old_address, const IpAddress &new_address, bool policy); bool AddIpamRoutes(Agent *agent, VnIpam *ipam); void DelIpamRoutes(Agent *agent, VnIpam *ipam, VrfEntry *vrf); void AddHostRoute(const IpAddress &address, bool policy); void DelHostRoute(const IpAddress &address); void AddSubnetRoute(VnIpam *ipam); void DelSubnetRoute(VnIpam *ipam); Agent *agent_; uuid uuid_; string name_; AclDBEntryRef acl_; AclDBEntryRef mirror_acl_; AclDBEntryRef mirror_cfg_acl_; VrfEntryRef vrf_; std::vector<VnIpam> ipam_; VnData::VnIpamDataMap vn_ipam_data_; std::vector<VnStaticRoute> static_route_; int vxlan_id_; int vnid_; // Based on vxlan-network-identifier mode, the active_vxlan_id_ is picked // from either vxlan_id_ or vnid_ int active_vxlan_id_; bool bridging_; bool layer3_forwarding_; bool admin_state_; VxLanIdRef vxlan_id_ref_; uint32_t table_label_; bool enable_rpf_; bool flood_unknown_unicast_; Agent::ForwardingMode forwarding_mode_; AgentRouteWalkerPtr route_resync_walker_; AgentQosConfigConstRef qos_config_; bool mirror_destination_; bool pbb_etree_enable_; bool pbb_evpn_enable_; bool layer2_control_word_; UuidList slo_list_; DISALLOW_COPY_AND_ASSIGN(VnEntry); }; class VnTable : public AgentOperDBTable { public: VnTable(DB *db, const std::string &name); virtual ~VnTable(); virtual std::auto_ptr<DBEntry> AllocEntry(const DBRequestKey *k) const; virtual size_t Hash(const DBEntry *entry) const {return 0;}; virtual size_t Hash(const DBRequestKey *key) const {return 0;}; virtual AgentSandeshPtr GetAgentSandesh(const AgentSandeshArguments *args, const std::string &context); virtual DBEntry *OperDBAdd(const DBRequest *req); virtual bool OperDBOnChange(DBEntry *entry, const DBRequest *req); virtual bool OperDBDelete(DBEntry *entry, const DBRequest *req); virtual bool OperDBResync(DBEntry *entry, const DBRequest *req); virtual bool IFNodeToReq(IFMapNode *node, DBRequest &req, const boost::uuids::uuid &u); virtual bool IFNodeToUuid(IFMapNode *node, boost::uuids::uuid &u); virtual bool ProcessConfig(IFMapNode *node, DBRequest &req, const boost::uuids::uuid &u); virtual void Clear(); int ComputeCfgVxlanId(IFMapNode *node); void CfgForwardingFlags(IFMapNode *node, bool *rpf, bool *flood_unknown_unicast, Agent::ForwardingMode *forwarding_mode, bool *mirror_destination); static DBTableBase *CreateTable(DB *db, const std::string &name); static VnTable *GetInstance() {return vn_table_;}; void AddVn(const uuid &vn_uuid, const string &name, const uuid &acl_id, const string &vrf_name, const std::vector<VnIpam> &ipam, const VnData::VnIpamDataMap &vn_ipam_data, int vn_id, int vxlan_id, bool admin_state, bool enable_rpf, bool flood_unknown_unicast, bool pbb_etree_enable, bool pbb_evpn_enable, bool layer2_control_word); void DelVn(const uuid &vn_uuid); void ResyncReq(const boost::uuids::uuid &vn); VnEntry *Find(const uuid &vn_uuid); void GlobalVrouterConfigChanged(); bool VnEntryWalk(DBTablePartBase *partition, DBEntryBase *entry); void VnEntryWalkDone(DBTable::DBTableWalkRef walk_ref, DBTableBase *partition); int GetCfgVnId(autogen::VirtualNetwork *cfg_vn); private: static VnTable *vn_table_; bool IsGwHostRouteRequired(); bool IsGatewayL2(const string &gateway) const; void BuildVnIpamData(const std::vector<autogen::IpamSubnetType> &subnets, const std::string &ipam_name, std::vector<VnIpam> *vn_ipam); VnData *BuildData(IFMapNode *node); IFMapNode *FindTarget(IFMapAgentTable *table, IFMapNode *node, std::string node_type); DBTable::DBTableWalkRef walk_ref_; DISALLOW_COPY_AND_ASSIGN(VnTable); }; class OperNetworkIpam : public OperIFMapTable { public: OperNetworkIpam(Agent *agent, DomainConfig *domain_config); virtual ~OperNetworkIpam(); void ConfigDelete(IFMapNode *node); void ConfigAddChange(IFMapNode *node); void ConfigManagerEnqueue(IFMapNode *node); private: DomainConfig *domain_config_; DISALLOW_COPY_AND_ASSIGN(OperNetworkIpam); }; class OperVirtualDns : public OperIFMapTable { public: OperVirtualDns(Agent *agent, DomainConfig *domain_config); virtual ~OperVirtualDns(); void ConfigDelete(IFMapNode *node); void ConfigAddChange(IFMapNode *node); void ConfigManagerEnqueue(IFMapNode *node); private: DomainConfig *domain_config_; DISALLOW_COPY_AND_ASSIGN(OperVirtualDns); }; class DomainConfig { public: typedef std::map<std::string, autogen::IpamType> IpamDomainConfigMap; typedef std::pair<std::string, autogen::IpamType> IpamDomainConfigPair; typedef std::map<std::string, autogen::VirtualDnsType> VdnsDomainConfigMap; typedef std::pair<std::string, autogen::VirtualDnsType> VdnsDomainConfigPair; typedef boost::function<void(IFMapNode *)> Callback; DomainConfig(Agent *); virtual ~DomainConfig(); void Init(); void Terminate(); void RegisterIpamCb(Callback cb); void RegisterVdnsCb(Callback cb); void IpamDelete(IFMapNode *node); void IpamAddChange(IFMapNode *node); void VDnsDelete(IFMapNode *node); void VDnsAddChange(IFMapNode *node); bool GetIpam(const std::string &name, autogen::IpamType *ipam); bool GetVDns(const std::string &vdns, autogen::VirtualDnsType *vdns_type); private: void CallVdnsCb(IFMapNode *node); void CallIpamCb(IFMapNode *node); bool IpamChanged(const autogen::IpamType &old, const autogen::IpamType &cur) const; IpamDomainConfigMap ipam_config_; VdnsDomainConfigMap vdns_config_; std::vector<Callback> ipam_callback_; std::vector<Callback> vdns_callback_; DISALLOW_COPY_AND_ASSIGN(DomainConfig); }; #endif // vnsw_agent_vn_hpp
[ "zhengx@certusnet.com.cn" ]
zhengx@certusnet.com.cn
60814098dbc5b90d1976cc8ab9ab9b9ecca053ca
15d8fe4a6858378e350b9df832062bc2050a75ce
/012-freetype-fonts-pt1/HUD012.cpp
8894dd1065cefda323afbe4af834c76e5dfd1090
[ "MIT" ]
permissive
michalbb1/opengl4-tutorials-mbsoftworks
cdf6ea187914792f237e4f4c60194d40472ade60
85909d0d22f51a4ebff5f22ac3f7456d77a6058a
refs/heads/dev
2022-11-05T09:27:03.270344
2022-10-29T05:14:35
2022-10-29T05:14:35
123,883,165
71
21
MIT
2022-10-29T05:14:36
2018-03-05T07:43:53
C++
UTF-8
C++
false
false
795
cpp
// STL #include <mutex> // Project #include "HUD012.h" namespace opengl4_mbsoftworks { namespace tutorial012 { HUD012::HUD012(const OpenGLWindow& window) : HUD(window) { static std::once_flag prepareOnceFlag; std::call_once(prepareOnceFlag, []() { FreeTypeFontManager::getInstance().loadSystemFreeTypeFont(DEFAULT_FONT_KEY, "arial.ttf", 24); }); } void HUD012::renderHUD() const { printBuilder().print(10, 10, "FPS: {}", _window.getFPS()); printBuilder().print(10, 40, "Vertical Synchronization: {} (Press F3 to toggle)", _window.isVerticalSynchronizationEnabled() ? "On" : "Off"); printBuilder() .fromRight() .fromBottom() .print(10, 10, "www.mbsoftworks.sk"); } } // namespace tutorial012 } // namespace opengl4_mbsoftworks
[ "michalbb1@gmail.com" ]
michalbb1@gmail.com
e9e2f92fff726fc1f94c2a43f1167631ddb1d7e3
372f75df550b0c09f5ea669142c6cc15bbf8ef8f
/Source/bmalloc/bmalloc/ObjectType.h
bce8aeef752c1d98f7b22b4455de86ec6e2a45f4
[]
no_license
exhumesw/webkit
048265798a78f4c9d33bb945cfafd54c7cd7c405
539494f3b02be9df9eb6dbd23b759c3539380607
refs/heads/master
2023-01-09T08:54:30.720864
2014-04-08T08:08:31
2014-04-08T08:08:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,812
h
/* * Copyright (C) 2014 Apple 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. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef ObjectType_h #define ObjectType_h #include "BAssert.h" #include "Sizes.h" namespace bmalloc { enum ObjectType { Small, Medium, Large, XLarge }; ObjectType objectType(void*); inline bool isSmallOrMedium(void* object) { return test(object, smallOrMediumTypeMask); } inline bool isSmall(void* smallOrMedium) { ASSERT(isSmallOrMedium(smallOrMedium)); return test(smallOrMedium, smallOrMediumSmallTypeMask); } } // namespace bmalloc #endif // ObjectType_h
[ "ggaren@apple.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc" ]
ggaren@apple.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc
d446c9a772d13e4a84d5e534992d46cadbe37cb4
6ab9a3229719f457e4883f8b9c5f1d4c7b349362
/cf/058B.cpp
387847d796a2272857218b84cae97beca371a947
[]
no_license
ajmarin/coding
77c91ee760b3af34db7c45c64f90b23f6f5def16
8af901372ade9d3d913f69b1532df36fc9461603
refs/heads/master
2022-01-26T09:54:38.068385
2022-01-09T11:26:30
2022-01-09T11:26:30
2,166,262
33
15
null
null
null
null
UTF-8
C++
false
false
363
cpp
#include <cstdio> int reduce(int n){ if(!(n & 1)) return n >> 1; if(!(n % 3)) return n / 3; for(int i = 6; ; i += 6){ int t1 = i + 1, t2 = i - 1; if(!(n % t2)) return n / t2; if(!(n % t1)) return n / t1; if(t1 * t1 > n) return 1; } } int main(void){ int n; scanf("%d", &n); while(n != 1){ printf("%d ", n); n = reduce(n); } printf("1\n"); }
[ "mistermarin@gmail.com" ]
mistermarin@gmail.com
5521bf4e62aabec14a3070f5c8373c858711b709
32709d5de776d864df9581b1a9c2d9d966c3c31f
/isaac/08_06_Isaac_UI/MousePoint.cpp
8bc875a2a83d547403ab8e0f1473b39d69042b5c
[]
no_license
dadm8473/DirectX_Class
76010b18e490306cd44c21554cc8ab31f53df1ce
34dd319d39d93c1f73a7c7dd6c2047aa20694e69
refs/heads/master
2022-03-16T05:30:41.434207
2019-11-10T12:45:37
2019-11-10T12:45:37
186,415,853
0
0
null
null
null
null
UTF-8
C++
false
false
323
cpp
#include "DXUT.h" #include "MousePoint.h" MousePoint::MousePoint() { } MousePoint::~MousePoint() { } void MousePoint::Start() { type = UIOBJECT; CreateCollider(CL_MOUSE, 3); bCollision = false; } void MousePoint::Update(float deltaTime) { CGameObject::Update(deltaTime); if (bCollision) bCollision = false; }
[ "dadm8473@gmail.com" ]
dadm8473@gmail.com
bae560c3baae729bb520af9f0846f859ddc06423
7f610e8792081df5955492c9b55755c72c79da17
/CodeChefProblems/Guddu And His Mother/main.cpp
78179a31a4b7c8c03630076dacf278d4ce54d216
[]
no_license
Parikshit22/Data-Structures-Algorithms-Cpp
8da910d0c1ba745ccfc016e0d0865f108b30cb04
4515f41c8a41850bc2888d4c83b9ce5dc9b66d68
refs/heads/master
2022-12-09T09:54:42.240609
2020-09-02T03:48:43
2020-09-02T03:48:43
276,821,418
1
0
null
null
null
null
UTF-8
C++
false
false
620
cpp
#include <bits/stdc++.h> using namespace std; #define ll long long int main() { int t; cin>>t; while(t>0){ ll n; cin>>n; ll arr[n]; for(ll i=0;i<n;i++){ cin>>arr[i]; } ll sum = arr[0]; for(ll i=1;i<n;i++){ sum = sum^arr[i]; } ll num=0; ll temp; ll series=0; for(ll i=0;i<n-1;i++){ series = series^arr[i]; temp = sum^series; if(temp == series){ num++; } } cout<<num<<endl; t--; } return 0; }
[ "parikshitagarwal40@gmail.com" ]
parikshitagarwal40@gmail.com
500660fd6f95dadd46ceac24528d2fcfbeb17133
32bfc176a5db0d59129f3c39381c46b0a520eb86
/demos/QMPlay/src/plugins/mp3/build/moc/moc_formMp3.cpp
f3e90d2b90fb3bd2ed69256f27e5e022b3559028
[]
no_license
varzhou/Hifi-Pod
2fb4c6bd3172720f8813fbbdf48375a10598a834
eec4e27e37bc5d99b9fddb65be06ef5978da2eee
refs/heads/master
2021-05-28T18:26:14.507496
2012-09-16T05:45:28
2012-09-16T05:45:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,436
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'formMp3.h' ** ** Created: Tue Aug 21 20:18:31 2012 ** by: The Qt Meta Object Compiler version 62 (Qt 4.6.2) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../forms/formMp3.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'formMp3.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 62 #error "This file was generated using the moc from 4.6.2. 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_FormMp3[] = { // content: 4, // revision 0, // classname 0, 0, // classinfo 3, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: signature, parameters, type, tag, flags 9, 8, 8, 8, 0x0a, 19, 8, 8, 8, 0x0a, 30, 8, 8, 8, 0x0a, 0 // eod }; static const char qt_meta_stringdata_FormMp3[] = { "FormMp3\0\0zamknij()\0timRefDo()\0editId3()\0" }; const QMetaObject FormMp3::staticMetaObject = { { &QWidget::staticMetaObject, qt_meta_stringdata_FormMp3, qt_meta_data_FormMp3, 0 } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &FormMp3::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *FormMp3::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *FormMp3::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_FormMp3)) return static_cast<void*>(const_cast< FormMp3*>(this)); return QWidget::qt_metacast(_clname); } int FormMp3::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { switch (_id) { case 0: zamknij(); break; case 1: timRefDo(); break; case 2: editId3(); break; default: ; } _id -= 3; } return _id; } QT_END_MOC_NAMESPACE
[ "litroncn@gmail.com" ]
litroncn@gmail.com
5b5bf060678e626976ae06c27a1da8a91cddfe2e
cf3e9398e4a1a8b41aa12e3ef42aa2a73bff2507
/src/analyst/propagate.cpp
48d83e1b27a6a92662c18b9838ffeeafdaf49f88
[ "Apache-2.0", "MIT" ]
permissive
fritzo/pomagma
fb207e8bfd77c7ac592ddb27d5fd3213da50a532
ad2bf9c12eb58190f2761608c053ac89d3ddf305
refs/heads/master
2023-02-24T16:54:31.981623
2023-02-10T23:17:42
2023-02-10T23:17:42
4,943,857
12
0
NOASSERTION
2023-02-10T23:17:43
2012-07-08T05:22:16
C++
UTF-8
C++
false
false
11,401
cpp
#include <pomagma/analyst/propagate.hpp> #include <pomagma/atlas/macro/structure_impl.hpp> #include <pomagma/atlas/parser.hpp> #include <unordered_map> #include <unordered_set> #include <tuple> // defined in pomagma/third_party/farmhash/farmhash.h namespace util { size_t Hash(const char *s, size_t len); } namespace pomagma { namespace propagate { //---------------------------------------------------------------------------- // parsing inline size_t hash_data(const void *data, size_t size) { return util::Hash(reinterpret_cast<const char *>(data), size); } struct HashExprPtr { size_t operator()(const std::shared_ptr<Expr> &expr) const { POMAGMA_ASSERT1(expr, "expr is null"); std::tuple<Arity, size_t, const Expr *, const Expr *> data{ expr->arity, hash_data(expr->name.data(), expr->name.size()), expr->args[0].get(), expr->args[1].get()}; return hash_data(&data, sizeof(data)); } }; struct EqExprPtr { bool operator()(const std::shared_ptr<Expr> &lhs, const std::shared_ptr<Expr> &rhs) const { POMAGMA_ASSERT1(lhs, "lhs is null"); POMAGMA_ASSERT1(rhs, "rhs is null"); return lhs->arity == rhs->arity and lhs->name == rhs->name and lhs->args[0].get() == rhs->args[0].get() and lhs->args[1].get() == rhs->args[1].get(); } }; typedef std::unordered_set<std::shared_ptr<Expr>, HashExprPtr, EqExprPtr> ExprSet; class Reducer { public: explicit Reducer(ExprSet &deduped) : m_deduped(deduped) {} typedef std::shared_ptr<Expr> Term; Term reduce(const std::string &token, const NullaryFunction *) { return new_term(NULLARY_FUNCTION, token); } Term reduce(const std::string &token, const InjectiveFunction *, const Term &key) { return key ? new_term(INJECTIVE_FUNCTION, token, key) : Term(); } Term reduce(const std::string &token, const BinaryFunction *, const Term &lhs, const Term &rhs) { return lhs and rhs ? new_term(BINARY_FUNCTION, token, lhs, rhs) : Term(); } Term reduce(const std::string &token, const SymmetricFunction *, const Term &lhs, const Term &rhs) { return lhs and rhs ? new_term(SYMMETRIC_FUNCTION, token, lhs, rhs) : Term(); } Term reduce(const std::string &token, const UnaryRelation *, const Term &key) { return key ? new_term(UNARY_RELATION, token, key) : Term(); } Term reduce(const std::string &token, const BinaryRelation *, const Term &lhs, const Term &rhs) { return lhs and rhs ? new_term(BINARY_RELATION, token, lhs, rhs) : Term(); } Term reduce_equal(const Term &lhs, const Term &rhs) { return lhs and rhs ? new_term(EQUAL, "", lhs, rhs) : Term(); } Term reduce_hole() { return new_term(HOLE, ""); } Term reduce_var(const std::string &name) { return new_term(VAR, name); } Term reduce_error(const std::string &) { return Term(); } private: Term new_term(Arity arity, const std::string &name, Term arg0 = Term(), Term arg1 = Term()) { // kludge to deal with old gcc syntax Expr expr = {arity, name, {arg0, arg1}}; Term result(new Expr(std::move(expr))); return *m_deduped.insert(result).first; } ExprSet &m_deduped; }; class Parser : public ExprParser<Reducer> { public: Parser(Signature &signature, ExprSet &deduped, std::vector<std::string> &error_log) : ExprParser<Reducer>(signature, m_reducer, error_log), m_reducer(deduped) {} private: Reducer m_reducer; }; inline bool is_fact(const Expr &expr) { switch (expr.arity) { case UNARY_RELATION: case BINARY_RELATION: case EQUAL: return true; default: return false; } } Theory parse_theory(Signature &signature, const std::vector<std::string> &polish_facts, std::vector<std::string> &error_log) { std::vector<std::shared_ptr<Expr>> facts; ExprSet deduped; { Parser parser(signature, deduped, error_log); bool error = false; for (size_t i = 0; i < polish_facts.size(); ++i) { POMAGMA_DEBUG("parsing " << polish_facts[i]); auto fact = parser.parse(polish_facts[i]); if (unlikely(not fact)) { std::ostringstream message; message << "Error parsing fact " << i << " of " << polish_facts.size(); error_log.push_back(message.str()); error = true; } else if (unlikely(not is_fact(*fact))) { std::ostringstream message; message << "Error: fact " << i << " of " << polish_facts.size() << " is not a relation"; error_log.push_back(message.str()); error = true; } else { facts.push_back(fact); } } if (error) { POMAGMA_WARN("error parsing facts"); return Theory(); } } std::vector<const Expr *> exprs; for (auto expr_ptr : deduped) { POMAGMA_ASSERT1(expr_ptr, "programmer error"); exprs.push_back(expr_ptr.get()); } return {std::move(facts), std::move(exprs)}; } //---------------------------------------------------------------------------- // propagation typedef intervals::Approximation State; namespace { inline void propagate_constraint( const Expr *expr, const std::unordered_map<const Expr *, State> &states, std::unordered_map<const Expr *, std::vector<State>> &message_queues, Approximator &approximator) { const std::string &name = expr->name; switch (expr->arity) { case NULLARY_FUNCTION: { const Expr *val = expr; message_queues[val].push_back(approximator.nullary_function(name)); } break; case INJECTIVE_FUNCTION: { if (name == "QUOTE") break; // QUOTE is not monotone TODO("propagate injective_function " << name); } break; case BINARY_FUNCTION: case SYMMETRIC_FUNCTION: { const Expr *lhs = expr->args[0].get(); const Expr *rhs = expr->args[1].get(); const Expr *val = expr; POMAGMA_ASSERT1(lhs, "missing lhs"); POMAGMA_ASSERT1(rhs, "missing rhs"); message_queues[val].push_back( approximator.lazy_binary_function_lhs_rhs(name, states.at(lhs), states.at(rhs))); message_queues[rhs].push_back( approximator.lazy_binary_function_lhs_val(name, states.at(lhs), states.at(val))); message_queues[lhs].push_back( approximator.lazy_binary_function_rhs_val(name, states.at(rhs), states.at(val))); } break; case UNARY_RELATION: { TODO("propagate unary_relation " << name); } break; case BINARY_RELATION: { const Expr *lhs = expr->args[0].get(); const Expr *rhs = expr->args[1].get(); POMAGMA_ASSERT1(lhs, "missing lhs"); POMAGMA_ASSERT1(rhs, "missing rhs"); if (name == "LESS") { message_queues[lhs].push_back( approximator.less_rhs(states.at(rhs))); message_queues[rhs].push_back( approximator.less_lhs(states.at(lhs))); } else if (name == "NLESS") { message_queues[lhs].push_back( approximator.nless_rhs(states.at(rhs))); message_queues[rhs].push_back( approximator.nless_lhs(states.at(lhs))); } else { TODO("propagate binary_relation " << name); } } break; case EQUAL: { const Expr *lhs = expr->args[0].get(); const Expr *rhs = expr->args[1].get(); POMAGMA_ASSERT1(lhs, "missing lhs"); POMAGMA_ASSERT1(rhs, "missing rhs"); message_queues[lhs].push_back(states.at(rhs)); message_queues[rhs].push_back(states.at(lhs)); } break; case HOLE: break; // no information case VAR: break; // no information } } inline void log_change_count(std::unordered_map<const Expr *, State> &states, size_t change_count) { if (states.size() > 10) { POMAGMA_DEBUG("propagation found " << change_count << " changes"); } else { std::string message = "[ "; for (const auto &pair : states) { for (int p = 0; p < 4; ++p) { message.push_back(pair.second.bounds[p] ? '-' : '?'); } message.push_back(' '); } POMAGMA_DEBUG(message << "] " << change_count << " changes "); } } // this should have time complexity O(#constraints) inline size_t propagate_step( std::unordered_map<const Expr *, State> &states, std::unordered_map<const Expr *, std::vector<State>> &message_queues, const Theory &theory, Approximator &approximator) { for (const Expr *expr : theory.exprs) { propagate_constraint(expr, states, message_queues, approximator); } size_t change_count = 0; for (auto &i : states) { const Expr *expr = i.first; State &state = i.second; std::vector<State> &messages = message_queues[expr]; const State updated_state = approximator.lazy_fuse(messages); messages.clear(); if (updated_state == state) continue; POMAGMA_ASSERT1(approximator.expensive_refines(updated_state, state), "propagation was not monotone"); if (approximator.observably_differ(state, updated_state)) { ++change_count; } state = updated_state; if (approximator.lazy_is_valid(state) == Trool::FALSE) { POMAGMA_DEBUG("solution is invalid"); return 0; } } if (pomagma::Log::level() >= 3) { log_change_count(states, change_count); } return change_count; } } // namespace Trool lazy_validate(const Theory &theory, Approximator &approximator) { POMAGMA_DEBUG("Propagating " << theory.exprs.size() << " variables"); std::unordered_map<const Expr *, State> states; for (const Expr *expr : theory.exprs) { states.insert({expr, approximator.unknown()}); } std::unordered_map<const Expr *, std::vector<State>> message_queues; const size_t max_steps = 1000; size_t step = 0; while (propagate_step(states, message_queues, theory, approximator)) { ++step; POMAGMA_ASSERT(step < max_steps, "propagation failed to converge in " << max_steps << " steps"); } Trool is_valid = Trool::TRUE; for (const auto &i : states) { is_valid = and_trool(is_valid, approximator.lazy_is_valid(i.second)); } return is_valid; } } // namespace propagate } // namespace pomagma
[ "fritz.obermeyer@gmail.com" ]
fritz.obermeyer@gmail.com
270f68a6b0e5066f891cdf3ef447bf7695573a19
1ebc6909a717690b0f5245598069b8ea001a62a1
/source/Game/Objects/Gen/Common/Button.cpp
f5dff34fc50089493df14594cb92232d1020a07d
[]
no_license
aknetk/Sonic-3-Mixed
8342b290bc83abcf3c29a69b4f518addeb3454c3
8e5803281669677878d449a0234515654ed958fd
refs/heads/master
2020-07-18T11:14:42.533813
2019-09-04T05:09:03
2019-09-04T05:09:03
206,234,998
0
1
null
null
null
null
UTF-8
C++
false
false
1,906
cpp
// Object ID: 0x33 // Object Name: Button.cpp #include "Button.h" typedef IMath Math; void Button::Create() { Object::Create(); Active = true; Priority = false; Permanent = (SubType >> 4 & 0x1); TriggerID = (SubType & 0xF); TriggerType = (SubType >> 6 & 0x1); CollisionType = (SubType >> 5 & 0x1); if (!CollisionType) Solid = true; else SolidTop = true; Scene->AddSelfToRegistry(this, "Solid"); W = 32; H = 16; Rotation = 0; StartY = this->Y; CurrentAnimation = 15; if (Scene->ZoneID == 2) CurrentAnimation = 0; Down = false; Pressed = false; } void Button::Update() { this->Down = Scene->Players[0]->Ground && Scene->Players[0]->LastObject == this; if (Down) { if (!Pressed) { Pressed = true; Sound::Play(Sound::SFX_SCORE_ADD); Scene->LevelTriggerFlag |= 1 << TriggerID; CollidingWithPlayer = true; } } Y = StartY + 4 + 4 * Down; Object::Update(); } void Button::Render(int CamX, int CamY) { if (Scene->ZoneID != 2) G->DrawSprite(Sprite, CurrentAnimation, Down, X - CamX, Y - 4 * Down - CamY, 0, IE_NOFLIP); else { G->DrawSprite(Sprite, CurrentAnimation, 0, X - CamX, Y - 4 * Down - CamY + 3, 0, IE_NOFLIP); G->DrawSprite(Sprite, CurrentAnimation, Down + 1, X - CamX, StartY - CamY + 7, 0, IE_NOFLIP); } if (DrawCollisions) { G->SetDrawAlpha(0x80); G->DrawRectangle(X - (W / 2) - CamX, Y - (H / 2) - CamY, W, H, DrawCollisionsColor); G->SetDrawAlpha(0xFF); } } int Button::OnCollisionWithPlayer(int PlayerID, int HitFrom, int Data) { if (HitFrom != CollideSide::TOP) { this->CollidingWithPlayer = false; return 0; } if (Scene->Players[PlayerID]->YSpeed <= 0) { this->CollidingWithPlayer = false; return 0; } return 1; }
[ "aurumdude@gmail.com" ]
aurumdude@gmail.com
d589e0c9af34cf9370e9b92f1d568252afbb88d0
f81b774e5306ac01d2c6c1289d9e01b5264aae70
/components/permissions/android/permission_prompt_android.cc
245b0c7bc4eb01c98464cd14f94a4cdbb4241f1f
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
waaberi/chromium
a4015160d8460233b33fe1304e8fd9960a3650a9
6549065bd785179608f7b8828da403f3ca5f7aab
refs/heads/master
2022-12-13T03:09:16.887475
2020-09-05T20:29:36
2020-09-05T20:29:36
293,153,821
1
1
BSD-3-Clause
2020-09-05T21:02:50
2020-09-05T21:02:49
null
UTF-8
C++
false
false
6,582
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 "components/permissions/android/permission_prompt_android.h" #include <memory> #include "components/infobars/core/infobar.h" #include "components/infobars/core/infobar_manager.h" #include "components/permissions/android/permission_dialog_delegate.h" #include "components/permissions/permission_request.h" #include "components/permissions/permissions_client.h" #include "components/resources/android/theme_resources.h" #include "components/strings/grit/components_strings.h" #include "components/url_formatter/elide_url.h" #include "ui/base/l10n/l10n_util.h" namespace permissions { PermissionPromptAndroid::PermissionPromptAndroid( content::WebContents* web_contents, Delegate* delegate) : web_contents_(web_contents), delegate_(delegate), permission_infobar_(nullptr), weak_factory_(this) { DCHECK(web_contents); infobars::InfoBarManager* infobar_manager = PermissionsClient::Get()->GetInfoBarManager(web_contents_); if (infobar_manager) { permission_infobar_ = PermissionsClient::Get()->MaybeCreateInfoBar( web_contents, GetContentSettingType(0u /* position */), weak_factory_.GetWeakPtr()); if (permission_infobar_) { infobar_manager->AddObserver(this); return; } } PermissionDialogDelegate::Create(web_contents_, this); } PermissionPromptAndroid::~PermissionPromptAndroid() { infobars::InfoBarManager* infobar_manager = PermissionsClient::Get()->GetInfoBarManager(web_contents_); if (!infobar_manager) return; // RemoveObserver before RemoveInfoBar to not get notified about the removal // of the `permission_infobar_` infobar. infobar_manager->RemoveObserver(this); if (permission_infobar_) { infobar_manager->RemoveInfoBar(permission_infobar_); } } void PermissionPromptAndroid::UpdateAnchorPosition() { NOTREACHED() << "UpdateAnchorPosition is not implemented"; } permissions::PermissionPrompt::TabSwitchingBehavior PermissionPromptAndroid::GetTabSwitchingBehavior() { return TabSwitchingBehavior::kKeepPromptAlive; } void PermissionPromptAndroid::Closing() { delegate_->Closing(); } void PermissionPromptAndroid::Accept() { delegate_->Accept(); } void PermissionPromptAndroid::Deny() { delegate_->Deny(); } size_t PermissionPromptAndroid::PermissionCount() const { return delegate_->Requests().size(); } ContentSettingsType PermissionPromptAndroid::GetContentSettingType( size_t position) const { const std::vector<permissions::PermissionRequest*>& requests = delegate_->Requests(); CHECK_LT(position, requests.size()); return requests[position]->GetContentSettingsType(); } static bool IsValidMediaRequestGroup( const std::vector<permissions::PermissionRequest*>& requests) { if (requests.size() < 2) return false; return ( (requests[0]->GetPermissionRequestType() == permissions::PermissionRequestType::PERMISSION_MEDIASTREAM_MIC && requests[1]->GetPermissionRequestType() == permissions::PermissionRequestType::PERMISSION_MEDIASTREAM_CAMERA) || (requests[0]->GetPermissionRequestType() == permissions::PermissionRequestType::PERMISSION_MEDIASTREAM_CAMERA && requests[1]->GetPermissionRequestType() == permissions::PermissionRequestType::PERMISSION_MEDIASTREAM_MIC)); } static bool IsValidARCameraAccessRequestGroup( const std::vector<permissions::PermissionRequest*>& requests) { if (requests.size() < 2) return false; return ( (requests[0]->GetPermissionRequestType() == permissions::PermissionRequestType::PERMISSION_AR && requests[1]->GetPermissionRequestType() == permissions::PermissionRequestType::PERMISSION_MEDIASTREAM_CAMERA) || (requests[0]->GetPermissionRequestType() == permissions::PermissionRequestType::PERMISSION_MEDIASTREAM_CAMERA && requests[1]->GetPermissionRequestType() == permissions::PermissionRequestType::PERMISSION_AR)); } // Grouped permission requests can only be Mic+Camera, Camera+Mic, // AR + Camera, or Camera + AR. static void CheckValidRequestGroup( const std::vector<permissions::PermissionRequest*>& requests) { DCHECK_EQ(static_cast<size_t>(2u), requests.size()); DCHECK_EQ(requests[0]->GetOrigin(), requests[1]->GetOrigin()); DCHECK((IsValidMediaRequestGroup(requests)) || (IsValidARCameraAccessRequestGroup(requests))); } int PermissionPromptAndroid::GetIconId() const { const std::vector<permissions::PermissionRequest*>& requests = delegate_->Requests(); if (requests.size() == 1) return requests[0]->GetIconId(); CheckValidRequestGroup(requests); return IDR_ANDROID_INFOBAR_MEDIA_STREAM_CAMERA; } base::string16 PermissionPromptAndroid::GetMessageText() const { const std::vector<permissions::PermissionRequest*>& requests = delegate_->Requests(); if (requests.size() == 1) return requests[0]->GetMessageText(); CheckValidRequestGroup(requests); if (IsValidARCameraAccessRequestGroup(requests)) { return l10n_util::GetStringFUTF16( IDS_AR_AND_MEDIA_CAPTURE_VIDEO_INFOBAR_TEXT, url_formatter::FormatUrlForSecurityDisplay( requests[0]->GetOrigin(), url_formatter::SchemeDisplay::OMIT_CRYPTOGRAPHIC)); } else { return l10n_util::GetStringFUTF16( IDS_MEDIA_CAPTURE_AUDIO_AND_VIDEO_INFOBAR_TEXT, url_formatter::FormatUrlForSecurityDisplay( requests[0]->GetOrigin(), url_formatter::SchemeDisplay::OMIT_CRYPTOGRAPHIC)); } } void PermissionPromptAndroid::OnInfoBarRemoved(infobars::InfoBar* infobar, bool animate) { if (infobar != permission_infobar_) return; permission_infobar_ = nullptr; infobars::InfoBarManager* infobar_manager = PermissionsClient::Get()->GetInfoBarManager(web_contents_); if (infobar_manager) infobar_manager->RemoveObserver(this); } void PermissionPromptAndroid::OnManagerShuttingDown( infobars::InfoBarManager* manager) { permission_infobar_ = nullptr; manager->RemoveObserver(this); } // static std::unique_ptr<permissions::PermissionPrompt> permissions::PermissionPrompt::Create(content::WebContents* web_contents, Delegate* delegate) { return std::make_unique<PermissionPromptAndroid>(web_contents, delegate); } } // namespace permissions
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
2dbd91cd5548a957ec1c1ca247292c429c74b1f2
cfeac52f970e8901871bd02d9acb7de66b9fb6b4
/generated/src/aws-cpp-sdk-datasync/include/aws/datasync/model/EfsInTransitEncryption.h
6eab760f5057307aac15abad0f4baabe50a12920
[ "Apache-2.0", "MIT", "JSON" ]
permissive
aws/aws-sdk-cpp
aff116ddf9ca2b41e45c47dba1c2b7754935c585
9a7606a6c98e13c759032c2e920c7c64a6a35264
refs/heads/main
2023-08-25T11:16:55.982089
2023-08-24T18:14:53
2023-08-24T18:14:53
35,440,404
1,681
1,133
Apache-2.0
2023-09-12T15:59:33
2015-05-11T17:57:32
null
UTF-8
C++
false
false
705
h
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/datasync/DataSync_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> namespace Aws { namespace DataSync { namespace Model { enum class EfsInTransitEncryption { NOT_SET, NONE, TLS1_2 }; namespace EfsInTransitEncryptionMapper { AWS_DATASYNC_API EfsInTransitEncryption GetEfsInTransitEncryptionForName(const Aws::String& name); AWS_DATASYNC_API Aws::String GetNameForEfsInTransitEncryption(EfsInTransitEncryption value); } // namespace EfsInTransitEncryptionMapper } // namespace Model } // namespace DataSync } // namespace Aws
[ "sdavtaker@users.noreply.github.com" ]
sdavtaker@users.noreply.github.com
d23996cad65a9ce75018d2e4e56272d292866daf
edfed5a1fd65c610e806e14d2af24c0911a7e35d
/src/version.h
91b0e2da827c0eddee6196958955279f4a3c317b
[ "MIT" ]
permissive
Earlz/v1.0.3snowballs
f4e838d3351495f0a41a5e8662a6aa7c76cd8be7
268f188ff6254981a01a24a27e8573066aeb78ee
refs/heads/master
2016-09-05T15:08:49.434507
2014-11-02T01:35:39
2014-11-02T01:35:39
30,275,688
0
0
null
null
null
null
UTF-8
C++
false
false
2,214
h
// Copyright (c) 2012 The Bitcoin developers // Copyright (c) 2012-2013 The Snowballs developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_VERSION_H #define BITCOIN_VERSION_H //#include <string> // // client versioning // // These need to be macro's, as version.cpp's voodoo requires it #define CLIENT_VERSION_MAJOR 0 #define CLIENT_VERSION_MINOR 6 #define CLIENT_VERSION_REVISION 4 #define CLIENT_VERSION_BUILD 0 static const int CLIENT_VERSION = 1000000 * CLIENT_VERSION_MAJOR + 10000 * CLIENT_VERSION_MINOR + 100 * CLIENT_VERSION_REVISION + 1 * CLIENT_VERSION_BUILD; extern const std::string CLIENT_NAME; extern const std::string CLIENT_BUILD; extern const std::string CLIENT_DATE; // Snowballs version - intended for display purpose ONLY #define PPCOIN_VERSION_MAJOR 1 #define PPCOIN_VERSION_MINOR 0 #define PPCOIN_VERSION_REVISION 3 #define PPCOIN_VERSION_BUILD 0 static const int PPCOIN_VERSION = 1000000 * PPCOIN_VERSION_MAJOR + 10000 * PPCOIN_VERSION_MINOR + 100 * PPCOIN_VERSION_REVISION + 1 * PPCOIN_VERSION_BUILD; // // network protocol versioning // static const int PROTOCOL_VERSION = 60007; // earlier versions not supported as of Feb 2012, and are disconnected // NOTE: as of bitcoin v0.6 message serialization (vSend, vRecv) still // uses MIN_PROTO_VERSION(209), where message format uses PROTOCOL_VERSION static const int MIN_PROTO_VERSION = 209; // nTime field added to CAddress, starting with this version; // if possible, avoid requesting addresses nodes older than this static const int CADDR_TIME_VERSION = 31402; // only request blocks from nodes outside this range of versions static const int NOBLKS_VERSION_START = 32000; static const int NOBLKS_VERSION_END = 32400; // BIP 0031, pong message, is enabled for all versions AFTER this one static const int BIP0031_VERSION = 60000; #endif
[ "pfeffer.robert@gmail.com" ]
pfeffer.robert@gmail.com
9e0a9970feb982b3a1cbaedddd3903f217ffe33a
e48917bc51306284b972c490f76c277110bb003d
/sinbad-ogre-4c20a40dae61/Samples/Water/include/Water.h
6356a98fbbffb9d2b82d3f64e44a962594e4303f
[ "MIT" ]
permissive
sujoyp/ogre
9912316bd53bfa3b3a714eb657967ca9bbe9cdea
a6e3250385b8425f80a1fe0e93e1ae45c4608b6b
refs/heads/master
2020-03-29T23:11:52.337911
2018-09-26T16:57:34
2018-09-26T16:57:34
150,460,944
0
0
null
null
null
null
UTF-8
C++
false
false
20,143
h
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2013 Torus Knot Software Ltd Also see acknowledgements in Readme.html You may use this sample code for anything you like, it is not covered by the same license as the rest of the engine. ----------------------------------------------------------------------------- */ #ifndef _WATER_H_ #define _WATER_H_ #include "SdkSample.h" #include "OgreBillboardParticleRenderer.h" #include "WaterMesh.h" #include <iostream> using namespace Ogre; using namespace OgreBites; // Mesh stuff #define MESH_NAME "WaterMesh" #define ENTITY_NAME "WaterEntity" #define MATERIAL_PREFIX "Examples/Water" #define MATERIAL_NAME "Examples/Water0" #define COMPLEXITY 64 // watch out - number of polys is 2*ACCURACY*ACCURACY ! #define PLANE_SIZE 3000.0f #define CIRCLES_MATERIAL "Examples/Water/Circles" void prepareCircleMaterial() { char *bmap = new char[256 * 256 * 4] ; memset(bmap, 127, 256 * 256 * 4); for(int b=0;b<16;b++) { int x0 = b % 4 ; int y0 = b >> 2 ; Real radius = 4.0f + 1.4 * (float) b ; for(int x=0;x<64;x++) { for(int y=0;y<64;y++) { Real dist = Math::Sqrt((x-32)*(x-32)+(y-32)*(y-32)); // 0..ca.45 dist = fabs(dist -radius -2) / 2.0f ; dist = dist * 255.0f; if (dist>255) dist=255 ; int colour = 255-(int)dist ; colour = (int)( ((Real)(15-b))/15.0f * (Real) colour ); bmap[4*(256*(y+64*y0)+x+64*x0)+0]=colour ; bmap[4*(256*(y+64*y0)+x+64*x0)+1]=colour ; bmap[4*(256*(y+64*y0)+x+64*x0)+2]=colour ; bmap[4*(256*(y+64*y0)+x+64*x0)+3]=colour ; } } } DataStreamPtr imgstream(new MemoryDataStream(bmap, 256 * 256 * 4)); //~ Image img; //~ img.loadRawData( imgstream, 256, 256, PF_A8R8G8B8 ); //~ TextureManager::getSingleton().loadImage( CIRCLES_MATERIAL , img ); TextureManager::getSingleton().loadRawData(CIRCLES_MATERIAL, ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, imgstream, 256, 256, PF_A8R8G8B8); MaterialPtr material = MaterialManager::getSingleton().create( CIRCLES_MATERIAL, ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); TextureUnitState *texLayer = material->getTechnique(0)->getPass(0)->createTextureUnitState( CIRCLES_MATERIAL ); texLayer->setTextureAddressingMode( TextureUnitState::TAM_CLAMP ); material->setSceneBlending( SBT_ADD ); material->setDepthWriteEnabled( false ) ; material->load(); // finished with bmap so release the memory delete [] bmap; } /* =========================================================================*/ /* WaterCircle class */ /* =========================================================================*/ #define CIRCLE_SIZE 500.0 #define CIRCLE_TIME 0.5f class WaterCircle { private: String name ; SceneNode *node ; MeshPtr mesh ; SubMesh *subMesh ; Entity *entity ; Real tm ; SceneManager *sceneMgr ; static bool first ; // some buffers shared by all circles static HardwareVertexBufferSharedPtr posnormVertexBuffer ; static HardwareIndexBufferSharedPtr indexBuffer ; // indices for 2 faces static HardwareVertexBufferSharedPtr *texcoordsVertexBuffers ; void _prepareMesh() { int i,texLvl ; mesh = MeshManager::getSingleton().createManual(name, ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME) ; subMesh = mesh->createSubMesh(); subMesh->useSharedVertices=false; int numVertices = 4 ; if (first) { // first Circle, create some static common data first = false ; // static buffer for position and normals posnormVertexBuffer = HardwareBufferManager::getSingleton().createVertexBuffer( 6*sizeof(float), // size of one vertex data 4, // number of vertices HardwareBuffer::HBU_STATIC_WRITE_ONLY, // usage false); // no shadow buffer float *posnormBufData = (float*) posnormVertexBuffer-> lock(HardwareBuffer::HBL_DISCARD); for(i=0;i<numVertices;i++) { posnormBufData[6*i+0]=((Real)(i%2)-0.5f)*CIRCLE_SIZE; // pos X posnormBufData[6*i+1]=0; // pos Y posnormBufData[6*i+2]=((Real)(i/2)-0.5f)*CIRCLE_SIZE; // pos Z posnormBufData[6*i+3]=0 ; // normal X posnormBufData[6*i+4]=1 ; // normal Y posnormBufData[6*i+5]=0 ; // normal Z } posnormVertexBuffer->unlock(); // static buffers for 16 sets of texture coordinates texcoordsVertexBuffers = new HardwareVertexBufferSharedPtr[16]; for(texLvl=0;texLvl<16;texLvl++) { texcoordsVertexBuffers[texLvl] = HardwareBufferManager::getSingleton().createVertexBuffer( 2*sizeof(float), // size of one vertex data numVertices, // number of vertices HardwareBuffer::HBU_STATIC_WRITE_ONLY, // usage false); // no shadow buffer float *texcoordsBufData = (float*) texcoordsVertexBuffers[texLvl]-> lock(HardwareBuffer::HBL_DISCARD); float x0 = (Real)(texLvl % 4) * 0.25 ; float y0 = (Real)(texLvl / 4) * 0.25 ; y0 = 0.75-y0 ; // upside down for(i=0;i<4;i++) { texcoordsBufData[i*2 + 0]= x0 + 0.25 * (Real)(i%2) ; texcoordsBufData[i*2 + 1]= y0 + 0.25 * (Real)(i/2) ; } texcoordsVertexBuffers[texLvl]->unlock(); } // Index buffer for 2 faces unsigned short faces[6] = {2,1,0, 2,3,1}; indexBuffer = HardwareBufferManager::getSingleton().createIndexBuffer( HardwareIndexBuffer::IT_16BIT, 6, HardwareBuffer::HBU_STATIC_WRITE_ONLY); indexBuffer->writeData(0, indexBuffer->getSizeInBytes(), faces, true); // true? } // Initialize vertex data subMesh->vertexData = new VertexData(); subMesh->vertexData->vertexStart = 0; subMesh->vertexData->vertexCount = 4; // first, set vertex buffer bindings VertexBufferBinding *vbind = subMesh->vertexData->vertexBufferBinding ; vbind->setBinding(0, posnormVertexBuffer); vbind->setBinding(1, texcoordsVertexBuffers[0]); // now, set vertex buffer declaration VertexDeclaration *vdecl = subMesh->vertexData->vertexDeclaration ; vdecl->addElement(0, 0, VET_FLOAT3, VES_POSITION); vdecl->addElement(0, 3*sizeof(float), VET_FLOAT3, VES_NORMAL); vdecl->addElement(1, 0, VET_FLOAT2, VES_TEXTURE_COORDINATES); // Initialize index data subMesh->indexData->indexBuffer = indexBuffer; subMesh->indexData->indexStart = 0; subMesh->indexData->indexCount = 6; // set mesh bounds AxisAlignedBox circleBounds(-CIRCLE_SIZE/2.0f, 0, -CIRCLE_SIZE/2.0f, CIRCLE_SIZE/2.0f, 0, CIRCLE_SIZE/2.0f); mesh->_setBounds(circleBounds); mesh->load(); mesh->touch(); } public: int lvl ; void setTextureLevel() { subMesh->vertexData->vertexBufferBinding->setBinding(1, texcoordsVertexBuffers[lvl]); } WaterCircle(SceneManager *mgr, const String& inName, Real x, Real y) { sceneMgr = mgr; name = inName ; _prepareMesh(); node = static_cast<SceneNode*> (sceneMgr->getRootSceneNode()->createChild(name)); node->translate(x*(PLANE_SIZE/COMPLEXITY), 10, y*(PLANE_SIZE/COMPLEXITY)); entity = sceneMgr->createEntity(name, name); entity->setMaterialName(CIRCLES_MATERIAL); node->attachObject(entity); tm = 0 ; lvl = 0 ; setTextureLevel(); } ~WaterCircle() { MeshManager::getSingleton().remove(mesh->getHandle()); sceneMgr->destroyEntity(entity->getName()); static_cast<SceneNode*> (sceneMgr->getRootSceneNode())->removeChild(node->getName()); } void animate(Real timeSinceLastFrame) { int lastlvl = lvl ; tm += timeSinceLastFrame ; lvl = (int) ( (Real)(tm)/CIRCLE_TIME * 16 ); if (lvl<16 && lvl!=lastlvl) { setTextureLevel(); } } static void clearStaticBuffers() { posnormVertexBuffer = HardwareVertexBufferSharedPtr() ; indexBuffer = HardwareIndexBufferSharedPtr() ; if(texcoordsVertexBuffers != NULL) { for(int i=0;i<16;i++) { texcoordsVertexBuffers[i] = HardwareVertexBufferSharedPtr() ; } delete [] texcoordsVertexBuffers; texcoordsVertexBuffers = NULL; } first = true; } } ; bool WaterCircle::first = true ; HardwareVertexBufferSharedPtr WaterCircle::posnormVertexBuffer = HardwareVertexBufferSharedPtr() ; HardwareIndexBufferSharedPtr WaterCircle::indexBuffer = HardwareIndexBufferSharedPtr() ; HardwareVertexBufferSharedPtr* WaterCircle::texcoordsVertexBuffers = 0 ; class _OgreSampleClassExport Sample_Water : public SdkSample { public: Sample_Water(): waterMesh(0) { mInfo["Title"] = "Water"; mInfo["Description"] = "A demo of a simple water effect."; mInfo["Thumbnail"] = "thumb_water.png"; mInfo["Category"] = "Environment"; } virtual void _shutdown() { // cleanup all allocated circles for(unsigned i = 0 ; i < circles.size() ; i++) { delete (circles[i]); } circles.clear(); SdkSample::_shutdown(); } protected: WaterMesh *waterMesh ; Entity *waterEntity ; AnimationState* mAnimState; SceneNode *headNode ; Overlay* waterOverlay ; ParticleSystem *particleSystem ; ParticleEmitter *particleEmitter ; SceneManager *sceneMgr ; // Just override the mandatory create scene method void setupContent(void) { sceneMgr = mSceneMgr ; // Set ambient light mSceneMgr->setAmbientLight(ColourValue(0.75, 0.75, 0.75)); // Create a light Light* l = mSceneMgr->createLight("MainLight"); // Accept default settings: point light, white diffuse, just set position // NB I could attach the light to a SceneNode if I wanted it to move automatically with // other objects, but I don't l->setPosition(200,300,100); // Create water mesh and entity waterMesh = new WaterMesh(MESH_NAME, PLANE_SIZE, COMPLEXITY); waterEntity = mSceneMgr->createEntity(ENTITY_NAME, MESH_NAME); //~ waterEntity->setMaterialName(MATERIAL_NAME); SceneNode *waterNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); waterNode->attachObject(waterEntity); // Add a head, give it it's own node headNode = waterNode->createChildSceneNode(); Entity *ent = mSceneMgr->createEntity("head", "ogrehead.mesh"); headNode->attachObject(ent); // Make sure the camera track this node //~ mCamera->setAutoTracking(true, headNode); // Create the camera node, set its position & attach camera SceneNode* camNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); camNode->translate(0, 500, PLANE_SIZE); camNode->yaw(Degree(-45)); camNode->attachObject(mCamera); // Create light node SceneNode* lightNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); lightNode->attachObject(l); // set up spline animation of light node Animation* anim = mSceneMgr->createAnimation("WaterLight", 20); NodeAnimationTrack *track ; TransformKeyFrame *key ; // create a random spline for light track = anim->createNodeTrack(0, lightNode); track->createNodeKeyFrame(0); for(int ff=1;ff<=19;ff++) { key = track->createNodeKeyFrame(ff); Vector3 lpos ( rand()%(int)PLANE_SIZE , //- PLANE_SIZE/2, rand()%300+100, rand()%(int)PLANE_SIZE //- PLANE_SIZE/2 ); key->setTranslate(lpos); } track->createNodeKeyFrame(20); // Create a new animation state to track this mAnimState = mSceneMgr->createAnimationState("WaterLight"); mAnimState->setEnabled(true); // Put in a bit of fog for the hell of it //mSceneMgr->setFog(FOG_EXP, ColourValue::White, 0.0002); // Let there be rain particleSystem = mSceneMgr->createParticleSystem("rain", "Examples/Water/Rain"); particleEmitter = particleSystem->getEmitter(0); particleEmitter->setEmissionRate(0); SceneNode* rNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); rNode->translate(PLANE_SIZE/2.0f, 3000, PLANE_SIZE/2.0f); rNode->attachObject(particleSystem); // Fast-forward the rain so it looks more natural particleSystem->fastForward(20); // It can't be set in .particle file, and we need it ;) static_cast<BillboardParticleRenderer*>(particleSystem->getRenderer())->setBillboardOrigin(BBO_BOTTOM_CENTER); prepareCircleMaterial(); setupControls(); #if OGRE_PLATFORM != OGRE_PLATFORM_APPLE_IOS setDragLook(true); #endif timeoutDelay = 0.0f; } #define PANEL_WIDTH 200 void setupControls() { mTrayMgr->createLabel(TL_TOPLEFT, "GeneralLabel", "General", PANEL_WIDTH); mTrayMgr->createCheckBox(TL_TOPLEFT, "FakeNormalsCB", "Fake normals", PANEL_WIDTH); mTrayMgr->createCheckBox(TL_TOPLEFT, "SkyboxCB", "Skybox", PANEL_WIDTH); mTrayMgr->createThickSlider(TL_TOPLEFT, "HeadDepthSlider", "Head Depth", PANEL_WIDTH, 80, 1, 3, 50)->setValue(2.0f); SelectMenu* waterMaterial = mTrayMgr->createThickSelectMenu(TL_TOPLEFT, "WaterMaterialMenu", "Water material", PANEL_WIDTH, 9); for (size_t i = 0; i < 9; i++) { waterMaterial->addItem(MATERIAL_PREFIX + StringConverter::toString(i)); } waterMaterial->selectItem(8); mTrayMgr->createLabel(TL_TOPLEFT, "RainLabel", "Rain : [Space]", PANEL_WIDTH); mTrayMgr->createLabel(TL_TOPRIGHT, "AdvancedLabel", "Advanced", PANEL_WIDTH); mTrayMgr->createThickSlider(TL_TOPRIGHT, "RippleSpeedSlider", "Ripple Speed", PANEL_WIDTH, 80, 0, 2, 50)->setValue(0.3, false); mTrayMgr->createThickSlider(TL_TOPRIGHT, "DistanceSlider", "Distance", PANEL_WIDTH, 80, 0.1, 5.0, 50)->setValue(0.4, false); mTrayMgr->createThickSlider(TL_TOPRIGHT, "ViscositySlider", "Viscosity", PANEL_WIDTH, 80, 0, 1, 50)->setValue(0.05, false); mTrayMgr->createThickSlider(TL_TOPRIGHT, "FrameTimeSlider", "FrameTime", PANEL_WIDTH, 80, 0, 1, 61)->setValue(0.13, false); mTrayMgr->showCursor(); } void cleanupContent() { // If when you finish the application is still raining there // are water circles that are still being processed unsigned int activeCircles = (unsigned int)this->circles.size (); // Kill the active water circles for (unsigned int i = 0; i < activeCircles; i++) delete (this->circles[i]); delete waterMesh; waterMesh = 0; WaterCircle::clearStaticBuffers(); } protected: Real timeoutDelay ; #define RAIN_HEIGHT_RANDOM 5 #define RAIN_HEIGHT_CONSTANT 5 typedef vector<WaterCircle*>::type WaterCircles ; WaterCircles circles ; void processCircles(Real timeSinceLastFrame) { for(unsigned int i=0;i<circles.size();i++) { circles[i]->animate(timeSinceLastFrame); } bool found ; do { found = false ; for(WaterCircles::iterator it = circles.begin() ; it != circles.end(); ++it) { if ((*it)->lvl>=16) { delete (*it); circles.erase(it); found = true ; break ; } } } while (found) ; } void processParticles() { static int pindex = 0 ; ParticleIterator pit = particleSystem->_getIterator() ; while(!pit.end()) { Particle *particle = pit.getNext(); Vector3 ppos = particle->position; if (ppos.y<=0 && particle->timeToLive>0) { // hits the water! // delete particle particle->timeToLive = 0.0f; // push the water float x = ppos.x / PLANE_SIZE * COMPLEXITY ; float y = ppos.z / PLANE_SIZE * COMPLEXITY ; float h = rand() % RAIN_HEIGHT_RANDOM + RAIN_HEIGHT_CONSTANT ; if (x<1) x=1 ; if (x>COMPLEXITY-1) x=COMPLEXITY-1; if (y<1) y=1 ; if (y>COMPLEXITY-1) y=COMPLEXITY-1; waterMesh->push(x,y,-h) ; WaterCircle *circle = new WaterCircle(mSceneMgr, "Circle#"+StringConverter::toString(pindex++), x, y); circles.push_back(circle); } } } void sliderMoved(Slider* slider) { if (slider->getName() == "HeadDepthSlider") { headDepth = slider->getValue(); } else if (slider->getName() == "RippleSpeedSlider") { waterMesh->PARAM_C = slider->getValue(); } else if (slider->getName() == "DistanceSlider") { waterMesh->PARAM_D = slider->getValue(); } else if (slider->getName() == "ViscositySlider") { waterMesh->PARAM_U = slider->getValue(); } else if (slider->getName() == "FrameTimeSlider") { waterMesh->PARAM_T = slider->getValue(); } } void checkBoxToggled(CheckBox* checkBox) { if (checkBox->getName() == "FakeNormalsCB") { waterMesh->useFakeNormals = checkBox->isChecked(); } else if (checkBox->getName() == "SkyboxCB") { sceneMgr->setSkyBox(checkBox->isChecked(), "Examples/SceneSkyBox2"); } } void itemSelected(SelectMenu* menu) { //Only one menu in this demo const String& materialName = menu->getSelectedItem(); MaterialPtr material = MaterialManager::getSingleton().getByName(materialName); if (material.isNull()) { OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "Material "+materialName+"doesn't exist!", "WaterListener::updateMaterial"); } waterEntity->setMaterialName(materialName); } /** Head animation */ Real headDepth ; void animateHead(Real timeSinceLastFrame) { // sine track? :) static double sines[4] = {0,100,200,300}; static const double adds[4] = {0.3,-1.6,1.1,0.5}; static Vector3 oldPos = Vector3::UNIT_Z; for(int i=0;i<4;i++) { sines[i]+=adds[i]*timeSinceLastFrame; } Real tx = ((sin(sines[0]) + sin(sines[1])) / 4 + 0.5 ) * (float)(COMPLEXITY-2) + 1 ; Real ty = ((sin(sines[2]) + sin(sines[3])) / 4 + 0.5 ) * (float)(COMPLEXITY-2) + 1 ; waterMesh->push(tx,ty, -headDepth); Real step = PLANE_SIZE / COMPLEXITY ; headNode->resetToInitialState(); headNode->scale(3,3,3); Vector3 newPos = Vector3(step*tx, headDepth, step*ty); Vector3 diffPos = newPos - oldPos ; Quaternion headRotation = Vector3::UNIT_Z.getRotationTo(diffPos); oldPos = newPos ; headNode->translate(newPos); headNode->rotate(headRotation); } public: bool frameRenderingQueued(const FrameEvent& evt) { if( SdkSample::frameRenderingQueued(evt) == false ) return false; mAnimState->addTime(evt.timeSinceLastFrame); // rain processCircles(evt.timeSinceLastFrame); if(mInputContext.mKeyboard) { particleEmitter->setEmissionRate(mInputContext.mKeyboard->isKeyDown(OIS::KC_SPACE) ? 20.0f : 0.0f); } processParticles(); timeoutDelay-=evt.timeSinceLastFrame ; if (timeoutDelay<=0) timeoutDelay = 0; animateHead(evt.timeSinceLastFrame); waterMesh->updateMesh(evt.timeSinceLastFrame); return true; } }; #endif
[ "paul.sujoy.ju@gmail.com" ]
paul.sujoy.ju@gmail.com
6ac45a88eacc59049a80455b8e135115d898e1ce
37e6f1a2a71809ab873eca160901e9ab43177704
/RayTracer/RayTracer/RayTracer.cpp
63163d3f70364dd1fc6fa59ffcb12ecedb785b5c
[]
no_license
mcmlevi/Portfolio_Levi_de_koning
1a1868c65917f59e0ded88bba900bd8a8ddadc57
9ed1797c96051163ba3b5703d7ee0f1193af9a0f
refs/heads/main
2023-04-28T21:53:28.011662
2021-05-27T20:29:45
2021-05-27T20:29:45
371,030,224
1
0
null
null
null
null
UTF-8
C++
false
false
23,087
cpp
#include "RayTracer.h" #include <cassert> #include "Utility.h" #include "Light.h" #include "clock.h" #include "Mat4x4.h" #include <thread> #include "STB/stb_image_write.h" #pragma warning(push) #pragma warning(disable: 6386) #pragma warning(disable: 26451) constexpr uint8_t MASK_moveLeft{ 0b0000'0001 }; // represents bit 0 constexpr uint8_t MASK_moveRight{ 0b0000'0010 }; // represents bit 1 constexpr uint8_t MASK_moveUp{ 0b0000'0100 }; // represents bit 2 constexpr uint8_t MASK_moveDown{ 0b0000'1000 }; // represents bit 3 constexpr uint8_t MASK_moveForward{ 0b0001'0000 }; // represents bit 4 constexpr uint8_t MASK_moveBack{ 0b0010'0000 }; // represents bit 5 constexpr uint8_t MASK_rotLeft{ 0b0000'0001 }; // represents bit 0 constexpr uint8_t MASK_rotRight{ 0b0000'0010 }; // represents bit 1 constexpr uint8_t MASK_rotUp{ 0b0000'0100 }; // represents bit 2 constexpr uint8_t MASK_rotDown{ 0b0000'1000 }; // represents bit 3 constexpr uint8_t MASK_rotTiltLeft{ 0b0001'0000 }; // represents bit 4 constexpr uint8_t MASK_rotTiltRight{ 0b0010'0000 }; // represents bit 5 RayTracer::RayTracer(int width, int height, const Camera& camera) :SFML(width, height), m_camera(camera), m_world(m_camera) { m_camera.m_highResHeight = static_cast<float>(SFML.m_highResHeight); m_camera.m_highResWidth = static_cast<float>(SFML.m_highResWidth); } std::atomic<int32_t> jobsLeft{ -4 }; Status* threadStatuses; Job** joblist; Job** highResJobList; float angle{}; void HandleJob(int threadID, sf::Uint8*& pixels, const int width, RayTracer& tracer) { while (threadStatuses[threadID] != Status::EXIT) { while (jobsLeft >= 0) { threadStatuses[threadID] = Status::WORKING; int jobID{ jobsLeft-- }; if (jobID < 0) { break; } Job* currentJob{ }; if (tracer.screenShotMode == false) currentJob = joblist[abs(jobID)]; else currentJob = highResJobList[abs(jobID)]; assert(currentJob != nullptr); for (int y = currentJob->yPos; y < currentJob->yPos + currentJob->tileSize; ++y) { for (int x = currentJob->xPos; x < currentJob->xPos + currentJob->tileSize; ++x) { Color color = tracer.trace(tracer.m_camera.getRayAt(y, x, tracer.screenShotMode), 0); if (tracer.screenShotMode == false) { pixels[(y) * 4 * width + x * 4] = static_cast<sf::Uint8>(color.clamp(color.R) * 255); pixels[(y) * 4 * width + x * 4 + 1] = static_cast<sf::Uint8>(color.clamp(color.G) * 255); pixels[(y) * 4 * width + x * 4 + 2] = static_cast<sf::Uint8>(color.clamp(color.B) * 255); pixels[(y) * 4 * width + x * 4 + 3] = 255; } else { unsigned highResWidth{ tracer.SFML.m_highResWidth }; tracer.SFML.pixelBuffer[(y) * 4 * highResWidth + x * 4] += color.clamp(color.R); tracer.SFML.pixelBuffer[(y) * 4 * highResWidth + x * 4 + 1] += color.clamp(color.G); tracer.SFML.pixelBuffer[(y) * 4 * highResWidth + x * 4 + 2] += color.clamp(color.B); tracer.SFML.pixelBuffer[(y) * 4 * highResWidth + x * 4 + 3] += 255; tracer.SFML.highResPixels[(y) * 4 * highResWidth + x * 4] = static_cast<sf::Uint8>((tracer.SFML.pixelBuffer[(y) * 4 * highResWidth + x * 4] / static_cast<float>(tracer.frameCountForPixelBuffer - 1)) * 255); tracer.SFML.highResPixels[(y) * 4 * highResWidth + x * 4 + 1] = static_cast<sf::Uint8>((tracer.SFML.pixelBuffer[(y) * 4 * highResWidth + x * 4 + 1] / static_cast<float>(tracer.frameCountForPixelBuffer -1)) * 255); tracer.SFML.highResPixels[(y) * 4 * highResWidth + x * 4 + 2] = static_cast<sf::Uint8>((tracer.SFML.pixelBuffer[(y) * 4 * highResWidth + x * 4 + 2] / static_cast<float>(tracer.frameCountForPixelBuffer - 1)) * 255); tracer.SFML.highResPixels[(y) * 4 * highResWidth + x * 4 + 3] = 255; } } } } threadStatuses[threadID] = Status::DONE; } } void RayTracer::RenderImage() { int height{ SFML.m_height }; int width{ SFML.m_width }; numOfThreadsAvailable = std::thread::hardware_concurrency(); threadStatuses = new Status[numOfThreadsAvailable]{ Status::WAITING }; std::thread** threads = new std::thread * [numOfThreadsAvailable] {nullptr}; for (unsigned i = 0; i < numOfThreadsAvailable; ++i) { threads[i] = new std::thread(HandleJob, i, std::ref(SFML.pixels), width, std::ref(*this)); } //char result[10]; int tileSize{ 8 }; int numOfJobs{ static_cast<int>((width * height) / (tileSize * tileSize)) }; int numOfHighResJobs{ static_cast<int>((SFML.m_highResWidth * SFML.m_highResHeight) / (tileSize * tileSize)) }; int currentJob{ 0 }; joblist = new Job * [numOfJobs] {nullptr}; highResJobList = new Job * [numOfHighResJobs] {nullptr}; for (int y = 0; y < height; y += tileSize) { for (int x = 0; x < width; x += tileSize) { joblist[currentJob] = new Job(x, y, tileSize); ++currentJob; } } int currentHighResJob{ 0 }; for (unsigned y = 0; y < SFML.m_highResHeight; y += tileSize) { for (unsigned x = 0; x < SFML.m_highResWidth; x += tileSize) { highResJobList[currentHighResJob] = new Job(x, y, tileSize); ++currentHighResJob; } } //preCalculateNextFrame(); while (exitApplication == false) { Clock timer{}; deltaTime = clamp(deltaTime, 0.f, 1000.f / 15.f); //m_camera.m_cameraOrigin = { cosf(angle) * 10.f, 1.f,sinf(angle) * 10.f }; //m_camera.updateViewMatrix(); beginTick(); m_world.buildBVH(); if (brakeOnTraceBegin) { sf::Vector2i pos{ sf::Mouse::getPosition(SFML.getWindow()) }; Ray debugRay(m_camera.getRayAt(pos.y, pos.x)); Color debugColor = trace(debugRay, 0); continue; } //printf("Layers %ld \n", m_world.layers); for (unsigned i = 0; i < numOfThreadsAvailable; ++i) threadStatuses[i] = Status::GO; if (screenShotMode == false) jobsLeft = numOfJobs - 1; else jobsLeft = numOfHighResJobs - 1; #if(PRINTINFO) printf("Time taken %f \n", timer.endTimer()); printf("Average calculations per query: %llu \n", m_world.numOfTests / m_world.timesQueried); printf("Average number of intersection tests for early out %llu \n", m_world.earllyOutTests / m_world.timesQueriedEarlyOut); printf("Number of BVH layers %i \n", m_world.numOfLayers); #endif while (true) { bool done{ true }; for (unsigned i = 0; i < numOfThreadsAvailable; ++i) { if (threadStatuses[i] != Status::DONE || jobsLeft >= 0) done = false; } if (done) break; } //SFML.getWindow().setTitle(windowName + "100"); deltaTime = static_cast<float>(timer.endTimer() * 1000.f); frameTimeCounter += deltaTime; ++numberOfFrames; endTick(); if (screenShotMode) ++frameCountForPixelBuffer; } for (int i = 0; i < numOfJobs; ++i) { delete joblist[i]; joblist[i] = nullptr; } } //Light light{ { 3.f,20.f,10.f } ,{1.f,1.f,1.f,1.f} }; Color RayTracer::trace(Ray ray, int depth) { if (brakeOnTraceBegin) { brakeOnTraceBegin = false; __debugbreak(); } Color visualize{}; if (visualizeBVH) visualize = m_world.visualizeBox(ray); if (depth > maxDepth) { return { 0.f,0.f,0.f }; //return { 12.f / 255.f,40.f / 255.f,120.f / 255.f }; } Shape* closestShape{ nullptr }; Vec3f intersectPoint{}; // Get the closest object or if we hit nothing set the background color if (getClosestObject(ray, intersectPoint, closestShape) == false) { if (visualizeBVH) { if (visualize.R > 0.f || visualize.G > 0.f || visualize.B > 0.f) return visualize; } return _background; } Shape* workingShape{ nullptr }; closestShape->IntersectionTest(ray, intersectPoint, workingShape); Vec3f normalVec{ closestShape->calculateNormal(intersectPoint) }; normalVec.normalize(); Color colorToPrint{}; if (visualizeNormals == false) { colorToPrint = closestShape->getColor(intersectPoint); // Calculate shadows colorToPrint = calculateShadows(intersectPoint, normalVec, closestShape, colorToPrint, ray.m_orgin); // Reflection + Refraction can be a maximum of 1 float fresnel{ 0.f }; Color refractionColor = calculateRefraction(ray, intersectPoint, normalVec, closestShape, depth, fresnel); colorToPrint += refractionColor; if (closestShape->m_mat.reflectiveIndex > 0.f) { // Calculate reflections Color reflectionColor{ calulateReflection(ray.m_direction, intersectPoint, normalVec, closestShape, depth) }; reflectionColor = reflectionColor * closestShape->m_mat.reflectiveIndex; colorToPrint += reflectionColor; } } else colorToPrint = { normalVec.m_x * 0.5f + 0.5f ,normalVec.m_y * 0.5f + 0.5f,normalVec.m_z < 0 ? normalVec.m_z * -1.f * 0.5f + 0.5f : normalVec.m_z * 0.5f + 0.5f }; if (visualizeBVH) { if (depth == 0) colorToPrint += visualize; } // Clamp the color colorToPrint.clamp(); return colorToPrint; } Vec3f RayTracer::reflect(const Vec3f& I, const Vec3f& N) { return I - 2.f * I.dot(N)* N; } Color RayTracer::calculateShadows(const Vec3f& intersectPoint, const Vec3f& normalVector, const Shape* closestShape, const Color& beginColor, const Vec3f& viewLocation) { assert(closestShape != nullptr); Color colorResult{}; Vec3f Lookingat{ viewLocation - intersectPoint }; Lookingat.normalize(); for (int i = 0; i < m_world.scene->m_numberOfLights; ++i) { Vec3f lightPos{ m_world.scene->lights[i]->m_lightLocation }; if (screenShotMode) { float offsetX = cosf(static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (2 * M_PI))))* m_world.scene->lights[i]->m_area; float offsetZ = sinf(static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (2 * M_PI))))* m_world.scene->lights[i]->m_area; lightPos.m_x += offsetX; lightPos.m_z += offsetZ; } Vec3f lightDirection{ lightPos - (intersectPoint) }; float lambert{ normalVector.dot(lightDirection) }; if (lambert > epsilon) { float result{}; float attenuation{ lightDirection.lenght2() }; lightDirection.normalize(); Ray shadowRay{ lightDirection ,intersectPoint + normalVector * 1e-4f ,{} }; bool lightVisable{ true }; float maxDistance{ (m_world.scene->lights[i]->m_lightLocation - shadowRay.m_orgin).lenght2() }; if (m_world.getAIntersection(shadowRay, maxDistance)) { lightVisable = false; } Vec3f Half{ Lookingat + lightDirection }; Half.normalize(); float specular{ powf(max(0.f, (Half.dot(normalVector))),200) }; result = (lightVisable * (m_world.scene->lights[i]->m_lightIntensity / attenuation) * lambert * closestShape->m_mat.albedo); colorResult += (m_world.scene->lights[i]->m_lightColor * result); // Specular light colorResult += m_world.scene->lights[i]->m_lightColor * specular * (m_world.scene->lights[i]->m_lightIntensity / attenuation) * lightVisable; } } // Ambient lighting colorResult += Color{ 1.f,1.f,1.f } *0.1f; return { beginColor.R * colorResult.R , beginColor.G * colorResult.G,beginColor.B * colorResult.B }; } Color RayTracer::calulateReflection(const Vec3f& rayDirection, const Vec3f& intersectPoint, const Vec3f& normalVector, const Shape* closestShape, int depth) { assert(closestShape != nullptr); if (closestShape->m_mat.reflectiveIndex > 0.f) { bool outside{ rayDirection.dot(normalVector) < 0 }; Vec3f reflectRayDirection{ reflect(rayDirection,normalVector) }; reflectRayDirection.normalize(); Vec3f ReflectRayOrgin{ outside ? intersectPoint + normalVector * 1e-4f : intersectPoint - normalVector * 1e-4f }; Ray reflectiveRay{ reflectRayDirection,ReflectRayOrgin,{} }; Color test = (trace(reflectiveRay, depth + 1)); if (closestShape->m_mat.reflectiveIndex > 0) test = test * closestShape->m_mat.reflectiveIndex; else test = _background; return test; } else return Color{ 0.f,0.f,0.f }; } Vec3f RayTracer::refract(const Ray& ray, const Vec3f& normal, const Shape* closestShape) { float cosi = clamp(-1.f, 1.f, ray.m_direction.dot(normal)); float etai = 1.f, etat = closestShape->m_mat.refractionIndex; Vec3f n = normal; if (cosi < 0) { cosi = -cosi; } else { swap(etai, etat); n = -1.f * normal; } float eta = etai / etat; float k = 1.f - eta * eta * (1.f - cosi * cosi); return k < 0.f ? 0.f : eta * ray.m_direction + (eta * cosi - sqrtf(k)) * n; } float RayTracer::Calculatefresnel(const Ray& ray, const Vec3f& normal, const Shape* closestShape) { float cosi = clamp(-1.f, 1.f, ray.m_direction.dot(normal)); float etai = 1.f, etat = closestShape->m_mat.refractionIndex; if (cosi > 0) { swap(etai, etat); } // Compute sini using Snell's law float sint = etai / etat * sqrtf(std::max(0.f, 1.f - cosi * cosi)); // Total internal reflection if (sint >= 1.f) { return 1.f; } else { float cost = sqrtf(std::max(0.f, 1.f - sint * sint)); cosi = fabsf(cosi); float Rs = ((etat * cosi) - (etai * cost)) / ((etat * cosi) + (etai * cost)); float Rp = ((etai * cosi) - (etat * cost)) / ((etai * cosi) + (etat * cost)); return (Rs * Rs + Rp * Rp) / 2.f; } } Color RayTracer::calculateRefraction(const Ray& ray, const Vec3f& intersectPoint, const Vec3f& normalVector, Shape* closestShape, int depth, float& fresnel) { assert(closestShape != nullptr); Color RefractionColor{}; Color ReflectionColor{}; if (closestShape->m_mat.refractionIndex > 0) { fresnel = Calculatefresnel(ray, normalVector, closestShape); bool outside{ ray.m_direction.dot(normalVector) < 0 }; if (fresnel < 1.f ) { // get the transmission Ray Vec3f TransmissionRay{ refract(ray,normalVector,closestShape) }; /* if (TransmissionRay.m_x < epsilon && TransmissionRay.m_x > -epsilon && TransmissionRay.m_y < epsilon && TransmissionRay.m_y > -epsilon && TransmissionRay.m_z < epsilon && TransmissionRay.m_z >-epsilon ) { } else*/ { TransmissionRay.normalize(); // Make the actual refraction Ray Ray refractionRay{ TransmissionRay, outside ? intersectPoint - normalVector * 1e-4f : intersectPoint + normalVector * 1e-4f }; RefractionColor = trace(refractionRay, depth + 1); } } Vec3f reflectionDirection = reflect(ray.m_direction, normalVector).normalize(); Vec3f reflectionRayOrig{ outside ? intersectPoint - normalVector * 1e-4f : intersectPoint + normalVector * 1e-4f }; ReflectionColor = trace(Ray{reflectionDirection,reflectionRayOrig}, depth + 1); return ReflectionColor * fresnel + RefractionColor * (1.f - fresnel); } return { 0.f,0.f,0.f }; } bool RayTracer::getClosestObject(const Ray& ray, Vec3f& intersectPoint, Shape*& closestShape) { closestShape = m_world.queryIntersection(ray, intersectPoint); if (closestShape != nullptr) return true; return false; } void RayTracer::handleInput() { while (SFML.getWindow().pollEvent(event)) { if (sf::Mouse::isButtonPressed(sf::Mouse::Left) && sf::Keyboard::isKeyPressed(sf::Keyboard::LShift)) { brakeOnTraceBegin = true; } if (event.type == sf::Event::KeyReleased) { switch (event.key.code) { case sf::Keyboard::D: moveInfoMASK &= ~MASK_moveRight; break; case sf::Keyboard::A: moveInfoMASK &= ~MASK_moveLeft; break; case sf::Keyboard::W: moveInfoMASK &= ~MASK_moveForward; break; case sf::Keyboard::S: moveInfoMASK &= ~MASK_moveBack; break; case sf::Keyboard::Q: moveInfoMASK &= ~MASK_moveDown; break; case sf::Keyboard::E: moveInfoMASK &= ~MASK_moveUp; break; case sf::Keyboard::Numpad4: rotationInfoMASK &= ~MASK_rotLeft; break; case sf::Keyboard::Numpad6: rotationInfoMASK &= ~MASK_rotRight; break; case sf::Keyboard::Numpad8: rotationInfoMASK &= ~MASK_moveDown; break; case sf::Keyboard::Numpad5: rotationInfoMASK &= ~MASK_moveUp; break; case sf::Keyboard::Numpad7: rotationInfoMASK &= ~MASK_rotTiltLeft; break; case sf::Keyboard::Numpad9: rotationInfoMASK &= ~MASK_rotTiltRight; break; } } if (event.type == sf::Event::KeyPressed) { switch (event.key.code) { case sf::Keyboard::F1: SFML.showInfoText = !SFML.showInfoText; break; case sf::Keyboard::F2: SFML.showStats = !SFML.showStats; break; case sf::Keyboard::F5: { Scenes next = (static_cast<Scenes>(static_cast<int>(m_world.currentScene) - 1)); if (next == Scenes::BEGIN) next = (static_cast<Scenes>(static_cast<int>(Scenes::MAX) - 1)); m_world.loadScene(next, m_camera); break; } case sf::Keyboard::F6: { Scenes next = (static_cast<Scenes>(static_cast<int>(m_world.currentScene) + 1)); if (next == Scenes::MAX) next = (static_cast<Scenes>(static_cast<int>(Scenes::BEGIN) + 1)); m_world.loadScene(next, m_camera); break; } case sf::Keyboard::Add: movementSpeedModifier = clamp(movementSpeedModifier + 0.1f, 0.f, 10.f); break; case sf::Keyboard::Subtract: movementSpeedModifier = clamp(movementSpeedModifier - 0.1f, 0.f, 10.f); break; case sf::Keyboard::PageUp: m_camera.changeFOV(1); break; case sf::Keyboard::PageDown: m_camera.changeFOV(-1); break; case sf::Keyboard::A: moveInfoMASK |= MASK_moveLeft; break; case sf::Keyboard::D: moveInfoMASK |= MASK_moveRight; break; case sf::Keyboard::W: moveInfoMASK |= MASK_moveForward; break; case sf::Keyboard::S: moveInfoMASK |= MASK_moveBack; break; case sf::Keyboard::Q: moveInfoMASK |= MASK_moveDown; break; case sf::Keyboard::E: moveInfoMASK |= MASK_moveUp; break; case sf::Keyboard::Numpad4: rotationInfoMASK |= MASK_rotLeft; break; case sf::Keyboard::Numpad6: rotationInfoMASK |= MASK_rotRight; break; case sf::Keyboard::Numpad8: rotationInfoMASK |= MASK_moveDown; break; case sf::Keyboard::Numpad5: rotationInfoMASK |= MASK_moveUp; break; case sf::Keyboard::Numpad7: rotationInfoMASK |= MASK_rotTiltLeft; break; case sf::Keyboard::Numpad9: rotationInfoMASK |= MASK_rotTiltRight; break; case sf::Keyboard::Numpad1: maxDepth = max(maxDepth - 1, 0); break; case sf::Keyboard::Numpad2: maxDepth = maxDepth + 1; break; case sf::Keyboard::N: visualizeNormals = !visualizeNormals; break; case sf::Keyboard::M: visualizeBVH = !visualizeBVH; break; case sf::Keyboard::Up: m_camera.changeFocalLenght(-0.1f); if (screenShotMode == true) { frameCountForPixelBuffer = 1; memset(SFML.pixelBuffer, 0, SFML.m_highResWidth * SFML.m_highResHeight * 4 * sizeof(float)); } break; case sf::Keyboard::Down: m_camera.changeFocalLenght(0.1f); if (screenShotMode == true) { frameCountForPixelBuffer = 1; memset(SFML.pixelBuffer, 0, SFML.m_highResWidth * SFML.m_highResHeight * 4 * sizeof(float)); } break; case sf::Keyboard::Left: m_camera.changeAppetureSize(-0.001f); if (screenShotMode == true) { frameCountForPixelBuffer = 1; memset(SFML.pixelBuffer, 0, SFML.m_highResWidth* SFML.m_highResHeight * 4 * sizeof(float)); } break; case sf::Keyboard::Right: m_camera.changeAppetureSize(0.001f); if (screenShotMode == true) { frameCountForPixelBuffer = 1; memset(SFML.pixelBuffer, 0, SFML.m_highResWidth* SFML.m_highResHeight * 4 * sizeof(float)); } break; case sf::Keyboard::V: screenShotMode = !screenShotMode; if (screenShotMode == false) { frameCountForPixelBuffer = 1; memset(SFML.pixelBuffer, 0, SFML.m_highResWidth * SFML.m_highResHeight * 4 * sizeof(float)); SFML.getWindow().setSize(sf::Vector2u{ static_cast<unsigned>(SFML.m_width),static_cast<unsigned>(SFML.m_height) }); } else { SFML.getWindow().setSize({ SFML.m_highResWidth, SFML.m_highResHeight }); SFML.getWindow().setPosition({ 0,0 }); } break; case sf::Keyboard::F9: m_world.testDepth += 1; break; case sf::Keyboard::F10: m_world.testDepth = max(m_world.testDepth - 1, 0); break; case sf::Keyboard::Escape: SFML.getWindow().close(); exitApplication = true; for (unsigned i = 0; i < numOfThreadsAvailable; ++i) threadStatuses[i] = Status::EXIT; break; case sf::Keyboard::C: std::string filename{ "screenshots/screenshot" + std::to_string(screenshotIndex) + ".png" }; if(screenShotMode == false) stbi_write_png(filename.c_str(), SFML.m_width, SFML.m_height, 4, static_cast<uint8_t*>(SFML.pixels), SFML.m_width * 4); else stbi_write_png(filename.c_str(), SFML.m_highResWidth, SFML.m_highResHeight, 4, static_cast<uint8_t*>(SFML.highResPixels), SFML.m_highResWidth * 4); ++screenshotIndex; break; } } if (event.type == sf::Event::Closed) { SFML.getWindow().close(); exitApplication = true; for (unsigned i = 0; i < numOfThreadsAvailable; ++i) { threadStatuses[i] = Status::EXIT; } } } } void RayTracer::beginTick() { if (screenShotMode == false) { if ((moveInfoMASK & MASK_moveRight) == MASK_moveRight) m_camera.moveRelative(Vec4f{ 1.f, 0.f, 0.f, 0.f } *(deltaTime * movementSpeed * movementSpeedModifier)); if ((moveInfoMASK & MASK_moveLeft) == MASK_moveLeft) m_camera.moveRelative(Vec4f{ -1.f, 0.f, 0.f, 0.f } *(deltaTime * movementSpeed * movementSpeedModifier)); if ((moveInfoMASK & MASK_moveForward) == MASK_moveForward) m_camera.moveRelative(Vec4f{ 0.f, 0.f, -1.f, 0.f } *deltaTime * movementSpeed * movementSpeedModifier); if ((moveInfoMASK & MASK_moveBack) == MASK_moveBack) m_camera.moveRelative(Vec4f{ 0.f, 0.f, 1.f, 0.f } *deltaTime * movementSpeed * movementSpeedModifier); if ((moveInfoMASK & MASK_moveDown) == MASK_moveDown) m_camera.moveRelative(Vec4f{ 0.f, -1.f, 0.f, 0.f } *deltaTime * movementSpeed * movementSpeedModifier); if ((moveInfoMASK & MASK_moveUp) == MASK_moveUp) m_camera.moveRelative(Vec4f{ 0.f, 1.f, 0.f, 0.f } *deltaTime * movementSpeed * movementSpeedModifier); if ((rotationInfoMASK & MASK_rotLeft) == MASK_rotLeft) m_camera.rotateY(1 * deltaTime * rotationSpeed * rotationSpeedModifier); if ((rotationInfoMASK & MASK_rotRight) == MASK_rotRight) m_camera.rotateY(-1 * deltaTime * rotationSpeed * rotationSpeedModifier); if ((rotationInfoMASK & MASK_rotDown) == MASK_rotDown) m_camera.rotateX(1 * deltaTime * rotationSpeed * rotationSpeedModifier); if ((rotationInfoMASK & MASK_rotUp) == MASK_rotUp) m_camera.rotateX(-1 * deltaTime * rotationSpeed * rotationSpeedModifier); if ((rotationInfoMASK & MASK_rotTiltLeft) == MASK_rotTiltLeft) m_camera.rotateZ(1 * deltaTime * rotationSpeed * rotationSpeedModifier); if ((rotationInfoMASK & MASK_rotTiltRight) == MASK_rotTiltRight) m_camera.rotateZ(-1 * deltaTime * rotationSpeed * rotationSpeedModifier); m_world.scene->tick(deltaTime); } } void RayTracer::endTick() { m_world.scene->endTick(deltaTime); SFML.setStats(static_cast<float>(frameTimeCounter / numberOfFrames), m_camera, movementSpeedModifier, maxDepth, visualizeNormals, m_world.currentScene, visualizeBVH, m_world.testDepth, screenShotMode, m_camera.getFocalLenght(), m_camera.getApeture()); if (frameTimeCounter > 1000) { frameTimeCounter = 0; numberOfFrames = 0; } SFML.updateImage(); SFML.updateWindow(screenShotMode); m_world.clearBVH(); //SFML.lockWindow(); handleInput(); } #pragma warning(pop)
[ "39926733+mcmlevi@users.noreply.github.com" ]
39926733+mcmlevi@users.noreply.github.com
b6947edc933ee3f12cbd5888d905975797e931dd
5dcb9f1f256def4ec4916544989cc47381826dae
/1. Line Following Robot/Final codes/pid/pid2/pid2.ino
05650f1fcf3d56d03aa40696f2a0c5904a20828f
[]
no_license
always186/Btech-Projects
55122183ae9244b12ff8eef6db0cc1bbe2cda16a
cd335bba479b1e1d55c1796febefc97419db5e23
refs/heads/master
2020-04-01T10:12:13.054040
2017-11-29T13:23:33
2017-11-29T13:23:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,012
ino
#include <PID_v1.h> //INPUT PINS const int ls=A0;//pins on which sensors have been connected const int ms=A1; const int rs=A2; int max_speed=255, right_speed, left_speed ; double Setpoint=0; long sensors_average; long sensors_sum; double Intput; double Output; long a[3] = {0, 0, 0}; //OUTPUT PINS const int ml1=5; const int ml2=2; const int mr1=3; const int mr2=4; double kp = 5.0; double ki = 0.0; double kd = 0.0; PID myPID(&Intput, &Output, &Setpoint, kp, ki, kd, DIRECT); void setup() { Serial.begin(9600); pinMode(ls,INPUT); pinMode(ms,INPUT); pinMode(rs,INPUT); pinMode(ml1,OUTPUT); pinMode(ml2,OUTPUT); pinMode(mr1,OUTPUT); pinMode(mr2,OUTPUT); Serial.println(" STARTING SETUP"); long st = millis(); while(millis() - st < 3000) //through this loop we are determining the setpoint for 3s { sensors_read(); if(Intput > Setpoint) Setpoint=Intput; } Serial.print("Setpoint ="); Serial.print(Setpoint); Serial.println(" "); Serial.println("SETUP DONE"); myPID.SetOutputLimits(-255, 255); myPID.SetSampleTime(10); //Determines how often the PID algorithm evaluates myPID.SetMode(AUTOMATIC); } void loop() { sensors_read(); //Reads sensor values and computes sensor sum and weighted average myPID.SetTunings(kp, ki, kd); myPID.Compute(); calc_turn(); //Computes the error to be corrected motor_drive(); //Sends PWM signals to the motors } void sensors_read() { sensors_average = 0; sensors_sum = 0; a[0]=analogRead(ls); a[1]=analogRead(ms); a[2]=analogRead(rs); for (int i = 0; i < 3; i++) { sensors_average += int(a[i] * (i+1) * 1000); sensors_sum += int(a[i]); } Intput = int(sensors_average / sensors_sum); Serial.print("Intput ="); Serial.println(Intput); delay(1); //Set the number to change frequency of readings. } void calc_turn() { /*Output= k(Setpoint- Intput) * setpoint will be when 1 0 1 * let setpoint be 50 * when left sensor is on black line Intput=0 * when right sensor is on black line Intput=100 * so when left sensor is on black line error value=50 ---> +ve ---> we need to move towards left ---> left motor should have lesser speed than right motor * and when left sensor is on black line error value= -50 ---> -ve ---> we need to move towards right ---> right motor should have lesser speed than left motor */ Serial.print("\t Output= ");Serial.print(Output); if (Output< -255) { Output = -255; } if (Output> 255) { Output = 255; } // If Output is negative calculate right turn speed values if (Output< 0) { right_speed = max_speed + Output; left_speed = max_speed; } // If Output is +ve calculate left turn values else { right_speed = max_speed; left_speed = max_speed - Output; } Serial.print("right_speed ="); Serial.print(right_speed); Serial.print(" "); Serial.print("left_speed ="); Serial.print(left_speed); Serial.println(" "); } void motor_drive() { // Drive motors according to the calculated values for a turn analogWrite(ml1,0); analogWrite(ml2,left_speed); analogWrite(mr1,0); analogWrite(mr2,right_speed); }
[ "shrutibhatia221197@gmail.com" ]
shrutibhatia221197@gmail.com
dd24393c4860b746b9f2943f03aa6e942f35d313
96592a6b5d159f843fe0e0ee18308cc0ebefcf82
/third_party/boost/libs/serialization/test/polymorphic_derived2.hpp
c8496b978a2f7597941b27515a9ee194da19e418
[ "BSL-1.0" ]
permissive
avplayer/tinyrpc
8d505b9f2a8594c59a6cab2d186ec945c7952394
7049b4079fac78b3828e68f787d04d699ce52f6d
refs/heads/master
2020-04-25T02:29:18.753768
2019-05-24T01:55:28
2019-05-24T01:55:28
172,441,102
8
3
null
null
null
null
UTF-8
C++
false
false
2,643
hpp
#ifndef BOOST_SERIALIZATION_TEST_POLYMORPHIC_DERIVED2_HPP #define BOOST_SERIALIZATION_TEST_POLYMORPHIC_DERIVED2_HPP // MS compatible compilers support #pragma once #if defined(_MSC_VER) # pragma once #endif /////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8 // polymorphic_derived2.hpp simple class test // (C) Copyright 2002 Robert Ramey - http://www.rrsd.com . // Use, modification and distribution is subject to the Boost Software // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org for updates, documentation, and revision history. #include <boost/config.hpp> #include <boost/serialization/access.hpp> #include <boost/serialization/nvp.hpp> #include <boost/serialization/base_object.hpp> #include <boost/serialization/type_info_implementation.hpp> #include <boost/serialization/extended_type_info_typeid.hpp> #if defined(BOOST_ALL_DYN_LINK) || defined(BOOST_SERIALIZATION_DYN_LINK) #if defined(POLYMORPHIC_DERIVED2_IMPORT) #define POLYMORPHIC_DERIVED2_DLL_DECL BOOST_SYMBOL_IMPORT #pragma message ("polymorphic_derived2 imported") #elif defined(POLYMORPHIC_DERIVED2_EXPORT) #define POLYMORPHIC_DERIVED2_DLL_DECL BOOST_SYMBOL_EXPORT #pragma message ("polymorphic_derived2 exported") #endif #endif #ifndef POLYMORPHIC_DERIVED2_DLL_DECL #define POLYMORPHIC_DERIVED2_DLL_DECL #endif #define POLYMORPHIC_BASE_IMPORT #include "polymorphic_base.hpp" class BOOST_SYMBOL_VISIBLE polymorphic_derived2 : public polymorphic_base { friend class boost::serialization::access; template<class Archive> POLYMORPHIC_DERIVED2_DLL_DECL void serialize( Archive &ar, const unsigned int /* file_version */ ); POLYMORPHIC_DERIVED2_DLL_DECL const char * get_key() const; public: POLYMORPHIC_DERIVED2_DLL_DECL polymorphic_derived2(); POLYMORPHIC_DERIVED2_DLL_DECL ~polymorphic_derived2(); }; // we use this because we want to assign a key to this type // but we don't want to explicitly instantiate code every time // we do so!!!. If we don't do this, we end up with the same // code in BOTH the DLL which implements polymorphic_derived2 // as well as the main program. BOOST_CLASS_EXPORT_KEY(polymorphic_derived2) // note the mixing of type_info systems is supported. BOOST_CLASS_TYPE_INFO( polymorphic_derived2, boost::serialization::extended_type_info_typeid<polymorphic_derived2> ) #endif // BOOST_SERIALIZATION_TEST_POLYMORPHIC_DERIVED2_HPP
[ "jack.wgm@gmail.com" ]
jack.wgm@gmail.com
f1431a133b2da308056e0ecedaab144396a33c64
1505db51031fb3b81cff6f061e050626ebad88e3
/speedwriter/src/speedwriterapp.cpp
e915b9657ca66465d62c73f66254bc5ad0834d63
[ "Apache-2.0" ]
permissive
dvijayak/Cascades-Samples
6070954811891061c054ba5fcb8f56fad5c56ff3
000886fd612691d998a87c7045932d3baf359431
refs/heads/master
2021-01-17T21:31:53.763664
2013-04-23T18:24:31
2013-04-23T18:24:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,684
cpp
/* Copyright (c) 2012 Research In Motion Limited. * * 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 "speedwriterapp.h" #include "speedgauge.h" #include "wordchecker.h" #include <bb/cascades/Page> #include <bb/cascades/QmlDocument> using namespace bb::cascades; SpeedWriterApp::SpeedWriterApp() { // Registration of the CustomControl which will show the current speed and // the WordChecker object that is used for checking if the entered text is // correct or not. qmlRegisterType will make the objects recongnizable by the // QML parsing engine. qmlRegisterType < SpeedGauge > ("com.speedwriter", 1, 0, "SpeedGauge"); qmlRegisterType < WordChecker > ("com.speedwriter", 1, 0, "WordChecker"); // Create a QMLDocument and load it, using build patterns QmlDocument *qml = QmlDocument::create("asset:///speedwriter.qml"); if (!qml->hasErrors()) { // Create the application Page from QML. Page *appPage = qml->createRootObject<Page>(); if (appPage) { // Set the application scene Application::instance()->setScene(appPage); } } } SpeedWriterApp::~SpeedWriterApp() { }
[ "jlarsby@rim.com" ]
jlarsby@rim.com
0b8826750f3bc7f8b4edbb711ac875876ebf91a0
1e335d28ee6b5984bbb8472abde3dafc682d2323
/include/robot_controller.h
1275d07e81fc97a7ce6c7aea79e16d56d66f7788
[]
no_license
sgteja/Building-kit-with-order-update
795ce917e3a3aec64c33a2a7044ede79984cdb7c
304ecfdd27bce52c5a8de646ebea5a0967948fd9
refs/heads/master
2021-06-21T14:31:57.381808
2020-04-15T18:51:33
2020-04-15T18:51:33
254,497,491
0
0
null
null
null
null
UTF-8
C++
false
false
3,118
h
// // Created by zeid on 2/27/20. // #ifndef SRC_ROBOT_CONTROLLER_H #define SRC_ROBOT_CONTROLLER_H #include <geometry_msgs/Pose.h> #include <geometry_msgs/PoseStamped.h> #include <moveit/move_group_interface/move_group_interface.h> #include <moveit/planning_scene_interface/planning_scene_interface.h> #include <ros/ros.h> #include <stdarg.h> #include <tf/transform_listener.h> #include <iostream> #include <string> #include <initializer_list> #include <osrf_gear/VacuumGripperControl.h> #include <osrf_gear/VacuumGripperState.h> class RobotController { public: RobotController(std::string arm_id); ~RobotController(); bool Planner(); void Execute(); void GoToTarget(std::initializer_list<geometry_msgs::Pose> list); void GoToTarget(const geometry_msgs::Pose& pose); void SendRobotHome(std::string pose); void SendRobotExch(std::string arm, double buffer); bool DropPart(geometry_msgs::Pose pose); bool DropPart(geometry_msgs::Pose pose, geometry_msgs::Pose part_pose); void GripperToggle(const bool& state); void GripperCallback(const osrf_gear::VacuumGripperState::ConstPtr& grip); void GripperStateCheck(geometry_msgs::Pose pose); bool PickPart(geometry_msgs::Pose& part_pose); bool PickPartFromConv(geometry_msgs::Pose& part_pose); void ChangeOrientation(geometry_msgs::Quaternion orientation,geometry_msgs::Quaternion orientation_part); bool GetGripperState(){ return gripper_state_; } private: ros::NodeHandle robot_controller_nh_; moveit::planning_interface::MoveGroupInterface::Options robot_controller_options; ros::ServiceClient gripper_client_; ros::NodeHandle gripper_nh_; ros::Subscriber gripper_subscriber_; tf::TransformListener robot_tf_listener_; tf::StampedTransform robot_tf_transform_; tf::TransformListener agv_tf_listener_; tf::StampedTransform agv_tf_transform_; geometry_msgs::Pose target_pose_; moveit::planning_interface::MoveGroupInterface robot_move_group_; moveit::planning_interface::MoveGroupInterface::Plan robot_planner_; osrf_gear::VacuumGripperControl gripper_service_; osrf_gear::VacuumGripperState gripper_status_; std::string object; std::string arm_id_; bool plan_success_; std::vector<double> home_joint_pose_conv_; std::vector<double> home_joint_pose_bin_; std::vector<double> home_joint_pose_kit1_; std::vector<double> home_joint_pose_kit2_; std::vector<double> home_arm_1_pose_; std::vector<double> home_arm_2_pose_; std::vector<double> part_flip_arm_1_pose_; std::vector<double> part_flip_arm_2_pose_; std::vector<double> part_exch_arm_1_pose_; std::vector<double> part_exch_arm_2_pose_; std::vector<std::string> joint_names_; geometry_msgs::Pose home_cart_pose_; geometry_msgs::Quaternion fixed_orientation_; geometry_msgs::Pose agv_position_; std::vector<double> end_position_; double offset_; double roll_def_,pitch_def_,yaw_def_; tf::Quaternion q; int counter_; bool gripper_state_, drop_flag_; }; #endif //SRC_ROBOT_CONTROLLER_H
[ "gnyanateja@gmail.com" ]
gnyanateja@gmail.com
fdce04adffca63fc3a4a69f7b10b26d8326a0fb9
978c8440bad518a032cadec90a486a63621b481c
/System/Main.cpp
0b9186d1a7c8393a35f63f1290532c8039223b6b
[]
no_license
tengxian4/Animal-Shelter-Management-System
1fc84df1c69988240000d1d30356b5cc608e3257
186754c841ad84ddde3cbb5f3a2baf17e169a604
refs/heads/main
2023-05-30T19:31:07.644810
2021-06-13T15:11:09
2021-06-13T15:11:09
376,572,640
0
0
null
null
null
null
UTF-8
C++
false
false
296
cpp
#include <Windows.h> #include <iostream> #include <string> #include <iomanip> #include <algorithm> using namespace std; #include "Staff.h" #include "Login.h" #include "StaffManager.h" int main() { Login* login = new Login(); login->displayLogin(); return 0; }
[ "noreply@github.com" ]
noreply@github.com
0112d906080f94faa980a36751072b86da3b7dbf
f3dc1bfda2c3fa5d392deec35046a0d37d494feb
/src/entities/include/diguyTypeLookup.h
3b690d3ff65ff1c834c193f757a5437b7d04f3e2
[]
no_license
yanjunlinzju/NPSNET-IV
14d15168bfc958a555e1e5be616f8afff37c3e1b
09ad5905964b1eb3463b8500b0a6c541707fa13f
refs/heads/master
2021-12-02T12:48:49.891646
2013-05-16T18:14:53
2013-05-16T18:14:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
480
h
#ifndef DIGUY_TYPE_LOOK_UP_DOT_H #define DIGUY_TYPE_LOOK_UP_DOT_H const int LU_ARRAY_SIZE = 255; typedef struct _luStorage { char **equipment; } luStorage; #ifndef TRUE #define TRUE (int)1 #endif #ifndef FALSE #define FALSE (int)NULL #endif class diguyTypeLookup { private: luStorage stuff[LU_ARRAY_SIZE + 1]; public: diguyTypeLookup (); ~diguyTypeLookup () {;} int addType (int, char *); char **lookUpType (int); }; #endif
[ "simstorm@mac.com" ]
simstorm@mac.com
7389ee50b3ee46181235980f580ae572fbea4695
87df5af480872d126164a8b669b2d872a150709f
/smartbin1.ino
a0ebfc51827947488a6ae265473f73a189b24a3c
[]
no_license
Chirag-raichu/Arduino-Codes
806453d6bb3329558c9aca4115addf7f6fd18092
5df6c3336eaa5ca523c7e883273561b019f0eee3
refs/heads/master
2021-07-21T12:53:59.999341
2020-09-20T10:37:36
2020-09-20T10:37:36
216,881,410
0
0
null
null
null
null
UTF-8
C++
false
false
5,291
ino
int b=0; int a=0; int c=0; int motor1_state; #include <ESP8266WiFi.h> #include "Adafruit_MQTT.h" #include "Adafruit_MQTT_Client.h" #define TRIGGER D1 #define ECHO D2 #define LED1 D6 #define LED2 D7 /************************* WiFi Access Point *********************************/ #define WLAN_SSID "ProtoSem" #define WLAN_PASS "proto123" /************************* Adafruit.io Setup *********************************/ #define AIO_SERVER "io.adafruit.com" #define AIO_SERVERPORT 1883 // use 8883 for SSL #define AIO_USERNAME "venkey4" #define AIO_KEY "ffc03238861748439567fc5e33c39e54" /************ Global State (you don't need to change this!) ******************/ // Create an ESP8266 WiFiClient class to connect to the MQTT server. WiFiClient client; // or... use WiFiFlientSecure for SSL //WiFiClientSecure client; // Setup the MQTT client class by passing in the WiFi client and MQTT server and login details. Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY); /****************************** Feeds ***************************************/ // Setup a feed called 'cm' for publishing. // Notice MQTT paths for AIO follow the form: <username>/feeds/<feedname> Adafruit_MQTT_Publish cm = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/cm"); Adafruit_MQTT_Publish Boxes = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/Boxes"); Adafruit_MQTT_Publish Motor = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/Motor"); Adafruit_MQTT_Publish bottlemissing = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/bottlemissing"); // Setup a feed called 'onoff' for subscribing to changes. Adafruit_MQTT_Subscribe motor1 = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/Motor"); Adafruit_MQTT_Subscribe light2 = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/L2"); /*************************** Sketch Code ************************************/ // Bug workaround for Arduino 1.6.6, it seems to need a function declaration // for some reason (only affects ESP8266, likely an arduino-builder bug). void MQTT_connect(); void setup() { Serial.begin(115200); delay(10); pinMode(TRIGGER,OUTPUT); pinMode(ECHO,INPUT); // Connect to WiFi access point. Serial.println(); Serial.println(); Serial.print("Connecting to "); Serial.println(WLAN_SSID); WiFi.begin(WLAN_SSID, WLAN_PASS); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); // Setup MQTT subscription for onoff feed. mqtt.subscribe(&motor1); mqtt.subscribe(&light2); } uint32_t x=D0; void loop() { // Ensure the connection to the MQTT server is alive (this will make the first // connection and automatically reconnect when disconnected). See the MQTT_connect // function definition further below. MQTT_connect(); // this is our 'wait for incoming subscription packets' busy subloop // try to spend your time here Adafruit_MQTT_Subscribe *subscription; while ((subscription = mqtt.readSubscription(2500))) { if (subscription == &motor1) { Serial.print(F("Got: ")); Serial.println((char *)motor1.lastread); int motor1_state=atoi((char *)motor1.lastread); Serial.println(motor1_state); digitalWrite(LED1,HIGH); } if (subscription == &light2) { Serial.print(F("Got: ")); Serial.println((char *)light2.lastread); int light2_state=atoi((char *)light2.lastread); digitalWrite(LED2,light2_state); } } // Now we can publish stuff! int duration, distance; digitalWrite(TRIGGER, LOW); delayMicroseconds(2); digitalWrite(TRIGGER, HIGH); delayMicroseconds(10); digitalWrite(TRIGGER, LOW); duration = pulseIn(ECHO, HIGH); distance = (duration/2) / 29.1; a=100-distance; Serial.println(a); digitalWrite(LED1,HIGH); cm.publish(a); //Serial.print(b); // Serial.print("..."); //if (Bottle.publish(b)) { //Serial.println(F("fILLED!")); // } else { // Serial.println(F("Failed")); //} // .publish(a); // ping the server to keep the mqtt connection alive // NOT required if you are publishing once every KEEPALIVE seconds /* if(! mqtt.ping()) { mqtt.disconnect(); } */ } // Function to connect and reconnect as necessary to the MQTT server. // Should be called in the loop function and it will take care if connecting. void MQTT_connect() { int8_t ret; // Stop if already connected. if (mqtt.connected()) { return; } Serial.print("Connecting to MQTT... "); uint8_t retries = 3; while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected Serial.println(mqtt.connectErrorString(ret)); Serial.println("Retrying MQTT connection in 5 seconds..."); mqtt.disconnect(); delay(5000); // wait 5 seconds retries--; if (retries == 0) { // basically die and wait for WDT to reset me while (1); } } Serial.println("MQTT Connected!"); }
[ "noreply@github.com" ]
noreply@github.com
a4a5d6fa043a1a182d9b44d9d121a5e77ccb1972
59a53ffbfe19eb84ba310e66889462ce67451318
/704.search.cpp
1ce3d5cc43808a15e44a845b22888b2a78c29cc5
[]
no_license
wfnuser/leetcode
0877e03fed6617836a8c4dd695f62868d00c0f05
3202104983b4b68272766a3285ffe8683e9b1712
refs/heads/master
2022-06-29T04:16:12.874513
2022-05-25T05:52:03
2022-05-25T05:52:03
142,956,247
42
14
null
null
null
null
UTF-8
C++
false
false
568
cpp
class Solution { public: int search(vector<int>& nums, int target) { int left = 0; int right = nums.size() - 1; while (left <= right) { if (left == right) { if (nums[left] == target) return left; return -1; } int mid = left + (right - left) / 2; if (nums[mid] == target) return mid; if (nums[mid] > target) { right = mid - 1; } else { left = mid + 1; } } return -1; } };
[ "wfnuser@126.com" ]
wfnuser@126.com
433cb1bd287a965c895f1e17c1654183a525363c
d25c3d2a553bf57574c72288cc54d6321b83a972
/libraries/SHT85/SHT85.h
64e7068653b6f871f09fa8d40cb58c8cff24c202
[ "MIT" ]
permissive
roberto-lopardo-aimen/Arduino
32f99d48920d3cacefb7135a1528e1cd641b6a47
f4d0b1d978fbf4009cd87d0fa6cb7c11cc76aea3
refs/heads/master
2023-05-07T13:21:12.226603
2021-05-26T14:39:03
2021-05-26T14:39:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,761
h
#pragma once // // FILE: SHT85.h // AUTHOR: Rob Tillaart // VERSION: 0.1.1 // DATE: 2021-02-10 // PURPOSE: Arduino library for the SHT85 temperature and humidity sensor // https://nl.rs-online.com/web/p/temperature-humidity-sensor-ics/1826530 // URL: https://github.com/RobTillaart/SHT85 // // keep lib in sync with https://github.com/RobTillaart/SHT31 // TOPVIEW // +-------+ // +-----\ | SDA 4 ----- // | +-+ ----+ VCC 3 ----- // | +-+ ----+ GND 2 ----- // +-----/ | SCL 1 ----- // +-------+ #include "Arduino.h" #include "Wire.h" #define SHT85_LIB_VERSION "0.1.1" // fields readStatus #define SHT_STATUS_ALERT_PENDING (1 << 15) #define SHT_STATUS_HEATER_ON (1 << 13) #define SHT_STATUS_HUM_TRACK_ALERT (1 << 11) #define SHT_STATUS_TEMP_TRACK_ALERT (1 << 10) #define SHT_STATUS_SYSTEM_RESET (1 << 4) #define SHT_STATUS_COMMAND_STATUS (1 << 1) #define SHT_STATUS_WRITE_CRC_STATUS (1 << 0) // error codes #define SHT_OK 0x00 #define SHT_ERR_WRITECMD 0x81 #define SHT_ERR_READBYTES 0x82 #define SHT_ERR_HEATER_OFF 0x83 #define SHT_ERR_NOT_CONNECT 0x84 #define SHT_ERR_CRC_TEMP 0x85 #define SHT_ERR_CRC_HUM 0x86 #define SHT_ERR_CRC_STATUS 0x87 class SHT85 { public: SHT85(); #if defined(ESP8266) || defined(ESP32) bool begin(const uint8_t address, uint8_t dataPin, uint8_t clockPin); #endif bool begin(const uint8_t address, TwoWire *wire = &Wire); // blocks 15 milliseconds + actual read + math bool read(bool fast = true); // check senosr is reachable over I2C bool isConnected(); // details see datasheet; summary in SHT31.cpp file uint16_t readStatus(); // lastRead is in milliSeconds since start uint32_t lastRead() { return _lastRead; }; bool reset(bool hard = false); // do not use heater for long periods, // use it for max 3 minutes to heat up // and let it cool down an equal period. void setHeatTimeout(uint8_t seconds); bool heatOn(); bool heatOff(); bool isHeaterOn(); // is the sensor still heating up? float getHumidity() { return humidity; }; float getTemperature() { return temperature; }; // ASYNC INTERFACE bool requestData(); bool dataReady(); bool readData(bool fast = true); int getError(); // clears error flag private: uint8_t crc8(const uint8_t *data, uint8_t len); bool writeCmd(uint16_t cmd); bool readBytes(uint8_t n, uint8_t *val); TwoWire* _wire; uint8_t _addr; uint8_t _heatTimeOut; // seconds uint32_t _lastRead; uint32_t _lastRequest; // for async interface uint32_t _heaterStart; float humidity; float temperature; uint8_t _error; }; // -- END OF FILE --
[ "rob.tillaart@gmail.com" ]
rob.tillaart@gmail.com
44cc1904776be7d2db1fbd71972f4cc11d726084
553cdf6a503ac1678188d248f82a2cd7bba1e720
/Assignment3/assignment3/objects/quad.cpp
afcbfd422766575e71cc01521bd91b1e057ee7a0
[]
no_license
zhaozhao15/Computer-Graphics
f8af984f72b4849201f9fb9b3095bb45378e35fe
2657d068a4cfae2b677594a294cddec733a2843d
refs/heads/master
2020-05-17T13:57:40.635700
2019-04-27T08:48:06
2019-04-27T08:48:06
183,749,423
0
0
null
null
null
null
UTF-8
C++
false
false
1,986
cpp
#include "quad.h" namespace Orchid { Quad::Quad( const Vector3d & a, const Vector3d & b, const Vector3d & c, const Vector3d & d, const Material & material) : _a{ a } , _b{ b } , _c{ c } , _d{ d } , _material{ material } { } ObjectIntersection Quad::getIntersection(const Ray & ray) { //triangle abc const Vector3d e1 = _b - _a; const Vector3d e2 = _c - _a; Vector3d n = Vector3d::cross(e1, e2).normalized(); Vector3d o = ray.origin(); Vector3d d = ray.direction(); //Vector3d Normal = Vector3d::cross(_a - _b, _b - _c).normalized(); double c = n.dot(_a); double t = (c - n.dot(o)) / (n.dot(d)); Vector3d cor = o + d * t; double area0 = 0.5 * Vector3d::cross(e1, e2).norm(); const Vector3d v10 = _a - cor; const Vector3d v11 = _b - cor; double area1 = 0.5 * Vector3d::cross(v10, v11).norm(); const Vector3d v20 = _a - cor; const Vector3d v21 = _c - cor; double area2 = 0.5 * Vector3d::cross(v20, v21).norm(); const Vector3d v30 = _b - cor; const Vector3d v31 = _c - cor; double area3 = 0.5 * Vector3d::cross(v30, v31).norm(); if (-area0 + (area1 + area2 + area3) <= area0*0.01) { return ObjectIntersection(true, t, n, _material); }else { //triangle acd const Vector3d e3 = _a - _d; const Vector3d e4 = _a - _c; double area0_ = 0.5 * Vector3d::cross(e3, e4).norm(); const Vector3d v10_ = _a - cor; const Vector3d v11_ = _d - cor; double area1_ = 0.5 * Vector3d::cross(v10_, v11_).norm(); const Vector3d v20_ = _c - cor; const Vector3d v21_ = _d - cor; double area2_ = 0.5 * Vector3d::cross(v20_, v21_).norm(); const Vector3d v30_ = _a - cor; const Vector3d v31_ = _c - cor; double area3_ = 0.5 * Vector3d::cross(v30_, v31_).norm(); if ((area1_ + area2_ + area3_) - area0_ <= area0_ * 0.01) { return ObjectIntersection(true, t, n, _material); } else { return ObjectIntersection(false, 0.0, Vector3d(0), Material(DIFF, Vector3d(0.0))); } } } }
[ "zhaodonghao0105@163.com" ]
zhaodonghao0105@163.com
c15f2ea3c675e1717c742340df8cbf9e2e3eaab7
51cced907524ee0039cd0b129178caf939e56912
/media/libaaudio/src/binding/AudioEndpointParcelable.h
e4f8b9ee13181b56d7164018d8b8a27b8eac2bc5
[ "LicenseRef-scancode-unicode", "Apache-2.0" ]
permissive
crdroidandroid/android_frameworks_av
ea109b991a177220dbc597a43df01e919112f545
9f6a26f1e4cb02c6504d670f292a9b88ec6a7106
refs/heads/10.0
2023-08-31T06:58:55.034080
2022-01-23T08:25:07
2022-01-23T08:25:07
277,145,615
8
80
NOASSERTION
2023-09-13T07:10:14
2020-07-04T16:22:52
C++
UTF-8
C++
false
false
2,530
h
/* * Copyright 2016 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. */ #ifndef ANDROID_BINDING_AUDIO_ENDPOINT_PARCELABLE_H #define ANDROID_BINDING_AUDIO_ENDPOINT_PARCELABLE_H #include <stdint.h> //#include <sys/mman.h> #include <android-base/unique_fd.h> #include <binder/Parcel.h> #include <binder/Parcelable.h> #include "binding/AAudioServiceDefinitions.h" #include "binding/RingBufferParcelable.h" using android::status_t; using android::Parcel; using android::Parcelable; namespace aaudio { /** * Container for information about the message queues plus * general stream information needed by AAudio clients. * It contains no addresses, just sizes, offsets and file descriptors for * shared memory that can be passed through Binder. */ class AudioEndpointParcelable : public Parcelable { public: AudioEndpointParcelable(); virtual ~AudioEndpointParcelable(); /** * Add the file descriptor to the table. * @return index in table or negative error */ int32_t addFileDescriptor(const android::base::unique_fd& fd, int32_t sizeInBytes); virtual status_t writeToParcel(Parcel* parcel) const override; virtual status_t readFromParcel(const Parcel* parcel) override; aaudio_result_t resolve(EndpointDescriptor *descriptor); aaudio_result_t close(); void dump(); public: // TODO add getters // Set capacityInFrames to zero if Queue is unused. RingBufferParcelable mUpMessageQueueParcelable; // server to client RingBufferParcelable mDownMessageQueueParcelable; // to server RingBufferParcelable mUpDataQueueParcelable; // eg. record, could share same queue RingBufferParcelable mDownDataQueueParcelable; // eg. playback private: aaudio_result_t validate() const; int32_t mNumSharedMemories = 0; SharedMemoryParcelable mSharedMemories[MAX_SHARED_MEMORIES]; }; } /* namespace aaudio */ #endif //ANDROID_BINDING_AUDIO_ENDPOINT_PARCELABLE_H
[ "philburk@google.com" ]
philburk@google.com
75a270243a46ec13be8aa964495c72d8a3784c28
c474c1c3743ce3362bce0823fcf1840d2d22b4a8
/window.cpp
3290c346e98a6bfe831bdf5e23ae8a7c9756bdd1
[]
no_license
ab93/Satellite-Tracking-and-Visualization
22afa05b6968ffaee99fc0412a0a824263569516
f095f2ea99cc3b35375726671c737901b4fca115
refs/heads/master
2021-01-10T14:47:53.065886
2015-10-13T22:11:56
2015-10-13T22:11:56
44,208,493
2
2
null
null
null
null
UTF-8
C++
false
false
319
cpp
#include <QtGui> #include<qt4/QtGui/qlayout.h> #include "glwidget.h" #include "window.h" Window::Window(int index) { glWidget = new GLWidget(index); QHBoxLayout *mainLayout = new QHBoxLayout; mainLayout->addWidget(glWidget); setLayout(mainLayout); setWindowTitle(tr("Satellite Tracking")); }
[ "avikbasu93@gmail.com" ]
avikbasu93@gmail.com
aeb70a5569c862842033bca36442db20463edfb3
a38646f0798adf035aa76147e36b27edf3170b92
/src/cpp/classification/models_test.cc
6750923b1ebeaeca889fd9d3e9a9e6de6871bcc6
[ "Apache-2.0" ]
permissive
powderluv/edgetpu
d305cbf9a7a6a0981e2c33288dc5a2b3cb07f243
a968b4a72546c8cad26d25fcb6bb504849503c4a
refs/heads/master
2020-07-31T20:20:50.762191
2019-10-18T23:14:38
2020-02-16T01:47:12
210,742,049
1
1
Apache-2.0
2019-10-18T23:55:04
2019-09-25T02:51:10
C++
UTF-8
C++
false
false
8,920
cc
#include "absl/flags/parse.h" #include "glog/logging.h" #include "gtest/gtest.h" #include "src/cpp/classification/engine.h" #include "src/cpp/test_utils.h" namespace coral { namespace { TEST(ClassificationEngineTest, TestMobilenetModels) { // Mobilenet V1 1.0 TestClassification(TestDataPath("mobilenet_v1_1.0_224_quant.tflite"), TestDataPath("cat.bmp"), /*score_threshold=*/0.78, /*expected_top1_label=*/286); // Egyptian cat TestClassification(TestDataPath("mobilenet_v1_1.0_224_quant_edgetpu.tflite"), TestDataPath("cat.bmp"), /*score_threshold=*/0.78, /*expected_top1_label=*/286); // Egyptian cat // Mobilenet V1 0.25 TestClassification(TestDataPath("mobilenet_v1_0.25_128_quant.tflite"), TestDataPath("cat.bmp"), /*score_threshold=*/0.36, /*expected_top1_label=*/283); // tiger cat TestClassification(TestDataPath("mobilenet_v1_0.25_128_quant_edgetpu.tflite"), TestDataPath("cat.bmp"), /*score_threshold=*/0.36, /*expected_top1_label=*/283); // tiger cat // Mobilenet V1 0.5 TestClassification(TestDataPath("mobilenet_v1_0.5_160_quant.tflite"), TestDataPath("cat.bmp"), /*score_threshold=*/0.68, /*expected_top1_label=*/286); // Egyptian cat TestClassification(TestDataPath("mobilenet_v1_0.5_160_quant_edgetpu.tflite"), TestDataPath("cat.bmp"), /*score_threshold=*/0.68, /*expected_top1_label=*/286); // Egyptian cat // Mobilenet V1 0.75 TestClassification(TestDataPath("mobilenet_v1_0.75_192_quant.tflite"), TestDataPath("cat.bmp"), /*score_threshold=*/0.4, /*expected_top1_label=*/283); // tiger cat TestClassification(TestDataPath("mobilenet_v1_0.75_192_quant_edgetpu.tflite"), TestDataPath("cat.bmp"), /*score_threshold=*/0.4, /*expected_top1_label=*/283); // tiger cat // Mobilenet V2 TestClassification(TestDataPath("mobilenet_v2_1.0_224_quant.tflite"), TestDataPath("cat.bmp"), /*score_threshold=*/0.8, /*expected_top1_label=*/286); // Egyptian cat TestClassification(TestDataPath("mobilenet_v2_1.0_224_quant_edgetpu.tflite"), TestDataPath("cat.bmp"), /*score_threshold=*/0.79, /*expected_top1_label=*/286); // Egyptian cat } TEST(ClassificationEngineTest, TestInceptionModels) { // Inception V1 TestClassification(TestDataPath("inception_v1_224_quant.tflite"), TestDataPath("cat.bmp"), /*score_threshold=*/0.37, /*expected_top1_label=*/282); // tabby, tabby cat TestClassification(TestDataPath("inception_v1_224_quant_edgetpu.tflite"), TestDataPath("cat.bmp"), /*score_threshold=*/0.38, /*expected_top1_label=*/286); // Egyptian cat // Inception V2 TestClassification(TestDataPath("inception_v2_224_quant.tflite"), TestDataPath("cat.bmp"), /*score_threshold=*/0.65, /*expected_top1_label=*/286); // Egyptian cat TestClassification(TestDataPath("inception_v2_224_quant_edgetpu.tflite"), TestDataPath("cat.bmp"), /*score_threshold=*/0.61, /*expected_top1_label=*/286); // Egyptian cat // Inception V3 TestClassification(TestDataPath("inception_v3_299_quant.tflite"), TestDataPath("cat.bmp"), /*score_threshold=*/0.58, /*expected_top1_label=*/282); // tabby, tabby cat TestClassification(TestDataPath("inception_v3_299_quant_edgetpu.tflite"), TestDataPath("cat.bmp"), /*score_threshold=*/0.597, /*expected_top1_label=*/282); // tabby, tabby cat // Inception V4 TestClassification(TestDataPath("inception_v4_299_quant.tflite"), TestDataPath("cat.bmp"), /*score_threshold=*/0.35, /*expected_top1_label=*/286); // Egyptian cat TestClassification(TestDataPath("inception_v4_299_quant_edgetpu.tflite"), TestDataPath("cat.bmp"), /*score_threshold=*/0.41, /*expected_top1_label=*/282); // tabby, tabby cat } TEST(ClassificationEngineTest, TestINatModels) { // Plant model TestClassification( TestDataPath("mobilenet_v2_1.0_224_inat_plant_quant.tflite"), TestDataPath("sunflower.bmp"), /*score_threshold=*/0.8, /*expected_top1_label=*/1680); // Helianthus annuus (common sunflower) TestClassification( TestDataPath("mobilenet_v2_1.0_224_inat_plant_quant_edgetpu.tflite"), TestDataPath("sunflower.bmp"), /*score_threshold=*/0.8, /*expected_top1_label=*/1680); // Helianthus annuus (common sunflower) // Insect model TestClassification( TestDataPath("mobilenet_v2_1.0_224_inat_insect_quant.tflite"), TestDataPath("dragonfly.bmp"), /*score_threshold=*/0.2, /*expected_top1_label=*/912); // Thornbush Dasher TestClassification( TestDataPath("mobilenet_v2_1.0_224_inat_insect_quant_edgetpu.tflite"), TestDataPath("dragonfly.bmp"), /*score_threshold=*/0.2, /*expected_top1_label=*/912); // Thornbush Dasher // Bird model TestClassification( TestDataPath("mobilenet_v2_1.0_224_inat_bird_quant.tflite"), TestDataPath("bird.bmp"), /*score_threshold=*/0.5, /*expected_top1_label=*/659); // Black-capped Chickadee TestClassification( TestDataPath("mobilenet_v2_1.0_224_inat_bird_quant_edgetpu.tflite"), TestDataPath("bird.bmp"), /*score_threshold=*/0.5, /*expected_top1_label=*/659); // Black-capped Chickadee } TEST(ClassificationEngineTest, TestEfficientNetEdgeTpuModelsCustomPreprocessing) { const int kTopk = 3; // Custom preprocessing is done by: // (v - (mean - zero_point * scale * stddev)) / (stddev * scale) { // mean 127, stddev 128 // first input tensor scale: 0.012566, zero_point: 131 const float effective_scale = 128 * 0.012566; const std::vector<float> effective_means(3, 127 - 131 * effective_scale); TestClassification(TestDataPath("efficientnet-edgetpu-S_quant.tflite"), TestDataPath("cat.bmp"), effective_scale, effective_means, /*score_threshold=*/0.4, kTopk, /*expected_topk_label=*/286); // Egyptian cat TestClassification( TestDataPath("efficientnet-edgetpu-S_quant_edgetpu.tflite"), TestDataPath("cat.bmp"), effective_scale, effective_means, /*score_threshold=*/0.4, kTopk, /*expected_topk_label=*/286); // Egyptian cat } { // mean 127, stddev 128 // first input tensor scale: 0.012089, zero_point: 129 const float effective_scale = 128 * 0.012089; const std::vector<float> effective_means(3, 127 - 129 * effective_scale); TestClassification(TestDataPath("efficientnet-edgetpu-M_quant.tflite"), TestDataPath("cat.bmp"), effective_scale, effective_means, /*score_threshold=*/0.6, kTopk, /*expected_topk_label=*/286); // Egyptian cat TestClassification( TestDataPath("efficientnet-edgetpu-M_quant_edgetpu.tflite"), TestDataPath("cat.bmp"), effective_scale, effective_means, /*score_threshold=*/0.6, kTopk, /*expected_topk_label=*/286); // Egyptian cat } { // mean 127, stddev 128 // first input tensor scale: 0.01246, zero_point: 129 const float effective_scale = 128 * 0.01246; const std::vector<float> effective_means(3, 127 - 129 * effective_scale); TestClassification(TestDataPath("efficientnet-edgetpu-L_quant.tflite"), TestDataPath("cat.bmp"), effective_scale, effective_means, /*score_threshold=*/0.6, kTopk, /*expected_topk_label=*/286); // Egyptian cat TestClassification( TestDataPath("efficientnet-edgetpu-L_quant_edgetpu.tflite"), TestDataPath("cat.bmp"), effective_scale, effective_means, /*score_threshold=*/0.6, kTopk, /*expected_topk_label=*/286); // Egyptian cat } } } // namespace } // namespace coral int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); absl::ParseCommandLine(argc, argv); return RUN_ALL_TESTS(); }
[ "dkovalev@google.com" ]
dkovalev@google.com
ae6f30b78d9b22485f1298d9f2d0f1251cf737df
e78567ba6b987526a12429527e2c691bc381837a
/include/GTL/algorithm.h
1333d9c9a15df9923ad6d4207d5aa244b46be051
[]
no_license
archieren/SSD_Tracker
60c742b21cc77961464a08a395a5623e86446e81
225e9f9dbf22b18ace41370a6fa3b648d7f0cca5
refs/heads/master
2020-07-02T17:29:34.139377
2020-04-22T09:59:41
2020-04-22T09:59:41
201,605,726
1
0
null
null
null
null
UTF-8
C++
false
false
2,018
h
#ifndef GTL_ALGORITHM_H #define GTL_ALGORITHM_H #include <GTL/GTL.h> #include <GTL/graph.h> #include <iostream> __GTL_BEGIN_NAMESPACE /** * $Date: 2003/03/24 15:58:54 $ * $Revision: 1.14 $ * * @brief Abstract baseclass for all algoritm-classes. */ class GTL_EXTERN algorithm { public: /** * @var algorithm::GTL_OK * Used as (positive) return value of algorithm::check and * algorithm::run. */ /** * @var algorithm::GTL_ERROR * Used as (negative) return value of algorithm::check and * algorithm::run. */ /** * @brief Return values for algorithm::check and algorithm::run */ enum { GTL_OK = 1, GTL_ERROR = 0 }; /** * @brief Creates an algorithm object. */ algorithm () { }; /** * @brief Destroys the algorithm object. */ virtual ~algorithm () { }; /** * @brief Applies %algorithm to %graph g. * * @param g %graph * @retval algorithm::GTL_OK on success * @retval algorithm::GTL_ERROR otherwise */ virtual int run (graph& g) = 0; /** * @brief Checks whether all preconditions are satisfied. * * @em Please @em note: It is * definitly required (and #run relies on it), * that this method was called in advance. * * @param g %graph * @retval algorithm::GTL_OK if %algorithm can be applied * @retval algorithm::GTL_ERROR otherwise. */ virtual int check (graph& g) = 0; /** * @brief Resets %algorithm * * Prepares the %algorithm to be applied to * another %graph. @em Please @em note: The options an * %algorithm may support do @em not get reset by * this. It is just to reset internally used datastructures. */ virtual void reset () = 0; }; __GTL_END_NAMESPACE #endif // GTL_ALGORITHM_H //-------------------------------------------------------------------------- // end of file //--------------------------------------------------------------------------
[ "renjianpeng@gmail.com" ]
renjianpeng@gmail.com
f1f4068fddcb3d822a46af9c92788add99edb12b
44e7e032439086c833ffc080a947f5cbe8342f93
/renderdoc/replay/replay_controller.cpp
9ec2ddd1b65fc60ebb68e7e05dbc477ba830d747
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
gomson/renderdoc
3c58b589b435d96b321f1faa12c3969d881e9163
8f6973578058f04e02f5a4b92026ae09b9fe1e19
refs/heads/master
2021-01-20T04:36:35.168879
2017-04-27T20:35:49
2017-04-27T21:16:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
55,380
cpp
/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2015-2017 Baldur Karlsson * Copyright (c) 2014 Crytek * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ #include "replay_controller.h" #include <string.h> #include <time.h> #include "common/dds_readwrite.h" #include "jpeg-compressor/jpgd.h" #include "jpeg-compressor/jpge.h" #include "maths/formatpacking.h" #include "os/os_specific.h" #include "serialise/serialiser.h" #include "serialise/string_utils.h" #include "stb/stb_image.h" #include "stb/stb_image_write.h" #include "tinyexr/tinyexr.h" float ConvertComponent(const ResourceFormat &fmt, byte *data) { if(fmt.compByteWidth == 4) { uint32_t *u32 = (uint32_t *)data; int32_t *i32 = (int32_t *)data; if(fmt.compType == CompType::Float) { return *(float *)u32; } else if(fmt.compType == CompType::UInt || fmt.compType == CompType::UScaled) { return float(*u32); } else if(fmt.compType == CompType::SInt || fmt.compType == CompType::SScaled) { return float(*i32); } } else if(fmt.compByteWidth == 3 && fmt.compType == CompType::Depth) { // 24-bit depth is a weird edge case we need to assemble it by hand uint8_t *u8 = (uint8_t *)data; uint32_t depth = 0; depth |= uint32_t(u8[1]); depth |= uint32_t(u8[2]) << 8; depth |= uint32_t(u8[3]) << 16; return float(depth) / float(16777215.0f); } else if(fmt.compByteWidth == 2) { uint16_t *u16 = (uint16_t *)data; int16_t *i16 = (int16_t *)data; if(fmt.compType == CompType::Float) { return ConvertFromHalf(*u16); } else if(fmt.compType == CompType::UInt || fmt.compType == CompType::UScaled) { return float(*u16); } else if(fmt.compType == CompType::SInt || fmt.compType == CompType::SScaled) { return float(*i16); } // 16-bit depth is UNORM else if(fmt.compType == CompType::UNorm || fmt.compType == CompType::Depth) { return float(*u16) / 65535.0f; } else if(fmt.compType == CompType::SNorm) { float f = -1.0f; if(*i16 == -32768) f = -1.0f; else f = ((float)*i16) / 32767.0f; return f; } } else if(fmt.compByteWidth == 1) { uint8_t *u8 = (uint8_t *)data; int8_t *i8 = (int8_t *)data; if(fmt.compType == CompType::UInt || fmt.compType == CompType::UScaled) { return float(*u8); } else if(fmt.compType == CompType::SInt || fmt.compType == CompType::SScaled) { return float(*i8); } else if(fmt.compType == CompType::UNorm) { if(fmt.srgbCorrected) return SRGB8_lookuptable[*u8]; else return float(*u8) / 255.0f; } else if(fmt.compType == CompType::SNorm) { float f = -1.0f; if(*i8 == -128) f = -1.0f; else f = ((float)*i8) / 127.0f; return f; } } RDCERR("Unexpected format to convert from"); return 0.0f; } static void fileWriteFunc(void *context, void *data, int size) { FileIO::fwrite(data, 1, size, (FILE *)context); } ReplayController::ReplayController() { m_pDevice = NULL; m_EventID = 100000; } ReplayController::~ReplayController() { RDCLOG("Shutting down replay renderer"); for(size_t i = 0; i < m_Outputs.size(); i++) SAFE_DELETE(m_Outputs[i]); m_Outputs.clear(); for(auto it = m_CustomShaders.begin(); it != m_CustomShaders.end(); ++it) m_pDevice->FreeCustomShader(*it); m_CustomShaders.clear(); for(auto it = m_TargetResources.begin(); it != m_TargetResources.end(); ++it) m_pDevice->FreeTargetResource(*it); m_TargetResources.clear(); if(m_pDevice) m_pDevice->Shutdown(); m_pDevice = NULL; } void ReplayController::SetFrameEvent(uint32_t eventID, bool force) { if(eventID != m_EventID || force) { m_EventID = eventID; m_pDevice->ReplayLog(eventID, eReplay_WithoutDraw); for(size_t i = 0; i < m_Outputs.size(); i++) m_Outputs[i]->SetFrameEvent(eventID); m_pDevice->ReplayLog(eventID, eReplay_OnlyDraw); FetchPipelineState(); } } D3D11Pipe::State ReplayController::GetD3D11PipelineState() { return m_D3D11PipelineState; } D3D12Pipe::State ReplayController::GetD3D12PipelineState() { return m_D3D12PipelineState; } GLPipe::State ReplayController::GetGLPipelineState() { return m_GLPipelineState; } VKPipe::State ReplayController::GetVulkanPipelineState() { return m_VulkanPipelineState; } FrameDescription ReplayController::GetFrameInfo() { return m_FrameRecord.frameInfo; } DrawcallDescription *ReplayController::GetDrawcallByEID(uint32_t eventID) { if(eventID >= m_Drawcalls.size()) return NULL; return m_Drawcalls[eventID]; } rdctype::array<DrawcallDescription> ReplayController::GetDrawcalls() { return m_FrameRecord.drawcallList; } rdctype::array<CounterResult> ReplayController::FetchCounters(const rdctype::array<GPUCounter> &counters) { vector<GPUCounter> counterArray; counterArray.reserve(counters.count); for(int32_t i = 0; i < counters.count; i++) counterArray.push_back(counters[i]); return m_pDevice->FetchCounters(counterArray); } rdctype::array<GPUCounter> ReplayController::EnumerateCounters() { return m_pDevice->EnumerateCounters(); } CounterDescription ReplayController::DescribeCounter(GPUCounter counterID) { CounterDescription ret; m_pDevice->DescribeCounter(counterID, ret); return ret; } rdctype::array<BufferDescription> ReplayController::GetBuffers() { if(m_Buffers.empty()) { vector<ResourceId> ids = m_pDevice->GetBuffers(); m_Buffers.resize(ids.size()); for(size_t i = 0; i < ids.size(); i++) m_Buffers[i] = m_pDevice->GetBuffer(ids[i]); } return m_Buffers; } rdctype::array<TextureDescription> ReplayController::GetTextures() { if(m_Textures.empty()) { vector<ResourceId> ids = m_pDevice->GetTextures(); m_Textures.resize(ids.size()); for(size_t i = 0; i < ids.size(); i++) m_Textures[i] = m_pDevice->GetTexture(ids[i]); } return m_Textures; } rdctype::array<rdctype::str> ReplayController::GetResolve(const rdctype::array<uint64_t> &callstack) { rdctype::array<rdctype::str> ret; if(callstack.empty()) return ret; Callstack::StackResolver *resolv = m_pDevice->GetCallstackResolver(); if(resolv == NULL) return ret; create_array_uninit(ret, (size_t)callstack.count); for(int32_t i = 0; i < callstack.count; i++) { Callstack::AddressDetails info = resolv->GetAddr(callstack[i]); ret[i] = info.formattedString(); } return ret; } rdctype::array<DebugMessage> ReplayController::GetDebugMessages() { return m_pDevice->GetDebugMessages(); } rdctype::array<EventUsage> ReplayController::GetUsage(ResourceId id) { return m_pDevice->GetUsage(m_pDevice->GetLiveID(id)); } MeshFormat ReplayController::GetPostVSData(uint32_t instID, MeshDataStage stage) { DrawcallDescription *draw = GetDrawcallByEID(m_EventID); MeshFormat ret; RDCEraseEl(ret); if(draw == NULL || !(draw->flags & DrawFlags::Drawcall)) return MeshFormat(); instID = RDCMIN(instID, draw->numInstances - 1); return m_pDevice->GetPostVSBuffers(draw->eventID, instID, stage); } rdctype::array<byte> ReplayController::GetBufferData(ResourceId buff, uint64_t offset, uint64_t len) { rdctype::array<byte> ret; if(buff == ResourceId()) return ret; ResourceId liveId = m_pDevice->GetLiveID(buff); if(liveId == ResourceId()) { RDCERR("Couldn't get Live ID for %llu getting buffer data", buff); return ret; } vector<byte> retData; m_pDevice->GetBufferData(liveId, offset, len, retData); create_array_init(ret, retData.size(), !retData.empty() ? &retData[0] : NULL); return ret; } rdctype::array<byte> ReplayController::GetTextureData(ResourceId tex, uint32_t arrayIdx, uint32_t mip) { rdctype::array<byte> ret; ResourceId liveId = m_pDevice->GetLiveID(tex); if(liveId == ResourceId()) { RDCERR("Couldn't get Live ID for %llu getting texture data", tex); return ret; } size_t sz = 0; byte *bytes = m_pDevice->GetTextureData(liveId, arrayIdx, mip, GetTextureDataParams(), sz); if(sz == 0 || bytes == NULL) create_array_uninit(ret, 0); else create_array_init(ret, sz, bytes); SAFE_DELETE_ARRAY(bytes); return ret; } bool ReplayController::SaveTexture(const TextureSave &saveData, const char *path) { TextureSave sd = saveData; // mutable copy ResourceId liveid = m_pDevice->GetLiveID(sd.id); TextureDescription td = m_pDevice->GetTexture(liveid); bool success = false; // clamp sample/mip/slice indices if(td.msSamp == 1) { sd.sample.sampleIndex = 0; sd.sample.mapToArray = false; } else { if(sd.sample.sampleIndex != ~0U) sd.sample.sampleIndex = RDCCLAMP(sd.sample.sampleIndex, 0U, td.msSamp); } // don't support cube cruciform for non cubemaps, or // cubemap arrays if(!td.cubemap || td.arraysize != 6 || td.msSamp != 1) sd.slice.cubeCruciform = false; if(sd.mip != -1) sd.mip = RDCCLAMP(sd.mip, 0, (int32_t)td.mips); if(sd.slice.sliceIndex != -1) sd.slice.sliceIndex = RDCCLAMP(sd.slice.sliceIndex, 0, int32_t(td.arraysize * td.depth)); if(td.arraysize * td.depth * td.msSamp == 1) { sd.slice.sliceIndex = 0; sd.slice.slicesAsGrid = false; } // can't extract a channel that's not in the source texture if(sd.channelExtract >= 0 && (uint32_t)sd.channelExtract >= td.format.compCount) sd.channelExtract = -1; sd.slice.sliceGridWidth = RDCMAX(sd.slice.sliceGridWidth, 1); // store sample count so we know how many 'slices' is one real slice // multisampled textures cannot have mips, subresource layout is same as would be for mips: // [slice0 sample0], [slice0 sample1], [slice1 sample0], [slice1 sample1] uint32_t sampleCount = td.msSamp; bool multisampled = td.msSamp > 1; bool resolveSamples = (sd.sample.sampleIndex == ~0U); if(resolveSamples) { td.msSamp = 1; sd.sample.mapToArray = false; sd.sample.sampleIndex = 0; } // treat any multisampled texture as if it were an array // of <sample count> dimension (on top of potential existing array // dimension). GetTextureData() uses the same convention. if(td.msSamp > 1) { td.arraysize *= td.msSamp; td.msSamp = 1; } if(sd.destType != FileType::DDS && sd.sample.mapToArray && !sd.slice.slicesAsGrid && sd.slice.sliceIndex == -1) { sd.sample.mapToArray = false; sd.sample.sampleIndex = 0; } // only DDS supports writing multiple mips, fall back to mip 0 if 'all mips' was specified if(sd.destType != FileType::DDS && sd.mip == -1) sd.mip = 0; // only DDS supports writing multiple slices, fall back to slice 0 if 'all slices' was specified if(sd.destType != FileType::DDS && sd.slice.sliceIndex == -1 && !sd.slice.slicesAsGrid && !sd.slice.cubeCruciform) sd.slice.sliceIndex = 0; // fetch source data subresources (typically only one, possibly more // if we're writing to DDS (so writing multiple mips/slices) or resolving // down a multisampled texture for writing as a single 'image' elsewhere) uint32_t sliceOffset = 0; uint32_t sliceStride = 1; uint32_t numSlices = td.arraysize * td.depth; uint32_t mipOffset = 0; uint32_t numMips = td.mips; bool singleSlice = (sd.slice.sliceIndex != -1); // set which slices/mips we need if(multisampled) { bool singleSample = !sd.sample.mapToArray; // multisampled images have no mips mipOffset = 0; numMips = 1; if(singleSlice) { if(singleSample) { // we want a specific sample in a specific real slice sliceOffset = sd.slice.sliceIndex * sampleCount + sd.sample.sampleIndex; numSlices = 1; } else { // we want all the samples (now mapped to slices) in a specific real slice sliceOffset = sd.slice.sliceIndex; numSlices = sampleCount; } } else { if(singleSample) { // we want one sample in every slice, so we have to set the stride to sampleCount // to skip every other sample (mapped to slices), starting from the sample we want // in the first real slice sliceOffset = sd.sample.sampleIndex; sliceStride = sampleCount; numSlices = RDCMAX(1U, td.arraysize / sampleCount); } else { // we want all slices, all samples sliceOffset = 0; numSlices = td.arraysize; } } } else { if(singleSlice) { numSlices = 1; sliceOffset = sd.slice.sliceIndex; } // otherwise take all slices, as by default if(sd.mip != -1) { mipOffset = sd.mip; numMips = 1; } // otherwise take all mips, as by default } vector<byte *> subdata; bool downcast = false; // don't support slice mappings for DDS - it supports slices natively if(sd.destType == FileType::DDS) { sd.slice.cubeCruciform = false; sd.slice.slicesAsGrid = false; } // force downcast to be able to do grid mappings if(sd.slice.cubeCruciform || sd.slice.slicesAsGrid) downcast = true; // we don't support any file formats that handle these block compression formats if(td.format.specialFormat == SpecialFormat::ETC2 || td.format.specialFormat == SpecialFormat::EAC || td.format.specialFormat == SpecialFormat::ASTC) downcast = true; // for DDS don't downcast, for non-HDR always downcast if we're not already RGBA8 unorm // for HDR&EXR we can convert from most regular types as well as 10.10.10.2 and 11.11.10 if((sd.destType != FileType::DDS && sd.destType != FileType::HDR && sd.destType != FileType::EXR && (td.format.compByteWidth != 1 || td.format.compCount != 4 || td.format.compType != CompType::UNorm || td.format.bgraOrder)) || downcast || (sd.destType != FileType::DDS && td.format.special && td.format.specialFormat != SpecialFormat::R10G10B10A2 && td.format.specialFormat != SpecialFormat::R11G11B10)) { downcast = true; td.format.compByteWidth = 1; td.format.compCount = 4; td.format.compType = CompType::UNorm; td.format.special = false; td.format.specialFormat = SpecialFormat::Unknown; } uint32_t rowPitch = 0; uint32_t slicePitch = 0; bool blockformat = false; int blockSize = 0; uint32_t bytesPerPixel = 1; td.width = RDCMAX(1U, td.width >> mipOffset); td.height = RDCMAX(1U, td.height >> mipOffset); td.depth = RDCMAX(1U, td.depth >> mipOffset); if(td.format.specialFormat == SpecialFormat::BC1 || td.format.specialFormat == SpecialFormat::BC2 || td.format.specialFormat == SpecialFormat::BC3 || td.format.specialFormat == SpecialFormat::BC4 || td.format.specialFormat == SpecialFormat::BC5 || td.format.specialFormat == SpecialFormat::BC6 || td.format.specialFormat == SpecialFormat::BC7) { blockSize = (td.format.specialFormat == SpecialFormat::BC1 || td.format.specialFormat == SpecialFormat::BC4) ? 8 : 16; rowPitch = RDCMAX(1U, ((td.width + 3) / 4)) * blockSize; slicePitch = rowPitch * RDCMAX(1U, td.height / 4); blockformat = true; } else { switch(td.format.specialFormat) { case SpecialFormat::S8: bytesPerPixel = 1; break; case SpecialFormat::R10G10B10A2: case SpecialFormat::R9G9B9E5: case SpecialFormat::R11G11B10: case SpecialFormat::D24S8: bytesPerPixel = 4; break; case SpecialFormat::R5G6B5: case SpecialFormat::R5G5B5A1: case SpecialFormat::R4G4B4A4: bytesPerPixel = 2; break; case SpecialFormat::D32S8: bytesPerPixel = 8; break; case SpecialFormat::D16S8: case SpecialFormat::YUV: case SpecialFormat::R4G4: RDCERR("Unsupported file format %u", td.format.specialFormat); return false; default: bytesPerPixel = td.format.compCount * td.format.compByteWidth; } rowPitch = td.width * bytesPerPixel; slicePitch = rowPitch * td.height; } // loop over fetching subresources for(uint32_t s = 0; s < numSlices; s++) { uint32_t slice = s * sliceStride + sliceOffset; for(uint32_t m = 0; m < numMips; m++) { uint32_t mip = m + mipOffset; GetTextureDataParams params; params.forDiskSave = true; params.typeHint = sd.typeHint; params.resolve = resolveSamples; params.remap = downcast ? eRemap_RGBA8 : eRemap_None; params.blackPoint = sd.comp.blackPoint; params.whitePoint = sd.comp.whitePoint; size_t datasize = 0; byte *bytes = m_pDevice->GetTextureData(liveid, slice, mip, params, datasize); if(bytes == NULL) { RDCERR("Couldn't get bytes for mip %u, slice %u", mip, slice); for(size_t i = 0; i < subdata.size(); i++) delete[] subdata[i]; return false; } if(td.depth == 1) { subdata.push_back(bytes); continue; } uint32_t mipSlicePitch = slicePitch; uint32_t w = RDCMAX(1U, td.width >> m); uint32_t h = RDCMAX(1U, td.height >> m); uint32_t d = RDCMAX(1U, td.depth >> m); if(blockformat) { mipSlicePitch = RDCMAX(1U, ((w + 3) / 4)) * blockSize * RDCMAX(1U, h / 4); } else { mipSlicePitch = w * bytesPerPixel * h; } // we don't support slice ranges, only all-or-nothing // we're also not dealing with multisampled slices if // depth > 1. So if we only want one slice out of a 3D texture // then make sure we get it if(numSlices == 1) { byte *depthslice = new byte[mipSlicePitch]; byte *b = bytes + mipSlicePitch * sliceOffset; memcpy(depthslice, b, slicePitch); subdata.push_back(depthslice); delete[] bytes; continue; } s += (d - 1); byte *b = bytes; // add each depth slice as a separate subdata for(uint32_t di = 0; di < d; di++) { byte *depthslice = new byte[mipSlicePitch]; memcpy(depthslice, b, mipSlicePitch); subdata.push_back(depthslice); b += mipSlicePitch; } delete[] bytes; } } // should have been handled above, but verify incoming data is RGBA8 if(sd.slice.slicesAsGrid && td.format.compByteWidth == 1 && td.format.compCount == 4) { uint32_t sliceWidth = td.width; uint32_t sliceHeight = td.height; uint32_t sliceGridHeight = (td.arraysize * td.depth) / sd.slice.sliceGridWidth; if((td.arraysize * td.depth) % sd.slice.sliceGridWidth != 0) sliceGridHeight++; td.width *= sd.slice.sliceGridWidth; td.height *= sliceGridHeight; byte *combinedData = new byte[td.width * td.height * td.format.compCount]; memset(combinedData, 0, td.width * td.height * td.format.compCount); for(size_t i = 0; i < subdata.size(); i++) { uint32_t gridx = (uint32_t)i % sd.slice.sliceGridWidth; uint32_t gridy = (uint32_t)i / sd.slice.sliceGridWidth; uint32_t yoffs = gridy * sliceHeight; uint32_t xoffs = gridx * sliceWidth; for(uint32_t y = 0; y < sliceHeight; y++) { for(uint32_t x = 0; x < sliceWidth; x++) { uint32_t *srcpix = (uint32_t *)&subdata[i][(y * sliceWidth + x) * 4 + 0]; uint32_t *dstpix = (uint32_t *)&combinedData[((y + yoffs) * td.width + x + xoffs) * 4 + 0]; *dstpix = *srcpix; } } delete[] subdata[i]; } subdata.resize(1); subdata[0] = combinedData; rowPitch = td.width * 4; } // should have been handled above, but verify incoming data is RGBA8 and 6 slices if(sd.slice.cubeCruciform && td.format.compByteWidth == 1 && td.format.compCount == 4 && subdata.size() == 6) { uint32_t sliceWidth = td.width; uint32_t sliceHeight = td.height; td.width *= 4; td.height *= 3; byte *combinedData = new byte[td.width * td.height * td.format.compCount]; memset(combinedData, 0, td.width * td.height * td.format.compCount); /* Y X=0 1 2 3 = +---+ 0 |+y | |[2]| +---+---+---+---+ 1 |-x |+z |+x |-z | |[1]|[4]|[0]|[5]| +---+---+---+---+ 2 |-y | |[3]| +---+ */ uint32_t gridx[6] = {2, 0, 1, 1, 1, 3}; uint32_t gridy[6] = {1, 1, 0, 2, 1, 1}; for(size_t i = 0; i < subdata.size(); i++) { uint32_t yoffs = gridy[i] * sliceHeight; uint32_t xoffs = gridx[i] * sliceWidth; for(uint32_t y = 0; y < sliceHeight; y++) { for(uint32_t x = 0; x < sliceWidth; x++) { uint32_t *srcpix = (uint32_t *)&subdata[i][(y * sliceWidth + x) * 4 + 0]; uint32_t *dstpix = (uint32_t *)&combinedData[((y + yoffs) * td.width + x + xoffs) * 4 + 0]; *dstpix = *srcpix; } } delete[] subdata[i]; } subdata.resize(1); subdata[0] = combinedData; rowPitch = td.width * 4; } int numComps = td.format.compCount; // if we want a grayscale image of one channel, splat it across all channels // and set alpha to full if(sd.channelExtract >= 0 && td.format.compByteWidth == 1 && (uint32_t)sd.channelExtract < td.format.compCount) { uint32_t cc = td.format.compCount; for(uint32_t y = 0; y < td.height; y++) { for(uint32_t x = 0; x < td.width; x++) { subdata[0][(y * td.width + x) * cc + 0] = subdata[0][(y * td.width + x) * cc + sd.channelExtract]; if(cc >= 2) subdata[0][(y * td.width + x) * cc + 1] = subdata[0][(y * td.width + x) * cc + sd.channelExtract]; if(cc >= 3) subdata[0][(y * td.width + x) * cc + 2] = subdata[0][(y * td.width + x) * cc + sd.channelExtract]; if(cc >= 4) subdata[0][(y * td.width + x) * cc + 3] = 255; } } } // handle formats that don't support alpha if(numComps == 4 && (sd.destType == FileType::BMP || sd.destType == FileType::JPG)) { byte *nonalpha = new byte[td.width * td.height * 3]; for(uint32_t y = 0; y < td.height; y++) { for(uint32_t x = 0; x < td.width; x++) { byte r = subdata[0][(y * td.width + x) * 4 + 0]; byte g = subdata[0][(y * td.width + x) * 4 + 1]; byte b = subdata[0][(y * td.width + x) * 4 + 2]; byte a = subdata[0][(y * td.width + x) * 4 + 3]; if(sd.alpha != AlphaMapping::Discard) { FloatVector col = sd.alphaCol; if(sd.alpha == AlphaMapping::BlendToCheckerboard) { bool lightSquare = ((x / 64) % 2) == ((y / 64) % 2); col = lightSquare ? sd.alphaCol : sd.alphaColSecondary; } col.x = powf(col.x, 1.0f / 2.2f); col.y = powf(col.y, 1.0f / 2.2f); col.z = powf(col.z, 1.0f / 2.2f); FloatVector pixel = FloatVector(float(r) / 255.0f, float(g) / 255.0f, float(b) / 255.0f, float(a) / 255.0f); pixel.x = pixel.x * pixel.w + col.x * (1.0f - pixel.w); pixel.y = pixel.y * pixel.w + col.y * (1.0f - pixel.w); pixel.z = pixel.z * pixel.w + col.z * (1.0f - pixel.w); r = byte(pixel.x * 255.0f); g = byte(pixel.y * 255.0f); b = byte(pixel.z * 255.0f); } nonalpha[(y * td.width + x) * 3 + 0] = r; nonalpha[(y * td.width + x) * 3 + 1] = g; nonalpha[(y * td.width + x) * 3 + 2] = b; } } delete[] subdata[0]; subdata[0] = nonalpha; numComps = 3; rowPitch = td.width * 3; } // assume that (R,G,0) is better mapping than (Y,A) for 2 component data if(numComps == 2 && (sd.destType == FileType::BMP || sd.destType == FileType::JPG || sd.destType == FileType::PNG || sd.destType == FileType::TGA)) { byte *rg0 = new byte[td.width * td.height * 3]; for(uint32_t y = 0; y < td.height; y++) { for(uint32_t x = 0; x < td.width; x++) { byte r = subdata[0][(y * td.width + x) * 2 + 0]; byte g = subdata[0][(y * td.width + x) * 2 + 1]; rg0[(y * td.width + x) * 3 + 0] = r; rg0[(y * td.width + x) * 3 + 1] = g; rg0[(y * td.width + x) * 3 + 2] = 0; // if we're greyscaling the image, then keep the greyscale here. if(sd.channelExtract >= 0) rg0[(y * td.width + x) * 3 + 2] = r; } } delete[] subdata[0]; subdata[0] = rg0; numComps = 3; rowPitch = td.width * 3; } FILE *f = FileIO::fopen(path, "wb"); if(!f) { success = false; } else { if(sd.destType == FileType::DDS) { dds_data ddsData; ddsData.width = td.width; ddsData.height = td.height; ddsData.depth = td.depth; ddsData.format = td.format; ddsData.mips = numMips; ddsData.slices = numSlices / td.depth; ddsData.subdata = &subdata[0]; ddsData.cubemap = td.cubemap && numSlices == 6; success = write_dds_to_file(f, ddsData); } else if(sd.destType == FileType::BMP) { int ret = stbi_write_bmp_to_func(fileWriteFunc, (void *)f, td.width, td.height, numComps, subdata[0]); success = (ret != 0); } else if(sd.destType == FileType::PNG) { // discard alpha if requested for(uint32_t p = 0; sd.alpha == AlphaMapping::Discard && p < td.width * td.height; p++) subdata[0][p * 4 + 3] = 255; int ret = stbi_write_png_to_func(fileWriteFunc, (void *)f, td.width, td.height, numComps, subdata[0], rowPitch); success = (ret != 0); } else if(sd.destType == FileType::TGA) { // discard alpha if requested for(uint32_t p = 0; sd.alpha == AlphaMapping::Discard && p < td.width * td.height; p++) subdata[0][p * 4 + 3] = 255; int ret = stbi_write_tga_to_func(fileWriteFunc, (void *)f, td.width, td.height, numComps, subdata[0]); success = (ret != 0); } else if(sd.destType == FileType::JPG) { jpge::params p; p.m_quality = sd.jpegQuality; int len = td.width * td.height * td.format.compCount; // ensure buffer is at least 1024 if(len < 1024) len = 1024; char *jpgdst = new char[len]; success = jpge::compress_image_to_jpeg_file_in_memory(jpgdst, len, td.width, td.height, numComps, subdata[0], p); if(success) fwrite(jpgdst, 1, len, f); delete[] jpgdst; } else if(sd.destType == FileType::HDR || sd.destType == FileType::EXR) { float *fldata = NULL; float *abgr[4] = {NULL, NULL, NULL, NULL}; if(sd.destType == FileType::HDR) { fldata = new float[td.width * td.height * 4]; } else { abgr[0] = new float[td.width * td.height]; abgr[1] = new float[td.width * td.height]; abgr[2] = new float[td.width * td.height]; abgr[3] = new float[td.width * td.height]; } byte *srcData = subdata[0]; ResourceFormat saveFmt = td.format; if(saveFmt.compType == CompType::Typeless) saveFmt.compType = sd.typeHint; if(saveFmt.compType == CompType::Typeless) saveFmt.compType = saveFmt.compByteWidth == 4 ? CompType::Float : CompType::UNorm; uint32_t pixStride = saveFmt.compCount * saveFmt.compByteWidth; // 24-bit depth still has a stride of 4 bytes. if(saveFmt.compType == CompType::Depth && pixStride == 3) pixStride = 4; for(uint32_t y = 0; y < td.height; y++) { for(uint32_t x = 0; x < td.width; x++) { float r = 0.0f; float g = 0.0f; float b = 0.0f; float a = 1.0f; if(saveFmt.special && saveFmt.specialFormat == SpecialFormat::R10G10B10A2) { uint32_t *u32 = (uint32_t *)srcData; Vec4f vec = ConvertFromR10G10B10A2(*u32); r = vec.x; g = vec.y; b = vec.z; a = vec.w; srcData += 4; } else if(saveFmt.special && saveFmt.specialFormat == SpecialFormat::R11G11B10) { uint32_t *u32 = (uint32_t *)srcData; Vec3f vec = ConvertFromR11G11B10(*u32); r = vec.x; g = vec.y; b = vec.z; a = 1.0f; srcData += 4; } else { if(saveFmt.compCount >= 1) r = ConvertComponent(saveFmt, srcData + saveFmt.compByteWidth * 0); if(saveFmt.compCount >= 2) g = ConvertComponent(saveFmt, srcData + saveFmt.compByteWidth * 1); if(saveFmt.compCount >= 3) b = ConvertComponent(saveFmt, srcData + saveFmt.compByteWidth * 2); if(saveFmt.compCount >= 4) a = ConvertComponent(saveFmt, srcData + saveFmt.compByteWidth * 3); srcData += pixStride; } if(saveFmt.bgraOrder) std::swap(r, b); // HDR can't represent negative values if(sd.destType == FileType::HDR) { r = RDCMAX(r, 0.0f); g = RDCMAX(g, 0.0f); b = RDCMAX(b, 0.0f); a = RDCMAX(a, 0.0f); } if(sd.channelExtract == 0) { g = b = r; a = 1.0f; } if(sd.channelExtract == 1) { r = b = g; a = 1.0f; } if(sd.channelExtract == 2) { r = g = b; a = 1.0f; } if(sd.channelExtract == 3) { r = g = b = a; a = 1.0f; } if(fldata) { fldata[(y * td.width + x) * 4 + 0] = r; fldata[(y * td.width + x) * 4 + 1] = g; fldata[(y * td.width + x) * 4 + 2] = b; fldata[(y * td.width + x) * 4 + 3] = a; } else { abgr[0][(y * td.width + x)] = a; abgr[1][(y * td.width + x)] = b; abgr[2][(y * td.width + x)] = g; abgr[3][(y * td.width + x)] = r; } } } if(sd.destType == FileType::HDR) { int ret = stbi_write_hdr_to_func(fileWriteFunc, (void *)f, td.width, td.height, 4, fldata); success = (ret != 0); } else if(sd.destType == FileType::EXR) { const char *err = NULL; EXRImage exrImage; InitEXRImage(&exrImage); int pixTypes[4] = {TINYEXR_PIXELTYPE_FLOAT, TINYEXR_PIXELTYPE_FLOAT, TINYEXR_PIXELTYPE_FLOAT, TINYEXR_PIXELTYPE_FLOAT}; int reqTypes[4] = {TINYEXR_PIXELTYPE_HALF, TINYEXR_PIXELTYPE_HALF, TINYEXR_PIXELTYPE_HALF, TINYEXR_PIXELTYPE_HALF}; // must be in this order as many viewers don't pay attention to channels and just assume // they are in this order const char *bgraNames[4] = {"A", "B", "G", "R"}; exrImage.num_channels = 4; exrImage.channel_names = bgraNames; exrImage.images = (unsigned char **)abgr; exrImage.width = td.width; exrImage.height = td.height; exrImage.pixel_types = pixTypes; exrImage.requested_pixel_types = reqTypes; unsigned char *mem = NULL; size_t ret = SaveMultiChannelEXRToMemory(&exrImage, &mem, &err); success = (ret > 0); if(success) FileIO::fwrite(mem, 1, ret, f); else RDCERR("Error saving EXR file %d: '%s'", ret, err); free(mem); } if(fldata) { delete[] fldata; } else { delete[] abgr[0]; delete[] abgr[1]; delete[] abgr[2]; delete[] abgr[3]; } } FileIO::fclose(f); } for(size_t i = 0; i < subdata.size(); i++) delete[] subdata[i]; return success; } rdctype::array<PixelModification> ReplayController::PixelHistory(ResourceId target, uint32_t x, uint32_t y, uint32_t slice, uint32_t mip, uint32_t sampleIdx, CompType typeHint) { rdctype::array<PixelModification> ret; for(size_t t = 0; t < m_Textures.size(); t++) { if(m_Textures[t].ID == target) { if(x >= m_Textures[t].width || y >= m_Textures[t].height) { RDCDEBUG("PixelHistory out of bounds on %llu (%u,%u) vs (%u,%u)", target, x, y, m_Textures[t].width, m_Textures[t].height); return ret; } if(m_Textures[t].msSamp == 1) sampleIdx = ~0U; slice = RDCCLAMP(slice, 0U, m_Textures[t].arraysize); mip = RDCCLAMP(mip, 0U, m_Textures[t].mips); break; } } auto usage = m_pDevice->GetUsage(m_pDevice->GetLiveID(target)); vector<EventUsage> events; for(size_t i = 0; i < usage.size(); i++) { if(usage[i].eventID > m_EventID) continue; switch(usage[i].usage) { case ResourceUsage::VertexBuffer: case ResourceUsage::IndexBuffer: case ResourceUsage::VS_Constants: case ResourceUsage::HS_Constants: case ResourceUsage::DS_Constants: case ResourceUsage::GS_Constants: case ResourceUsage::PS_Constants: case ResourceUsage::CS_Constants: case ResourceUsage::All_Constants: case ResourceUsage::VS_Resource: case ResourceUsage::HS_Resource: case ResourceUsage::DS_Resource: case ResourceUsage::GS_Resource: case ResourceUsage::PS_Resource: case ResourceUsage::CS_Resource: case ResourceUsage::All_Resource: case ResourceUsage::InputTarget: case ResourceUsage::CopySrc: case ResourceUsage::ResolveSrc: case ResourceUsage::Barrier: case ResourceUsage::Indirect: // read-only, not a valid pixel history event continue; case ResourceUsage::Unused: case ResourceUsage::StreamOut: case ResourceUsage::VS_RWResource: case ResourceUsage::HS_RWResource: case ResourceUsage::DS_RWResource: case ResourceUsage::GS_RWResource: case ResourceUsage::PS_RWResource: case ResourceUsage::CS_RWResource: case ResourceUsage::All_RWResource: case ResourceUsage::ColorTarget: case ResourceUsage::DepthStencilTarget: case ResourceUsage::Clear: case ResourceUsage::Copy: case ResourceUsage::CopyDst: case ResourceUsage::Resolve: case ResourceUsage::ResolveDst: case ResourceUsage::GenMips: // writing - include in pixel history events break; } events.push_back(usage[i]); } if(events.empty()) { RDCDEBUG("Target %llu not written to before %u", target, m_EventID); return ret; } ret = m_pDevice->PixelHistory(events, m_pDevice->GetLiveID(target), x, y, slice, mip, sampleIdx, typeHint); SetFrameEvent(m_EventID, true); return ret; } ShaderDebugTrace *ReplayController::DebugVertex(uint32_t vertid, uint32_t instid, uint32_t idx, uint32_t instOffset, uint32_t vertOffset) { ShaderDebugTrace *ret = new ShaderDebugTrace; *ret = m_pDevice->DebugVertex(m_EventID, vertid, instid, idx, instOffset, vertOffset); SetFrameEvent(m_EventID, true); return ret; } ShaderDebugTrace *ReplayController::DebugPixel(uint32_t x, uint32_t y, uint32_t sample, uint32_t primitive) { ShaderDebugTrace *ret = new ShaderDebugTrace; *ret = m_pDevice->DebugPixel(m_EventID, x, y, sample, primitive); SetFrameEvent(m_EventID, true); return ret; } ShaderDebugTrace *ReplayController::DebugThread(uint32_t groupid[3], uint32_t threadid[3]) { ShaderDebugTrace *ret = new ShaderDebugTrace; *ret = m_pDevice->DebugThread(m_EventID, groupid, threadid); SetFrameEvent(m_EventID, true); return ret; } void ReplayController::FreeTrace(ShaderDebugTrace *trace) { delete trace; } rdctype::array<ShaderVariable> ReplayController::GetCBufferVariableContents( ResourceId shader, const char *entryPoint, uint32_t cbufslot, ResourceId buffer, uint64_t offs) { vector<byte> data; if(buffer != ResourceId()) m_pDevice->GetBufferData(m_pDevice->GetLiveID(buffer), offs, 0, data); vector<ShaderVariable> v; m_pDevice->FillCBufferVariables(m_pDevice->GetLiveID(shader), entryPoint, cbufslot, v, data); return v; } rdctype::array<WindowingSystem> ReplayController::GetSupportedWindowSystems() { return m_pDevice->GetSupportedWindowSystems(); } ReplayOutput *ReplayController::CreateOutput(WindowingSystem system, void *data, ReplayOutputType type) { ReplayOutput *out = new ReplayOutput(this, system, data, type); m_Outputs.push_back(out); m_pDevice->ReplayLog(m_EventID, eReplay_WithoutDraw); out->SetFrameEvent(m_EventID); m_pDevice->ReplayLog(m_EventID, eReplay_OnlyDraw); return out; } void ReplayController::ShutdownOutput(IReplayOutput *output) { RDCUNIMPLEMENTED("Shutting down individual outputs"); } void ReplayController::Shutdown() { delete this; } rdctype::pair<ResourceId, rdctype::str> ReplayController::BuildTargetShader( const char *entry, const char *source, const uint32_t compileFlags, ShaderStage type) { ResourceId id; string errs; switch(type) { case ShaderStage::Vertex: case ShaderStage::Hull: case ShaderStage::Domain: case ShaderStage::Geometry: case ShaderStage::Pixel: case ShaderStage::Compute: break; default: RDCERR("Unexpected type in BuildShader!"); return rdctype::pair<ResourceId, rdctype::str>(); } m_pDevice->BuildTargetShader(source, entry, compileFlags, type, &id, &errs); if(id != ResourceId()) m_TargetResources.insert(id); return rdctype::make_pair<ResourceId, rdctype::str>(id, errs); } rdctype::pair<ResourceId, rdctype::str> ReplayController::BuildCustomShader( const char *entry, const char *source, const uint32_t compileFlags, ShaderStage type) { ResourceId id; string errs; switch(type) { case ShaderStage::Vertex: case ShaderStage::Hull: case ShaderStage::Domain: case ShaderStage::Geometry: case ShaderStage::Pixel: case ShaderStage::Compute: break; default: RDCERR("Unexpected type in BuildShader!"); return rdctype::pair<ResourceId, rdctype::str>(); } m_pDevice->BuildCustomShader(source, entry, compileFlags, type, &id, &errs); if(id != ResourceId()) m_CustomShaders.insert(id); return rdctype::make_pair<ResourceId, rdctype::str>(id, errs); } void ReplayController::FreeTargetResource(ResourceId id) { m_TargetResources.erase(id); m_pDevice->FreeTargetResource(id); } void ReplayController::FreeCustomShader(ResourceId id) { m_CustomShaders.erase(id); m_pDevice->FreeCustomShader(id); } void ReplayController::ReplaceResource(ResourceId from, ResourceId to) { m_pDevice->ReplaceResource(from, to); SetFrameEvent(m_EventID, true); for(size_t i = 0; i < m_Outputs.size(); i++) if(m_Outputs[i]->GetType() != ReplayOutputType::Headless) m_Outputs[i]->Display(); } void ReplayController::RemoveReplacement(ResourceId id) { m_pDevice->RemoveReplacement(id); SetFrameEvent(m_EventID, true); for(size_t i = 0; i < m_Outputs.size(); i++) if(m_Outputs[i]->GetType() != ReplayOutputType::Headless) m_Outputs[i]->Display(); } ReplayStatus ReplayController::CreateDevice(const char *logfile) { RDCLOG("Creating replay device for %s", logfile); RDCDriver driverType = RDC_Unknown; string driverName = ""; uint64_t fileMachineIdent = 0; auto status = RenderDoc::Inst().FillInitParams(logfile, driverType, driverName, fileMachineIdent, NULL); if(driverType == RDC_Unknown || driverName == "" || status != ReplayStatus::Succeeded) { RDCERR("Couldn't get device type from log"); return status; } IReplayDriver *driver = NULL; status = RenderDoc::Inst().CreateReplayDriver(driverType, logfile, &driver); if(driver && status == ReplayStatus::Succeeded) { RDCLOG("Created replay driver."); return PostCreateInit(driver); } RDCERR("Couldn't create a replay device :(."); return status; } ReplayStatus ReplayController::SetDevice(IReplayDriver *device) { if(device) { RDCLOG("Got replay driver."); return PostCreateInit(device); } RDCERR("Given invalid replay driver."); return ReplayStatus::InternalError; } ReplayStatus ReplayController::PostCreateInit(IReplayDriver *device) { m_pDevice = device; m_pDevice->ReadLogInitialisation(); FetchPipelineState(); m_FrameRecord = m_pDevice->GetFrameRecord(); SetupDrawcallPointers(&m_Drawcalls, m_FrameRecord.drawcallList, NULL, NULL); return ReplayStatus::Succeeded; } void ReplayController::FileChanged() { m_pDevice->FileChanged(); } bool ReplayController::HasCallstacks() { return m_pDevice->HasCallstacks(); } APIProperties ReplayController::GetAPIProperties() { return m_pDevice->GetAPIProperties(); } bool ReplayController::InitResolver() { m_pDevice->InitCallstackResolver(); return m_pDevice->GetCallstackResolver() != NULL; } void ReplayController::FetchPipelineState() { m_pDevice->SavePipelineState(); m_D3D11PipelineState = m_pDevice->GetD3D11PipelineState(); m_D3D12PipelineState = m_pDevice->GetD3D12PipelineState(); m_GLPipelineState = m_pDevice->GetGLPipelineState(); m_VulkanPipelineState = m_pDevice->GetVulkanPipelineState(); { D3D11Pipe::Shader *stages[] = { &m_D3D11PipelineState.m_VS, &m_D3D11PipelineState.m_HS, &m_D3D11PipelineState.m_DS, &m_D3D11PipelineState.m_GS, &m_D3D11PipelineState.m_PS, &m_D3D11PipelineState.m_CS, }; for(int i = 0; i < 6; i++) if(stages[i]->Object != ResourceId()) stages[i]->ShaderDetails = m_pDevice->GetShader(m_pDevice->GetLiveID(stages[i]->Object), ""); } { D3D12Pipe::Shader *stages[] = { &m_D3D12PipelineState.m_VS, &m_D3D12PipelineState.m_HS, &m_D3D12PipelineState.m_DS, &m_D3D12PipelineState.m_GS, &m_D3D12PipelineState.m_PS, &m_D3D12PipelineState.m_CS, }; for(int i = 0; i < 6; i++) if(stages[i]->Object != ResourceId()) stages[i]->ShaderDetails = m_pDevice->GetShader(m_pDevice->GetLiveID(stages[i]->Object), ""); } { GLPipe::Shader *stages[] = { &m_GLPipelineState.m_VS, &m_GLPipelineState.m_TCS, &m_GLPipelineState.m_TES, &m_GLPipelineState.m_GS, &m_GLPipelineState.m_FS, &m_GLPipelineState.m_CS, }; for(int i = 0; i < 6; i++) if(stages[i]->Object != ResourceId()) stages[i]->ShaderDetails = m_pDevice->GetShader(m_pDevice->GetLiveID(stages[i]->Object), ""); } { VKPipe::Shader *stages[] = { &m_VulkanPipelineState.m_VS, &m_VulkanPipelineState.m_TCS, &m_VulkanPipelineState.m_TES, &m_VulkanPipelineState.m_GS, &m_VulkanPipelineState.m_FS, &m_VulkanPipelineState.m_CS, }; for(int i = 0; i < 6; i++) if(stages[i]->Object != ResourceId()) stages[i]->ShaderDetails = m_pDevice->GetShader(m_pDevice->GetLiveID(stages[i]->Object), stages[i]->entryPoint.elems); } } extern "C" RENDERDOC_API void RENDERDOC_CC ReplayRenderer_GetAPIProperties(IReplayController *rend, APIProperties *props) { if(props) *props = rend->GetAPIProperties(); } extern "C" RENDERDOC_API void RENDERDOC_CC ReplayRenderer_GetSupportedWindowSystems( IReplayController *rend, rdctype::array<WindowingSystem> *systems) { *systems = rend->GetSupportedWindowSystems(); } extern "C" RENDERDOC_API IReplayOutput *RENDERDOC_CC ReplayRenderer_CreateOutput( IReplayController *rend, WindowingSystem system, void *data, ReplayOutputType type) { return rend->CreateOutput(system, data, type); } extern "C" RENDERDOC_API void RENDERDOC_CC ReplayRenderer_Shutdown(IReplayController *rend) { rend->Shutdown(); } extern "C" RENDERDOC_API void RENDERDOC_CC ReplayRenderer_ShutdownOutput(IReplayController *rend, IReplayOutput *output) { rend->ShutdownOutput(output); } extern "C" RENDERDOC_API void RENDERDOC_CC ReplayRenderer_FileChanged(IReplayController *rend) { rend->FileChanged(); } extern "C" RENDERDOC_API bool32 RENDERDOC_CC ReplayRenderer_HasCallstacks(IReplayController *rend) { return rend->HasCallstacks(); } extern "C" RENDERDOC_API bool32 RENDERDOC_CC ReplayRenderer_InitResolver(IReplayController *rend) { return rend->InitResolver(); } extern "C" RENDERDOC_API void RENDERDOC_CC ReplayRenderer_SetFrameEvent(IReplayController *rend, uint32_t eventID, bool32 force) { rend->SetFrameEvent(eventID, force != 0); } extern "C" RENDERDOC_API void RENDERDOC_CC ReplayRenderer_GetD3D11PipelineState(IReplayController *rend, D3D11Pipe::State *state) { *state = rend->GetD3D11PipelineState(); } extern "C" RENDERDOC_API void RENDERDOC_CC ReplayRenderer_GetD3D12PipelineState(IReplayController *rend, D3D12Pipe::State *state) { *state = rend->GetD3D12PipelineState(); } extern "C" RENDERDOC_API void RENDERDOC_CC ReplayRenderer_GetGLPipelineState(IReplayController *rend, GLPipe::State *state) { *state = rend->GetGLPipelineState(); } extern "C" RENDERDOC_API void RENDERDOC_CC ReplayRenderer_GetVulkanPipelineState(IReplayController *rend, VKPipe::State *state) { *state = rend->GetVulkanPipelineState(); } extern "C" RENDERDOC_API void RENDERDOC_CC ReplayRenderer_BuildCustomShader( IReplayController *rend, const char *entry, const char *source, const uint32_t compileFlags, ShaderStage type, ResourceId *shaderID, rdctype::str *errors) { if(shaderID == NULL) return; auto ret = rend->BuildCustomShader(entry, source, compileFlags, type); *shaderID = ret.first; if(errors) *errors = ret.second; } extern "C" RENDERDOC_API void RENDERDOC_CC ReplayRenderer_FreeCustomShader(IReplayController *rend, ResourceId id) { rend->FreeCustomShader(id); } extern "C" RENDERDOC_API void RENDERDOC_CC ReplayRenderer_BuildTargetShader( IReplayController *rend, const char *entry, const char *source, const uint32_t compileFlags, ShaderStage type, ResourceId *shaderID, rdctype::str *errors) { if(shaderID == NULL) return; auto ret = rend->BuildTargetShader(entry, source, compileFlags, type); *shaderID = ret.first; if(errors) *errors = ret.second; } extern "C" RENDERDOC_API void RENDERDOC_CC ReplayRenderer_ReplaceResource(IReplayController *rend, ResourceId from, ResourceId to) { rend->ReplaceResource(from, to); } extern "C" RENDERDOC_API void RENDERDOC_CC ReplayRenderer_RemoveReplacement(IReplayController *rend, ResourceId id) { rend->RemoveReplacement(id); } extern "C" RENDERDOC_API void RENDERDOC_CC ReplayRenderer_FreeTargetResource(IReplayController *rend, ResourceId id) { rend->FreeTargetResource(id); } extern "C" RENDERDOC_API void RENDERDOC_CC ReplayRenderer_GetFrameInfo(IReplayController *rend, FrameDescription *frame) { *frame = rend->GetFrameInfo(); } extern "C" RENDERDOC_API void RENDERDOC_CC ReplayRenderer_GetDrawcalls(IReplayController *rend, rdctype::array<DrawcallDescription> *draws) { *draws = rend->GetDrawcalls(); } extern "C" RENDERDOC_API void RENDERDOC_CC ReplayRenderer_FetchCounters(IReplayController *rend, GPUCounter *counters, uint32_t numCounters, rdctype::array<CounterResult> *results) { rdctype::array<GPUCounter> counterArray; create_array_init(counterArray, (size_t)numCounters, counters); *results = rend->FetchCounters(counterArray); } extern "C" RENDERDOC_API void RENDERDOC_CC ReplayRenderer_EnumerateCounters(IReplayController *rend, rdctype::array<GPUCounter> *counters) { *counters = rend->EnumerateCounters(); } extern "C" RENDERDOC_API void RENDERDOC_CC ReplayRenderer_DescribeCounter(IReplayController *rend, GPUCounter counterID, CounterDescription *desc) { *desc = rend->DescribeCounter(counterID); } extern "C" RENDERDOC_API void RENDERDOC_CC ReplayRenderer_GetTextures(IReplayController *rend, rdctype::array<TextureDescription> *texs) { *texs = rend->GetTextures(); } extern "C" RENDERDOC_API void RENDERDOC_CC ReplayRenderer_GetBuffers(IReplayController *rend, rdctype::array<BufferDescription> *bufs) { *bufs = rend->GetBuffers(); } extern "C" RENDERDOC_API void RENDERDOC_CC ReplayRenderer_GetResolve(IReplayController *rend, uint64_t *callstack, uint32_t callstackLen, rdctype::array<rdctype::str> *trace) { rdctype::array<uint64_t> stack; create_array_init(stack, (size_t)callstackLen, callstack); *trace = rend->GetResolve(stack); } extern "C" RENDERDOC_API void RENDERDOC_CC ReplayRenderer_GetDebugMessages(IReplayController *rend, rdctype::array<DebugMessage> *msgs) { *msgs = rend->GetDebugMessages(); } extern "C" RENDERDOC_API void RENDERDOC_CC ReplayRenderer_PixelHistory( IReplayController *rend, ResourceId target, uint32_t x, uint32_t y, uint32_t slice, uint32_t mip, uint32_t sampleIdx, CompType typeHint, rdctype::array<PixelModification> *history) { *history = rend->PixelHistory(target, x, y, slice, mip, sampleIdx, typeHint); } extern "C" RENDERDOC_API void RENDERDOC_CC ReplayRenderer_DebugVertex(IReplayController *rend, uint32_t vertid, uint32_t instid, uint32_t idx, uint32_t instOffset, uint32_t vertOffset, ShaderDebugTrace *trace) { ShaderDebugTrace *ret = rend->DebugVertex(vertid, instid, idx, instOffset, vertOffset); *trace = *ret; delete ret; } extern "C" RENDERDOC_API void RENDERDOC_CC ReplayRenderer_DebugPixel(IReplayController *rend, uint32_t x, uint32_t y, uint32_t sample, uint32_t primitive, ShaderDebugTrace *trace) { ShaderDebugTrace *ret = rend->DebugPixel(x, y, sample, primitive); *trace = *ret; delete ret; } extern "C" RENDERDOC_API void RENDERDOC_CC ReplayRenderer_DebugThread(IReplayController *rend, uint32_t groupid[3], uint32_t threadid[3], ShaderDebugTrace *trace) { ShaderDebugTrace *ret = rend->DebugThread(groupid, threadid); *trace = *ret; delete ret; } extern "C" RENDERDOC_API void RENDERDOC_CC ReplayRenderer_GetUsage(IReplayController *rend, ResourceId id, rdctype::array<EventUsage> *usage) { *usage = rend->GetUsage(id); } extern "C" RENDERDOC_API void RENDERDOC_CC ReplayRenderer_GetCBufferVariableContents( IReplayController *rend, ResourceId shader, const char *entryPoint, uint32_t cbufslot, ResourceId buffer, uint64_t offs, rdctype::array<ShaderVariable> *vars) { *vars = rend->GetCBufferVariableContents(shader, entryPoint, cbufslot, buffer, offs); } extern "C" RENDERDOC_API bool32 RENDERDOC_CC ReplayRenderer_SaveTexture(IReplayController *rend, const TextureSave &saveData, const char *path) { return rend->SaveTexture(saveData, path); } extern "C" RENDERDOC_API void RENDERDOC_CC ReplayRenderer_GetPostVSData(IReplayController *rend, uint32_t instID, MeshDataStage stage, MeshFormat *data) { *data = rend->GetPostVSData(instID, stage); } extern "C" RENDERDOC_API void RENDERDOC_CC ReplayRenderer_GetBufferData(IReplayController *rend, ResourceId buff, uint64_t offset, uint64_t len, rdctype::array<byte> *data) { *data = rend->GetBufferData(buff, offset, len); } extern "C" RENDERDOC_API void RENDERDOC_CC ReplayRenderer_GetTextureData(IReplayController *rend, ResourceId tex, uint32_t arrayIdx, uint32_t mip, rdctype::array<byte> *data) { *data = rend->GetTextureData(tex, arrayIdx, mip); }
[ "baldurk@baldurk.org" ]
baldurk@baldurk.org
962a5f2a9c685ab044bdd99894979dc3073112c0
0904dad5193e3bdf9455950a5b37e50c42e3337e
/Chapter5/5.5判断字符数组中是否所有的字符都只出现过一次.cpp
81b40e6bbd74c58521f995a04eff4a76dc572993
[]
no_license
dtdongwenbo/coding-interview-guide-according-Zuo-master
f095c1732423d2e7720f453562592bdbe6f5b7d6
1b64563ade41142bd80878af876efe5de6f96ab0
refs/heads/master
2020-06-05T05:39:38.104224
2019-07-04T07:46:35
2019-07-04T07:46:35
192,332,706
0
0
null
null
null
null
MacCentralEurope
C++
false
false
416
cpp
#include <iostream> #include <string> using namespace std; bool isUnique1(string str) { if(str.empty()) return false; bool map[256];//”√bool for(int i = 0;i<str.size();i++) { if(map[str[i]]) return false; map[str[i]] = true; } return true; } int main() { string str1 = "abc"; string str2 = "121"; cout<<isUnique1(str1)<<endl; cout<<isUnique1(str2)<<endl; }
[ "noreply@github.com" ]
noreply@github.com
8f8a80bc7eedc3091b70ee9e04c40b115ce6c1c9
4d9bdc9f2085de71cfc909506cdce63c8a0a1370
/chrome/updater/win/net/network_winhttp.cc
88f9c9ce09f85e0d65e21415dd5c5f7f59b2ac65
[ "BSD-3-Clause" ]
permissive
gdpr69/chromium
5629de8d51b9b789aed3010fdda5e0b2ca3db6b9
2752c22743a71b417e8c257ca6d1cacc8318683e
refs/heads/master
2022-11-06T04:55:02.118967
2020-05-31T09:10:44
2020-05-31T09:10:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
17,864
cc
// Copyright 2019 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/updater/win/net/network_winhttp.h" #include <limits> #include <utility> #include "base/bind.h" #include "base/callback.h" #include "base/callback_helpers.h" #include "base/files/file.h" #include "base/files/file_util.h" #include "base/logging.h" #include "base/numerics/safe_math.h" #include "base/strings/strcat.h" #include "base/strings/string16.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_piece.h" #include "base/strings/stringprintf.h" #include "base/strings/sys_string_conversions.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "base/threading/thread_task_runner_handle.h" #include "chrome/updater/win/net/net_util.h" #include "chrome/updater/win/net/network.h" #include "chrome/updater/win/net/scoped_hinternet.h" #include "chrome/updater/win/util.h" #include "url/url_constants.h" namespace updater { namespace { void CrackUrl(const GURL& url, bool* is_https, std::string* host, int* port, std::string* path_for_request) { if (is_https) *is_https = url.SchemeIs(url::kHttpsScheme); if (host) *host = url.host(); if (port) *port = url.EffectiveIntPort(); if (path_for_request) *path_for_request = url.PathForRequest(); } } // namespace NetworkFetcherWinHTTP::NetworkFetcherWinHTTP(const HINTERNET& session_handle) : main_thread_task_runner_(base::ThreadTaskRunnerHandle::Get()), session_handle_(session_handle) {} NetworkFetcherWinHTTP::~NetworkFetcherWinHTTP() = default; void NetworkFetcherWinHTTP::Close() { request_handle_.reset(); } std::string NetworkFetcherWinHTTP::GetResponseBody() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); return post_response_body_; } HRESULT NetworkFetcherWinHTTP::GetNetError() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); return net_error_; } std::string NetworkFetcherWinHTTP::GetHeaderETag() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); return etag_; } int64_t NetworkFetcherWinHTTP::GetXHeaderRetryAfterSec() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); return xheader_retry_after_sec_; } base::FilePath NetworkFetcherWinHTTP::GetFilePath() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); return file_path_; } int64_t NetworkFetcherWinHTTP::GetContentSize() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); return content_size_; } void NetworkFetcherWinHTTP::PostRequest( const GURL& url, const std::string& post_data, const base::flat_map<std::string, std::string>& post_additional_headers, FetchStartedCallback fetch_started_callback, FetchProgressCallback fetch_progress_callback, FetchCompleteCallback fetch_complete_callback) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); url_ = url; fetch_started_callback_ = std::move(fetch_started_callback); fetch_progress_callback_ = std::move(fetch_progress_callback); fetch_complete_callback_ = std::move(fetch_complete_callback); DCHECK(url.SchemeIsHTTPOrHTTPS()); CrackUrl(url, &is_https_, &host_, &port_, &path_for_request_); verb_ = L"POST"; content_type_ = L"Content-Type: application/json\r\n"; write_data_callback_ = base::BindRepeating(&NetworkFetcherWinHTTP::WriteDataToMemory, this); net_error_ = BeginFetch(post_data, post_additional_headers); if (FAILED(net_error_)) std::move(fetch_complete_callback_).Run(); } void NetworkFetcherWinHTTP::DownloadToFile( const GURL& url, const base::FilePath& file_path, FetchStartedCallback fetch_started_callback, FetchProgressCallback fetch_progress_callback, FetchCompleteCallback fetch_complete_callback) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); url_ = url; file_path_ = file_path; fetch_started_callback_ = std::move(fetch_started_callback); fetch_progress_callback_ = std::move(fetch_progress_callback); fetch_complete_callback_ = std::move(fetch_complete_callback); DCHECK(url.SchemeIsHTTPOrHTTPS()); CrackUrl(url, &is_https_, &host_, &port_, &path_for_request_); verb_ = L"GET"; write_data_callback_ = base::BindRepeating(&NetworkFetcherWinHTTP::WriteDataToFile, this); net_error_ = BeginFetch({}, {}); if (FAILED(net_error_)) std::move(fetch_complete_callback_).Run(); } HRESULT NetworkFetcherWinHTTP::BeginFetch( const std::string& data, const base::flat_map<std::string, std::string>& additional_headers) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); connect_handle_ = Connect(); if (!connect_handle_.get()) return HRESULTFromLastError(); request_handle_ = OpenRequest(); if (!request_handle_.get()) return HRESULTFromLastError(); const auto winhttp_callback = ::WinHttpSetStatusCallback( request_handle_.get(), &NetworkFetcherWinHTTP::WinHttpStatusCallback, WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS, 0); if (winhttp_callback == WINHTTP_INVALID_STATUS_CALLBACK) return HRESULTFromLastError(); auto hr = SetOption(request_handle_.get(), WINHTTP_OPTION_CONTEXT_VALUE, context()); if (FAILED(hr)) return hr; self_ = this; // Disables both saving and sending cookies. hr = SetOption(request_handle_.get(), WINHTTP_OPTION_DISABLE_FEATURE, WINHTTP_DISABLE_COOKIES); if (FAILED(hr)) return hr; if (!content_type_.empty()) { ::WinHttpAddRequestHeaders( request_handle_.get(), content_type_.data(), content_type_.size(), WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE); } for (const auto& header : additional_headers) { const auto raw_header = base::SysUTF8ToWide( base::StrCat({header.first, ": ", header.second, "\r\n"})); ::WinHttpAddRequestHeaders( request_handle_.get(), raw_header.c_str(), raw_header.size(), WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE); } hr = SendRequest(data); if (FAILED(hr)) return hr; return S_OK; } scoped_hinternet NetworkFetcherWinHTTP::Connect() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); return scoped_hinternet(::WinHttpConnect( session_handle_, base::SysUTF8ToWide(host_).c_str(), port_, 0)); } scoped_hinternet NetworkFetcherWinHTTP::OpenRequest() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); uint32_t flags = WINHTTP_FLAG_REFRESH; if (is_https_) flags |= WINHTTP_FLAG_SECURE; return scoped_hinternet(::WinHttpOpenRequest( connect_handle_.get(), verb_.data(), base::SysUTF8ToWide(path_for_request_).c_str(), nullptr, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, flags)); } HRESULT NetworkFetcherWinHTTP::SendRequest(const std::string& data) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); VLOG(2) << data; const uint32_t bytes_to_send = base::saturated_cast<uint32_t>(data.size()); void* request_body = bytes_to_send ? const_cast<char*>(data.c_str()) : WINHTTP_NO_REQUEST_DATA; if (!::WinHttpSendRequest(request_handle_.get(), WINHTTP_NO_ADDITIONAL_HEADERS, 0, request_body, bytes_to_send, bytes_to_send, context())) { return HRESULTFromLastError(); } return S_OK; } void NetworkFetcherWinHTTP::SendRequestComplete() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); base::string16 all; QueryHeadersString( request_handle_.get(), WINHTTP_QUERY_RAW_HEADERS_CRLF | WINHTTP_QUERY_FLAG_REQUEST_HEADERS, WINHTTP_HEADER_NAME_BY_INDEX, &all); VLOG(3) << "request headers: " << all; net_error_ = ReceiveResponse(); if (FAILED(net_error_)) std::move(fetch_complete_callback_).Run(); } HRESULT NetworkFetcherWinHTTP::ReceiveResponse() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (!::WinHttpReceiveResponse(request_handle_.get(), nullptr)) return HRESULTFromLastError(); return S_OK; } void NetworkFetcherWinHTTP::HeadersAvailable() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); base::string16 all; QueryHeadersString(request_handle_.get(), WINHTTP_QUERY_RAW_HEADERS_CRLF, WINHTTP_HEADER_NAME_BY_INDEX, &all); VLOG(3) << "response headers: " << all; int response_code = 0; net_error_ = QueryHeadersInt(request_handle_.get(), WINHTTP_QUERY_STATUS_CODE, WINHTTP_HEADER_NAME_BY_INDEX, &response_code); if (FAILED(net_error_)) { std::move(fetch_complete_callback_).Run(); return; } int content_length = 0; net_error_ = QueryHeadersInt(request_handle_.get(), WINHTTP_QUERY_CONTENT_LENGTH, WINHTTP_HEADER_NAME_BY_INDEX, &content_length); if (FAILED(net_error_)) { std::move(fetch_complete_callback_).Run(); return; } base::string16 etag; if (SUCCEEDED(QueryHeadersString(request_handle_.get(), WINHTTP_QUERY_ETAG, WINHTTP_HEADER_NAME_BY_INDEX, &etag))) { etag_ = base::SysWideToUTF8(etag); } int xheader_retry_after_sec = 0; if (SUCCEEDED(QueryHeadersInt( request_handle_.get(), WINHTTP_QUERY_CUSTOM, base::SysUTF8ToWide( update_client::NetworkFetcher::kHeaderXRetryAfter), &xheader_retry_after_sec))) { xheader_retry_after_sec_ = xheader_retry_after_sec; } std::move(fetch_started_callback_).Run(response_code, content_length); // Start reading the body of response. net_error_ = ReadData(); if (FAILED(net_error_)) std::move(fetch_complete_callback_).Run(); } HRESULT NetworkFetcherWinHTTP::ReadData() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // Use a fixed buffer size, larger than the internal WinHTTP buffer size (8K), // according to the documentation for WinHttpReadData. constexpr size_t kNumBytesToRead = 0x4000; // 16KiB. read_buffer_.resize(kNumBytesToRead); if (!::WinHttpReadData(request_handle_.get(), &read_buffer_.front(), read_buffer_.size(), nullptr)) { return HRESULTFromLastError(); } VLOG(3) << "reading data..."; return S_OK; } void NetworkFetcherWinHTTP::ReadDataComplete(size_t num_bytes_read) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); read_buffer_.resize(num_bytes_read); write_data_callback_.Run(); } void NetworkFetcherWinHTTP::RequestError(const WINHTTP_ASYNC_RESULT* result) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); net_error_ = HRESULTFromUpdaterError(result->dwError); std::move(fetch_complete_callback_).Run(); } void NetworkFetcherWinHTTP::WriteDataToFile() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); constexpr base::TaskTraits kTaskTraits = { base::MayBlock(), base::TaskPriority::BEST_EFFORT, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}; base::ThreadPool::PostTaskAndReplyWithResult( FROM_HERE, kTaskTraits, base::BindOnce(&NetworkFetcherWinHTTP::WriteDataToFileBlocking, this), base::BindOnce(&NetworkFetcherWinHTTP::WriteDataToFileComplete, this)); } // Returns true if EOF is reached. bool NetworkFetcherWinHTTP::WriteDataToFileBlocking() { if (read_buffer_.empty()) { file_.Close(); net_error_ = S_OK; return true; } if (!file_.IsValid()) { file_.Initialize(file_path_, base::File::Flags::FLAG_CREATE_ALWAYS | base::File::Flags::FLAG_WRITE | base::File::Flags::FLAG_SEQUENTIAL_SCAN); if (!file_.IsValid()) { net_error_ = HRESULTFromUpdaterError(file_.error_details()); return false; } } DCHECK(file_.IsValid()); if (file_.WriteAtCurrentPos(&read_buffer_.front(), read_buffer_.size()) == -1) { net_error_ = HRESULTFromUpdaterError(base::File::GetLastFileError()); file_.Close(); base::DeleteFile(file_path_, false); return false; } content_size_ += read_buffer_.size(); return false; } void NetworkFetcherWinHTTP::WriteDataToFileComplete(bool is_eof) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); fetch_progress_callback_.Run(base::saturated_cast<int64_t>(content_size_)); if (is_eof || FAILED(net_error_)) { std::move(fetch_complete_callback_).Run(); return; } net_error_ = ReadData(); if (FAILED(net_error_)) std::move(fetch_complete_callback_).Run(); } void NetworkFetcherWinHTTP::WriteDataToMemory() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (read_buffer_.empty()) { VLOG(2) << post_response_body_; net_error_ = S_OK; std::move(fetch_complete_callback_).Run(); return; } post_response_body_.append(read_buffer_.begin(), read_buffer_.end()); content_size_ += read_buffer_.size(); fetch_progress_callback_.Run(base::saturated_cast<int64_t>(content_size_)); net_error_ = ReadData(); if (FAILED(net_error_)) std::move(fetch_complete_callback_).Run(); } void __stdcall NetworkFetcherWinHTTP::WinHttpStatusCallback(HINTERNET handle, DWORD_PTR context, DWORD status, void* info, DWORD info_len) { DCHECK(handle); DCHECK(context); NetworkFetcherWinHTTP* network_fetcher = reinterpret_cast<NetworkFetcherWinHTTP*>(context); network_fetcher->main_thread_task_runner_->PostTask( FROM_HERE, base::BindOnce(&NetworkFetcherWinHTTP::StatusCallback, base::Unretained(network_fetcher), handle, status, info, info_len)); } void NetworkFetcherWinHTTP::StatusCallback(HINTERNET handle, uint32_t status, void* info, uint32_t info_len) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); base::StringPiece status_string; base::string16 info_string; switch (status) { case WINHTTP_CALLBACK_STATUS_HANDLE_CREATED: status_string = "handle created"; break; case WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING: status_string = "handle closing"; break; case WINHTTP_CALLBACK_STATUS_RESOLVING_NAME: status_string = "resolving"; info_string.assign(static_cast<base::char16*>(info), info_len); // host. break; case WINHTTP_CALLBACK_STATUS_NAME_RESOLVED: status_string = "resolved"; break; case WINHTTP_CALLBACK_STATUS_CONNECTING_TO_SERVER: status_string = "connecting"; info_string.assign(static_cast<base::char16*>(info), info_len); // IP. break; case WINHTTP_CALLBACK_STATUS_CONNECTED_TO_SERVER: status_string = "connected"; break; case WINHTTP_CALLBACK_STATUS_SENDING_REQUEST: status_string = "sending"; break; case WINHTTP_CALLBACK_STATUS_REQUEST_SENT: status_string = "sent"; break; case WINHTTP_CALLBACK_STATUS_RECEIVING_RESPONSE: status_string = "receiving response"; break; case WINHTTP_CALLBACK_STATUS_RESPONSE_RECEIVED: status_string = "response received"; break; case WINHTTP_CALLBACK_STATUS_CLOSING_CONNECTION: status_string = "connection closing"; break; case WINHTTP_CALLBACK_STATUS_CONNECTION_CLOSED: status_string = "connection closed"; break; case WINHTTP_CALLBACK_STATUS_REDIRECT: // |info| may contain invalid URL data and not safe to reference always. status_string = "redirect"; break; case WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE: status_string = "data available"; DCHECK_EQ(info_len, sizeof(uint32_t)); info_string = base::StringPrintf(L"%lu", *static_cast<uint32_t*>(info)); break; case WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE: status_string = "headers available"; break; case WINHTTP_CALLBACK_STATUS_READ_COMPLETE: status_string = "read complete"; info_string = base::StringPrintf(L"%lu", info_len); break; case WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE: status_string = "send request complete"; break; case WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE: status_string = "write complete"; break; case WINHTTP_CALLBACK_STATUS_REQUEST_ERROR: status_string = "request error"; break; case WINHTTP_CALLBACK_STATUS_SECURE_FAILURE: status_string = "https failure"; DCHECK(info); DCHECK_EQ(info_len, sizeof(uint32_t)); info_string = base::StringPrintf(L"%#x", *static_cast<uint32_t*>(info)); break; default: status_string = "unknown callback"; break; } std::string msg; if (!status_string.empty()) base::StringAppendF(&msg, "status=%s", status_string.data()); else base::StringAppendF(&msg, "status=%#x", status); if (!info_string.empty()) base::StringAppendF(&msg, ", info=%s", base::SysWideToUTF8(info_string).c_str()); VLOG(3) << "WinHttp status callback:" << " handle=" << handle << ", " << msg; switch (status) { case WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING: self_ = nullptr; break; case WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE: SendRequestComplete(); break; case WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE: HeadersAvailable(); break; case WINHTTP_CALLBACK_STATUS_READ_COMPLETE: DCHECK_EQ(info, &read_buffer_.front()); ReadDataComplete(info_len); break; case WINHTTP_CALLBACK_STATUS_REQUEST_ERROR: RequestError(static_cast<const WINHTTP_ASYNC_RESULT*>(info)); break; } } } // namespace updater
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
36b4766284995c1d9974796837497557af9595e8
8cdd62807f116fb92851f99bfcdd7de3c3330ed6
/arduino/opencr_arduino/opencr/libraries/OpenManipulator/src/open_manipulator_msgs/JointPosition.h
9a046a3887a187b88167d9c80a2fb4d3a70c364b
[ "Apache-2.0" ]
permissive
ROBOTIS-GIT/OpenCR
60ae4d28e39207430687b18e09bab88e5aee6107
68ec75d8a400949580ecf263e0105ea9743b878e
refs/heads/master
2023-08-24T23:05:27.672638
2023-08-01T08:58:39
2023-08-01T08:58:39
57,167,157
388
258
Apache-2.0
2023-09-05T04:41:46
2016-04-26T22:48:46
C
UTF-8
C++
false
false
4,804
h
#ifndef _ROS_open_manipulator_msgs_JointPosition_h #define _ROS_open_manipulator_msgs_JointPosition_h #include <stdint.h> #include <string.h> #include <stdlib.h> #include "ros/msg.h" namespace open_manipulator_msgs { class JointPosition : public ros::Msg { public: uint32_t joint_name_length; typedef char* _joint_name_type; _joint_name_type st_joint_name; _joint_name_type * joint_name; uint32_t position_length; typedef float _position_type; _position_type st_position; _position_type * position; typedef float _max_accelerations_scaling_factor_type; _max_accelerations_scaling_factor_type max_accelerations_scaling_factor; typedef float _max_velocity_scaling_factor_type; _max_velocity_scaling_factor_type max_velocity_scaling_factor; JointPosition(): joint_name_length(0), joint_name(NULL), position_length(0), position(NULL), max_accelerations_scaling_factor(0), max_velocity_scaling_factor(0) { } virtual int serialize(unsigned char *outbuffer) const { int offset = 0; *(outbuffer + offset + 0) = (this->joint_name_length >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (this->joint_name_length >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (this->joint_name_length >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (this->joint_name_length >> (8 * 3)) & 0xFF; offset += sizeof(this->joint_name_length); for( uint32_t i = 0; i < joint_name_length; i++){ uint32_t length_joint_namei = strlen(this->joint_name[i]); varToArr(outbuffer + offset, length_joint_namei); offset += 4; memcpy(outbuffer + offset, this->joint_name[i], length_joint_namei); offset += length_joint_namei; } *(outbuffer + offset + 0) = (this->position_length >> (8 * 0)) & 0xFF; *(outbuffer + offset + 1) = (this->position_length >> (8 * 1)) & 0xFF; *(outbuffer + offset + 2) = (this->position_length >> (8 * 2)) & 0xFF; *(outbuffer + offset + 3) = (this->position_length >> (8 * 3)) & 0xFF; offset += sizeof(this->position_length); for( uint32_t i = 0; i < position_length; i++){ offset += serializeAvrFloat64(outbuffer + offset, this->position[i]); } offset += serializeAvrFloat64(outbuffer + offset, this->max_accelerations_scaling_factor); offset += serializeAvrFloat64(outbuffer + offset, this->max_velocity_scaling_factor); return offset; } virtual int deserialize(unsigned char *inbuffer) { int offset = 0; uint32_t joint_name_lengthT = ((uint32_t) (*(inbuffer + offset))); joint_name_lengthT |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); joint_name_lengthT |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); joint_name_lengthT |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); offset += sizeof(this->joint_name_length); if(joint_name_lengthT > joint_name_length) this->joint_name = (char**)realloc(this->joint_name, joint_name_lengthT * sizeof(char*)); joint_name_length = joint_name_lengthT; for( uint32_t i = 0; i < joint_name_length; i++){ uint32_t length_st_joint_name; arrToVar(length_st_joint_name, (inbuffer + offset)); offset += 4; for(unsigned int k= offset; k< offset+length_st_joint_name; ++k){ inbuffer[k-1]=inbuffer[k]; } inbuffer[offset+length_st_joint_name-1]=0; this->st_joint_name = (char *)(inbuffer + offset-1); offset += length_st_joint_name; memcpy( &(this->joint_name[i]), &(this->st_joint_name), sizeof(char*)); } uint32_t position_lengthT = ((uint32_t) (*(inbuffer + offset))); position_lengthT |= ((uint32_t) (*(inbuffer + offset + 1))) << (8 * 1); position_lengthT |= ((uint32_t) (*(inbuffer + offset + 2))) << (8 * 2); position_lengthT |= ((uint32_t) (*(inbuffer + offset + 3))) << (8 * 3); offset += sizeof(this->position_length); if(position_lengthT > position_length) this->position = (float*)realloc(this->position, position_lengthT * sizeof(float)); position_length = position_lengthT; for( uint32_t i = 0; i < position_length; i++){ offset += deserializeAvrFloat64(inbuffer + offset, &(this->st_position)); memcpy( &(this->position[i]), &(this->st_position), sizeof(float)); } offset += deserializeAvrFloat64(inbuffer + offset, &(this->max_accelerations_scaling_factor)); offset += deserializeAvrFloat64(inbuffer + offset, &(this->max_velocity_scaling_factor)); return offset; } const char * getType(){ return "open_manipulator_msgs/JointPosition"; }; const char * getMD5(){ return "b6b6bc3417b5da955b766eb41a6c1698"; }; }; } #endif
[ "yhna@robotis.com" ]
yhna@robotis.com
ac6948bcb80fae96d0c6eafdebce359286068a8e
600df3590cce1fe49b9a96e9ca5b5242884a2a70
/third_party/skia/samplecode/SampleText.cpp
ca09cc749a8e13add92253d7a7feff729dd308ee
[ "BSD-3-Clause", "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0" ]
permissive
metux/chromium-suckless
efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a
72a05af97787001756bae2511b7985e61498c965
refs/heads/orig
2022-12-04T23:53:58.681218
2017-04-30T10:59:06
2017-04-30T23:35:58
89,884,931
5
3
BSD-3-Clause
2022-11-23T20:52:53
2017-05-01T00:09:08
null
UTF-8
C++
false
false
5,172
cpp
/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SampleCode.h" #include "SkView.h" #include "SkCanvas.h" #include "SkReadBuffer.h" #include "SkWriteBuffer.h" #include "SkGradientShader.h" #include "SkGraphics.h" #include "SkPath.h" #include "SkRandom.h" #include "SkRegion.h" #include "SkShader.h" #include "SkUtils.h" #include "SkColorPriv.h" #include "SkColorFilter.h" #include "SkTime.h" #include "SkTypeface.h" #include "SkXfermode.h" #include "SkStream.h" static const struct { const char* fName; uint32_t fFlags; bool fFlushCache; } gHints[] = { { "Linear", SkPaint::kLinearText_Flag, false }, { "Normal", 0, true }, { "Subpixel", SkPaint::kSubpixelText_Flag, true } }; static void DrawTheText(SkCanvas* canvas, const char text[], size_t length, SkScalar x, SkScalar y, const SkPaint& paint, SkScalar clickX) { SkPaint p(paint); #if 0 canvas->drawText(text, length, x, y, paint); #else { SkPoint pts[1000]; SkScalar xpos = x; SkASSERT(length <= SK_ARRAY_COUNT(pts)); for (size_t i = 0; i < length; i++) { pts[i].set(xpos, y), xpos += paint.getTextSize(); } canvas->drawPosText(text, length, pts, paint); } #endif p.setSubpixelText(true); x += SkIntToScalar(180); canvas->drawText(text, length, x, y, p); #ifdef SK_DEBUG if (true) { p.setSubpixelText(false); p.setLinearText(true); x += SkIntToScalar(180); canvas->drawText(text, length, x, y, p); } #endif } class TextSpeedView : public SampleView { public: TextSpeedView() { fHints = 0; fClickX = 0; } protected: // overrides from SkEventSink bool onQuery(SkEvent* evt) override { if (SampleCode::TitleQ(*evt)) { SampleCode::TitleR(evt, "Text"); return true; } return this->INHERITED::onQuery(evt); } static void make_textstrip(SkBitmap* bm) { bm->allocPixels(SkImageInfo::Make(200, 18, kRGB_565_SkColorType, kOpaque_SkAlphaType)); bm->eraseColor(SK_ColorWHITE); SkCanvas canvas(*bm); SkPaint paint; const char* s = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit"; paint.setFlags(paint.getFlags() | SkPaint::kAntiAlias_Flag | SkPaint::kDevKernText_Flag); paint.setTextSize(SkIntToScalar(14)); canvas.drawText(s, strlen(s), SkIntToScalar(8), SkIntToScalar(14), paint); } static void fill_pts(SkPoint pts[], size_t n, SkRandom* rand) { for (size_t i = 0; i < n; i++) pts[i].set(rand->nextUScalar1() * 640, rand->nextUScalar1() * 480); } void onDrawContent(SkCanvas* canvas) override { SkAutoCanvasRestore restore(canvas, false); { SkRect r; r.set(0, 0, SkIntToScalar(1000), SkIntToScalar(20)); // canvas->saveLayer(&r, nullptr, SkCanvas::kHasAlphaLayer_SaveFlag); } SkPaint paint; // const uint16_t glyphs[] = { 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19 }; int index = fHints % SK_ARRAY_COUNT(gHints); index = 1; // const char* style = gHints[index].fName; // canvas->translate(0, SkIntToScalar(50)); // canvas->drawText(style, strlen(style), SkIntToScalar(20), SkIntToScalar(20), paint); paint.setTypeface(SkTypeface::MakeFromFile("/skimages/samplefont.ttf")); paint.setAntiAlias(true); paint.setFlags(paint.getFlags() | gHints[index].fFlags); SkRect clip; clip.set(SkIntToScalar(25), SkIntToScalar(34), SkIntToScalar(88), SkIntToScalar(155)); const char* text = "Hamburgefons"; size_t length = strlen(text); SkScalar y = SkIntToScalar(0); for (int i = 9; i <= 24; i++) { paint.setTextSize(SkIntToScalar(i) /*+ (gRand.nextU() & 0xFFFF)*/); for (SkScalar dx = 0; dx <= SkIntToScalar(3)/4; dx += SkIntToScalar(1) /* /4 */) { y += paint.getFontSpacing(); DrawTheText(canvas, text, length, SkIntToScalar(20) + dx, y, paint, fClickX); } } if (gHints[index].fFlushCache) { // SkGraphics::SetFontCacheUsed(0); } } virtual SkView::Click* onFindClickHandler(SkScalar x, SkScalar y, unsigned modi) override { fClickX = x; this->inval(nullptr); return this->INHERITED::onFindClickHandler(x, y, modi); } bool onClick(Click* click) override { return this->INHERITED::onClick(click); } private: int fHints; SkScalar fClickX; typedef SampleView INHERITED; }; ////////////////////////////////////////////////////////////////////////////// static SkView* MyFactory() { return new TextSpeedView; } static SkViewRegister reg(MyFactory);
[ "enrico.weigelt@gr13.net" ]
enrico.weigelt@gr13.net
6cc393215b249372dfb5c31e1e7af55f826805e4
5eb87aed89e90e6e0eff8de966b1bf0e5cc78608
/main.cpp
ab331578a3418d42b64f4969d87784d7d1005c42
[]
no_license
Philip-Ch/investment_Capitalisation_Calculator
d3b389d0e5ef52376c18d281da77806db1bf4419
51847c8335b1183f7b4101f639675d626eb1f153
refs/heads/master
2022-11-07T23:11:19.422950
2020-06-24T19:01:34
2020-06-24T19:01:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,780
cpp
#include <iostream> #include <random> using namespace std; void message(unsigned int y, float czas = 0) { switch (y) { case 0: { cout << "\nProgram obliczy okres lokaty kapitałowej do osiągnięcia upragnionych odsetek.\n"; break; } case 1: { cout << "Uzyskanie wybranej kapitalizacji odsetek nastąpi po okresie: " << czas << ".\n"; break; } } } void pobierz_dane(unsigned int &kw_poczatkowa, unsigned int &kw_odsetek, double &oprocentowanie, double &kapitalizacja) { cout << "Jaka ma być kwota początkowa lokaty?\n"; cin >> kw_poczatkowa; cout << "Jaka ma być oczekiwana wartość odsetek?\n"; cin >> kw_odsetek; cout << "Jakie jest oprocentowanie lokaty? (Dla 1% -> 0.01)\n"; do { cin >> oprocentowanie; } while (oprocentowanie > 1 || oprocentowanie <= 0); cout << "Ile wynosi okres kapitalizacji lokaty? (Dla pół roku -> 0.5)\n"; do { cin >> kapitalizacja; } while (kapitalizacja < 0); } float okres_kapitalizacji(double kw_szukana, unsigned int kw_odsetek, float oprocentowanie, float kapitalizacja) { static float czas = 0; static int kw_poczatkowa = kw_szukana; if (kw_szukana - kw_poczatkowa < kw_odsetek) { kw_szukana = kw_szukana + kw_szukana * (oprocentowanie * kapitalizacja); czas += kapitalizacja; cout << "Dla okresu kapitalizacji: " << czas << ", kwota lokaty wynosi: " << kw_szukana << endl; okres_kapitalizacji(kw_szukana, kw_odsetek, oprocentowanie, kapitalizacja); } return czas; } int main() { unsigned int kw_poczatkowa, kw_odsetek, y; double oprocentowanie, kapitalizacja, wynik; message(y = 0); pobierz_dane(kw_poczatkowa, kw_odsetek, oprocentowanie, kapitalizacja); wynik = okres_kapitalizacji(kw_poczatkowa, kw_odsetek, oprocentowanie, kapitalizacja); message(y = 1, wynik); return 0; }
[ "thesarlysec@gmail.com" ]
thesarlysec@gmail.com
f0580e2d8461b4e6b048419659839181c667a64e
88cebe716e9d6cc830199c6a4798156a7f80123e
/createshowdialog.cpp
cdc47bb65dc6803cd3f40d3efdeb95e07cec4c70
[]
no_license
maksiplus19/db_coursework_admin
b2c00e57b122c048af50bb9454b412ab686ee821
43e97aae7506955f59fa41b83cb6ee999dacf472
refs/heads/master
2020-09-05T11:21:30.855998
2019-11-07T19:15:43
2019-11-07T19:15:43
220,088,778
0
0
null
null
null
null
UTF-8
C++
false
false
840
cpp
#include "createshowdialog.h" #include "ui_createshowdialog.h" CreateShowDialog::CreateShowDialog(QWidget *parent) : QDialog(parent), ui(new Ui::CreateShowDialog) { ui->setupUi(this); } CreateShowDialog::~CreateShowDialog() { delete ui; } int CreateShowDialog::getYear() const { return year; } int CreateShowDialog::getTiming() const { return timing; } QString CreateShowDialog::getName() const { return name; } QString CreateShowDialog::getDescription() const { return description; } void CreateShowDialog::on_buttonBox_accepted() { name = ui->nameEdit->text(); if (name == "") isOk &= false; year = ui->yearSpin->value(); timing = ui->timingSpin->value(); description = ui->textEdit->toPlainText(); } void CreateShowDialog::on_buttonBox_rejected() { isOk = false; }
[ "Niklvitoz1" ]
Niklvitoz1
f46d9e6cd2bc80b6830ce935a1b4e4635babf867
8a2820a15b8dfd987602299baec7468bd825fd8d
/Volume1/1040/1040.cpp
8297d20ac0b1bf316b5263441997ebea9e992e28
[]
no_license
lijiancheng0614/poj_solutions
eda5c2c799473aae398ec17aca9c52788ebe5b0a
919fb848f21ea9a0b7eff258c1788bb8f8d11bac
refs/heads/master
2018-09-25T10:47:36.585143
2018-07-14T07:29:12
2018-07-14T07:29:12
108,067,130
0
0
null
null
null
null
UTF-8
C++
false
false
1,785
cpp
#include <iostream> #include <vector> #include <algorithm> using namespace std; typedef pair<int, int> pii; typedef pair<pii, int> piii; class Solution { public: int solve(vector<piii> a, int n, int m) { sort(a.begin(), a.end()); this->a = a; this->n = n; n_a = a.size(); ans = 0; b.assign(n_a, pii(0, 0)); for (int i = n_a - 1; i >= 0; --i) { b[i].second = b[i].first = (a[i].first.second - a[i].first.first) * a[i].second; if (i < n_a - 1) b[i].second += b[i + 1].second; } v.assign(m + 1, 0); dfs(0, 0); return ans; } private: vector<piii> a; vector<pii> b; vector<int> v; int n, n_a, ans; void dfs(int k, int s) { if (k >= n_a) { ans = max(ans, s); return; } if (s + b[k].second <= ans) return; if (can(k)) { for (int i = a[k].first.first; i < a[k].first.second; ++i) v[i] += a[k].second; dfs(k + 1, s + b[k].first); for (int i = a[k].first.first; i < a[k].first.second; ++i) v[i] -= a[k].second; } dfs(k + 1, s); } inline bool can(int k) { for (int i = a[k].first.first; i < a[k].first.second; ++i) if (v[i] + a[k].second > n) return false; return true; } }; int main() { int n, m, q; while (cin >> n >> m >> q && n + m + q) { vector<piii> a; while (q--) { int x, y, z; cin >> x >> y >> z; a.push_back(piii(pii(x, y), z)); } cout << Solution().solve(a, n, m) << endl; } return 0; }
[ "lijiancheng0614@gmail.com" ]
lijiancheng0614@gmail.com
2aa3e2b5b55d7b841638c17e9fb95e81f0b06feb
471fc6e1255582b63d0abb054cb8c35f65f8a581
/ProjectDFA/dfa.h
28d9ef7d295c2fafa55211a3af7f3c023de63ed4
[]
no_license
mihaela96/ProjectsFromUniversity
676920f205ae334302abad540be5c06c694c9097
3c9c82287c96f2e4323347ade8caaab399934cfb
refs/heads/master
2021-01-21T09:54:02.324382
2017-02-27T23:28:01
2017-02-27T23:28:01
83,350,350
0
0
null
null
null
null
UTF-8
C++
false
false
1,031
h
#ifndef DFA_H_INCLUDED #define DFA_H_INCLUDED #include<map> #include<set> #include <windows.h> #include<utility> class DFA { private: int number_states; int startstate; set<int>finalstates; char* alphabet; typedef pair<int,char> trans; map<trans,int> transition; public: DFA(); DFA(DFA const&); ~DFA(); DFA& operator=(DFA const&); DFA(int,int); void setfinal(int); void setmaps(); void setalphabet(); int getNumberState() const; int getStartstate() const; int returmap(const pair<int,char> sth); int finalstatesize() const; int countalpha() const; char* alpha() const; bool tranfind(int,char) const; bool iffinalstate(int) const; void print() const; bool isinalpha(char) const; void clearfinal(); void newfinal(int x); void infolanguage(); bool isAccepted(char* word); void errorstate(); DFA& dopalnenie(); DFA& obedinenie(DFA&); friend ostream& operator<<(ostream&,DFA const&); }; DFA& se4enie (DFA& , DFA&); #endif // DFA_H_INCLUDED
[ "noreply@github.com" ]
noreply@github.com
1a25c4e08f0d2a5a656fcd794b62f38de9d6c05e
333908d32505e317ec683fbfb3f4ffd7d7d2198c
/project/CatchAFairy/Ishikawa/DirectX/Texture/ITTextureData.cpp
ee690aba29e985b62207280ebabbb4b0def1d2ff
[]
no_license
TakayoshiIshikawa/CatchAFairy
ac4a963802a1d7bf9f33d48102a00d2bab557e7a
645b690612744dc759b88c6ba488bf9b3e466181
refs/heads/master
2020-09-12T08:55:29.492895
2019-11-29T01:10:43
2019-11-29T01:10:43
222,374,532
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
7,369
cpp
//============================================================================= // ITTextureData.cpp // // 自作テクスチャデータのソースファイル // // Copyright(c) 2019 Ishikawa Takayoshi All Rights Reserved. //============================================================================= #include "ITTextureData.h" #pragma warning(disable:4061) #pragma warning(disable:4365) #pragma warning(disable:4668) #pragma warning(disable:4820) #pragma warning(disable:4917) #include <d3d11_1.h> #pragma warning(default:4917) #pragma warning(default:4820) #pragma warning(default:4668) #pragma warning(default:4365) #pragma warning(default:4061) #include "Ishikawa/Common/DebugLog.h" #include "Ishikawa/Common/Exception/ITExceptions.h" using namespace Ishikawa::DirectX; /// <summary> /// テクスチャバインド可能フラグをD3D11バインドフラグに対応するuint値に変換 /// </summary> /// <param name="_bindableflag">テクスチャバインド可能フラグ</param> /// <returns>D3D11バインドフラグに対応するuint値</returns> unsigned int Texture::ConvertBindableFlagToUInt(BindableFlag _bindableflag){ switch(_bindableflag){ case BindableFlag::ShaderResource: return D3D11_BIND_SHADER_RESOURCE; case BindableFlag::RenderTarget: return D3D11_BIND_RENDER_TARGET; case BindableFlag::DepthStencil: return D3D11_BIND_DEPTH_STENCIL; case BindableFlag::SR_RT: return (D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET); case BindableFlag::SR_DS: return (D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_DEPTH_STENCIL); default: // 異常終了 throw ::Ishikawa::Common::Exception::FunctionFailed("Couldn't convert bindable flag.[_bindableFlag is unknown]"); } } /// /// <summary> /// テクスチャバインドフラグをD3D11バインドフラグに変換 /// </summary> /// <param name="_bindflag">テクスチャバインドフラグ</param> /// <returns>D3D11バインドフラグ</returns> D3D11_BIND_FLAG Texture::ConvertBindFlagToD3D11BindFlag(BindFlag _bindflag){ switch(_bindflag){ case BindFlag::NotBind: // 異常終了 throw ::Ishikawa::Common::Exception::FunctionFailed("Couldn't convert bind flag.[_bindFlag is NotBind]"); case BindFlag::ShaderResource: return D3D11_BIND_SHADER_RESOURCE; case BindFlag::RenderTarget: return D3D11_BIND_RENDER_TARGET; case BindFlag::DepthStencil: return D3D11_BIND_DEPTH_STENCIL; default: // 異常終了 throw ::Ishikawa::Common::Exception::FunctionFailed("Couldn't convert bind flag.[_bindFlag is unknown]"); } } /// <summary> /// テクスチャフォーマットをDXGIフォーマットに変換 /// </summary> /// <param name="_format">テクスチャフォーマット</param> /// <returns>DXGIフォーマット</returns> DXGI_FORMAT Texture::ConvertFormatToDxgiFormat(Format _format){ switch(_format){ case Format::Unknown: return DXGI_FORMAT_UNKNOWN; case Format::R8G8B8A8UNorm: return DXGI_FORMAT_R8G8B8A8_UNORM; case Format::R10G10B10A2UNorm: return DXGI_FORMAT_R10G10B10A2_UNORM; case Format::R32G32B32A32Float: return DXGI_FORMAT_R32G32B32A32_FLOAT; case Format::R32Float: return DXGI_FORMAT_R32_FLOAT; case Format::D24UNormS8UInt: return DXGI_FORMAT_D24_UNORM_S8_UINT; default: // 異常終了 throw ::Ishikawa::Common::Exception::FunctionFailed("Couldn't convert format.[_format is unknown]"); } } /// <summary> /// テクスチャディメンションをD3D11シェーダリソースビューディメンションに変換 /// </summary> /// <param name="_dimention">テクスチャディメンション</param> /// <returns>D3D11シェーダリソースビューディメンション</returns> D3D_SRV_DIMENSION Texture::ConvertDimentionToD3D11SRVDimention(Dimention _dimention){ switch(_dimention){ case Dimention::Texture2D: return D3D_SRV_DIMENSION_TEXTURE2D; case Dimention::MaltisampleTexture2D: return D3D_SRV_DIMENSION_TEXTURE2DMS; default: // 異常終了 throw ::Ishikawa::Common::Exception::FunctionFailed("Couldn't convert format.[_dimention is unknown]"); } } /// <summary> /// テクスチャディメンションをD3D11レンダーターゲットビューディメンションに変換 /// </summary> /// <param name="_dimention">テクスチャディメンション</param> /// <returns>D3D11レンダーターゲットビューディメンション</returns> D3D11_RTV_DIMENSION Texture::ConvertDimentionToD3D11RTVDimention(Dimention _dimention){ switch(_dimention){ case Dimention::Texture2D: return D3D11_RTV_DIMENSION_TEXTURE2D; case Dimention::MaltisampleTexture2D: return D3D11_RTV_DIMENSION_TEXTURE2DMS; default: // 異常終了 throw ::Ishikawa::Common::Exception::FunctionFailed("Couldn't convert format.[_dimention is unknown]"); } } /// <summary> /// テクスチャディメンションをD3D11デプスステンシルビューディメンションに変換 /// </summary> /// <param name="_dimention">テクスチャディメンション</param> /// <returns>D3D11デプスステンシルビューディメンション</returns> D3D11_DSV_DIMENSION Texture::ConvertDimentionToD3D11DSVDimention(Dimention _dimention){ switch(_dimention){ case Dimention::Texture2D: return D3D11_DSV_DIMENSION_TEXTURE2D; case Dimention::MaltisampleTexture2D: return D3D11_DSV_DIMENSION_TEXTURE2DMS; default: // 異常終了 throw ::Ishikawa::Common::Exception::FunctionFailed("Couldn't convert format.[_dimention is unknown]"); } } /// <summary> /// デフォルトサンプル設定データの取得 /// </summary> /// <param name="_sampleDescCount">サンプル設定カウント格納先</param> /// <param name="_sampleDescQuality">サンプル設定クォリティ格納先</param> /// <param name="_dimention">ディメンション格納先</param> void Texture::GetDefaultSampleDescData( unsigned int* const _sampleDescCount, unsigned int* const _sampleDescQuality, Dimention* const _dimention ){ if(_sampleDescCount != nullptr) (*_sampleDescCount) = 1U; if(_sampleDescQuality != nullptr) (*_sampleDescQuality) = 0U; if(_dimention != nullptr) (*_dimention) = Dimention::Texture2D; } /// <summary> /// マルチサンプル・アンチエイリアシング設定データの取得 /// </summary> /// <param name="_sampleDescCount">サンプル設定カウント格納先</param> /// <param name="_sampleDescQuality">サンプル設定クォリティ格納先</param> /// <param name="_dimention">ディメンション格納先</param> /// <param name="_device">デバイス</param> void Texture::GetMultisampleAntiAliasingDescData( unsigned int* const _sampleDescCount, unsigned int* const _sampleDescQuality, Dimention* const _dimention, ID3D11Device* const _device ){ // 最高品質を探す for(unsigned int i=D3D11_MAX_MULTISAMPLE_SAMPLE_COUNT; i>0U; --i){ unsigned int quality = 0U; HRESULT hr = _device->CheckMultisampleQualityLevels(DXGI_FORMAT_D24_UNORM_S8_UINT, i, &quality); if(SUCCEEDED(hr)){ if(quality > 0U){ if(_sampleDescCount != nullptr) (*_sampleDescCount) = i; if(_sampleDescQuality != nullptr) (*_sampleDescQuality) = quality - 1U; if(_dimention != nullptr) (*_dimention) = Dimention::MaltisampleTexture2D; return; } } } // できなければログを残す ::Ishikawa::Common::Debug::Log("Couldn't get multisample anti-aliasing desc data.\n"); }
[ "tkis0rei@gmail.com" ]
tkis0rei@gmail.com
0cbc3b89c6a54906e7ac2071985de87286f92649
6e72bfb69388f3be8af7e2887c56de30ff2a0ba1
/appinventor/Pods/geos/geos/src/simplify/TaggedLinesSimplifier.cpp
e33f5f1dcc68ecbf5df0d03b6057d286c5cf01da
[ "LGPL-2.1-only", "Apache-2.0" ]
permissive
bobanss/appinventor-sources
4a0fbc1867ffb2696cb19ff27ff68f0296236883
719e7244bf676675b95339871f16e54521a9a47f
refs/heads/master
2023-07-06T10:30:09.141453
2023-06-18T01:07:42
2023-06-18T01:07:42
208,414,643
0
0
Apache-2.0
2019-09-14T08:57:27
2019-09-14T08:57:27
null
UTF-8
C++
false
false
1,605
cpp
/********************************************************************** * * GEOS - Geometry Engine Open Source * http://geos.osgeo.org * * Copyright (C) 2006 Refractions Research Inc. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * ********************************************************************** * * Last port: simplify/TaggedLinesSimplifier.java rev. 1.4 (JTS-1.7.1) * **********************************************************************/ #include <geos/simplify/TaggedLinesSimplifier.h> #include <geos/simplify/LineSegmentIndex.h> #include <geos/simplify/TaggedLineStringSimplifier.h> #include <geos/algorithm/LineIntersector.h> #include <cassert> #include <algorithm> #include <memory> #ifndef GEOS_DEBUG #define GEOS_DEBUG 0 #endif #ifdef GEOS_DEBUG #include <iostream> #endif using namespace geos::geom; using namespace std; namespace geos { namespace simplify { // geos::simplify /*public*/ TaggedLinesSimplifier::TaggedLinesSimplifier() : inputIndex(new LineSegmentIndex()), outputIndex(new LineSegmentIndex()), taggedlineSimplifier(new TaggedLineStringSimplifier(inputIndex.get(), outputIndex.get())) { } /*public*/ void TaggedLinesSimplifier::setDistanceTolerance(double d) { taggedlineSimplifier->setDistanceTolerance(d); } /*private*/ void TaggedLinesSimplifier::simplify(TaggedLineString& tls) { taggedlineSimplifier->simplify(&tls); } } // namespace geos::simplify } // namespace geos
[ "ewpatton@mit.edu" ]
ewpatton@mit.edu
611f352fdcc483c5e6bfe1980fc5b1ea78ac194d
1a28b294cd51e419553f7c25be7eea36cfded041
/bird.cpp
0032f5928c1d09b8c739ac1449c4eb5bed4bc579
[]
no_license
RiceDam/Lab4
752bf69f49dc020ca3cfa871b2fdba5958db0eb2
1490619399a183ba3e5ba4574b43cfbe25cb5439
refs/heads/master
2022-12-25T00:59:09.576573
2020-10-03T04:32:32
2020-10-03T04:32:32
299,692,432
0
0
null
null
null
null
UTF-8
C++
false
false
993
cpp
// // Created by Eric Dam on 2020-10-01. // #include "bird.hpp" Bird::Bird() { cout << "Bird is being created" << endl; } Bird::Bird(int age1, double x1, double y1, double z1) { age = age1; x = x1; y = y1; z = z1; cout << "Bird is being created" << endl; } Bird::Bird(const Bird &bird) { id = bird.id; age = bird.age; x = bird.x; y = bird.y; z = bird.z; alive = bird.alive; cout << "Bird is being copied" << endl; } Bird::~Bird() { cout << "Bird is being destroyed" << endl; } void Bird::move(double x1, double y1, double z1) { x = x1; y = y1; z = z1; } void Bird::sleep() { cout << "Bird is sleeping" << endl; } void Bird::eat() { cout << "Bird is eating" << endl; } ostream &operator<<(ostream &os, const Bird& bird) { os << "Bird " << "ID: " << bird.id << " Age: " << bird.age << " Is Alive: " << bird.alive << " (X,Y,Z): " << bird.x << " " << bird.y << " " << bird.z << endl; return os; }
[ "dam.eric3@gmail.com" ]
dam.eric3@gmail.com
08ee626f1cd4ad96f416120591c63808fbe49867
c8fee515051cd890158037fe09d74285c3b02cfd
/run/quickTestStack/0/electrolyte/k
b20032c9d4c9c2868bfd9c2640b996a74770ead3
[]
no_license
ChangyongLeee/myOpenfuelcell
725950e31513fb21058ab3a47688ad80dd934982
21a5162266c777994ee749c5f1f2d450e46f8c6f
refs/heads/master
2022-12-30T06:55:31.255023
2020-10-19T10:39:45
2020-10-19T10:39:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,262
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 2.1.x | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "0"; object k; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [1 1 -3 -1 0 0 0]; internalField uniform 0; boundaryField { electrolyte_to_air { type calculated; value uniform 0; } electrolyte_to_fuel { type calculated; value uniform 0; } electrolyte_to_interconnect { type calculated; value uniform 0; } } // ************************************************************************* //
[ "rnishida@users.sourceforge.net" ]
rnishida@users.sourceforge.net
c2d3e20b727ace34bc75c7ac5b4691e1440a7845
fe90df7bbc1f5d5d76935c5adb70e73f2f5ee689
/Savitch_8thEd_Chp2_Prob3/main.cpp
1af6a91f1e1e801c35c5283340e00c388dd75077
[]
no_license
paulwilfley/Pablo
5dc848d377b0cf5555e2394679e3102c4310419a
c7c4c01450d4dfe8c1395bc724f1232d8a927983
refs/heads/master
2021-01-22T03:49:56.651630
2014-03-17T17:05:10
2014-03-17T17:05:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,181
cpp
/* * File: main.cpp * Author: Paul Wilfley * Created on March 17, 2014, 12:07 AM * Purpose: Determine the amount owed for 6 months retroactive pay at 7.6% */ //system Libraries #include <iostream> using namespace std; //Global Constants const float PAY_INC = .076; //Calculates the retroactive percentage. const float HALF_AN = .5; //Calculates 6 months of salary increase. //Function Prototypes //Program Begins Here int main(int argc, char** argv) { //Declare Variables float prAnSal, amt_owd, new_sal; //Ask for Total Annual Gross for last year. cout << "What was your Total gross salary for last year?" <<endl; cin >> prAnSal; //calculate amount owed and new rate amt_owd = (prAnSal * HALF_AN) * PAY_INC; new_sal = prAnSal * PAY_INC +prAnSal; //Output Amount of pay owed cout << "Based on your previous annual salary," <<endl; cout << "you will receive $" << amt_owd <<" retroactively." <<endl; //Added Line space cout << endl; //Output new salary cout << "Your New salary will be $" << new_sal; cout << " a year." <<endl; //End of Program return 0; }
[ "paulwilfley@gmail.com" ]
paulwilfley@gmail.com
01794178628de613fd33ff3f6cedd5e212fa5ca0
de808c366fb5399761c4109359f5abc23c8fe0e3
/HIB_SERVER/.svn/pristine/e6/e672d979a96e4c8264207fb9fc96fcc09e888481.svn-base
97a683c3e67bbbc3d3dd4b90202756f4911d34a2
[]
no_license
chos2008/chos-framework-c
063a54f7c593cce56d1f1802c314285d5e03bc7c
3bacf62b6a461f80195e7b32d1437f247e02ce94
refs/heads/master
2020-12-25T19:26:17.885448
2015-06-26T04:34:37
2015-06-26T04:34:37
29,383,162
0
0
null
null
null
null
UTF-8
C++
false
false
108
/* * * * */ #if ! defined NETWORK_ELEMENT #define NETWORK_ELEMENT class NetworkElement { }; #endif;
[ "chos2008@126.com" ]
chos2008@126.com
6382aca82849d58464939099b954c005897bfc52
d8a4379e3cb3e0776487e5f341f352c22d3a96ed
/bier/core/function_context.h
3a57337e3e68bd0ece97da3e743c517d5e398af9
[ "Apache-2.0" ]
permissive
IKholopov/BIeR
08e39915a5e76238b7c84127ff599a2d3b0d2bd2
c3cba6a7146b2a80129d43e850705f0e2520ea3f
refs/heads/master
2020-06-19T21:32:59.090751
2019-10-22T19:36:06
2019-10-22T19:36:06
196,882,006
0
0
null
null
null
null
UTF-8
C++
false
false
821
h
/* Copyright 2019 Igor Kholopov 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. */ #pragma once #include <bier/common.h> namespace bier { class FunctionContextMemeber { public: virtual ~FunctionContextMemeber() = default; virtual const Function* GetContextFunction() const = 0; }; } // namespace bier
[ "kholopov96@gmail.com" ]
kholopov96@gmail.com
fc6a92cd195b986476434f4d46b5547c4cb1c620
5702a2ca177ddf2b5554102aa71f056d4205f784
/src/PSILog.h
b593e31d1f3ac0657937f79ca2b94ae145ff3647
[]
no_license
Sakari369/PSILog
3088044e90210f6602ebeb3bfe637d2f6749bf52
c3f4389d781ab7324bd90bcbb79c4204ad0ec4fc
refs/heads/master
2021-09-26T00:11:12.695054
2018-10-26T10:48:00
2018-10-26T10:48:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,459
h
// PSILog.h // // Class for handling logging, with support for multiple outputs, thread safety and modular extensions of // user configurable output destinations // // Copyright (c) 2018 Sakari Lehtonen <sakari AT psitriangle DOT net> #include <iostream> #include <sstream> #include <string> #include <fstream> #include <vector> #include <stdio.h> using std::unique_ptr; using std::make_unique; using std::move; class PSILogOutput; class PSILogConsoleOutput; class PSILogStream; // Our main logger class class PSILog { public: // Binary arithmetic current log level mask enum LogLevel { NONE = 0, INFO = 1, WARN = 2, ERR = 2 << 1, FREQ = 2 << 2, ALL = (2 << 3) - 1 }; PSILog() = default; ~PSILog() = default; // Functors for returning a log stream, enabling multithreading safe logging PSILogStream operator ()(); PSILogStream operator ()(int log_level); // The main logging method void log(const std::string &entry, int log_level); // Return the log message prefix header std::string get_log_entry_prefix(const std::string &log_entry) const; // Add new logger to our output chain // We have multiple output destinations which implement the actual writing of the messages // This enables easy extending of log destinations by the user void add_output(unique_ptr<PSILogOutput> output); // Flush all output now to the destination outputs void flush(); // Pure accessors written here for easier implementation int get_level() const { return _level; } void set_level(int level) { _level = level; } int get_filter() const { return _filter; } void set_filter(int filter) { _filter = filter; } bool get_add_prefix() const { return _add_prefix; } void set_add_prefix(bool add_prefix) { _add_prefix = add_prefix; } private: // The current log level we are logging messages with int _level = LogLevel::INFO; // The log filter that filters the output, compared against the current // log level. Binary arithmetic mask. int _filter = LogLevel::INFO; // Do we add the log message prefix to our entries ? bool _add_prefix = true; // Our log message outputters chain // We dispatch the actual log messages to these in sequential order std::vector<unique_ptr<PSILogOutput>> _outputs; }; // Stream class for thread safety // Temporary instance of this class is returned when // logger() << "Log entry" << std::endl; // Or the << operation is called // Meaning the calling thread gets a temporary LogStream object // And when in the calling thread the object is destroyed, it actually logs the log messages // This enables thread safe log message construction, without multiple threads intefering // with each other class PSILogStream : public std::ostringstream { public: // Store reference to the current log level and logger object PSILogStream(PSILog &log, int log_level) : _log(log), _log_level(log_level) {} // Copy constructor PSILogStream(const PSILogStream &ls) : _log(ls._log), _log_level(ls._log_level) {} ~PSILogStream() { // Filter log messages with the binary arithmetic mask if (_log.get_filter() & _log_level) { _log.log(str(), _log_level); } } private: PSILog &_log; int _log_level; }; // The logger outputs to PSILogOutput objects // Base class for implementing logger outputs // This allows modular extension of the outputs by the user, // Just provide an implementatin extending this class, and call add_output() class PSILogOutput { public: PSILogOutput() = default; ~PSILogOutput() = default; // This will write the current log entry to the destination output, ensuring that // the output is flushed also virtual bool write_log_entry(const std::string &log_entry, int log_level) = 0; // Provide a way to implement flushing the output manually virtual void flush() = 0; }; // Default implementation of outputting log messages to the console class PSILogConsoleOutput : public PSILogOutput { public: PSILogConsoleOutput() = default; ~PSILogConsoleOutput() = default; bool write_log_entry(const std::string &log_entry, int log_level) override; void flush() override; }; // Default implementation of outputting to a file class PSILogFileOutput : public PSILogOutput { public: PSILogFileOutput(const char *output_path); ~PSILogFileOutput(); bool write_log_entry(const std::string &log_entry, int log_level) override; void flush() override; private: const char *_output_path = ""; std::fstream _fs; std::mutex _mutex; };
[ "sakari@psitriangle.net" ]
sakari@psitriangle.net
8a379e54e58b831a733d04fecb30dbc647029418
54cf4b6f2dab5c6ce359602790b17d61778536ff
/trie.cpp
d32946873f771e12f9b8a00d631c63a429405987
[]
no_license
GiveThanksAlways/UCSD_Algorithms_on_Strings
4c002215ec4728af32d87df84b71688bacc81c9e
fcccd63fa42435b1d129b0c57479db3417e0ed2b
refs/heads/master
2020-05-02T01:26:15.668857
2019-05-09T01:48:06
2019-05-09T01:48:06
177,686,226
0
0
null
null
null
null
UTF-8
C++
false
false
1,610
cpp
#include <string> #include <iostream> #include <vector> #include <map> using std::map; using std::vector; using std::string; using std::cout; using std::endl; typedef map<char, int> edges; typedef vector<edges> trie; trie build_trie(vector<string> & patterns) { trie t; edges root; t.push_back(root); // go through all patterns for(auto & daPattern : patterns){ int currentNode = 0;// root node string CurrentPattern = daPattern; //go through each letter of the pattern for(auto & currentSymbol : CurrentPattern){ //looks at the current node of mapped edges, finds if the letter key is in the map and returns 0 if it is not in the edges from the currentNode // if the current Symbol is in the trie then don't add, just go to the next child in the tree if( t[currentNode].find(currentSymbol)->second != 0){ currentNode = t[currentNode].find(currentSymbol)->second; }else{ // currentSymbol not a child of the current node. We add the currentSymbol as a child of the node edges newNode; t.push_back(newNode); t[currentNode].insert(std::pair<char,int>(currentSymbol,t.size()-1)); currentNode = t.size()-1; } } } return t; } int main() { size_t n; std::cin >> n; vector<string> patterns; for (size_t i = 0; i < n; i++) { string s; std::cin >> s; patterns.push_back(s); } trie t = build_trie(patterns); for (size_t i = 0; i < t.size(); ++i) { for (const auto & j : t[i]) { std::cout << i << "->" << j.second << ":" << j.first << "\n"; } } return 0; }
[ "noreply@github.com" ]
noreply@github.com
87f3e7879b30c5286fc85e6176af9b6a568556b1
b367fe5f0c2c50846b002b59472c50453e1629bc
/xbox_leak_may_2020/xbox trunk/xbox/private/ui/maxsdk/SAMPLES/Melt/MELT.CPP
dcafd427aca7ea3ee195bc39c521a35dcf2bd79b
[]
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
16,893
cpp
/*===========================================================================*\ | | FILE: melt.cpp | Simple melting modifier | | AUTHOR: Harry Denholm | All Rights Reserved. Copyright(c) Kinetix 1998 | | HIST: 3-6-98 : Ported | This is pretty self-contained. Bit messy.. | \*===========================================================================*/ #include "max.h" #include "iparamm.h" #include "simpmod.h" #include "resource.h" #define BIGFLOAT float(999999) float sign(float x) { return (x < 0.0f ? -1.0f : 1.0f); } #define MELT_ID1 0x36d04fa5 #define MELT_ID2 0x500727b3 // The DLL instance handle HINSTANCE hInstance; extern TCHAR *GetString(int sid); /*===========================================================================*\ | Melt Modifier \*===========================================================================*/ class MeltMod : public SimpleMod { public: static IParamMap *pmapParam; MeltMod(); void DeleteThis() { delete this; } void GetClassName(TSTR& s) { s= TSTR(GetString(IDS_MELTMOD)); } virtual Class_ID ClassID() { return Class_ID(MELT_ID1,MELT_ID2);} void BeginEditParams( IObjParam *ip, ULONG flags,Animatable *prev); void EndEditParams( IObjParam *ip,ULONG flags,Animatable *next); RefTargetHandle Clone(RemapDir& remap = NoRemap()); TCHAR *GetObjectName() { return GetString(IDS_MELTMOD); } IOResult Load(ILoad *iload); // From simple mod Deformer& GetDeformer(TimeValue t,ModContext &mc,Matrix3& mat, Matrix3& invmat); Interval GetValidity(TimeValue t); ParamDimension *GetParameterDim(int pbIndex); TSTR GetParameterName(int pbIndex); void InvalidateUI() {if (pmapParam) pmapParam->Invalidate();} }; /*===========================================================================*\ | Deformer (map) function \*===========================================================================*/ class MeltDeformer: public Deformer { public: float cx, cy, cz, xsize, ysize, zsize, size; Matrix3 tm,invtm; TimeValue time; Box3 bbox; float bulger; float ybr,zbr,visvaluea; int confiner,axis,vistypea,negaxis; MeltDeformer(); MeltDeformer( TimeValue t, ModContext &mc, float bulgea,float yba,float zba ,int confinea, int vistype, float visvalue, int axisa, int negaxisa, Matrix3& modmat, Matrix3& modinv); void SetAxis(Matrix3 &tmAxis); Point3 Map(int i, Point3 p); }; IParamMap *MeltMod::pmapParam = NULL; /*===========================================================================*\ | Variable Handling Stuff & PUID \*===========================================================================*/ #define PB_MELTAMT 0 #define PB_CONFINE 1 #define PB_YB 2 #define PB_ZB 3 #define PB_VISTYPE 4 #define PB_VISVAL 5 #define PB_AXIS 6 #define PB_NEGAXIS 7 static int visIDs[] = {IDC_S1,IDC_S2,IDC_S3,IDC_S4,IDC_S5}; static int axisIDs[] = {IDC_AX,IDC_AY,IDC_AZ}; static ParamUIDesc descParam[] = { ParamUIDesc( PB_MELTAMT, EDITTYPE_FLOAT, IDC_AMT_EDIT,IDC_AMT_SPIN, 0.0f,1000.0f, 1.0f), ParamUIDesc( PB_YB, EDITTYPE_FLOAT, IDC_SPREAD_EDIT,IDC_SPREAD_SPIN, 0.0f,100.0f, 0.1f), ParamUIDesc(PB_VISTYPE,TYPE_RADIO,visIDs,5), ParamUIDesc( PB_VISVAL, EDITTYPE_FLOAT, IDC_VIS_EDIT,IDC_VIS_SPIN, 0.2f,30.0f, 0.02f), ParamUIDesc(PB_AXIS,TYPE_RADIO,axisIDs,3), ParamUIDesc(PB_NEGAXIS,TYPE_SINGLECHEKBOX,IDC_NEGATIVE), }; #define PARAMDESC_LENGH 6 /*===========================================================================*\ | ParamBlocks \*===========================================================================*/ static ParamBlockDescID descVer1[] = { { TYPE_FLOAT, NULL, TRUE, 0 }, { TYPE_INT, NULL, FALSE, 1 }, { TYPE_FLOAT, NULL, TRUE, 2 }, { TYPE_FLOAT, NULL, TRUE, 3 }, }; static ParamBlockDescID descVer2[] = { { TYPE_FLOAT, NULL, TRUE, 0 }, { TYPE_INT, NULL, FALSE, 1 }, { TYPE_FLOAT, NULL, TRUE, 2 }, { TYPE_FLOAT, NULL, TRUE, 3 }, { TYPE_INT, NULL, FALSE, 4 }, { TYPE_FLOAT, NULL, TRUE, 5 }, }; static ParamBlockDescID descVer3[] = { { TYPE_FLOAT, NULL, TRUE, 0 }, { TYPE_INT, NULL, FALSE, 1 }, { TYPE_FLOAT, NULL, TRUE, 2 }, { TYPE_FLOAT, NULL, TRUE, 3 }, { TYPE_INT, NULL, FALSE, 4 }, { TYPE_FLOAT, NULL, TRUE, 5 }, { TYPE_INT, NULL, FALSE, 6 }, }; static ParamBlockDescID descVer4[] = { { TYPE_FLOAT, NULL, TRUE, 0 }, { TYPE_INT, NULL, FALSE, 1 }, { TYPE_FLOAT, NULL, TRUE, 2 }, { TYPE_FLOAT, NULL, TRUE, 3 }, { TYPE_INT, NULL, FALSE, 4 }, { TYPE_FLOAT, NULL, TRUE, 5 }, { TYPE_INT, NULL, FALSE, 6 }, { TYPE_INT, NULL, FALSE, 7 }, }; #define PBLOCK_LENGTH 8 /*===========================================================================*\ | Old Versions (as this is a port, keep it compatible) \*===========================================================================*/ static ParamVersionDesc versions[] = { ParamVersionDesc(descVer1,4,1), ParamVersionDesc(descVer2,6,2), ParamVersionDesc(descVer3,7,3) }; #define NUM_OLDVERSIONS 3 #define CURRENT_VERSION 4 static ParamVersionDesc curVersion(descVer4,PBLOCK_LENGTH,CURRENT_VERSION); /*===========================================================================*\ | Register PLCB at load time \*===========================================================================*/ IOResult MeltMod::Load(ILoad *iload) { iload->RegisterPostLoadCallback( new ParamBlockPLCB(versions,NUM_OLDVERSIONS,&curVersion,this, SIMPMOD_PBLOCKREF)); return IO_OK; } /*===========================================================================*\ | Melt Stuff \*===========================================================================*/ MeltMod::MeltMod() : SimpleMod() { MakeRefByID(FOREVER, SIMPMOD_PBLOCKREF, CreateParameterBlock(descVer4, PBLOCK_LENGTH, CURRENT_VERSION)); pblock->SetValue(PB_MELTAMT,0,0); pblock->SetValue(PB_YB,0,19.0f); pblock->SetValue(PB_ZB,0,0); pblock->SetValue(PB_CONFINE,0,0); pblock->SetValue(PB_VISTYPE,0,0); pblock->SetValue(PB_VISVAL,0,1.0f); pblock->SetValue(PB_AXIS,0,0); pblock->SetValue(PB_NEGAXIS,0,0); } /*===========================================================================*\ | BeginEditParams - called when user opens mod \*===========================================================================*/ void MeltMod::BeginEditParams( IObjParam *ip, ULONG flags,Animatable *prev ) { SimpleMod::BeginEditParams(ip,flags,prev); pmapParam = CreateCPParamMap( descParam,PARAMDESC_LENGH, pblock, ip, hInstance, MAKEINTRESOURCE(IDD_MELT), GetString(IDS_TITLE), 0); } /*===========================================================================*\ | EndEditParams - Hmm guess what this does \*===========================================================================*/ void MeltMod::EndEditParams( IObjParam *ip, ULONG flags,Animatable *next ) { SimpleMod::EndEditParams(ip,flags,next); DestroyCPParamMap(pmapParam); } /*===========================================================================*\ | Calculate validity \*===========================================================================*/ Interval MeltMod::GetValidity(TimeValue t) { float f; Interval valid = FOREVER; pblock->GetValue(PB_MELTAMT,t,f,valid); pblock->GetValue(PB_YB,t,f,valid); pblock->GetValue(PB_ZB,t,f,valid); pblock->GetValue(PB_CONFINE,t,f,valid); pblock->GetValue(PB_VISTYPE,t,f,valid); pblock->GetValue(PB_VISVAL,t,f,valid); pblock->GetValue(PB_AXIS,t,f,valid); pblock->GetValue(PB_NEGAXIS,t,f,valid); return valid; } /*===========================================================================*\ | Clone Method \*===========================================================================*/ RefTargetHandle MeltMod::Clone(RemapDir& remap) { MeltMod* newmod = new MeltMod(); newmod->ReplaceReference(SIMPMOD_PBLOCKREF,pblock->Clone(remap)); newmod->SimpleModClone(this); return(newmod); } /*===========================================================================*\ | Melt Deformer \*===========================================================================*/ MeltDeformer::MeltDeformer() { tm.IdentityMatrix(); invtm = Inverse(tm); time = 0; // to make purify happy: cx=cy=cz=xsize=ysize=zsize=size=bulger=ybr=zbr=visvaluea=0.0f; bbox.Init(); confiner=axis=vistypea=negaxis=0; } void MeltDeformer::SetAxis(Matrix3 &tmAxis) { Matrix3 itm = Inverse(tmAxis); tm = tm*tmAxis; invtm = itm*invtm; } /*===========================================================================*\ | Actual deforming function \*===========================================================================*/ Point3 MeltDeformer::Map(int i, Point3 p) { float x, y, z; float xw,yw,zw; float vdist,mfac,dx,dy; float defsinex,coldef,realmax; // Mult by mc p = p*tm; x = p.x; y = p.y; z = p.z; xw= x-cx; yw= y-cy; zw= z-cz; if(xw==0.0 && yw==0.0 && zw==0.0) xw=yw=zw=1.0f; // Kill singularity for XW,YW,ZW if(x==0.0 && y==0.0 && z==0.0) x=y=z=1.0f; // Kill singularity for XYZ // Find distance from centre vdist=(float) sqrt(xw*xw+yw*yw+zw*zw); mfac=size/vdist; if(axis==0){ dx = xw+sign(xw)*((float) (fabs(xw*mfac))*(bulger*ybr)); dy = yw+sign(yw)*((float) (fabs(yw*mfac))*(bulger*ybr)); x=(dx+cx); y=(dy+cy); } if(axis==1){ dx = xw+sign(xw)*((float) (fabs(xw*mfac))*(bulger*ybr)); dy = zw+sign(zw)*((float) (fabs(zw*mfac))*(bulger*ybr)); x=(dx+cx); z=(dy+cz); } if(axis==2){ dx = zw+sign(zw)*((float) (fabs(zw*mfac))*(bulger*ybr)); dy = yw+sign(yw)*((float) (fabs(yw*mfac))*(bulger*ybr)); z=(dx+cz); y=(dy+cy); } if(axis==0) if(p.z<(bbox.pmin.z+zbr)) goto skipmelt; if(axis==1) if(p.y<(bbox.pmin.y+zbr)) goto skipmelt; if(axis==2) if(p.x<(bbox.pmin.x+zbr)) goto skipmelt; if(axis==0) realmax = (float)hypot( (bbox.pmax.x-cx),(bbox.pmax.y-cy) ); if(axis==1) realmax = (float)hypot( (bbox.pmax.x-cx),(bbox.pmax.z-cz) ); if(axis==2) realmax = (float)hypot( (bbox.pmax.z-cz),(bbox.pmax.y-cy) ); if(axis==0){ defsinex = (float)hypot( (x-cx),(y-cy) ); coldef = realmax - (float)hypot( (x-cx),(y-cy) ); } if(axis==1){ defsinex = (float)hypot( (x-cx),(z-cz) ); coldef = realmax - (float)hypot( (x-cx),(z-cz) ); } if(axis==2){ defsinex = (float)hypot( (z-cz),(y-cy) ); coldef = realmax - (float)hypot( (z-cz),(y-cy) ); } if (coldef<0.0f) coldef=0.0f; defsinex+=(coldef/visvaluea); // Melt me! if(axis==0){ if(!negaxis) { z-=(defsinex*bulger); if(z<=bbox.pmin.z) z=bbox.pmin.z; if(z<=(bbox.pmin.z+zbr)) z=(bbox.pmin.z+zbr); } else { z+=(defsinex*bulger); if(z>=bbox.pmax.z) z=bbox.pmax.z; if(z>=(bbox.pmax.z+zbr)) z=(bbox.pmax.z+zbr); } } if(axis==1){ if(!negaxis) { y-=(defsinex*bulger); if(y<=bbox.pmin.y) y=bbox.pmin.y; if(y<=(bbox.pmin.y+zbr)) y=(bbox.pmin.y+zbr); } else { y+=(defsinex*bulger); if(y>=bbox.pmax.y) y=bbox.pmax.y; if(y>=(bbox.pmax.y+zbr)) y=(bbox.pmax.y+zbr); } } if(axis==2){ if(!negaxis) { x-=(defsinex*bulger); if(x<=bbox.pmin.x) x=bbox.pmin.x; if(x<=(bbox.pmin.x+zbr)) x=(bbox.pmin.x+zbr); } else { x+=(defsinex*bulger); if(x>=bbox.pmax.x) x=bbox.pmax.x; if(x>=(bbox.pmax.x+zbr)) x=(bbox.pmax.x+zbr); } } // [jump point] don't melt this point... skipmelt: p.x = x; p.y = y; p.z = z; p = p*invtm; return p; } MeltDeformer::MeltDeformer( TimeValue t, ModContext &mc, float bulgea, float yba, float zba,int confinea, int vistype, float visvalue, int axisa, int negaxisa, Matrix3& modmat, Matrix3& modinv) { // Save the tm and inverse tm tm = modmat; invtm = modinv; time = t; // mjm - 5.14.99 ybr = yba; zbr = zba; bulger = bulgea; confiner = confinea; vistypea=vistype; visvaluea=visvalue; axis=axisa; negaxis=negaxisa; // Save the bounding box assert(mc.box); bbox = *mc.box; cx = bbox.Center().x; cy = bbox.Center().y; cz = bbox.Center().z; // Compute the size and center xsize = bbox.pmax.x - bbox.pmin.x; ysize = bbox.pmax.y - bbox.pmin.y; zsize = bbox.pmax.z - bbox.pmin.z; size=(xsize>ysize) ? xsize:ysize; size=(zsize>size) ? zsize:size; size /= 2.0f; ybr/= 100.0f; zbr/= 10.0f; bulger/=100.0f; } // Provides a reference to our callback object to handle the deformation. Deformer& MeltMod::GetDeformer( TimeValue t,ModContext &mc,Matrix3& mat,Matrix3& invmat) { float yb,zb,bulge,visvaluer; int confine,vistyper,axis,negaxis; pblock->GetValue(PB_MELTAMT,t,bulge,FOREVER); pblock->GetValue(PB_YB,t,yb,FOREVER); pblock->GetValue(PB_ZB,t,zb,FOREVER); pblock->GetValue(PB_CONFINE,t,confine,FOREVER); pblock->GetValue(PB_VISTYPE,t,vistyper,FOREVER); pblock->GetValue(PB_VISVAL,t,visvaluer,FOREVER); pblock->GetValue(PB_AXIS,t,axis,FOREVER); pblock->GetValue(PB_NEGAXIS,t,negaxis,FOREVER); // Evaluate the presets to values // used to be called Viscosity, which is why this is vis<...> if(vistyper==0) visvaluer=2.0f; if(vistyper==1) visvaluer=12.0f; if(vistyper==2) visvaluer=0.4f; if(vistyper==3) visvaluer=0.7f; if(vistyper==4) visvaluer=visvaluer; // Build and return deformer static MeltDeformer deformer; deformer = MeltDeformer(t,mc,bulge,yb,zb,confine,vistyper,visvaluer, axis,negaxis,mat,invmat); return deformer; } /*===========================================================================*\ | Get parameter types \*===========================================================================*/ ParamDimension *MeltMod::GetParameterDim(int pbIndex) { return defaultDim; } /*===========================================================================*\ | Returns parameter names \*===========================================================================*/ TSTR MeltMod::GetParameterName(int pbIndex) { switch (pbIndex) { case PB_MELTAMT: return TSTR(GetString(IDS_MELTAMOUNT)); case PB_YB: return TSTR(GetString(IDS_SPREAD)); case PB_ZB: return TSTR(GetString(IDS_CUTOFF)); case PB_CONFINE: return TSTR(GetString(IDS_CONFINE)); case PB_VISTYPE: return TSTR(GetString(IDS_SOLIDITY)); case PB_VISVAL: return TSTR(GetString(IDS_SOLIDITYVAL)); case PB_AXIS: return TSTR(GetString(IDS_AXIS)); case PB_NEGAXIS: return TSTR(GetString(IDS_NEGAXIS)); default: return TSTR(_T("")); } } /*===========================================================================*\ | The Class Descriptor \*===========================================================================*/ class DecayClassDesc:public ClassDesc { public: int IsPublic() { return 1; } void * Create(BOOL loading = FALSE) { return new MeltMod; } const TCHAR * ClassName() { return GetString(IDS_MELTMOD); } SClass_ID SuperClassID() { return OSM_CLASS_ID; } Class_ID ClassID() { return Class_ID(MELT_ID1,MELT_ID2); } const TCHAR* Category() { return GetString(IDS_CATEGORY); } }; static DecayClassDesc decayDesc; ClassDesc* GetMeltModDesc() { return &decayDesc; } /*===========================================================================*\ | The DLL Functions \*===========================================================================*/ int controlsInit = FALSE; BOOL WINAPI DllMain(HINSTANCE hinstDLL,ULONG fdwReason,LPVOID lpvReserved) { // Hang on to this DLL's instance handle. hInstance = hinstDLL; if (! controlsInit) { controlsInit = TRUE; InitCustomControls(hInstance); InitCommonControls(); } return(TRUE); } /*===========================================================================*\ | Plugin interface code \*===========================================================================*/ __declspec( dllexport ) int LibNumberClasses() {return 1;} __declspec( dllexport ) ClassDesc* LibClassDesc(int i) { switch(i) { case 0: return GetMeltModDesc(); default: return 0; } } __declspec( dllexport ) const TCHAR * LibDescription() { return GetString(IDS_LIBDESC); } __declspec( dllexport ) ULONG LibVersion() { return VERSION_3DSMAX; } // Let the plug-in register itself for deferred loading __declspec( dllexport ) ULONG CanAutoDefer() { return 1; } TCHAR *GetString(int id) { static TCHAR buf[256]; if (hInstance) return LoadString(hInstance, id, buf, sizeof(buf)) ? buf : NULL; return NULL; }
[ "benjamin.barratt@icloud.com" ]
benjamin.barratt@icloud.com
fc1d857e412f634d879e6163a2b30755b1dcb703
7188c98e04cd9c48942195b7f0f22e4717efb674
/chrome/chrome_cleaner/chrome_utils/extensions_util_unittest.cc
a8d420fd195de541f64d5fc87207b715c5afafd7
[ "BSD-3-Clause" ]
permissive
tornodo/chromium
1aa8fda7e9f506ddf26d69cd74fcf0e9e6595e39
1d748d142bde525249a816b1d9179cd9b9fa6419
refs/heads/master
2022-11-30T12:17:02.909786
2020-08-01T03:40:02
2020-08-01T03:40:02
197,871,448
0
0
BSD-3-Clause
2020-08-01T03:40:03
2019-07-20T02:53:57
null
UTF-8
C++
false
false
21,905
cc
// Copyright 2018 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/chrome_cleaner/chrome_utils/extensions_util.h" #include <memory> #include <string> #include <unordered_set> #include <utility> #include <vector> #include "base/base_paths_win.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/json/json_string_value_serializer.h" #include "base/path_service.h" #include "base/stl_util.h" #include "base/strings/string16.h" #include "base/strings/utf_string_conversions.h" #include "base/synchronization/waitable_event.h" #include "base/test/scoped_path_override.h" #include "base/test/test_reg_util_win.h" #include "base/test/test_timeouts.h" #include "base/win/registry.h" #include "chrome/chrome_cleaner/parsers/json_parser/test_json_parser.h" #include "chrome/chrome_cleaner/test/test_extensions.h" #include "chrome/chrome_cleaner/test/test_file_util.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using base::WaitableEvent; namespace chrome_cleaner { namespace { const int kExtensionIdLength = 32; struct ExtensionIDHash { size_t operator()(const ForceInstalledExtension& extension) const { return std::hash<std::string>{}(extension.id.AsString()); } }; struct ExtensionIDEqual { bool operator()(const ForceInstalledExtension& lhs, const ForceInstalledExtension& rhs) const { return lhs.id == rhs.id; } }; bool ExtensionPolicyRegistryEntryFound( TestRegistryEntry test_entry, const std::vector<ExtensionPolicyRegistryEntry>& found_policies) { for (const ExtensionPolicyRegistryEntry& policy : found_policies) { base::string16 test_entry_value(test_entry.value); if (policy.extension_id == test_entry_value.substr(0, kExtensionIdLength) && policy.hkey == test_entry.hkey && policy.path == test_entry.path && policy.name == test_entry.name) { return true; } } return false; } } // namespace TEST(ExtensionsUtilTest, GetExtensionForcelistRegistryPolicies) { registry_util::RegistryOverrideManager registry_override; registry_override.OverrideRegistry(HKEY_CURRENT_USER); registry_override.OverrideRegistry(HKEY_LOCAL_MACHINE); for (const TestRegistryEntry& policy : kExtensionForcelistEntries) { base::win::RegKey policy_key; ASSERT_EQ(ERROR_SUCCESS, policy_key.Create(policy.hkey, policy.path.c_str(), KEY_ALL_ACCESS)); ASSERT_TRUE(policy_key.Valid()); ASSERT_EQ(ERROR_SUCCESS, policy_key.WriteValue(policy.name.c_str(), policy.value.c_str())); } std::vector<ExtensionPolicyRegistryEntry> policies; GetExtensionForcelistRegistryPolicies(&policies); for (const TestRegistryEntry& expected_result : kExtensionForcelistEntries) { EXPECT_TRUE(ExtensionPolicyRegistryEntryFound(expected_result, policies)); } } TEST(ExtensionsUtilTest, RemoveForcelistPolicyExtensions) { registry_util::RegistryOverrideManager registry_override; registry_override.OverrideRegistry(HKEY_CURRENT_USER); registry_override.OverrideRegistry(HKEY_LOCAL_MACHINE); for (const TestRegistryEntry& policy : kExtensionForcelistEntries) { base::win::RegKey policy_key; ASSERT_EQ(ERROR_SUCCESS, policy_key.Create(policy.hkey, policy.path.c_str(), KEY_ALL_ACCESS)); DCHECK(policy_key.Valid()); ASSERT_EQ(ERROR_SUCCESS, policy_key.WriteValue(policy.name.c_str(), policy.value.c_str())); base::string16 value; policy_key.ReadValue(policy.name.c_str(), &value); ASSERT_EQ(value, policy.value); } std::vector<ForceInstalledExtension> extensions; std::vector<ExtensionPolicyRegistryEntry> policies; GetExtensionForcelistRegistryPolicies(&policies); for (ExtensionPolicyRegistryEntry& policy : policies) { ForceInstalledExtension extension( ExtensionID::Create(base::WideToUTF8(policy.extension_id)).value(), POLICY_EXTENSION_FORCELIST, "", ""); extension.policy_registry_entry = std::make_shared<ExtensionPolicyRegistryEntry>(std::move(policy)); extensions.push_back(extension); } for (ForceInstalledExtension& extension : extensions) { base::win::RegKey policy_key; ASSERT_TRUE(RemoveForcelistPolicyExtension(extension)); ASSERT_EQ(ERROR_SUCCESS, policy_key.Open(extension.policy_registry_entry->hkey, extension.policy_registry_entry->path.c_str(), KEY_READ)); base::string16 value; policy_key.ReadValue(extension.policy_registry_entry->name.c_str(), &value); ASSERT_EQ(value, L""); } } TEST(ExtensionsUtilTest, GetNonWhitelistedDefaultExtensions) { // Set up a fake default extensions JSON file. base::ScopedPathOverride program_files_override(base::DIR_PROGRAM_FILES); base::FilePath program_files_dir; ASSERT_TRUE( base::PathService::Get(base::DIR_PROGRAM_FILES, &program_files_dir)); base::FilePath fake_apps_dir( program_files_dir.Append(kFakeChromeFolder).Append(L"default_apps")); ASSERT_TRUE(base::CreateDirectoryAndGetError(fake_apps_dir, nullptr)); base::FilePath default_extensions_file = fake_apps_dir.Append(L"external_extensions.json"); CreateFileWithContent(default_extensions_file, kDefaultExtensionsJson, sizeof(kDefaultExtensionsJson) - 1); ASSERT_TRUE(base::PathExists(default_extensions_file)); // Set up an invalid default extensions JSON file base::ScopedPathOverride program_files_x86_override( base::DIR_PROGRAM_FILESX86); ASSERT_TRUE( base::PathService::Get(base::DIR_PROGRAM_FILESX86, &program_files_dir)); fake_apps_dir = program_files_dir.Append(kFakeChromeFolder).Append(L"default_apps"); ASSERT_TRUE(base::CreateDirectoryAndGetError(fake_apps_dir, nullptr)); default_extensions_file = fake_apps_dir.Append(L"external_extensions.json"); CreateFileWithContent(default_extensions_file, kInvalidDefaultExtensionsJson, sizeof(kInvalidDefaultExtensionsJson) - 1); ASSERT_TRUE(base::PathExists(default_extensions_file)); TestJsonParser json_parser; std::vector<ExtensionPolicyFile> policies; base::WaitableEvent done(WaitableEvent::ResetPolicy::MANUAL, WaitableEvent::InitialState::NOT_SIGNALED); GetNonWhitelistedDefaultExtensions(&json_parser, &policies, &done); ASSERT_TRUE(done.TimedWait(TestTimeouts::action_timeout())); const base::string16 expected_extension_ids[] = {kTestExtensionId1, kTestExtensionId2}; ASSERT_EQ(base::size(expected_extension_ids), policies.size()); const base::string16 found_extension_ids[] = {policies[0].extension_id, policies[1].extension_id}; EXPECT_THAT(expected_extension_ids, ::testing::UnorderedElementsAreArray(found_extension_ids)); } TEST(ExtensionsUtilTest, RemoveNonWhitelistedDefaultExtensions) { // Set up a fake default extensions JSON file. base::ScopedPathOverride program_files_override(base::DIR_PROGRAM_FILES); base::FilePath program_files_dir; ASSERT_TRUE( base::PathService::Get(base::DIR_PROGRAM_FILES, &program_files_dir)); base::FilePath fake_apps_dir( program_files_dir.Append(kFakeChromeFolder).Append(L"default_apps")); ASSERT_TRUE(base::CreateDirectoryAndGetError(fake_apps_dir, nullptr)); base::FilePath default_extensions_file = fake_apps_dir.Append(L"external_extensions.json"); CreateFileWithContent(default_extensions_file, kDefaultExtensionsJson, sizeof(kDefaultExtensionsJson) - 1); ASSERT_TRUE(base::PathExists(default_extensions_file)); // Set up an invalid default extensions JSON file base::ScopedPathOverride program_files_x86_override( base::DIR_PROGRAM_FILESX86); ASSERT_TRUE( base::PathService::Get(base::DIR_PROGRAM_FILESX86, &program_files_dir)); fake_apps_dir = program_files_dir.Append(kFakeChromeFolder).Append(L"default_apps"); ASSERT_TRUE(base::CreateDirectoryAndGetError(fake_apps_dir, nullptr)); default_extensions_file = fake_apps_dir.Append(L"external_extensions.json"); CreateFileWithContent(default_extensions_file, kInvalidDefaultExtensionsJson, sizeof(kInvalidDefaultExtensionsJson) - 1); ASSERT_TRUE(base::PathExists(default_extensions_file)); TestJsonParser json_parser; std::vector<ExtensionPolicyFile> policies; base::WaitableEvent done(WaitableEvent::ResetPolicy::MANUAL, WaitableEvent::InitialState::NOT_SIGNALED); GetNonWhitelistedDefaultExtensions(&json_parser, &policies, &done); ASSERT_TRUE(done.TimedWait(TestTimeouts::action_timeout())); std::vector<ForceInstalledExtension> extensions; for (ExtensionPolicyFile& policy : policies) { ForceInstalledExtension extension( ExtensionID::Create(base::WideToUTF8(policy.extension_id)).value(), DEFAULT_APPS_EXTENSION, "", ""); extension.policy_file = std::make_shared<ExtensionPolicyFile>(std::move(policy)); extensions.push_back(extension); } base::Value json_result = extensions[0].policy_file->json->data.Clone(); for (ForceInstalledExtension& extension : extensions) { ASSERT_TRUE(RemoveDefaultExtension(extension, &json_result)); } std::string result; JSONStringValueSerializer serializer(&result); ASSERT_TRUE(serializer.Serialize(json_result)); ASSERT_EQ(result, kValidDefaultExtensionsJson); base::Value original = json_result.Clone(); for (ForceInstalledExtension& extension : extensions) { ASSERT_FALSE(RemoveDefaultExtension(extension, &json_result)); ASSERT_EQ(original, json_result); } } TEST(ExtensionsUtilTest, GetNonWhitelistedDefaultExtensionsNoFilesFound) { base::ScopedPathOverride program_files_override(base::DIR_PROGRAM_FILES); base::ScopedPathOverride program_files_x86_override( base::DIR_PROGRAM_FILESX86); TestJsonParser json_parser; std::vector<ExtensionPolicyFile> policies; base::WaitableEvent done(WaitableEvent::ResetPolicy::MANUAL, WaitableEvent::InitialState::NOT_SIGNALED); GetNonWhitelistedDefaultExtensions(&json_parser, &policies, &done); ASSERT_TRUE(done.TimedWait(TestTimeouts::action_timeout())); size_t expected_policies_found = 0; ASSERT_EQ(expected_policies_found, policies.size()); } TEST(ExtensionsUtilTest, GetExtensionSettingsForceInstalledExtensions) { registry_util::RegistryOverrideManager registry_override; registry_override.OverrideRegistry(HKEY_CURRENT_USER); registry_override.OverrideRegistry(HKEY_LOCAL_MACHINE); base::win::RegKey settings_key; ASSERT_EQ(ERROR_SUCCESS, settings_key.Create(HKEY_LOCAL_MACHINE, kExtensionSettingsPolicyPath, KEY_ALL_ACCESS)); ASSERT_TRUE(settings_key.Valid()); ASSERT_EQ(ERROR_SUCCESS, settings_key.WriteValue(kExtensionSettingsName, kExtensionSettingsJsonOnlyForced)); TestJsonParser json_parser; std::vector<ExtensionPolicyRegistryEntry> policies; base::WaitableEvent done(WaitableEvent::ResetPolicy::MANUAL, WaitableEvent::InitialState::NOT_SIGNALED); GetExtensionSettingsForceInstalledExtensions(&json_parser, &policies, &done); ASSERT_TRUE(done.TimedWait(TestTimeouts::action_timeout())); // Check that only the two force installed extensions were found const base::string16 expected_extension_ids[] = {kTestExtensionId4, kTestExtensionId5}; const base::string16 found_extension_ids[] = {policies[0].extension_id, policies[1].extension_id}; EXPECT_THAT(expected_extension_ids, ::testing::UnorderedElementsAreArray(found_extension_ids)); // Also check that the collected registry entries match the values in the // registry. for (const ExtensionPolicyRegistryEntry& policy : policies) { EXPECT_EQ(policy.hkey, HKEY_LOCAL_MACHINE); EXPECT_EQ(policy.path, kExtensionSettingsPolicyPath); EXPECT_EQ(policy.name, kExtensionSettingsName); } } TEST(ExtensionsUtilTest, RemoveExtensionSettingsForceInstalledExtensions) { registry_util::RegistryOverrideManager registry_override; registry_override.OverrideRegistry(HKEY_CURRENT_USER); registry_override.OverrideRegistry(HKEY_LOCAL_MACHINE); base::win::RegKey settings_key; ASSERT_EQ(ERROR_SUCCESS, settings_key.Create(HKEY_LOCAL_MACHINE, kExtensionSettingsPolicyPath, KEY_ALL_ACCESS)); DCHECK(settings_key.Valid()); ASSERT_EQ(ERROR_SUCCESS, settings_key.WriteValue(kExtensionSettingsName, kExtensionSettingsJsonOnlyForced)); TestJsonParser json_parser; std::vector<ExtensionPolicyRegistryEntry> policies; base::WaitableEvent done(WaitableEvent::ResetPolicy::MANUAL, WaitableEvent::InitialState::NOT_SIGNALED); GetExtensionSettingsForceInstalledExtensions(&json_parser, &policies, &done); ASSERT_TRUE(done.TimedWait(TestTimeouts::action_timeout())); std::unordered_set<ForceInstalledExtension, ExtensionIDHash, ExtensionIDEqual> extensions; base::Value json_result = policies[0].json->data.Clone(); for (ExtensionPolicyRegistryEntry& policy : policies) { ForceInstalledExtension extension( ExtensionID::Create(base::WideToUTF8(policy.extension_id)).value(), POLICY_EXTENSION_SETTINGS, "", ""); extension.policy_registry_entry = std::make_shared<ExtensionPolicyRegistryEntry>(std::move(policy)); extensions.insert(extension); } for (const ForceInstalledExtension& extension : extensions) { ASSERT_TRUE( RemoveExtensionSettingsPoliciesExtension(extension, &json_result)); } std::string result; JSONStringValueSerializer serializer(&result); ASSERT_TRUE(serializer.Serialize(json_result)); ASSERT_EQ(result, "{}"); base::Value original = json_result.Clone(); for (const ForceInstalledExtension& extension : extensions) { ASSERT_FALSE( RemoveExtensionSettingsPoliciesExtension(extension, &json_result)); ASSERT_EQ(original, json_result); } } TEST(ExtensionsUtilTest, RemoveSomeExtensionSettingsForceInstalledExtensions) { registry_util::RegistryOverrideManager registry_override; registry_override.OverrideRegistry(HKEY_CURRENT_USER); registry_override.OverrideRegistry(HKEY_LOCAL_MACHINE); base::win::RegKey settings_key; ASSERT_EQ(ERROR_SUCCESS, settings_key.Create(HKEY_LOCAL_MACHINE, kExtensionSettingsPolicyPath, KEY_ALL_ACCESS)); DCHECK(settings_key.Valid()); ASSERT_EQ(ERROR_SUCCESS, settings_key.WriteValue(kExtensionSettingsName, kExtensionSettingsJson)); TestJsonParser json_parser; std::vector<ExtensionPolicyRegistryEntry> policies; base::WaitableEvent done(WaitableEvent::ResetPolicy::MANUAL, WaitableEvent::InitialState::NOT_SIGNALED); GetExtensionSettingsForceInstalledExtensions(&json_parser, &policies, &done); ASSERT_TRUE(done.TimedWait(TestTimeouts::action_timeout())); std::unordered_set<ForceInstalledExtension, ExtensionIDHash, ExtensionIDEqual> extensions; base::Value json_result = policies[0].json->data.Clone(); for (ExtensionPolicyRegistryEntry& policy : policies) { ForceInstalledExtension extension( ExtensionID::Create(base::WideToUTF8(policy.extension_id)).value(), POLICY_EXTENSION_SETTINGS, "", ""); extension.policy_registry_entry = std::make_shared<ExtensionPolicyRegistryEntry>(std::move(policy)); extensions.insert(extension); } for (const ForceInstalledExtension& extension : extensions) { ASSERT_TRUE( RemoveExtensionSettingsPoliciesExtension(extension, &json_result)); } std::string result; JSONStringValueSerializer serializer(&result); ASSERT_TRUE(serializer.Serialize(json_result)); ASSERT_EQ(result, kValidExtensionSettingsJson); base::Value original = json_result.Clone(); for (const ForceInstalledExtension& extension : extensions) { ASSERT_FALSE( RemoveExtensionSettingsPoliciesExtension(extension, &json_result)); ASSERT_EQ(original, json_result); } } TEST(ExtensionsUtilTest, GetExtensionSettingsForceInstalledExtensionsNoneFound) { registry_util::RegistryOverrideManager registry_override; registry_override.OverrideRegistry(HKEY_CURRENT_USER); registry_override.OverrideRegistry(HKEY_LOCAL_MACHINE); TestJsonParser json_parser; std::vector<ExtensionPolicyRegistryEntry> policies; base::WaitableEvent done(WaitableEvent::ResetPolicy::MANUAL, WaitableEvent::InitialState::NOT_SIGNALED); GetExtensionSettingsForceInstalledExtensions(&json_parser, &policies, &done); ASSERT_TRUE(done.TimedWait(TestTimeouts::action_timeout())); size_t expected_policies_found = 0; ASSERT_EQ(expected_policies_found, policies.size()); } TEST(ExtensionsUtilTest, GetMasterPreferencesExtensions) { // Set up a fake master preferences JSON file. base::ScopedPathOverride program_files_override(base::DIR_PROGRAM_FILES); base::FilePath program_files_dir; ASSERT_TRUE( base::PathService::Get(base::DIR_PROGRAM_FILES, &program_files_dir)); base::FilePath chrome_dir(program_files_dir.Append(kChromeExePath)); ASSERT_TRUE(base::CreateDirectoryAndGetError(chrome_dir, nullptr)); base::FilePath master_preferences = chrome_dir.Append(kMasterPreferencesFileName); CreateFileWithContent(master_preferences, kMasterPreferencesJson, sizeof(kMasterPreferencesJson) - 1); ASSERT_TRUE(base::PathExists(master_preferences)); TestJsonParser json_parser; std::vector<ExtensionPolicyFile> policies; base::WaitableEvent done(WaitableEvent::ResetPolicy::MANUAL, WaitableEvent::InitialState::NOT_SIGNALED); GetMasterPreferencesExtensions(&json_parser, &policies, &done); ASSERT_TRUE(done.TimedWait(TestTimeouts::action_timeout())); const base::string16 expected_extension_ids[] = {kTestExtensionId6, kTestExtensionId7}; ASSERT_EQ(base::size(expected_extension_ids), policies.size()); const base::string16 found_extension_ids[] = {policies[0].extension_id, policies[1].extension_id}; EXPECT_THAT(expected_extension_ids, ::testing::UnorderedElementsAreArray(found_extension_ids)); } TEST(ExtensionsUtilTest, RemoveMasterPreferencesExtensionsNoneFound) { // Set up a fake master preferences JSON file. base::ScopedPathOverride program_files_override(base::DIR_PROGRAM_FILES); base::FilePath program_files_dir; ASSERT_TRUE( base::PathService::Get(base::DIR_PROGRAM_FILES, &program_files_dir)); base::FilePath chrome_dir(program_files_dir.Append(kChromeExePath)); ASSERT_TRUE(base::CreateDirectoryAndGetError(chrome_dir, nullptr)); base::FilePath master_preferences = chrome_dir.Append(kMasterPreferencesFileName); CreateFileWithContent(master_preferences, kMasterPreferencesJson, sizeof(kMasterPreferencesJson) - 1); ASSERT_TRUE(base::PathExists(master_preferences)); TestJsonParser json_parser; std::vector<ExtensionPolicyFile> policies; base::WaitableEvent done(WaitableEvent::ResetPolicy::MANUAL, WaitableEvent::InitialState::NOT_SIGNALED); GetMasterPreferencesExtensions(&json_parser, &policies, &done); ASSERT_TRUE(done.TimedWait(TestTimeouts::action_timeout())); std::vector<ForceInstalledExtension> extensions; for (ExtensionPolicyFile& policy : policies) { ForceInstalledExtension extension( ExtensionID::Create(base::WideToUTF8(policy.extension_id)).value(), POLICY_MASTER_PREFERENCES, "", ""); extension.policy_file = std::make_shared<ExtensionPolicyFile>(std::move(policy)); extensions.push_back(extension); } base::Value json_result = extensions[0].policy_file->json->data.Clone(); for (ForceInstalledExtension& extension : extensions) { ASSERT_TRUE(RemoveMasterPreferencesExtension(extension, &json_result)); } std::string result; JSONStringValueSerializer serializer(&result); ASSERT_TRUE(serializer.Serialize(json_result)); ASSERT_EQ(result, kValidMasterPreferencesJson); } TEST(ExtensionsUtilTest, GetMasterPreferencesExtensionsNoneFound) { // Set up a fake master preferences JSON file. base::ScopedPathOverride program_files_override(base::DIR_PROGRAM_FILES); base::FilePath program_files_dir; ASSERT_TRUE( base::PathService::Get(base::DIR_PROGRAM_FILES, &program_files_dir)); base::FilePath chrome_dir(program_files_dir.Append(kChromeExePath)); ASSERT_TRUE(base::CreateDirectoryAndGetError(chrome_dir, nullptr)); base::FilePath master_preferences = chrome_dir.Append(kMasterPreferencesFileName); CreateFileWithContent(master_preferences, kMasterPreferencesJsonNoExtensions, sizeof(kMasterPreferencesJsonNoExtensions) - 1); ASSERT_TRUE(base::PathExists(master_preferences)); TestJsonParser json_parser; std::vector<ExtensionPolicyFile> policies; base::WaitableEvent done(WaitableEvent::ResetPolicy::MANUAL, WaitableEvent::InitialState::NOT_SIGNALED); GetMasterPreferencesExtensions(&json_parser, &policies, &done); ASSERT_TRUE(done.TimedWait(TestTimeouts::action_timeout())); size_t expected_policies_found = 0; ASSERT_EQ(expected_policies_found, policies.size()); } } // namespace chrome_cleaner
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
ca4b07848603afd3bc5a5b9cdd969e7f003adcf9
11a0a5ab2fa132ea71e09b93f120d418fd034b45
/Workspace/src/localization_converter/src/localization_converter_node.cpp
af273968b1994c0e2ad9fb9286b8f1fe296784b5
[]
no_license
mluczyn/MarsRover2019
17b05753536967378d01a48c8911b2e996f00a69
43167763e58886c73543df27a0592055ecb2bf00
refs/heads/master
2020-04-18T10:36:34.984976
2019-01-19T02:39:56
2019-01-19T02:39:56
167,472,609
0
0
null
2019-01-25T02:35:48
2019-01-25T02:35:48
null
UTF-8
C++
false
false
2,860
cpp
#include <ros/ros.h> #include <geometry_msgs/Pose2D.h> #include <nav_msgs/Odometry.h> #include <sensor_msgs/NavSatFix.h> #include <tf/tf.h> #include <tf2_geometry_msgs/tf2_geometry_msgs.h> #include <tf2_ros/buffer.h> #include <tf2_ros/transform_listener.h> #include <robot_localization/SetDatum.h> tf2_ros::Buffer tfBuffer; sensor_msgs::NavSatFixConstPtr pNavSatOrigin = nullptr; void NavSatCallback(sensor_msgs::NavSatFixConstPtr msg) { pNavSatOrigin = msg; } // Helper to fill in pose messages void CreatePoseMsgForFrame(const std::string& worldFrameId, geometry_msgs::Pose2D& poseMsg) { geometry_msgs::TransformStamped roverLocToFrame; try { roverLocToFrame = tfBuffer.lookupTransform( worldFrameId, "base_link", ros::Time(0), ros::Duration(2)); } catch (tf2::TransformException &ex) { ROS_ERROR("%s", ex.what()); } double curGpsUtmX = roverLocToFrame.transform.translation.x; double curGpsUtmY = roverLocToFrame.transform.translation.y; double heading = 0; heading = tf::getYaw(roverLocToFrame.transform.rotation);// - M_PI / 2; if (heading < -M_PI) { heading += 2 * M_PI; } //ROS_INFO("X: %f, Y: %f, Heading: %f",curGpsUtmX, curGpsUtmY, heading); poseMsg.x = curGpsUtmX; poseMsg.y = curGpsUtmY; poseMsg.theta = heading; } int main(int argc, char** argv) { ros::init(argc, argv, "localization_converter"); ros::NodeHandle nh; tf2_ros::TransformListener tfListener(tfBuffer); ros::Subscriber navSatSub = nh.subscribe("/navsat/fix", 1, NavSatCallback); ros::Publisher utmPub = nh.advertise<geometry_msgs::Pose2D>("/localization/pose_utm",1); ros::Publisher mapPub = nh.advertise<geometry_msgs::Pose2D>("/localization/pose_map",1); ros::Rate loopRate(10); // Wait until we get coord so we can manually set datum while (ros::ok() && !pNavSatOrigin) { loopRate.sleep(); ros::spinOnce(); } if (!ros::ok()) { return -1; } // Set the datum ros::ServiceClient datumClient = nh.serviceClient<robot_localization::SetDatum>("/datum"); if (!datumClient.exists()) { ROS_WARN("Datum service does not exist. Waiting..."); datumClient.waitForExistence(); } robot_localization::SetDatum request; request.request.geo_pose.position.latitude = pNavSatOrigin->latitude; request.request.geo_pose.position.longitude = pNavSatOrigin->longitude; request.request.geo_pose.orientation.w = 1.0; ROS_INFO("Setting Datum"); if(!datumClient.call(request)) { ROS_ERROR("SetDatum failed"); return -1; } // Publish pose in map and utm frames while(ros::ok()) { geometry_msgs::Pose2D utmPose; CreatePoseMsgForFrame("utm",utmPose); utmPub.publish(utmPose); geometry_msgs::Pose2D mapPose; CreatePoseMsgForFrame("map",mapPose); mapPub.publish(mapPose); loopRate.sleep(); } return 0; }
[ "tommeredith14@gmail.com" ]
tommeredith14@gmail.com
7143c05336535ef26aabfb20ba246cac53287cea
ee81010b5bbd0c8ecb432f17d608e27dd9d22906
/Chapter7/Asio/Tutorial/timer4.cpp
0e7694a7deb1d25a99814f1313d2b1721813f7b6
[]
no_license
xujie-nm/learnMuduo
c7a5b9e106e575e6c328aacacdc78dc8ac9ba20f
fbb9c9abb278f7e9a7346084eda320590fdff113
refs/heads/master
2021-01-10T01:18:22.589885
2016-01-08T08:37:54
2016-01-08T08:37:54
43,409,342
0
0
null
null
null
null
UTF-8
C++
false
false
951
cpp
#include <muduo/net/EventLoop.h> #include <iostream> #include <boost/bind.hpp> #include <boost/noncopyable.hpp> class Printer : boost::noncopyable{ public: Printer(muduo::net::EventLoop* loop) : loop_(loop), count_(0){ loop_->runAfter(1, boost::bind(&Printer::print, this)); } ~Printer(){ std::cout << "Final count is " << count_ << "\n"; } void print(){ if(count_ < 5){ std::cout << count_ << "\n"; ++count_; loop_->runAfter(1, boost::bind(&Printer::print, this)); }else{ loop_->quit(); } } private: muduo::net::EventLoop* loop_; int count_; }; // 以成员函数作为timerCallback int main(int argc, const char *argv[]) { muduo::net::EventLoop loop; Printer printer(&loop); loop.loop(); return 0; }
[ "xujie_nm@163.com" ]
xujie_nm@163.com
5b599bb70d0d45b98ace1135d7e8ed83e1128690
0014fb5ce4aa3a6f460128bb646a3c3cfe81eb9e
/testdata/14/7/src/node7.cpp
afc5cca2affec0554b4add209134bda80a087831
[]
no_license
yps158/randomGraph
c1fa9c531b11bb935d112d1c9e510b5c02921df2
68f9e2e5b0bed1f04095642ee6924a68c0768f0c
refs/heads/master
2021-09-05T05:32:45.210171
2018-01-24T11:23:06
2018-01-24T11:23:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,868
cpp
#include "ros/ros.h" #include "std_msgs/String.h" #include "unistd.h" #include <sstream> #include <random> std::random_device rd; std::mt19937 gen(rd()); std::normal_distribution<> d(0.012325, 0.005); class Node7{ public: Node7(){ sub_3_7_flag = 0; sub_3_7 = n.subscribe("topic_3_7", 1, &Node7::middlemanCallback3,this); sub_6_7_flag = 0; sub_6_7 = n.subscribe("topic_6_7", 1, &Node7::middlemanCallback6,this); pub_7_10 = n.advertise<std_msgs::String>("topic_7_10", 1); pub_7_9 = n.advertise<std_msgs::String>("topic_7_9", 1); pub_7_8 = n.advertise<std_msgs::String>("topic_7_8", 1); } void middlemanCallback3(const std_msgs::String::ConstPtr& msg){ if(sub_6_7_flag == 1 && true){ usleep(d(gen)*1000000); ROS_INFO("I'm node7 last from node3, intercepted: [%s]", msg->data.c_str()); pub_7_10.publish(msg); pub_7_9.publish(msg); pub_7_8.publish(msg); sub_6_7_flag = 0; } else{ ROS_INFO("I'm node7, from node3 intercepted: [%s]", msg->data.c_str()); sub_3_7_flag = 1; } } void middlemanCallback6(const std_msgs::String::ConstPtr& msg){ if(sub_3_7_flag == 1 && true){ usleep(d(gen)*1000000); ROS_INFO("I'm node7 last from node6, intercepted: [%s]", msg->data.c_str()); pub_7_10.publish(msg); pub_7_9.publish(msg); pub_7_8.publish(msg); sub_3_7_flag = 0; } else{ ROS_INFO("I'm node7, from node6 intercepted: [%s]", msg->data.c_str()); sub_6_7_flag = 1; } } private: ros::NodeHandle n; ros::Publisher pub_7_10; ros::Publisher pub_7_9; ros::Publisher pub_7_8; int sub_3_7_flag; ros::Subscriber sub_3_7; int sub_6_7_flag; ros::Subscriber sub_6_7; }; int main(int argc, char **argv){ ros::init(argc, argv, "node7"); Node7 node7; ros::spin(); return 0; }
[ "sasaki@thinkingreed.co.jp" ]
sasaki@thinkingreed.co.jp
38bc8d41bac84cdcb4859156db475ee621ea72eb
ad8271700e52ec93bc62a6fa3ee52ef080e320f2
/CatalystRichPresence/CatalystSDK/ClientPlayerInputPlaybackEntityData.h
2a8c0f158a07c1b41718861daba43d01b4d2da27
[]
no_license
RubberDuckShobe/CatalystRPC
6b0cd4482d514a8be3b992b55ec143273b3ada7b
92d0e2723e600d03c33f9f027c3980d0f087c6bf
refs/heads/master
2022-07-29T20:50:50.640653
2021-03-25T06:21:35
2021-03-25T06:21:35
351,097,185
2
0
null
null
null
null
UTF-8
C++
false
false
631
h
// // Generated with FrostbiteGen by Chod // File: SDK\ClientPlayerInputPlaybackEntityData.h // Created: Wed Mar 10 19:07:53 2021 // #ifndef FBGEN_ClientPlayerInputPlaybackEntityData_H #define FBGEN_ClientPlayerInputPlaybackEntityData_H #include "Realm.h" #include "EntityData.h" class ClientPlayerInputPlaybackEntityData : public EntityData // size = 0x18 { public: static void* GetTypeInfo() { return (void*)0x000000014281FB90; } Realm m_Realm; // 0x18 unsigned char _0x1c[0x4]; const char* m_FileName; // 0x20 const char* m_TestName; // 0x28 }; // size = 0x30 #endif // FBGEN_ClientPlayerInputPlaybackEntityData_H
[ "dog@dog.dog" ]
dog@dog.dog
d508a7ffc7eaff65983b34679e1396ff98a59c7d
3ed684f77dda3a153c8379005a5baae4d0409f27
/D_Platform_Ver3.020/games/30300400_4GJQ/GameCode/Client/Jq.h
28e32d2ee210ea1f234787fd1b6cf3d8efc628eb
[]
no_license
StarKnowData/robinerp
c3f36259ef0f2efc6a3e2a516b40c632e25832f9
65bae698466bad45488971d07ccb9455c0d7d3d9
refs/heads/master
2021-05-30T07:35:35.803122
2012-12-17T13:42:33
2012-12-17T13:42:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,973
h
#pragma once class CJq { public: int m_iPs; bool IsValidateJq() { return true; } ///void ShowAJq(CDC* pDC,CPoint ptStart); public: CJq(void); CJq(int ps); CJq(int hs,int pd); ~CJq(void); }; class CPStack { public: CPtrList List; void operator=(const CPStack & pStack) { memcpy(&List, &pStack.List, sizeof(List)); } bool GetTop(int& i,int& j) { if(List.IsEmpty ())return false; CPoint *p=(CPoint *)List.GetHead (); i=p->x ; j=p->y; return true; } void Push(int i,int j) { CPoint *p=new CPoint(); p->x =i; p->y = j; List.AddHead (p); } bool Pop(int& i,int& j) { if(List.IsEmpty ())return false; CPoint *p=(CPoint *)List.RemoveHead (); i=p->x ; j=p->y; delete p; p=NULL; return true; } BOOL IsEmpty() { return List.IsEmpty () ; } void Empty() { while(!List.IsEmpty ()) { CPoint *p=(CPoint *)List.RemoveHead (); delete p; p=NULL; } List.RemoveAll (); } CPStack(){} ~CPStack() { Empty(); } }; class CStaticGlbJq { public: void ShowACross(CDC* pDC,CPoint& destCenterPt,int angle); void ShowPath(CDC* pDC, CPoint& destCenterPt, int iDirection, int angle,int x, int y); void ShowAPisa(int ps,CDC* pDC,CPoint& destCenterPt,int angle,bool showback,bool bDraw); CRect GetJqSrcRect(int ps,int angle,bool showback); void Init(); CStaticGlbJq(void) { p_hp_AllQiZi = NULL; Init(); } ~CStaticGlbJq(void) { if(p_hp_AllQiZi)delete p_hp_AllQiZi; // if(p_hp_AllOther)delete p_hp_AllOther; p_hp_AllQiZi =NULL; } CSize mSzSrcQiZi,mSzGrade; private: CGameImageHelper* p_hp_AllQiZi; ///CGameImageHelper* p_hp_AllOther; CGameImage m_bit_AllQiZi_1024;//,m_bit_AllOther_1024; CGameImage m_bit_Path; CGameImage m_btOther; }; extern CStaticGlbJq g_CStaticGlbMj; /*CBitmap* GetAPisa(int ps); CBitmap m_bit_jq_r_sl, m_bit_jq_r_jz, m_bit_jq_r_sz, m_bit_jq_r_liz, m_bit_jq_r_tz, m_bit_jq_r_yz, m_bit_jq_r_lianz, m_bit_jq_r_pz, m_bit_jq_r_gb, m_bit_jq_r_dl, m_bit_jq_r_jq, m_bit_jq_r_zd, m_bit_jq_b_sl, m_bit_jq_b_jz, m_bit_jq_b_sz, m_bit_jq_b_liz, m_bit_jq_b_tz, m_bit_jq_b_yz, m_bit_jq_b_lianz, m_bit_jq_b_pz, m_bit_jq_b_gb, m_bit_jq_b_dl, m_bit_jq_b_jq, m_bit_jq_b_zd, m_bit_jq_k_sl, m_bit_jq_k_jz, m_bit_jq_k_sz, m_bit_jq_k_liz, m_bit_jq_k_tz, m_bit_jq_k_yz, m_bit_jq_k_lianz, m_bit_jq_k_pz, m_bit_jq_k_gb, m_bit_jq_k_dl, m_bit_jq_k_jq, m_bit_jq_k_zd, m_bit_jq_g_sl, m_bit_jq_g_jz, m_bit_jq_g_sz, m_bit_jq_g_liz, m_bit_jq_g_tz, m_bit_jq_g_yz, m_bit_jq_g_lianz, m_bit_jq_g_pz, m_bit_jq_g_gb, m_bit_jq_g_dl, m_bit_jq_g_jq, m_bit_jq_g_zd ; */
[ "china.jeffery@gmail.com" ]
china.jeffery@gmail.com
770dcbfd4b97f9e7176f8cf0b454fee62225fdb6
6acaf6553d71582f3807ad89cc5927070b70569f
/src/player/balancedaiplayer.h
aa90c600474c7b0922d32f4c9f692529bc6783dc
[ "BSD-3-Clause" ]
permissive
Top-Ranger/android-reversi
581f90650c6ba64a6cc6afa8ecdf4e308ecdde04
c56a948f6b0f749d172f54a61882366326cdc5be
refs/heads/master
2021-01-17T13:52:58.675781
2016-06-19T16:53:36
2016-06-19T16:53:36
21,957,215
0
0
null
null
null
null
UTF-8
C++
false
false
2,262
h
/* Copyright (C) 2014 Marcus Soll All rights reserved. You may use this file under the terms of BSD license as follows: Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Jolla Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef BALANCEDAIPLAYER_H #define BALANCEDAIPLAYER_H #include "greedyaiplayer.h" #include "treeaiplayer.h" class BalancedAIPlayer : public Player { Q_OBJECT public: explicit BalancedAIPlayer(QObject *parent = 0); virtual bool isHuman(); virtual void doTurn(Gameboard board, int player); public slots: virtual void humanInput(int x, int y); private slots: void getTurn(int x, int y); private: static const int _modifierPlaystileLow = -3; static const int _modifierPlaystileHigh = -8; static const int _boarderLowHigh = 25; GreedyAIPlayer _greed; TreeAIPlayer _tree; }; #endif // BALANCEDAIPLAYER_H
[ "Superschlumpf@web.de" ]
Superschlumpf@web.de
9588b21c03d53935cec90eda7f034cc02fdf822e
517b880b7ded942855318f8fde7d8b8b5e44e943
/src/pow.cpp
ba0029108f0f332b6e465fcd3fd46d196b5d814e
[ "MIT" ]
permissive
percussionpc/grovcoina
3d8fe5b1215b79cad021c54f1b0a033647049460
900c37d969a8876a66e87e6d94e9c1ec9e847bfe
refs/heads/main
2023-04-08T19:22:04.526917
2021-04-16T20:33:23
2021-04-16T20:33:23
358,711,188
0
0
null
null
null
null
UTF-8
C++
false
false
3,919
cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <pow.h> #include <arith_uint256.h> #include <chain.h> #include <primitives/block.h> #include <uint256.h> unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params) { assert(pindexLast != nullptr); unsigned int nProofOfWorkLimit = UintToArith256(params.powLimit).GetCompact(); // Only change once per difficulty adjustment interval if ((pindexLast->nHeight+1) % params.DifficultyAdjustmentInterval() != 0) { if (params.fPowAllowMinDifficultyBlocks) { // Special difficulty rule for testnet: // If the new block's timestamp is more than 2* 10 minutes // then allow mining of a min-difficulty block. if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing*2) return nProofOfWorkLimit; else { // Return the last non-special-min-difficulty-rules-block const CBlockIndex* pindex = pindexLast; while (pindex->pprev && pindex->nHeight % params.DifficultyAdjustmentInterval() != 0 && pindex->nBits == nProofOfWorkLimit) pindex = pindex->pprev; return pindex->nBits; } } return pindexLast->nBits; } // Go back by what we want to be 14 days worth of blocks // grovcoin: This fixes an issue where a 51% attack can change difficulty at will. // Go back the full period unless it's the first retarget after genesis. Code courtesy of Art Forz int blockstogoback = params.DifficultyAdjustmentInterval()-1; if ((pindexLast->nHeight+1) != params.DifficultyAdjustmentInterval()) blockstogoback = params.DifficultyAdjustmentInterval(); // Go back by what we want to be 14 days worth of blocks const CBlockIndex* pindexFirst = pindexLast; for (int i = 0; pindexFirst && i < blockstogoback; i++) pindexFirst = pindexFirst->pprev; assert(pindexFirst); return CalculateNextWorkRequired(pindexLast, pindexFirst->GetBlockTime(), params); } unsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params) { if (params.fPowNoRetargeting) return pindexLast->nBits; // Limit adjustment step int64_t nActualTimespan = pindexLast->GetBlockTime() - nFirstBlockTime; if (nActualTimespan < params.nPowTargetTimespan/4) nActualTimespan = params.nPowTargetTimespan/4; if (nActualTimespan > params.nPowTargetTimespan*4) nActualTimespan = params.nPowTargetTimespan*4; // Retarget arith_uint256 bnNew; arith_uint256 bnOld; bnNew.SetCompact(pindexLast->nBits); bnOld = bnNew; // grovcoin: intermediate uint256 can overflow by 1 bit const arith_uint256 bnPowLimit = UintToArith256(params.powLimit); bool fShift = bnNew.bits() > bnPowLimit.bits() - 1; if (fShift) bnNew >>= 1; bnNew *= nActualTimespan; bnNew /= params.nPowTargetTimespan; if (fShift) bnNew <<= 1; if (bnNew > bnPowLimit) bnNew = bnPowLimit; return bnNew.GetCompact(); } bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params) { bool fNegative; bool fOverflow; arith_uint256 bnTarget; bnTarget.SetCompact(nBits, &fNegative, &fOverflow); // Check range if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit)) return false; // Check proof of work matches claimed amount if (UintToArith256(hash) > bnTarget) return false; return true; }
[ "82010260+percussionpc@users.noreply.github.com" ]
82010260+percussionpc@users.noreply.github.com
83698a37a1908b87a694a8f6cb802f9177f92d4c
9d9af6723cbfbc1affcb656ec26b0ffafd6386ea
/PhysicsForGamesvs2015_Start/PhysicsForGames/Box.h
e2737422d9c51b64832ceb5f6c3c2df4523ceb53
[]
no_license
RoyKirk/AIEWork
4d3e41b4daa49357b64d0242aa87a72542a28055
e94dfa21303a6dca802d5add0c8a07f6f3f44b0b
refs/heads/master
2021-01-21T04:28:25.086397
2016-08-02T00:41:04
2016-08-02T00:41:04
50,807,839
0
0
null
null
null
null
UTF-8
C++
false
false
424
h
#ifndef _BOX_H_ #define _BOX_H_ #include "RigidBody.h" class Box : public RigidBody { public: Box(); ~Box(); float height; float width; float depth; glm::mat4 rotation; glm::vec3 extents; Box(glm::vec3 _position, glm::vec3 _velocity, float _mass, float _width, float _height, float _depth, glm::mat4 _rotation, glm::vec4 _colour, float _linearDrag, bool _dynamic); virtual void makeGizmo(); }; #endif // !_BOX_H_
[ "ricotalzier@gmail.com" ]
ricotalzier@gmail.com
44736ca6b78a3957136ea602bf5deafd8e016c0d
f0cb4d70e356431819e43f9b29cf8060afc0ae50
/code/sorting/sortingtest.cpp
209db18c0c1b7f0432b54c4aec4d216e4880d4cb
[]
no_license
adityashah30/eecs570termproject
c45e1c0491a2e0e23452bc98df6a0ea10812ef1e
b5d9c3d6613eaf782e99d8f2227c43db3667af75
refs/heads/master
2021-01-18T06:25:34.866150
2016-04-16T14:54:27
2016-04-16T14:54:27
52,625,150
0
0
null
null
null
null
UTF-8
C++
false
false
1,195
cpp
#include "sorting.h" #include "../timer/timer.h" #include <string> #include <cassert> using namespace std; void populateData(Dataset&, Dataset&); int main() { Dataset input; Dataset output; Dataset expectedOutput; int index = 0; for(int numThreads = 1; numThreads < 9; numThreads++) { populateData(input, expectedOutput); Timer timer; timer.startTimer(); sortData(output, input, index, numThreads); timer.stopTimer(); std::cout << "Time to sort data on " << numThreads << " threads : " << timer.getElapsedTime() << std::endl; assert(output == expectedOutput); std::cout << "NumThreads: " << numThreads << "; Test passed!" << std::endl; } return 0; } void populateData(Dataset& input, Dataset& expectedOutput) { input.clear(); expectedOutput.clear(); int numRecords = 1024; int offset = 123; for(int i=0; i<numRecords; i++) { Record inputRecord = {(i+offset)%numRecords, 0, 0.0, 0}; Record outputRecord = {i, 0, 0.0, 0}; input.push_back(inputRecord); expectedOutput.push_back(outputRecord); } }
[ "adityashah30@gmail.com" ]
adityashah30@gmail.com
d78ee19a38968a0561ade6942833c5be5e76f0c6
cc542c374356b2e1be27564bffb5c05fedb0b4c5
/cpp/Circular Array Rotation.cpp
fcaa80449143f435ecc5070a93e9a06965acd125
[]
no_license
shantanumallik/hackerrank-codes
fa9437582c50e7ee2cc68f88e265a54aa1b8e0eb
9649556c84287fb5632b9dc9333c4918efaeee4b
refs/heads/master
2022-05-22T04:52:09.623665
2020-04-22T17:18:10
2020-04-22T17:18:10
256,753,521
0
0
null
null
null
null
UTF-8
C++
false
false
2,265
cpp
#include <bits/stdc++.h> using namespace std; vector<string> split_string(string); // Complete the circularArrayRotation function below. vector<long long> circularArrayRotation(vector<int> a, int k, vector<int> queries) { vector<long long>result; int size = a.size(); for(int x:queries) { int index = (x-(k%size)); if(index<0){ result.push_back(a[size-1 + index + 1]); //continue; } else result.push_back(a[index]); } return result; } int main() { ofstream fout(getenv("OUTPUT_PATH")); string nkq_temp; getline(cin, nkq_temp); vector<string> nkq = split_string(nkq_temp); int n = stoi(nkq[0]); int k = stoi(nkq[1]); int q = stoi(nkq[2]); string a_temp_temp; getline(cin, a_temp_temp); vector<string> a_temp = split_string(a_temp_temp); vector<int> a(n); for (int i = 0; i < n; i++) { int a_item = stoi(a_temp[i]); a[i] = a_item; } vector<int> queries(q); for (int i = 0; i < q; i++) { int queries_item; cin >> queries_item; cin.ignore(numeric_limits<streamsize>::max(), '\n'); queries[i] = queries_item; } vector<long long> result = circularArrayRotation(a, k, queries); for (int i = 0; i < result.size(); i++) { fout << result[i]; if (i != result.size() - 1) { fout << "\n"; } } fout << "\n"; fout.close(); return 0; } vector<string> split_string(string input_string) { string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) { return x == y and x == ' '; }); input_string.erase(new_end, input_string.end()); while (input_string[input_string.length() - 1] == ' ') { input_string.pop_back(); } vector<string> splits; char delimiter = ' '; size_t i = 0; size_t pos = input_string.find(delimiter); while (pos != string::npos) { splits.push_back(input_string.substr(i, pos - i)); i = pos + 1; pos = input_string.find(delimiter, i); } splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1)); return splits; }
[ "shantanu@nim.ba" ]
shantanu@nim.ba
f69f40411c9986a827721816f0dc0aa91eb35f95
260e5dec446d12a7dd3f32e331c1fde8157e5cea
/Indi/SDK/Indi_ThirstSpell_T5_parameters.hpp
c0e72da3483dfa7b6ca0ee4fba7f5f8f0aa6207b
[]
no_license
jfmherokiller/TheOuterWorldsSdkDump
6e140fde4fcd1cade94ce0d7ea69f8a3f769e1c0
18a8c6b1f5d87bb1ad4334be4a9f22c52897f640
refs/heads/main
2023-08-30T09:27:17.723265
2021-09-17T00:24:52
2021-09-17T00:24:52
407,437,218
0
0
null
null
null
null
UTF-8
C++
false
false
361
hpp
#pragma once // TheOuterWorlds SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "Indi_ThirstSpell_T5_classes.hpp" namespace SDK { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "peterpan0413@live.com" ]
peterpan0413@live.com
6abb98cc21ee78f61497b6137f2280d4e1de9241
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
/NT/printscan/ui/prevwnd/pwframe.cpp
1018ed45744fc03447a9aa48cfc43d1a00b95301
[]
no_license
jjzhang166/WinNT5_src_20201004
712894fcf94fb82c49e5cd09d719da00740e0436
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
refs/heads/Win2K3
2023-08-12T01:31:59.670176
2021-10-14T15:14:37
2021-10-14T15:14:37
586,134,273
1
0
null
2023-01-07T03:47:45
2023-01-07T03:47:44
null
UTF-8
C++
false
false
22,347
cpp
/******************************************************************************* * * (C) COPYRIGHT MICROSOFT CORPORATION, 1998 * * TITLE: PWFRAME.CPP * * VERSION: 1.0 * * AUTHOR: ShaunIv * * DATE: 8/12/1999 * * DESCRIPTION: Preview frame class definition * *******************************************************************************/ #include "precomp.h" #pragma hdrstop #include "pwframe.h" #include "simrect.h" #include "miscutil.h" #include "pviewids.h" #include "prevwnd.h" #include "simcrack.h" void WINAPI RegisterWiaPreviewClasses( HINSTANCE hInstance ) { CWiaPreviewWindowFrame::RegisterClass( hInstance ); CWiaPreviewWindow::RegisterClass( hInstance ); } CWiaPreviewWindowFrame::CWiaPreviewWindowFrame( HWND hWnd ) : m_hWnd(hWnd), m_nSizeBorder(DEFAULT_BORDER_SIZE), m_hBackgroundBrush(CreateSolidBrush(GetSysColor(COLOR_WINDOW))), m_bEnableStretch(true), m_bHideEmptyPreview(false), m_nPreviewAlignment(MAKELPARAM(PREVIEW_WINDOW_CENTER,PREVIEW_WINDOW_CENTER)) { ZeroMemory( &m_sizeAspectRatio, sizeof(m_sizeAspectRatio) ); ZeroMemory( &m_sizeDefAspectRatio, sizeof(m_sizeDefAspectRatio) ); } CWiaPreviewWindowFrame::~CWiaPreviewWindowFrame(void) { if (m_hBackgroundBrush) { DeleteObject(m_hBackgroundBrush); m_hBackgroundBrush = NULL; } } LRESULT CWiaPreviewWindowFrame::OnCreate( WPARAM, LPARAM lParam ) { // // Turn off RTL for this window // SetWindowLong( m_hWnd, GWL_EXSTYLE, GetWindowLong(m_hWnd,GWL_EXSTYLE) & ~WS_EX_LAYOUTRTL ); LPCREATESTRUCT lpcs = (LPCREATESTRUCT)lParam; CWiaPreviewWindow::RegisterClass(lpcs->hInstance); HWND hWndPreview = CreateWindowEx( 0, PREVIEW_WINDOW_CLASS, TEXT(""), WS_CHILD|WS_VISIBLE|WS_BORDER|WS_CLIPCHILDREN, 0, 0, 0, 0, m_hWnd, (HMENU)IDC_INNER_PREVIEW_WINDOW, lpcs->hInstance, NULL ); if (!hWndPreview) return(-1); return(0); } LRESULT CWiaPreviewWindowFrame::OnSize( WPARAM wParam, LPARAM ) { if ((SIZE_MAXIMIZED==wParam || SIZE_RESTORED==wParam)) AdjustWindowSize(); return(0); } LRESULT CWiaPreviewWindowFrame::OnSetFocus( WPARAM, LPARAM ) { SetFocus( GetDlgItem(m_hWnd,IDC_INNER_PREVIEW_WINDOW) ); return(0); } LRESULT CWiaPreviewWindowFrame::OnEnable( WPARAM wParam, LPARAM ) { EnableWindow( GetDlgItem(m_hWnd,IDC_INNER_PREVIEW_WINDOW), (BOOL)wParam ); return(0); } int CWiaPreviewWindowFrame::FillRect( HDC hDC, HBRUSH hBrush, int x1, int y1, int x2, int y2 ) { RECT rc; rc.left = x1; rc.top = y1; rc.right = x2; rc.bottom = y2; return(::FillRect( hDC, &rc, hBrush )); } LRESULT CWiaPreviewWindowFrame::OnEraseBkgnd( WPARAM wParam, LPARAM ) { // Only paint the regions around the preview control RECT rcClient; GetClientRect(m_hWnd,&rcClient); HDC hDC = (HDC)wParam; if (hDC) { HWND hWndPreview = GetDlgItem(m_hWnd,IDC_INNER_PREVIEW_WINDOW); if (!hWndPreview || !IsWindowVisible(hWndPreview)) { ::FillRect( hDC, &rcClient, m_hBackgroundBrush ); } else { CSimpleRect rcPreviewWnd = CSimpleRect(hWndPreview,CSimpleRect::WindowRect).ScreenToClient(m_hWnd); FillRect( hDC, m_hBackgroundBrush, 0, 0, rcClient.right, rcPreviewWnd.top ); // top FillRect( hDC, m_hBackgroundBrush, 0, rcPreviewWnd.top, rcPreviewWnd.left, rcPreviewWnd.bottom ); // left FillRect( hDC, m_hBackgroundBrush, rcPreviewWnd.right, rcPreviewWnd.top, rcClient.right, rcPreviewWnd.bottom ); // right FillRect( hDC, m_hBackgroundBrush, 0, rcPreviewWnd.bottom, rcClient.right, rcClient.bottom ); // bottom } } return(1); } LRESULT CWiaPreviewWindowFrame::OnGetBorderSize( WPARAM wParam, LPARAM lParam ) { if (!wParam) { return SendDlgItemMessage( m_hWnd, IDC_INNER_PREVIEW_WINDOW, PWM_GETBORDERSIZE, wParam, lParam ); } else { return m_nSizeBorder; } } LRESULT CWiaPreviewWindowFrame::OnSetBorderSize( WPARAM wParam, LPARAM lParam ) { if (!HIWORD(wParam)) { return SendDlgItemMessage( m_hWnd, IDC_INNER_PREVIEW_WINDOW, PWM_SETBORDERSIZE, wParam, lParam ); } else { m_nSizeBorder = static_cast<UINT>(lParam); if (LOWORD(wParam)) { SendMessage( m_hWnd, WM_SETREDRAW, 0, 0 ); ResizeClientIfNecessary(); SendMessage( m_hWnd, WM_SETREDRAW, 1, 0 ); // Make sure the border of the preview control is drawn correctly. // This is a workaround for a weird bug that causes the resized border to not be redrawn SetWindowPos( GetDlgItem( m_hWnd, IDC_INNER_PREVIEW_WINDOW ), NULL, 0, 0, 0, 0, SWP_NOSIZE|SWP_NOMOVE|SWP_NOACTIVATE|SWP_NOZORDER|SWP_DRAWFRAME ); InvalidateRect( GetDlgItem( m_hWnd, IDC_INNER_PREVIEW_WINDOW ), NULL, FALSE ); UpdateWindow( GetDlgItem( m_hWnd, IDC_INNER_PREVIEW_WINDOW ) ); InvalidateRect( m_hWnd, NULL, TRUE ); UpdateWindow( m_hWnd ); } } return 0; } LRESULT CWiaPreviewWindowFrame::OnHideEmptyPreview( WPARAM, LPARAM lParam ) { m_bHideEmptyPreview = (lParam != 0); AdjustWindowSize(); return 0; } // This gets the exact maximum image size that could be displayed in the preview control LRESULT CWiaPreviewWindowFrame::OnGetClientSize( WPARAM, LPARAM lParam ) { bool bSuccess = false; SIZE *pSize = reinterpret_cast<SIZE*>(lParam); if (pSize) { HWND hWndPreview = GetDlgItem(m_hWnd,IDC_INNER_PREVIEW_WINDOW); if (hWndPreview) { // This will be used to take into account the size of the internal border and frame, so we will // have *EXACT* aspect ratio calculations UINT nAdditionalBorder = WiaPreviewControl_GetBorderSize(hWndPreview,0) * 2; // Add in the size of the border, calculated by comparing the window rect with the client rect // I am assuming the border will be same size in pixels on all sides nAdditionalBorder += CSimpleRect( hWndPreview, CSimpleRect::WindowRect ).Width() - CSimpleRect( hWndPreview, CSimpleRect::ClientRect ).Width(); // Get the client rect for our window CSimpleRect rcClient( m_hWnd, CSimpleRect::ClientRect ); if (rcClient.Width() && rcClient.Height()) { pSize->cx = rcClient.Width() - nAdditionalBorder - m_nSizeBorder * 2; pSize->cy = rcClient.Height() - nAdditionalBorder - m_nSizeBorder * 2; bSuccess = (pSize->cx > 0 && pSize->cy > 0); } } } return (bSuccess != false); } LRESULT CWiaPreviewWindowFrame::OnSetPreviewAlignment( WPARAM wParam, LPARAM lParam ) { m_nPreviewAlignment = lParam; if (wParam) AdjustWindowSize(); return 0; } void CWiaPreviewWindowFrame::AdjustWindowSize(void) { HWND hWndPreview = GetDlgItem(m_hWnd,IDC_INNER_PREVIEW_WINDOW); if (hWndPreview) { if (!m_bHideEmptyPreview || WiaPreviewControl_GetBitmap(hWndPreview)) { // Make sure the window is visible if (!IsWindowVisible(hWndPreview)) { ShowWindow(hWndPreview,SW_SHOW); } // Get the window's client size and shrink it by the border size CSimpleRect rcClient(m_hWnd); rcClient.Inflate(-(int)m_nSizeBorder,-(int)m_nSizeBorder); // This will be used to take into account the size of the internal border and frame, so we will // have *EXACT* aspect ratio calculations UINT nAdditionalBorder = WiaPreviewControl_GetBorderSize(hWndPreview,0) * 2; // I am assuming the border will be same size in pixels on all sides nAdditionalBorder += GetSystemMetrics( SM_CXBORDER ) * 2; // Normally, we will allow stretching. // Assume we won't be doing a proportional resize POINT ptPreviewWndOrigin = { rcClient.left, rcClient.top }; SIZE sizePreviewWindowExtent = { rcClient.Width(), rcClient.Height() }; // Don't want any divide by zero errors if (m_sizeAspectRatio.cx && m_sizeAspectRatio.cy) { SIZE sizePreview = m_sizeAspectRatio; if (m_bEnableStretch || sizePreview.cx > (int)(rcClient.Width()-nAdditionalBorder) || sizePreview.cy > (int)(rcClient.Height()-nAdditionalBorder)) { sizePreview = WiaUiUtil::ScalePreserveAspectRatio( rcClient.Width()-nAdditionalBorder, rcClient.Height()-nAdditionalBorder, m_sizeAspectRatio.cx, m_sizeAspectRatio.cy ); } // Make sure it won't be invisible if (sizePreview.cx && sizePreview.cy) { // Decide where to place it in the x direction if (LOWORD(m_nPreviewAlignment) & PREVIEW_WINDOW_RIGHT) ptPreviewWndOrigin.x = m_nSizeBorder + rcClient.Width() - sizePreview.cx - nAdditionalBorder; else if (LOWORD(m_nPreviewAlignment) & PREVIEW_WINDOW_LEFT) ptPreviewWndOrigin.x = m_nSizeBorder; else ptPreviewWndOrigin.x = ((rcClient.Width() + m_nSizeBorder*2) - sizePreview.cx - nAdditionalBorder) / 2; // Decide where to place it in the y direction if (HIWORD(m_nPreviewAlignment) & PREVIEW_WINDOW_BOTTOM) ptPreviewWndOrigin.y = m_nSizeBorder + rcClient.Height() - sizePreview.cy - nAdditionalBorder; else if (HIWORD(m_nPreviewAlignment) & PREVIEW_WINDOW_TOP) ptPreviewWndOrigin.y = m_nSizeBorder; else ptPreviewWndOrigin.y = ((rcClient.Height() + m_nSizeBorder*2) - sizePreview.cy - nAdditionalBorder) / 2; sizePreviewWindowExtent.cx = sizePreview.cx + nAdditionalBorder; sizePreviewWindowExtent.cy = sizePreview.cy + nAdditionalBorder; } } // Now get the current size to make sure we don't resize the window unnecessarily CSimpleRect rcPreview( hWndPreview, CSimpleRect::WindowRect ); rcPreview.ScreenToClient( m_hWnd ); if (rcPreview.left != ptPreviewWndOrigin.x || rcPreview.top != ptPreviewWndOrigin.y || rcPreview.Width() != sizePreviewWindowExtent.cx || rcPreview.Height() != sizePreviewWindowExtent.cy) { SetWindowPos( hWndPreview, NULL, ptPreviewWndOrigin.x, ptPreviewWndOrigin.y, sizePreviewWindowExtent.cx, sizePreviewWindowExtent.cy, SWP_NOZORDER|SWP_NOACTIVATE ); } } else { // Hide the preview window if we're supposed to ShowWindow(hWndPreview,SW_HIDE); } } } void CWiaPreviewWindowFrame::ResizeClientIfNecessary(void) { HWND hWndPreview = GetDlgItem( m_hWnd, IDC_INNER_PREVIEW_WINDOW ); if (hWndPreview) { SIZE sizePreviousAspectRatio = m_sizeAspectRatio; m_sizeAspectRatio.cx = m_sizeAspectRatio.cy = 0; if (WiaPreviewControl_GetPreviewMode(hWndPreview)) { SIZE sizeCurrResolution; if (WiaPreviewControl_GetResolution( hWndPreview, &sizeCurrResolution )) { SIZE sizePixelResolution; if (WiaPreviewControl_GetImageSize( hWndPreview, &sizePixelResolution )) { WiaPreviewControl_SetResolution( hWndPreview, &sizePixelResolution ); SIZE sizeSelExtent; if (WiaPreviewControl_GetSelExtent( hWndPreview, 0, 0, &sizeSelExtent )) { m_sizeAspectRatio = sizeSelExtent; } WiaPreviewControl_SetResolution( hWndPreview, &sizeCurrResolution ); } } } else { if (m_sizeDefAspectRatio.cx || m_sizeDefAspectRatio.cy) { m_sizeAspectRatio = m_sizeDefAspectRatio; } else { SIZE sizeImage; if (WiaPreviewControl_GetImageSize( hWndPreview, &sizeImage )) { m_sizeAspectRatio = sizeImage; } } } if (!m_sizeAspectRatio.cx || !m_sizeAspectRatio.cy) { m_sizeAspectRatio = m_sizeDefAspectRatio; } if (m_sizeAspectRatio.cx != sizePreviousAspectRatio.cx || m_sizeAspectRatio.cy != sizePreviousAspectRatio.cy) { AdjustWindowSize(); } } } LRESULT CWiaPreviewWindowFrame::OnGetEnableStretch( WPARAM, LPARAM ) { return (m_bEnableStretch != false); } LRESULT CWiaPreviewWindowFrame::OnSetEnableStretch( WPARAM, LPARAM lParam ) { m_bEnableStretch = (lParam != FALSE); ResizeClientIfNecessary(); return 0; } LRESULT CWiaPreviewWindowFrame::OnSetBitmap( WPARAM wParam, LPARAM lParam ) { SendMessage( m_hWnd, WM_SETREDRAW, 0, 0 ); SendDlgItemMessage( m_hWnd, IDC_INNER_PREVIEW_WINDOW, PWM_SETBITMAP, wParam, lParam ); ResizeClientIfNecessary(); SendMessage( m_hWnd, WM_SETREDRAW, 1, 0 ); // Make sure the border of the preview control is drawn correctly. // This is a workaround for a weird bug that causes the resized border to not be redrawn SetWindowPos( GetDlgItem( m_hWnd, IDC_INNER_PREVIEW_WINDOW ), NULL, 0, 0, 0, 0, SWP_NOSIZE|SWP_NOMOVE|SWP_NOACTIVATE|SWP_NOZORDER|SWP_DRAWFRAME ); InvalidateRect( GetDlgItem( m_hWnd, IDC_INNER_PREVIEW_WINDOW ), NULL, FALSE ); UpdateWindow( GetDlgItem( m_hWnd, IDC_INNER_PREVIEW_WINDOW ) ); InvalidateRect( m_hWnd, NULL, TRUE ); UpdateWindow( m_hWnd ); return 0; } // wParam = MAKEWPARAM((BOOL)bOuterBorder,0), lParam = 0 LRESULT CWiaPreviewWindowFrame::OnGetBkColor( WPARAM wParam, LPARAM ) { if (!LOWORD(wParam)) { // Meant for the inner window return (SendMessage( GetDlgItem( m_hWnd, IDC_INNER_PREVIEW_WINDOW ), PWM_GETBKCOLOR, 0, 0 )); } else { LOGBRUSH lb = {0}; GetObject(m_hBackgroundBrush,sizeof(LOGBRUSH),&lb); return (lb.lbColor); } } // wParam = MAKEWPARAM((BOOL)bOuterBorder,(BOOL)bRepaint), lParam = (COLORREF)color LRESULT CWiaPreviewWindowFrame::OnSetBkColor( WPARAM wParam, LPARAM lParam ) { if (!LOWORD(wParam)) { // Meant for the inner window SendMessage( GetDlgItem( m_hWnd, IDC_INNER_PREVIEW_WINDOW ), PWM_SETBKCOLOR, HIWORD(wParam), lParam ); } else { HBRUSH hBrush = CreateSolidBrush( static_cast<COLORREF>(lParam) ); if (hBrush) { if (m_hBackgroundBrush) { DeleteObject(m_hBackgroundBrush); m_hBackgroundBrush = NULL; } m_hBackgroundBrush = hBrush; if (HIWORD(wParam)) { InvalidateRect( m_hWnd, NULL, TRUE ); UpdateWindow( m_hWnd ); } } } return (0); } LRESULT CWiaPreviewWindowFrame::OnCommand( WPARAM wParam, LPARAM lParam ) { // Forward notifications to the parent return (SendNotifyMessage( GetParent(m_hWnd), WM_COMMAND, MAKEWPARAM(GetWindowLongPtr(m_hWnd,GWLP_ID),HIWORD(wParam)), reinterpret_cast<LPARAM>(m_hWnd) )); } LRESULT CWiaPreviewWindowFrame::OnSetDefAspectRatio( WPARAM wParam, LPARAM lParam ) { SIZE *pNewDefAspectRatio = reinterpret_cast<SIZE*>(lParam); if (pNewDefAspectRatio) { m_sizeDefAspectRatio = *pNewDefAspectRatio; } else { m_sizeDefAspectRatio.cx = m_sizeDefAspectRatio.cy = 0; } ResizeClientIfNecessary(); return (0); } BOOL CWiaPreviewWindowFrame::RegisterClass( HINSTANCE hInstance ) { WNDCLASS wc; memset( &wc, 0, sizeof(wc) ); wc.style = CS_DBLCLKS; wc.lpfnWndProc = WndProc; wc.hInstance = hInstance; wc.hbrBackground = NULL; wc.lpszClassName = PREVIEW_WINDOW_FRAME_CLASS; BOOL res = (::RegisterClass(&wc) != 0); return(res != 0); } LRESULT CWiaPreviewWindowFrame::OnSetPreviewMode( WPARAM wParam, LPARAM lParam ) { SendMessage( m_hWnd, WM_SETREDRAW, 0, 0 ); LRESULT lRes = SendDlgItemMessage( m_hWnd, IDC_INNER_PREVIEW_WINDOW, PWM_SETPREVIEWMODE, wParam, lParam ); ResizeClientIfNecessary(); SendMessage( m_hWnd, WM_SETREDRAW, 1, 0 ); // Make sure the border of the preview control is drawn correctly. // This is a workaround for a weird bug that causes the resized border to not be redrawn SetWindowPos( GetDlgItem( m_hWnd, IDC_INNER_PREVIEW_WINDOW ), NULL, 0, 0, 0, 0, SWP_NOSIZE|SWP_NOMOVE|SWP_NOACTIVATE|SWP_NOZORDER|SWP_DRAWFRAME ); InvalidateRect( GetDlgItem( m_hWnd, IDC_INNER_PREVIEW_WINDOW ), NULL, FALSE ); UpdateWindow( GetDlgItem( m_hWnd, IDC_INNER_PREVIEW_WINDOW ) ); InvalidateRect( m_hWnd, NULL, TRUE ); UpdateWindow( m_hWnd ); return lRes; } LRESULT CALLBACK CWiaPreviewWindowFrame::WndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam ) { SC_BEGIN_MESSAGE_HANDLERS(CWiaPreviewWindowFrame) { // Handle these messages SC_HANDLE_MESSAGE( WM_CREATE, OnCreate ); SC_HANDLE_MESSAGE( WM_SIZE, OnSize ); SC_HANDLE_MESSAGE( WM_SETFOCUS, OnSetFocus ); SC_HANDLE_MESSAGE( WM_ENABLE, OnEnable ); SC_HANDLE_MESSAGE( WM_ERASEBKGND, OnEraseBkgnd ); SC_HANDLE_MESSAGE( PWM_SETBITMAP, OnSetBitmap ); SC_HANDLE_MESSAGE( WM_COMMAND, OnCommand ); SC_HANDLE_MESSAGE( PWM_GETBKCOLOR, OnGetBkColor ); SC_HANDLE_MESSAGE( PWM_SETBKCOLOR, OnSetBkColor ); SC_HANDLE_MESSAGE( PWM_SETDEFASPECTRATIO, OnSetDefAspectRatio ); SC_HANDLE_MESSAGE( PWM_SETPREVIEWMODE, OnSetPreviewMode ); SC_HANDLE_MESSAGE( PWM_GETCLIENTSIZE, OnGetClientSize ); SC_HANDLE_MESSAGE( PWM_GETENABLESTRETCH, OnGetEnableStretch ); SC_HANDLE_MESSAGE( PWM_SETENABLESTRETCH, OnSetEnableStretch ); SC_HANDLE_MESSAGE( PWM_SETBORDERSIZE, OnSetBorderSize ); SC_HANDLE_MESSAGE( PWM_GETBORDERSIZE, OnGetBorderSize ); SC_HANDLE_MESSAGE( PWM_HIDEEMPTYPREVIEW, OnHideEmptyPreview ); SC_HANDLE_MESSAGE( PWM_SETPREVIEWALIGNMENT, OnSetPreviewAlignment ); // Forward all of these standard messages to the control SC_FORWARD_MESSAGE( WM_ENTERSIZEMOVE, GetDlgItem( hWnd, IDC_INNER_PREVIEW_WINDOW ) ); SC_FORWARD_MESSAGE( WM_EXITSIZEMOVE, GetDlgItem( hWnd, IDC_INNER_PREVIEW_WINDOW ) ); SC_FORWARD_MESSAGE( WM_SETTEXT, GetDlgItem( hWnd, IDC_INNER_PREVIEW_WINDOW ) ); // Forward all of these private messages to the control SC_FORWARD_MESSAGE( PWM_SETRESOLUTION, GetDlgItem( hWnd, IDC_INNER_PREVIEW_WINDOW ) ); SC_FORWARD_MESSAGE( PWM_GETRESOLUTION, GetDlgItem( hWnd, IDC_INNER_PREVIEW_WINDOW ) ); SC_FORWARD_MESSAGE( PWM_CLEARSELECTION, GetDlgItem( hWnd, IDC_INNER_PREVIEW_WINDOW ) ); SC_FORWARD_MESSAGE( PWM_GETIMAGESIZE, GetDlgItem( hWnd, IDC_INNER_PREVIEW_WINDOW ) ); SC_FORWARD_MESSAGE( PWM_GETBITMAP, GetDlgItem( hWnd, IDC_INNER_PREVIEW_WINDOW ) ); SC_FORWARD_MESSAGE( PWM_GETHANDLESIZE, GetDlgItem( hWnd, IDC_INNER_PREVIEW_WINDOW ) ); SC_FORWARD_MESSAGE( PWM_GETBGALPHA, GetDlgItem( hWnd, IDC_INNER_PREVIEW_WINDOW ) ); SC_FORWARD_MESSAGE( PWM_GETHANDLETYPE, GetDlgItem( hWnd, IDC_INNER_PREVIEW_WINDOW ) ); SC_FORWARD_MESSAGE( PWM_SETBGALPHA, GetDlgItem( hWnd, IDC_INNER_PREVIEW_WINDOW ) ); SC_FORWARD_MESSAGE( PWM_SETHANDLETYPE, GetDlgItem( hWnd, IDC_INNER_PREVIEW_WINDOW ) ); SC_FORWARD_MESSAGE( PWM_GETSELCOUNT, GetDlgItem( hWnd, IDC_INNER_PREVIEW_WINDOW ) ); SC_FORWARD_MESSAGE( PWM_GETSELORIGIN, GetDlgItem( hWnd, IDC_INNER_PREVIEW_WINDOW ) ); SC_FORWARD_MESSAGE( PWM_GETSELEXTENT, GetDlgItem( hWnd, IDC_INNER_PREVIEW_WINDOW ) ); SC_FORWARD_MESSAGE( PWM_SETSELORIGIN, GetDlgItem( hWnd, IDC_INNER_PREVIEW_WINDOW ) ); SC_FORWARD_MESSAGE( PWM_SETSELEXTENT, GetDlgItem( hWnd, IDC_INNER_PREVIEW_WINDOW ) ); SC_FORWARD_MESSAGE( PWM_GETALLOWNULLSELECTION, GetDlgItem( hWnd, IDC_INNER_PREVIEW_WINDOW ) ); SC_FORWARD_MESSAGE( PWM_SETALLOWNULLSELECTION, GetDlgItem( hWnd, IDC_INNER_PREVIEW_WINDOW ) ); SC_FORWARD_MESSAGE( PWM_SELECTIONDISABLED, GetDlgItem( hWnd, IDC_INNER_PREVIEW_WINDOW ) ); SC_FORWARD_MESSAGE( PWM_SETHANDLESIZE, GetDlgItem( hWnd, IDC_INNER_PREVIEW_WINDOW ) ); SC_FORWARD_MESSAGE( PWM_DISABLESELECTION, GetDlgItem( hWnd, IDC_INNER_PREVIEW_WINDOW ) ); SC_FORWARD_MESSAGE( PWM_DETECTREGIONS, GetDlgItem( hWnd, IDC_INNER_PREVIEW_WINDOW ) ); SC_FORWARD_MESSAGE( PWM_GETPREVIEWMODE, GetDlgItem( hWnd, IDC_INNER_PREVIEW_WINDOW ) ); SC_FORWARD_MESSAGE( PWM_SETBORDERSTYLE, GetDlgItem( hWnd, IDC_INNER_PREVIEW_WINDOW ) ); SC_FORWARD_MESSAGE( PWM_SETBORDERCOLOR, GetDlgItem( hWnd, IDC_INNER_PREVIEW_WINDOW ) ); SC_FORWARD_MESSAGE( PWM_SETHANDLECOLOR, GetDlgItem( hWnd, IDC_INNER_PREVIEW_WINDOW ) ); SC_FORWARD_MESSAGE( PWM_REFRESHBITMAP, GetDlgItem( hWnd, IDC_INNER_PREVIEW_WINDOW ) ); SC_FORWARD_MESSAGE( PWM_SETPROGRESS, GetDlgItem( hWnd, IDC_INNER_PREVIEW_WINDOW ) ); SC_FORWARD_MESSAGE( PWM_GETPROGRESS, GetDlgItem( hWnd, IDC_INNER_PREVIEW_WINDOW ) ); SC_FORWARD_MESSAGE( PWM_GETUSERCHANGEDSELECTION, GetDlgItem( hWnd, IDC_INNER_PREVIEW_WINDOW ) ); SC_FORWARD_MESSAGE( PWM_SETUSERCHANGEDSELECTION, GetDlgItem( hWnd, IDC_INNER_PREVIEW_WINDOW ) ); } SC_END_MESSAGE_HANDLERS(); }
[ "seta7D5@protonmail.com" ]
seta7D5@protonmail.com
b7f9fbba23f4ca5718ca8501844a22bb32e70733
d0d60936f0872daa5caff4866df7ac9063c2ddc7
/testApp/utilitiesx.cpp
098753560b36417f7619f14178280c529ad46189
[ "MIT" ]
permissive
epics-base/pva2pva
36cad1a98e38a872b1e365c57ab5723309f503a4
3b9990e3650fca2673eebfb83645193ac0e5297d
refs/heads/master
2023-03-24T05:59:39.609136
2022-11-03T17:01:22
2022-11-03T17:01:29
104,084,268
4
11
NOASSERTION
2023-03-09T17:07:16
2017-09-19T14:16:27
C++
UTF-8
C++
false
false
64
cpp
// hack to avoid a convienence library #include "utilities.cpp"
[ "mdavidsaver@gmail.com" ]
mdavidsaver@gmail.com
89824b0f748b6903a6516d58600249335473bd80
d81ada4a9b293429649aa5f678b3eac6f2509f2e
/src/LiteSerialLogger.h
b3d5086a1f7d00ab052d361ef2b1f86f4142a779
[]
no_license
Syonyk/LiteSerialLogger
5fc64d225d8914279f502a13ee862e03d8f3e98c
724d9880be3ce26960842f78f6d5f16c84dc2ff8
refs/heads/master
2021-01-19T03:56:09.096941
2017-02-18T16:40:58
2017-02-18T16:40:58
72,374,401
4
1
null
null
null
null
UTF-8
C++
false
false
2,927
h
#include <Arduino.h> /** * LiteSerialLogger - Lightweight serial logging for Arduino. * Copyright (C) 2016 Russell E Graves (Syonyk) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA. */ // Format specifiers for conversions. These are the same as in Print.h #define HEX 16 #define DEC 10 class LiteSerialLogger { public: // Initialize the serial port. Call before any output. void begin(long baudrate); // All the print/println functions return the length written. // String handlers. Print the characters. // __FlashStringHelper is a helpful wrapper for a char* in progmem. You can // use F() when passing things to this to store the data in PROGMEM, and this // works properly. int print(const __FlashStringHelper* message); int print(const char *message); // Null print, just for completeness sake. int print(); // 8 bit types, printed in specified format, with no newline appended. // This prints the decimal or hexadecimal value of the byte. // If you want to print a char as a character, use write(). int print(const char &value, const byte base = DEC); int print(const byte &value, const byte base = DEC); // 16 bit types, printed in specified format. int print(const int &value, const byte base = DEC); int print(const word &value, const byte base = DEC); // 32-bit types, printed in specified format. int print(const long &value, const byte base = DEC); int print(const unsigned long &value, const byte base = DEC); int print(const float &value); // Same stuff, with a newline. int println(); int println(const __FlashStringHelper* message); int println(const char *message); int println(const char &value, const byte base = DEC); int println(const byte &value, const byte base = DEC); int println(const int &value, const byte base = DEC); int println(const word &value, const byte base = DEC); int println(const long &value, const byte base = DEC); int println(const unsigned long &value, const byte format = DEC); int println(const float &value); // Push a byte out onto the port as-is. int write(const char &value); private: // Synchronous put of a character to the port. void put_char(const char c); }; extern LiteSerialLogger LiteSerial;
[ "rgraves@rgravess-iMac-5.local" ]
rgraves@rgravess-iMac-5.local