blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
10ab3d0940b921cfa94fd7370196b8d4f0709c4b
9dae820bb66d277a291a8b36997823aee02adae5
/Source/PhysBCFunctMaestro.H
12531b803b17393a63ebf57d82ccd942bf6c1c56
[ "BSD-3-Clause" ]
permissive
AMReX-Astro/MAESTROeX
1264e4d5e7a193b7c1d2a6ad027381c2d8a8cad9
a391e674d46d9af5a71732283ef005df81fb5df4
refs/heads/main
2023-07-06T21:30:28.724631
2023-07-04T21:44:07
2023-07-04T21:44:07
104,002,862
44
36
BSD-3-Clause
2023-09-14T21:36:46
2017-09-18T23:39:12
C++
UTF-8
C++
false
false
1,921
h
PhysBCFunctMaestro.H
#ifndef PhysBCFunctMaestro_H_ #define PhysBCFunctMaestro_H_ #include <AMReX_PhysBCFunct.H> extern "C" { typedef void (*BndryFuncDefaultMaestro)( const amrex::Array4<amrex::Real>& scal, const amrex::Box& bx, const amrex::Box& domainBox, const amrex::Real* dx, const amrex::BCRec bcs, const amrex::Real* gridlo, const int comp); } /// This version calls function working on array class BndryFuncArrayMaestro : public amrex::BndryFuncArray { public: BndryFuncArrayMaestro() noexcept {} BndryFuncArrayMaestro(BndryFuncDefaultMaestro inFunc) noexcept : m_func(inFunc) {} void operator()(amrex::Box const& bx, amrex::FArrayBox& dest, const int dcomp, const int numcomp, amrex::Geometry const& geom, [[maybe_unused]] const amrex::Real time, const amrex::Vector<amrex::BCRec>& bcr, const int bcomp, // BCRec for this box [[maybe_unused]] const int orig_comp) { BL_ASSERT(m_func != nullptr); const int* lo = dest.loVect(); const amrex::Box& domain = geom.Domain(); const int* dom_lo = domain.loVect(); const amrex::Real* dx = geom.CellSize(); amrex::Real grd_lo[AMREX_SPACEDIM]; const amrex::Real* problo = geom.ProbLo(); for (int i = 0; i < AMREX_SPACEDIM; i++) { grd_lo[i] = problo[i] + dx[i] * (lo[i] - dom_lo[i]); } static_assert(sizeof(amrex::BCRec) == 2 * AMREX_SPACEDIM * sizeof(int), "Let us know if this assertion fails"); for (int icomp = 0; icomp < numcomp; ++icomp) { m_func(dest.array(dcomp + icomp), bx, domain, dx, bcr[bcomp + icomp], grd_lo, dcomp + icomp); } } protected: BndryFuncDefaultMaestro m_func = nullptr; }; using PhysBCFunctMaestro = amrex::PhysBCFunct<BndryFuncArrayMaestro>; #endif
158f72aaf93481c236d00b5b3a2348e10ff7844d
1b3ee9bf0741aca2745dd6720de1b5ec2c737055
/Queue_c.cpp
8efa5bdca59a230556e0ef49d737700f2603c1ce
[]
no_license
kimehwa/untitled2
ee80ab3671a57508ba470882eb49a59322c9d0be
bbecd2712e67358f586df0eaff7488ad8d3fa7d6
refs/heads/master
2020-06-26T06:51:24.423083
2019-07-30T03:03:11
2019-07-30T03:03:11
199,563,892
0
0
null
null
null
null
UTF-8
C++
false
false
1,047
cpp
Queue_c.cpp
// // Created by 管晓东 on 2019-07-29. // #include "Queue_c.h" #include <iostream> #include <vector> using namespace std; class MyCircularQueue { private: vector<int> data; int head; int tail; int size; public: MyCircularQueue(int k) {//初始化链表 data.resize(k); head = -1; tail = -1; size = k; } bool enQueue(int value) { if (isFull()) { return false; } if (isEmpty()) { head = 0; } tail = (tail + 1) % size;//这样完成了一个循环队列的结构了撒 data[tail] = value; return true; } bool deQueue() { if (isEmpty()) { return false; } if (head == tail) { head = -1; tail = -1; return true; } head = (head + 1) % size; return true; } bool isEmpty() { return head == -1; } bool isFull() { return ((tail + 1) % size) == head; } }; int main(){ }
11fe927ebc682ada83f25a19ad01dae70d2b719e
a062d5ed6ab62b1b5c352646d42637021bb2b3fc
/src/arealight.cpp
e84848230a688397d2f5b93492e7699e24a41ce5
[]
no_license
blizmax/nori-cs187
225841efc191018f648feaa43139e58b1daf0fd4
8367fd120b06c39637638367b1364b6fa538c402
refs/heads/master
2021-08-08T16:15:56.994452
2017-11-03T19:51:49
2017-11-03T19:51:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,352
cpp
arealight.cpp
/* This file is part of Nori, a simple educational ray tracer Copyright (c) 2015 by Romain Prévost Nori is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License Version 3 as published by the Free Software Foundation. Nori is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <nori/emitter.h> #include <nori/warp.h> #include <nori/mesh.h> NORI_NAMESPACE_BEGIN class AreaEmitter : public Emitter { public: AreaEmitter(const PropertyList &props) { m_type = EmitterType::EMITTER_AREA; m_radiance = props.getColor("radiance"); } virtual std::string toString() const { return tfm::format( "AreaLight[\n" " radiance = %s,\n" "]", m_radiance.toString()); } // We don't assume anything about the visibility of points specified in 'ref' and 'p' in the EmitterQueryRecord. virtual Color3f eval(const EmitterQueryRecord & lRec) const { if(!m_mesh) throw NoriException("There is no shape attached to this Area light!"); // This function call can be done by bsdf sampling routines. // Hence the ray was already traced for us - i.e a visibility test was already performed. // Hence just check if the associated normal in emitter query record and incoming direction are not backfacing if (lRec.n.dot(lRec.wi) < 0.0f) return m_radiance; else return 0.0f; } virtual Color3f sample(EmitterQueryRecord & lRec, const Point2f & sample, float optional_u) const { if(!m_mesh) throw NoriException("There is no shape attached to this Area light!"); // Sample the underlying mesh for a position and normal. m_mesh->samplePosition(sample, lRec.p, lRec.n, optional_u); // Construct the EmitterQueryRecord structure. lRec.wi = (lRec.p - lRec.ref).normalized(); lRec.emitter = this; lRec.dist = (lRec.p - lRec.ref).norm(); lRec.pdf = pdf(lRec); // Return the appropriately weighted radiance term back // NOTE: We are not checking visibility here. It's the integrator's responsibility to check for the shadow ray test. if(lRec.pdf != 0.0f || fabsf(lRec.pdf) != INFINITY) return eval(lRec) / lRec.pdf; else return 0.0f; } // Returns probability with respect to solid angle given by all the information inside the emitterqueryrecord. // Assumes all information about the intersection point is already provided inside. // WARNING: Use with care. Malformed EmitterQueryRecords can result in undefined behavior. Plus no visibility is considered. virtual float pdf(const EmitterQueryRecord &lRec) const { if(!m_mesh) throw NoriException("There is no shape attached to this Area light!"); Vector3f inv_wi = -lRec.wi; float costheta_here = fabsf(lRec.n.dot(inv_wi)); float pW = m_mesh->pdf() * lRec.dist * lRec.dist / costheta_here; if (isnan(pW) || fabsf(pW) == INFINITY) return 0.0f; return pW; } virtual Color3f samplePhoton(Ray3f &ray, const Point2f &sample1, const Point2f &sample2, float another_rand_u) const { if (!m_mesh) throw NoriException("There is no shape attached to this area light"); // global pdf float _pdf = 0.0f; // Sample a point to emit from the mesh EmitterQueryRecord eRec; m_mesh->samplePosition(sample1, eRec.p, eRec.n, another_rand_u); // Sample a direction Vector3f wi = Warp::squareToCosineHemisphere(sample2); Frame my_frame(eRec.n); Vector3f xfm_wi = my_frame.toWorld(wi); _pdf = (1.0f / m_mesh->pdf()) * (Warp::squareToCosineHemispherePdf(wi)); // Get the ray out. ray = Ray3f(eRec.p, xfm_wi, Epsilon, INFINITY); // Return power return M_PI * m_mesh->totalSurfaceArea() * m_radiance; } // Get the parent mesh void setParent(NoriObject *parent) { auto type = parent->getClassType(); if (type == EMesh) m_mesh = static_cast<Mesh*>(parent); } protected: Color3f m_radiance; }; NORI_REGISTER_CLASS(AreaEmitter, "area") NORI_NAMESPACE_END
23b97fbb9e19db6097683bbdc6c91d8b41a3097a
aedec0779dca9bf78daeeb7b30b0fe02dee139dc
/Modules/PointSet/src/Stripper.cc
70d29ad0e4f206a7eb1bba8127094af24390ffa1
[ "LicenseRef-scancode-proprietary-license", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
BioMedIA/MIRTK
ca92f52b60f7db98c16940cd427a898a461f856c
973ce2fe3f9508dec68892dbf97cca39067aa3d6
refs/heads/master
2022-08-08T01:05:11.841458
2022-07-28T00:03:25
2022-07-28T10:18:00
48,962,880
171
78
Apache-2.0
2022-07-28T10:18:01
2016-01-03T22:25:55
C++
UTF-8
C++
false
false
5,194
cc
Stripper.cc
/* * Medical Image Registration ToolKit (MIRTK) * * Copyright 2016 Imperial College London * Copyright 2016 Andreas Schuh * * 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 "mirtk/Stripper.h" #include "mirtk/List.h" #include "mirtk/Vtk.h" #include "vtkStripper.h" #include "vtkCellArray.h" namespace mirtk { // ============================================================================= // Auxiliares // ============================================================================= namespace { // ----------------------------------------------------------------------------- void GrowLine(vtkPolyData *output, List<vtkIdType> &line) { vtkIdType cellId; vtkNew<vtkIdList> cellIds, ptIds; while (true) { cellId = -1; output->GetPointCells(line.back(), cellIds.GetPointer()); for (vtkIdType i = 0; i < cellIds->GetNumberOfIds(); ++i) { if (output->GetCellType(cellIds->GetId(i)) == VTK_LINE) { if (cellId == -1) { cellId = cellIds->GetId(i); } else { cellId = -1; break; } } } if (cellId == -1) break; GetCellPoints(output, cellId, ptIds.GetPointer()); output->RemoveCellReference(cellId); output->DeleteCell(cellId); if (ptIds->GetNumberOfIds() == 0) break; if (ptIds->GetId(0) == line.back()) { for (vtkIdType i = 1; i < ptIds->GetNumberOfIds(); ++i) { line.push_back(ptIds->GetId(i)); } } else if (ptIds->GetId(ptIds->GetNumberOfIds() - 1) == line.back()) { for (vtkIdType i = ptIds->GetNumberOfIds() - 2; i >= 0; --i) { line.push_back(ptIds->GetId(i)); } } else { break; } } } } // namespace // ============================================================================= // Construction/destruction // ============================================================================= // ----------------------------------------------------------------------------- void Stripper::CopyAttributes(const Stripper &other) { _StripLines = other._StripLines; _StripTriangles = other._StripTriangles; } // ----------------------------------------------------------------------------- Stripper::Stripper() : _StripLines(true), _StripTriangles(true) { } // ----------------------------------------------------------------------------- Stripper::Stripper(const Stripper &other) : MeshFilter(other) { CopyAttributes(other); } // ----------------------------------------------------------------------------- Stripper &Stripper::operator =(const Stripper &other) { if (this != &other) { MeshFilter::operator =(other); CopyAttributes(other); } return *this; } // ----------------------------------------------------------------------------- Stripper::~Stripper() { } // ============================================================================= // Execution // ============================================================================= // ----------------------------------------------------------------------------- void Stripper::Execute() { // Strip lines if (_StripLines && _Output->GetNumberOfLines() > 0) { List<List<vtkIdType>> lines; vtkNew<vtkIdList> ptIds; // Pick each line segment as possible seed for contiguous line for (vtkIdType seedId = 0; seedId < _Output->GetNumberOfCells(); ++seedId) { // Skip non-line cells and those that are already marked as deleted if (_Output->GetCellType(seedId) != VTK_LINE) continue; // Start new line in reverse order List<vtkIdType> line; GetCellPoints(_Output, seedId, ptIds.GetPointer()); for (vtkIdType i = 0; i < ptIds->GetNumberOfIds(); ++i) { line.push_front(ptIds->GetId(i)); } _Output->RemoveCellReference(seedId); _Output->DeleteCell(seedId); // Append line at the front GrowLine(_Output, line); // Reverse line line.reverse(); // Append line at the back GrowLine(_Output, line); // Add to list of joined lines lines.push_back(move(line)); } // Remove lines which are being joined _Output->RemoveDeletedCells(); // Add new joined line (**after** RemoveDeletedCells) vtkCellArray * const arr = _Output->GetLines(); for (const auto &line : lines) { arr->InsertNextCell(static_cast<int>(line.size())); for (const auto &ptId : line) { arr->InsertCellPoint(ptId); } } } // Strip triangles if (_StripTriangles && _Output->GetNumberOfPolys() > 0) { vtkNew<vtkStripper> stripper; stripper->SetInputData(_Output); stripper->Update(); _Output = stripper->GetOutput(); } } } // namespace mirtk
2001a02250c941be664918df942d740044b57939
fa4fa0e01ac89211fe69d0447c68779da1eaaf6a
/HW/HW5a_BasketballHashing-main/mapcheck.cpp
87014f05f95beab554c9ee3c1ad85180eccfc8d6
[ "Apache-2.0" ]
permissive
hwilt/CS174
92a1bdc78c7d2ce4b882237d689efaea95f177b0
4fea28a294ec4d32ef8509937242c382facdbfd6
refs/heads/main
2023-02-13T03:47:10.048222
2021-01-05T02:25:18
2021-01-05T02:25:18
312,004,537
0
0
null
null
null
null
UTF-8
C++
false
false
2,006
cpp
mapcheck.cpp
#include <stdio.h> #include <string> #include <iostream> #include <fstream> #include "hashable.h" #include "cloneable.h" #include "hashtable.h" #include "linkedmap.h" #include "player.h" void compareMaps() { // TODO: Fill this in // 1. Create a map m1 of type LinkedMap and a map m2 of type HashMap // and fill them with the players. // 2. Reset the operation counts of each map // 3. Loop through all of the keys in m1 and make sure they're in m2 // by calling the containsKey() method. If they're not, print out // the ones that are missing to help you debug // 4. Loop through all of the keys in m2 and make sure they're in m1 // by calling the containsKey() method. If they're not, print out // the ones that are missing to help you debug // 5. Report the number of operations in steps 3 and 4, and the average // number of operations per player //Step 1 Map* m1 = new LinkedMap(); Map* m2 = new HashTable(100); loadPlayers(m1); loadPlayers(m2); //Step 2 m1->resetOps(); m2->resetOps(); //Step 3 size_t N; Hashable** LinkedKeyList = m1->getKeyList(&N); for(int i = 0; i < N; i++){ Hashable* linkedKey = LinkedKeyList[i]; if(linkedKey != NULL && !m2->containsKey(linkedKey)){ cout << linkedKey << ": Does not Exist" << endl; } } //Step 4 Hashable** HashKeyList = m2->getKeyList(&N); for(int i = 0; i < N; i++){ Hashable* hashKey = HashKeyList[i]; if(hashKey != NULL && !m1->containsKey(hashKey)){ cout << hashKey << ": Does not Exist" << endl; } } //Step 5 printf("%zu number of Players\n", N); printf("Number of Operations in hash table: %zu\nAverage %zu per player\n", m2->numOps, m2->numOps/N); printf("Number of Operations in linked map: %zu\nAverage %zu per player", m1->numOps, m1->numOps/N); delete m1; delete m2; } int main() { compareMaps(); return 0; }
7b50994d64f904bcd90f6ce266d6c9c7edb04c03
51006c4a675ab1ea4cb322feba13ffa8328a79d2
/src/OtherAbsorptionOutOfTargetReweighter.cpp
6a37f6f21a1f87d92a1926623b2c13348c29ade8
[]
no_license
ryounsumiko/ppfx
7451a1d43edf188075c5755817dd6c880e446364
1da13690a39a04ee180612c445bb5e627b86f52d
refs/heads/master
2023-01-19T20:22:59.782252
2020-05-21T18:27:41
2020-05-21T18:27:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,520
cpp
OtherAbsorptionOutOfTargetReweighter.cpp
#include "OtherAbsorptionOutOfTargetReweighter.h" #include "CentralValuesAndUncertainties.h" #include <cstdlib> #include <iostream> namespace NeutrinoFluxReweight{ OtherAbsorptionOutOfTargetReweighter::OtherAbsorptionOutOfTargetReweighter(int iuniv, const ParameterTable& cv_pars, const ParameterTable& univ_pars):cvPars(cv_pars),univPars(univ_pars),iUniv(iuniv){ // const boost::interprocess::flat_map<std::string, double>& dsig_table = univPars.getMap(); inel_kapAl_xsec_lowP = univPars.getParameterValue("inel_kapAl_xsec_lowP"); inel_kapAl_xsec_highP = univPars.getParameterValue("inel_kapAl_xsec_highP"); } OtherAbsorptionOutOfTargetReweighter::~OtherAbsorptionOutOfTargetReweighter(){ } std::vector<bool> OtherAbsorptionOutOfTargetReweighter::canReweight(const InteractionChainData& aa){ std::vector<bool> this_nodes; //int index_vol = 0; double low_val = 1.E-20; std::vector<ParticlesThroughVolumesData> vec_ptv = aa.ptv_info; bool passVOL = false; //Cheking at least one ancestor with amount of materail value: for(int index_vol=0;index_vol<3;index_vol++){ for(int ii=0;ii<3;ii++){ passVOL = passVOL || (vec_ptv[index_vol].AmountMat[ii] >low_val && (abs(vec_ptv[index_vol].Pdgs[ii])!=211 && abs(vec_ptv[index_vol].Pdgs[ii])!=321 && vec_ptv[index_vol].Pdgs[ii]!=2212 && vec_ptv[index_vol].Pdgs[ii]!=2112 && abs(vec_ptv[index_vol].Pdgs[ii])>99)); } } this_nodes.push_back(passVOL); return this_nodes; } double OtherAbsorptionOutOfTargetReweighter::calculateWeight(const InteractionChainData& aa){ std::vector<ParticlesThroughVolumesData> vec_ptv = aa.ptv_info; double shift_lowP = inel_kapAl_xsec_lowP; double shift_highP = inel_kapAl_xsec_highP; double NA_mb = 6.02E-4; double wgt = 1.0; double tot_dist = 0.0; double low_val = 1.E-20; for(int index_vol=0;index_vol<3;index_vol++){ for(int ii=0;ii<3;ii++){ tot_dist = vec_ptv[index_vol].AmountMat[ii]; if(tot_dist<low_val)continue; if(abs(vec_ptv[index_vol].Pdgs[ii])==321 || abs(vec_ptv[index_vol].Pdgs[ii])==211 || vec_ptv[index_vol].Pdgs[ii]==2212 || vec_ptv[index_vol].Pdgs[ii]==2112 || abs(vec_ptv[index_vol].Pdgs[ii])<100)continue; tot_dist *= NA_mb; if(vec_ptv[index_vol].Moms[ii]<2.0){ tot_dist *= shift_lowP; } else if(vec_ptv[index_vol].Moms[ii]>=2.0){ tot_dist *= shift_highP; } wgt *= exp(-1.0*tot_dist); } } return wgt; } }
f43d94abf659f5d7f5e48584105ac0604c1fa6d0
433918960a7a3c6b09d9b29a63ed1e8fb5de1050
/src/pscs/src_gen/PSCS/Semantics/Loci/impl/LociPackageImpl.hpp
f82185addfec52d4c118cb20c920ba975ce972a1
[ "EPL-1.0", "MIT" ]
permissive
MDE4CPP/MDE4CPP
476709da6c9f0d92504c1539ee4b1012786e3254
24e8ef69956d2a3c6b04dca3a61a97223f6aa959
refs/heads/master
2023-08-31T03:15:56.104582
2023-01-05T14:45:37
2023-01-05T14:45:37
82,116,322
14
27
MIT
2023-06-23T09:23:01
2017-02-15T23:11:29
C++
UTF-8
C++
false
false
4,134
hpp
LociPackageImpl.hpp
//******************************************************************** //* //* Warning: This file was generated by ecore4CPP Generator //* //******************************************************************** #ifndef PSCS_SEMANTICS_LOCIPACKAGEIMPL_HPP #define PSCS_SEMANTICS_LOCIPACKAGEIMPL_HPP // namespace macro header include #include "PSCS/PSCS.hpp" #include "ecore/ecorePackage.hpp" #include "ecore/impl/EPackageImpl.hpp" #include "PSCS/Semantics/Loci/LociPackage.hpp" namespace PSCS::Semantics::Loci { class CS_ExecutionFactory; class CS_Executor; class CS_Locus;} namespace ecore { class ecoreFactory; } namespace PSCS::Semantics::Loci { class PSCS_API LociPackageImpl : public ecore::EPackageImpl ,virtual public LociPackage { private: LociPackageImpl(LociPackageImpl const&) = delete; LociPackageImpl& operator=(LociPackageImpl const&) = delete; protected: LociPackageImpl(); public: virtual ~LociPackageImpl(); // Begin Class CS_ExecutionFactory //Class and Feature Getter virtual std::shared_ptr<ecore::EClass> getCS_ExecutionFactory_Class() const ; virtual std::shared_ptr<ecore::EReference> getCS_ExecutionFactory_Attribute_appliedProfiles() const ; virtual std::shared_ptr<ecore::EOperation> getCS_ExecutionFactory_Operation_getStereotypeApplication_Class_Element() const ; virtual std::shared_ptr<ecore::EOperation> getCS_ExecutionFactory_Operation_getStereotypeClass_EString_EString() const ; virtual std::shared_ptr<ecore::EOperation> getCS_ExecutionFactory_Operation_instantiateVisitor_Element() const ; // End Class CS_ExecutionFactory // Begin Class CS_Executor //Class and Feature Getter virtual std::shared_ptr<ecore::EClass> getCS_Executor_Class() const ; virtual std::shared_ptr<ecore::EOperation> getCS_Executor_Operation_start_Class_ParameterValue() const ; // End Class CS_Executor // Begin Class CS_Locus //Class and Feature Getter virtual std::shared_ptr<ecore::EClass> getCS_Locus_Class() const ; virtual std::shared_ptr<ecore::EOperation> getCS_Locus_Operation_instantiate_Class() const ; // End Class CS_Locus // SubPackages Getters private: std::shared_ptr<ecore::EClass> m_cS_ExecutionFactory_Class = nullptr;std::shared_ptr<ecore::EClass> m_cS_Executor_Class = nullptr;std::shared_ptr<ecore::EClass> m_cS_Locus_Class = nullptr; std::shared_ptr<ecore::EReference> m_cS_ExecutionFactory_Attribute_appliedProfiles = nullptr; std::shared_ptr<ecore::EOperation> m_cS_ExecutionFactory_Operation_getStereotypeApplication_Class_Element = nullptr;std::shared_ptr<ecore::EOperation> m_cS_ExecutionFactory_Operation_getStereotypeClass_EString_EString = nullptr;std::shared_ptr<ecore::EOperation> m_cS_Locus_Operation_instantiate_Class = nullptr;std::shared_ptr<ecore::EOperation> m_cS_ExecutionFactory_Operation_instantiateVisitor_Element = nullptr;std::shared_ptr<ecore::EOperation> m_cS_Executor_Operation_start_Class_ParameterValue = nullptr; friend class LociPackage; static bool isInited; static LociPackage* create(); bool isInitialized = false; bool isCreated = false; virtual void init(std::shared_ptr<ecore::EPackage> package); public: void createPackageContents(std::shared_ptr<ecore::EPackage> package); void initializePackageContents(); private: void createCS_ExecutionFactoryContent(std::shared_ptr<ecore::EPackage> package, std::shared_ptr<ecore::ecoreFactory> factory); void createCS_ExecutorContent(std::shared_ptr<ecore::EPackage> package, std::shared_ptr<ecore::ecoreFactory> factory); void createCS_LocusContent(std::shared_ptr<ecore::EPackage> package, std::shared_ptr<ecore::ecoreFactory> factory); void createPackageEDataTypes(std::shared_ptr<ecore::EPackage> package, std::shared_ptr<ecore::ecoreFactory> factory); void initializeCS_ExecutionFactoryContent(); void initializeCS_ExecutorContent(); void initializeCS_LocusContent(); void initializePackageEDataTypes(); }; } #endif /* end of include guard: PSCS_SEMANTICS_LOCIPACKAGEIMPL_HPP */
8d724fcc44658b8036c7dede029d74e47eaf068c
021df2f4ed5796796aeda5a4323f23f9bf1a897e
/imaging/imaginginttest/imageencoder/src/tsi_icl_encode_extinterface.cpp
8e255a9712482c08a1008b4de4fd42fe0ff6db52
[]
no_license
SymbianSource/oss.FCL.sf.os.mmimaging
5f484b77a8f77fd9d9496512bc0e62743793168e
dcc68da0bf7c10c664c864262d3213b5b30124c9
refs/heads/master
2021-01-12T11:16:03.475384
2010-10-22T05:01:17
2010-10-22T05:01:17
72,886,075
0
0
null
null
null
null
UTF-8
C++
false
false
9,483
cpp
tsi_icl_encode_extinterface.cpp
// Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). // All rights reserved. // This component and the accompanying materials are made available // under the terms of "Eclipse Public License v1.0" // which accompanies this distribution, and is available // at the URL "http://www.eclipse.org/legal/epl-v10.html". // // Initial Contributors: // Nokia Corporation - initial contribution. // // Contributors: // // Description: // This file contains test step class implementation for confirming which extension interface(s) are supported. // Test Design: //EPOC/DV3/team/2005/Multimedia/WorkingDocumentation/Test_Design/ICL_IntTestDesign_ImageDecoder.doc // Test Spec: //EPOC/DV3/team/2005/Multimedia/WorkingDocumentation/Test_Specs/ICL_IntTestSpec_ImageEncoder.xls // // // Test user includes #include "tsi_icl_encode_extinterface.h" #ifdef SYMBIAN_ENABLE_SPLIT_HEADERS #include <icl/icl_uids_const.hrh> #include <icl/icl_uids_def.hrh> #endif // Read common input from the configuration file TInt RStepBaseImageEncoderExtInterface::ReadCommonInputFromConfigFile() { // last 14 chars of the test case number is the name of the section iSectionName = iTestStepName.Right(KSectionNameLen + 7); TPtrC tmpFilename; // iOptionsIndex corresponds to extension interface(s) if ((!GetStringFromConfig(iSectionName, _L("outputimage"), tmpFilename)) || (!GetStringFromConfig(_L("directory"), _L("outputpath"), iOutputPath)) || (!GetIntFromConfig(iSectionName, _L("optionsindex"), iOptionsIndex)) || (!GetIntFromConfig(iSectionName, _L("implementationuidindex"), iImplementationUidIndex))) { return KErrNotFound; } iOutputImage.Append(tmpFilename); return KErrNone; } // Get the encoder Implementation uid which supports multiple options TUid RStepBaseImageEncoderExtInterface::EncoderImplementationUidValue() { TUid implementationUid; implementationUid.iUid = 0; switch(iImplementationUidIndex) { case 1: implementationUid.iUid = KBMPEncoderImplementationUidValue; INFO_PRINTF1(_L("Codec: BMP Encoder")); break; case 2: implementationUid.iUid = KJPGEncoderImplementationUidValue; INFO_PRINTF1(_L("Codec: JPG Encoder")); break; case 3: implementationUid.iUid = KGIFEncoderImplementationUidValue; INFO_PRINTF1(_L("Codec: GIF Encoder")); break; case 4: implementationUid.iUid = KMBMEncoderImplementationUidValue; INFO_PRINTF1(_L("Codec: MBM Encoder")); break; case 5: implementationUid.iUid = KPNGEncoderImplementationUidValue; INFO_PRINTF1(_L("Codec: PNG Encoder")); break; case 6: implementationUid.iUid = KJPGEncoderImplementation2UidValue; INFO_PRINTF1(_L("Codec: JPG Encoder 2")); break; default: // in this case, implUid.iUid = 0; ERR_PRINTF2(_L("Invalid implementation Uid index, %d"), iImplementationUidIndex); break; } return implementationUid; } void RStepBaseImageEncoderExtInterface::DoKickoffTestL() { INFO_PRINTF2(_L("%S"), &iTestCaseDescription); // read input from the configuration file User::LeaveIfError(ReadCommonInputFromConfigFile()); // Create output directory User::LeaveIfError(CreateOutputDirectory()); TFileName tmpname; tmpname.Append(iOutputPath); tmpname.Append(iOutputImage); iOutputImage.Copy(tmpname); // Getting implementation uid iImageEncoderImplementationUidValue = EncoderImplementationUidValue(); if (iImageEncoderImplementationUidValue.iUid == 0) { ERR_PRINTF2(_L("Implementation uid %d is not supported"), iImageEncoderImplementationUidValue.iUid); StopTest(EFail); return; } // Set iOptions User::LeaveIfError(GetEncodeOptions()); switch (iOptionsIndex) { // case 1- 3 are not included as they specify how the encoding should happen i.e client thread,seperatethread etc // following options specify the extension interfaces case 4: INFO_PRINTF1(_L("Extensions: Streamed encoding")); break; case 5: INFO_PRINTF1(_L("Extensions: Rotation during encoding")); break; case 6: INFO_PRINTF1(_L("Extensions: Mirroring during encoding along horizontal axis")); break; case 7: INFO_PRINTF1(_L("Extensions: Mirroring during encoding along vertical axis")); break; case 8: INFO_PRINTF1(_L("Extensions: Setthumbnail duing encoding")); break; case 9: INFO_PRINTF1(_L("Extensions: Reserved1")); break; case 10: INFO_PRINTF1(_L("Extensions: Reserved2")); break; case 11: INFO_PRINTF1(_L("Extensions: Reserved3")); break; // Multiple CImageEncoder::TOptions case 30: INFO_PRINTF1(_L("Extensions: Mirror horizontal and vertical during encoding")); break; case 31: INFO_PRINTF1(_L("Extensions: Mirror horizontal and vertical then setthumbnail during encoding")); break; case 32: INFO_PRINTF1(_L("Extensions: Rotation and set thumbnail during encoding")); break; case 33: INFO_PRINTF1(_L("Extensions: Rotation and Mirror horizontal and vertical during encoding")); break; case 34: INFO_PRINTF1(_L("Extensions: Stream encoding and rotation during encoding")); break; case 35: INFO_PRINTF1(_L("Extensions: Stream encoding then setthumbnail during encoding")); break; case 36: INFO_PRINTF1(_L("Extensions: Stream encoding and Mirror horizontal during encoding")); break; case 37: INFO_PRINTF1(_L("Extensions: Mirror vertical and set Reserved1 option during encoding")); break; default: ERR_PRINTF2(_L("Invalid value for CImageEncoder::TOptions, %d"), iOptionsIndex); StopTest(EFail); return; } DoTest(); } // Confirm that a codec, which supports // mirror/rotation/setthumbnail/streamed encoding // extension interface during encoding RStepEncodeExtInterfaceSupportUsingPluginProp* RStepEncodeExtInterfaceSupportUsingPluginProp::NewL(const TDesC& aStepName, const TDesC& aTestCaseDescription) { return (new (ELeave) RStepEncodeExtInterfaceSupportUsingPluginProp(aStepName, aTestCaseDescription)); } RStepEncodeExtInterfaceSupportUsingPluginProp::RStepEncodeExtInterfaceSupportUsingPluginProp(const TDesC& aStepName, const TDesC& aTestCaseDescription) : RStepBaseImageEncoderExtInterface(aStepName, aTestCaseDescription) { } void RStepEncodeExtInterfaceSupportUsingPluginProp::DoTest() { iPropertiesArray.Reset(); // Extracting plugin proeprties TRAPD(err, CImageEncoder::GetPluginPropertiesL(iImageEncoderImplementationUidValue, iPropertiesArray)); if (err != KErrNone) { ERR_PRINTF2(_L("GetPluginPropertiesL() left, error = %d"), err); StopTest(err, EFail); return; } if (iPropertiesArray.Count() > 0) { INFO_PRINTF1(_L("GetPluginPropertiesL(): Codec may support the extension interface during decoding, check further")); } else { ERR_PRINTF1(_L("GetPluginPropertiesL() returned 0 entries")); StopTest(err, EFail); return; } TBool found = EFalse; for (TInt i = 0; i < iPropertiesArray.Count()-1; i++) { if (iPropertiesArray[i] == KICLExtensionUidValue) { if ((iPropertiesArray[i+1].iUid & iOptions) == iOptions) { INFO_PRINTF1(_L("Extension interface is supported by the Codec")); found = ETrue; StopTest(EPass); return; } else { if ((iTestStepName.Compare(_L("MM-ICL-ENC-RTMR-I-0085-HP")) == 0) || (iTestStepName.Compare(_L("MM-ICL-ENC-STRM-I-0020-HP")) == 0) || (iTestStepName.Compare(_L("MM-ICL-ENC-STRM-I-0030-HP")) == 0)) { ERR_PRINTF1(_L("Extension interface is not supported by the Codec")); StopTest(EPass); return; } } } } if (!found) { ERR_PRINTF1(_L("Extension interface is not supported by the Codec")); StopTest(EFail); } } // Confirm that a codec, which supports // streamed encoding/mirror/rotation/setthumbnail/streamedencoding // extension interface during encoding RStepEncodeExtInterfaceSupportByLoadingCodec* RStepEncodeExtInterfaceSupportByLoadingCodec::NewL(const TDesC& aStepName, const TDesC& aTestCaseDescription) { return (new (ELeave) RStepEncodeExtInterfaceSupportByLoadingCodec(aStepName, aTestCaseDescription)); } RStepEncodeExtInterfaceSupportByLoadingCodec::RStepEncodeExtInterfaceSupportByLoadingCodec(const TDesC& aStepName, const TDesC& aTestCaseDescription) : RStepBaseImageEncoderExtInterface(aStepName, aTestCaseDescription) { } void RStepEncodeExtInterfaceSupportByLoadingCodec::DoTest() { iImageTypeUid = ImageType(); // Check the support for this extension interface in the implementation uid TRAPD(err, iImageEncoder = CImageEncoder::FileNewL(iFs, iOutputImage, iOptions, iImageTypeUid, KNullUid, iImageEncoderImplementationUidValue)); if (err != KErrNone) { if ((iTestStepName.Compare(_L("MM-ICL-ENC-STRM-I-0050-HP")) == 0) || (iTestStepName.Compare(_L("MM-ICL-ENC-STRM-I-0060-HP")) == 0)) { ERR_PRINTF1(_L("Extension interface is not supported by the Codec")); StopTest(err, EPass); return; } ERR_PRINTF1(_L("Extension interface is not supported by the Codec")); StopTest(err, EFail); return; } INFO_PRINTF1(_L("Extension interface is supported by the Codec")); StopTest(EPass); }
ccae196b7973e0afc6c98f97fa402b37f9366954
c5244f34085d0368f53fc4ffc4f371c108ac22c2
/FileDownloadContainer.cc
bce96fd76145c748edcfd69f467b328af7bca392
[]
no_license
arunpn123/ns3-gnutella
f3af21c558e08e353590fcd2798b0c122177b7a2
8a1c9d6ed0e28103ae5a3e47250e5fcc866f85a0
refs/heads/master
2021-01-19T09:44:11.712713
2013-04-25T00:30:19
2013-04-25T00:30:19
9,122,705
1
1
null
null
null
null
UTF-8
C++
false
false
684
cc
FileDownloadContainer.cc
#include "FileDownloadContainer.h" #include "Peer.h" #include <map> void FileDownloadContainer::AddDownload(Peer *p, std::string fn, int fi) { FileInfo f; f.file_name = fn; f.file_index = fi; map_[p] = f; } std::string FileDownloadContainer::GetFileName(Peer *p) { std::map<Peer *, FileInfo>::iterator it = map_.find(p); if (it == map_.end()) return ""; return (it->second).file_name; } int FileDownloadContainer::GetIndex(Peer *p) { std::map<Peer *, FileInfo>::iterator it = map_.find(p); if (it == map_.end()) return -1; return (it->second).file_index; } void FileDownloadContainer::RemoveDownload(Peer *p) { map_.erase(p); }
d4cb496beec101ca391c9d9b5f80d70f6b6daa52
33f1b5f6afa115be45cade93479bb7fbc33e7da0
/UVA/11413/10919677_AC_0ms_0kB.cpp
aba235a24227ac4a6d5a70f908f4aed86d80d4ad
[]
no_license
showmic96/Online-Judge-Solution
3960c37a646f4885210c09096c21dabd7f2154d2
94c34e9db2833fb84d0ac885b637dfebac30a5a2
refs/heads/master
2022-11-26T09:56:58.469560
2020-08-02T04:42:33
2020-08-02T04:42:33
230,185,618
1
0
null
null
null
null
UTF-8
C++
false
false
971
cpp
10919677_AC_0ms_0kB.cpp
// In the name of Allah the Most Merciful. #include<bits/stdc++.h> using namespace std; typedef long long ll; int n , m; vector<int>v; bool check(int lim) { int mt = m-1 , limt = lim; for(int i=0;i<n;i++){ if(v[i]>limt){ limt = lim; mt--; } if(v[i]>lim)return false; limt-=v[i]; } if(mt>=0)return true; return false; } int main(void) { ios::sync_with_stdio(0); cin.tie(0); while(cin >> n >> m){ v.clear(); for(int i=0;i<n;i++){ int in; cin >> in; v.push_back(in); } ll hi = 1e8 , low = 1 , mid , t = 200 , ans = 0; while(t--){ mid = (hi+low)/2; if(check(mid)==true){ ans = mid; hi = mid-1; } else{ low = mid+1; } } cout << ans << endl; } return 0; }
ddf8e2568da54563a61a7c6a373baa16d7f6ca5a
e503b342926d619dd62c0f86fed8bd1c5d4a5a46
/OpenSSLWinRTComponent/OpenSSLWrapper.h
4b7bdf21fd4e5a3cc29a964ce407b407ddf8c746
[]
no_license
siddhu10/MFPBackupRestoreviaFTP
f74c8621ffe4e03aba44a36a2d028325dbd14c2f
211924d6619b200ed1b9ea9d53477fdad786ade1
refs/heads/master
2020-05-04T17:47:35.778976
2019-04-03T16:19:31
2019-04-03T16:19:31
176,989,904
0
0
null
null
null
null
UTF-8
C++
false
false
212
h
OpenSSLWrapper.h
#pragma once namespace OpenSSLWinRTComponent { public ref class OpenSSLWrapper sealed { public: OpenSSLWrapper(); Platform::String^ Entry_AES_Encrypt(Platform::String^ strPwd); }; }
1ea28d884565cecb191ed5b8453c607ef1268c07
b746e4639e27d351cebf4e8b15aa26c3bf7da83b
/Heaps/5.joining_ropes.cpp
e4cb6f02fb2859d90c54e38b26903d0219c8a58e
[]
no_license
JanviMahajan14/Algorithms
97a2d40449565ac0f0b91d8e47bfa953d348dfce
cd951af6496066027586a0fcd4a9f48ee028a173
refs/heads/master
2023-07-16T19:08:42.917575
2021-09-02T07:33:44
2021-09-02T07:33:44
273,521,356
0
0
null
null
null
null
UTF-8
C++
false
false
490
cpp
5.joining_ropes.cpp
#include <iostream> #include <vector> #include <queue> using namespace std; int main() { int n; cin >> n; priority_queue<int, vector<int>, greater<int>> pq; while (n--) { int in; cin >> in; pq.push(in); } int sum = 0; while (!pq.empty() && pq.size() != 1) { int r1 = pq.top(); pq.pop(); int r2 = pq.top(); pq.pop(); sum = sum + r1 + r2; pq.push(r1 + r2); } cout << sum; }
056f43722ecf8f56b73d4491435d2bae3685f91c
5bbda9dd673303e35a0c783e3ac456dcb3e1545b
/src/pwm/pca9685.cpp
adc3b847027b1ff824ed7fb557e2534e12c5ac84
[ "BSD-2-Clause" ]
permissive
NemoLeiYANG/generalvisodom
c32d2b8dd68db8e52da357d5a3acfd0077093e8d
c9eb10539ba1442be9c296b084c152a511cec690
refs/heads/master
2020-03-17T00:29:34.346800
2018-05-09T04:14:27
2018-05-09T04:14:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,252
cpp
pca9685.cpp
#include "gvio/pwm/pca9685.hpp" namespace gvio { int PCA9685::configure(const int freq) { // Setup this->i2c = I2C(); if (this->i2c.setup() != 0) { LOG_INFO("Failed to open i2c connection!"); return -1; } this->i2c.setSlave(PCA9685_I2C_ADDR); this->reset(); this->setAllPWM(0); // Configure mode 2 register this->i2c.writeByte(PCA9685_MODE2, 0x04); this->i2c.writeByte(PCA9685_MODE1, 0x01); usleep(PCA9685_WAIT_MS); // Configure mode 1 register char mode_1; this->i2c.readByte(PCA9685_MODE1, &mode_1); mode_1 = mode_1 & ~0x10; this->i2c.writeByte(PCA9685_MODE1, mode_1); usleep(PCA9685_WAIT_MS); // Set frequency this->setPWMFrequency(freq); usleep(PCA9685_WAIT_MS); return 0; } void PCA9685::setPWMFrequency(const int freq) { // Setup this->i2c.setSlave(PCA9685_I2C_ADDR); // Set pca9685 to sleep char mode_1_old; this->i2c.readByte(PCA9685_MODE1, &mode_1_old); char mode_1_new = (mode_1_old & 0x7F) | 0x10; this->i2c.writeByte(PCA9685_MODE1, mode_1_new); // Set pwm prescaler float prescale = (25000000 / (4096.0 * freq)) - 1; prescale = floor(prescale + 0.5); // LOG_INFO("prescale: %d", (int) prescale); this->i2c.writeByte(PCA9685_PRE_SCALE, (int) prescale); this->i2c.writeByte(PCA9685_MODE1, mode_1_old); // Wait for oscillator usleep(PCA9685_WAIT_MS); // Reset this->i2c.writeByte(PCA9685_MODE1, mode_1_old | (1 << 7)); } void PCA9685::setPWM(const int8_t channel, const int16_t off) { this->i2c.setSlave(PCA9685_I2C_ADDR); this->i2c.writeByte(PCA9685_LED0_ON_L + (4 * channel), 0 & 0xFF); this->i2c.writeByte(PCA9685_LED0_ON_H + (4 * channel), 0 >> 8); this->i2c.writeByte(PCA9685_LED0_OFF_L + (4 * channel), off & 0xFF); this->i2c.writeByte(PCA9685_LED0_OFF_H + (4 * channel), off >> 8); } void PCA9685::setAllPWM(const int16_t off) { this->i2c.setSlave(PCA9685_I2C_ADDR); this->i2c.writeByte(PCA9685_ALL_LED_ON_L, 0 & 0xFF); this->i2c.writeByte(PCA9685_ALL_LED_ON_H, 0 >> 8); this->i2c.writeByte(PCA9685_ALL_LED_OFF_L, off & 0xFF); this->i2c.writeByte(PCA9685_ALL_LED_OFF_H, off >> 8); } void PCA9685::reset() { this->i2c.setSlave(0x00); this->i2c.writeRawByte(0x06); usleep(PCA9685_WAIT_MS); } } // gvio namespace
9e5c4951569abe9d3ae62113f3573c5164b1308d
a2c655a24d09f3b2d325bfe9cc7f533ad0e4001f
/Developpement/Composant5_Dev/Wallet_3/CompoProject/Wallet.cpp
77900caafe1a2666d7c7da27a011e37d94fa0816
[]
no_license
lifakpo/Composant_5
0794f883a24a6cfecf5d79f519f45c49e11c62f1
2721bc7820227dea1c9bb688f9f7686ebdccd2c1
refs/heads/master
2021-04-30T05:41:23.898511
2018-04-23T20:48:20
2018-04-23T20:48:20
121,421,365
0
1
null
null
null
null
WINDOWS-1252
C++
false
false
5,770
cpp
Wallet.cpp
#include "Bloc.h" #include "stdafx.h" #include "Wallet.h" using namespace std; Wallet::Wallet(string file): bc_file(file), mineur(bc_file.findByIndex(1),0) { blocs = bc_file.readAll(); } void stringToUnsignedChar64(string s, unsigned char*& uc) { for (int i = 0; i < s.length(); i++) { uc[i] = s[i]; } return; } void Wallet::depenser(string publicDestinataire, string publicEmetteur, int montant) { if (solde(publicEmetteur) < montant) { cout << "Solde insuffisant ! " << endl; } else { int solde = 0; vector<TXI> TXIs; for (int i = 0; i < blocs.size(); i++) { Bloc b = blocs[i]; UTXO utxo0 = b.tx1.UTXOs[0]; UTXO utxo1 = b.tx1.UTXOs[1]; //on m a envoye de l argent if(strcmp(publicDestinataire.c_str(), (const char *)utxo0.dest)==0){ solde += utxo0.montant; TXI txi; txi.nBloc = i; txi.nUtxo = 0; string stringdata = to_string(montant) + publicDestinataire + to_string(i) + to_string(0); string hash = hasheur.hacher(stringdata);//need other composant string s = signature.signMessage(hash, privateKeys[i]); for (int k = 0; k < s.length(); k++) txi.signature[k] = s[k]; TXIs.push_back(txi); for (Bloc b0 : blocs) { for (TXI txi : b0.tx1.TXIs) { //si utxo0 a ete depense if (txi.nBloc == i && txi.nUtxo == 0) { solde -= utxo0.montant; TXIs.pop_back(); } } } if (solde > montant) { TX tx; tx.TXIs = TXIs; // payer le destinataire UTXO newUtxo0; newUtxo0.montant = montant; for (int k = 0; k < publicDestinataire.size(); k++) newUtxo0.dest[k] = publicDestinataire[k]; //newUtxo0.dest = uu; string stringdata = to_string(montant) + publicDestinataire + to_string(i) + to_string(0); string hashTmp = hasheur.hacher(stringdata); for (int k = 0; k < hashTmp.length(); k++) newUtxo0.hash[k] = hashTmp[k]; tx.UTXOs[0] = newUtxo0; // me rendre la monnaie UTXO newUtxo1; newUtxo1.montant = solde - montant; for (int k = 0; k < publicDestinataire.size(); k++) newUtxo1.dest[k] = publicDestinataire[k]; string stringdatam = to_string(montant) + publicDestinataire + to_string(i) + to_string(1); string hashm = hasheur.hacher(stringdatam); for (int k = 0; k < hashm.length(); k++) newUtxo0.dest[k] = hashm[k]; tx.UTXOs[1] = newUtxo1; //Bloc newBloc = mineur.CreerBloc(tx, (unsigned char *)blocs[blocs.size()].hash);//need to be implemented Bloc newBloc; blocs.push_back(newBloc); bc_file.verification(); bc_file.insert(newBloc); } } // if(strcmp(publicDestinataire.c_str(), (const char *)utxo1.dest)==0) { solde += utxo1.montant; TXI txi; txi.nBloc = i; txi.nUtxo = 0; //signature à faire // string sign(string data, string privKey); hasheur = Hacheur(); string stringdata = to_string(montant) + publicDestinataire + to_string(i) + to_string(0); string hash = hasheur.hacher(stringdata);//need other composant string s = signature.signMessage(hash, privateKeys[i]); for(int k = 0; k < s.length(); k++) txi.signature[k] = s[k]; TXIs.push_back(txi); for (Bloc b0 : blocs) { for (TXI txi : b0.tx1.TXIs) { //si utxo0 a ete depense if (txi.nBloc == i && txi.nUtxo == 0) { solde -= utxo1.montant; TXIs.pop_back(); } } } if (solde > montant) { TX tx; tx.TXIs = TXIs; // payer le destinataire UTXO newUtxo0; newUtxo0.montant = montant; for (int k = 0; k < publicDestinataire.size(); k++) newUtxo0.dest[k] = publicDestinataire[k]; string stringdata = to_string(montant) + publicDestinataire + to_string(i) + to_string(0); string hash = hasheur.hacher(stringdata); for (int k = 0; k < hash.length(); k++) newUtxo0.hash[k] = hash[k]; tx.UTXOs[0] = newUtxo0; // me rendre la monnaie UTXO newUtxo1; newUtxo1.montant = solde - montant; for (int k = 0; k < publicDestinataire.size(); k++) newUtxo1.hash[k] = publicDestinataire[k]; string stringdatam = to_string(montant) + publicDestinataire + to_string(i) + to_string(1); string hashm = hasheur.hacher(stringdatam); for (int k = 0; k < hashm.length(); k++) newUtxo1.hash[k] = hashm[k]; tx.UTXOs[1] = newUtxo1; //Bloc newBloc = mineur.CreerBloc(tx, (unsigned char *)blocs[blocs.size()-1].hash);//need other composant Bloc newBloc; blocs.push_back(newBloc); bc_file.verification(); bc_file.insert(newBloc); break; } } } } } string Wallet::solde() { stringstream ss; for (int i = 0; i < (int)(blocs.size()); i++) { for (int j = 0; j < blocs[i].tx1.UTXOs.size(); j++) { ss << blocs[i].tx1.UTXOs[j].dest << " : " << blocs[i].tx1.UTXOs[j].montant << endl; } } return ss.str(); } int MyCompare(string a, unsigned char* b) { if (a.length() != strlen((char*)b)) return 0; for (int i = 0; i < a.length(); i++) { if (a[i] != b[i]) return 0; } return 1; } int Wallet::solde(string publicKey) { int solde = 0; for (int i = 0; i < blocs.size(); i++) { Bloc b = blocs[i]; UTXO utxo0 = b.tx1.UTXOs[0]; UTXO utxo1 = b.tx1.UTXOs[1]; //on m a envoye de l argent if (MyCompare(publicKey, utxo0.dest) == 0) { solde += utxo0.montant; for (Bloc b0 : blocs) { for (TXI txi : b0.tx1.TXIs) { //si utxo0 a ete depense if (txi.nBloc == i && txi.nUtxo == 0) { solde -= utxo0.montant; } } } } //je me rends la monnaie if(MyCompare(publicKey,utxo1.dest)) { solde += utxo0.montant; for (Bloc b0 : blocs) { for (TXI txi : b0.tx1.TXIs) { //si utxo0 a ete depense if (txi.nBloc == i && txi.nUtxo == 1) { solde -= utxo1.montant; } } } } } return solde; }
989f1d2c48d79362f38047454e9115bc3411c40c
7fbe7f4af92842656ff9af8e102dfb65a27a73f9
/src/SinricProThermostat.h
1b45b3882c8249f7a0d321172650724c84f136a0
[]
no_license
Tejeet/esp8266-esp32-sdk
bde4e828bda76b62e35dda53b3bf0358355948f1
bb52038c1d2594a4d11ba13f36c8396dd7998f93
refs/heads/master
2020-09-02T23:03:17.312025
2019-11-03T06:48:56
2019-11-03T06:48:56
219,326,990
1
0
null
2019-11-03T16:03:32
2019-11-03T16:03:31
null
UTF-8
C++
false
false
5,084
h
SinricProThermostat.h
/* * Copyright (c) 2019 Sinric. All rights reserved. * Licensed under Creative Commons Attribution-Share Alike (CC BY-SA) * * This file is part of the Sinric Pro (https://github.com/sinricpro/) */ #ifndef _SINRICTHERMOSTAT_H_ #define _SINRICTHERMOSTAT_H_ #include "SinricProDevice.h" #include <ArduinoJson.h> class SinricProThermostat : public SinricProDevice { public: SinricProThermostat(const char* deviceId, unsigned long eventWaitTime=100); // callback typedef std::function<bool(const String, bool&)> PowerStateCallback; // void onPowerState(const char* deviceId, bool& powerState); typedef std::function<bool(const String, float&)> TargetTemperatureCallback; typedef std::function<bool(const String, String&)> ThermostatModeCallback; void onPowerState(PowerStateCallback cb) { powerStateCallback = cb; } void onTargetTemperatue(TargetTemperatureCallback cb) { targetTemperatureCallback = cb; } void onAdjustTargetTemperature(TargetTemperatureCallback cb) { adjustTargetTemperatureCallback = cb; } void onThermostatMode(ThermostatModeCallback cb) { thermostatModeCallback = cb; } // event void sendPowerStateEvent(bool state, String cause = "PHYSICAL_INTERACTION"); void sendTemperatureEvent(float temperature, float humidity = -1, String cause = "PERIODIC_POLL"); void sendTargetTemperatureEvent(float temperature, String cause = "PHYSICAL_INTERACTION"); void sendThermostatModeEvent(String thermostatMode, String cause = "PHYSICAL_INTERACTION"); // handle bool handleRequest(const char* deviceId, const char* action, JsonObject &request_value, JsonObject &response_value) override; private: PowerStateCallback powerStateCallback; TargetTemperatureCallback targetTemperatureCallback; TargetTemperatureCallback adjustTargetTemperatureCallback; ThermostatModeCallback thermostatModeCallback; }; SinricProThermostat::SinricProThermostat(const char* deviceId, unsigned long eventWaitTime) : SinricProDevice(deviceId, eventWaitTime), powerStateCallback(nullptr), targetTemperatureCallback(nullptr), adjustTargetTemperatureCallback(nullptr), thermostatModeCallback(nullptr) {} bool SinricProThermostat::handleRequest(const char* deviceId, const char* action, JsonObject &request_value, JsonObject &response_value) { if (strcmp(deviceId, this->deviceId) != 0) return false; bool success = false; String actionString = String(action); if (actionString == "setPowerState" && powerStateCallback) { bool powerState = request_value["state"]=="On"?true:false; success = powerStateCallback(String(deviceId), powerState); response_value["state"] = powerState?"On":"Off"; return success; } if (actionString == "targetTemperature" && targetTemperatureCallback) { float temperature; if (request_value.containsKey("temperature")) { temperature = request_value["temperature"]; } else { temperature = 1; } success = targetTemperatureCallback(String(deviceId), temperature); response_value["temperature"] = temperature; return success; } if (actionString == "adjustTargetTemperature" && adjustTargetTemperatureCallback) { float temperatureDelta = request_value["temperature"]; success = adjustTargetTemperatureCallback(String(deviceId), temperatureDelta); response_value["temperature"] = temperatureDelta; return success; } if (actionString == "setThermostatMode" && thermostatModeCallback) { String thermostatMode = request_value["thermostatMode"] | ""; success = thermostatModeCallback(String(deviceId), thermostatMode); response_value["thermostatMode"] = thermostatMode; return success; } return success; } void SinricProThermostat::sendPowerStateEvent(bool state, String cause) { DynamicJsonDocument eventMessage = prepareEvent(deviceId, "setPowerState", cause.c_str()); JsonObject event_value = eventMessage["payload"]["value"]; event_value["state"] = state?"On":"Off"; sendEvent(eventMessage); } void SinricProThermostat::sendTemperatureEvent(float temperature, float humidity, String cause) { DynamicJsonDocument eventMessage = prepareEvent(deviceId, "currentTemperature", cause.c_str()); JsonObject event_value = eventMessage["payload"]["value"]; event_value["humidity"] = humidity; event_value["temperature"] = roundf(temperature *10) / 10; sendEvent(eventMessage); } void SinricProThermostat::sendTargetTemperatureEvent(float temperature, String cause) { DynamicJsonDocument eventMessage = prepareEvent(deviceId, "targetTemperature", cause.c_str()); JsonObject event_value = eventMessage["payload"]["value"]; event_value["temperature"] = roundf(temperature * 10) / 10.0; sendEvent(eventMessage); } void SinricProThermostat::sendThermostatModeEvent(String thermostatMode, String cause) { DynamicJsonDocument eventMessage = prepareEvent(deviceId, "setThermostatMode", cause.c_str()); JsonObject event_value = eventMessage["payload"]["value"]; event_value["thermostatMode"] = thermostatMode; sendEvent(eventMessage); } #endif
9bc2ebc15430e0c3454163af575ea6366f4af85f
3468c616bdb7bd1497307b6273ddded84be2d867
/src/sounddb.cpp
62bd00d9d40bb23cbb59154680760c4e1bb50039
[ "MIT" ]
permissive
fu7mu4/entonetics
0563915143c5e804140df7a7527516b6da7cf3c4
d0b2643f039a890b25d5036cc94bfe3b4d840480
refs/heads/master
2021-01-10T11:11:14.062751
2016-01-26T06:21:40
2016-01-26T06:21:40
50,407,962
0
0
null
null
null
null
UTF-8
C++
false
false
3,908
cpp
sounddb.cpp
#include <sounddb.hpp> #include <cassert> #include <sstream> namespace ento { SoundDB::SoundDB( void ) : m_anon_count(0) { } bool SoundDB::isSound( const std::string& name ) { std::map<std::string,SoundEntry>::iterator found; found = m_sounds.find(name); return found != m_sounds.end(); } SoundDB::Ref SoundDB::addSound( const std::string& name, const std::string& file ) { SoundEntry se; se.file_name = file; se.references = 0; se.sb = NULL; std::pair< std::map<std::string,SoundEntry>::iterator, bool > inserted; inserted = m_sounds.insert( std::make_pair(name, se ) ); if( ! inserted.second ) { std::ostringstream oss; oss << "sound '" << name << "' already exists"; throw SoundError( oss.str() ); } return &((inserted.first)->second); } SoundDB::Ref SoundDB::getSoundRef( const std::string& name ) { std::map<std::string,SoundEntry>::iterator found; found = m_sounds.find(name); if( found == m_sounds.end() ) { std::ostringstream oss; oss << "'" << name << "' not found"; throw SoundError( oss.str() ); } return &found->second; } Sound SoundDB::getSound( const std::string& name ) { return getSound( getSoundRef( name ) ); } Sound SoundDB::getSound( SoundDB::Ref ref ) { SoundEntry& se = *static_cast<SoundEntry*>(ref); init_entry( se ); std::list<SoundInstance>::iterator inst; inst = m_active.insert(m_active.begin(), SoundInstance( se ) ); return Sound( *this, inst ); } Sound SoundDB::newSound( const std::string& file ) { std::ostringstream oss; oss << this << m_anon_count++; return newSound( oss.str(), file ); } Sound SoundDB::newSound( const std::string& name, const std::string& file ) { return getSound( addSound( name, file ) ); } void SoundDB::init_entry( SoundEntry& se ) { ++se.references; if( se.sb != NULL ) return; se.sb = new sf::SoundBuffer(); if( ! se.sb->LoadFromFile(se.file_name) ) { std::ostringstream oss; oss << "unable to load sound from file '" << se.file_name << "'"; throw SoundError( oss.str() ); } } void SoundDB::collect( void ) { m_playing.remove_if( SoundDB::soundDone ); } bool SoundDB::soundDone( SoundInstance& si ) { return si.sound.GetStatus() != sf::Sound::Playing; } void SoundDB::incr_inst( std::list<SoundInstance>::iterator& inst ) { ++(inst->references); } void SoundDB::decr_inst( std::list<SoundInstance>::iterator& inst ) { --(inst->references); if( inst->references == 0 ) { if( inst->sound.GetStatus() == sf::Sound::Playing ) { // move the SoundInstance to the playing list m_playing.splice( m_playing.begin(), m_active, inst ); } else { // delete the SoundInstance --(inst->se->references); m_active.erase( inst ); } } } // // ---------------------------- Sound::SoundInstance --------------------------- // SoundDB::SoundInstance::SoundInstance( SoundDB::SoundEntry& se_ ) :sound(*se_.sb),references(0),se(&se_) { } // // ----------------------------------- Sound ----------------------------------- // Sound::Sound( SoundDB& db, std::list<SoundDB::SoundInstance>::iterator inst):m_db(db), m_inst(inst) { m_db.incr_inst(m_inst); } Sound::Sound( const Sound& other ):m_db(other.m_db), m_inst(other.m_inst) { m_db.incr_inst(m_inst); } Sound& Sound::operator = ( const Sound& rhs ) { assert( &m_db == &rhs.m_db ); m_db.decr_inst(m_inst); m_inst = rhs.m_inst; m_db.incr_inst(m_inst); return *this; } Sound::~Sound( void ) { m_db.decr_inst(m_inst); } void Sound::play( void ) { m_inst->sound.Play(); } Sound::Status Sound::getStatus( void ) { switch( m_inst->sound.GetStatus() ) { case sf::Sound::Playing: return e_Playing; case sf::Sound::Paused: return e_Playing; default: return e_Playing; } } } // namespace ento
7e743cdd3c15469ec73cf30060ef7f86c77a46ee
d0fb2290d6dbb918ad1c902ae74f747eac7f9d44
/webkit/tag/body.cpp
b52730584dc48793ffbc0162066aed331d2b8cc8
[]
no_license
drWebber/qt-webkit
81ec9c26ad24d800d9410a16ae91f314faaa96c9
78b610d55b3c5f26c45debc764ff9b2af7804b27
refs/heads/master
2020-04-10T08:59:54.446752
2018-11-25T10:34:10
2018-11-25T10:34:10
160,922,421
0
0
null
null
null
null
UTF-8
C++
false
false
1,184
cpp
body.cpp
#include "body.h" QString Body::name() { return "body"; } QString Body::innerText() { QString text = outerHtml(); RegExp::replace("(?si)<script.+?/script>", text, ""); RegExp::replace("(?si)</?p>|<p\\s.+?>", text, "\r\n"); RegExp::replace("<br/?>|<br\\s.+?>", text, "\r\n"); RegExp::replace("(?si)</?li>|<li\\s.+?>", text, "\r\n"); RegExp::replace("(?si)</?h\\d>|<h\\d\\s.+?>", text, "\r\n"); RegExp::replace("(?si)<.+?>", text, ""); return text; } int Body::cyrillicSymbolsCount() { return RegExp::matchesCount("[А-я]", innerText()); } QStringList Body::getPhoneNumbers() { QStringList phones; QStringList patt; patt << "\\d{1,3}-\\d{2,5}-\\d{2,3}-\\d{2}-\\d{2}" << "\\d{1,3} \\d{2,5} \\d{2,3} \\d{2} \\d{2}" << "\\d{1,3} ?\\(\\d{2,5}\\) \\d{2,3} \\d{2} \\d{2}" << "\\d{1,3} ?\\(\\d{2,5}\\) \\d{2,3}-\\d{2}-\\d{2}" << "\\d{1,3} ?\\(\\d{2,5}\\) \\d{3}-\\d{3}"; QString inner = innerText(); foreach (QString pattern, patt) { if (inner.contains(QRegularExpression(pattern))) { phones << RegExp::matches(pattern, inner, 0); } } return phones; }
c3722217afd362301c7fac16bd7ab37bdce1b4e6
1c6c9772ca8ad9da9d316c580853409085e4b880
/Board.h
dca9d1734821358ef7fee72afee69c77e9bbe2f1
[]
no_license
M-Berkaliyeva/Tetris
b4475b58c215f14e15aad423c0c1d63ce46762fa
40f7590a3e29981d257cc7a037214cecd12bc3db
refs/heads/master
2020-06-03T16:29:31.451496
2014-01-17T18:03:04
2014-01-17T18:03:04
16,007,334
2
2
null
null
null
null
UTF-8
C++
false
false
1,351
h
Board.h
#ifndef _BOARD_ #define _BOARD_ #include "Tetromino.h" #define BOARD_LINE_WIDTH 6 // Width of each of the two lines that delimit the board #define BLOCK_SIZE 30 // Width and Height of each block of a tetromino #define BOARD_POSITION 220 // Center position of the board from the left of the screen #define BOARD_WIDTH 10 // Board width in blocks #define BOARD_HEIGHT 20 // Board height in blocks #define MIN_VERTICAL_MARGIN 20 // Minimum vertical margin for the board limit #define MIN_HORIZONTAL_MARGIN 20 // Minimum horizontal margin for the board limit #define PIECE_BLOCKS 5// Number of horizontal and vertical blocks of a matrix piece class Board { public: Board(Tetromino *tetros, int screenHeight); int getXPosInPixels(int pPos); int getYPosInPixels(int pPos); bool isFreeBlock(int pX, int pY); bool isPossibleMovement(int pX, int pY, int tetroType, int rotationtype); void storeTetromino(int pX, int pY, int tetroType, int rotationType); void deletePossibleLines(); bool isGameOver(); void initBoard(); bool gameOver; int deletedLineCount; int points; int score; int level; int timer; private: enum {POS_FREE, POS_FILLED}; int board[BOARD_WIDTH][BOARD_HEIGHT]; Tetromino *tetromino; int screenHeight; void deleteLine(int pY); }; #endif
8f40443eeb7c66f0228540f2af43dec8686a88a1
d12a2023c519eab2c8e75a73bb58d73c97f2220f
/qt try/ui_outline/bookstackedpage.h
2e9af0f347a63bf38f1c0448bf0d2ff020e9dbbd
[]
no_license
GhostofAdam/LibraryManagement
ad8f9448ffd55e7370dec8ae28310e0cb59c983e
154d7599f4d5b6bd0651c433a8040bbe44bfff55
refs/heads/master
2020-03-10T12:17:43.190999
2018-07-01T12:26:53
2018-07-01T12:26:53
129,374,461
0
2
null
2018-05-30T16:04:46
2018-04-13T08:42:46
C++
UTF-8
C++
false
false
1,011
h
bookstackedpage.h
#ifndef BOOKSTACKEDPAGE_H #define BOOKSTACKEDPAGE_H #include <QWidget> #include <QMainWindow> #include <QSplitter> #include <QVBoxLayout> #include <QHBoxLayout> #include <QAction> #include <QListWidget> #include <QStackedWidget> #include <QLabel> #include <QString> #include "databookadapter.h" #include "databook.h" namespace Ui { class BookStackedPage; } class BookStackedPage : public QWidget { Q_OBJECT public: explicit BookStackedPage(QWidget *parent = 0); ~BookStackedPage(); void SetBookTable(QVector<DataBook *>); void Adapt2User(); void Adapt2Administer(); void ClearTable(); signals: void SearchBook(QString search_info, QString search_type); void SelectBookId(QString id); void InsertBook(); void ChangeBook(QString id); private slots: void on_SearchButton_clicked(); void on_ViewButton_clicked(); void on_InsertButton_clicked(); void on_ChangeButton_clicked(); private: Ui::BookStackedPage *ui; }; #endif // BOOKSTACKEDPAGE_H
3dcc41aa0af6bd3187bf57429fe6916d263e4f6e
4b162d4e70022705555596f161954b909d29047a
/equilibrium_index.cpp
6098769c0aab2993febbf6e453b86a2af0738c0e
[]
no_license
kashyap99saksham/Preparation
53d4a48b99ed9bc5b6f3da29a07c3d44e5ad22a9
df1f938fca7fbd406a715d7a80db3c7c464039ea
refs/heads/master
2020-06-24T18:49:33.021059
2019-08-21T16:44:20
2019-08-21T16:44:20
199,051,644
1
0
null
null
null
null
UTF-8
C++
false
false
477
cpp
equilibrium_index.cpp
#include<iostream> using namespace std; int main(){ int t; cin>>t; while(t--) { int n,j,k; cin>>n; bool f = false; int arr[n]; for(int i=0;i<n;i++) cin>>arr[i]; for(int i=0;i<n;i++) { int sum_l=0,sum_r=0; for(j=0;j<i;j++) { sum_l+= arr[j]; } for(k=i+1;k<n;k++) { sum_r+= arr[k]; } if(sum_l==sum_r) { f = true; cout<<i; break; } } if(k==false) cout<<-1; } }
41a5e200dfacf0ea4a7d6bd11e3e6afc18b7b6c0
0e0883cd9d8fe9cbf0598483988a4ff0a12622dd
/src/include/Sprite.hpp
26ab85755dd1e4d908fbe69320f141e6d933942d
[ "BSD-3-Clause" ]
permissive
J-Clip9/Distillate
3dfb86860f73444af70e85b257431c3e8967e84c
40d3f3f14beea973b985f9a04d837463169023cb
refs/heads/master
2022-02-09T08:37:33.495857
2011-08-03T02:37:15
2011-08-03T02:37:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,100
hpp
Sprite.hpp
/** * Copyright (c) 2010 - 2011 Distillate Project * * ______ ________________________ _____________________ * | \ | |______ | | | | |_____| | |______ * |_____/__|________| | __|__|_____|_____| | | |______ * * * License: BSD * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name of Wintermoon 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 __SPRITE_HPP__ #define __SPRITE_HPP__ #if defined(SDL_VIDEO) #include <SDL/SDL.h> #endif #if defined(HW_RENDER) #if defined(__APPLE__) #include <OpenGLES/ES1/gl.h> #include <OpenGLES/ES1/glext.h> #else #include <GL/gl.h> #include <GL/glu.h> #endif #if defined(X11_VIDEO) #include <X11/X.h> #include <X11/Xlib.h> #include <GL/glext.h> #include <GL/glx.h> #include <X11/extensions/xf86vmode.h> #endif #endif #include <string> #include <vector> #include "Defs.hpp" #include "Object.hpp" #include "Utils.hpp" NAMESPACE_BEGIN /* Forward */ class Point; class Anim; class TextureResource; /** * The main "game object" class, handles basic physics and animation. */ class Sprite : public Object { friend class DState; public: /** * Store the animation frames */ typedef std::vector<unsigned int> AnimationFrames; /** * Callback function for Sprite */ typedef bool (callbackFunctionSprite)(Anim*, unsigned int); /** * Useful for controlling flipped animations and checking player orientation. */ static const unsigned int LEFT = 0; /** * Useful for controlling flipped animations and checking player orientation. */ static const unsigned int RIGHT = 1; /** * Useful for checking player orientation. */ static const unsigned int UP = 2; /** * Useful for checking player orientation. */ static const unsigned int DOWN = 3; /** * If you changed the size of your sprite object to shrink the bounding box, * you might need to offset the new bounding box from the top-left corner of the sprite. */ Point offset; /** * Whether the current animation has finished its first (or only) loop. */ bool finished; /** * The width of the actual graphic or image being displayed (not necessarily the game object/bounding box). * NOTE: Edit at your own risk!! This is intended to be read-only. */ unsigned int frameWidth; /** * The height of the actual graphic or image being displayed (not necessarily the game object/bounding box). * NOTE: Edit at your own risk!! This is intended to be read-only. */ unsigned int frameHeight; /** * The total number of frames in this image (assumes each row is full) */ unsigned int frames; protected: /* Animation helpers */ std::vector<Anim*> _animations; unsigned int _flipped; Anim* _curAnim; unsigned int _curFrame; unsigned int _caf; float _frameTimer; callbackFunctionSprite *_callback; unsigned int _facing; int _bakedRotation; float _alpha; bool _boundsVisible; Point _rendering_rect; /* Surface stuff */ TextureResource *_pixels; public: /** * Creates a white 8x8 square <code>FlxSprite</code> at the specified position. * Optionally can load a simple, one-frame graphic instead. * * @param X The initial X position of the sprite. * @param Y The initial Y position of the sprite. * @param SimpleGraphic The graphic you want to display (OPTIONAL - for simple stuff only, do NOT use for animated images!). */ Sprite(float X = 0, float Y = 0, const std::string &SimpleGraphic = ""); virtual ~Sprite(); /** * Load an image from an embedded graphic file. * * @param Graphic The image you want to use. * @param Animated Whether the Graphic parameter is a single sprite or a row of sprites. * @param Reverse Whether you need this class to generate horizontally flipped versions of the animation frames. * @param Width OPTIONAL - Specify the width of your sprite (helps FlxSprite figure out what to do with non-square sprites or sprite sheets). * @param Height OPTIONAL - Specify the height of your sprite (helps FlxSprite figure out what to do with non-square sprites or sprite sheets). * @param Textures * @param Unique Whether the graphic should be a unique instance in the graphics cache. * * @return This FlxSprite instance (nice for chaining stuff together, if you're into that). */ Sprite *loadGraphic(const std::string &Graphic, bool Animated = false, bool Reverse = false, unsigned int Width = 0, unsigned int Height = 0, unsigned int Textures = 1, bool Unique = false); /** * This function creates a flat colored square image dynamically. * * @param Width The width of the sprite you want to generate. * @param Height The height of the sprite you want to generate. * @param Color Specifies the color of the generated block. * @param Unique Whether the graphic should be a unique instance in the graphics cache. * @param Key Optional parameter - specify a string key to identify this graphic in the cache. Trumps Unique flag. * * @return This FlxSprite instance (nice for chaining stuff together, if you're into that). */ Sprite *createGraphic(const std::string &Key, unsigned int Width, unsigned int Height, unsigned int Color = 0xffffffff); protected: /** * Resets some important variables for sprite optimization and rendering. */ void resetHelpers(); /** * Internal function that performs the actual sprite rendering, called by render(). */ void renderSprite(); public: /** * Main game loop update function. Override this to create your own sprite logic! * Just don't forget to call super.update() or any of the helper functions. */ virtual void update(); /** * Called by game loop, updates then blits or renders current frame of animation to the screen */ virtual void render(); /** * Checks to see if a point in 2D space overlaps this FlxCore object. * * @param X The X coordinate of the point. * @param Y The Y coordinate of the point. * @param PerPixel Whether or not to use per pixel collision checking. * * @return Whether or not the point overlaps this object. */ bool overlapsPoint(unsigned int X, unsigned int Y, bool PerPixel = false); /** * Triggered whenever this sprite is launched by a <code>FlxEmitter</code>. */ virtual void onEmit() {}; /** * Adds a new animation to the sprite. * * @param Name What this animation should be called (e.g. "run"). * @param Frames An array of numbers indicating what frames to play in what order (e.g. 1, 2, 3). * @param FrameRate The speed in frames per second that the animation should play at (e.g. 40 fps). * @param Looped Whether or not the animation is looped or just plays once. */ void addAnimation(const std::string &Name, std::vector<unsigned int> &Frames, float FrameRate, bool Looped = true); /** * Plays an existing animation (e.g. "run"). * If you call an animation that is already playing it will be ignored. * * @param AnimName The string name of the animation you want to play. * @param Force Whether to force the animation to restart. */ void play(const std::string &AnimName, bool Boolean = false); /** * Call this function to figure out the on-screen position of the object. * * @param P Takes a <code>Point</code> object and assigns the post-scrolled X and Y values of this object to it. * * @return The <code>Point</code> you passed in, or a new <code>Point</code> if you didn't pass one, containing the screen X and Y position of this object. */ virtual Point * getScreenXY(Point &Point); /** * Internal function to update the current animation frame. */ void calcFrame(); /** * Internal function for updating the sprite's animation. * Useful for cases when you need to update this but are buried down in too many supers. * This function is called automatically by <code>FlxSprite.update()</code>. */ void updateAnimation(); void frame(unsigned int Frame) { _curAnim = NULL; _caf = Frame; calcFrame(); } }; NAMESPACE_END #endif /* __SPRITE_HPP__ */
57dde7d29e369dc97df1b393b79ea9c89ff8430a
869e0f4ead411ba097d2154be37f81de10579069
/UDPSever/UDPSever/UDPSever.cpp
dbaf8a872d46009e0ceb02977e022ab69b33b9b8
[]
no_license
jacobishao/SampleUdpSocket
cf9428f9c8395af6671c701a62cfb31797aa0207
1275e34c20558d226293409e4ed429ef484d6f9a
refs/heads/master
2021-01-10T10:30:11.250893
2015-10-28T06:02:09
2015-10-28T06:02:09
36,866,783
3
0
null
null
null
null
GB18030
C++
false
false
2,154
cpp
UDPSever.cpp
#include <winsock2.h> #include <stdio.h> #include <windows.h> // Need to link with Ws2_32.lib #pragma comment (lib, "Ws2_32.lib") int main(int argc, char* argv[]) { //---------------------- // Initialize Winsock. WSADATA wsaData; int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); if (iResult != NO_ERROR) { wprintf(L"WSAStartup failed with error: %ld\n", iResult); return 1; } //---------------------- // Create a SOCKET for listening for // incoming connection requests. SOCKET SrvSocket; SrvSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (SrvSocket == INVALID_SOCKET) { wprintf(L"socket failed with error: %ld\n", WSAGetLastError()); WSACleanup(); return 1; } //---------------------- // The sockaddr_in structure specifies the address family, // IP address, and port for the socket that is being bound. sockaddr_in addrServer; addrServer.sin_family = AF_INET; addrServer.sin_addr.s_addr = htonl(INADDR_ANY); //实际上是0 addrServer.sin_port = htons(20131); //绑定套接字到一个IP地址和一个端口上 if (bind(SrvSocket, (SOCKADDR *)& addrServer, sizeof(addrServer)) == SOCKET_ERROR) { wprintf(L"bind failed with error: %ld\n", WSAGetLastError()); closesocket(SrvSocket); WSACleanup(); return 1; } //以一个无限循环的方式,不停地接收客户端socket连接 while (1) { //接收缓冲区的大小是1024个字符 char recvBuf[2048 + 1]; struct sockaddr_in cliAddr; //定义IPV4地址变量 int cliAddrLen = sizeof(cliAddr); int count = recvfrom(SrvSocket, recvBuf, 2048, 0, (struct sockaddr *)&cliAddr, &cliAddrLen); if (count == 0)break;//被对方关闭 if (count == SOCKET_ERROR)break;//错误count<0 recvBuf[count] = '\0'; printf("client IP = %s,端口:%d\n", inet_ntoa(cliAddr.sin_addr),ntohs(cliAddr.sin_port)); //显示发送数据的IP地址 printf("%s\n", recvBuf); //对于udp包只能一次成功 //将收到的字符串转化为大写字符串 strupr(recvBuf); if (sendto(SrvSocket, recvBuf, count, 0, (struct sockaddr *)&cliAddr, cliAddrLen)<count) break; } closesocket(SrvSocket); WSACleanup(); return 0; }
c83b6cd523adba47445365f7ad6acdbbd11d5fd7
ecf6d488d37cd90978425c03a0b204e195181981
/M3105/tp5/Interpreteur.cpp
7f4a6c5f03aa33cc7089a8f3a5e6b66464ffb936
[]
no_license
m-cabezas/Interpreteur
93797f468e87e689518b49d52289fbf72785e97d
885aba8e8c3726de5d354335f583d6bb5c848d66
refs/heads/master
2022-03-02T02:41:12.360641
2019-11-07T14:51:46
2019-11-07T14:51:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,619
cpp
Interpreteur.cpp
#include "Interpreteur.h" #include <stdlib.h> #include <iostream> using namespace std; Interpreteur::Interpreteur(ifstream & fichier) : m_lecteur(fichier), m_table(), m_arbre(nullptr) { } void Interpreteur::analyse() { m_arbre = programme(); // on lance l'analyse de la première règle if (nbErreurs != 0) { m_arbre = nullptr; cerr << "Nombres d'erreurs : " << nbErreurs << endl; } } void Interpreteur::tester(const string & symboleAttendu) const throw (SyntaxeException) { // Teste si le symbole courant est égal au symboleAttendu... Si non, lève une exception static char messageWhat[256]; if (m_lecteur.getSymbole() != symboleAttendu) { sprintf(messageWhat, "Ligne %d, Colonne %d - Erreur de syntaxe - Symbole attendu : %s - Symbole trouvé : %s", m_lecteur.getLigne(), m_lecteur.getColonne(), symboleAttendu.c_str(), m_lecteur.getSymbole().getChaine().c_str()); throw SyntaxeException(messageWhat); } } void Interpreteur::testerEtAvancer(const string & symboleAttendu) throw (SyntaxeException) { // Teste si le symbole courant est égal au symboleAttendu... Si oui, avance, Sinon, lève une exception try { tester(symboleAttendu); m_lecteur.avancer(); } catch (const SyntaxeException& e) { cerr << e.what() << endl; nbErreurs++; m_lecteur.avancer(); } } void Interpreteur::erreur(const string & message) const throw (SyntaxeException) { // Lève une exception contenant le message et le symbole courant trouvé // Utilisé lorsqu'il y a plusieurs symboles attendus possibles... static char messageWhat[256]; sprintf(messageWhat, "Ligne %d, Colonne %d - Erreur de syntaxe - %s - Symbole trouvé : %s", m_lecteur.getLigne(), m_lecteur.getColonne(), message.c_str(), m_lecteur.getSymbole().getChaine().c_str()); throw SyntaxeException(messageWhat); } Noeud* Interpreteur::programme() { // <programme> ::= procedure principale() <seqInst> finproc FIN_FICHIER testerEtAvancer("procedure"); testerEtAvancer("principale"); testerEtAvancer("("); testerEtAvancer(")"); Noeud* sequence = seqInst(); testerEtAvancer("finproc"); try { tester("<FINDEFICHIER>"); } catch (const SyntaxeException& e) { cerr << e.what() << endl; nbErreurs++; } return sequence; } Noeud* Interpreteur::seqInst() { // <seqInst> ::= <inst> { <inst> } NoeudSeqInst* sequence = new NoeudSeqInst(); do { sequence->ajoute(inst()); } while (m_lecteur.getSymbole() == "<VARIABLE>" || m_lecteur.getSymbole() == "si" || m_lecteur.getSymbole() == "selon" || m_lecteur.getSymbole() == "tantque" || m_lecteur.getSymbole() == "repeter" || m_lecteur.getSymbole() == "pour" || m_lecteur.getSymbole() == "ecrire" || m_lecteur.getSymbole() == "lire"); // Tant que le symbole courant est un début possible d'instruction... // Il faut compléter cette condition chaque fois qu'on rajoute une nouvelle instruction return sequence; } Noeud* Interpreteur::inst() { // <inst> ::= <affectation> ; | <instSiRiche> | <instTantQue> | <instPour> | <ecrire> | <lire> if (m_lecteur.getSymbole() == "<VARIABLE>") { Noeud *affect = affectation(); testerEtAvancer(";"); return affect; } else if (m_lecteur.getSymbole() == "si") return instSiRiche(); else if (m_lecteur.getSymbole() == "tantque") return instTantQue(); else if (m_lecteur.getSymbole() == "pour") return instPour(); else if (m_lecteur.getSymbole() == "repeter") { Noeud *repeter = instRepeter(); testerEtAvancer(";"); return repeter; } else if (m_lecteur.getSymbole() == "lire") { Noeud *lire = instLire(); testerEtAvancer(";"); return lire; } else if (m_lecteur.getSymbole() == "ecrire") { Noeud *ecrire = instEcrire(); testerEtAvancer(";"); return ecrire; } else if (m_lecteur.getSymbole() == "selon") { Noeud *selon = instSelon(); return selon; }// Compléter les alternatives chaque fois qu'on rajoute une nouvelle instruction else erreur("Instruction incorrecte"); } Noeud* Interpreteur::affectation() { // <affectation> ::= <variable> = <expression> try { tester("<VARIABLE>"); } catch (const SyntaxeException& e) { cerr << e.what() << endl; nbErreurs++; } Noeud* var = m_table.chercheAjoute(m_lecteur.getSymbole()); // La variable est ajoutée à la table et on la mémorise m_lecteur.avancer(); testerEtAvancer("="); Noeud* exp = expression(); // On mémorise l'expression trouvée return new NoeudAffectation(var, exp); // On renvoie un noeud affectation } Noeud* Interpreteur::expression() { // <expression> ::= <terme> { + <terme> | - <terme> } Noeud* term = terme(); while (m_lecteur.getSymbole() == "+" || m_lecteur.getSymbole() == "-") { Symbole operateur = m_lecteur.getSymbole(); // On mémorise le symbole de l'opérateur m_lecteur.avancer(); Noeud* termeDroit = terme(); // On mémorise l'opérande droit term = new NoeudOperateurBinaire(operateur, term, termeDroit); // Et on construuit un noeud opérateur binaire } return term; // On renvoie terme qui pointe sur la racine de l'expression } Noeud* Interpreteur::terme() { // <terme> ::= <facteur> { * <facteur> | / <facteur } Noeud* fact = facteur(); while (m_lecteur.getSymbole() == "*" || m_lecteur.getSymbole() == "/") { Symbole operateur = m_lecteur.getSymbole(); // On mémorise le symbole de l'opérateur m_lecteur.avancer(); Noeud* factDroit = facteur(); // On mémorise l'opérande droit fact = new NoeudOperateurBinaire(operateur, fact, factDroit); // Et on construuit un noeud opérateur binaire } return fact; } Noeud* Interpreteur::facteur() { // <facteur> ::= <entier> | <variable> | - <expBool> | non <expBool> | ( <expBool> ) Noeud* exprBool = nullptr; if (m_lecteur.getSymbole() == "<VARIABLE>" || m_lecteur.getSymbole() == "<ENTIER>") { exprBool = m_table.chercheAjoute(m_lecteur.getSymbole()); // on ajoute la variable ou l'entier à la table m_lecteur.avancer(); } else if (m_lecteur.getSymbole() == "-") { // - <expBool> m_lecteur.avancer(); // on représente le moins unaire (- expBool) par une soustraction binaire (0 - expBool) exprBool = new NoeudOperateurBinaire(Symbole("-"), m_table.chercheAjoute(Symbole("0")), expBool()); } else if (m_lecteur.getSymbole() == "non") { // non <expBool> m_lecteur.avancer(); // on représente le moins unaire (- expBool) par une soustractin binaire (0 - expBool) exprBool = new NoeudOperateurBinaire(Symbole("non"), expBool(), nullptr); } else if (m_lecteur.getSymbole() == "(") { // expression parenthésée m_lecteur.avancer(); exprBool = expression(); testerEtAvancer(")"); } else erreur("Expression booléenne incorrect"); return exprBool; } Noeud* Interpreteur::expBool() { // <expbool> ::= <relationET> { ou <relationEt> } Noeud* relEt = relationEt(); while (m_lecteur.getSymbole() == "ou") { Symbole operateur = m_lecteur.getSymbole(); // On mémorise le symbole de l'opérateur m_lecteur.avancer(); Noeud* relEtDroit = relationEt(); // On mémorise l'opérande droit relEt = new NoeudOperateurBinaire(operateur, relEt, relEtDroit); // Et on construuit un noeud opérateur binaire } return relEt; } Noeud* Interpreteur::relationEt() { // <relationET> ::= <relation> { et <relation> } Noeud* rel = relation(); while (m_lecteur.getSymbole() == "et") { Symbole operateur = m_lecteur.getSymbole(); // On mémorise le symbole de l'opérateur m_lecteur.avancer(); Noeud* relDroit = relation(); // On mémorise l'opérande droit rel = new NoeudOperateurBinaire(operateur, rel, relDroit); // Et on construuit un noeud opérateur binaire } return rel; } Noeud* Interpreteur::relation() { // <relation> ::= <expression> { <opRel> <expression> } Noeud* expr = expression(); while (m_lecteur.getSymbole() == "==" || m_lecteur.getSymbole() == "!=" || m_lecteur.getSymbole() == "<" || m_lecteur.getSymbole() == "<=" || m_lecteur.getSymbole() == ">" || m_lecteur.getSymbole() == ">=") { Symbole op = opRel(); Noeud* exprDroit = expression(); // On mémorise l'opérande droit expr = new NoeudOperateurBinaire(op, expr, exprDroit); // Et on construuit un noeud opérateur binaire } return expr; } Symbole Interpreteur::opRel() { if (m_lecteur.getSymbole() == "==" || m_lecteur.getSymbole() == "!=" || m_lecteur.getSymbole() == "<" || m_lecteur.getSymbole() == "<=" || m_lecteur.getSymbole() == ">" || m_lecteur.getSymbole() == ">=") { Symbole operateur = m_lecteur.getSymbole(); m_lecteur.avancer(); return operateur; } else { erreur("opérateur incorrect"); } } //Noeud* Interpreteur::instSi() { // // <instSi> ::= si ( <expression> ) <seqInst> finsi // testerEtAvancer("si"); // testerEtAvancer("("); // Noeud* condition = expression(); // On mémorise la condition // testerEtAvancer(")"); // Noeud* sequence = seqInst(); // On mémorise la séquence d'instruction // testerEtAvancer("finsi"); // return new NoeudInstSi(condition, sequence); // Et on renvoie un noeud Instruction Si //} Noeud* Interpreteur::instSiRiche() { //<instSiRiche> ::= si(<expression>)<seqInst> {sinon si(<expression>)<seqInst> }[sinon<seqInst>]finsi NoeudInstSiRiche* noeud = new NoeudInstSiRiche(); testerEtAvancer("si"); testerEtAvancer("("); noeud->ajouterCond(expBool()); testerEtAvancer(")"); noeud->ajouterSeq(seqInst()); while (m_lecteur.getSymbole() == "sinonsi") { testerEtAvancer("sinonsi"); testerEtAvancer("("); noeud->ajouterCond(expBool()); testerEtAvancer(")"); noeud->ajouterSeq(seqInst()); } if (m_lecteur.getSymbole() == "sinon") { testerEtAvancer("sinon"); noeud->ajouterSinon(seqInst()); } testerEtAvancer("finsi"); return noeud; } Noeud* Interpreteur::instTantQue() { testerEtAvancer("tantque"); testerEtAvancer("("); Noeud* condition = expBool(); testerEtAvancer(")"); Noeud* sequence = seqInst(); testerEtAvancer("fintantque"); NoeudInstTantQue* noeud = new NoeudInstTantQue(condition, sequence); return noeud; } Noeud * Interpreteur::instRepeter() { testerEtAvancer("repeter"); Noeud* sequence = seqInst(); testerEtAvancer("jusqua"); testerEtAvancer("("); Noeud* condition = expBool(); testerEtAvancer(")"); return new NoeudInstRepeter(condition, sequence); } Noeud* Interpreteur::instPour() { //<instPour>::= pour([<affectation>];<expression>;[<affectation>])< seqInst> finpour NoeudInstPour* noeud = new NoeudInstPour(); testerEtAvancer("pour"); testerEtAvancer("("); if (m_lecteur.getSymbole() != ";") { noeud->setInit(affectation()); } testerEtAvancer(";"); noeud->setCondition(expBool()); testerEtAvancer(";"); if (m_lecteur.getSymbole() != ")") { noeud->setIncrement(affectation()); } testerEtAvancer(")"); noeud->setSequence(seqInst()); testerEtAvancer("finpour"); return noeud; } Noeud* Interpreteur::instEcrire() { //<instEcrire> ::= ecrire(<expression> |<chaine> {,<exp(string)expression->executer();ression> | <chaine> }) testerEtAvancer("ecrire"); testerEtAvancer("("); NoeudInstEcrire* noeud = new NoeudInstEcrire(); bool premierPassage = true; do { if (!premierPassage) { testerEtAvancer(","); } if (m_lecteur.getSymbole() == "<CHAINE>") { Noeud* chaine = m_table.chercheAjoute(m_lecteur.getSymbole()); // La variable est ajoutée à la table et on la mémorise noeud->ajouterInstruction(chaine); testerEtAvancer("<CHAINE>"); } else { Noeud* instru = expBool(); noeud->ajouterInstruction(instru); } premierPassage = false; } while (m_lecteur.getSymbole() != ")"); testerEtAvancer(")"); return noeud; } Noeud* Interpreteur::instLire() { //<instLire> ::=lire( <variable> {,<variable> }) testerEtAvancer("lire"); testerEtAvancer("("); try { tester("<VARIABLE>"); } catch (const SyntaxeException& e) { cerr << e.what() << endl; nbErreurs++; } Noeud* var = m_table.chercheAjoute(m_lecteur.getSymbole()); Noeud* noeud = new NoeudInstLire(var); m_lecteur.avancer(); while (m_lecteur.getSymbole() != ")") { testerEtAvancer(","); try { tester("<VARIABLE>"); } catch (const SyntaxeException& e) { cerr << e.what() << endl; nbErreurs++; } var = m_table.chercheAjoute(m_lecteur.getSymbole()); noeud->ajoute(var); m_lecteur.avancer(); } testerEtAvancer(")"); return noeud; } void Interpreteur::traduitEncpp(ostream & cout, unsigned int indentation) const { cout << "#include <iostream>" << endl << endl; cout << "using namespace std;" << endl << endl; cout << setw(4 * indentation) << "" << "int main() {" << endl; for (int i = 0; i < m_table.getTaille(); i++) { if (m_table[i] == "<VARIABLE>") { cout << setw(4 * (indentation + 1)) << "" << "int " << m_table[i].getChaine() << ";" << endl; } } getArbre()->traduitEncpp(cout, indentation + 1); cout << setw(4 * (indentation + 1)) << "" << "return 0;" << endl; cout << setw(4 * indentation) << "}" << endl; } Noeud* Interpreteur::instSelon() { NoeudInstSelon* noeud = new NoeudInstSelon(); testerEtAvancer("selon"); testerEtAvancer("("); Noeud* var = m_table.chercheAjoute(m_lecteur.getSymbole()); noeud->ajouterVar(var); m_lecteur.avancer(); testerEtAvancer(")"); while (m_lecteur.getSymbole() == "cas") { testerEtAvancer("cas"); cout << "TYRUTYFF"; try { tester("<ENTIER>"); } catch (const SyntaxeException& e) { cerr << e.what() << endl; nbErreurs++; } Noeud* cas = m_table.chercheAjoute(m_lecteur.getSymbole()); noeud->ajouterCas(cas); m_lecteur.avancer(); testerEtAvancer(":"); noeud->ajouterSeq(seqInst()); } testerEtAvancer("defaut"); testerEtAvancer(":"); noeud->ajouterSeqDef(seqInst()); testerEtAvancer("finselon"); return noeud; } //procedure // //Noeud* Interpreteur::instProcedure() { // testerEtAvancer("procedure"); // testerEtAvancer("("); // if (m_lecteur.getSymbole() == "<VARIABLE") { // m_table.chercheAjoute(m_lecteur.getSymbole()); // La variable est ajoutée à la table et on la mémorise // m_lecteur.avancer(); // while (m_lecteur.getSymbole() == ",") { // m_table.chercheAjoute(m_lecteur.getSymbole()); // La variable est ajoutée à la table et on la mémorise // m_lecteur.avancer(); // } // } // // // NoeudProc* noeud = new NoeudProc(seqInst); // return noeud; //} //Noeud* Interpreteur::instAppel(){ // //}
467cc4c0d7a93fe54d401f178773b5cd55c5764c
411cdc4aabc554a640a18f1f4be114de74efe3b0
/Instruction.cpp
9e9e25fa03d260dee17268b1e0baa9800f0bc437
[ "MIT" ]
permissive
UtkrishtDhankar/TuringMachine
82d652ceea902fae47f9e17678127b79cd99c01d
a8f96a17d1a25f50d9a0225ae608d703d2ac84ca
refs/heads/master
2021-01-20T08:29:29.540436
2017-05-03T13:29:22
2017-05-03T13:29:22
90,151,173
0
1
null
2017-05-03T16:54:57
2017-05-03T13:19:21
C++
UTF-8
C++
false
false
661
cpp
Instruction.cpp
#include "Instruction.hpp" Instruction::Instruction() { moveType = MoveType::STAY; overwrite = 0; nextCard = 0; } Instruction::Instruction(MoveType m, bool o, unsigned int n) { moveType = m; overwrite = o; nextCard = n; } Instruction::Instruction(const Instruction& other) { moveType = other.moveType; overwrite = other.overwrite; nextCard = other.nextCard; } Instruction::Instruction(Instruction&& other) { moveType = other.moveType; overwrite = other.overwrite; nextCard = other.nextCard; } void Instruction::operator=(const Instruction& other) { moveType = other.moveType; overwrite = other.overwrite; nextCard = other.nextCard; }
e8cdaefbebcbe364d10ec702976a83639cfe9e63
3e91e71323a043bd404203bd4d5efd9aae15b18e
/Dev-CppProject/Demo02_Min.cpp
9811fb002b2fe53f7b3e2ab7aaebadb0a047b05f
[]
no_license
ZhanXiaoFeng/MyProject
f5dc60612a0c644f3837192f4298bad68c2d927a
61ecfb266173e5dc7b283cb4fd5bc4a40912b6cd
refs/heads/master
2022-07-17T15:41:49.300176
2018-08-23T10:53:07
2018-08-23T10:53:07
141,031,392
1
0
null
2022-06-29T16:45:38
2018-07-15T13:54:32
JavaScript
GB18030
C++
false
false
493
cpp
Demo02_Min.cpp
#include<stdio.h> int main(){ int i,j, row=0,colum=0,min; //这里理解为a[3][4]的一个二维数组 int a[][4]={{1,2,3,4},{9,8,7,6},{-10,10,-5,2}}; //定义一开始最小的一个数为a[0][0],即为数组中的第一个数 min=a[0][0]; for(i=0;i<3;i++) //或者i<=2 for(j=0;j<4;j++) if(min>a[i][j]){//用当前的min值和a[i][j]依次比较 min=a[i][j]; row=i; colum=j; } printf("min=%d\nrow=%d\ncolum=%d\n",min,row,colum); return 0; }
bc2abb91986740e20dd11026530d2dd6ac404927
26be1f025256e2320f46b739d87fc0afadc825c9
/src/entities/collision_handler.cpp
dba02b38ba2a0c294507f510c0381bf82813f97f
[]
no_license
CCAtAlvis/ray-n-vader
f1292bdb454985fc6c89b767acd09384bb4dcb4d
c5885d1476a0cd2a353ff996120a3ca28d046bc5
refs/heads/main
2023-07-09T20:06:30.973525
2021-08-15T18:22:58
2021-08-15T18:22:58
391,450,809
1
1
null
null
null
null
UTF-8
C++
false
false
1,034
cpp
collision_handler.cpp
#include <iostream> #include "raylib.h" #include "../headers/game.h" #include "../headers/collision_handler.h" #include "../headers/enemy.h" #include "../headers/player.h" #include "../headers/bullet.h" void CheckPlayerCollision() { for (auto &e : Enemy::enemies) { Rectangle rec{Player::position.x - Player::SHIP_WIDTH / 2 - 20, Player::position.y - Player::SHIP_HEIGHT / 2 - 20, Player::SHIP_WIDTH + 40, Player::SHIP_HEIGHT + 40}; DrawRectangleLinesEx(rec, 2, ORANGE); bool collision = CheckCollisionCircleRec(e.center, e.radius, rec); if (collision) { Player::TakeDamage(20); e.Reset(); } } } void CheckBulletCollision() { for (auto &e : Enemy::enemies) { for (auto &b : Bullet::bulletes) { if (!b.isEnabled) continue; bool collision = CheckCollisionCircles(e.center, e.radius, b.center, b.RADIUS); if (collision) { e.TakeDamage(e.unitStrength); b.Disable(); Const::score++; } } } }
ddb5952223bae5347d78dda5f7811e9fc66d8c14
e4b6dbbec45e36f8399710318f6a53327fbf7529
/include/gmml/internal/library_file.h
eb1a65616de0a34438afe17041f08deb0fd46624
[ "MIT" ]
permissive
rtdavis22/GMML
9994205b8529ec11d0d29997149f848ee0c3d307
78da13bafa5256b87ad17f624099fed09b534b74
refs/heads/master
2021-01-22T09:32:58.244273
2014-02-05T16:17:33
2014-02-05T16:17:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,792
h
library_file.h
// Copyright (c) 2012 The University of Georgia // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // Author: Robert Davis #ifndef GMML_INTERNAL_LIBRARY_FILE_H_ #define GMML_INTERNAL_LIBRARY_FILE_H_ #include <iosfwd> #include <map> #include <string> #include <utility> #include <vector> #include "boost/shared_ptr.hpp" #include "gmml/internal/boxed_structure.h" #include "gmml/internal/stubs/common.h" #include "gmml/internal/stubs/file.h" namespace gmml { class LibraryFileStructure; // This class represents an AMBER OFF library file. The file specification can // be found here: library file http://ambermd.org/doc/OFF_file_format.txt. class LibraryFile : public Readable { public: typedef boost::shared_ptr<LibraryFileStructure> StructurePtr; typedef std::map<std::string, StructurePtr>::iterator iterator; typedef std::map<std::string, StructurePtr>::const_iterator const_iterator; explicit LibraryFile(const std::string& file_name) { Readable::read(file_name); } const_iterator begin() const { return structures_.begin(); } const_iterator end() const { return structures_.end(); } // This returns the structure with given name. The name comes from the // listing at the top of the file. If the structure isn't present, // StructurePtr() is returned. const StructurePtr operator[](const std::string& name) const; private: void read(std::istream&); // A mapping from the structure names at the top of the file to the // corresponding structure in the file. std::map<std::string, StructurePtr> structures_; DISALLOW_COPY_AND_ASSIGN(LibraryFile); }; inline const LibraryFile::StructurePtr LibraryFile::operator[]( const std::string& name) const { const_iterator it = structures_.find(name); if (it != structures_.end()) return it->second; else return StructurePtr(); } class LibraryFileSet { public: typedef LibraryFile::iterator iterator; typedef LibraryFile::const_iterator const_iterator; LibraryFileSet() {} const_iterator begin() const { return structures_.begin(); } const_iterator end() const { return structures_.end(); } // These add the structures in a library file to the current set of // structure. If a structure name already exists in the set, it is // overwritten and a warning is displayed. void load(const LibraryFile& file); void load(const std::string& file_name) { load(LibraryFile(file_name)); } // This returns the structure with the given name. If the structure is // not present, StructurePtr() is returned. const LibraryFile::StructurePtr operator[](const std::string& name) const; private: // A mapping from the structure names found in the library files their // corresonding structures. std::map<std::string, LibraryFile::StructurePtr> structures_; DISALLOW_COPY_AND_ASSIGN(LibraryFileSet); }; inline const LibraryFile::StructurePtr LibraryFileSet::operator[]( const std::string& name) const { const_iterator it = structures_.find(name); if (it != structures_.end()) return it->second; else return LibraryFile::StructurePtr(); } class LibraryFileStructure : public BoxedStructure { public: // This constructor reads a library file structure from a stream. The first // line of the stream must be the first atom of the structure. // The stream will read until the first atom of the next structure in the // stream. explicit LibraryFileStructure(std::istream& in) : BoxedStructure() { read(in); } virtual ~LibraryFileStructure() {} virtual LibraryFileStructure *clone() const; private: LibraryFileStructure() : BoxedStructure() {} void clone_from(const LibraryFileStructure& structure); void read(std::istream& in); std::pair<Atom*, int> read_atom(std::istream& in) const; void read_box(std::istream& in); void read_connect_atoms(std::istream& in); void read_connectivity_info(std::istream& in, const std::map<int, int>& atom_map); void read_positions(std::istream& in, const std::map<int, int>& atom_map); void read_residue_info(std::istream& in, const std::map<int, int>& residue_map); DISALLOW_COPY_AND_ASSIGN(LibraryFileStructure); }; inline LibraryFileStructure *LibraryFileStructure::clone() const { LibraryFileStructure *structure = new LibraryFileStructure; structure->clone_from(*this); return structure; } inline LibraryFileStructure *build_library_file_structure( const LibraryFileStructure& structure) { return structure.clone(); } } // namespace gmml #endif // GMML_INTERNAL_LIBRARY_FILE_H_
046abfe9edd2cc7cce7ffdcef803f5979d53d3d8
cac3e17dcddaa4dbec8dc5f6ab3dade7c8c36dca
/codex/include/codex/codex.hpp
01e9761462a114843ceaf2aa994f7618909bb4d5
[ "MIT" ]
permissive
codex-tk/libcodex
ac7b0505aae0402418176e2625e357b7242d9b7d
003f20242b8139b9a805dc9bfd9bdc96a28555e3
refs/heads/master
2020-12-02T09:57:57.352661
2017-09-18T12:50:55
2017-09-18T12:50:55
96,666,338
1
0
null
null
null
null
UTF-8
C++
false
false
1,327
hpp
codex.hpp
#ifndef __libcodex_codex_h__ #define __libcodex_codex_h__ #if defined( _WIN32 ) #if !defined(NOMINMAX) #define NOMINMAX #endif #include <WinSock2.h> #include <MSWSock.h> #include <ws2tcpip.h> #include <Windows.h> #else #include <sys/types.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <string.h> #include <netinet/tcp.h> #endif #include <errno.h> #include <iostream> #include <mutex> #include <atomic> #include <system_error> #include <memory> #include <deque> #include <vector> #include <algorithm> #include <functional> #if defined( _WIN32 ) /// @brief win32 predef /// @detail /// _WIN32 always /// _WIN64 : win64 application /// _M_AMD64 or _M_X64 : x64 /// _M_IX86 : x86 /// _M_ARM : ARM /// _M_ARMT : ARM Thumb Mode #define __codex_win32__ #elif defined( __linux__ ) /// @brief linux predef /// @detail /// __x86_64__ : x64 /// __arm__ : ARM /// __thumb__ : ARM Thumb Mode /// __i386__ : x86 /// __ANDROID__ : android #define __codex_linux__ #elif defined( __APPLE__ ) /// @brief apple predef /// @detail /// __x86_64__ : x64 /// __arm__ : ARM /// __thumb__ : ARM Thumb Mode /// __i386__ : x86 /// TARGET_IPHONE_SIMULATOR /// TARGET_OS_IPHONE /// TARGET_OS_MAC #define __codex_apple__ #endif namespace codex{ int universe(void); } #endif
531337fe9c3fe562dd65802c3d4c6f0f0c32f6f6
513e061ab4bcb8755f13e927de39322b44b04c14
/cpp/conv2D.cpp
3ae6685d7cc73d5c123719ffc5cf3c07d61c7d4a
[]
no_license
EC500-Convolution-Project/2D-image
ed6718eeab3bd61c402718350fde56e4704869e1
0c0da1667e36d5a47eff684878766da37b393628
refs/heads/master
2020-03-11T09:36:47.890868
2018-05-03T17:48:25
2018-05-03T17:48:25
129,917,174
0
0
null
2018-05-01T15:54:02
2018-04-17T14:28:37
C++
UTF-8
C++
false
false
4,685
cpp
conv2D.cpp
/* Parallelization of 2D Convolution on GPU Michael Clifford, Patrick Dillon, Frank Tranghese EC500 E1 - Parallel Programming Group 1 */ #include "conv2D.h" using namespace std; /* *** INPUTS *** array is an array of N doubles that need to be made circulant (assumes already zero padded) circArray is where the circulant matrix produced will be stored N is # of entries in array */ void circ(double * array, double ** circArray, int N){ int x,y,dim,dim2; //lower triangle for(x=0;x<N;x++){ for(y=0;y<N;y++){ if(x+y < N){ circArray[y+x][y] = array[x]; } } } //upper triangle, skip middle since already done dim = N-2; dim2 = 0; for(x=0;x<N;x++){ for(y=1;y<N;y++){ if(y+dim<N && y+dim2<N){ circArray[x][y+dim2] = array[y+dim]; } dim=dim-2; } dim2++; dim=N-2; } } /* *** INPUTS *** hpad is 2D zero-padded h to make into block circulant matrix circH is storage for block circulant matrix N is # of entries in columns of hpad, since each column a will need to be circ() M is # of columns in hpad */ void circ2(double ** hpad, double ** circH, int N, int M){ int i,j,k,x,y,dim,dim2; double * arrayTmp = new double[N]; double ** matrixTmp = new double*[N]; for(i=0;i<N;i++){ matrixTmp[i] = new double[N]; } //for columns in hpad, create circulant matrices - lower triangle for(i=0;i<M;i++){ for(j=0;j<N;j++){ arrayTmp[j] = hpad[j][i]; } circ(arrayTmp,matrixTmp,N); // get circulant of that column //place into correct position for(dim=0;dim<N;dim++){ for(x=0;x<N;x++){ for(y=0;y<N;y++){ if((x+(N*dim)+(i*N)) < (N*M)){ circH[(x+(N*dim)+(i*N))][y+(N*dim)] = matrixTmp[x][y]; } } } } } //for columns in hpad, create circulant matrices - upper triangle //skip middle portion, since already complete dim2 = 1; for(i=M-1;i>0;i--){ for(j=0;j<N;j++){ arrayTmp[j] = hpad[j][i]; } circ(arrayTmp,matrixTmp,N); // get circulant of that column //place into correct position for(dim=dim2;dim<N;dim++){ for(x=0;x<N;x++){ for(y=0;y<N;y++){ if((y+(N*dim2)) < (N*M)){ circH[(x+(N*(dim-dim2)))][y+(N*dim)] = matrixTmp[x][y]; } } } } dim2++; } } /* *** INPUTS *** f is 2D matrix of our signal/image h is 2D matrix of our TF/Filter/Kernel fpad is place to put zero-padded f hpad is place to put zero-padded h */ void padder2D(double ** f, double ** h, double ** fpad, double** hpad, int N){ int x, y; int size_f = *(&f[0] + 1) - f[0] -2 ; //int size_h = *(&h[0] + 1) - h[0]-2 ; for(x = 0; x <= size_f; x++){ for(y = 0; y <= size_f; y ++){ fpad[x][y] = f[x][y]; } } //for(x = 0; x < size_h; x++){ // for(y = 0; y < size_h; y ++){ // hpad[x+pad][y+pad] = h[x][y]; // } //} } /* *** INPUTS *** which - char signifying if stacking or unstacking (s or u) image - matrix to be row stacked or storage for unstacked image stacked - array to be unstacked or storage for stacked image */ void stacker(double ** image, double * stacked, int N){ int x,y; int position = 0; for (x = 0; x < N; x++){ for(y = 0; y < N; y++){ stacked[position] = image[x][y]; position++; } } } /* *** INPUTS *** image - zero matrix to be filled stacked - array to be unstacked */ void unstacker(double * stacked, double ** image, int N){ int x,y; int position = 0; for (x = 0; x < N; x++){ for (y = 0; y < N; y++){ image[x][y] = stacked[position]; position++; } } } /* *** INPUTS *** A is 2D block circulant matrix fstacked is 1D array of stacked image rows output is an empty array that will be populated through the convolution */ void conv2(double ** A, double * fstacked, double * output, int N){ int x, y; int position = 0; int position2 = 0; for(x = 0; x < N; x++){ for(y = 0; y < N ; y++){ output[position] += A[x][y]*fstacked[position2]; position2 ++; } position2 = 0; position++; } } void conv2_dir(double ** A, double ** filter, double ** output, int N, int filter_N){ int x, y; int x_pos, y_pos; for(x = 0; x < N; x++){ for(y = 0; y < N ; y++){ for( x_pos = 0; x_pos <filter_N; x_pos++){ for(y_pos = 0 ; y_pos < filter_N; y_pos++){ if (x+x_pos < N && y+y_pos < N){ output[x][y] += A[x+x_pos][y+y_pos]*filter[x_pos][y_pos]; //cout << x+x_pos <<" , " << y+y_pos << endl; } } } } } }
0152b1a5441118b0268baab673003f355a434a68
23227f0cb7807f4d6ba165164d2111c0e8f8e6a3
/Instance_Set.h
ef917d354191e1858f2a40d7dae8fa1bc94d691a
[]
no_license
Ying-Syuam-Wang/Multi-objective_performance_matrices
c845ac71030a3696660df93f87d6c15975701762
690bf7e1654c1fd3ff7190da8a312009abe162c6
refs/heads/master
2020-04-06T04:11:52.353754
2017-05-22T20:48:09
2017-05-22T20:48:09
83,007,812
0
0
null
null
null
null
UTF-8
C++
false
false
1,086
h
Instance_Set.h
#ifndef INSTANCE_SET_H_INCLUDED #define INSTANCE_SET_H_INCLUDED #include "algo_Instance_Result.h" class CInstanceSet { public: CInstanceSet(){} explicit CInstanceSet(size_t s):_insResult(s){} void resizeIns(size_t s){_insResult.resize(s);} const CInstanceResult & Ins(size_t i)const{return _insResult[i];} CInstanceResult & Ins(size_t i) { return const_cast<CInstanceResult&>(static_cast<const CInstanceSet&>(*this).Ins(i));} const CInstanceResult & operator[](size_t i)const{return _insResult[i];} CInstanceResult& operator[](size_t i) { return const_cast<CInstanceResult&>(static_cast<const CInstanceSet&>(*this)[i]);} void calAvgPerforamce(); const CPerformace & avgPerformance()const{return _avgInsPerformance;} CPerformace & avgPerformance() { return const_cast<CPerformace&>(static_cast<const CInstanceSet&>(*this).avgPerformance());} size_t numIns(){return _insResult.size();} private: std::vector<CInstanceResult> _insResult; CPerformace _avgInsPerformance; }; #endif // INSTANCE_SET_H_INCLUDED
f705a174bdfb7537085c4c8d11c5b861a4f18f1b
478928f7a41b87f821070e6c0ee78820b580b127
/extlibs/SSVUtils/include/SSVUtils/String/Split.h
88e685fce516d36a565e5cbce7ff0e42bc005c6d
[ "AFL-3.0", "LicenseRef-scancode-unknown-license-reference", "AFL-2.1" ]
permissive
questor/git-ws
316bdd7165e752195fc40b05e2af1e0778623038
4c6db1dd6586be21baf74d97e3caf1006a239aec
refs/heads/master
2021-01-17T22:50:06.476220
2015-01-26T11:34:38
2015-01-26T11:34:38
11,098,394
0
0
null
null
null
null
UTF-8
C++
false
false
1,879
h
Split.h
// Copyright (c) 2013 Vittorio Romeo // License: Academic Free License ("AFL") v. 3.0 // AFL License page: http://opensource.org/licenses/AFL-3.0 #ifndef SSVU_STRING_SPLIT #define SSVU_STRING_SPLIT #include <string> #include <vector> #include "SSVUtils/String/Enums.h" #include "SSVUtils/String/Internal/SplitHelper.h" namespace ssvu { /*! * * @brief Splits a string in smaller strings, filling a target vector<string>. * * @tparam T Type of the separator. Can be a char, a string, a vector<char> or a vector<string>. * @tparam TM Separation mode. Can be SplitMode::Normal or SplitMode::KeepSeparator (keeps the separator in the splitted strings). * @param mTarget Vector to fill with the splitted strings. * @param mString String to split. * @param mSeparator Separator to split at. Every occurrence of the separator will cause a split. * */ template<typename T, SplitMode TM = SplitMode::Normal> void split(std::vector<std::string>& mTarget, const std::string& mString, const T& mSeparator) { Internal::SplitHelper<T, TM>::split(mTarget, mString, mSeparator); } /*! * * @brief Splits a string in smaller strings, returning a vector<string>. * * @tparam T Type of the separator. Can be a char, a string, a vector<char> or a vector<string>. * @tparam TM Separation mode. Can be SplitMode::Normal or SplitMode::KeepSeparator (keeps the separator in the splitted strings). * @param mString String to split. * @param mSeparator Separator to split at. Every occurrence of the separator will cause a split. * * @return Returns a std::vector containing all splitted strings. * */ template<typename T, SplitMode TM = SplitMode::Normal> std::vector<std::string> getSplit(const std::string& mString, const T& mSeparator) { std::vector<std::string> result; split<T, TM>(result, mString, mSeparator); return result; } } #endif
a88d2ec77197257c422116d2cd6e2a4dc1e2982c
70c1fdc0a0206e7e869635efa222518d502f29f5
/rangequeries/range_queries_with_tree.cpp
40f2db81184f5dc4d0e6eb58fd02a490353e3e9e
[]
no_license
AndyLi23/cses
6f87fa82017f2b1396c9ea1641b7dad85122d85f
4c0ccf82b89b144b6badb29ac15f4c1633fbc159
refs/heads/master
2023-07-05T01:10:22.588140
2021-08-23T15:15:48
2021-08-23T15:15:48
389,780,612
0
0
null
null
null
null
UTF-8
C++
false
false
1,282
cpp
range_queries_with_tree.cpp
#include <bits/stdc++.h> using namespace std; #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; template <class T> using Tree = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; #define FOR(i, n) for(int (i) = 0 ; (i) < (n); ++(i)) #define FOR2(i, a, b) for(int (i) = (a); (i) < (b); ++(i)) #define FOR2R(i, b, a) for(int (i) = (b); (i) >= (a); --(i)) #define ll long long #define pb push_back int N, Q, a[200001], a1, b1; Tree<pair<int, int> > o; char c; int main() { ios::sync_with_stdio(0); cin.tie(0); //use cin >> and cout << //run local: g++ -std=c++11 -O2 -Wall task.cpp -o a vector<int> m; cin >> N >> Q; FOR(i, N) { cin >> a[i]; //need pair to differentiate same element but different index o.insert({a[i], i}); } FOR(i, Q) { cin >> c >> a1 >> b1; if(c == '!') { //update element at index a1 to b1 a1--; o.erase({a[a1], a1}); a[a1] = b1; o.insert({a[a1], a1}); } else { //get number of elements from a1 to b1 cout << o.order_of_key({b1, INT_MAX}) - o.order_of_key({a1 - 1, INT_MAX}) << endl; } } }
77f40b91e77427d6ab43e37c6cc598a9d68c369d
a6bc975db9ce2e4579f73245ee571988cd0c7c8f
/q1.cpp
b379ddd3ba60b13318a803e98f4aa47acd7aaebe
[]
no_license
y-gupta/col757-ass1
9189b73204f9f74d87d19d2e768b39f0fe0a8d75
eb0dd723913f2fb12d1c37102d066260020d0474
refs/heads/master
2021-06-14T12:54:31.393401
2017-05-19T15:49:16
2017-05-19T15:49:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,273
cpp
q1.cpp
#include <iostream> #include <omp.h> #include <cassert> #include <cstdlib> #define P 12 #define LOGP 4 #define N 10000000 #define T 1000 //number of testcases #define N1 1 using namespace std; inline double timer(bool output=false) { static double prev=0; double current = omp_get_wtime(); double delta = current - prev; prev = current; if(output){ cout<<"Time taken = "<<delta<<endl; } return delta; } int main(int argc, char **argv){ srand(time(NULL)); // assert(N % P == 0); cout<<"N = "<<N<<"\nP = "<<P<<endl; char *bits; int correct_result = 0; bits = new char[N]; omp_set_num_threads(P); correct_result = 0; #pragma omp parallel for for(int i = 0; i < N; ++i) { auto p = N*float(rand())/RAND_MAX; if(p <= N1){ bits[i] = 1; correct_result = 1; }else bits[i] = 0; } cout<<"correct_result = "<<correct_result<<endl; double results[3]={0,0,0}; double times[3]={0,0,0}; for(int t=0;t<T;t++){ int result = 0; timer(); for(int i=0;i<N;i++) { result |= bits[i]; } times[0] += timer(); results[0] += result; // cout<<"result = "<<result<<" (SERIAL)"<<endl; result = 0; timer(); #pragma omp parallel for for(int i=0; i < N;i++){ if(bits[i] == 1){ // #pragma omp atomic result = 1; } // result |= bits[i]; } times[1] += timer(); results[1] += result; // cout<<"result = "<<result<<" (CW)"<<endl; result = 0; int tmp_result[P] = {0}; timer(); #pragma omp parallel { int j = omp_get_thread_num(); int local_result = 0; #pragma omp for for(int i = 0; i < N;i++){ local_result |= bits[i]; } tmp_result[j] = local_result; for(int r=1;r<=LOGP;r++){ #pragma omp barrier if((j & ((1<<r)-1)) == (1<<(r-1))){ tmp_result[j - (1<<(r-1))] |= tmp_result[j]; } } } result = tmp_result[0]; times[2] += timer(); results[2] += result; } cout<<"result = "<<results[0]/T<<", t = "<<times[0]/T<<" (SERIAL)"<<endl; cout<<"result = "<<results[1]/T<<", t = "<<times[1]/T<<" (CW)"<<endl; cout<<"result = "<<results[2]/T<<", t = "<<times[2]/T<<" (BINTREE)"<<endl; return 0; }
df36ab1c1fc3a1483c691e44b122a603d65dc602
c021ea6ec2a1882f71617b7fed430e8e40c66573
/src/component/mainview.h
1bb081bd231a5df50894bfeed9204686779aff19
[ "MIT" ]
permissive
top-master/Android-BuildTools
e9a32b8b6c6a78ef0d6543265eedec3d284329ab
b268e65f88cd15be049f25191c18f26caae043fb
refs/heads/master
2020-04-15T16:35:55.012331
2019-01-09T10:36:17
2019-01-16T12:37:17
164,842,525
0
0
null
null
null
null
UTF-8
C++
false
false
437
h
mainview.h
#ifndef MAINVIEW_H #define MAINVIEW_H #include <QWidget> namespace Ui { class MainView; } class MainView : public QWidget { Q_OBJECT typedef QWidget super; public: explicit MainView(QWidget *parent = 0); ~MainView(); public slots: void build(); protected slots: void restore(); void browseNdk(); void browseQmake(); void browseProject(); private: Ui::MainView *ui; }; #endif // MAINVIEW_H
01df8e09740c1a2e4dd3dd11dc17afa0492af8a0
b7afa85b16359b4f6171197c7188439489ab95ad
/Singleton/InsideObject/main.cpp
3168aa31fb3cc06497761b1908e7fbe3ddcbd376
[]
no_license
gdgy/LearnCpp
e250b613971e0a2d2ebb26879781a900b4a390f2
5fd90116eb630a4aba98edeb1219f893a551c7c7
refs/heads/master
2021-01-21T19:51:47.571825
2017-05-28T01:00:24
2017-05-28T01:00:24
92,169,428
0
0
null
null
null
null
GB18030
C++
false
false
1,314
cpp
main.cpp
#include <iostream> #include <cstdlib> using namespace std; typedef void(*Fun)(); class Base { public: Base(int i) :baseI(i){}; virtual void print(void){ cout << "调用了虚函数Base::print()"; } virtual void setI(){ cout << "调用了虚函数Base::setI()" << endl; } virtual ~Base(){ cout << "call Base::~Base()" << endl; } private: int baseI; }; void TestB() { Base b(5); //虚函数表 Fun vfunc = (Fun)*((int *)*((int*)(&b))); Fun vfunb = (Fun)*((int *)*((int*)(&b)) + 1); cout << "Hello world" << endl; vfunc(); vfunb(); } class Derive : public Base { public: Derive(int d) :Base(1000), DeriveI(d){}; //overwrite父类虚函数 virtual void print(void){ cout << "Drive::Drive print()" << endl; } // Derive声明的新的虚函数 virtual void Drive_print(){ cout << "Drive::Drive_print()" << endl; } virtual ~Derive(){ cout << "call Derive::~Derive" << endl; } private: int DeriveI; }; void TestD() { //测试单继承Derive Derive d(10); Fun pFun = (Fun)(*(int*)*(int*)&d); Fun pFun2 = (Fun)*((int*)*(int*)&d + 1); //析构函数 Fun pFun3 = (Fun)*((int*)*(int*)&d + 2); Fun pFun4 = (Fun)*((int*)*(int*)&d + 3); pFun(); pFun2(); //pFun3(); pFun4(); } void fun1() { cout << "call fun1 last" << endl; } int main() { //TestD(); atexit(fun1); system("pause"); }
735a43942da66842877de9e9d8e152733a6f3054
0dc20516079aaae4756d28e67db7cae9c0d33708
/server/src/server/net/link.cpp
85a1f0a178601d4566e4631c94c3ffe2b8c13de0
[]
no_license
psymicgit/dummy
149365d586f0d4083a7a5719ad7c7268e7dc4bc3
483f2d410f353ae4c42abdfe4c606ed542186053
refs/heads/master
2020-12-24T07:48:56.132871
2017-08-05T07:20:18
2017-08-05T07:20:18
32,851,013
3
8
null
null
null
null
GB18030
C++
false
false
10,851
cpp
link.cpp
///<------------------------------------------------------------------------------ //< @file: server\net\link.cpp //< @author: 洪坤安 //< @date: 2015年1月14日 23:7:5 //< @brief: //< Copyright (c) 2015 服务器. All rights reserved. ///<------------------------------------------------------------------------------ #include "link.h" #include <google/protobuf/message.h> #include "netmodel.h" #include "netaddress.h" #include "listener.h" #include "protocol/message.h" #include "tool/sockettool.h" #include "tool/atomictool.h" #include "basic/evbuffer.h" void Link::open() { socktool::setNonBlocking(m_sockfd); socktool::setKeepAlive(m_sockfd, true, 120); // socktool::setSendBufSize(m_sockfd, 256 * 1024); // socktool::setRecvBufSize(m_sockfd, 256 * 1024); if (!socktool::setTcpNoDelay(m_sockfd)) { LOG_ERROR << m_logic->name() << " " << getLocalAddr().toIpPort() << "<-->" << getPeerAddr().toIpPort() << " setTcpNoDelay failed!"; } m_net->addFd(this); } Link::~Link() { } void Link::close() { if (m_closed) { return; } // 投递到网络线程执行close命令 m_net->getTaskQueue()->put(boost::bind(&Link::closing, this)); } void Link::closing() { // 检测是否重复close if (m_closed) { LOG_ERROR << m_logic->name() << " double closed, canceled, m_sendBuf left size = " << evbuffer_get_length(&m_sendBuf); return; } // 如果未发生错误,则先将未发送的数据发送完毕 if (!m_error && !m_isPeerClosed) { lock_guard_t<> lock(m_sendBufLock); // 若数据未发送完毕,则暂缓关闭,只停止接收数据,等待之前的发送操作执行完毕后再关闭 if (evbuffer_get_length(&m_sendBuf) > 0) { if (m_isWaitingClose) { // LOG_ERROR << m_logic->name() << " is waiting close"; return; } m_isWaitingClose = true; // shutdown(m_sockfd, SHUT_RD); // 禁止读取数据 m_net->disableRead(this); if (!m_isWaitingWrite) { LOG_ERROR << m_logic->name() << " m_sendBuf != empty(), left size = " << evbuffer_get_length(&m_sendBuf) << ", socket = " << m_sockfd; } // LOG_ERROR << m_logic->name() << " is waiting write"; return; } } // LOG_INFO << m_logic->name() << " Link::closing"; { lock_guard_t<> lock(m_sendBufLock); if (evbuffer_get_length(&m_sendBuf) > 0) { LOG_ERROR << m_logic->name() << " close, left size = " << evbuffer_get_length(&m_sendBuf) << ", socket = " << m_sockfd; } } m_closed = true; // shutdown(m_sockfd, SHUT_RDWR); // 首先屏蔽本连接上的所有网络输出 socktool::closeSocket(m_sockfd); #ifdef WIN // 若是windows平台,则需要再从读写集上取消注册 m_net->disableAll(this); #endif // 等业务层处理好关闭操作 m_logic->getTaskQueue().put(boost::bind(&Link::onLogicClose, this)); } void Link::erase() { LinkPool &linkPool = m_net->getLinkPool(); linkPool.free(this); } void Link::onLogicClose() { m_logic->onDisconnect(this, m_localAddr, m_peerAddr); m_net->delFd(this); } void Link::onSend() { if (!isopen()) { return; } if (!m_isWaitingWrite) { return; } // LOG_INFO << "Link::onSend, socket = " << m_sockfd; // { // lock_guard_t<> lock(m_sendBufLock); // if(m_sendBuf.empty()) { // LOG_ERROR << m_logic->name() << " m_sendBuf.empty(), m_isWaitingWrite = " << m_isWaitingWrite; // return; // } // } // 1. 将发送缓冲区的数据全部取出 evbuffer sendSwapBuf; evbuffer *buf = &sendSwapBuf; { lock_guard_t<> lock(m_sendBufLock); evbuffer_add_buffer(buf, &m_sendBuf); m_isWaitingWrite = false; } // 2. 尝试发送数据,若数据未能全部发送,则注册写事件 int left = trySend(buf); if (left < 0) { // 发送异常: 则关闭连接 // LOG_ERROR << m_logic->name() << " = socket<" << m_sockfd << "> trySend fail, ret = " << left; m_error = true; this ->close(); return; } else if (left > 0) { // 数据未能全部发送: 则将残余数据重新拷贝到发送缓冲区的头部以保持正确的发送顺序 // LOG_ERROR << m_logic->name() << " register write, socket = " << m_sockfd; { lock_guard_t<> lock(m_sendBufLock); int size = evbuffer_get_length(&m_sendBuf); if (size > 0) { evbuffer_prepend_buffer(&m_sendBuf, buf); } else { evbuffer_add_buffer(&m_sendBuf, buf); } m_isWaitingWrite = true; } // 注册写事件,以待当本连接可写时再尝试发送 m_net->enableWrite(this); #ifdef WIN // LOG_INFO << m_logic->name() << " register write, m_sendBuf.readableBytes() = " << m_sendBuf.readableBytes(); #endif } else { // 本次数据已发送成功: 检查本连接是否已<待关闭>,是的话,若本次数据已全部发送成功且在此期间没有新的数据等待发送,则执行close操作 bool isWaitingClose = false; { lock_guard_t<> lock(m_sendBufLock); isWaitingClose = (m_isWaitingClose && (0 == evbuffer_get_length(&m_sendBuf))); // if(isWaitingClose) { // LOG_ERROR << m_logic->name() << " isWaitingClose = true, m_sendBuf.size() = " << m_sendBuf.readableBytes() << " && m_isWaitingWrite = " << m_isWaitingWrite; // } } if(isWaitingClose) { close(); } } } void Link::sendBuffer() { if (!isopen()) { return; } // { // lock_guard_t<> lock(m_sendBufLock); // if (m_isWaitingWrite) { // LOG_ERROR << "m_isWaitingWrite = true"; // return; // } // // if (evbuffer_get_length(&m_sendBuf) == 0) { // LOG_ERROR << m_logic->name() << " m_sendBuf.empty(), socket = " << m_sockfd; // return; // } // // m_isWaitingWrite = true; // } // m_net->interruptLoop(); m_net->getTaskQueue()->put(boost::bind(&Link::onSend, this)); } void Link::send(const char *data, int len) { if (!isopen()) { return; } { lock_guard_t<> lock(m_sendBufLock); evbuffer_add(&m_sendBuf, data, len); if (m_isWaitingWrite) { return; } m_isWaitingWrite = true; } this->sendBuffer(); } void Link::send(const char *text) { send(text, strlen(text)); } void Link::send(int msgId, const Message & msg) { if (!isopen()) { return; } int size = msg.ByteSize(); std::string buf; buf.resize(size); msg.SerializeToArray((void*)buf.c_str(), size); this->send(msgId, buf.c_str(), size); } void Link::send(int msgId, const char *data, int len) { if (!isopen()) { return; } NetMsgHead msgHead; msgtool::BuildNetHeader(&msgHead, msgId, len); { lock_guard_t<> lock(m_sendBufLock); evbuffer_add(&m_sendBuf, &msgHead, sizeof(msgHead)); evbuffer_add(&m_sendBuf, data, len); if (m_isWaitingWrite) { return; } m_isWaitingWrite = true; } this->sendBuffer(); } void Link::beginRead(evbuffer *readto) { // m_recvBuf数据取出到readto lock_guard_t<> lock(m_recvBufLock); evbuffer_add_buffer(readto, &m_recvBuf); m_isWaitingRead = false; } void Link::endRead(evbuffer *remain) { // remain数据移动到m_recvBuf前面 int left = evbuffer_get_length(remain); if (left > 0) { lock_guard_t<> lock(m_recvBufLock); int size = evbuffer_get_length(&m_recvBuf); if (size > 0) { evbuffer_prepend_buffer(&m_recvBuf, remain); } else { evbuffer_add_buffer(&m_recvBuf, remain); } } } void Link::handleRead() { if (!isopen()) { LOG_ERROR << m_logic->name() << " != open"; return; } // 记录本次接收数据的总长度 int totalRecvLen = 0; // 循环接收数据直到无法再接收 int nread = 0; do { //nread = evbuffer_read(buf, m_sockfd, -1); nread = ::recv(m_sockfd, m_net->g_recvBuf, MAX_PACKET_LEN, 0); if (nread > 0) { // 成功接收到数据:将本次接收到的数据拷贝到接收缓冲区末尾 { lock_guard_t<> lock(m_recvBufLock); evbuffer_add(&m_recvBuf, m_net->g_recvBuf, nread); } totalRecvLen += nread; } else if (0 == nread) { // eof // 接收到0字节的数据: 说明已检测到对端关闭,此时直接关闭本连接,不再处理未发送的数据 // LOG_WARN << m_logic->name() << " read 0, closed! buffer len = " << m_recvBuf.readableBytes() << ", g_closecnt = " << g_closecnt; m_isPeerClosed = true; this->close(); break; } else { // 发生异常:EAGAIN及EWOULDBLOCK信号说明已接收完毕,EINTR信号应忽略,其余信号说明本连接发生错误 int err = socktool::geterrno(); if(EINTR == err) { // LOG_WARN << "socket<" << m_sockfd << "> error = EINTR " << err; continue; } else if(EAGAIN == err || EWOULDBLOCK == err) { // LOG_WARN << "read task socket<" << m_sockfd << "> EWOULDBLOCK || EAGAIN, err = " << err; break; } else { // LOG_SOCKET_ERR(m_sockfd, err) << m_logic->name() << " recv fail, err = " << err << ", history recv buf size = " << m_recvBuf.readableBytes(); m_error = true; this->close(); break; } } } while(true); if(0 == totalRecvLen) { return; } // 检测业务层是否已存在处理本连接接收数据的任务,若有则无需再次通知业务层,由之前的数据处理任务一并处理本次接收到的所有数据 { lock_guard_t<> lock(m_recvBufLock); if (m_isWaitingRead) { return; } m_isWaitingRead = true; } // 由业务层进行数据接收处理 m_logic->onRecv(this); } void Link::handleWrite() { // LOG_INFO << m_logic->name() << " socket <" << m_sockfd << "> is writable"; if (!isopen()) { return; } #ifdef WIN // windows下select模型属于LT,需要屏蔽可写事件 m_net->disableWrite(this); #endif onSend(); return; } void Link::handleError() { if (m_isPeerClosed || m_error || m_isWaitingClose || m_closed) { return; } int err = socktool::getSocketError(m_sockfd); LOG_SOCKET_ERR(m_sockfd, err) << m_logic->name() << " socket<" << m_sockfd << "> error, m_error = " << m_error << ", m_isWaitingClose=" << m_isWaitingClose << ", m_closed = " << m_closed; m_error = true; this->close(); return; } int Link::trySend(evbuffer *buffer) { size_t nleft = evbuffer_get_length(buffer); int nwritten = 0; // 循环发送数据直到无法再发送 while(nleft > 0) { nwritten = evbuffer_write(buffer, m_sockfd); if (nwritten > 0) { nleft -= nwritten; } else if(SOCKET_ERROR == nwritten) { int err = socktool::geterrno(); switch(err) { case EINTR: // 忽略(正常来说非阻塞socket进行send操作并不会触发EINTR信号,这里以防万一) break; case EAGAIN: #ifdef WIN case EWOULDBLOCK: #endif // 说明已无法再发送,中断发送 return nleft; default: // LOG_SOCKET_ERR(m_sockfd, err) << m_logic->name() << " send fail, err = " << err << ",nleft = " << nleft << ", nwritten = " << nwritten; return -1; } } } return nleft; } NetAddress Link::getLocalAddr() const { return NetAddress(socktool::getLocalAddr(m_sockfd)); } NetAddress Link::getPeerAddr() const { return NetAddress(socktool::getPeerAddr(m_sockfd)); }
1baff3f8b77404dfff9367a5785cbc1c019edb72
fad2f4cbff4d3b0957e63f3e7ee8cf1ce9f00a61
/scientific.h
52783dbbfc4d392967101470469181ade8f02cf8
[]
no_license
yzxhx/yzxhx2
538ab2442b2456a9a408cb54f128eb1a336a3768
34c2192d330ce8046d478eaac9bcbabade57f68a
refs/heads/master
2022-12-11T08:20:05.741176
2020-09-15T23:46:55
2020-09-15T23:46:55
292,030,356
0
0
null
2020-09-10T12:07:00
2020-09-01T15:07:11
C++
UTF-8
C++
false
false
326
h
scientific.h
#ifndef SCIENTIFIC_H #define SCIENTIFIC_H #include <QMainWindow> class scientific : public QMainWindow { Q_OBJECT public: explicit scientific(QWidget *parent = nullptr); public: void sendst(); void sendp(); signals: void sst(); void sp(); public slots: }; #endif // SCIENTIFIC_H
c3b55fe604b47b81dc42f8d9843d535433ae9fc1
f925b7fe5ba4c057f38f4389c12cf8e253a0e8a6
/pylongigecamera.cpp
591c8bfe5c6400ff6dd65dbc98f156ebd5fb5413
[]
no_license
lzj12321/XG_Vision
5b944aaeb917442e4e6f68ed9c1c86122fd9b218
a6ad51dade27d0af18aa85ef7393c4358a77b2a8
refs/heads/master
2020-03-21T05:00:52.642387
2018-06-21T08:26:25
2018-06-21T08:26:25
138,139,802
1
0
null
null
null
null
UTF-8
C++
false
false
12,788
cpp
pylongigecamera.cpp
#include "pylongigecamera.h" #include<QException> #include<QString> #include<iostream> pylonGigeCamera::pylonGigeCamera() { isCameraEverOpened=false; cameraEventPtr=new pylonCameraEventHandler; imageEventPtr=new pylonImageEventHandler; connect(cameraEventPtr,SIGNAL(Esignal_cameraOpened(std::string)),this,SIGNAL(signal_cameraOpened(std::string))); connect(cameraEventPtr,SIGNAL(Esignal_cameraRemoved(std::string)),this,SIGNAL(signal_cameraRemoved(std::string))); connect(imageEventPtr,SIGNAL(Esignal_grabbedImage(std::string,cv::Mat&)),this,SIGNAL(signal_grabbedImage(std::string,cv::Mat&))); } pylonGigeCamera::~pylonGigeCamera() { ////////////在相机掉线的时候自动清除////////////////// //deallcoate the resource when camera offline// } void pylonGigeCamera::PylonEnvInitialize() { PylonInitialize(); } void pylonGigeCamera::PylonEnvTerminate() { PylonTerminate(); } void pylonGigeCamera::EnumerateCameras(std::vector<std::string>& vecCameraSerial) { vecCameraSerial.clear(); CTlFactory& tlFactory = CTlFactory::GetInstance(); DeviceInfoList_t devices; size_t cameraNum=tlFactory.EnumerateDevices(devices); for(size_t i=0;i<cameraNum;++i){ vecCameraSerial.push_back(std::string(devices[i].GetSerialNumber().c_str())); } } bool pylonGigeCamera::connectCamera(const std::string tmpCameraSerialNumber) { cameraStatus=cameraCreate(tmpCameraSerialNumber); if(cameraStatus) cameraInit(); emit signal_connectedCamera(cameraStatus); return cameraStatus; } bool pylonGigeCamera::cameraCreate(const std::string cameraNum) { try { CDeviceInfo cameraInfo; cameraSerialNumber= cameraNum; String_t STR_cameraSerialNum=String_t(cameraNum.c_str()); cameraInfo.SetSerialNumber(STR_cameraSerialNum); if(!isCameraEverOpened) { DeviceInfoList_t tmpCameraInfoList; DeviceInfoList_t detectedCamerDevices; tmpCameraInfoList.push_back(cameraInfo); CTlFactory& cameraFactory = CTlFactory::GetInstance(); if(cameraFactory.EnumerateDevices(detectedCamerDevices,tmpCameraInfoList)>0) { if(!cameraFactory.IsDeviceAccessible(cameraInfo)){ return false; } gigeCamera.Attach(cameraFactory.CreateDevice(detectedCamerDevices[0])); if(gigeCamera.IsPylonDeviceAttached()) { cameraStatus=true; nodemap=&gigeCamera.GetNodeMap(); GenApi::CIntegerPtr heartBeatTimePtr(NULL); heartBeatTimePtr=gigeCamera.GetTLNodeMap().GetNode("HeartbeatTimeout"); int64_t NewValue=1000; int64_t correctedValue = NewValue - (NewValue % heartBeatTimePtr->GetInc()); heartBeatTimePtr->SetValue(correctedValue); return true; } else return false; } else return false; } else { //////////////////////reconnect camera part//////////////////////////// DeviceInfoList_t tmpCameraInfoList; DeviceInfoList_t detectedCamerDevices; tmpCameraInfoList.push_back(openedCameraInfo); CTlFactory& cameraFactory = CTlFactory::GetInstance(); if(cameraFactory.EnumerateDevices(detectedCamerDevices,tmpCameraInfoList)>0) { gigeCamera.Attach(cameraFactory.CreateDevice(detectedCamerDevices[0])); WaitObject::Sleep(250); if(gigeCamera.IsPylonDeviceAttached()) { nodemap=&gigeCamera.GetNodeMap(); cameraStatus=true; return true; } else return false; } else return false; } } catch(GenericException e) { return false; } catch(QException& ex) { return false; } } void pylonGigeCamera::cameraInit() { try { if(!isCameraEverOpened) { gigeCamera.RegisterConfiguration(new CAcquireContinuousConfiguration,RegistrationMode_ReplaceAll,Cleanup_Delete);//注册实时模式 gigeCamera.RegisterConfiguration(cameraEventPtr,RegistrationMode_Append,Cleanup_Delete); gigeCamera.RegisterImageEventHandler(imageEventPtr,RegistrationMode_Append,Cleanup_Delete); } gigeCamera.Open(); if(gigeCamera.IsOpen()) isCameraEverOpened=true; } catch(GenericException ex) { } } void pylonGigeCamera::cameraDestroy() { gigeCamera.DestroyDevice(); } double pylonGigeCamera::getCameraExpose() { try { if(cameraStatus) { CFloatPtr ExpTimeCur(nodemap->GetNode("ExposureTimeAbs")); return ((double)ExpTimeCur->GetValue()); } else return 0; } catch(GenericException& ex) { return 0; } } void pylonGigeCamera::setCameraExpose(double value) { if(cameraStatus) { CEnumerationPtr ExpAuto(nodemap->GetNode("ExposureAuto")); if (IsWritable(ExpAuto)) { ExpAuto->FromString("Off"); } CFloatPtr SetExpTime(nodemap->GetNode("ExposureTimeAbs")); if (value <SetExpTime->GetMin()) { SetExpTime->SetValue(SetExpTime->GetMin()); } else if (value > SetExpTime->GetMax()) { SetExpTime->SetValue(SetExpTime->GetMax()); } else { SetExpTime->SetValue(value); } } } void pylonGigeCamera::cameraStartGrab() { if(cameraStatus) { if(!gigeCamera.IsGrabbing()) gigeCamera.StartGrabbing(GrabStrategy_OneByOne,GrabLoop_ProvidedByInstantCamera); } } void pylonGigeCamera::cameraStopGrab() { if(cameraStatus) { if(gigeCamera.IsGrabbing()) gigeCamera.StopGrabbing(); } } void pylonGigeCamera::setHardWareTrigger() { if(cameraStatus) { CEnumerationPtr triggerSelector(nodemap->GetNode("TriggerSelector")); CEnumerationPtr triggerMode(nodemap->GetNode("TriggerMode")); CEnumerationPtr triggerSource(nodemap->GetNode("TriggerSource")); setCameraDebouncerTime(10000); triggerSelector->FromString("FrameStart"); triggerMode->FromString("On"); triggerSource->FromString("Line1"); } } void pylonGigeCamera::setSoftTrigger() { if(cameraStatus) { CEnumerationPtr triggerSelector(nodemap->GetNode("TriggerSelector")); CEnumerationPtr triggerMode(nodemap->GetNode("TriggerMode")); CEnumerationPtr triggerSource(nodemap->GetNode("TriggerSource")); triggerSelector->FromString("FrameStart"); triggerMode->FromString("On"); triggerSource->FromString("Software"); } } int pylonGigeCamera::getCameraWidth() { if(cameraStatus) { CIntegerPtr CWidth(nodemap->GetNode("SensorWidth")); return CWidth->GetValue(); } else return 0; } void pylonGigeCamera::setCameraWidth(int value) { if(cameraStatus) { CIntegerPtr CHeight(nodemap->GetNode("SensorHeight")); CHeight->SetValue(value); } } int pylonGigeCamera::getCameraHeight() { if(cameraStatus) { CIntegerPtr CHeight(nodemap->GetNode("SensorHeight")); return CHeight->GetValue(); } else return 0; } void pylonGigeCamera::setCameraHeight(int value) { if(cameraStatus) { CIntegerPtr CHeight(nodemap->GetNode("SensorHeight")); CHeight->SetValue(value); } } void pylonGigeCamera::setCameraDebouncerTime(double value) { if(cameraStatus) { CEnumerationPtr Lselector(nodemap->GetNode("LineSelector")); Lselector->SetIntValue(LineSelector_Line1); CFloatPtr lineDeb=nodemap->GetNode("LineDebouncerTimeAbs"); lineDeb->SetValue(value); } } void pylonGigeCamera::closeHardWareTrigger() { if(cameraStatus) { CEnumerationPtr triggerMode(nodemap->GetNode("TriggerMode")); triggerMode->FromString("Off"); } } void pylonGigeCamera::closeSoftTrigger() { if(cameraStatus) { CEnumerationPtr triggerMode(nodemap->GetNode("TriggerMode")); triggerMode->FromString("Off"); } } std::string pylonGigeCamera::getCameraSerialNum()const { return cameraSerialNumber; } double pylonGigeCamera::getCameraFrameRate() { if(cameraStatus) { CFloatPtr FrameRate(nodemap->GetNode("ResultingFrameRateAbs")); return ((double)FrameRate->GetValue()); } else return 0; } void pylonGigeCamera::setCameraFrameRate(double value) { if(cameraStatus) { try { CFloatPtr FrameRate(nodemap->GetNode("ResultingFrameRateAbs")); FrameRate->SetValue(value); } catch(GenericException e) { } } } bool pylonGigeCamera::grabOneImage(cv::Mat&mat) { if(cameraStatus) { if(gigeCamera.IsGrabbing()) cameraStopGrab(); CGrabResultPtr ptrGrabResult; gigeCamera.GrabOne(1000, ptrGrabResult, TimeoutHandling_ThrowException); if(ptrGrabResult->GrabSucceeded()&&ptrGrabResult) { imageEventPtr->getGrabbedMat().copyTo(mat); return true; } } else return false; } void pylonGigeCamera::executeSoftTrigger() { if(cameraStatus) { CEnumerationPtr triggerMode(nodemap->GetNode("TriggerMode")); CEnumerationPtr triggerSource(nodemap->GetNode("TriggerSource")); if(triggerMode->GetIntValue()==1&&triggerSource->GetIntValue()==0) { if (gigeCamera.CanWaitForFrameTriggerReady()) { cameraStartGrab(); if (gigeCamera.WaitForFrameTriggerReady( 500, TimeoutHandling_ThrowException)) { gigeCamera.ExecuteSoftwareTrigger(); } } } } } void pylonGigeCamera::slot_cameraRemoved(const std::string) { cameraStatus=cameraClosed; openedCameraInfo.SetDeviceClass(gigeCamera.GetDeviceInfo().GetDeviceClass()); openedCameraInfo.SetSerialNumber(gigeCamera.GetDeviceInfo().GetSerialNumber()); cameraDestroy(); } pylonImageEventHandler::pylonImageEventHandler() { } void pylonImageEventHandler::OnImageGrabbed(CInstantCamera &camera, const CGrabResultPtr &grabResult) { std::string strCameraNum=std::string(camera.GetDeviceInfo().GetSerialNumber().c_str()); if(grabResult->GrabSucceeded()&&grabResult) { int rows = grabResult->GetHeight(); int columns = grabResult->GetWidth(); uchar* grabPtr=(uchar*)grabResult->GetBuffer(); int nCols = rows*columns; grabbedMat=cv::Mat(rows, columns, CV_8UC1); uchar* matPtr; matPtr =grabbedMat.data; if (grabbedMat.isContinuous()) { for (int i = 0; i < nCols; i++){ matPtr[i] = grabPtr[i]; } emit Esignal_grabbedImage(strCameraNum,grabbedMat); } } } const cv::Mat &pylonImageEventHandler::getGrabbedMat() const { return grabbedMat; } pylonCameraEventHandler::pylonCameraEventHandler() { } void pylonCameraEventHandler::OnCameraDeviceRemoved(CInstantCamera &camera) { std::string strCameraNum=std::string(camera.GetDeviceInfo().GetSerialNumber().c_str()); emit Esignal_cameraRemoved(strCameraNum); camera.DestroyDevice(); camera.DetachDevice(); } void pylonCameraEventHandler::OnOpened(CInstantCamera &camera) { std::string strCameraNum=std::string(camera.GetDeviceInfo().GetSerialNumber().c_str()); emit Esignal_cameraOpened(strCameraNum); } void pylonCameraEventHandler::OnAttach(CInstantCamera &camera) { std::string strCameraNum=std::string(camera.GetDeviceInfo().GetSerialNumber().c_str()); } void pylonCameraEventHandler::OnAttached(CInstantCamera &camera) { std::string strCameraNum=std::string(camera.GetDeviceInfo().GetSerialNumber().c_str()); emit Esignal_cameraOpened(strCameraNum); }
e9655485b785c52d812b93c6e73ab1d07efd6f04
a5a99f646e371b45974a6fb6ccc06b0a674818f2
/FWCore/Framework/interface/PathsAndConsumesOfModules.h
46d709c7bfe6406add579f18699f758a11209029
[ "Apache-2.0" ]
permissive
cms-sw/cmssw
4ecd2c1105d59c66d385551230542c6615b9ab58
19c178740257eb48367778593da55dcad08b7a4f
refs/heads/master
2023-08-23T21:57:42.491143
2023-08-22T20:22:40
2023-08-22T20:22:40
10,969,551
1,006
3,696
Apache-2.0
2023-09-14T19:14:28
2013-06-26T14:09:07
C++
UTF-8
C++
false
false
3,236
h
PathsAndConsumesOfModules.h
#ifndef FWCore_Framework_PathsAndConsumesOfModules_h #define FWCore_Framework_PathsAndConsumesOfModules_h /**\class edm::PathsAndConsumesOfModules Description: See comments in the base class Usage: */ // // Original Author: W. David Dagenhart // Created: 11/5/2014 #include "FWCore/ServiceRegistry/interface/ConsumesInfo.h" #include "FWCore/ServiceRegistry/interface/PathsAndConsumesOfModulesBase.h" #include "FWCore/Framework/interface/ModuleProcessName.h" #include "FWCore/Utilities/interface/BranchType.h" #include <array> #include <memory> #include <string> #include <utility> #include <vector> namespace edm { class ModuleDescription; class ProductRegistry; class Schedule; class PathsAndConsumesOfModules : public PathsAndConsumesOfModulesBase { public: PathsAndConsumesOfModules(); ~PathsAndConsumesOfModules() override; void initialize(Schedule const*, std::shared_ptr<ProductRegistry const>); void removeModules(std::vector<ModuleDescription const*> const& modules); std::vector<ModuleProcessName> const& modulesInPreviousProcessesWhoseProductsAreConsumedBy( unsigned int moduleID) const; private: std::vector<std::string> const& doPaths() const override { return paths_; } std::vector<std::string> const& doEndPaths() const override { return endPaths_; } std::vector<ModuleDescription const*> const& doAllModules() const override { return allModuleDescriptions_; } ModuleDescription const* doModuleDescription(unsigned int moduleID) const override; std::vector<ModuleDescription const*> const& doModulesOnPath(unsigned int pathIndex) const override; std::vector<ModuleDescription const*> const& doModulesOnEndPath(unsigned int endPathIndex) const override; std::vector<ModuleDescription const*> const& doModulesWhoseProductsAreConsumedBy( unsigned int moduleID, BranchType branchType) const override; std::vector<ConsumesInfo> doConsumesInfo(unsigned int moduleID) const override; unsigned int doLargestModuleID() const override; unsigned int moduleIndex(unsigned int moduleID) const; // data members std::vector<std::string> paths_; std::vector<std::string> endPaths_; std::vector<ModuleDescription const*> allModuleDescriptions_; std::vector<std::vector<ModuleDescription const*> > modulesOnPaths_; std::vector<std::vector<ModuleDescription const*> > modulesOnEndPaths_; // Gives a translation from the module ID to the index into the // following data member std::vector<std::pair<unsigned int, unsigned int> > moduleIDToIndex_; std::array<std::vector<std::vector<ModuleDescription const*> >, NumBranchTypes> modulesWhoseProductsAreConsumedBy_; std::vector<std::vector<ModuleProcessName> > modulesInPreviousProcessesWhoseProductsAreConsumedBy_; Schedule const* schedule_; std::shared_ptr<ProductRegistry const> preg_; }; std::vector<ModuleDescription const*> nonConsumedUnscheduledModules( edm::PathsAndConsumesOfModulesBase const& iPnC, std::vector<ModuleProcessName>& consumedByChildren); void checkForModuleDependencyCorrectness(edm::PathsAndConsumesOfModulesBase const& iPnC, bool iPrintDependencies); } // namespace edm #endif
73c3dd5932950d01b56291f59ea85a90ec299567
cf56272527c1859a0c17e152a600882f4ef6fded
/Engine/GraphicsEngine/RasterZsiros/Core/src/multithreading/spinlock.cpp
22479bdd41658b52f27c18209067ffeba9d0322a
[]
no_license
Almahmudrony/ExcessiveEngine
d56d29ba2d7d5fd32efdca6cec64f0e6356a0e46
6e4124e363bbd9ee1ebba0c20c4d71bda986f9df
refs/heads/master
2021-01-01T18:58:16.594424
2017-05-01T18:59:21
2017-05-01T18:59:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,815
cpp
spinlock.cpp
//////////////////////////////////////////////////////////////////////////////// // File: spinlock.cpp // Author: Péter Kardos //////////////////////////////////////////////////////////////////////////////// // See header. // //////////////////////////////////////////////////////////////////////////////// #include "spinlock.h" //////////////////////////////////////////////////////////////////////////////// // mutex member functions //////////////////////////////////////// // constructor spinlock::spinlock() { lock_var = false; } //////////////////////////////////////// // acquire mutex void spinlock::lock() { bool success; // loop infinitely while (true) { // loop until mutex is free while (lock_var != false); // exchange the value success = lock_var.exchange(true); // if the value is false, thus the mutex was previously unlocked, we've acquired it if (success == false) { break; } // if the value is true, the mutex is still locked by some other thread } } //////////////////////////////////////// // try to lock mutex // Only one attempt, and then returns. Does not 'block' the calling thread. // True on successful locking, otherwise false (see cppreference.com). bool spinlock::try_lock() { bool success; // one try to lock this success = lock_var.exchange(true); // previously 'false' means we've just acquired the lock if (success == false) { return true; } else { return false; } } //////////////////////////////////////// // release the mutex // WARNING: There is no fool protection! // It is assumed that the mutex is locked by the calling thread, // if you do it otherwise, your application might die. // Attempt to unlock an already unlocked mutex from any thread is totally safe. void spinlock::unlock() { lock_var.store(false); }
d8a3df5ca37e2fa25afa9098ff5e6457c7da4a8b
f5b146fe9c112cd05cda78cf9c135e588aa51a35
/include/bedroom.hpp
08d64a32aee14917fde2301d04d3a633ffab0516
[]
no_license
bsphair/Cat-Game
d6cad0430b38184e2bbd3c2e1b49acd982695c80
62ff19335030e95fee8f8bdf3b48bfc34342d00a
refs/heads/master
2020-03-21T04:33:09.087471
2019-03-31T23:01:14
2019-03-31T23:01:14
138,114,305
0
0
null
null
null
null
UTF-8
C++
false
false
948
hpp
bedroom.hpp
/**************************************************************************************************************************** ** File Name: bedroom.hpp ** Author: Brian Phair ** Date: March 21, 2017 ** Description: Contains the function declarations of the BedRoom class ****************************************************************************************************************************/ #ifndef BEDROOM_H #define BEDROOM_H class LivingRoom; class BathRoom; class BedRoom : public Room { protected: bool isHumanIsAsleep; int humanAsleepStrength; bool alarmClockIsOnNightStand; public: BedRoom(); virtual ~BedRoom(); void setBedRoomWalls(LivingRoom* , BathRoom*); bool getIsHumanAsleep(); void wakeHumanUp(int); int getHumanSleepStrength(); bool getisAlarmClockOnNightStand(); void changeAlarmClockPosition(); }; #endif // BEDROOM_H
7e9f79ac53c40620b228f3572060f460c46efe6d
97bc34cfaa815a00926cf0fe6e9babf30bad0fb4
/express_num_as_sum_of_two_primes.cpp
d69ffdc34d7960a041767e22cc02d85dd181a2f7
[]
no_license
sreekv514/MyCaptain_CPP
ca407369d5779983d4dbf5af0b61767b15cb7a3d
d2d2c3bde6658a3d53f5ce89b3850fd5b2933e29
refs/heads/master
2022-11-23T23:51:24.090197
2020-07-24T11:01:51
2020-07-24T11:01:51
276,346,741
1
0
null
null
null
null
UTF-8
C++
false
false
1,564
cpp
express_num_as_sum_of_two_primes.cpp
//Program to check whether a number can be expressed as the sum of two prime numbers #include<iostream> using namespace std; void express_sum(int num); int checkprime(int a); int main() { int num; char choice = 'y'; cout<<"\n\tProgram to express any number as the sum of two prime numbers\n"; cout<<"-----------------------------------------------------------------------------\n"; do { cout<<"\n\n\t Enter a positive integer: "; cin>>num; if(checkprime(num)) { cout<<"\n\t "<<num<<" is a prime number. So it cannot be expressed as the sum of 2 prime numbers.\n"; } else { express_sum(num); } cout<<"\n\n\t Would you like to run the program again? Y/N: "; cin>>choice; }while(choice == 'y' || choice=='Y'); cout<<"\n\n\t End of program. Press X to exit...\n"; cin>>choice; return 0; } int checkprime(int a) { if (a <= 1) return 0; for (int i = 2; i < a; i++) { if(a%i == 0) return 0; } return 1; } void express_sum(int num) { int i, j, cnt==0; cout<<"\n\t "; for(i=1, j=num-1; i<num && i<=j; i++, j--) { if(checkprime(i) && checkprime(j)) { cout<<num<<" = "<<i<<" + "<<j<<"\n\t "; ++cnt; continue; } } if(cnt==0) { cout<<num<<" is not a prime number, however it cannot be expressed as a sum of 2 prime numbers.\n"; } }
7767c42ac1e0582ec43619dc197b6e312a513863
d9e3769ece8f45c87c4a1b886112aca20ed89ad9
/app/mainwindow.h
f7db4705310ca061a799835484d3e363d2608f86
[ "Apache-2.0" ]
permissive
mingxin-zheng/CathShapeSense
80535f81b2c5dfcd8211b482d9ce2690d5cf5090
ad4bc8232ad5319c332d895d8eb6e295b695b0a2
refs/heads/master
2023-08-19T10:41:05.796889
2021-09-07T04:29:39
2021-09-07T04:29:39
403,221,129
0
0
null
null
null
null
UTF-8
C++
false
false
2,150
h
mainwindow.h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QTimer> #include "dataSource.h" #include "frontEnd.h" #include "backEnd.h" #include <chrono> enum class AppState { AppState_Unitialized = 0, AppState_Idle, AppState_Running }; enum class SimulationDensity; namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget* parent = 0); ~MainWindow(); public slots: //! Show the licensing dialog void ShowLicenseDialog(); //! Show the 'Open config file...' dialog void ShowOpenConfigDialog(); //! Play/Fake-streaming the dataset void Run(); //! Pause playing dataset void Pause(); //!Updates every part of the GUI (called by ui refresh timer) void UpdateGUI(); private: /*! Open a config file * \param[in] fileName The name of the file including the path */ void OpenConfigFile(const QString& fileName); //! Initialize the scene and objects bool Init(); //! Step to the next frame and update the scene bool Step(); /*! Sets display mode (visibility of actors) according to the current state * \param[in] AppState_Unitialized, AppState_Idle, or AppState_Running */ void SetState(AppState state); Ui::MainWindow* ui; //Main UI QTimer* m_UiRefreshTimer; // Timer that refreshes the UI CatheterPoints::Ptr m_CathPts = nullptr; // Catheter point class BackEnd::Ptr m_BackEnd = nullptr; // Backend optimizer std::string m_Source1FileName; // Dataset 1 filename std::string m_Source2FileName; // Dataset 2 filename DataSource m_Source1; // Fake data source 1 DataSource m_Source2; // Fake data source 2 int m_FrameRate = 30; // frame rate of the system, default 30 Hz int m_KeyFrameInterval = 1; // front end parameter int m_CatheterLengthInMM = 100; // length of the catheter (Unit: mm) AppState m_State = AppState::AppState_Unitialized; // Internal state of the system SimulationDensity m_NumPointSimualation = SimulationDensity::LOW; // front end and back end parameter }; #endif // MAINWINDOW_H
a51d9ee0779166f5fc8bf545f4b92373a9a21862
371c5b952a7d002f2565a51799ce4581a28bd2db
/Chapter4/Chap4_ex14.cpp
650c47680a176d0088757898ec14cbf682b3b778
[]
no_license
tail95/CPP_FromScratch
b1de1022195db7bab89db212336cd8ba315db288
83f40235ecd4e5d89f6a52e551d48a1463c4a9a7
refs/heads/master
2020-08-05T12:32:38.985724
2019-10-23T13:00:07
2019-10-23T13:00:07
212,496,410
0
0
null
null
null
null
UTF-8
C++
false
false
1,322
cpp
Chap4_ex14.cpp
#include <iostream> #include <string> #include <ctime> using namespace std; class Player { string name; public: Player() { this->name = ""; } void setName(string name) { this->name = name; } string getName() { return this->name; } }; class GamblingGame { Player* players; public: GamblingGame(); ~GamblingGame(); void play(); }; GamblingGame::GamblingGame() { string name[2]; cout << "***** 갬블링 게임을 시작합니다. *****" << endl; cout << "첫번째 선수 이름>>"; cin >> name[0]; cout << "두번째 선수 이름>>"; cin >> name[1]; players = new Player[2]; for (int i = 0; i < 2; i++) { players[i].setName(name[i]); } } GamblingGame::~GamblingGame() { delete[] players; } void GamblingGame::play() { int numbers[3]; string tmp; bool flag = false; while (!flag) { for (int i = 0; i < 2; i++) { cout << players[i].getName() << ":<Enter>" << endl; getline(cin, tmp); for (int j = 0; j < 3; j++) { numbers[j] = rand() % 3; cout << '\t' << numbers[j]; } cout << '\t'; if (numbers[0] == numbers[1] && numbers[1] == numbers[2]) { cout << players[i].getName() << "님 승리 !!" << endl; flag = true; break; } else { cout << "아쉽군요!" << endl; } } } } int main() { srand((unsigned)time(0)); GamblingGame gg; gg.play(); }
e41e969459588010c124c4ee0c74f680ff2b9afd
b9d6c4070002da6d0a24f4231e1b276cfd99959f
/wrapper/include/tensorflow/core/status.h
67bc930d754205ac617b51a6cdb1e7912c33357d
[ "Apache-2.0" ]
permissive
andyshrk/Tengine
08b65ba9867676aef93329e1d78f11ab779f0141
91958eaab6d4e251c6da65f40a7e412d8298525a
refs/heads/master
2020-07-15T08:28:12.861903
2019-07-24T09:17:01
2019-07-24T09:17:01
205,521,698
1
1
Apache-2.0
2019-08-31T09:07:08
2019-08-31T09:07:08
null
UTF-8
C++
false
false
1,705
h
status.h
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * License); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (c) 2018, Open AI Lab * Author: jingyou@openailab.com */ #ifndef __TENSORFLOW_CORE_STATUS_H__ #define __TENSORFLOW_CORE_STATUS_H__ #include <memory> namespace tensorflow { class Status { public: Status() {} Status(int code, std::string msg); bool ok() const { return (state_ == NULL); } int code() const { return ok() ? 0 : state_->code; } const std::string& error_message() const { return ok() ? empty_string() : state_->msg; } private: static const std::string& empty_string(); struct State { int code; std::string msg; }; // OK status has a `NULL` state_. Otherwise, `state_` points to // a `State` structure containing the error code and message(s) std::unique_ptr<State> state_; }; } // namespace tensorflow #endif // __TENSORFLOW_CORE_STATUS_H__
2c62553cd5f3174152244636323903aa71ce600a
f8e7acf343289f9bd24bb72fc815f59a90cd4a7c
/state_pattern/state.cpp
376153002e743295c297031d9013544f5fcd1449
[]
no_license
xiaobai2017/DesignPattern
5e8fd84f6b883fda7b1dff9b8b450d6815ef1998
5930aa4404a37811dd3d182c7a23456fa2fbdcfa
refs/heads/master
2020-04-01T06:40:31.378110
2018-12-30T08:16:28
2018-12-30T08:16:28
152,958,476
0
0
null
null
null
null
UTF-8
C++
false
false
1,076
cpp
state.cpp
#include"state.h" #include<iostream> using namespace std; Context::Context() { state_ = ConcreteStateA::Instance(); } Context::~Context() {} void Context::ChangeState(State* state) { state_ = state; } void Context::request() { state_->Handle(this); } State::~State() {} ConcreteStateA* ConcreteStateA::state_a_ = NULL; ConcreteStateA::ConcreteStateA() {} State* ConcreteStateA::Instance() { if (state_a_ == NULL) { state_a_ = new ConcreteStateA; } return state_a_; } void ConcreteStateA::Handle(Context* context) { cout << "doing something in state A...\n" "done.change state to B\n"; context->ChangeState(ConcreteStateB::Instance()); } ConcreteStateB* ConcreteStateB::state_b_ = NULL; ConcreteStateB::ConcreteStateB() {} State* ConcreteStateB::Instance() { if (state_b_ == NULL) { state_b_ = new ConcreteStateB; } return state_b_; } void ConcreteStateB::Handle(Context* context) { cout << "doing something in state B...\n" "done.change state to A\n"; context->ChangeState(ConcreteStateA::Instance()); }
54a4abbfa4b9a489612391f935ae24863572952f
55a4fa8f0fe859d9683b5dd826a9b8378a6503df
/item/sk_server/src/uhandler_default.cpp
d3aee0008d1c9659382963eb8439f3bf2ab7aa88
[]
no_license
rongc5/test
399536df25d3d3e71cac8552e573f6e2447de631
acb4f9254ecf647b8f36743899ae38a901b01aa6
refs/heads/master
2023-06-26T05:38:37.147507
2023-06-15T03:33:08
2023-06-15T03:33:08
33,905,442
2
1
null
null
null
null
UTF-8
C++
false
false
1,327
cpp
uhandler_default.cpp
#include "uhandler_default.h" #include "proc_data.h" void uhandler_default::perform(http_req_head_para * req_head, std::string * recv_body, http_res_head_para * res_head, std::string * send_body) { if (!req_head || !recv_body || !send_body || !res_head) return; proc_data* p_data = proc_data::instance(); int recode; char t_buf[SIZE_LEN_256]; t_buf[0] = '\0'; Document document; Document::AllocatorType& allocator = document.GetAllocator(); Value root(kObjectType); Value data_array(kArrayType); recode = HTPP_REQ_PATH_ERR; Value key(kStringType); Value value(kStringType); key.SetString("recode", allocator); root.AddMember(key, recode, allocator); key.SetString("data", allocator); root.AddMember(key, data_array, allocator); StringBuffer buffer; Writer<StringBuffer> writer(buffer); root.Accept(writer); send_body->append(buffer.GetString()); res_head->_headers.insert(std::make_pair("Date", SecToHttpTime(time(NULL)))); res_head->_headers.insert(std::make_pair("Server", p_data->proc_name)); res_head->_headers.insert(std::make_pair("Connection", "close")); snprintf(t_buf, sizeof(t_buf), "%d", send_body->length()); res_head->_headers.insert(std::make_pair("Content-Length", t_buf)); }
bfc792fff3dfc9d443b5f764c86b492386d01a7d
5ec06dab1409d790496ce082dacb321392b32fe9
/clients/cpp-restsdk/generated/model/ComDayCqMailerDefaultMailServiceProperties.h
709d0ef55fcfdef83ca4e00444ddf18f2527248f
[ "Apache-2.0" ]
permissive
shinesolutions/swagger-aem-osgi
e9d2385f44bee70e5bbdc0d577e99a9f2525266f
c2f6e076971d2592c1cbd3f70695c679e807396b
refs/heads/master
2022-10-29T13:07:40.422092
2021-04-09T07:46:03
2021-04-09T07:46:03
190,217,155
3
3
Apache-2.0
2022-10-05T03:26:20
2019-06-04T14:23:28
null
UTF-8
C++
false
false
4,464
h
ComDayCqMailerDefaultMailServiceProperties.h
/** * Adobe Experience Manager OSGI config (AEM) API * Swagger AEM OSGI is an OpenAPI specification for Adobe Experience Manager (AEM) OSGI Configurations API * * OpenAPI spec version: 1.0.0-pre.0 * Contact: opensource@shinesolutions.com * * NOTE: This class is auto generated by OpenAPI-Generator 3.2.1-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ /* * ComDayCqMailerDefaultMailServiceProperties.h * * */ #ifndef ORG_OPENAPITOOLS_CLIENT_MODEL_ComDayCqMailerDefaultMailServiceProperties_H_ #define ORG_OPENAPITOOLS_CLIENT_MODEL_ComDayCqMailerDefaultMailServiceProperties_H_ #include "../ModelBase.h" #include "ConfigNodePropertyBoolean.h" #include "ConfigNodePropertyInteger.h" #include "ConfigNodePropertyString.h" namespace org { namespace openapitools { namespace client { namespace model { /// <summary> /// /// </summary> class ComDayCqMailerDefaultMailServiceProperties : public ModelBase { public: ComDayCqMailerDefaultMailServiceProperties(); virtual ~ComDayCqMailerDefaultMailServiceProperties(); ///////////////////////////////////////////// /// ModelBase overrides void validate() override; web::json::value toJson() const override; void fromJson(web::json::value& json) override; void toMultipart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& namePrefix) const override; void fromMultiPart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& namePrefix) override; ///////////////////////////////////////////// /// ComDayCqMailerDefaultMailServiceProperties members /// <summary> /// /// </summary> std::shared_ptr<ConfigNodePropertyString> getSmtpHost() const; bool smtpHostIsSet() const; void unsetSmtp_host(); void setSmtpHost(std::shared_ptr<ConfigNodePropertyString> value); /// <summary> /// /// </summary> std::shared_ptr<ConfigNodePropertyInteger> getSmtpPort() const; bool smtpPortIsSet() const; void unsetSmtp_port(); void setSmtpPort(std::shared_ptr<ConfigNodePropertyInteger> value); /// <summary> /// /// </summary> std::shared_ptr<ConfigNodePropertyString> getSmtpUser() const; bool smtpUserIsSet() const; void unsetSmtp_user(); void setSmtpUser(std::shared_ptr<ConfigNodePropertyString> value); /// <summary> /// /// </summary> std::shared_ptr<ConfigNodePropertyString> getSmtpPassword() const; bool smtpPasswordIsSet() const; void unsetSmtp_password(); void setSmtpPassword(std::shared_ptr<ConfigNodePropertyString> value); /// <summary> /// /// </summary> std::shared_ptr<ConfigNodePropertyString> getFromAddress() const; bool fromAddressIsSet() const; void unsetFrom_address(); void setFromAddress(std::shared_ptr<ConfigNodePropertyString> value); /// <summary> /// /// </summary> std::shared_ptr<ConfigNodePropertyBoolean> getSmtpSsl() const; bool smtpSslIsSet() const; void unsetSmtp_ssl(); void setSmtpSsl(std::shared_ptr<ConfigNodePropertyBoolean> value); /// <summary> /// /// </summary> std::shared_ptr<ConfigNodePropertyBoolean> getSmtpStarttls() const; bool smtpStarttlsIsSet() const; void unsetSmtp_starttls(); void setSmtpStarttls(std::shared_ptr<ConfigNodePropertyBoolean> value); /// <summary> /// /// </summary> std::shared_ptr<ConfigNodePropertyBoolean> getDebugEmail() const; bool debugEmailIsSet() const; void unsetDebug_email(); void setDebugEmail(std::shared_ptr<ConfigNodePropertyBoolean> value); protected: std::shared_ptr<ConfigNodePropertyString> m_Smtp_host; bool m_Smtp_hostIsSet; std::shared_ptr<ConfigNodePropertyInteger> m_Smtp_port; bool m_Smtp_portIsSet; std::shared_ptr<ConfigNodePropertyString> m_Smtp_user; bool m_Smtp_userIsSet; std::shared_ptr<ConfigNodePropertyString> m_Smtp_password; bool m_Smtp_passwordIsSet; std::shared_ptr<ConfigNodePropertyString> m_From_address; bool m_From_addressIsSet; std::shared_ptr<ConfigNodePropertyBoolean> m_Smtp_ssl; bool m_Smtp_sslIsSet; std::shared_ptr<ConfigNodePropertyBoolean> m_Smtp_starttls; bool m_Smtp_starttlsIsSet; std::shared_ptr<ConfigNodePropertyBoolean> m_Debug_email; bool m_Debug_emailIsSet; }; } } } } #endif /* ORG_OPENAPITOOLS_CLIENT_MODEL_ComDayCqMailerDefaultMailServiceProperties_H_ */
7738dae0bcdd035d4da09fab9cb43ddf5f0c188f
bfc139bb91b1c505cf4f8843d97d41dc04c675ae
/1325 整除的尾数.cpp
2dc536b3b1d7ba1f14382bdb0a133d21c36cebef
[]
no_license
superYe7/ZCMU-OJ
66683a0beaa065736be0590d4defaf91f2259911
2c8a1730eb5e7ecaf239f0bef084663d98ac3785
refs/heads/master
2020-03-27T23:20:58.707579
2018-09-04T08:20:22
2018-09-04T08:22:07
147,311,659
0
0
null
null
null
null
UTF-8
C++
false
false
422
cpp
1325 整除的尾数.cpp
#include<bits/stdc++.h> #include<algorithm> using namespace std; int main() { int a,b; while(cin>>a>>b) { if (a==0&&b==0) break; int str[100];int k,j=0; for (int i=0;i<100;i++) { int m=a*100+i; if (m%b==0) { str[j]=i;j++; } } for (k=0;k<j;k++) { if (str[k]<10) printf("0%d%c",str[k],k==j-1?'\n':' '); else printf("%d%c",str[k],k==j-1?'\n':' '); } } return 0; }
0e5ebf0d21666a2828aaf2c8b9a09870c6597767
9c7c38e1d7ceafa78896e32616d88b31716d388e
/src/Game/Ship.cpp
2b2f934585f70b5931fe5d2b7ea17e4e50deb240
[]
no_license
Canadadry/Asteroid
329994826045420cc075cda6b48e1679e6f84ad7
a6686247bf36ad88fe63daa184f5fdea044d17a7
refs/heads/master
2020-06-01T09:26:44.828832
2013-12-14T10:56:26
2013-12-14T10:56:26
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
2,997
cpp
Ship.cpp
/* * Ship.cpp * * Asteroid - Copyright (c) 12 fŽvr. 2013 - Jerome Mourey * * 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. * * Created on: 12 fŽvr. 2013 */ #include "Ship.h" #include <Engine/Body.h> #include <Engine/Physics.h> #include <Engine/View.h> #include <Engine/Health.h> #include <Engine/Weapon.h> #include <Game/BonusEntity.h> #include <Game/Gun.h> #include <Game/EntityType.h> #include <Game/AsteroidGame.h> #include <SFML/Graphics/Sprite.hpp> #include <SFML/Graphics/Texture.hpp> #include <cmath> #define PI 3.14151 extern std::string path; Ship::Ship() : Entity() , m_shape(new sf::Sprite ) , m_texture(new sf::Texture) { name = "Ship"; setBody(new Body(this)); body()->x = 400; body()->y = 300; body()->radius = 10; body()->type = EntityType::EntityShip; body()->collisionHandler = this; setPhysics(new Physics(this)); physics()->drag = 0.9; setView(new View(this)); view()->drawable = m_shape; m_texture->loadFromFile(path+"ship.png"); m_shape->setTexture(*m_texture); m_shape->setOrigin(sf::Vector2f(m_texture->getSize().x/2,m_texture->getSize().y/2)); setHealth(new Health(this)); health()->hits = 5; health()->invincibilityFrame = 1000; health()->died.Connect(this,&Ship::onDied); Weapon* weapon = 0; weapon = new Gun(this); setWeapon(weapon); } Ship::~Ship() { if(health()->hits > 0) destroyed(this); delete body(); delete physics(); delete view(); delete weapon(); } bool Ship::HandleCollision(Body* body) { return false; } void Ship::onDied() { destroyed(this); } void Ship::update() { AsteroidGame* agame = (AsteroidGame*)game; agame->shipHealth = health()->hits; if(health()->invincible()) { m_shape->setColor(sf::Color(255,255,255,128)); } else { m_shape->setColor(sf::Color(255,255,255,255)); } } void Ship::setBonus(int bonus) { switch(bonus) { case BonusEntity::HealthBonus : health()->hit(-1);break; case BonusEntity::RayBonus : ((Gun*)weapon())->rayCount++;break; case BonusEntity::PiercingBonus : ((Gun*)weapon())->piercing = true;break; case BonusEntity::LenghtBonus : ((Gun*)weapon())->bulletLifeTime += 5;break; default: break; } }
880f256aef51e4871db194452096d4a6d9cb8e94
0577a46d8d28e1fd8636893bbdd2b18270bb8eb8
/chromium/chrome/browser/ui/views/page_info/accuracy_tip_bubble_view_browsertest.cc
60058acc66b700a0e8ce596f83aa13f1944cc50d
[ "BSD-3-Clause" ]
permissive
ric2b/Vivaldi-browser
388a328b4cb838a4c3822357a5529642f86316a5
87244f4ee50062e59667bf8b9ca4d5291b6818d7
refs/heads/master
2022-12-21T04:44:13.804535
2022-12-17T16:30:35
2022-12-17T16:30:35
86,637,416
166
41
BSD-3-Clause
2021-03-31T18:49:30
2017-03-29T23:09:05
null
UTF-8
C++
false
false
20,829
cc
accuracy_tip_bubble_view_browsertest.cc
// Copyright 2021 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <algorithm> #include <string> #include <utility> #include <vector> #include "base/bind.h" #include "base/callback_helpers.h" #include "base/test/metrics/histogram_tester.h" #include "base/test/scoped_feature_list.h" #include "base/test/simple_test_clock.h" #include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" #include "chrome/browser/accuracy_tips/accuracy_service_factory.h" #include "chrome/browser/engagement/site_engagement_service_factory.h" #include "chrome/browser/metrics/chrome_metrics_service_accessor.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/hats/hats_service_factory.h" #include "chrome/browser/ui/hats/mock_hats_service.h" #include "chrome/browser/ui/page_info/chrome_accuracy_tip_ui.h" #include "chrome/browser/ui/test/test_browser_dialog.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/browser/ui/views/location_bar/location_bar_view.h" #include "chrome/browser/ui/views/page_info/page_info_bubble_view_base.h" #include "chrome/common/url_constants.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "chrome/test/permissions/permission_request_manager_test_api.h" #include "components/accuracy_tips/accuracy_service.h" #include "components/accuracy_tips/accuracy_tip_interaction.h" #include "components/accuracy_tips/features.h" #include "components/history/core/browser/history_types.h" #include "components/safe_browsing/core/common/features.h" #include "components/site_engagement/content/site_engagement_score.h" #include "components/site_engagement/content/site_engagement_service.h" #include "components/strings/grit/components_strings.h" #include "components/ukm/test_ukm_recorder.h" #include "content/public/test/browser_test.h" #include "content/public/test/prerender_test_util.h" #include "net/dns/mock_host_resolver.h" #include "services/metrics/public/cpp/ukm_builders.h" #include "ui/base/l10n/l10n_util.h" #include "ui/events/base_event_utils.h" #include "ui/views/controls/button/button.h" #include "ui/views/test/button_test_api.h" #include "ui/views/test/widget_test.h" #include "ui/views/test/widget_test_api.h" using ::testing::_; namespace { using accuracy_tips::AccuracyTipInteraction; using accuracy_tips::AccuracyTipStatus; const char kAccuracyTipUrl[] = "a.test"; const char kRegularUrl[] = "b.test"; bool IsUIShowing() { return PageInfoBubbleViewBase::BUBBLE_ACCURACY_TIP == PageInfoBubbleViewBase::GetShownBubbleType(); } } // namespace class AccuracyTipBubbleViewBrowserTest : public InProcessBrowserTest { protected: GURL GetUrl(const std::string& host) { return https_server_.GetURL(host, "/title1.html"); } void SetUp() override { https_server_.SetSSLConfig(net::EmbeddedTestServer::CERT_TEST_NAMES); https_server_.ServeFilesFromSourceDirectory(GetChromeTestDataDir()); ASSERT_TRUE(https_server_.Start()); SetUpFeatureList(); // Disable "close on deactivation" since there seems to be an issue with // windows losing focus during tests. views::DisableActivationChangeHandlingForTests(); InProcessBrowserTest::SetUp(); } void SetUpOnMainThread() override { host_resolver()->AddRule("*", "127.0.0.1"); } void ClickExtraButton() { auto* view = PageInfoBubbleViewBase::GetPageInfoBubbleForTesting(); views::test::WidgetDestroyedWaiter waiter(view->GetWidget()); auto* button = static_cast<views::Button*>(view->GetExtraView()); ui::MouseEvent event(ui::ET_MOUSE_PRESSED, gfx::Point(), gfx::Point(), ui::EventTimeForNow(), 0, 0); views::test::ButtonTestApi(button).NotifyClick(event); waiter.Wait(); } base::HistogramTester* histogram_tester() { return &histogram_tester_; } net::EmbeddedTestServer* https_server() { return &https_server_; } private: virtual void SetUpFeatureList() { const base::FieldTrialParams accuracy_tips_params = { {accuracy_tips::features::kSampleUrl.name, GetUrl(kAccuracyTipUrl).spec()}, {accuracy_tips::features::kNumIgnorePrompts.name, "1"}}; const base::FieldTrialParams accuracy_survey_params = { {accuracy_tips::features::kMinPromptCountRequiredForSurvey.name, "2"}, {"probability", "1.000"}}; feature_list_.InitWithFeaturesAndParameters( {{safe_browsing::kAccuracyTipsFeature, accuracy_tips_params}, {accuracy_tips::features::kAccuracyTipsSurveyFeature, accuracy_survey_params}}, {}); } base::test::ScopedFeatureList feature_list_; base::HistogramTester histogram_tester_; net::EmbeddedTestServer https_server_{net::EmbeddedTestServer::TYPE_HTTPS}; }; IN_PROC_BROWSER_TEST_F(AccuracyTipBubbleViewBrowserTest, NoShowOnRegularUrl) { ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GetUrl(kRegularUrl))); EXPECT_FALSE(IsUIShowing()); histogram_tester()->ExpectUniqueSample("Privacy.AccuracyTip.PageStatus", AccuracyTipStatus::kNone, 1); } IN_PROC_BROWSER_TEST_F(AccuracyTipBubbleViewBrowserTest, ShowOnUrlInList) { ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GetUrl(kAccuracyTipUrl))); EXPECT_TRUE(IsUIShowing()); histogram_tester()->ExpectUniqueSample( "Privacy.AccuracyTip.PageStatus", AccuracyTipStatus::kShowAccuracyTip, 1); } IN_PROC_BROWSER_TEST_F(AccuracyTipBubbleViewBrowserTest, DontShowOnUrlInListWithEngagement) { ukm::TestAutoSetUkmRecorder ukm_recorder; const GURL url = GetUrl(kAccuracyTipUrl); auto* engagement_service = site_engagement::SiteEngagementServiceFactory::GetForProfile( browser()->profile()); engagement_service->AddPointsForTesting( GetUrl(kAccuracyTipUrl), site_engagement::SiteEngagementScore::GetMediumEngagementBoundary()); ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); EXPECT_FALSE(IsUIShowing()); histogram_tester()->ExpectUniqueSample( "Privacy.AccuracyTip.PageStatus", AccuracyTipStatus::kHighEnagagement, 1); auto entries = ukm_recorder.GetEntriesByName( ukm::builders::AccuracyTipStatus::kEntryName); EXPECT_EQ(1u, entries.size()); ukm_recorder.ExpectEntrySourceHasUrl(entries[0], url); ukm_recorder.ExpectEntryMetric( entries[0], ukm::builders::AccuracyTipStatus::kStatusName, static_cast<int>(AccuracyTipStatus::kHighEnagagement)); } IN_PROC_BROWSER_TEST_F(AccuracyTipBubbleViewBrowserTest, PressIgnoreButton) { ukm::TestAutoSetUkmRecorder ukm_recorder; const GURL url = GetUrl(kAccuracyTipUrl); ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); EXPECT_TRUE(IsUIShowing()); auto* view = PageInfoBubbleViewBase::GetPageInfoBubbleForTesting(); views::test::WidgetDestroyedWaiter waiter(view->GetWidget()); view->CancelDialog(); waiter.Wait(); EXPECT_FALSE(IsUIShowing()); histogram_tester()->ExpectUniqueSample( "Privacy.AccuracyTip.AccuracyTipInteraction", AccuracyTipInteraction::kClosed, 1); auto status_entries = ukm_recorder.GetEntriesByName( ukm::builders::AccuracyTipStatus::kEntryName); EXPECT_EQ(1u, status_entries.size()); ukm_recorder.ExpectEntrySourceHasUrl(status_entries[0], url); ukm_recorder.ExpectEntryMetric( status_entries[0], ukm::builders::AccuracyTipStatus::kStatusName, static_cast<int>(AccuracyTipStatus::kShowAccuracyTip)); auto interaction_entries = ukm_recorder.GetEntriesByName( ukm::builders::AccuracyTipDialog::kEntryName); EXPECT_EQ(1u, interaction_entries.size()); ukm_recorder.ExpectEntrySourceHasUrl(interaction_entries[0], url); ukm_recorder.ExpectEntryMetric( interaction_entries[0], ukm::builders::AccuracyTipDialog::kInteractionName, static_cast<int>(AccuracyTipInteraction::kClosed)); } // TODO(crbug.com/1363619): Disabled for flakiness. IN_PROC_BROWSER_TEST_F(AccuracyTipBubbleViewBrowserTest, DISABLED_PressEsc) { ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GetUrl(kAccuracyTipUrl))); EXPECT_TRUE(IsUIShowing()); BrowserView* browser_view = BrowserView::GetBrowserViewForBrowser(browser()); LocationBarView* location_bar_view = browser_view->GetLocationBarView(); EXPECT_TRUE(location_bar_view->location_icon_view()->ShouldShowLabel()); EXPECT_EQ(location_bar_view->location_icon_view()->GetText(), l10n_util::GetStringUTF16(IDS_ACCURACY_CHECK_VERBOSE_STATE)); auto* view = PageInfoBubbleViewBase::GetPageInfoBubbleForTesting(); views::test::WidgetDestroyedWaiter waiter(view->GetWidget()); // Simulate esc key pressed. ui::KeyEvent key_event(ui::ET_KEY_PRESSED, ui::VKEY_ESCAPE, ui::EF_NONE); view->GetWidget()->OnKeyEvent(&key_event); waiter.Wait(); EXPECT_FALSE(IsUIShowing()); EXPECT_FALSE(location_bar_view->location_icon_view()->ShouldShowLabel()); EXPECT_TRUE(location_bar_view->location_icon_view()->GetText().empty()); histogram_tester()->ExpectUniqueSample( "Privacy.AccuracyTip.AccuracyTipInteraction", AccuracyTipInteraction::kClosed, 1); } IN_PROC_BROWSER_TEST_F(AccuracyTipBubbleViewBrowserTest, OptOut) { auto* service = AccuracyServiceFactory::GetForProfile(browser()->profile()); base::SimpleTestClock clock; clock.SetNow(base::Time::Now()); service->SetClockForTesting(&clock); // The first time the dialog is shown, it has an "ignore" button. ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GetUrl(kAccuracyTipUrl))); EXPECT_TRUE(IsUIShowing()); ClickExtraButton(); EXPECT_FALSE(IsUIShowing()); histogram_tester()->ExpectUniqueSample( "Privacy.AccuracyTip.AccuracyTipInteraction", AccuracyTipInteraction::kIgnore, 1); // The ui won't show again on an immediate navigation. ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GetUrl(kAccuracyTipUrl))); EXPECT_FALSE(IsUIShowing()); // But a week later it shows up again with an opt-out button. clock.Advance(base::Days(7)); ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GetUrl(kAccuracyTipUrl))); EXPECT_TRUE(IsUIShowing()); ClickExtraButton(); EXPECT_FALSE(IsUIShowing()); histogram_tester()->ExpectTotalCount( "Privacy.AccuracyTip.AccuracyTipInteraction", 2); histogram_tester()->ExpectBucketCount( "Privacy.AccuracyTip.AccuracyTipInteraction", AccuracyTipInteraction::kOptOut, 1); } IN_PROC_BROWSER_TEST_F(AccuracyTipBubbleViewBrowserTest, DisappearOnNavigate) { ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GetUrl(kAccuracyTipUrl))); EXPECT_TRUE(IsUIShowing()); // Tip disappears when navigating somewhere else. auto* view = PageInfoBubbleViewBase::GetPageInfoBubbleForTesting(); views::test::WidgetDestroyedWaiter waiter(view->GetWidget()); ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GetUrl(kRegularUrl))); waiter.Wait(); EXPECT_FALSE(IsUIShowing()); histogram_tester()->ExpectUniqueSample( "Privacy.AccuracyTip.AccuracyTipInteraction", AccuracyTipInteraction::kNoAction, 1); } IN_PROC_BROWSER_TEST_F(AccuracyTipBubbleViewBrowserTest, CloseBrowserWhileTipIsOpened) { ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GetUrl(kAccuracyTipUrl))); EXPECT_TRUE(IsUIShowing()); CloseAllBrowsers(); } IN_PROC_BROWSER_TEST_F(AccuracyTipBubbleViewBrowserTest, DisappearAfterPermissionRequested) { ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GetUrl(kAccuracyTipUrl))); EXPECT_TRUE(IsUIShowing()); // Tip disappears when the site requested permission. auto test_api = std::make_unique<test::PermissionRequestManagerTestApi>(browser()); EXPECT_TRUE(test_api->manager()); test_api->AddSimpleRequest(browser() ->tab_strip_model() ->GetActiveWebContents() ->GetPrimaryMainFrame(), permissions::RequestType::kGeolocation); base::RunLoop().RunUntilIdle(); EXPECT_FALSE(IsUIShowing()); histogram_tester()->ExpectUniqueSample( "Privacy.AccuracyTip.AccuracyTipInteraction", AccuracyTipInteraction::kPermissionRequested, 1); } IN_PROC_BROWSER_TEST_F(AccuracyTipBubbleViewBrowserTest, OpenLearnMoreLink) { ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GetUrl(kAccuracyTipUrl))); EXPECT_TRUE(IsUIShowing()); // Click "learn more" and expect help center to open. auto* view = PageInfoBubbleViewBase::GetPageInfoBubbleForTesting(); content::WebContentsAddedObserver new_tab_observer; views::test::WidgetDestroyedWaiter waiter(view->GetWidget()); view->AcceptDialog(); EXPECT_EQ(GURL(chrome::kSafetyTipHelpCenterURL), new_tab_observer.GetWebContents()->GetVisibleURL()); waiter.Wait(); EXPECT_FALSE(IsUIShowing()); histogram_tester()->ExpectUniqueSample( "Privacy.AccuracyTip.AccuracyTipInteraction", AccuracyTipInteraction::kLearnMore, 1); } // Test is flaky on MSAN. https://crbug.com/1241933 #if defined(MEMORY_SANITIZER) #define MAYBE_SurveyShownAfterShowingTip DISABLED_SurveyShownAfterShowingTip #else #define MAYBE_SurveyShownAfterShowingTip SurveyShownAfterShowingTip #endif IN_PROC_BROWSER_TEST_F(AccuracyTipBubbleViewBrowserTest, MAYBE_SurveyShownAfterShowingTip) { auto* tips_service = AccuracyServiceFactory::GetForProfile(browser()->profile()); auto* hats_service = HatsServiceFactory::GetForProfile(browser()->profile(), true); base::SimpleTestClock clock; clock.SetNow(base::Time::Now()); tips_service->SetClockForTesting(&clock); for (int i = 0; i < accuracy_tips::features::kMinPromptCountRequiredForSurvey.Get(); i++) { clock.Advance(base::Days(7)); ASSERT_TRUE( ui_test_utils::NavigateToURL(browser(), GetUrl(kAccuracyTipUrl))); EXPECT_TRUE(IsUIShowing()); ui_test_utils::NavigateToURLWithDisposition( browser(), GURL(chrome::kChromeUINewTabURL), WindowOpenDisposition::NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP); } // Enable metrics and set the profile creation time to be old enough to ensure // the survey triggering. bool enable_metrics = true; ChromeMetricsServiceAccessor::SetMetricsAndCrashReportingForTesting( &enable_metrics); browser()->profile()->SetCreationTimeForTesting(base::Time::Now() - base::Days(45)); clock.Advance(accuracy_tips::features::kMinTimeToShowSurvey.Get()); ui_test_utils::NavigateToURLWithDisposition( browser(), GURL(chrome::kChromeUINewTabURL), WindowOpenDisposition::NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP); base::RunLoop().RunUntilIdle(); EXPECT_TRUE(hats_service->hats_next_dialog_exists_for_testing()); } IN_PROC_BROWSER_TEST_F(AccuracyTipBubbleViewBrowserTest, SurveyNotShownAfterDeletingHistory) { auto* tips_service = AccuracyServiceFactory::GetForProfile(browser()->profile()); auto* hats_service = HatsServiceFactory::GetForProfile(browser()->profile(), true); base::SimpleTestClock clock; clock.SetNow(base::Time::Now()); tips_service->SetClockForTesting(&clock); for (int i = 0; i < accuracy_tips::features::kMinPromptCountRequiredForSurvey.Get(); i++) { clock.Advance(base::Days(7)); ASSERT_TRUE( ui_test_utils::NavigateToURL(browser(), GetUrl(kAccuracyTipUrl))); EXPECT_TRUE(IsUIShowing()); ui_test_utils::NavigateToURLWithDisposition( browser(), GURL(chrome::kChromeUINewTabURL), WindowOpenDisposition::NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP); } // Enable metrics and set the profile creation time to be old enough to ensure // the survey triggering. bool enable_metrics = true; ChromeMetricsServiceAccessor::SetMetricsAndCrashReportingForTesting( &enable_metrics); browser()->profile()->SetCreationTimeForTesting(base::Time::Now() - base::Days(45)); // Delete all history... tips_service->OnURLsDeleted(nullptr, history::DeletionInfo::ForAllHistory()); clock.Advance(accuracy_tips::features::kMinTimeToShowSurvey.Get()); ui_test_utils::NavigateToURLWithDisposition( browser(), GURL(chrome::kChromeUINewTabURL), WindowOpenDisposition::NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP); base::RunLoop().RunUntilIdle(); // ...and because of that, a survey won't be shown. EXPECT_FALSE(hats_service->hats_next_dialog_exists_for_testing()); } class AccuracyTipBubbleViewHttpBrowserTest : public AccuracyTipBubbleViewBrowserTest { public: GURL GetHttpUrl(const std::string& host) { return embedded_test_server()->GetURL(host, "/title1.html"); } void SetUp() override { ASSERT_TRUE(embedded_test_server()->Start()); AccuracyTipBubbleViewBrowserTest::SetUp(); } private: void SetUpFeatureList() override { const base::FieldTrialParams accuraty_tips_params = { {accuracy_tips::features::kSampleUrl.name, GetHttpUrl(kAccuracyTipUrl).spec()}, {accuracy_tips::features::kNumIgnorePrompts.name, "1"}}; feature_list_.InitWithFeaturesAndParameters( {{safe_browsing::kAccuracyTipsFeature, accuraty_tips_params}}, {}); } net::EmbeddedTestServer https_server_{net::EmbeddedTestServer::TYPE_HTTPS}; base::test::ScopedFeatureList feature_list_; }; IN_PROC_BROWSER_TEST_F(AccuracyTipBubbleViewHttpBrowserTest, ShowOnUrlInListButNotSecure) { ASSERT_TRUE( ui_test_utils::NavigateToURL(browser(), GetHttpUrl(kAccuracyTipUrl))); EXPECT_FALSE(IsUIShowing()); BrowserView* browser_view = BrowserView::GetBrowserViewForBrowser(browser()); LocationBarView* location_bar_view = browser_view->GetLocationBarView(); EXPECT_TRUE(location_bar_view->location_icon_view()->ShouldShowLabel()); EXPECT_EQ(location_bar_view->location_icon_view()->GetText(), l10n_util::GetStringUTF16(IDS_NOT_SECURE_VERBOSE_STATE)); } // Render test for accuracy tip ui. class AccuracyTipBubbleViewDialogBrowserTest : public DialogBrowserTest { public: // DialogBrowserTest: void ShowUi(const std::string& name) override { bool show_opt_out = name != "ignore_button"; ShowAccuracyTipDialog(browser()->tab_strip_model()->GetActiveWebContents(), accuracy_tips::AccuracyTipStatus::kShowAccuracyTip, show_opt_out, base::DoNothing()); } }; IN_PROC_BROWSER_TEST_F(AccuracyTipBubbleViewDialogBrowserTest, InvokeUi_default) { ShowAndVerifyUi(); } IN_PROC_BROWSER_TEST_F(AccuracyTipBubbleViewDialogBrowserTest, InvokeUi_ignore_button) { ShowAndVerifyUi(); } class AccuracyTipBubbleViewPrerenderBrowserTest : public AccuracyTipBubbleViewBrowserTest { public: AccuracyTipBubbleViewPrerenderBrowserTest() : prerender_helper_(base::BindRepeating( &AccuracyTipBubbleViewPrerenderBrowserTest::web_contents, base::Unretained(this))) {} ~AccuracyTipBubbleViewPrerenderBrowserTest() override = default; void SetUp() override { prerender_helper_.SetUp(https_server()); AccuracyTipBubbleViewBrowserTest::SetUp(); } content::WebContents* web_contents() { return browser()->tab_strip_model()->GetActiveWebContents(); } protected: content::test::PrerenderTestHelper prerender_helper_; private: void SetUpFeatureList() override { const base::FieldTrialParams accuraty_tips_params = { {accuracy_tips::features::kSampleUrl.name, GetUrl(kAccuracyTipUrl).spec()}}; feature_list_.InitWithFeaturesAndParameters( {{safe_browsing::kAccuracyTipsFeature, accuraty_tips_params}}, {}); } base::test::ScopedFeatureList feature_list_; }; IN_PROC_BROWSER_TEST_F(AccuracyTipBubbleViewPrerenderBrowserTest, StillShowAfterPrerenderNavigation) { // Generate a Accuracy Tip. ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GetUrl(kAccuracyTipUrl))); EXPECT_TRUE(IsUIShowing()); histogram_tester()->ExpectUniqueSample( "Privacy.AccuracyTip.PageStatus", AccuracyTipStatus::kShowAccuracyTip, 1); // Start a prerender. prerender_helper_.AddPrerender( https_server()->GetURL(kAccuracyTipUrl, "/title2.html")); // Ensure the tip isn't closed by prerender navigation and isn't from the // prerendered page. EXPECT_TRUE(IsUIShowing()); histogram_tester()->ExpectUniqueSample( "Privacy.AccuracyTip.PageStatus", AccuracyTipStatus::kShowAccuracyTip, 1); }
edc408ecd1ca7dcac0818dd279dca753660745b4
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/CMake/CMake-gumtree/Kitware_CMake_repos_basic_block_block_10488.cpp
0949f65fccb44391a836b684ee279ed135d99c85
[]
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
76
cpp
Kitware_CMake_repos_basic_block_block_10488.cpp
(uncompressed_size == (uint64_t)ARCHIVE_LITERAL_LL(-1)) bits_checked += 64
e8a6a6b05aa72a90257580efe0b8ffb3faf48d0b
40be08bbfed4bd6a951c18cc4bc0bf1f00e7e8a6
/test/modulemanager/TestCheckpoint.cpp
393cfbea5462cfce0c08f5dbfa64070697c813a7
[ "BSD-3-Clause" ]
permissive
pulsar-chem/Pulsar-Core
5bf4239c0a0de74d3f12a1c8b9bea2867fd8960c
f8e64e04fdb01947708f098e833600c459c2ff0e
refs/heads/master
2021-01-18T06:51:05.905464
2017-06-04T02:31:44
2017-06-04T02:31:44
46,251,809
0
2
null
2017-05-25T14:59:51
2015-11-16T04:21:59
C++
UTF-8
C++
false
false
2,180
cpp
TestCheckpoint.cpp
#include <pulsar/testing/CppTester.hpp> #include <pulsar/modulemanager/Checkpoint.hpp> #include <pulsar/modulemanager/checkpoint_backends/BDBCheckpointIO.hpp> #include <pulsar/modulebase/TestModule.hpp> #include <pulsar/system/Atom.hpp> using namespace std; using namespace pulsar; Atom H=create_atom({0.0,0.0,0.0},1); struct CXXModule:public TestModule{ CXXModule(ID_t id):TestModule(id){} static bool was_called; void run_test_(){ auto data=cache().get<double>("Some data",false); if(data) { if(!was_called) throw PulsarException("Data shouldn't be there"); else if(std::fabs(*data-2.1)>1e-5) throw PulsarException("Data isn't right"); } else if(was_called) throw PulsarException("Data should be here"); cache().set("Some data",2.1,CacheData::CachePolicy::CheckpointLocal); auto data2=cache().get<Atom>("Other data",false); if(data2) { if(!was_called) throw PulsarException("Data shouldn't be there"); else if(*data2!=H) throw PulsarException("Data isn't right"); } else if(was_called) throw PulsarException("Data should be here"); cache().set("Other data",H,CacheData::CachePolicy::CheckpointLocal); was_called=true; } }; bool CXXModule::was_called=false; TEST_SIMPLE(TestCheckpoint){ CppTester tester("Testing the Checkpoint class"); for(size_t i=0;i<2;++i) { Checkpoint mychk(make_shared<BDBCheckpointIO>("local"), make_shared<BDBCheckpointIO>("global")); auto pmm=make_shared<ModuleManager>(); ModuleManager& mm=*pmm; mm.load_lambda_module<CXXModule>("C++ Module","Module"); if(i==1)mychk.load_local_cache(mm); auto my_mod=mm.get_module<TestModule>("Module",0); auto msg=(i==0?"Checkpointing results":"Reading checkpoint"); tester.test_member_call(msg,true,&TestModule::run_test,my_mod.operator->()); if(i==0)mychk.save_local_cache(mm); } tester.print_results(); return tester.nfailed(); }
0e85b93e3dbf63956b37ce0711dd43cfa6782441
0ec10036e2acb41ca23194ca23ece577a657c47d
/binary-search-tree/maximum-binary-tree.cpp
8a5c4fd649399b0d9486bc260794367061ea7927
[]
no_license
Sneh1999/LeetCode--Competitive-Programming
f1f8f252553e3f1682128b56c06e8ac32bfe4926
cd9f44d79c8f7f87139f789e2dd39b14bdade67f
refs/heads/master
2022-11-09T21:29:27.942182
2020-06-28T23:04:13
2020-06-28T23:04:13
140,437,165
1
0
null
null
null
null
UTF-8
C++
false
false
1,550
cpp
maximum-binary-tree.cpp
/* 654. Maximum Binary Tree Given an integer array with no duplicates. A maximum tree building on this array is defined as follow: The root is the maximum number in the array. The left subtree is the maximum tree constructed from left part subarray divided by the maximum number. The right subtree is the maximum tree constructed from right part subarray divided by the maximum number. Construct the maximum tree by the given array and output the root node of this tree. Example 1: Input: [3,2,1,6,0,5] Output: return the tree root node representing the following tree: 6 / \ 3 5 \ / 2 0 \ 1 */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* constructMaximumBinaryTree(vector<int>& nums) { if (nums.empty()) return NULL; int size = nums.size(); TreeNode *root = new TreeNode(*max_element(nums.begin(),nums.end())); auto element = max_element(nums.begin(),nums.end()); cout<<*element; if(element != begin(nums)){ vector<int> left(begin(nums),element); root->left = constructMaximumBinaryTree(left); } if(element != end(nums) - 1){ vector<int> right(element+1,end(nums)); root->right = constructMaximumBinaryTree(right); } return root; } };
7b3cb9c58f5a4560e2a6a8088f32b664f7b24b1d
db8dfd7ef00432842d187335ca6598341edc1922
/kandinsky/test/rect.cpp
755fce7958dd2633ff2fc93f64a89a94f51a22dd
[]
no_license
EmilieNumworks/epsilon
a60746285ede5a603916e5dc9361a689926f0fbd
bb3baa7466f39f32b285f2d14b6dc1f28e22e7a5
refs/heads/master
2023-01-28T20:49:55.903580
2022-09-02T13:15:05
2022-09-02T13:15:05
102,631,554
1
0
null
2017-09-06T16:20:48
2017-09-06T16:20:48
null
UTF-8
C++
false
false
1,662
cpp
rect.cpp
#include <quiz.h> #include <kandinsky/rect.h> #include <assert.h> QUIZ_CASE(kandinsky_rect_intersect) { KDRect a(-5,-5, 10, 10); KDRect b(0, 0, 10, 10); quiz_assert(a.intersects(b)); quiz_assert(b.intersects(a)); KDRect c = a.intersectedWith(b); KDRect result(0, 0, 5, 5); quiz_assert(c == result); c = b.intersectedWith(a); quiz_assert(c == result); } QUIZ_CASE(kandinsky_rect_union) { KDRect a(-5, -5, 10, 10); KDRect b(0, 0, 10, 10); KDRect c = a.unionedWith(b); quiz_assert(c == KDRect(-5, -5, 15, 15)); } QUIZ_CASE(kandinsky_rect_empty_union) { KDRect a(1, 2, 3, 4); KDRect b(5, 6, 0, 0); KDRect c(-2, -1, 0, 1); KDRect t = a.unionedWith(b); quiz_assert(t == a); t = b.unionedWith(a); quiz_assert(t == a); t = a.unionedWith(c); quiz_assert(t == a); } QUIZ_CASE(kandinsky_rect_difference) { KDRect a(-1, 0, 11, 2); KDRect b(-4, -3, 4, 7); KDRect c(3, -2, 1, 5); KDRect d(7, -3, 5, 7); KDRect e(-2, -1, 13, 5); KDRect f(2, -4, 3, 3); KDRect t = e.differencedWith(a); quiz_assert(t == e); t = a.differencedWith(e); quiz_assert(t == KDRectZero); t = f.differencedWith(d); quiz_assert(t == f); t = f.differencedWith(e); quiz_assert(t == f); t = b.differencedWith(e); quiz_assert(t == b); t = c.differencedWith(f); quiz_assert(t == KDRect(3, -1, 1, 4)); t = c.differencedWith(a); quiz_assert(t == c); t = c.differencedWith(e); quiz_assert(t == KDRect(3, -2, 1, 1)); t = a.differencedWith(b); quiz_assert(t == KDRect(0, 0, 10, 2)); t = a.differencedWith(c); quiz_assert(t == a); t = a.differencedWith(d); quiz_assert(t == KDRect(-1, 0, 8, 2)); }
8dea95361d73070ac28eb7310d86391786bc0000
c301c81f7560125e130a9eb67f5231b3d08a9d67
/lc/lc/2021_target/techiedelight/backtracking/three_partition.cpp
9a5e109410257411b1e975a0c199931b1267110d
[]
no_license
vikashkumarjha/missionpeace
f55f593b52754c9681e6c32d46337e5e4b2d5f8b
7d5db52486c55b48fe761e0616d550439584f199
refs/heads/master
2021-07-11T07:34:08.789819
2021-07-06T04:25:18
2021-07-06T04:25:18
241,745,271
0
0
null
null
null
null
UTF-8
C++
false
false
4,248
cpp
three_partition.cpp
#include <iostream> #include <numeric> using namespace std; // Helper function for solving 3 partition problem. // It returns true if there exist three subsets with a given sum bool subsetSum(int S[], int n, int a, int b, int c) { // return true if the subset is found if (a == 0 && b == 0 && c == 0) { return true; } // base case: no items left if (n < 0) { return false; } // Case 1. The current item becomes part of the first subset bool A = false; if (a - S[n] >= 0) { A = subsetSum(S, n - 1, a - S[n], b, c); } // Case 2. The current item becomes part of the second subset bool B = false; if (!A && (b - S[n] >= 0)) { B = subsetSum(S, n - 1, a, b - S[n], c); } // Case 3. The current item becomes part of the third subset bool C = false; if ((!A && !B) && (c - S[n] >= 0)) { C = subsetSum(S, n - 1, a, b, c - S[n]); } // return true if we get a solution return A || B || C; } // Function for solving the 3–partition problem. It returns true if the given // set `S[0…n-1]` can be divided into three subsets with an equal sum. bool partition(int S[], int n) { if (n < 3) { return false; } // get the sum of all elements in the set int sum = accumulate(S, S + n, 0); // return true if the sum is divisible by 3 and the set `S` can // be divided into three subsets with an equal sum return !(sum % 3) && subsetSum(S, n - 1, sum/3, sum/3, sum/3); } int main() { // Input: a set of integers int S[] = { 7, 3, 2, 1, 5, 4, 8 }; // total number of items in `S` int n = sizeof(S) / sizeof(S[0]); if (partition(S, n)) { cout << "Set can be partitioned"; } else { cout << "Set cannot be partitioned"; } return 0; } // Helper function for solving 3 partition problem. // It returns true if there exist three subsets with the given sum bool subsetSum(int S[], int n, int a, int b, int c, auto &lookup) { // return true if the subset is found if (a == 0 && b == 0 && c == 0) { return true; } // base case: no items left if (n < 0) { return false; } // construct a unique map key from dynamic elements of the input string key = to_string(a) + "|" + to_string(b) + "|" + to_string(c) + "|" + to_string(n); // if the subproblem is seen for the first time, solve it and // store its result in a map if (lookup.find(key) == lookup.end()) { // Case 1. The current item becomes part of the first subset bool A = false; if (a - S[n] >= 0) { A = subsetSum(S, n - 1, a - S[n], b, c, lookup); } // Case 2. The current item becomes part of the second subset bool B = false; if (!A && (b - S[n] >= 0)) { B = subsetSum(S, n - 1, a, b - S[n], c, lookup); } // Case 3. The current item becomes part of the third subset bool C = false; if ((!A && !B) && (c - S[n] >= 0)) { C = subsetSum(S, n - 1, a, b, c - S[n], lookup); } // return true if we get a solution lookup[key] = A || B || C; } // return the subproblem solution from the map return lookup[key]; } // Function for solving the 3–partition problem. It returns true if the given // set `S[0…n-1]` can be divided into three subsets with an equal sum. bool partition(int S[], int n) { if (n < 3) { return false; } // create a map to store solutions to a subproblem unordered_map<string, bool> lookup; // get the sum of all elements in the set int sum = accumulate(S, S + n, 0); // return true if the sum is divisible by 3 and the set `S` can // be divided into three subsets with an equal sum return !(sum % 3) && subsetSum(S, n - 1, sum/3, sum/3, sum/3, lookup); } int main() { // Input: a set of integers int S[] = { 7, 3, 2, 1, 5, 4, 8 }; // total number of items in `S` int n = sizeof(S) / sizeof(S[0]); if (partition(S, n)) { cout << "Set can be partitioned"; } else { cout << "Set cannot be partitioned"; } return 0; }
62da30d8af33321e4a985e8ebb6244147b697ea2
e2a61dd27d06135b8fa39ba522383fefef38a3d7
/include/CountrySolution.h
5f346940417079470586de59a2423fb5edd8f86b
[]
no_license
SAGNA01/ImperialistComptetiveAlgorithm-
8f9175abb6041885424d5648a34f8f8872b21af2
23c6ff25ce521681ec27f3ad19219244f078ed5b
refs/heads/main
2023-02-08T18:39:40.690842
2021-01-06T01:32:48
2021-01-06T01:32:48
314,642,044
0
0
null
null
null
null
UTF-8
C++
false
false
757
h
CountrySolution.h
#ifndef COUNTRYSOLUTION_H #define COUNTRYSOLUTION_H #include <cmath> #include"Problem.h" #include<vector> #include <ctime> class CountrySolution { public: CountrySolution(const Problem& pbm); CountrySolution(const CountrySolution& sol); virtual ~CountrySolution(); const Problem& pbm() const; CountrySolution& operator = (const CountrySolution& sol); void initialize(); double fitness(); double get_fitness(); bool isColony() const; void setisColony() ; void setCountry(vector<double>& country); vector<double>& getCountry(); private: vector<double> _Country; bool is_Colony = false; double _current_fitness; const Problem& _pbm; }; #endif // COUNTRYSOLUTION_H
74c3baf4a2afda6e9b75d72cec78f75bb07da067
6358f1b0b4f97f448ca5d8a5c00e99bc0bd85d70
/EmojicodeCompiler/Types/Type.cpp
ccb918957f1f666a76d55eae40eaca02db932b3d
[ "LicenseRef-scancode-warranty-disclaimer", "Artistic-2.0" ]
permissive
darkmastermindz/emojicode
1aaadd9bc262e326c5e9e67dba961f03bb0da68f
12f8b06bf8b58548f854bcbec655b437c50a1dd7
refs/heads/master
2021-07-05T11:14:14.493895
2017-09-26T15:01:13
2017-09-26T15:01:13
105,840,024
1
0
null
2017-10-05T02:08:18
2017-10-05T02:08:18
null
UTF-8
C++
false
false
23,930
cpp
Type.cpp
// // Type.c // Emojicode // // Created by Theo Weidmann on 04.03.15. // Copyright (c) 2015 Theo Weidmann. All rights reserved. // #include "Type.hpp" #include "../EmojicodeCompiler.hpp" #include "../Functions/Function.hpp" #include "Class.hpp" #include "CommonTypeFinder.hpp" #include "Enum.hpp" #include "Protocol.hpp" #include "TypeContext.hpp" #include "ValueType.hpp" #include <algorithm> #include <cstring> #include <vector> namespace EmojicodeCompiler { Class *CL_STRING; Class *CL_LIST; Class *CL_DATA; Class *CL_DICTIONARY; Protocol *PR_ENUMERATEABLE; Protocol *PR_ENUMERATOR; ValueType *VT_BOOLEAN; ValueType *VT_SYMBOL; ValueType *VT_INTEGER; ValueType *VT_DOUBLE; Type::Type(Protocol *protocol, bool optional) : typeContent_(TypeType::Protocol), typeDefinition_(protocol), optional_(optional) {} Type::Type(Enum *enumeration, bool optional) : typeContent_(TypeType::Enum), typeDefinition_(enumeration), optional_(optional) {} Type::Type(Extension *extension) : typeContent_(TypeType::Extension), typeDefinition_(extension), optional_(false) {} Type::Type(ValueType *valueType, bool optional) : typeContent_(TypeType::ValueType), typeDefinition_(valueType), optional_(optional), mutable_(false) { for (size_t i = 0; i < valueType->genericParameterCount(); i++) { genericArguments_.emplace_back(false, i, valueType); } } Type::Type(Class *klass, bool optional) : typeContent_(TypeType::Class), typeDefinition_(klass), optional_(optional) { for (size_t i = 0; i < klass->genericParameterCount() + klass->superGenericArguments().size(); i++) { genericArguments_.emplace_back(false, i, klass); } } Class* Type::eclass() const { return dynamic_cast<Class *>(typeDefinition_); } Protocol* Type::protocol() const { return dynamic_cast<Protocol *>(typeDefinition_); } Enum* Type::eenum() const { return dynamic_cast<Enum *>(typeDefinition_); } ValueType* Type::valueType() const { return dynamic_cast<ValueType *>(typeDefinition_); } TypeDefinition* Type::typeDefinition() const { return typeDefinition_; } bool Type::canHaveGenericArguments() const { return type() == TypeType::Class || type() == TypeType::Protocol || type() == TypeType::ValueType; } void Type::sortMultiProtocolType() { std::sort(genericArguments_.begin(), genericArguments_.end(), [](const Type &a, const Type &b) { return a.protocol()->index < b.protocol()->index; }); } size_t Type::genericVariableIndex() const { if (type() != TypeType::GenericVariable && type() != TypeType::LocalGenericVariable) { throw std::domain_error("Tried to get reference from non-reference type"); } return genericArgumentIndex_; } bool Type::allowsMetaType() const { return type() == TypeType::Class || type() == TypeType::Enum || type() == TypeType::ValueType; } Type Type::resolveReferenceToBaseReferenceOnSuperArguments(const TypeContext &typeContext) const { TypeDefinition *c = typeContext.calleeType().typeDefinition(); Type t = *this; // Try to resolve on the generic arguments to the superclass. while (t.type() == TypeType::GenericVariable && c->canBeUsedToResolve(t.typeDefinition()) && t.genericVariableIndex() < c->superGenericArguments().size()) { Type tn = c->superGenericArguments()[t.genericVariableIndex()]; if (tn.type() == TypeType::GenericVariable && tn.genericVariableIndex() == t.genericVariableIndex() && tn.typeDefinition() == t.typeDefinition()) { break; } t = tn; } return t; } Type Type::resolveOnSuperArgumentsAndConstraints(const TypeContext &typeContext) const { if (typeContext.calleeType().type() == TypeType::NoReturn) { return *this; } TypeDefinition *c = typeContext.calleeType().typeDefinition(); Type t = *this; if (type() == TypeType::NoReturn) { return t; } bool optional = t.optional(); bool box = t.storageType() == StorageType::Box; // Try to resolve on the generic arguments to the superclass. while (t.type() == TypeType::GenericVariable && t.genericVariableIndex() < c->superGenericArguments().size()) { t = c->superGenericArguments()[t.genericArgumentIndex_]; } while (t.type() == TypeType::LocalGenericVariable && typeContext.function() == t.localResolutionConstraint_) { t = typeContext.function()->constraintForIndex(t.genericArgumentIndex_); } while (t.type() == TypeType::GenericVariable && typeContext.calleeType().typeDefinition()->canBeUsedToResolve(t.typeDefinition())) { t = typeContext.calleeType().typeDefinition()->constraintForIndex(t.genericArgumentIndex_); } if (optional) { t.setOptional(); } if (box) { t.forceBox_ = true; } return t; } Type Type::resolveOn(const TypeContext &typeContext) const { Type t = *this; if (type() == TypeType::NoReturn) { return t; } bool optional = t.optional(); bool box = t.storageType() == StorageType::Box; while (t.type() == TypeType::LocalGenericVariable && typeContext.function() == t.localResolutionConstraint_ && typeContext.functionGenericArguments() != nullptr) { t = (*typeContext.functionGenericArguments())[t.genericVariableIndex()]; } if (typeContext.calleeType().canHaveGenericArguments()) { while (t.type() == TypeType::GenericVariable && typeContext.calleeType().typeDefinition()->canBeUsedToResolve(t.typeDefinition())) { Type tn = typeContext.calleeType().genericArguments_[t.genericVariableIndex()]; if (tn.type() == TypeType::GenericVariable && tn.genericVariableIndex() == t.genericVariableIndex() && tn.typeDefinition() == t.typeDefinition()) { break; } t = tn; } } if (optional) { t.setOptional(); } for (auto &arg : t.genericArguments_) { arg = arg.resolveOn(typeContext); } if (box) { t.forceBox_ = true; } return t; } bool Type::identicalGenericArguments(Type to, const TypeContext &typeContext, std::vector<CommonTypeFinder> *ctargs) const { for (size_t i = to.typeDefinition()->superGenericArguments().size(); i < to.genericArguments().size(); i++) { if (!this->genericArguments_[i].identicalTo(to.genericArguments_[i], typeContext, ctargs)) { return false; } } return true; } bool Type::compatibleTo(const Type &to, const TypeContext &tc, std::vector<CommonTypeFinder> *ctargs) const { if (type() == TypeType::Error) { return to.type() == TypeType::Error && genericArguments()[0].identicalTo(to.genericArguments()[0], tc, ctargs) && genericArguments()[1].compatibleTo(to.genericArguments()[1], tc); } if (to.type() == TypeType::Something) { return true; } if (to.meta_ != meta_) { return false; } if (this->optional() && !to.optional()) { return false; } if ((this->type() == TypeType::GenericVariable && to.type() == TypeType::GenericVariable) || (this->type() == TypeType::LocalGenericVariable && to.type() == TypeType::LocalGenericVariable)) { return (this->genericVariableIndex() == to.genericVariableIndex() && this->typeDefinition() == to.typeDefinition()) || this->resolveOnSuperArgumentsAndConstraints(tc) .compatibleTo(to.resolveOnSuperArgumentsAndConstraints(tc), tc, ctargs); } if (type() == TypeType::GenericVariable) { return resolveOnSuperArgumentsAndConstraints(tc).compatibleTo(to, tc, ctargs); } if (type() == TypeType::LocalGenericVariable) { return ctargs != nullptr || resolveOnSuperArgumentsAndConstraints(tc).compatibleTo(to, tc, ctargs); } switch (to.type()) { case TypeType::GenericVariable: return compatibleTo(to.resolveOnSuperArgumentsAndConstraints(tc), tc, ctargs); case TypeType::LocalGenericVariable: if (ctargs != nullptr) { (*ctargs)[to.genericVariableIndex()].addType(*this, tc); return true; } return this->compatibleTo(to.resolveOnSuperArgumentsAndConstraints(tc), tc, ctargs); case TypeType::Class: return type() == TypeType::Class && eclass()->inheritsFrom(to.eclass()) && identicalGenericArguments(to, tc, ctargs); case TypeType::ValueType: return type() == TypeType::ValueType && typeDefinition() == to.typeDefinition() && identicalGenericArguments(to, tc, ctargs); case TypeType::Enum: return type() == TypeType::Enum && eenum() == to.eenum(); case TypeType::Someobject: return type() == TypeType::Class || type() == TypeType::Someobject; case TypeType::Error: return compatibleTo(to.genericArguments()[1], tc); case TypeType::MultiProtocol: return isCompatibleToMultiProtocol(to, tc, ctargs); case TypeType::Protocol: return isCompatibleToProtocol(to, tc, ctargs); case TypeType::Callable: return isCompatibleToCallable(to, tc, ctargs); case TypeType::NoReturn: return type() == TypeType::NoReturn; default: break; } return false; } bool Type::isCompatibleToMultiProtocol(const Type &to, const TypeContext &ct, std::vector<CommonTypeFinder> *ctargs) const { if (type() == TypeType::MultiProtocol) { return std::equal(protocols().begin(), protocols().end(), to.protocols().begin(), to.protocols().end(), [ct, ctargs](const Type &a, const Type &b) { return a.compatibleTo(b, ct, ctargs); }); } return std::all_of(to.protocols().begin(), to.protocols().end(), [this, ct](const Type &p) { return compatibleTo(p, ct); }); } bool Type::isCompatibleToProtocol(const Type &to, const TypeContext &ct, std::vector<CommonTypeFinder> *ctargs) const { if (type() == TypeType::Class) { for (Class *a = this->eclass(); a != nullptr; a = a->superclass()) { for (auto &protocol : a->protocols()) { if (protocol.resolveOn(TypeContext(*this)).compatibleTo(to.resolveOn(ct), ct, ctargs)) { return true; } } } return false; } if (type() == TypeType::ValueType || type() == TypeType::Enum) { for (auto &protocol : typeDefinition()->protocols()) { if (protocol.resolveOn(TypeContext(*this)).compatibleTo(to.resolveOn(ct), ct, ctargs)) { return true; } } return false; } if (type() == TypeType::Protocol) { return this->typeDefinition() == to.typeDefinition() && identicalGenericArguments(to, ct, ctargs); } return false; } bool Type::isCompatibleToCallable(const Type &to, const TypeContext &ct, std::vector<CommonTypeFinder> *ctargs) const { if (type() == TypeType::Callable) { if (genericArguments_[0].compatibleTo(to.genericArguments_[0], ct, ctargs) && to.genericArguments_.size() == genericArguments_.size()) { for (size_t i = 1; i < to.genericArguments_.size(); i++) { if (!to.genericArguments_[i].compatibleTo(genericArguments_[i], ct, ctargs)) { return false; } } return true; } } return false; } bool Type::identicalTo(Type to, const TypeContext &tc, std::vector<CommonTypeFinder> *ctargs) const { if (optional() != to.optional()) { return false; } if (ctargs != nullptr && to.type() == TypeType::LocalGenericVariable) { (*ctargs)[to.genericVariableIndex()].addType(*this, tc); return true; } if (type() == to.type()) { switch (type()) { case TypeType::Class: case TypeType::Protocol: case TypeType::ValueType: return typeDefinition() == to.typeDefinition() && identicalGenericArguments(to, tc, ctargs); case TypeType::Callable: return to.genericArguments_.size() == this->genericArguments_.size() && identicalGenericArguments(to, tc, ctargs); case TypeType::Enum: return eenum() == to.eenum(); case TypeType::GenericVariable: case TypeType::LocalGenericVariable: return resolveReferenceToBaseReferenceOnSuperArguments(tc).genericVariableIndex() == to.resolveReferenceToBaseReferenceOnSuperArguments(tc).genericVariableIndex(); case TypeType::Something: case TypeType::Someobject: case TypeType::NoReturn: return true; case TypeType::Error: return genericArguments_[0].identicalTo(to.genericArguments_[0], tc, ctargs) && genericArguments_[1].identicalTo(to.genericArguments_[1], tc, ctargs); case TypeType::MultiProtocol: return std::equal(protocols().begin(), protocols().end(), to.protocols().begin(), to.protocols().end(), [&tc, ctargs](const Type &a, const Type &b) { return a.identicalTo(b, tc, ctargs); }); case TypeType::StorageExpectation: case TypeType::Extension: return false; } } return false; } // MARK: Storage int Type::size() const { int basesize = 0; switch (storageType()) { case StorageType::SimpleOptional: basesize = 1; case StorageType::Simple: switch (type()) { case TypeType::ValueType: case TypeType::Enum: return basesize + typeDefinition()->size(); case TypeType::Callable: case TypeType::Class: case TypeType::Someobject: return basesize + 1; case TypeType::Error: if (genericArguments()[1].storageType() == StorageType::SimpleOptional) { return std::max(2, genericArguments()[1].size()); } return std::max(1, genericArguments()[1].size()) + basesize; case TypeType::NoReturn: return 0; default: throw std::logic_error("Type is wrongly simply stored"); } case StorageType::Box: return 4; default: throw std::logic_error("Type has invalid storage type"); } } StorageType Type::storageType() const { if (forceBox_ || requiresBox()) { return StorageType::Box; } if (type() == TypeType::Error) { return StorageType::SimpleOptional; } return optional() ? StorageType::SimpleOptional : StorageType::Simple; } EmojicodeInstruction Type::boxIdentifier() const { EmojicodeInstruction value; switch (type()) { case TypeType::ValueType: case TypeType::Enum: value = valueType()->boxIdFor(genericArguments_); break; case TypeType::Callable: case TypeType::Class: case TypeType::Someobject: value = T_OBJECT; break; case TypeType::NoReturn: case TypeType::Protocol: case TypeType::MultiProtocol: case TypeType::Something: case TypeType::GenericVariable: case TypeType::LocalGenericVariable: case TypeType::Error: return 0; // This can only be executed in the case of a semantic error, return any value case TypeType::StorageExpectation: case TypeType::Extension: throw std::logic_error("Box identifier for StorageExpectation/Extension"); } return remotelyStored() ? value | REMOTE_MASK : value; } bool Type::requiresBox() const { switch (type()) { case TypeType::ValueType: case TypeType::Enum: case TypeType::Callable: case TypeType::Class: case TypeType::Someobject: case TypeType::NoReturn: case TypeType::StorageExpectation: case TypeType::Extension: return false; case TypeType::Error: return genericArguments()[1].storageType() == StorageType::Box; case TypeType::Something: case TypeType::GenericVariable: case TypeType::LocalGenericVariable: case TypeType::Protocol: case TypeType::MultiProtocol: return true; } } bool Type::isReferencable() const { switch (type()) { case TypeType::Callable: case TypeType::Class: case TypeType::Someobject: case TypeType::GenericVariable: case TypeType::LocalGenericVariable: return storageType() != StorageType::Simple; case TypeType::NoReturn: return false; case TypeType::ValueType: case TypeType::Enum: case TypeType::Protocol: case TypeType::MultiProtocol: case TypeType::Something: case TypeType::Error: return true; case TypeType::StorageExpectation: case TypeType::Extension: throw std::logic_error("isReferenceWorthy for StorageExpectation/Extension"); } } template <typename T, typename... Us> void Type::objectVariableRecords(int index, std::vector<T> *information, Us... args) const { switch (type()) { case TypeType::ValueType: { if (storageType() == StorageType::Box) { information->push_back(T(index, ObjectVariableType::Box, args...)); return; } auto optional = storageType() == StorageType::SimpleOptional; auto size = information->size(); for (auto variable : valueType()->instanceScope().map()) { // TODO: auto vindex = index + variable.second.id() + (optional ? 1 : 0); // variable.second.type().objectVariableRecords(vindex, information, args...); } if (optional) { auto info = T(static_cast<unsigned int>(information->size() - size), index, ObjectVariableType::ConditionalSkip, args...); information->insert(information->begin() + size, info); } return; } case TypeType::Class: case TypeType::Someobject: case TypeType::Callable: case TypeType::Protocol: case TypeType::MultiProtocol: case TypeType::Something: case TypeType::GenericVariable: case TypeType::LocalGenericVariable: case TypeType::Error: // Is or may be an object pointer switch (storageType()) { case StorageType::SimpleOptional: information->push_back(T(index + 1, index, ObjectVariableType::Condition, args...)); return; case StorageType::Simple: information->push_back(T(index, ObjectVariableType::Simple, args...)); return; case StorageType::Box: information->push_back(T(index, ObjectVariableType::Box, args...)); return; default: throw std::domain_error("invalid storage type"); } case TypeType::Enum: case TypeType::NoReturn: case TypeType::StorageExpectation: case TypeType::Extension: return; // Can't be object pointer } } template void Type::objectVariableRecords(int, std::vector<ObjectVariableInformation>*) const; template void Type::objectVariableRecords(int, std::vector<FunctionObjectVariableInformation>*, InstructionCount, InstructionCount) const; // MARK: Type Visulisation std::string Type::typePackage() const { switch (this->type()) { case TypeType::Class: case TypeType::ValueType: case TypeType::Protocol: case TypeType::Enum: return typeDefinition()->package()->name(); case TypeType::NoReturn: case TypeType::Something: case TypeType::Someobject: case TypeType::GenericVariable: case TypeType::LocalGenericVariable: case TypeType::Callable: case TypeType::MultiProtocol: // should actually never come in here case TypeType::Error: return ""; case TypeType::StorageExpectation: case TypeType::Extension: throw std::logic_error("typePackage for StorageExpectation/Extension"); } } void Type::typeName(Type type, const TypeContext &typeContext, std::string &string, bool package) const { if (type.meta_) { string.append("🔳"); } if (type.optional()) { string.append("🍬"); } if (package) { string.append(type.typePackage()); } switch (type.type()) { case TypeType::Class: case TypeType::Protocol: case TypeType::Enum: case TypeType::ValueType: string.append(utf8(type.typeDefinition()->name())); break; case TypeType::MultiProtocol: string.append("🍱"); for (auto &protocol : type.protocols()) { typeName(protocol, typeContext, string, package); } string.append("🍱"); return; case TypeType::NoReturn: string.append("✨"); return; case TypeType::Something: string.append("⚪️"); return; case TypeType::Someobject: string.append("🔵"); return; case TypeType::Callable: string.append("🍇"); for (size_t i = 1; i < type.genericArguments_.size(); i++) { typeName(type.genericArguments_[i], typeContext, string, package); } string.append("➡️"); typeName(type.genericArguments_[0], typeContext, string, package); string.append("🍉"); return; case TypeType::Error: string.append("🚨"); typeName(type.genericArguments_[0], typeContext, string, package); typeName(type.genericArguments_[1], typeContext, string, package); return; case TypeType::GenericVariable: if (typeContext.calleeType().canHaveGenericArguments()) { auto str = typeContext.calleeType().typeDefinition()->findGenericName(type.genericVariableIndex()); string.append(utf8(str)); } else { string.append("T" + std::to_string(type.genericVariableIndex()) + "?"); } return; case TypeType::LocalGenericVariable: if (typeContext.function() != nullptr) { string.append(utf8(typeContext.function()->findGenericName(type.genericVariableIndex()))); } else { string.append("L" + std::to_string(type.genericVariableIndex()) + "?"); } return; case TypeType::StorageExpectation: case TypeType::Extension: return; } if (type.canHaveGenericArguments()) { for (size_t i = type.typeDefinition()->superGenericArguments().size(); i < type.genericArguments().size(); i++) { string.append("🐚"); typeName(type.genericArguments()[i], typeContext, string, package); } } } std::string Type::toString(const TypeContext &typeContext, bool package) const { std::string string; typeName(*this, typeContext, string, package); return string; } } // namespace EmojicodeCompiler
eb020bae8b5152dac84aa55f04c14005ba03781a
8bd162170a6e0411ba5c6722f7e9671e4ec23a39
/include/Wisp.h
bc730e3b13813376c6ea4272cf78a1367eff7f3d
[]
no_license
Muzamba/RenialaAlternativo
43a17152b04731107f3451933afe21c6c1a40c8b
969bc0b4eecf910ee719598c1540e793babe7824
refs/heads/master
2020-06-14T20:49:29.467470
2019-07-15T14:49:31
2019-07-15T14:49:31
195,121,845
0
0
null
null
null
null
UTF-8
C++
false
false
490
h
Wisp.h
#ifndef WISP_H #define WISP_H #include "Component.h" #include "Player.h" #include "Geometric.h" #include <memory> class Wisp : public Component { public: Wisp(GameObject& associated, std::weak_ptr<GameObject> player, bool fase2 = false); void Update(float dt) override; void Render() override; bool Is(std::string type) override; bool fase2; private: std::weak_ptr<GameObject> player; Vec2 posRel; GameObject* luz; bool animacao; }; #endif //WISP_H
a608d505c364c76a88401575bf261389264f5daa
a22aca3b49dd00162bd38c387e12e9c13b4b8eb0
/arena2d-sim/level/WandererBipedal.hpp
f576043b5937cf8067e629fee3b9d185432fa6a5
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Sirupli/arena2D
b2289331aa583802971c46ffd602ccf34d035185
2214754fe8e9358fa8065be5187d73104949dc4f
refs/heads/master
2023-01-05T19:38:51.073509
2020-10-26T15:49:24
2020-10-26T15:49:24
295,663,771
0
0
MIT
2020-10-26T15:50:02
2020-09-15T08:29:25
C++
UTF-8
C++
false
false
623
hpp
WandererBipedal.hpp
#ifndef WANDERERBIPEDAL_H #define WANDERERBIPEDAL_H #include "Wanderer.hpp" #define HUMAN_LEG_SIZE 0.09f #define HUMAN_LEG_DISTANCE 0.04f /* human wanderer represented by two circles (legs) */ class WandererBipedal : public Wanderer{ public: /* constructor */ WandererBipedal(b2World * w,const b2Vec2 & position, float velocity, float change_rate, float stop_rate, float max_angle_change = 60.0f, unsigned int type = 0); /* destructor */ ~WandererBipedal(){} /* return radius of circle surrounding all fixtures */ static float getRadius(){return (HUMAN_LEG_DISTANCE+2*HUMAN_LEG_SIZE)/2.f;} }; #endif
cf5a781f426851b1607937d269bd9fa286b1cf2f
3cdeb3766bc5fd42f7802cc8b11652f2702409e1
/DP/LCS/recursion.cpp
bfa227cbeb46dfba63a0b8eb92a26fbd22b5866c
[]
no_license
abhishek0777/CPCodes
a24167b782baa946bca0a70e4d91322bfec76dad
dcfe863de899d90fa982464104fbeaa94b0bc4db
refs/heads/master
2023-06-02T02:29:13.439508
2021-06-18T08:21:07
2021-06-18T08:21:07
298,038,665
0
1
null
null
null
null
UTF-8
C++
false
false
490
cpp
recursion.cpp
#include<bits/stdc++.h> #define ll long long int #define pb push_back #define mp make_pair #define pii pair<ll,ll> #define ios_base::sync_with_stdio(NULL);cin.tie(false); using namespace std; ll lcs(string s1,string s2,ll m,ll n) { if(m==0||n==0)return 0; if(s1[m-1]==s2[n-1])return (1+lcs(s1,s2,m-1,n-1)); else return max(lcs(s1,s2,m-1,n),lcs(s1,s2,m,n-1)); } int main() { string s1,s2;cin>>s1>>s2; ll m=s1.length(); ll n=s2.length(); cout<<lcs(s1,s2,m,n); }
b2a690ec2aebb4dcb4dc763e631860606d6c0b61
117eb2e15359eebd133052d7370edfce356abaf1
/Normal Skyrim/plugin_example/plugin_example/RawDataHandler.h
b3db27d11b96d6008648a6d2ad9241681fb7d868
[]
no_license
akl-game-lab/exergaming-mod-skyrim
04530ee9ac1711f8a87b86e0d00db35fd08ae02e
e8c0871239f467e76e2ebb1a27084fc140927e0f
refs/heads/master
2021-01-17T03:06:55.930405
2019-11-22T12:15:30
2019-11-22T12:15:30
55,924,945
3
3
null
2017-11-09T21:58:46
2016-04-10T22:04:50
C++
UTF-8
C++
false
false
518
h
RawDataHandler.h
#include "JSONHandler.h" #ifndef __RAWDATAHANDLER_H_INCLUDED__ #define __RAWDATAHANDLER_H_INCLUDED__ #ifdef COMPILE_MYLIBRARY #define MYLIBRARY_EXPORT __declspec(dllexport) #else #define MYLIBRARY_EXPORT __declspec(dllimport) #endif class MYLIBRARY_EXPORT RawDataHandler : public JSONHandler { public: RawDataHandler(); void refresh(); void getDefaultData(); void clear(); int getWorkoutCount(); json getWorkout(int workoutNumber); int getResponseCode(); void setData(json newData); }; #endif
029d3a9e33159c403153b7b1dbd5d8989034f861
508efd553572f28ebeb93bac77d913b514094256
/csacademy/odd_divisors.cpp
e31df12bcb388e135fa23b8d55c9142026177327
[]
no_license
pimukthee/competitive-prog
4eaa917c27ddd02c8e4ff56502fa53eb7f884011
0a40e9fe8b229ce3534ad6e6e316e0b94c028847
refs/heads/master
2021-05-23T05:59:02.243040
2018-06-08T08:54:03
2018-06-08T08:54:03
94,750,445
0
0
null
null
null
null
UTF-8
C++
false
false
275
cpp
odd_divisors.cpp
#include <bits/stdc++.h> using namespace std; int main() { int n, k; stack <int> st; scanf("%d", &n); for (int i = 0; i < n; ++i) { scanf("%d", &k); if (st.empty() || ((st.top() & 1) != (k & 1))) st.push(k); } printf("%d", n - st.size()); return 0; }
673dc269b195f58d6c69d06d6590a1c3b3b1452c
a46296e5a9aa2131dbca8faa1d1fa35109a6ea3f
/iOS_Developer/DevelopGuide_iOS/DevelopGuide_iOS/dwvlt_v3.0_0522/M3Core_iOS4/source/MPFDrawer/GraphicFormatParser/EMF/EnhEMR/Header/XdwGraphicFormatEMFEnhEMRSetDIBRecord.h
e8efc0201cd52e7ecd92e52b15301366e3ad1ee6
[]
no_license
fourglod/iOSDevelopment
df0ae061c2dc5480cdaed9a4e04acd13b1a85815
9362143a0a423232a5c6cac787b84840cd2564b3
refs/heads/master
2021-06-14T09:24:28.627123
2017-01-11T03:10:10
2017-01-11T03:10:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,573
h
XdwGraphicFormatEMFEnhEMRSetDIBRecord.h
/** * @file XdwGraphicFormatEMFEnhEMRSetDIBRecord.h * @brief XdwGraphicFormat::EMF::EnhEMR::SetDIBRecordクラスの定義 * * @author DPC DS&S STD T31G Tomohiro Yamada <Tomohiro.Yamada@fujiexreox.co.jp> * @date 2002-3-28 * @version 1.0 * $Id: XdwGraphicFormatEMFEnhEMRSetDIBRecord.h,v 1.4 2009/12/22 08:11:38 chikyu Exp $ * * Copyright (C) 2002 Fuji Xerox Co., Ltd. */ #ifndef _XDW_GRAPHICFORMAT_EMF_ENH_EMR_SET_DIB_RECORD_H_ #define _XDW_GRAPHICFORMAT_EMF_ENH_EMR_SET_DIB_RECORD_H_ /* パッケージを記述するためのIncludeファイル */ #include "XdwGraphicFormatEMFEnhEMR.h" #include "XdwDocuWorks.h" /* 親クラスのIncludeファイル */ #include "XdwGraphicFormatEMFEnhEMRSetRasterRecord.h" /* 集約するクラスのIncludeファイル */ #include "XdwGraphicFormatGDIBitmapInfo.h" /** * @brief 参照されるDIBを規定するクラス * */ class XdwGraphicFormat::EMF::EnhEMR::SetDIBRecord : public XdwGraphicFormat::EMF::EnhEMR::SetRasterRecord { public: /********************************************/ /* メソッド */ /** * @brief デフォルトコンストラクタ * * @param content コンテントを管理するインターフェース */ SetDIBRecord(XdwDocuWorks::ContentManager* content = XdwNull); /** * @brief デストラクタ */ virtual ~SetDIBRecord(); /** * @brief DocuWorks独自のEMF中の参照されるDIBに関するレコードをパースする * * パースしたDIBの状態は、保存する * * @return XdwErrorCode参照 */ virtual XdwErrorCode Parse(); /** * @brief ラスター属性をセットする * * @param attribute セットされる属性管理のインスタンス * * @return XdwErrorCode参照 */ virtual XdwErrorCode SetAttribute(XdwRasterImageAttribute* attribute); protected: /********************************************/ /* 集約 */ /*! BITMAPINFO構造体を管理するクラス */ XdwGraphicFormat::GDI::BitmapInfo fBitmapInfo; /********************************************/ /* 関連 */ /*! コンテントを管理するインターフェース */ XdwDocuWorks::ContentManager* fContent; /********************************************/ /* メソッド */ /** * @brief インスタンスを初期化する * * 集約や属性の初期化 * * @return XdwErrorCode参照 */ virtual XdwErrorCode Initialize(); }; #endif
c15f795f62a5ff9af0f083bbe16b7614d69ab0e2
7e5be101928eb7ea43bc1a335d3475536f8a5bb2
/2015 Training/Summer Training/Competitive Contest Last/I.cpp
a2bbe727f07358176e4c0b958d096d6c6b0fc785
[]
no_license
TaoSama/ICPC-Code-Library
f94d4df0786a8a1c175da02de0a3033f9bd103ec
ec80ec66a94a5ea1d560c54fe08be0ecfcfc025e
refs/heads/master
2020-04-04T06:19:21.023777
2018-11-05T18:22:32
2018-11-05T18:22:32
54,618,194
0
2
null
null
null
null
UTF-8
C++
false
false
2,576
cpp
I.cpp
// // Created by TaoSama on 2015-09-12 // Copyright (c) 2015 TaoSama. All rights reserved. // //#pragma comment(linker, "/STACK:1024000000,1024000000") #include <algorithm> #include <cctype> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <iomanip> #include <iostream> #include <map> #include <queue> #include <string> #include <set> #include <vector> using namespace std; #define pr(x) cout << #x << " = " << x << " " #define prln(x) cout << #x << " = " << x << endl const int N = 1e5 + 10, INF = 0x3f3f3f3f, MOD = 1e9 + 7; int n, m, c; char a[5005][5005]; typedef pair<int, int> P; vector<P> p; int sx, sy, tx, ty; map<P, int> dp; int d[][2] = { -1, 0, 0, -1, 1, 0, 0, 1}; set<P> in; int spfa() { queue<P> q; q.push(P(sx, sy)); dp.clear(); in.clear(); dp[P(sx, sy)] = 0; in.insert(P(sx, sy)); while(q.size()) { P cur = q.front(), nxt; q.pop(); in.erase(cur); for(int i = 0; i < 4; ++i) { int nx = cur.first + d[i][0], ny = cur.second + d[i][1]; if(nx < 1 || nx > n || ny < 1 || ny > m || a[nx][ny] == '#') continue; nxt = make_pair(nx, ny); if(!dp.count(nxt)) dp[nxt] = INF; if(dp[nxt] > dp[cur] + (a[nx][ny] == '*' ? c : 0)) { dp[nxt] = dp[cur] + (a[nx][ny] == '*' ? c : 0); if(!in.count(nxt)) in.insert(nxt), q.push(nxt); } } if(a[cur.first][cur.second] != 'P') continue; for(int i = 0; i < p.size(); ++i) { nxt = p[i]; if(nxt == cur) continue; if(!dp.count(nxt)) dp[nxt] = INF; if(dp[nxt] > dp[cur]) { dp[nxt] = dp[cur]; if(!in.count(nxt)) in.insert(nxt), q.push(nxt); } } } P t = make_pair(tx, ty); return dp.count(t) ? dp[t] : -1; } int main() { #ifdef LOCAL freopen("in.txt", "r", stdin); // freopen("out.txt","w",stdout); #endif ios_base::sync_with_stdio(0); while(scanf("%d%d%d", &n, &m, &c) == 3) { p.clear(); for(int i = 1; i <= n; ++i) { scanf("%s", a[i] + 1); for(int j = 1; j <= m; ++j) if(a[i][j] == 'P') p.push_back(P(i, j)); else if(a[i][j] == 'Y') sx = i, sy = j; else if(a[i][j] == 'C') tx = i, ty = j; } // printf("sx: %d sy: %d\n", sx, sy); // printf("tx: %d ty: %d\n", tx, ty); int ans = spfa(); if(ans == -1) puts("Damn teoy!"); else printf("%d\n", ans); } return 0; }
59ae17a392b1aa7d61e335fd1bb9809d3c7f6927
8686f343ded56bbf6458d15e410739de58317c60
/src/source/IVS_SDK_WINDOWS/IVS_SDK/IVS_SDK/service/UserDataMgr/UserDataMgr.cpp
3ba4ecb5419133cb780fa65828e5a1274ab597a8
[ "Apache-2.0" ]
permissive
Noel1992/eSDK_VCN_API_Windows_CPP
0ad5543bc8f16635a650a0305557f751f78a2ed1
ce457ab6e40fd0c007d362d0aa94b223d9f4a442
refs/heads/master
2020-05-02T02:31:35.720156
2016-11-17T12:04:40
2016-11-17T12:04:40
null
0
0
null
null
null
null
GB18030
C++
false
false
24,893
cpp
UserDataMgr.cpp
/*Copyright 2015 Huawei Technologies Co., Ltd. All rights reserved. eSDK is licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.*/ /******************************************************************** filename : UserDataMgr.cpp author : x00192614 created : 2013/01/17 description : 用户数据上传下载 copyright : Copyright (c) 2012-2016 Huawei Tech.Co.,Ltd history : 2013/01/17 初始版本 *********************************************************************/ #include "UserDataMgr.h" #include "UserMgr.h" #include "openssl/md5.h" #include "IVS_Trace.h" #define MD5LEN 32 CUserDataMgr::CUserDataMgr(void) : m_pUserMgr(NULL) { } CUserDataMgr::~CUserDataMgr(void) { m_pUserMgr = NULL; } void CUserDataMgr::SetUserMgr(CUserMgr *pUserMgr) { m_pUserMgr = pUserMgr; } // 上传用户数据到服务器 IVS_INT32 CUserDataMgr::BackupUserData(const IVS_CHAR* pFileName)const { CHECK_POINTER(pFileName, IVS_PARA_INVALID); CHECK_POINTER(m_pUserMgr, IVS_OPERATE_MEMORY_ERROR); IVS_DEBUG_TRACE("filename %s", pFileName); //读取压缩文件 ifstream ifUserFile; ifUserFile.open(pFileName, ios::binary); // 校验文件大小 ifUserFile.seekg(0, ios::end); //lint !e747 IVS_UINT32 ifLength = (IVS_UINT32)ifUserFile.tellg(); ifUserFile.seekg(0, ios::beg); //lint !e747 if (ifLength > MAX_FILE_LENGTH) { BP_RUN_LOG_ERR(IVS_FAIL, "Backup UserData failed", "file is oversize"); return IVS_FAIL; } IVS_CHAR *buffer = IVS_NEW((IVS_CHAR* &)buffer, ifLength+1); CHECK_POINTER(buffer, IVS_ALLOC_MEMORY_ERROR); eSDK_MEMSET(buffer, 0, ifLength+1); ifUserFile.read(buffer, ifLength); //lint !e747 ifUserFile.close(); //获取MD5的值 string strMd5 = GetFileMd5(pFileName); //对文件MD5算法 获取唯一的字符串,用于平台问下载文件的校验 const IVS_CHAR* strFailMd5 = strMd5.c_str();//lint !e64 匹配 // 拼装文件的TLV TNssTLVMsg tlvMsg; tlvMsg.usiTag = BINSTREAM_TAG; // 以二进制方式读取 tlvMsg.uiLength = (IVS_UINT32)ifLength; //lint !e1924 tlvMsg.pszValue = buffer; //文件流加上MD5码的长度 IVS_UINT32 tlvFileBuffer = (IVS_UINT32)(MD5LEN + ifLength + sizeof(uint16_t) + sizeof(uint32_t));//lint !e1924 IVS_CHAR* tlvMsgBuffer = IVS_NEW((IVS_CHAR* &)tlvMsgBuffer, tlvFileBuffer + 1); if (NULL == tlvMsgBuffer) { IVS_DELETE(buffer, MUILI); BP_RUN_LOG_ERR(IVS_ALLOC_MEMORY_ERROR, "Backup User Data", "alloc memory failed"); return IVS_ALLOC_MEMORY_ERROR; } eSDK_MEMSET(tlvMsgBuffer, 0, tlvFileBuffer + 1); //将文件PLV转换成字符串 uint16_t usiTag = htons(tlvMsg.usiTag); uint32_t uiLength = htonl(tlvMsg.uiLength); IVS_UINT32 uiLen = 0; eSDK_MEMCPY(tlvMsgBuffer + uiLen, MD5LEN, strFailMd5, MD5LEN); uiLen += MD5LEN; if (!CToolsHelp::Memcpy(tlvMsgBuffer + uiLen,sizeof(IVS_USHORT), &usiTag, sizeof(IVS_USHORT))) { IVS_DELETE(buffer, MUILI); IVS_DELETE(tlvMsgBuffer, MUILI); BP_RUN_LOG_ERR(IVS_ALLOC_MEMORY_ERROR, "Copy tlvMsgBuffer", "fail"); return IVS_ALLOC_MEMORY_ERROR; } uiLen += sizeof(IVS_USHORT); if (!CToolsHelp::Memcpy(tlvMsgBuffer + uiLen, sizeof(IVS_UINT32), &uiLength, sizeof(IVS_UINT32))) { IVS_DELETE(buffer, MUILI); IVS_DELETE(tlvMsgBuffer, MUILI); BP_RUN_LOG_ERR(IVS_ALLOC_MEMORY_ERROR, "Copy tlvMsgBuffer", "fail"); return IVS_ALLOC_MEMORY_ERROR; } uiLen += sizeof(IVS_UINT32); if (!CToolsHelp::Memcpy(tlvMsgBuffer + uiLen, tlvMsg.uiLength, tlvMsg.pszValue, tlvMsg.uiLength)) { IVS_DELETE(buffer, MUILI); IVS_DELETE(tlvMsgBuffer, MUILI); BP_RUN_LOG_ERR(IVS_ALLOC_MEMORY_ERROR, "Copy tlvMsgBuffer", "fail"); return IVS_ALLOC_MEMORY_ERROR; } // 获取本域SMU连接 std::string strSMULinkID; IVS_INT32 iGetLinkRet = m_pUserMgr->GetLocalDomainLinkID(NET_ELE_SMU_NSS, strSMULinkID); if (IVS_SUCCEED != iGetLinkRet) { BP_RUN_LOG_ERR(iGetLinkRet, "Get LocalDomainLinkID failed", "NA"); IVS_DELETE(buffer, MUILI); IVS_DELETE(tlvMsgBuffer, MUILI); return iGetLinkRet; } CCmd* pCmd = CNSSOperator::instance().BuildCmd(strSMULinkID, NET_ELE_SMU_NSS, NSS_UPLOAD_USER_CONFIG_FILE_REQ, tlvMsgBuffer, (IVS_INT32)(tlvFileBuffer + 1));//lint !e64 匹配 if (NULL == pCmd) { IVS_DELETE(buffer, MUILI); IVS_DELETE(tlvMsgBuffer, MUILI); BP_RUN_LOG_ERR(IVS_OPERATE_MEMORY_ERROR, "Build Cmd ", "fail"); return IVS_OPERATE_MEMORY_ERROR; } //调试用 // RestoreUserData(pUserDataFile, pCmd); //发送消息 CCmd *pCmdRsp = CNSSOperator::instance().SendSyncCmd(pCmd); if (NULL == pCmdRsp) { IVS_DELETE(buffer, MUILI); IVS_DELETE(tlvMsgBuffer, MUILI); BP_RUN_LOG_ERR(IVS_NET_RECV_TIMEOUT, "Send Cmd ", "fail"); return IVS_NET_RECV_TIMEOUT; } IVS_DELETE(buffer, MUILI); IVS_DELETE(tlvMsgBuffer, MUILI); int iRet = CNSSOperator::instance().ParseCmd2NSS(pCmdRsp); HW_DELETE(pCmdRsp); return iRet; } // 下载用户数据 IVS_INT32 CUserDataMgr::RestoreUserData(const IVS_CHAR* pFileName) { CHECK_POINTER(pFileName, IVS_PARA_INVALID); CHECK_POINTER(m_pUserMgr,IVS_OPERATE_MEMORY_ERROR); IVS_DEBUG_TRACE("filename %s", pFileName); CXml reqXml; IVS_INT32 iRet = GetRestoreUserDataReqXml(m_pUserMgr->GetLoginId(), reqXml); //lint !e1013 !e1055 !e746 !e64 !e613 if(IVS_SUCCEED != iRet) { BP_RUN_LOG_ERR(iRet, "Backup User Data", "Get RestoreUserData ReqXml fail"); return iRet; } IVS_UINT32 iLen = 0; const IVS_CHAR* pUserDataTemp = reqXml.GetXMLStream(iLen); CHECK_POINTER(pUserDataTemp, IVS_OPERATE_MEMORY_ERROR); // 获取本域SMU连接 std::string strSMULinkID; IVS_INT32 iGetLinkRet = m_pUserMgr->GetLocalDomainLinkID(NET_ELE_SMU_NSS, strSMULinkID); if (IVS_SUCCEED != iGetLinkRet) { BP_RUN_LOG_ERR(iGetLinkRet, "Get LocalDomainLinkID failed", "NA"); return iGetLinkRet; } //创建要发送的CMD,拼装了NSS消息头 CCmd* pCmd = CNSSOperator::instance().BuildSMUCmd(NSS_DOWNLOAD_USER_CONFIG_FILE_REQ, pUserDataTemp, strSMULinkID); CHECK_POINTER(pCmd, IVS_OPERATE_MEMORY_ERROR); //发送消息 CCmd *pCmdRsp = CNSSOperator::instance().SendSyncCmd(pCmd); CHECK_POINTER(pCmdRsp, IVS_NET_RECV_TIMEOUT); // 先判断返回值 iRet = CNSSOperator::instance().ParseCmd2NSS(pCmdRsp); if (IVS_SUCCEED != iRet) { BP_RUN_LOG_ERR(iRet, "Backup User Data fail", "NA"); return iRet; } IVS_INT32 length = 0; const IVS_CHAR* pRsp = CNSSOperator::instance().ParseCmd2Data(pCmdRsp, length); if (NULL == pRsp) { BP_RUN_LOG_ERR( IVS_FAIL, "Restore User Data", "SMU response failed"); HW_DELETE(pCmdRsp); return IVS_FAIL; } //pRsp进行压缩并解压文件 iRet = GetUserDataResp(pFileName, pRsp); IVS_DELETE(pRsp, MUILI); HW_DELETE(pCmdRsp); return iRet; } // 获取下载用户数据请求xml IVS_INT32 CUserDataMgr::GetRestoreUserDataReqXml(const IVS_CHAR* cLoginId, CXml &reqXml) const { CHECK_POINTER(cLoginId, IVS_OPERATE_MEMORY_ERROR); (void)reqXml.AddDeclaration("1.0","UTF-8",""); (void)reqXml.AddElem("Content"); reqXml.GetRootPos(); return IVS_SUCCEED; } // 解析备份用户数据响应xml //IVS_INT32 CUserDataMgr::GetRestoreUserDataParseRspXml(const string &strFailMd5, const IVS_CHAR* pFileName, CXml &rspXml) const //{ // CHECK_POINTER(pFileName, IVS_PARA_INVALID); // IVS_DEBUG_TRACE("strFailMd5: %s,pFileName: %s", strFailMd5.c_str(), pFileName); // const IVS_CHAR* szXMLValue = NULL; // if (!rspXml.FindElemEx("Content/FileMD5")) // { // BP_RUN_LOG_ERR(IVS_XML_INVALID, "Get RestoreUserData Parse RspXml", "Content/FileMD5 not exist"); // return IVS_XML_INVALID; // } // szXMLValue = rspXml.GetElemValue(); // if (NULL != szXMLValue) // { // //(void)CToolsHelp::Strncpy(pUserDataFile, szXMLValue, strlen(szXMLValue)); // } // return IVS_SUCCEED; //} // 获取文件的MD5值 std::string CUserDataMgr::GetFileMd5(const IVS_CHAR *pFileName) const { CHECK_POINTER(pFileName, "");//lint !e64 匹配 IVS_DEBUG_TRACE("pFileName:%s", pFileName); MD5_CTX md5; IVS_INT64 readBuffer = 1024; unsigned char md[16]; char tmp[33]={0}; IVS_UINT32 length,i; IVS_CHAR buffer[1024]; std::string hash=""; (void)MD5_Init(&md5); ifstream fin(pFileName, ios::in|ios::binary); while(!fin.eof()) { fin.read(buffer, readBuffer); //lint !e747 length = (IVS_UINT32)fin.gcount(); if (length > 0) { MD5_Update(&md5,buffer, length); } } MD5_Final(md,&md5); for(i=0; i<16; i++) { eSDK_SPRINTF(tmp, sizeof(tmp), "%02X", md[i]); hash+=(string)tmp; } return hash; //lint !e252 !e1036 } //lint !e253 // 获取用户数据请求 IVS_INT32 CUserDataMgr::GetUserDataResp(const IVS_CHAR* pFileName, const IVS_CHAR* pResp) const { CHECK_POINTER(pFileName, IVS_PARA_INVALID); CHECK_POINTER(pResp, IVS_PARA_INVALID); IVS_DEBUG_TRACE("pFileName:%s, pResp:%s", pFileName, pResp); //取出MD5值 IVS_CHAR szMD5[33] = {0}; if (!CToolsHelp::Memcpy(szMD5, 32, pResp, 32)) { BP_RUN_LOG_ERR(IVS_ALLOC_MEMORY_ERROR, "Copy szMD5", "fail"); return IVS_ALLOC_MEMORY_ERROR; } //取出文件大小 IVS_UINT32 iFilelength = 0; if (!CToolsHelp::Memcpy(&iFilelength, sizeof(IVS_UINT32), pResp + sizeof(IVS_USHORT) + 32, sizeof(IVS_UINT32))) { BP_RUN_LOG_ERR(IVS_ALLOC_MEMORY_ERROR, "Copy pResp", "fail"); return IVS_ALLOC_MEMORY_ERROR; } IVS_UINT32 uiFileLength = ntohl(iFilelength); // 这里做个大小保护,如果太大会挂 if (uiFileLength > MAX_FILE_LENGTH) { BP_RUN_LOG_ERR(IVS_FAIL, "file length oversize","uiFileLength= %d", uiFileLength); return IVS_FAIL; } // 取出文件流 const IVS_CHAR *pFile = pResp + sizeof(IVS_USHORT) + sizeof(IVS_UINT32) + 32; ofstream fUserData (pFileName,ofstream::binary); fUserData.write(pFile, (IVS_INT64)uiFileLength); fUserData.close(); // 对比MD5 查看是否正确下载 std::string strTempMd5 = szMD5; const std::string strMd5 = GetFileMd5(pFileName); if (0 != strcmp(strMd5.c_str(), strTempMd5.c_str())) { BP_RUN_LOG_ERR(IVS_SDK_ERR_CHEACKMD5_FAILED, "Get UserData Resp", "write file failed."); return IVS_SDK_ERR_CHEACKMD5_FAILED; } return IVS_SUCCEED; } // 上传logo文件 IVS_INT32 CUserDataMgr::UploadLogo(IVS_UINT32 uiLogoType, const IVS_CHAR* pLogoFile)const { CHECK_POINTER(pLogoFile, IVS_PARA_INVALID); CHECK_POINTER(m_pUserMgr, IVS_OPERATE_MEMORY_ERROR); // logo类型,转成网络字节 IVS_USHORT u16logType = htons((IVS_USHORT)uiLogoType); // logo文件路径,包含文件名 std::string strLogoFile = pLogoFile; // 获取文件后缀名, 最大位10 std::string strLogoFileSuffix = strLogoFile.substr(strLogoFile.rfind(".") + 1, strlen(strLogoFile.c_str())); if (strLogoFileSuffix.size() > MAX_FILE_SUFFIX_LENGTH) { BP_RUN_LOG_ERR(IVS_FAIL, "file suffix oversize", "NA") return IVS_FAIL; } //读取文件 ifstream ifLogoFile; ifLogoFile.open(strLogoFile.c_str(), ios::binary); if(!ifLogoFile) { BP_RUN_LOG_ERR(IVS_FAIL, "file open failed", "NA") return IVS_FAIL; } // 校验文件大小,不能超过最大 ifLogoFile.seekg(0, ios::end); //lint !e747 IVS_UINT32 ifLength = (IVS_UINT32)ifLogoFile.tellg(); ifLogoFile.seekg(0, ios::beg); //lint !e747 if (ifLength > MAX_FILE_LENGTH) { BP_RUN_LOG_ERR(IVS_FAIL, "upload logo failed", "file is oversize"); return IVS_FAIL; } IVS_CHAR *buffer = IVS_NEW(buffer,ifLength + 1); CHECK_POINTER(buffer, IVS_ALLOC_MEMORY_ERROR); eSDK_MEMSET(buffer, 0, ifLength + 1); ifLogoFile.read(buffer, ifLength); //lint !e747 ifLogoFile.close(); // 拼装文件的TLV TNssTLVMsg tlvMsg; tlvMsg.usiTag = BINSTREAM_TAG; // 以二进制方式读取 tlvMsg.uiLength = (IVS_UINT32)ifLength; tlvMsg.pszValue = buffer; IVS_UINT32 uiMsgBuffer = ifLength + 2*sizeof(IVS_USHORT) + sizeof(IVS_UINT32) + MAX_FILE_SUFFIX_LENGTH; IVS_CHAR* pMsgBuffer = IVS_NEW(pMsgBuffer, uiMsgBuffer); if (NULL == pMsgBuffer) { IVS_DELETE(buffer, MUILI); BP_RUN_LOG_ERR(IVS_ALLOC_MEMORY_ERROR, "UploadLogo", "alloc memory failed"); return IVS_ALLOC_MEMORY_ERROR; } eSDK_MEMSET(pMsgBuffer, 0, uiMsgBuffer); //将文件TLV转换成字符串 IVS_USHORT usiTag = htons(tlvMsg.usiTag); IVS_UINT32 uiLength = htonl(tlvMsg.uiLength); IVS_UINT32 uiLen = 0; (void)CToolsHelp::Memcpy(pMsgBuffer, sizeof(IVS_USHORT), &u16logType, sizeof(IVS_USHORT)); uiLen += sizeof(IVS_USHORT); (void)CToolsHelp::Memcpy(pMsgBuffer + uiLen, MAX_FILE_SUFFIX_LENGTH, strLogoFileSuffix.c_str(), strLogoFileSuffix.size());//lint !e64 匹配 uiLen += MAX_FILE_SUFFIX_LENGTH; (void)CToolsHelp::Memcpy(pMsgBuffer + uiLen, sizeof(IVS_USHORT), &usiTag, sizeof(IVS_USHORT)); uiLen += sizeof(IVS_USHORT); (void)CToolsHelp::Memcpy(pMsgBuffer + uiLen, sizeof(IVS_UINT32), &uiLength, sizeof(IVS_UINT32)); uiLen += sizeof(IVS_UINT32); (void)CToolsHelp::Memcpy(pMsgBuffer + uiLen, tlvMsg.uiLength, tlvMsg.pszValue, tlvMsg.uiLength); // 获取本域SMU连接 std::string strSMULinkID; IVS_INT32 iGetLinkRet = m_pUserMgr->GetLocalDomainLinkID(NET_ELE_SMU_NSS, strSMULinkID); if (IVS_SUCCEED != iGetLinkRet) { BP_RUN_LOG_ERR(iGetLinkRet, "Get LocalDomainLinkID failed", "NA"); IVS_DELETE(buffer, MUILI); IVS_DELETE(pMsgBuffer, MUILI); return iGetLinkRet; } CCmd* pCmd = CNSSOperator::instance().BuildCmd(strSMULinkID, NET_ELE_SMU_NSS,NSS_UPLOAD_LOGO_REQ, pMsgBuffer, (int)uiMsgBuffer);//lint !e64 匹配 if (NULL == pCmd) { IVS_DELETE(buffer, MUILI); IVS_DELETE(pMsgBuffer, MUILI); BP_RUN_LOG_ERR(IVS_OPERATE_MEMORY_ERROR, "Build Cmd ", "fail"); return IVS_OPERATE_MEMORY_ERROR; } //发送消息 CCmd *pCmdRsp = CNSSOperator::instance().SendSyncCmd(pCmd); if (NULL == pCmdRsp) { IVS_DELETE(buffer, MUILI); IVS_DELETE(pMsgBuffer, MUILI); BP_RUN_LOG_ERR(IVS_NET_RECV_TIMEOUT, "Send Cmd ", "fail"); return IVS_NET_RECV_TIMEOUT; } IVS_DELETE(buffer, MUILI); IVS_DELETE(pMsgBuffer, MUILI); IVS_INT32 iRet = CNSSOperator::instance().ParseCmd2NSS(pCmdRsp); HW_DELETE(pCmdRsp); return iRet; } // 下载logo文件 IVS_INT32 CUserDataMgr::GetLogo(IVS_UINT32 uiLogoType, const IVS_CHAR* pLogoFile)const { CHECK_POINTER(pLogoFile, IVS_PARA_INVALID); // 判断文件是否存在,不存在返回失败 if(_access(pLogoFile,0) != 0) { BP_RUN_LOG_ERR(IVS_OPEN_FILE_ERROR, "file not exist", "NA"); return IVS_OPEN_FILE_ERROR; } // 根据文件全路径,读取文件,并生成MD5 const std::string strSendMd5 = GetFileMd5(pLogoFile); // 拼装请求 CXml xmlReq; (void)xmlReq.AddDeclaration("1.0","UTF-8",""); (void)xmlReq.AddElem("Content"); (void)xmlReq.AddChildElem("LogoInfo"); (void)xmlReq.IntoElem(); (void)xmlReq.AddChildElem("LogoType"); (void)xmlReq.IntoElem(); (void)xmlReq.SetElemValue(CToolsHelp::Int2Str((IVS_INT32)uiLogoType).c_str());//lint !e64 匹配 (void)xmlReq.AddElem("MD5"); (void)xmlReq.IntoElem(); (void)xmlReq.SetElemValue(strSendMd5.c_str());//lint !e64 匹配 xmlReq.OutOfElem(); xmlReq.OutOfElem(); unsigned int uilen = 0; const char* pReq = xmlReq.GetXMLStream(uilen); CHECK_POINTER(pReq, IVS_OPERATE_MEMORY_ERROR); // 获取本域SMU连接 std::string strSMULinkID; if (NULL == m_pUserMgr) { BP_RUN_LOG_ERR(IVS_OPERATE_MEMORY_ERROR, "Get Logo", "m_pUserMgr = NULL"); return IVS_OPERATE_MEMORY_ERROR; } IVS_INT32 iGetLinkRet = m_pUserMgr->GetLocalDomainLinkID(NET_ELE_SMU_NSS, strSMULinkID); if (IVS_SUCCEED != iGetLinkRet) { BP_RUN_LOG_ERR(iGetLinkRet, "Get LocalDomainLinkID failed", "NA"); return iGetLinkRet; } // 构造发送CMD对象 CCmd* pCmd = CNSSOperator::instance().BuildSMUCmd(NSS_GET_LOGO_REQ,pReq,strSMULinkID); if (NULL == pCmd) { BP_RUN_LOG_ERR(IVS_FAIL, "build cmd failed", "NA"); return IVS_FAIL; } // 发送nss消息 CCmd *pCmdRsp = CNSSOperator::instance().SendSyncCmd(pCmd); if (NULL == pCmdRsp) { BP_RUN_LOG_ERR(IVS_NET_RECV_TIMEOUT, "Send General AuthCmd failed", "msg no response"); return IVS_NET_RECV_TIMEOUT; } // 先判断返回值 IVS_INT32 iRet = CNSSOperator::instance().ParseCmd2NSS(pCmdRsp); if (IVS_SUCCEED != iRet) { HW_DELETE(pCmdRsp); BP_RUN_LOG_ERR(iRet, "download failed", "NA"); return iRet; } // 解析响应CMD,获取返回码 int ilen = 0; IVS_CHAR* pData = CNSSOperator::instance().ParseCmd2Data(pCmdRsp, ilen); HW_DELETE(pCmdRsp); if (0 == ilen || NULL == pData) { BP_RUN_LOG_INF("rsp content length is zero ,file is new", "NA"); return IVS_SUCCEED; } IVS_CHAR szMD5[33] = {0}; (void)CToolsHelp::Memcpy(szMD5, 32 , pData, 32); // 解析TLV,将数据保存到目录中 uint32_t iFilelength = 0; if (!CToolsHelp::Memcpy(&iFilelength, sizeof(IVS_UINT32), pData + 32 + sizeof(IVS_USHORT), sizeof(IVS_UINT32))) { IVS_DELETE(pData, MUILI); BP_RUN_LOG_ERR(IVS_ALLOC_MEMORY_ERROR, "Copy pResp", "fail"); return IVS_ALLOC_MEMORY_ERROR; } IVS_DELETE(pData, MUILI); IVS_UINT32 uiFileLength = ntohl(iFilelength); const IVS_CHAR *pFile = pData + 32 + (sizeof(IVS_USHORT) + sizeof(IVS_UINT32)); // pLogoFile重命名文件名为_temp std::string strFile = pLogoFile; std::string strFilePath = strFile.substr(0, strFile.rfind("\\")); std::string strFileWholeName = strFile.substr(strFile.rfind("\\") + 1, strlen(strFile.c_str())); std::string strFileName = strFileWholeName.substr(0, strFileWholeName.rfind(".")); std::string strFileSuffix = strFileWholeName.substr(strFileWholeName.rfind("."), strlen(strFileWholeName.c_str())); std::string strFileRename = strFileName; strFileRename += "_temp"; strFileRename += strFileSuffix; std::string strRenameFile = strFilePath; strRenameFile += "\\"; strRenameFile += strFileRename; ofstream fLogoData (strRenameFile.c_str(),ofstream::binary); fLogoData.write(pFile, (IVS_INT64)uiFileLength); fLogoData.close(); const std::string strMd5 = GetFileMd5(strRenameFile.c_str()); if (0 != strcmp(strMd5.c_str(), szMD5)) { // 删除文件 (void)remove(strRenameFile.c_str()); BP_RUN_LOG_ERR(IVS_SDK_ERR_CHEACKMD5_FAILED, "Get logo Resp", "md5 not match"); return IVS_SDK_ERR_CHEACKMD5_FAILED; } return IVS_SUCCEED; } // 上传申明信息 IVS_INT32 CUserDataMgr::UploadStatement(const IVS_CHAR* pLanguageType,const IVS_CHAR* pStatementFile)const { CHECK_POINTER(pLanguageType, IVS_PARA_INVALID); CHECK_POINTER(pStatementFile, IVS_PARA_INVALID); // 申明信息文件路径,包含文件名 std::string strStatementFile = pStatementFile; // 获取文件后缀名, 最大位10 std::string strStatementFileSuffix = strStatementFile.substr(strStatementFile.rfind(".") + 1, strlen(strStatementFile.c_str())); if (strlen(strStatementFileSuffix.c_str()) > MAX_FILE_SUFFIX_LENGTH) { BP_RUN_LOG_ERR(IVS_FAIL, "file suffix oversize", "NA") return IVS_FAIL; } //读取文件 ifstream ifLogoFile; ifLogoFile.open(strStatementFile.c_str(), ios::binary); if(!ifLogoFile) { BP_RUN_LOG_ERR(IVS_FAIL, "file open failed", "NA") return IVS_FAIL; } // 校验文件大小,不能超过最大 ifLogoFile.seekg(0, ios::end); //lint !e747 IVS_UINT32 ifLength = (IVS_UINT32)ifLogoFile.tellg(); ifLogoFile.seekg(0, ios::beg); //lint !e747 if (ifLength > MAX_FILE_LENGTH) { BP_RUN_LOG_ERR(IVS_FAIL, "upload logo failed", "file is oversize"); return IVS_FAIL; } IVS_CHAR *buffer = IVS_NEW(buffer,ifLength + 1); CHECK_POINTER(buffer, IVS_ALLOC_MEMORY_ERROR); eSDK_MEMSET(buffer, 0, ifLength + 1); ifLogoFile.read(buffer, ifLength); //lint !e747 ifLogoFile.close(); // 拼装文件的TLV TNssTLVMsg tlvMsg; tlvMsg.usiTag = BINSTREAM_TAG; // 以二进制方式存取 tlvMsg.uiLength = (IVS_UINT32)ifLength; tlvMsg.pszValue = buffer; IVS_UINT32 uiMsgBuffer = ifLength + sizeof(IVS_USHORT) + sizeof(IVS_UINT32) + MAX_FILE_SUFFIX_LENGTH + LANGUAGE_TYPE_LENGTH; IVS_CHAR* pMsgBuffer = IVS_NEW(pMsgBuffer, uiMsgBuffer); if (NULL == pMsgBuffer) { IVS_DELETE(buffer, MUILI); BP_RUN_LOG_ERR(IVS_ALLOC_MEMORY_ERROR, "Upload Statement", "alloc memory failed"); return IVS_ALLOC_MEMORY_ERROR; } eSDK_MEMSET(pMsgBuffer, 0, uiMsgBuffer); //将文件TLV转换成字符串 IVS_USHORT usiTag = htons(tlvMsg.usiTag); IVS_UINT32 uiLength = htonl(tlvMsg.uiLength); IVS_UINT32 uiLen = 0; (void)CToolsHelp::Memcpy(pMsgBuffer, LANGUAGE_TYPE_LENGTH, pLanguageType, strlen(pLanguageType)); uiLen += LANGUAGE_TYPE_LENGTH; (void)CToolsHelp::Memcpy(pMsgBuffer + uiLen, MAX_FILE_SUFFIX_LENGTH, (const void *)strStatementFileSuffix.c_str(), strlen(strStatementFileSuffix.c_str())); uiLen += MAX_FILE_SUFFIX_LENGTH; (void)CToolsHelp::Memcpy(pMsgBuffer + uiLen, sizeof(IVS_USHORT), &usiTag, sizeof(IVS_USHORT)); uiLen += sizeof(IVS_USHORT); (void)CToolsHelp::Memcpy(pMsgBuffer + uiLen, sizeof(IVS_UINT32), &uiLength, sizeof(IVS_UINT32)); uiLen += sizeof(IVS_UINT32); (void)CToolsHelp::Memcpy(pMsgBuffer + uiLen, tlvMsg.uiLength, tlvMsg.pszValue, tlvMsg.uiLength); // 获取本域SMU连接 std::string strSMULinkID; IVS_INT32 iGetLinkRet = IVS_FAIL; if (NULL != m_pUserMgr) { iGetLinkRet = m_pUserMgr->GetLocalDomainLinkID(NET_ELE_SMU_NSS, strSMULinkID); } if (IVS_SUCCEED != iGetLinkRet) { BP_RUN_LOG_ERR(iGetLinkRet, "Get LocalDomainLinkID failed", "NA"); IVS_DELETE(buffer, MUILI); IVS_DELETE(pMsgBuffer, MUILI); return iGetLinkRet; } // TODO 修改为sendcmd? CCmd* pCmd = CNSSOperator::instance().BuildCmd(strSMULinkID, NET_ELE_SMU_NSS, NSS_UPLOAD_STATEMENT_REQ, pMsgBuffer, (int)uiMsgBuffer);//lint !e64 匹配 if (NULL == pCmd) { IVS_DELETE(buffer, MUILI); IVS_DELETE(pMsgBuffer, MUILI); BP_RUN_LOG_ERR(IVS_OPERATE_MEMORY_ERROR, "Build Cmd ", "fail"); return IVS_OPERATE_MEMORY_ERROR; } //发送消息 CCmd *pCmdRsp = CNSSOperator::instance().SendSyncCmd(pCmd); if (NULL == pCmdRsp) { IVS_DELETE(buffer, MUILI); IVS_DELETE(pMsgBuffer, MUILI); BP_RUN_LOG_ERR(IVS_NET_RECV_TIMEOUT, "Send Cmd ", "fail"); return IVS_NET_RECV_TIMEOUT; } IVS_DELETE(buffer, MUILI); IVS_DELETE(pMsgBuffer, MUILI); IVS_INT32 iRet = CNSSOperator::instance().ParseCmd2NSS(pCmdRsp); HW_DELETE(pCmdRsp); return iRet; } // 获取申明信息 IVS_INT32 CUserDataMgr::GetStatement(const IVS_CHAR* pLanguageType,IVS_CHAR** pStatement) { // 拼装请求 CXml xmlReq; (void)xmlReq.AddDeclaration("1.0","UTF-8",""); (void)xmlReq.AddElem("Content"); (void)xmlReq.AddChildElem("StatementInfo"); (void)xmlReq.IntoElem(); (void)xmlReq.AddChildElem("LanguageType"); (void)xmlReq.IntoElem(); (void)xmlReq.SetElemValue(pLanguageType); xmlReq.OutOfElem(); xmlReq.OutOfElem(); unsigned int len = 0; const char* pReq = xmlReq.GetXMLStream(len); CHECK_POINTER(pReq, IVS_OPERATE_MEMORY_ERROR); // 构造带域的请求消息,并发送 CSendNssMsgInfo sendNssMsgInfo; sendNssMsgInfo.SetNeedXml(TYPE_NSS_XML); sendNssMsgInfo.SetNetElemType(NET_ELE_SMU_NSS); sendNssMsgInfo.SetReqID(NSS_GET_STATEMENT_REQ); sendNssMsgInfo.SetReqData(pReq); std::string strRsp; IVS_INT32 iNeedRedirect = IVS_FAIL; CHECK_POINTER(m_pUserMgr, IVS_OPERATE_MEMORY_ERROR); IVS_INT32 iRet = m_pUserMgr->SendCmd(sendNssMsgInfo,strRsp,iNeedRedirect); if(IVS_SUCCEED != iRet) { BP_RUN_LOG_ERR(iRet, "get statement","SendCmd to SMU Return Failed"); return iRet; } // 解析xml CXml xmlRsp; if (!xmlRsp.Parse(strRsp.c_str()))//lint !e64 匹配 { BP_RUN_LOG_ERR(IVS_SMU_XML_INVALID, "parse xml failed","NA"); return IVS_SMU_XML_INVALID; } if (!xmlRsp.FindElemEx("Content/StatementInfo/Statement")) { BP_RUN_LOG_ERR(IVS_SMU_XML_INVALID, "cannot find Statement","NA"); return IVS_SMU_XML_INVALID; } const char* pStatementValue = xmlRsp.GetElemValue(); CHECK_POINTER(pStatementValue, IVS_OPERATE_MEMORY_ERROR); char* pCopy = IVS_NEW(pCopy, strlen(pStatementValue) + 1); // 在外部释放掉 eSDK_MEMSET(pCopy, 0, strlen(pStatementValue) + 1); if (!CToolsHelp::Memcpy(pCopy, strlen(pStatementValue) + 1, pStatementValue, strlen(pStatementValue))) { BP_RUN_LOG_ERR(IVS_ALLOC_MEMORY_ERROR, "CToolsHelp::Memcpy pRsp to pResultXml fail", "NA"); return IVS_ALLOC_MEMORY_ERROR; } *pStatement = pCopy; return IVS_SUCCEED; }
c9d81d96d0afeee9ed1d929562a6e04d6e34b3c8
782e04174af86acf8ba9838e00846611e2893dbf
/Engine/Code/Engine/Math/EulerAngles.hpp
46d3f91f0c0415e714c6bdb2988282d0c6cbff10
[]
no_license
DylanSByrd/Defiance
343e96fb5a91f197bbb6427da2ee3bd2bca1885a
3d239dd637e5fc6dd02e60e760f82b0fca9f9564
refs/heads/master
2021-04-30T23:32:26.666295
2017-01-23T07:25:39
2017-01-23T07:25:39
79,777,947
2
1
null
null
null
null
UTF-8
C++
false
false
429
hpp
EulerAngles.hpp
#pragma once //----------------------------------------------------------------------------------------------- class EulerAngles { public: EulerAngles() {} EulerAngles(float inRoll, float inPitch, float inYaw); static const EulerAngles ZERO; float roll; float pitch; float yaw; }; inline EulerAngles::EulerAngles( float inRoll, float inPitch, float inYaw) : roll(inRoll) , pitch(inPitch) , yaw(inYaw) {}
691ffacfaaf34c52c3c6a2ac08f348a33189062d
448ae129ff28b0e4688fbf105d40681f9aa896d5
/2DWalking/src/graphics/paints/sprite.h
8c51b6df3c27d233ada5d6514a9c7e9892893ccd
[]
no_license
ISahoneI/2DWalking
00ef06711946f837de3a897bfa9187f5723a9884
bbdd5a3d11becfd26d806a056b6950e25db310c0
refs/heads/master
2021-06-24T06:23:53.274731
2020-10-25T23:46:49
2020-10-25T23:46:49
138,442,552
0
0
null
null
null
null
UTF-8
C++
false
false
3,241
h
sprite.h
#pragma once #include "../rendering/renderer.h" #include "../paints/texture.h" #include "../paints/colormanager.h" #include "../../utilities/mathmanager.h" enum class SpriteLevel { BACKGROUND = -1, LEVEL0 = 0, LEVEL1 = 1, LEVEL2 = 2, LEVEL3 = 3, LEVEL4 = 4, FOREGROUND = 5 }; class Sprite { protected: bool isRender; bool isVisible; glm::vec3 position; glm::vec2 size; glm::vec4 colorParameters; unsigned int color; std::vector<glm::vec2> uv; Texture* texture; SpriteLevel level; public: Sprite(); Sprite(Texture* texture); //Sprite(glm::vec3 position, glm::vec2 size, unsigned int color); Sprite(glm::vec3 position, glm::vec2 size, const glm::vec4 color); //Sprite(float x, float y, float width, float height, unsigned int color = 0xffffffff); Sprite(float x, float y, float width, float height, const glm::vec4 color = glm::vec4(255, 255, 255, 255)); //Sprite(float x, float y, float width, float height, Texture* texture, unsigned int color = 0xffffffff); Sprite(float x, float y, float width, float height, Texture* texture, const glm::vec4 color = glm::vec4(255, 255, 255, 255)); virtual ~Sprite(); virtual void submit(Renderer* renderer) const; const bool getIsRender() const { return isRender; } void setIsRender(bool isRender) { this->isRender = isRender; } const bool getIsVisible() const { return isVisible; } void setIsVisible(bool isVisible) { this->isVisible = isVisible; } void setPosition(float x, float y, float z = 0.0f) { this->position = glm::vec3(x, y, z); } void setPositionX(float x) { this->position.x = x; } void setPositionY(float y) { this->position.y = y; } void setPositionZ(float z) { this->position.z = z; } void setSize(float width, float height) { this->size = glm::vec2(width, height); } void setWidth(float width) { this->size.x = width; } void setHeight(float height) { this->size.y = height; } void setColor(unsigned int r, unsigned int g, unsigned int b, unsigned int a); void setColor(const glm::vec4 color); void setColorRed(unsigned int r); void setColorGreen(unsigned int g); void setColorBlue(unsigned int b); void setTransparency(float alpha); void setTexture(Texture* tex) { this->texture = tex; } void setLevel(SpriteLevel level) { this->level = level; } const glm::vec3& getPosition() const { return position; } const float getPositionX() const { return position.x; } const float getPositionY() const { return position.y; } const float getPositionZ() const { return position.z; } const float getCenterX() const { return getPositionX() + getWidth() * 0.5f; } const float getCenterY() const { return getPositionY() + getHeight() * 0.5f; } const glm::vec2& getSize() const { return size; } const float getWidth() const { return size.x; } const float getHeight() const { return size.y; } const unsigned int getColor() const { return color; } const glm::vec4 getColorParameters() const { return colorParameters; } const float getTransparency() { return colorParameters.w; } const std::vector<glm::vec2>& getUV() const { return this->uv; } const GLuint getTID() const { return this->texture == nullptr ? false : this->texture->getID(); } const SpriteLevel getLevel() const { return level; } private: void setTexUV(); };
ad535d84ff8f0f20927adb27cfb8418083fa216c
d533d23de41af23b3b16761f2e1183c319c8d3bf
/file.cc
c5f1a6e56ad16f074c3da110e537b7d796cd28a3
[]
no_license
alpha-netzilla/file-management
200cbd2617c32bb39334588f12803801457e313e
a8b1d931a0efba5a523907daa3abe27551a5cf5e
refs/heads/master
2021-01-01T06:45:38.877473
2015-05-21T15:51:55
2015-05-21T15:51:55
35,260,761
1
0
null
null
null
null
UTF-8
C++
false
false
500
cc
file.cc
#include "file.h" #include <fstream> #include <assert.h> using namespace std; File::File( const char* filename ) : mFilename( filename ), mData( 0 ), mSize( 0 ) { } File::~File() { if ( mData ) { delete[]( mData ); } mSize = 0; } bool File::isReady() const { return ( mData != 0 ); } int File::getSize() const { assert( mData && "loading is not finished." ); return mSize; } const char* File::getData() const { assert( mData && "loading is not finished." ); return mData; }
4f9d145b7299644104929caeb587098140344373
51b6e15c2df62c6dec776c734b7296d798863e3f
/src/Game.hpp
0d94298c5895ea1e7058780e0c147ab0ae65b277
[]
no_license
stanisz13/muchKills
650ac2c4614e7b972b4c2673680a07b63002c2ce
80294735b0a51ae5034bbcdfc9c62ea5fd297c70
refs/heads/master
2020-03-23T16:54:58.010486
2018-07-22T17:57:05
2018-07-22T17:57:05
141,833,305
0
0
null
null
null
null
UTF-8
C++
false
false
149
hpp
Game.hpp
#pragma once #include <SFML/Graphics.hpp> namespace Game { void init(); void update(float deltaTime); void draw(); void deinit(); }
4a0647cd02b2930b9a8cdd783b1a8a6b9a50d774
906741afd445767ff4f3a01fb6b1c874856cddfc
/work/src/CGRA350/grass_bundle.h
7182dcf5724ecbd1ff7a9c24c6bf27eaacf860e2
[]
no_license
HenryLee0314/SwayingGrass
203b7ae57efc8eec5e9cbab3802b8f72d088f506
dd7bc254b78361f3c3e3643e72f68249843371aa
refs/heads/master
2023-06-09T11:40:08.370458
2021-07-02T04:38:27
2021-07-02T04:38:27
308,500,203
0
0
null
null
null
null
UTF-8
C++
false
false
621
h
grass_bundle.h
#ifndef grass_bundle_h #define grass_bundle_h #include "grass.h" #include "object.h" namespace CGRA350 { class GrassBundle : public Object { public: static GrassBundle* getInstance(); virtual void update(); virtual void render(); private: GrassBundle(Object* parent = nullptr); virtual ~GrassBundle(); GrassBundle(const GrassBundle&); GrassBundle& operator = (const GrassBundle&); private: void createGrass(float x, float z); float getRandomNumber(float scale = 1.0); Vec3 getRandomPoint(float scale = 1.0); private: static GrassBundle* _instance; }; } // namespace CGRA350 #endif // grass_bundle_h
be2e39a8c2bd609519516441a4f6524d96c2d262
f31558c867590e22bab50ec661d105c282ee1146
/src/ResourceNotLoaded.cpp
dd65c37f7c5bd311060e95d3d72e5c8691302f71
[ "MIT" ]
permissive
EleDe01/Arkanoid-Returns
56b23ffaa13f273977de0b97a5a8d52e504effeb
478ae8df92f978dce95fd227a9047e83dea9a855
refs/heads/master
2022-05-09T08:42:38.462501
2019-08-25T17:51:30
2019-08-25T17:51:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
183
cpp
ResourceNotLoaded.cpp
#include "ResourceNotLoaded.hpp" ResourceNotLoaded::ResourceNotLoaded(const std::string& urlResource) : Exception("Error Este recurso no se cargo correctamente " + urlResource) { }
9ed23e8c4f90de4941b140cbc08971e56c9f5d96
4d36e47f8f02ce5b7135f866803b2f3ea7c4891d
/controller/strategies/trafficobjectreplacedstrategy.cpp
c0d73487493524791093c978ae37d329ff1610b4
[]
no_license
bshkola/StreetSimulator
bb426c999e223aed40ab6595763106fdbabdc87b
1c0afbf0dc5fb83c9a9bc309f49ebc2152c648f4
refs/heads/master
2016-09-16T09:47:11.755240
2015-01-25T23:03:49
2015-01-25T23:03:49
25,729,779
0
1
null
null
null
null
UTF-8
C++
false
false
735
cpp
trafficobjectreplacedstrategy.cpp
//Author: Bogdan Shkola //Implementation of TrafficObjectReplacedStrategy class #include "../../controller/strategies/trafficobjectreplacedstrategy.h" #include "../../common/events/trafficobjectreplacedevent.h" TrafficObjectReplacedStrategy::TrafficObjectReplacedStrategy(std::shared_ptr<IModel> model, IView* view) : model_(model), view_(view) { } TrafficObjectReplacedStrategy::~TrafficObjectReplacedStrategy() { } void TrafficObjectReplacedStrategy::perform(std::shared_ptr<IEvent> event) { TrafficObjectReplacedEvent* trafficObjectReplacedEvent = static_cast<TrafficObjectReplacedEvent*>(event.get()); model_->replaceTrafficObject(trafficObjectReplacedEvent->getId(), trafficObjectReplacedEvent->getNewCoordinates()); }
9fbd5f17444d3696e2e808f094db8caefe6b0d1e
3d8a2a2b9c2e79fc4f73df4714cae79d8dbcc9d9
/Source/UnRealTutorial/FinishedLine.cpp
a49a75f15a69a1547fcccded04d57b172ee5941c
[]
no_license
youssefmyh/unreal
f9da3f9a9d1258eb02f971717f2aaf8f8d41ea51
44dd86447557776075214bcb852cd2c86d6fce1f
refs/heads/master
2022-12-25T14:05:25.750997
2020-10-04T15:23:02
2020-10-04T15:23:02
284,723,012
1
0
null
null
null
null
UTF-8
C++
false
false
1,141
cpp
FinishedLine.cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "FinishedLine.h" // Sets default values AFinishedLine::AFinishedLine() { // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; finalBox = CreateDefaultSubobject<UBoxComponent>(TEXT("Final Object")); RootComponent = finalBox; finalBox->SetGenerateOverlapEvents(true); finalBox->OnComponentBeginOverlap.AddDynamic(this, &AFinishedLine::TriggerEnter); } // Called when the game starts or when spawned void AFinishedLine::BeginPlay() { Super::BeginPlay(); } // Called every frame void AFinishedLine::Tick(float DeltaTime) { Super::Tick(DeltaTime); } void AFinishedLine::TriggerEnter(class UPrimitiveComponent* Comp, class AActor* OtherActor, class UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult) { if (OtherActor->IsA(ACharacter::StaticClass())) { UGameplayStatics::PlaySoundAtLocation(this, MySound, GetActorLocation()); } }
14f43c53b8a229a500b844ea99dd166f343726e5
07fe1adc36bbf8ad101cd73cb4f7919e6705d9ae
/Assignment 5/Point.h
000bcb5b3f28351a6ab54ecaa844f0e9f9922516
[]
no_license
we2ohs/Assignment-5
b1cf28a7277f94ebda7e4db8d0b0dd4ec93b810d
2b0bc93b37436ade6f08bfc0c7bcc788c9583070
refs/heads/master
2020-09-20T12:12:44.064902
2019-11-29T20:02:56
2019-11-29T20:02:56
224,472,867
0
0
null
null
null
null
UTF-8
C++
false
false
636
h
Point.h
// Assignment 5 // Student Name : Ahmed Ali // Student ID : 40102454 // Student Name : Nikolaos Chaskis // Student ID : 40092571 // Point.h #ifndef POINT_H #define POINT_H #include "Shape.h" class Point:public Shape { private: double x_coor; double y_coor; public: //Constructors Point(); Point(double, double); //Destructor ~Point(); //Set Functions void setx(double); void sety(double); //Get Functions double getx() const; double gety() const; //Print Function void print(); }; #endif /* POINT_H */
43c64720cbcea2fa63d90623094e7a29a53a2564
da1500e0d3040497614d5327d2461a22e934b4d8
/net/third_party/quic/platform/api/quic_endian.h
dd2081df824e5bf0e86b07947130a85a7c05afa0
[ "BSD-3-Clause" ]
permissive
youtube/cobalt
34085fc93972ebe05b988b15410e99845efd1968
acefdaaadd3ef46f10f63d1acae2259e4024d383
refs/heads/main
2023-09-01T13:09:47.225174
2023-09-01T08:54:54
2023-09-01T08:54:54
50,049,789
169
80
BSD-3-Clause
2023-09-14T21:50:50
2016-01-20T18:11:34
null
UTF-8
C++
false
false
1,704
h
quic_endian.h
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef NET_THIRD_PARTY_QUIC_PLATFORM_API_QUIC_ENDIAN_H_ #define NET_THIRD_PARTY_QUIC_PLATFORM_API_QUIC_ENDIAN_H_ #include "net/third_party/quic/platform/impl/quic_endian_impl.h" namespace quic { enum Endianness { NETWORK_BYTE_ORDER, // big endian HOST_BYTE_ORDER // little endian }; // Provide utility functions that convert from/to network order (big endian) // to/from host order (can be either little or big endian depending on the // platform). class QuicEndian { public: // Convert |x| from host order (can be either little or big endian depending // on the platform) to network order (big endian). static uint16_t HostToNet16(uint16_t x) { return QuicEndianImpl::HostToNet16(x); } static uint32_t HostToNet32(uint32_t x) { return QuicEndianImpl::HostToNet32(x); } static uint64_t HostToNet64(uint64_t x) { return QuicEndianImpl::HostToNet64(x); } // Convert |x| from network order (big endian) to host order (can be either // little or big endian depending on the platform). static uint16_t NetToHost16(uint16_t x) { return QuicEndianImpl::NetToHost16(x); } static uint32_t NetToHost32(uint32_t x) { return QuicEndianImpl::NetToHost32(x); } static uint64_t NetToHost64(uint64_t x) { return QuicEndianImpl::NetToHost64(x); } // Returns true if current host order is little endian. static bool HostIsLittleEndian() { return QuicEndianImpl::HostIsLittleEndian(); } }; } // namespace quic #endif // NET_THIRD_PARTY_QUIC_PLATFORM_API_QUIC_ENDIAN_H_
9f4942be82bd2502c58b7d7da7dc3f127c08a3f7
35d6d1029feff7dd6b757b93baa89ca75aa7c5d9
/UVA/Data Structure/484 - The Department of Redundancy Department.cpp
5a6003b8114f05100e81e45ae69a940d7c0e66a8
[]
no_license
SbrTa/Online-Judge
3709f496ebfb23155270c4ba37ada202dae0aef4
b190d27d19140faef58218a611bf38ab7e2398d3
refs/heads/master
2021-04-28T08:12:48.785378
2019-01-15T14:27:24
2019-01-15T14:27:24
122,243,679
1
0
null
null
null
null
UTF-8
C++
false
false
274
cpp
484 - The Department of Redundancy Department.cpp
#include<bits/stdc++.h> using namespace std; int main() { map<long,long>mp; long i,a,s[10000],n=0; while(cin>>a) { if(!mp[a]) s[n++]=a; mp[a]++; } for(i=0;i<n;i++) cout<<s[i]<<" "<<mp[s[i]]<<endl; return 0; }
e57cdbd499c329a0998369156821c1055c968120
efd52e8891954623b48e1f197bb3bbfc8a23207d
/examples/console/bezier_test/bezier_test.cpp
ac7f9a9e5d5a50d5f370ccea5bb17185e45ca249
[ "LicenseRef-scancode-boost-original", "LicenseRef-scancode-unknown-license-reference" ]
permissive
JamesCrook/agg21
1231bfdd9bbfa82e5e8e2e5cbda5bc2dc6dd1c01
7f911df81b18bfdb11ebe93adbaaa291f1c9e1f1
refs/heads/master
2021-01-01T03:34:11.396030
2016-05-19T17:18:36
2016-05-19T17:18:36
59,225,655
1
0
null
null
null
null
UTF-8
C++
false
false
3,653
cpp
bezier_test.cpp
#include <stdio.h> #include <stdlib.h> #include <time.h> #include "agg_rendering_buffer.h" #include "agg_curves.h" #include "agg_conv_stroke.h" #include "agg_rasterizer_scanline_aa.h" #include "agg_scanline_p.h" #include "agg_renderer_scanline.h" #include "agg_pixfmt_rgb24.h" void write_bmp_24(const char* filename, unsigned char* frame_buffer, unsigned w, unsigned h, unsigned stride) { #pragma pack(1) struct { agg::int16u bfType; agg::int32u bfSize; agg::int16u bfReserved1; agg::int16u bfReserved2; agg::int32u bfOffBits; } bmf; struct { agg::int32u biSize; agg::int32 biWidth; agg::int32 biHeight; agg::int16u biPlanes; agg::int16u biBitCount; agg::int32u biCompression; agg::int32u biSizeImage; agg::int32 biXPelsPerMeter; agg::int32 biYPelsPerMeter; agg::int32u biClrUsed; agg::int32u biClrImportant; } bmh; #pragma pack() bmf.bfType = 0x4D42; bmf.bfOffBits = sizeof(bmf) + sizeof(bmh); bmf.bfSize = bmf.bfOffBits + h * stride; bmf.bfReserved1 = 0; bmf.bfReserved2 = 0; bmh.biSize = sizeof(bmh); bmh.biWidth = w; bmh.biHeight = h; bmh.biPlanes = 1; bmh.biBitCount = 24; bmh.biCompression = 0; bmh.biSizeImage = h * stride; bmh.biXPelsPerMeter = 0; bmh.biYPelsPerMeter = 0; bmh.biClrUsed = 0; bmh.biClrImportant = 0; FILE* fd = fopen(filename, "wb"); if(fd) { fwrite(&bmf, sizeof(bmf), 1, fd); fwrite(&bmh, sizeof(bmh), 1, fd); fwrite(frame_buffer, stride, h, fd); fclose(fd); } } int main(int argc, char* argv[]) { if(argc < 4) { printf("usage: bezier_test <width> <height> <number_of_curves>\n"); return 1; } unsigned w = atoi(argv[1]); unsigned h = atoi(argv[2]); unsigned n = atoi(argv[3]); if(w < 20 || h < 20) { printf("Width and hight must be at least 20\n"); return 1; } if(w > 4096 || h > 4096) { printf("Width and hight mustn't exceed 4096\n"); return 1; } unsigned stride = (w * 3 + 3) / 4 * 4; unsigned char* frame_buffer = new unsigned char[stride * h]; agg::rendering_buffer rbuf; rbuf.attach((unsigned char*)frame_buffer, w, h, stride); agg::pixfmt_bgr24 pixf(rbuf); agg::renderer_base<agg::pixfmt_bgr24> renb(pixf); agg::renderer_scanline_p_solid<agg::renderer_base<agg::pixfmt_bgr24> > ren(renb); renb.clear(agg::rgba(1.0, 1.0, 1.0)); clock_t t1 = clock(); agg::curve4 curve; agg::conv_stroke<agg::curve4> poly(curve); agg::rasterizer_scanline_aa<> ras; agg::scanline_p8 sl; unsigned i; for(i = 0; i < n; i++) { poly.width(double(rand() % 3500 + 500) / 500.0); curve.init(rand() % w, rand() % h, rand() % w, rand() % h, rand() % w, rand() % h, rand() % w, rand() % h); ren.color(agg::rgba8(rand() & 0xFF, rand() & 0xFF, rand() & 0xFF, rand() & 0xFF)); ras.add_path(poly, 0); ras.render(sl, ren); } clock_t t2 = clock(); double sec = double(t2 - t1) / CLOCKS_PER_SEC; printf("%10.3f sec, %10.3f curves per sec\n", sec, double(n) / sec); write_bmp_24("output.bmp", (unsigned char*)frame_buffer, w, h, stride); delete [] frame_buffer; return 0; }
7920d7edf367bee4df29ae3a4bc65f20784b7ffc
50f170d3eac1b7b0a94671096213592e4fed6956
/Orango-Tango/intpreguntas.cpp
195f9e8ffb2b2949b6bb4adb42610c5869f7a28e
[]
no_license
Nicortiz72/OrangoTango_MarketApp
48ee358a85f44f7ba8b77e965cc35fd4184cb34f
453cdb6ba5f33f90e0d1ba428e29fd5ec55fe9fe
refs/heads/main
2023-07-06T05:44:09.576309
2021-08-15T23:36:54
2021-08-15T23:36:54
396,534,180
0
0
null
null
null
null
UTF-8
C++
false
false
997
cpp
intpreguntas.cpp
#include "intpreguntas.h" #include "ui_intpreguntas.h" #include <mainwindow.h> #include <cbasedatos.h> #include <QMessageBox> Intpreguntas::Intpreguntas(QWidget *parent) : QWidget(parent), ui(new Ui::Intpreguntas) { ui->setupUi(this); CBaseDatos BD; QVector <CPregunta> preguntas=BD.getPreguntas(); for(int i=0;i<preguntas.length();i++){ ui->listWidget->addItem(preguntas[i].getPregunta()); } } Intpreguntas::~Intpreguntas() { delete ui; } void Intpreguntas::on_listWidget_itemClicked(QListWidgetItem *item) { QMessageBox msg; CBaseDatos BD; QVector <CPregunta> preguntas=BD.getPreguntas(); for(int i=0;i<preguntas.length();i++){ if(preguntas[i].getPregunta()==item->text()){ msg.setText(preguntas[i].getRespuesta()); } } msg.exec(); } void Intpreguntas::on_pushButton_clicked() { MainWindow *intm=new MainWindow; intm->show(); this->close(); }
af6f9f053a26277fa671ff4c0f12ddfa0ffa7400
a366815640d5577dd5d7286d8fa375d2df5a5e34
/src/ArpaReader.cc
1493ae5fcc71d57738fc66c8382448e524f07fc2
[ "BSD-3-Clause" ]
permissive
vsiivola/variKN
04b6da3972e969768ee29328791ecdd741d93daf
3e9afd38a40c6f2547a362e9c885a2716a54834f
refs/heads/master
2023-02-04T18:43:36.575696
2023-02-01T17:47:59
2023-02-01T17:47:59
4,142,885
40
15
NOASSERTION
2023-01-30T07:22:55
2012-04-26T00:45:00
C++
UTF-8
C++
false
false
4,940
cc
ArpaReader.cc
// Routines for reading arpa format files to the internal prefix tree // format. #include "ArpaReader.hh" #include "def.hh" #include "str.hh" #include <stdlib.h> void ArpaReader::read_error() { fprintf(stderr, "ArpaReader::read(): error on line %d\n", m_lineno); exit(1); } void ArpaReader::read_header(FILE *file, bool &interpolated, std::string &line) { int order; // Just for efficiency m_vec.reserve(16); bool ok = true; interpolated = false; m_lineno = 0; // Find header while (1) { ok = str::read_line(&line, file, true); m_lineno++; if (!ok) { fprintf(stderr, "ArpaReader::read(): " "error on line %d while waiting \\data\\", m_lineno); exit(1); } // iARPA is used by the IRSTLM toolkit if (line == "\\interpolated" || line == "iARPA") interpolated = true; if (line == "\\data\\") break; } // Read header order = 1; int max_order_count = 0; while (1) { ok = str::read_line(&line, file, true); m_lineno++; if (!ok) { fprintf(stderr, "ArpaReader::read(): " "error on line %d while reading counts", m_lineno); exit(1); } // Header ends in a \-command if (line[0] == '\\') break; // Skip empty lines if (line.find_first_not_of(" \t\n") == line.npos) continue; // All non-empty header lines must be ngram counts if (line.substr(0, 6) != "ngram ") read_error(); { std::string tmp(line.substr(6)); str::split(&tmp, "=", false, &m_vec); } if (m_vec.size() != 2) read_error(); int count = atoi(m_vec[1].c_str()); if (count > max_order_count) max_order_count = count; counts.push_back(count); if (atoi(m_vec[0].c_str()) != order || counts.back() < 0) read_error(); order++; } } bool ArpaReader::next_gram(FILE *file, std::string &line, std::vector<int> &gram, float &log_prob, float &back_off) { // Read ngrams order by order while (m_read_order == 0 || m_gram_num >= counts[m_read_order - 1]) { m_gram_num = 0; m_read_order++; // Skip empty lines before the next order. bool skip_empty_lines = line != "\\1-grams:"; while (skip_empty_lines) { if (!str::read_line(&line, file, true)) { if (ferror(file)) read_error(); if (feof(file)) break; } m_lineno++; if (line.find_first_not_of(" \t\n") != line.npos) break; } // We must always have the correct header line at this point if (m_read_order > counts.size()) { if (line != "\\end\\") { fprintf(stderr, "ArpaReader::next_gram():" "expected end, got '%s' on line %d\n", line.c_str(), m_lineno); exit(1); } return false; } fprintf(stderr, "Found %d grams for order %d\n", counts[m_read_order - 1], m_read_order); if (line[0] != '\\') { fprintf(stderr, "ArpaReader::next_gram(): " "\\%d-grams expected on line %d\n", m_read_order, m_lineno); exit(1); } str::clean(&line, " \t"); str::split(&line, "-", false, &m_vec); if (atoi(m_vec[0].substr(1).c_str()) != m_read_order || m_vec[1] != "grams:") { fprintf(stderr, "ArpaReader::next_gram(): " "unexpected command on line %d: %s\n", m_lineno, line.c_str()); exit(1); } } gram.resize(m_read_order); // Read and split the line while (true) { if (!str::read_line(&line, file)) read_error(); str::clean(&line, " \t\n"); m_lineno++; // Ignore empty lines if (line.find_first_not_of(" \t\n") == line.npos) { continue; } break; } str::split(&line, " \t", true, &m_vec); // Check the number of columns on the line if (m_vec.size() < m_read_order + 1 || m_vec.size() > m_read_order + 2) { fprintf(stderr, "ArpaReader::next_gram(): " "%d columns on line %d\n", (int)m_vec.size(), m_lineno); exit(1); } if (m_read_order == counts.size() && m_vec.size() != m_read_order + 1) { fprintf(stderr, "WARNING: %d columns on line %d\n", (int)m_vec.size(), m_lineno); } // FIXME: should we deny new words in higher order ngrams? // Parse log-probability, back-off weight and word indices // FIXME: check the conversion of floats log_prob = strtod(m_vec[0].c_str(), NULL); back_off = 0; if (m_vec.size() == m_read_order + 2) back_off = strtod(m_vec[m_read_order + 1].c_str(), NULL); // Add the gram to sorter // fprintf(stderr,"add gram ["); for (int i = 0; i < m_read_order; i++) { gram[i] = m_vocab->add_word(m_vec[i + 1]); } m_gram_num++; return true; }
cb599041503eab0c47f2d5139c4eed1a1e649bfa
43ae1d4dbb622fe109979759dc162c56b26a04ad
/pkuOJ/pku_复试_is it a tree.cpp
87103565f68006d12105d482dff8385b17938f45
[]
no_license
lalaland1921/OnlineJudge
a06475c3ef57ec962ce117e5b4087f5df2f79d52
f55f94c333f18a044588088b8a001108f3d8f7bc
refs/heads/master
2021-01-16T06:51:26.314738
2020-02-25T23:59:19
2020-02-25T23:59:19
243,014,834
1
0
null
null
null
null
GB18030
C++
false
false
1,506
cpp
pku_复试_is it a tree.cpp
#include <stdio.h> #include <queue> using namespace std; int main() { int c=1,n1,n2; while(scanf("%d %d",&n1,&n2)&&n1!=-1&&n2!=-1)//若是-1-1则说明结束 { if(n1==0&&n2==0)//若是0 0则输出是一棵树 { printf("Case %d is a tree.\n",c++); continue; } int exist[10001]={0},vis[10001]={0},edge[10001][10001],isroot[10001]={0},maxn=0;//初始化变量 bool flag=true; exist[n1]=exist[n2]=1; edge[n1][n2]=1; maxn=max(n1,n2); while(scanf("%d %d",&n1,&n2)&&n1!=0&&n2!=0)//继续输入其他边 { exist[n1]=exist[n2]=1; edge[n1][n2]=1; isroot[n2]=1; maxn=max(n1,n2); } int root=0; while(root<=maxn&&(isroot[root]==1||exist[root]==0))//找到根结点 root++; if(root==0)//若未找到则不是树 flag=false; else//若找到则继续判断,用层序遍历进行判断 { queue<int> q; q.push(root); int p; while(!q.empty()) { p=q.front(); q.pop(); if(vis[p]==1)//若现在访问的结点已经被访问过说明不是树 { flag=false; break; } vis[p]=1; for(int i=1;i<=maxn;i++) { if(edge[p][i]) q.push(i); } } if(flag==true)//继续判断,找出层序遍历未访问到的结点,若找到则不是树 { for(int i=1;i<=maxn;i++) { if(exist[i]==1&&vis[i]==0) { flag=false; break; } } } } if(flag==true) printf("Case %d is a tree.\n",c); else printf("Case %d is not a tree.\n",c); c++; } return 0; }
8c39daeb8443f7ee9649e9ab31120c1885a7d543
0e4feea7a102604abbc2912a9beb073d769722db
/thinking_in_c-plus-plus/virtual/instrument.cpp
df8da526ab6bfe2503e18ee636c03cefcae3ac44
[]
no_license
ganghelloworld/C_plus_plus
9df140d17b7289719da39d03b43f5965867cd691
74f5a42156f6fa04d287c3a7047babd84939e222
refs/heads/master
2016-09-06T07:20:50.942686
2012-06-04T08:48:39
2012-06-04T08:48:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
587
cpp
instrument.cpp
#include <iostream> using namespace std; enum note {middle_c, c_sharp, c_flat}; class Instrument { int a; public: virtual void play(note n) const = 0; }; void Instrument::play(note n) const { cout << "Instrument::play()" << endl; } class Wind : public Instrument { public: void play(note n) const { cout << "Wind::play()" << endl; } }; class Flute : public Wind { public: void play(note n) const { cout << "Flute::play()" << endl; } }; void tune(Instrument& i) { i.play(middle_c); } int main() { Instrument* w[] = {new Wind, new Flute}; tune(*w[0]); tune(*w[1]); }
4f6d642448bb87f37cad322e262e32f32f2ae095
1a23603407a82f8c16dfd25b1be8573fa9d1e5f0
/room.cpp
72adbc40ed02889294fb440685c837f399a75b57
[]
no_license
accountexpired/greed
288df1977380d542427ce64d74ac15f5004a3676
96eae3bafe9e3a66a2802dcf282c1d8a8bbb1fd7
refs/heads/master
2021-06-01T09:06:57.005497
2016-08-14T15:34:55
2016-08-14T15:34:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,738
cpp
room.cpp
#include <iostream> #include <map> #include <memory> #include <vector> #include <ncurses.h> #include "creature.h" #include "room.h" Room::~Room() { } Room* Room::perform_action(const std::string& kbd_input, bool& valid_input) { if (actions.find(kbd_input) != actions.end()) { valid_input = true; actions.at(kbd_input)->exec(); } return this; } Room* Room::next_room(const std::string& kbd_input, bool& valid_input) { if (exits.find(kbd_input) == exits.end()) { return this; } valid_input = true; return exits.at(kbd_input); } void Room::enter() const { display(); } void Room::display() const { printw("%s\n", desc.c_str()); // Display creatures in the room. for (std::vector<std::unique_ptr<Creature>>::const_iterator creature = creatures.begin(); creature != creatures.end(); ++creature) { attron(COLOR_PAIR(1)); printw("%s\n", (*creature)->name.c_str()); attroff(COLOR_PAIR(1)); } // Display items in the room. for (std::vector<std::unique_ptr<Item>>::const_iterator item = items.begin(); item != items.end(); ++item) { attron(COLOR_PAIR(2)); printw("%s\n", (*item)->name.c_str()); attroff(COLOR_PAIR(2)); } // Display exits from the room. printw("Exits: "); auto exit = exits.begin(); if (exit == exits.end() || exit->first == "unnamed") { printw("None."); } else { for (; exit != exits.end(); ++exit) { printw("%s", exit->first.c_str()); if (std::distance(exit, exits.end()) > 1) { printw(", "); } } } printw("\n"); }
76873874ba6f730a3f961402baf9f5945a92cf0f
dfd413672b1736044ae6ca2e288a69bf9de3cfda
/webkit/tools/test_shell/test_shell_webthemeengine.h
03d1127957b27464930c625001609696e5a5e2d2
[ "BSD-3-Clause" ]
permissive
cha63506/chromium-capsicum
fb71128ba218fec097265908c2f41086cdb99892
b03da8e897f897c6ad2cda03ceda217b760fd528
HEAD
2017-10-03T02:40:24.085668
2010-02-01T15:24:05
2010-02-01T15:24:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,540
h
test_shell_webthemeengine.h
// Copyright (c) 2009 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. // TestShellWebTheme::Engine implements the WebThemeEngine // API used by the Windows version of Chromium to render native form // controls like checkboxes, radio buttons, and scroll bars. The normal // implementation (native_theme) renders the controls using either the // UXTheme theming engine present in XP, Vista, and Win 7, or the "classic" // theme used if that theme is selected in the Desktop settings. // Unfortunately, both of these themes render controls differently on the // different versions of Windows. // // In order to ensure maximum consistency of baselines across the different // Windows versions, we provide a simple implementation for test_shell here // instead. These controls are actually platform-independent (they're rendered // using Skia) and could be used on Linux and the Mac as well, should we // choose to do so at some point. // #ifndef WEBKIT_TOOLS_TEST_SHELL_TEST_SHELL_WEBTHEMEENGINE_H_ #define WEBKIT_TOOLS_TEST_SHELL_TEST_SHELL_WEBTHEMEENGINE_H_ #include "base/basictypes.h" #include "third_party/WebKit/WebKit/chromium/public/win/WebThemeEngine.h" namespace TestShellWebTheme { class Engine : public WebKit::WebThemeEngine { public: Engine() {} // WebThemeEngine methods: virtual void paintButton( WebKit::WebCanvas*, int part, int state, int classic_state, const WebKit::WebRect&); virtual void paintMenuList( WebKit::WebCanvas*, int part, int state, int classic_state, const WebKit::WebRect&); virtual void paintScrollbarArrow( WebKit::WebCanvas*, int state, int classic_state, const WebKit::WebRect&); virtual void paintScrollbarThumb( WebKit::WebCanvas*, int part, int state, int classic_state, const WebKit::WebRect&); virtual void paintScrollbarTrack( WebKit::WebCanvas*, int part, int state, int classic_state, const WebKit::WebRect&, const WebKit::WebRect& align_rect); virtual void paintTextField( WebKit::WebCanvas*, int part, int state, int classic_state, const WebKit::WebRect&, WebKit::WebColor, bool fill_content_area, bool draw_edges); virtual void paintTrackbar( WebKit::WebCanvas*, int part, int state, int classic_state, const WebKit::WebRect&); private: DISALLOW_COPY_AND_ASSIGN(Engine); }; } // namespace TestShellWebTheme #endif // WEBKIT_TOOLS_TEST_SHELL_TEST_SHELL_WEBTHEMEENGINE_H_
15ed7e46ded06b0b193ad3e58fb7b5ae2c46df68
159aed4755e47623d0aa7b652e178296be5c9604
/src/swganh_core/messages/controllers/starting_location.h
4abe79f29143466e6a0d6bff3bc9148f148053d6
[ "MIT" ]
permissive
anhstudios/swganh
fb67d42776864b1371e95f769f6864d0784061a3
41c519f6cdef5a1c68b369e760781652ece7fec9
refs/heads/develop
2020-12-24T16:15:31.813207
2016-03-08T03:54:32
2016-03-08T03:54:32
1,380,891
33
44
null
2016-03-08T03:54:32
2011-02-18T02:32:45
Python
UTF-8
C++
false
false
2,350
h
starting_location.h
// This file is part of SWGANH which is released under the MIT license. // See file LICENSE or go to http://swganh.com/LICENSE #pragma once #include <cstdint> #include <string> #include "swganh/byte_buffer.h" #include "swganh_core/messages/obj_controller_message.h" namespace swganh { namespace messages { namespace controllers { struct StartPlanet { StartPlanet() : starting_name("") , planet_name("") , x(0.0f), y(0.0f) , image_style("") , route_open(0) {} std::string starting_name; std::string planet_name; float x,y; std::string image_style; uint8_t route_open; }; class StartingLocation : public ObjControllerMessage { public: explicit StartingLocation(uint32_t controller_type = 0x0000000B) : ObjControllerMessage(controller_type, message_type()) , starting_locations(std::vector<StartPlanet>()) {} StartingLocation(const ObjControllerMessage& base) : ObjControllerMessage(base) { } static uint32_t message_type() { return 0x000001FC; } std::vector<StartPlanet> starting_locations; void OnControllerSerialize(swganh::ByteBuffer& buffer) const { buffer.write(starting_locations.size()); for(auto& location : starting_locations) { buffer.write(location.starting_name); buffer.write(location.planet_name); buffer.write<float>(0); buffer.write<float>(0); buffer.write(0); buffer.write(location.image_style); buffer.write(0); buffer.write(location.route_open); } } void OnControllerDeserialize(swganh::ByteBuffer& buffer) { int size = buffer.read<uint32_t>(); for (int i = 0; i < size; i++) { StartPlanet p; p.starting_name = buffer.read<std::string>(); p.planet_name = buffer.read<std::string>(); p.x = buffer.read<float>(); p.y = buffer.read<float>(); buffer.read<std::string>(); p.image_style = buffer.read<std::string>(); buffer.read<std::string>(); p.route_open = buffer.read<uint8_t>(); starting_locations.push_back(std::move(p)); } } }; } } } // namespace swganh::messages::controllers
b9c3515453c956a96883227a15c6491d18c97beb
47a16a6fd9e3daf9208fcaee046bdaf716f760eb
/code/265.cpp
d8512d73b0240f298c1fb59cdecaac5835c99fbd
[ "MIT" ]
permissive
Nightwish-cn/my_leetcode
ba9bf05487b60ac1d1277fb4bf1741da4556f87a
40f206e346f3f734fb28f52b9cde0e0041436973
refs/heads/master
2022-11-29T03:32:54.069824
2020-08-08T14:46:47
2020-08-08T14:46:47
287,178,162
0
0
null
null
null
null
UTF-8
C++
false
false
1,453
cpp
265.cpp
#include <bits/stdc++.h> #define INF 2000000000 using namespace std; typedef long long ll; int read(){ int f = 1, x = 0; char c = getchar(); while(c < '0' || c > '9'){if(c == '-') f = -f; c = getchar();} while(c >= '0' && c <= '9')x = x * 10 + c - '0', c = getchar(); return f * x; } struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; bool isLeaf(TreeNode* root) { return root->left == NULL && root->right == NULL; } struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: int f[1005], g[1005], h[1005]; int minCostII(vector<vector<int>>& costs) { int n = costs.size(), k = costs[0].size(); for (int i = 1; i <= k; ++i) f[i] = costs[0][i - 1]; g[0] = h[k + 1] = 0x3f3f3f3f; for (int i = 1; i < n; ++i){ for (int j = 1; j <= k; ++j) g[j] = min(g[j - 1], f[j]), h[k - j + 1] = min(h[k - j + 2], f[k - j + 1]); for (int j = 1; j <= k; ++j) f[j] = min(g[j - 1], h[j + 1]) + costs[i][j - 1]; } int ans = 0x3f3f3f3f; for (int i = 1; i <= k; ++i) ans = min(ans, f[i]); return ans; } }; Solution sol; void init(){ } void solve(){ // sol.convert(); } int main(){ init(); solve(); return 0; }
ffd793faedd67400435251a8524b98568b11837d
c6534626f28a020a25593ae274d8a49e1bfcdc7a
/mod/killbonus/main.command.h
d2353f765a33cb6f9fdd494847777242def2460d
[ "MIT" ]
permissive
MeetinaXD/bdlauncher-mods
de28267cf8db11ae0aa9bec7e99e0ab3ee56f94a
b8ba6e9c5aea50f37dc623757ae2864457eb9633
refs/heads/master
2021-01-03T19:21:57.995224
2020-02-14T12:32:29
2020-02-14T12:32:29
240,206,972
0
0
MIT
2020-02-13T08:02:57
2020-02-13T08:02:56
null
UTF-8
C++
false
false
667
h
main.command.h
#include "../command/command.h" #include "../command/parameter.h" using namespace BDL::CustomCommand; command_register_function register_commands(); enum class KillbonusMode { Reload, Debug }; class CommandKillbonus : public CustomCommandContext { public: inline static alias_list aliases = {"kbonus"}; static constexpr auto cmd_name = "killbonus"; static constexpr auto description = "Kill bonus operation"; static constexpr auto permission = CommandPermissionLevel::OP; CommandKillbonus(CommandOrigin const &origin, CommandOutput &output) noexcept : CustomCommandContext(origin, output) {} void invoke(mandatory<KillbonusMode> mode); };
9732c19bba7b3a910f88977f1ba07416764841f3
a73aee531940a43be46a51b6ec868b2de3879470
/EntityComponentSystem/ComponentPool.h
0a3f1f18dfb50e8ac2f12c96de160395af1a444c
[]
no_license
93214015/CppObjects
d6436b008edd50dc0d6213604e7dc08812890265
4325fdecf47f5738fc8648dc353c2c10d1d5e810
refs/heads/master
2023-06-25T07:04:28.194987
2021-07-29T07:34:11
2021-07-29T07:34:11
384,327,262
1
0
null
null
null
null
UTF-8
C++
false
false
597
h
ComponentPool.h
#pragma once namespace ECS { class ComponentPool final { public: ComponentPool(size_t _ComponentSize); //Copy Contructors are deleted ComponentPool(const ComponentPool&) = delete; ComponentPool& operator=(const ComponentPool&) = delete; //Move Constructor ComponentPool(ComponentPool&& _ComponentPool) noexcept; ComponentPool& operator=(ComponentPool&& _ComponentPool) noexcept; ~ComponentPool(); void* Get(size_t _Index); void* Add(); private: char* m_Data; size_t m_ComponentSize; size_t m_PoolSize; static constexpr size_t MAX_COMPONENTS = 1024; }; }
b58dd08a884efbf9eaa085379eeb67b7c43fec7c
3687ee904728af0aa012c2eba0442c3c22ff33b1
/src/Recorder.cpp
0444eac46529c6d96c1e01a4fb063016dddde586
[]
no_license
lucasjliu/omtt
f93f9e2d1de1254819a7080f8165d97b40c80149
2045ff80a23ba2afa89be1d6cbcc24cd341e2441
refs/heads/master
2020-07-02T11:49:27.967803
2017-02-13T00:52:40
2017-02-13T00:52:40
74,307,706
0
0
null
null
null
null
UTF-8
C++
false
false
3,897
cpp
Recorder.cpp
/* * by Jiahuan.Liu * 05/01/2016 * @SCUT */ #include "Recorder.h" XmlHandler::XmlHandler() :_doc() { } void XmlHandler::initialize(const char* fname) { TiXmlDeclaration* decl = new TiXmlDeclaration("1.0", "", ""); _doc.LinkEndChild(decl); _video = new TiXmlElement("Video"); _doc.LinkEndChild(_video); _video->SetAttribute("fname", fname); _video->SetAttribute("start_frame", 0); } void XmlHandler::terminate(int endFrame) { _video->SetAttribute("end_frame", endFrame); } void XmlHandler::saveTrack(unsigned int id, Track track) { _track = new TiXmlElement("Trajectory"); _video->LinkEndChild(_track); _track->SetAttribute("obj_id", id); _track->SetAttribute("start_frame", track.startFrame); _track->SetAttribute("end_frame", track.endFrame); RecordItr recordItr = track.records.begin(); for (; recordItr != track.records.end(); ++recordItr) { this->_saveRecord(*recordItr); } } void XmlHandler::_saveRecord(Record record) { _frame = new TiXmlElement("Frame"); _frame->LinkEndChild(new TiXmlText("")); _track->LinkEndChild(_frame); _frame->SetAttribute("frame_no", record.frameNum); _frame->SetAttribute("x", record.px); _frame->SetAttribute("y", record.py); _frame->SetAttribute("width", record.width); _frame->SetAttribute("height", record.height); _frame->SetAttribute("observation", "1"); } void XmlHandler::saveFile(const char* filename) { _doc.SaveFile(filename); } Recorder::Recorder() { _tracks = std::map<unsigned int, Track>(); memset(_isUsed, 0, MAX_TARGET_NUM); _xml = XmlHandler(); } Recorder::~Recorder() { std::map<unsigned int, Track>::iterator tracksItr = _tracks.begin(); for (; tracksItr != _tracks.end(); ++tracksItr) { tracksItr->second.records.clear(); } _tracks.clear(); } void Recorder::initialize(std::string videoName) { _xml.initialize(videoName.c_str()); } void Recorder::terminate(unsigned int endFrame) { _xml.terminate(endFrame); } void Recorder::saveXml(std::string filepath) { for (size_t i = 0; i < MAX_TARGET_NUM; ++i) { if (_isUsed[i]) { _xml.saveTrack(i, _tracks[i]); } } _xml.saveFile(filepath.c_str()); } int Recorder::addTrack(unsigned int frameNum) { for (size_t i = 0; i < MAX_TARGET_NUM; ++i) { if (!_isUsed[i]) { _isUsed[i] = true; _tracks[i] = Track(frameNum); return i; } } return -1; } bool Recorder::endTrack(unsigned int id, unsigned int frameNum) { if (!_isUsed[id]) return false; _tracks[id].endFrame = frameNum; return true; } bool Recorder::rmTrack(unsigned int id) { if (!_isUsed[id]) return false; _isUsed[id] = false; _tracks[id].records.clear(); _tracks.erase(id); return true; } bool Recorder::addRecord(unsigned int id, float px, float py, float width, float height, unsigned int frameNum) { if (!_isUsed[id]) return false; _tracks[id].records.push_back(Record(frameNum, px, py, width, height)); return true; } bool Recorder::mergeTrack(unsigned int id1, unsigned int id2) { if (!_isUsed[id1] || !_isUsed[id2]) return false; return true; } int Recorder::exclusionCount(unsigned int id1, unsigned int id2) { if (!_isUsed[id1] || !_isUsed[id2]) return -1; unsigned int start = Min(_tracks[id1].startFrame, _tracks[id2].startFrame); unsigned int end = Max(_tracks[id1].endFrame, _tracks[id2].endFrame); bool *flag = new bool[start - end + 1]; memset(flag, 0, start - end + 1); std::vector<Record>::iterator record = _tracks[id1].records.begin(); for (; record != _tracks[id1].records.end(); ++record) { flag[record->frameNum] = true; } int count = 0; for (; record != _tracks[id2].records.end(); ++record) { if (flag[record->frameNum]) ++count; } delete []flag; return count; } int Recorder::getStartFrame(unsigned int id) { if (!_isUsed[id]) return -1; return _tracks[id].startFrame; } int Recorder::getEndFrame(unsigned int id) { if (!_isUsed[id]) return -1; return _tracks[id].endFrame; }
82e8c8c902e1d767a00831b065ef3f88c302a5a6
eba11468cc01a8ae1d51c222473f9a66e11e22c7
/exception.h
12390efb2f3f66867bca4c18fa8574e782a456b1
[]
no_license
bakwc/lamp
3a69d3c91a7eb1394cc0170c887500ec50c39c9e
2a32935817b6b868855dfee6367aadbee19fd47b
refs/heads/master
2021-01-19T12:36:38.375028
2014-01-14T18:36:03
2014-01-14T18:36:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
286
h
exception.h
#pragma once #include <string> #include <exception> struct BaseException: public std::string, public std::exception { BaseException(const std::string &error) : std::string(error) { } const char *what() const throw() { return this->data(); } };
0e55500f83c5026bc225bebb5791e6277705655f
e2bd18a0b6a1d92755573befb52553f90c21d177
/cores/arduino/Tone.cpp
f28b03471a6e6ac1b296b6dc5e4aa38be42d6108
[ "BSD-3-Clause" ]
permissive
stm32duino/Arduino_Core_STM8
2b86bf16943a0ae4f984df79e8a8d7890feae5bf
cc4d30f28145a4778dfe228856e6ea48b00390b5
refs/heads/main
2023-09-02T11:14:06.407352
2023-03-31T07:08:07
2023-03-31T07:08:07
124,064,982
143
52
BSD-3-Clause
2021-12-08T09:57:52
2018-03-06T10:56:31
C
UTF-8
C++
false
false
1,248
cpp
Tone.cpp
/* Tone.cpp A Tone Generator Library Written by Brett Hagman This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "Arduino.h" uint8_t g_lastPin = NUM_DIGITAL_PINS; // frequency (in hertz) and duration (in milliseconds). void tone(uint8_t _pin, unsigned int frequency, unsigned long duration) { if ((g_lastPin == NUM_DIGITAL_PINS) || (g_lastPin == _pin)) { TimerPinInit(_pin, frequency, duration); g_lastPin = _pin; } } void noTone(uint8_t _pin) { TimerPinDeinit(_pin); digitalWrite((uint32_t)_pin, 0); g_lastPin = NUM_DIGITAL_PINS; }
7505ea6c5aaceffc8796a447cc2b29f492f06693
99bb7246a5577376694968cc320e34b4b8db1693
/CommonLibF4/src/RE/Bethesda/Calendar.cpp
8ef6514e13f5bf0c467c1ff003446b03063f5f65
[ "MIT" ]
permissive
Ryan-rsm-McKenzie/CommonLibF4
0d8f3baa4e3c18708e6427959f1d4f88bcf3d691
cdd932ad1f4e37f33c28ea7d7e429428f5be43dd
refs/heads/master
2023-07-26T23:24:09.615310
2023-07-16T22:53:24
2023-07-16T22:53:24
194,604,556
50
21
MIT
2023-07-20T22:20:02
2019-07-01T05:20:18
C++
UTF-8
C++
false
false
237
cpp
Calendar.cpp
#include "RE/Bethesda/Calendar.h" #include "RE/Bethesda/TESForms.h" namespace RE { float Calendar::GetHoursPassed() const noexcept { const auto days = gameDaysPassed ? gameDaysPassed->GetValue() : 1.0F; return days * 24.0F; } }
cfb5dfa72c8fe429febee5f39bc5868e3757ea7e
96f8fb7fb764026ede7e927d8b4768b8b6f44abb
/01_Code/11_win32/Day12/WinMap/WinMap.cpp
07a9046bd7198b3d6c76ac1fc2f4ea03afc483a5
[]
no_license
isongbo/MyCode
a513beaa8f43bc751aab5217314615c728ba771e
eb2330b1dbae9032ba5ad8ccd65b68375219e451
refs/heads/master
2021-01-10T09:48:53.587674
2016-01-15T10:21:04
2016-01-15T10:21:04
49,700,737
2
1
null
null
null
null
GB18030
C++
false
false
1,155
cpp
WinMap.cpp
#include "stdafx.h" #include "windows.h" #include "stdio.h" int main(int argc, char* argv[]) { // HANDLE hFile = CreateFile( "c:/map.dat", // GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ, // NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); HANDLE hMap = CreateFileMapping( NULL, NULL, PAGE_READWRITE, 0, 1024*1024, "ZJW" ); //如果第一个参数为 hFile 内核中创建一个结构 //(内存映射文件)维护一个硬盘文件 //如果第一个参数为 NULL 内核中创建一个结构 //(内存映射文件),同时申请1M内存,内存映射文件维护 //1M内存 char *pszText = (char*)MapViewOfFile( hMap, FILE_MAP_ALL_ACCESS, 0, 64*1024, 0 ); //将hMap找到的内核结构维护的硬盘文件和本进程地址建立映射 //将hMap找到的内核结构维护的1M内存和本进程地址建立映射 strcpy( pszText, "hello map" ); // printf( "%s\n", pszText ); UnmapViewOfFile( pszText ); //将本进程地址 和 硬盘文件 解除映射 //将本进程地址 和 1M内存 解除映射 CloseHandle( hMap ); //内存映射文件这个结构 一旦关闭就没了 // CloseHandle( hFile ); return 0; }
2825cf09f266173ab40f49043064ad226aaa1af5
426cb04fa92ab2c2fbaeff02847693050866e793
/src/visualizer_node.cpp
c46c51f4fd992438a151e01193017aa1e5a44eed
[ "BSD-2-Clause" ]
permissive
MIT-SPARK/pose_graph_tools
7b37afd32b2f9bb29269c8fd0e5aecbbf3185825
6012c1320cdf27aeaeee373d23f47bb3f53dd33e
refs/heads/master
2023-03-11T16:10:24.593895
2023-03-07T16:12:03
2023-03-07T16:12:03
212,649,638
21
10
BSD-2-Clause
2023-03-07T16:12:06
2019-10-03T18:25:02
C++
UTF-8
C++
false
false
240
cpp
visualizer_node.cpp
#include <pose_graph_tools/visualizer.h> #include <ros/ros.h> #include <ros/console.h> int main(int argc, char *argv[]) { // Initiallize visualizer ros::init(argc, argv, "visualizer"); ros::NodeHandle nh("~"); Visualizer viz(nh); }
645fd55b6c11d4e2242ad3929cac9168c48ec408
c646fe6627440c2653a6ff056d6f0089059c5af0
/Client/src/EncoderDecoder.cpp
a62f119233beab0d0da7f9c87dcdaac0e121bb16
[]
no_license
AsafStern/CoursesRegistrationSystem
a99ad917bcf7c5e819757ab3d1dc6ca4bf5a5bc5
10a26b59cd7fb2a5006ccb4f2d2356cce767bd49
refs/heads/master
2023-06-09T12:06:02.091546
2021-07-07T11:14:47
2021-07-07T11:14:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,752
cpp
EncoderDecoder.cpp
// // Created by spl211 on 07/01/2021. // #include <EncoderDecoder.h> #include <sstream> #include <iterator> #include <iostream> // int len // vector<char> bytes std::string EncoderDecoder::decodeLine(std::string &line) { return std::string(line.begin(), line.end()-1); } std::string EncoderDecoder::encode(std::string &message) { // a msg the client want to send std::vector<char> bytesArr(2,0); // init with {0,0} std::istringstream iss(message); std::vector<std::string> split((std::istream_iterator<std::string>(iss)), // "some string" -> ["some", "string"] std::istream_iterator<std::string>()); std::string op = split[0]; short opCode; split.erase(split.begin()); if (op == "ADMINREG") { opCode = 1; encodeString(bytesArr, split); } else if (op == "STUDENTREG") { opCode = 2; encodeString(bytesArr, split); } else if (op == "LOGIN") { opCode = 3; encodeString(bytesArr, split); } else if (op == "LOGOUT") { opCode = 4; } else if (op == "COURSEREG") { opCode = 5; encodeShort(bytesArr,split); } else if (op == "KDAMCHECK") { opCode = 6; encodeShort(bytesArr,split); } else if (op == "COURSESTAT") { opCode = 7; encodeShort(bytesArr,split); } else if (op == "STUDENTSTAT") { opCode = 8; encodeString(bytesArr, split); } else if (op == "ISREGISTERED") { opCode = 9; encodeShort(bytesArr,split); } else if (op == "UNREGISTER") { opCode = 10; encodeShort(bytesArr,split); } else if (op == "MYCOURSES") { opCode = 11; } shortToBytes(opCode, bytesArr); // inserting opCode first. return std::string(bytesArr.begin(), bytesArr.end()); // converts the vector to string } void EncoderDecoder::shortToBytes(short num, std::vector<char> &bytesArr) { bytesArr[0] = ((num >> 8) & 0xFF); bytesArr[1] = (num & 0xFF); } void EncoderDecoder::encodeString(std::vector<char> &bytesArr, std::vector<std::string> &msg) { for (std::string s:msg){ std::copy(s.begin(), s.end(), std::back_inserter(bytesArr)); // if s = "cd" and bytesArr = {'a','b'} it gives: {'a','b','c','d'} bytesArr.push_back(0); // pushing null char } } void EncoderDecoder::encodeShort(std::vector<char> &bytesArr, std::vector<std::string> &msg) { short n = std::stoi(msg[0]); // convert string to int (or short) bytesArr.push_back(((n >> 8) & 0xFF)); bytesArr.push_back((n & 0xFF)); } short EncoderDecoder::bytesToShort(char *bytesArr) { short result = (short)((bytesArr[0] & 0xff) << 8); result += (short)(bytesArr[1] & 0xff); return result; }
70ca05578e6d4c1ae80ee031fff0615643016e1d
1187ddfec6c09e1799d2557c1e0c69954c57b187
/B2/Cours/Unix/Dossier3/main.cpp
3465cf54e36e571143a74ebd78df5912fa40dc26
[]
no_license
PartageHEPL/Cours
c6714e2d81ba6bbaa70858bc16d4840de9511aaf
e4aeb746ca42bc390737f8e835999901d7d52524
refs/heads/master
2020-12-30T00:42:15.878339
2020-02-17T13:43:29
2020-02-17T13:43:29
238,799,892
0
0
null
null
null
null
UTF-8
C++
false
false
477
cpp
main.cpp
#include "MainListeEtudiants2019.h" #include <QApplication> #include <QTextCodec> #include <stdio.h> int main(int argc, char *argv[]) { QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8")); QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8")); FILE* hfF = fopen("Trace.log","w+"); dup2(fileno(hfF),2); QApplication a(argc, argv); MainListeEtudiants2019 w; w.show(); return a.exec(); }
30da06e08283399b5416ada7c7cf015bc72b9076
55060eb7ad93f401c079c768d79d752e468309f4
/main.cpp
ab250dcc71220d5021c2c533855f26f216034db9
[ "MIT" ]
permissive
VNGLR/Tic-Tac-Toe
a16b910fc5e17c4ee60cb2957ab2e3c736611f73
f740a317a6ec92a9977bad93465a25e47ffc7245
refs/heads/master
2020-03-27T14:14:40.542414
2018-08-29T20:02:57
2018-08-29T20:02:57
146,651,216
0
0
null
null
null
null
UTF-8
C++
false
false
12,613
cpp
main.cpp
/****************************************************************************** Welcome to GDB Online. GDB online is an online compiler and debugger tool for C, C++, Python, PHP, Ruby, C#, VB, Perl, Swift, Prolog, Javascript, Pascal, HTML, CSS, JS Code, Compile, Run and Debug online from anywhere in world. *******************************************************************************/ #include <stdio.h> #include <iostream> #include <string.h> #include <stdlib.h> using namespace std; //this function draws the board void drawBoard(char board[45]) { for(int i=0; i<45; i++){ cout << board[i]; } } //this functio determines if there is a draw bool drawDeterminor(char board[45], int boardCoordinates[9]){ int drawcounter = 0; for (int i = 0; i<9;i++){ if (board[boardCoordinates[i]]=='X' or board[boardCoordinates[i]]=='O'){ drawcounter++; } } if (drawcounter==9){ return true; } else{ return false; } } //this function checks if any of the players have won bool WincheckX(char board[45]){ // all win conditions with a piece in a1 if ((board[9]=='X') and (board[11]=='X') and (board[13]=='X')) { return true ; } if ((board[9]=='X') and (board[23]=='X') and (board[37]=='X')) { return true ; } if ((board[9]=='X') and (board[25]=='X') and (board[41]=='X')) { return true ; } //all win conditions starting in a2 if ((board[11]=='X') and (board[25]=='X') and (board[39]=='X')) { return true ; } //all win conditions starting in A3 if ((board[13]=='X') and (board[27]=='X') and (board[41]=='X')) { return true ; } if (board[13]=='X' and board[25]=='X' and board[37] =='X'){ return true; } //all win conditions starting in B1 if ((board[23]=='X') and (board[25]=='X') and (board[27]=='X')) { return true ; } // all win conditions starting in C1 if ((board[37]=='X') and (board[39]=='X') and (board[41]=='X')) { return true ; } return false ; } bool WincheckO(char board[45]){ // all win conditions with a piece in a1 if ((board[9]=='O') and (board[11]=='O') and (board[13]=='O')) { return true ; } if ((board[9]=='O') and (board[23]=='O') and (board[37]=='O')) { return true ; } if ((board[9]=='O') and (board[25]=='O') and (board[41]=='O')) { return true ; } //all win conditions starting in a2 if ((board[11]=='O') and (board[25]=='O') and (board[39]=='O')) { return true ; } //all win conditions starting in A3 if ((board[13]=='O') and (board[27]=='O') and (board[41]=='O')) { return true ; } if (board[13]=='O' and board[25]=='O' and board[37] =='O'){ return true; } //all win conditions starting in B1 if ((board[23]=='O') and (board[25]=='O') and (board[27]=='O')) { return true ; } // all win conditions starting in C1 if ((board[37]=='O') and (board[39]=='O') and (board[41]=='O')) { return true ; } return false; } //A function used by player to determine if space is being used before making move, and records the turn char* Checkspace(char board[45],int position,bool moveX){ if ((board[position]=='X') or (board[position]=='O') or (board[position]=='-') or (board[position]=='|')){ cout << "Space already occupied please select another move"; } else{ if (moveX== true){ board[position] ='X'; } else{ board[position] ='O'; } return board; } } //This function handles the "AI" //The "AI" works with random number generation char* aiTurn(char board[45],bool AIx){ // cout << "AI turn started"; int aiGuess = 0; bool aiHit = false; //the user X bool will be flipped for the AI purpose, making it comptaible with checkspace if(AIx==true){ AIx=false; } else if(AIx==false){ AIx=true; } //initalizes random seed srand (time(NULL)); //cout << "random number initialized"; while (aiHit== false){ //generates random number 0 through 8(9 playable spaces) aiGuess = rand() % 8; if (aiGuess==0){ if (board[9]!='X' and board[9]!='O'){ strcpy(board,Checkspace(board,9,AIx)); cout <<"the ai moved to a1"; return board; } } else if (aiGuess==1){ if (board[11]!='X' and board[11]!='O'){ strcpy(board,Checkspace(board,11,AIx)); cout <<"the ai moved to a2"; return board; } } else if (aiGuess==2){ if (board[13]!='X' and board[13]!='O'){ strcpy(board,Checkspace(board,13,AIx)); cout <<"the ai moved to a3"; return board; } } else if (aiGuess==3){ if (board[23]!='X' and board[23]!='O'){ strcpy(board,Checkspace(board,23,AIx)); cout <<"the ai moved to b1"; return board; } } else if (aiGuess==4){ if (board[25]!='X' and board[25]!='O'){ strcpy(board,Checkspace(board,25,AIx)); cout <<"the ai moved to b2"; return board; } } else if (aiGuess==5){ if (board[27]!='X' and board[27]!='O'){ strcpy(board,Checkspace(board,27,AIx)); cout <<"the ai moved to b3"; return board; } } else if (aiGuess==6){ if (board[37]!='X' and board[37]!='O'){ strcpy(board,Checkspace(board,37,AIx)); cout <<"the ai moved to c1"; return board; } } else if (aiGuess==7){ if (board[39]!='X' and board[39]!='O'){ strcpy(board,Checkspace(board,39,AIx)); cout <<"the ai moved to c2"; return board; } } else if (aiGuess==8){ if (board[41]!='X' and board[41]!='O'){ strcpy(board,Checkspace(board,41,AIx)); cout <<"the ai moved to c3"; return board; } } } } // This function handles player turns char* userTurn(char board[45],bool userX){ string UserInputTurn; bool playerTurnComplete = false; int moveCoordinates = 0; cout <<"In coordinates, where do you want to mark?"; cin>>UserInputTurn; while(playerTurnComplete==false){ if ((UserInputTurn=="A1") and (board[9]!='X') and (board[9]!='O')){ strcpy(board,Checkspace(board,9,userX)); return board; } else if ((UserInputTurn=="A2") and (board[11]!='X') and (board[11]!='O')){ strcpy(board,Checkspace(board,11,userX)); return board; } else if ((UserInputTurn=="A3") and (board[13]!='X') and (board[13]!='O')){ strcpy(board,Checkspace(board,13,userX)); return board; } else if ((UserInputTurn=="B1") and (board[23]!='X') and (board[23]!='O')){ strcpy(board,Checkspace(board,23,userX)); return board; } else if ((UserInputTurn=="B2") and (board[25]!='X') and (board[25]!='O')){ strcpy(board,Checkspace(board,25,userX)); return board; } else if ((UserInputTurn=="B3") and (board[27]!='X') and (board[27]!='O')){ strcpy(board,Checkspace(board,27,userX)); return board; } else if ((UserInputTurn=="C1") and (board[37]!='X') and (board[37]!='O')){ strcpy(board,Checkspace(board,37,userX)); return board; } else if ((UserInputTurn=="C2") and (board[39]!='X') and (board[39]!='O')){ strcpy(board,Checkspace(board,39,userX)); return board; } else if ((UserInputTurn=="C3") and (board[41]!='X') and (board[41]!='O')){ strcpy(board,Checkspace(board,41,userX)); return board; } else{ cout<<"Coordinates invalid, please retype informat A1:"; cin>>UserInputTurn; } } } int main() { //variables for team bool userX; bool userTeamset = false; //variables for go first or second bool userFirst = false; bool userSecond = false; string Userinput; bool win=false ; bool playerwin = false; bool draw = false; bool aiWin= false; int boardCoordinates[9] ={9,11,13,23,25,27,37,39,41}; //game board // for some reason string aray didn't work? char board[45] = {' ','1',' ','2',' ','3' ,' ','\n' ,'A',' ', '|', ' ', '|', ' ', '\n' ,' ', '-', '-', '-', '-', '-', '\n' ,'B', ' ', '|', ' ', '|', ' ', '\n' ,' ', '-', '-', '-', '-', '-', '\n' ,'C', ' ', '|', ' ', '|', ' ', '\n'}; //Handles user team cout << "Do you want to be X or Os? "; while(userTeamset == false){ cin >> Userinput; if(Userinput == "X"){ userX = true; userTeamset = true; } else if(Userinput == "O") { userX = false; userTeamset = true; } else{ cout << "Please specify the letter X or O: "; } } //handles if user goes first or second cout << "Do you want go first or second? "; while((userFirst == false) and (userSecond == false)){ cin >> Userinput; if(Userinput == "first"){ userFirst = true; userSecond = false; } else if(Userinput == "second") { userFirst = false; userSecond = true; } else{ cout << "Please specify first or second: "; } } //draws game board drawBoard(board); //deals with user turns // both bools are needed for user first and second to tell if one is set if (userFirst==false){ cout<< "------The AI makes his turn-----"<<endl; strcpy(board,aiTurn(board,userX)); drawBoard(board); } while(win== false){ // if(userFirst== true){ draw = drawDeterminor(board,boardCoordinates); if (draw== true){ win= true; } if (win==false){ strcpy(board,userTurn(board,userX)); drawBoard(board); } win = WincheckX(board); if (win== false){ draw = drawDeterminor(board,boardCoordinates); } if (win== true){ if (userX== true){ playerwin= true; } } if (win ==false){ win = WincheckO(board); } if (win== true){ if (userX== false){ playerwin= true; } } if ((win == false) and draw== false){ cout<< "------The AI makes his turn-----"<<endl; strcpy(board,aiTurn(board,userX)); drawBoard(board); win = WincheckX(board); if (win== true){ if (userX== true){ playerwin= false; aiWin= true; } } if (win ==false){ win = WincheckO(board); } if (win== true){ if (userX== false){ playerwin= false; aiWin= true; } } } if (draw==true){ win = true; } } if (draw== true){ cout<<"draw!"; } else if (playerwin== true){ cout <<"Congradulations player!"; } else{ cout<<"better luck next time"; } return 0; }
cb11d6cb756e5f8ce6edd065c4d443fbfa43a2da
5abfdfe1b17a1f42009693d57b8354274dcbbfbe
/Controller/anomalia.h
c4bd23d168469c3b060491279c1474d7878460f0
[]
no_license
gomitolof/CarsCrew
b310a3d6468d1678af32ca130b65105a73906cdc
49673dbdb995eea03b0c572244f5a8bad34d5c67
refs/heads/master
2021-03-27T22:56:45.727229
2020-03-16T21:29:55
2020-03-16T21:29:55
247,815,585
0
0
null
null
null
null
UTF-8
C++
false
false
172
h
anomalia.h
#ifndef ANOMALIA_H #define ANOMALIA_H class Anomalia { private: char err; public: Anomalia(char x='d'); char getError() const; }; #endif // ANOMALIA_H
86fb1b044cdc03f3f3b0c13f5dec96ef6e7fed80
a2b2e7496e604d6921dc8400120501bc9435ba16
/src/pelmeni/graphics/Frame.hpp
89a60b0f3774dea2372ec6aa9984d09ab133df7c
[]
no_license
tomvidm/Pelmeni2D
aae4f18dbaf54361ae139ef8c14c50bbdcd4c257
1366459c471cdbf52cf5f044d2a0369c0436ad2d
refs/heads/master
2021-03-30T22:53:45.084594
2018-07-13T13:45:21
2018-07-13T13:45:21
124,583,807
0
0
null
null
null
null
UTF-8
C++
false
false
631
hpp
Frame.hpp
#pragma once #include "SFML/System/Time.hpp" #include "SFML/Graphics/Rect.hpp" namespace p2d { namespace graphics { struct Frame { Frame(const sf::Time& t, const sf::Rect<float>& rect) : duration(t), frameRect(rect) {;} Frame(const sf::Time& t, const float x, const float y, const float xsize, const float ysize) : duration(t) { frameRect = sf::Rect<float>(x, y, xsize, ysize); } sf::Time duration; sf::Rect<float> frameRect; }; // struct Frame } // namespace graphics } // namespace p2d
b3b7569fc66013a45b31d957ba48eddeaaee6789
760813dcae563bc8cb071b571c61ea1786118359
/fastIA-master/test/features/sample_test.cpp
940d9b35cbf3970a44fa1da9bdc86b4941141f06
[ "Apache-2.0" ]
permissive
sharmaashish/emory-cci-fast-ia-gsoc
9fa085e37177d0eafc79d5be21f924dba37d4804
5e8af0ba1d422d577b8125eecc8e7de9ac148fb6
refs/heads/master
2021-01-10T04:19:55.824176
2013-10-19T15:06:22
2013-10-19T15:06:22
53,596,067
0
0
null
null
null
null
UTF-8
C++
false
false
150
cpp
sample_test.cpp
#define BOOST_TEST_MAIN #define BOOST_TEST_DYN_LINK #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_CASE( test1 ) { BOOST_CHECK(2 == 2); }