blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
941 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
142 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
121 values
content
stringlengths
3
10.4M
authors
sequencelengths
1
1
author_id
stringlengths
0
158
ae87739c045ea0c8bc03b31469eb4d63ff4fb84a
c2b161ce52e127f7036882f0ffa523f520dc1c87
/programs/agents/agent-2-0.cpp
20f8987344433330692e870d7ac0f279127a0ab7
[]
no_license
dmosher42/cosmos-core
9991e7268044fa3b139716a48e3bf3c707ea3422
625d1de84eded5ff69b2870a9cbf57c1a6476f89
refs/heads/master
2023-03-21T17:26:05.288081
2021-01-28T00:12:33
2021-01-28T00:12:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
19,098
cpp
/******************************************************************** * Copyright (C) 2015 by Interstel Technologies, Inc. * and Hawaii Space Flight Laboratory. * * This file is part of the COSMOS/core that is the central * module for COSMOS. For more information on COSMOS go to * <http://cosmos-project.com> * * The COSMOS/core software is licenced under the * GNU Lesser General Public License (LGPL) version 3 licence. * * You should have received a copy of the * GNU Lesser General Public License * If not, go to <http://www.gnu.org/licenses/> * * COSMOS/core is free software: you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * COSMOS/core is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * Refer to the "licences" folder for further information on the * condititons and terms to use this software. ********************************************************************/ /*! \file agent.cpp * \brief Agent control program source */ //! \ingroup general //! \defgroup agent_client Agent control program //! This program allows communication with any of the Agents on the local network. //! With it you can: //! - list available Agents //! - acquire the request list of specific Agents //! - command specific Agents //! - monitor Agent traffic #include "support/configCosmos.h" #include <stdlib.h> #include "agent/agentclass.h" #include "support/jsonlib.h" #include "physics/physicslib.h" #include "support/datalib.h" #include "sys/stat.h" #include "limits.h" #include <iostream> const int REQUEST_WAIT_TIME = 2; const int SERVER_WAIT_TIME = 6; string output; string node_name = ""; string agent_name = ""; int main(int argc, char *argv[]) { int nbytes; beatstruc cbeat; Agent *agent; // dont' print debug messages //agent->debug_level = 0; agent = new Agent(); if (agent->cinfo == nullptr) { fprintf(agent->get_debug_fd(), "%16.10f %s Failed to start Agent %s on Node %s Dated %s : %s\n",currentmjd(), mjd2iso8601(currentmjd()).c_str(), agent->getAgent().c_str(), agent->getNode().c_str(), utc2iso8601(data_ctime(argv[0])).c_str(), cosmos_error_string(NODE_ERROR_NODE).c_str()); exit(NODE_ERROR_NODE); } // check command line arguments switch (argc) { case 1: { printf("Usage: agent [ list | dump [soh, beat, ###] | node_name agent_name \"request [ arguments ]\" ]\n"); exit(1); } break; case 2: case 3: case 4: case 5: // agent dump request if (!strcmp(argv[1],"dump")) { double lmjd = 0., dmjd; string channel; Agent::AgentMessage message_type; Agent::messstruc message; int i; locstruc loc; // JIMNOTE: this block will never be entered switch(argc) { case 5: agent_name = argv[4]; case 4: node_name = argv[3]; case 3: channel = argv[2]; if (channel == "soh") { message_type = Agent::AgentMessage::SOH; } else if (channel == "beat") { message_type = Agent::AgentMessage::BEAT; } else if (channel == "request") { message_type = Agent::AgentMessage::REQUEST; } else if (channel == "response") { message_type = Agent::AgentMessage::RESPONSE; } else { message_type = (Agent::AgentMessage)atoi(channel.c_str()); } break; case 2: channel.clear(); message_type = Agent::AgentMessage::ALL; break; } while (1) { int32_t iretn; if ((iretn=agent->readring(message, message_type, 1., Agent::Where::TAIL)) > 0) { Agent::AgentMessage message_type_read = (Agent::AgentMessage)iretn; // Skip if either not Agent::AgentMessage::ALL, or not desired AGENT_MESSAGE if (!channel.empty() && message_type != message_type_read) { continue; } if (!node_name.empty() && node_name != message.meta.beat.node) { continue; } if (!agent_name.empty() && agent_name != message.meta.beat.proc) { continue; } switch (message_type_read) { case Agent::AgentMessage::SOH: printf("[SOH]"); break; case Agent::AgentMessage::BEAT: printf("[BEAT]"); break; case Agent::AgentMessage::REQUEST: printf("[REQUEST]"); break; case Agent::AgentMessage::RESPONSE: printf("[RESPONSE]"); break; default: printf("[%d]",message_type_read); break; } printf("%.15g:[%s:%s][%s:%u](%lu:%lu:%zu)\n",message.meta.beat.utc, message.meta.beat.node, message.meta.beat.proc, message.meta.beat.addr, message.meta.beat.port, message.jdata.size(), message.adata.size(), message.bdata.size()); printf("%s\n",message.jdata.c_str()); if (message_type_read < Agent::AgentMessage::BINARY) { if (!channel.empty()) { printf("%s\n",message.adata.c_str()); } } if ((channel=="info") && message_type_read == Agent::AgentMessage::TRACK) { if (agent->cinfo->node.loc.utc > 0.) { if (lmjd > 0.) dmjd = 86400.*(agent->cinfo->node.loc.utc-lmjd); else dmjd = 0.; loc.pos.icrf.s = agent->cinfo->node.loc.pos.icrf.s; loc.pos.utc = agent->cinfo->node.loc.utc; pos_eci(&loc); printf("%16.15g %6.4g %s %8.3f %8.3f %8.3f %5.1f %5.1f %5.1f\n",agent->cinfo->node.loc.utc,dmjd,agent->cinfo->node.name,DEGOF(loc.pos.geod.s.lon),DEGOF(loc.pos.geod.s.lat),loc.pos.geod.s.h,agent->cinfo->node.phys.powgen,agent->cinfo->node.phys.powuse,agent->cinfo->node.phys.battlev); lmjd = agent->cinfo->node.loc.utc; } } if ((channel=="imu") && message_type_read == Agent::AgentMessage::IMU) { for (i=0; i<agent->cinfo->devspec.imu_cnt; i++) { if (agent->cinfo->agent[0].beat.utc > 0.) { if (lmjd > 0.) dmjd = 86400.*(agent->cinfo->agent[0].beat.utc-lmjd); else dmjd = 0.; printf("%.15g %.4g\n",loc.utc,dmjd); lmjd = agent->cinfo->agent[0].beat.utc; } } } } fflush(stdout); } //end infinite while loop break; } else if (!strcmp(argv[1],"list")) { size_t agent_count = 0; ElapsedTime et; agent->post(Agent::AgentMessage::REQUEST, "heartbeat"); COSMOS_SLEEP(.5); do { if (agent->agent_list.size() > agent_count) { for (size_t i=agent_count; i<agent->agent_list.size(); ++i) { beatstruc cbeat = agent->agent_list[i]; // NS1 //agent->send_request(cbeat,(char *)"getvalue {\"agent_pid\"}", output, REQUEST_WAIT_TIME); // NS2 -- works! agent->send_request(cbeat, "get_value {\"agent[0].pid\"}", output, REQUEST_WAIT_TIME); printf("[%lu] %.15g %s %s %s %hu %u\n",i,cbeat.utc,cbeat.node,cbeat.proc,cbeat.addr,cbeat.port,cbeat.bsz); printf("\t%s\n",output.c_str()); fflush(stdout); } agent_count = agent->agent_list.size(); } COSMOS_SLEEP(.1); } while (et.split() < SERVER_WAIT_TIME); exit(0); break; } else if (!strcmp(argv[1],"list_json")) { size_t agent_count = 0; ElapsedTime et; agent->post(Agent::AgentMessage::REQUEST, "heartbeat"); COSMOS_SLEEP(.1); printf("{\"agent_list\":["); do { if (agent->agent_list.size() > agent_count) { for (size_t i=agent_count; i<agent->agent_list.size(); ++i) { beatstruc cbeat = agent->agent_list[i]; // NS1 //agent->send_request(cbeat,(char *)"getvalue {\"agent_pid\"}", output, REQUEST_WAIT_TIME); // NS2 -- works! agent->send_request(cbeat, "get_value {\"agent[0].pid\"}", output, REQUEST_WAIT_TIME); if(i>0) printf(","); printf("{\"agent_proc\": \"%s\", ", cbeat.proc); printf("\"agent_utc\": %.15g, ", cbeat.utc); printf("\"agent_node\": \"%s\", ", cbeat.node); printf("\"agent_addr\": \"%s\", ", cbeat.addr); printf("\"agent_port\": %hu, ", cbeat.port); printf("\"agent_bsz\": %u, ", cbeat.bsz); // HANDLE RESPONSE OUTPUT FORMAT size_t status_pos; if((status_pos= output.find("[OK]") )!= string::npos){ if(output.at(0) == '{'){ if(status_pos - 1 >= 0 && output.at(status_pos - 1) == '}'){ printf("\"output\": %s,", output.substr(0, status_pos).c_str()); } else { printf("\"output\": %s,", output.c_str()); } } else { printf("\"output\": \"%s\",", output.substr(status_pos ).c_str()); } printf("\"status\": \"OK\"}"); } else if((status_pos = output.find("[NOK]") )!= string::npos){ printf("\"status\": \"NOK\"}"); } else { printf("\"output\": %s }", output.c_str()); } fflush(stdout); } fflush(stdout); agent_count = agent->agent_list.size(); } COSMOS_SLEEP(.1); } while (et.split() < SERVER_WAIT_TIME); printf("]}\n"); exit(0); break; } default: if (!strcmp(argv[1],"dump")) { double lmjd = 0., dmjd; string channel; Agent::AgentMessage message_type; Agent::messstruc message; string header; int i; locstruc loc; if(argc == 3) { channel = argv[2]; if (channel == "soh") { message_type = Agent::AgentMessage::SOH; } else { if (channel == "beat") { message_type = Agent::AgentMessage::BEAT; } else { message_type = (Agent::AgentMessage)atoi(channel.c_str()); } } } else { channel.clear(); message_type = Agent::AgentMessage::ALL; } while (1) { int32_t iretn; if ((iretn=agent->readring(message, Agent::AgentMessage::ALL, 1., Agent::Where::TAIL)) > 0) { Agent::AgentMessage message_type_read = (Agent::AgentMessage)iretn; // Skip if either not Agent::AgentMessage::ALL, or not desired AGENT_MESSAGE if (!channel.empty() && message_type != message_type_read) { continue; } header.resize(message.meta.jlength); if (message_type_read < Agent::AgentMessage::BINARY) { // NS1 memcpy(&header[0], message.adata.data(), message.meta.jlength); json_clear_cosmosstruc(JSON_STRUCT_NODE, agent->cinfo); json_clear_cosmosstruc(JSON_STRUCT_DEVICE, agent->cinfo); json_parse(message.adata.c_str(), agent->cinfo); // NS2 } else { memcpy(&header[0], message.bdata.data(), message.meta.jlength); } switch (message_type_read) { case Agent::AgentMessage::SOH: printf("[SOH]"); break; case Agent::AgentMessage::BEAT: printf("[BEAT]"); break; case Agent::AgentMessage::REQUEST: printf("[REQUEST]"); break; case Agent::AgentMessage::RESPONSE: printf("[RESPONSE]"); break; default: printf("[%d]",message_type_read); break; } printf("[%d] %.15g %s %s %s %hu %u\n",i,message.meta.beat.utc,message.meta.beat.node,message.meta.beat.proc,message.meta.beat.addr,message.meta.beat.port,message.meta.beat.bsz); if (message_type_read < Agent::AgentMessage::BINARY && !channel.empty()) { printf("%s\n",message.adata.c_str()); } if ((channel=="info") && message_type_read == Agent::AgentMessage::TRACK) { if (agent->cinfo->node.loc.utc > 0.) { if (lmjd > 0.) dmjd = 86400.*(agent->cinfo->node.loc.utc-lmjd); else dmjd = 0.; loc.pos.icrf.s = agent->cinfo->node.loc.pos.icrf.s; loc.pos.utc = agent->cinfo->node.loc.utc; pos_eci(&loc); printf("%16.15g %6.4g %s %8.3f %8.3f %8.3f %5.1f %5.1f %5.1f\n",agent->cinfo->node.loc.utc,dmjd,agent->cinfo->node.name,DEGOF(loc.pos.geod.s.lon),DEGOF(loc.pos.geod.s.lat),loc.pos.geod.s.h,agent->cinfo->node.phys.powgen,agent->cinfo->node.phys.powuse,agent->cinfo->node.phys.battlev); lmjd = agent->cinfo->node.loc.utc; } } if ((channel=="imu") && message_type_read == Agent::AgentMessage::IMU) { for (i=0; i<agent->cinfo->devspec.imu_cnt; i++) { if (agent->cinfo->agent[0].beat.utc > 0.) { if (lmjd > 0.) dmjd = 86400.*(agent->cinfo->agent[0].beat.utc-lmjd); else dmjd = 0.; printf("%.15g %.4g\n",loc.utc,dmjd); lmjd = agent->cinfo->agent[0].beat.utc; } } } } fflush(stdout); } //end infinite while loop } else { // cbeat = agent->find_agent(argv[1], argv[2], SERVER_WAIT_TIME); // if (cbeat.exists) if ((nbytes = agent->get_agent(argv[1], argv[2], SERVER_WAIT_TIME, cbeat)) > 0) { if(argc == 3) { nbytes = agent->send_request(cbeat, "help", std::ref(output), REQUEST_WAIT_TIME); printf("%s [%d]\n", output.c_str(), nbytes); } else { string request; request = argv[3]; for (size_t i=0; i<(size_t)argc-4; ++i) { request += " "; request += argv[i+4]; } nbytes = agent->send_request(cbeat,request.c_str(), output, REQUEST_WAIT_TIME); // printf("%s [%d]\n", output.c_str(), nbytes); // printf("{\"request_output\": %s, \"bytes\": %d }\n", output.c_str(), nbytes); // HANDLE RESPONSE OUTPUT FORMAT printf("{"); size_t status_pos; if((status_pos= output.find("[OK]") )!= string::npos){ if(output.at(0) == '{'){ if(status_pos - 1 >= 0 && output.at(status_pos - 1) == '}'){ printf("\"output\": %s,", output.substr(0, status_pos).c_str()); } else { printf("\"output\": %s,", output.c_str()); } } else { printf("\"output\": \"%s\",", output.substr(0,status_pos ).c_str()); } printf("\"status\": \"OK\"}\n"); } else if((status_pos = output.find("[NOK]") )!= string::npos){ printf("\"status\": \"NOK\"}\n"); } else { printf("\"output\": %s }\n", output.c_str()); } } } else { if (!nbytes){ fprintf(stderr,"node-agent pair [%s:%s] not found\n",argv[1],argv[2]); printf("{\"error\": \"node-agent pair [%s:%s] not found\" }\n",argv[1],argv[2]); } else printf("Error: %d\n", nbytes); } } } }
def0afc4d292baf33836a74b2a8f061db998708c
8fbac4a872eb60796bd30d6c73aaa652a5e0f0d7
/samples/softrender/Textures.cpp
62e5ec927e800668aceb7bfe81fe6f94d81f59df
[ "MIT" ]
permissive
brucelevis/SoftRender
7914382d1b58f816fec3b5cb2c53c2c48213387b
8089844e9ab00ab71ef1a820641ec07ae8df248d
refs/heads/master
2020-04-18T11:50:32.233918
2018-09-06T04:42:49
2018-09-06T04:42:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,328
cpp
// // Created by huangkun on 2018/8/19. // #include "Textures.h" TEST_NODE_IMP_BEGIN Textures::Textures() { TEX_WIDTH = 1024; TEX_HEIGHT = 1024; } bool Textures::init() { SoftRender::init(); verticesPlane = { // postions // texture coords 0.5f, 0.5f, 0.0f, 2.0f, 2.0f, // top right 0.5f, -0.5f, 0.0f, 2.0f, -1.0f, // bottom right -0.5f, -0.5f, 0.0f, -1.0f, -1.0f, // bottom left -0.5f, 0.5f, 0.0f, -1.0f, 2.0f, // bottom top }; indicesPlane = { // note that we start from 0! 0, 1, 3, // first triangle 1, 2, 3 // second triangle }; Mesh *mesh = new Mesh(createVertexs(verticesPlane, 3, 0, 2), indicesPlane); planeMeshes.push_back(mesh); texture2D.load("../res/cat.jpg"); return true; } void Textures::draw(const mat4 &transform) { clearColor(25, 25, 25, 255); modelMatrix.setIdentity(); viewMatrix.setIdentity(); projectMatrix.setIdentity(); // top left modelMatrix.translate(Vector(-0.5f, 0.5f, 0)); Matrix m = modelMatrix; m.mult(viewMatrix); m.mult(projectMatrix); bindTextures({&texture2D}); texture2D.setWrap(GL_REPEAT); for (unsigned int i = 0; i < planeMeshes.size(); i++) drawMesh(*planeMeshes[i], m, 2); // top right modelMatrix.setIdentity(); modelMatrix.translate(Vector(0.5f, 0.5f, 0)); m = modelMatrix; m.mult(viewMatrix); m.mult(projectMatrix); bindTextures({&texture2D}); texture2D.setWrap(GL_MIRRORED_REPEAT); for (unsigned int i = 0; i < planeMeshes.size(); i++) drawMesh(*planeMeshes[i], m, 2); // bottom left modelMatrix.setIdentity(); modelMatrix.translate(Vector(-0.5f, -0.5f, 0)); m = modelMatrix; m.mult(viewMatrix); m.mult(projectMatrix); bindTextures({&texture2D}); texture2D.setWrap(GL_CLAMP_TO_EDGE); for (unsigned int i = 0; i < planeMeshes.size(); i++) drawMesh(*planeMeshes[i], m, 2); // bottom right modelMatrix.setIdentity(); modelMatrix.translate(Vector(0.5f, -0.5f, 0)); m = modelMatrix; m.mult(viewMatrix); m.mult(projectMatrix); bindTextures({&texture2D}); texture2D.setWrap(GL_CLAMP_TO_BORDER); texture2D.setBorderColor(vec4(255, 255, 0, 255)); for (unsigned int i = 0; i < planeMeshes.size(); i++) drawMesh(*planeMeshes[i], m, 2); SoftRender::draw(transform); } void Textures::setPixel(int x, int y, float z, float u, float v, vec3 varying[], const std::vector<vec3> &uniforms, float dudx, float dvdy) { Texture2D *texture = _bindTextures["texture0"]; if (texture) { const vec3 &textureColor = texture->sample(u, v, dudx, dvdy); vec4 color = vec4(vec3(textureColor), 255); SoftRender::setPixel(x, y, z, color); } } Textures::~Textures() { for (unsigned int i = 0; i < planeMeshes.size(); i++) delete planeMeshes[i]; } TEST_NODE_IMP_END
6a64a230ab987ed9f0e640e585cc2e619ff10e8e
b5dca27578786a05a64ee5cbcdac8b85758cc4f6
/Week1/week1-1-bootStrap.cpp
7b7fefc9b981bbb40698ca7adc5392b0bedd72d2
[]
no_license
KieraBacon/GameEngineDevelopment
a7f90df937cb00890b50678e7ea68d3e1b2ac8d6
7ce0420cd40b223bd9df0f54521de6234350ee5d
refs/heads/master
2023-09-04T03:10:48.472815
2021-10-17T06:17:52
2021-10-17T06:17:52
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
3,038
cpp
/*------------------------------------------------------------------------- Welcome to OGRE Object-Oriented Graphics Rendering Engine Minimum code xcopy /y $(ogre_home_v2)\build\bin\debug\*.* $(ProjectDir)x64\debug\ copy /y "C:\Hooman\GBC\GAME3121\Course Materials\GameEngineDevelopment\ogre-sdk-v2.1\build\bin\debug\*.*" "C:\Hooman\GBC\GAME3121\Week1\Week1\$(projectname)\x64\debug\" -------------------------------------------------------------------------*/ //! [fullsource] #include "Ogre.h" #include "OgreApplicationContext.h" #include "OgreInput.h" #include "OgreRTShaderSystem.h" #include <iostream> using namespace Ogre; using namespace OgreBites; class BasicTutorial1 : public ApplicationContext , public InputListener { public: BasicTutorial1(); virtual ~BasicTutorial1() {} void setup(); bool keyPressed(const KeyboardEvent& evt); }; BasicTutorial1::BasicTutorial1() : ApplicationContext("OgreTemplate-V2") { } void BasicTutorial1::setup() { // do not forget to call the base first ApplicationContext::setup(); addInputListener(this); // get a pointer to the already created root Root* root = getRoot(); SceneManager* scnMgr = root->createSceneManager(); // register our scene with the RTSS RTShader::ShaderGenerator* shadergen = RTShader::ShaderGenerator::getSingletonPtr(); shadergen->addSceneManager(scnMgr); //// without light we would just get a black screen //Ogre::Light* light = scnMgr->createLight("MainLight"); //Ogre::SceneNode* lightNode = scnMgr->getRootSceneNode()->createChildSceneNode(); //lightNode->setPosition(0, 10, 15); //lightNode->attachObject(light); //scnMgr->setAmbientLight(ColourValue(1.0, 0.0, 0.0)); //// also need to tell where we are //Ogre::SceneNode* camNode = scnMgr->getRootSceneNode()->createChildSceneNode(); //camNode->setPosition(0, 0, 15); //camNode->lookAt(Ogre::Vector3(0, 0, -1), Ogre::Node::TS_PARENT); //// create the camera //Ogre::Camera* cam = scnMgr->createCamera("myCam"); //cam->setNearClipDistance(5); // specific to this sample //cam->setAutoAspectRatio(true); //camNode->attachObject(cam); //// and tell it to render into the main window //getRenderWindow()->addViewport(cam); //// finally something to render //Ogre::Entity* ent = scnMgr->createEntity("Sinbad.mesh"); //Ogre::SceneNode* node = scnMgr->getRootSceneNode()->createChildSceneNode(); //node->attachObject(ent); } bool BasicTutorial1::keyPressed(const KeyboardEvent& evt) { if (evt.keysym.sym == SDLK_ESCAPE) { getRoot()->queueEndRendering(); } return true; } int main(int argc, char** argv) { try { BasicTutorial1 app; app.initApp(); app.getRoot()->startRendering(); app.closeApp(); } catch (const std::exception& e) { std::cerr << "Error occurred during execution: " << e.what() << '\n'; return 1; } return 0; } //! [fullsource]
832d4782d9e0ba61ec036f452162714dcbacc0ed
efdc794bc1152d9e702ea03e32142cf4ff1031cd
/third_party/pdfium/xfa/fxbarcode/cbc_upca.h
bf90b922b5053e8e39d6792001ac4141cedc6b44
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
taggun/node-pdfium
c3c7c85fd4a280993aa0ce99dcb2f41ce8d592dc
1990bc55e39f700434841e35078cecaa347b1e36
refs/heads/master
2020-12-02T12:44:31.341993
2020-02-26T20:52:34
2020-02-26T20:52:34
96,583,707
3
3
BSD-2-Clause
2020-02-26T20:48:59
2017-07-07T23:34:05
C++
UTF-8
C++
false
false
1,047
h
// Copyright 2016 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #ifndef XFA_FXBARCODE_CBC_UPCA_H_ #define XFA_FXBARCODE_CBC_UPCA_H_ #include "core/fxcrt/fx_string.h" #include "core/fxcrt/fx_system.h" #include "core/fxge/fx_dib.h" #include "xfa/fxbarcode/cbc_onecode.h" class CBC_UPCA : public CBC_OneCode { public: CBC_UPCA(); ~CBC_UPCA() override; // CBC_CodeBase bool Encode(const CFX_WideStringC& contents, bool isDevice, int32_t& e) override; bool RenderDevice(CFX_RenderDevice* device, const CFX_Matrix* matrix, int32_t& e) override; bool RenderBitmap(CFX_DIBitmap*& pOutBitmap, int32_t& e) override; BC_TYPE GetType() override; private: CFX_WideString Preprocess(const CFX_WideStringC& contents); CFX_WideString m_renderContents; }; #endif // XFA_FXBARCODE_CBC_UPCA_H_
9729e5a80760f3f40e261335d0b7bfd9e430af9b
b42ff57503362bd3771b2509335a5bfcec05c452
/utils/customwidgets/customtablemodel/datapointitemmodel.cpp
7e12aef6ae7566a66c561cf0aeb0c2b8ccd5cca6
[]
no_license
yinzhi009/lib
fbda036d06e6cfb35dffa9fb36316f13b6a206b0
db96f6164db7858fa10b7b5bff2410641eca9932
refs/heads/master
2020-05-22T13:34:06.188057
2019-05-13T07:15:03
2019-05-13T07:15:03
186,362,791
0
1
null
null
null
null
UTF-8
C++
false
false
3,950
cpp
#include <QStringList> #include <QSize> #include <QColor> #include "datapointitemmodel.h" DataPointItemModel::DataPointItemModel(QObject *parent) : QAbstractTableModel(parent) , m_headerDatas() , m_datas() { } int DataPointItemModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return m_datas.size(); } int DataPointItemModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent); if (m_headerDatas.isEmpty()) { return 0; } return m_headerDatas.size(); } QVariant DataPointItemModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) { return QVariant(); } if (role == Qt::TextAlignmentRole) { return int(Qt::AlignHCenter| Qt::AlignVCenter); } if (Qt::TextColorRole == role) { if (index.row() < m_datas.size() && index.column() < m_datas[index.row()].size()) { return QVariant(m_datas[index.row()].at(index.column()).getTextColor()); } return QVariant(); } if (role == Qt::DisplayRole) { if (index.row() < m_datas.size() && index.column() < m_datas[index.row()].size()) { return m_datas[index.row()].at(index.column()).data(); } } return QVariant(); } QVariant DataPointItemModel::headerData(int section, Qt::Orientation orientation, int role) const { // 横向标题 if (orientation == Qt::Horizontal && role == Qt::DisplayRole && section < m_headerDatas.count()) { return m_headerDatas.at(section); } return QAbstractTableModel::headerData(section, orientation, role); } bool DataPointItemModel::setData(const QModelIndex &index, const QVariant &value, int role) { if (!index.isValid() || role != Qt::EditRole) { return QAbstractTableModel::setData(index, value, role); } int row = index.row(); int col = index.column(); if (row >= m_datas.size() || col >= m_datas[row].size()) { return false; } DataPointItem &item = m_datas[row][col]; item.setShowText(value.toString()); emit dataChanged(index, index); return true; } Qt::ItemFlags DataPointItemModel::flags(const QModelIndex &index) const { Qt::ItemFlags flags = QAbstractItemModel::flags(index); if (index.isValid()) { flags |= Qt::ItemIsEditable; } return flags; } void DataPointItemModel::setHeader(const QStringList &header) { if (header.isEmpty() || m_headerDatas == header) { return; } // 当表格头变化时,意味着在执行新的案例,重置所有信息 beginResetModel(); m_datas.clear(); m_headerDatas = header; endResetModel(); } void DataPointItemModel::addData(const DataPointItem &data) { int rowIndex = rowCount(QModelIndex()); beginInsertRows(QModelIndex(), rowIndex, rowIndex); if (m_datas.isEmpty()) { addNewLine(data); } else { QList<DataPointItem> &lineDatas = m_datas.last(); if (lineDatas.size() == m_headerDatas.size()) { // new line addNewLine(data); } else { lineDatas << data; } } endInsertRows(); } void DataPointItemModel::clearDatas() { beginResetModel(); m_headerDatas.clear(); m_datas.clear(); endResetModel(); } void DataPointItemModel::refresh() { beginResetModel(); endResetModel(); } void DataPointItemModel::writeMemory(bool isFirstTime) { for (int i = 0; i < m_datas.size(); i++) { for (int j = 0; j < m_datas[i].size(); j++) { m_datas[i][j].writeMemory(isFirstTime); } } // 写完后刷新一下界面 refresh(); } void DataPointItemModel::addNewLine(const DataPointItem &data) { QList<DataPointItem> lineDatas; lineDatas << data; m_datas << lineDatas; }
ab3c863f848fddf30ded3dd8e6c2521774d1b90f
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/git/new_hunk_3239.cpp
33bd9aecc10e9b66914bf7b8f635c4f6490ded0a
[]
no_license
ccdxc/logSurvey
eaf28e9c2d6307140b17986d5c05106d1fd8e943
6b80226e1667c1e0760ab39160893ee19b0e9fb1
refs/heads/master
2022-01-07T21:31:55.446839
2018-04-21T14:12:43
2018-04-21T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
184
cpp
if (!do_for_each_entry_in_dir(dir, 0, nonmatching_ref_fn, &data)) return 1; error("'%s' exists; cannot create '%s'", data.conflicting_refname, refname); return 0; }
72828656f3c9d835dcdb0d1bef030bce081904c8
a3f61587f7e27a0ba0a6e774243ba976a28f5111
/entities/Background.h
cf154eeea5e84b09ccb6d730af45059c4539496f
[]
no_license
Swordelf2/mg2
164e93a10d3914d8d1081f382db69d36b332e8e4
52ec89ce9c3249c81278c17ad07eb067eaf0071d
refs/heads/master
2020-05-19T03:45:12.579391
2019-10-06T13:43:17
2019-10-06T13:43:17
184,808,692
0
0
null
null
null
null
UTF-8
C++
false
false
300
h
#ifndef ENTITIES_BACKGROUND_H #define ENTITIES_BACKGROUND_H #include "../graphics/Entity.h" class Background : public Entity { public: Background(Mesh *mesh = nullptr, Shader *shader = nullptr, Texture *texture = nullptr); virtual ~Background() = default; void Draw() const; }; #endif
cbdd3f7ecbae16e656be58fa203e562f100b8da3
8e97a71b84848e9c91d7675ee118a48b3e324c05
/04.Matrices/Matrices.cpp
d88317a234bac40cc81de33bc202cb6668959bb8
[]
no_license
AndreyPootMay/coursecpp
c1b2bc8cdfa59667c785916efb8e08c34cbc60bd
e9f4ae515947fc70828ebb8e943b74da72073194
refs/heads/master
2020-09-21T12:12:59.391417
2019-12-06T00:38:58
2019-12-06T00:38:58
224,785,838
0
0
null
null
null
null
UTF-8
C++
false
false
1,671
cpp
/* * Matrices.cpp * * Copyright 2019 andrey <andrey@andrey-HP-Notebook> * * 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. * * */ #include <iostream> #include <stdio.h> #define SIZE 100 using namespace std; int main(int argc, char **argv) { int m[SIZE][SIZE], column=0, row=0, index_row=0, index_column=0; cout<<"Ingresa el número de las columnas"<<endl; cin>>column; cout<<"Ingrese el número de las filas"<<endl; cin>>row; for(index_row = 0;index_row < row; index_row++) { for (index_column = 0; index_column < column; index_column++) { cout<<"Escribe las calificaciones para ["<<index_row+1<<"]"<<"["<<index_column+1<<"]"<<endl; cin>>m[index_row][index_column]; } } cout<<"\n\tLas calificaciones almacenadas en la matriz son: "<<endl; cout<<"\n\n"; for(index_row = 0;index_row < row; index_row++) { cout<<"\n\t"; for (index_column = 0; index_column < column; index_column++) { cout<<m[index_row][index_column]<<" "; } } getchar(); return 0; }
44570cedd0643e15645a3b7e31ad353e807bb66a
441036d7bf7b6b17bb478dd8194df27a9ac3dc42
/lib/int128.h
4a3508e5f72af0243bf29380e0f7cec4b535fe4a
[ "MIT" ]
permissive
zjl410091917/int128
d2415cb42003f4a85c1b9b96dc6c23082c88e3c2
c11df72e0cc735acb462b13d12d8bcad7aa9ebfb
refs/heads/main
2023-07-21T21:55:23.489410
2021-08-27T02:33:33
2021-08-27T02:33:33
370,219,773
0
0
null
null
null
null
UTF-8
C++
false
false
12,420
h
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // 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 Google Inc. 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 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #ifndef GOOGLE_PROTOBUF_STUBS_INT128_H_ #define GOOGLE_PROTOBUF_STUBS_INT128_H_ #include <iosfwd> #include <cstdint> #include <string> typedef int8_t int8; typedef int16_t int16; typedef int32_t int32; typedef int64_t int64; typedef uint8_t uint8; typedef uint16_t uint16; typedef uint32_t uint32; typedef uint64_t uint64; struct uint128_pod; // An unsigned 128-bit integer type. Thread-compatible. class uint128 { public: uint128(); // Sets to 0, but don't trust on this behavior. uint128(uint64 top, uint64 bottom); #ifndef SWIG uint128(int bottom); uint128(uint32 bottom); // Top 96 bits = 0 #endif uint128(uint64 bottom); // hi_ = 0 uint128(const uint128_pod &val); // Trivial copy constructor, assignment operator and destructor. void Initialize(uint64 top, uint64 bottom); std::string toString(); // Arithmetic operators. uint128 &operator+=(const uint128 &b); uint128 &operator-=(const uint128 &b); uint128 &operator*=(const uint128 &b); // Long division/modulo for uint128. uint128 &operator/=(const uint128 &b); uint128 &operator%=(const uint128 &b); uint128 operator++(int); uint128 operator--(int); uint128 &operator<<=(int); uint128 &operator>>=(int); uint128 &operator&=(const uint128 &b); uint128 &operator|=(const uint128 &b); uint128 &operator^=(const uint128 &b); uint128 &operator++(); uint128 &operator--(); friend uint64 Uint128Low64(const uint128 &v); friend uint64 Uint128High64(const uint128 &v); // We add "std::" to avoid including all of port.h. friend std::ostream &operator<<(std::ostream &o, const uint128 &b); private: static void DivModImpl(uint128 dividend, uint128 divisor, uint128 *quotient_ret, uint128 *remainder_ret); // Little-endian memory order optimizations can benefit from // having lo_ first, hi_ last. // See util/endian/endian.h and Load128/Store128 for storing a uint128. uint64 lo_; uint64 hi_; // Not implemented, just declared for catching automatic type conversions. uint128(uint8); uint128(uint16); uint128(float v); uint128(double v); }; // This is a POD form of uint128 which can be used for static variables which // need to be operated on as uint128. struct uint128_pod { // Note: The ordering of fields is different than 'class uint128' but the // same as its 2-arg constructor. This enables more obvious initialization // of static instances, which is the primary reason for this struct in the // first place. This does not seem to defeat any optimizations wrt // operations involving this struct. uint64 hi; uint64 lo; }; extern const uint128_pod kuint128max; // allow uint128 to be logged extern std::ostream &operator<<(std::ostream &o, const uint128 &b); // Methods to access low and high pieces of 128-bit value. // Defined externally from uint128 to facilitate conversion // to native 128-bit types when compilers support them. inline uint64 Uint128Low64(const uint128 &v) { return v.lo_; } inline uint64 Uint128High64(const uint128 &v) { return v.hi_; } // TODO: perhaps it would be nice to have int128, a signed 128-bit type? // -------------------------------------------------------------------------- // Implementation details follow // -------------------------------------------------------------------------- inline bool operator==(const uint128 &lhs, const uint128 &rhs) { return (Uint128Low64(lhs) == Uint128Low64(rhs) && Uint128High64(lhs) == Uint128High64(rhs)); } inline bool operator!=(const uint128 &lhs, const uint128 &rhs) { return !(lhs == rhs); } inline uint128::uint128() : lo_(0), hi_(0) {} inline uint128::uint128(uint64 top, uint64 bottom) : lo_(bottom), hi_(top) { } inline uint128::uint128(const uint128_pod &v) : lo_(v.lo), hi_(v.hi) {} inline uint128::uint128(uint64 bottom) : lo_(bottom), hi_(0) {} #ifndef SWIG inline uint128::uint128(uint32 bottom) : lo_(bottom), hi_(0) { } inline uint128::uint128(int bottom) : lo_(bottom), hi_(static_cast<int64>((bottom < 0) ? -1 : 0)) {} #endif inline void uint128::Initialize(uint64 top, uint64 bottom) { hi_ = top; lo_ = bottom; } // Comparison operators. #define CMP128(op) \ inline bool operator op(const uint128 &lhs, const uint128 &rhs) \ { \ return (Uint128High64(lhs) == Uint128High64(rhs)) ? (Uint128Low64(lhs) op Uint128Low64(rhs)) : (Uint128High64(lhs) op Uint128High64(rhs)); \ } CMP128(<) CMP128(>) CMP128(>=) CMP128(<=) #undef CMP128 // Unary operators inline uint128 operator-(const uint128 &val) { const uint64 hi_flip = ~Uint128High64(val); const uint64 lo_flip = ~Uint128Low64(val); const uint64 lo_add = lo_flip + 1; if (lo_add < lo_flip) { return uint128(hi_flip + 1, lo_add); } return uint128(hi_flip, lo_add); } inline bool operator!(const uint128 &val) { return !Uint128High64(val) && !Uint128Low64(val); } // Logical operators. inline uint128 operator~(const uint128 &val) { return uint128(~Uint128High64(val), ~Uint128Low64(val)); } #define LOGIC128(op) \ inline uint128 operator op(const uint128 &lhs, const uint128 &rhs) \ { \ return uint128(Uint128High64(lhs) op Uint128High64(rhs), \ Uint128Low64(lhs) op Uint128Low64(rhs)); \ } LOGIC128(|) LOGIC128(&) LOGIC128(^) #undef LOGIC128 #define LOGICASSIGN128(op) \ inline uint128 &uint128::operator op(const uint128 &other) \ { \ hi_ op other.hi_; \ lo_ op other.lo_; \ return *this; \ } LOGICASSIGN128(|=) LOGICASSIGN128(&=) LOGICASSIGN128(^=) #undef LOGICASSIGN128 // Shift operators. inline uint128 operator<<(const uint128 &val, int amount) { // uint64 shifts of >= 64 are undefined, so we will need some special-casing. if (amount < 64) { if (amount == 0) { return val; } uint64 new_hi = (Uint128High64(val) << amount) | (Uint128Low64(val) >> (64 - amount)); uint64 new_lo = Uint128Low64(val) << amount; return uint128(new_hi, new_lo); } else if (amount < 128) { return uint128(Uint128Low64(val) << (amount - 64), 0); } else { return uint128(0, 0); } } inline uint128 operator>>(const uint128 &val, int amount) { // uint64 shifts of >= 64 are undefined, so we will need some special-casing. if (amount < 64) { if (amount == 0) { return val; } uint64 new_hi = Uint128High64(val) >> amount; uint64 new_lo = (Uint128Low64(val) >> amount) | (Uint128High64(val) << (64 - amount)); return uint128(new_hi, new_lo); } else if (amount < 128) { return uint128(0, Uint128High64(val) >> (amount - 64)); } else { return uint128(0, 0); } } inline uint128 &uint128::operator<<=(int amount) { // uint64 shifts of >= 64 are undefined, so we will need some special-casing. if (amount < 64) { if (amount != 0) { hi_ = (hi_ << amount) | (lo_ >> (64 - amount)); lo_ = lo_ << amount; } } else if (amount < 128) { hi_ = lo_ << (amount - 64); lo_ = 0; } else { hi_ = 0; lo_ = 0; } return *this; } inline uint128 &uint128::operator>>=(int amount) { // uint64 shifts of >= 64 are undefined, so we will need some special-casing. if (amount < 64) { if (amount != 0) { lo_ = (lo_ >> amount) | (hi_ << (64 - amount)); hi_ = hi_ >> amount; } } else if (amount < 128) { lo_ = hi_ >> (amount - 64); hi_ = 0; } else { lo_ = 0; hi_ = 0; } return *this; } inline uint128 operator+(const uint128 &lhs, const uint128 &rhs) { return uint128(lhs) += rhs; } inline uint128 operator-(const uint128 &lhs, const uint128 &rhs) { return uint128(lhs) -= rhs; } inline uint128 operator*(const uint128 &lhs, const uint128 &rhs) { return uint128(lhs) *= rhs; } inline uint128 operator/(const uint128 &lhs, const uint128 &rhs) { return uint128(lhs) /= rhs; } inline uint128 operator%(const uint128 &lhs, const uint128 &rhs) { return uint128(lhs) %= rhs; } inline uint128 &uint128::operator+=(const uint128 &b) { hi_ += b.hi_; uint64 lolo = lo_ + b.lo_; if (lolo < lo_) ++hi_; lo_ = lolo; return *this; } inline uint128 &uint128::operator-=(const uint128 &b) { hi_ -= b.hi_; if (b.lo_ > lo_) --hi_; lo_ -= b.lo_; return *this; } inline uint128 &uint128::operator*=(const uint128 &b) { uint64 a96 = hi_ >> 32; uint64 a64 = hi_ & 0xffffffffu; uint64 a32 = lo_ >> 32; uint64 a00 = lo_ & 0xffffffffu; uint64 b96 = b.hi_ >> 32; uint64 b64 = b.hi_ & 0xffffffffu; uint64 b32 = b.lo_ >> 32; uint64 b00 = b.lo_ & 0xffffffffu; // multiply [a96 .. a00] x [b96 .. b00] // terms higher than c96 disappear off the high side // terms c96 and c64 are safe to ignore carry bit uint64 c96 = a96 * b00 + a64 * b32 + a32 * b64 + a00 * b96; uint64 c64 = a64 * b00 + a32 * b32 + a00 * b64; this->hi_ = (c96 << 32) + c64; this->lo_ = 0; // add terms after this one at a time to capture carry *this += uint128(a32 * b00) << 32; *this += uint128(a00 * b32) << 32; *this += a00 * b00; return *this; } inline uint128 uint128::operator++(int) { uint128 tmp(*this); *this += 1; return tmp; } inline uint128 uint128::operator--(int) { uint128 tmp(*this); *this -= 1; return tmp; } inline uint128 &uint128::operator++() { *this += 1; return *this; } inline uint128 &uint128::operator--() { *this -= 1; return *this; } #endif // GOOGLE_PROTOBUF_STUBS_INT128_H_
2c8e1571c08d4cb27a476c6c12fc689257a7ac89
c67cbd22f9bc3c465fd763fdf87172f2c8ec77d4
/Desktop/Please Work/build/Android/Preview/app/src/main/include/Fuse.Android.TextRend-b6e4a886.h
c861548e3f48b2af5777465b0f4fb3f1d5ab63a7
[]
no_license
AzazelMoreno/Soteria-project
7c58896d6bf5a9ad919bde6ddc2a30f4a07fa0d4
04fdb71065941176867fb9007ecf38bbf851ad47
refs/heads/master
2020-03-11T16:33:22.153713
2018-04-19T19:47:55
2018-04-19T19:47:55
130,120,337
0
0
null
null
null
null
UTF-8
C++
false
false
2,110
h
// This file was generated based on C:/Users/rudy0/AppData/Local/Fusetools/Packages/Fuse.Android.TextRenderer/1.8.1/TextRenderer.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.Object.h> #include <Uno.Recti.h> namespace g{namespace Fuse{namespace Android{struct StaticLayout;}}} namespace g{namespace Fuse{namespace Android{struct TextRenderer;}}} namespace g{namespace Fuse{namespace Android{struct TextRenderer__BackgroundRender;}}} namespace g{namespace Uno{namespace Graphics{struct Texture2D;}}} namespace g{ namespace Fuse{ namespace Android{ // private sealed class TextRenderer.BackgroundRender :282 // { uType* TextRenderer__BackgroundRender_typeof(); void TextRenderer__BackgroundRender__ctor__fn(TextRenderer__BackgroundRender* __this, ::g::Fuse::Android::TextRenderer* textRenderer, uint64_t* textureVersion, ::g::Fuse::Android::StaticLayout* layout, ::g::Uno::Recti* pixelBounds); void TextRenderer__BackgroundRender__DoneCallback_fn(TextRenderer__BackgroundRender* __this); void TextRenderer__BackgroundRender__New1_fn(::g::Fuse::Android::TextRenderer* textRenderer, uint64_t* textureVersion, ::g::Fuse::Android::StaticLayout* layout, ::g::Uno::Recti* pixelBounds, TextRenderer__BackgroundRender** __retval); void TextRenderer__BackgroundRender__UpdateTextureAsync_fn(TextRenderer__BackgroundRender* __this); struct TextRenderer__BackgroundRender : uObject { uStrong< ::g::Fuse::Android::TextRenderer*> _textRenderer; uint64_t _textureVersion; uStrong< ::g::Fuse::Android::StaticLayout*> _layout; ::g::Uno::Recti _pixelBounds; uStrong< ::g::Uno::Graphics::Texture2D*> _result; void ctor_(::g::Fuse::Android::TextRenderer* textRenderer, uint64_t textureVersion, ::g::Fuse::Android::StaticLayout* layout, ::g::Uno::Recti pixelBounds); void DoneCallback(); void UpdateTextureAsync(); static TextRenderer__BackgroundRender* New1(::g::Fuse::Android::TextRenderer* textRenderer, uint64_t textureVersion, ::g::Fuse::Android::StaticLayout* layout, ::g::Uno::Recti pixelBounds); }; // } }}} // ::g::Fuse::Android
158f3030f4e51f760a3292b4cb462527f8a28246
ad107e8812705a73bf9fd30174cbb925b2cfabf5
/Kehu/News.h
26832914c031ec5782a16f3d9c8d361b23010512
[]
no_license
gongxijun/Ad-Client
51f71e14d8270d127d8197a0a16ca1b330109719
c86537dcf25f93921994c4707135081cca9b5a62
refs/heads/master
2021-04-26T16:43:39.579377
2016-12-22T05:09:46
2016-12-22T05:09:46
48,827,026
1
3
null
null
null
null
GB18030
C++
false
false
868
h
#pragma once #include "explorer1.h" #ifdef _WIN32_WCE #error "Windows CE 不支持 CDHtmlDialog。" #endif extern CImage Resour; extern struct usr ower; // News 对话框 class News : public CDHtmlDialog { DECLARE_DYNCREATE(News) public: News(CWnd* pParent = NULL); // 标准构造函数 virtual ~News(); //重写 HRESULT OnButtonOK(IHTMLElement *pElement); HRESULT OnButtonCancel(IHTMLElement *pElement); // 对话框数据 //enum { IDD = IDD_DIALOG3, IDH = IDR_HTML_NEWS }; // enum { IDD = IDD_DIALOG3, IDH = 0 }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 virtual BOOL OnInitDialog(); DECLARE_MESSAGE_MAP() DECLARE_DHTML_EVENT_MAP() public: afx_msg void OnBnClickedOk(); afx_msg void OnBnClickedCancel(); afx_msg void GotoUrl(LPCTSTR pszUrl); afx_msg void OnDestroy(); afx_msg void OnClose(); };
1ef55f89eb8f6afbc6aa90d377f33e305737e033
f5deac52f73fffbdcebaadb24fabbb1c33a6a808
/src/stable/queue.cpp
3fb993c3307393581c4afe49347f54bd64dcc562
[ "BSD-3-Clause", "LicenseRef-scancode-other-permissive" ]
permissive
zippy/libbu
d92557f8ece66c70e8ba37768194b2d6aad8bd89
6c79102419f9e79d25751fefc155f746496f4b50
refs/heads/master
2021-01-18T05:53:00.876941
2013-02-17T02:46:00
2013-02-17T02:46:00
8,282,197
3
0
null
null
null
null
UTF-8
C++
false
false
216
cpp
/* * Copyright (C) 2007-2013 Xagasoft, All rights reserved. * * This file is part of the libbu++ library and is released under the * terms of the license contained in the file LICENSE. */ #include "bu/queue.h"
195d4096ed752df9751a2da11de07435167aafa9
927fad9a4b5b170d681eda830ab92e37c6722ee7
/Classes/Game/GameScene1Obj1.h
6cf569919534a5cc4d35630e02a65d54277eb91f
[]
no_license
the-last-language/Last-Language-2014
71af13da9a677af2c66fb8229a94196feb10d704
7c6911f9c53eed6cbd1e4dd1e9f48adaec95746a
refs/heads/master
2021-01-21T05:10:45.805766
2015-04-08T15:58:29
2015-04-08T15:58:29
23,354,061
0
0
null
null
null
null
UTF-8
C++
false
false
653
h
#ifndef __GameScene1Obj1_SCENE_H__ #define __GameScene1Obj1_SCENE_H__ #include "cocos2d.h" class GameScene1Obj1 : public cocos2d::Layer { public: // there's no 'id' in cpp, so we recommend returning the class instance pointer static cocos2d::Scene* createScene(); // Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone virtual bool init(); // a selector callback void menuCloseCallback(cocos2d::Ref* pSender); void initCancel(); // implement the "static create()" method manually CREATE_FUNC(GameScene1Obj1); }; #endif // __MenuScene_SCENE_H__
1c6b435463be46cbf043325fc2ced8bfd7e76d6a
d9e197288fea7783119b8adf81dd34e2619d9fb4
/src/hydro/srcterms/shearing_box.cpp
073f66c22b314cbfe3902c9037b807a30b687d9b
[ "BSD-3-Clause" ]
permissive
ziyanxu/athena-pp_xu
a2204bb216ac2e91e3075c96bdfaaff41b5e81bd
fce21992cc107aa553e83dd76b8d03ae90e990c7
refs/heads/master
2023-03-05T16:06:38.850733
2021-02-10T13:18:13
2021-02-10T13:18:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,678
cpp
//====================================================================================== // Athena++ astrophysical MHD code // Copyright(C) 2014 James M. Stone <[email protected]> and other code contributors // Licensed under the 3-clause BSD License, see LICENSE file for details //====================================================================================== //! \file shearing_box.cpp //! \brief Adds source terms due to local shearing box approximation //====================================================================================== // C headers // C++ headers // Athena++ headers #include "../../athena.hpp" #include "../../athena_arrays.hpp" #include "../../coordinates/coordinates.hpp" #include "../../mesh/mesh.hpp" #include "../hydro.hpp" #include "hydro_srcterms.hpp" //-------------------------------------------------------------------------------------- //! \fn void HydroSourceTerms::ShearingBoxSourceTerms(const Real dt, //! const AthenaArray<Real> *flux, const AthenaArray<Real> &prim, //! AthenaArray<Real> &cons) //! \brief Shearing Box source terms //! //! We add shearing box source term via operator splitting method. The source terms are //! added after the fluxes are computed in each step of the integration (in //! FluxDivergence) to give predictions of the conservative variables for either the //! next step or the final update. void HydroSourceTerms::ShearingBoxSourceTerms(const Real dt, const AthenaArray<Real> *flux, const AthenaArray<Real> &prim, AthenaArray<Real> &cons) { MeshBlock *pmb = pmy_hydro_->pmy_block; // 1) Tidal force: // dM1/dt = 2q\rho\Omega^2 x // dE /dt = 2q\Omega^2 (\rho v_x) x // 2) Coriolis forces: // dM1/dt = 2\Omega(\rho v_y) // dM2/dt = -2\Omega(\rho v_x) if (ShBoxCoord_== 1) { for (int k=pmb->ks; k<=pmb->ke; ++k) { for (int j=pmb->js; j<=pmb->je; ++j) { #pragma omp simd for (int i=pmb->is; i<=pmb->ie; ++i) { Real den = prim(IDN,k,j,i); Real qO2 = qshear_*SQR(Omega_0_); Real mom1 = den*prim(IVX,k,j,i); Real xc = pmb->pcoord->x1v(i); cons(IM1,k,j,i) += 2.0*dt*(Omega_0_*(den*prim(IVY,k,j,i))+qO2*den*xc); cons(IM2,k,j,i) -= 2.0*dt*Omega_0_*mom1; if (NON_BAROTROPIC_EOS) { Real phic = qO2*SQR(xc); Real phil = qO2*SQR(pmb->pcoord->x1f(i)); Real phir = qO2*SQR(pmb->pcoord->x1f(i+1)); cons(IEN,k,j,i) += dt*(flux[X1DIR](IDN,k,j,i)*(phic-phil)+ flux[X1DIR](IDN,k,j,i+1)*(phir-phic)) /pmb->pcoord->dx1f(i); } } } } } else { // ShBoxCoord_== 2 int ks = pmb->ks; for (int j=pmb->js; j<=pmb->je; ++j) { #pragma omp simd for (int i=pmb->is; i<=pmb->ie; ++i) { Real den = prim(IDN,ks,j,i); Real qO2 = qshear_*SQR(Omega_0_); Real mom1 = den*prim(IVX,ks,j,i); Real xc = pmb->pcoord->x1v(i); cons(IM1,ks,j,i) += 2.0*dt*(Omega_0_*(den*prim(IVZ,ks,j,i))+qO2*den*xc); cons(IM3,ks,j,i) -= 2.0*dt*Omega_0_*mom1; if (NON_BAROTROPIC_EOS) { Real phic = qO2*SQR(xc); Real phil = qO2*SQR(pmb->pcoord->x1f(i)); Real phir = qO2*SQR(pmb->pcoord->x1f(i+1)); cons(IEN,ks,j,i) += dt*(flux[X1DIR](IDN,ks,j,i)*(phic-phil)+ flux[X1DIR](IDN,ks,j,i+1)*(phir-phic)) /pmb->pcoord->dx1f(i); } } } } return; }
23954c1c24f15ada36612a853322eb931c591ae0
8174a4304d797cc68210ab115659ba20d7090e76
/aws-cpp-sdk-ecs/source/model/CreateTaskSetRequest.cpp
6a75da2f534eb91bb235046d3992c0b9c784a963
[ "Apache-2.0", "MIT", "JSON" ]
permissive
Lectem/aws-sdk-cpp
0f167407ec05d59486b080f998c611891dce943e
24deb4bc44d05c890712f8cd2e5b24eb379f3ecd
refs/heads/master
2020-12-15T10:41:05.408067
2020-01-17T20:13:58
2020-01-17T20:13:58
235,075,690
0
0
Apache-2.0
2020-01-20T10:29:07
2020-01-20T10:29:06
null
UTF-8
C++
false
false
4,067
cpp
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/ecs/model/CreateTaskSetRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::ECS::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; CreateTaskSetRequest::CreateTaskSetRequest() : m_serviceHasBeenSet(false), m_clusterHasBeenSet(false), m_externalIdHasBeenSet(false), m_taskDefinitionHasBeenSet(false), m_networkConfigurationHasBeenSet(false), m_loadBalancersHasBeenSet(false), m_serviceRegistriesHasBeenSet(false), m_launchType(LaunchType::NOT_SET), m_launchTypeHasBeenSet(false), m_capacityProviderStrategyHasBeenSet(false), m_platformVersionHasBeenSet(false), m_scaleHasBeenSet(false), m_clientTokenHasBeenSet(false) { } Aws::String CreateTaskSetRequest::SerializePayload() const { JsonValue payload; if(m_serviceHasBeenSet) { payload.WithString("service", m_service); } if(m_clusterHasBeenSet) { payload.WithString("cluster", m_cluster); } if(m_externalIdHasBeenSet) { payload.WithString("externalId", m_externalId); } if(m_taskDefinitionHasBeenSet) { payload.WithString("taskDefinition", m_taskDefinition); } if(m_networkConfigurationHasBeenSet) { payload.WithObject("networkConfiguration", m_networkConfiguration.Jsonize()); } if(m_loadBalancersHasBeenSet) { Array<JsonValue> loadBalancersJsonList(m_loadBalancers.size()); for(unsigned loadBalancersIndex = 0; loadBalancersIndex < loadBalancersJsonList.GetLength(); ++loadBalancersIndex) { loadBalancersJsonList[loadBalancersIndex].AsObject(m_loadBalancers[loadBalancersIndex].Jsonize()); } payload.WithArray("loadBalancers", std::move(loadBalancersJsonList)); } if(m_serviceRegistriesHasBeenSet) { Array<JsonValue> serviceRegistriesJsonList(m_serviceRegistries.size()); for(unsigned serviceRegistriesIndex = 0; serviceRegistriesIndex < serviceRegistriesJsonList.GetLength(); ++serviceRegistriesIndex) { serviceRegistriesJsonList[serviceRegistriesIndex].AsObject(m_serviceRegistries[serviceRegistriesIndex].Jsonize()); } payload.WithArray("serviceRegistries", std::move(serviceRegistriesJsonList)); } if(m_launchTypeHasBeenSet) { payload.WithString("launchType", LaunchTypeMapper::GetNameForLaunchType(m_launchType)); } if(m_capacityProviderStrategyHasBeenSet) { Array<JsonValue> capacityProviderStrategyJsonList(m_capacityProviderStrategy.size()); for(unsigned capacityProviderStrategyIndex = 0; capacityProviderStrategyIndex < capacityProviderStrategyJsonList.GetLength(); ++capacityProviderStrategyIndex) { capacityProviderStrategyJsonList[capacityProviderStrategyIndex].AsObject(m_capacityProviderStrategy[capacityProviderStrategyIndex].Jsonize()); } payload.WithArray("capacityProviderStrategy", std::move(capacityProviderStrategyJsonList)); } if(m_platformVersionHasBeenSet) { payload.WithString("platformVersion", m_platformVersion); } if(m_scaleHasBeenSet) { payload.WithObject("scale", m_scale.Jsonize()); } if(m_clientTokenHasBeenSet) { payload.WithString("clientToken", m_clientToken); } return payload.View().WriteReadable(); } Aws::Http::HeaderValueCollection CreateTaskSetRequest::GetRequestSpecificHeaders() const { Aws::Http::HeaderValueCollection headers; headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "AmazonEC2ContainerServiceV20141113.CreateTaskSet")); return headers; }
64c67f62a3830198cd4c84fe84ba26cd8ce3dd6d
49d669ee077b5701563edf35de26f60cfa6e090c
/Android/app/src/main/cpp/native-lib.cpp
193ebff7c1606a32827a44a1e921ff0eec9926e7
[ "MIT" ]
permissive
sevenfortune/ZLMediaKit
767c0de7c67414ee04ee765db82bde6a5620d3e3
54b2cd008947e108e737432e7319a3acac309991
refs/heads/master
2020-08-08T12:33:49.953801
2019-10-08T09:22:27
2019-10-08T09:22:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,989
cpp
#include <jni.h> #include <string> #include "Util/logger.h" #include "Thread/semaphore.h" #include "Common/config.h" #include "Player/MediaPlayer.h" #include "Extension/Frame.h" using namespace std; using namespace toolkit; using namespace mediakit; #define JNI_API(retType,funName,...) extern "C" JNIEXPORT retType Java_com_zlmediakit_jni_ZLMediaKit_##funName(JNIEnv* env, jclass cls,##__VA_ARGS__) #define MediaPlayerCallBackSign "com/zlmediakit/jni/ZLMediaKit$MediaPlayerCallBack" #define MediaFrameSign "com/zlmediakit/jni/ZLMediaKit$MediaFrame" string stringFromJstring(JNIEnv *env,jstring jstr){ if(!env || !jstr){ WarnL << "invalid args"; return ""; } const char *field_char = env->GetStringUTFChars(jstr, 0); string ret(field_char,env->GetStringUTFLength(jstr)); env->ReleaseStringUTFChars(jstr, field_char); return ret; } string stringFromJbytes(JNIEnv *env,jbyteArray jbytes){ if(!env || !jbytes){ WarnL << "invalid args"; return ""; } jbyte *bytes = env->GetByteArrayElements(jbytes, 0); string ret((char *)bytes,env->GetArrayLength(jbytes)); env->ReleaseByteArrayElements(jbytes,bytes,0); return ret; } string stringFieldFromJava(JNIEnv *env, jobject jdata,jfieldID jid){ if(!env || !jdata || !jid){ WarnL << "invalid args"; return ""; } jstring field_str = (jstring)env->GetObjectField(jdata,jid); auto ret = stringFromJstring(env,field_str); env->DeleteLocalRef(field_str); return ret; } string bytesFieldFromJava(JNIEnv *env, jobject jdata,jfieldID jid){ if(!env || !jdata || !jid){ WarnL << "invalid args"; return ""; } jbyteArray jbufArray = (jbyteArray)env->GetObjectField(jdata, jid); string ret = stringFromJbytes(env,jbufArray); env->DeleteLocalRef(jbufArray); return ret; } jstring jstringFromString(JNIEnv* env, const char* pat) { return (jstring)env->NewStringUTF(pat); } jbyteArray jbyteArrayFromString(JNIEnv* env, const char* pat,int len = 0){ if(len <= 0){ len = strlen(pat); } jbyteArray jarray = env->NewByteArray(len); env->SetByteArrayRegion(jarray, 0, len, (jbyte *)(pat)); return jarray; } jobject makeJavaFrame(JNIEnv* env,const Frame::Ptr &frame){ static jclass jclass_obj = (jclass)env->NewGlobalRef(env->FindClass(MediaFrameSign)); static jmethodID jmethodID_init = env->GetMethodID(jclass_obj, "<init>", "()V"); static jfieldID jfieldID_dts = env->GetFieldID(jclass_obj,"dts","I"); static jfieldID jfieldID_pts = env->GetFieldID(jclass_obj,"pts","I"); static jfieldID jfieldID_prefixSize = env->GetFieldID(jclass_obj,"prefixSize","I"); static jfieldID jfieldID_keyFrame = env->GetFieldID(jclass_obj,"keyFrame","Z"); static jfieldID jfieldID_data = env->GetFieldID(jclass_obj,"data","[B"); static jfieldID jfieldID_trackType = env->GetFieldID(jclass_obj,"trackType","I"); static jfieldID jfieldID_codecId = env->GetFieldID(jclass_obj,"codecId","I"); if(!frame){ return nullptr; } jobject ret = env->NewObject(jclass_obj, jmethodID_init); env->SetIntField(ret,jfieldID_dts,frame->dts()); env->SetIntField(ret,jfieldID_pts,frame->pts()); env->SetIntField(ret,jfieldID_prefixSize,frame->prefixSize()); env->SetBooleanField(ret,jfieldID_keyFrame,frame->keyFrame()); env->SetObjectField(ret,jfieldID_data,jbyteArrayFromString(env,frame->data(),frame->size())); env->SetIntField(ret,jfieldID_trackType,frame->getTrackType()); env->SetIntField(ret,jfieldID_codecId,frame->getCodecId()); return ret; } static JavaVM *s_jvm = nullptr; template <typename FUN> void doInJavaThread(FUN &&fun){ JNIEnv *env; int status = s_jvm->GetEnv((void **) &env, JNI_VERSION_1_6); if (status != JNI_OK) { if (s_jvm->AttachCurrentThread(&env, NULL) != JNI_OK) { return; } } fun(env); if (status != JNI_OK) { //Detach线程 s_jvm->DetachCurrentThread(); } } #define emitEvent(delegate,method,argFmt,...) \ { \ doInJavaThread([&](JNIEnv* env) { \ static jclass cls = env->GetObjectClass(delegate); \ static jmethodID jmid = env->GetMethodID(cls, method, argFmt); \ jobject localRef = env->NewLocalRef(delegate); \ if(localRef){ \ env->CallVoidMethod(localRef, jmid, ##__VA_ARGS__); \ }else{ \ WarnL << "弱引用已经释放:" << method << " " << argFmt; \ }\ }); \ } /* * 加载动态库 */ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved) { //设置日志 s_jvm = vm; Logger::Instance().add(std::make_shared<ConsoleChannel>()); Logger::Instance().setWriter(std::make_shared<AsyncLogWriter>()); InfoL; return JNI_VERSION_1_6; } static pthread_t s_tread_id = 0; /* * 卸载动态库 */ JNIEXPORT void JNICALL JNI_OnUnload(JavaVM* vm, void* reserved){ InfoL; if(s_tread_id){ pthread_kill(s_tread_id,SIGINT); } } extern int start_main(int argc,char *argv[]); JNI_API(jboolean,startDemo,jstring ini_dir){ string sd_path = stringFromJstring(env,ini_dir); string ini_file = sd_path + "/zlmediakit.ini"; //可以在sd卡根目录下放置ssl证书以便支持https服务器,证书支持p12或pem格式 string pem_file = sd_path + "/zlmediakit.pem"; DebugL << "sd_path:" << sd_path; DebugL << "ini file:" << ini_file; static thread s_th([sd_path,ini_file,pem_file](){ s_tread_id = pthread_self(); try { //http根目录修改默认路径 mINI::Instance()[Http::kRootPath] = mINI::Instance()[Hls::kFilePath] = sd_path + "/httpRoot"; //mp4录制点播根目录修改默认路径 mINI::Instance()[Record::kFilePath] = mINI::Instance()[Hls::kFilePath] = sd_path + "/httpRoot"; //hls根目录修改默认路径 mINI::Instance()[Hls::kFilePath] = mINI::Instance()[Hls::kFilePath] = sd_path + "/httpRoot"; //替换默认端口号(在配置文件未生成时有效) mINI::Instance()["http.port"] = 8080; mINI::Instance()["http.sslport"] = 8443; mINI::Instance()["rtsp.port"] = 8554; mINI::Instance()["rtsp.sslport"] = 8332; for(auto &pr : mINI::Instance()){ //替换hook默认地址 replace(pr.second,"https://127.0.0.1/","http://127.0.0.1:8080/"); } //默认打开hook mINI::Instance()["hook.enable"] = 0; //默认打开http api调试 mINI::Instance()["api.apiDebug"] = 1; int argc = 5; const char *argv[] = {"","-c",ini_file.data(),"-s",pem_file.data()}; start_main(argc,(char **)argv); }catch (std::exception &ex){ WarnL << ex.what(); } }); static onceToken s_token([]{ s_th.detach(); }); return true; }; JNI_API(jlong,createMediaPlayer,jstring url,jobject callback){ static auto loadFrameClass = makeJavaFrame(env,nullptr); MediaPlayer::Ptr *ret = new MediaPlayer::Ptr(new MediaPlayer()); MediaPlayer::Ptr &player = *ret; weak_ptr<MediaPlayer> weakPlayer = player; jobject globalWeakRef = env->NewWeakGlobalRef(callback); player->setOnPlayResult([weakPlayer,globalWeakRef](const SockException &ex) { auto strongPlayer = weakPlayer.lock(); if (!strongPlayer) { return; } emitEvent((jobject)globalWeakRef,"onPlayResult","(ILjava/lang/String;)V",(jint)ex.getErrCode(),env->NewStringUTF(ex.what())); if(ex){ return; } auto viedoTrack = strongPlayer->getTrack(TrackVideo); if (viedoTrack) { viedoTrack->addDelegate(std::make_shared<FrameWriterInterfaceHelper>([globalWeakRef](const Frame::Ptr &frame) { emitEvent((jobject)globalWeakRef,"onData","(L" MediaFrameSign ";)V",makeJavaFrame(env,frame)); })); } auto audioTrack = strongPlayer->getTrack(TrackAudio); if (audioTrack) { audioTrack->addDelegate(std::make_shared<FrameWriterInterfaceHelper>([globalWeakRef](const Frame::Ptr &frame) { emitEvent((jobject)globalWeakRef,"onData","(L" MediaFrameSign ";)V",makeJavaFrame(env,frame)); })); } }); player->setOnShutdown([globalWeakRef,weakPlayer](const SockException &ex) { auto strongPlayer = weakPlayer.lock(); if (!strongPlayer) { return; } emitEvent((jobject)globalWeakRef,"onShutdown","(ILjava/lang/String;)V",(jint)ex.getErrCode(),env->NewStringUTF(ex.what())); }); (*player)[Client::kRtpType] = Rtsp::RTP_TCP; player->play(stringFromJstring(env,url)); return (jlong)(ret); } JNI_API(void,releaseMediaPlayer,jlong ptr){ MediaPlayer::Ptr *player = (MediaPlayer::Ptr *)ptr; delete player; }
1b7c5570cb4d07358f7e055ee1c24acb65fc0c76
5dbefd69106e7573148e6f9926e4168e387c31c5
/SMB-172.2/Tetris/Source.cpp
d1d2e559449c3c7e954dd48f80bee7846a8e7b91
[]
no_license
Dakosia/Cpp
0a74cbea2b4b5d22fc8c1bc768fbd52b6ee4f39c
85435da7f35b707c66b5c107f6a95f8f153d513c
refs/heads/master
2020-03-09T02:00:31.854534
2018-06-20T17:49:04
2018-06-20T17:49:04
128,530,023
1
0
null
null
null
null
UTF-8
C++
false
false
1,932
cpp
#include <iostream> #include <Windows.h> #include <conio.h> #include <stdlib.h> using namespace std; struct Point { short x, y; }; struct Figure { Point body[4]; byte size; int type; }; struct Ground { bool filled[10][10]; int groundHeight; int size; }; struct Wall { Point gates[20]; short size; }; void draw(Point & p, char sign) { COORD position = { p.x, p.y }; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), position); cout << sign; } void drawEverything(Figure & f, Wall & w, Ground & g) { for (byte i = 0; i < f.size; ++i) { draw(f.body[i], '#'); } for (short i = 0; i < w.size; ++i) { draw(w.gates[i], '|'); } } void init(Figure & f, Wall & w, Ground & g) { f.body[0].x = 2; f.body[0].y = 1; f.body[1].x = 2; f.body[1].y = 2; f.body[2].x = 2; f.body[2].y = 3; f.body[3].x = 2; f.body[3].y = 4; f.size = 4; f.type = 1; g.body = new Point[20]; g.size = 0; w.size = 20; for (int i = 0; i < 10; ++i) { w.gates[i].x = 1; w.gates[i].y = i; w.gates[i + 10].x = 10; w.gates[i + 10].y = i; } } void move(Figure & f, int dx) { for (byte i = 0; i < f.size; ++i) { f.body[i].x += dx; ++f.body[i].y; } } void rotate(Figure & f) { switch (f.type) { case 1: f.body[0].x--; f.body[0].y++; f.body[2].x++; f.body[2].y--; f.body[3].x += 2; f.body[3].y -= 2; break; default: break; } } void landing() { } void game() { Figure figure; Wall wall; Ground ground; bool isActive = true; init(figure, wall, ground); while (isActive) { system("cls"); drawEverything(figure, wall, ground); int dx = 0; if (_kbhit()) { dx = 0; char action = _getch(); switch (action) { case 'a': dx = -1; break; case 'd': dx = 1; break; case 'w': rotate(figure); break; case 's': break; default: break; } } move(figure, dx); Sleep(1000); } delete[] ground.body; } int main() { game(); return 0; }
943e8c302a43a8030047d7f7c3e2006477bcda7a
f51b3b7f6a5110a704d5bd4e7920fc675a75f2bd
/src/lang/builtins/transforms/tile.cpp
e27d08d28f82a9ee5393867bf9f56f8e96f46bd0
[ "MIT" ]
permissive
v-dobrev/occa
6857905566e39334d47ff2efa6a8e5be9a085cde
58e47f5ccf0d87f5b91e6851b2d74a9456c46b2c
refs/heads/master
2020-03-26T07:50:51.784589
2018-08-26T19:10:56
2018-08-26T19:46:22
144,674,039
0
0
MIT
2018-08-14T05:45:39
2018-08-14T05:45:38
null
UTF-8
C++
false
false
12,149
cpp
/* The MIT License (MIT) * * Copyright (c) 2014-2018 David Medina and Tim Warburton * * 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 */ #include <occa/lang/exprNode.hpp> #include <occa/lang/mode/oklForStatement.hpp> #include <occa/lang/variable.hpp> #include <occa/lang/builtins/types.hpp> #include <occa/lang/builtins/transforms/tile.hpp> #include <occa/lang/builtins/transforms/replacer.hpp> namespace occa { namespace lang { namespace transforms { tile::tile() { validStatementTypes = statementType::for_; } statement_t* tile::transformStatement(statement_t &smnt) { forStatement &forSmnt = (forStatement&) smnt; attributeTokenMap::iterator it = forSmnt.attributes.find("tile"); if (it == forSmnt.attributes.end()) { return &smnt; } attributeToken_t &attr = it->second; exprNode &tileSize = *(attr.args[0].expr); okl::oklForStatement oklForSmnt(forSmnt, "@tile"); if (!oklForSmnt.isValid()) { return NULL; } // Create the block and inner-block for-loops forStatement &blockForSmnt = *(new forStatement(forSmnt.up, forSmnt.source)); forStatement &innerForSmnt = *(new forStatement(&blockForSmnt, forSmnt.source)); blockForSmnt.add(innerForSmnt); // Rename the block interator variable_t &iter = *(oklForSmnt.iterator); variable_t &blockIter = iter.clone(); blockIter.name() = "_occa_tiled_" + iter.name(); blockForSmnt.scope.add(blockIter); setupNewForStatements(attr, oklForSmnt, blockIter, blockForSmnt, innerForSmnt); setupBlockForStatement(oklForSmnt, tileSize, blockIter, blockForSmnt, innerForSmnt); setupInnerForStatement(oklForSmnt, tileSize, blockIter, blockForSmnt, innerForSmnt); setupCheckStatement(attr, oklForSmnt, blockIter, blockForSmnt, innerForSmnt); return &blockForSmnt; } void tile::setupNewForStatements(attributeToken_t &attr, okl::oklForStatement &oklForSmnt, variable_t &blockIter, forStatement &blockForSmnt, forStatement &innerForSmnt) { // Add @tile attributes const int attrArgCount = (int) attr.args.size(); if (attrArgCount > 1) { attributeTokenMap &blockAttrs = attr.args[1].attributes; blockForSmnt.attributes.insert(blockAttrs.begin(), blockAttrs.end()); if (attrArgCount > 2) { attributeTokenMap &innerAttrs = attr.args[2].attributes; innerForSmnt.attributes.insert(innerAttrs.begin(), innerAttrs.end()); } } // Remove @tile to prevent recursive updates innerForSmnt.attributes.erase("tile"); forStatement &forSmnt = oklForSmnt.forSmnt; innerForSmnt.swap(forSmnt); // Setup initial statements blockForSmnt.setLoopStatements(forSmnt.init, forSmnt.check, NULL); innerForSmnt.setLoopStatements(NULL, NULL, forSmnt.update); forSmnt.setLoopStatements(NULL, NULL, NULL); // Replace instances of x with _occa_tiled_x replaceVariables(*blockForSmnt.init, *oklForSmnt.iterator, blockIter); replaceVariables(*blockForSmnt.check, *oklForSmnt.iterator, blockIter); } void tile::setupBlockForStatement(okl::oklForStatement &oklForSmnt, exprNode &tileSize, variable_t &blockIter, forStatement &blockForSmnt, forStatement &innerForSmnt) { /* for (x = START; x < END; x += INC) -> for (xTile = START; xTile < END; NULL ) -> for (xTile = START; xTile < END; xTile += (TILE * (INC))) */ exprNode &updateExpr = *(((expressionStatement*) innerForSmnt.update)->expr); opType_t opType = ((exprOpNode&) updateExpr).opType(); token_t *updateToken =updateExpr.startNode()->token; exprNode *updateSizeExpr = &tileSize; const binaryOperator_t *updateOp = &op::addEq; if (opType & (operatorType::leftDecrement | operatorType::rightDecrement)) { updateOp = &op::subEq; } else if (opType & (operatorType::addEq | operatorType::subEq)) { // INC exprNode *updateSize = ((binaryOpNode&) updateExpr).rightValue; // (INC) parenthesesNode updateInParen(updateToken, *updateSize); // TILE * (INC) binaryOpNode mult(updateToken, op::mult, tileSize, updateInParen); // (TILE * (INC)) updateSizeExpr = new parenthesesNode(updateToken, mult); if (opType & operatorType::subEq) { updateOp = &op::subEq; } } // VAR += (TILE * (INC)) variableNode varNode(updateToken, blockIter); exprNode *newUpdateExpr = new binaryOpNode(updateToken, *updateOp, varNode, *updateSizeExpr); if (updateSizeExpr != &tileSize) { // Delete (TILE * (INC)) if it was created delete updateSizeExpr; } blockForSmnt.update = new expressionStatement(&blockForSmnt, *newUpdateExpr, false); } void tile::setupInnerForStatement(okl::oklForStatement &oklForSmnt, exprNode &tileSize, variable_t &blockIter, forStatement &blockForSmnt, forStatement &innerForSmnt) { /* for (x = START; x < END; x += INC) -> for (NULL; NULL; x += INC) -> for (x = xTile; x < (xTile + TILE); x += INC) */ // Init variables variableDeclaration &decl = (((declarationStatement*) blockForSmnt.init) ->declarations[0]); token_t *initToken = decl.variable->source; variableNode iterNode(initToken, *oklForSmnt.iterator); variableNode blockIterNode(initToken, blockIter); // Check variables binaryOpNode &checkExpr = ((binaryOpNode&) *(((expressionStatement*) blockForSmnt.check)->expr)); token_t *checkToken = checkExpr.startNode()->token; // Update variables const operator_t &updateOp = ( ((binaryOpNode&) *(((expressionStatement*) blockForSmnt.update)->expr) ).op); const bool addUpdate = (updateOp.opType & operatorType::addEq); // Create init innerForSmnt.init = new declarationStatement(&innerForSmnt, initToken); variableDeclarationVector &decls = ( ((declarationStatement*) innerForSmnt.init) ->declarations ); decls.push_back( variableDeclaration(*oklForSmnt.iterator, *(blockIterNode.clone())) ); // Create check binaryOpNode checkValueNode(checkToken, addUpdate ? op::add : op::sub, blockIterNode, tileSize); parenthesesNode checkInParen(checkToken, checkValueNode); const bool varInLeft = oklForSmnt.checkValueOnRight; binaryOpNode &newCheckNode = *( new binaryOpNode( checkToken, (const binaryOperator_t&) checkExpr.op, varInLeft ? (exprNode&) iterNode : (exprNode&) checkInParen, varInLeft ? (exprNode&) checkInParen : (exprNode&) iterNode )); innerForSmnt.check = new expressionStatement(&innerForSmnt, newCheckNode); } void tile::setupCheckStatement(attributeToken_t &attr, okl::oklForStatement &oklForSmnt, variable_t &blockIter, forStatement &blockForSmnt, forStatement &innerForSmnt) { attributeArgMap::iterator it = attr.kwargs.find("check"); bool check = true; if (it != attr.kwargs.end()) { check = (bool) it->second.expr->evaluate(); } if (!check) { return; } // Check variables binaryOpNode &checkExpr = ((binaryOpNode&) *(((expressionStatement*) blockForSmnt.check)->expr)); token_t *checkToken = checkExpr.startNode()->token; const bool varInLeft = oklForSmnt.checkValueOnRight; // Make ifStatement ifStatement &ifSmnt = *(new ifStatement(&innerForSmnt, checkToken)); innerForSmnt.swap(ifSmnt); innerForSmnt.scope.swap(ifSmnt.scope); innerForSmnt.add(ifSmnt); // Get global check token_t *iterToken = (varInLeft ? checkExpr.leftValue->token : checkExpr.rightValue->token); variableNode iterNode(iterToken, *oklForSmnt.iterator); binaryOpNode &newCheckNode = *( new binaryOpNode( checkExpr.token, (const binaryOperator_t&) checkExpr.op, varInLeft ? (exprNode&) iterNode : *(checkExpr.leftValue), varInLeft ? (exprNode&) *(checkExpr.rightValue) : (exprNode&) iterNode )); ifSmnt.setCondition(new expressionStatement(&ifSmnt, newCheckNode, false)); } bool applyTileTransforms(statement_t &smnt) { tile tileTransform; return tileTransform.apply(smnt); } } } }
53a23e4a780c74f9366fed6734a238e495f68749
4c1d7aee068d08bcfc1267d4501d32609e902301
/arc086_a.cc
45b205e1506283e7ee235856ff95e9c70f33ec11
[ "MIT" ]
permissive
mnrn/xxx-coder
9e7ba7cb9328203135134c889783e69df7f3b597
2db331c57f15fbd36fbb61a5526afc07af010727
refs/heads/master
2021-09-26T21:42:07.317083
2021-09-23T09:43:05
2021-09-23T09:43:05
213,385,527
0
0
null
null
null
null
UTF-8
C++
false
false
1,081
cc
// #define _GLIBCXX_DEBUG #include <bits/stdc++.h> #define FOR(i, a, b) for (int i = (a); i < int(b); ++i) #define RFOR(i, a, b) for (int i = (b)-1; i >= int(a); --i) #define REP(i, n) FOR(i, 0, n) #define REP1(i, n) FOR(i, 1, int(n) + 1) #define RREP(i, n) RFOR(i, 0, n) #define RREP1(i, n) RFOR(i, 1, int(n) + 1) #define ALL(c) begin(c), end(c) int _ = ( #ifndef LOCAL std::cin.tie(nullptr), std::ios::sync_with_stdio(false), #endif std::cout.precision(10), std::cout.setf(std::ios::fixed)); using ll = long long; using ull = unsigned long long; using ld = long double; template <typename T> using vec = std::vector<T>; using namespace std; int main() { ll K, N; cin >> N >> K; vec<ll> A(N); REP(i, N) cin >> A[i]; vec<ll> C(200'000, 0); REP(i, N) C[A[i]]++; C.erase(remove_if(ALL(C), [](ll c) { return c == 0; }), end(C)); ll k = C.size(); if (k <= K) { cout << 0 << endl; return 0; } sort(ALL(C)); ll res = 0; for (const auto e : C) { res += e; if (--k <= K) { break; } } cout << res << endl; return 0; }
43abfd7e26c1ae865400d0924ee2e50b743e5b03
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/squid/gumtree/squid_patch_hunk_226.cpp
c62049a1d12bf5b4bc0ecfe4887b63ddbf106f06
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,531
cpp
/**** PUBLIC FUNCTIONS ****/ /* * start a TCP connection to the peer host on port 113 */ void -Ident::Start(IpAddress &me, IpAddress &my_peer, IDCB * callback, void *data) +Ident::Start(const Comm::ConnectionPointer &conn, IDCB * callback, void *data) { IdentStateData *state; - int fd; char key1[IDENT_KEY_SZ]; char key2[IDENT_KEY_SZ]; char key[IDENT_KEY_SZ]; - char ntoabuf[MAX_IPSTRLEN]; - me.ToURL(key1, IDENT_KEY_SZ); - my_peer.ToURL(key2, IDENT_KEY_SZ); + conn->local.ToURL(key1, IDENT_KEY_SZ); + conn->remote.ToURL(key2, IDENT_KEY_SZ); snprintf(key, IDENT_KEY_SZ, "%s,%s", key1, key2); if (!ident_hash) { Init(); } if ((state = (IdentStateData *)hash_lookup(ident_hash, key)) != NULL) { ClientAdd(state, callback, data); return; } - IpAddress addr = me; - addr.SetPort(0); // NP: use random port for secure outbound to IDENT_PORT - - fd = comm_open_listener(SOCK_STREAM, - IPPROTO_TCP, - addr, - COMM_NONBLOCKING, - "ident"); - - if (fd == COMM_ERROR) { - /* Failed to get a local socket */ - callback(NULL, data); - return; - } - CBDATA_INIT_TYPE(IdentStateData); state = cbdataAlloc(IdentStateData); state->hash.key = xstrdup(key); - state->fd = fd; - state->me = me; - state->my_peer = my_peer; + + // copy the conn details. We dont want the original FD to be re-used by IDENT. + state->conn = conn->copyDetails(); + // NP: use random port for secure outbound to IDENT_PORT + state->conn->local.SetPort(0); + state->conn->remote.SetPort(IDENT_PORT); + + // build our query from the original connection details + state->queryMsg.init(); + state->queryMsg.Printf("%d, %d\r\n", conn->remote.GetPort(), conn->local.GetPort()); + ClientAdd(state, callback, data); hash_join(ident_hash, &state->hash); - comm_add_close_handler(fd, Ident::Close, state); - commSetTimeout(fd, Ident::TheConfig.timeout, Ident::Timeout, state); - state->my_peer.NtoA(ntoabuf,MAX_IPSTRLEN); - commConnectStart(fd, ntoabuf, IDENT_PORT, Ident::ConnectDone, state); + + AsyncCall::Pointer call = commCbCall(30,3, "Ident::ConnectDone", CommConnectCbPtrFun(Ident::ConnectDone, state)); + AsyncJob::Start(new Comm::ConnOpener(state->conn, call, Ident::TheConfig.timeout)); } void Ident::Init(void) { if (ident_hash) {
4d3606d3b0a9c4edd7e3fb5e8f40035a1c8efae8
6a9cd5f5202eaa17c7e5704561d652cdefcf4650
/week4/box2.cpp
e08ae61ac5142fd6238c5acddb42c73776f341c7
[]
no_license
ppipee/ProblemSolving
eb8e9a5e0cbdb5a9731f6d3dc90bf343fe3b041d
edb1a939608b954e0a32a29d3a061abe049d4f40
refs/heads/master
2020-05-27T02:29:49.125784
2019-05-24T18:47:31
2019-05-24T18:47:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,720
cpp
#include <iostream> #include <string> using namespace std; bool end_path = false; bool find_out = false; // bool find_start = false; int r, c; void printMap(char **map) { for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) cout << map[i][j]; cout << endl; } cout << endl; } int move(char **map, int UL0, int UL1, int UR0, int UR1, int DL0, int DL1, int DR0, int DR1) { //UR,UL,DR,DL // cout << "from: " << UL0 << UL1 << " " << UR0 << UR1 << endl; // cout << " " << DL0 << DL1 << " " << DR0 << DR1 << endl; printMap(map); //check end if (DL0 + 1 == r && DR0 + 1 == r) { find_out = true; // cout << "find" << endl; return 0; } if (find_out) return 0; // down if (DL0 + 1 < r) { if (map[DL0 + 1][DL1] == '.' && map[DR0 + 1][DR1] == '.') // || map[DR0 + 1][DL1] == 'X')) || (map[DL0 + 1][DL1] == '.' || (map[DL0 + 1][DL1] == 'X') && (map[DR0 + 1][DL1] == '.'))) { // cout << " down\n"; int tmp_UL0 = UL0, tmp_UL1 = UL1; int tmp_UR0 = UR0, tmp_UR1 = UR1; int tmp_DL0 = DL0, tmp_DL1 = DL1; int tmp_DR0 = DR0, tmp_DR1 = DR1; tmp_UL0 += 1, tmp_UR0 += 1; tmp_DL0 += 1, tmp_DR0 += 1; map[tmp_DL0][tmp_DL1] = 'X', map[tmp_DR0][tmp_DR1] = 'X'; move(map, tmp_UL0, tmp_UL1, tmp_UR0, tmp_UR1, tmp_DL0, tmp_DL1, tmp_DR0, tmp_DR1); } } // left if (UL1 - 1 >= 0) { if (map[UL0][UL1 - 1] == '.' && map[DL0][DL1 - 1] == '.') { // cout << " left\n"; int tmp_UL0 = UL0, tmp_UL1 = UL1; int tmp_UR0 = UR0, tmp_UR1 = UR1; int tmp_DL0 = DL0, tmp_DL1 = DL1; int tmp_DR0 = DR0, tmp_DR1 = DR1; tmp_UL1 -= 1, tmp_UR1 -= 1; tmp_DL1 -= 1, tmp_DR1 -= 1; map[tmp_UL0][tmp_UL1] = 'X', map[tmp_DL0][tmp_DL1] = 'X'; move(map, tmp_UL0, tmp_UL1, tmp_UR0, tmp_UR1, tmp_DL0, tmp_DL1, tmp_DR0, tmp_DR1); } } // right if (UR1 + 1 < c) { if (map[UR0][UR1 + 1] == '.' && map[DR0][DR1 + 1] == '.') { // cout << " right\n"; int tmp_UL0 = UL0, tmp_UL1 = UL1; int tmp_UR0 = UR0, tmp_UR1 = UR1; int tmp_DL0 = DL0, tmp_DL1 = DL1; int tmp_DR0 = DR0, tmp_DR1 = DR1; tmp_UL1 += 1, tmp_UR1 += 1; tmp_DL1 += 1, tmp_DR1 += 1; map[tmp_UR0][tmp_UR1] = 'X', map[tmp_DR0][tmp_DR1] = 'X'; move(map, tmp_UL0, tmp_UL1, tmp_UR0, tmp_UR1, tmp_DL0, tmp_DL1, tmp_DR0, tmp_DR1); } } // up if (UL0 - 1 >= 0) { if (map[UL0 - 1][UL1] == '.' && map[UR0 - 1][UR1] == '.') { // cout << " up\n"; int tmp_UL0 = UL0, tmp_UL1 = UL1; int tmp_UR0 = UR0, tmp_UR1 = UR1; int tmp_DL0 = DL0, tmp_DL1 = DL1; int tmp_DR0 = DR0, tmp_DR1 = DR1; tmp_UL0 -= 1, tmp_UR0 -= 1; tmp_DL0 -= 1, tmp_DR0 -= 1; map[tmp_UL0][tmp_UL1] = 'X', map[tmp_UR0][tmp_UR1] = 'X'; move(map, tmp_UL0, tmp_UL1, tmp_UR0, tmp_UR1, tmp_DL0, tmp_DL1, tmp_DR0, tmp_DR1); } } // cout << "endway\n"; return 0; } void start(char **map) { bool find_start = true; while (find_start) { for (int i = 0; i < c - 1; i++) { if (map[0][i] == '.' && map[0][i + 1] == '.' && map[1][i] == '.' && map[1][i + 1] == '.') { int UL[2] = {0, 0}, UR[2] = {0, 1}; int DL[2] = {1, 0}, DR[2] = {1, 1}; find_start = true; UL[1] += i, UR[1] += i; DL[1] += i, DR[1] += i; map[0][i] = 'X', map[0][i + 1] = 'X'; map[1][i] = 'X', map[1][i + 1] = 'X'; int UL0 = UL[0], UL1 = UL[1]; int UR0 = UR[0], UR1 = UR[1]; int DL0 = DL[0], DL1 = DL[1]; int DR0 = DR[0], DR1 = DR[1]; // cout << "start: " << UL0 << UL1 << " " << UR0 << UR1 << endl; // cout << " " << DL0 << DL1 << " " << DR0 << DR1 << endl; move(map, UL0, UL1, UR0, UR1, DL0, DL1, DR0, DR1); } } find_start = false; } } int main() { cin >> r >> c; char *map[r]; //create map for (int i = 0; i < r; i++) map[i] = new char[10]; for (int i = 0; i < r; i++) cin >> map[i]; //start //00 01 10 11 //checkstart start(map); // printMap(map); if (find_out) cout << "yes\n"; else cout << "no\n"; }
[ "kittapon.ku.ac.th" ]
kittapon.ku.ac.th
c91917191a0b92de284c3d2b7114944fb2e28560
5b8cb5332a9768161d2208ece834dba57431c63c
/SDL Game 2 - Master - Handout/ModuleTextures.cpp
1a216ced77c34a0f6500ec6f1827e556d45a7282
[]
no_license
lowysole/master_exercises
c88befb21be4265970d254ee517be83d18d13720
5eb8dbc78b56b944530ad747bad1fbec4e3a346d
refs/heads/master
2023-01-20T15:03:24.417870
2020-12-02T16:41:06
2020-12-02T16:41:06
306,142,733
0
0
null
null
null
null
UTF-8
C++
false
false
1,898
cpp
#include "Globals.h" #include "Application.h" #include "ModuleRender.h" #include "ModuleTextures.h" #include "SDL/include/SDL.h" #include "SDL_image/include/SDL_image.h" #pragma comment( lib, "SDL_image/libx86/SDL2_image.lib" ) using namespace std; ModuleTextures::ModuleTextures() { } // Destructor ModuleTextures::~ModuleTextures() { IMG_Quit(); } // Called before render is available bool ModuleTextures::Init() { LOG("Init Image library"); bool ret = true; // load support for the PNG image format int flags = IMG_INIT_PNG; int init = IMG_Init(flags); if((init & flags) != flags) { LOG("Could not initialize Image lib. IMG_Init: %s", IMG_GetError()); ret = false; } return ret; } // Called before quitting bool ModuleTextures::CleanUp() { LOG("Freeing textures and Image library"); for(list<SDL_Texture*>::iterator it = textures.begin(); it != textures.end(); ++it) SDL_DestroyTexture(*it); textures.clear(); return true; } // Load new texture from file path SDL_Texture* const ModuleTextures::Load(const char* path) { SDL_Texture* texture = nullptr; SDL_Surface* surface = IMG_Load(path); if(surface == nullptr) { LOG("Could not load surface with path: %s. IMG_Load: %s", path, IMG_GetError()); } else { texture = SDL_CreateTextureFromSurface(App->renderer->renderer, surface); if(texture == nullptr) { LOG("Unable to create texture from surface! SDL Error: %s\n", SDL_GetError()); } else { textures.push_back(texture); } SDL_FreeSurface(surface); } return texture; } // Free texture from memory void ModuleTextures::Unload(SDL_Texture* texture) { for(list<SDL_Texture*>::iterator it = textures.begin(); it != textures.end(); ++it) { if(*it == texture) { SDL_DestroyTexture(*it); textures.erase(it); break; } } }
0aa1d3951899cbb155a4af6b93fa57cdb8f6c65d
670af94f93e7c7ef680dcc63b770a9bb7bf5071b
/libs/misc/linearinterpolator.cpp
6d14cd573843e4f7e250add61f2e37aa5663c36d
[]
no_license
Leon-Zhang/prepost-gui
ef2e570bed88bd3232253cfd99e89b3eadfc661f
bff4db57df6a282f6e76e3942dbb02d66fbb5d9e
refs/heads/master
2021-01-01T19:05:10.124321
2017-07-27T04:36:47
2017-07-27T04:36:47
98,504,251
0
0
null
2017-07-27T07:00:00
2017-07-27T07:00:00
null
UTF-8
C++
false
false
1,054
cpp
#include "linearinterpolator.h" LinearInterpolator1D1::LinearInterpolator1D1() : Interpolator1D1() { m_value0 = 0; m_value1 = 0; } LinearInterpolator1D1::LinearInterpolator1D1(double v0, double v1) : Interpolator1D1() { m_value0 = v0; m_value1 = v1; } void LinearInterpolator1D1::setValues(double v0, double v1) { m_value0 = v0; m_value1 = v1; } double LinearInterpolator1D1::interpolate(double t) const { return t * m_value1 + (1 - t) * m_value0; } LinearInterpolator2D1::LinearInterpolator2D1() : Interpolator2D1() { } LinearInterpolator2D1::LinearInterpolator2D1(const QVector2D& v0, const QVector2D& v1) { m_value0 = v0; m_value1 = v1; } void LinearInterpolator2D1::setValues(const QVector2D& v0, const QVector2D& v1) { m_value0 = v0; m_value1 = v1; } QVector2D LinearInterpolator2D1::interpolate(double t) const { return t * m_value1 + (1 - t) * m_value0; } Interpolator2D1* LinearInterpolator2D1::copy() const { return new LinearInterpolator2D1(m_value0, m_value1); }
[ "kinoue@2cc7cdd0-1db9-4218-aa4a-1d8dad43e0f0" ]
kinoue@2cc7cdd0-1db9-4218-aa4a-1d8dad43e0f0
e0cca8c74151c83264b9e69513bd03e1107b82b2
a995091ae322b16728a5be9f1c551e413f57cfa9
/logdevice/server/locallogstore/RocksDBListener.h
0c365752aabad8fad4fb90b91fdad728488e5dae
[ "BSD-3-Clause" ]
permissive
ethio123/LogDevice
3fb387058eedee05c52fffd9b05384a093b3dd4a
f5083568dd295fb750ed39d2a336a22486bd106c
refs/heads/master
2020-04-08T00:59:19.185546
2018-11-23T14:48:08
2018-11-23T14:49:53
158,876,580
1
0
NOASSERTION
2018-11-23T20:46:37
2018-11-23T20:46:37
null
UTF-8
C++
false
false
5,120
h
/** * Copyright (c) 2017-present, Facebook, Inc. and its affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <queue> #include <folly/ThreadLocal.h> #include <rocksdb/listener.h> #include <rocksdb/version.h> #include "logdevice/common/configuration/Configuration.h" #include "logdevice/common/configuration/UpdateableConfig.h" #include "logdevice/common/stats/PerShardHistograms.h" #include "logdevice/common/stats/Stats.h" namespace facebook { namespace logdevice { /** * RocksDBListener gets notified by rocksdb about flushes and compactions. * We use it to collect stats about table files. * RocksDBTablePropertiesCollector collects: * - the histogram of the amount of data each log has in table file, * - the amount of data for each backlog duration in each table file; this * is used by RocksDBLocalLogStore to estimate the amount of space a * compaction can reclaim. * Note that rocksdb allows registering multiple listeners, and RocksDBListener * is not the only one used by logdevice. */ class RocksDBListener : public rocksdb::EventListener { public: RocksDBListener(StatsHolder* stats, size_t shard) : stats_(stats), shard_(shard) {} void OnFlushCompleted(rocksdb::DB* db, const rocksdb::FlushJobInfo& flush_job_info) override; void OnCompactionCompleted(rocksdb::DB* db, const rocksdb::CompactionJobInfo& ci) override; void OnTableFileCreated(const rocksdb::TableFileCreationInfo& info) override; private: StatsHolder* stats_; const size_t shard_; // TableFileCreationInfo is passed from OnTableFileCreated() callback to // flush and compaction callbacks through this queue. This is based on // the following assumptions: // - all file creation callbacks corresponding to a flush/compaction job // are called before the flush/compaction callback, // - they are called on the same thread, // - jobs on the same thread don't interleave. folly::ThreadLocal<std::queue<rocksdb::TableFileCreationInfo>> recently_created_files_; static bool isDataCF(const std::string& cf_name); void onJobCompleted(const std::string& cf_name, const std::vector<std::string>& paths, PerShardHistograms::size_histogram_t& file_size_hist, PerShardHistograms::size_histogram_t& log_run_length_hist); }; class RocksDBTablePropertiesCollector : public rocksdb::TablePropertiesCollector { public: // Backlog duration -> total size of records. using RetentionSizeMap = std::map<std::chrono::seconds, uint64_t>; explicit RocksDBTablePropertiesCollector( std::shared_ptr<Configuration> config, StatsHolder* stats) : config_(config), stats_(stats) {} rocksdb::Status AddUserKey(const rocksdb::Slice& key, const rocksdb::Slice& value, rocksdb::EntryType type, rocksdb::SequenceNumber seq, uint64_t file_size) override; rocksdb::Status Finish(rocksdb::UserCollectedProperties* properties) override; rocksdb::UserCollectedProperties GetReadableProperties() const override; const char* Name() const override; // Parses properties of the form "ld.bytes_with_retention.86400s" => "12345" // and adds them to the given map. static void extractRetentionSizeMap( const std::map<std::string, std::string>& table_properties, RetentionSizeMap& inout_map); private: enum class DataKind { PAYLOAD = 0, RECORD_HEADER, CSI, INDEX, OTHER, MAX, }; using DataKindNamesEnumMap = EnumMap<DataKind, std::string, DataKind::MAX>; friend class EnumMap<DataKind, std::string, DataKind::MAX>; std::shared_ptr<Configuration> config_; StatsHolder* stats_; logid_t current_log_ = LOGID_INVALID; uint64_t current_size_ = 0; SizeHistogram log_size_histogram_; RetentionSizeMap backlog_sizes_; // Approximate number of bytes used for various types of data. std::array<size_t, (int)DataKind::MAX> data_size_per_kind_{}; static DataKindNamesEnumMap& dataKindNames(); void flushCurrentLog(); }; class RocksDBTablePropertiesCollectorFactory : public rocksdb::TablePropertiesCollectorFactory { public: explicit RocksDBTablePropertiesCollectorFactory( std::shared_ptr<UpdateableConfig> updateable_config, StatsHolder* stats) : updateable_config_(updateable_config), stats_(stats) {} #if defined(ROCKSDB_MAJOR) && \ (ROCKSDB_MAJOR > 4 || (ROCKSDB_MAJOR == 4 && ROCKSDB_MINOR >= 2)) rocksdb::TablePropertiesCollector* CreateTablePropertiesCollector( rocksdb::TablePropertiesCollectorFactory::Context context) override; #else rocksdb::TablePropertiesCollector* CreateTablePropertiesCollector() override; #endif const char* Name() const override; private: std::shared_ptr<UpdateableConfig> updateable_config_; StatsHolder* stats_; }; }} // namespace facebook::logdevice
480d6cfd33f155868d85e247fc54ad7141a15edc
9a728b6c31bfd6963712d38b30a6963fd7c531a8
/OrgXueBang/Classes/CoreHelper/Message/MsgParam.hpp
273e9911263fac7a20df327070c85a8615e2c5f0
[]
no_license
daxingyou/MRK-OrgXueBang
5fba171f759ccae2f1e28b4f4364df7d088fe5d2
09f10f3fd22c3791d0c9ec84c2042a36a7a8f22d
refs/heads/master
2021-10-21T20:46:18.280434
2019-03-06T09:03:18
2019-03-06T09:03:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
840
hpp
// // MsgParam.hpp // OrgXueBang-mobile // // Created by liuwei on 2019/1/8. // #ifndef MsgParam_hpp #define MsgParam_hpp #include <stdio.h> #include <string> using namespace std; #include "cocos2d.h" class MsgParam { private: enum eRES{ RES_OK = 0,//消息 RES_ERROR, }; public: MsgParam(); ~MsgParam(); MsgParam(string errTip); bool getIsResOK(); string getErrorTip(); void setErrorTip(string errTip); void setRefData(cocos2d::Ref* data); cocos2d::Ref* getRefData(); void setVecTemp(vector<string>* vecStr); vector<string> getVecTemp(); private: eRES resFlag;//返回结果 string errorTip;//错误提示 vector<string>* vecStrTemp; cocos2d::Ref* _data;//扩展用 int _type;//扩展用 }; #endif /* MsgParam_hpp */
1407992f26e832cce2b36a3c856d0e07f0ca92aa
3f3a42f429f8bcd769644148b24c3b0e6e2589ed
/GameProject/GameEngine/EngineCore/Math/Vector.h
730023c58975c1418d629e7c939e606767c91359
[]
no_license
DanielNeander/my-3d-engine
d10ad3e57a205f6148357f47467b550c7e0e0f33
7f0babbfdf0b719ea4b114a89997d3e52bcb2b6c
refs/heads/master
2021-01-10T17:58:25.691360
2013-04-24T07:37:31
2013-04-24T07:37:31
53,236,587
3
0
null
null
null
null
UTF-8
C++
false
false
50,432
h
#pragma once #ifndef __MATH_VECTOR_H__ #define __MATH_VECTOR_H__ //#include <Core/SysCommon.h> #include "Math.h" #include "Enginecore/Heap.h" /* =============================================================================== Vector classes =============================================================================== */ #define VECTOR_EPSILON 0.001f class idPolar3; class noQuat; class noVec2 { public: float x,y; noVec2(); explicit noVec2( const float x, const float y ); explicit noVec2( const float x); void Set( const float x, const float y); void Zero( void ); float operator[]( int index ) const; float& operator[]( int index ); noVec2 operator-() const; float operator*( const noVec2& a ) const; noVec2 operator*( const float a ) const; noVec2 operator/( const float a ) const; noVec2 operator+( const noVec2& a ) const; noVec2 operator-( const noVec2& a ) const; noVec2& operator+=( const noVec2& a); noVec2& operator-=( const noVec2& a); noVec2& operator/=( const noVec2& a); noVec2& operator/=( const float a); noVec2& operator*=( const float a); friend noVec2 operator*( const float a, const noVec2 b ); bool Compare( const noVec2& a ) const; bool Compare( const noVec2& a, const float epsilon ) const; bool operator==( const noVec2& a ) const; bool operator!=( const noVec2& a ) const; float Length( void ) const; float LengthFast( void ) const; float LengthSqr( void ) const; float Normalize( void ); float NormalizeFast( void ); noVec2& Truncate( float length ); void Clamp( const noVec2& min, const noVec2& max ); void Snap( void ); void SnapInt( void ); //returns the vector that is perpendicular to this one. noVec2 Perp()const; int GetDimension( void ) const; const float * ToFloatPtr( void ) const; float * ToFloatPtr( void ); const char * ToString( int precision = 2 ) const; void Lerp( const noVec2 &v1, const noVec2 &v2, const float l ); int Sign(const noVec2& v2) const; int IsNearlyZero(FLOAT Tolerance=KINDA_SMALL_NUMBER) const; }; extern noVec2 vec2_origin; #define vec2_zero vec2_origin NO_INLINE noVec2::noVec2( void ) {} NO_INLINE noVec2::noVec2( const float x, const float y) { this->x = x; this->y = y; } NO_INLINE noVec2::noVec2( const float _x ) :x(_x), y(_x) { } NO_INLINE void noVec2::Set( const float x, const float y ) { this->x = x; this->y = y; } NO_INLINE void noVec2::Zero( void ) { x = y = 0.0f; } NO_INLINE float noVec2::operator[]( int index ) const { return (&x)[index]; } NO_INLINE float& noVec2::operator[]( int index ) { return (&x)[index]; } NO_INLINE noVec2 noVec2::operator-() const { return noVec2(-x, -y); } NO_INLINE float noVec2::operator*( const noVec2& a ) const { return x * a.x + y * a.y; } NO_INLINE noVec2 noVec2::operator*( const float a ) const { return noVec2( x * a, y * a); } NO_INLINE noVec2 operator*( const float a, const noVec2 b ) { return noVec2( b.x * a, b.y * a); } NO_INLINE noVec2 noVec2::operator/( const float a ) const { float inva = 1.0f / a; return noVec2( x * inva, y * inva ); } NO_INLINE noVec2 noVec2::operator+( const noVec2& a ) const { return noVec2( x + a.x, y + a.y ); } NO_INLINE noVec2 noVec2::operator-( const noVec2& a ) const { return noVec2( x - a.x, y - a.y ); } NO_INLINE int noVec2::IsNearlyZero(FLOAT Tolerance) const { return noMath::Fabs(x)<Tolerance && noMath::Fabs(y)<Tolerance; } NO_INLINE noVec2& noVec2::operator+=( const noVec2& a ) { x += a.x; y += a.y; return *this; } NO_INLINE noVec2& noVec2::operator-=( const noVec2& a ) { x -= a.x; y -= a.y; return *this; } NO_INLINE noVec2& noVec2::operator/=( const noVec2& a ) { x /= a.x; y /= a.y; return *this; } NO_INLINE noVec2& noVec2::operator/=( const float a ) { float inva = 1.0f / a; x *= inva; y *= inva; return *this; } NO_INLINE noVec2& noVec2::operator*=( const float a ) { x *= a; y *= a; return *this; } NO_INLINE bool noVec2::Compare( const noVec2& a ) const { return ( x == a.x) && ( y == a.y); } NO_INLINE bool noVec2::Compare( const noVec2& a, const float epsilon ) const { if ( noMath::Fabs( x - a.x ) > epsilon ) { return false; } if ( noMath::Fabs( y - a.y ) > epsilon ) { return false; } return true; } NO_INLINE bool noVec2::operator==( const noVec2& a ) const { return Compare( a ); } NO_INLINE bool noVec2::operator!=( const noVec2& a ) const { return !Compare( a ); } NO_INLINE float noVec2::Length( void ) const { return ( float )noMath::Sqrt( x * x + y * y ); } NO_INLINE float noVec2::LengthFast( void ) const { return 0.f; } NO_INLINE float noVec2::LengthSqr( void ) const { return ( x * x + y * y ); } NO_INLINE float noVec2::Normalize( void ) { float sqrLen, invLen; sqrLen = x * x + y * y; invLen = noMath::InvSqrt( sqrLen ); x *= invLen; y *= invLen; return invLen * sqrLen; } NO_INLINE float noVec2::NormalizeFast( void ) { return 0.f; } NO_INLINE noVec2& noVec2::Truncate( float length ) { float len2; float ilen; if ( !length ) { Zero(); } else { len2 = LengthSqr(); if ( len2 > length * length ) { ilen = length * noMath::InvSqrt( len2 ); x *= ilen; y *= ilen; } } return *this; } NO_INLINE noVec2 noVec2::Perp() const { return noVec2(-y, x); } NO_INLINE void noVec2::Clamp( const noVec2& min, const noVec2& max ) { if ( x < min.x ) { x = min.x; } else if ( x > max.x ) { x = max.x; } if ( y < min.y ) { y = min.y; } else if ( y > max.y ) { y = max.y; } } NO_INLINE void noVec2::Snap( void ) { x = floor( x + 0.5f ); y = floor( y + 0.5f ); } NO_INLINE void noVec2::SnapInt( void ) { x = float( int( x ) ); y = float( int( y ) ); } NO_INLINE int noVec2::GetDimension( void ) const { return 2; } NO_INLINE const float * noVec2::ToFloatPtr( void ) const { return &x; } NO_INLINE float * noVec2::ToFloatPtr( void ) { return &x; } //------------------------ Sign ------------------------------------------ // // returns positive if v2 is clockwise of this vector, // minus if anticlockwise (Y axis pointing down, X axis to right) //------------------------------------------------------------------------ enum {clockwise = 1, anticlockwise = -1}; NO_INLINE int noVec2::Sign(const noVec2& v2)const { if (y*v2.x > x*v2.y) { return anticlockwise; } else { return clockwise; } } class noVec3 { public: float x,y,z; noVec3( void ); explicit noVec3( const float x, const float y, const float z ); explicit noVec3( const float x); void Set( const float x, const float y, const float z ); void Zero( void ); float operator[]( const int index ) const; float & operator[]( const int index ); noVec3 operator-() const; noVec3 & operator=( const noVec3 &a ); // required because of a msvc 6 & 7 bug float operator*( const noVec3 &a ) const; noVec3 operator*( const float a ) const; noVec3 operator/( const float a ) const; noVec3 operator+( const noVec3 &a ) const; noVec3 operator-( const noVec3 &a ) const; noVec3 & operator+=( const noVec3 &a ); noVec3 & operator-=( const noVec3 &a ); noVec3 & operator/=( const noVec3 &a ); noVec3 & operator/=( const float a ); noVec3 & operator*=( const float a ); bool operator<(const noVec3& vIn) const; friend noVec3 operator*( const float a, const noVec3 b ); bool Compare( const noVec3 &a ) const; // exact compare, no epsilon bool Compare( const noVec3 &a, const float epsilon ) const; // compare with epsilon bool operator==( const noVec3 &a ) const; // exact compare, no epsilon bool operator!=( const noVec3 &a ) const; // exact compare, no epsilon bool FixDegenerateNormal( void ); // fix degenerate axial cases bool FixDenormals( void ); // change tiny numbers to zero noVec3 Cross( const noVec3 &a ) const; noVec3 & Cross( const noVec3 &a, const noVec3 &b ); float Length( void ) const; float LengthSqr( void ) const; float LengthFast( void ) const; float Normalize( void ); // returns length float NormalizeFast( void ); // returns length noVec3 & Truncate( float length ); // cap length void Clamp( const noVec3 &min, const noVec3 &max ); void Snap( void ); // snap to closest integer value void SnapInt( void ); // snap towards integer (floor) void Lerp( const noVec3 &v1, const noVec3 &v2, const float l ); void SLerp( const noVec3 &v1, const noVec3 &v2, const float l ); int GetDimension( void ) const; noMat3 ToMat3( void ) const; float ToYaw( void ) const; float ToPitch( void ) const; noAngles ToAngles( void ) const; idPolar3 ToPolar( void ) const; const noVec2 & ToVec2( void ) const; noVec2 & ToVec2( void ); const float * ToFloatPtr( void ) const; float * ToFloatPtr( void ); float Distance(const noVec3& vIn) const; float DistanceSqr(const noVec3& vIn) const; void Max(const noVec3 &other ); void Min(const noVec3 &other ); FLOAT GetMax() const { return ::Max(::Max(x,y),z); } FLOAT GetAbsMax() const { return ::Max(::Max(abs(x),abs(y)),abs(z)); } FLOAT GetMin() const { return ::Min(::Min(x,y),z); } noQuat getRotationTo(const noVec3& dest, const noVec3& fallbackAxis = noVec3(0.0f, 0.0f, 0.0f)) const; int Sign(const noVec3& v2)const; noVec3 Perp() const; noVec3 NormalizeCopy(void) const; /** Calculates a reflection vector to the plane with the given normal . @remarks NB assumes 'this' is pointing AWAY FROM the plane, invert if it is not. */ inline noVec3 Reflect(const noVec3& normal) const { return noVec3( *this - ( 2 * (*this) * (normal) * normal ) ); } const noVec3 Multiply(const noVec3& vIn) const; noVec3 Perpendicular(void) const; noVec3 SafeNormal2D(FLOAT Tolerance=1e-8) const; noVec3 SafeNormal(FLOAT Tolerance=1e-8) const; int IsNearlyZero(FLOAT Tolerance=KINDA_SMALL_NUMBER) const; void ProjectSelfOntoSphere( const float radius ); bool ProjectAlongPlane( const noVec3 &normal, const float epsilon, const float overBounce ); void ProjectOntoPlane( const noVec3 &normal, const float overBounce ); void OrthogonalBasis( noVec3 &left, noVec3 &up ) const; void NormalVectors( noVec3 &left, noVec3 &down ) const; const char *ToString( int precision = 2) const; }; extern noVec3 vec3_origin; extern noVec3 vec3_origin; #define vec3_zero vec3_origin NO_INLINE noVec3::noVec3( void ) {} NO_INLINE noVec3::noVec3( const float x, const float y, const float z) { this->x = x; this->y = y; this->z = z; } NO_INLINE noVec3::noVec3( const float _x ) :x(_x), y(_x), z(_x) { } NO_INLINE void noVec3::Set( const float x, const float y, const float z ) { this->x = x; this->y = y; this->z = z; } NO_INLINE void noVec3::Zero( void ) { x = y = z = 0.0f; } NO_INLINE float noVec3::operator[]( int index ) const { return (&x)[index]; } NO_INLINE float& noVec3::operator[]( int index ) { return (&x)[index]; } NO_INLINE noVec3 & noVec3::operator=( const noVec3 &a ) { x = a.x; y = a.y; z = a.z; return *this; } NO_INLINE noVec3 noVec3::operator-() const { return noVec3(-x, -y, -z); } NO_INLINE float noVec3::operator*( const noVec3& a ) const { return x * a.x + y * a.y + z * a.z; } NO_INLINE noVec3 noVec3::operator*( const float a ) const { return noVec3( x * a, y * a, z * a ); } NO_INLINE noVec3 noVec3::operator/( const float a ) const { float inva = 1.0f / a; return noVec3( x * inva, y * inva, z * inva ); } NO_INLINE noVec3 noVec3::operator+( const noVec3& a ) const { return noVec3( x + a.x, y + a.y, z + a.z ); } NO_INLINE noVec3 operator*( const float a, const noVec3 b ) { return noVec3( b.x * a, b.y * a, b.z * a); } NO_INLINE noVec3 noVec3::operator-( const noVec3& a ) const { return noVec3( x - a.x, y - a.y, z - a.z ); } NO_INLINE noVec3& noVec3::operator+=( const noVec3& a ) { x += a.x; y += a.y; z += a.z; return *this; } NO_INLINE noVec3& noVec3::operator-=( const noVec3& a ) { x -= a.x; y -= a.y; z -= a.z; return *this; } NO_INLINE noVec3& noVec3::operator/=( const noVec3& a ) { x /= a.x; y /= a.y; z /= a.z; return *this; } NO_INLINE noVec3& noVec3::operator/=( const float a ) { float inva = 1.0f / a; x *= inva; y *= inva; z *= inva; return *this; } NO_INLINE noVec3& noVec3::operator*=( const float a ) { x *= a; y *= a; z *= a; return *this; } NO_INLINE bool noVec3::operator<(const noVec3& vIn) const { if (x == vIn.x) { if (y == vIn.y) return z < vIn.z; else return y < vIn.y; } else return x < vIn.x; } NO_INLINE bool noVec3::Compare( const noVec3& a ) const { return ( x == a.x) && ( y == a.y) && ( z == a.z ); } NO_INLINE bool noVec3::Compare( const noVec3& a, const float epsilon ) const { if ( noMath::Fabs( x - a.x ) > epsilon ) { return false; } if ( noMath::Fabs( y - a.y ) > epsilon ) { return false; } if ( noMath::Fabs( z - a.z ) > epsilon ) { return false; } return true; } NO_INLINE bool noVec3::operator==( const noVec3& a ) const { return Compare( a ); } NO_INLINE bool noVec3::operator!=( const noVec3& a ) const { return !Compare( a ); } NO_INLINE float noVec3::Length( void ) const { return ( float )noMath::Sqrt( x * x + y * y + z * z ); } NO_INLINE float noVec3::LengthFast( void ) const { return 0.f; } NO_INLINE float noVec3::LengthSqr( void ) const { return ( x * x + y * y + z * z ); } NO_INLINE float noVec3::DistanceSqr( const noVec3& vIn ) const { return ((*this - vIn).LengthSqr()); } NO_INLINE float noVec3::Distance( const noVec3& vIn ) const { return ((*this - vIn).Length()); } NO_INLINE float noVec3::Normalize( void ) { float sqrLen, invLen; sqrLen = x * x + y * y + z * z; invLen = noMath::InvSqrt( sqrLen ); x *= invLen; y *= invLen; z *= invLen; return invLen * sqrLen; } NO_INLINE float noVec3::NormalizeFast( void ) { return 0.f; } NO_INLINE noVec3 noVec3::SafeNormal(FLOAT Tolerance) const { const float SquareSum = x*x + y*y + z*z; // Not sure if it's safe to add tolerance in there. Might introduce too many errors if( SquareSum == 1.f ) { return *this; } else if( SquareSum < Tolerance ) { return noVec3(0.f); } const FLOAT Scale = noMath::InvSqrt(SquareSum); return noVec3(x*Scale, y*Scale, z*Scale); } NO_INLINE noVec3 noVec3::SafeNormal2D(FLOAT Tolerance) const { const FLOAT SquareSum = x*x + y*y; // Not sure if it's safe to add tolerance in there. Might introduce too many errors if( SquareSum == 1.f ) { if( z == 0.f ) { return *this; } else { return noVec3(x, y, 0.f); } } else if( SquareSum < Tolerance ) { return noVec3(0.f); } const FLOAT Scale = noMath::InvSqrt(SquareSum); return noVec3(x*Scale, y*Scale, 0.f); } NO_INLINE noVec3& noVec3::Truncate( float length ) { float len2; float ilen; if ( !length ) { Zero(); } else { len2 = LengthSqr(); if ( len2 > length * length ) { ilen = length * noMath::InvSqrt( len2 ); x *= ilen; y *= ilen; z *= ilen; } } return *this; } NO_INLINE void noVec3::Clamp( const noVec3& min, const noVec3& max ) { if ( x < min.x ) { x = min.x; } else if ( x > max.x ) { x = max.x; } if ( y < min.y ) { y = min.y; } else if ( y > max.y ) { y = max.y; } if ( z < min.z ) { z = min.z; } else if ( z > max.z ) { z = max.z; } } NO_INLINE void noVec3::Snap( void ) { x = floor( x + 0.5f ); y = floor( y + 0.5f ); z = floor( z + 0.5f ); } NO_INLINE void noVec3::SnapInt( void ) { x = float( int( x ) ); y = float( int( y ) ); z = float( int( z ) ); } NO_INLINE int noVec3::GetDimension( void ) const { return 3; } NO_INLINE const noVec2 & noVec3::ToVec2( void ) const { return *reinterpret_cast<const noVec2 *>(this); } NO_INLINE noVec2 & noVec3::ToVec2( void ) { return *reinterpret_cast<noVec2 *>(this); } NO_INLINE const float * noVec3::ToFloatPtr( void ) const { return &x; } NO_INLINE float * noVec3::ToFloatPtr( void ) { return &x; } NO_INLINE void noVec3::Min(const noVec3 &other ) { x = __min(x,other.x); y = __min(y,other.y); z = __min(z,other.z); } NO_INLINE void noVec3::Max(const noVec3 &other ) { x = __max(x,other.x); y = __max(y,other.y); z = __max(z,other.z); } NO_INLINE int noVec3::Sign(const noVec3& v2)const { if (z*v2.x > x*v2.z) { return anticlockwise; } else { return clockwise; } } NO_INLINE noVec3 noVec3::Perp() const { return noVec3(-z, y, x); } NO_INLINE noVec3 noVec3::NormalizeCopy(void) const { noVec3 ret = *this; ret.Normalize(); return ret; } NO_INLINE const noVec3 noVec3::Multiply(const noVec3& vIn) const { return noVec3(x * vIn.x, y * vIn.y, z * vIn.z); } NO_INLINE int noVec3::IsNearlyZero( FLOAT Tolerance/*=KINDA_SMALL_NUMBER*/ ) const { return noMath::Fabs(x) < Tolerance && noMath::Fabs(y) < Tolerance && noMath::Fabs(z) < Tolerance; } NO_INLINE void noVec3::NormalVectors( noVec3 &left, noVec3 &down ) const { float d; d = x * x + y * y; if ( !d ) { left[0] = 1; left[1] = 0; left[2] = 0; } else { d = noMath::InvSqrt( d ); left[0] = -y * d; left[1] = x * d; left[2] = 0; } down = left.Cross( *this ); } NO_INLINE void noVec3::OrthogonalBasis( noVec3 &left, noVec3 &up ) const { float l, s; if ( noMath::Fabs( z ) > 0.7f ) { l = y * y + z * z; s = noMath::InvSqrt( l ); up[0] = 0; up[1] = z * s; up[2] = -y * s; left[0] = l * s; left[1] = -x * up[2]; left[2] = x * up[1]; } else { l = x * x + y * y; s = noMath::InvSqrt( l ); left[0] = -y * s; left[1] = x * s; left[2] = 0; up[0] = -z * left[1]; up[1] = z * left[0]; up[2] = l * s; } } NO_INLINE void noVec3::ProjectOntoPlane( const noVec3 &normal, const float overBounce ) { float backoff; backoff = *this * normal; if ( overBounce != 1.0 ) { if ( backoff < 0 ) { backoff *= overBounce; } else { backoff /= overBounce; } } *this -= backoff * normal; } NO_INLINE bool noVec3::ProjectAlongPlane( const noVec3 &normal, const float epsilon, const float overBounce ) { noVec3 cross; float len; cross = this->Cross( normal ).Cross( (*this) ); // normalize so a fixed epsilon can be used cross.Normalize(); len = normal * cross; if ( noMath::Fabs( len ) < epsilon ) { return false; } cross *= overBounce * ( normal * (*this) ) / len; (*this) -= cross; return true; } /** Generates a vector perpendicular to this vector (eg an 'up' vector). @remarks This method will return a vector which is perpendicular to this vector. There are an infinite number of possibilities but this method will guarantee to generate one of them. If you need more control you should use the Quaternion class. */ NO_INLINE noVec3 noVec3::Perpendicular(void) const { static const Real fSquareZero = (Real)(1e-06 * 1e-06); noVec3 perp = this->Cross( noVec3(1.f, 0.f, 0.f) ); // Check length if( perp.LengthSqr() < fSquareZero ) { /* This vector is the Y axis multiplied by a scalar, so we have to use another axis. */ perp = this->Cross( noVec3(0.f, 1.0f, 0.f) ); } perp.Normalize(); return perp; } class noVec4 { public: noVec4() {} noVec4(float x, float y, float z, float w); noVec4(const noVec3& v, float w); NO_INLINE void Set(float x, float y, float z, float w=0); NO_INLINE void SetAll( float x ); NO_INLINE void SetAll3( float x ); NO_INLINE void SetZero4( void ); float operator[]( const int index ) const; float & operator[]( const int index ); noVec4 operator-() const; noVec4 & operator=( const noVec4 &a ); // required because of a msvc 6 & 7 bug float operator*( const noVec4 &a ) const; noVec4 operator*( const float a ) const; noVec4 operator/( const float a ) const; noVec4 operator+( const noVec4 &a ) const; noVec4 operator-( const noVec4 &a ) const; noVec4 & operator+=( const noVec4 &a ); noVec4 & operator-=( const noVec4 &a ); noVec4 & operator/=( const noVec4 &a ); noVec4 & operator/=( const float a ); noVec4 & operator*=( const float a ); friend noVec4 operator*( const float a, const noVec4 b ); bool Compare( const noVec4 &a, const float epsilon ) const; float Normalize(); float Length( void ) const; int GetDimension( void ) const; const noVec2 & ToVec2( void ) const; noVec2 & ToVec2( void ); const noVec3 & ToVec3( void ) const; noVec3 & ToVec3( void ); const float * ToFloatPtr( void ) const; float * ToFloatPtr( void ); const noVec4 Multiply(const noVec4& vIn) const; void Min(const noVec4 &other ); void Max(const noVec4 &other ); //NO_ALIGN16( float x ); float x ; float y,z,w; }; extern noVec4 vec4_origin; #define vec4_zero vec4_origin NO_INLINE noVec4::noVec4( float x, float y, float z, float w ) { Set(x, y, z, w); } NO_INLINE noVec4::noVec4( const noVec3& v, float _w ) { x = v.x; y = v.y; z = v.z; w = _w; } NO_INLINE void noVec4::Set( float x, float y, float z, float w/*=0*/ ) { this->x = x; this->y = y; this->z = z; this->w = w; } NO_INLINE void noVec4::SetAll( float a ) { x = y = z = w = a; } NO_INLINE void noVec4::SetAll3( float a ) { x = y = z = a; } NO_INLINE void noVec4::SetZero4( void ) { x = y = z = w = 0.f; } NO_INLINE float noVec4::operator[]( const int index ) const { return (&x)[ index ]; } NO_INLINE float & noVec4::operator[]( const int index ) { return (&x)[ index ]; } NO_INLINE noVec4 & noVec4::operator=( const noVec4 &a ) { x = a.x; y = a.y; z = a.z; w = a.w; return *this; } ID_INLINE bool noVec4::Compare( const noVec4 &a, const float epsilon ) const { if ( noMath::Fabs( x - a.x ) > epsilon ) { return false; } if ( noMath::Fabs( y - a.y ) > epsilon ) { return false; } if ( noMath::Fabs( z - a.z ) > epsilon ) { return false; } if ( noMath::Fabs( w - a.w ) > epsilon ) { return false; } return true; } NO_INLINE noVec4 noVec4::operator-() const { return noVec4(-x, -y, -z, -w); } NO_INLINE float noVec4::operator*( const noVec4 &a ) const { return (x * a.x) + (y * a.y) + (z * a.z) + ( w * a.w); } NO_INLINE noVec4 noVec4::operator*( const float a ) const { return noVec4(x * a, y * a, z * a, w * a); } NO_INLINE noVec4 noVec4::operator/( const float a ) const { return noVec4(x / a, y / a, z / a, w / a); } NO_INLINE noVec4 noVec4::operator+( const noVec4 &a ) const { return noVec4(x + a.x, y + a.y, z + a.z, w + a.w); } NO_INLINE noVec4 noVec4::operator-( const noVec4 &a ) const { return noVec4(x - a.x, y - a.y, z - a.z, w - a.w); } NO_INLINE noVec4 & noVec4::operator+=( const noVec4 &a ) { x += a.x; y += a.y; z += a.z; w += a.w; return *this; } NO_INLINE noVec4 & noVec4::operator-=( const noVec4 &a ) { x -= a.x; y -= a.y; z -= a.z; w -= a.w; return *this; } NO_INLINE noVec4 & noVec4::operator/=( const noVec4 &a ) { x /= a.x; y /= a.y; z /= a.z; w /= a.w; return *this; } NO_INLINE noVec4 & noVec4::operator/=( const float a ) { x /= a; y /= a; z /= a; w /= a; return *this; } NO_INLINE noVec4 & noVec4::operator*=( const float a ) { x *= a; y *= a; z *= a; w *= a; return *this; } NO_INLINE noVec4 operator*( const float a, const noVec4 b ) { return noVec4( b.x * a, b.y * a, b.z * a, b.w * a ); } NO_INLINE const noVec4 noVec4::Multiply(const noVec4& vIn) const { return noVec4(x * vIn.x, y * vIn.y, z * vIn.z, w * vIn.w); } ID_INLINE const noVec2 &noVec4::ToVec2( void ) const { return *reinterpret_cast<const noVec2 *>(this); } ID_INLINE noVec2 &noVec4::ToVec2( void ) { return *reinterpret_cast<noVec2 *>(this); } ID_INLINE const noVec3 &noVec4::ToVec3( void ) const { return *reinterpret_cast<const noVec3 *>(this); } ID_INLINE noVec3 &noVec4::ToVec3( void ) { return *reinterpret_cast<noVec3 *>(this); } NO_INLINE const float * noVec4::ToFloatPtr( void ) const { return &x; } NO_INLINE float * noVec4::ToFloatPtr( void ) { return &x; } NO_INLINE float noVec4::Length( void ) const { return ( float )noMath::Sqrt( x * x + y * y + z * z + w * w); } NO_INLINE bool noVec3::FixDegenerateNormal( void ) { if ( x == 0.0f ) { if ( y == 0.0f ) { if ( z > 0.0f ) { if ( z != 1.0f ) { z = 1.0f; return true; } } else { if ( z != -1.0f ) { z = -1.0f; return true; } } return false; } else if ( z == 0.0f ) { if ( y > 0.0f ) { if ( y != 1.0f ) { y = 1.0f; return true; } } else { if ( y != -1.0f ) { y = -1.0f; return true; } } return false; } } else if ( y == 0.0f ) { if ( z == 0.0f ) { if ( x > 0.0f ) { if ( x != 1.0f ) { x = 1.0f; return true; } } else { if ( x != -1.0f ) { x = -1.0f; return true; } } return false; } } if ( noMath::Fabs( x ) == 1.0f ) { if ( y != 0.0f || z != 0.0f ) { y = z = 0.0f; return true; } return false; } else if ( noMath::Fabs( y ) == 1.0f ) { if ( x != 0.0f || z != 0.0f ) { x = z = 0.0f; return true; } return false; } else if ( noMath::Fabs( z ) == 1.0f ) { if ( x != 0.0f || y != 0.0f ) { x = y = 0.0f; return true; } return false; } return false; } NO_INLINE bool noVec3::FixDenormals( void ) { bool denormal = false; if ( fabs( x ) < 1e-30f ) { x = 0.0f; denormal = true; } if ( fabs( y ) < 1e-30f ) { y = 0.0f; denormal = true; } if ( fabs( z ) < 1e-30f ) { z = 0.0f; denormal = true; } return denormal; } NO_INLINE noVec3 noVec3::Cross( const noVec3 &a ) const { return noVec3( y * a.z - z * a.y, z * a.x - x * a.z, x * a.y - y * a.x ); } NO_INLINE noVec3 & noVec3::Cross( const noVec3 &a, const noVec3 &b ) { x = a.y * b.z - a.z * b.y; y = a.z * b.x - a.x * b.z; z = a.x * b.y - a.y * b.x; return *this; } NO_INLINE float noVec4::Normalize( void ) { float sqrLen, invLen; sqrLen = x * x + y * y + z * z + w * w; invLen = noMath::InvSqrt( sqrLen ); x *= invLen; y *= invLen; z *= invLen; w *= invLen; return invLen * sqrLen; } NO_INLINE void noVec4::Min(const noVec4 &other ) { x = __min(x,other.x); y = __min(y,other.y); z = __min(z,other.z); w = __min(w,other.w); } NO_INLINE void noVec4::Max(const noVec4 &other ) { x = __max(x,other.x); y = __max(y,other.y); z = __max(z,other.z); w = __max(w,other.w); } //=============================================================== // // idVec5 - 5D vector // //=============================================================== class idVec5 { public: float x; float y; float z; float s; float t; idVec5( void ); explicit idVec5( const noVec3 &xyz, const noVec2 &st ); explicit idVec5( const float x, const float y, const float z, const float s, const float t ); float operator[]( int index ) const; float & operator[]( int index ); idVec5 & operator=( const noVec3 &a ); int GetDimension( void ) const; const noVec3 & ToVec3( void ) const; noVec3 & ToVec3( void ); const float * ToFloatPtr( void ) const; float * ToFloatPtr( void ); const char * ToString( int precision = 2 ) const; void Lerp( const idVec5 &v1, const idVec5 &v2, const float l ); }; extern idVec5 vec5_origin; #define vec5_zero vec5_origin ID_INLINE idVec5::idVec5( void ) { } ID_INLINE idVec5::idVec5( const noVec3 &xyz, const noVec2 &st ) { x = xyz.x; y = xyz.y; z = xyz.z; s = st[0]; t = st[1]; } ID_INLINE idVec5::idVec5( const float x, const float y, const float z, const float s, const float t ) { this->x = x; this->y = y; this->z = z; this->s = s; this->t = t; } ID_INLINE float idVec5::operator[]( int index ) const { return ( &x )[ index ]; } ID_INLINE float& idVec5::operator[]( int index ) { return ( &x )[ index ]; } ID_INLINE idVec5 &idVec5::operator=( const noVec3 &a ) { x = a.x; y = a.y; z = a.z; s = t = 0; return *this; } ID_INLINE int idVec5::GetDimension( void ) const { return 5; } ID_INLINE const noVec3 &idVec5::ToVec3( void ) const { return *reinterpret_cast<const noVec3 *>(this); } ID_INLINE noVec3 &idVec5::ToVec3( void ) { return *reinterpret_cast<noVec3 *>(this); } ID_INLINE const float *idVec5::ToFloatPtr( void ) const { return &x; } ID_INLINE float *idVec5::ToFloatPtr( void ) { return &x; } //=============================================================== // // idVec6 - 6D vector // //=============================================================== class idVec6 { public: idVec6( void ); explicit idVec6( const float *a ); explicit idVec6( const float a1, const float a2, const float a3, const float a4, const float a5, const float a6 ); void Set( const float a1, const float a2, const float a3, const float a4, const float a5, const float a6 ); void Zero( void ); float operator[]( const int index ) const; float & operator[]( const int index ); idVec6 operator-() const; idVec6 operator*( const float a ) const; idVec6 operator/( const float a ) const; float operator*( const idVec6 &a ) const; idVec6 operator-( const idVec6 &a ) const; idVec6 operator+( const idVec6 &a ) const; idVec6 & operator*=( const float a ); idVec6 & operator/=( const float a ); idVec6 & operator+=( const idVec6 &a ); idVec6 & operator-=( const idVec6 &a ); friend idVec6 operator*( const float a, const idVec6 b ); bool Compare( const idVec6 &a ) const; // exact compare, no epsilon bool Compare( const idVec6 &a, const float epsilon ) const; // compare with epsilon bool operator==( const idVec6 &a ) const; // exact compare, no epsilon bool operator!=( const idVec6 &a ) const; // exact compare, no epsilon float Length( void ) const; float LengthSqr( void ) const; float Normalize( void ); // returns length float NormalizeFast( void ); // returns length int GetDimension( void ) const; const noVec3 & SubVec3( int index ) const; noVec3 & SubVec3( int index ); const float * ToFloatPtr( void ) const; float * ToFloatPtr( void ); const char * ToString( int precision = 2 ) const; private: float p[6]; }; extern idVec6 vec6_origin; #define vec6_zero vec6_origin extern idVec6 vec6_infinity; ID_INLINE idVec6::idVec6( void ) { } ID_INLINE idVec6::idVec6( const float *a ) { memcpy( p, a, 6 * sizeof( float ) ); } ID_INLINE idVec6::idVec6( const float a1, const float a2, const float a3, const float a4, const float a5, const float a6 ) { p[0] = a1; p[1] = a2; p[2] = a3; p[3] = a4; p[4] = a5; p[5] = a6; } ID_INLINE idVec6 idVec6::operator-() const { return idVec6( -p[0], -p[1], -p[2], -p[3], -p[4], -p[5] ); } ID_INLINE float idVec6::operator[]( const int index ) const { return p[index]; } ID_INLINE float &idVec6::operator[]( const int index ) { return p[index]; } ID_INLINE idVec6 idVec6::operator*( const float a ) const { return idVec6( p[0]*a, p[1]*a, p[2]*a, p[3]*a, p[4]*a, p[5]*a ); } ID_INLINE float idVec6::operator*( const idVec6 &a ) const { return p[0] * a[0] + p[1] * a[1] + p[2] * a[2] + p[3] * a[3] + p[4] * a[4] + p[5] * a[5]; } ID_INLINE idVec6 idVec6::operator/( const float a ) const { float inva; assert( a != 0.0f ); inva = 1.0f / a; return idVec6( p[0]*inva, p[1]*inva, p[2]*inva, p[3]*inva, p[4]*inva, p[5]*inva ); } ID_INLINE idVec6 idVec6::operator+( const idVec6 &a ) const { return idVec6( p[0] + a[0], p[1] + a[1], p[2] + a[2], p[3] + a[3], p[4] + a[4], p[5] + a[5] ); } ID_INLINE idVec6 idVec6::operator-( const idVec6 &a ) const { return idVec6( p[0] - a[0], p[1] - a[1], p[2] - a[2], p[3] - a[3], p[4] - a[4], p[5] - a[5] ); } ID_INLINE idVec6 &idVec6::operator*=( const float a ) { p[0] *= a; p[1] *= a; p[2] *= a; p[3] *= a; p[4] *= a; p[5] *= a; return *this; } ID_INLINE idVec6 &idVec6::operator/=( const float a ) { float inva; assert( a != 0.0f ); inva = 1.0f / a; p[0] *= inva; p[1] *= inva; p[2] *= inva; p[3] *= inva; p[4] *= inva; p[5] *= inva; return *this; } ID_INLINE idVec6 &idVec6::operator+=( const idVec6 &a ) { p[0] += a[0]; p[1] += a[1]; p[2] += a[2]; p[3] += a[3]; p[4] += a[4]; p[5] += a[5]; return *this; } ID_INLINE idVec6 &idVec6::operator-=( const idVec6 &a ) { p[0] -= a[0]; p[1] -= a[1]; p[2] -= a[2]; p[3] -= a[3]; p[4] -= a[4]; p[5] -= a[5]; return *this; } ID_INLINE idVec6 operator*( const float a, const idVec6 b ) { return b * a; } ID_INLINE bool idVec6::Compare( const idVec6 &a ) const { return ( ( p[0] == a[0] ) && ( p[1] == a[1] ) && ( p[2] == a[2] ) && ( p[3] == a[3] ) && ( p[4] == a[4] ) && ( p[5] == a[5] ) ); } ID_INLINE bool idVec6::Compare( const idVec6 &a, const float epsilon ) const { if ( noMath::Fabs( p[0] - a[0] ) > epsilon ) { return false; } if ( noMath::Fabs( p[1] - a[1] ) > epsilon ) { return false; } if ( noMath::Fabs( p[2] - a[2] ) > epsilon ) { return false; } if ( noMath::Fabs( p[3] - a[3] ) > epsilon ) { return false; } if ( noMath::Fabs( p[4] - a[4] ) > epsilon ) { return false; } if ( noMath::Fabs( p[5] - a[5] ) > epsilon ) { return false; } return true; } ID_INLINE bool idVec6::operator==( const idVec6 &a ) const { return Compare( a ); } ID_INLINE bool idVec6::operator!=( const idVec6 &a ) const { return !Compare( a ); } ID_INLINE void idVec6::Set( const float a1, const float a2, const float a3, const float a4, const float a5, const float a6 ) { p[0] = a1; p[1] = a2; p[2] = a3; p[3] = a4; p[4] = a5; p[5] = a6; } ID_INLINE void idVec6::Zero( void ) { p[0] = p[1] = p[2] = p[3] = p[4] = p[5] = 0.0f; } ID_INLINE float idVec6::Length( void ) const { return ( float )noMath::Sqrt( p[0] * p[0] + p[1] * p[1] + p[2] * p[2] + p[3] * p[3] + p[4] * p[4] + p[5] * p[5] ); } ID_INLINE float idVec6::LengthSqr( void ) const { return ( p[0] * p[0] + p[1] * p[1] + p[2] * p[2] + p[3] * p[3] + p[4] * p[4] + p[5] * p[5] ); } ID_INLINE float idVec6::Normalize( void ) { float sqrLength, invLength; sqrLength = p[0] * p[0] + p[1] * p[1] + p[2] * p[2] + p[3] * p[3] + p[4] * p[4] + p[5] * p[5]; invLength = noMath::InvSqrt( sqrLength ); p[0] *= invLength; p[1] *= invLength; p[2] *= invLength; p[3] *= invLength; p[4] *= invLength; p[5] *= invLength; return invLength * sqrLength; } ID_INLINE float idVec6::NormalizeFast( void ) { float sqrLength, invLength; sqrLength = p[0] * p[0] + p[1] * p[1] + p[2] * p[2] + p[3] * p[3] + p[4] * p[4] + p[5] * p[5]; invLength = noMath::RSqrt( sqrLength ); p[0] *= invLength; p[1] *= invLength; p[2] *= invLength; p[3] *= invLength; p[4] *= invLength; p[5] *= invLength; return invLength * sqrLength; } ID_INLINE int idVec6::GetDimension( void ) const { return 6; } ID_INLINE const noVec3 &idVec6::SubVec3( int index ) const { return *reinterpret_cast<const noVec3 *>(p + index * 3); } ID_INLINE noVec3 &idVec6::SubVec3( int index ) { return *reinterpret_cast<noVec3 *>(p + index * 3); } ID_INLINE const float *idVec6::ToFloatPtr( void ) const { return p; } ID_INLINE float *idVec6::ToFloatPtr( void ) { return p; } //=============================================================== // // idVecX - arbitrary sized vector // // The vector lives on 16 byte aligned and 16 byte padded memory. // // NOTE: due to the temporary memory pool idVecX cannot be used by multiple threads // //=============================================================== #define VECX_MAX_TEMP 1024 #define VECX_QUAD( x ) ( ( ( ( x ) + 3 ) & ~3 ) * sizeof( float ) ) #define VECX_CLEAREND() int s = size; while( s < ( ( s + 3) & ~3 ) ) { p[s++] = 0.0f; } #define VECX_ALLOCA( n ) ( (float *) _alloca16( VECX_QUAD( n ) ) ) #define VECX_SIMD class idVecX { friend class idMatX; public: idVecX( void ); explicit idVecX( int length ); explicit idVecX( int length, float *data ); ~idVecX( void ); float operator[]( const int index ) const; float & operator[]( const int index ); idVecX operator-() const; idVecX & operator=( const idVecX &a ); idVecX operator*( const float a ) const; idVecX operator/( const float a ) const; float operator*( const idVecX &a ) const; idVecX operator-( const idVecX &a ) const; idVecX operator+( const idVecX &a ) const; idVecX & operator*=( const float a ); idVecX & operator/=( const float a ); idVecX & operator+=( const idVecX &a ); idVecX & operator-=( const idVecX &a ); friend idVecX operator*( const float a, const idVecX b ); bool Compare( const idVecX &a ) const; // exact compare, no epsilon bool Compare( const idVecX &a, const float epsilon ) const; // compare with epsilon bool operator==( const idVecX &a ) const; // exact compare, no epsilon bool operator!=( const idVecX &a ) const; // exact compare, no epsilon void SetSize( int size ); void ChangeSize( int size, bool makeZero = false ); int GetSize( void ) const { return size; } void SetData( int length, float *data ); void Zero( void ); void Zero( int length ); void Random( int seed, float l = 0.0f, float u = 1.0f ); void Random( int length, int seed, float l = 0.0f, float u = 1.0f ); void Negate( void ); void Clamp( float min, float max ); idVecX & SwapElements( int e1, int e2 ); float Length( void ) const; float LengthSqr( void ) const; idVecX Normalize( void ) const; float NormalizeSelf( void ); int GetDimension( void ) const; const noVec3 & SubVec3( int index ) const; noVec3 & SubVec3( int index ); const idVec6 & SubVec6( int index ) const; idVec6 & SubVec6( int index ); const float * ToFloatPtr( void ) const; float * ToFloatPtr( void ); const char * ToString( int precision = 2 ) const; private: int size; // size of the vector int alloced; // if -1 p points to data set with SetData float * p; // memory the vector is stored static float temp[VECX_MAX_TEMP+4]; // used to store intermediate results static float * tempPtr; // pointer to 16 byte aligned temporary memory static int tempIndex; // index into memory pool, wraps around private: void SetTempSize( int size ); }; ID_INLINE idVecX::idVecX( void ) { size = alloced = 0; p = NULL; } ID_INLINE idVecX::idVecX( int length ) { size = alloced = 0; p = NULL; SetSize( length ); } ID_INLINE idVecX::idVecX( int length, float *data ) { size = alloced = 0; p = NULL; SetData( length, data ); } ID_INLINE idVecX::~idVecX( void ) { // if not temp memory if ( p && ( p < idVecX::tempPtr || p >= idVecX::tempPtr + VECX_MAX_TEMP ) && alloced != -1 ) { Mem_Free16( p ); } } ID_INLINE float idVecX::operator[]( const int index ) const { assert( index >= 0 && index < size ); return p[index]; } ID_INLINE float &idVecX::operator[]( const int index ) { assert( index >= 0 && index < size ); return p[index]; } ID_INLINE idVecX idVecX::operator-() const { int i; idVecX m; m.SetTempSize( size ); for ( i = 0; i < size; i++ ) { m.p[i] = -p[i]; } return m; } ID_INLINE idVecX &idVecX::operator=( const idVecX &a ) { SetSize( a.size ); #ifdef VECX_SIMD SIMDProcessor->Copy16( p, a.p, a.size ); #else memcpy( p, a.p, a.size * sizeof( float ) ); #endif idVecX::tempIndex = 0; return *this; } ID_INLINE idVecX idVecX::operator+( const idVecX &a ) const { idVecX m; assert( size == a.size ); m.SetTempSize( size ); #ifdef VECX_SIMD SIMDProcessor->Add16( m.p, p, a.p, size ); #else int i; for ( i = 0; i < size; i++ ) { m.p[i] = p[i] + a.p[i]; } #endif return m; } ID_INLINE idVecX idVecX::operator-( const idVecX &a ) const { idVecX m; assert( size == a.size ); m.SetTempSize( size ); #ifdef VECX_SIMD SIMDProcessor->Sub16( m.p, p, a.p, size ); #else int i; for ( i = 0; i < size; i++ ) { m.p[i] = p[i] - a.p[i]; } #endif return m; } ID_INLINE idVecX &idVecX::operator+=( const idVecX &a ) { assert( size == a.size ); #ifdef VECX_SIMD SIMDProcessor->AddAssign16( p, a.p, size ); #else int i; for ( i = 0; i < size; i++ ) { p[i] += a.p[i]; } #endif idVecX::tempIndex = 0; return *this; } ID_INLINE idVecX &idVecX::operator-=( const idVecX &a ) { assert( size == a.size ); #ifdef VECX_SIMD SIMDProcessor->SubAssign16( p, a.p, size ); #else int i; for ( i = 0; i < size; i++ ) { p[i] -= a.p[i]; } #endif idVecX::tempIndex = 0; return *this; } ID_INLINE idVecX idVecX::operator*( const float a ) const { idVecX m; m.SetTempSize( size ); #ifdef VECX_SIMD SIMDProcessor->Mul16( m.p, p, a, size ); #else int i; for ( i = 0; i < size; i++ ) { m.p[i] = p[i] * a; } #endif return m; } ID_INLINE idVecX &idVecX::operator*=( const float a ) { #ifdef VECX_SIMD SIMDProcessor->MulAssign16( p, a, size ); #else int i; for ( i = 0; i < size; i++ ) { p[i] *= a; } #endif return *this; } ID_INLINE idVecX idVecX::operator/( const float a ) const { assert( a != 0.0f ); return (*this) * ( 1.0f / a ); } ID_INLINE idVecX &idVecX::operator/=( const float a ) { assert( a != 0.0f ); (*this) *= ( 1.0f / a ); return *this; } ID_INLINE idVecX operator*( const float a, const idVecX b ) { return b * a; } ID_INLINE float idVecX::operator*( const idVecX &a ) const { int i; float sum = 0.0f; assert( size == a.size ); for ( i = 0; i < size; i++ ) { sum += p[i] * a.p[i]; } return sum; } ID_INLINE bool idVecX::Compare( const idVecX &a ) const { int i; assert( size == a.size ); for ( i = 0; i < size; i++ ) { if ( p[i] != a.p[i] ) { return false; } } return true; } ID_INLINE bool idVecX::Compare( const idVecX &a, const float epsilon ) const { int i; assert( size == a.size ); for ( i = 0; i < size; i++ ) { if ( noMath::Fabs( p[i] - a.p[i] ) > epsilon ) { return false; } } return true; } ID_INLINE bool idVecX::operator==( const idVecX &a ) const { return Compare( a ); } ID_INLINE bool idVecX::operator!=( const idVecX &a ) const { return !Compare( a ); } ID_INLINE void idVecX::SetSize( int newSize ) { int alloc = ( newSize + 3 ) & ~3; if ( alloc > alloced && alloced != -1 ) { if ( p ) { Mem_Free16( p ); } p = (float *) Mem_Alloc16( alloc * sizeof( float ) ); alloced = alloc; } size = newSize; VECX_CLEAREND(); } ID_INLINE void idVecX::ChangeSize( int newSize, bool makeZero ) { int alloc = ( newSize + 3 ) & ~3; if ( alloc > alloced && alloced != -1 ) { float *oldVec = p; p = (float *) Mem_Alloc16( alloc * sizeof( float ) ); alloced = alloc; if ( oldVec ) { for ( int i = 0; i < size; i++ ) { p[i] = oldVec[i]; } Mem_Free16( oldVec ); } if ( makeZero ) { // zero any new elements for ( int i = size; i < newSize; i++ ) { p[i] = 0.0f; } } } size = newSize; VECX_CLEAREND(); } ID_INLINE void idVecX::SetTempSize( int newSize ) { size = newSize; alloced = ( newSize + 3 ) & ~3; assert( alloced < VECX_MAX_TEMP ); if ( idVecX::tempIndex + alloced > VECX_MAX_TEMP ) { idVecX::tempIndex = 0; } p = idVecX::tempPtr + idVecX::tempIndex; idVecX::tempIndex += alloced; VECX_CLEAREND(); } ID_INLINE void idVecX::SetData( int length, float *data ) { if ( p && ( p < idVecX::tempPtr || p >= idVecX::tempPtr + VECX_MAX_TEMP ) && alloced != -1 ) { Mem_Free16( p ); } assert( ( ( (int) data ) & 15 ) == 0 ); // data must be 16 byte aligned p = data; size = length; alloced = -1; VECX_CLEAREND(); } ID_INLINE void idVecX::Zero( void ) { #ifdef VECX_SIMD SIMDProcessor->Zero16( p, size ); #else memset( p, 0, size * sizeof( float ) ); #endif } ID_INLINE void idVecX::Zero( int length ) { SetSize( length ); #ifdef VECX_SIMD SIMDProcessor->Zero16( p, length ); #else memset( p, 0, size * sizeof( float ) ); #endif } ID_INLINE void idVecX::Random( int seed, float l, float u ) { int i; float c; idRandom rnd( seed ); c = u - l; for ( i = 0; i < size; i++ ) { p[i] = l + rnd.RandomFloat() * c; } } ID_INLINE void idVecX::Random( int length, int seed, float l, float u ) { int i; float c; idRandom rnd( seed ); SetSize( length ); c = u - l; for ( i = 0; i < size; i++ ) { p[i] = l + rnd.RandomFloat() * c; } } ID_INLINE void idVecX::Negate( void ) { #ifdef VECX_SIMD SIMDProcessor->Negate16( p, size ); #else int i; for ( i = 0; i < size; i++ ) { p[i] = -p[i]; } #endif } ID_INLINE void idVecX::Clamp( float min, float max ) { int i; for ( i = 0; i < size; i++ ) { if ( p[i] < min ) { p[i] = min; } else if ( p[i] > max ) { p[i] = max; } } } ID_INLINE idVecX &idVecX::SwapElements( int e1, int e2 ) { float tmp; tmp = p[e1]; p[e1] = p[e2]; p[e2] = tmp; return *this; } ID_INLINE float idVecX::Length( void ) const { int i; float sum = 0.0f; for ( i = 0; i < size; i++ ) { sum += p[i] * p[i]; } return noMath::Sqrt( sum ); } ID_INLINE float idVecX::LengthSqr( void ) const { int i; float sum = 0.0f; for ( i = 0; i < size; i++ ) { sum += p[i] * p[i]; } return sum; } ID_INLINE idVecX idVecX::Normalize( void ) const { int i; idVecX m; float invSqrt, sum = 0.0f; m.SetTempSize( size ); for ( i = 0; i < size; i++ ) { sum += p[i] * p[i]; } invSqrt = noMath::InvSqrt( sum ); for ( i = 0; i < size; i++ ) { m.p[i] = p[i] * invSqrt; } return m; } ID_INLINE float idVecX::NormalizeSelf( void ) { float invSqrt, sum = 0.0f; int i; for ( i = 0; i < size; i++ ) { sum += p[i] * p[i]; } invSqrt = noMath::InvSqrt( sum ); for ( i = 0; i < size; i++ ) { p[i] *= invSqrt; } return invSqrt * sum; } ID_INLINE int idVecX::GetDimension( void ) const { return size; } ID_INLINE noVec3 &idVecX::SubVec3( int index ) { assert( index >= 0 && index * 3 + 3 <= size ); return *reinterpret_cast<noVec3 *>(p + index * 3); } ID_INLINE const noVec3 &idVecX::SubVec3( int index ) const { assert( index >= 0 && index * 3 + 3 <= size ); return *reinterpret_cast<const noVec3 *>(p + index * 3); } ID_INLINE idVec6 &idVecX::SubVec6( int index ) { assert( index >= 0 && index * 6 + 6 <= size ); return *reinterpret_cast<idVec6 *>(p + index * 6); } ID_INLINE const idVec6 &idVecX::SubVec6( int index ) const { assert( index >= 0 && index * 6 + 6 <= size ); return *reinterpret_cast<const idVec6 *>(p + index * 6); } ID_INLINE const float *idVecX::ToFloatPtr( void ) const { return p; } ID_INLINE float *idVecX::ToFloatPtr( void ) { return p; } //=============================================================== // // idPolar3 // //=============================================================== class idPolar3 { public: float radius, theta, phi; idPolar3( void ); explicit idPolar3( const float radius, const float theta, const float phi ); void Set( const float radius, const float theta, const float phi ); float operator[]( const int index ) const; float & operator[]( const int index ); idPolar3 operator-() const; idPolar3 & operator=( const idPolar3 &a ); noVec3 ToVec3( void ) const; }; ID_INLINE idPolar3::idPolar3( void ) { } ID_INLINE idPolar3::idPolar3( const float radius, const float theta, const float phi ) { assert( radius > 0 ); this->radius = radius; this->theta = theta; this->phi = phi; } ID_INLINE void idPolar3::Set( const float radius, const float theta, const float phi ) { assert( radius > 0 ); this->radius = radius; this->theta = theta; this->phi = phi; } ID_INLINE float idPolar3::operator[]( const int index ) const { return ( &radius )[ index ]; } ID_INLINE float &idPolar3::operator[]( const int index ) { return ( &radius )[ index ]; } ID_INLINE idPolar3 idPolar3::operator-() const { return idPolar3( radius, -theta, -phi ); } ID_INLINE idPolar3 &idPolar3::operator=( const idPolar3 &a ) { radius = a.radius; theta = a.theta; phi = a.phi; return *this; } ID_INLINE noVec3 idPolar3::ToVec3( void ) const { float sp, cp, st, ct; noMath::SinCos( phi, sp, cp ); noMath::SinCos( theta, st, ct ); return noVec3( cp * radius * ct, cp * radius * st, radius * sp ); } /* =============================================================================== Old 3D vector macros, should no longer be used. =============================================================================== */ #define DotProduct( a, b) ((a)[0]*(b)[0]+(a)[1]*(b)[1]+(a)[2]*(b)[2]) #define VectorSubtract2( a, b, c ) ((c)[0]=(a)[0]-(b)[0],(c)[1]=(a)[1]-(b)[1],(c)[2]=(a)[2]-(b)[2]) #define VectorAdd( a, b, c ) ((c)[0]=(a)[0]+(b)[0],(c)[1]=(a)[1]+(b)[1],(c)[2]=(a)[2]+(b)[2]) #define VectorScale( v, s, o ) ((o)[0]=(v)[0]*(s),(o)[1]=(v)[1]*(s),(o)[2]=(v)[2]*(s)) #define VectorMA( v, s, b, o ) ((o)[0]=(v)[0]+(b)[0]*(s),(o)[1]=(v)[1]+(b)[1]*(s),(o)[2]=(v)[2]+(b)[2]*(s)) #define VectorCopy( a, b ) ((b)[0]=(a)[0],(b)[1]=(a)[1],(b)[2]=(a)[2]) #endif /* !__MATH_VECTOR_H__ */
9384681a8ebcae72126edc49a2f1a1bd6af8758e
e132d5b086464fe0651223df74f06ff16dfbdcff
/example/doc/http_examples.hpp
4cd879ae33d50860d75cdddada4cbb427748f006
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
shibing/beast
fa1de3a19ecd1bf55120b92e4ebdf9cf99894f24
c495f946c92c1175d30e1e8e60d412c3a30025b4
refs/heads/develop
2021-01-02T22:56:23.222703
2017-08-03T15:53:12
2017-08-03T15:53:12
99,427,713
1
0
null
2017-08-05T14:29:21
2017-08-05T14:29:21
null
UTF-8
C++
false
false
35,802
hpp
// // Copyright (c) 2016-2017 Vinnie Falco (vinnie dot falco at gmail dot com) // // Distributed under 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) // // Official repository: https://github.com/boostorg/beast // #include <boost/beast.hpp> #include <iostream> /* This file contains the functions and classes found in the documentation They are compiled and run as part of the unit tests, so you can copy the code and use it in your own projects as a starting point for building a network application. */ // The documentation assumes the boost::beast::http namespace namespace boost { namespace beast { namespace http { //------------------------------------------------------------------------------ // // Example: Expect 100-continue // //------------------------------------------------------------------------------ //[example_http_send_expect_100_continue /** Send a request with Expect: 100-continue This function will send a request with the Expect: 100-continue field by first sending the header, then waiting for a successful response from the server before continuing to send the body. If a non-successful server response is received, the function returns immediately. @param stream The remote HTTP server stream. @param buffer The buffer used for reading. @param req The request to send. This function modifies the object: the Expect header field is inserted into the message if it does not already exist, and set to "100-continue". @param ec Set to the error, if any occurred. */ template< class SyncStream, class DynamicBuffer, class Body, class Allocator> void send_expect_100_continue( SyncStream& stream, DynamicBuffer& buffer, request<Body, basic_fields<Allocator>>& req, error_code& ec) { static_assert(is_sync_stream<SyncStream>::value, "SyncStream requirements not met"); static_assert(is_dynamic_buffer<DynamicBuffer>::value, "DynamicBuffer requirements not met"); // Insert or replace the Expect field req.set(field::expect, "100-continue"); // Create the serializer request_serializer<Body, basic_fields<Allocator>> sr{req}; // Send just the header write_header(stream, sr, ec); if(ec) return; // Read the response from the server. // A robust client could set a timeout here. { response<string_body> res; read(stream, buffer, res, ec); if(ec) return; if(res.result() != status::continue_) { // The server indicated that it will not // accept the request, so skip sending the body. return; } } // Server is OK with the request, send the body write(stream, sr, ec); } //] //[example_http_receive_expect_100_continue /** Receive a request, handling Expect: 100-continue if present. This function will read a request from the specified stream. If the request contains the Expect: 100-continue field, a status response will be delivered. @param stream The remote HTTP client stream. @param buffer The buffer used for reading. @param ec Set to the error, if any occurred. */ template< class SyncStream, class DynamicBuffer> void receive_expect_100_continue( SyncStream& stream, DynamicBuffer& buffer, error_code& ec) { static_assert(is_sync_stream<SyncStream>::value, "SyncStream requirements not met"); static_assert(is_dynamic_buffer<DynamicBuffer>::value, "DynamicBuffer requirements not met"); // Declare a parser for a request with a string body request_parser<string_body> parser; // Read the header read_header(stream, buffer, parser, ec); if(ec) return; // Check for the Expect field value if(parser.get()[field::expect] == "100-continue") { // send 100 response response<empty_body> res; res.version = 11; res.result(status::continue_); res.set(field::server, "test"); write(stream, res, ec); if(ec) return; } // Read the rest of the message. // // We use parser.base() to return a basic_parser&, to avoid an // ambiguous function error (from boost::asio::read). Another // solution is to qualify the call, e.g. `beast::http::read` // read(stream, buffer, parser.base(), ec); } //] //------------------------------------------------------------------------------ // // Example: Send Child Process Output // //------------------------------------------------------------------------------ //[example_http_send_cgi_response /** Send the output of a child process as an HTTP response. The output of the child process comes from a @b SyncReadStream. Data will be sent continuously as it is produced, without the requirement that the entire process output is buffered before being sent. The response will use the chunked transfer encoding. @param input A stream to read the child process output from. @param output A stream to write the HTTP response to. @param ec Set to the error, if any occurred. */ template< class SyncReadStream, class SyncWriteStream> void send_cgi_response( SyncReadStream& input, SyncWriteStream& output, error_code& ec) { static_assert(is_sync_read_stream<SyncReadStream>::value, "SyncReadStream requirements not met"); static_assert(is_sync_write_stream<SyncWriteStream>::value, "SyncWriteStream requirements not met"); using boost::asio::buffer_cast; using boost::asio::buffer_size; // Set up the response. We use the buffer_body type, // allowing serialization to use manually provided buffers. response<buffer_body> res; res.result(status::ok); res.version = 11; res.set(field::server, "Beast"); res.set(field::transfer_encoding, "chunked"); // No data yet, but we set more = true to indicate // that it might be coming later. Otherwise the // serializer::is_done would return true right after // sending the header. res.body.data = nullptr; res.body.more = true; // Create the serializer. response_serializer<buffer_body, fields> sr{res}; // Send the header immediately. write_header(output, sr, ec); if(ec) return; // Alternate between reading from the child process // and sending all the process output until there // is no more output. do { // Read a buffer from the child process char buffer[2048]; auto bytes_transferred = input.read_some( boost::asio::buffer(buffer, sizeof(buffer)), ec); if(ec == boost::asio::error::eof) { ec = {}; // `nullptr` indicates there is no buffer res.body.data = nullptr; // `false` means no more data is coming res.body.more = false; } else { if(ec) return; // Point to our buffer with the bytes that // we received, and indicate that there may // be some more data coming res.body.data = buffer; res.body.size = bytes_transferred; res.body.more = true; } // Write everything in the body buffer write(output, sr, ec); // This error is returned by body_buffer during // serialization when it is done sending the data // provided and needs another buffer. if(ec == error::need_buffer) { ec = {}; continue; } if(ec) return; } while(! sr.is_done()); } //] //-------------------------------------------------------------------------- // // Example: HEAD Request // //-------------------------------------------------------------------------- //[example_http_do_head_response /** Handle a HEAD request for a resource. */ template< class SyncStream, class DynamicBuffer > void do_server_head( SyncStream& stream, DynamicBuffer& buffer, error_code& ec) { static_assert(is_sync_stream<SyncStream>::value, "SyncStream requirements not met"); static_assert(is_dynamic_buffer<DynamicBuffer>::value, "DynamicBuffer requirments not met"); // We deliver this payload for all GET requests static std::string const payload = "Hello, world!"; // Read the request request<string_body> req; read(stream, buffer, req, ec); if(ec) return; // Set up the response, starting with the common fields response<string_body> res; res.version = 11; res.set(field::server, "test"); // Now handle request-specific fields switch(req.method()) { case verb::head: case verb::get: { // A HEAD request is handled by delivering the same // set of headers that would be sent for a GET request, // including the Content-Length, except for the body. res.result(status::ok); res.set(field::content_length, payload.size()); // For GET requests, we include the body if(req.method() == verb::get) { // We deliver the same payload for GET requests // regardless of the target. A real server might // deliver a file based on the target. res.body = payload; } break; } default: { // We return responses indicating an error if // we do not recognize the request method. res.result(status::bad_request); res.set(field::content_type, "text/plain"); res.body = "Invalid request-method '" + req.method_string().to_string() + "'"; res.prepare_payload(); break; } } // Send the response write(stream, res, ec); if(ec) return; } //] //[example_http_do_head_request /** Send a HEAD request for a resource. This function submits a HEAD request for the specified resource and returns the response. @param res The response. This is an output parameter. @param stream The synchronous stream to use. @param buffer The buffer to use. @param target The request target. @param ec Set to the error, if any occurred. @throws std::invalid_argument if target is empty. */ template< class SyncStream, class DynamicBuffer > response<empty_body> do_head_request( SyncStream& stream, DynamicBuffer& buffer, string_view target, error_code& ec) { // Do some type checking to be a good citizen static_assert(is_sync_stream<SyncStream>::value, "SyncStream requirements not met"); static_assert(is_dynamic_buffer<DynamicBuffer>::value, "DynamicBuffer requirments not met"); // The interfaces we are using are low level and do not // perform any checking of arguments; so we do it here. if(target.empty()) throw std::invalid_argument("target may not be empty"); // Build the HEAD request for the target request<empty_body> req; req.version = 11; req.method(verb::head); req.target(target); req.set(field::user_agent, "test"); // A client MUST send a Host header field in all HTTP/1.1 request messages. // https://tools.ietf.org/html/rfc7230#section-5.4 req.set(field::host, "localhost"); // Now send it write(stream, req, ec); if(ec) return {}; // Create a parser to read the response. // Responses to HEAD requests MUST NOT include // a body, so we use the `empty_body` type and // only attempt to read the header. parser<false, empty_body> p; read_header(stream, buffer, p, ec); if(ec) return {}; // Transfer ownership of the response to the caller. return p.release(); } //] //------------------------------------------------------------------------------ // // Example: HTTP Relay // //------------------------------------------------------------------------------ //[example_http_relay /** Relay an HTTP message. This function efficiently relays an HTTP message from a downstream client to an upstream server, or from an upstream server to a downstream client. After the message header is read from the input, a user provided transformation function is invoked which may change the contents of the header before forwarding to the output. This may be used to adjust fields such as Server, or proxy fields. @param output The stream to write to. @param input The stream to read from. @param buffer The buffer to use for the input. @param transform The header transformation to apply. The function will be called with this signature: @code template<class Body> void transform(message< isRequest, Body, Fields>&, // The message to transform error_code&); // Set to the error, if any @endcode @param ec Set to the error if any occurred. @tparam isRequest `true` to relay a request. @tparam Fields The type of fields to use for the message. */ template< bool isRequest, class SyncWriteStream, class SyncReadStream, class DynamicBuffer, class Transform> void relay( SyncWriteStream& output, SyncReadStream& input, DynamicBuffer& buffer, error_code& ec, Transform&& transform) { static_assert(is_sync_write_stream<SyncWriteStream>::value, "SyncWriteStream requirements not met"); static_assert(is_sync_read_stream<SyncReadStream>::value, "SyncReadStream requirements not met"); // A small buffer for relaying the body piece by piece char buf[2048]; // Create a parser with a buffer body to read from the input. parser<isRequest, buffer_body> p; // Create a serializer from the message contained in the parser. serializer<isRequest, buffer_body, fields> sr{p.get()}; // Read just the header from the input read_header(input, buffer, p, ec); if(ec) return; // Apply the caller's header tranformation transform(p.get(), ec); if(ec) return; // Send the transformed message to the output write_header(output, sr, ec); if(ec) return; // Loop over the input and transfer it to the output do { if(! p.is_done()) { // Set up the body for writing into our small buffer p.get().body.data = buf; p.get().body.size = sizeof(buf); // Read as much as we can read(input, buffer, p, ec); // This error is returned when buffer_body uses up the buffer if(ec == error::need_buffer) ec = {}; if(ec) return; // Set up the body for reading. // This is how much was parsed: p.get().body.size = sizeof(buf) - p.get().body.size; p.get().body.data = buf; p.get().body.more = ! p.is_done(); } else { p.get().body.data = nullptr; p.get().body.size = 0; } // Write everything in the buffer (which might be empty) write(output, sr, ec); // This error is returned when buffer_body uses up the buffer if(ec == error::need_buffer) ec = {}; if(ec) return; } while(! p.is_done() && ! sr.is_done()); } //] //------------------------------------------------------------------------------ // // Example: Serialize to std::ostream // //------------------------------------------------------------------------------ //[example_http_write_ostream // The detail namespace means "not public" namespace detail { // This helper is needed for C++11. // When invoked with a buffer sequence, writes the buffers `to the std::ostream`. template<class Serializer> class write_ostream_helper { Serializer& sr_; std::ostream& os_; public: write_ostream_helper(Serializer& sr, std::ostream& os) : sr_(sr) , os_(os) { } // This function is called by the serializer template<class ConstBufferSequence> void operator()(error_code& ec, ConstBufferSequence const& buffers) const { // These asio functions are needed to access a buffer's contents using boost::asio::buffer_cast; using boost::asio::buffer_size; // Error codes must be cleared on success ec = {}; // Keep a running total of how much we wrote std::size_t bytes_transferred = 0; // Loop over the buffer sequence for(auto it = buffers.begin(); it != buffers.end(); ++ it) { // This is the next buffer in the sequence boost::asio::const_buffer const buffer = *it; // Write it to the std::ostream os_.write( buffer_cast<char const*>(buffer), buffer_size(buffer)); // If the std::ostream fails, convert it to an error code if(os_.fail()) { ec = make_error_code(errc::io_error); return; } // Adjust our running total bytes_transferred += buffer_size(buffer); } // Inform the serializer of the amount we consumed sr_.consume(bytes_transferred); } }; } // detail /** Write a message to a `std::ostream`. This function writes the serialized representation of the HTTP/1 message to the sream. @param os The `std::ostream` to write to. @param msg The message to serialize. @param ec Set to the error, if any occurred. */ template< bool isRequest, class Body, class Fields> void write_ostream( std::ostream& os, message<isRequest, Body, Fields>& msg, error_code& ec) { // Create the serializer instance serializer<isRequest, Body, Fields> sr{msg}; // This lambda is used as the "visit" function detail::write_ostream_helper<decltype(sr)> lambda{sr, os}; do { // In C++14 we could use a generic lambda but since we want // to require only C++11, the lambda is written out by hand. // This function call retrieves the next serialized buffers. sr.next(ec, lambda); if(ec) return; } while(! sr.is_done()); } //] //------------------------------------------------------------------------------ // // Example: Parse from std::istream // //------------------------------------------------------------------------------ //[example_http_read_istream /** Read a message from a `std::istream`. This function attempts to parse a complete HTTP/1 message from the stream. @param is The `std::istream` to read from. @param buffer The buffer to use. @param msg The message to store the result. @param ec Set to the error, if any occurred. */ template< class Allocator, bool isRequest, class Body> void read_istream( std::istream& is, basic_flat_buffer<Allocator>& buffer, message<isRequest, Body, fields>& msg, error_code& ec) { // Create the message parser // // Arguments passed to the parser's constructor are // forwarded to the message constructor. Here, we use // a move construction in case the caller has constructed // their message in a non-default way. // parser<isRequest, Body> p{std::move(msg)}; do { // Extract whatever characters are presently available in the istream if(is.rdbuf()->in_avail() > 0) { // Get a mutable buffer sequence for writing auto const mb = buffer.prepare( static_cast<std::size_t>(is.rdbuf()->in_avail())); // Now get everything we can from the istream buffer.commit(static_cast<std::size_t>(is.readsome( boost::asio::buffer_cast<char*>(mb), boost::asio::buffer_size(mb)))); } else if(buffer.size() == 0) { // Our buffer is empty and we need more characters, // see if we've reached the end of file on the istream if(! is.eof()) { // Get a mutable buffer sequence for writing auto const mb = buffer.prepare(1024); // Try to get more from the istream. This might block. is.read( boost::asio::buffer_cast<char*>(mb), boost::asio::buffer_size(mb)); // If an error occurs on the istream then return it to the caller. if(is.fail() && ! is.eof()) { // We'll just re-use io_error since std::istream has no error_code interface. ec = make_error_code(errc::io_error); return; } // Commit the characters we got to the buffer. buffer.commit(static_cast<std::size_t>(is.gcount())); } else { // Inform the parser that we've reached the end of the istream. p.put_eof(ec); if(ec) return; break; } } // Write the data to the parser auto const bytes_used = p.put(buffer.data(), ec); // This error means that the parser needs additional octets. if(ec == error::need_more) ec = {}; if(ec) return; // Consume the buffer octets that were actually parsed. buffer.consume(bytes_used); } while(! p.is_done()); // Transfer ownership of the message container in the parser to the caller. msg = p.release(); } //] //------------------------------------------------------------------------------ // // Example: Deferred Body Type // //------------------------------------------------------------------------------ //[example_http_defer_body /** Handle a form POST request, choosing a body type depending on the Content-Type. This reads a request from the input stream. If the method is POST, and the Content-Type is "application/x-www-form-urlencoded " or "multipart/form-data", a `string_body` is used to receive and store the message body. Otherwise, a `dynamic_body` is used to store the message body. After the request is received, the handler will be invoked with the request. @param stream The stream to read from. @param buffer The buffer to use for reading. @param handler The handler to invoke when the request is complete. The handler must be invokable with this signature: @code template<class Body> void handler(request<Body>&& req); @endcode @throws system_error Thrown on failure. */ template< class SyncReadStream, class DynamicBuffer, class Handler> void do_form_request( SyncReadStream& stream, DynamicBuffer& buffer, Handler&& handler) { // Start with an empty_body parser request_parser<empty_body> req0; // Read just the header. Otherwise, the empty_body // would generate an error if body octets were received. read_header(stream, buffer, req0); // Choose a body depending on the method verb switch(req0.get().method()) { case verb::post: { // If this is not a form upload then use a string_body if( req0.get()[field::content_type] != "application/x-www-form-urlencoded" && req0.get()[field::content_type] != "multipart/form-data") goto do_dynamic_body; // Commit to string_body as the body type. // As long as there are no body octets in the parser // we are constructing from, no exception is thrown. request_parser<string_body> req{std::move(req0)}; // Finish reading the message read(stream, buffer, req); // Call the handler. It can take ownership // if desired, since we are calling release() handler(req.release()); break; } do_dynamic_body: default: { // Commit to dynamic_body as the body type. // As long as there are no body octets in the parser // we are constructing from, no exception is thrown. request_parser<dynamic_body> req{std::move(req0)}; // Finish reading the message read(stream, buffer, req); // Call the handler. It can take ownership // if desired, since we are calling release() handler(req.release()); break; } } } //] //------------------------------------------------------------------------------ // // Example: Custom Parser // //------------------------------------------------------------------------------ //[example_http_custom_parser template<bool isRequest> class custom_parser : public basic_parser<isRequest, custom_parser<isRequest>> { private: // The friend declaration is needed, // otherwise the callbacks must be made public. friend class basic_parser<isRequest, custom_parser>; /// Called after receiving the request-line (isRequest == true). void on_request_impl( verb method, // The method verb, verb::unknown if no match string_view method_str, // The method as a string string_view target, // The request-target int version, // The HTTP-version error_code& ec); // The error returned to the caller, if any /// Called after receiving the start-line (isRequest == false). void on_response_impl( int code, // The status-code string_view reason, // The obsolete reason-phrase int version, // The HTTP-version error_code& ec); // The error returned to the caller, if any /// Called after receiving a header field. void on_field_impl( field f, // The known-field enumeration constant string_view name, // The field name string. string_view value, // The field value error_code& ec); // The error returned to the caller, if any /// Called after the complete header is received. void on_header_impl( error_code& ec); // The error returned to the caller, if any /// Called just before processing the body, if a body exists. void on_body_init_impl( boost::optional< std::uint64_t> const& content_length, // Content length if known, else `boost::none` error_code& ec); // The error returned to the caller, if any /// Called for each piece of the body, if a body exists. //! //! This is used when there is no chunked transfer coding. //! //! The function returns the number of bytes consumed from the //! input buffer. Any input octets not consumed will be will be //! presented on subsequent calls. //! std::size_t on_body_impl( string_view s, // A portion of the body error_code& ec); // The error returned to the caller, if any /// Called for each chunk header. void on_chunk_header_impl( std::uint64_t size, // The size of the upcoming chunk, // or zero for the last chunk string_view extension, // The chunk extensions (may be empty) error_code& ec); // The error returned to the caller, if any /// Called to deliver the chunk body. //! //! This is used when there is a chunked transfer coding. The //! implementation will automatically remove the encoding before //! calling this function. //! //! The function returns the number of bytes consumed from the //! input buffer. Any input octets not consumed will be will be //! presented on subsequent calls. //! std::size_t on_chunk_body_impl( std::uint64_t remain, // The number of bytes remaining in the chunk, // including what is being passed here. // or zero for the last chunk string_view body, // The next piece of the chunk body error_code& ec); // The error returned to the caller, if any /// Called when the complete message is parsed. void on_finish_impl(error_code& ec); public: custom_parser() = default; }; //] // Definitions are not part of the docs but necessary to link template<bool isRequest> void custom_parser<isRequest>:: on_request_impl(verb method, string_view method_str, string_view path, int version, error_code& ec) { boost::ignore_unused(method, method_str, path, version); ec = {}; } template<bool isRequest> void custom_parser<isRequest>:: on_response_impl( int status, string_view reason, int version, error_code& ec) { boost::ignore_unused(status, reason, version); ec = {}; } template<bool isRequest> void custom_parser<isRequest>:: on_field_impl( field f, string_view name, string_view value, error_code& ec) { boost::ignore_unused(f, name, value); ec = {}; } template<bool isRequest> void custom_parser<isRequest>:: on_header_impl(error_code& ec) { ec = {}; } template<bool isRequest> void custom_parser<isRequest>:: on_body_init_impl( boost::optional<std::uint64_t> const& content_length, error_code& ec) { boost::ignore_unused(content_length); ec = {}; } template<bool isRequest> std::size_t custom_parser<isRequest>:: on_body_impl(string_view body, error_code& ec) { boost::ignore_unused(body); ec = {}; return body.size(); } template<bool isRequest> void custom_parser<isRequest>:: on_chunk_header_impl( std::uint64_t size, string_view extension, error_code& ec) { boost::ignore_unused(size, extension); ec = {}; } template<bool isRequest> std::size_t custom_parser<isRequest>:: on_chunk_body_impl( std::uint64_t remain, string_view body, error_code& ec) { boost::ignore_unused(remain); ec = {}; return body.size(); } template<bool isRequest> void custom_parser<isRequest>:: on_finish_impl(error_code& ec) { ec = {}; } //------------------------------------------------------------------------------ // // Example: Incremental Read // //------------------------------------------------------------------------------ //[example_incremental_read /* This function reads a message using a fixed size buffer to hold portions of the body, and prints the body contents to a `std::ostream`. */ template< bool isRequest, class SyncReadStream, class DynamicBuffer> void read_and_print_body( std::ostream& os, SyncReadStream& stream, DynamicBuffer& buffer, error_code& ec) { parser<isRequest, buffer_body> p; read_header(stream, buffer, p, ec); if(ec) return; while(! p.is_done()) { char buf[512]; p.get().body.data = buf; p.get().body.size = sizeof(buf); read(stream, buffer, p, ec); if(ec == error::need_buffer) ec.assign(0, ec.category()); if(ec) return; os.write(buf, sizeof(buf) - p.get().body.size); } } //] //------------------------------------------------------------------------------ // // Example: Expect 100-continue // //------------------------------------------------------------------------------ //[example_chunk_parsing /** Read a message with a chunked body and print the chunks and extensions */ template< bool isRequest, class SyncReadStream, class DynamicBuffer> void print_chunked_body( std::ostream& os, SyncReadStream& stream, DynamicBuffer& buffer, error_code& ec) { // Declare the parser with an empty body since // we plan on capturing the chunks ourselves. parser<isRequest, empty_body> p; // First read the complete header read_header(stream, buffer, p, ec); if(ec) return; // This container will hold the extensions for each chunk chunk_extensions ce; // This string will hold the body of each chunk std::string chunk; // Declare our chunk header callback This is invoked // after each chunk header and also after the last chunk. auto header_cb = [&](std::uint64_t size, // Size of the chunk, or zero for the last chunk string_view extensions, // The raw chunk-extensions string. Already validated. error_code& ev) // We can set this to indicate an error { // Parse the chunk extensions so we can access them easily ce.parse(extensions, ev); if(ev) return; // See if the chunk is too big if(size > (std::numeric_limits<std::size_t>::max)()) { ev = error::body_limit; return; } // Make sure we have enough storage, and // reset the container for the upcoming chunk chunk.reserve(static_cast<std::size_t>(size)); chunk.clear(); }; // Set the callback. The function requires a non-const reference so we // use a local variable, since temporaries can only bind to const refs. p.on_chunk_header(header_cb); // Declare the chunk body callback. This is called one or // more times for each piece of a chunk body. auto body_cb = [&](std::uint64_t remain, // The number of bytes left in this chunk string_view body, // A buffer holding chunk body data error_code& ec) // We can set this to indicate an error { // If this is the last piece of the chunk body, // set the error so that the call to `read` returns // and we can process the chunk. if(remain == body.size()) ec = error::end_of_chunk; // Append this piece to our container chunk.append(body.data(), body.size()); // The return value informs the parser of how much of the body we // consumed. We will indicate that we consumed everything passed in. return body.size(); }; p.on_chunk_body(body_cb); while(! p.is_done()) { // Read as much as we can. When we reach the end of the chunk, the chunk // body callback will make the read return with the end_of_chunk error. read(stream, buffer, p, ec); if(! ec) continue; else if(ec != error::end_of_chunk) return; else ec.assign(0, ec.category()); // We got a whole chunk, print the extensions: for(auto const& extension : ce) { os << "Extension: " << extension.first; if(! extension.second.empty()) os << " = " << extension.second << std::endl; else os << std::endl; } // Now print the chunk body os << "Chunk Body: " << chunk << std::endl; } // Get a reference to the parsed message, this is for convenience auto const& msg = p.get(); // Check each field promised in the "Trailer" header and output it for(auto const& name : token_list{msg[field::trailer]}) { // Find the trailer field auto it = msg.find(name); if(it == msg.end()) { // Oops! They promised the field but failed to deliver it os << "Missing Trailer: " << name << std::endl; continue; } os << it->name() << ": " << it->value() << std::endl; } } //] } // http } // beast } // boost
9fa549d7c479e9418d7f48cb50f14396236411bc
c91ba4e746dc5b8f2dface963b4096dd721070fd
/cloudphoto/src/model/MoveFacePhotosRequest.cc
ab2ba117f0126dd59750145ec9bc9a204beed98f
[ "Apache-2.0" ]
permissive
IthacaDream/aliyun-openapi-cpp-sdk
fa9120604ca3af4fc48a5f9bf70ff10542103c3a
31a064d1568f59e0731485a1b0452cfd5d767e42
refs/heads/master
2021-09-05T09:44:19.244166
2018-01-26T07:00:14
2018-01-26T07:00:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,202
cc
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/cloudphoto/model/MoveFacePhotosRequest.h> using namespace AlibabaCloud::CloudPhoto; using namespace AlibabaCloud::CloudPhoto::Model; MoveFacePhotosRequest::MoveFacePhotosRequest() : CloudPhotoRequest("MoveFacePhotos") {} MoveFacePhotosRequest::~MoveFacePhotosRequest() {} std::string MoveFacePhotosRequest::getLibraryId()const { return libraryId_; } void MoveFacePhotosRequest::setLibraryId(const std::string& libraryId) { libraryId_ = libraryId; setParameter("LibraryId", libraryId); } long MoveFacePhotosRequest::getTargetFaceId()const { return targetFaceId_; } void MoveFacePhotosRequest::setTargetFaceId(long targetFaceId) { targetFaceId_ = targetFaceId; setParameter("TargetFaceId", std::to_string(targetFaceId)); } std::vector<long> MoveFacePhotosRequest::getPhotoId()const { return photoId_; } void MoveFacePhotosRequest::setPhotoId(const std::vector<long>& photoId) { photoId_ = photoId; for(int i = 0; i!= photoId.size(); i++) setParameter("PhotoId."+ std::to_string(i), std::to_string(photoId.at(i))); } std::string MoveFacePhotosRequest::getStoreName()const { return storeName_; } void MoveFacePhotosRequest::setStoreName(const std::string& storeName) { storeName_ = storeName; setParameter("StoreName", storeName); } long MoveFacePhotosRequest::getSourceFaceId()const { return sourceFaceId_; } void MoveFacePhotosRequest::setSourceFaceId(long sourceFaceId) { sourceFaceId_ = sourceFaceId; setParameter("SourceFaceId", std::to_string(sourceFaceId)); }
df0e75c34d981106db95b88c53ab048107aa75b8
ae9ff784b524610de9abebea61a59df1152c3aad
/CH07/01.cpp
21b70cf02fa821555814d24060c2081ca1ec4015
[]
no_license
headmastersquall/Cpp
489ea7757d9b0a64b929fece3b1152121f69cdc8
daca75461ca00bb9f5af7550554e32d024d335d8
refs/heads/master
2020-05-17T22:39:57.086887
2015-11-09T20:12:31
2015-11-09T20:12:31
42,877,932
0
1
null
null
null
null
UTF-8
C++
false
false
979
cpp
/* * 01. Larges/Smallest Array Values * * Fill an array with user input, then show the smallest and largest values. */ #include <iostream> #include <string> using namespace std; int intPrompt(string prompt); void findAndShowSmallLarge(int [], int); int main() { const int NUMBER_COUNT = 10; const string PROMPT = "Enter a number: "; int numbers[NUMBER_COUNT]; for (int i = 0; i < NUMBER_COUNT; i++) { numbers[i] = intPrompt(PROMPT); } findAndShowSmallLarge(numbers, NUMBER_COUNT); return 0; } int intPrompt(const string prompt) { int value; cout << prompt; cin >> value; return value; } void findAndShowSmallLarge(int nums[], const int size) { int smallest = nums[0]; int largest = nums[0]; for (int i = 0; i < size; i++) { smallest = nums[i] < smallest ? nums[i] : smallest; largest = nums[i] > largest ? nums[i] : largest; } cout << "The largest number is: " << largest << endl; cout << "The smallest number is: " << smallest << endl; }
2430b1ec358eb5b946d7ac14b066074c7491392d
0c4bd1b977cc714a8a6b2839f51c4247ecfd32b1
/C++/miniNN/util.h
b0b6484b5f1b014ca43160112e7720641e56a53f
[]
no_license
ishine/neuralLOGIC
281d498b40159308815cee6327e6cf79c9426b16
3eb3b9980e7f7a7d87a77ef40b1794fb5137c459
refs/heads/master
2020-08-14T14:11:54.487922
2019-10-14T05:32:53
2019-10-14T05:32:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,412
h
#ifndef UTIL_H_ #define UTIL_H_ #include <sstream> #include <iostream> #include <vector> void usage(void **argtable, const char *progname) { FILE *fp = stdout; fprintf(fp, "Usage: %s ", progname); arg_print_syntaxv(fp, argtable, "\n"); arg_print_glossary(fp, argtable, " %-50s %s\n"); } template<class T> std::string vectorToString(const std::vector<T>& v) { std::stringstream ss; for (size_t i = 0; i < v.size(); ++i) { if (i > 0) { ss << " "; } ss << v[i]; } return ss.str(); } template<class T> inline std::string to_string(const T& t) { std::stringstream ss; ss << t; return ss.str(); } void progress(const size_t iter, const size_t corpus_size, const size_t speed, const bool force = false) { const size_t true_iter = iter % corpus_size; if (true_iter > 0 && true_iter % speed == 0) { std::cerr << "."; std::cerr.flush(); } if ((true_iter > 0 && true_iter % (50 * speed) == 0) != (force)) { std::cerr << "[" << iter % corpus_size << "]" << std::endl; std::cerr.flush(); } } template<class T> void printVector(const std::vector<T>& v, const double threshold=0.5, const bool verbose=false) { for (size_t i = 0; i < v.size(); ++i) { if (i > 0) { std::cout << " "; } std::cout << (v.at(i) > threshold); if (verbose) std::cout << " (" << v.at(i) << ")"; } std::cout << std::endl; } #endif /* UTIL_H_ */
d55b6eacb4ce537ffa0a602ccdf7627f9cb28155
e7006ef73d6ce0be377f81009ce82ca736ed7ef9
/unit_tests/TestElementQueue.cpp
ce1c90919ed018c44d12e2a1150d65654c0b3321
[]
no_license
mitikkak/KayakLogger
4ba509ad2944938e379bfbf6bf69070a0834d19c
4a85f59ef9be6515e4a15dbb9a6f849055cf95c5
refs/heads/master
2022-05-21T17:54:23.973524
2019-05-03T19:34:40
2019-05-03T19:34:40
38,321,895
0
1
null
null
null
null
UTF-8
C++
false
false
298
cpp
#include <gtest/gtest.h> #include <fstream> using namespace std; #include "ElementQueue.h" class TestElementQueue : public ::testing::Test { public: TestElementQueue() {} void SetUp() { } void TearDown() { } }; TEST_F(TestElementQueue, construct) { ElementQueue q; }
3e160237969fb0f9af72ac627bacd4c29e7a8098
58fbf85bc2dda72606c01cd2cd191bc0bc9fa7c2
/Source/Army/Public/Operation/ArmyFacsimileOperation.h
74a6195d2383a32da86c213fac53536bbf7f0f73
[]
no_license
myl2232/ArmyEngineSimulation
497d2affb2786af9aa0a0295cf98cc4377b87ca4
353f3ec93cb352d49ce95825bb2ffdcc678119cf
refs/heads/master
2020-11-26T07:03:36.383628
2019-12-20T09:48:18
2019-12-20T09:48:18
228,996,622
0
4
null
null
null
null
UTF-8
C++
false
false
928
h
#pragma once #include "ArmyOperation.h" class FArmyFacsimileOperation : public FArmyOperation { public: FArmyFacsimileOperation(EModelType InBelongModel); virtual ~FArmyFacsimileOperation() {} //~ Begin IArmyDrawHelper Interface virtual void DrawHUD(class UArmyEditorViewportClient* InViewPortClient, FViewport* ViewPort, const FSceneView* View, FCanvas* Canvas) override; virtual void BeginOperation(XRArgument InArg /* = XRArgument() */) override; virtual void EndOperation() override; virtual void Tick() override; virtual bool InputKey(class UArmyEditorViewportClient* InViewPortClient, class FViewport* InViewPort, FKey Key, EInputEvent Event) override; void ShowInputScaleWindow(); /** 设置比例尺 */ void SetFacsimileScale(int32 InScale); private: int32 CurrentState; FVector2D FacsimileStartPos; FVector2D FacsimileEndPos; TSharedPtr<class SArmyEditableNumberBox> ENB_ScaleValue; };
bc81c1cb857cd26b214a85033c6f9f7779b90f5e
adbc6eb4bdd5da47b4d35dd023d0a2e0505ed4e7
/src/ClassifiedObject.hh
e04382f5bf5e8cae0ce325bc74ade308b3aeab1d
[ "BSD-3-Clause" ]
permissive
michaeljones/alembic-fs
b57c10eed89fbff9ff22b30daf3cac4d97773dc8
765b51774e40b0a5656e9f59338539f5b11f3e4b
refs/heads/master
2021-01-13T02:26:05.177303
2011-11-26T05:30:27
2011-11-26T05:30:27
2,580,651
12
0
null
null
null
null
UTF-8
C++
false
false
906
hh
#ifndef ALEMBICFS_CLASSIFIEDOBJECT_HH #define ALEMBICFS_CLASSIFIEDOBJECT_HH #include "Types.hh" #include <Alembic/AbcCoreAbstract/All.h> #include <Alembic/AbcCoreHDF5/All.h> #include <Alembic/AbcGeom/All.h> class ClassifiedObject { public: enum Classification { kObject = 0, kProperties, kProperty }; public: ClassifiedObject( Alembic::AbcGeom::IObject _iObj, Classification _classification ) : iObj( _iObj ), classification( _classification ) {} ClassifiedObject( Alembic::AbcGeom::IObject _iObj, Classification _classification, PathSegments& _remainder ) : iObj( _iObj ), classification( _classification ), remainder( _remainder ) {} Alembic::AbcGeom::IObject iObj; Classification classification; PathSegments remainder; }; #endif // ALEMBICFS_CLASSIFIEDOBJECT_HH
0702d878c403f11e0458643d021bf57a173bb627
cbba3f1e70472d928e71ad39c4fc38a1a9cc1c66
/Baekjoon/15686.치킨 배달.cpp
60f16ce4ccaf61249dde58e9be4905cb04310830
[]
no_license
giraffeJ/baekjoon
0a02ffcc0228477859acad8cdf5dee3ba3d725af
dbbf11f7dd8d61520f63ec5b4ed3f3087be3c981
refs/heads/master
2020-04-14T11:40:14.878856
2019-04-12T10:42:56
2019-04-12T10:42:56
163,820,326
0
0
null
null
null
null
UTF-8
C++
false
false
1,869
cpp
#include<stdio.h> int n, m, h, c, res=2100000000; int min(int a, int b) { return a < b ? a : b; } struct co { int x; int y; }; co home[110], chicken[15]; int map[60][60], distance[15][110], index[60][60], q[3][100001], chosen[15]; void get_input() { scanf("%d %d", &n, &m); for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { scanf("%d", &map[i][j]); if (map[i][j] == 1) { home[++h] = { i, j }; index[i][j] = h; } if (map[i][j] == 2) { chicken[++c] = { i, j }; index[i][j] = c; } } } } int dx[5] = { 0, -1, 0, 1, 0 }; int dy[5] = { 0, 0, 1, 0, -1 }; void bfs(int ind) { int dis[60][60], ch[60][60] = { {0,} } , r, f, x, y, nx, ny; r = f = 0; q[0][++r] = chicken[ind].x; q[1][r] = chicken[ind].y; dis[chicken[ind].x][chicken[ind].y] = 0; while (r > f) { x = q[0][++f]; y = q[1][f]; for (int i = 1; i <= 4; i++) { nx = x + dx[i]; ny = y + dy[i]; if (ch[nx][ny] == 1 || nx==0 || nx==n+1 || ny==0 || ny==n+1) continue; q[0][++r] = nx; q[1][r] = ny; dis[nx][ny] = dis[x][y] + 1; ch[nx][ny] = 1; } } for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { if (map[i][j] == 1) { distance[ind][index[i][j]] = dis[i][j]; } } } } void get_distance() { for (int i = 1; i <= c; i++) { bfs(i); } } int calc_chicken_distance() { int sum = 0; for (int i = 1; i <= h; i++) { int min_ = 99999; for (int j = 1; j <= c; j++) { if (chosen[j] == 0) continue; min_ = min(min_, distance[j][i]); } sum += min_; } return sum; } void choose_chicken(int pos, int num) { if (pos == c + 1) { res = min(res, calc_chicken_distance()); return; } choose_chicken(pos + 1, num); if (num == m) return; chosen[pos] = 1; choose_chicken(pos + 1, num + 1); chosen[pos] = 0; } int main() { get_input(); get_distance(); choose_chicken(1, 0); printf("%d\n", res); }
54f54820ba62c040f9cb8d161804e7a0c2a424b3
3dca132fe1adbb7316aee2030a6ae6fa0cc696aa
/hw1/src/DFA.cpp
8692dfb4fcb2dc6e9e3878501b11cbd919118777
[ "Apache-2.0" ]
permissive
leesk0502/compiler-homework
ebfe74d42f8d89cadc5da41615b388b1feae47f4
395cf718698f1bc24838d2a986655e7778d6546e
refs/heads/master
2021-06-28T01:27:06.826858
2017-09-17T18:11:38
2017-09-17T18:11:38
103,850,803
0
0
null
null
null
null
UTF-8
C++
false
false
3,659
cpp
#include "DFA.h" using namespace std; void DFA::buildNfaToDfa(vector<NfaData> table) { for(int i=0; i<table.size(); i++){ bool is_end = epsilonClosure(table, table[i], table[i].my_state); if( table[i].value == "e" && find( closure[table[i].my_state].begin(), closure[table[i].my_state].end(), table[i] ) == closure[table[i].my_state].end() ){ closure[table[i].my_state].push_back(table[i]); } } cout << endl << "<epsilon closure>" << endl; for(int i=0; i<state_size; i++){ cout << i << " -> {"; for(int j=0; j<closure[i].size(); j++){ cout << closure[i][j].next_state << ", "; } cout << "} " << endl; } closerToTable(table); } bool DFA::test(string test) { int next_num = dfa_state_nums[start_state]; for(int i=0; i<test.length(); i++){ int lang_index = lang.find(test[i]); if( lang_index == -1 ){ cout << "The charater " << test[i] << " is not allow" << endl; return false; } if( dfa_table[next_num][lang_index] == -1 ) return false; next_num = dfa_table[next_num][lang_index]; } // Check final state int idx = -1; for(int k=0; k<state_size; k++){ if( next_num == dfa_state_nums[k] ) idx = k; } for(int k=0; k<closure[idx].size(); k++){ if( closure[idx][k].next_state == final_state ){ return true; } } return false; } int DFA::findNfaData(vector<NfaData> table, int my_state, string value) { for(int i=0; i<table.size(); i++){ if( table[i].my_state == my_state && table[i].value == value ){ return i; } } return -1; } bool DFA::epsilonClosure(vector<NfaData> table, NfaData curState, int my_state) { if( curState.value != "e" || curState.next_state == final_state) return true; for(int i=0; i<table.size(); i++){ if( table[i].my_state == curState.next_state ){ if( table[i].value == "e" ){ bool is_end = epsilonClosure(table, table[i], my_state); if( is_end && find( closure[curState.my_state].begin(), closure[curState.my_state].end(), table[i] ) == closure[curState.my_state].end() ){ closure[my_state].push_back(table[i]); } } else{ return true; } } } return false; } void DFA::closerToTable(vector<NfaData> table) { int dfa_state_size = 0; // Only closure have more than one, can be dfa state for(int i=0, j=0; i<state_size; i++){ dfa_state_nums[i] = -1; if( closure[i].size() > 0 ){ dfa_state_size++; dfa_state_nums[i] = j++; } } //int dfa_table[dfa_state_size][lang.length()]; // initialize dfa_table with -1, -1 means empty set for(int i=0; i<dfa_state_size; i++){ vector<int> temp; for(int j=0; j<lang.length(); j++){ temp.push_back(-1); } dfa_table.push_back(temp); } for(int i=0; i<dfa_state_size; i++){ for(int j=0; j<lang.length(); j++){ string value(1, lang[j]); int idx = -1; for(int k=0; k<state_size; k++){ if( i == dfa_state_nums[k] ) idx = k; } if( idx == -1 ) continue; for(int k=0; k<closure[idx].size(); k++){ // If nfa state in closure have same with value, // dfa_table of i, j has next dfa state. int d = findNfaData(table, closure[idx][k].next_state, value); if( d != -1 ){ dfa_table[i][j] = dfa_state_nums[ table[d].next_state ]; } } } } cout << endl << "<DFA Table>" << endl; for(int i=0; i<dfa_state_size; i++){ cout << i << " | "; for(int j=0; j<lang.length(); j++){ cout << dfa_table[i][j] << " "; } cout << endl; } }
dce6d7e2509b3145458c5ad456b48d5f38a13d40
92e7a96c196e563b70f78db321680d830af80a53
/InstitutionalTrading/Client/CltServerMgr/ServerAddrForm.cpp
889be0cdbf6a9a93b00dbe21a608a3d47ce1df06
[]
no_license
alexfordc/zq
513723341132dd2b01f5ca3debb567b2fd31c033
a0b05b7416fe68784e072da477e8c869097584e2
refs/heads/master
2021-05-25T14:19:37.317957
2018-02-24T05:57:23
2018-02-24T05:57:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
49
cpp
#include "StdAfx.h" #include "ServerAddrForm.h"
711c780f35f237eee2917da383cb918eb1e68631
6b757dfef2b648f31eb21342c65d6d5a5630434a
/testFirst/01背包算法.cpp
6e0e23a458987a72c252d4e50fb1a28e3a96433c
[]
no_license
QkqBeer/C-
4cd51c2058acd20433aaafd5ef4947aa9cb593cd
df1025582f099579a0dbbc00ce21f2f25708a5bb
refs/heads/master
2020-05-19T06:22:36.940458
2019-09-09T05:26:44
2019-09-09T05:26:44
184,873,261
1
0
null
null
null
null
GB18030
C++
false
false
1,031
cpp
#include <iostream> #include <vector> #include <algorithm> using namespace std; /* 01背包算法和部分背包算法的区别 01背包算法:每件物品或被带走,或被留下,每件东西只能拿一次 部分背包算法:可以只带走某个物品的一部分,不必做出0-1选择。 */ int solution(vector<int> weight, vector<int> capacity, int size, int n) { /* weight : 权重 capacity : 体积 size : 包的最大容量 n : 多少个商品 */ vector<vector<int>> data(n + 1, vector<int>(size + 1, 0)); cout << data.size() << endl; for (int i = 1; i <= n; i++) { for (int j = 1; j <= size; j++) { if (capacity[i - 1] > j) //放不下 { data[i][j] = data[i - 1][j]; } else { data[i][j] = max(data[i - 1][j - capacity[i - 1]] + weight[i - 1], data[i - 1][j]); } } } return data[n][size]; } int main01() { vector<int> weight = { 2,3,4,5 }; vector<int> capacity = { 3,4,5,6 }; int size = 8; int n = 4; cout << solution(weight, capacity, size, n); return 0; }
c66dafda3bf4263ded9063e519f4256b03f25826
60b680c69898d0f1a7f982c5ac68095adfb56113
/Sem_2/Lab_3/Task 2/src/screen/GameScreen.cpp
f69fd6b84e09d8bc5ee9ee2dba774d633a2982ff
[]
no_license
borgishmorg/bfu
ba2feb8c1179771c0cae7b0d1b76896b75be5003
426f41ae5b7f7e31491ba7aa5b8c3ae25505fefc
refs/heads/master
2020-03-31T08:46:36.914439
2019-05-29T23:19:51
2019-05-29T23:19:51
152,072,131
3
0
null
null
null
null
UTF-8
C++
false
false
1,107
cpp
#include "GameScreen.hpp" using BattleRoyale::GameScreen; GameScreen::GameScreen(Map & map): Screen(HEIGHT, WIDTH), mapElement_(map, 0, 0), playerElement_(PLAYER_ELEMENT_HPOS, PLAYER_ELEMENT_WPOS), messageElement_(MESSAGE_ELEMENT_HPOS, MESSAGE_ELEMENT_WPOS){ addElement(mapElement_); addElement(playerElement_); addElement(messageElement_); } GameScreen::~GameScreen(){}; void GameScreen::focusAtPlayer(std::shared_ptr<Player> player){ mapElement_.focusAtPlayer(player); playerElement_.focusAtPlayer(player); } void GameScreen::drawMessage(std::string message){ messageElement_.showMessage(message); draw(); } const unsigned int GameScreen::HEIGHT = 24; const unsigned int GameScreen::WIDTH = 80; const unsigned int GameScreen::MAP_ELEMENT_HPOS = 0; const unsigned int GameScreen::MAP_ELEMENT_WPOS = 0; const unsigned int GameScreen::PLAYER_ELEMENT_HPOS = 0; const unsigned int GameScreen::PLAYER_ELEMENT_WPOS = 24; const unsigned int GameScreen::MESSAGE_ELEMENT_HPOS = 12; const unsigned int GameScreen::MESSAGE_ELEMENT_WPOS = 24;
edb3e68003ce31df23926b19162cb23a72b0f1d7
2e765d9338314f35d15c1e1e00ae085c1eac37c6
/백준실/geometry/boj1358.cpp
59074c3e417f48539693c2bb9d2fe36d494a29c7
[]
no_license
chanmin4/BOJ-open-code-list
497874a104174e89ffc24ce566810c4e4c991841
211a548caba25006bbced2441d97a1c42650d81c
refs/heads/main
2023-07-16T02:54:16.658143
2021-09-06T10:21:06
2021-09-06T10:21:06
380,688,372
0
0
null
null
null
null
UTF-8
C++
false
false
1,245
cpp
#include<iostream> #include<string> #include<algorithm> #include<vector> #include<queue> #include<stack> #include<cmath> #include<stdio.h> #include<cstring> #include<cstdio> #include<cstring> #include<set> #include<map> #include<list> #include<unordered_set> #include<time.h> #define fup(i,a,b,c) for(int i=a;i<=b;i+=c) using namespace std; typedef long long ll; typedef long double ld; typedef long long int lli; typedef pair<ll, ll>P; typedef pair<ld, ld>dP; ll MOD = 1e6; ll n, t, m, k; int max_level; ll w, h, x, y, p; ll ccw(ll x1, ll y1, ll x2, ll y2) { return x1 * y2 - x2 * y1; } bool checkin(ll p1, ll p2) { if (ccw(w, 0, p1 - x, p2 - y) >= 0 && ccw(w, 0, p1 - x, p2 - (y + h)) <= 0) { if (x <= p1 && p1 <= x + w)return true; else if (((pow(p1 - x, 2) + pow(p2 - (y + (h / 2) * 1ll), 2) <= pow((h / 2) * 1ll, 2)) && p1 <= x) || (pow(p1 - (x + w), 2) + pow(p2 - (y + (h / 2) * 1ll), 2) <= pow((h / 2) * 1ll, 2)) && x + w <= p1)return true; else return false; } else return false; } int main() { ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0); cin >> w >> h >> x >> y >> p; int result = 0; for (int i = 0; i < p; i++) { ll a, b; cin >> a >> b; if (checkin(a, b))result++; } cout << result << endl; }
f9276e392fa53fed672c5d0f1ebc352bc8159c4b
600df3590cce1fe49b9a96e9ca5b5242884a2a70
/third_party/skia/src/effects/SkPaintImageFilter.cpp
0a0e4e92edf972b03c167acc8da5c43ed5f723a6
[ "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
2,432
cpp
/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkPaintImageFilter.h" #include "SkCanvas.h" #include "SkReadBuffer.h" #include "SkSpecialImage.h" #include "SkSpecialSurface.h" #include "SkWriteBuffer.h" sk_sp<SkImageFilter> SkPaintImageFilter::Make(const SkPaint& paint, const CropRect* cropRect) { return sk_sp<SkImageFilter>(new SkPaintImageFilter(paint, cropRect)); } SkPaintImageFilter::SkPaintImageFilter(const SkPaint& paint, const CropRect* cropRect) : INHERITED(nullptr, 0, cropRect) , fPaint(paint) { } sk_sp<SkFlattenable> SkPaintImageFilter::CreateProc(SkReadBuffer& buffer) { SK_IMAGEFILTER_UNFLATTEN_COMMON(common, 0); SkPaint paint; buffer.readPaint(&paint); return SkPaintImageFilter::Make(paint, &common.cropRect()); } void SkPaintImageFilter::flatten(SkWriteBuffer& buffer) const { this->INHERITED::flatten(buffer); buffer.writePaint(fPaint); } sk_sp<SkSpecialImage> SkPaintImageFilter::onFilterImage(SkSpecialImage* source, const Context& ctx, SkIPoint* offset) const { SkIRect bounds; const SkIRect srcBounds = SkIRect::MakeWH(source->width(), source->height()); if (!this->applyCropRect(ctx, srcBounds, &bounds)) { return nullptr; } sk_sp<SkSpecialSurface> surf(source->makeSurface(ctx.outputProperties(), bounds.size())); if (!surf) { return nullptr; } SkCanvas* canvas = surf->getCanvas(); SkASSERT(canvas); canvas->clear(0x0); SkMatrix matrix(ctx.ctm()); matrix.postTranslate(SkIntToScalar(-bounds.left()), SkIntToScalar(-bounds.top())); SkRect rect = SkRect::MakeIWH(bounds.width(), bounds.height()); SkMatrix inverse; if (matrix.invert(&inverse)) { inverse.mapRect(&rect); } canvas->setMatrix(matrix); canvas->drawRect(rect, fPaint); offset->fX = bounds.fLeft; offset->fY = bounds.fTop; return surf->makeImageSnapshot(); } bool SkPaintImageFilter::affectsTransparentBlack() const { return true; } #ifndef SK_IGNORE_TO_STRING void SkPaintImageFilter::toString(SkString* str) const { str->appendf("SkPaintImageFilter: ("); fPaint.toString(str); str->append(")"); } #endif
cdb77d8c28d7d331df68198b9eb38074fb8ba231
7de672dbbcc1b993ec061473c20a46f963e351b2
/SDK/PUBG_P_MotoDrive_Rock_Front_BP_classes.hpp
1b77c6628647dc3131612231591fa983f30b18a3
[]
no_license
mdbrelo/PUBG-SDK
71a15c680f589770b2d879bfd5d0a6ebc0b6481b
9628997ee0f007055e298ca55908c36317f18b36
refs/heads/master
2021-04-25T23:13:33.421457
2017-10-07T17:18:17
2017-10-07T17:18:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,014
hpp
#pragma once // PlayerUnknown's Battlegrounds (2.6.30.2) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace Classes { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass P_MotoDrive_Rock_Front_BP.P_MotoDrive_Rock_Front_BP_C // 0x0008 (0x0400 - 0x03F8) class AP_MotoDrive_Rock_Front_BP_C : public ATslParticle { public: struct FPointerToUberGraphFrame UberGraphFrame; // 0x03F8(0x0008) (CPF_ZeroConstructor, CPF_Transient, CPF_DuplicateTransient) static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass P_MotoDrive_Rock_Front_BP.P_MotoDrive_Rock_Front_BP_C"); return ptr; } void UserConstructionScript(); void OnParameterUpdated(); void ExecuteUbergraph_P_MotoDrive_Rock_Front_BP(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
d4880283a6963a6842d8a926192326e41f8984cc
ab7f35f161c051dd42f89be87d19807087ae8fce
/C/webcam.cpp
4ec1e84ef923dca5bfa9b1b0605250c7ce72fb59
[]
no_license
duprijil/TTA.BOSH
cbbe699f10fcc73ccdd1344b1bc40c64e70f6032
1441b1c32134e0cf1a20db134662520b1507c460
refs/heads/master
2022-12-25T17:03:34.563368
2020-10-11T17:34:06
2020-10-11T17:34:06
301,464,469
0
0
null
null
null
null
UTF-8
C++
false
false
10,432
cpp
/* (c) 2014 Séverin Lemaignan <[email protected]> (c) 2008 Hans de Goede <[email protected]> for yuyv_to_rgb24 This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA */ #include <stdlib.h> #include <assert.h> #include <fcntl.h> /* low-level i/o */ #include <unistd.h> #include <errno.h> #include <string.h> // strerrno #include <sys/stat.h> #include <sys/types.h> #include <sys/time.h> #include <sys/mman.h> #include <sys/ioctl.h> #include <stdexcept> #include <linux/videodev2.h> #include "webcam.h" #define CLEAR(x) memset(&(x), 0, sizeof(x)) using namespace std; static int xioctl(int fh, unsigned long int request, void *arg) { int r; do { r = ioctl(fh, request, arg); } while (-1 == r && EINTR == errno); return r; } /***** * Taken from libv4l2 (in v4l-utils) * * (C) 2008 Hans de Goede <[email protected]> * * Released under LGPL */ #define CLIP(color) (unsigned char)(((color) > 0xFF) ? 0xff : (((color) < 0) ? 0 : (color))) static void v4lconvert_yuyv_to_rgb24(const unsigned char *src, unsigned char *dest, int width, int height, int stride) { int j; while (--height >= 0) { for (j = 0; j + 1 < width; j += 2) { int u = src[1]; int v = src[3]; int u1 = (((u - 128) << 7) + (u - 128)) >> 6; int rg = (((u - 128) << 1) + (u - 128) + ((v - 128) << 2) + ((v - 128) << 1)) >> 3; int v1 = (((v - 128) << 1) + (v - 128)) >> 1; *dest++ = CLIP(src[0] + v1); *dest++ = CLIP(src[0] - rg); *dest++ = CLIP(src[0] + u1); *dest++ = CLIP(src[2] + v1); *dest++ = CLIP(src[2] - rg); *dest++ = CLIP(src[2] + u1); src += 4; } src += stride - (width * 2); } } /*******************************************************************/ Webcam::Webcam(const string& device, int width, int height) : device(device), xres(width), yres(height) { open_device(); init_device(); // xres and yres are set to the actual resolution provided by the cam // frame stored as RGB888 (ie, RGB24) rgb_frame.width = xres; rgb_frame.height = yres; rgb_frame.size = xres * yres * 3; rgb_frame.data = (unsigned char *) malloc(rgb_frame.size * sizeof(char)); start_capturing(); } Webcam::~Webcam() { stop_capturing(); uninit_device(); close_device(); free(rgb_frame.data); } const RGBImage& Webcam::frame(int timeout) { for (;;) { fd_set fds; struct timeval tv; int r; FD_ZERO(&fds); FD_SET(fd, &fds); /* Timeout. */ tv.tv_sec = timeout; tv.tv_usec = 0; r = select(fd + 1, &fds, NULL, NULL, &tv); if (-1 == r) { if (EINTR == errno) continue; throw runtime_error("select"); } if (0 == r) { throw runtime_error(device + ": select timeout"); } if (read_frame()) { return rgb_frame; } /* EAGAIN - continue select loop. */ } } bool Webcam::read_frame() { struct v4l2_buffer buf; //unsigned int i; CLEAR(buf); buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; buf.memory = V4L2_MEMORY_MMAP; if (-1 == xioctl(fd, VIDIOC_DQBUF, &buf)) { switch (errno) { case EAGAIN: return false; case EIO: /* Could ignore EIO, see spec. */ /* fall through */ default: throw runtime_error("VIDIOC_DQBUF"); } } assert(buf.index < n_buffers); v4lconvert_yuyv_to_rgb24((unsigned char *) buffers[buf.index].data, rgb_frame.data, xres, yres, stride); if (-1 == xioctl(fd, VIDIOC_QBUF, &buf)) throw runtime_error("VIDIOC_QBUF"); return true; } void Webcam::open_device(void) { struct stat st; if (-1 == stat(device.c_str(), &st)) { throw runtime_error(device + ": cannot identify! " + to_string(errno) + ": " + strerror(errno)); } if (!S_ISCHR(st.st_mode)) { throw runtime_error(device + " is no device"); } fd = open(device.c_str(), O_RDWR /* required */ | O_NONBLOCK, 0); if (-1 == fd) { throw runtime_error(device + ": cannot open! " + to_string(errno) + ": " + strerror(errno)); } } void Webcam::init_mmap(void) { struct v4l2_requestbuffers req; CLEAR(req); req.count = 4; req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; req.memory = V4L2_MEMORY_MMAP; if (-1 == xioctl(fd, VIDIOC_REQBUFS, &req)) { if (EINVAL == errno) { throw runtime_error(device + " does not support memory mapping"); } else { throw runtime_error("VIDIOC_REQBUFS"); } } if (req.count < 2) { throw runtime_error(string("Insufficient buffer memory on ") + device); } buffers = (buffer*) calloc(req.count, sizeof(*buffers)); if (!buffers) { throw runtime_error("Out of memory"); } for (n_buffers = 0; n_buffers < req.count; ++n_buffers) { struct v4l2_buffer buf; CLEAR(buf); buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; buf.memory = V4L2_MEMORY_MMAP; buf.index = n_buffers; if (-1 == xioctl(fd, VIDIOC_QUERYBUF, &buf)) throw runtime_error("VIDIOC_QUERYBUF"); buffers[n_buffers].size = buf.length; buffers[n_buffers].data = mmap(NULL /* start anywhere */, buf.length, PROT_READ | PROT_WRITE /* required */, MAP_SHARED /* recommended */, fd, buf.m.offset); if (MAP_FAILED == buffers[n_buffers].data) throw runtime_error("mmap"); } } void Webcam::close_device(void) { if (-1 == close(fd)) throw runtime_error("close"); fd = -1; } void Webcam::init_device(void) { struct v4l2_capability cap; struct v4l2_cropcap cropcap; struct v4l2_crop crop; struct v4l2_format fmt; //unsigned int min; if (-1 == xioctl(fd, VIDIOC_QUERYCAP, &cap)) { if (EINVAL == errno) { throw runtime_error(device + " is no V4L2 device"); } else { throw runtime_error("VIDIOC_QUERYCAP"); } } if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) { throw runtime_error(device + " is no video capture device"); } if (!(cap.capabilities & V4L2_CAP_STREAMING)) { throw runtime_error(device + " does not support streaming i/o"); } /* Select video input, video standard and tune here. */ CLEAR(cropcap); cropcap.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; if (0 == xioctl(fd, VIDIOC_CROPCAP, &cropcap)) { crop.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; crop.c = cropcap.defrect; /* reset to default */ if (-1 == xioctl(fd, VIDIOC_S_CROP, &crop)) { switch (errno) { case EINVAL: /* Cropping not supported. */ break; default: /* Errors ignored. */ break; } } } else { /* Errors ignored. */ } CLEAR(fmt); fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; if (force_format) { fmt.fmt.pix.width = xres; fmt.fmt.pix.height = yres; fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV; fmt.fmt.pix.field = V4L2_FIELD_INTERLACED; if (-1 == xioctl(fd, VIDIOC_S_FMT, &fmt)) throw runtime_error("VIDIOC_S_FMT"); if (fmt.fmt.pix.pixelformat != V4L2_PIX_FMT_YUYV) // note that libv4l2 (look for 'v4l-utils') provides helpers // to manage conversions throw runtime_error("Webcam does not support YUYV format. Support for more format need to be added!"); /* Note VIDIOC_S_FMT may change width and height. */ xres = fmt.fmt.pix.width; yres = fmt.fmt.pix.height; stride = fmt.fmt.pix.bytesperline; } else { /* Preserve original settings as set by v4l2-ctl for example */ if (-1 == xioctl(fd, VIDIOC_G_FMT, &fmt)) throw runtime_error("VIDIOC_G_FMT"); } init_mmap(); } void Webcam::uninit_device(void) { unsigned int i; for (i = 0; i < n_buffers; ++i) if (-1 == munmap(buffers[i].data, buffers[i].size)) throw runtime_error("munmap"); free(buffers); } void Webcam::start_capturing(void) { unsigned int i; enum v4l2_buf_type type; for (i = 0; i < n_buffers; ++i) { struct v4l2_buffer buf; CLEAR(buf); buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; buf.memory = V4L2_MEMORY_MMAP; buf.index = i; if (-1 == xioctl(fd, VIDIOC_QBUF, &buf)) throw runtime_error("VIDIOC_QBUF"); } type = V4L2_BUF_TYPE_VIDEO_CAPTURE; if (-1 == xioctl(fd, VIDIOC_STREAMON, &type)) throw runtime_error("VIDIOC_STREAMON"); } void Webcam::stop_capturing(void) { enum v4l2_buf_type type; type = V4L2_BUF_TYPE_VIDEO_CAPTURE; if (-1 == xioctl(fd, VIDIOC_STREAMOFF, &type)) throw runtime_error("VIDIOC_STREAMOFF"); }
b53d9d04eaa562aaef6123d0b5276177fe7b6447
b4b1152994445bcc67d022f28b87f6e962d01f34
/lab2/Code/function.h
cc25ae48fc64d84e5c6a7fff8d54f3ddcac7ce23
[]
no_license
rookielxy/compiler-2018-fall
45c13cb583ab526c30c99778ad25d32b8147b614
5f400baab81c29d9f87bf43b4873d8f2d9267a20
refs/heads/master
2020-04-16T23:09:06.229453
2019-01-16T11:00:38
2019-01-16T11:00:38
166,000,184
0
0
null
null
null
null
UTF-8
C++
false
false
743
h
#ifndef __FUNCTION__ #define __FUNCTION__ #include "type.h" #include "common.h" class Function { string name; Type ret; vector<Symbol> args; bool def; int line_no; public: Function() = default; Function(const Function &func) = default; ~Function() = default; Function& operator=(const Function &func) = default; Function(AstNode *funDec, const Type &type, bool def); string getName() const { return name; } bool isDef() const { return def; } bool operator==(const Function &func); int getLineNo() const { return line_no; } vector<Symbol> getArgs() const { return args; } vector<Type> getArgsType() const; string getArgsName() const; Type getRetType() const { return ret; } }; #endif
d6d8ea8ba2229379c43810bba588a484093d230f
3cfa229d1d57ce69e0e83bc99c3ca1d005ae38ad
/sphere/source/engine/rendersort.hpp
b2f1626e291d656fabc7612197302bd237a7fde9
[]
no_license
chadaustin/sphere
33fc2fe65acf2eb56e35ade3619643faaced7021
0d74cfb268c16d07ebb7cb2540b7b0697c2a127a
refs/heads/master
2021-01-10T13:28:33.766988
2009-11-08T00:38:57
2009-11-08T00:38:57
36,419,098
2
1
null
null
null
null
UTF-8
C++
false
false
571
hpp
#ifndef RENDER_SORT_HPP #define RENDER_SORT_HPP #include <vector> #include "video.hpp" class CRenderSort { public: void AddObject(int draw_x, int draw_y, int sort_y, int draw_w, int draw_h, bool is_angled, double angle, IMAGE image, RGBA mask); void DrawObjects(); private: struct Object { int draw_x; int draw_y; int sort_y; int draw_w; int draw_h; bool is_angled; double angle; IMAGE image; RGBA mask; }; private: std::vector<Object> m_objects; }; #endif
[ "tunginobi@c0eb2ce6-7f40-480a-a1e0-6c4aea08c2c2" ]
tunginobi@c0eb2ce6-7f40-480a-a1e0-6c4aea08c2c2
c68120fda696c1343baef63a65808aaea147b7a1
6343becde6901e0fcf3a791e719b9d2a08966be8
/include/rive/generated/animation/state_machine_base.hpp
b58972a9b47bff7c6869dfb6b7f30fe7f70b7f51
[ "MIT" ]
permissive
xiu810/rive-cpp
1bfd591eed9c80ec27a984d8b805ddb88754ee17
bfb16907447239687ef6dee918eda9b87beffb6e
refs/heads/master
2023-07-16T12:03:22.676575
2021-08-21T11:13:32
2021-08-31T23:14:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
706
hpp
#ifndef _RIVE_STATE_MACHINE_BASE_HPP_ #define _RIVE_STATE_MACHINE_BASE_HPP_ #include "rive/animation/animation.hpp" namespace rive { class StateMachineBase : public Animation { protected: typedef Animation Super; public: static const uint16_t typeKey = 53; /// Helper to quickly determine if a core object extends another without /// RTTI at runtime. bool isTypeOf(uint16_t typeKey) const override { switch (typeKey) { case StateMachineBase::typeKey: case AnimationBase::typeKey: return true; default: return false; } } uint16_t coreType() const override { return typeKey; } Core* clone() const override; protected: }; } // namespace rive #endif
74be4cb2f298829ec207b8264951c1f63a1307fa
4c8255fbb4ffb92c3c82bf88b1d30e89a75881de
/etc/examples/mojo/echo_server/poll.h
f8ca15e6eaea8b0c233033c447fb6d13de5f7f62
[]
no_license
Xardas2000/mojo-echo
6802b2709a87e09bf3403a0d46d4f33e8e94719e
7a728e3914c58de97ad0722e86af56f44b11d8bf
refs/heads/master
2021-01-07T22:40:09.253209
2020-02-20T09:51:34
2020-02-20T09:51:34
241,840,197
4
0
null
null
null
null
UTF-8
C++
false
false
284
h
#include <vector> #include "engine.h" class PollEngine : public Engine { public: explicit PollEngine(int port); ~PollEngine() override; void run() override; private: void acceptNewConnections(); void manageConnections(); private: std::vector<Client> m_Clients; };
8aab44ac3a4ae5f1824676d89912003f9f16c6d5
c967308d6aa41de943fa78b34afb11ef246088fc
/Classes/LotteryLayer.cpp
0466a2c664eda64210031fb7a374760b48a07bec
[]
no_license
IceCoffee2011/CatchFish3
ab9be97481f8b6cb73c8eb82d41053082f928e24
0f034d96447b282e8e75b88afd891dd7864ed561
refs/heads/master
2020-05-05T11:00:41.150725
2017-01-14T08:02:45
2017-01-14T08:02:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
24,161
cpp
#include "header.h" LotteryLayer::~LotteryLayer() { } LotteryLayer* LotteryLayer::create(bool bLocalOpen, int nLotteryNum) { LotteryLayer* pRet = new LotteryLayer(); if(pRet && pRet->init(bLocalOpen, nLotteryNum)) { pRet->autorelease(); return pRet; } else { delete pRet; pRet = NULL; return NULL; } } bool LotteryLayer::init(bool bLocalOpen, int nLotteryNum) { if(!CCLayer::init()) { return false; } m_bLocalOpen = bLocalOpen; m_bRequestStatus = false; m_nCurrentMobileCount = 0; loadUI(); if(m_bLocalOpen) { readLotteryConfig(); } this -> setTouchEnabled(true); return true; } void LotteryLayer::loadUI() { CCSprite* pBg = CCSprite::create("lottery/lotterybg.png"); pBg -> setPosition(ccp(CLIENT_WIDTH/2, CLIENT_HEIGHT/2)); this -> addChild(pBg); CCMenuItemImage* closeItem = CCMenuItemImage::create("lottery/closeItem.png", "lottery/closeItem.png", this, menu_selector(LotteryLayer::closeMenu)); closeItem -> setPosition(ccp(CLIENT_WIDTH-closeItem->getContentSize().width/2, CLIENT_HEIGHT-closeItem->getContentSize().height/2)); CCMenu* pCloseMenu = CCMenu::create(closeItem, NULL); pCloseMenu -> setPosition(CCPointZero); pCloseMenu -> setAnchorPoint(CCPointZero); pBg -> addChild(pCloseMenu); pCloseMenu -> setTouchPriority(-130); CCMenuItemImage* yidongItem = CCMenuItemImage::create("lottery/yidongItem.png", "lottery/yidongItem.png", this, menu_selector(LotteryLayer::clickExchangeType)); yidongItem -> setTag(101); yidongItem -> setPosition(ccp(CLIENT_WIDTH/4-5, CLIENT_HEIGHT/4*3+45)); CCMenuItemImage* liantongItem = CCMenuItemImage::create("lottery/liantongItem.png", "lottery/liantongItem.png", this, menu_selector(LotteryLayer::clickExchangeType)); liantongItem -> setTag(102); liantongItem -> setPosition(ccp(CLIENT_WIDTH/2, CLIENT_HEIGHT/4*3+45)); CCMenuItemImage* dianxinItem = CCMenuItemImage::create("lottery/dianxinItem.png", "lottery/dianxinItem.png", this, menu_selector(LotteryLayer::clickExchangeType)); dianxinItem -> setTag(103); dianxinItem -> setPosition(ccp(CLIENT_WIDTH/4*3+5, CLIENT_HEIGHT/4*3+45)); CCMenu* pMenuType = CCMenu::create(yidongItem, liantongItem, dianxinItem, NULL); pMenuType -> setPosition(CCPointZero); pMenuType -> setAnchorPoint(CCPointZero); pBg -> addChild(pMenuType); pMenuType -> setTouchPriority(-130); m_spYidong = CCSprite::create("lottery/yidongSp.png"); m_spYidong -> setPosition(ccp(CLIENT_WIDTH/4-5, CLIENT_HEIGHT/4*3+45)); pBg -> addChild(m_spYidong); m_spLiantong = CCSprite::create("lottery/liantongSp.png"); m_spLiantong -> setPosition(ccp(CLIENT_WIDTH/2, CLIENT_HEIGHT/4*3+45)); pBg -> addChild(m_spLiantong); m_spDianxin = CCSprite::create("lottery/dianxinSp.png"); m_spDianxin -> setPosition(ccp(CLIENT_WIDTH/4*3+5, CLIENT_HEIGHT/4*3+45)); pBg -> addChild(m_spDianxin); m_spLiantong -> setVisible(false); m_spDianxin -> setVisible(false); m_nSelectID = 1; m_nPriseName = 0; m_labelMobile = CCLabelAtlas::create("", "lottery/lotterymobilenum.png", 30, 54, '0'); m_labelMobile -> setAnchorPoint(ccp(0, 0.5f)); m_labelMobile -> setPosition(ccp(CLIENT_WIDTH/4*3-70, CLIENT_HEIGHT/3*2-8)); pBg -> addChild(m_labelMobile); m_labelMobileInfo = CCLabelTTF::create("正在查询", "Arial", 32); m_labelMobileInfo -> setPosition(ccp(CLIENT_WIDTH/4*3-70, CLIENT_HEIGHT/3*2-8)); m_labelMobileInfo -> setAnchorPoint(ccp(0, 0.5f)); pBg -> addChild(m_labelMobileInfo); m_nodeYidong = CCNode::create(); this -> addChild(m_nodeYidong); m_nodeLiantong = CCNode::create(); this -> addChild(m_nodeLiantong); m_nodeLiantong -> setVisible(false); m_nodeDianxin = CCNode::create(); this -> addChild(m_nodeDianxin); m_nodeDianxin -> setVisible(false); m_spSelect = CCSprite::create("lottery/lotterySelect.png"); m_spSelect -> setPosition(ccp(CLIENT_WIDTH/4-5, CLIENT_HEIGHT/4*3+45)); pBg -> addChild(m_spSelect); CMD_GPR_MobileCount MobileCount = {0}; MobileCount.dwUserId = CMainLogic::sharedMainLogic()->m_nUserID; CMainLogic::sharedMainLogic()->SendData(CMainLogic::sharedMainLogic()->m_nHallSocketHandle, MDM_GP_USER_SERVICE, SUB_GPR_MOBILE_COUNT, &MobileCount,sizeof(MobileCount)); } void LotteryLayer::readLotteryConfig() { std::string path = CCFileUtils::sharedFileUtils() -> getWritablePath(); std::string xmlPath = path + std::string("ExchangeShopConfig.xml"); TiXmlDocument* document = new TiXmlDocument(xmlPath.c_str()); if(document != NULL) { document -> LoadFile(); TiXmlElement* rootElement = document->RootElement(); if(rootElement != NULL) { std::string nodename=rootElement->Value(); if (0!=nodename.compare("exchangeShop")) { delete document; return; } TiXmlElement* firstElement = rootElement->FirstChildElement(); std::string firstValue = firstElement->Value(); if(firstValue == "telCards") { TiXmlElement* pCurrentElement = firstElement->FirstChildElement(); while (pCurrentElement != NULL) { std::string telCardValue = pCurrentElement->Value(); if(telCardValue == "telCard") { TelCardConfig* pTelCardConfig = new TelCardConfig; m_vctTelCard.push_back(pTelCardConfig); const char* prize = pCurrentElement->Attribute("prize"); pTelCardConfig->nPrize = atoi(prize); const char* lotteryCount = pCurrentElement->Attribute("lotteryCount"); pTelCardConfig->nLotteryCount = atoi(lotteryCount); const char* cardType = pCurrentElement->Attribute("cardType"); pTelCardConfig->nCardType = atoi(cardType); const char* sID = pCurrentElement->Attribute("id"); pTelCardConfig->nID = atoi(sID); } pCurrentElement = pCurrentElement->NextSiblingElement(); } } } } delete document; loadUILotteryBg((int)m_vctTelCard.size()); } void LotteryLayer::parseData(std::string str) { TiXmlDocument* document = new TiXmlDocument(); int len = (int)strlen(str.c_str()); if(document->LoadFile2((unsigned char *)str.c_str(), len)) { TiXmlElement* rootElement = document->RootElement(); std::string nodename=rootElement->Value(); if (0!=nodename.compare("exchangeShop")) { delete document; return; } TiXmlElement* firstElement = rootElement->FirstChildElement(); std::string firstValue = firstElement->Value(); if(firstValue == "telCards") { TiXmlElement* pCurrentElement = firstElement->FirstChildElement(); while (pCurrentElement != NULL) { std::string telCardValue = pCurrentElement->Value(); if(telCardValue == "telCard") { TelCardConfig* pTelCardConfig = new TelCardConfig; m_vctTelCard.push_back(pTelCardConfig); const char* prize = pCurrentElement->Attribute("prize"); pTelCardConfig->nPrize = atoi(prize); const char* lotteryCount = pCurrentElement->Attribute("lotteryCount"); pTelCardConfig->nLotteryCount = atoi(lotteryCount); const char* cardType = pCurrentElement->Attribute("cardType"); pTelCardConfig->nCardType = atoi(cardType); const char* sID = pCurrentElement->Attribute("id"); pTelCardConfig->nID = atoi(sID); } pCurrentElement = pCurrentElement->NextSiblingElement(); } } } delete document; loadUILotteryBg((int)m_vctTelCard.size()); //保存文件 saveFile(str); } void LotteryLayer::saveFile(std::string str) { //在Documents目录下创建一个可读写的文件 std::string path = CCFileUtils::sharedFileUtils() -> getWritablePath(); std::string xmlPath = path + std::string("ExchangeShopConfig.xml"); const char* buf = str.c_str(); FILE* file = fopen(xmlPath.c_str(), "w"); if(file) { fputs(buf, file); fclose(file); CCLog("save succeed"); } else { CCLog("save file error"); } } void LotteryLayer::loadUILotteryBg(int nCount) { for(int i = 0; i < nCount; i++) { if(m_vctTelCard[i]->nCardType == 1)//移动 { CCSprite* pTypeBg = CCSprite::create("lottery/lotterytypebg.png"); pTypeBg -> setPosition(ccp(CLIENT_WIDTH/4*(1+i%3)-(i%3-1)*10, CLIENT_HEIGHT/3+20)); m_nodeYidong -> addChild(pTypeBg); CCMenuItemImage* duihuanItem = CCMenuItemImage::create("lottery/duihuanItem.png", "lottery/duihuanItem.png", this, menu_selector(LotteryLayer::sendExchangeData)); duihuanItem -> setPosition(ccp(pTypeBg->getContentSize().width/2, duihuanItem->getContentSize().height-10)); CCMenu* pMenu = CCMenu::create(duihuanItem, NULL); pMenu -> setPosition(CCPointZero); pMenu -> setAnchorPoint(CCPointZero); pTypeBg -> addChild(pMenu); pMenu -> setTouchPriority(-130); duihuanItem -> setTag(201+i); char temp[32]; sprintf(temp, "%d话费券", m_vctTelCard[i]->nLotteryCount); CCLabelTTF* pLabelTitle = CCLabelTTF::create(temp, "Arial-BoldMT", 36); pLabelTitle -> setPosition(ccp(pTypeBg->getContentSize().width/2, pTypeBg->getContentSize().height-30)); pTypeBg -> addChild(pLabelTitle); sprintf(temp, "%d", m_vctTelCard[i]->nPrize); CCLabelTTF* pLabelNum = CCLabelTTF::create(temp, "Arial-BoldMT", 44); pLabelNum -> setAnchorPoint(ccp(0.5, 0.5)); pLabelNum -> setPosition(ccp(pTypeBg->getContentSize().width/2+10, pTypeBg->getContentSize().height/2+8)); pLabelNum->setRotation(15); pTypeBg->addChild(pLabelNum); } else if(m_vctTelCard[i]->nCardType == 2)//联通 { CCSprite* pTypeBg = CCSprite::create("lottery/lotterytypebg.png"); pTypeBg -> setPosition(ccp(CLIENT_WIDTH/4*(1+i%3)-(i%3-1)*10, CLIENT_HEIGHT/3+20)); m_nodeLiantong -> addChild(pTypeBg); CCMenuItemImage* duihuanItem = CCMenuItemImage::create("lottery/duihuanItem.png", "lottery/duihuanItem.png", this, menu_selector(LotteryLayer::sendExchangeData)); duihuanItem -> setPosition(ccp(pTypeBg->getContentSize().width/2, duihuanItem->getContentSize().height-10)); CCMenu* pMenu = CCMenu::create(duihuanItem, NULL); pMenu -> setPosition(CCPointZero); pMenu -> setAnchorPoint(CCPointZero); pTypeBg -> addChild(pMenu); pMenu -> setTouchPriority(-130); duihuanItem -> setTag(201+i); char temp[32]; sprintf(temp, "%d话费券", m_vctTelCard[i]->nLotteryCount); CCLabelTTF* pLabelTitle = CCLabelTTF::create(temp, "Arial-BoldMT", 36); pLabelTitle -> setPosition(ccp(pTypeBg->getContentSize().width/2, pTypeBg->getContentSize().height-30)); pTypeBg -> addChild(pLabelTitle); sprintf(temp, "%d", m_vctTelCard[i]->nPrize); CCLabelTTF* pLabelNum = CCLabelTTF::create(temp, "Arial-BoldMT", 44); pLabelNum -> setAnchorPoint(ccp(0.5, 0.5)); pLabelNum -> setPosition(ccp(pTypeBg->getContentSize().width/2+10, pTypeBg->getContentSize().height/2+8)); pLabelNum->setRotation(15); pTypeBg->addChild(pLabelNum); } else if(m_vctTelCard[i]->nCardType == 3)//电信 { CCSprite* pTypeBg = CCSprite::create("lottery/lotterytypebg.png"); pTypeBg -> setPosition(ccp(CLIENT_WIDTH/4*(1+i%3)-(i%3-1)*10, CLIENT_HEIGHT/3+20)); m_nodeDianxin -> addChild(pTypeBg); CCMenuItemImage* duihuanItem = CCMenuItemImage::create("lottery/duihuanItem.png", "lottery/duihuanItem.png", this, menu_selector(LotteryLayer::sendExchangeData)); duihuanItem -> setPosition(ccp(pTypeBg->getContentSize().width/2, duihuanItem->getContentSize().height-10)); CCMenu* pMenu = CCMenu::create(duihuanItem, NULL); pMenu -> setPosition(CCPointZero); pMenu -> setAnchorPoint(CCPointZero); pTypeBg -> addChild(pMenu); pMenu -> setTouchPriority(-130); duihuanItem -> setTag(201+i); char temp[32]; sprintf(temp, "%d话费券", m_vctTelCard[i]->nLotteryCount); CCLabelTTF* pLabelTitle = CCLabelTTF::create(temp, "Arial-BoldMT", 36); pLabelTitle -> setPosition(ccp(pTypeBg->getContentSize().width/2, pTypeBg->getContentSize().height-30)); pTypeBg -> addChild(pLabelTitle); sprintf(temp, "%d", m_vctTelCard[i]->nPrize); CCLabelTTF* pLabelNum = CCLabelTTF::create(temp, "Arial-BoldMT", 44); pLabelNum -> setAnchorPoint(ccp(0.5, 0.5)); pLabelNum -> setPosition(ccp(pTypeBg->getContentSize().width/2+10, pTypeBg->getContentSize().height/2+8)); pLabelNum->setRotation(15); pTypeBg->addChild(pLabelNum); } } } void LotteryLayer::sendExchangeData(CCObject* object) { if(!m_bRequestStatus) { return ; } SimpleAudioEngine::sharedEngine()->playEffect(BUTTON_EFFECT); CCMenuItem* item = (CCMenuItem*)object; if(item != NULL) { int nTag = item->getTag()-201; for(int i = 0; i < m_vctTelCard.size(); i++) { if(nTag == i) { if(m_vctTelCard[i]->nLotteryCount <= m_nCurrentMobileCount) { m_nPriseName = m_vctTelCard[i]->nPrize; sendUserInfo(); } else { CMainLogic::sharedMainLogic()->ShowMessage("非常抱歉,您当前的话费券数量不足", eMBOK); } } } } } void LotteryLayer::sendUserInfo() { int nUserID = CMainLogic::sharedMainLogic()->m_nUserID; char temp[256]; sprintf(temp, "http://%s/Getexchange.aspx?type=1&uid=%d&uadress=%s&utel=%s&uitem=%d&uname=%s&cardtype=%d",NORMAL_URL, nUserID, "", "",m_nPriseName, "", m_nSelectID); CCHttpRequest* request = new CCHttpRequest(); request -> setUrl(temp); request -> setRequestType(CCHttpRequest::kHttpGet); request -> setResponseCallback(this, httpresponse_selector(LotteryLayer::OnHttpExchangeLotteryComplete)); CCHttpClient::getInstance()->send(request); request -> release(); //正在发送兑换请求,请稍候 CMainLogic::sharedMainLogic()->ShowMessage("正在发送兑换请求,请稍候", eMBNull); if (m_nSelectID == 1) { if (m_nPriseName == 30) { CMainLogic::sharedMainLogic()->sendUserBehavior(CMainLogic::sharedMainLogic()->m_nUserID, eHallLotteryToThirtyCMCC); } else if (m_nPriseName == 50) { CMainLogic::sharedMainLogic()->sendUserBehavior(CMainLogic::sharedMainLogic()->m_nUserID, eHallLotteryToFiftyCMCC); } else if (m_nPriseName == 100) { CMainLogic::sharedMainLogic()->sendUserBehavior(CMainLogic::sharedMainLogic()->m_nUserID, eHallLotteryToHundredCMCC); } } else if (m_nSelectID == 2) { if (m_nPriseName == 30) { CMainLogic::sharedMainLogic()->sendUserBehavior(CMainLogic::sharedMainLogic()->m_nUserID, eHallLotteryToThirtyCUCC); } else if (m_nPriseName == 50) { CMainLogic::sharedMainLogic()->sendUserBehavior(CMainLogic::sharedMainLogic()->m_nUserID, eHallLotteryToFiftyCUCC); } else if (m_nPriseName == 100) { CMainLogic::sharedMainLogic()->sendUserBehavior(CMainLogic::sharedMainLogic()->m_nUserID, eHallLotteryToHundredCUCC); } } else if (m_nSelectID == 3) { if (m_nPriseName == 30) { CMainLogic::sharedMainLogic()->sendUserBehavior(CMainLogic::sharedMainLogic()->m_nUserID, eHallLotteryToThirtyCTCC); } else if (m_nPriseName == 50) { CMainLogic::sharedMainLogic()->sendUserBehavior(CMainLogic::sharedMainLogic()->m_nUserID, eHallLotteryToFiftyCTCC); } else if (m_nPriseName == 100) { CMainLogic::sharedMainLogic()->sendUserBehavior(CMainLogic::sharedMainLogic()->m_nUserID, eHallLotteryToHundredCTCC); } } } void LotteryLayer::OnHttpExchangeLotteryComplete(CCHttpClient* sender, CCHttpResponse* response) { if (!response) { CMainLogic::sharedMainLogic()->ShowMessage("对不起,本次请求失败了,请稍后再试一次。", eMBOK); return; } if (!response->isSucceed()) { CMainLogic::sharedMainLogic()->ShowMessage("对不起,本次请求失败了,请稍后再试一次。", eMBOK); return; } std::vector<char> *buffer = response->getResponseData(); std::string str; for (unsigned int i = 0; i < buffer->size(); i++) { char a = (*buffer)[i]; str.append(1,a); } int nLottery = 0; //解析xml文件,显示结果,并且更新大厅界面和奖券界面上的奖券数量 TiXmlDocument* document = new TiXmlDocument(); int len = (int)strlen(str.c_str()); if(document->LoadFile2((unsigned char *)str.c_str(), len)) { TiXmlElement* rootElement = document->RootElement(); std::string nodename=rootElement->Value(); if (0!=nodename.compare("userExchange")) { CMainLogic::sharedMainLogic()->ShowMessage("对不起,本次兑换失败了,请稍后再试一次。", eMBOK); CMainLogic::sharedMainLogic()->sendUserBehavior(CMainLogic::sharedMainLogic()->m_nUserID, ehallLotteryDuiHuanFail); return; } std::string type=rootElement->Attribute("value"); if(!std::strcmp(type.c_str(), "0"))//兑换失败 { std::string sReason = rootElement->GetText(); CMainLogic::sharedMainLogic()->ShowMessage(sReason.c_str(), eMBOK); CMainLogic::sharedMainLogic()->sendUserBehavior(CMainLogic::sharedMainLogic()->m_nUserID, ehallLotteryDuiHuanFail); } else if(!std::strcmp(type.c_str(), "1")) { TiXmlElement* pFirstElement = rootElement->FirstChildElement(); if(pFirstElement != NULL) { std::string firstValue = pFirstElement->Attribute("lotteryCount"); nLottery = atoi(firstValue.c_str()); std::string sResult = pFirstElement->GetText(); CMainLogic::sharedMainLogic()->sendUserBehavior(CMainLogic::sharedMainLogic()->m_nUserID, eHallLotteryDuiHuanSuccess); setLabelMoney(nLottery); if(CMainLogic::sharedMainLogic()->m_bCanBandingTel) { if(CCUserDefault::sharedUserDefault()->getStringForKey("BindingTel", "") != CMainLogic::sharedMainLogic()->getCurrentUserIDTime("BindingTel")) { CCUserDefault::sharedUserDefault()->setStringForKey("BindingTel", CMainLogic::sharedMainLogic()->getCurrentUserIDTime("BindingTel")); CMainLogic::sharedMainLogic()->ShowMessage(sResult.c_str(), eMBOK, eShowMobileBinding); } else { CMainLogic::sharedMainLogic()->ShowMessage(sResult.c_str(), eMBOK); } } else { CMainLogic::sharedMainLogic()->ShowMessage(sResult.c_str(), eMBOK); } //向服务端发送公告 CMD_GPR_ExchangeMobile ExchangeMobile = {0}; ExchangeMobile.nExchangeType = m_nSelectID; ExchangeMobile.nExchangeCount = m_nPriseName; strncpy(ExchangeMobile.szNickName, CCharCode::UTF8ToGB2312(CMainLogic::sharedMainLogic()->m_sNickName.c_str()).c_str(), sizeof(ExchangeMobile.szNickName)); CMainLogic::sharedMainLogic()->SendData(CMainLogic::sharedMainLogic()->m_nHallSocketHandle, MDM_GP_USER_NOTICE, SUB_GPR_EXCHANGE_MOBILE, &ExchangeMobile,sizeof(ExchangeMobile)); } } } delete document; } void LotteryLayer::clickExchangeType(CCObject* object) { CCMenuItem* item = (CCMenuItem*)object; if(item != NULL) { switch (item->getTag()) { case 101: { if(m_nSelectID != 1) { SimpleAudioEngine::sharedEngine()->playEffect(BUTTON_EFFECT); } m_nSelectID = 1; m_spDianxin -> setVisible(false); m_spLiantong -> setVisible(false); m_spYidong -> setVisible(true); m_nodeYidong -> setVisible(true); m_nodeLiantong -> setVisible(false); m_nodeDianxin -> setVisible(false); m_spSelect -> setPosition(ccp(CLIENT_WIDTH/4-5, CLIENT_HEIGHT/4*3+45)); break; } case 102: { if(m_nSelectID != 2) { SimpleAudioEngine::sharedEngine()->playEffect(BUTTON_EFFECT); } m_nSelectID = 2; m_spLiantong -> setVisible(true); m_spYidong -> setVisible(false); m_spDianxin -> setVisible(false); m_nodeLiantong -> setVisible(true); m_nodeYidong -> setVisible(false); m_nodeDianxin -> setVisible(false); m_spSelect -> setPosition(ccp(CLIENT_WIDTH/2, CLIENT_HEIGHT/4*3+45)); break; } case 103: { if(m_nSelectID != 3) { SimpleAudioEngine::sharedEngine()->playEffect(BUTTON_EFFECT); } m_nSelectID = 3; m_spDianxin -> setVisible(true); m_spYidong -> setVisible(false); m_spLiantong -> setVisible(false); m_nodeDianxin -> setVisible(true); m_nodeYidong -> setVisible(false); m_nodeLiantong -> setVisible(false); m_spSelect -> setPosition(ccp(CLIENT_WIDTH/4*3+5, CLIENT_HEIGHT/4*3+45)); break; } default: break; } } } void LotteryLayer::setLabelMoney(int nCount) { m_nCurrentMobileCount = nCount; m_bRequestStatus = true; char temp[16]; sprintf(temp, "%d", nCount); m_labelMobile -> setString(temp); m_labelMobileInfo -> setVisible(false); } void LotteryLayer::closeMenu(CCObject* object) { SimpleAudioEngine::sharedEngine()->playEffect(BUTTON_CLOSE_EFFECT); this -> removeFromParent(); if(GameMainScene::_instance != NULL) { GameMainScene::GetInstance()->setWndHave(false); GameMainScene::GetInstance()->setAutoFire(); GameMainScene::GetInstance()->setMatchShowStatus(true); } } void LotteryLayer::registerWithTouchDispatcher() { CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, -129, true); } bool LotteryLayer::ccTouchBegan(CCTouch* pTouch, CCEvent* pEvent) { return true; }
42c1e8f32c2ce2e9dae1873a14d1f811c8e95faa
31f5cddb9885fc03b5c05fba5f9727b2f775cf47
/thirdparty/physx/physx/source/lowlevel/software/src/PxsDefaultMemoryManager.cpp
e53ea5dbcfdaa2ac6477997c0d226bd7d8e627ba
[ "MIT" ]
permissive
timi-liuliang/echo
2935a34b80b598eeb2c2039d686a15d42907d6f7
d6e40d83c86431a819c6ef4ebb0f930c1b4d0f24
refs/heads/master
2023-08-17T05:35:08.104918
2023-08-11T18:10:35
2023-08-11T18:10:35
124,620,874
822
102
MIT
2021-06-11T14:29:03
2018-03-10T04:07:35
C++
UTF-8
C++
false
false
2,902
cpp
// // 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 NVIDIA CORPORATION 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 ``AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2018 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "PxsDefaultMemoryManager.h" namespace physx { PxsDefaultMemoryManager::~PxsDefaultMemoryManager() { for (PxU32 i = 0; i < mAllocators.size(); ++i) { mAllocators[i]->~VirtualAllocatorCallback(); PX_FREE(mAllocators[i]); } } Ps::VirtualAllocatorCallback* PxsDefaultMemoryManager::createHostMemoryAllocator(const PxU32 gpuComputeVersion) { PX_UNUSED(gpuComputeVersion); Ps::VirtualAllocatorCallback* allocator = PX_PLACEMENT_NEW(PX_ALLOC(sizeof(PxsDefaultMemoryAllocator), "PxsDefaultMemoryAllocator"), PxsDefaultMemoryAllocator()); mAllocators.pushBack(allocator); return allocator; } //this is an empty stub Ps::VirtualAllocatorCallback* PxsDefaultMemoryManager::createDeviceMemoryAllocator(const PxU32 gpuComputeVersion) { PX_UNUSED(gpuComputeVersion); return NULL; } void PxsDefaultMemoryManager::destroyMemoryAllocator() { for (PxU32 i = 0; i < mAllocators.size(); ++i) { mAllocators[i]->~VirtualAllocatorCallback(); PX_FREE(mAllocators[i]); } } PxsMemoryManager* createMemoryManager() { return PX_PLACEMENT_NEW(PX_ALLOC(sizeof(PxsDefaultMemoryManager), PX_DEBUG_EXP("PxsDefaultMemoryManager")), PxsDefaultMemoryManager()); } }
2313edf7728a235ecc432c26f159df4e0cdc804d
fae45a23a885b72cd27c0ad1b918ad754b5de9fd
/benchmarks/shenango/parsec/pkgs/tools/cmake/src/Source/cmExternalMakefileProjectGenerator.h
d841a6f61b5a678574f17a34b8e634b4b952dfea
[ "MIT", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-other-permissive", "Apache-2.0" ]
permissive
bitslab/CompilerInterrupts
6678700651c7c83fd06451c94188716e37e258f0
053a105eaf176b85b4c0d5e796ac1d6ee02ad41b
refs/heads/main
2023-06-24T18:09:43.148845
2021-07-26T17:32:28
2021-07-26T17:32:28
342,868,949
3
3
MIT
2021-07-19T15:38:30
2021-02-27T13:57:16
C
UTF-8
C++
false
false
3,066
h
/*========================================================================= Program: CMake - Cross-Platform Makefile Generator Module: $RCSfile: cmExternalMakefileProjectGenerator.h,v $ Language: C++ Date: $Date: 2012/03/29 17:21:08 $ Version: $Revision: 1.1.1.1 $ Copyright (c) 2007 Kitware, Inc., Insight Consortium. All rights reserved. See Copyright.txt or http://www.cmake.org/HTML/Copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef cmExternalMakefileProjectGenerator_h #define cmExternalMakefileProjectGenerator_h #include "cmStandardIncludes.h" #include "cmDocumentation.h" class cmGlobalGenerator; /** \class cmExternalMakefileProjectGenerator * \brief Base class for generators for "External Makefile based IDE projects". * * cmExternalMakefileProjectGenerator is a base class for generators * for "external makefile based projects", i.e. IDE projects which work * an already existing makefiles. * See cmGlobalKdevelopGenerator as an example. * After the makefiles have been generated by one of the Makefile * generators, the Generate() method is called and this generator * can iterate over the local generators and/or projects to produce the * project files for the IDE. */ class cmExternalMakefileProjectGenerator { public: virtual ~cmExternalMakefileProjectGenerator() {} ///! Get the name for this generator. virtual const char* GetName() const = 0; /** Get the documentation entry for this generator. */ virtual void GetDocumentation(cmDocumentationEntry& entry, const char* fullName) const = 0; ///! set the global generator which will generate the makefiles virtual void SetGlobalGenerator(cmGlobalGenerator* generator) {this->GlobalGenerator = generator;} ///! Return the list of global generators supported by this extra generator const std::vector<std::string>& GetSupportedGlobalGenerators() const {return this->SupportedGlobalGenerators;} ///! Get the name of the global generator for the given full name const char* GetGlobalGeneratorName(const char* fullName); /** Create a full name from the given global generator name and the * extra generator name */ static std::string CreateFullGeneratorName(const char* globalGenerator, const char* extraGenerator); ///! Generate the project files, the Makefiles have already been generated virtual void Generate() = 0; protected: ///! Contains the names of the global generators support by this generator. std::vector<std::string> SupportedGlobalGenerators; ///! the global generator which creates the makefiles const cmGlobalGenerator* GlobalGenerator; }; #endif
08c80e25b5ff3846ae0b42db155dea631acb8001
1c0ec16578f2951f64442f1577b83a4c78194924
/cpp/OpenGL/09_Tetris/Grid.h
2fca64854af177fcfb316c096ff29865e9db996b
[]
no_license
sdraeger/lnc
5e8381325caf01667597a0e3ed6d5e9b2df22dc8
dc5762d58449b1b5a98c914fd41bd300190dc2c4
refs/heads/master
2023-03-10T10:14:58.728940
2021-02-22T21:53:43
2021-02-22T21:53:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
851
h
#pragma once #include <memory> #include <vector> #include <string> #include "Renderer.h" #include "Vec2.h" class Grid { public: Grid(std::shared_ptr<Renderer> renderer); void render(const std::array<Vec2i,4>& tetrominoPos, const Vec3& currentColor, const std::array<Vec2i,4>& nextTetrominoPos, const Vec3& nextColor, const std::array<Vec2i,4>& targerTetrominoPos, float time) const; void clear(); void setPixel(size_t x, size_t y, int8_t val); int8_t getPixel(size_t x, size_t y) const; std::string toString() const; uint32_t getWidth() const {return width;} uint32_t getHeight() const {return height;} std::shared_ptr<Renderer> getRenderer() const {return renderer;} private: uint32_t width; uint32_t height; std::shared_ptr<Renderer> renderer; std::vector<int8_t> data; size_t gridIndex(size_t x, size_t y) const; };
c56f1bd87e840a7d5fb8b931f2240d86049565db
10aea50c07ae8a95f8409762520e8e51b11cd2ed
/Applications/HexEditor/main.cpp
5f70b92b0bf8d578fa0e35469982120b124bf9e5
[ "BSD-2-Clause" ]
permissive
Tristochi/serenity
ad199c5ac4eecc1a59c853155a5cef8b5032a2fe
d9385d7d6252dbd0f5882a43d4a6b328fce0daf0
refs/heads/master
2020-12-12T18:23:48.942610
2020-01-15T21:45:02
2020-01-15T22:14:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,057
cpp
#include "HexEditorWidget.h" #include <LibDraw/PNGLoader.h> #include <stdio.h> int main(int argc, char** argv) { if (pledge("stdio shared_buffer unix rpath cpath wpath fattr", nullptr) < 0) { perror("pledge"); return 1; } GApplication app(argc, argv); if (pledge("stdio shared_buffer rpath cpath wpath", nullptr) < 0) { perror("pledge"); return 1; } auto window = GWindow::construct(); window->set_title("Hex Editor"); window->set_rect(20, 200, 640, 400); auto hex_editor_widget = HexEditorWidget::construct(); window->set_main_widget(hex_editor_widget); window->on_close_request = [&]() -> GWindow::CloseRequestDecision { if (hex_editor_widget->request_close()) return GWindow::CloseRequestDecision::Close; return GWindow::CloseRequestDecision::StayOpen; }; window->show(); window->set_icon(load_png("/res/icons/16x16/app-hexeditor.png")); if (argc >= 2) hex_editor_widget->open_file(argv[1]); return app.exec(); }
66b913e0f79cf5467227c094977d4ce66638283e
a9f36724f0a13e02d509583b990eb2a24b4b754c
/ship.h
50f8404044fd4d51242395a49be0ff6078ffd251
[ "MIT" ]
permissive
runemoennike/asteroids
c52e99cd4ba630dc4aa04e24d71b43bb413942d7
bdef23a43ccbca8964dd12ee8192757ee87113c6
refs/heads/master
2021-01-21T12:46:54.615453
2015-05-06T20:25:04
2015-05-06T20:25:04
35,181,013
0
0
null
null
null
null
UTF-8
C++
false
false
227
h
#ifndef __SHIP_H #define __SHIP_H #include "entity.h" class cShip : public cEntity { // Funcs public: void thrust(float amount); void dampenSpeed(float amount); bool checkCollide(); }; #endif
1b24c31d5ee3bac78b60aaa805e1d51c3b8ab61a
6f7355a9cebf80857d12165f5159695c5aa2d6a5
/set_measurement_unit.h
ea047722c4c1fd90d7340ad0220ebbb6642e9cfd
[]
no_license
fengzhimiwu/my_popwil
814e48059833860682373732fe6178b7fd5acddd
fcaa859d6d4356d458d2d7b77d99616634541a3f
refs/heads/master
2023-05-28T02:42:44.969903
2020-05-05T10:53:37
2020-05-05T10:53:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
444
h
#ifndef SET_MEASUREMENT_UNIT_H #define SET_MEASUREMENT_UNIT_H #include <QDialog> #include <QTableWidget> namespace Ui { class set_measurement_unit; } class set_measurement_unit : public QDialog { Q_OBJECT public: explicit set_measurement_unit(QWidget *parent = 0); ~set_measurement_unit(); private: Ui::set_measurement_unit *ui; QTableWidget *change_unit; }; #endif // SET_MEASUREMENT_UNIT_H
f34645b605a883ab8061d8812f4eaa2dc6cd5648
b1697a5d8d1f480417f7c294f83e0d355b2ae0ad
/src/Zombie.h
a461d1a8eb7fe82748f1334823a383d284bcd316
[]
no_license
jkh920184196/Qt-PlantsVsZombies
385236057fae13380d88cded8c3ba309ca30184d
5d0c2780ceaba82b7efc4ae31017cdbc786fdf5c
refs/heads/master
2021-06-05T13:01:29.843994
2016-09-08T22:25:31
2016-09-08T22:25:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,253
h
// // Created by sun on 8/26/16. // #ifndef PLANTS_VS_ZOMBIES_ZOMBIE_H #define PLANTS_VS_ZOMBIES_ZOMBIE_H #include <QtCore> #include <QtWidgets> #include <QtMultimedia> class MoviePixmapItem; class GameScene; class PlantInstance; class Zombie { Q_DECLARE_TR_FUNCTIONS(Zombie) public: Zombie(); virtual ~Zombie() {} QString eName, cName; int width, height; int hp, level; qreal speed; int aKind, attack; bool canSelect, canDisplay; QString cardGif, staticGif, normalGif, attackGif, lostHeadGif, lostHeadAttackGif, headGif, dieGif, boomDieGif, standGif; int beAttackedPointL, beAttackedPointR; int breakPoint, sunNum; qreal coolTime; virtual bool canPass(int row) const; void update(); GameScene *scene; }; class Zombie1: public Zombie { Q_DECLARE_TR_FUNCTIONS(Zombie1) public: Zombie1(); }; class Zombie2: public Zombie1 { Q_DECLARE_TR_FUNCTIONS(Zombie2) public: Zombie2(); }; class Zombie3: public Zombie1 { Q_DECLARE_TR_FUNCTIONS(Zombie3) public: Zombie3(); }; class FlagZombie: public Zombie1 { Q_DECLARE_TR_FUNCTIONS(FlagZombie) public: FlagZombie(); }; class ZombieInstance { public: ZombieInstance(const Zombie *zombie); virtual ~ZombieInstance(); virtual void birth(int row); virtual void checkActs(); virtual void judgeAttack(); virtual void normalAttack(PlantInstance *plant); virtual void crushDie(); virtual void getPea(int attack, int direction); virtual void getHit(int attack); virtual void autoReduceHp(); virtual void normalDie(); virtual void playNormalballAudio(); QUuid uuid; int hp; qreal speed; int altitude; bool beAttacked, isAttacking, goingDie; qreal X, ZX; qreal attackedLX, attackedRX; int row; const Zombie *zombieProtoType; QString normalGif, attackGif; QGraphicsPixmapItem *shadowPNG; MoviePixmapItem *picture; QMediaPlayer *attackMusic, *hitMusic; }; class OrnZombie1: public Zombie1 { Q_DECLARE_TR_FUNCTIONS(OrnZombie1) public: int ornHp; QString ornLostNormalGif, ornLostAttackGif; }; class OrnZombieInstance1: public ZombieInstance { public: OrnZombieInstance1(const Zombie *zombie); const OrnZombie1 *getZombieProtoType(); virtual void getHit(int attack); int ornHp; bool hasOrnaments; }; class ConeheadZombie: public OrnZombie1 { Q_DECLARE_TR_FUNCTIONS(ConeheadZombie) public: ConeheadZombie(); }; class ConeheadZombieInstance: public OrnZombieInstance1 { public: ConeheadZombieInstance(const Zombie *zombie); virtual void playNormalballAudio(); }; class BucketheadZombie: public ConeheadZombie { Q_DECLARE_TR_FUNCTIONS(BucketheadZombie) public: BucketheadZombie(); }; class BucketheadZombieInstance: public OrnZombieInstance1 { public: BucketheadZombieInstance(const Zombie *zombie); virtual void playNormalballAudio(); }; class PoleVaultingZombie: public Zombie1 { Q_DECLARE_TR_FUNCTIONS(PoleVaultingZombie) public: PoleVaultingZombie(); }; Zombie *ZombieFactory(GameScene *scene, const QString &ename); ZombieInstance *ZombieInstanceFactory(const Zombie *zombie); #endif //PLANTS_VS_ZOMBIES_ZOMBIE_H
9211bfd7409897ed08d881fbe99e56799ea48bcf
73141cdef7f0a059d885bb061f9ba5f948431350
/include/ugu/renderer/base.h
5091074fcc377416bd4ba7bf48f0c945d6818a2f
[ "BSD-3-Clause" ]
permissive
PeterZhouSZ/ugu
60058fe8f90b0f065a7c65c02705cc8b6aae8334
e3c61565ef0acfb34a783f7efcc0d6fb7f4340ed
refs/heads/master
2023-06-02T17:14:08.917987
2020-05-19T14:39:10
2020-05-19T14:39:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,275
h
/* * Copyright (C) 2019, unclearness * All rights reserved. */ #pragma once #include <memory> #include <vector> #include "ugu/camera.h" #include "ugu/mesh.h" namespace ugu { // Diffuse color enum class DiffuseColor { kNone = 0, // Default white color kTexture = 1, // From diffuse uv texture kVertex = 2 // From vertex color }; // Normal used for shading // Also returned as output normal enum class ShadingNormal { kFace = 0, // Face normal kVertex = 1 // Vertex normal. Maybe average of face normals }; // Diffuse shading // Light ray same to viewing ray is used for shading enum class DiffuseShading { kNone = 0, // No shading kLambertian = 1, // Lambertian reflectance model kOrenNayar = 2 // Simplified Oren-Nayar reflectatnce model described in wikipedia // https://en.wikipedia.org/wiki/Oren%E2%80%93Nayar_reflectance_model }; // Interpolation method in texture uv space // Meaningful only if DiffuseColor::kTexture is specified otherwise ignored enum class ColorInterpolation { kNn = 0, // Nearest Neigbor kBilinear = 1 // Bilinear interpolation }; struct RendererOption { DiffuseColor diffuse_color{DiffuseColor::kNone}; ColorInterpolation interp{ColorInterpolation::kBilinear}; ShadingNormal shading_normal{ShadingNormal::kVertex}; DiffuseShading diffuse_shading{DiffuseShading::kNone}; float depth_scale{1.0f}; // Multiplied to output depth bool backface_culling{true}; // Back-face culling flag float oren_nayar_sigma{0.3f}; // Oren-Nayar's sigma RendererOption() {} ~RendererOption() {} void CopyTo(RendererOption* dst) const { dst->diffuse_color = diffuse_color; dst->depth_scale = depth_scale; dst->interp = interp; dst->shading_normal = shading_normal; dst->diffuse_shading = diffuse_shading; dst->backface_culling = backface_culling; } }; // interface (pure abstract base class with no state or defined methods) for // renderer class Renderer { public: virtual ~Renderer() {} // Set option virtual void set_option(const RendererOption& option) = 0; // Set mesh virtual void set_mesh(std::shared_ptr<const Mesh> mesh) = 0; // Should call after set_mesh() and before Render() // Don't modify mesh outside after calling PrepareMesh() virtual bool PrepareMesh() = 0; // Set camera virtual void set_camera(std::shared_ptr<const Camera> camera) = 0; // Rendering all images // If you don't need some of them, pass nullptr virtual bool Render(Image3b* color, Image1f* depth, Image3f* normal, Image1b* mask, Image1i* face_id) const = 0; // Rendering a image virtual bool RenderColor(Image3b* color) const = 0; virtual bool RenderDepth(Image1f* depth) const = 0; virtual bool RenderNormal(Image3f* normal) const = 0; virtual bool RenderMask(Image1b* mask) const = 0; virtual bool RenderFaceId(Image1i* face_id) const = 0; // These Image1w* depth interfaces are prepared for widely used 16 bit // (unsigned short) and mm-scale depth image format virtual bool RenderW(Image3b* color, Image1w* depth, Image3f* normal, Image1b* mask, Image1i* face_id) const = 0; virtual bool RenderDepthW(Image1w* depth) const = 0; }; } // namespace ugu
0889cd75092b4916668534ca1c615548bbf09b88
27e639ac647a99782a606e7814284ec91f925e36
/build_tmp_gcc/arm-linux-androideabi/libstdc++-v3/include/ext/pb_ds/detail/bin_search_tree_/node_iterators.hpp
1eb93e25f4ec0a3072bc0987cffbc334c7b80e56
[]
no_license
heliumfire/androux
6c063802f841988bb90b76322514bb46b8e52559
cbc1882f7841caef914f98711d9a78b9732bcc15
refs/heads/master
2021-01-02T22:38:29.582201
2015-01-12T09:51:28
2015-01-12T09:51:28
28,706,891
2
0
null
null
null
null
UTF-8
C++
false
false
106
hpp
/home/anushruth/exps/androux/gcc/libstdc++-v3/include/ext/pb_ds/detail/bin_search_tree_/node_iterators.hpp
81fb61c0989ba1e5f0cff1f71d3d229ae59497eb
4a61888ed98a9a042a00a26e76c010c2f73526e0
/lib/dg_cli.cc
51a5961a6420c5c41b3c78a87663a6c270de26bb
[]
no_license
nani0119/UNP
b37484363a1d23021b53befe1db36e5c3b51fa8a
c26db4f64728a5a89a6cddcfbb6e08dae2da9e0e
refs/heads/master
2022-11-15T04:28:25.908696
2020-07-15T02:02:41
2020-07-15T02:02:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,287
cc
#include "unp.h" namespace unp { void dg_cli(FILE *fp, int sockfd, const SA *pservaddr, socklen_t servlen) { int n; socklen_t len; char sendline[MAXLINE], recvline[MAXLINE + 1]; struct sockaddr* preply_addr; preply_addr =(struct sockaddr*) malloc(servlen); while (Fgets(sendline, MAXLINE, fp) != NULL) { if(Sendto(sockfd, sendline, strlen(sendline), 0, pservaddr, servlen) < 0) { err_quit("exit"); } len = servlen; n = Recvfrom(sockfd, recvline, MAXLINE, 0, preply_addr, &len); if(preply_addr->sa_family == AF_LOCAL) { if(memcmp(pservaddr, preply_addr, len) != 0) { printf("replay from %s (ignored)\n", Sock_ntop(preply_addr, len)); continue; } } else if(len != servlen || memcmp(pservaddr, preply_addr, len) != 0) { printf("replay from %s (ignored)\n", Sock_ntop(preply_addr, len)); continue; } recvline[n] = 0; /* null terminate */ Fputs(recvline, stdout); } // can not reach free(preply_addr); } }
357c5029ad7b79184c6d6cb8a9c09fae00ba9b8d
053d5e673a0b3da2eddb556fbac9b50042afe75a
/repeated-string.cpp
046ddb194ca4375efd536e8a4cc88cb9211bb32b
[]
no_license
powe0101/hackerrank
e990f1e48a29e471db4695d0e081d6ea0b6797e7
c76700ee4825487e03353a19fceca119bbba4857
refs/heads/master
2021-01-12T11:08:00.749765
2020-06-24T02:17:59
2020-06-24T02:17:59
72,836,436
0
0
null
null
null
null
UTF-8
C++
false
false
1,060
cpp
//https://www.hackerrank.com/challenges/repeated-string //Created by G([email protected]) #include <map> #include <set> #include <list> #include <cmath> #include <ctime> #include <deque> #include <queue> #include <stack> #include <string> #include <bitset> #include <cstdio> #include <limits> #include <vector> #include <climits> #include <cstring> #include <cstdlib> #include <fstream> #include <numeric> #include <sstream> #include <iostream> #include <algorithm> #include <unordered_map> using namespace std; long checkAstring(string s); int main(){ string s; cin >> s; long n; cin >> n; long count = checkAstring(s); long result = count * (n / s.size()); for(unsigned i =0; i < n%s.size(); ++i) if(s[i] == 'a') result += 1; cout << result << endl; return 0; } long checkAstring(string s){ long result = 0; string::iterator seek = s.begin(); string::iterator end = s.end(); for(; seek != end; ++seek) if(*seek == 'a') result += 1; return result; }
4c1c4aac6be56c95836546f6f40ae7142da141ba
ca13b19679add6020a9b456bbd1b31bd58156f4f
/main.cc
72dccdb846528dfbe384852d43f2d6f326e19ebb
[]
no_license
Lunderberg/lua-bindings
08f6527ce48b15315977c3ebfb3a0c732f1f86af
59de6723ccbab999724f097a6cdf020fdaacdc94
refs/heads/master
2021-07-06T08:14:22.043729
2021-04-10T03:02:31
2021-04-10T14:12:26
31,801,329
1
0
null
null
null
null
UTF-8
C++
false
false
341
cc
#include <iostream> #include <string> #include <tuple> #include "lua-bindings/LuaState.hh" int main(){ Lua::LuaState L; L.LoadSafeLibs(); L.LoadString("a = {'one', 'two', 'three'} " "for i,v in ipairs(a) do " " print(i,v) " "end "); L.LoadString("print(os.time())"); return 0; }
b5f929512e136e9f06cec1c172169e8e4c86cde7
5ebd5cee801215bc3302fca26dbe534e6992c086
/blazetest/src/mathtest/dvecdvecdiv/VDaV2b.cpp
fe1b15a3be61da736fb7d7ea34606f09199e1138
[ "BSD-3-Clause" ]
permissive
mhochsteger/blaze
c66d8cf179deeab4f5bd692001cc917fe23e1811
fd397e60717c4870d942055496d5b484beac9f1a
refs/heads/master
2020-09-17T01:56:48.483627
2019-11-20T05:40:29
2019-11-20T05:41:35
223,951,030
0
0
null
null
null
null
UTF-8
C++
false
false
3,759
cpp
//================================================================================================= /*! // \file src/mathtest/dvecdvecdiv/VDaV2b.cpp // \brief Source file for the VDaV2b dense vector/dense vector division math test // // Copyright (C) 2012-2019 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. Redistribution and use in source and binary // forms, with or without modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // 3. Neither the names of the Blaze development group 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. */ //================================================================================================= //************************************************************************************************* // Includes //************************************************************************************************* #include <cstdlib> #include <iostream> #include <blaze/math/DynamicVector.h> #include <blaze/math/StaticVector.h> #include <blazetest/mathtest/Creator.h> #include <blazetest/mathtest/dvecdvecdiv/OperationTest.h> #include <blazetest/system/MathTest.h> #ifdef BLAZE_USE_HPX_THREADS # include <hpx/hpx_main.hpp> #endif //================================================================================================= // // MAIN FUNCTION // //================================================================================================= //************************************************************************************************* int main() { std::cout << " Running 'VDaV2b'..." << std::endl; using blazetest::mathtest::TypeA; using blazetest::mathtest::TypeB; try { // Vector type definitions using VDa = blaze::DynamicVector<TypeA>; using V2b = blaze::StaticVector<TypeB,2UL>; // Creator type definitions using CVDa = blazetest::Creator<VDa>; using CV2b = blazetest::Creator<V2b>; // Running the tests RUN_DVECDVECDIV_OPERATION_TEST( CVDa( 2UL ), CV2b() ); } catch( std::exception& ex ) { std::cerr << "\n\n ERROR DETECTED during dense vector/dense vector division:\n" << ex.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } //*************************************************************************************************
f07cbe87f92fe94281d2956c9b268ae7abaadcf1
8dc84558f0058d90dfc4955e905dab1b22d12c08
/chrome/browser/safe_browsing/incident_reporting/last_download_finder.cc
66d0c89897bd203a0b5f995d6d497cdf322253f5
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
meniossin/src
42a95cc6c4a9c71d43d62bc4311224ca1fd61e03
44f73f7e76119e5ab415d4593ac66485e65d700a
refs/heads/master
2022-12-16T20:17:03.747113
2020-09-03T10:43:12
2020-09-03T10:43:12
263,710,168
1
0
BSD-3-Clause
2020-05-13T18:20:09
2020-05-13T18:20:08
null
UTF-8
C++
false
false
17,994
cc
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/safe_browsing/incident_reporting/last_download_finder.h" #include <stddef.h> #include <stdint.h> #include <algorithm> #include <functional> #include <utility> #include "base/bind.h" #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/history/history_service_factory.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/safe_browsing/incident_reporting/incident_reporting_service.h" #include "chrome/common/pref_names.h" #include "chrome/common/safe_browsing/download_protection_util.h" #include "chrome/common/safe_browsing/file_type_policies.h" #include "components/history/core/browser/download_constants.h" #include "components/history/core/browser/history_service.h" #include "components/language/core/common/locale_util.h" #include "components/prefs/pref_service.h" #include "components/safe_browsing/proto/csd.pb.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_source.h" #include "crypto/sha2.h" #include "extensions/buildflags/buildflags.h" namespace safe_browsing { namespace { // The following functions are overloaded for the two object types that // represent the metadata for a download: history::DownloadRow and // ClientIncidentReport_DownloadDetails. These are used by the template // functions that follow. // Returns the end time of a download represented by a DownloadRow. int64_t GetEndTime(const history::DownloadRow& row) { return row.end_time.ToJavaTime(); } // Returns the end time of a download represented by a DownloadDetails. int64_t GetEndTime(const ClientIncidentReport_DownloadDetails& details) { return details.download_time_msec(); } bool IsBinaryDownloadForCurrentOS( ClientDownloadRequest::DownloadType download_type) { // Whenever a new DownloadType is introduced, the following set of conditions // should also be updated so that the IsBinaryDownloadForCurrentOS() will // return true for that DownloadType as appropriate. static_assert(ClientDownloadRequest::DownloadType_MAX == ClientDownloadRequest::SAMPLED_UNSUPPORTED_FILE, "Update logic below"); // Platform-specific types are relevant only for their own platforms. #if defined(OS_MACOSX) if (download_type == ClientDownloadRequest::MAC_EXECUTABLE || download_type == ClientDownloadRequest::INVALID_MAC_ARCHIVE) return true; #elif defined(OS_ANDROID) if (download_type == ClientDownloadRequest::ANDROID_APK) return true; #endif // Extensions are supported where enabled. #if BUILDFLAG(ENABLE_EXTENSIONS) if (download_type == ClientDownloadRequest::CHROME_EXTENSION) return true; #endif if (download_type == ClientDownloadRequest::ZIPPED_EXECUTABLE || download_type == ClientDownloadRequest::ZIPPED_ARCHIVE || download_type == ClientDownloadRequest::INVALID_ZIP || download_type == ClientDownloadRequest::ARCHIVE || download_type == ClientDownloadRequest::PPAPI_SAVE_REQUEST) { return true; } // The default return value of download_protection_util::GetDownloadType is // ClientDownloadRequest::WIN_EXECUTABLE. return download_type == ClientDownloadRequest::WIN_EXECUTABLE; } // Returns true if a download represented by a DownloadRow is a binary file for // the current OS. bool IsBinaryDownload(const history::DownloadRow& row) { // TODO(grt): Peek into archives to see if they contain binaries; // http://crbug.com/386915. FileTypePolicies* policies = FileTypePolicies::GetInstance(); return (policies->IsCheckedBinaryFile(row.target_path) && !policies->IsArchiveFile(row.target_path) && IsBinaryDownloadForCurrentOS( download_protection_util::GetDownloadType(row.target_path))); } // Returns true if a download represented by a DownloadRow is not a binary file. bool IsNonBinaryDownload(const history::DownloadRow& row) { return !FileTypePolicies::GetInstance()->IsCheckedBinaryFile( row.target_path); } // Returns true if a download represented by a DownloadDetails is binary file // for the current OS. bool IsBinaryDownload(const ClientIncidentReport_DownloadDetails& details) { // DownloadDetails are only generated for binary downloads. return IsBinaryDownloadForCurrentOS(details.download().download_type()); } // Returns true if a download represented by a DownloadRow has been opened. bool HasBeenOpened(const history::DownloadRow& row) { return row.opened; } // Returns true if a download represented by a DownloadDetails has been opened. bool HasBeenOpened(const ClientIncidentReport_DownloadDetails& details) { return details.has_open_time_msec() && details.open_time_msec(); } // Returns true if |first| is more recent than |second|, preferring opened over // non-opened for downloads that completed at the same time (extraordinarily // unlikely). Only files that look like some kind of executable are considered. template <class A, class B> bool IsMoreInterestingBinaryThan(const A& first, const B& second) { if (GetEndTime(first) < GetEndTime(second) || !IsBinaryDownload(first)) return false; return (GetEndTime(first) != GetEndTime(second) || (HasBeenOpened(first) && !HasBeenOpened(second))); } // Returns true if |first| is more recent than |second|, preferring opened over // non-opened for downloads that completed at the same time (extraordinarily // unlikely). Only files that do not look like an executable are considered. bool IsMoreInterestingNonBinaryThan(const history::DownloadRow& first, const history::DownloadRow& second) { if (GetEndTime(first) < GetEndTime(second) || !IsNonBinaryDownload(first)) return false; return (GetEndTime(first) != GetEndTime(second) || (HasBeenOpened(first) && !HasBeenOpened(second))); } // Returns a pointer to the most interesting completed download in |downloads|. const history::DownloadRow* FindMostInteresting( const std::vector<history::DownloadRow>& downloads, bool is_binary) { const history::DownloadRow* most_recent_row = nullptr; for (const auto& row : downloads) { // Ignore incomplete downloads. if (row.state != history::DownloadState::COMPLETE) continue; if (!most_recent_row || (is_binary ? IsMoreInterestingBinaryThan(row, *most_recent_row) : IsMoreInterestingNonBinaryThan(row, *most_recent_row))) { most_recent_row = &row; } } return most_recent_row; } // Returns true if |candidate| is more interesting than whichever of |details| // or |best_row| is present. template <class D> bool IsMostInterestingBinary( const D& candidate, const ClientIncidentReport_DownloadDetails* details, const history::DownloadRow& best_row) { return details ? IsMoreInterestingBinaryThan(candidate, *details) : IsMoreInterestingBinaryThan(candidate, best_row); } // Populates the |details| protobuf with information pertaining to |download|. void PopulateDetailsFromRow(const history::DownloadRow& download, ClientIncidentReport_DownloadDetails* details) { ClientDownloadRequest* download_request = details->mutable_download(); download_request->set_url(download.url_chain.back().spec()); // digests is a required field, so force it to exist. // TODO(grt): Include digests in reports; http://crbug.com/389123. ignore_result(download_request->mutable_digests()); download_request->set_length(download.received_bytes); for (size_t i = 0; i < download.url_chain.size(); ++i) { const GURL& url = download.url_chain[i]; ClientDownloadRequest_Resource* resource = download_request->add_resources(); resource->set_url(url.spec()); if (i != download.url_chain.size() - 1) { // An intermediate redirect. resource->set_type(ClientDownloadRequest::DOWNLOAD_REDIRECT); } else { // The final download URL. resource->set_type(ClientDownloadRequest::DOWNLOAD_URL); if (!download.referrer_url.is_empty()) resource->set_referrer(download.referrer_url.spec()); } } download_request->set_file_basename( download.target_path.BaseName().AsUTF8Unsafe()); download_request->set_download_type( download_protection_util::GetDownloadType(download.target_path)); std::string pref_locale = g_browser_process->local_state()->GetString(prefs::kApplicationLocale); language::ConvertToActualUILocale(&pref_locale); download_request->set_locale(pref_locale); details->set_download_time_msec(download.end_time.ToJavaTime()); // Opened time is unknown for now, so use the download time if the file was // opened in Chrome. if (download.opened) details->set_open_time_msec(download.end_time.ToJavaTime()); } // Populates the |details| protobuf with information pertaining to the // (non-binary) |download|. void PopulateNonBinaryDetailsFromRow( const history::DownloadRow& download, ClientIncidentReport_NonBinaryDownloadDetails* details) { details->set_file_type( base::FilePath(FileTypePolicies::GetFileExtension(download.target_path)) .AsUTF8Unsafe()); details->set_length(download.received_bytes); if (download.url_chain.back().has_host()) details->set_host(download.url_chain.back().host()); details->set_url_spec_sha256( crypto::SHA256HashString(download.url_chain.back().spec())); } } // namespace LastDownloadFinder::~LastDownloadFinder() { } // static std::unique_ptr<LastDownloadFinder> LastDownloadFinder::Create( const DownloadDetailsGetter& download_details_getter, const LastDownloadCallback& callback) { std::unique_ptr<LastDownloadFinder> finder( base::WrapUnique(new LastDownloadFinder( download_details_getter, g_browser_process->profile_manager()->GetLoadedProfiles(), callback))); // Return NULL if there is no work to do. if (finder->profile_states_.empty()) return std::unique_ptr<LastDownloadFinder>(); return finder; } LastDownloadFinder::LastDownloadFinder() : history_service_observer_(this), weak_ptr_factory_(this) { } LastDownloadFinder::LastDownloadFinder( const DownloadDetailsGetter& download_details_getter, const std::vector<Profile*>& profiles, const LastDownloadCallback& callback) : download_details_getter_(download_details_getter), callback_(callback), history_service_observer_(this), weak_ptr_factory_(this) { // Observe profile lifecycle events so that the finder can begin or abandon // the search in profiles while it is running. notification_registrar_.Add(this, chrome::NOTIFICATION_PROFILE_ADDED, content::NotificationService::AllSources()); notification_registrar_.Add(this, chrome::NOTIFICATION_PROFILE_DESTROYED, content::NotificationService::AllSources()); // Begin the search for all given profiles. for (auto* profile : profiles) SearchInProfile(profile); } void LastDownloadFinder::SearchInProfile(Profile* profile) { // Do not look in OTR profiles or in profiles that do not participate in // safe browsing extended reporting. if (!IncidentReportingService::IsEnabledForProfile(profile)) return; // Exit early if already processing this profile. This could happen if, for // example, NOTIFICATION_PROFILE_ADDED arrives after construction while // waiting for OnHistoryServiceLoaded. if (profile_states_.count(profile)) return; // Initiate a metadata search. profile_states_[profile] = WAITING_FOR_METADATA; download_details_getter_.Run(profile, base::Bind(&LastDownloadFinder::OnMetadataQuery, weak_ptr_factory_.GetWeakPtr(), profile)); } void LastDownloadFinder::OnMetadataQuery( Profile* profile, std::unique_ptr<ClientIncidentReport_DownloadDetails> details) { auto iter = profile_states_.find(profile); // Early-exit if the search for this profile was abandoned. if (iter == profile_states_.end()) return; if (details) { if (IsMostInterestingBinary(*details, details_.get(), most_recent_binary_row_)) { details_ = std::move(details); most_recent_binary_row_.end_time = base::Time(); } iter->second = WAITING_FOR_NON_BINARY_HISTORY; } else { iter->second = WAITING_FOR_HISTORY; } // Initiate a history search history::HistoryService* history_service = HistoryServiceFactory::GetForProfile(profile, ServiceAccessType::IMPLICIT_ACCESS); // No history service is returned for profiles that do not save history. if (!history_service) { RemoveProfileAndReportIfDone(iter); return; } if (history_service->BackendLoaded()) { history_service->QueryDownloads( base::Bind(&LastDownloadFinder::OnDownloadQuery, weak_ptr_factory_.GetWeakPtr(), profile)); } else { // else wait until history is loaded. history_service_observer_.Add(history_service); } } void LastDownloadFinder::AbandonSearchInProfile(Profile* profile) { // |profile| may not be present in the set of profiles. auto iter = profile_states_.find(profile); if (iter != profile_states_.end()) RemoveProfileAndReportIfDone(iter); } void LastDownloadFinder::OnDownloadQuery( Profile* profile, std::unique_ptr<std::vector<history::DownloadRow>> downloads) { // Early-exit if the history search for this profile was abandoned. auto iter = profile_states_.find(profile); if (iter == profile_states_.end()) return; // Don't overwrite the download from metadata if it came from this profile. if (iter->second == WAITING_FOR_HISTORY) { // Find the most recent from this profile and use it if it's better than // anything else found so far. const history::DownloadRow* profile_best_binary = FindMostInteresting(*downloads, true); if (profile_best_binary && IsMostInterestingBinary(*profile_best_binary, details_.get(), most_recent_binary_row_)) { details_.reset(); most_recent_binary_row_ = *profile_best_binary; } } const history::DownloadRow* profile_best_non_binary = FindMostInteresting(*downloads, false); if (profile_best_non_binary && IsMoreInterestingNonBinaryThan(*profile_best_non_binary, most_recent_non_binary_row_)) { most_recent_non_binary_row_ = *profile_best_non_binary; } RemoveProfileAndReportIfDone(iter); } void LastDownloadFinder::RemoveProfileAndReportIfDone( std::map<Profile*, ProfileWaitState>::iterator iter) { DCHECK(iter != profile_states_.end()); profile_states_.erase(iter); // Finish processing if all results are in. if (profile_states_.empty()) ReportResults(); // Do not touch this LastDownloadFinder after reporting results. } void LastDownloadFinder::ReportResults() { DCHECK(profile_states_.empty()); std::unique_ptr<ClientIncidentReport_DownloadDetails> binary_details = nullptr; std::unique_ptr<ClientIncidentReport_NonBinaryDownloadDetails> non_binary_details = nullptr; if (details_) { binary_details.reset(new ClientIncidentReport_DownloadDetails(*details_)); } else if (!most_recent_binary_row_.end_time.is_null()) { binary_details.reset(new ClientIncidentReport_DownloadDetails()); PopulateDetailsFromRow(most_recent_binary_row_, binary_details.get()); } if (!most_recent_non_binary_row_.end_time.is_null()) { non_binary_details.reset( new ClientIncidentReport_NonBinaryDownloadDetails()); PopulateNonBinaryDetailsFromRow(most_recent_non_binary_row_, non_binary_details.get()); } callback_.Run(std::move(binary_details), std::move(non_binary_details)); // Do not touch this LastDownloadFinder after running the callback, since it // may have been deleted. } void LastDownloadFinder::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { switch (type) { case chrome::NOTIFICATION_PROFILE_ADDED: SearchInProfile(content::Source<Profile>(source).ptr()); break; case chrome::NOTIFICATION_PROFILE_DESTROYED: AbandonSearchInProfile(content::Source<Profile>(source).ptr()); break; default: break; } } void LastDownloadFinder::OnHistoryServiceLoaded( history::HistoryService* history_service) { for (const auto& pair : profile_states_) { history::HistoryService* hs = HistoryServiceFactory::GetForProfileIfExists( pair.first, ServiceAccessType::EXPLICIT_ACCESS); if (hs == history_service) { // Start the query in the history service if the finder was waiting for // the service to load. if (pair.second == WAITING_FOR_HISTORY || pair.second == WAITING_FOR_NON_BINARY_HISTORY) { history_service->QueryDownloads( base::Bind(&LastDownloadFinder::OnDownloadQuery, weak_ptr_factory_.GetWeakPtr(), pair.first)); } return; } } } void LastDownloadFinder::HistoryServiceBeingDeleted( history::HistoryService* history_service) { history_service_observer_.Remove(history_service); } } // namespace safe_browsing
7fb6c7c147e1b06091f4e8a05e2fbd29e99712b6
fab5498a07621a3a1fe642aba754d3efeb582017
/src/osg/wrappers/BufferData_wrap.cpp
861b2742309d585c4c61da6fa36c74214e59ba10
[ "MIT" ]
permissive
vuvk/osg_vala_wrapper
e0beb1cdde040a1ac0917be40cbab7c333a63bc9
1d764277926a745844f8f7a9e5e1fe46f128bed1
refs/heads/master
2022-10-08T16:58:42.617097
2020-06-09T03:47:43
2020-06-09T03:47:43
268,712,396
2
0
null
null
null
null
UTF-8
C++
false
false
46
cpp
#include <osg/BufferObject> extern "C" { }
bb8c2c1e0361eaaa1c92134152a49cf34e3d7a27
1d60b962456da3a0dcf8a5dbd82c72cf1be42521
/include/fruit/impl/injector.defn.h
eb518896741963c5f904bfa46a11a54ab43de0e2
[ "Apache-2.0" ]
permissive
txxia/fruit
9ac02fa28823197697eae1fc6d1e3164f67886d7
b645d155220b21d81b0080c4f2a0ed3985d40689
refs/heads/master
2021-01-01T20:36:02.085118
2017-07-30T20:55:52
2017-07-30T20:55:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,686
h
/* * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef FRUIT_INJECTOR_DEFN_H #define FRUIT_INJECTOR_DEFN_H #include <fruit/component.h> // Redundant, but makes KDevelop happy. #include <fruit/injector.h> namespace fruit { template <typename... P> inline Injector<P...>::Injector(Component<P...> component) { fruit::impl::MemoryPool memory_pool; using exposed_types_t = std::vector<fruit::impl::TypeId, fruit::impl::ArenaAllocator<fruit::impl::TypeId>>; exposed_types_t exposed_types = exposed_types_t( std::initializer_list<fruit::impl::TypeId>{fruit::impl::getTypeId<P>()...}, fruit::impl::ArenaAllocator<fruit::impl::TypeId>(memory_pool)); storage = std::unique_ptr<fruit::impl::InjectorStorage>( new fruit::impl::InjectorStorage( std::move(component.storage), exposed_types, fruit::impl::getTypeId<Component<P...>(*)()>(), memory_pool)); } namespace impl { namespace meta { template <typename... P> struct InjectorImplHelper { // This performs all checks needed in the constructor of Injector that takes NormalizedComponent. template <typename NormalizedComp, typename Comp> struct CheckConstructionFromNormalizedComponent { using Op = InstallComponent(Comp, NormalizedComp); // The calculation of MergedComp will also do some checks, e.g. multiple bindings for the same type. using MergedComp = GetResult(Op); using TypesNotProvided = SetDifference(RemoveConstFromTypes(Vector<Type<P>...>), GetComponentPs(MergedComp)); using MergedCompRs = SetDifference(GetComponentRsSuperset(MergedComp), GetComponentPs(MergedComp)); using type = Eval< If(Not(IsEmptySet(GetComponentRsSuperset(Comp))), ConstructErrorWithArgVector(ComponentWithRequirementsInInjectorErrorTag, SetToVector(GetComponentRsSuperset(Comp))), If(Not(IsEmptySet(MergedCompRs)), ConstructErrorWithArgVector(UnsatisfiedRequirementsInNormalizedComponentErrorTag, SetToVector(MergedCompRs)), If(Not(IsContained(VectorToSetUnchecked(RemoveConstFromTypes(Vector<Type<P>...>)), GetComponentPs(MergedComp))), ConstructErrorWithArgVector(TypesInInjectorNotProvidedErrorTag, SetToVector(TypesNotProvided)), If(Not(IsContained(VectorToSetUnchecked(RemoveConstTypes(Vector<Type<P>...>)), GetComponentNonConstRsPs(MergedComp))), ConstructErrorWithArgVector(TypesInInjectorProvidedAsConstOnlyErrorTag, SetToVector(SetDifference(VectorToSetUnchecked(RemoveConstTypes(Vector<Type<P>...>)), GetComponentNonConstRsPs(MergedComp)))), None))))>; }; template <typename T> struct CheckGet { using Comp = ConstructComponentImpl(Type<P>...); using type = Eval< PropagateError(CheckInjectableType(RemoveAnnotations(Type<T>)), If(Not(IsInSet(NormalizeType(Type<T>), GetComponentPs(Comp))), ConstructError(TypeNotProvidedErrorTag, Type<T>), If(And(TypeInjectionRequiresNonConstBinding(Type<T>), Not(IsInSet(NormalizeType(Type<T>), GetComponentNonConstRsPs(Comp)))), ConstructError(TypeProvidedAsConstOnlyErrorTag, Type<T>), None)))>; }; }; } // namespace meta } // namespace impl template <typename... P> template <typename... NormalizedComponentParams, typename... ComponentParams> inline Injector<P...>::Injector(const NormalizedComponent<NormalizedComponentParams...>& normalized_component, Component<ComponentParams...> component) { fruit::impl::MemoryPool memory_pool; storage = std::unique_ptr<fruit::impl::InjectorStorage>( new fruit::impl::InjectorStorage( *(normalized_component.storage.storage), std::move(component.storage), fruit::impl::getTypeId<Component<P...>(*)()>(), memory_pool)); using NormalizedComp = fruit::impl::meta::ConstructComponentImpl(fruit::impl::meta::Type<NormalizedComponentParams>...); using Comp1 = fruit::impl::meta::ConstructComponentImpl(fruit::impl::meta::Type<ComponentParams>...); // We don't check whether the construction of NormalizedComp or Comp resulted in errors here; if they did, the instantiation // of NormalizedComponent<NormalizedComponentParams...> or Component<ComponentParams...> would have resulted in an error already. using E = typename fruit::impl::meta::InjectorImplHelper<P...>::template CheckConstructionFromNormalizedComponent<NormalizedComp, Comp1>::type; (void)typename fruit::impl::meta::CheckIfError<E>::type(); } template <typename... P> template <typename T> inline Injector<P...>::RemoveAnnotations<T> Injector<P...>::get() { using E = typename fruit::impl::meta::InjectorImplHelper<P...>::template CheckGet<T>::type; (void)typename fruit::impl::meta::CheckIfError<E>::type(); return storage->template get<T>(); } template <typename... P> template <typename T> inline Injector<P...>::operator T() { return get<T>(); } template <typename... P> template <typename AnnotatedC> inline const std::vector< typename fruit::Injector<P...>::template RemoveAnnotationsHelper<AnnotatedC>::type *>& Injector<P...>::getMultibindings() { using Op = fruit::impl::meta::Eval< fruit::impl::meta::CheckNormalizedTypes( fruit::impl::meta::Vector< fruit::impl::meta::Type<AnnotatedC>>)>; (void)typename fruit::impl::meta::CheckIfError<Op>::type(); return storage->template getMultibindings<AnnotatedC>(); } template <typename... P> inline void Injector<P...>::eagerlyInjectAll() { // Eagerly inject normal bindings. void* unused[] = {reinterpret_cast<void*>(storage->template get<fruit::impl::meta::UnwrapType<fruit::impl::meta::Eval<fruit::impl::meta::AddPointerInAnnotatedType(fruit::impl::meta::Type<P>)>>>())...}; (void)unused; storage->eagerlyInjectMultibindings(); } } // namespace fruit #endif // FRUIT_INJECTOR_DEFN_H
2c50b9660909344c0f3495d522ce9acfca846773
04b1abce39ba6c07bc3a9f57ce372041056a11c1
/myGame/myGame/Object.h
65b0354fe183a41020e9de3f1383c2b5f32bacd3
[]
no_license
890popbox/collision_test
a6e56d7f6e3649ae2e6e6c39570a769590eb3e6f
ea37bdafb7306af854363624ff883d61a91eb76f
refs/heads/master
2022-12-12T04:56:31.358167
2020-09-05T03:53:24
2020-09-05T03:53:24
292,993,195
0
0
null
null
null
null
UTF-8
C++
false
false
531
h
#ifndef GAME_OBJECT #define GAME_OBJECT #include "../Engine/Graphics/Sprite.h" #include "../Engine/Physics/Rigidbody.h" #include "../Engine/Math/Rect.h" class Object { public: Object(); Object(Sprite _sprite); void setGravity(int x); void Update(); void Render(); void EndRender(); void straightenOb(); void flap(); //Accessors Sprite& GetSprite(); Rigidbody& GetRB(); private: Sprite sprite; Rigidbody rb; Rect boundingRect; float objectForce; float maxRot; float minRot; float straightSpot; }; #endif
3649143baa7fe96ae471256a32e09f90b857f001
3835370277ec24dd6135c4adfd5317dbc1d4ccc6
/osgtoy/trunk/src/osgPlugins/simplifier/ReaderWriterSIMPLIFIER.cpp
2d5854d0702801d390a74fbefb351afe56c572c3
[ "BSD-3-Clause", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
rendergather/osgtoy
d1c9bd3bcb65e6c6bd31ecbad930131c3723b915
d66fbffa134e8c1be43d9eee4b389c8376a31db1
refs/heads/master
2021-05-11T12:53:39.910986
2015-10-21T08:27:37
2015-10-21T08:27:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,176
cpp
/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2004 Robert Osfield * * This application is open source and may be redistributed and/or modified * freely and without restriction, both in commericial and non commericial * applications, as long as this copyright notice is maintained. * * This application 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. * */ /* file: src/osgPlugins/simplifier/ReaderWriterSIMPLIFIER.cpp * author: Mike Weiblen * copyright: (C) 2004-2006 Michael Weiblen http://mew.cx/ * license: OpenSceneGraph Public License (OSGPL) * $Id$ */ #include <osg/Notify> #include <osgDB/ReaderWriter> #include <osgDB/FileNameUtils> #include <osgDB/Registry> #include <osgDB/ReadFile> #include <osgUtil/Simplifier> #include <stdio.h> #define EXTENSION_NAME "simplifier" /////////////////////////////////////////////////////////////////////////// /** * An OSG reader plugin for the ".simplifier" pseudo-loader, which runs * osgUtil::Simplifier on the loaded model. * This pseudo-loader makes it simple to simplify a saved model by * specifying a correcting sampling percentage as part of the filename. * * Usage: <modelfile.ext>.<sp>.simplifier * where: * <modelfile.ext> = an model filename. * <sp> = sampling percentage (integer, 1 to 100) * * example: osgviewer cow.osg.20.simplifier */ class ReaderWriterSIMPLIFIER : public osgDB::ReaderWriter { public: ReaderWriterSIMPLIFIER() { supportsExtension( EXTENSION_NAME, "osgUtil::Simplifier pseudo-loader" ); } const char* className() const { return "osgUtil::Simplifier pseudo-loader"; } ReadResult readNode(const std::string& fileName, const osgDB::ReaderWriter::Options* options) const { std::string ext( osgDB::getLowerCaseFileExtension(fileName) ); if( !acceptsExtension(ext) ) return ReadResult::FILE_NOT_HANDLED; osg::notify(osg::INFO) << "ReaderWriterSIMPLIFIER( \"" << fileName << "\" )" << std::endl; // strip the pseudo-loader extension std::string tmpName( osgDB::getNameLessExtension(fileName) ); // get the next "extension", which actually contains the pseudo-loader parameters std::string params( osgDB::getFileExtension(tmpName) ); if( params.empty() ) { osg::notify(osg::WARN) << "Missing parameters for " EXTENSION_NAME " pseudo-loader" << std::endl; return ReadResult::FILE_NOT_HANDLED; } // strip the "params extension", which must leave a sub-filename. std::string subFileName( osgDB::getNameLessExtension(tmpName) ); if( subFileName == tmpName ) { osg::notify(osg::WARN) << "Missing subfilename for " EXTENSION_NAME " pseudo-loader" << std::endl; return ReadResult::FILE_NOT_HANDLED; } osg::notify(osg::INFO) << EXTENSION_NAME " params = \"" << params << "\"" << std::endl; int samplePercentage; int count( sscanf( params.c_str(), "%d", &samplePercentage ) ); if( (count != 1) || (samplePercentage < 1) || (samplePercentage > 100) ) { osg::notify(osg::WARN) << "Bad parameters for " EXTENSION_NAME " pseudo-loader: \"" << params << "\"" << std::endl; return ReadResult::FILE_NOT_HANDLED; } // recursively load the subfile. osg::Node *node( osgDB::readNodeFile( subFileName, options ) ); if( !node ) { // propagate the read failure upwards osg::notify(osg::WARN) << "Subfile \"" << subFileName << "\" could not be loaded" << std::endl; return ReadResult::FILE_NOT_HANDLED; } float sampleRatio( samplePercentage / 100.0 ); osgUtil::Simplifier simplifier( sampleRatio ); node->accept( simplifier ); return node; } }; // Add ourself to the Registry to instantiate the reader/writer. osgDB::RegisterReaderWriterProxy<ReaderWriterSIMPLIFIER> g_readerWriter_SIMPLIFIER_Proxy; // vim: set sw=4 ts=8 et ic ai:
468aaed7255022f01b1f200cbb7f72a6473c6748
651cbae33f34feeb9b45931910c1ba83cb48ba69
/SP3_Framework/App/Source/Scene2D/Bullets2D.cpp
be8f800c1cf9a5f5e22dab7bacce746263ce0c8f
[]
no_license
beatsmoon/SP3
0fa605a1fa16794a0f6eeb8a8d20185021cb3507
2abc6c9d3609544dda9888569f8714ee67d3ffa4
refs/heads/master
2022-12-03T08:10:01.618874
2020-08-20T04:52:26
2020-08-20T04:52:26
288,071,534
0
0
null
2020-08-19T09:05:29
2020-08-17T03:07:51
C++
UTF-8
C++
false
false
11,370
cpp
#include "Bullets2D.h" #include <iostream> using namespace std; // Include GLEW #include <GL/glew.h> // Include ImageLoader #include "System\ImageLoader.h" // Include the Map2D as we will use it to check the player's movements and actions #include "Map2D.h" #include "Entity2DFactory.h" CBullets2D::CBullets2D() : cMap2D(NULL) , cSettings(NULL) , isActive(false) { transform = glm::mat4(1.0f); // make sure to initialize matrix to identity matrix first // Initialise vecIndex i32vec2Index = glm::i32vec2(0); // Initialise vecNumMicroSteps i32vec2NumMicroSteps = glm::i32vec2(0); // Initialise vec2UVCoordinate vec2UVCoordinate = glm::vec2(0.0f); } CBullets2D::~CBullets2D() { // We won't delete this since it was created elsewhere cMap2D = NULL; glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); glDeleteBuffers(1, &EBO); } bool CBullets2D::Init(void) { // Get the handler to the CSettings instance cSettings = CSettings::GetInstance(); // Get the handler to the CMap2D instance cMap2D = CMap2D::GetInstance(); // set up vertex data (and buffer(s)) and configure vertex attributes float vertices[] = { // positions // texture coords (cSettings->TILE_WIDTH / 2.0f), (cSettings->TILE_HEIGHT / 2.0f), 0.0f, 1.0f, 1.0f, // top right (cSettings->TILE_WIDTH / 2.0f), -(cSettings->TILE_HEIGHT / 2.0f), 0.0f, 1.0f, 0.0f, // bottom right -(cSettings->TILE_WIDTH / 2.0f), -(cSettings->TILE_HEIGHT / 2.0f), 0.0f, 0.0f, 0.0f, // bottom left -(cSettings->TILE_WIDTH / 2.0f), (cSettings->TILE_HEIGHT / 2.0f), 0.0f, 0.0f, 1.0f // top left }; unsigned int indices[] = { 0, 1, 3, // first triangle 1, 2, 3 // second triangle }; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenBuffers(1, &EBO); glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); // position attribute glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); // texture coord attribute glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float))); glEnableVertexAttribArray(1); // Load the player texture if (LoadTexture("Images/shooting_bullets.tga", iTextureID) == false) { std::cout << "Failed to load bullets sprite texture" << std::endl; return false; } isActive = true; } void CBullets2D::Update(const double dElapsedTime) { if (cAnimatedSprites.isFacingRight == true) { const int iOldIndex = i32vec2Index.x; // moving bullet right i32vec2NumMicroSteps.x += 3; if (i32vec2NumMicroSteps.x >= cSettings->NUM_STEPS_PER_TILE_XAXIS) { i32vec2NumMicroSteps.x = 0; i32vec2Index.x++; } // Constraint the Bullet's position within the screen boundary Constraint(RIGHT); // checking if bullet is near obsticle if (FindFeasiblePosition(iOldIndex, RIGHT) == true) { i32vec2Index.x = NULL; i32vec2Index.y = NULL; isActive = false; } } else { //cout << "VK_LEFT is called" << endl; const int iOldIndex = i32vec2Index.x; // moving player left i32vec2NumMicroSteps.x -= 3; if (i32vec2NumMicroSteps.x < 0) { i32vec2NumMicroSteps.x = (int)(cSettings->NUM_STEPS_PER_TILE_XAXIS) - 1; i32vec2Index.x--; } // Constraint the player's position within the screen boundary Constraint(LEFT); // FindFeasiblePosition if (FindFeasiblePosition(iOldIndex, LEFT) == true) { i32vec2Index.x = NULL; i32vec2Index.y = NULL; isActive = false; } } std::vector<CEntity2D*> it = CEntity2DFactory::GetInstance()->FindAllEntity(CEntity2D::TYPE::ENEMY); for (std::vector<CEntity2D*>::iterator itt = it.begin(); itt != it.end(); ++itt) { CEnemy2D* go = static_cast<CEnemy2D*>((CEntity2D*)*itt); if (i32vec2Index.x == go->Geti32vec2Index().x && i32vec2Index.y == go->Geti32vec2Index().y) { CPlayer2D* c = CPlayer2D::GetInstance(); int s = c->GetScore(); c->SetScore(s += 20); //isActive = 0; go->SetIsActive(0); } } vec2UVCoordinate.x = cSettings->ConvertIndexToUVSpace(cSettings->x, i32vec2Index.x, false, i32vec2NumMicroSteps.x * cSettings->MICRO_STEP_XAXIS); vec2UVCoordinate.y = cSettings->ConvertIndexToUVSpace(cSettings->y, i32vec2Index.y, false, i32vec2NumMicroSteps.y * cSettings->MICRO_STEP_YAXIS); } void CBullets2D::PreRender(void) { // bind textures on corresponding texture units glActiveTexture(GL_TEXTURE0); // Activate blending mode glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Activate the shader cShader->use(); } void CBullets2D::Render(void) { //cout << i32vec2Index.x << " " << i32vec2Index.y << endl; //cout << vec2UVCoordinate.x << endl; // get matrix's uniform location and set matrix if (isActive != false) { unsigned int transformLoc = glGetUniformLocation(cShader->ID, "transform"); glUniformMatrix4fv(transformLoc, 1, GL_FALSE, glm::value_ptr(transform)); transform = glm::mat4(1.0f); // make sure to initialize matrix to identity matrix first transform = glm::translate(transform, glm::vec3(vec2UVCoordinate.x, vec2UVCoordinate.y, 0.0f)); // Update the shaders with the latest transform glUniformMatrix4fv(transformLoc, 1, GL_FALSE, glm::value_ptr(transform)); // Get the texture to be rendered glBindTexture(GL_TEXTURE_2D, iTextureID); glBindVertexArray(VAO); // Render the tile glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); glBindVertexArray(0); } //unsigned int transformLoc = glGetUniformLocation(cShader->ID, "transform"); //glUniformMatrix4fv(transformLoc, 1, GL_FALSE, glm::value_ptr(transform)); //transform = glm::mat4(1.0f); // make sure to initialize matrix to identity matrix first //transform = glm::translate(transform, glm::vec3(vec2UVCoordinate.x, // vec2UVCoordinate.y, // 0.0f)); //// Update the shaders with the latest transform //glUniformMatrix4fv(transformLoc, 1, GL_FALSE, glm::value_ptr(transform)); //// Get the texture to be rendered //glBindTexture(GL_TEXTURE_2D, iTextureID); //glBindVertexArray(VAO); //// Render the tile //glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); //glBindVertexArray(0); } bool CBullets2D::LoadTexture(const char* filename, GLuint& iTextureID) { // Variables used in loading the texture int width, height, nrChannels; // texture 1 // --------- glGenTextures(1, &iTextureID); glBindTexture(GL_TEXTURE_2D, iTextureID); // set the texture wrapping parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // set texture filtering parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); CImageLoader* cImageLoader = CImageLoader::GetInstance(); unsigned char* data = cImageLoader->Load(filename, width, height, nrChannels, true); if (data) { if (nrChannels == 3) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); else if (nrChannels == 4) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); // Generate mipmaps glGenerateMipmap(GL_TEXTURE_2D); } else { return false; } // Free up the memory of the file data read in free(data); return true; } void CBullets2D::Constraint(BULLETDIRECTION eDirection) { if (eDirection == LEFT) { if (i32vec2Index.x < 0) { i32vec2Index.x = 0; i32vec2NumMicroSteps.x = 0; i32vec2Index.x = NULL; i32vec2Index.y = NULL; isActive = false; } } else { if (i32vec2Index.x >= ((int)(cSettings->NUM_TILES_XAXIS)) - 1) { i32vec2Index.x = ((int)(cSettings->NUM_TILES_XAXIS)) - 1; i32vec2NumMicroSteps.x = 0; i32vec2Index.x = NULL; i32vec2Index.y = NULL; isActive = false; } } } void CBullets2D::InteractWithMap(void) { } bool CBullets2D::FindFeasiblePosition(const int iOldIndex, BULLETDIRECTION eDirection) { bool state = false; if (eDirection == LEFT) { // If the player within the screen boundary, then check further if ((i32vec2NumMicroSteps.x != 0) && (i32vec2Index.x >= 0)) { // Check if this new position is not accessible, then go back to old position if (cMap2D->GetMapInfo(i32vec2Index.y, i32vec2Index.x) == 1) // 1 is wall in map.csv if thrs are many diff kind of wall a range of number is more suitable { // Snap to the previous index i32vec2Index.x = iOldIndex; // Reset the i32vec2NumMicroSteps.x so that the player is aligned to the column i32vec2NumMicroSteps.x = 0; state = true; } // If the new position is between 2 rows, then check the other row as well if (i32vec2NumMicroSteps.y != 0) { // If the new position is not feasible, then go back to the old position if (cMap2D->GetMapInfo(i32vec2Index.y + 1, i32vec2Index.x) == 1) { // Snap to the previous index i32vec2Index.x = iOldIndex; // Reset the i32vec2NumMicroSteps.x so that the player is aligned to the column i32vec2NumMicroSteps.x = 0; state = true; } } } } else if (eDirection == RIGHT) { // If the player within the screen boundary, then check further if ((i32vec2NumMicroSteps.x != 0) && (i32vec2Index.x < ((int)cSettings->NUM_TILES_XAXIS) - 1)) { // Check if this new position is not accessible, then go back to old position if (cMap2D->GetMapInfo(i32vec2Index.y, i32vec2Index.x + 1) == 1) { // Snap to the previous index i32vec2Index.x = iOldIndex; // Reset the i32vec2NumMicroSteps.x so that the player is aligned to the column i32vec2NumMicroSteps.x = 0; state = true; } // If the new position is between 2 rows, then check the other row as well if (i32vec2NumMicroSteps.y != 0) { // If the new position is not feasible, then go back to the old position if (cMap2D->GetMapInfo(i32vec2Index.y + 1, i32vec2Index.x + 1) == 1) { // Snap to the previous index i32vec2Index.x = iOldIndex; // Reset the i32vec2NumMicroSteps.x so that the player is aligned to the column i32vec2NumMicroSteps.x = 0; state = true; } } } } return state; } bool CBullets2D::ShootBullets(BULLETDIRECTION edirection) { isActive = true; if (edirection == RIGHT) { const int iOldIndex = i32vec2Index.x; // moving bullet right i32vec2NumMicroSteps.x++; if (i32vec2NumMicroSteps.x >= cSettings->NUM_STEPS_PER_TILE_XAXIS) { i32vec2NumMicroSteps.x = 0; i32vec2Index.x++; } // Constraint the Bullet's position within the screen boundary Constraint(RIGHT); // checking if bullet is near obsticle if (FindFeasiblePosition(iOldIndex, RIGHT) == true) { isActive = false; } } else { //cout << "VK_LEFT is called" << endl; const int iOldIndex = i32vec2Index.x; // moving player left i32vec2NumMicroSteps.x--; if (i32vec2NumMicroSteps.x < 0) { i32vec2NumMicroSteps.x = (int)(cSettings->NUM_STEPS_PER_TILE_XAXIS) - 1; i32vec2Index.x--; } // Constraint the player's position within the screen boundary Constraint(LEFT); // FindFeasiblePosition if (FindFeasiblePosition(iOldIndex, RIGHT) == true) { isActive = false; } } return true; }
462547c1340dc9fc8d366a97d8ff6c559947ece2
e81771cedd0ffaa2ebf62578828bbec2410dde05
/CVSystem/PointCloud.h
edd84a3fe3d34b598c48fe9019401f8abb0b93e3
[]
no_license
azer89/MangaVectorizer
a17b3c7f3579a0b0d434e94e6b194316af9804ed
e3c6e847d77b6d1f8214b60bc76a2699eca4e5c9
refs/heads/master
2021-06-05T19:51:44.028686
2016-10-05T16:30:51
2016-10-05T16:30:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,105
h
/** * KD-Tree data * * Author: Reza Adhitya Saputra ([email protected]) * Version: 2014 * */ #ifndef __Point_Cloud__ #define __Point_Cloud__ template <typename T> struct PointCloud { struct Point { //// coordinate in 2D T x; T y; //// Something 1 int info1; //// Something 2 int info2; }; std::vector<Point> pts; inline void PushPoint(T x, T y) const { pts.push_back(Point(x, y)); } // for nanoflann internal use inline size_t kdtree_get_point_count() const { return pts.size(); } // for nanoflann internal use inline T kdtree_distance(const T *p1, const size_t idx_p2, size_t size) const { const T d0 = p1[0] - pts[idx_p2].x; const T d1 = p1[1] - pts[idx_p2].y; return sqrt(d0 * d0 + d1 * d1); } // for nanoflann internal use inline T kdtree_get_pt(const size_t idx, int dim) const { if (dim == 0) { return pts[idx].x; } else { return pts[idx].y; } } // for nanoflann internal use template <class BBOX> bool kdtree_get_bbox(BBOX &bb) const { return false; } }; #endif
753e0053d7359ba9ecba8e2fffeec7f78282e2c8
325d0ecf79bec8e3d630c26195da689ea5bb567e
/dynalib/include/dynalib/setup.h
cade0735aa07e771d553da7c061b7b1a62b55394
[]
no_license
nvtienanh/Hitechlab_humanoid
ccaac64885967334f41a161f1684ff3a1571ab0f
34c899f70af7390b9fbdb1a1ad03faf864a550be
refs/heads/master
2020-04-22T10:34:21.944422
2016-08-28T06:02:00
2016-08-28T06:02:00
66,521,772
2
0
null
null
null
null
UTF-8
C++
false
false
878
h
//Setup specification for different robot configurations //Author: Sebastian Schüller <[email protected]> #ifndef SETUP_H #define SETUP_H #include <vector> #include <string> #if YAML_NEW_API #include <yaml-cpp/yaml.h> #else #include <yaml-cpp/node.h> #include <yaml-cpp/iterator.h> #endif #include <dynalib/device_setup.h> namespace dynalib { class Setup { public: Setup(std::string filename) : filename(filename) {}; bool parseFile(); bool nextDevice(); std::string deviceType(); std::string deviceName(); int deviceId(); bool writeSetup(DeviceSetup& deviceSetup); void setFilename(std::string filename) {this->filename = filename;}; private: std::string filename; const YAML::Node& currentDevice(); YAML::Node setup; #if YAML_NEW_API YAML::iterator deviceIt; #else YAML::Iterator deviceIt; #endif }; } #endif
3ad020711b70882836f665f842cb4543fb747eb1
59e1182083d840e8558e1aa015f0440e92ac2310
/ContainerSet.h
0e9bf113833daccbcc0ead1ab32697944b4e2c9a
[]
no_license
kamil-nowowiejski/Chralie-Game
e5220ac940bb59574a412a645f78a41225305b0e
19c73331f894255954ca75fa7f2a1b486d028260
refs/heads/master
2021-06-01T00:14:32.831561
2016-05-19T05:46:03
2016-05-19T05:46:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
357
h
#pragma once #include <SFML\Graphics.hpp> #include <vector> #include "Container.h" using namespace std; class ContainerSet { private: vector<Container*> c_containerSet; Texture *pc_containerTex; public: ContainerSet(); ~ContainerSet(); int iCollect(Collider &c_object); void vSpawnContainer(); void vDraw(RenderWindow &c_window); };
4b9def7262b1b4f3f69f18f43f3082a39c54bd1f
30773b649ebd89ffadd16d30fd62740b77ca7865
/SDK/Title_MA_07_MerchantCommander_classes.h
42f97e5aeacb22ec3e0cc608304e91c3bd95813c
[]
no_license
The-Jani/Sot-SDK
7f2772fb5df421e02b8fec237248af407cb2540b
2a158a461c697cca8db67aa28ffe3e43677dcf11
refs/heads/main
2023-07-09T07:17:56.972569
2021-08-18T23:45:06
2021-08-18T23:45:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
782
h
#pragma once // Name: S, Version: 2.2.1 /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass Title_MA_07_MerchantCommander.Title_MA_07_MerchantCommander_C // 0x0000 (FullSize[0x00E0] - InheritedSize[0x00E0]) class UTitle_MA_07_MerchantCommander_C : public UTitleDesc { public: static UClass* StaticClass() { static UClass* ptr = UObject::FindClass("BlueprintGeneratedClass Title_MA_07_MerchantCommander.Title_MA_07_MerchantCommander_C"); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
f8b231adfba334ab55178af683900d097e61b854
449977fc135fd708ffa9b2dedb15873c0bbdf775
/sp/SctpSocket/SctpSocket/SctpSocketAsyncResult.h
aba16a9df0d6187e2ab68afe35975c7c67e72990
[ "BSD-3-Clause" ]
permissive
yang123vc/sctpdrv
8d38f590e214591a72b887b338b046c0e9300c1a
30732e4750e2b6e8643d9406b6055d888269dda6
refs/heads/master
2020-07-02T14:41:28.933329
2013-01-09T17:40:06
2013-01-09T17:40:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,618
h
/* * Copyright (c) 2010 Bruce Cran. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #pragma once using namespace System; using namespace System::Threading; using namespace Microsoft::Win32::SafeHandles; namespace SctpDrv { public ref class SctpSocketWaitHandle : public WaitHandle { public: SctpSocketWaitHandle(Microsoft::Win32::SafeHandles::SafeWaitHandle ^handle) : WaitHandle() { SafeWaitHandle = handle; } }; public ref class SctpSocketAsyncResult : public IAsyncResult { public: property bool IsCompleted { virtual bool get() { return m_handle->WaitOne(); } } property WaitHandle^ AsyncWaitHandle { virtual WaitHandle^ get() { return m_handle; } } property Object^ AsyncState { virtual Object^ get() { return userState; } } property bool CompletedSynchronously { virtual bool get() { return m_completedSynchronously; } void set(bool completedSynchronously) { m_completedSynchronously = completedSynchronously; } } SctpSocketAsyncResult(HANDLE handle, Object ^state) { SafeWaitHandle ^safeHandle = gcnew SafeWaitHandle(IntPtr(handle), true); m_handle = gcnew SctpSocketWaitHandle(safeHandle); userState = state; } private: SctpSocketWaitHandle ^m_handle; Object ^userState; bool m_completedSynchronously; }; }
[ "devnull@localhost" ]
devnull@localhost
69d6cd79654712831af753fe4a65a1b0ad756a62
f43bc90509568df9fe23e902bca0402292b0785e
/tensorflow/compiler/xla/service/gpu/buffer_allocations.cc
20d428576633a1438e1ec0b00edf40f40b2d82f7
[ "Apache-2.0" ]
permissive
haoyan01/tensorflow
cd76e6e7b142968d3eb5fb564242eef05a01f7c5
f2508547d57d376ff1d3f58b27e34fddd8e8abbc
refs/heads/master
2020-03-24T05:52:28.648913
2018-10-04T14:47:37
2018-10-04T14:47:37
142,506,007
0
0
null
2018-07-26T23:55:35
2018-07-26T23:55:34
null
UTF-8
C++
false
false
8,674
cc
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/service/gpu/buffer_allocations.h" #include <utility> #include "tensorflow/compiler/xla/map_util.h" #include "tensorflow/compiler/xla/ptr_util.h" #include "tensorflow/compiler/xla/service/gpu/gpu_constants.h" #include "tensorflow/compiler/xla/status_macros.h" #include "tensorflow/compiler/xla/types.h" #include "tensorflow/compiler/xla/util.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/strings/numbers.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/types.h" namespace xla { namespace gpu { void BufferAllocations::Builder::RegisterBuffer(BufferAllocation::Index index, se::DeviceMemoryBase address) { InsertOrDie(&registered_buffers_, index, address); } StatusOr<std::unique_ptr<BufferAllocations>> BufferAllocations::Builder::Build( const BufferAssignment* buffer_assignment, int device_ordinal, DeviceMemoryAllocator* memory_allocator) { const int64 num_buffers = buffer_assignment->Allocations().size(); auto buffer_allocations = WrapUnique(new BufferAllocations( num_buffers, device_ordinal, memory_allocator, buffer_assignment)); for (BufferAllocation::Index i = 0; i < num_buffers; ++i) { const BufferAllocation& allocation = buffer_assignment->GetAllocation(i); const int64 expected_alignment = [&] { if (allocation.is_entry_computation_parameter()) { return kEntryParameterAlignBytes; } else if (allocation.is_constant()) { return kConstantBufferAlignBytes; } else { return kXlaAllocatedBufferAlignBytes; } }(); // If buffer #i's address is already registered (e.g. external arguments or // result buffers), use that registered buffer. if (registered_buffers_.count(i)) { se::DeviceMemoryBase address = FindOrDie(registered_buffers_, i); if (reinterpret_cast<uintptr_t>(address.opaque()) % expected_alignment != 0) { return InternalError( "Address of registered buffer %lld must be a multiple of %llx, but " "was %p", i, kEntryParameterAlignBytes, address.opaque()); } buffer_allocations->SetBuffer(i, FindOrDie(registered_buffers_, i)); continue; } // Allocate each allocation that might escape, or is the temp buffer. bool seen_temp_buffer = false; if (allocation.maybe_live_out() || allocation.IsPreallocatedTempBuffer()) { const int64 buffer_size = allocation.size(); se::DeviceMemoryBase buffer_address; if (buffer_size > 0) { OwningDeviceMemory buffer; TF_ASSIGN_OR_RETURN( buffer, memory_allocator->Allocate(device_ordinal, buffer_size)); if (reinterpret_cast<uintptr_t>(buffer.opaque()) % expected_alignment != 0) { return InternalError( "Address returned by memory_allocator->Allocate must be a " "multiple of %llx, but was %p", kXlaAllocatedBufferAlignBytes, buffer.opaque()); } // We do manual memory management within BufferAllocations. Be sure not // to do a TF_RETURN_IF_ERROR between this line and the // buffer_allocations->SetBuffer(buffer_address) call below! buffer_address = buffer.Forget(); } buffer_allocations->SetBuffer(i, buffer_address); if (allocation.IsPreallocatedTempBuffer()) { if (seen_temp_buffer) { LOG(FATAL) << "Multiple temporary buffers detected. BufferAssigner " << "must guarantee at most one temporary buffer."; } seen_temp_buffer = true; buffer_allocations->temp_buffer_base_ = buffer_address; } } } if (VLOG_IS_ON(2)) { for (BufferAllocation::Index i = 0; i < num_buffers; ++i) { const auto& buf = buffer_allocations->buffers_[i]; VLOG(2) << "Buffer " << i << " -> " << buf.opaque() << " (" << buf.size() << "B)"; } } return std::move(buffer_allocations); } BufferAllocations::~BufferAllocations() { if (!torn_down_) { // Presumably if we're executing this branch, the caller is in an error // state, otherwise it would have explicitly called TearDown so it could // save some set of live addresses. So ignoring any errors in TearDown is // sensible. TearDown(/*live_addresses=*/{}).IgnoreError(); } } Status BufferAllocations::TearDown( const std::set<se::DeviceMemoryBase>& live_addresses) { // Deallocate temporary buffers, taking care to try to deallocate all of them // even if one of the deallocations fails. Status status; const int64 num_buffers = buffer_assignment_->Allocations().size(); for (BufferAllocation::Index i = 0; i < num_buffers; ++i) { const BufferAllocation& allocation = buffer_assignment_->GetAllocation(i); se::DeviceMemoryBase buffer_address = GetDeviceAddress(allocation.index()); // Deallocate buffers marked "maybe_live_out" but aren't actually live out, // and temp buffers. if ((allocation.maybe_live_out() && !live_addresses.count(buffer_address)) || allocation.IsPreallocatedTempBuffer()) { auto dealloc_result = memory_allocator_->Deallocate(device_ordinal_, buffer_address); if (!dealloc_result.ok() && status.ok()) { status = dealloc_result; } } } torn_down_ = true; return status; } se::DeviceMemoryBase BufferAllocations::GetDeviceAddress( BufferAllocation::Index buffer_index) const { CHECK_GE(buffer_index, 0); CHECK_LT(buffer_index, buffers_.size()); return buffers_[buffer_index]; } se::DeviceMemoryBase BufferAllocations::GetDeviceAddress( const BufferAllocation::Slice& buffer_slice) const { se::DeviceMemoryBase base = GetDeviceAddress(buffer_slice.index()); CHECK_LE(buffer_slice.offset(), base.size()); CHECK_LE(buffer_slice.offset() + buffer_slice.size(), base.size()); return se::DeviceMemoryBase( static_cast<char*>(base.opaque()) + buffer_slice.offset(), buffer_slice.size(), /*is_sub_buffer=*/true); } void BufferAllocations::SetBuffer(BufferAllocation::Index buffer_index, se::DeviceMemoryBase buffer) { CHECK_GE(buffer_index, 0); CHECK_LT(buffer_index, buffers_.size()); buffers_[buffer_index] = buffer; } static const HloInstruction& InstrForConstantBufferAllocation( const BufferAllocation& allocation) { CHECK(allocation.is_constant()); HloInstruction* const_instr = nullptr; for (const auto& buffer_offset_pair : allocation.assigned_buffers()) { const LogicalBuffer* buffer = buffer_offset_pair.first; // BufferAssignment may have assigned non-constant instructions to this // allocation too so we can't CHECK this condition. E.g. for // // while(init = constant, body = identity, cond = ...) // // the LogicalBuffer for the kWhile instruction will have the same // BufferAllocation as the LogicalBuffer for the (init) constant. if (buffer->instruction()->opcode() == HloOpcode::kConstant) { CHECK_EQ(const_instr, nullptr) << const_instr->ToString() << " " << buffer->ToString(); const_instr = buffer->instruction(); } } CHECK_NE(const_instr, nullptr); return *const_instr; } string ConstantBufferAllocationToGlobalName( const BufferAllocation& allocation) { string instr_name = InstrForConstantBufferAllocation(allocation).name(); for (char& c : instr_name) { if (c == '.') { c = '_'; } } return tensorflow::strings::StrCat("buffer_for_", instr_name); } const Literal& LiteralForConstantAllocation( const BufferAllocation& allocation) { return InstrForConstantBufferAllocation(allocation).literal(); } bool ShouldEmitLiteralInLlvmIr(const Literal& literal) { // LLVM can sometimes do interesting optimizations using scalar constants. return ShapeUtil::IsScalar(literal.shape()); } } // namespace gpu } // namespace xla
796517e802805820209ab9b07cc971e529e0bad8
4ed8364da72396ee833c106eb0fae2beaecdf777
/app/panda/config/panda/codegen/cpp/template/foo.h
ec8431245c2ad718367980df956b4b5a34c1d34f
[]
no_license
SSSSSolution/my_lib
ea9d2f7c4bd7896df3762484a063684d3a9b6b93
26fb2f933efcc06888164e23ee7036cb11315180
refs/heads/main
2023-03-01T20:25:37.881756
2021-02-06T14:50:13
2021-02-06T14:50:13
313,587,300
0
0
null
null
null
null
UTF-8
C++
false
false
530
h
$[head]#ifndef ${HEAD_DEFINE}_H #define ${HEAD_DEFINE}_H $[/head]#endif //${HEAD_DEFINE}_H $[namespace]${NAME_SPACE} { $[/namespace]} $[class]class ${CLASS_NAME} { public: $[c]${CLASS_NAME}(); $[d]~${CLASS_NAME}(); $[vd]virtual ~${CLASS_NAME}(); $[cc]${CLASS_NAME}(const ${CLASS_NAME} &other); $[a]${CLASS_NAME} &operator=(const ${CLASS_NAME} &other); $[mc]${CLASS_NAME}(${CLASS_NAME} &&other); $[ma]${CLASS_NAME} &operator=(const ${CLASS_NAME} &&other); $[/class]};
dcf361c9223dcfec05e17a0b58a803768e2c904c
58fbf85bc2dda72606c01cd2cd191bc0bc9fa7c2
/Plugins/SCTXRResource/Source/SCTXRUser/Private/SCTXRCommonTools.cpp
75d3be2ce9b7a18fd0aaa27fba09a6c3c65baee3
[]
no_license
myl2232/ArmyEngineSimulation
497d2affb2786af9aa0a0295cf98cc4377b87ca4
353f3ec93cb352d49ce95825bb2ffdcc678119cf
refs/heads/master
2020-11-26T07:03:36.383628
2019-12-20T09:48:18
2019-12-20T09:48:18
228,996,622
0
4
null
null
null
null
UTF-8
C++
false
false
18,275
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "SCTXRCommonTools.h" #include "Regex.h" #include "Developer/DesktopPlatform/Public/DesktopPlatformModule.h" #include "AES.h" //#include "PhysicsEngine/BodySetup.h" #include "PlatformFilemanager.h" FSCTXRCommonTools::FSCTXRCommonTools() { } FString FSCTXRCommonTools::GetPathFromFileName(ESCTResourceType InResourceType, const FString& InFileName) { FString FilePath; //绘制户型文件 if (InResourceType == ESCTResourceType::DrawHome) FilePath = GetDrawHomeDir() + InFileName; //烘焙户型文件 else if (InResourceType == ESCTResourceType::CookedHome) FilePath = GetCookedHomeDir() + InFileName; //模型文件 else if (InResourceType == ESCTResourceType::MoveableMesh) FilePath = GetModelDir() + InFileName; //材质文件 else if (InResourceType == ESCTResourceType::Material) FilePath = GetModelDir() + InFileName; //Actor文件 else if (InResourceType == ESCTResourceType::BlueprintClass) FilePath = GetModelDir() + InFileName; //组方案 else if (InResourceType == ESCTResourceType::GroupPlan) FilePath = GetGroupPlanDir() + InFileName; //户型方案 else if (InResourceType == ESCTResourceType::LevelPlan) FilePath = GetLevelPlanDir() + InFileName; //地板拼花方案 else if (InResourceType == ESCTResourceType::Texture) FilePath = GetFloorTextureDir()+ InFileName; return FilePath; } bool FSCTXRCommonTools::RemoveFileNameExtension(FString& _FileName) { int32 pos = _FileName.Find(TEXT("."), ESearchCase::IgnoreCase, ESearchDir::FromEnd); if (pos != -1) { _FileName = _FileName.Mid(0, pos); return true; } return false; } FString FSCTXRCommonTools::GetFileExtension(FString& _FileName) { int32 pos = _FileName.Find(TEXT("."), ESearchCase::IgnoreCase, ESearchDir::FromEnd); if (pos != -1) { return _FileName.RightChop(pos + 1); } return TEXT(""); } FString FSCTXRCommonTools::GetDrawHomeDir() { return FPaths::ProjectContentDir() + TEXT("DBJCache/DrawHome/"); } FString FSCTXRCommonTools::GetConstructionDir() { return FPaths::ProjectContentDir() + TEXT("DBJCache/Construction/"); } FString FSCTXRCommonTools::GetCookedHomeDir() { return FPaths::ProjectContentDir() + TEXT("DBJCache/CookedHome/"); } FString FSCTXRCommonTools::GetModelDir() { return FPaths::ProjectContentDir() + TEXT("DBJCache/Model/"); } FString FSCTXRCommonTools::GetGroupPlanDir() { return FPaths::ProjectContentDir() + TEXT("DBJCache/GroupPlan/"); } FString FSCTXRCommonTools::GetAutoDesignGroupPlanDir() { return FPaths::ProjectContentDir() + TEXT("DBJCache/AutoDesignGroupPlan/"); } FString FSCTXRCommonTools::GetLevelPlanDir() { return FPaths::ProjectContentDir() + TEXT("DBJCache/LevelPlan/"); } FString FSCTXRCommonTools::GetFloorTextureDir() { return FPaths::ProjectContentDir() + TEXT("DBJCache/FloorTexture/"); } FString FSCTXRCommonTools::GetFileNameFromPath(FString& _FilePath) { int32 pos = _FilePath.Find(TEXT("/"), ESearchCase::IgnoreCase, ESearchDir::FromEnd); FString FileName = _FilePath.RightChop(pos + 1); return FileName; } FString FSCTXRCommonTools::GetFolderFromPath(FString& _FilePath) { int32 pos = _FilePath.Find(TEXT("/"), ESearchCase::IgnoreCase, ESearchDir::FromEnd); if (pos != -1) { return _FilePath.Mid(0, pos); } return ""; } int32 FSCTXRCommonTools::GetFileIDFromName(FString _FileNameWithMD5) { int32 pos = _FileNameWithMD5.Find(TEXT("_"), ESearchCase::IgnoreCase, ESearchDir::FromEnd); if (pos != -1) { return FCString::Atoi(*_FileNameWithMD5.Mid(0, pos)); } return FCString::Atoi(*_FileNameWithMD5); } bool FSCTXRCommonTools::CheckTeleNumberValid(FString _str) { const FRegexPattern Pattern(TEXT("^(1)\\d{10}$")); FRegexMatcher Matcher(Pattern, _str); if (Matcher.FindNext()) return true; else return false; } bool FSCTXRCommonTools::CheckNumberValid(FString _str) { const FRegexPattern Pattern(TEXT("^(0|[1-9][0-9]*)$")); FRegexMatcher Matcher(Pattern, _str); if (Matcher.FindNext()) return true; else return false; } bool FSCTXRCommonTools::CheckIDCodeValid(FString _str) { const FRegexPattern Pattern(TEXT("^\\d{17}(\\d|X|x)$")); FRegexMatcher Matcher(Pattern, _str); if (Matcher.FindNext()) return true; return false; } bool FSCTXRCommonTools::CheckPasswordValid(FString _str) { //字母开头,字母数字下划线组成,6-18长度 //const FRegexPattern Pattern(TEXT("^[a-zA-Z]\\w{5,17}$")); //密码有6-18个字母、数字组成 const FRegexPattern Pattern(TEXT("^\\w{6,18}$")); FRegexMatcher Matcher(Pattern, _str); if (Matcher.FindNext()) return true; return false; } bool FSCTXRCommonTools::CheckEmpty(FString _str) { const FRegexPattern Pattern(TEXT("^\\s*|\\s*$")); FRegexMatcher Matcher(Pattern, _str); if (Matcher.FindNext()) return false; return true; } bool FSCTXRCommonTools::CheckAreaValid(FString _str) { const FRegexPattern Pattern(TEXT("^([1-9][0-9]*)$")); FRegexMatcher Matcher(Pattern, _str); if (Matcher.FindNext()) return true; return false; } FString FSCTXRCommonTools::AddCommaForNumber(FString _Number) { int32 pos = _Number.Find(TEXT(".")); if (pos != -1) { pos -= 3; while (pos >= 1) { _Number.InsertAt(pos, TEXT(",")); pos -= 3; } return _Number; } else { pos = _Number.Len(); pos -= 3; while (pos >= 1) { _Number.InsertAt(pos, TEXT(",")); pos -= 3; } return _Number; } } FString FSCTXRCommonTools::AddCommaForNumber(float _Number) { FString str = FString::Printf(TEXT("%.2f"), _Number); int32 pos = str.Find(TEXT(".")); if (pos != -1) { pos -= 3; while (pos >= 1) { str.InsertAt(pos, TEXT(",")); pos -= 3; } return str; } else { pos = str.Len(); pos -= 3; while (pos >= 1) { str.InsertAt(pos, TEXT(",")); pos -= 3; } return str; } } void FSCTXRCommonTools::DeleteFiles(int32 InID, ESCTResourceType InType) { FString FileExtension; if (InType == ESCTResourceType::DrawHome || InType == ESCTResourceType::LevelPlan || InType == ESCTResourceType::GroupPlan || InType == ESCTResourceType::Construction || InType == ESCTResourceType::CustomlizedFloor || InType == ESCTResourceType::CustomlizedCeling || InType == ESCTResourceType::CustomlizedWall ) { FileExtension = "json"; } else { FileExtension = "pak"; } FString FileFolder = FSCTXRCommonTools::GetPathFromFileName(InType, ""); FString FileNameMatchedID = FString::Printf(TEXT("%d_*.%s"), InID, *FileExtension); TArray<FString> Filenames; IFileManager::Get().FindFilesRecursive(Filenames, *FileFolder, *FileNameMatchedID, true, false); for (auto& It : Filenames) { FPlatformFileManager::Get().GetPlatformFile().DeleteFile(*It); } } //TSharedPtr<FProjectContentItem> FSCTXRCommonTools::ParseProjectContentItemFromJson(TSharedPtr<FJsonObject> InJsonObject) //{ // if (InJsonObject.IsValid()) // { // int32 ID = InJsonObject->GetIntegerField("id"); // FString Name = InJsonObject->GetStringField("name"); // FString ThumbnailURL = InJsonObject->GetStringField("thumbnailUrl"); // // FString CreateDateStr = InJsonObject->GetStringField("createDate"); // int64 CreateDate = FCString::Atoi64(*CreateDateStr); // // FString UpdateDateStr = InJsonObject->GetStringField("updateDate"); // int64 UpdateDate = FCString::Atoi64(*UpdateDateStr); // // return MakeShareable(new FProjectContentItem(ID, Name, ThumbnailURL, CreateDate, UpdateDate)); // } // return NULL; //} FSCTCategoryContentItem FSCTXRCommonTools::ParseCategoryFromJson(TSharedPtr<FJsonObject> InJsonObject) { if (InJsonObject.IsValid()) { FString Name = InJsonObject->GetStringField("name"); int32 Key = InJsonObject->GetIntegerField("key"); int32 Value = InJsonObject->GetIntegerField("value"); FSCTCategoryContentItem CategoryData = FSCTCategoryContentItem(Name, Key, Value); const TArray<TSharedPtr<FJsonValue>> JArray = InJsonObject->GetArrayField("categoryList"); for (auto& ArrayIt : JArray) { CategoryData.CategoryList.Add(ParseCategoryFromJson(ArrayIt->AsObject())); } return CategoryData; } return FSCTCategoryContentItem(); } TSharedPtr<FSCTContentItemSpace::FContentItem> FSCTXRCommonTools::ParseTextureContentItemFromJson(TSharedPtr<FJsonObject> InJsonObject, int32 categoryID, ESCTPavingMethodType PavingType) { if (InJsonObject.IsValid()) { //获取缩略图相关信息 int32 ID = InJsonObject->GetIntegerField("id"); FString Name = InJsonObject->GetStringField("name"); FString ThumbnailURL = InJsonObject->GetStringField("thumbnailUrl"); int32 resourceType = InJsonObject->GetIntegerField("resourceType"); TSharedPtr<FSCTContentItemSpace::FContentItem> contentItem = MakeShareable(new FSCTContentItemSpace::FContentItem()); TSharedPtr<FSCTContentItemSpace::FResObj> ResPtr = MakeShareable(new FSCTContentItemSpace::FArmyTextureRes()); TSharedPtr<FSCTContentItemSpace::FArmyTextureRes> TxtRes = StaticCastSharedPtr<FSCTContentItemSpace::FArmyTextureRes>(ResPtr); TxtRes->FileThumbnailURL = ThumbnailURL; TxtRes->EPavingMethod = ESCTPavingMethodType(PavingType); TxtRes->ThumbnailID = ID; contentItem->ResourceType = ESCTResourceType(resourceType); contentItem->ID = ID; contentItem->Name = Name; //int index = 0; const TArray<TSharedPtr<FJsonValue>> JArrayPre = InJsonObject->GetArrayField("previewGoodsList"); for (auto &ArrayIt: JArrayPre) { TSharedPtr<FSCTContentItemSpace::FArmyTextureRes::TextureStruct> txtStr = ParseTextureStructItemFromJson(ArrayIt,categoryID, ESCTResourceType(resourceType)); TxtRes->TextureArr.Add(txtStr); //index++; } contentItem->ResObj = ResPtr; return contentItem; } return nullptr; } TSharedPtr<FSCTContentItemSpace::FContentItem> FSCTXRCommonTools::ParseTextureReplaceContentItemFromJson(TSharedPtr<FJsonValue> InJsonObject, int32 categoryID, ESCTPavingMethodType PavingType) { if (InJsonObject.IsValid()) { TSharedPtr<FSCTContentItemSpace::FArmyTextureRes::TextureStruct> txtStr = ParseTextureStructItemFromJson(InJsonObject, categoryID, ESCTResourceType(0)); //设置缩略图相关信息 int32 ID = txtStr->ID; FString Name = txtStr->TextureName; FString ThumbnailURL = txtStr->RealFileThumbnailURL; int32 resourceType = txtStr->ResourceType; TSharedPtr<FSCTContentItemSpace::FContentItem> contentItem = MakeShareable(new FSCTContentItemSpace::FContentItem()); TSharedPtr<FSCTContentItemSpace::FResObj> ResPtr = MakeShareable(new FSCTContentItemSpace::FArmyTextureRes()); TSharedPtr<FSCTContentItemSpace::FArmyTextureRes> TxtRes = StaticCastSharedPtr<FSCTContentItemSpace::FArmyTextureRes>(ResPtr); TxtRes->FileThumbnailURL = ThumbnailURL; TxtRes->EPavingMethod = ESCTPavingMethodType(PavingType); TxtRes->ThumbnailID = ID; contentItem->ResourceType = ESCTResourceType(resourceType); contentItem->ID = ID; contentItem->Name = Name; TxtRes->TextureArr.Add(txtStr); contentItem->ResObj = ResPtr; return contentItem; } return nullptr; } TSharedPtr<FSCTContentItemSpace::FArmyTextureRes::TextureStruct> FSCTXRCommonTools::ParseTextureStructItemFromJson(TSharedPtr<FJsonValue> ArrayIt, int32 categoryID, ESCTResourceType resourceType) { //获取缩略图关联的纹理相关信息 int32 IDPre = ArrayIt->AsObject()->GetIntegerField("id"); FString imagePre = ArrayIt->AsObject()->GetStringField("image"); FString NamePre = ArrayIt->AsObject()->GetStringField("name"); int32 Width = ArrayIt->AsObject()->GetIntegerField("customWidth"); int32 Length = ArrayIt->AsObject()->GetIntegerField("customLength"); int32 Height = ArrayIt->AsObject()->GetIntegerField("customHeight"); int32 resType = 0; if ((int32)resourceType == 0) { resType = ArrayIt->AsObject()->GetIntegerField("resourceType");//此处资源类型从服务器获取 } else { resType = (int32)resourceType; } //const TSharedPtr<FJsonObject> JObjectSource = ArrayIt->AsObject()->GetObjectField("resource"); //获取法线贴图数据 const TSharedPtr<FJsonObject> JArrayNormal = ArrayIt->AsObject()->GetObjectField("normalMap"); FString NormalMd5 = JArrayNormal->GetStringField("fileMd5"); FString NormalUrl = JArrayNormal->GetStringField("fileUrl"); FString NameAndExtensionNormal = FString::Printf(TEXT("%d_%s.%s"), IDPre, *NormalMd5, *GetFileExtension(NormalUrl)); FString FilePathNormal = GetPathFromFileName(ESCTResourceType(resType), NameAndExtensionNormal); //获取真实材质贴图数据 const TSharedPtr<FJsonObject> JArrayTexture = ArrayIt->AsObject()->GetObjectField("textureMap"); FString TextureMd5 = JArrayTexture->GetStringField("fileMd5"); FString TextureUrl = JArrayTexture->GetStringField("fileUrl"); FString NameAndExtensionTexture = FString::Printf(TEXT("%d_%s.%s"), IDPre, *TextureMd5, *GetFileExtension(TextureUrl)); FString FilePathTexture = GetPathFromFileName(ESCTResourceType(resType), NameAndExtensionTexture); bool upShelves = ArrayIt->AsObject()->GetBoolField("upShelves"); TSharedPtr<FSCTContentItemSpace::FArmyTextureRes::TextureStruct> txtStr = MakeShareable<FSCTContentItemSpace::FArmyTextureRes::TextureStruct>(new FSCTContentItemSpace::FArmyTextureRes::TextureStruct); TSharedPtr<FSCTContentItemSpace::FArmyTextureRes::NoramlAndTexture> txtNormal = MakeShareable<FSCTContentItemSpace::FArmyTextureRes::NoramlAndTexture>(new FSCTContentItemSpace::FArmyTextureRes::NoramlAndTexture); TSharedPtr<FSCTContentItemSpace::FArmyTextureRes::NoramlAndTexture> txtTexture = MakeShareable<FSCTContentItemSpace::FArmyTextureRes::NoramlAndTexture>(new FSCTContentItemSpace::FArmyTextureRes::NoramlAndTexture); txtStr->ID = IDPre; txtStr->TextureName = NamePre; txtStr->Length = Length; txtStr->Width = Width; txtStr->Height = Height; txtStr->CategoryID = categoryID; txtStr->RealFileThumbnailURL = imagePre; txtStr->ResourceType = resType; //txtStr->EPavingMethod = PavingType; //存储法线贴图 txtNormal->MD5 = NormalMd5; txtNormal->FileURL = NormalUrl; txtNormal->FilePath = FilePathNormal; txtStr->NoramlAndTextureArr.Add(txtNormal); //存储真实纹理 txtTexture->MD5 = TextureMd5; txtTexture->FileURL = TextureUrl; txtTexture->FilePath = FilePathTexture; txtStr->NoramlAndTextureArr.Add(txtTexture); return txtStr; } TSharedPtr<FSCTContentItemSpace::FContentItem> FSCTXRCommonTools::ParseContentItemFromJson(TSharedPtr<FJsonObject> InJsonObject) { if (InJsonObject.IsValid()) { const TSharedPtr<FJsonObject> JObject = InJsonObject->GetObjectField("data"); int32 Version = InJsonObject->GetIntegerField("version"); if (JObject.IsValid()) { int32 ID = JObject->GetIntegerField("id"); FString Name = JObject->GetStringField("name"); FString ThumbnailURL = JObject->GetStringField("thumbnailUrl"); int32 ResourceType = JObject->GetIntegerField("resourceType"); TSharedPtr<FSCTContentItemSpace::FResObj> ResPtr; const TSharedPtr<FJsonObject> ResourceObject = JObject->GetObjectField("resource"); if (ResourceObject.IsValid()) { FString FileURL = ResourceObject->GetStringField("fileUrl"); FString FileMD5 = ResourceObject->GetStringField("fileMd5"); FString FileName = FString::Printf(TEXT("%d_%s.%s"), ID, *FileMD5, *GetFileExtension(FileURL)); FString FilePath = GetPathFromFileName(ESCTResourceType(ResourceType), FileName); if (ResourceType == (int32)ESCTResourceType::MoveableMesh || ResourceType == (int32)ESCTResourceType::Material || ResourceType == (int32)ESCTResourceType::BlueprintClass) { FString MaterialParameter = ResourceObject->GetStringField("materialParameter"); FString LightParameter = ResourceObject->GetStringField("lightParameter"); //创建ModelRes ResPtr = MakeShareable(new FSCTContentItemSpace::FModelRes(FileName, FilePath, FileURL, FileMD5, MaterialParameter, LightParameter)); } else if (ResourceType == (int32)ESCTResourceType::Project) { FString CreateDateStr = ResourceObject->GetStringField("createDate"); int64 CreateDate = FCString::Atoi64(*CreateDateStr); FString UpdateDateStr = ResourceObject->GetStringField("updateDate"); int64 UpdateDate = FCString::Atoi64(*UpdateDateStr); //创建ProjectRes ResPtr = MakeShareable(new FSCTContentItemSpace::FProjectRes(FileName, FilePath, FileURL, FileMD5, CreateDate, UpdateDate)); } else if (ResourceType == (int32)ESCTResourceType::DrawHome) { int32 HomeId = JObject->GetIntegerField("id"); FString HomeName = JObject->GetStringField("name"); int32 BedRoomNum = ResourceObject->GetIntegerField("bedroom"); int32 LivingRoomNum = ResourceObject->GetIntegerField("livingRoom"); int32 KitchenNum = ResourceObject->GetIntegerField("kitchen"); int32 BathroomNum = ResourceObject->GetIntegerField("bathroom"); float FloorArea = ResourceObject->GetNumberField("floorArea"); float InnerArea = ResourceObject->GetNumberField("innerArea"); int32 ProvinceId = ResourceObject->GetIntegerField("provinceId"); int32 CityId = ResourceObject->GetIntegerField("cityId"); int32 AreaId = ResourceObject->GetIntegerField("areaId"); int32 VillageId = ResourceObject->GetIntegerField("village"); FString AddressDetail = ResourceObject->GetStringField("addressDetail"); int32 OrientationId = ResourceObject->GetIntegerField("homeForward"); int32 BuildingTypeId = ResourceObject->GetIntegerField("buildingType"); FString ConstructionFileURL = ResourceObject->GetStringField("constructionFileUrl"); FString ConstructionFileMD5 = ResourceObject->GetStringField("constructionFileMd5"); // 创建resource ResPtr = MakeShareable(new FSCTContentItemSpace::FArmyHomeRes( FileName, FilePath, FileURL, FileMD5, HomeId, HomeName, BedRoomNum, LivingRoomNum, KitchenNum, BathroomNum, FloorArea, InnerArea, ProvinceId, CityId, AreaId, VillageId, AddressDetail, OrientationId, BuildingTypeId )); } else { ResPtr = MakeShareable(new FSCTContentItemSpace::FResObj(FileName, FilePath, FileURL, FileMD5)); } } //创建ContentItem return MakeShareable(new FSCTContentItemSpace::FContentItem( ESCTResourceType(ResourceType), ID, Name, ThumbnailURL, ResPtr) ); } } return NULL; }
b4e880a507dbc2b1383dd552f69458ed362325c0
dc25b23f8132469fd95cee14189672cebc06aa56
/vendor/mediatek/proprietary/hardware/audio/common/V2/include/AudioMTKVolumeInterface.h
4eb9cbe1b612587b3c2623f9a0f2c4074279e621
[]
no_license
nofearnohappy/alps_mm
b407d3ab2ea9fa0a36d09333a2af480b42cfe65c
9907611f8c2298fe4a45767df91276ec3118dd27
refs/heads/master
2020-04-23T08:46:58.421689
2019-03-28T21:19:33
2019-03-28T21:19:33
171,048,255
1
5
null
2020-03-08T03:49:37
2019-02-16T20:25:00
Java
UTF-8
C++
false
false
7,719
h
#ifndef ANDROID_AUDIO_MTK_VOLUME_INTERFACE_H #define ANDROID_AUDIO_MTK_VOLUME_INTERFACE_H #include "AudioType.h" #include <utils/Errors.h> #include <utils/Vector.h> #include <utils/String16.h> #include <utils/String8.h> //! AAudioMTKVolumeInterface interface /*! this class is hold for volume controlb base on mode and device. need to take care both input and output volume. */ class AudioMTKVolumeInterface { public: /** * virtual destrutor */ virtual ~AudioMTKVolumeInterface() {}; /** * check volume control init done. * @return status_t */ virtual status_t initCheck() = 0; /** * volume controller init funciton * @return status_t */ virtual status_t initVolumeController() = 0; /** * volume controller setMasterVolume, usually set master volume is by setting analog gain, * @param v * @param mode * @param routes * @return status_t */ virtual status_t setMasterVolume(float v, audio_mode_t mode, uint32_t devices) = 0 ; /** * volume controller GetMasterVolume * @return mastervolume */ virtual float getMasterVolume() = 0 ; /** * volume controller setVoiceVolume, usually set voice volume is use by incall mode * @param v * @param mode * @param routes * @return status_t */ virtual status_t setVoiceVolume(float v, audio_mode_t mode, uint32_t devices) = 0 ; /** * volume controller getVoiceVolume * @return VoiceVolume */ virtual float getVoiceVolume(void) = 0; /** * volume controller setStreamVolume, this function basicaaly use for FM or MATV * which need set volume by hardware, diogital is set by audiopolicymanager. * @param stream * @param v * @return status_t */ virtual status_t setStreamVolume(int stream, float v) = 0 ; /** * volume controller setStreamMute * @param stream * @param mute * @return status_t */ virtual status_t setStreamMute(int stream, bool mute) = 0 ; /** * volume controller getStreamVolume * @param stream * @return status_t */ virtual float getStreamVolume(int stream) = 0; virtual status_t setAnalogVolume(int stream, int device, int index,audio_mode_t mode) =0; virtual status_t speechBandChange(bool nb) = 0; virtual bool isNbSpeechBand() = 0; virtual status_t setBtVolumeCapability(bool support) = 0; /** * volume controller SetLineInPlaybackGain * should depend on different usage , FM ,MATV and output device to setline in gain * @param type * @return status_t */ virtual status_t SetLineInPlaybackGain(int type) = 0; /** * volume controller SetLineInRecordingGain * should depend on different usage , FM ,MATV and output device to setline in gain * @param type * @return status_t */ virtual status_t SetLineInRecordingGain(int type) = 0; /** * volume controller SetFmVolume * Set FM playback volume * @param volume * @return bool */ virtual bool SetFmVolume(int volume) = 0; virtual bool SetFmVolume(float volume) = 0; /** * volume controller GetFmVolume * Set FM playback volume * @param void * @return int */ virtual int GetFmVolume(void) = 0; /** * volume controller SetFmVolume * Set FM playback volume * @param volume * @return bool */ virtual bool SetFmChipVolume(int volume) = 0; /** * volume controller SetSideTone * base on mode gain and route to decide sidetone gain * @param Mode * @param Gain * @param routes * @return status_t */ virtual status_t SetSideTone(uint32_t Mode, uint32_t gain) = 0 ; /** * volume controller setMatvVolume * set Matv Volume * @param volume * @return bool */ virtual bool setMatvVolume(int volume) = 0 ; /** * volume controller SetMatvMute * Set Matv Mute * @param b_mute * @return bool */ virtual bool SetMatvMute(bool b_mute) = 0 ; /** * volume controller GetSideToneGain * base on output device get sidetone gain * @param device * @return gain */ virtual uint32_t GetSideToneGain(uint32_t device) = 0 ; /** * volume controller SetMicGain * base on mode gain and route to decide sidetone gain * @param Mode * @param Gain * @param routes * @return status_t */ virtual status_t SetMicGain(uint32_t Mode, uint32_t gain) = 0 ; /** * volume controller SetULTotalGain * base on mode and gain * @param Mode * @param Gain * @return status_t */ virtual status_t SetULTotalGain(uint32_t Mode, unsigned char Volume) = 0 ; /** * volume controller SetMicGain * base on mode gain and route to decide sidetone gain * @param Mode * @param Gain * @param routes * @return status_t */ virtual status_t ApplyMicGain(uint32_t MicType, int mode) = 0 ; virtual void ApplyMicGainByDevice(uint32 device, audio_mode_t mode) = 0 ; /** * volume controller SetDigitalHwGain * base on mode gain and route to decide sidetone GAIN_MUTE * @param Mode * @param Gain * @param routes * @return status_t */ virtual status_t SetDigitalHwGain(uint32_t Mode, uint32_t Gain , uint32_t devices) = 0 ; /** * volume controller GetSWMICGain * get MIC software digital gain for HD record library */ virtual uint8_t GetSWMICGain(void) = 0 ; /** * volume controller GetULTotalGain * get MIC software digital gain for BesRecord library */ virtual uint8_t GetULTotalGain(void) = 0 ; /** * volume controller Set modem DL gain * @param Gain * @return status_t */ virtual void ApplyMdDlGain(int Gain) = 0 ; /** * volume controller Set modem DL Ehn gain * @param Gain * @return status_t */ virtual void ApplyMdDlEhn1Gain(int Gain) = 0 ; /** * volume controller Set modem Ul gain * @param Gain * @return status_t */ virtual void ApplyMdUlGain(int Gain) = 0 ; /** * volume controller map volume to digital gain * @param Gain * @return digital gain */ virtual uint16_t MappingToDigitalGain(unsigned char Gain) = 0 ; /** * volume controller map volume to PGA gain * @param Gain * @return PGA gain */ virtual uint16_t MappingToPGAGain(unsigned char Gain) = 0; /** * volume controller SetMicGainTuning * base on mode gain and route to decide sidetone gain * @param Mode * @param Gain * @param routes * @return status_t */ virtual status_t SetMicGainTuning(uint32_t Mode, uint32_t gain) = 0 ; virtual status_t ApplySideTone(uint32_t Mode) = 0; }; #endif
c8116e8b2e9c51e845d09766118ea703a369a7b0
e39a0354db4013d2a8aec4a4565cfb5f6443ae8f
/UVa/UVa10935 - Throwing cards away I.cpp
0bb5baf19a150a0fb02ad482b886840bda97e377
[]
no_license
YimingPan/UVa-Solution
8afd41673ff3aeebcedbfbf379247af5e2a6eca4
92862dcfc49baed97ea72f4467f12f8d588a9010
refs/heads/master
2021-09-09T21:52:13.645907
2018-03-19T22:48:06
2018-03-19T22:48:06
116,416,034
0
0
null
null
null
null
GB18030
C++
false
false
713
cpp
#include <cstdio> #include <queue> using namespace std; int main() { int n; //n表示总卡片数 while(scanf("%d",&n), n) { queue<int> q; //开始时队列必须为空,故每次重建一个 for(int i=1;i<=n;i++) q.push(i); printf("Discarded cards:"); for(int k=0;k<n-1;k++) //k表示丢弃的张数 { if(k == n-2) printf(" %d",q.front()); //输出格式校正 else printf(" %d,",q.front()); q.pop(); //丢弃第一张牌,第二章牌成为队首元素 q.push(q.front()); //第二张牌入队 q.pop(); } printf("\nRemaining card: %d\n",q.front()); } return 0; }
40f52d72c7d72d5d1587d4bace78f684d161aea1
cef8d1ddd7c64582b56458b0ebf3fb39423e3f67
/source/grafica/transformations.cpp
5575ee2c633ea26498e2812da921f5fda50e8ce7
[ "MIT" ]
permissive
dantros/grafica_cpp
ecb9c093a7270933fe27bb6b018380c6bdff006f
1ad0283295e79b755c546f50944f433c290b5c25
refs/heads/dev
2023-08-26T04:55:34.883134
2021-10-18T04:24:36
2021-10-18T04:24:36
356,721,014
1
5
MIT
2021-10-18T00:40:53
2021-04-10T23:27:32
C++
UTF-8
C++
false
false
4,761
cpp
/** * @file transformations.cpp * @brief Convenience transformation matrices written in 3D homogeneous coordinates (i.e. matrices shape is 4x4). * Under the hood, Eigen matrices are used. * * @author Daniel Calderón * @license MIT */ #include "transformations.h" #include <cmath> #include <numbers> #include <Eigen/Geometry> namespace Grafica { namespace Transformations { Matrix4f identity() { return Matrix4f::Identity(); } Matrix4f uniformScale(Coord s) { return (Matrix4f() << s, 0, 0, 0, 0, s, 0, 0, 0, 0, s, 0, 0, 0, 0, 1).finished(); } Matrix4f scale(Coord sx, Coord sy, Coord sz) { return (Matrix4f() << sx, 0, 0, 0, 0, sy, 0, 0, 0, 0, sz, 0, 0, 0, 0, 1).finished(); } Matrix4f rotationX(Coord theta_radians) { Coord sin_theta = std::sin(theta_radians); Coord cos_theta = std::cos(theta_radians); return (Matrix4f() << 1, 0, 0, 0, 0, cos_theta, -sin_theta, 0, 0, sin_theta, cos_theta, 0, 0, 0, 0, 1).finished(); } Matrix4f rotationY(Coord theta_radians) { Coord sin_theta = std::sin(theta_radians); Coord cos_theta = std::cos(theta_radians); return (Matrix4f() << cos_theta, 0, sin_theta, 0, 0, 1, 0, 0, -sin_theta, 0, cos_theta, 0, 0, 0, 0, 1).finished(); } Matrix4f rotationZ(Coord theta_radians) { Coord sin_theta = std::sin(theta_radians); Coord cos_theta = std::cos(theta_radians); return (Matrix4f() << cos_theta, -sin_theta, 0, 0, sin_theta, cos_theta, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1).finished(); } Matrix4f rotationA(Coord theta_radians, Vector3f axis) { Coord s = std::sin(theta_radians); Coord c = std::cos(theta_radians); axis.normalize(); Coord x = axis[0]; Coord y = axis[1]; Coord z = axis[2]; return (Matrix4f() << // First row c + (1 - c) * x * x, (1 - c) * x * y - s * z, (1 - c) * x * z + s * y, 0, // Second row (1 - c) * x * y + s * z, c + (1 - c) * y * y, (1 - c) * y * z - s * x, 0, // Third row (1 - c) * x * z - s * y, (1 - c) * y * z + s * x, c + (1 - c) * z * z, 0, // Fourth row 0,0,0,1).finished(); } Matrix4f translate(Coord tx, Coord ty, Coord tz) { return (Matrix4f() << 1, 0, 0, tx, 0, 1, 0, ty, 0, 0, 1, tz, 0, 0, 0, 1).finished(); } Matrix4f shearing(Coord xy, Coord yx, Coord xz, Coord zx, Coord yz, Coord zy) { return (Matrix4f() << 1, xy, xz, 0, yx, 1, yz, 0, zx, zy, 1, 0, 0, 0, 0, 1).finished(); } Matrix4f frustum(Coord left, Coord right, Coord bottom, Coord top, Coord near, Coord far) { Coord r_l = right - left; Coord t_b = top - bottom; Coord f_n = far - near; return (Matrix4f() << // First row 2 * near / r_l, 0, (right + left) / r_l, 0, // Second row 0, 2 * near / t_b, (top + bottom) / t_b, 0, // Third row 0, 0, -(far + near) / f_n, -2 * near * far / f_n, // Fourth row 0, 0, -1, 0).finished(); } Matrix4f perspective(Coord fovy, Coord aspect, Coord near, Coord far) { Coord halfHeight = std::tan(std::numbers::pi * fovy / 360) * near; Coord halfWidth = halfHeight * aspect; return frustum(-halfWidth, halfWidth, -halfHeight, halfHeight, near, far); } Matrix4f ortho(Coord left, Coord right, Coord bottom, Coord top, Coord near, Coord far) { Coord r_l = right - left; Coord t_b = top - bottom; Coord f_n = far - near; return (Matrix4f() << // First row 2 / r_l, 0, 0, -(right + left) / r_l, // Second row 0, 2 / t_b, 0, -(top + bottom) / t_b, // Third row 0, 0, -2 / f_n, -(far + near) / f_n, // Fourth row 0, 0, 0, 1).finished(); } Matrix4f lookAt(Vector3f const& eye, Vector3f const& at, Vector3f const& up) { Vector3f forward = at - eye; forward.normalize(); Vector3f side = forward.cross(up); side.normalize(); Vector3f newUp = side.cross(forward); newUp.normalize(); return (Matrix4f() << side[0], side[1], side[2], -side.dot(eye), newUp[0], newUp[1], newUp[2], -newUp.dot(eye), -forward[0], -forward[1], -forward[2], forward.dot(eye), 0,0,0,1).finished(); } } // Transformations } // Grafica
6850521cc337482e260b914d20bc80c016933f00
e62fdfd7a2e892d5f1d6d5baf70ee04de20340bb
/Windows/Mailslot/Client/Client.cpp
e4d1d5327c4b35f8dbd6553fb2eda62f1d836e09
[]
no_license
Otteri/cpp-examples
5537c702408369c8ee4dbad3ae2cbc9ee0ee9882
bf86b999dc1a5a650c56b1be266e20c7954b3d90
refs/heads/master
2020-07-26T01:12:32.586013
2019-10-06T23:51:29
2019-10-06T23:51:29
208,482,718
0
0
null
null
null
null
UTF-8
C++
false
false
1,362
cpp
// Creating and writing mailslot example #include <windows.h> #include <stdio.h> #include <iostream> LPCTSTR SlotName = TEXT("\\\\.\\mailslot\\example_mailslot"); BOOL WriteSlot(HANDLE hSlot, LPCTSTR lpszMessage) { BOOL fResult; DWORD cbWritten; fResult = WriteFile(hSlot, lpszMessage, (DWORD)(lstrlen(lpszMessage) + 1) * sizeof(TCHAR), &cbWritten, (LPOVERLAPPED)NULL); if (!fResult) { std::cout << "WriteFile() failed with error code:" << GetLastError() << std::endl; return FALSE; } else { std::cout << "Wrote a message to mailslot" << std::endl; } return TRUE; } int main(int argc, char** argv) { HANDLE hFile; // Open handle to the mailslot hFile = CreateFile(SlotName, GENERIC_WRITE, FILE_SHARE_READ, (LPSECURITY_ATTRIBUTES)NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, (HANDLE)NULL); if (hFile == INVALID_HANDLE_VALUE) { std::cout << "CreateFile() failed with error code: " << GetLastError() << std::endl; return FALSE; } // Send messages WriteSlot(hFile, TEXT("First message")); WriteSlot(hFile, TEXT("Second message")); Sleep(3000); WriteSlot(hFile, TEXT("Third messge")); if (CloseHandle(hFile) == 0) { std::cout << "Fail to close hFile handle, error:" << GetLastError() << std::endl; } return TRUE; }
ecb9b5c98cfcba967a52af8e12c8771a5ae20472
7993f562d912c37c8d419622793d732c567df8d2
/adseebooklist.cpp
74565a6a05a47287316ae727a26d36beeddc44ff
[]
no_license
tazbid/OnlineBookStore
e71fc2dd148d52fc69f7470d2a5e66af09666f4b
56f0a3d701be2f25099c8e37a005e1de71548cca
refs/heads/master
2022-09-16T16:50:37.386849
2020-06-01T07:12:38
2020-06-01T07:12:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
323
cpp
#include "adseebooklist.h" #include "ui_adseebooklist.h" adseebooklist::adseebooklist(QWidget *parent) : QDialog(parent), ui(new Ui::adseebooklist) { ui->setupUi(this); this->setWindowTitle("Book List"); this->setWindowState(Qt::WindowMaximized); } adseebooklist::~adseebooklist() { delete ui; }
0bbd4f199662cfcc9c67b98338f693d497ecdf14
af0a0e3114932c6573fcaf9c753ed3076c134a83
/exercise2.3-jumpBalls/src/ball.h
362a66b2f92ba905fe963f8e18578697dbda8e74
[]
no_license
Paul92/NatureOfCode
ea556e6f436502d2871a5a486b9bd9cbf1005c58
e1d963b9eb051c6ab2e1c99fb0b1973dce9e71ef
refs/heads/master
2021-01-17T21:11:57.960155
2016-07-08T22:54:37
2016-07-08T22:54:37
62,155,614
0
0
null
null
null
null
UTF-8
C++
false
false
581
h
/** * @class Ball * * A sample ball class that implements some physics properties. * Can be used in particle systems. */ #include "ofMain.h" class Ball { private: ofPoint position; ofVec3f velocity; ofVec3f acceleration; float mass; public: Ball(); Ball(float mass); Ball(ofPoint position, float mass); void addForce(ofVec3f force); ofPoint getPosition() const; /// Bounce off the window boundaries. void boundaryCheck(); void update(); void draw() const; };
598d9e3bf146811077d89fba3cc3b537d1c189f8
7ab9732bfea95712d13ad0a0f9193c03e41ab3f4
/C++ Primer/C++ Primer&17/Example&17.30.cpp
6faaaea22d16c8075b9d81734d450f20ff2c619a
[]
no_license
LuckPsyduck/CPP-Example
611a09a3b80deb00ceff348acee7dd7c3db25a4f
8b4b75e1c90313811130c9c24484dce8ee951067
refs/heads/master
2021-05-23T00:18:57.770829
2020-04-05T13:05:58
2020-04-05T13:05:58
253,151,908
1
0
null
null
null
null
UTF-8
C++
false
false
745
cpp
#include<iostream> #include<random> using namespace std; unsigned int rand_int(long seed = -1,long min=1,long max=0) { static uniform_int_distribution<unsigned> u(0, 9999); static default_random_engine e; if (seed >= 0) e.seed(seed); if (min <= max) u = uniform_int_distribution<unsigned>(min, max); return u(e); } int main() { for (int i = 0; i < 10; i++) cout << rand_int() << " "; cout << endl; cout << rand_int(0) << " "; for (int i = 0; i < 9; i++) cout << rand_int() << " "; cout << endl; cout << rand_int(19743) << " "; for (int i = 0; i < 9; i++) cout << rand_int() << " "; cout << endl; cout << rand_int(19743,0,9) << " "; for (int i = 0; i < 9; i++) cout << rand_int() << " "; cout << endl; return 0; }
6f8a7e56bd4949fd7c0354fd886abdc42cd45df5
4ed7dd878a2b34bace1fd91a49106eebe570a360
/CodeChef/JUNE14/FORGETPW.cpp
dd53336345d2fa2a9a0593474ec4ba16438960ad
[]
no_license
mayukuner/AC
fb63be04a1fcf7f3af080aa50bf7c6e0e070b1b9
c21b2970b7288d7b36cbed468101446c615e79ff
refs/heads/master
2020-12-15T02:38:51.758676
2017-10-11T13:01:11
2017-10-11T13:01:11
46,971,415
3
1
null
null
null
null
UTF-8
C++
false
false
1,193
cpp
#include<stdio.h> #include<algorithm> #include<cstring> #include<vector> #include<map> #include<set> #define REP(i,n) for(int i=0; i<n; i++) #define FOR(i,n) for(int i=1; i<=n; i++) using namespace std; int n,m; char s1[5],s2[5],str[1000010],change[256]; int main(){ #ifdef QWERTIER freopen("in","r",stdin); #endif int T; scanf("%d",&T); while(T--){ memset(change,0,sizeof(change)); scanf("%d",&m); while(m--){ scanf("%s%s",s1,s2); change[s1[0]]=s2[0]; } scanf("%s",str); n=strlen(str); REP(i,n)if(change[str[i]]){ str[i]=change[str[i]]; } int comma=0; REP(i,n)if(str[i]=='.')comma=1; int st=0,ed=n-1; if(comma){ while(str[st]=='0')st++; while(str[ed]=='0')ed--; if(st==ed){ puts("0"); }else{ if(str[ed]=='.'){ for(int i=st; i<ed; i++) putchar(str[i]); putchar('\n'); }else{ for(int i=st; i<=ed; i++) putchar(str[i]); putchar('\n'); } } }else{ while(str[st]=='0' && st<ed)st++; for(int i=st; i<=ed; i++) putchar(str[i]); putchar('\n'); } } return 0; }
35c853756c54168af754088380c85e8dc062156d
ed9017f0222c52af0d2a6da73b9d046acae1ed76
/workspace/Activity_timak/src/Graphics/Activity/ForkAlgorithm.cpp
7ee95c135f9e0d56db648d24bcebb62c61627a2f
[]
no_license
next-dimension-team/Timak_15-16
7989d3a90d3cb20ec2a0d78fe604bf60740bf31d
0902a296ff835a1a7f091b1d25351330ea5e74e8
refs/heads/master
2021-01-11T02:11:11.558451
2016-10-06T10:08:31
2016-10-06T10:08:31
70,096,900
0
1
null
null
null
null
UTF-8
C++
false
false
4,691
cpp
#include "ForkAlgorithm.h" #include <math.h> #include <OgreBlendMode.h> #include <OgreCommon.h> #include <OgreHardwarePixelBuffer.h> #include <OgreLogManager.h> #include <OgreManualObject.h> #include <OgreMaterial.h> #include <OgreMaterialManager.h> #include <OgrePass.h> #include <OgrePixelFormat.h> #include <OgreRenderOperation.h> #include <OgreSceneNode.h> #include <OgreSharedPtr.h> #include <OgreTechnique.h> #include <OgreTexture.h> #include <OgreTextureManager.h> #include <sstream> #include <string> #include "../../Core/Activity/Fork.h" #include "ForkGraphics.h" #include "../../Core/Metamodel/include/Element.h" #include "../../ApplicationManagement/ElementCollection.h" #include "../../Core/Metamodel/include/ForkNode.h" const double ForkAlgorithm::SIZE = 3; ForkAlgorithm::ForkAlgorithm() : DrawingAlgorithm() { setSize((int)ForkAlgorithm::SIZE); } ForkAlgorithm::~ForkAlgorithm() {} void ForkAlgorithm::draw(const std::string& A_name) { std::pair<Element*, team4::MetamodelElement*> elem = ElementCollection::getInstance()->findElement(A_name); Fork* elemCasted; ForkGraphics* elemGraphicsCasted; if (elem.second->getType() != team4::ForkNode::ELEMENT_TYPE) { std::ostringstream os; os << "Invalid element type: "; os << "Expecting '"; os << team4::ForkNode::ELEMENT_TYPE; os << "' instead of '"; os << elem.second->getType(); os << "'."; Ogre::LogManager::getSingleton().logMessage(os.str()); return; } else { elemCasted = static_cast<Fork*>(elem.first); elemGraphicsCasted = static_cast<ForkGraphics*>(elem.first->getGraphics()); } this->elem = elemCasted; this->elemGraphics = elemGraphicsCasted; double size = ForkAlgorithm::SIZE; double z = 0; Ogre::ManualObject* manualObject = elemGraphicsCasted->getManualObject(); int width = size; int height = size *20; manualObject->begin(elem.second->getName() + "_material", Ogre::RenderOperation::OT_TRIANGLE_STRIP); manualObject->position(-height, width, z); manualObject->position(height, width, z); manualObject->position(-height, -width, z); manualObject->position(height, -width, z); manualObject->end(); manualObject->begin("BaseLineMaterial", Ogre::RenderOperation::OT_LINE_LIST); manualObject->position(-height, width, z); manualObject->position(height, width, z); manualObject->position(-height, -width, z); manualObject->position(height, -width, z); manualObject->position(-height, width, z); manualObject->position(-height, -width, z); manualObject->position(height, width, z); manualObject->position(height, -width, z); manualObject->end(); Ogre::SceneNode* node = elemGraphicsCasted->getSceneNode(); node->attachObject(manualObject); Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().create(elem.second->getName() + "_material", "General"); elem.first->material=material; material->getTechnique(0)->getPass(0)->createTextureUnitState(elem.second->getName() + "_texture"); material->getTechnique(0)->getPass(0)->setDepthCheckEnabled(false); material->getTechnique(0)->getPass(0)->setSceneBlending(Ogre::SBT_MODULATE); material->getTechnique(0)->getPass(0)->setDepthWriteEnabled(false); material->getTechnique(0)->getPass(0)->setLightingEnabled(false); material->getTechnique(0)->getPass(0)->setCullingMode(Ogre::CULL_NONE); double textureSizeScale = 5; Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().createManual( elem.second->getName() + "_texture", "General", Ogre::TEX_TYPE_2D, textureSizeScale * sqrt(2*pow(size,2)), textureSizeScale * sqrt(2*pow(size,2)), Ogre::MIP_UNLIMITED, Ogre::PF_X8R8G8B8, Ogre::TU_STATIC|Ogre::TU_AUTOMIPMAP); Ogre::Texture* background = Ogre::TextureManager::getSingleton().load("3D_material_3.png", "General").getPointer(); texture->getBuffer()->blit(background->getBuffer()); } void ForkAlgorithm::select(Element* elem) { Ogre::MaterialPtr material = elem->material; material->getTechnique(0)->getPass(0)->setLightingEnabled(true); } void ForkAlgorithm::unselected(Element* elem) { Ogre::MaterialPtr material = elem->material; material->getTechnique(0)->getPass(0)->setLightingEnabled(false); } double ForkAlgorithm::getFullSize() { return ForkAlgorithm::SIZE; }
efc466d1307692ddda6f1281c9f54871ec047c55
c3ffa07567d3d29a7439e33a6885a5544e896644
/UVa/821.cpp
49f7342156f1a2a6b253f0cf0b45bd45291f39fc
[]
no_license
a00012025/Online_Judge_Code
398c90c046f402218bd14867a06ae301c0c67687
7084865a7050fc09ffb0e734f77996172a93d3ce
refs/heads/master
2018-01-08T11:33:26.352408
2015-10-10T23:20:35
2015-10-10T23:20:35
44,031,127
0
0
null
null
null
null
UTF-8
C++
false
false
784
cpp
#include<stdio.h> #include<algorithm> #define INF 1000000 using namespace std; int d[101][101] ; main() { int a,b,tc=0 ; while(scanf("%d%d",&a,&b)==2 && a+b) { for(int i=0;i<=100;i++) for(int j=0;j<=100;j++) d[i][j]= (i==j ? 0 : INF) ; d[a][b]=1 ; while(scanf("%d%d",&a,&b)==2 && a+b) d[a][b]=1 ; for(int k=1;k<=100;k++) for(int i=1;i<=100;i++) for(int j=1;j<=100;j++) d[i][j]=min(d[i][j],d[i][k]+d[k][j]) ; double ans=0.0,cnt=0.0 ; for(int i=1;i<=100;i++) for(int j=1;j<=100;j++) if(d[i][j]!=INF) {ans+=d[i][j] ; if(i!=j) cnt++ ;} printf("Case %d: average length between pages = %.3lf clicks\n",++tc,ans/cnt) ; } }
72ccffca7796cf079a37937970b9163d083f3029
898ecea918175f07a36f7719ed3e0241a504f96b
/SNU Longest Hairpin Sequence/smallest.cpp
95df57c9cb04abda5ced7da94205fe78d8670946
[]
no_license
AdamBJ/Longest-Hairpin
b8abd0b508b1c317ccc0014a3955e5db5e35350a
18167d394712d009b64e0093dd7688a51a26b6d6
refs/heads/master
2021-01-13T00:44:44.578462
2015-05-31T10:12:18
2015-05-31T10:12:18
36,597,709
0
0
null
null
null
null
UTF-8
C++
false
false
153
cpp
#include <algorithm> // std::min //returns the minium of three input values int smallest(int x, int y, int z){ return std::min(std::min(x, y), z); }
7d45221b20beec0864ee7e7a4d34246a438f9211
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/squid/gumtree/squid_old_hunk_398.cpp
414dc9fe7b74c670bdbec1a0d64cee3b75c3710d
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
512
cpp
DelayTaggedBucket::~DelayTaggedBucket() { debugs(77, 3, "DelayTaggedBucket::~DelayTaggedBucket"); } void DelayTaggedBucket::stats (StoreEntry *entry) const { storeAppendPrintf(entry, " :" SQUIDSTRINGPH , SQUIDSTRINGPRINT(tag)); theBucket.stats (entry); } DelayTagged::Id::Id(DelayTagged::Pointer aDelayTagged, String &aTag) : theTagged(aDelayTagged) { theBucket = new DelayTaggedBucket(aTag); DelayTaggedBucket::Pointer const *existing = theTagged->buckets.find(theBucket, DelayTaggedCmp);
3529df8f8363115fb24802f3fd0705f170c09594
ced1bc5e9b6035da5ff91b3ef4344faa45a477ea
/RE-flex-master/examples/ugrep.cpp
d5ab98850014c1071fb769a26eb8eb9ef38e3252
[ "BSD-3-Clause" ]
permissive
WarlockD/BYOND_Compiler
2892365967797b8abe4e05adf2ae0e755929a448
1fd2da9ed1465bbad42ad2fcc0592a308a735490
refs/heads/master
2020-06-13T05:36:45.687386
2019-12-22T14:16:51
2019-12-22T14:16:51
194,555,014
1
0
null
null
null
null
UTF-8
C++
false
false
28,108
cpp
/******************************************************************************\ * Copyright (c) 2019, Robert van Engelen, Genivia Inc. All rights reserved. * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions are met: * * * * (1) Redistributions of source code must retain the above copyright notice, * * this list of conditions and the following disclaimer. * * * * (2) Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * * * (3) The name of the author may not be used to endorse or promote products * * derived from this software without specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * \******************************************************************************/ /** @file ugrep.cpp @brief Universal grep - high-performance Unicode file search utility @author Robert van Engelen - [email protected] @copyright (c) 2019-2019, Robert van Engelen, Genivia Inc. All rights reserved. @copyright (c) BSD-3 License - see LICENSE.txt Universal grep - high-performance universal search utility finds Unicode patterns in UTF-8/16/32, ASCII, ISO-8859-1, EBCDIC, code pages 437, 850, 1250 to 1258, and other file formats. For download and installation of the latest version, see: https://github.com/Genivia/ugrep Features: - Patterns are ERE POSIX syntax compliant, extended with RE/flex pattern syntax. - Unicode support for \p{} character categories, bracket list classes, etc. - File encoding support for UTF-8/16/32, EBCDIC, and many other code pages. - ugrep command-line options are the same as grep, simulates grep behavior. Differences with grep: - When option -b is used with option -o or with option -g, ugrep displays the exact byte offset of the pattern match instead of the byte offset of the start of the matched line. - Adds option -g, --no-group to not group matches per line. This option displays a matched input line again for each additional pattern match. This option also changes option -c to report the total number of pattern matches per file instead of the number of lines matched. - Adds option -k, --column-number to display the column number, taking tab spacing into account by expanding tabs. Examples: # display the lines in places.txt that contain capitalized Unicode words ugrep '\p{Upper}\p{Lower}*' places.txt # display the lines in places.txt with capitalized Unicode words color-highlighted ugrep --color=auto '\p{Upper}\p{Lower}*' places.txt # list all capitalized Unicode words in places.txt ugrep -o '\p{Upper}\p{Lower}*' places.txt # list all laughing face emojis (Unicode code points U+1F600 to U+1F60F) in birthday.txt ugrep -o '[😀-😏]' birthday.txt # list all laughing face emojis (Unicode code points U+1F600 to U+1F60F) in birthday.txt ugrep -o '[\x{1F600}-\x{1F60F}]' birthday.txt # display lines containing the names Gödel (or Goedel), Escher, or Bach in GEB.txt and wiki.txt ugrep 'G(ö|oe)del|Escher|Bach' GEB.txt wiki.txt # display lines that do not contain the names Gödel (or Goedel), Escher, or Bach in GEB.txt and wiki.txt ugrep -v 'G(ö|oe)del|Escher|Bach' GEB.txt wiki.txt # count the number of lines containing the names Gödel (or Goedel), Escher, or Bach in GEB.txt and wiki.txt ugrep -c 'G(ö|oe)del|Escher|Bach' GEB.txt wiki.txt # count the number of occurrences of the names Gödel (or Goedel), Escher, or Bach in GEB.txt and wiki.txt ugrep -c -g 'G(ö|oe)del|Escher|Bach' GEB.txt wiki.txt # check if some.txt file contains any non-ASCII (i.e. Unicode) characters ugrep -q '[^[:ascii:]]' some.txt && echo "some.txt contains Unicode" # display word-anchored 'lorem' in UTF-16 formatted file utf16lorem.txt that contains a UTF-16 BOM ugrep -w -i 'lorem' utf16lorem.txt # display word-anchored 'lorem' in UTF-16 formatted file utf16lorem.txt that does not contain a UTF-16 BOM ugrep --file-format=UTF-16 -w -i 'lorem' utf16lorem.txt # list the lines to fix in a C/C++ source file by looking for the word FIXME while skipping any FIXME in quoted strings by using a negative pattern `(?^X)' to ignore quoted strings: ugrep -n -o -e 'FIXME' -e '(?^"(\\.|\\\r?\n|[^\\\n"])*")' file.cpp # check if 'main' is defined in a C/C++ source file, skipping the word 'main' in comments and strings: ugrep -q -e '\<main\>' -e '(?^"(\\.|\\\r?\n|[^\\\n"])*"|//.*|/[*](.|\n)*?[*]/)' file.cpp Compile: c++ -std=c++11 -o ugrep ugrep.cpp -lreflex */ #include <reflex/matcher.h> // check if we are on a windows OS #if defined(__WIN32__) || defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__MINGW64__) || defined(__BORLANDC__) # define OS_WIN #endif // windows has no isatty() #ifdef OS_WIN #define isatty(fildes) ((fildes) == 1) #else #include <unistd.h> #endif // ugrep version #define VERSION "1.0.0" // ugrep platform -- see configure.ac #if !defined(PLATFORM) # if defined(OS_WIN) # define PLATFORM "WIN" # else # define PLATFORM "" # endif #endif // ugrep exit codes #define EXIT_OK 0 // One or more lines were selected #define EXIT_FAIL 1 // No lines were selected #define EXIT_ERROR 2 // An error occurred // GREP_COLOR environment variable const char *grep_color = NULL; // ugrep command-line options bool flag_filename = false; bool flag_no_filename = false; bool flag_no_group = false; bool flag_no_messages = false; bool flag_byte_offset = false; bool flag_count = false; bool flag_fixed_strings = false; bool flag_free_space = false; bool flag_ignore_case = false; bool flag_invert_match = false; bool flag_column_number = false; bool flag_line_number = false; bool flag_line_buffered = false; bool flag_only_matching = false; bool flag_quiet = false; bool flag_word_regexp = false; bool flag_line_regexp = false; const char *flag_color = NULL; const char *flag_file_format = NULL; int flag_tabs = 8; // function protos bool ugrep(reflex::Pattern& pattern, FILE *file, reflex::Input::file_encoding_type encoding, const char *infile); void help(const char *message = NULL, const char *arg = NULL); void version(); // table of file formats for ugrep option --file-format const struct { const char *format; reflex::Input::file_encoding_type encoding; } format_table[] = { { "binary", reflex::Input::file_encoding::plain }, { "ISO-8859-1", reflex::Input::file_encoding::latin }, { "ASCII", reflex::Input::file_encoding::utf8 }, { "EBCDIC", reflex::Input::file_encoding::ebcdic }, { "UTF-8", reflex::Input::file_encoding::utf8 }, { "UTF-16", reflex::Input::file_encoding::utf16be }, { "UTF-16BE", reflex::Input::file_encoding::utf16be }, { "UTF-16LE", reflex::Input::file_encoding::utf16le }, { "UTF-32", reflex::Input::file_encoding::utf32be }, { "UTF-32BE", reflex::Input::file_encoding::utf32be }, { "UTF-32LE", reflex::Input::file_encoding::utf32le }, { "CP437", reflex::Input::file_encoding::cp437 }, { "CP850", reflex::Input::file_encoding::cp850 }, { "CP1250", reflex::Input::file_encoding::cp1250 }, { "CP1251", reflex::Input::file_encoding::cp1251 }, { "CP1252", reflex::Input::file_encoding::cp1252 }, { "CP1253", reflex::Input::file_encoding::cp1253 }, { "CP1254", reflex::Input::file_encoding::cp1254 }, { "CP1255", reflex::Input::file_encoding::cp1255 }, { "CP1256", reflex::Input::file_encoding::cp1256 }, { "CP1257", reflex::Input::file_encoding::cp1257 }, { "CP1258", reflex::Input::file_encoding::cp1258 }, { NULL, 0 } }; // ugrep main() int main(int argc, char **argv) { std::string regex; std::vector<const char*> infiles; bool color_term = false; #ifndef OS_WIN // check whether we have a color terminal const char *term = getenv("TERM"); color_term = term && (strstr(term, "ansi") || strstr(term, "xterm") || strstr(term, "color")); grep_color = getenv("GREP_COLOR"); #endif // parse ugrep command-line options and arguments for (int i = 1; i < argc; ++i) { const char *arg = argv[i]; if (*arg == '-' #ifdef OS_WIN || *arg == '/' #endif ) { bool is_grouped = true; // parse a ugrep command-line option while (is_grouped && *++arg) { switch (*arg) { case '-': ++arg; if (strcmp(arg, "byte-offset") == 0) flag_byte_offset = true; else if (strcmp(arg, "color") == 0 || strcmp(arg, "colour") == 0) flag_color = "auto"; else if (strncmp(arg, "color=", 6) == 0) flag_color = arg + 6; else if (strncmp(arg, "colour=", 7) == 0) flag_color = arg + 7; else if (strcmp(arg, "column-number") == 0) flag_column_number = true; else if (strcmp(arg, "count") == 0) flag_count = true; else if (strcmp(arg, "extended-regexp") == 0) ; else if (strncmp(arg, "file-format=", 12) == 0) flag_file_format = arg + 12; else if (strcmp(arg, "fixed-strings") == 0) flag_fixed_strings = true; else if (strcmp(arg, "free-space") == 0) flag_free_space = true; else if (strcmp(arg, "help") == 0) help(); else if (strcmp(arg, "ignore-case") == 0) flag_ignore_case = true; else if (strcmp(arg, "invert-match") == 0) flag_invert_match = true; else if (strcmp(arg, "line-number") == 0) flag_line_number = true; else if (strcmp(arg, "line-regexp") == 0) flag_line_regexp = true; else if (strcmp(arg, "no-filename") == 0) flag_no_filename = true; else if (strcmp(arg, "no-group") == 0) flag_no_group = true; else if (strcmp(arg, "no-messages") == 0) flag_no_messages = true; else if (strcmp(arg, "only-matching") == 0) flag_only_matching = true; else if (strcmp(arg, "quiet") == 0 || strcmp(arg, "silent") == 0) flag_quiet = true; else if (strncmp(arg, "regexp=", 7) == 0) regex.append(arg + 7).push_back('|'); else if (strncmp(arg, "tabs=", 5) == 0) flag_tabs = atoi(arg + 5); else if (strcmp(arg, "version") == 0) version(); else if (strcmp(arg, "word-regexp") == 0) flag_word_regexp = true; else help("unknown option --", arg); is_grouped = false; break; case 'b': flag_byte_offset = true; break; case 'c': flag_count = true; break; case 'E': break; case 'e': ++arg; if (*arg) regex.append(&arg[*arg == '=']).push_back('|'); else if (++i < argc) regex.append(argv[i]).push_back('|'); else help("missing pattern for option -e"); is_grouped = false; break; case 'F': flag_fixed_strings = true; break; case 'g': flag_no_group = true; break; case 'H': flag_filename = true; flag_no_filename = false; break; case 'h': flag_filename = false; flag_no_filename = true; break; case 'i': flag_ignore_case = true; break; case 'k': flag_column_number = true; break; case 'n': flag_line_number = true; break; case 'o': flag_only_matching = true; break; case 'q': flag_quiet = true; break; case 's': flag_no_messages = true; break; case 'V': version(); break; case 'v': flag_invert_match = true; break; case 'w': flag_word_regexp = true; break; case 'x': flag_line_regexp = true; break; case '?': help(); default: help("unknown option -", arg); } } } else { // parse a ugrep command-line argument if (regex.empty()) // no regex pattern specified yet, so assign it to the regex string regex.assign(arg).push_back('|'); else // otherwise add the file argument to the list of files infiles.push_back(arg); } } // if no regex pattern was specified then exit if (regex.empty()) help(); // remove the ending '|' from the |-concatenated regexes in the regex string regex.pop_back(); if (regex.empty()) { // if the specified regex is empty then it matches every line regex.assign(".*"); } else { // if -F --fixed-strings: make regex literal with \Q and \E if (flag_fixed_strings) regex.insert(0, "\\Q").append("\\E"); // if -w or -x: make the regex word- or line-anchored, respectively if (flag_word_regexp) regex.insert(0, "\\<(").append(")\\>"); else if (flag_line_regexp) regex.insert(0, "^(").append(")$"); } // if -v invert-match: options -g --no-group and -o --only-matching options cannot be used if (flag_invert_match) { flag_no_group = false; flag_only_matching = false; } // input is line-buffered if options -c --count -o --only-matching -q --quiet are not specified if (!flag_count && !flag_only_matching && !flag_quiet) flag_line_buffered = true; // display file name if more than one input file is specified and option -h --no-filename is not specified if (infiles.size() > 1 && !flag_no_filename) flag_filename = true; // (re)set grep_color depending on color_term, isatty(), and the ugrep --color option if (!flag_color || strcmp(flag_color, "never") == 0) { grep_color = NULL; } else if (strcmp(flag_color, "always") == 0) { if (!grep_color) grep_color = "1"; } else if (strcmp(flag_color, "auto") == 0) { if (!color_term || !isatty(1)) grep_color = NULL; else if (!grep_color) grep_color = "1"; } else { help("unknown --color=when value"); } // if any match was found in any of the input files then we set found==true bool found = false; try { reflex::Input::file_encoding_type encoding = reflex::Input::file_encoding::plain; // parse ugrep option --file-format=format if (flag_file_format) { int i; // scan the format_table[] for a matching format for (i = 0; format_table[i].format != NULL; ++i) if (strcmp(flag_file_format, format_table[i].format) == 0) break; if (format_table[i].format == NULL) help("unknown --file-format=format encoding"); // encoding is the file format used by all input files, if no BOM is present encoding = format_table[i].encoding; } std::string modifiers = "(?m"; if (flag_ignore_case) modifiers.append("i"); if (flag_free_space) modifiers.append("x"); modifiers.append(")"); std::string pattern_options; if (flag_tabs) { if (flag_tabs == 1 || flag_tabs == 2 || flag_tabs == 4 || flag_tabs == 8) pattern_options.assign("T=").push_back(flag_tabs + '0'); else help("invalid value for option --tabs"); } reflex::Pattern pattern(modifiers + reflex::Matcher::convert(regex, reflex::convert_flag::unicode), pattern_options); if (infiles.empty()) { // read standard input to find pattern matches found |= ugrep(pattern, stdin, encoding, "(standard input)"); } else { // read each file to find pattern matches for (auto infile : infiles) { FILE *file = fopen(infile, "r"); if (file == NULL) { if (flag_no_messages) continue; perror("Cannot open file for reading"); exit(EXIT_ERROR); } found |= ugrep(pattern, file, encoding, infile); fclose(file); } } } catch (reflex::regex_error& error) { std::cerr << error.what(); exit(EXIT_ERROR); } exit(found ? EXIT_OK : EXIT_FAIL); } // Search file, display pattern matches, return true when pattern matched anywhere bool ugrep(reflex::Pattern& pattern, FILE *file, reflex::Input::file_encoding_type encoding, const char *infile) { bool found = false; std::string label, mark, unmark; if (flag_filename && infile) label.assign(infile).append(":"); if (grep_color) { mark.assign("\033[").append(grep_color).append("m"); unmark.assign("\033[0m"); } // create an input object to read the file (or stdin) using the given file format encoding reflex::Input input(file, encoding); if (flag_quiet) { // -q quite mode: report if a single pattern match was found in the input found = reflex::Matcher(pattern, input).find(); if (flag_invert_match) found = !found; } else if (flag_count) { // -c count mode: count the number of lines/patterns matched if (flag_invert_match) { size_t lines = 0; std::string line; // -c count mode w/ -v: count the number of non-matching lines while (input) { int ch; // read the next line line.clear(); while ((ch = input.get()) != EOF && ch != '\n') line.push_back(ch); if (ch == EOF && line.empty()) break; // count this line if not matched if (!reflex::Matcher(pattern, line).find()) { found = true; ++lines; } } std::cout << label << lines << std::endl; } else if (flag_no_group) { // -c count mode w/ -g: count the number of patterns matched in the file reflex::Matcher matcher(pattern, input); size_t matches = std::distance(matcher.find.begin(), matcher.find.end()); std::cout << label << matches << std::endl; found = matches > 0; } else { // -c count mode w/o -g: count the number of matching lines size_t lineno = 0; size_t lines = 0; reflex::Matcher matcher(pattern, input); for (auto& match : matcher.find) { if (lineno != match.lineno()) { lineno = match.lineno(); ++lines; } } std::cout << label << lines << std::endl; found = lines > 0; } } else if (flag_line_buffered) { // line-buffered input: read input line-by-line and display lines that matched the pattern size_t byte_offset = 0; size_t lineno = 1; std::string line; while (input) { int ch; // read the next line line.clear(); while ((ch = input.get()) != EOF && ch != '\n') line.push_back(ch); if (ch == EOF && line.empty()) break; if (flag_invert_match) { // -v invert match: display non-matching line if (!reflex::Matcher(pattern, line).find()) { std::cout << label; if (flag_line_number) std::cout << lineno << ":"; if (flag_byte_offset) std::cout << byte_offset << ":"; std::cout << line << std::endl; found = true; } } else if (flag_no_group) { // search the line for pattern matches and display the line again (with exact offset) for each pattern match reflex::Matcher matcher(pattern, line); for (auto& match : matcher.find) { std::cout << label; if (flag_line_number) std::cout << lineno << ":"; if (flag_column_number) std::cout << match.columno() + 1 << ":"; if (flag_byte_offset) std::cout << byte_offset << ":"; std::cout << line.substr(0, match.first()) << mark << match.text() << unmark << line.substr(match.last()) << std::endl; found = true; } } else { // search the line for pattern matches and display the line just once with all matches size_t last = 0; reflex::Matcher matcher(pattern, line); for (auto& match : matcher.find) { if (last == 0) { std::cout << label; if (flag_line_number) std::cout << lineno << ":"; if (flag_column_number) std::cout << match.columno() + 1 << ":"; if (flag_byte_offset) std::cout << byte_offset + match.first() << ":"; std::cout << line.substr(0, match.first()) << mark << match.text() << unmark; last = match.last(); found = true; } else { std::cout << line.substr(last, match.first() - last) << mark << match.text() << unmark; last = match.last(); } } if (last > 0) std::cout << line.substr(last) << std::endl; } // update byte offset and line number byte_offset += line.size() + 1; ++lineno; } } else { // block-buffered input: echo all pattern matches size_t lineno = 0; reflex::Matcher matcher(pattern, input); for (auto& match : matcher.find) { if (flag_no_group || lineno != match.lineno()) { lineno = match.lineno(); std::cout << label; if (flag_line_number) std::cout << lineno << ":"; if (flag_column_number) std::cout << match.columno() + 1 << ":"; if (flag_byte_offset) std::cout << match.first() << ":"; } std::cout << mark << match.text() << unmark << std::endl; found = true; } } return found; } // Display help information with an optional diagnostic message and exit void help(const char *message, const char *arg) { if (message) std::cout << "ugrep: " << message << (arg != NULL ? arg : "") << std::endl; std::cout << "Usage: ugrep [-bcEFgHhiknoqsVvwx] [--colour[=when]|--color[=when]] [-e pattern] [pattern] [file ...]\n\ \n\ -b, --byte-offset\n\ The offset in bytes of a matched pattern is displayed in front of\n\ the respective matched line.\n\ -c, --count\n\ Only a count of selected lines is written to standard output.\n\ When used with option -g, counts the number of patterns matched.\n\ --colour[=when], --color[=when]\n\ Mark up the matching text with the expression stored in the\n\ GREP_COLOR environment variable. The possible values of when can\n\ be `never', `always' or `auto'.\n\ -E, --extended-regexp\n\ Ignored, intended for grep compatibility.\n\ -e pattern, --regexp=pattern\n\ Specify a pattern used during the search of the input: an input\n\ line is selected if it matches any of the specified patterns.\n\ This option is most useful when multiple -e options are used to\n\ specify multiple patterns, or when a pattern begins with a dash\n\ (`-').\n\ --file-format=format\n\ The input file format. The possible values of format can be:"; for (int i = 0; format_table[i].format != NULL; ++i) std::cout << (i % 8 ? " " : "\n ") << format_table[i].format; std::cout << "\n\ -F, --fixed-strings\n\ Interpret pattern as a set of fixed strings (i.e. force ugrep to\n\ behave as fgrep).\n\ --free-space\n\ Spacing (blanks and tabs) in regular expressions are ignored.\n\ -g, --no-group\n\ Do not group pattern matches on the same line. Display the\n\ matched line again for each additional pattern match.\n\ -H\n\ Always print filename headers with output lines.\n\ -h, --no-filename\n\ Never print filename headers (i.e. filenames) with output lines.\n\ -?, --help\n\ Print a help message.\n\ -i, --ignore-case\n\ Perform case insensitive matching. This option applies\n\ case-insensitive matching of ASCII characters in the input.\n\ By default, ugrep is case sensitive.\n\ -k, --column-number\n\ The column number of a matched pattern is displayed in front of\n\ the respective matched line, starting at column 1. Tabs are\n\ expanded before columns are counted.\n\ -n, --line-number\n\ Each output line is preceded by its relative line number in the\n\ file, starting at line 1. The line number counter is reset for\n\ each file processed.\n\ -o, --only-matching\n\ Prints only the matching part of the lines. Allows a pattern\n\ match to span multiple lines.\n\ -q, --quiet, --silent\n\ Quiet mode: suppress normal output. ugrep will only search a file\n\ until a match has been found, making searches potentially less\n\ expensive. Allows a pattern match to span multiple lines.\n\ -s, --no-messages\n\ Silent mode. Nonexistent and unreadable files are ignored (i.e.\n\ their error messages are suppressed).\n\ --tabs=size\n\ Set the tab size to 1, 2, 4, or 8 to expand tabs for option -k.\n\ -V, --version\n\ Display version information and exit.\n\ -v, --invert-match\n\ Selected lines are those not matching any of the specified\n\ patterns.\n\ -w, --word-regexp\n\ The pattern is searched for as a word (as if surrounded by\n\ `\\<' and `\\>').\n\ -x, --line-regexp\n\ Only input lines selected against an entire pattern are considered\n\ to be matching lines (as if surrounded by ^ and $).\n\ \n\ The ugrep utility exits with one of the following values:\n\ \n\ 0 One or more lines were selected.\n\ 1 No lines were selected.\n\ >1 An error occurred.\n\ " << std::endl; exit(EXIT_ERROR); } // Display version info void version() { std::cout << "ugrep " VERSION " " PLATFORM << std::endl; exit(EXIT_OK); }
9804e71beeb76ad473191987527ba716cdf4df4c
ebd3360a127b9f0f38363dc0dad35a5d452140ac
/27.cpp
aa0c747a5a174888b0716293f94f9b6398f71f42
[]
no_license
peachhhhh/CodingInterviews
e4c0f41ad956f0519e59d28de0064e381b9f5693
54e0bea986a30188b716c5a794222054b015b98f
refs/heads/master
2020-09-12T06:54:39.782020
2020-01-16T08:33:50
2020-01-16T08:33:50
222,347,045
0
0
null
null
null
null
UTF-8
C++
false
false
750
cpp
#include <iostream> #include <vector> #include <algorithm> using namespace std; void dfs(vector<string> &res, string s, int pos) { if (pos == s.size() - 1) { if (find(res.begin(), res.end(), s) == res.end()) { res.push_back(s); //如果res中已有重复结果,则不push } return; } for (int i = pos; i < s.size(); i++) { swap(s[i], s[pos]); dfs(res, s, pos + 1); swap(s[i], s[pos]); } } //字符串的排列(全排列,leetcode-46) vector<string> Permutation(string str) { vector<string> res; dfs(res, str, 0); sort(res.begin(), res.end()); //转换成字典序 return res; } void test() { } int main() { test(); return 0; }
60c209c20172cafec6359051133a097118e8065a
83b0c001f3655386f2545a3418a545e1d479ff01
/Guadalajara/InterfaceDefinitions.cpp
f613601d3f5af16b822c7773ba4ab04a63c886e0
[]
no_license
liamdebellada/Guadalajara
60766ae3dc225547b1164b9df176261af029c40a
9e3953bc9fbc28b0066b68188283f9aa4345ff87
refs/heads/main
2023-03-21T18:08:51.221129
2021-03-10T20:07:05
2021-03-10T20:07:05
343,461,899
1
1
null
2021-03-04T20:57:07
2021-03-01T15:21:40
null
UTF-8
C++
false
false
923
cpp
#include "InterfaceDefinitions.h" #include <Windows.h> #include <iostream> InterfaceCollection* Interfaces = nullptr; typedef void* (*tCreateInterface)(const char* name, int* returnCode); void* GetInterface(const char* dllName, const char* interfaceName) { tCreateInterface CreateInterface = (tCreateInterface)GetProcAddress(GetModuleHandle(dllName), "CreateInterface"); int returnCode = 0; void* Interface = CreateInterface(interfaceName, &returnCode); return Interface; } InterfaceCollection::InterfaceCollection() { ClientEntityList = (IClientEntityList*)GetInterface("client.dll", "VClientEntityList003"); EngineClient = (IEngineClient*)GetInterface("engine.dll", "VEngineClient014"); InputSystem = (IInputSystem*)GetInterface("inputsystem.dll", "InputSystemVersion001"); Client = (IBaseClientDLL*)GetInterface("client.dll", "VClient018"); ClientMode = **(IClientMode***)((*(DWORD**)Client)[10] + 0x5); }
f1a434ed81af1ff8e428723b47e3894115e37e03
d62af3d2dd56df30c190a59bf7699bc38865d610
/cc/array/longest_consecutive_sequence.cc
5c806132737a13ee731d283736f9efdb208c8b0e
[]
no_license
colinblack/leetcode
abadc3045c90b15694a17eb8d3916ac16f813332
9368bbc41993958fb4b538ef873f0dfc23488ba0
refs/heads/master
2020-07-24T20:30:48.841711
2020-01-13T23:51:51
2020-01-13T23:51:51
208,040,195
0
0
null
null
null
null
UTF-8
C++
false
false
730
cc
#include <iostream> #include <unordered_map> #include <vector> #include <algorithm> using std::vector; using std::unordered_map; class Solution { public: int longestConsecutive(vector<int> &num) { unordered_map<int, bool> hash_table; for (auto i : num) { hash_table[i] = false; } int length = 0; for (auto i : num) { if (hash_table[i]) continue; int len = 1; hash_table[i] = true; for (int j = i + 1; hash_table.find(j) != hash_table.end(); ++j) { hash_table[j] = true; ++len; } for (int j = i - 1; hash_table.find(j) != hash_table.end(); --j) { hash_table[j] = true; ++len; } length = std::max(length, len); } return length; } }; int main() { return 0; }
54267294af1ff08e226a18605b3dd0b45f6a6914
5544235b9aa443ff5dc0731ee8cf7d557e9bc346
/src/ch11.cpp
fbe85d9938bf4a77b7669fa34b9c1b3ebd965179
[]
no_license
eric-simon/TMPBook
67617cb2378aecdd19d378c0a50ffe5826f939b1
949c0d50fb396eb9cf3071ef059b30614985a7c4
refs/heads/master
2020-06-19T10:20:44.343955
2019-06-23T01:22:37
2019-06-23T01:22:37
74,908,953
0
0
null
null
null
null
UTF-8
C++
false
false
438
cpp
#include "stdafx.h" #include "ch11.h" #include "player.h" #include <vector> #include <ctime> int ch11(int argc, _TCHAR* argv[]) { player p; p.process_event(open_close()); p.process_event(open_close()); //p.process_event(cd_detected("Louie, Louie", std::vector<std::clock_t>())); p.process_event(cd_detected()); p.process_event(play()); p.process_event(pause()); p.process_event(play()); p.process_event(stop()); return 0; }
a39fb648311aad564eff2611ebab95d7d74c083c
01b8c8094dc5beb8518dbed3be7775b79071a9c8
/sky/engine/tonic/dart_string_cache.cc
d82deb1eb035a7f21260478bd888fa04d9f53f5d
[ "BSD-3-Clause" ]
permissive
bprosnitz/mojo
2e01c9fed8326ad86d6364baf0790ff99e2d8f3c
0c7f1938808f0df20704c336ccbe47b429c92f70
refs/heads/master
2021-01-09T07:00:22.139224
2015-06-23T17:20:56
2015-06-23T17:20:56
37,934,424
0
0
null
2015-06-23T17:39:27
2015-06-23T17:39:27
null
UTF-8
C++
false
false
2,008
cc
// Copyright 2014 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 "sky/engine/config.h" #include "sky/engine/tonic/dart_string_cache.h" #include "sky/engine/tonic/dart_state.h" #include "sky/engine/tonic/dart_string.h" namespace blink { DartStringCache::DartStringCache() : last_dart_string_(nullptr) { } DartStringCache::~DartStringCache() { } Dart_WeakPersistentHandle DartStringCache::GetSlow(StringImpl* string_impl, bool auto_scope) { if (Dart_WeakPersistentHandle string = cache_.get(string_impl)) { last_dart_string_ = string; last_string_impl_ = string_impl; return string; } if (!auto_scope) Dart_EnterScope(); Dart_Handle string = CreateDartString(string_impl); DCHECK(!Dart_IsError(string)); intptr_t size_in_bytes = string_impl->sizeInBytes(); Dart_WeakPersistentHandle wrapper = Dart_NewWeakPersistentHandle( string, string_impl, size_in_bytes, FinalizeCacheEntry); string_impl->ref(); // Balanced in FinalizeCacheEntry. cache_.set(string_impl, wrapper); last_dart_string_ = wrapper; last_string_impl_ = string_impl; if (!auto_scope) Dart_ExitScope(); return wrapper; } void DartStringCache::FinalizeCacheEntry(void* isolate_callback_data, Dart_WeakPersistentHandle handle, void* peer) { DartState* state = reinterpret_cast<DartState*>(isolate_callback_data); StringImpl* string_impl = reinterpret_cast<StringImpl*>(peer); DartStringCache& cache = state->string_cache(); Dart_WeakPersistentHandle cached_handle = cache.cache_.take(string_impl); ASSERT_UNUSED(cached_handle, handle == cached_handle); if (cache.last_dart_string_ == handle) { cache.last_dart_string_ = nullptr; cache.last_string_impl_ = nullptr; } string_impl->deref(); } } // namespace blink
a368f9ccd5c955e722941c78dcef007b6840b843
ac1c9fbc1f1019efb19d0a8f3a088e8889f1e83c
/out/release/gen/third_party/blink/renderer/bindings/core/v8/v8_hash_change_event.cc
38877198dd920e0296c490553215f0d577e2fdf9
[ "BSD-3-Clause" ]
permissive
xueqiya/chromium_src
5d20b4d3a2a0251c063a7fb9952195cda6d29e34
d4aa7a8f0e07cfaa448fcad8c12b29242a615103
refs/heads/main
2022-07-30T03:15:14.818330
2021-01-16T16:47:22
2021-01-16T16:47:22
330,115,551
1
0
null
null
null
null
UTF-8
C++
false
false
10,745
cc
// Copyright 2014 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. // This file has been auto-generated from the Jinja2 template // third_party/blink/renderer/bindings/templates/interface.cc.tmpl // by the script code_generator_v8.py. // DO NOT MODIFY! // clang-format off #include "third_party/blink/renderer/bindings/core/v8/v8_hash_change_event.h" #include <algorithm> #include "base/memory/scoped_refptr.h" #include "third_party/blink/renderer/bindings/core/v8/idl_types.h" #include "third_party/blink/renderer/bindings/core/v8/native_value_traits_impl.h" #include "third_party/blink/renderer/bindings/core/v8/v8_dom_configuration.h" #include "third_party/blink/renderer/bindings/core/v8/v8_hash_change_event_init.h" #include "third_party/blink/renderer/core/execution_context/execution_context.h" #include "third_party/blink/renderer/core/frame/local_dom_window.h" #include "third_party/blink/renderer/platform/bindings/exception_messages.h" #include "third_party/blink/renderer/platform/bindings/exception_state.h" #include "third_party/blink/renderer/platform/bindings/runtime_call_stats.h" #include "third_party/blink/renderer/platform/bindings/v8_object_constructor.h" #include "third_party/blink/renderer/platform/scheduler/public/cooperative_scheduling_manager.h" #include "third_party/blink/renderer/platform/wtf/get_ptr.h" namespace blink { // Suppress warning: global constructors, because struct WrapperTypeInfo is trivial // and does not depend on another global objects. #if defined(COMPONENT_BUILD) && defined(WIN32) && defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wglobal-constructors" #endif const WrapperTypeInfo v8_hash_change_event_wrapper_type_info = { gin::kEmbedderBlink, V8HashChangeEvent::DomTemplate, nullptr, "HashChangeEvent", V8Event::GetWrapperTypeInfo(), WrapperTypeInfo::kWrapperTypeObjectPrototype, WrapperTypeInfo::kObjectClassId, WrapperTypeInfo::kNotInheritFromActiveScriptWrappable, }; #if defined(COMPONENT_BUILD) && defined(WIN32) && defined(__clang__) #pragma clang diagnostic pop #endif // This static member must be declared by DEFINE_WRAPPERTYPEINFO in HashChangeEvent.h. // For details, see the comment of DEFINE_WRAPPERTYPEINFO in // platform/bindings/ScriptWrappable.h. const WrapperTypeInfo& HashChangeEvent::wrapper_type_info_ = v8_hash_change_event_wrapper_type_info; // not [ActiveScriptWrappable] static_assert( !std::is_base_of<ActiveScriptWrappableBase, HashChangeEvent>::value, "HashChangeEvent inherits from ActiveScriptWrappable<>, but is not specifying " "[ActiveScriptWrappable] extended attribute in the IDL file. " "Be consistent."); static_assert( std::is_same<decltype(&HashChangeEvent::HasPendingActivity), decltype(&ScriptWrappable::HasPendingActivity)>::value, "HashChangeEvent is overriding hasPendingActivity(), but is not specifying " "[ActiveScriptWrappable] extended attribute in the IDL file. " "Be consistent."); namespace hash_change_event_v8_internal { static void OldURLAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Local<v8::Object> holder = info.Holder(); HashChangeEvent* impl = V8HashChangeEvent::ToImpl(holder); V8SetReturnValueString(info, impl->oldURL(), info.GetIsolate()); } static void NewURLAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Local<v8::Object> holder = info.Holder(); HashChangeEvent* impl = V8HashChangeEvent::ToImpl(holder); V8SetReturnValueString(info, impl->newURL(), info.GetIsolate()); } static void IsTrustedAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Local<v8::Object> holder = info.Holder(); HashChangeEvent* impl = V8HashChangeEvent::ToImpl(holder); V8SetReturnValueBool(info, impl->isTrusted()); } static void Constructor(const v8::FunctionCallbackInfo<v8::Value>& info) { RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_HashChangeEvent_ConstructorCallback"); ExceptionState exception_state(info.GetIsolate(), ExceptionState::kConstructionContext, "HashChangeEvent"); if (UNLIKELY(info.Length() < 1)) { exception_state.ThrowTypeError(ExceptionMessages::NotEnoughArguments(1, info.Length())); return; } V8StringResource<> type; HashChangeEventInit* event_init_dict; type = info[0]; if (!type.Prepare()) return; if (!info[1]->IsNullOrUndefined() && !info[1]->IsObject()) { exception_state.ThrowTypeError("parameter 2 ('eventInitDict') is not an object."); return; } event_init_dict = NativeValueTraits<HashChangeEventInit>::NativeValue(info.GetIsolate(), info[1], exception_state); if (exception_state.HadException()) return; HashChangeEvent* impl = HashChangeEvent::Create(type, event_init_dict); v8::Local<v8::Object> wrapper = info.Holder(); wrapper = impl->AssociateWithWrapper(info.GetIsolate(), V8HashChangeEvent::GetWrapperTypeInfo(), wrapper); V8SetReturnValue(info, wrapper); } CORE_EXPORT void ConstructorCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_HashChangeEvent_Constructor"); if (!info.IsConstructCall()) { V8ThrowException::ThrowTypeError( info.GetIsolate(), ExceptionMessages::ConstructorNotCallableAsFunction("HashChangeEvent")); return; } if (ConstructorMode::Current(info.GetIsolate()) == ConstructorMode::kWrapExistingObject) { V8SetReturnValue(info, info.Holder()); return; } hash_change_event_v8_internal::Constructor(info); } } // namespace hash_change_event_v8_internal void V8HashChangeEvent::OldURLAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_HashChangeEvent_oldURL_Getter"); hash_change_event_v8_internal::OldURLAttributeGetter(info); } void V8HashChangeEvent::NewURLAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_HashChangeEvent_newURL_Getter"); hash_change_event_v8_internal::NewURLAttributeGetter(info); } void V8HashChangeEvent::IsTrustedAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_HashChangeEvent_isTrusted_Getter"); hash_change_event_v8_internal::IsTrustedAttributeGetter(info); } static void InstallV8HashChangeEventTemplate( v8::Isolate* isolate, const DOMWrapperWorld& world, v8::Local<v8::FunctionTemplate> interface_template) { // Initialize the interface object's template. V8DOMConfiguration::InitializeDOMInterfaceTemplate(isolate, interface_template, V8HashChangeEvent::GetWrapperTypeInfo()->interface_name, V8Event::DomTemplate(isolate, world), V8HashChangeEvent::kInternalFieldCount); interface_template->SetCallHandler(hash_change_event_v8_internal::ConstructorCallback); interface_template->SetLength(1); v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interface_template); ALLOW_UNUSED_LOCAL(signature); v8::Local<v8::ObjectTemplate> instance_template = interface_template->InstanceTemplate(); ALLOW_UNUSED_LOCAL(instance_template); v8::Local<v8::ObjectTemplate> prototype_template = interface_template->PrototypeTemplate(); ALLOW_UNUSED_LOCAL(prototype_template); // Register IDL constants, attributes and operations. static constexpr V8DOMConfiguration::AccessorConfiguration kAccessorConfigurations[] = { { "oldURL", V8HashChangeEvent::OldURLAttributeGetterCallback, nullptr, V8PrivateProperty::kNoCachedAccessor, static_cast<v8::PropertyAttribute>(v8::ReadOnly), V8DOMConfiguration::kOnPrototype, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kHasSideEffect, V8DOMConfiguration::kAlwaysCallGetter, V8DOMConfiguration::kAllWorlds }, { "newURL", V8HashChangeEvent::NewURLAttributeGetterCallback, nullptr, V8PrivateProperty::kNoCachedAccessor, static_cast<v8::PropertyAttribute>(v8::ReadOnly), V8DOMConfiguration::kOnPrototype, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kHasSideEffect, V8DOMConfiguration::kAlwaysCallGetter, V8DOMConfiguration::kAllWorlds }, { "isTrusted", V8HashChangeEvent::IsTrustedAttributeGetterCallback, nullptr, V8PrivateProperty::kNoCachedAccessor, static_cast<v8::PropertyAttribute>(v8::DontDelete | v8::ReadOnly), V8DOMConfiguration::kOnInstance, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kHasSideEffect, V8DOMConfiguration::kAlwaysCallGetter, V8DOMConfiguration::kAllWorlds }, }; V8DOMConfiguration::InstallAccessors( isolate, world, instance_template, prototype_template, interface_template, signature, kAccessorConfigurations, base::size(kAccessorConfigurations)); // Custom signature V8HashChangeEvent::InstallRuntimeEnabledFeaturesOnTemplate( isolate, world, interface_template); } void V8HashChangeEvent::InstallRuntimeEnabledFeaturesOnTemplate( v8::Isolate* isolate, const DOMWrapperWorld& world, v8::Local<v8::FunctionTemplate> interface_template) { v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interface_template); ALLOW_UNUSED_LOCAL(signature); v8::Local<v8::ObjectTemplate> instance_template = interface_template->InstanceTemplate(); ALLOW_UNUSED_LOCAL(instance_template); v8::Local<v8::ObjectTemplate> prototype_template = interface_template->PrototypeTemplate(); ALLOW_UNUSED_LOCAL(prototype_template); // Register IDL constants, attributes and operations. // Custom signature } v8::Local<v8::FunctionTemplate> V8HashChangeEvent::DomTemplate( v8::Isolate* isolate, const DOMWrapperWorld& world) { return V8DOMConfiguration::DomClassTemplate( isolate, world, const_cast<WrapperTypeInfo*>(V8HashChangeEvent::GetWrapperTypeInfo()), InstallV8HashChangeEventTemplate); } bool V8HashChangeEvent::HasInstance(v8::Local<v8::Value> v8_value, v8::Isolate* isolate) { return V8PerIsolateData::From(isolate)->HasInstance(V8HashChangeEvent::GetWrapperTypeInfo(), v8_value); } v8::Local<v8::Object> V8HashChangeEvent::FindInstanceInPrototypeChain( v8::Local<v8::Value> v8_value, v8::Isolate* isolate) { return V8PerIsolateData::From(isolate)->FindInstanceInPrototypeChain( V8HashChangeEvent::GetWrapperTypeInfo(), v8_value); } HashChangeEvent* V8HashChangeEvent::ToImplWithTypeCheck( v8::Isolate* isolate, v8::Local<v8::Value> value) { return HasInstance(value, isolate) ? ToImpl(v8::Local<v8::Object>::Cast(value)) : nullptr; } } // namespace blink
eb46a25d11bc8b682cefbc5384facc319d294d74
dec817636542866fcb33b8ca41d1be119a51f5b1
/myview/main.cpp
b68c617fc3319aa9bca8d2081c997a55a8a8b57e
[]
no_license
jinsook/cpluspluscodes
dfc6882a3e2489747cfb8a49800b115123483cca
7d2be7b57b363e104d0aa774dfc420309972e691
refs/heads/master
2021-01-02T09:14:01.537354
2015-02-04T07:54:20
2015-02-04T07:54:20
23,863,934
0
0
null
null
null
null
UTF-8
C++
false
false
342
cpp
#include "ui_mainwindow.h" #include <QtGui> #include <QApplication> #include "qtgui/ecanvas.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); QMainWindow *widget = new QMainWindow; Ui::MainWindow ui; ui.setupUi(widget); widget->setCentralWidget(new ECanvas()); widget->show(); return a.exec(); }
f48d8806f14c1e8493263b2a03fc7d2500825e94
91a882547e393d4c4946a6c2c99186b5f72122dd
/Source/XPSP1/NT/admin/pchealth/sr/tools/logdump/logdump.cpp
dc979a0d647c24295743214653da6e7d09d7e11c
[]
no_license
IAmAnubhavSaini/cryptoAlgorithm-nt5src
94f9b46f101b983954ac6e453d0cf8d02aa76fc7
d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2
refs/heads/master
2023-09-02T10:14:14.795579
2021-11-20T13:47:06
2021-11-20T13:47:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,595
cpp
/*++ Copyright (c) 1998-1999 Microsoft Corporation Module Name: logdump.c Abstract: this file implements functrionality to read and dump the sr logs Author: Kanwaljit Marok (kmarok) 01-May-2000 Revision History: --*/ #include <nt.h> #include <ntrtl.h> #include <nturtl.h> #include <windows.h> #include <stdio.h> #include "logfmt.h" #include "srapi.h" struct _EVENT_STR_MAP { DWORD EventId; PCHAR pEventStr; } EventMap[ 13 ] = { {SrEventInvalid , "INVALID " }, {SrEventStreamChange, "FILE-MODIFY" }, {SrEventAclChange, "ACL-CHANGE " }, {SrEventAttribChange, "ATTR-CHANGE" }, {SrEventStreamOverwrite,"FILE-MODIFY" }, {SrEventFileDelete, "FILE-DELETE" }, {SrEventFileCreate, "FILE-CREATE" }, {SrEventFileRename, "FILE-RENAME" }, {SrEventDirectoryCreate,"DIR-CREATE " }, {SrEventDirectoryRename,"DIR-RENAME " }, {SrEventDirectoryDelete,"DIR-DELETE " }, {SrEventMountCreate, "MNT-CREATE " }, {SrEventMountDelete, "MNT-DELETE " } }; BYTE Buffer[4096]; PCHAR GetEventString( DWORD EventId ) { PCHAR pStr = NULL; static CHAR EventStringBuffer[8]; for( int i=0; i<sizeof(EventMap)/sizeof(_EVENT_STR_MAP);i++) { if ( EventMap[i].EventId == EventId ) { pStr = EventMap[i].pEventStr; } } if (pStr == NULL) { pStr = &EventStringBuffer[0]; wsprintf(pStr, "0x%X", EventId); } return pStr; } BOOLEAN ProcessLogEntry( BOOLEAN bPrintDebug, LPCSTR pszSerNo, LPCSTR pszSize, LPCSTR pszEndSize, LPCSTR pszSeqNo, LPCSTR pszFlags, LPCSTR pszProcess, LPCSTR pszOperation, LPCSTR pszAttr, LPCSTR pszTmpFile, LPCSTR pszPath1, LPCSTR pszPath2, LPCSTR pszAcl, LPCSTR pszShortName, LPCSTR pszProcessHandle, LPCSTR pszThreadHandle) { BOOLEAN Status = TRUE; if( bPrintDebug == FALSE ) { printf( "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t", pszSerNo, pszSize, pszSeqNo, pszOperation, pszAttr, pszAcl, pszPath1, pszShortName); } else { printf( "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t", pszSerNo, pszSize, pszSeqNo, pszOperation, pszAttr, pszProcess, pszProcessHandle, pszThreadHandle, pszAcl, pszPath1, pszShortName); } if(pszTmpFile) { printf( "%s\t", pszTmpFile); } if(pszPath2) { printf( "%s\t", pszPath2); } printf("\n"); return Status; } #define SR_MAX_PATH ((1000) + sizeof (CHAR)) // Name will always be at most 1000 characters plus a NULL. BOOLEAN ReadLogData( BOOLEAN bPrintDebugInfo, LPTSTR pszFileName ) { BOOLEAN Status = FALSE; BOOLEAN bHaveDebugInfo = FALSE; HANDLE hFile; DWORD nRead; DWORD cbSize = 0, dwEntries = 0, dwEntriesAdded = 0; DWORD dwSizeLow , dwSizeHigh; CHAR szSerNo [10]; CHAR szSize [10]; CHAR szEndSize[10]; CHAR szSeqNo [20]; CHAR szOperation[50]; CHAR szAttr[50]; CHAR szFlags[10]; PCHAR szPath1 = NULL; PCHAR szPath2 = NULL; CHAR szTmpFile[MAX_PATH]; CHAR szAcl[MAX_PATH]; CHAR szShortName[MAX_PATH]; CHAR szProcess[32]; CHAR szProcessHandle[16]; CHAR szThreadHandle[16]; BYTE LogHeader[2048]; PSR_LOG_HEADER pLogHeader = (PSR_LOG_HEADER)LogHeader; static INT s_dwEntries = -1; szPath1 = (PCHAR) LocalAlloc( LMEM_FIXED, SR_MAX_PATH ); if (szPath1 == NULL ) { fprintf( stderr, "Insufficient memory\n" ); } szPath2 = (PCHAR) LocalAlloc( LMEM_FIXED, SR_MAX_PATH ); if (szPath2 == NULL ) { fprintf( stderr, "Insufficient memory\n" ); } hFile = CreateFile( pszFileName, GENERIC_READ, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ); if ( hFile != INVALID_HANDLE_VALUE ) { PBYTE pLoc = NULL; dwSizeLow = GetFileSize( hFile, &dwSizeHigh ); // // Read the header size // ReadFile( hFile, &cbSize, sizeof(DWORD), &nRead, NULL ); SetFilePointer( hFile, - (INT)sizeof(DWORD), NULL, FILE_CURRENT ); // // Read the whole header entry // ReadFile( hFile, pLogHeader, cbSize, &nRead, NULL ); pLoc = (PBYTE)(&pLogHeader->SubRecords); fprintf( stderr, "Header Size: %ld, Version: %ld, Tool Version: %ld\n%S\n", pLogHeader->Header.RecordSize, pLogHeader->LogVersion, SR_LOG_VERSION, (LPWSTR)(pLoc + sizeof(RECORD_HEADER)) ); if( pLogHeader->LogVersion != SR_LOG_VERSION || pLogHeader->MagicNum != SR_LOG_MAGIC_NUMBER ) { fprintf( stderr, "Invalid version or Corrupt log\n" ); CloseHandle(hFile); goto End; } dwSizeLow -= pLogHeader->Header.RecordSize; SetFilePointer (hFile, pLogHeader->Header.RecordSize, NULL, FILE_BEGIN); // // Start reading the log entries // while( dwSizeLow ) { PSR_LOG_ENTRY pLogEntry = (PSR_LOG_ENTRY)Buffer; ZeroMemory(pLogEntry, sizeof(Buffer)); // // Read the size of the entry // if ( !ReadFile( hFile, &pLogEntry->Header.RecordSize, sizeof(DWORD), &nRead, NULL ) ) { break; } cbSize = pLogEntry->Header.RecordSize; if (cbSize == 0 ) { // // Zero size indicates end of the log // break; } SetFilePointer( hFile, - (INT)sizeof(DWORD), NULL, FILE_CURRENT ); // // Read the rest of the entry // if ( !ReadFile( hFile, ((PBYTE)pLogEntry), cbSize, &nRead, NULL ) ) { break; } // // Check the magic number // if( pLogEntry->MagicNum != SR_LOG_MAGIC_NUMBER ) { fprintf(stderr, "Invalid Entry ( Magic num )\n"); break; } // // Read the entries in to the buffer // sprintf( szSerNo , "%05d" , dwEntries + 1); sprintf( szSize , "%04d" , pLogEntry->Header.RecordSize ); sprintf( szOperation, "%s" , GetEventString( pLogEntry->EntryType )); sprintf( szFlags , "%08x" , pLogEntry->EntryFlags ); sprintf( szSeqNo , "%010d" , pLogEntry->SequenceNum); sprintf( szAttr , "%08x" , pLogEntry->Attributes ); sprintf( szProcess , "%12.12s" , pLogEntry->ProcName ); // // get the first path // PBYTE pLoc = (PBYTE)&pLogEntry->SubRecords; sprintf( szPath1 , "%S" , pLoc + sizeof(RECORD_HEADER) ); if (pLogEntry->EntryFlags & ENTRYFLAGS_TEMPPATH) { pLoc += RECORD_SIZE(pLoc); sprintf( szTmpFile , "%S" , pLoc + sizeof(RECORD_HEADER) ); } else { sprintf( szTmpFile , "" ); } if (pLogEntry->EntryFlags & ENTRYFLAGS_SECONDPATH) { pLoc += RECORD_SIZE(pLoc); sprintf( szPath2 , "%S" , pLoc + sizeof(RECORD_HEADER) ); } else { sprintf( szPath2 , "" ); } if (pLogEntry->EntryFlags & ENTRYFLAGS_ACLINFO) { ULONG AclInfoSize; pLoc += RECORD_SIZE(pLoc); AclInfoSize = RECORD_SIZE(pLoc); sprintf( szAcl , "ACL(%04d)%" , AclInfoSize ); } else { sprintf( szAcl , "" ); } if (pLogEntry->EntryFlags & ENTRYFLAGS_DEBUGINFO) { bHaveDebugInfo = TRUE; pLoc += RECORD_SIZE(pLoc); sprintf( szProcess , "%12.12s", ((PSR_LOG_DEBUG_INFO)pLoc)->ProcessName ); sprintf( szProcessHandle,"0x%08X", ((PSR_LOG_DEBUG_INFO)pLoc)->ProcessId ); sprintf( szThreadHandle,"0x%08X", ((PSR_LOG_DEBUG_INFO)pLoc)->ThreadId ); } else { bHaveDebugInfo = FALSE; sprintf( szProcess , "" ); sprintf( szThreadHandle , "" ); sprintf( szProcessHandle , "" ); } if (pLogEntry->EntryFlags & ENTRYFLAGS_SHORTNAME) { pLoc += RECORD_SIZE(pLoc); sprintf( szShortName , "%S" , pLoc + sizeof(RECORD_HEADER) ); } else { sprintf( szShortName , "" ); } // // read the trailing record size // sprintf( szEndSize , "%04d", GET_END_SIZE(pLogEntry)); ProcessLogEntry( bPrintDebugInfo && bHaveDebugInfo, szSerNo, szSize, szEndSize, szSeqNo, szFlags, szProcess, szOperation, szAttr, szTmpFile, szPath1, szPath2, szAcl, szShortName, szProcessHandle, szThreadHandle); dwEntries++; dwSizeLow -= cbSize; cbSize = 0; } CloseHandle( hFile ); Status = TRUE; } else { fprintf( stderr, "Error opening LogFile %s\n", pszFileName ); } End: fprintf( stderr, "Number of entries read :%d\n", dwEntries ); if (szPath1 != NULL) LocalFree( szPath1 ); if (szPath2 != NULL) LocalFree( szPath2 ); return Status; } INT __cdecl main( int argc, char *argv[] ) { if( argc < 2 || argc > 3 ) { fprintf( stderr, "USAGE: %s [-d] <LogFile> \n\t -d : debug info\n", argv[0] ); } else { int i = 1; if ( argc == 3 && !strcmp( argv[i], "-d" ) ) { i++; ReadLogData(TRUE, argv[i] ); } else { ReadLogData(FALSE, argv[i] ); } } return 0; }
09f26ee93a849945be0d9e043580fcfea3eccec0
fe91ffa11707887e4cdddde8f386a8c8e724aa58
/chrome/browser/ui/webui/feed_internals/feed_internals_page_handler.cc
e8b0ad925e7c107dd5b05b7c311473f3a207be7e
[ "BSD-3-Clause" ]
permissive
akshaymarch7/chromium
78baac2b45526031846ccbaeca96c639d1d60ace
d273c844a313b1e527dec0d59ce70c95fd2bd458
refs/heads/master
2023-02-26T23:48:03.686055
2020-04-15T01:20:07
2020-04-15T01:20:07
255,778,651
2
1
BSD-3-Clause
2020-04-15T02:04:56
2020-04-15T02:04:55
null
UTF-8
C++
false
false
6,703
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/browser/ui/webui/feed_internals/feed_internals_page_handler.h" #include <string> #include <utility> #include "base/feature_list.h" #include "base/metrics/statistics_recorder.h" #include "base/time/time.h" #include "chrome/browser/android/feed/feed_debugging_bridge.h" #include "chrome/browser/android/feed/feed_lifecycle_bridge.h" #include "chrome/browser/ui/webui/feed_internals/feed_internals.mojom.h" #include "components/feed/content/feed_host_service.h" #include "components/feed/content/feed_offline_host.h" #include "components/feed/core/common/pref_names.h" #include "components/feed/core/common/user_classifier.h" #include "components/feed/core/feed_scheduler_host.h" #include "components/feed/core/shared_prefs/pref_names.h" #include "components/feed/feed_feature_list.h" #include "components/offline_pages/core/prefetch/prefetch_prefs.h" #include "components/offline_pages/core/prefetch/suggestions_provider.h" #include "components/prefs/pref_service.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/receiver.h" namespace { const char kFeedHistogramPrefix[] = "ContentSuggestions.Feed."; feed_internals::mojom::TimePtr ToMojoTime(base::Time time) { return time.is_null() ? nullptr : feed_internals::mojom::Time::New(time.ToJsTime()); } std::string TriggerTypeToString(feed::TriggerType* trigger) { if (trigger == nullptr) return "Not set"; switch (*trigger) { case feed::TriggerType::kNtpShown: return "NTP Shown"; case feed::TriggerType::kForegrounded: return "Foregrounded"; case feed::TriggerType::kFixedTimer: return "Fixed Timer"; } } } // namespace FeedInternalsPageHandler::FeedInternalsPageHandler( mojo::PendingReceiver<feed_internals::mojom::PageHandler> receiver, feed::FeedHostService* feed_host_service, PrefService* pref_service) : receiver_(this, std::move(receiver)), feed_scheduler_host_(feed_host_service->GetSchedulerHost()), feed_offline_host_(feed_host_service->GetOfflineHost()), pref_service_(pref_service) {} FeedInternalsPageHandler::~FeedInternalsPageHandler() = default; void FeedInternalsPageHandler::GetGeneralProperties( GetGeneralPropertiesCallback callback) { auto properties = feed_internals::mojom::Properties::New(); properties->is_feed_enabled = base::FeatureList::IsEnabled(feed::kInterestFeedContentSuggestions); properties->is_feed_visible = pref_service_->GetBoolean(feed::prefs::kArticlesListVisible); properties->is_feed_allowed = IsFeedAllowed(); properties->is_prefetching_enabled = offline_pages::prefetch_prefs::IsEnabled(pref_service_); properties->feed_fetch_url = feed::GetFeedFetchUrlForDebugging(); std::move(callback).Run(std::move(properties)); } void FeedInternalsPageHandler::GetUserClassifierProperties( GetUserClassifierPropertiesCallback callback) { auto properties = feed_internals::mojom::UserClassifier::New(); feed::UserClassifier* user_classifier = feed_scheduler_host_->GetUserClassifierForDebugging(); properties->user_class_description = user_classifier->GetUserClassDescriptionForDebugging(); properties->avg_hours_between_views = user_classifier->GetEstimatedAvgTime( feed::UserClassifier::Event::kSuggestionsViewed); properties->avg_hours_between_uses = user_classifier->GetEstimatedAvgTime( feed::UserClassifier::Event::kSuggestionsUsed); std::move(callback).Run(std::move(properties)); } void FeedInternalsPageHandler::GetLastFetchProperties( GetLastFetchPropertiesCallback callback) { auto properties = feed_internals::mojom::LastFetchProperties::New(); properties->last_fetch_status = feed_scheduler_host_->GetLastFetchStatusForDebugging(); properties->last_fetch_trigger = TriggerTypeToString( feed_scheduler_host_->GetLastFetchTriggerTypeForDebugging()); properties->last_fetch_time = ToMojoTime(pref_service_->GetTime(feed::prefs::kLastFetchAttemptTime)); properties->refresh_suppress_time = ToMojoTime(feed_scheduler_host_->GetSuppressRefreshesUntilForDebugging()); properties->last_bless_nonce = pref_service_->GetString(feed::prefs::kHostOverrideBlessNonce); std::move(callback).Run(std::move(properties)); } void FeedInternalsPageHandler::ClearUserClassifierProperties() { feed_scheduler_host_->GetUserClassifierForDebugging() ->ClearClassificationForDebugging(); } void FeedInternalsPageHandler::ClearCachedDataAndRefreshFeed() { feed::FeedLifecycleBridge::ClearCachedData(); } void FeedInternalsPageHandler::RefreshFeed() { feed::TriggerRefreshForDebugging(); } void FeedInternalsPageHandler::GetCurrentContent( GetCurrentContentCallback callback) { if (!IsFeedAllowed()) { std::move(callback).Run( std::vector<feed_internals::mojom::SuggestionPtr>()); return; } feed_offline_host_->GetCurrentArticleSuggestions(base::BindOnce( &FeedInternalsPageHandler::OnGetCurrentArticleSuggestionsDone, weak_ptr_factory_.GetWeakPtr(), std::move(callback))); } void FeedInternalsPageHandler::OnGetCurrentArticleSuggestionsDone( GetCurrentContentCallback callback, std::vector<offline_pages::PrefetchSuggestion> results) { std::vector<feed_internals::mojom::SuggestionPtr> suggestions; for (offline_pages::PrefetchSuggestion result : results) { auto suggestion = feed_internals::mojom::Suggestion::New(); suggestion->title = std::move(result.article_title); suggestion->url = std::move(result.article_url); suggestion->publisher_name = std::move(result.article_attribution); suggestion->image_url = std::move(result.thumbnail_url); suggestion->favicon_url = std::move(result.favicon_url); suggestions.push_back(std::move(suggestion)); } std::move(callback).Run(std::move(suggestions)); } void FeedInternalsPageHandler::GetFeedProcessScopeDump( GetFeedProcessScopeDumpCallback callback) { std::move(callback).Run(feed::GetFeedProcessScopeDumpForDebugging()); } bool FeedInternalsPageHandler::IsFeedAllowed() { return pref_service_->GetBoolean(feed::prefs::kEnableSnippets); } void FeedInternalsPageHandler::GetFeedHistograms( GetFeedHistogramsCallback callback) { std::string log; base::StatisticsRecorder::WriteGraph(kFeedHistogramPrefix, &log); std::move(callback).Run(log); } void FeedInternalsPageHandler::OverrideFeedHost(const std::string& host) { return pref_service_->SetString(feed::prefs::kHostOverrideHost, host); }
ceea2d0ca8ebb5f1043e95d940890890c3d89782
7a3ba9759b81b486d3f701a635f73a697a6f44b8
/sourceCompiler/cores/arduino/Briko/Temperature.h
5f6c30982cec9977c6fe7681ac20be51c3220940
[]
no_license
adrianloma/briko
7cfd49273badf3268a16e87391d6f254393f3bd2
7b9df74d8505ad9c107e1ba2d8aae99ad29444ec
refs/heads/master
2021-01-16T20:30:28.246371
2015-08-09T17:55:43
2015-08-09T17:55:43
40,435,688
0
0
null
2015-08-09T12:32:09
2015-08-09T12:32:08
null
UTF-8
C++
false
false
932
h
/* * * Temperature.h * * Copyright 2014 IPSUM <[email protected]> * * This library is free software; you can redistribute it and/or * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * 14/08/14 Mexico. * */ #ifndef Temperature //if not defined #define Temperature //defines header name #define TEMP_SAMPLES 5 //number of samples to average #define C 0 #define F 1 #include "Arduino.h" //includes Arduino.h library class temperaturebk { public: temperaturebk(uint8_t pin); //initialize constructor int read(); //read analog input function int read(byte unit); private: uint8_t _pin; //declares a variable }; #endif //end define
b2c0c0ec2f2bc32fc4320b2af0c469018cca2cfd
15f6b119c19db8471210fc99650a1974c27fbc4c
/A/1176A.cpp
7fc31d65e8b719dc605998e8b084c91ecb34c5b6
[]
no_license
AsifWatson/codeforces
8d1afd7f56fe84836e770d2de68f9caad596480b
ee38a5e8c19a54588fecf4f26986975e258e3b6b
refs/heads/master
2021-07-12T23:33:54.021007
2021-02-28T14:06:09
2021-02-28T14:06:09
234,949,673
1
0
null
null
null
null
UTF-8
C++
false
false
928
cpp
#include "bits/stdc++.h" #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define all(v) v.begin(),v.end() #define allre(v) v.rbegin(),v.rend() #define sp(x,y) fixed<<setprecision(y)<<x #define max3(a,b,c) max(a,max(b,c)) #define min3(a,b,c) min(a,min(b,c)) #define GCD(a,b) __gcd(a,b) #define LCM(a,b) ((a*b)/__gcd(a,b)) using namespace std; const double pi = acos(-1.0); const double EPS = 1e-6; const int MOD = (int)1e9+7; bool Reverse(long long a,long long b){return a>b;} int main() { IOS long long q,n,ans; cin>>q; while(q--) { cin>>n; ans=0; while(true) { if(n==1)break; if(n%2==0){n/=2;ans++;} else { if(n%3==0){n/=3;n*=2;ans++;} else if(n%5==0){n/=5;n*=4;ans++;} else {ans=-1;break;} } } cout<<ans<<endl; } return 0; }
6d580017737fb63134410a05b3a52c8ef8855827
8260762b35ea04ab54eac2043007bb1dd1a4be12
/Streams/OStream.h
3ecd2a60d3411df7aa551df517752a19662be888
[]
no_license
analyst1001/SSHHandshakeFuzzer
6253c447496daf8442ce4da6756c368e44e1e068
16d14605369a2589cc67bea6d55507ff9e055395
refs/heads/master
2020-03-13T18:40:23.962497
2018-05-03T23:18:02
2018-05-03T23:18:02
131,239,961
1
1
null
null
null
null
UTF-8
C++
false
false
205
h
#include "Stream.h" #include "../MessageBuffers/MessageBuffer.h" #ifndef OSTREAM_H #define OSTREAM_H class OStream : public Stream { public: virtual void write(MessageBuffer *) = 0; }; #endif
2025f61152e3a8c0021cd985ef0b715f2f4c1fc3
bd0bf2438dbe8a16cb79a045ed73f28361af0504
/GAME_SECOND/bulletPhysics/src/BulletCollision/CollisionShapes/btCollisionShape.cpp
b33bc445700ef5e4c6db72483b348e61abc09924
[ "Zlib" ]
permissive
RyujiNanjyou/rnGame
bc3d2429457803e3b0cbeba0e4e7bc43b28977df
fb22a4a4cdee14956a73e0d0d1b2e51b1bdb9637
refs/heads/master
2021-01-22T03:23:35.219980
2017-07-13T02:45:07
2017-07-13T02:45:07
92,374,788
0
0
null
null
null
null
UTF-8
C++
false
false
4,290
cpp
/* Bullet Continuous Collision Detection and Physics Library Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "BulletCollision/CollisionShapes/btCollisionShape.h" #include "LinearMath/btSerializer.h" /* Make sure this dummy function never changes so that it can be used by probes that are checking whether the library is actually installed. */ extern "C" { void btBulletCollisionProbe (); void btBulletCollisionProbe () {} } void btCollisionShape::getBoundingSphere(btVector3& center,btScalar& radius) const { btTransform tr; tr.setIdentity(); btVector3 aabbMin,aabbMax; getAabb(tr,aabbMin,aabbMax); radius = (aabbMax-aabbMin).length()*btScalar(0.5); center = (aabbMin+aabbMax)*btScalar(0.5); } btScalar btCollisionShape::getContactBreakingThreshold(btScalar defaultContactThreshold) const { return getAngularMotionDisc() * defaultContactThreshold; } btScalar btCollisionShape::getAngularMotionDisc() const { ///@todo cache this value, to improve performance btVector3 center; btScalar disc; getBoundingSphere(center,disc); disc += (center).length(); return disc; } void btCollisionShape::calculateTemporalAabb(const btTransform& curTrans,const btVector3& linvel,const btVector3& angvel,btScalar timeStep, btVector3& temporalAabbMin,btVector3& temporalAabbMax) const { //start with static aabb getAabb(curTrans,temporalAabbMin,temporalAabbMax); btScalar temporalAabbMaxx = temporalAabbMax.getX(); btScalar temporalAabbMaxy = temporalAabbMax.getY(); btScalar temporalAabbMaxz = temporalAabbMax.getZ(); btScalar temporalAabbMinx = temporalAabbMin.getX(); btScalar temporalAabbMiny = temporalAabbMin.getY(); btScalar temporalAabbMinz = temporalAabbMin.getZ(); // add linear motion btVector3 linMotion = linvel*timeStep; ///@todo: simd would have a vector max/min operation, instead of per-element access if (linMotion.x() > btScalar(0.)) temporalAabbMaxx += linMotion.x(); else temporalAabbMinx += linMotion.x(); if (linMotion.y() > btScalar(0.)) temporalAabbMaxy += linMotion.y(); else temporalAabbMiny += linMotion.y(); if (linMotion.z() > btScalar(0.)) temporalAabbMaxz += linMotion.z(); else temporalAabbMinz += linMotion.z(); //add conservative angular motion btScalar angularMotion = angvel.length() * getAngularMotionDisc() * timeStep; btVector3 angularMotion3d(angularMotion,angularMotion,angularMotion); temporalAabbMin = btVector3(temporalAabbMinx,temporalAabbMiny,temporalAabbMinz); temporalAabbMax = btVector3(temporalAabbMaxx,temporalAabbMaxy,temporalAabbMaxz); temporalAabbMin -= angularMotion3d; temporalAabbMax += angularMotion3d; } ///fills the dataBuffer and returns the struct name (and 0 on failure) const char* btCollisionShape::serialize(void* dataBuffer, btSerializer* serializer) const { btCollisionShapeData* shapeData = (btCollisionShapeData*) dataBuffer; char* name = (char*) serializer->findNameForPointer(this); shapeData->m_name = (char*)serializer->getorimaquePointer(name); if (shapeData->m_name) { serializer->serializeName(name); } shapeData->m_shapeType = m_shapeType; //shapeData->m_padding//?? return "btCollisionShapeData"; } void btCollisionShape::serializeSingleShape(btSerializer* serializer) const { int len = calculateSerializeBufferSize(); btChunk* chunk = serializer->allocate(len,1); const char* structType = serialize(chunk->m_oldPtr, serializer); serializer->finalizeChunk(chunk,structType,BT_SHAPE_CODE,(void*)this); }