hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
1ded228953a0084792047c7956b4bfbcdb53be37
16,807
cpp
C++
llvm/tools/file-table-tform/file-table-tform.cpp
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
653
2018-12-27T15:00:01.000Z
2022-03-30T11:52:23.000Z
llvm/tools/file-table-tform/file-table-tform.cpp
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
3,740
2019-01-23T15:36:48.000Z
2022-03-31T22:01:13.000Z
llvm/tools/file-table-tform/file-table-tform.cpp
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
500
2019-01-23T07:49:22.000Z
2022-03-30T02:59:37.000Z
//===- file-table-tform.cpp - transform files with tables of strings ------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // This tool transforms a series of input file tables into single output file // table according to operations passed on the command line. Operations' // arguments are input files, and some operations like 'rename' take single // input, others like 'replace' take two. Operations are executed in // command-line order and consume needed amount of inputs left-to-right in the // command-line order. Table files and operation example: // $ cat a.txt // [Code|Symbols|Properties] // a_0.bc|a_0.sym|a_0.props // a_1.bc|a_1.sym|a_1.props // // $ cat b.txt: // [Files|Attrs] // a_0.spv|aa.attr // a_1.spv|bb.attr // // $ file-table-tform --replace=Code,Files a.txt b.txt -o c.txt // // $ cat c.txt // [Code|Symbols|Properties] // a_0.spv|a_0.sym|a_0.props // a_1.spv|a_1.sym|a_1.props // // The tool for now supports only linear transformation sequences like shown on // the graph below. 'op*' represent operations, 'Input' is the main input file, // 'Output' is the single output file, edges are directed and designate inputs // and outputs of the operations. // File1 File3 // \ \ // Input - op1 - op2 - op3 - Output // / // File2 // More complex transformation trees such as: // File0 - op0 File3 // \ \ // Input - op1 - op2 - op3 - Output // / // File2 // are not supported. For now, "File0 - op0" transformation must be done in a // separate tool invocation. // TODO support SQL-like transformation style if the tool ever evolves. #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/Twine.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Errc.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/InitLLVM.h" #include "llvm/Support/SimpleTable.h" #include "llvm/Support/WithColor.h" #include <algorithm> #include <functional> #include <map> #include <memory> #include <string> using namespace llvm; static StringRef ToolName; // set in main first thing cl::OptionCategory FileTableTformCat{"file-table-tform Options"}; static cl::list<std::string> Inputs(cl::Positional, cl::ZeroOrMore, cl::desc("<input filenames>"), cl::cat(FileTableTformCat)); static cl::opt<std::string> Output("o", cl::Required, cl::desc("<output filename>"), cl::value_desc("filename"), cl::cat(FileTableTformCat)); static constexpr char OPT_REPLACE[] = "replace"; static constexpr char OPT_REPLACE_CELL[] = "replace_cell"; static constexpr char OPT_RENAME[] = "rename"; static constexpr char OPT_EXTRACT[] = "extract"; static constexpr char OPT_COPY_SINGLE_FILE[] = "copy_single_file"; static cl::list<std::string> TformReplace{ OPT_REPLACE, cl::ZeroOrMore, cl::desc("replace a column"), cl::value_desc("<column name or ordinal>"), cl::cat(FileTableTformCat)}; static cl::list<std::string> TformReplaceCell{ OPT_REPLACE_CELL, cl::ZeroOrMore, cl::desc("replace a cell"), cl::value_desc("<column name or ordinal>,<row id ordinal>"), cl::cat(FileTableTformCat)}; static cl::list<std::string> TformRename{ OPT_RENAME, cl::ZeroOrMore, cl::desc("rename a column"), cl::value_desc("<old_name>,<new_name>"), cl::cat(FileTableTformCat)}; static cl::list<std::string> TformExtract{ OPT_EXTRACT, cl::ZeroOrMore, cl::desc("extract column(s) identified by names"), cl::value_desc("<name1>,<name2>,..."), cl::cat(FileTableTformCat)}; static cl::list<std::string> TformCopySingleFile{ OPT_COPY_SINGLE_FILE, cl::ZeroOrMore, cl::desc("copy the file in a cell and make it the output"), cl::value_desc("<column name or ordinal>,<row id ordinal>"), cl::cat(FileTableTformCat)}; static cl::opt<bool> DropTitles{"drop_titles", cl::Optional, cl::desc("drop column titles"), cl::cat(FileTableTformCat)}; Error makeToolError(Twine Msg) { return make_error<StringError>("*** " + llvm::Twine(ToolName) + " ERROR: " + Msg, inconvertibleErrorCode()); } Error makeIOError(Twine Msg) { return make_error<StringError>( "*** " + Twine(ToolName) + " SYSTEM ERROR: " + Msg, errc::io_error); } Error makeUserError(Twine Msg) { return createStringError(errc::invalid_argument, "*** " + Twine(ToolName) + " usage ERROR: " + Msg); } struct TformCmd { using UPtrTy = std::unique_ptr<TformCmd>; StringRef Kind; SmallVector<StringRef, 2> Args; SmallVector<StringRef, 2> Inputs; TformCmd() = default; TformCmd(StringRef Kind) : Kind(Kind) {} static Expected<UPtrTy> create(StringRef Kind, StringRef RawArg = "") { UPtrTy Res = std::make_unique<TformCmd>(Kind); Error E = Res->parseArg(RawArg); if (E) return std::move(E); return std::move(Res); } using InpIt = cl::list<std::string>::iterator; Error consumeSingleInput(InpIt &Cur, const InpIt End) { if (Cur == End) return makeUserError("no input for '" + Twine(Kind) + "' command"); if (!llvm::sys::fs::exists(*Cur)) return makeIOError("file not found: " + Twine(*Cur)); Inputs.push_back(*Cur); Cur++; return Error::success(); } using Func = std::function<Error(TformCmd *)>; Error consumeInput(InpIt Cur, const InpIt End) { Func F = StringSwitch<Func>(Kind) .Case(OPT_REPLACE, [&](TformCmd *Cmd) { return Cmd->consumeSingleInput(Cur, End); }) .Case(OPT_REPLACE_CELL, [&](TformCmd *Cmd) { return Cmd->consumeSingleInput(Cur, End); }) .Case(OPT_RENAME, [&](TformCmd *Cmd) { return Error::success(); }) .Case(OPT_EXTRACT, [&](TformCmd *Cmd) { return Error::success(); }) .Case(OPT_COPY_SINGLE_FILE, [&](TformCmd *Cmd) { return Error::success(); }); return F(this); } Error parseArg(StringRef Arg) { Func F = StringSwitch<Func>(Kind) // need '-> Error' return type declaration in the lambdas below as // it can't be deduced automatically .Case(OPT_REPLACE, [&](TformCmd *Cmd) -> Error { // argument is <column name> if (Arg.empty()) return makeUserError("empty argument in " + Twine(OPT_REPLACE)); Arg.split(Args, ','); if (Args.size() != 2 || Args[0].empty() || Args[1].empty()) return makeUserError("invalid argument in " + Twine(OPT_REPLACE)); return Error::success(); }) .Case(OPT_REPLACE_CELL, [&](TformCmd *Cmd) -> Error { // argument is <column name>,<row index> if (Arg.empty()) return makeUserError("empty argument in " + Twine(OPT_REPLACE_CELL)); Arg.split(Args, ','); if (Args.size() != 2 || Args[0].empty() || Args[1].empty()) return makeUserError("invalid argument in " + Twine(OPT_REPLACE_CELL)); return Error::success(); }) .Case(OPT_RENAME, [&](TformCmd *Cmd) -> Error { // argument is <old_name>,<new_name> if (Arg.empty()) return makeUserError("empty argument in " + Twine(OPT_RENAME)); auto Names = Arg.split(','); if (Names.first.empty() || Names.second.empty()) return makeUserError("invalid argument in " + Twine(OPT_RENAME)); Args.push_back(Names.first); Args.push_back(Names.second); return Error::success(); }) .Case( OPT_EXTRACT, [&](TformCmd *Cmd) -> Error { // argument is <name1>,<name2>,... (1 or more) if (Arg.empty()) return makeUserError("empty argument in " + Twine(OPT_RENAME)); SmallVector<StringRef, 3> Names; Arg.split(Names, ','); if (std::find(Names.begin(), Names.end(), "") != Names.end()) return makeUserError("empty name in " + Twine(OPT_RENAME)); std::copy(Names.begin(), Names.end(), std::back_inserter(Args)); return Error::success(); }) .Case(OPT_COPY_SINGLE_FILE, [&](TformCmd *Cmd) -> Error { // argument is <column name>,<row index> if (Arg.empty()) return makeUserError("empty argument in " + Twine(OPT_COPY_SINGLE_FILE)); Arg.split(Args, ','); if (Args.size() != 2 || Args[0].empty() || Args[1].empty()) return makeUserError("invalid argument in " + Twine(OPT_COPY_SINGLE_FILE)); return Error::success(); }); return F(this); } Error execute(util::SimpleTable &Table) { Func F = StringSwitch<Func>(Kind) .Case(OPT_REPLACE, [&](TformCmd *Cmd) -> Error { // argument is <column name> assert(Cmd->Args.size() == 2 && Cmd->Inputs.size() == 1); Expected<util::SimpleTable::UPtrTy> Table1 = util::SimpleTable::read(Cmd->Inputs[0]); if (!Table1) return Table1.takeError(); Error Res = Table.replaceColumn(Args[0], *Table1->get(), Args[1]); return Res ? std::move(Res) : std::move(Error::success()); }) .Case(OPT_REPLACE_CELL, [&](TformCmd *Cmd) -> Error { // argument is <column name>,<row index> assert(Args.size() == 2 && Cmd->Inputs.size() == 1); const int Row = std::stoi(Args[1].str()); Error Res = Table.updateCellValue(Args[0], Row, Cmd->Inputs[0]); return Res ? std::move(Res) : std::move(Error::success()); }) .Case(OPT_RENAME, [&](TformCmd *Cmd) -> Error { // argument is <old_name>,<new_name> assert(Args.size() == 2); Error Res = Table.renameColumn(Args[0], Args[1]); return Res ? std::move(Res) : std::move(Error::success()); }) .Case(OPT_EXTRACT, [&](TformCmd *Cmd) -> Error { // argument is <name1>,<name2>,... (1 or more) assert(!Args.empty()); Error Res = Table.peelColumns(Args); return Res ? std::move(Res) : std::move(Error::success()); }) .Case(OPT_COPY_SINGLE_FILE, [&](TformCmd *Cmd) -> Error { // argument is <column name>,<row index> assert(Args.size() == 2); const int Row = std::stoi(Args[1].str()); if (Row >= Table.getNumRows()) return makeUserError("row index is out of bounds"); // Copy the file from the only remaining row at specified // column StringRef FileToCopy = Table[Row].getCell(Args[0], ""); if (FileToCopy.empty()) return makeUserError("no file found in specified column"); std::error_code EC = sys::fs::copy_file(FileToCopy, Output); return EC ? createFileError(Output, EC) : std::move(Error::success()); }); return F(this); } }; #define CHECK_AND_EXIT(E) \ { \ Error LocE = E; \ if (LocE) { \ logAllUnhandledErrors(std::move(LocE), WithColor::error(errs())); \ return 1; \ } \ } int main(int argc, char **argv) { ToolName = argv[0]; // make tool name available for functions in this source InitLLVM X{argc, argv}; cl::HideUnrelatedOptions(FileTableTformCat); cl::ParseCommandLineOptions( argc, argv, "File table transformation tool.\n" "Inputs and output of this tool is a \"file table\" files containing\n" "2D table of strings with optional row of column titles. Based on\n" "transformation actions passed via the command line, the tool\n" "transforms the first input file table and emits either a new file\n" "table or a copy of a file in a cell of the input table.\n" "\n" "Transformation actions are:\n" "- replace a column\n" "- replace a cell\n" "- rename a column\n" "- extract column(s)\n" "- ouput a copy of a file in a cell\n"); std::map<int, TformCmd::UPtrTy> Cmds; // Partially construct commands (w/o input information). Can't fully construct // yet, as an order across all command line options-commands needs to be // established first to properly map inputs to commands. auto Lists = {std::addressof(TformReplace), std::addressof(TformReplaceCell), std::addressof(TformRename), std::addressof(TformExtract), std::addressof(TformCopySingleFile)}; for (const auto *L : Lists) { for (auto It = L->begin(); It != L->end(); It++) { Expected<TformCmd::UPtrTy> Cmd = TformCmd::create(L->ArgStr, *It); if (!Cmd) CHECK_AND_EXIT(Cmd.takeError()); const int Pos = L->getPosition(It - L->begin()); Cmds.emplace(Pos, std::move(Cmd.get())); } } // finish command construction first w/o execution to make sure command line // is valid auto CurInput = Inputs.begin(); const auto EndInput = Inputs.end(); // first input is the "current" - it will undergo the transformation sequence if (CurInput == EndInput) CHECK_AND_EXIT(makeUserError("no inputs")); std::string &InputFile = *CurInput++; // ensure that if copy_single_file is specified, it must be the last tform bool HasCopySingleFileTform = false; for (auto &P : Cmds) { if (HasCopySingleFileTform) { CHECK_AND_EXIT( makeUserError("copy_single_file must be the last transformation")); } HasCopySingleFileTform = P.second->Kind == OPT_COPY_SINGLE_FILE; } for (auto &P : Cmds) { TformCmd::UPtrTy &Cmd = P.second; // this will advance cur iterator as far as needed Error E = Cmd->consumeInput(CurInput, EndInput); CHECK_AND_EXIT(std::move(E)); } // commands are constructed, command line is correct - read input and execute // transformations on it Expected<util::SimpleTable::UPtrTy> Table = util::SimpleTable::read(InputFile); if (!Table) CHECK_AND_EXIT(Table.takeError()); for (auto &P : Cmds) { TformCmd::UPtrTy &Cmd = P.second; Error Res = Cmd->execute(*Table->get()); CHECK_AND_EXIT(std::move(Res)); } // If copy_single_file was specified the output file is generated by the // corresponding transformation. if (!HasCopySingleFileTform) { // Write the transformed table to file std::error_code EC; raw_fd_ostream Out{Output, EC, sys::fs::OpenFlags::OF_None}; if (EC) CHECK_AND_EXIT(createFileError(Output, EC)); Table->get()->write(Out, !DropTitles); if (Out.has_error()) CHECK_AND_EXIT(createFileError(Output, Out.error())); Out.close(); } return 0; }
40.304556
80
0.540311
[ "transform" ]
1df40a5f8b906a90684526c651dcc2de72f83bb1
4,909
cpp
C++
src/pcl_midterm/pclFastTriangular.cpp
michael081906/ros-project-robotic-polishing
12f02befa244dc2cfdb3e3e5f89c8d3f25fde7bb
[ "BSD-3-Clause" ]
5
2020-10-01T19:59:23.000Z
2022-02-09T02:48:53.000Z
src/pcl_midterm/pclFastTriangular.cpp
michael081906/Robotic-polishing
12f02befa244dc2cfdb3e3e5f89c8d3f25fde7bb
[ "BSD-3-Clause" ]
1
2021-01-08T07:20:12.000Z
2021-01-08T07:33:21.000Z
src/pcl_midterm/pclFastTriangular.cpp
michael081906/Robotic-polishing
12f02befa244dc2cfdb3e3e5f89c8d3f25fde7bb
[ "BSD-3-Clause" ]
4
2020-12-03T12:47:33.000Z
2022-01-28T06:25:37.000Z
// "Copyright [2017] <Michael Kam>" /** @file pclFastTriangular.cpp * @brief This is the implementation of the pclFastTriangular class. This class consists of 6 methods. * Please refer the pclFastTriangular.h for more detail. * * @author Michael Kam (michael081906) * @bug No known bugs. * @copyright GNU Public License. * * pclFastTriangular is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * pclFastTriangular 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 pclFastTriangular. If not, see <http://www.gnu.org/licenses/>. */ #include <pcl/io/io.h> #include <pcl/io/pcd_io.h> #include <pcl/point_types.h> #include <pcl/kdtree/kdtree_flann.h> #include <pcl/features/normal_3d.h> #include <pcl/surface/gp3.h> #include <pclFastTriangular.h> #include <ios> #include <vector> #include <iostream> // using namespace pcl; pclFastTriangular::pclFastTriangular() { searchRadius = 0; } void pclFastTriangular::setSearchRadius(double radius) { searchRadius = radius; } double pclFastTriangular::getSearchRadius() { return searchRadius; } void pclFastTriangular::setInputCloud( pcl::PointCloud<pcl::PointNormal>& cloudIn) { cloud = cloudIn; } void pclFastTriangular::getInputCloud( pcl::PointCloud<pcl::PointNormal>& cloudOut) { cloudOut = cloud; } void pclFastTriangular::reconctruct(pcl::PolygonMesh& triangles) { pcl::search::KdTree<pcl::PointNormal>::Ptr tree( new pcl::search::KdTree<pcl::PointNormal>); cloudPtr = cloud.makeShared(); tree->setInputCloud(cloudPtr); // Set the maximum distance between connected points (maximum edge length) /* * The method works by maintaining a list of points from which the mesh can be * grown (“fringe” points) and extending it until all possible points are connected. * It can deal with unorganized points, coming from one or multiple scans, and having * multiple connected parts. It works best if the surface is locally smooth and there * are smooth transitions between areas with different point densities. * * Triangulation is performed locally, by projecting the local neighborhood of a point * along the point’s normal, and connecting unconnected points. Thus, the following parameters * can be set: * * 1. setMaximumNearestNeighbors(unsigned) and setMu(double) control the size of the neighborhood. * The former defines how many neighbors are searched for, while the latter specifies the maximum * acceptable distance for a point to be considered, relative to the distance of the nearest point * (in order to adjust to changing densities). Typical values are 50-100 and 2.5-3 (or 1.5 for grids). * * 2. setSearchRadius(double) is practically the maximum edge length for every triangle. This has * to be set by the user such that to allow for the biggest triangles that should be possible. * * 3. setMinimumAngle(double) and setMaximumAngle(double) are the minimum and maximum angles * in each triangle. While the first is not guaranteed, the second is. Typical values are 10 * and 120 degrees (in radians). * * 4.setMaximumSurfaceAgle(double) and setNormalConsistency(bool) are meant to deal with * the cases where there are sharp edges or corners and where two sides of a surface run very * close to each other. To achieve this, points are not connected to the current point if their * normals deviate more than the specified angle (note that most surface normal estimation methods * produce smooth transitions between normal angles even at sharp edges). This angle is computed * as the angle between the lines defined by the normals (disregarding the normal’s direction) * if the normal-consistency-flag is not set, as not all normal estimation methods can guarantee * consistently oriented normals. Typically, 45 degrees (in radians) and false works on most datasets. */ gp3.setSearchRadius(searchRadius); gp3.setMu(5); // specifies the maximum acceptable distance for a point to be considered gp3.setMaximumNearestNeighbors(20); // how many neighbors are searched for gp3.setMaximumSurfaceAngle(M_PI / 4); // 45 degrees gp3.setMinimumAngle(M_PI / 18); // 10 degrees gp3.setMaximumAngle(2 * M_PI / 3); // 120 degrees gp3.setNormalConsistency(false); // Get result gp3.setInputCloud(cloudPtr); gp3.setSearchMethod(tree); gp3.reconstruct(triangles); } std::vector<int> pclFastTriangular::getSegID() { return gp3.getPartIDs(); }
45.036697
104
0.746995
[ "mesh", "vector" ]
1dfbb47c2000b6b225ca914e3f195446e0b65d56
2,900
hh
C++
policy-decision-point/function.hh
SSICLOPS/cppl
265514bc461352b7b5bc58fd7482328601029e4a
[ "Apache-2.0" ]
1
2018-06-02T11:50:06.000Z
2018-06-02T11:50:06.000Z
policy-decision-point/function.hh
SSICLOPS/cppl
265514bc461352b7b5bc58fd7482328601029e4a
[ "Apache-2.0" ]
1
2018-01-17T04:16:29.000Z
2018-01-30T09:01:44.000Z
policy-decision-point/function.hh
SSICLOPS/cppl
265514bc461352b7b5bc58fd7482328601029e4a
[ "Apache-2.0" ]
1
2018-11-18T20:31:54.000Z
2018-11-18T20:31:54.000Z
// Copyright 2015-2018 RWTH Aachen University // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include <vector> #include "variable.hh" #include "node_parameter.hh" #ifdef __DEBUG__ #include<iostream> #endif #define __DO_FUNC_EVAL__(op) \ Variable * pv = (*handler)(param_list, *current_node_parameters);\ bool b = (*pv op v);\ delete pv;\ return b typedef Variable * (* func_handler_type)(const std::vector<Variable *> &, const NodeParameters *); class Function:public Variable{ public: Function(id_type id, func_handler_type h, const NodeParameters ** current) :Variable(Variable::Types::FUNCTION), current_node_parameters(current), id(id), handler(h) { } ~Function(){ for (auto it = param_list.begin(); it != param_list.end(); ++it) delete *it; } inline id_type get_id() const{return id;} void addParam(Variable * v){param_list.push_back(v);} inline id_type getParameterNum() const {return param_list.size();} inline const Variable * getParameter(id_type id) const {return param_list[id];} private: bool isEqu(const Variable & v) const{ __DO_FUNC_EVAL__(==); } bool isNeq(const Variable & v) const{ __DO_FUNC_EVAL__(!=); } bool isLess(const Variable & v) const { __DO_FUNC_EVAL__(<); } bool isLeq(const Variable & v) const { __DO_FUNC_EVAL__(<=); } bool isGre(const Variable & v) const { __DO_FUNC_EVAL__(>); } bool isGeq(const Variable & v) const { __DO_FUNC_EVAL__(>=); } bool _isTrue() const { #ifdef __DEBUG__ std::cout<<"funtion handler: "<<handler<<std::endl; std::cout<<"node parameters: "<<current_node_parameters<<std::endl; #endif Variable * pv = (*handler)(param_list, *current_node_parameters); bool b = pv->isTrue(); delete pv; return b; } bool _sameAs(const Variable & v) const{ if (this->get_type() != v.get_type()) return false; if (id != reinterpret_cast<const Function &>(v).get_id()) return false; size_t i = 0; for (; i != param_list.size() && param_list[i]->sameAs(*(reinterpret_cast<const Function &>(v).param_list[i])); ++i); if (i == param_list.size()) return true; else return false; } const NodeParameters ** current_node_parameters; id_type id; std::vector<Variable *> param_list; Variable * (*handler)(const std::vector<Variable *> & param, const NodeParameters * current); };
27.102804
120
0.686897
[ "vector" ]
3800aa91f80ffb57f3702bed923cc49a4de586da
28,000
cpp
C++
Source/WebCore/editing/AlternativeTextController.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
6
2021-07-05T16:09:39.000Z
2022-03-06T22:44:42.000Z
Source/WebCore/editing/AlternativeTextController.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
7
2022-03-15T13:25:39.000Z
2022-03-15T13:25:44.000Z
Source/WebCore/editing/AlternativeTextController.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (C) 2006-2017 Apple Inc. All rights reserved. * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "AlternativeTextController.h" #include "Document.h" #include "DocumentMarkerController.h" #include "Editing.h" #include "Editor.h" #include "EditorClient.h" #include "Element.h" #include "FloatQuad.h" #include "Frame.h" #include "FrameView.h" #include "Page.h" #include "Range.h" #include "RenderedDocumentMarker.h" #include "SpellingCorrectionCommand.h" #include "TextCheckerClient.h" #include "TextCheckingHelper.h" #include "TextEvent.h" #include "TextIterator.h" #include "VisibleUnits.h" #include "markup.h" namespace WebCore { #if USE(DICTATION_ALTERNATIVES) || USE(AUTOCORRECTION_PANEL) constexpr OptionSet<DocumentMarker::MarkerType> markerTypesForAppliedDictationAlternative() { return DocumentMarker::SpellCheckingExemption; } #endif #if USE(AUTOCORRECTION_PANEL) static inline OptionSet<DocumentMarker::MarkerType> markerTypesForAutocorrection() { return { DocumentMarker::Autocorrected, DocumentMarker::CorrectionIndicator, DocumentMarker::Replacement, DocumentMarker::SpellCheckingExemption }; } static inline OptionSet<DocumentMarker::MarkerType> markerTypesForReplacement() { return { DocumentMarker::Replacement, DocumentMarker::SpellCheckingExemption }; } static bool markersHaveIdenticalDescription(const Vector<RenderedDocumentMarker*>& markers) { if (markers.isEmpty()) return true; const String& description = markers[0]->description(); for (size_t i = 1; i < markers.size(); ++i) { if (description != markers[i]->description()) return false; } return true; } AlternativeTextController::AlternativeTextController(Document& document) : m_timer(*this, &AlternativeTextController::timerFired) , m_document(document) { } AlternativeTextController::~AlternativeTextController() { dismiss(ReasonForDismissingAlternativeTextIgnored); } void AlternativeTextController::startAlternativeTextUITimer(AlternativeTextType type) { const Seconds correctionPanelTimerInterval { 300_ms }; if (!isAutomaticSpellingCorrectionEnabled()) return; // If type is PanelTypeReversion, then the new range has been set. So we shouldn't clear it. if (type == AlternativeTextTypeCorrection) m_rangeWithAlternative = WTF::nullopt; m_type = type; m_timer.startOneShot(correctionPanelTimerInterval); } void AlternativeTextController::stopAlternativeTextUITimer() { m_timer.stop(); m_rangeWithAlternative = WTF::nullopt; } void AlternativeTextController::stopPendingCorrection(const VisibleSelection& oldSelection) { // Make sure there's no pending autocorrection before we call markMisspellingsAndBadGrammar() below. VisibleSelection currentSelection(m_document.selection().selection()); if (currentSelection == oldSelection) return; stopAlternativeTextUITimer(); dismiss(ReasonForDismissingAlternativeTextIgnored); } void AlternativeTextController::applyPendingCorrection(const VisibleSelection& selectionAfterTyping) { // Apply pending autocorrection before next round of spell checking. bool doApplyCorrection = true; VisiblePosition startOfSelection = selectionAfterTyping.visibleStart(); VisibleSelection currentWord = VisibleSelection(startOfWord(startOfSelection, LeftWordIfOnBoundary), endOfWord(startOfSelection, RightWordIfOnBoundary)); if (currentWord.visibleEnd() == startOfSelection) { if (auto wordRange = currentWord.firstRange()) { String wordText = plainText(*wordRange); if (!wordText.isEmpty() && isAmbiguousBoundaryCharacter(wordText[wordText.length() - 1])) doApplyCorrection = false; } } if (doApplyCorrection) handleAlternativeTextUIResult(dismissSoon(ReasonForDismissingAlternativeTextAccepted)); else m_rangeWithAlternative = WTF::nullopt; } bool AlternativeTextController::hasPendingCorrection() const { return m_rangeWithAlternative.hasValue(); } bool AlternativeTextController::isSpellingMarkerAllowed(const SimpleRange& misspellingRange) const { return !m_document.markers().hasMarkers(misspellingRange, DocumentMarker::SpellCheckingExemption); } void AlternativeTextController::show(const SimpleRange& rangeToReplace, const String& replacement) { auto boundingBox = rootViewRectForRange(rangeToReplace); if (boundingBox.isEmpty()) return; m_originalText = plainText(rangeToReplace); m_rangeWithAlternative = rangeToReplace; m_details = replacement; m_isActive = true; if (AlternativeTextClient* client = alternativeTextClient()) client->showCorrectionAlternative(m_type, boundingBox, m_originalText, replacement, { }); } void AlternativeTextController::handleCancelOperation() { if (!m_isActive) return; m_isActive = false; dismiss(ReasonForDismissingAlternativeTextCancelled); } void AlternativeTextController::dismiss(ReasonForDismissingAlternativeText reasonForDismissing) { if (!m_isActive) return; m_isActive = false; m_isDismissedByEditing = true; if (AlternativeTextClient* client = alternativeTextClient()) client->dismissAlternative(reasonForDismissing); } String AlternativeTextController::dismissSoon(ReasonForDismissingAlternativeText reasonForDismissing) { if (!m_isActive) return String(); m_isActive = false; m_isDismissedByEditing = true; if (AlternativeTextClient* client = alternativeTextClient()) return client->dismissAlternativeSoon(reasonForDismissing); return String(); } bool AlternativeTextController::applyAutocorrectionBeforeTypingIfAppropriate() { if (!m_rangeWithAlternative || !m_isActive) return false; if (m_type != AlternativeTextTypeCorrection) return false; Position caretPosition = m_document.selection().selection().start(); if (createLegacyEditingPosition(m_rangeWithAlternative->end) == caretPosition) { handleAlternativeTextUIResult(dismissSoon(ReasonForDismissingAlternativeTextAccepted)); return true; } // Pending correction should always be where caret is. But in case this is not always true, we still want to dismiss the panel without accepting the correction. ASSERT(createLegacyEditingPosition(m_rangeWithAlternative->end) == caretPosition); dismiss(ReasonForDismissingAlternativeTextIgnored); return false; } void AlternativeTextController::respondToUnappliedSpellCorrection(const VisibleSelection& selectionOfCorrected, const String& corrected, const String& correction) { if (auto client = alternativeTextClient()) client->recordAutocorrectionResponse(AutocorrectionResponse::Reverted, corrected, correction); RefPtr<Frame> protector(m_document.frame()); m_document.updateLayout(); m_document.selection().setSelection(selectionOfCorrected, FrameSelection::defaultSetSelectionOptions() | FrameSelection::SpellCorrectionTriggered); auto range = m_document.selection().selection().firstRange(); if (!range) return; removeMarkers(*range, OptionSet<DocumentMarker::MarkerType> { DocumentMarker::Spelling, DocumentMarker::Autocorrected }, RemovePartiallyOverlappingMarker::Yes); addMarker(*range, DocumentMarker::Replacement); addMarker(*range, DocumentMarker::SpellCheckingExemption); } void AlternativeTextController::timerFired() { m_isDismissedByEditing = false; switch (m_type) { case AlternativeTextTypeCorrection: { VisibleSelection selection(m_document.selection().selection()); VisiblePosition start(selection.start(), selection.affinity()); VisiblePosition p = startOfWord(start, LeftWordIfOnBoundary); VisibleSelection adjacentWords = VisibleSelection(p, start); auto adjacentWordRange = adjacentWords.toNormalizedRange(); m_document.editor().markAllMisspellingsAndBadGrammarInRanges({ TextCheckingType::Spelling, TextCheckingType::Replacement, TextCheckingType::ShowCorrectionPanel }, adjacentWordRange, adjacentWordRange, WTF::nullopt); } break; case AlternativeTextTypeReversion: { if (!m_rangeWithAlternative) break; String replacementString = WTF::get<AutocorrectionReplacement>(m_details); if (replacementString.isEmpty()) break; m_isActive = true; m_originalText = plainText(*m_rangeWithAlternative); auto boundingBox = rootViewRectForRange(*m_rangeWithAlternative); if (!boundingBox.isEmpty()) { if (AlternativeTextClient* client = alternativeTextClient()) client->showCorrectionAlternative(m_type, boundingBox, m_originalText, replacementString, { }); } } break; case AlternativeTextTypeSpellingSuggestions: { if (!m_rangeWithAlternative || plainText(*m_rangeWithAlternative) != m_originalText) break; String paragraphText = plainText(TextCheckingParagraph(*m_rangeWithAlternative).paragraphRange()); Vector<String> suggestions; textChecker()->getGuessesForWord(m_originalText, paragraphText, m_document.selection().selection(), suggestions); if (suggestions.isEmpty()) { m_rangeWithAlternative = WTF::nullopt; break; } String topSuggestion = suggestions.first(); suggestions.remove(0); m_isActive = true; auto boundingBox = rootViewRectForRange(*m_rangeWithAlternative); if (!boundingBox.isEmpty()) { if (AlternativeTextClient* client = alternativeTextClient()) client->showCorrectionAlternative(m_type, boundingBox, m_originalText, topSuggestion, suggestions); } } break; case AlternativeTextTypeDictationAlternatives: { #if USE(DICTATION_ALTERNATIVES) if (!m_rangeWithAlternative) return; auto dictationContext = WTF::get<DictationContext>(m_details); if (!dictationContext) return; auto boundingBox = rootViewRectForRange(*m_rangeWithAlternative); m_isActive = true; if (!boundingBox.isEmpty()) { if (auto client = alternativeTextClient()) client->showDictationAlternativeUI(boundingBox, dictationContext); } #endif } break; } } void AlternativeTextController::handleAlternativeTextUIResult(const String& result) { if (!m_rangeWithAlternative || &m_document != &m_rangeWithAlternative->start.document()) return; String currentWord = plainText(*m_rangeWithAlternative); // Check to see if the word we are about to correct has been changed between timer firing and callback being triggered. if (currentWord != m_originalText) return; m_isActive = false; switch (m_type) { case AlternativeTextTypeCorrection: if (result.length()) applyAlternativeTextToRange(*m_rangeWithAlternative, result, m_type, markerTypesForAutocorrection()); else if (!m_isDismissedByEditing) addMarker(*m_rangeWithAlternative, DocumentMarker::RejectedCorrection, m_originalText); break; case AlternativeTextTypeReversion: case AlternativeTextTypeSpellingSuggestions: if (result.length()) applyAlternativeTextToRange(*m_rangeWithAlternative, result, m_type, markerTypesForReplacement()); break; case AlternativeTextTypeDictationAlternatives: if (result.length()) applyAlternativeTextToRange(*m_rangeWithAlternative, result, m_type, markerTypesForAppliedDictationAlternative()); break; } m_rangeWithAlternative = WTF::nullopt; } bool AlternativeTextController::isAutomaticSpellingCorrectionEnabled() { if (!editorClient() || !editorClient()->isAutomaticSpellingCorrectionEnabled()) return false; #if ENABLE(AUTOCORRECT) auto position = m_document.selection().selection().start(); if (auto editableRoot = position.rootEditableElement()) { if (is<HTMLElement>(editableRoot) && !downcast<HTMLElement>(*editableRoot).shouldAutocorrect()) return false; } if (auto control = enclosingTextFormControl(position)) { if (!control->shouldAutocorrect()) return false; } #endif return true; } FloatRect AlternativeTextController::rootViewRectForRange(const SimpleRange& range) const { auto* view = m_document.view(); if (!view) return { }; return view->contentsToRootView(unitedBoundingBoxes(RenderObject::absoluteTextQuads(range))); } void AlternativeTextController::respondToChangedSelection(const VisibleSelection& oldSelection) { VisibleSelection currentSelection(m_document.selection().selection()); // When user moves caret to the end of autocorrected word and pauses, we show the panel // containing the original pre-correction word so that user can quickly revert the // undesired autocorrection. Here, we start correction panel timer once we confirm that // the new caret position is at the end of a word. if (!currentSelection.isCaret() || currentSelection == oldSelection || !currentSelection.isContentEditable()) return; VisiblePosition selectionPosition = currentSelection.start(); // Creating a Visible position triggers a layout and there is no // guarantee that the selection is still valid. if (selectionPosition.isNull()) return; VisiblePosition endPositionOfWord = endOfWord(selectionPosition, LeftWordIfOnBoundary); if (selectionPosition != endPositionOfWord) return; Position position = endPositionOfWord.deepEquivalent(); if (position.anchorType() != Position::PositionIsOffsetInAnchor) return; Node* node = position.containerNode(); ASSERT(node); for (auto* marker : node->document().markers().markersFor(*node)) { ASSERT(marker); if (respondToMarkerAtEndOfWord(*marker, position)) break; } } void AlternativeTextController::respondToAppliedEditing(CompositeEditCommand* command) { if (command->isTopLevelCommand() && !command->shouldRetainAutocorrectionIndicator()) m_document.markers().removeMarkers(DocumentMarker::CorrectionIndicator); markPrecedingWhitespaceForDeletedAutocorrectionAfterCommand(command); m_originalStringForLastDeletedAutocorrection = String(); dismiss(ReasonForDismissingAlternativeTextIgnored); } void AlternativeTextController::respondToUnappliedEditing(EditCommandComposition* command) { if (!command->wasCreateLinkCommand()) return; auto range = command->startingSelection().firstRange(); if (!range) return; addMarker(*range, DocumentMarker::Replacement); addMarker(*range, DocumentMarker::SpellCheckingExemption); } EditorClient* AlternativeTextController::editorClient() { return m_document.page() ? &m_document.page()->editorClient() : nullptr; } TextCheckerClient* AlternativeTextController::textChecker() { if (EditorClient* owner = editorClient()) return owner->textChecker(); return nullptr; } void AlternativeTextController::recordAutocorrectionResponse(AutocorrectionResponse response, const String& replacedString, const SimpleRange& replacementRange) { if (auto client = alternativeTextClient()) client->recordAutocorrectionResponse(response, replacedString, plainText(replacementRange)); } void AlternativeTextController::markReversed(const SimpleRange& changedRange) { removeMarkers(changedRange, DocumentMarker::Autocorrected, RemovePartiallyOverlappingMarker::Yes); addMarker(changedRange, DocumentMarker::SpellCheckingExemption); } void AlternativeTextController::markCorrection(const SimpleRange& replacedRange, const String& replacedString) { for (auto markerType : markerTypesForAutocorrection()) { if (markerType == DocumentMarker::Replacement || markerType == DocumentMarker::Autocorrected) addMarker(replacedRange, markerType, replacedString); else addMarker(replacedRange, markerType); } } void AlternativeTextController::recordSpellcheckerResponseForModifiedCorrection(const SimpleRange& rangeOfCorrection, const String& corrected, const String& correction) { DocumentMarkerController& markers = rangeOfCorrection.startContainer().document().markers(); Vector<RenderedDocumentMarker*> correctedOnceMarkers = markers.markersInRange(rangeOfCorrection, DocumentMarker::Autocorrected); if (correctedOnceMarkers.isEmpty()) return; if (AlternativeTextClient* client = alternativeTextClient()) { // Spelling corrected text has been edited. We need to determine whether user has reverted it to original text or // edited it to something else, and notify spellchecker accordingly. if (markersHaveIdenticalDescription(correctedOnceMarkers) && correctedOnceMarkers[0]->description() == corrected) client->recordAutocorrectionResponse(AutocorrectionResponse::Reverted, corrected, correction); else client->recordAutocorrectionResponse(AutocorrectionResponse::Edited, corrected, correction); } removeMarkers(rangeOfCorrection, DocumentMarker::Autocorrected, RemovePartiallyOverlappingMarker::Yes); } void AlternativeTextController::deletedAutocorrectionAtPosition(const Position& position, const String& originalString) { m_originalStringForLastDeletedAutocorrection = originalString; m_positionForLastDeletedAutocorrection = position; } void AlternativeTextController::markPrecedingWhitespaceForDeletedAutocorrectionAfterCommand(EditCommand* command) { Position endOfSelection = command->endingSelection().end(); if (endOfSelection != m_positionForLastDeletedAutocorrection) return; Position precedingCharacterPosition = endOfSelection.previous(); if (endOfSelection == precedingCharacterPosition) return; auto precedingCharacterRange = makeSimpleRange(precedingCharacterPosition, endOfSelection); if (!precedingCharacterRange) return; String string = plainText(*precedingCharacterRange); if (string.isEmpty() || !deprecatedIsEditingWhitespace(string[string.length() - 1])) return; // Mark this whitespace to indicate we have deleted an autocorrection following this // whitespace. So if the user types the same original word again at this position, we // won't autocorrect it again. addMarker(*precedingCharacterRange, DocumentMarker::DeletedAutocorrection, m_originalStringForLastDeletedAutocorrection); } bool AlternativeTextController::processMarkersOnTextToBeReplacedByResult(const TextCheckingResult& result, const SimpleRange& rangeWithAlternative, const String& stringToBeReplaced) { auto& markers = m_document.markers(); if (markers.hasMarkers(rangeWithAlternative, DocumentMarker::Replacement)) { if (result.type == TextCheckingType::Correction) recordSpellcheckerResponseForModifiedCorrection(rangeWithAlternative, stringToBeReplaced, result.replacement); return false; } if (markers.hasMarkers(rangeWithAlternative, DocumentMarker::RejectedCorrection)) return false; if (markers.hasMarkers(rangeWithAlternative, DocumentMarker::AcceptedCandidate)) return false; auto precedingCharacterRange = makeSimpleRange(createLegacyEditingPosition(rangeWithAlternative.start).previous(), rangeWithAlternative.start); if (!precedingCharacterRange) return false; for (auto& marker : markers.markersInRange(*precedingCharacterRange, DocumentMarker::DeletedAutocorrection)) { if (marker->description() == stringToBeReplaced) return false; } return true; } bool AlternativeTextController::shouldStartTimerFor(const WebCore::DocumentMarker &marker, int endOffset) const { return (((marker.type() == DocumentMarker::Replacement && !marker.description().isNull()) || marker.type() == DocumentMarker::Spelling || marker.type() == DocumentMarker::DictationAlternatives) && static_cast<int>(marker.endOffset()) == endOffset); } bool AlternativeTextController::respondToMarkerAtEndOfWord(const DocumentMarker& marker, const Position& endOfWordPosition) { if (!shouldStartTimerFor(marker, endOfWordPosition.offsetInContainerNode())) return false; Node* node = endOfWordPosition.containerNode(); auto wordRange = makeSimpleRange(*node, marker); String currentWord = plainText(wordRange); if (!currentWord.length()) return false; m_originalText = currentWord; switch (marker.type()) { case DocumentMarker::Spelling: m_rangeWithAlternative = WTFMove(wordRange); m_details = emptyString(); startAlternativeTextUITimer(AlternativeTextTypeSpellingSuggestions); break; case DocumentMarker::Replacement: m_rangeWithAlternative = WTFMove(wordRange); m_details = marker.description(); startAlternativeTextUITimer(AlternativeTextTypeReversion); break; case DocumentMarker::DictationAlternatives: { auto& markerData = WTF::get<DocumentMarker::DictationData>(marker.data()); if (currentWord != markerData.originalText) return false; m_rangeWithAlternative = WTFMove(wordRange); m_details = markerData.context; startAlternativeTextUITimer(AlternativeTextTypeDictationAlternatives); } break; default: ASSERT_NOT_REACHED(); break; } return true; } #endif // USE(AUTOCORRECTION_PANEL) #if USE(DICTATION_ALTERNATIVES) || USE(AUTOCORRECTION_PANEL) AlternativeTextClient* AlternativeTextController::alternativeTextClient() { return m_document.frame() && m_document.page() ? m_document.page()->alternativeTextClient() : nullptr; } String AlternativeTextController::markerDescriptionForAppliedAlternativeText(AlternativeTextType alternativeTextType, DocumentMarker::MarkerType markerType) { #if USE(AUTOCORRECTION_PANEL) if (alternativeTextType != AlternativeTextTypeReversion && alternativeTextType != AlternativeTextTypeDictationAlternatives && (markerType == DocumentMarker::Replacement || markerType == DocumentMarker::Autocorrected)) return m_originalText; #else UNUSED_PARAM(alternativeTextType); UNUSED_PARAM(markerType); #endif return emptyString(); } void AlternativeTextController::applyAlternativeTextToRange(const SimpleRange& range, const String& alternative, AlternativeTextType alternativeType, OptionSet<DocumentMarker::MarkerType> markerTypesToAdd) { // After we replace the word at range rangeWithAlternative, we need to add markers to that range. // So before we carry out the replacement,store the start position relative to the start position // of the containing paragraph. // Take note of the location of autocorrection so that we can add marker after the replacement took place. auto paragraphStart = makeBoundaryPoint(startOfParagraph(createLegacyEditingPosition(range.start))); if (!paragraphStart) return; auto treeScopeRoot = makeRef(range.start.container->treeScope().rootNode()); auto treeScopeStart = BoundaryPoint { treeScopeRoot.get(), 0 }; auto correctionOffsetInParagraph = characterCount({ *paragraphStart, range.start }); auto paragraphOffsetInTreeScope = characterCount({ treeScopeStart, *paragraphStart }); SpellingCorrectionCommand::create(range, alternative)->apply(); // Recalculate pragraphRangeContainingCorrection, since SpellingCorrectionCommand modified the DOM, such that the original paragraphRangeContainingCorrection is no longer valid. Radar: 10305315 Bugzilla: 89526 auto updatedParagraphStartContainingCorrection = resolveCharacterLocation(makeRangeSelectingNodeContents(treeScopeRoot), paragraphOffsetInTreeScope); auto updatedParagraphEndContainingCorrection = makeBoundaryPoint(m_document.selection().selection().start()); if (!updatedParagraphEndContainingCorrection) return; auto replacementRange = resolveCharacterRange({ updatedParagraphStartContainingCorrection, *updatedParagraphEndContainingCorrection }, CharacterRange(correctionOffsetInParagraph, alternative.length())); // Check to see if replacement succeeded. if (plainText(replacementRange) != alternative) return; for (auto markerType : markerTypesToAdd) addMarker(replacementRange, markerType, markerDescriptionForAppliedAlternativeText(alternativeType, markerType)); } #endif bool AlternativeTextController::insertDictatedText(const String& text, const Vector<DictationAlternative>& dictationAlternatives, Event* triggeringEvent) { EventTarget* target; if (triggeringEvent) target = triggeringEvent->target(); else target = eventTargetElementForDocument(&m_document); if (!target) return false; auto event = TextEvent::createForDictation(&m_document.frame()->windowProxy(), text, dictationAlternatives); event->setUnderlyingEvent(triggeringEvent); target->dispatchEvent(event); return event->defaultHandled(); } void AlternativeTextController::removeDictationAlternativesForMarker(const DocumentMarker& marker) { #if USE(DICTATION_ALTERNATIVES) if (auto* client = alternativeTextClient()) client->removeDictationAlternatives(WTF::get<DocumentMarker::DictationData>(marker.data()).context); #else UNUSED_PARAM(marker); #endif } Vector<String> AlternativeTextController::dictationAlternativesForMarker(const DocumentMarker& marker) { #if USE(DICTATION_ALTERNATIVES) if (auto* client = alternativeTextClient()) return client->dictationAlternatives(WTF::get<DocumentMarker::DictationData>(marker.data()).context); return Vector<String>(); #else UNUSED_PARAM(marker); return Vector<String>(); #endif } void AlternativeTextController::applyDictationAlternative(const String& alternativeString) { #if USE(DICTATION_ALTERNATIVES) auto& editor = m_document.editor(); auto selection = editor.selectedRange(); if (!selection || !editor.shouldInsertText(alternativeString, *selection, EditorInsertAction::Pasted)) return; for (auto* marker : selection->startContainer().document().markers().markersInRange(*selection, DocumentMarker::DictationAlternatives)) removeDictationAlternativesForMarker(*marker); applyAlternativeTextToRange(*selection, alternativeString, AlternativeTextTypeDictationAlternatives, markerTypesForAppliedDictationAlternative()); #else UNUSED_PARAM(alternativeString); #endif } } // namespace WebCore
40.935673
252
0.750179
[ "vector" ]
3809028186ef76c3df76638bbcdbfe09f8eeaff6
13,975
cc
C++
examples/cpp_cb/route_guide/route_guide_cb_client.cc
jinq0123/grpc_cb
1b3058528d66dd6777a3248550a3d87f6b9e1b7f
[ "Apache-2.0" ]
43
2016-11-02T15:19:00.000Z
2021-08-19T08:46:24.000Z
examples/cpp_cb/route_guide/route_guide_cb_client.cc
jinq0123/grpc_cb
1b3058528d66dd6777a3248550a3d87f6b9e1b7f
[ "Apache-2.0" ]
2
2018-02-09T09:06:37.000Z
2018-08-18T01:26:13.000Z
examples/cpp_cb/route_guide/route_guide_cb_client.cc
jinq0123/grpc_cb
1b3058528d66dd6777a3248550a3d87f6b9e1b7f
[ "Apache-2.0" ]
19
2016-12-04T08:49:27.000Z
2022-03-29T07:30:59.000Z
/* * * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <atomic> #include <chrono> #include <future> // for async() #include <iostream> #include <memory> #include <random> #include <string> #include "helper.h" #include "route_guide.grpc_cb.pb.h" using grpc_cb::Channel; using grpc_cb::ChannelSptr; using grpc_cb::Status; using routeguide::Point; using routeguide::Feature; using routeguide::Rectangle; using routeguide::RouteSummary; using routeguide::RouteNote; using routeguide::RouteGuide::Stub; const float kCoordFactor = 10000000.0; static unsigned seed = (unsigned)std::chrono::system_clock::now().time_since_epoch().count(); static std::default_random_engine generator(seed); Point MakePoint(long latitude, long longitude) { Point p; p.set_latitude(latitude); p.set_longitude(longitude); return p; } routeguide::Rectangle MakeRect(const Point& lo, const Point& hi) { routeguide::Rectangle rect; *rect.mutable_lo() = lo; *rect.mutable_hi() = hi; return rect; } routeguide::Rectangle MakeRect(long lo_latitude, long lo_longitude, long hi_latitude, long hi_longitude) { return MakeRect(MakePoint(lo_latitude, lo_longitude), MakePoint(hi_latitude, hi_longitude)); } Feature MakeFeature(const std::string& name, long latitude, long longitude) { Feature f; f.set_name(name); f.mutable_location()->CopyFrom(MakePoint(latitude, longitude)); return f; } RouteNote MakeRouteNote(const std::string& message, long latitude, long longitude) { RouteNote n; n.set_message(message); n.mutable_location()->CopyFrom(MakePoint(latitude, longitude)); return n; } void PrintFeature(const Feature& feature) { if (!feature.has_location()) { std::cout << "Server returns incomplete feature." << std::endl; return; } if (feature.name().empty()) { std::cout << "Found no feature at " << feature.location().latitude()/kCoordFactor << ", " << feature.location().longitude()/kCoordFactor << std::endl; } else { std::cout << "Found feature called " << feature.name() << " at " << feature.location().latitude()/kCoordFactor << ", " << feature.location().longitude()/kCoordFactor << std::endl; } } // PrintFeature() void PrintServerNote(const RouteNote& server_note) { std::cout << "Got message " << server_note.message() << " at " << server_note.location().latitude() << ", " << server_note.location().longitude() << std::endl; } void RandomSleep() { std::uniform_int_distribution<int> delay_distribution(500, 1500); std::this_thread::sleep_for(std::chrono::milliseconds( delay_distribution(generator))); } void RunWriteRouteNote(Stub::RouteChat_SyncReaderWriter sync_reader_writer) { std::vector<RouteNote> notes{ MakeRouteNote("First message", 0, 0), MakeRouteNote("Second message", 0, 1), MakeRouteNote("Third message", 1, 0), MakeRouteNote("Fourth message", 0, 0)}; for (const RouteNote& note : notes) { std::cout << "Sending message " << note.message() << " at " << note.location().latitude() << ", " << note.location().longitude() << std::endl; sync_reader_writer.Write(note); // RandomSleep(); } sync_reader_writer.CloseWriting(); } class RouteGuideClient { public: RouteGuideClient(std::shared_ptr<Channel> channel, const std::string& db) : stub_(new Stub(channel)) { routeguide::ParseDb(db, &feature_list_); assert(!feature_list_.empty()); } void SyncGetFeature() { Point point; Feature feature; point = MakePoint(409146138, -746188906); SyncGetOneFeature(point, &feature); point = MakePoint(0, 0); SyncGetOneFeature(point, &feature); } void SyncListFeatures() { routeguide::Rectangle rect = MakeRect( 400000000, -750000000, 420000000, -730000000); Feature feature; std::cout << "Looking for features between 40, -75 and 42, -73" << std::endl; auto sync_reader(stub_->Sync_ListFeatures(rect)); while (sync_reader.ReadOne(&feature)) { std::cout << "Found feature called " << feature.name() << " at " << feature.location().latitude()/kCoordFactor << ", " << feature.location().longitude()/kCoordFactor << std::endl; } Status status = sync_reader.RecvStatus(); if (status.ok()) { std::cout << "ListFeatures rpc succeeded." << std::endl; } else { std::cout << "ListFeatures rpc failed." << std::endl; } } void SyncRecordRoute() { Point point; const int kPoints = 10; std::uniform_int_distribution<int> feature_distribution( 0, feature_list_.size() - 1); auto sync_writer(stub_->Sync_RecordRoute()); for (int i = 0; i < kPoints; i++) { const Feature& f = feature_list_[feature_distribution(generator)]; std::cout << "Visiting point " << f.location().latitude()/kCoordFactor << ", " << f.location().longitude()/kCoordFactor << std::endl; if (!sync_writer.Write(f.location())) { // Broken stream. break; } RandomSleep(); } RouteSummary stats; // Recv reponse and status. Status status = sync_writer.Close(&stats); // Todo: timeout if (status.ok()) { std::cout << "Finished trip with " << stats.point_count() << " points\n" << "Passed " << stats.feature_count() << " features\n" << "Traveled " << stats.distance() << " meters\n" << "It took " << stats.elapsed_time() << " seconds" << std::endl; } else { std::cout << "RecordRoute rpc failed." << std::endl; } } // Todo: Callback on client stream response and status. void SyncRouteChat() { auto sync_reader_writer(stub_->Sync_RouteChat()); auto f = std::async(std::launch::async, [sync_reader_writer]() { RunWriteRouteNote(sync_reader_writer); }); RouteNote server_note; while (sync_reader_writer.ReadOne(&server_note)) PrintServerNote(server_note); f.wait(); // Todo: Close() should auto close writing. Status status = sync_reader_writer.RecvStatus(); if (!status.ok()) { std::cout << "RouteChat rpc failed." << std::endl; } } private: bool SyncGetOneFeature(const Point& point, Feature* feature) { Status status = stub_->Sync_GetFeature(point, feature); if (!status.ok()) { std::cout << "GetFeature rpc failed." << std::endl; return false; } PrintFeature(*feature); return feature->has_location(); } std::unique_ptr<Stub> stub_; std::vector<Feature> feature_list_; }; void GetFeatureAsync(const ChannelSptr& channel) { Stub stub(channel); // Ignore error status. stub.Async_GetFeature(MakePoint(0, 0), [](const Feature& feature) { PrintFeature(feature); }); // Ignore response. stub.Async_GetFeature(MakePoint(0, 0)); Point point1 = MakePoint(409146138, -746188906); stub.Async_GetFeature(point1, [&stub](const Feature& feature) { PrintFeature(feature); stub.Shutdown(); }, [&stub](const Status& err) { std::cout << "AsyncGetFeature rpc failed. " << err.GetDetails() << std::endl; stub.Shutdown(); }); // AsyncGetFeature() stub.Run(); // until stub.Shutdown() } void ListFeaturesAsync(const ChannelSptr& channel) { Stub stub(channel); routeguide::Rectangle rect = MakeRect( 400000000, -750000000, 420000000, -730000000); std::cout << "Looking for features between 40, -75 and 42, -73" << std::endl; stub.Async_ListFeatures(rect, [](const Feature& feature) { std::cout << "Found feature called " << feature.name() << " at " << feature.location().latitude()/kCoordFactor << ", " << feature.location().longitude()/kCoordFactor << std::endl; }, [&stub](const Status& status) { if (status.ok()) { std::cout << "ListFeatures rpc succeeded." << std::endl; } else { std::cout << "ListFeatures rpc failed." << std::endl; } stub.Shutdown(); // To break Run(). }); stub.Run(); // until stub.Shutdown() } void RecordRouteAsync(const ChannelSptr& channel, const std::string& db) { assert(!db.empty()); std::vector<Feature> feature_list; routeguide::ParseDb(db, &feature_list); assert(!feature_list.empty()); Point point; const int kPoints = 10; std::uniform_int_distribution<int> feature_distribution( 0, feature_list.size() - 1); Stub stub(channel); auto f = std::async(std::launch::async, [&stub]() { stub.Run(); }); // ClientAsyncWriter<Point, RouteSummary> async_writer; auto async_writer = stub.Async_RecordRoute(); for (int i = 0; i < kPoints; i++) { const Feature& f = feature_list[feature_distribution(generator)]; std::cout << "Visiting point " << f.location().latitude()/kCoordFactor << ", " << f.location().longitude()/kCoordFactor << std::endl; if (!async_writer.Write(f.location())) { // Broken stream. break; } RandomSleep(); } // Recv reponse and status. async_writer.Close([](const Status& status, const RouteSummary& resp) { if (!status.ok()) { std::cout << "RecordRoute rpc failed." << std::endl; return; } std::cout << "Finished trip with " << resp.point_count() << " points\n" << "Passed " << resp.feature_count() << " features\n" << "Traveled " << resp.distance() << " meters\n" << "It took " << resp.elapsed_time() << " seconds" << std::endl; }); // Todo: timeout stub.Shutdown(); } // RecordRouteAsync() void AsyncWriteRouteNotes(Stub::RouteChat_AsyncReaderWriter async_reader_writer) { std::vector<RouteNote> notes{ MakeRouteNote("First message", 0, 0), MakeRouteNote("Second message", 0, 1), MakeRouteNote("Third message", 1, 0), MakeRouteNote("Fourth message", 0, 0)}; for (const RouteNote& note : notes) { std::cout << "Sending message " << note.message() << " at " << note.location().latitude() << ", " << note.location().longitude() << std::endl; async_reader_writer.Write(note); RandomSleep(); } async_reader_writer.CloseWriting(); // Tell server. } void RouteChatAsync(const ChannelSptr& channel) { Stub stub(channel); auto f_run = std::async(std::launch::async, [&stub]() { stub.Run(); }); std::atomic_bool bReaderDone = false; auto async_reader_writer( stub.Async_RouteChat([&bReaderDone](const Status& status) { if (!status.ok()) { std::cout << "RouteChat rpc failed. " << status.GetDetails() << std::endl; } bReaderDone = true; })); async_reader_writer.ReadEach( [](const RouteNote& note) { PrintServerNote(note); }); AsyncWriteRouteNotes(async_reader_writer); while (!bReaderDone) std::this_thread::sleep_for(std::chrono::milliseconds(1)); stub.Shutdown(); // To break Run(). } // RouteChatAsync() void TestRpcTimeout(const ChannelSptr& channel) { Stub stub(channel); stub.SetCallTimeoutMs(INT64_MIN); Point point = MakePoint(0, 0); Feature feature; Status status = stub.Sync_GetFeature(point, &feature); assert(status.GetCode() == GRPC_STATUS_DEADLINE_EXCEEDED); } int main(int argc, char** argv) { // Expect only arg: --db_path=path/to/route_guide_db.json. std::string db = routeguide::GetDbFileContent(argc, argv); assert(!db.empty()); ChannelSptr channel(new Channel("localhost:50051")); RouteGuideClient guide(channel, db); TestRpcTimeout(channel); std::cout << "---- SyncGetFeature --------------" << std::endl; guide.SyncGetFeature(); std::cout << "---- SyncListFeatures --------------" << std::endl; guide.SyncListFeatures(); std::cout << "---- SyncRecordRoute --------------" << std::endl; guide.SyncRecordRoute(); std::cout << "---- SyncRouteChat --------------" << std::endl; guide.SyncRouteChat(); std::cout << "---- GetFeatureAsync ----" << std::endl; GetFeatureAsync(channel); std::cout << "---- ListFeaturesAsync ----" << std::endl; ListFeaturesAsync(channel); std::cout << "---- RecordRouteAsnyc ----" << std::endl; RecordRouteAsync(channel, db); std::cout << "---- RouteChatAsync ---" << std::endl; RouteChatAsync(channel); return 0; }
33.433014
93
0.640072
[ "vector" ]
380e1bc363028d31e3f1ab4977cdf7306c6b704e
17,244
cpp
C++
src/topp/AdditiveSeries.cpp
raghav17083/OpenMS
ddcdd3068a93a7c415675c39bac43d796a845f1d
[ "BSL-1.0", "Apache-2.0", "Zlib" ]
null
null
null
src/topp/AdditiveSeries.cpp
raghav17083/OpenMS
ddcdd3068a93a7c415675c39bac43d796a845f1d
[ "BSL-1.0", "Apache-2.0", "Zlib" ]
null
null
null
src/topp/AdditiveSeries.cpp
raghav17083/OpenMS
ddcdd3068a93a7c415675c39bac43d796a845f1d
[ "BSL-1.0", "Apache-2.0", "Zlib" ]
null
null
null
// -------------------------------------------------------------------------- // OpenMS -- Open-Source Mass Spectrometry // -------------------------------------------------------------------------- // Copyright The OpenMS Team -- Eberhard Karls University Tuebingen, // ETH Zurich, and Freie Universitaet Berlin 2002-2017. // // This software is released under a three-clause BSD license: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of any author or any participating institution // may be used to endorse or promote products derived from this software // without specific prior written permission. // For a full list of authors, refer to the file AUTHORS. // -------------------------------------------------------------------------- // 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 ANY OF THE AUTHORS OR THE CONTRIBUTING // INSTITUTIONS 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. // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow $ // $Authors: Clemens Groepl, Chris Bielow$ // -------------------------------------------------------------------------- #include <OpenMS/FORMAT/FeatureXMLFile.h> #include <OpenMS/KERNEL/FeatureMap.h> #include <OpenMS/APPLICATIONS/TOPPBase.h> #include <OpenMS/MATH/STATISTICS/LinearRegression.h> #include <OpenMS/SYSTEM/File.h> #include <map> #include <vector> #include <algorithm> using namespace OpenMS; using namespace Math; using namespace std; typedef Feature::CoordinateType CoordinateType; //------------------------------------------------------------- //Doxygen docu //------------------------------------------------------------- /** @page TOPP_AdditiveSeries AdditiveSeries @brief Computes an additive series to quantify a peptide in a set of samples. <CENTER> <table> <tr> <td ALIGN = "center" BGCOLOR="#EBEBEB"> pot. predecessor tools </td> <td VALIGN="middle" ROWSPAN=3> \f$ \longrightarrow \f$ AdditiveSeries \f$ \longrightarrow \f$</td> <td ALIGN = "center" BGCOLOR="#EBEBEB"> pot. successor tools </td> </tr> <tr> <td VALIGN="middle" ALIGN = "center" ROWSPAN=1> @ref TOPP_FeatureFinderCentroided </td> <td VALIGN="middle" ALIGN = "center" ROWSPAN=2> - </td> </tr> <tr> <td VALIGN="middle" ALIGN = "center" ROWSPAN=1> @ref TOPP_IDMapper </td> </tr> </table> </CENTER> This module computes an additive series for an absolute quantification of a peptide in a set of samples. The output consists of a GNUplot script which can be used to visualize the results and some XML output for further processing. In this version, the application computes the additive series as a ratio of the intensities of two different peptides. One of these peptides serves as internal standard for calibration. <B>The command line parameters of this tool are:</B> @verbinclude TOPP_AdditiveSeries.cli <B>INI file documentation of this tool:</B> @htmlinclude TOPP_AdditiveSeries.html */ // We do not want this class to show up in the docu: /// @cond TOPPCLASSES class AdditiveSeries : public TOPPBase { public: AdditiveSeries() : TOPPBase("AdditiveSeries", "Computes an additive series to quantify a peptide in a set of samples.") { } protected: void registerOptionsAndFlags_() override { registerInputFileList_("in", "<files>", StringList(), "input files separated by blanks", true); setValidFormats_("in", ListUtils::create<String>("featureXML")); registerOutputFile_("out", "<file>", "", "output XML file containg regression line and confidence interval"); setValidFormats_("out", ListUtils::create<String>("XML")); registerDoubleOption_("mz_tolerance", "<tol>", 1.0, "Tolerance in m/z dimension", false); registerDoubleOption_("rt_tolerance", "<tol>", 1.0, "Tolerance in RT dimension", false); registerDoubleList_("concentrations", "<concentrations>", DoubleList(), "List of spiked concentrations"); addEmptyLine_(); registerDoubleOption_("feature_rt", "<rt>", -1, "RT position of the feature", false); registerDoubleOption_("feature_mz", "<mz>", -1, "m/z position of the feature", false); registerDoubleOption_("standard_rt", "<rt>", -1, "RT position of the standard", false); registerDoubleOption_("standard_mz", "<mz>", -1, "m/z position of the standard", false); addEmptyLine_(); registerTOPPSubsection_("plot", "GNUplot options"); registerFlag_("plot:write_gnuplot_output", "Flag that activates the GNUplot output"); registerStringOption_("plot:out_gp", "<name>", "", "base file name (3 files with different extensions are created)", false); } // searches for a features with coordinates within the tolerance in this map // NOTE: It might happen that there are several features at similar coordinates. // In this case, the program cannot be sure which one is the correct. So we decided // to use the one with the strongest intensity. bool readMapFile_(String filename, vector<double> & intensities, CoordinateType tol_mz, CoordinateType tol_rt, DPosition<2> fpos1, DPosition<2> fpos2) { if (!File::exists(filename)) { cout << "File " << filename << " not found. " << endl; return false; } cout << "Reading from " << filename << endl; FeatureXMLFile map_file; FeatureMap map; map_file.load(filename, map); Feature * feat1 = nullptr; Feature * feat2 = nullptr; FeatureMap::iterator iter = map.begin(); while (iter != map.end()) { // cout << "Read: " << *iter << endl; if ((iter->getRT() < fpos1[Feature::RT] + tol_rt) && (iter->getRT() > fpos1[Feature::RT] - tol_rt) && (iter->getMZ() < fpos1[Feature::MZ] + tol_mz) && (iter->getMZ() > fpos1[Feature::MZ] - tol_mz)) { // cout << "Found feature1 at " << endl; // cout << iter->getRT() << " " << iter->getMZ() << " " << iter->getIntensity() << endl; // feature at correct position found, save intensity if (!feat1) { feat1 = &(*iter); } else if (feat1->getIntensity() < iter->getIntensity()) { feat1 = &(*iter); } // f1_sum += iter->getIntensity(); } if ((iter->getRT() < fpos2[Feature::RT] + tol_rt) && (iter->getRT() > fpos2[Feature::RT] - tol_rt) && (iter->getMZ() < fpos2[Feature::MZ] + tol_mz) && (iter->getMZ() > fpos2[Feature::MZ] - tol_mz)) { // cout << "Found feature2 at " << endl; // cout << iter->getRT() << " " << iter->getMZ() << " " << iter->getIntensity() << endl; // same as above if (!feat2) { feat2 = &(*iter); } else if (feat2->getIntensity() < iter->getIntensity()) { feat2 = &(*iter); } // f2_sum += iter->getIntensity(); } ++iter; } // end of while if (feat1 != nullptr && feat2 != nullptr) //(f1_sum != 0 && f2_sum != 0) { cout << "Feature 1: " << *feat1 << endl; cout << "Feature 2: " << *feat2 << endl; cout << "Intensity ratio : " << (feat1->getIntensity() / feat2->getIntensity()) << endl; intensities.push_back(feat1->getIntensity() / feat2->getIntensity()); return true; } if (!feat1) writeDebug_(String("Feature 1 was not found. "), 1); if (!feat2) writeDebug_(String("Feature 2 was not found. "), 1); return false; } /* Computes the linear regression for a series of measurements, the x-axis intercept of the regression line and its confidence interval, and writes a couple of files from which a nice plot of all this can be generated using the gnuplot program. */ bool computeRegressionAndWriteGnuplotFiles_(vector<double>::const_iterator const conc_vec_begin, vector<double>::const_iterator const conc_vec_end, vector<double>::const_iterator const area_vec_begin, double const confidence_p, String const filename_prefix, String const output_filename, String const format = "", bool const write_gnuplot = true ) { try { LinearRegression linreg; linreg.computeRegression(confidence_p, conc_vec_begin, conc_vec_end, area_vec_begin); if (write_gnuplot) { // the peak data goes here String datafilename(filename_prefix); datafilename += String(".dat"); ofstream dataout(datafilename.c_str()); // the gnuplot commands go here String commandfilename(filename_prefix); commandfilename += String(".cmd"); ofstream cmdout(commandfilename.c_str()); // the error bar for the x-axis intercept goes here String errorbarfilename(filename_prefix); errorbarfilename += String(".err"); ofstream errout(errorbarfilename.c_str()); // writing the commands cmdout << "set ylabel \"ion count\"\n" "set xlabel \"concentration\"\n" "set key left Left reverse\n"; if (!format.empty()) { if (format == "png") { cmdout << "set terminal png \n" "set output \"" << filename_prefix << ".png\"\n"; } else if (format == "eps") { cmdout << "set terminal postscript eps \n" "set output \"" << filename_prefix << ".eps\"\n"; } } cmdout << "plot \"" << datafilename << "\" w points ps 2 pt 1 lt 8 title \"data\" " // want data on first line of key ", " << linreg.getIntercept() << "+" << linreg.getSlope() << "*x lt 2 lw 3 title \"linear regression: " << linreg.getIntercept() << " + " << linreg.getSlope() << " * x\" " ", \"" << datafilename << "\" w points ps 2 pt 1 lt 8 notitle " // draw data a second time, on top of reg. line ", \"" << errorbarfilename << "\" using ($1):(0) w points pt 13 ps 2 lt 1 title \"x-intercept: " << linreg.getXIntercept() << "\" " ", \"" << errorbarfilename << "\" w xerrorbars lw 3 lt 1 title \"95% interval: [ " << linreg.getLower() << ", " << linreg.getUpper() << " ]\"\n"; cmdout.close(); // writing the x-axis intercept error bar errout << linreg.getXIntercept() << " 0 " << linreg.getLower() << " " << linreg.getUpper() << endl; errout.close(); // writing the peak data points vector<double>::const_iterator cit = conc_vec_begin; vector<double>::const_iterator ait = area_vec_begin; dataout.precision(writtenDigits<double>(0.0)); for (; cit != conc_vec_end; ++cit, ++ait) { dataout << *cit << ' ' << *ait << '\n'; } dataout.close(); } // end if (write_gnuplot) // write results to XML file ofstream results; results.open(output_filename.c_str()); results << "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" << endl; results << "<results_additiveseries>" << endl; results << "\t<slope>" << linreg.getSlope() << "</slope>" << endl; results << "\t<intercept>" << linreg.getIntercept() << "</intercept>" << endl; results << "\t<x_intercept>" << linreg.getXIntercept() << "</x_intercept>" << endl; results << "\t<confidence_lowerlimit>" << linreg.getLower() << "</confidence_lowerlimit>" << endl; results << "\t<confidence_upperlimit>" << linreg.getUpper() << "</confidence_upperlimit>" << endl; results << "\t<pearson_squared>" << linreg.getRSquared() << "</pearson_squared>" << endl; results << "\t<std_residuals>" << linreg.getStandDevRes() << "</std_residuals>" << endl; results << "\t<t_statistic>" << linreg.getTValue() << "</t_statistic>" << endl; results << "</results_additiveseries>" << endl; results.close(); } catch (string & s) { cout << s << endl; return 1; } return 0; } ExitCodes main_(int, const char **) override { //------------------------------------------------------------- // parsing parameters //------------------------------------------------------------- Param const & add_param = getParam_(); writeDebug_("Used parameters", add_param, 3); CoordinateType tol_mz = getDoubleOption_("mz_tolerance"); CoordinateType tol_rt = getDoubleOption_("rt_tolerance"); String out_f = getStringOption_("out"); if (getDoubleOption_("feature_mz") == -1|| getDoubleOption_("feature_rt") == -1) { writeLog_("Feature coordinates not given. Aborting."); return ILLEGAL_PARAMETERS; } DPosition<2> feat_pos1; feat_pos1[Feature::MZ] = (CoordinateType) add_param.getValue("feature_mz"); feat_pos1[Feature::RT] = (CoordinateType) add_param.getValue("feature_rt"); if (getDoubleOption_("standard_mz") == -1 || getDoubleOption_("standard_rt") == -1) { writeLog_("Standard coordinates not given. Aborting."); return ILLEGAL_PARAMETERS; } DPosition<2> feat_pos2; feat_pos2[Feature::MZ] = (CoordinateType) add_param.getValue("standard_mz"); feat_pos2[Feature::RT] = (CoordinateType) add_param.getValue("standard_rt"); writeDebug_(String("Setting tolerances to ") + tol_mz + " " + tol_rt, 1); // introduce a flag for each concentration. true => the corresponding feature was found vector<bool> flags; // fetching list of files StringList files = getStringList_("in"); // collect features vector<double> intensities; vector<String>::const_iterator cit = files.begin(); while (cit != files.end()) { if (readMapFile_(*cit, intensities, tol_mz, tol_rt, feat_pos1, feat_pos2)) { flags.push_back(true); } else { flags.push_back(false); } ++cit; } // read the spiked concentrations DoubleList sp_concentrations = getDoubleList_("concentrations"); vector<double> sp_concentrations2; for (Size i = 0; i < sp_concentrations.size(); i++) { if (flags.at(i) == true) { sp_concentrations2.push_back(sp_concentrations.at(i)); } } cout << "Found feature pairs: " << intensities.size() << endl; cout << "Spiked concentrations: " << sp_concentrations.size() << endl; if (intensities.empty() || sp_concentrations.empty()) { writeLog_("Did not find any data. Aborting!"); return ILLEGAL_PARAMETERS; } // set prefix of gnuplot output String filename_prefix = getStringOption_("plot:out_gp"); if (getFlag_("plot:write_gnuplot_output")) { writeDebug_(String("Writing gnuplot output"), 1); computeRegressionAndWriteGnuplotFiles_(sp_concentrations2.begin(), sp_concentrations2.end(), intensities.begin(), 0.95, filename_prefix, out_f, "eps", true); } else { writeDebug_(" No GNUplot output is written...", 1); computeRegressionAndWriteGnuplotFiles_(sp_concentrations2.begin(), sp_concentrations2.end(), intensities.begin(), 0.95, filename_prefix, out_f, "eps", false); } return EXECUTION_OK; } }; int main(int argc, const char ** argv) { AdditiveSeries tool; return tool.main(argc, argv); } /// @endcond
39.459954
367
0.571677
[ "vector" ]
381134000af223f60d04c4bdef6e76c2927311d2
448
cpp
C++
Codility/003_02_PermMissingElem.cpp
HaileyGu/Algorithm
229002f27cc3cb4b5ab8785997d0790a892f7741
[ "MIT" ]
1
2019-03-09T04:22:33.000Z
2019-03-09T04:22:33.000Z
Codility/003_02_PermMissingElem.cpp
HaileyGu/Algorithm
229002f27cc3cb4b5ab8785997d0790a892f7741
[ "MIT" ]
null
null
null
Codility/003_02_PermMissingElem.cpp
HaileyGu/Algorithm
229002f27cc3cb4b5ab8785997d0790a892f7741
[ "MIT" ]
null
null
null
// you can use includes, for example: // #include <algorithm> // you can write to stdout for debugging purposes, e.g. // cout << "this is a debug message" << endl; int solution(vector<int> &A) { // write your code in C++14 (g++ 6.2.0) int n = A.size(); int ans = 0; int sumI = 0; int sumA = 0; for(int i = 0; i < n; i++) { sumI += (i+1); sumA += A[i]; } sumI += (n+1); return (sumI-sumA); }
19.478261
55
0.511161
[ "vector" ]
3815780ff0f79fc549b48faab6b05b05acbef4f3
5,988
cpp
C++
src/decoder-phrasebased/src/native/decoder/moses/ScoreComponentCollectionTest.cpp
ugermann/MMT
715ad16b4467f44c8103e16165261d1391a69fb8
[ "Apache-2.0" ]
null
null
null
src/decoder-phrasebased/src/native/decoder/moses/ScoreComponentCollectionTest.cpp
ugermann/MMT
715ad16b4467f44c8103e16165261d1391a69fb8
[ "Apache-2.0" ]
null
null
null
src/decoder-phrasebased/src/native/decoder/moses/ScoreComponentCollectionTest.cpp
ugermann/MMT
715ad16b4467f44c8103e16165261d1391a69fb8
[ "Apache-2.0" ]
null
null
null
/*********************************************************************** Moses - factored phrase-based language decoder Copyright (C) 2010 University of Edinburgh 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 Street, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #include <stdexcept> #include <boost/test/unit_test.hpp> #include "FF/StatelessFeatureFunction.h" #include "ScoreComponentCollection.h" using namespace Moses; using namespace std; BOOST_AUTO_TEST_SUITE(scc) class MockStatelessFeatureFunction : public StatelessFeatureFunction { public: MockStatelessFeatureFunction(size_t n, const string &line) : StatelessFeatureFunction(n, line) {} void EvaluateWhenApplied(const Hypothesis&, ScoreComponentCollection*) const {} void EvaluateWhenApplied(const ChartHypothesis&, ScoreComponentCollection*) const {} void EvaluateWithSourceContext(const InputType &input , const InputPath &inputPath , const TargetPhrase &targetPhrase , const StackVec *stackVec , ScoreComponentCollection &scoreBreakdown , ScoreComponentCollection *estimatedScores) const { } void EvaluateTranslationOptionListWithSourceContext(const InputType &input , const TranslationOptionList &translationOptionList) const { } void EvaluateInIsolation(const Phrase &source , const TargetPhrase &targetPhrase , ScoreComponentCollection &scoreBreakdown , ScoreComponentCollection &estimatedScores) const { } }; class MockSingleFeature : public MockStatelessFeatureFunction { public: MockSingleFeature(): MockStatelessFeatureFunction(1, "MockSingle") {} bool IsUseable(const FactorMask &mask) const { return true; } }; class MockMultiFeature : public MockStatelessFeatureFunction { public: MockMultiFeature(): MockStatelessFeatureFunction(5, "MockMulti") {} bool IsUseable(const FactorMask &mask) const { return true; } }; class MockSparseFeature : public MockStatelessFeatureFunction { public: MockSparseFeature(): MockStatelessFeatureFunction(0, "MockSparse") {} bool IsUseable(const FactorMask &mask) const { return true; } }; struct MockProducers { MockProducers() { FeatureFunction::Register(&single); FeatureFunction::Register(&multi); FeatureFunction::Register(&sparse); } MockSingleFeature single; MockMultiFeature multi; MockSparseFeature sparse; }; BOOST_FIXTURE_TEST_CASE(ctor, MockProducers) { ScoreComponentCollection scc; BOOST_CHECK_EQUAL(scc.GetScoreForProducer(&single),0); float expected[] = {0,0,0,0,0}; std::vector<float> actual= scc.GetScoresForProducer(&multi); BOOST_CHECK_EQUAL_COLLECTIONS(expected, expected+5, actual.begin(), actual.begin()+5); } BOOST_FIXTURE_TEST_CASE(plusequals, MockProducers) { float arr1[] = {1,2,3,4,5}; float arr2[] = {2,4,6,8,10}; std::vector<float> vec1(arr1,arr1+5); std::vector<float> vec2(arr2,arr2+5); ScoreComponentCollection scc; scc.PlusEquals(&single, 3.4f); BOOST_CHECK_EQUAL(scc.GetScoreForProducer(&single), 3.4f); scc.PlusEquals(&multi,vec1); std::vector<float> actual = scc.GetScoresForProducer(&multi); BOOST_CHECK_EQUAL_COLLECTIONS(vec1.begin(),vec1.end() ,actual.begin(), actual.end()); scc.PlusEquals(&multi,vec1); actual = scc.GetScoresForProducer(&multi); BOOST_CHECK_EQUAL_COLLECTIONS(vec2.begin(),vec2.end(), actual.begin(), actual.end()); BOOST_CHECK_EQUAL(scc.GetScoreForProducer(&single), 3.4f); } BOOST_FIXTURE_TEST_CASE(sparse_feature, MockProducers) { ScoreComponentCollection scc; scc.Assign(&sparse, "first", 1.3f); scc.Assign(&sparse, "second", 2.1f); BOOST_CHECK_EQUAL( scc.GetScoreForProducer(&sparse,"first"), 1.3f); BOOST_CHECK_EQUAL( scc.GetScoreForProducer(&sparse,"second"), 2.1f); BOOST_CHECK_EQUAL( scc.GetScoreForProducer(&sparse,"third"), 0.0f); scc.Assign(&sparse, "first", -1.9f); BOOST_CHECK_EQUAL( scc.GetScoreForProducer(&sparse,"first"), -1.9f); scc.PlusEquals(&sparse, StringPiece("first"), -1.9f); BOOST_CHECK_EQUAL( scc.GetScoreForProducer(&sparse,"first"), -3.8f); } /* Doesn't work because of the static registration of ScoreProducers in ScoreComponentCollection. BOOST_FIXTURE_TEST_CASE(save, MockProducers) { ScoreComponentCollection scc; scc.Assign(&sparse, "first", 1.1f); scc.Assign(&single, 0.25f); float arr[] = {1,2.1,3,4,5}; std::vector<float> vec1(arr,arr+5); scc.Assign(&multi,vec1); ostringstream out; scc.Save(out); cerr << out.str() << endl; istringstream in (out.str()); string line; getline(in,line); BOOST_CHECK_EQUAL(line, "MockSingle:4_1 0.25"); getline(in,line); BOOST_CHECK_EQUAL(line, "MockMulti:4_1 1"); getline(in,line); BOOST_CHECK_EQUAL(line, "MockMulti:4_2 2.1"); getline(in,line); BOOST_CHECK_EQUAL(line, "MockMulti:4_3 3"); getline(in,line); BOOST_CHECK_EQUAL(line, "MockMulti:4_4 4"); getline(in,line); BOOST_CHECK_EQUAL(line, "MockMulti:4_5 5"); getline(in,line); BOOST_CHECK_EQUAL(line,"MockSparse:4_first 1.1"); BOOST_CHECK(!getline(in,line)); } */ BOOST_AUTO_TEST_SUITE_END()
32.367568
88
0.69823
[ "vector" ]
38165e9bfad9bf0ddd39d784ce8eeefaae0e0948
8,209
cpp
C++
Tga3D/Source/tga2dcore/tga2d/shaders/SpriteShader.cpp
sarisman84/C-CommonUtilities
a3649c32232ec342c25b804001c16c295885ce0c
[ "MIT" ]
1
2022-03-10T11:43:24.000Z
2022-03-10T11:43:24.000Z
Tga3D/Source/tga2dcore/tga2d/shaders/SpriteShader.cpp
sarisman84/C-CommonUtilities
a3649c32232ec342c25b804001c16c295885ce0c
[ "MIT" ]
null
null
null
Tga3D/Source/tga2dcore/tga2d/shaders/SpriteShader.cpp
sarisman84/C-CommonUtilities
a3649c32232ec342c25b804001c16c295885ce0c
[ "MIT" ]
null
null
null
#include "stdafx.h" #include <tga2d/graphics/DX11.h> #include <tga2d/shaders/SpriteShader.h> #include <tga2d/shaders/ShaderCommon.h> #include <tga2d/texture/texture.h> #include <tga2d/texture/TextureManager.h> #include <tga2d/render/RenderObject.h> #include <d3dcommon.h> #include <d3d11.h> Tga2D::SpriteShader::SpriteShader() : Shader(Engine::GetInstance()) { myCurrentDataIndex = -1; myBufferIndex = (int)ShaderDataBufferIndex::Index_1; myCurrentTextureCount = 0; } bool Tga2D::SpriteShader::Init(const wchar_t* aVertex, const wchar_t* aPixel) { if (!CreateShaders(aVertex, aPixel)) { return false; } D3D11_BUFFER_DESC commonBufferDesc; commonBufferDesc.Usage = D3D11_USAGE_DYNAMIC; commonBufferDesc.ByteWidth = sizeof(Tga2D::Vector4f) * 64; commonBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; commonBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; commonBufferDesc.MiscFlags = 0; commonBufferDesc.StructureByteStride = 0; HRESULT result = DX11::Device->CreateBuffer(&commonBufferDesc, NULL, myCustomBuffer.ReleaseAndGetAddressOf()); if (result != S_OK) { ERROR_PRINT("DX2D::CCustomShader::PostInit - Size missmatch between CPU and GPU(shader)"); return false; } return true; } void Tga2D::SpriteShader::SetDataBufferIndex(ShaderDataBufferIndex aBufferRegisterIndex) { myBufferIndex = (unsigned char)aBufferRegisterIndex; } void Tga2D::SpriteShader::SetShaderdataFloat4(Tga2D::Vector4f someData, ShaderDataID aID) { if (aID > MAX_SHADER_DATA) { ERROR_PRINT("DX2D::CCustomShader::SetShaderdataFloat4() The id is bigger than allowed size"); return; } myCustomData[aID] = someData; if (aID > myCurrentDataIndex) { myCurrentDataIndex = aID; } } void Tga2D::SpriteShader::SetTextureAtRegister(Tga2D::TextureResource* aTexture, ShaderTextureSlot aRegisterIndex) { myBoundTextures[aRegisterIndex - 4] = BoundTexture(aTexture, (unsigned char)aRegisterIndex); if (myCurrentTextureCount < (aRegisterIndex - 4) + 1) { myCurrentTextureCount = static_cast<unsigned char>((aRegisterIndex - 4) + 1); } } bool Tga2D::SpriteShader::PrepareRender(const SpriteSharedData& aSharedData) { if (!Shader::PrepareRender(aSharedData)) return false; Engine& engine = *Engine::GetInstance(); ID3D11DeviceContext* context = DX11::Context; ID3D11ShaderResourceView* textures[1 + ShaderMap::MAP_MAX]; textures[0] = aSharedData.myTexture ? aSharedData.myTexture->GetShaderResourceView() : engine.GetTextureManager().GetWhiteSquareTexture()->GetShaderResourceView(); for (unsigned short index = 0; index < ShaderMap::MAP_MAX; index++) { textures[1 + index] = engine.GetTextureManager().GetDefaultNormalMapResource(); if (aSharedData.myMaps[index]) { textures[1 + index] = aSharedData.myMaps[index]->GetShaderResourceView(); } } DX11::Context->PSSetShaderResources(1, 1 + ShaderMap::MAP_MAX, textures); if (myCustomBuffer) { D3D11_MAPPED_SUBRESOURCE mappedResourceCommon; Tga2D::Vector4f* dataPtrCommon; HRESULT result = context->Map(myCustomBuffer.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResourceCommon); if (FAILED(result)) { return false; } dataPtrCommon = (Tga2D::Vector4f*)mappedResourceCommon.pData; for (int i = 0; i < myCurrentDataIndex + 1; i++) { dataPtrCommon[i].x = myCustomData[i].x; dataPtrCommon[i].y = myCustomData[i].y; dataPtrCommon[i].z = myCustomData[i].z; dataPtrCommon[i].w = myCustomData[i].w; } context->Unmap(myCustomBuffer.Get(), 0); context->VSSetConstantBuffers(myBufferIndex, 1, myCustomBuffer.GetAddressOf()); context->PSSetConstantBuffers(myBufferIndex, 1, myCustomBuffer.GetAddressOf()); } for (int i = 0; i < myCurrentTextureCount; i++) { ID3D11ShaderResourceView* customTextures[1]; customTextures[0] = myBoundTextures[i].myTexture->GetShaderResourceView(); context->PSSetShaderResources(myBoundTextures[i].myIndex, 1, customTextures); } return true; } bool Tga2D::SpriteShader::CreateInputLayout(const std::string& aVS) { D3D11_INPUT_ELEMENT_DESC polygonLayout[10]; int i = 0; polygonLayout[i].SemanticName = "POSITION"; polygonLayout[i].SemanticIndex = 0; polygonLayout[i].Format = DXGI_FORMAT_R32G32B32A32_FLOAT; polygonLayout[i].InputSlot = 0; polygonLayout[i].AlignedByteOffset = 0; polygonLayout[i].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[i].InstanceDataStepRate = 0; i++; polygonLayout[i].SemanticName = "TEXCOORD"; polygonLayout[i].SemanticIndex = i - 1; polygonLayout[i].Format = DXGI_FORMAT_R32G32B32A32_UINT; polygonLayout[i].InputSlot = 0; polygonLayout[i].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[i].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[i].InstanceDataStepRate = 0; i++; polygonLayout[i].SemanticName = "TEXCOORD"; polygonLayout[i].SemanticIndex = i - 1; polygonLayout[i].Format = DXGI_FORMAT_R32G32B32A32_FLOAT; polygonLayout[i].InputSlot = 1; polygonLayout[i].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[i].InputSlotClass = D3D11_INPUT_PER_INSTANCE_DATA; polygonLayout[i].InstanceDataStepRate = 1; i++; polygonLayout[i].SemanticName = "TEXCOORD"; polygonLayout[i].SemanticIndex = i - 1; polygonLayout[i].Format = DXGI_FORMAT_R32G32B32A32_FLOAT; polygonLayout[i].InputSlot = 1; polygonLayout[i].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[i].InputSlotClass = D3D11_INPUT_PER_INSTANCE_DATA; polygonLayout[i].InstanceDataStepRate = 1; i++; polygonLayout[i].SemanticName = "TEXCOORD"; polygonLayout[i].SemanticIndex = i - 1; polygonLayout[i].Format = DXGI_FORMAT_R32G32B32A32_FLOAT; polygonLayout[i].InputSlot = 1; polygonLayout[i].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[i].InputSlotClass = D3D11_INPUT_PER_INSTANCE_DATA; polygonLayout[i].InstanceDataStepRate = 1; i++; polygonLayout[i].SemanticName = "TEXCOORD"; polygonLayout[i].SemanticIndex = i - 1; polygonLayout[i].Format = DXGI_FORMAT_R32G32B32A32_FLOAT; polygonLayout[i].InputSlot = 1; polygonLayout[i].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[i].InputSlotClass = D3D11_INPUT_PER_INSTANCE_DATA; polygonLayout[i].InstanceDataStepRate = 1; i++; polygonLayout[i].SemanticName = "TEXCOORD"; polygonLayout[i].SemanticIndex = i - 1; polygonLayout[i].Format = DXGI_FORMAT_R32G32B32A32_FLOAT; polygonLayout[i].InputSlot = 1; polygonLayout[i].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[i].InputSlotClass = D3D11_INPUT_PER_INSTANCE_DATA; polygonLayout[i].InstanceDataStepRate = 1; i++; polygonLayout[i].SemanticName = "TEXCOORD"; polygonLayout[i].SemanticIndex = i - 1; polygonLayout[i].Format = DXGI_FORMAT_R32G32B32A32_FLOAT; polygonLayout[i].InputSlot = 1; polygonLayout[i].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[i].InputSlotClass = D3D11_INPUT_PER_INSTANCE_DATA; polygonLayout[i].InstanceDataStepRate = 1; i++; polygonLayout[i].SemanticName = "TEXCOORD"; polygonLayout[i].SemanticIndex = i - 1; polygonLayout[i].Format = DXGI_FORMAT_R32G32B32A32_FLOAT; polygonLayout[i].InputSlot = 1; polygonLayout[i].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[i].InputSlotClass = D3D11_INPUT_PER_INSTANCE_DATA; polygonLayout[i].InstanceDataStepRate = 1; i++; polygonLayout[i].SemanticName = "TEXCOORD"; polygonLayout[i].SemanticIndex = i - 1; polygonLayout[i].Format = DXGI_FORMAT_R32G32B32A32_FLOAT; polygonLayout[i].InputSlot = 1; polygonLayout[i].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[i].InputSlotClass = D3D11_INPUT_PER_INSTANCE_DATA; polygonLayout[i].InstanceDataStepRate = 1; i++; unsigned int numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]); // Create the vertex input layout. HRESULT result = DX11::Device->CreateInputLayout(polygonLayout, numElements, aVS.data(), aVS.size(), myLayout.ReleaseAndGetAddressOf()); if (FAILED(result)) { ERROR_PRINT("%s", "Layout error"); } return true; }
34.204167
165
0.749787
[ "render" ]
381a1e42782a2e9100ec412da1a2ae1e6376ec6b
11,301
cpp
C++
src/swift2d/trails/TrailSystem.cpp
Simmesimme/swift2d
147a862208dee56f972361b5325009e020124137
[ "MIT" ]
null
null
null
src/swift2d/trails/TrailSystem.cpp
Simmesimme/swift2d
147a862208dee56f972361b5325009e020124137
[ "MIT" ]
null
null
null
src/swift2d/trails/TrailSystem.cpp
Simmesimme/swift2d
147a862208dee56f972361b5325009e020124137
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // // // This file is part of Swift2D. // // // // Copyright: (c) 2011-2015 Simon Schneegans & Felix Lauer // // // // This software may be modified and distributed under the terms // // of the MIT license. See the LICENSE file for details. // // // //////////////////////////////////////////////////////////////////////////////// // includes ------------------------------------------------------------------- #include <swift2d/trails/TrailSystem.hpp> #include <swift2d/physics/Physics.hpp> #include <swift2d/trails/TrailSystemComponent.hpp> #include <swift2d/trails/TrailUpdateShader.hpp> #include <swift2d/textures/NoiseTexture.hpp> #include <swift2d/math.hpp> #include <swift2d/utils/Logger.hpp> #include <swift2d/graphics/Pipeline.hpp> #include <sstream> namespace swift { //////////////////////////////////////////////////////////////////////////////// struct GPUTrailSegment { math::vec2 pos; math::vec2 life; math::vec2 prev_u_texcoords; // last and prev_1 math::vec2 prev_1_pos; math::vec2 prev_2_pos; math::vec2 prev_3_pos; }; //////////////////////////////////////////////////////////////////////////////// TrailSystem::TrailSystem(int max_trail_points) : transform_feedbacks_() , trail_vaos_() , trail_buffers_() , emitter_buffer_(nullptr) , emitter_vao_(nullptr) , ping_(true) , update_max_trail_points_(max_trail_points) {} //////////////////////////////////////////////////////////////////////////////// void TrailSystem::set_max_trail_points(int max_trail_points) { update_max_trail_points_ = max_trail_points; } //////////////////////////////////////////////////////////////////////////////// void TrailSystem::spawn( std::vector<TrailSegment> const& end_segments, std::vector<TrailSegment> const& new_segments) { std::unique_lock<std::mutex> lock(mutex_); new_segments_.insert(new_segments_.begin(), new_segments.begin(), new_segments.end()); end_segments_ping_ = end_segments; } //////////////////////////////////////////////////////////////////////////////// void TrailSystem::upload_to(RenderContext const& ctx) { // allocate GPU resources for (int i(0); i<2; ++i) { transform_feedbacks_.push_back(ogl::TransformFeedback()); trail_vaos_.push_back(ogl::VertexArray()); trail_buffers_.push_back(ogl::Buffer()); trail_vaos_[i].Bind(); trail_buffers_[i].Bind(ose::Array()); for (long j(0); j<6; ++j) { ogl::VertexArrayAttrib(j).Enable(); ogl::VertexArrayAttrib(j).Pointer(2, ogl::DataType::Float, false, sizeof(GPUTrailSegment), (void const*)(j*2*sizeof(float))); } ogl::NoVertexArray().Bind(); } emitter_buffer_ = new ogl::Buffer(); emitter_vao_ = new ogl::VertexArray(); emitter_vao_->Bind(); emitter_buffer_->Bind(ose::Array()); for (long j(0); j<6; ++j) { ogl::VertexArrayAttrib(j).Enable(); ogl::VertexArrayAttrib(j).Pointer(2, ogl::DataType::Float, false, sizeof(GPUTrailSegment), (void const*)(j*2*sizeof(float))); } ogl::NoVertexArray().Bind(); } //////////////////////////////////////////////////////////////////////////////// void TrailSystem::update_trails( TrailSystemComponent::Serialized const& system, RenderContext const& ctx) { bool first_draw(false); // upload to GPU if neccessary if (trail_buffers_.empty()) { upload_to(ctx); first_draw = true; } // update buffer size if necessary if (update_max_trail_points_ > 0) { for (int i(0); i<2; ++i) { trail_buffers_[i].Bind(ose::Array()); std::vector<GPUTrailSegment> data(update_max_trail_points_); data.front().pos = math::vec2(0.f, 0.f); data.front().life = math::vec2(0.f, 0.f); data.front().prev_u_texcoords = math::vec2(0.f, 0.f); data.front().prev_1_pos = math::vec2(0.f, 0.f); data.front().prev_2_pos = math::vec2(0.f, 0.f); data.front().prev_3_pos = math::vec2(0.f, 0.f); ogl::Buffer::Data(ose::Array(), data, ose::StreamCopy()); } update_max_trail_points_ = 0; } // get frame time double frame_time(ctx.pipeline->get_frame_time()); double total_time(ctx.pipeline->get_total_time()); // swap ping pong buffers ping_ = !ping_; ogl::Context::Enable(ogl::Capability::RasterizerDiscard); trail_vaos_ [current_vb()].Bind(); transform_feedbacks_[current_tf()].Bind(); trail_buffers_ [current_tf()].BindBase(ose::TransformFeedback(), 0); auto& shader(TrailUpdateShader::get()); shader.use(); shader.time. Set(math::vec2(frame_time, total_time)*1000.0); shader.use_global_texcoords. Set(system.UseGlobalTexCoords ? 1 : 0); std::vector<math::vec2> positions0; std::vector<math::vec2> positions1; std::vector<math::vec2> positions2; std::vector<math::vec2> positions3; std::vector<math::vec4> times; transform_feedbacks_[current_tf()].BeginPoints(); { // spawn new particles ----------------------------------------------------- { std::unique_lock<std::mutex> lock(mutex_); for (auto const& segment: new_segments_) { times.push_back(math::vec4( segment.TimeSincePrev1Spawn * 1000.0f, segment.TimeSincePrev2Spawn * 1000.0f, segment.Life * 1000.0f, segment.StartAge * 1000.f )); positions0.push_back(segment.Prev1Position); positions1.push_back(segment.Prev2Position); positions2.push_back(segment.Prev3Position); positions3.push_back(segment.Prev4Position); } new_segments_.clear(); end_segments_pong_ = end_segments_ping_; } int index(0); while (index < positions0.size()) { std::size_t count(std::min(50, (int)positions0.size()-index)); shader.spawn_count. Set(count); shader.times. Set(count, (const math::vec4*)&times[index]); shader.position. Set(count, (const math::vec2*)&positions0[index]); shader.prev_1_position. Set(count, (const math::vec2*)&positions1[index]); shader.prev_2_position. Set(count, (const math::vec2*)&positions2[index]); shader.prev_3_position. Set(count, (const math::vec2*)&positions3[index]); ogl::Context::DrawArrays(ogl::PrimitiveType::Points, 0, 1); index += count; } // update existing particles ----------------------------------------------- if (!first_draw) { shader.spawn_count.Set(-1); ogl::Context::DrawTransformFeedback( ogl::PrimitiveType::Points, transform_feedbacks_[current_vb()] ); } } transform_feedbacks_[current_tf()].End(); ogl::DefaultTransformFeedback().Bind(); ogl::Context::Disable(ogl::Capability::RasterizerDiscard); ogl::NoVertexArray().Bind(); } //////////////////////////////////////////////////////////////////////////////// void TrailSystem::draw_trails( TrailSystemComponent::Serialized const& system, RenderContext const& ctx) { std::vector<GPUTrailSegment> segments; double total_time(ctx.pipeline->get_total_time()); { std::unique_lock<std::mutex> lock(mutex_); for (auto const& segment : end_segments_pong_) { GPUTrailSegment trail_point; math::vec2 start_age(segment.StartAge / segment.Life, segment.StartAge / segment.Life); trail_point.life = math::vec2(start_age.x(), segment.Life * 1000.0); if (segment.Prev1Position != segment.Position) { // create last segment auto next_dir(segment.Position - segment.Prev1Position); trail_point.pos = segment.Position + next_dir; if (system.UseGlobalTexCoords) { trail_point.prev_u_texcoords = 1.0/segment.Life * math::vec2(total_time, total_time - segment.TimeSinceLastSpawn); trail_point.prev_u_texcoords -= start_age; } else { trail_point.prev_u_texcoords = 1.0/segment.Life * math::vec2(0.0, segment.TimeSinceLastSpawn); trail_point.prev_u_texcoords += start_age; } trail_point.prev_1_pos = segment.Position; trail_point.prev_2_pos = segment.Prev1Position; trail_point.prev_3_pos = segment.Prev2Position; segments.push_back(trail_point); // create last but one segment if (system.UseGlobalTexCoords) { trail_point.prev_u_texcoords = 1.0/segment.Life * math::vec2(total_time - segment.TimeSinceLastSpawn, total_time - segment.TimeSincePrev1Spawn); trail_point.prev_u_texcoords -= start_age; } else { trail_point.prev_u_texcoords = 1.0/segment.Life * math::vec2(segment.TimeSinceLastSpawn, segment.TimeSincePrev1Spawn); trail_point.prev_u_texcoords += start_age; } trail_point.pos = segment.Position; trail_point.prev_1_pos = segment.Prev1Position; trail_point.prev_2_pos = segment.Prev2Position; trail_point.prev_3_pos = segment.Prev3Position; segments.push_back(trail_point); } else { // create only last segment auto next_dir(segment.Prev1Position - segment.Prev2Position); trail_point.pos = segment.Prev1Position + next_dir; if (system.UseGlobalTexCoords) { trail_point.prev_u_texcoords = 1.0/segment.Life * math::vec2(total_time, total_time - segment.TimeSincePrev1Spawn); trail_point.prev_u_texcoords -= start_age; } else { trail_point.prev_u_texcoords = 1.0/segment.Life * math::vec2(0.0, segment.TimeSincePrev1Spawn); trail_point.prev_u_texcoords += start_age; } trail_point.prev_1_pos = segment.Prev1Position; trail_point.prev_2_pos = segment.Prev2Position; trail_point.prev_3_pos = segment.Prev3Position; segments.push_back(trail_point); } } } emitter_buffer_->Bind(oglplus::Buffer::Target::Array); oglplus::Buffer::Data(oglplus::Buffer::Target::Array, segments, ose::StreamDraw()); emitter_vao_->Bind(); ogl::Context::DrawArrays(ogl::PrimitiveType::Points, 0, segments.size()); trail_vaos_[current_tf()].Bind(); ogl::Context::DrawTransformFeedback( ogl::PrimitiveType::Points, transform_feedbacks_[current_tf()] ); } //////////////////////////////////////////////////////////////////////////////// }
35.096273
131
0.55473
[ "vector" ]
381a8c52e34a4a1765bb346c25fac932723526bf
31,624
cpp
C++
src/TEM.cpp
rarutter/dvm-dos-tem
8e776005c3883aae67b83bb71c5e1e25c94fc842
[ "MIT" ]
null
null
null
src/TEM.cpp
rarutter/dvm-dos-tem
8e776005c3883aae67b83bb71c5e1e25c94fc842
[ "MIT" ]
null
null
null
src/TEM.cpp
rarutter/dvm-dos-tem
8e776005c3883aae67b83bb71c5e1e25c94fc842
[ "MIT" ]
null
null
null
/** * TEM.cpp * main program for running DVM-DOS-TEM * * It runs at 3 run-mods: * (1) site-specific * (2) regional - time series * (3) regional - spatially (not yet available) * * Authors: * Shuhua Yi - the original codes * Fengming Yuan - re-designing and re-coding for * (1) easily code managing; * (2) java interface developing for calibration; * (3) stand-alone application of TEM (java-c++) * (4) inputs/outputs using netcdf format, have to be modified to fix memory-leaks * (5) fix the snow/soil thermal/hydraulic algorithms * (6) DVM coupled * Tobey Carman - modifications and maintenance * (1) update application entry point with boost command line arg. handling. * * Affilation: Spatial Ecology Lab, University of Alaska Fairbanks * * started: 11/01/2010 * last modified: 09/18/2012 */ #include <string> #include <iostream> #include <fstream> #include <sstream> #include <ctime> #include <cstdlib> #include <cstddef> // for offsetof() #include <exception> #include <map> #include <set> #include <json/writer.h> #include <json/value.h> #include <boost/filesystem.hpp> #include <boost/asio/signal_set.hpp> #include <boost/thread.hpp> #include <boost/shared_ptr.hpp> #include <boost/bind.hpp> #include <boost/asio.hpp> #include <json/value.h> #include <omp.h> #ifdef WITHMPI #include <mpi.h> #include "data/RestartData.h" // for defining MPI typemap... //#include "inc/tbc_mpi_constants.h" #endif // For managing the floating point environment #ifdef BSD_FPE #include <xmmintrin.h> // BSD (OSX) #endif #ifdef GNU_FPE #include <fenv.h> // GNU Linux #endif #include "inc/timeconst.h" #include "../include/ArgHandler.h" #include "../include/OutputEstimate.h" #include "TEMLogger.h" #include "TEMUtilityFunctions.h" #include "../include/Runner.h" #include "data/RestartData.h" #include <netcdf.h> /** Quick 'n dirty pretty printer for vector of things */ template <typename TYPE> void ppv(const std::vector<TYPE> &v){ typename std::vector<TYPE>::const_iterator it; for (it = v.begin(); it != v.end(); ++it) { std::cout << *it << " "; } std::cout << "\n"; } /** Write out a status code to a particular pixel in the run status file. */ void write_status(const std::string fname, int row, int col, int statusCode); /** Builds an empty netcdf file for recording the run status. * Ultimately we might want to spit the run status out in a more easily * consumable way like txt to stdout or json, but for now we can use netcdf. * Also it makes for a simple netcdf file to experiment with for MPI, * parallel output */ void create_empty_run_status_file(const std::string& fname, const int ysize, const int xsize); // The main driving function void advance_model(const int rowidx, const int colidx, const ModelData&, const bool calmode, const std::string& eq_restart_fname, const std::string& sp_restart_fname, const std::string& tr_restart_fname, const std::string& sc_restart_fname); // draft pretty-printers... void pp_2dvec(const std::vector<std::vector<int> > & vv); // draft - generate a netcdf file that can follow CF conventions //void create_netCDF_output_files(int ysize, int xsize); // draft - reading new-style co2 file std::vector<float> read_new_co2_file(const std::string &filename); /** Enables a 'floating point exception' mask that will make the program crash * when a floating point number is generated (and or operated upon). * * Some more info * http://www.johndcook.com/blog/ieee_exceptions_in_cpp/ * http://stackoverflow.com/questions/247053/enabling-floating-point-interrupts-on-mac-os-x-intel * * It might be helpful to add a singal handler at some point that could report * on what/where the exception is generated? */ void enable_floating_point_exceptions() { std::cout << "Enabling floating point exceptions mask!" << std::endl; // BSD (OSX) #ifdef BSD_FPE _MM_SET_EXCEPTION_MASK(_MM_GET_EXCEPTION_MASK() & ~_MM_MASK_INVALID); #endif // GNU Linux #ifdef GNU_FPE feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW); #endif } ArgHandler* args = new ArgHandler(); extern src::severity_logger< severity_level > glg; int main(int argc, char* argv[]){ // Read in and parse the command line arguments args->parse(argc, argv); if (args->get_help()) { args->show_help(); return 0; } std::cout << "Setting up logging...\n"; setup_logging(args->get_log_level(), args->get_log_scope()); BOOST_LOG_SEV(glg, note) << "Checking command line arguments..."; args->verify(); // stub - doesn't really do anything yet BOOST_LOG_SEV(glg, note) << "Turn floating point exceptions on?: " << args->get_fpe(); if (args->get_fpe()) { enable_floating_point_exceptions(); } BOOST_LOG_SEV(glg, note) << "Reading controlfile into main(..) scope..."; Json::Value controldata = temutil::parse_control_file(args->get_ctrl_file()); BOOST_LOG_SEV(glg, note) << "Creating a ModelData object based on settings in the control file"; ModelData modeldata(controldata); BOOST_LOG_SEV(glg, note) << "Update model settings based on command line flags/options..."; modeldata.update(args); /* Someday it may be worth the time/effort to make better use of boots::program_options here to manage the arguments from config file and the command line. */ BOOST_LOG_SEV(glg, note) << "Running PR stage: " << modeldata.pr_yrs << "yrs"; BOOST_LOG_SEV(glg, note) << "Running EQ stage: " << modeldata.eq_yrs << "yrs"; BOOST_LOG_SEV(glg, note) << "Running SP stage: " << modeldata.sp_yrs << "yrs"; BOOST_LOG_SEV(glg, note) << "Running TR stage: " << modeldata.tr_yrs << "yrs"; BOOST_LOG_SEV(glg, note) << "Running SC stage: " << modeldata.sc_yrs << "yrs"; // Turn off buffering... setvbuf(stdout, NULL, _IONBF, 0); setvbuf(stderr, NULL, _IONBF, 0); time_t stime; time_t etime; stime = time(0); BOOST_LOG_SEV(glg, note) << "Start dvmdostem @ " << ctime(&stime); BOOST_LOG_SEV(glg, debug) << "NEW STYLE: Going to run space-major over a 2D area covered by run mask..."; // Open the run mask (spatial mask) std::vector< std::vector<int> > run_mask = temutil::read_run_mask(modeldata.runmask_file); // Figure out how big the run_mask is int num_rows = run_mask.size(); int num_cols = run_mask[0].size(); // Make some convenient handles for later... std::string run_status_fname = modeldata.output_dir + "run_status.nc"; std::string eq_restart_fname = modeldata.output_dir + "restart-eq.nc"; std::string sp_restart_fname = modeldata.output_dir + "restart-sp.nc"; std::string tr_restart_fname = modeldata.output_dir + "restart-tr.nc"; std::string sc_restart_fname = modeldata.output_dir + "restart-sc.nc"; #ifdef WITHMPI BOOST_LOG_SEV(glg, fatal) << "Built and running with MPI"; // Intended for passing argc and argv, the arguments to MPI_Init // are currently unnecessary. MPI_Init(NULL, NULL); int id = MPI::COMM_WORLD.Get_rank(); int ntasks = MPI::COMM_WORLD.Get_size(); #else // int id = 0; #endif // Limit output directory and file setup to a single process. // variable 'id' is artificially set to 0 if not built with MPI. if(id==0){ BOOST_LOG_SEV(glg, info) << "Handling single-process setup"; BOOST_LOG_SEV(glg, info) << "Checking for output directory: "<<modeldata.output_dir; boost::filesystem::path out_dir_path(modeldata.output_dir); if( boost::filesystem::exists(out_dir_path) ){ if (args->get_no_output_cleanup()) { BOOST_LOG_SEV(glg, warn) << "WARNING!! Not cleaning up output directory! " << "Old and potentially confusing files may be " << "present from previous runs!!"; } else { BOOST_LOG_SEV(glg, info) << "Output directory exists. Deleting..."; boost::filesystem::remove_all(out_dir_path); } } BOOST_LOG_SEV(glg, info) << "Creating output directory: "<<modeldata.output_dir; boost::filesystem::create_directories(out_dir_path); // Create empty restart files for all stages based on size of run mask BOOST_LOG_SEV(glg, info) << "Creating empty restart files."; RestartData::create_empty_file(eq_restart_fname, num_rows, num_cols); RestartData::create_empty_file(sp_restart_fname, num_rows, num_cols); RestartData::create_empty_file(tr_restart_fname, num_rows, num_cols); RestartData::create_empty_file(sc_restart_fname, num_rows, num_cols); #ifdef WITHMPI MPI_Barrier(MPI::COMM_WORLD); } // End of single-process setup else{ // Block all processes until process 0 has completed output // directory setup. MPI_Barrier(MPI::COMM_WORLD); } #else } // Nothing to do; only one process, id will equal 0. #endif // Create empty run status file BOOST_LOG_SEV(glg, info) << "Creating empty run status file."; create_empty_run_status_file(run_status_fname, num_rows, num_cols); // Create empty output files now so that later, as the program // proceeds, there is somewhere to append output data... BOOST_LOG_SEV(glg, info) << "Creating a set of empty NetCDF output files"; if(modeldata.eq_yrs > 0 && modeldata.nc_eq){ modeldata.create_netCDF_output_files(num_rows, num_cols, "eq"); if(modeldata.eq_yrs > 100 && modeldata.daily_netcdf_outputs.size() > 0){ BOOST_LOG_SEV(glg, fatal) << "Daily outputs specified with EQ run greater than 100 years! Reconsider..."; } } if(modeldata.sp_yrs > 0 && modeldata.nc_sp){ modeldata.create_netCDF_output_files(num_rows, num_cols, "sp"); } if(modeldata.tr_yrs > 0 && modeldata.nc_tr){ modeldata.create_netCDF_output_files(num_rows, num_cols, "tr"); } if(modeldata.sc_yrs > 0 && modeldata.nc_sc){ modeldata.create_netCDF_output_files(num_rows, num_cols, "sc"); } // Work on checking that the particular configuration will not result in too // much output. OutputEstimate oe = OutputEstimate(modeldata, args->get_cal_mode()); BOOST_LOG_SEV(glg, info) << oe.estimate_as_table(); if (args->get_max_output_volume().compare("-1") == 0) { // pass - nothing to do, user doesn't want to check for excessive output. } else { std::string mxsz_s = args->get_max_output_volume(); double mxsz = oe.hsize2bytes(mxsz_s); if ( !(mxsz >= 0) ) { BOOST_LOG_SEV(glg, fatal) << "Invalid size specification!: " << mxsz_s; exit(-1); } if ( oe.all_cells_total() > mxsz ) { BOOST_LOG_SEV(glg, fatal) << oe.estimate_as_table(); BOOST_LOG_SEV(glg, fatal) << "TOO MUCH OUTPUT SPECIFIED! " << "ADJUST YOUR SETTINGS AND TRY AGAIN. " << "Or run with '--max-output-volume=-1'"; exit(-1); } } if (args->get_loop_order() == "space-major") { // y <==> row <==> lat // x <==> col <==> lon // Loop over a 2D grid of 'cells' (cohorts?), // run each cell for some number of years. // // Processing starts in the lower left corner (0,0). // Should really look into replacing this loop with // something like python's map(...) function... // --> Could this allow us to use a map reduce strategy?? // // Look into std::transform. // Use a few type definitions to save some typing. typedef std::vector<int> vec; typedef std::vector<vec> vec2D; vec2D::const_iterator row; vec::const_iterator col; // OpenMP requires: // - The structured block to have a single entry and exit point. // - The loop variable must be of type signed integer. // - The comparison operator must be in the form // loop_variable [<|<=|>|>=] loop_invariant integer // - The third expression must be either integer addition or // subtraction by a loop invariant value // - The loop must increment or decrement on every iteration, // depending on the comparison operator // - The loop must be a basic block: no jump to outside the loop // other than the exit statement. #ifdef WITHMPI BOOST_LOG_SEV(glg, info) << "Beginning MPI parallel section"; int id = MPI::COMM_WORLD.Get_rank(); int ntasks = MPI::COMM_WORLD.Get_size(); int total_cells = num_rows*num_cols; BOOST_LOG_SEV(glg, debug) << "id: "<<id<<" of ntasks: "<<ntasks; #pragma omp parallel for schedule(dynamic) for(int curr_cell=id; curr_cell<total_cells; curr_cell+=ntasks){ int rowidx = curr_cell / num_cols; int colidx = curr_cell % num_cols; bool mask_value = run_mask[rowidx][colidx]; BOOST_LOG_SEV(glg, fatal) << "MPI rank: "<<id<<", cell: "<<rowidx\ << ", "<<colidx<<" run: "<<mask_value; #else BOOST_LOG_SEV(glg, debug) << "Not built with MPI"; #pragma omp parallel for collapse(2) schedule(dynamic) for(int rowidx=0; rowidx<num_rows; rowidx++){ for(int colidx=0; colidx<num_cols; colidx++){ bool mask_value = run_mask[rowidx].at(colidx); #endif if (true == mask_value) { // I think this is safe w/in our OpenMP block because I am // handling the exception here... // Not sure about other OpenMP pragama blocks w/in this one? Any // Exceptions would leak out of the inner pragma and be handled // by this try/catch?? try { advance_model(rowidx, colidx, modeldata, args->get_cal_mode(), eq_restart_fname, sp_restart_fname, tr_restart_fname, sc_restart_fname); std::cout << "SUCCESS! Finished cell " << rowidx << ", " << colidx << ". Writing status file..\n"; write_status(run_status_fname, rowidx, colidx, 100); } catch (std::exception& e) { BOOST_LOG_SEV(glg, err) << "EXCEPTION!! (row, col): (" << rowidx << ", " << colidx << "): " << e.what(); // IS THIS THREAD SAFE?? // IS IT SAFE WITH MPI?? std::ofstream outfile; outfile.open((modeldata.output_dir + "fail_log.txt").c_str(), std::ios_base::app); // Append mode outfile << "EXCEPTION!! At pixel at (row, col): ("<<rowidx <<", "<<colidx<<") "<< e.what() <<"\n"; outfile.close(); // Write to fail_mask.nc file?? or json? might be good for visualization write_status(run_status_fname, rowidx, colidx, -100); // <- what if this throws?? BOOST_LOG_SEV(glg, err) << "End of exception handler."; } } else { BOOST_LOG_SEV(glg, fatal) << "Skipping cell (" << rowidx << ", " << colidx << ")"; write_status(run_status_fname, rowidx, colidx, 0); } #ifdef WITHMPI } MPI_Finalize(); #else }//end col loop }//end row loop #endif } else if (args->get_loop_order() == "time-major") { BOOST_LOG_SEV(glg, warn) << "DO NOTHING. NOT IMPLEMENTED YET."; // for each year // Read in Climate - all locations, one year/timestep // Read in Vegetation - all locations // Read in Drainage - all locations // Read in Fire - all locations // for each cohort // updateMonthly(...) } BOOST_LOG_SEV(glg, note) << "DONE WITH NEW STYLE run (" << args->get_loop_order() << ")"; etime = time(0); BOOST_LOG_SEV(glg, info) << "Total Seconds: " << difftime(etime, stime); return 0; } /* End main() */ /** Pretty print a 2D vector of ints */ void pp_2dvec(const std::vector<std::vector<int> > & vv) { typedef std::vector<int> vec; typedef std::vector<vec> vec2D; for (vec2D::const_iterator row = vv.begin(); row != vv.end(); ++row) { for (vec::const_iterator col = row->begin(); col != row->end(); ++col) { std::cout << *col << " "; } std::cout << std::endl; } } /** rough draft for reading new-style co2 data */ std::vector<float> read_new_co2_file(const std::string &filename) { int ncid; BOOST_LOG_SEV(glg, debug) << "Opening dataset: " << filename; temutil::nc( nc_open(filename.c_str(), NC_NOWRITE, &ncid) ); BOOST_LOG_SEV(glg, debug) << "Find out how much data there is..."; int yearD; size_t yearD_len; temutil::nc( nc_inq_dimid(ncid, "year", &yearD) ); temutil::nc( nc_inq_dimlen(ncid, yearD, &yearD_len) ); BOOST_LOG_SEV(glg, debug) << "Allocate vector big enough for " << yearD_len << " years of co2 data..."; std::vector<float> co2data(yearD_len); BOOST_LOG_SEV(glg, debug) << "Read the co2 data from the file into the vector..."; int co2V; temutil::nc( nc_inq_varid(ncid, "co2", &co2V) ); temutil::nc( nc_get_var(ncid, co2V, &co2data[0]) ); temutil::nc( nc_close(ncid) ); BOOST_LOG_SEV(glg, debug) << "Return the vector..."; return co2data; } /** Advance model. Attempt to drive the model thru the run-stages. * May throw exceptions. (Which kind?) */ void advance_model(const int rowidx, const int colidx, const ModelData& modeldata, const bool calmode, const std::string& eq_restart_fname, const std::string& sp_restart_fname, const std::string& tr_restart_fname, const std::string& sc_restart_fname) { BOOST_LOG_SEV(glg, note) << "Running cell (" << rowidx << ", " << colidx << ")"; //modeldata.initmode = 1; // OBSOLETE? BOOST_LOG_SEV(glg, info) << "Setup the NEW STYLE RUNNER OBJECT ..."; Runner runner(modeldata, calmode, rowidx, colidx); BOOST_LOG_SEV(glg, debug) << runner.cohort.ground.layer_report_string("depth thermal"); // seg fault w/o preparing climate...so prepare year zero... // this is also called inside run_years(...) runner.cohort.climate.prepare_daily_driving_data(0, "eq"); runner.cohort.initialize_internal_pointers(); // sets up lots of pointers to various things runner.cohort.initialize_state_parameters(); // sets data based on values in cohortlookup BOOST_LOG_SEV(glg, debug) << "right after initialize_internal_pointers() and initialize_state_parameters()" << runner.cohort.ground.layer_report_string("depth ptr"); // PRE RUN STAGE (PR) if (modeldata.pr_yrs > 0) { BOOST_LOG_NAMED_SCOPE("PRE-RUN"); /** Env-only "pre-run" stage. - should use only the env module - number of years to run can be controlled on cmd line - use fixed climate that is averaged over first X years - use static (fixed) co2 value (first element of co2 file) - FIX: need to set yrs since dsb ? - FIX: should ignore calibration directives? */ if (runner.calcontroller_ptr) { runner.calcontroller_ptr->handle_stage_start(); } // turn off everything but env runner.cohort.md->set_envmodule(true); runner.cohort.md->set_bgcmodule(false); runner.cohort.md->set_nfeed(false); runner.cohort.md->set_avlnflg(false); runner.cohort.md->set_baseline(false); runner.cohort.md->set_dsbmodule(false); runner.cohort.md->set_dslmodule(false); runner.cohort.md->set_dvmmodule(false); BOOST_LOG_SEV(glg, debug) << "Ground, right before 'pre-run'. " << runner.cohort.ground.layer_report_string("depth thermal"); runner.run_years(0, modeldata.pr_yrs, "pre-run"); // climate is prepared w/in here. BOOST_LOG_SEV(glg, debug) << "Ground, right after 'pre-run'" << runner.cohort.ground.layer_report_string("depth thermal"); if (runner.calcontroller_ptr) { runner.calcontroller_ptr->handle_stage_end("pr"); } } // EQUILIBRIUM STAGE (EQ) if (modeldata.eq_yrs > 0) { BOOST_LOG_NAMED_SCOPE("EQ"); BOOST_LOG_SEV(glg, fatal) << "Equilibrium Initial Year Count: " << modeldata.eq_yrs; if (runner.calcontroller_ptr) { runner.calcontroller_ptr->handle_stage_start(); } runner.cohort.md->set_envmodule(true); runner.cohort.md->set_dvmmodule(true); runner.cohort.md->set_bgcmodule(true); runner.cohort.md->set_dslmodule(true); runner.cohort.md->set_nfeed(true); runner.cohort.md->set_avlnflg(true); runner.cohort.md->set_baseline(true); runner.cohort.md->set_dsbmodule(true); // This variable ensures that OpenMP threads do not modify // the shared modeldata.eq_yrs value. int fri_adj_eq_yrs = modeldata.eq_yrs;//EQ years adjusted by FRI if necessary if (runner.cohort.md->get_dsbmodule()) { // The transition to SP must occur at the completion of a // fire cycle (i.e. a year or two prior to the next fire). // To ensure this, re-set modeldata's EQ year count to an // even multiple of the FRI minus 2 (to be safe) if (modeldata.eq_yrs < runner.cohort.fire.getFRI()) { BOOST_LOG_SEV(glg, err) << "The model will not run enough years to complete a disturbance cycle!"; } else { int fri = runner.cohort.fire.getFRI(); int EQ_fire_cycles = modeldata.eq_yrs / fri; if (modeldata.eq_yrs%fri != 0) { // Extend the run to the end of the current fire cycle fri_adj_eq_yrs = fri * (EQ_fire_cycles + 1) - 2; } else{ fri_adj_eq_yrs -= 2; } } } // Run model BOOST_LOG_SEV(glg, fatal) << "Running Equilibrium, " << fri_adj_eq_yrs << " years."; runner.run_years(0, fri_adj_eq_yrs, "eq-run"); // Update restartdata structure from the running state runner.cohort.set_restartdata_from_state(); runner.cohort.restartdata.verify_logical_values(); BOOST_LOG_SEV(glg, debug) << "RestartData post EQ"; runner.cohort.restartdata.restartdata_to_log(); BOOST_LOG_SEV(glg, note) << "Writing RestartData to: " << eq_restart_fname; runner.cohort.restartdata.write_pixel_to_ncfile(eq_restart_fname, rowidx, colidx); if (modeldata.eq_yrs < runner.cohort.fire.getFRI()) { BOOST_LOG_SEV(glg, err) << "The model did not run enough years to complete a disturbance cycle!"; } if (runner.calcontroller_ptr) { runner.calcontroller_ptr->handle_stage_end("eq"); } } // SPINUP STAGE (SP) if (modeldata.sp_yrs > 0) { BOOST_LOG_NAMED_SCOPE("SP"); BOOST_LOG_SEV(glg, fatal) << "Running Spinup, " << modeldata.sp_yrs << " years."; if (runner.calcontroller_ptr) { runner.calcontroller_ptr->handle_stage_start(); } runner.cohort.climate.monthlycontainers2log(); BOOST_LOG_SEV(glg, debug) << "Loading RestartData from: " << eq_restart_fname; runner.cohort.restartdata.update_from_ncfile(eq_restart_fname, rowidx, colidx); // FIX: if restart file has -9999, then soil temps can end up // impossibly low should check for valid values prior to actual use // Maybe a diffcult to maintain in the future // when/if more variables are added? runner.cohort.restartdata.verify_logical_values(); BOOST_LOG_SEV(glg, debug) << "RestartData pre SP"; runner.cohort.restartdata.restartdata_to_log(); // Copy values from the updated restart data to cohort and cd runner.cohort.set_state_from_restartdata(); // Run model runner.run_years(0, modeldata.sp_yrs, "sp-run"); // Update restartdata structure from the running state runner.cohort.set_restartdata_from_state(); BOOST_LOG_SEV(glg, debug) << "RestartData post SP"; runner.cohort.restartdata.restartdata_to_log(); BOOST_LOG_SEV(glg, note) << "Writing RestartData out to: " << sp_restart_fname; runner.cohort.restartdata.write_pixel_to_ncfile(sp_restart_fname, rowidx, colidx); if (runner.calcontroller_ptr) { runner.calcontroller_ptr->handle_stage_end("sp"); } } // TRANSIENT STAGE (TR) if (modeldata.tr_yrs > 0) { BOOST_LOG_NAMED_SCOPE("TR"); BOOST_LOG_SEV(glg, fatal) << "Running Transient, " << modeldata.tr_yrs << " years"; if (runner.calcontroller_ptr) { runner.calcontroller_ptr->handle_stage_start(); } // update the cohort's restart data object BOOST_LOG_SEV(glg, debug) << "Loading RestartData from: " << sp_restart_fname; runner.cohort.restartdata.update_from_ncfile(sp_restart_fname, rowidx, colidx); runner.cohort.restartdata.verify_logical_values(); BOOST_LOG_SEV(glg, debug) << "RestartData pre TR"; runner.cohort.restartdata.restartdata_to_log(); // Copy values from the updated restart data to cohort and cd runner.cohort.set_state_from_restartdata(); BOOST_LOG_SEV(glg,err) << "MAKE SURE YOUR FIRE INPUTS ARE SETUP CORRECTLY!"; // Run model runner.run_years(0, modeldata.tr_yrs, "tr-run"); // Update restartdata structure from the running state runner.cohort.set_restartdata_from_state(); BOOST_LOG_SEV(glg, debug) << "RestartData post TR"; runner.cohort.restartdata.restartdata_to_log(); BOOST_LOG_SEV(glg, note) << "Writing RestartData out to: " << tr_restart_fname; runner.cohort.restartdata.write_pixel_to_ncfile(tr_restart_fname, rowidx, colidx); if (runner.calcontroller_ptr) { runner.calcontroller_ptr->handle_stage_end("tr"); } } // SCENARIO STAGE (SC) if (modeldata.sc_yrs > 0) { BOOST_LOG_NAMED_SCOPE("SC"); BOOST_LOG_SEV(glg, fatal) << "Running Scenario, " << modeldata.sc_yrs << " years."; if (runner.calcontroller_ptr) { runner.calcontroller_ptr->handle_stage_start(); } // update the cohort's restart data object BOOST_LOG_SEV(glg, debug) << "Loading RestartData from: " << tr_restart_fname; runner.cohort.restartdata.update_from_ncfile(tr_restart_fname, rowidx, colidx); BOOST_LOG_SEV(glg, debug) << "RestartData pre SC"; runner.cohort.restartdata.restartdata_to_log(); // Copy values from the updated restart data to cohort and cd runner.cohort.set_state_from_restartdata(); // Loading projected data instead of historic. FIX? runner.cohort.load_proj_climate(modeldata.proj_climate_file); BOOST_LOG_SEV(glg,err) << "MAKE SURE YOUR FIRE INPUTS ARE SETUP CORRECTLY!"; // Run model runner.run_years(0, modeldata.sc_yrs, "sc-run"); // Update restartdata structure from the running state runner.cohort.set_restartdata_from_state(); BOOST_LOG_SEV(glg, debug) << "RestartData post SC"; runner.cohort.restartdata.restartdata_to_log(); BOOST_LOG_SEV(glg, note) << "Writing RestartData out to: " << sc_restart_fname; runner.cohort.restartdata.write_pixel_to_ncfile(sc_restart_fname, rowidx, colidx); if (runner.calcontroller_ptr) { runner.calcontroller_ptr->handle_stage_end("sc"); } } // NOTE: Could have an option to set some time constants based on // some sizes/dimensions of the input driving data... /** eq - create the climate from the average of the first X years of the driving climate data. SIZE: 12 months, 1 year - set to default module settings to: ?? - run_years( 0 <= iy < MAX_EQ_YEAR ) - act on calibration directives - sp - create the climate from the first X years of the driving climate dataset. SIZE: 12 months, X years - set to default module settings: ?? - run_years( SP_BEG <= iy <= SP_END ) tr - create climate by loading the driving climate data (historic) SIZE: 12 months, length of driving dataset? OR number from inc/timeconst.h - set to default module settings: ?? - run_years( TR_BEG <= iy <= TR_END ) */ } // end advance_model /** Creates (overwrites) an empty run_status file. */ void create_empty_run_status_file(const std::string& fname, const int ysize, const int xsize) { BOOST_LOG_SEV(glg, debug) << "Creating new file: "<<fname<<" with 'NC_CLOBBER'"; int ncid; #ifdef WITHMPI int id = MPI::COMM_WORLD.Get_rank(); int ntasks = MPI::COMM_WORLD.Get_size(); // path c mode mpi comm obj mpi info netcdfid temutil::nc( nc_create_par(fname.c_str(), NC_CLOBBER|NC_NETCDF4|NC_MPIIO, MPI_COMM_WORLD, MPI_INFO_NULL, &ncid) ); std::cout << "(MPI " << id << "/" << ntasks << ") Creating PARALLEL run_status file! \n"; #else BOOST_LOG_SEV(glg, debug) << "Opening new file with 'NC_CLOBBER'"; temutil::nc( nc_create(fname.c_str(), NC_CLOBBER, &ncid) ); #endif // Define handles for dimensions int yD; int xD; BOOST_LOG_SEV(glg, debug) << "Creating dimensions..."; temutil::nc( nc_def_dim(ncid, "Y", ysize, &yD) ); temutil::nc( nc_def_dim(ncid, "X", xsize, &xD) ); // Setup arrays holding dimids for different "types" of variables // --> will re-arrange these later to define variables with different dims int vartype2D_dimids[2]; vartype2D_dimids[0] = yD; vartype2D_dimids[1] = xD; // Setup 2D vars, integer // Define handle for variable(s) int run_statusV; // Create variable(s) in nc file temutil::nc( nc_def_var(ncid, "run_status", NC_INT, 2, vartype2D_dimids, &run_statusV) ); // SET FILL VALUE? /* Create Attributes?? */ /* End Define Mode (not scrictly necessary for netcdf 4) */ BOOST_LOG_SEV(glg, debug) << "Leaving 'define mode'..."; temutil::nc( nc_enddef(ncid) ); /* Close file. */ BOOST_LOG_SEV(glg, debug) << "Closing new file..."; temutil::nc( nc_close(ncid) ); } void write_status(const std::string fname, int row, int col, int statusCode) { int ncid; int statusV; int NDIMS = 2; size_t start[NDIMS], count[NDIMS]; // Set point to write start[0] = row; start[1] = col; #ifdef WITHMPI // These are for logging identification only. int id = MPI::COMM_WORLD.Get_rank(); int ntasks = MPI::COMM_WORLD.Get_size(); // Open dataset temutil::nc( nc_open_par(fname.c_str(), NC_WRITE|NC_MPIIO, MPI_COMM_WORLD, MPI_INFO_NULL, &ncid) ); temutil::nc( nc_inq_varid(ncid, "run_status", &statusV) ); temutil::nc( nc_var_par_access(ncid, statusV, NC_INDEPENDENT) ); // Write data std::cout << "(MPI " << id << "/" << ntasks << ") WRITING FOR PIXEL (row, col): " << row << ", " << col << "\n"; temutil::nc( nc_put_var1_int(ncid, statusV, start, &statusCode) ); /* Close the netcdf file. */ std::cout << "(MPI " << id << "/" << ntasks << ") Closing PARALLEL file." << row << ", " << col << "\n"; temutil::nc( nc_close(ncid) ); #else // Open dataset temutil::nc( nc_open(fname.c_str(), NC_WRITE, &ncid) ); temutil::nc( nc_inq_varid(ncid, "run_status", &statusV) ); // Write data BOOST_LOG_SEV(glg, note) << "WRITING FOR OUTPUT STATUS FOR (row, col): " << row << ", " << col << "\n"; temutil::nc( nc_put_var1_int(ncid, statusV, start, &statusCode) ); /* Close the netcdf file. */ temutil::nc( nc_close(ncid) ); #endif }
35.098779
148
0.642423
[ "object", "vector", "model", "transform" ]
381d6037dc2d5510f55bd39af07e67d699225993
3,003
cc
C++
examples/parallelTest/src/ParallelPlugin.cc
janpipek/g4application
6b063636474a7a8f212023ada7fbb60bd4439606
[ "MIT" ]
1
2018-04-14T08:53:04.000Z
2018-04-14T08:53:04.000Z
examples/parallelTest/src/ParallelPlugin.cc
janpipek/g4application
6b063636474a7a8f212023ada7fbb60bd4439606
[ "MIT" ]
23
2015-01-13T10:57:36.000Z
2015-11-25T17:49:27.000Z
examples/parallelTest/src/ParallelPlugin.cc
janpipek/g4application
6b063636474a7a8f212023ada7fbb60bd4439606
[ "MIT" ]
null
null
null
#include "ParallelPlugin.hh" #include <Component.hh> // g4App #include <G4VUserParallelWorld.hh> #include <G4NistManager.hh> #include <G4Material.hh> #include <G4Box.hh> #include <G4SystemOfUnits.hh> #include <G4PVPlacement.hh> #include <G4VisAttributes.hh> MAKE_G4_PLUGIN( ParallelPlugin ) using namespace g4; using namespace std; class ParWorld1 : public G4VUserParallelWorld { public: ParWorld1() : G4VUserParallelWorld("parworld1") { } virtual void Construct() { auto nist = G4NistManager::Instance(); auto water = nist->FindOrBuildMaterial("G4_WATER"); G4VPhysicalVolume* ghostWorld = GetWorld(); G4LogicalVolume* worldLogical = ghostWorld->GetLogicalVolume(); G4VSolid* paraBox = new G4Box("paraBox",5.0*cm,5.0*cm,5.0*cm); G4LogicalVolume* paraBoxLogical = new G4LogicalVolume(paraBox,water,"paraBox"); G4VisAttributes* blue = new G4VisAttributes(G4Colour(0. ,0. ,1., 1.0)); blue->SetVisibility(true); blue->SetForceSolid(true); paraBoxLogical->SetVisAttributes(blue); new G4PVPlacement(0,G4ThreeVector(-10.0*cm,0.,0.),paraBoxLogical,"paraBox",worldLogical,false,0); } }; class Parallel1 : public Component { public: virtual std::vector<G4VUserParallelWorld *> CreateParallelWorlds() { return { new ParWorld1() }; } }; class ParWorld2 : public G4VUserParallelWorld { public: ParWorld2() : G4VUserParallelWorld("parworld2") { } virtual void Construct() { G4Element* carbon = G4NistManager::Instance()->FindOrBuildElement("C"); G4Element* hydrogen = G4NistManager::Instance()->FindOrBuildElement("H"); G4Element* oxygen = G4NistManager::Instance()->FindOrBuildElement("O"); auto polyester = new G4Material("polyester", 1.35 * g/cm3, 3); polyester->AddElement(hydrogen, 4.2 * perCent); polyester->AddElement(carbon, 62.5 * perCent); polyester->AddElement(oxygen, 33.3 * perCent); G4VPhysicalVolume* ghostWorld = GetWorld(); G4LogicalVolume* worldLogical = ghostWorld->GetLogicalVolume(); G4VSolid* paraBox = new G4Box("paraBox", 5.0*cm, 5.0*cm, 5.0*cm); G4LogicalVolume* paraBoxLogical = new G4LogicalVolume(paraBox, polyester, "paraBox"); G4VisAttributes* red = new G4VisAttributes(G4Colour(1. ,0. ,0., 1.0)); red->SetVisibility(true); red->SetForceSolid(true); paraBoxLogical->SetVisAttributes(red); new G4PVPlacement(0,G4ThreeVector(10.0*cm,0.,0.), paraBoxLogical, "paraBox", worldLogical, false, 0); } }; class Parallel2 : public Component { public: virtual std::vector<G4VUserParallelWorld *> CreateParallelWorlds() { return { new ParWorld2() }; } }; Component* ParallelPlugin::GetComponent(const string& name) { if (name == "parallel1") { return new Parallel1(); } else if (name == "parallel2") { return new Parallel2(); } return nullptr; }
29.15534
109
0.666334
[ "vector" ]
382e7d1308d525a689ebcb9aa38dec1c67c39f08
1,772
cpp
C++
libcxx/test/libcxx/ranges/range.adaptors/range.copy.wrap/properties.compile.pass.cpp
lxbndr/llvm-project
2b715b15f5f4c6dd60f05d1b62f9c404e8b56e34
[ "Apache-2.0" ]
null
null
null
libcxx/test/libcxx/ranges/range.adaptors/range.copy.wrap/properties.compile.pass.cpp
lxbndr/llvm-project
2b715b15f5f4c6dd60f05d1b62f9c404e8b56e34
[ "Apache-2.0" ]
null
null
null
libcxx/test/libcxx/ranges/range.adaptors/range.copy.wrap/properties.compile.pass.cpp
lxbndr/llvm-project
2b715b15f5f4c6dd60f05d1b62f9c404e8b56e34
[ "Apache-2.0" ]
null
null
null
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++03, c++11, c++14, c++17 // UNSUPPORTED: libcpp-has-no-incomplete-ranges // Test various properties of <copyable-box> #include <ranges> #include <optional> #include "types.h" template <class T> constexpr bool valid_copyable_box = requires { typename std::ranges::__copyable_box<T>; }; struct NotCopyConstructible { NotCopyConstructible() = default; NotCopyConstructible(NotCopyConstructible&&) = default; NotCopyConstructible(NotCopyConstructible const&) = delete; NotCopyConstructible& operator=(NotCopyConstructible&&) = default; NotCopyConstructible& operator=(NotCopyConstructible const&) = default; }; static_assert(!valid_copyable_box<void>); // not an object type static_assert(!valid_copyable_box<int&>); // not an object type static_assert(!valid_copyable_box<NotCopyConstructible>); // primary template static_assert(sizeof(std::ranges::__copyable_box<CopyConstructible>) == sizeof(std::optional<CopyConstructible>)); // optimization #1 static_assert(sizeof(std::ranges::__copyable_box<Copyable>) == sizeof(Copyable)); static_assert(alignof(std::ranges::__copyable_box<Copyable>) == alignof(Copyable)); // optimization #2 static_assert(sizeof(std::ranges::__copyable_box<NothrowCopyConstructible>) == sizeof(NothrowCopyConstructible)); static_assert(alignof(std::ranges::__copyable_box<NothrowCopyConstructible>) == alignof(NothrowCopyConstructible));
37.702128
115
0.704853
[ "object" ]
382ee46b1eea1ada9a3d79b2929a1095139e5846
665
cpp
C++
model-view/qt-item-model-class/my-abstract-list-model/MtAbstractListModel/fetchdatadynamically.cpp
gusenov/examples-qt
083a51feedf6cefe82b6de79d701da23d1da2a2f
[ "MIT" ]
2
2020-09-01T18:37:30.000Z
2021-11-28T16:25:04.000Z
model-view/qt-item-model-class/my-abstract-list-model/MtAbstractListModel/fetchdatadynamically.cpp
gusenov/examples-qt
083a51feedf6cefe82b6de79d701da23d1da2a2f
[ "MIT" ]
null
null
null
model-view/qt-item-model-class/my-abstract-list-model/MtAbstractListModel/fetchdatadynamically.cpp
gusenov/examples-qt
083a51feedf6cefe82b6de79d701da23d1da2a2f
[ "MIT" ]
null
null
null
#include "fetchdatadynamically.h" FetchDataDynamically::FetchDataDynamically(QObject *parent) : QAbstractListModel(parent) { } int FetchDataDynamically::rowCount(const QModelIndex &parent) const { // For list models only the root node (an invalid parent) should return the list's size. For all // other (valid) parents, rowCount() should return 0 so that it does not become a tree model. if (parent.isValid()) return 0; // FIXME: Implement me! } QVariant FetchDataDynamically::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); // FIXME: Implement me! return QVariant(); }
25.576923
100
0.700752
[ "model" ]
383212ff8036d613b5b8bdce83b6cbf264158ba8
10,670
cpp
C++
dev/Gems/EMotionFX/Code/Tests/AutoSkeletonLODTests.cpp
BadDevCode/lumberyard
3d688932f919dbf5821f0cb8a210ce24abe39e9e
[ "AML" ]
1,738
2017-09-21T10:59:12.000Z
2022-03-31T21:05:46.000Z
dev/Gems/EMotionFX/Code/Tests/AutoSkeletonLODTests.cpp
olivier-be/lumberyard
3d688932f919dbf5821f0cb8a210ce24abe39e9e
[ "AML" ]
427
2017-09-29T22:54:36.000Z
2022-02-15T19:26:50.000Z
dev/Gems/EMotionFX/Code/Tests/AutoSkeletonLODTests.cpp
olivier-be/lumberyard
3d688932f919dbf5821f0cb8a210ce24abe39e9e
[ "AML" ]
671
2017-09-21T08:04:01.000Z
2022-03-29T14:30:07.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include <Tests/SystemComponentFixture.h> #include <Tests/TestAssetCode/SimpleActors.h> #include <Tests/TestAssetCode/ActorFactory.h> #include <EMotionFX/Source/Actor.h> #include <EMotionFX/Source/ActorInstance.h> #include <EMotionFX/Source/Node.h> #include <EMotionFX/Source/Mesh.h> #include <EMotionFX/Source/SubMesh.h> #include <EMotionFX/Source/SkinningInfoVertexAttributeLayer.h> #include <EMotionFX/Source/Skeleton.h> #include <vector> #include <string> namespace EMotionFX { struct AutoLODTestParams { std::vector<AZ::u32> m_skinningJointIndices; // The joint indices used while skinning. std::vector<std::string> m_criticalJoints; // The list of critical joints std::vector<AZ::u32> m_expectedEnabledJointIndices; // The expected enabled joints. }; class AutoSkeletonLODActor : public SimpleJointChainActor { // This creates an Actor with following hierarchy. // The numbers are the joint indices. // // 5 // / // / // 0-----1-----2-----3-----4 // \ // \ // 6 // // 7 (a node with skinned mesh) // // The mesh is on node 7, which is also a root node, just like joint number 0. // We (fake) skin the first six joints to the mesh of node 7. // Our test will actually skin to only a selection of these first seven joints. // We then test which joints get disabled and which not. public: explicit AutoSkeletonLODActor(AZ::u32 numSubMeshJoints) : SimpleJointChainActor(5) { GetSkeleton()->GetNode(0)->SetName("Joint0"); GetSkeleton()->GetNode(1)->SetName("Joint1"); GetSkeleton()->GetNode(2)->SetName("Joint2"); GetSkeleton()->GetNode(3)->SetName("Joint3"); GetSkeleton()->GetNode(4)->SetName("Joint4"); AddNode(5, "ChildA", 4); AddNode(6, "ChildB", 4); // Create a node that has a mesh. // Please note that we don't go the full way here, by also filling vertex position, normal and skinning data. // Every submesh stores a list of joints used to skin that submesh. We simply fill that list, as the auto-skeletal LOD algorithm looks at this list and doesn't // look at the actual per vertex skinning information. // This way we simplify the test code slightly, while achieving the same correct test results. Node* meshNode = AddNode(7, "MeshNode"); Mesh* mesh = Mesh::Create(); SubMesh* subMesh = SubMesh::Create(mesh, 0, 0, 0, 8, 24, 12, 0, numSubMeshJoints); // The numbers are just some dummy values for a fake mesh. mesh->AddSubMesh(subMesh); if (numSubMeshJoints) { SkinningInfoVertexAttributeLayer* skinningLayer = SkinningInfoVertexAttributeLayer::Create(8); // Create a fake skinning layer. mesh->AddSharedVertexAttributeLayer(skinningLayer); } SetMesh(0, meshNode->GetNodeIndex(), mesh); } }; class AutoSkeletonLODFixture : public SystemComponentFixture , public ::testing::WithParamInterface<AutoLODTestParams> { public: void TearDown() override { if (m_actorInstance) { m_actorInstance->Destroy(); m_actorInstance = nullptr; } SystemComponentFixture::TearDown(); } SubMesh* SetupActor(AZ::u32 numSubMeshJoints) { m_actor = ActorFactory::CreateAndInit<AutoSkeletonLODActor>(numSubMeshJoints); return m_actor->GetMesh(0, m_actor->GetSkeleton()->FindNodeByName("MeshNode")->GetNodeIndex())->GetSubMesh(0); } public: AZStd::unique_ptr<Actor> m_actor = nullptr; ActorInstance* m_actorInstance = nullptr; }; TEST_F(AutoSkeletonLODFixture, VerifyHierarchy) { SetupActor(0); m_actorInstance = ActorInstance::Create(m_actor.get()); ASSERT_NE(m_actor, nullptr); ASSERT_NE(m_actorInstance, nullptr); // Verify integrity of the hierarchy. ASSERT_EQ(m_actor->GetNumNodes(), 8); for (AZ::u32 i = 0; i < 4; ++i) { const Node* node = m_actor->GetSkeleton()->GetNode(i); const AZStd::string jointName = AZStd::string::format("Joint%d", i); ASSERT_EQ(node->GetNumChildNodes(), 1); ASSERT_STREQ(node->GetName(), jointName.c_str()); } const Skeleton* skeleton = m_actor->GetSkeleton(); ASSERT_EQ(skeleton->GetNode(4)->GetNumChildNodes(), 2); ASSERT_EQ(skeleton->GetNode(5)->GetParentNode(), skeleton->GetNode(4)); ASSERT_EQ(skeleton->GetNode(5)->GetNumChildNodes(), 0); ASSERT_STREQ(skeleton->GetNode(5)->GetName(), "ChildA"); ASSERT_EQ(skeleton->GetNode(6)->GetParentNode(), skeleton->GetNode(4)); ASSERT_EQ(skeleton->GetNode(6)->GetNumChildNodes(), 0); ASSERT_STREQ(skeleton->GetNode(6)->GetName(), "ChildB"); ASSERT_EQ(skeleton->GetNode(7)->GetNumChildNodes(), 0); ASSERT_STREQ(skeleton->GetNode(7)->GetName(), "MeshNode"); } TEST_P(AutoSkeletonLODFixture, MainTest) { // Create a submesh that contains all joints, so act like we are skinned to all joints. const AZ::u32 numSkinJoints = static_cast<AZ::u32>(GetParam().m_skinningJointIndices.size()); SubMesh* subMesh = SetupActor(numSkinJoints); for (AZ::u32 i = 0; i < numSkinJoints; ++i) { subMesh->SetBone(i, GetParam().m_skinningJointIndices[i]); } // Generate our skeletal LODs. AZStd::vector<AZStd::string> criticalJoints; for (const std::string& jointName : GetParam().m_criticalJoints) { criticalJoints.emplace_back(jointName.c_str()); } m_actor->AutoSetupSkeletalLODsBasedOnSkinningData(criticalJoints); // Verify the skeletal LOD flags. m_actorInstance = ActorInstance::Create(m_actor.get()); const Skeleton* skeleton = m_actor->GetSkeleton(); // All nodes should be enabled as we use all joints. // And the mesh is also automatically enabled. for (AZ::u32 i = 0; i < 8; ++i) // 8 is the total number of joints plus one mesh node { const bool shouldBeEnabled = std::find(GetParam().m_expectedEnabledJointIndices.begin(), GetParam().m_expectedEnabledJointIndices.end(), i) != GetParam().m_expectedEnabledJointIndices.end(); EXPECT_EQ(skeleton->GetNode(i)->GetSkeletalLODStatus(0), shouldBeEnabled); } // Make sure the actor instance's number of enabled joints is the same. EXPECT_EQ(m_actorInstance->GetNumEnabledNodes(), static_cast<AZ::u32>(GetParam().m_expectedEnabledJointIndices.size())); // Also make sure the enabled number of nodes contents reflects the expectation. for (AZ::u32 i = 0; i < m_actorInstance->GetNumEnabledNodes(); ++i) { const AZ::u32 enabledJointIndex = static_cast<AZ::u32>(m_actorInstance->GetEnabledNode(i)); const bool enabledJointFound = std::find(GetParam().m_expectedEnabledJointIndices.begin(), GetParam().m_expectedEnabledJointIndices.end(), enabledJointIndex) != GetParam().m_expectedEnabledJointIndices.end(); EXPECT_TRUE(enabledJointFound); } } // Our test parameters. const std::vector<AutoLODTestParams> testParams { { { 0, 1, 2, 3, 4, 5, 6 }, // All joints used in skinning. Number 7 excluded as that is the mesh. { }, // Critical joint list. { 0, 1, 2, 3, 4, 5, 6, 7 } // We expect all nodes to be enabled. }, { { }, // No skinning joints used, so just an actor with a static mesh. { }, // Critical joint list. { 0, 1, 2, 3, 4, 5, 6, 7 } // We expect everything to remain enabled. }, { { 0, 1, 2, 3 }, // Skin only to the first 4 joints. { }, // Critical joint list. { 0, 1, 2, 3, 7 } // Expected enabled joints. }, { { 0 }, // Skin only to the first joint. { }, // Critical joint list. { 0, 7 } // Expected enabled joints. }, { { 0, 1 }, // Skin only to the first two joints. { }, // Critical joint list. { 0, 1, 7 } // Expected enabled joints. }, { { 0, 6 }, // Skin only to the first and a leaf joint. { }, // Critical joint list. { 0, 1, 2, 3, 4, 6, 7 } // Expected enabled joints. }, { { 4, 5 }, // Skin only to two joints down the hierarchy. { }, // Critical joint list. { 0, 1, 2, 3, 4, 5, 7 } // We expect all joints up to the root, and the mesh. }, { { 6 }, // Skin to only one leaf joint. { }, // Critical joint list. { 0, 1, 2, 3, 4, 6, 7 } // We expect all joints up to the root, and the mesh. }, { { 0, 1, 2 }, // Skin to only one leaf joint. { "ChildA" }, // Critical joint list. { 0, 1, 2, 3, 4, 5, 7 } // We expect all joints up to the root, and the mesh. }, { { 0 }, // One joint. { "ChildA", "ChildB" }, // Critical joint list. { 0, 1, 2, 3, 4, 5, 6, 7 } // We expect all joints up to the root, and the mesh. }, { { }, // No joints. { "ChildA", "ChildB" }, // Critical joint list. { 0, 1, 2, 3, 4, 5, 6, 7 } // We expect all joints up to the root, and the mesh. } }; INSTANTIATE_TEST_CASE_P(AutoSkeletonLOD_Tests, AutoSkeletonLODFixture, ::testing::ValuesIn(testParams) ); } // namespace EMotionFX
42.007874
220
0.584724
[ "mesh", "vector" ]
383dd8621b5aa39b844c53f61b34a5c1875a9693
8,659
cc
C++
contrib/trainer/libdg_tf/tensor_to_image.cc
Chicoryn/dream-go
6a4b71d7e1fcc28110ba859c0a2b59c10041c083
[ "Apache-2.0" ]
46
2017-12-08T01:40:08.000Z
2022-02-07T12:56:14.000Z
contrib/trainer/libdg_tf/tensor_to_image.cc
Chicoryn/dream-go
6a4b71d7e1fcc28110ba859c0a2b59c10041c083
[ "Apache-2.0" ]
56
2017-12-28T04:00:31.000Z
2022-03-20T12:39:39.000Z
contrib/trainer/libdg_tf/tensor_to_image.cc
Chicoryn/dream-go
6a4b71d7e1fcc28110ba859c0a2b59c10041c083
[ "Apache-2.0" ]
8
2018-02-01T13:12:32.000Z
2020-05-11T04:12:25.000Z
// Copyright 2020 Karl Sundequist Blomdahl <karl.sundequist.blomdahl@gmail.com> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/shape_inference.h" #include "tensorflow/core/lib/random/random_distributions.h" #include "tensorflow/core/util/guarded_philox_random.h" using namespace tensorflow; using shape_inference::DimensionHandle; using shape_inference::InferenceContext; using Eigen::half; #define IMAGE_SHAPE {1, 115, 115, 3} #define IMAGE_STRIDE 115 #define SPRITE_WIDTH 6 #define SPRITE_HEIGHT 6 /* * ``` * * xxx * x x * x x * x x * xxx * ``` */ static const float WHITE_STONE[] = { // row 0 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, // row 1 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, // row 2 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, // row 3 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, // row 4 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, // row 5 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, }; /* * ``` * * xxx * xxxxx * xxxxx * xxxxx * xxx * ``` */ static const float BLACK_STONE[] = { // row 0 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, // row 1 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, // row 2 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, // row 3 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, // row 4 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, // row 5 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, }; class TensorToHeatImageOp : public OpKernel { public: explicit TensorToHeatImageOp(OpKernelConstruction* context) : OpKernel(context) { // pass } void Compute(OpKernelContext* context) override { const Tensor* player_tensor; const Tensor* opponent_tensor; const Tensor* heat_tensor; OP_REQUIRES_OK(context, context->input("player", &player_tensor)); OP_REQUIRES( context, player_tensor->shape() == TensorShape({19, 19}), errors::InvalidArgument( "Input `player` should be shape [19, 19] but received shape: ", player_tensor->shape().DebugString() ) ); OP_REQUIRES_OK(context, context->input("opponent", &opponent_tensor)); OP_REQUIRES( context, opponent_tensor->shape() == TensorShape({19, 19}), errors::InvalidArgument( "Input `opponent` should be shape [19, 19] but received shape: ", opponent_tensor->shape().DebugString() ) ); OP_REQUIRES_OK(context, context->input("heat", &heat_tensor)); OP_REQUIRES( context, heat_tensor->shape() == TensorShape({19, 19}), errors::InvalidArgument( "Input `heat` should be shape [19, 19] but received shape: ", heat_tensor->shape().DebugString() ) ); // allocate the output tensor Tensor* image_tensor; OP_REQUIRES_OK( context, context->allocate_output( 0, TensorShape(IMAGE_SHAPE), &image_tensor ) ); // fill in the current board state auto player = player_tensor->flat<half>(); auto opponent = opponent_tensor->flat<half>(); auto heat = heat_tensor->flat<float>(); auto image = image_tensor->flat<float>(); float max_heat = -1.0; float min_heat = 1.0; for (auto i = 0; i < image.size(); ++i) { image(i) = 1.0; } for (auto i = 0; i < 361; ++i) { if (heat(i) > max_heat) { max_heat = heat(i); } if (heat(i) < min_heat) { min_heat = heat(i); } } for (auto y = 0; y < 19; ++y) { for (auto x = 0; x < 19; ++x) { const auto i = 19 * y + x; if (static_cast<float>(player(i)) > 1e-4f) { this->CopySpriteTo(image, SPRITE_WIDTH * x, SPRITE_HEIGHT * y, BLACK_STONE); } else if (static_cast<float>(opponent(i)) > 1e-4f) { this->CopySpriteTo(image, SPRITE_WIDTH * x, SPRITE_HEIGHT * y, WHITE_STONE); } this->Heat(image, SPRITE_WIDTH * x, SPRITE_HEIGHT * y, heat(i), min_heat, max_heat); } } } private: void CopySpriteTo( Eigen::TensorMap<Eigen::Tensor<float, 1, 1, long int>, 16, Eigen::MakePointer>& dst, int x, int y, const float* sprite ) { for (auto dy = 0; dy < SPRITE_HEIGHT; ++dy) { for (auto dx = 0; dx < SPRITE_WIDTH; ++dx) { for (auto j = 0; j < 3; ++j) { auto dst_index = 3 * (IMAGE_STRIDE * (y + dy) + (x + dx)) + j; auto src_index = 3 * (SPRITE_WIDTH * dy + dx) + j; dst(dst_index) = sprite[src_index]; } } } } void Heat( Eigen::TensorMap<Eigen::Tensor<float, 1, 1, long int>, 16, Eigen::MakePointer>& dst, int x, int y, float heat, float min_heat, float max_heat ) { for (auto dy = 1; dy < SPRITE_HEIGHT; ++dy) { for (auto dx = 1; dx < SPRITE_WIDTH; ++dx) { auto r_index = 3 * (IMAGE_STRIDE * (y + dy) + (x + dx)) + 0; auto g_index = 3 * (IMAGE_STRIDE * (y + dy) + (x + dx)) + 1; auto b_index = 3 * (IMAGE_STRIDE * (y + dy) + (x + dx)) + 2; if (heat < -3e-3) { const float alpha = 0.9f - 0.7f * heat / min_heat; dst(r_index) = alpha * dst(r_index) + (1.0f - alpha) * 1.0f; dst(g_index) = alpha * dst(g_index) + (1.0f - alpha) * 0.0f; dst(b_index) = alpha * dst(b_index) + (1.0f - alpha) * 0.0f; } else if (heat > 3e-3) { const float alpha = 0.9f - 0.7f * heat / max_heat; dst(r_index) = alpha * dst(r_index) + (1.0f - alpha) * 0.0f; dst(g_index) = alpha * dst(g_index) + (1.0f - alpha) * 1.0f; dst(b_index) = alpha * dst(b_index) + (1.0f - alpha) * 0.0f; } } } } }; REGISTER_OP("TensorToHeatImage") .Input("player: float16") .Input("opponent: float16") .Input("heat: float32") .Output("image: float32") .SetShapeFn([](InferenceContext* c) { c->set_output(0, c->MakeShape(IMAGE_SHAPE)); return Status::OK(); }); REGISTER_KERNEL_BUILDER(Name("TensorToHeatImage").Device(DEVICE_CPU), TensorToHeatImageOp);
28.022654
104
0.46622
[ "shape" ]
38412723e52565450072b5ccaf8f842da919a298
4,431
cpp
C++
Engine/Source/Hect/IO/BinaryDecoder.cpp
colinhect/hect
2ef89be60ba9d450c5b56f5be6cef9803cc1855a
[ "MIT" ]
2
2015-01-17T00:56:34.000Z
2015-12-01T07:02:47.000Z
Engine/Source/Hect/IO/BinaryDecoder.cpp
colinhect/hect
2ef89be60ba9d450c5b56f5be6cef9803cc1855a
[ "MIT" ]
63
2015-01-06T17:42:22.000Z
2017-09-10T00:21:52.000Z
Engine/Source/Hect/IO/BinaryDecoder.cpp
colinhect/hect
2ef89be60ba9d450c5b56f5be6cef9803cc1855a
[ "MIT" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// // This source file is part of Hect. // // Copyright (c) 2016 Colin Hill // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. /////////////////////////////////////////////////////////////////////////////// #include "BinaryDecoder.h" #include "Hect/Core/Exception.h" #include "Hect/IO/MemoryReadStream.h" using namespace hect; BinaryDecoder::BinaryDecoder(ReadStream& stream) : _stream(stream) { } BinaryDecoder::BinaryDecoder(ReadStream& stream, AssetCache& asset_cache) : Decoder(asset_cache), _stream(stream) { } BinaryDecoder::BinaryDecoder(const ByteVector& data) : _owned_stream(new MemoryReadStream(data)), _stream(*_owned_stream) { } bool BinaryDecoder::is_binary_stream() const { return true; } ReadStream& BinaryDecoder::binary_stream() { return _stream; } void BinaryDecoder::begin_array() { increment_index(); uint32_t count; _stream >> count; _value_type_stack.push(ValueType_Array); _count_stack.push(count); _index_stack.push(0); } void BinaryDecoder::end_array() { _index_stack.pop(); _count_stack.pop(); _value_type_stack.pop(); } bool BinaryDecoder::has_more_elements() const { return _index_stack.top() < _count_stack.top(); } void BinaryDecoder::begin_object() { increment_index(); _value_type_stack.push(ValueType_Object); } void BinaryDecoder::end_object() { _value_type_stack.pop(); } bool BinaryDecoder::select_member(const char* name) { (void)name; return true; } std::vector<std::string> BinaryDecoder::member_names() const { throw InvalidOperation("Cannot enumerate member names from a binary data source"); } std::string BinaryDecoder::decode_string() { increment_index(); std::string value; _stream >> value; return value; } int8_t BinaryDecoder::decode_int8() { increment_index(); int8_t value; _stream >> value; return value; } uint8_t BinaryDecoder::decode_uint8() { increment_index(); uint8_t value; _stream >> value; return value; } int16_t BinaryDecoder::decode_int16() { increment_index(); int16_t value; _stream >> value; return value; } uint16_t BinaryDecoder::decode_uint16() { increment_index(); uint16_t value; _stream >> value; return value; } int32_t BinaryDecoder::decode_int32() { increment_index(); int32_t value; _stream >> value; return value; } uint32_t BinaryDecoder::decode_uint32() { increment_index(); uint32_t value; _stream >> value; return value; } int64_t BinaryDecoder::decode_int64() { increment_index(); int64_t value; _stream >> value; return value; } uint64_t BinaryDecoder::decode_uint64() { increment_index(); uint64_t value; _stream >> value; return value; } float BinaryDecoder::decode_float32() { increment_index(); float value; _stream >> value; return value; } double BinaryDecoder::decode_float64() { increment_index(); double value; _stream >> value; return value; } bool BinaryDecoder::decode_bool() { increment_index(); bool value; _stream >> value; return value; } void BinaryDecoder::increment_index() { if (!_value_type_stack.empty() && _value_type_stack.top() == ValueType_Array) { ++_index_stack.top(); } }
20.232877
86
0.678402
[ "vector" ]
38412804d015213fbb99c1885daef8b59850605b
3,203
cpp
C++
plugins/OSPRay_plugin/src/OSPRayQuadMesh.cpp
voei/megamol
569b7b58c1f9bc5405b79549b86f84009329f668
[ "BSD-3-Clause" ]
null
null
null
plugins/OSPRay_plugin/src/OSPRayQuadMesh.cpp
voei/megamol
569b7b58c1f9bc5405b79549b86f84009329f668
[ "BSD-3-Clause" ]
null
null
null
plugins/OSPRay_plugin/src/OSPRayQuadMesh.cpp
voei/megamol
569b7b58c1f9bc5405b79549b86f84009329f668
[ "BSD-3-Clause" ]
null
null
null
/* * OSPRayQuadMesh.cpp * Copyright (C) 2019 by MegaMol Team * Alle Rechte vorbehalten. */ #include "stdafx.h" #include "OSPRayQuadMesh.h" #include "geometry_calls/CallTriMeshData.h" #include "vislib/sys/Log.h" #include "mmcore/BoundingBoxes_2.h" using namespace megamol::ospray; OSPRayQuadMesh::OSPRayQuadMesh(void) : AbstractOSPRayStructure() , getMeshDataSlot("getMeshData", "Connects to the data source") { this->getMeshDataSlot.SetCompatibleCall<mesh::CallMeshDescription>(); this->MakeSlotAvailable(&this->getMeshDataSlot); } bool OSPRayQuadMesh::readData(megamol::core::Call& call) { // fill material container this->processMaterial(); // fill transformation container this->processTransformation(); // read Data, calculate shape parameters, fill data vectors CallOSPRayStructure* os = dynamic_cast<CallOSPRayStructure*>(&call); mesh::CallMesh* cm = this->getMeshDataSlot.CallAs<mesh::CallMesh>(); if (cm != nullptr) { auto meta_data = cm->getMetaData(); this->structureContainer.dataChanged = false; if (os->getTime() > meta_data.m_frame_cnt) { meta_data.m_frame_ID = meta_data.m_frame_cnt - 1; } else { meta_data.m_frame_ID = os->getTime(); } cm->setMetaData(meta_data); if (!(*cm)(1)) return false; if (!(*cm)(0)) return false; meta_data = cm->getMetaData(); if (cm->hasUpdate() || this->time != os->getTime() || this->InterfaceIsDirty()) { this->time = os->getTime(); this->structureContainer.dataChanged = true; this->extendContainer.boundingBox = std::make_shared<megamol::core::BoundingBoxes_2>(meta_data.m_bboxs); this->extendContainer.timeFramesCount = meta_data.m_frame_cnt; this->extendContainer.isValid = true; this->structureContainer.mesh = cm->getData(); } } // Write stuff into the structureContainer this->structureContainer.type = structureTypeEnum::GEOMETRY; this->structureContainer.geometryType = geometryTypeEnum::QUADS; return true; } OSPRayQuadMesh::~OSPRayQuadMesh() { this->Release(); } bool OSPRayQuadMesh::create() { return true; } void OSPRayQuadMesh::release() {} /* ospray::OSPRaySphereGeometry::InterfaceIsDirty() */ bool OSPRayQuadMesh::InterfaceIsDirty() { return false; } bool OSPRayQuadMesh::getExtends(megamol::core::Call& call) { CallOSPRayStructure* os = dynamic_cast<CallOSPRayStructure*>(&call); mesh::CallMesh* cm = this->getMeshDataSlot.CallAs<mesh::CallMesh>(); if (cm != nullptr) { if (!(*cm)(1)) return false; auto meta_data = cm->getMetaData(); if (os->getTime() > meta_data.m_frame_cnt) { meta_data.m_frame_ID = meta_data.m_frame_cnt - 1; } else { meta_data.m_frame_ID = os->getTime(); } cm->setMetaData(meta_data); this->extendContainer.boundingBox = std::make_shared<megamol::core::BoundingBoxes_2>(meta_data.m_bboxs); this->extendContainer.timeFramesCount = meta_data.m_frame_cnt; this->extendContainer.isValid = true; } return true; }
30.216981
116
0.661567
[ "mesh", "geometry", "shape" ]
3846c6cf16084427e1a613080d8b442ba65a7215
18,470
cpp
C++
Code/Framework/AzCore/Tests/Asset/AssetDataStreamTests.cpp
BreakerOfThings/o3de
f4c59f868c726470ec910623facd836047d059c3
[ "Apache-2.0", "MIT" ]
1
2022-03-28T08:06:58.000Z
2022-03-28T08:06:58.000Z
Code/Framework/AzCore/Tests/Asset/AssetDataStreamTests.cpp
BreakerOfThings/o3de
f4c59f868c726470ec910623facd836047d059c3
[ "Apache-2.0", "MIT" ]
null
null
null
Code/Framework/AzCore/Tests/Asset/AssetDataStreamTests.cpp
BreakerOfThings/o3de
f4c59f868c726470ec910623facd836047d059c3
[ "Apache-2.0", "MIT" ]
null
null
null
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <AzCore/Asset/AssetDataStream.h> #include <AzCore/IO/Streamer/FileRequest.h> #include <AzCore/UnitTest/TestTypes.h> #include <AZTestShared/Utils/Utils.h> #include <Tests/Streamer/IStreamerMock.h> class AssetDataStreamTest : public UnitTest::ScopedAllocatorSetupFixture { public: void SetUp() override { using ::testing::_; using ::testing::NiceMock; using ::testing::Return; UnitTest::ScopedAllocatorSetupFixture::SetUp(); AZ::Interface<AZ::IO::IStreamer>::Register(&m_mockStreamer); // Reroute enough mock streamer calls to this class to let us validate the input parameters and mock // out a "functioning" read request. ON_CALL(m_mockStreamer, Read(_,::testing::An<IStreamerTypes::RequestMemoryAllocator&>(),_,_,_,_)) .WillByDefault([this]( AZStd::string_view relativePath, IStreamerTypes::RequestMemoryAllocator& allocator, size_t size, AZStd::chrono::microseconds deadline, IStreamerTypes::Priority priority, size_t offset) { // Save off all the input parameters to the read request so that we can validate that they match expectations. m_allocator = &allocator; m_relativePath = relativePath; m_size = size; m_deadline = deadline; m_priority = priority; m_offset = offset; return nullptr; }); ON_CALL(m_mockStreamer, SetRequestCompleteCallback(_, _)) .WillByDefault([this](FileRequestPtr& request, AZ::IO::IStreamer::OnCompleteCallback callback) -> FileRequestPtr& { // Save off the callback just so that we can call it when the request is "done" m_callback = callback; return request; }); ON_CALL(m_mockStreamer, QueueRequest(_)) .WillByDefault([this](const FileRequestPtr& request) { // As soon as the request is queued to run, consider it "done" and call the callback if (m_callback) { FileRequestHandle handle(request); m_callback(handle); } }); ON_CALL(m_mockStreamer, GetRequestStatus(_)) .WillByDefault([this]([[maybe_unused]] FileRequestHandle request) { // Return whatever request status has been set in this class return m_requestStatus; }); ON_CALL(m_mockStreamer, GetReadRequestResult(_, _, _, _)) .WillByDefault([this]( [[maybe_unused]] FileRequestHandle request, void*& buffer, AZ::u64& numBytesRead, [[maybe_unused]] IStreamerTypes::ClaimMemory claimMemory) { auto result = m_allocator->Allocate(m_size, m_size, AZCORE_GLOBAL_NEW_ALIGNMENT); m_buffer = static_cast<AZ::u8*>(result.m_address); memset(m_buffer, m_expectedBufferChar, m_size); numBytesRead = m_size; buffer = m_buffer; return true; }); } void TearDown() override { AZ::Interface<AZ::IO::IStreamer>::Unregister(&m_mockStreamer); UnitTest::ScopedAllocatorSetupFixture::TearDown(); } protected: ::testing::NiceMock<StreamerMock> m_mockStreamer; AZStd::string_view m_relativePath; size_t m_size{ 0 }; AZStd::chrono::microseconds m_deadline{ 0 }; IStreamerTypes::Priority m_priority{ IStreamerTypes::s_priorityLowest }; size_t m_offset{ 0 }; AZ::u8* m_buffer{ nullptr }; IStreamerTypes::RequestStatus m_requestStatus{ IStreamerTypes::RequestStatus::Completed }; AZ::IO::IStreamer::OnCompleteCallback m_callback{}; IStreamerTypes::RequestMemoryAllocator* m_allocator{ nullptr }; // Define some arbitrary numbers for validating buffer contents static inline constexpr AZ::u8 m_expectedBufferChar{ 0xFE }; static inline constexpr AZ::u8 m_badBufferChar{ 0xFD }; }; TEST_F(AssetDataStreamTest, Init_CreateTrivialInstance_CreationSuccessful) { AZ::Data::AssetDataStream assetDataStream; // AssetDataStream is a read-only stream EXPECT_TRUE(assetDataStream.CanRead()); EXPECT_FALSE(assetDataStream.CanWrite()); // AssetDataStream only supports forward seeking, not arbitrary seeking, so CanSeek() should be false. EXPECT_FALSE(assetDataStream.CanSeek()); } TEST_F(AssetDataStreamTest, Open_OpenAndCopyBuffer_BufferCopied) { // Pick an arbitrary buffer size constexpr int bufferSize = 100; // Create a buffer filled with an expected charater AZStd::vector<AZ::u8> buffer(bufferSize, m_expectedBufferChar); // Create an assetDataStream and *copy* the buffer into it AZ::Data::AssetDataStream assetDataStream; assetDataStream.Open(buffer); // Assign the buffer to a different, unexpected character buffer.assign(bufferSize, m_badBufferChar); // Create a new buffer, fill it with a bad character, and read the data from the assetDataStream into it AZStd::vector<AZ::u8> outBuffer(bufferSize, m_badBufferChar); AZ::IO::SizeType bytesRead = assetDataStream.Read(outBuffer.size(), outBuffer.data()); // Validate that we read the correct number of bytes EXPECT_EQ(bytesRead, outBuffer.size()); // Validate that the data read back does *not* match the invalid data. // This validates that the buffer got copied and not directly used. EXPECT_NE(buffer, outBuffer); // Validate that the data read back *does* match the original valid data. buffer.assign(bufferSize, m_expectedBufferChar); EXPECT_EQ(buffer, outBuffer); assetDataStream.Close(); } TEST_F(AssetDataStreamTest, Open_OpenAndUseBuffer_BufferUsed) { // Pick an arbitrary buffer size constexpr int bufferSize = 100; // Create a buffer filled with an expected charater AZStd::vector<AZ::u8> buffer(bufferSize, m_expectedBufferChar); // Create an assetDataStream and *move* the buffer into it AZ::Data::AssetDataStream assetDataStream; assetDataStream.Open(AZStd::move(buffer)); // The buffer should be moved, so it should no longer contain data. EXPECT_TRUE(buffer.empty()); // Create a new buffer, fill it with a bad character, and read the data from the assetDataStream into it AZStd::vector<AZ::u8> outBuffer(bufferSize, m_badBufferChar); AZ::IO::SizeType bytesRead = assetDataStream.Read(outBuffer.size(), outBuffer.data()); // Validate that we read the correct number of bytes EXPECT_EQ(bytesRead, outBuffer.size()); // Validate that the data read back matches the original valid data. buffer.assign(bufferSize, m_expectedBufferChar); EXPECT_EQ(buffer, outBuffer); assetDataStream.Close(); } TEST_F(AssetDataStreamTest, Open_OpenAndReadFile_FileReadSuccessfully) { // Choose some non-standard input values to pass in to our Open() request. const AZStd::string filePath("path/test"); const size_t fileOffset = 100; const size_t assetSize = 500; const AZStd::chrono::milliseconds deadline(1000); const AZ::IO::IStreamerTypes::Priority priority(AZ::IO::IStreamerTypes::s_priorityHigh); // Keep track of whether or not our callback gets called. bool callbackCalled = false; AZ::IO::IStreamerTypes::RequestStatus callbackStatus; // Create a callback to call on load completion. AZ::Data::AssetDataStream::OnCompleteCallback loadCallback = [&callbackCalled, &callbackStatus](AZ::IO::IStreamerTypes::RequestStatus status) { callbackCalled = true; callbackStatus = status; }; // Create an AssetDataStream, create a file open request, and wait for it to finish. AZ::Data::AssetDataStream assetDataStream; assetDataStream.Open(filePath, fileOffset, assetSize, deadline, priority, loadCallback); assetDataStream.BlockUntilLoadComplete(); // Validate that the AssetDataStream passed our input parameters correctly to the file streamer EXPECT_EQ(filePath, m_relativePath); EXPECT_EQ(assetSize, m_size); EXPECT_EQ(deadline, m_deadline); EXPECT_EQ(priority, m_priority); EXPECT_EQ(fileOffset, m_offset); // Validate that our completion callback got called EXPECT_TRUE(callbackCalled); EXPECT_EQ(callbackStatus, m_requestStatus); // Create a new buffer, fill it with a bad character, and read the data from the assetDataStream into it AZStd::vector<AZ::u8> outBuffer(assetSize, m_badBufferChar); AZ::IO::SizeType bytesRead = assetDataStream.Read(outBuffer.size(), outBuffer.data()); // Validate that we read the correct number of bytes EXPECT_EQ(bytesRead, outBuffer.size()); // Validate that the data read back matches the original valid data. EXPECT_EQ(memcmp(m_buffer, outBuffer.data(), bytesRead), 0); assetDataStream.Close(); } TEST_F(AssetDataStreamTest, IsOpen_OpenAndCloseStream_OnlyTrueWhileOpen) { // Pick an arbitrary buffer size constexpr int bufferSize = 100; // Create a buffer filled with an expected charater AZStd::vector<AZ::u8> buffer(bufferSize, m_expectedBufferChar); AZ::Data::AssetDataStream assetDataStream; EXPECT_FALSE(assetDataStream.IsOpen()); assetDataStream.Open(AZStd::move(buffer)); EXPECT_TRUE(assetDataStream.IsOpen()); assetDataStream.Close(); EXPECT_FALSE(assetDataStream.IsOpen()); } TEST_F(AssetDataStreamTest, IsFullyLoaded_OpenStreamFromBuffer_DataIsFullyLoaded) { // Pick an arbitrary buffer size constexpr int bufferSize = 100; // Create a buffer filled with an expected charater AZStd::vector<AZ::u8> buffer(bufferSize, m_expectedBufferChar); AZ::Data::AssetDataStream assetDataStream; EXPECT_FALSE(assetDataStream.IsFullyLoaded()); EXPECT_EQ(assetDataStream.GetLoadedSize(), 0); EXPECT_EQ(assetDataStream.GetLength(), 0); assetDataStream.Open(AZStd::move(buffer)); EXPECT_TRUE(assetDataStream.IsFullyLoaded()); EXPECT_EQ(assetDataStream.GetLoadedSize(), bufferSize); EXPECT_EQ(assetDataStream.GetLength(), bufferSize); assetDataStream.Close(); EXPECT_FALSE(assetDataStream.IsFullyLoaded()); EXPECT_EQ(assetDataStream.GetLoadedSize(), 0); EXPECT_EQ(assetDataStream.GetLength(), 0); } TEST_F(AssetDataStreamTest, IsFullyLoaded_FileDoesNotReadAllData_DataIsNotFullyLoaded) { // Set up some arbitrary file parameters. const AZStd::string filePath("path/test"); const size_t fileOffset = 0; const size_t assetSize = 500; // Pick a size less than assetSize to represent the amount of data actually loaded const size_t incompleteAssetSize = 200; using ::testing::_; ON_CALL(m_mockStreamer, GetReadRequestResult(_, _, _, _)) .WillByDefault([this]( [[maybe_unused]] FileRequestHandle request, void*& buffer, AZ::u64& numBytesRead, [[maybe_unused]] IStreamerTypes::ClaimMemory claimMemory) { // On the request for the read result, create a size and buffer that's less than the requested amount. m_size = incompleteAssetSize; auto result = m_allocator->Allocate(m_size, m_size, AZCORE_GLOBAL_NEW_ALIGNMENT); m_buffer = static_cast<AZ::u8*>(result.m_address); memset(m_buffer, m_expectedBufferChar, m_size); numBytesRead = m_size; buffer = m_buffer; return true; }); // Create an AssetDataStream, create a file open request, and wait for it to finish. AZ::Data::AssetDataStream assetDataStream; // We expect one error message during the load due to the incomplete file load. AZ_TEST_START_TRACE_SUPPRESSION; assetDataStream.Open(filePath, fileOffset, assetSize); assetDataStream.BlockUntilLoadComplete(); AZ_TEST_STOP_TRACE_SUPPRESSION(1); // Verify that the data reports back the incomplete size for loaded size, and that it is not fully loaded. EXPECT_FALSE(assetDataStream.IsFullyLoaded()); EXPECT_EQ(assetDataStream.GetLoadedSize(), incompleteAssetSize); // GetLength should still report back the expected size instead of the loaded size EXPECT_EQ(assetDataStream.GetLength(), assetSize); assetDataStream.Close(); } TEST_F(AssetDataStreamTest, Write_TryWritingToStream_WritingCausesAsserts) { // Create an arbitrary buffer constexpr int bufferSize = 100; AZStd::vector<AZ::u8> buffer(bufferSize, m_expectedBufferChar); // Create a data stream from the buffer AZ::Data::AssetDataStream assetDataStream; assetDataStream.Open(buffer); // We should get an error when trying to write to the stream. AZ_TEST_START_ASSERTTEST; assetDataStream.Write(bufferSize, buffer.data()); AZ_TEST_STOP_ASSERTTEST(1); assetDataStream.Close(); } TEST_F(AssetDataStreamTest, GetFilename_StreamOpenedWithFile_FileNameMatches) { // Set up some arbitrary file parameters. const AZStd::string filePath("path/test"); const size_t fileOffset = 0; const size_t assetSize = 500; // Create an AssetDataStream, create a file open request, and wait for it to finish. AZ::Data::AssetDataStream assetDataStream; assetDataStream.Open(filePath, fileOffset, assetSize); assetDataStream.BlockUntilLoadComplete(); // Verify that the stream has the expected filename EXPECT_EQ(strcmp(assetDataStream.GetFilename(), filePath.c_str()), 0); assetDataStream.Close(); } TEST_F(AssetDataStreamTest, GetFilename_StreamOpenedWithMemoryBuffer_FileNameIsEmpty) { // Create an arbitrary buffer constexpr int bufferSize = 100; AZStd::vector<AZ::u8> buffer(bufferSize, m_expectedBufferChar); // Create an AssetDataStream from the memory buffer AZ::Data::AssetDataStream assetDataStream; assetDataStream.Open(buffer); // Verify that the stream has no filename EXPECT_EQ(strcmp(assetDataStream.GetFilename(), ""), 0); assetDataStream.Close(); } TEST_F(AssetDataStreamTest, BlockUntilLoadComplete_BlockWhenOpenedWithMemoryBuffer_BlockReturnsSuccessfully) { // Create an arbitrary buffer constexpr int bufferSize = 100; AZStd::vector<AZ::u8> buffer(bufferSize, m_expectedBufferChar); // Create an AssetDataStream from the memory buffer AZ::Data::AssetDataStream assetDataStream; assetDataStream.Open(buffer); // Verify that calling BlockUntilLoadComplete doesn't cause problems when used with a memory buffer instead of a file. assetDataStream.BlockUntilLoadComplete(); assetDataStream.Close(); } TEST_F(AssetDataStreamTest, Read_ReadDataIncrementally_PartialDataReadSuccessfully) { // Create an arbitrary buffer with different data in every byte constexpr int bufferSize = 256; AZStd::vector<AZ::u8> buffer(bufferSize); for (int offset = 0; offset < bufferSize; offset++) { // Use the lowest 8 bits of offset to get a repeating pattern of 00 -> FF buffer[offset] = offset & 0xFF; } // Create an AssetDataStream from the memory buffer AZ::Data::AssetDataStream assetDataStream; assetDataStream.Open(buffer); for (int offset = 0; offset < bufferSize; offset++) { // Verify that the current position increments correctly on each read request EXPECT_EQ(offset, assetDataStream.GetCurPos()); AZ::u8 byte; auto bytesRead = assetDataStream.Read(1, &byte); // Verify that when we read one byte at a time, it's incrementing forward through the data set and getting the correct byte. EXPECT_EQ(bytesRead, 1); EXPECT_EQ(byte, buffer[offset]); } assetDataStream.Close(); } TEST_F(AssetDataStreamTest, Seek_SeekForward_SeekingForwardWorksSuccessfully) { // Create an arbitrary buffer with different data in every byte constexpr int bufferSize = 256; AZStd::vector<AZ::u8> buffer(bufferSize); for (int offset = 0; offset < bufferSize; offset++) { // Use the lowest 8 bits of offset to get a repeating pattern of 00 -> FF buffer[offset] = offset & 0xFF; } // Create an AssetDataStream from the memory buffer AZ::Data::AssetDataStream assetDataStream; assetDataStream.Open(buffer); // Pick an arbitrary amount to seek forward on every iteration constexpr int skipForwardBytes = 3; // The expected offset should increment by the byte read plus the seek on every iteration constexpr int offsetIncrement = skipForwardBytes + 1; for (int offset = 0; offset < bufferSize; offset+=offsetIncrement) { // Verify that the current position is correct on each read request, even with the seek EXPECT_EQ(offset, assetDataStream.GetCurPos()); AZ::u8 byte; assetDataStream.Read(1, &byte); // Verify that we're getting the byte we expected even with the seek EXPECT_EQ(byte, buffer[offset]); assetDataStream.Seek(skipForwardBytes, AZ::IO::GenericStream::SeekMode::ST_SEEK_CUR); } assetDataStream.Close(); } TEST_F(AssetDataStreamTest, Seek_SeekBackward_SeekingBackwardNotAllowed) { // Create an arbitrary buffer constexpr int bufferSize = 100; AZStd::vector<AZ::u8> buffer(bufferSize, m_expectedBufferChar); // Create an AssetDataStream from the memory buffer AZ::Data::AssetDataStream assetDataStream; assetDataStream.Open(buffer); // Moving to the start of the file doesn't move, so this should succeed assetDataStream.Seek(0, AZ::IO::GenericStream::SeekMode::ST_SEEK_BEGIN); // Read a byte AZ::u8 byte; assetDataStream.Read(1, &byte); // Moving to the start of the file now is moving backwards, so this should fail AZ_TEST_START_ASSERTTEST; assetDataStream.Seek(0, AZ::IO::GenericStream::SeekMode::ST_SEEK_BEGIN); AZ_TEST_STOP_ASSERTTEST(1); assetDataStream.Close(); }
37.014028
132
0.691608
[ "vector", "3d" ]
3847ff4f2c34e38621e0732e30523137b8d68edc
736
cpp
C++
Codeforces/Replacement.cpp
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
1
2018-08-28T19:58:40.000Z
2018-08-28T19:58:40.000Z
Codeforces/Replacement.cpp
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
2
2017-04-16T00:48:05.000Z
2017-08-03T20:12:26.000Z
Codeforces/Replacement.cpp
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
4
2016-03-04T19:42:00.000Z
2018-01-08T11:42:00.000Z
#include <iostream> #include <algorithm> #include <vector> #include <sstream> using namespace std; int main() { int n, temp; vector<int> v; string s; stringstream ss; cin >> n; getline(cin, s); getline(cin, s); ss << s; while(ss >> temp) { v.push_back(temp); } int tmp = *min_element(v.begin(), v.end()); if(tmp != 1) { *find(v.begin(), v.end(), tmp) = 1; } else { tmp = 1000000; for(int i = 0; i < v.size(); i++) { if(v[i] != 1 && v[i] < tmp) tmp = v[i]; } *find(v.begin(), v.end(), tmp) = 1; } for(int i = 0; i < v.size(); i++) { cout << v[i] << " "; } return 0; }
18.4
52
0.429348
[ "vector" ]
384943abe56bc4f6ec2c709f8b17e09b708b47c5
70,684
cpp
C++
src/chainparams.cpp
GenYuanLian/SourceChain
f278529e0a85d7be6aef1fa3989498a7dee70f51
[ "MIT" ]
7
2018-01-24T14:32:02.000Z
2019-06-27T12:09:24.000Z
src/chainparams.cpp
GenYuanLian/SourceChain
f278529e0a85d7be6aef1fa3989498a7dee70f51
[ "MIT" ]
null
null
null
src/chainparams.cpp
GenYuanLian/SourceChain
f278529e0a85d7be6aef1fa3989498a7dee70f51
[ "MIT" ]
4
2018-01-24T13:54:02.000Z
2018-05-03T02:38:13.000Z
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chainparams.h" #include "consensus/merkle.h" #include "tinyformat.h" #include "util.h" #include "utilstrencodings.h" #include "arith_uint256.h" #include <assert.h> #include "chainparamsseeds.h" static CBlock CreateGenesisBlock(const char* pszTimestamp, const CScript& genesisOutputScript, uint32_t nTime, uint32_t nNonce, uint32_t nBits, int32_t nVersion, const CAmount& genesisReward) { CMutableTransaction txNew; txNew.nVersion = 1; txNew.vin.resize(1); txNew.vout.resize(1); txNew.vin[0].scriptSig = CScript() << 486604799 << CScriptNum(4) << std::vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); txNew.vout[0].nValue = genesisReward; txNew.vout[0].scriptPubKey = genesisOutputScript; CBlock genesis; genesis.nTime = nTime; genesis.nBits = nBits; genesis.nNonce = nNonce; genesis.nVersion = nVersion; genesis.vtx.push_back(MakeTransactionRef(std::move(txNew))); genesis.hashPrevBlock.SetNull(); genesis.hashMerkleRoot = BlockMerkleRoot(genesis); return genesis; } //巨额基础预分配 地址 #define BASE_ALLOC_ADDR "04bbd2f8ba5aa4e66767ebf47143ab8d85ddc0bad8da9e1b994d5a43a188b20895b13dd5e39c62c6fb8979fee0a59c7e828fde38ee53180924f5d6f4fe5c24d5b1" //小额批量预分配 (地址,金额) static const struct { const char * ptrScriptPubKey; CAmount amAlloc; } arrPreAlloc[] = { //一期成功 {"049cd3d55b91f02247d8b11eb898e5c185fcb94ccd1192a6311e4f4ea9ea1fa76f12fb9bd905f49c1a56b2a41e1fbaf7828ab2f75d7768c7d09b9152305c8b867d", 20000000 * COIN }, {"04027d52e786845a53a15fc78b7893a276e58be9a4d964ccf0deed2018a8b197c172d8f8e0c45d481da37ad60d40ca6092fa990c4e5a4c4e703acb5538a8a3bc46", 20000000 * COIN }, {"046b3951aecd4455b5f8dd3f0378cf079ae2855bff53613a8e9d854ae96f961520fe64ce9eb794d0eecda02c5d94d7d4996169725ef3ae7e14e3c2a8717865798f", 1000000 * COIN }, {"0441406f6e126cfb42b62893e50dc90dafd8e76e358c07e56e2fca988ba7d4d08a5e2e857ae9623cd090933bc3a7573ad69135732b55ed34cbb1f057b0499ff677", 10000000 * COIN }, {"0471ec3c3f695df30bf20bf5af3f6e33fa0fd1bf6af92adee6333d062f3d534ddcfb9367664562324e122321403d87fdb3d5d0e1bbbd796af21e6c27ebeae43bec", 6000000 * COIN }, {"0424acbac5ce57617a5b9afcce16a9319e036cf42ddeb604567c15af829534a4b9c6d24b508816224368d6871177570797019599a79f42a0c59a9be5055082321e", 2400000 * COIN }, {"040dc4c32535986066cac6efd77a3fa2c55068e76ccc3326f8269a26a9c1d9ed9228ce3d248fbf65b156013f5714a0e5e9d04685572d8f49e1ae97fc78e0e351cf", 20000000 * COIN }, {"04d5618d4822ed3819f803d08997f9efddc6b4badf68ec98e98bdb8d52794a3b5082e6f8b577332c57656ca333dd951bcbe01bca7a49da39c02acf60aa8ae9eb44", 3000000 * COIN }, {"04112185e32c9dc27aa8dd19701fcece78a5e420127d3ce242bae427aa3329247532fb669725f582c8e168c1a18a4ee26ef2ee589d16a1c3355ed92691a51947d3", 1000000 * COIN }, {"048acffb70aee294b543630cee11a984fee756cc79b51d0d87884430c8b45795f528194945a8b7f415a93975462ee27dfd200feddcce662d937112a25d05c4574f", 19800000 * COIN }, {"04944012ec83bcc599f6f0b845dd0340bb19a348b90d9269717a49bb18ca1b219779638f5f33beeff881b1ad3f5dd066347520b9247f2085bde6902c5090a0341c", 3400000 * COIN }, {"048be7da63455e61607b619e4c869820add1d26fa956662732c06ed72bda6b150fad678ccf510c6b3a17c2e9d9eb1d8d44c69397333e6096e9970e622b0de46056", 9700000 * COIN }, {"04a834b2a77db2a8b172da6076ab96a2ec4f185a1a21757a64c8ca37568460653e0ab360ae53d8e99b0ea7b2d58d7bbb4c6451661a3dc5c2a26a1b8b8679b63dbb", 11000000 * COIN }, {"0434f4483d4a9647721bac31282ebb3fafee00644fd6d46885f3ec8c224ac13c466e0294a1c2a4f45e4bd3223ca0f8e2b77694762f57e32b9be7daaf2470f2ade7", 1800000 * COIN }, {"041723fffca2f0ee2a7787bfba4b591e74a3c612de2f386804d38f03ab928d2b53bb7a335d62de6f1895b735e57b59a0e5020a92cb1ebb499899909c5119397ac9", 10000000 * COIN }, {"04b7ac8a071ee8134e4c701b7f18ca96f904c513a002cebcb0f78f28455b4cc65adab078730459d73cb5b43d28d584b81264865a9f56d97b35c539a8f35f416ee9", 11400000 * COIN }, {"0423856c684a45518f141ed9f66afb07395d2ff5baf5032b3e92873ba611d3f2dcb168e447a16db32489e50f05d4b693f2fe5df45f5e436ec977e54bac8c0ca875", 8000000 * COIN }, {"04c7f19e3c67abaf085236500d628c38b4b0e4e09dd35dca5e39c25cf95608036f4e2f632005038d7b95883127d843b0e8e34eb9fe764b3bc9e4dd251592900952", 11800000 * COIN }, {"048ef8b2b6c45a6485463b296b13c9cedaa7b650f0fb31933dd104885bbf6d7f8d07dd7647c1a6b8971dd0aa49a6d62461ee532c4b6ad0247c55010defb3ae9081", 1600000 * COIN }, {"047ad54d908a00c07f3f5113e2e66966816332724996c55f671195c34a87452f8a28d7cd02bc649b7e8a2a64e88cf3b2c11dc2b58e1e7a80171e690c898342a18c", 4400000 * COIN }, {"0428ce4c02c4a62d6188841fac69b0fb7a875803d84e66260f57ef89d9f04f0afbc17c153491ceaa68171222fe0b23e911d74034b561897686aef47867110c4864", 20000000 * COIN }, {"04f0f1028088944641b72a9bbbb32f11f0bae2652ac0e5bedabde0d9eeb2cd2e4fa14094e8740b02d872dca2c91740e0e7e6ef5627f2f73fb73097d042a40b11ee", 1900000 * COIN }, {"04a2dce90a018a043f9232dc1538ee45698506726f73713fa167f12ee08576b9294a0fb22ea7ab6bf360512b432b7bfb86024df36e30e9a8d60f9b9d22517ef8d9", 3000000 * COIN }, {"04efce6457229a7a4acc24a4bc228dd8f7522322c508caf7a0abb55457d22cf74a7c116debc896e2c82c7eb277568cc7c282ea9044a3a8b361e6531fd42e85d02d", 20000000 * COIN }, {"04432056681d17ebb532c02ec5693e377a3b4802df874ceb0cd30d9054bc99ca4f7cd211ec58c01a2e18925e3680f22fe8949eae6ecf07f816cd7397ae6f8471a5", 28500000 * COIN }, {"04506bf06020153c394f358bde07df78dcf039884bc744977c044b149fb2c78f6df9509794017c89cdde98cbccd868a8b259b8b5ba3d2f3203e1889c93ef3fd242", 1300000 * COIN }, {"043398d94a7286017b0aa757f42da1b50203ba0349918b11aca1164dfbd32a45d8e8e164d08503d932ebead605dc5c49631e311a4b74ed4ddc3bc5b64aaa95fa2b", 6000000 * COIN }, {"045bbf7613b7842e790877b81cbfae5201c4fb7c5d9ba83783afe5f51a926e5bf2aff37efcab9d20e81048b1db20836e6e6c144b2f12f64a08ee38893ae8582be5", 640000 * COIN }, {"04dec95dfefdf7549db651c73a550287846b25403cd0509485f6d9dcb53ae0558a48b7d49ce9d1c69d36e9c72c1f35b3565c334d0c57a7644f59b3e63280015efc", 800000 * COIN }, {"04dc65876d8af9f3d2f74f4094b577e1e6e354eba07dc9c94dc2efee9486201eb512e34a25f1e90788bd39be57e265defb6714b2394cf6c0fd969f1135ff2b6fd5", 3353800 * COIN }, {"040c28d4ef7090868e937614528fb6a6978c75b2e9655c130cc6967da59cdea572414430382abc509c37391bdc69fc539ff1077c733af4395ebb9dba53b2a9bc7f", 1000000 * COIN }, {"047b4b8e7d872e154ec1ef65fbe20708058a77487e6205b43ab269309a1aee09867de53adff049a1c5af9e00ae1b42663c7e026e62c849343f1f9707b6e9112203", 14000000 * COIN }, {"04edd0f37175641b781691a65cd61a23e5ec757ecadc383dab8cc2285fb3b7c722cf2fc435eea4db78258d1f084f957bf95b7a0de9ea7002d0d5073606b46f8c1d", 1000000 * COIN }, {"042645a4c6345c3fe02bfdb9fd25242168711432e2f7eb3ed58ab617500511d12a55796fe826cd79368deccc898e2e2af8f4d660190a85dd36b26df77371034bf8", 4000000 * COIN }, {"04a1aa776b32ee612ba46adb353806cce80b3cff0d8849796c8d165406b037ebcb1715d967193d69c8301b99e33a39992b36aec7c729b77f2098fba02d818d0866", 600000 * COIN }, {"04525b24032740fabf19accc1911a4350b7668acb179a304044a7e80676f2a601ec1ef46c33ee3bbf6af0469f0aa5f80f8187a49a9934867a18102b9536a687a34", 20000000 * COIN }, {"042ada142ad7d4f30f0229c88e785675c13dcc45df2925d9dddf7cd7eaced2be658040b5ceb1beb9331a470ff9340be9ae01bdbd9b17d66ca97895a36cce160078", 3200000 * COIN }, {"041ea2a66049d1f3f83de01833273ac9710994ca8741de38e1bb36d4be5d987a492c9ad61627a4fb302bebbe84fed2e0931177472e02af92bc67800121db3e7238", 4000000 * COIN }, {"0447b5c54484acd7e09a1ec3b52a3e920307b0b76b545c2b16cb19a48a5878fbe5772cff6fd394e7e8b101f2fb41b5741ece973de5460807e08ea8dd019d71faf5", 1220000 * COIN }, {"048621c7c51e288f09874120c6ba9df040a8777b4ed22a345c8d615f760318864d9be975d348ef32c3d5444359b5417f38277ff8d8f2de75f4b20498dcfb1c5cdc", 1350000 * COIN }, {"049a338dc10883e30a61092791f11e4f3dd13fbd329a83f2a6b3a41fab0c92c1f00e8c35e8fe046f03a278d348fef7d550c2146299e7f2153fdecc276a84ee770d", 8000000 * COIN }, {"04d04fa6f5f403b12691eba42f0c6a5b74224db421c4fd7fd909d85cdd8035dad40495704c57b41338b5ddc710abe354df92e0e193ef0c597be1b4d33e935f2d4b", 61600000 * COIN }, {"045a3cc25b3095088a0d4e20a395d1260b69c67373258c8d1222afca4440a4aaab97e58ba2974d80ea5a7a9c3ae0aefc783467b56c35860f0405ef1520318e24de", 8600000 * COIN }, {"04ca4ded3821d349e2f887c9c656ba69027dc1ef11f764b3e71d5614e30ab69b2c9e4213d173771f3300b032dab9af3ef64a86b22b3776bff00b6594aa3bbc7674", 1800000 * COIN }, {"044b6a50010e291c4070d53064330d6faee55f5ea07ee0e79cf0db7970292a5a26ecf7cc8ded377eeb387924d15baf0adb71037c92401802acf5916b1f6652d8e8", 1400000 * COIN }, {"04b6b97ca09f52766db6bc319ec6213ef96ca22df07cf63df2700b33cf19ac97eca2f3622d3d0616de53389ee38eee210f0bd625e83ba843d2fb19026effe456ed", 2400000 * COIN }, {"04ea21ea003584edeb20054eeef98bf03aa1fde249c0219a52b9b435115b075cdfecc471a421475ef1cddf037cfc44e95d9f29a99826084cb05f3336a5377fe3d3", 2000000 * COIN }, {"04d3ce0a19ed2c9445e904859a271d13bac493b2b2aafe1025cea6b69448616bb156148c1988a53ea4db8ea03f89c14a0da032c372c70d8dd4249c2fde2d8b171c", 2000000 * COIN }, {"04d8385ba184fb421bede6fbe8be5fdfa8575717573b3ffe2486bdc63f2ca62ec116f2f8cc5cb62376709fc0252f59dac711908c702c94bc6411cdd4a2d732464b", 2000000 * COIN }, {"04852de151971f5c0701656cfd65e167e1bcc0843524069c6fd0d1c8f5ca4cdbf78e0506221838d31a4b63946fdec1fa4b524961f067cf8b9ad9c55b421ad11474", 1000000 * COIN }, {"048b14beebe2efd9e78ebccb28c2e969bfe915264d6cd452983c046f90d25a8d572490a315a7a13c1a641c47d850e5ef76689e246bf8d41d69e1bec0b6b89bd878", 1000000 * COIN }, {"04c1ca98ff58884c15f26f0a17ca48c5f49c61299e37f0deb2bc635051c08132428a14c087b404192c3c494a0e1c77d26aa5bdafac6d269d293b33f4e212655ece", 3000000 * COIN }, {"04c78e3e3f3f4ea04ef1bda1df0de545355cf2972136cf075881233d3c66d2560ed5359c31ea8928e289e2409623e65a06613261e967b3428ff5196d47ce3efbbc", 1000000 * COIN }, {"0497d93881bdcb0b9e03d325b6373151e1938ec72d9be53d2463801067751822d584ea6ade86a824dba2c8f7f7d060c7275a68e4d3d589931023fa3ae9f26185b0", 4980000 * COIN }, {"04c12cd6540931fe7af980e6f9de54c76e07ad605e272d2a28a7ba213cdde897a0aea5497aa7c68f0413385d3ec460d265f599cbf87a7fbbe715bfbdc1607eac48", 16000000 * COIN }, {"04c0a4864c66a1972a81a6b16642681a2911953fa37eaffa02e02f6d8255514212c5293d9ba56a5994ab892d07cdca233b2ca01d5df1cb794c2d1b548a3e1dc069", 60000000 * COIN }, {"0457a68c9ff77d965eb9a164eabebaafc1d013528df0375a16bb1735534851a906f954b040f4ea77a93bfb8e32f38c2b55b0790def51c6ae550d783940c739a6d5", 4000000 * COIN }, {"04956e4444f28a231ecccf2f08c316009c577830067f699d35f7bf2ceb198ae4adcb2f3878ceaaffa9c8476507f8209cb43ce04c9d13f53b8250ad6c230663540d", 7000000 * COIN }, {"049e801e2754c8296a78b87df29fc9979c617ce0daf3888fca72e9682ac9149dc93742639fea81e16970153820ae37ac2ba92e9576d30842374d0b40b9f5d79ff3", 1200000 * COIN }, {"0449c345f74d7205399b3af1dd04b342a3aa6ff7cc2b7c0941337172810f97e70c866f9869220fc54e233d81edc372339a1c573ba2fe2ff5d8978057e6f945b09a", 2000000 * COIN }, {"04dedac7ba3593e49fbb3448ad7c49c17461ffd74f83cd87f33809805ad9e66a663ad3974ee614044a85b1876df7c8bcf54aadca909853ae364c54ce10f9393fac", 5700000 * COIN }, {"047898e3c799bc7d813ff86d3e9dffa353dc1d873f6f9aa11d5b7975b48a6ca21390bdb023f84beff6cc91ce5a304b63b4805660fcd12e62ffaeb9c705c0e38ffb", 13200000 * COIN }, {"047bb04dd4fd94f40283fdd54d4590e2c1c89e29f16af103a1413fc75723bcd80ab7451ac6f55625a1d8e2f4b2e79422097f473ace3584ac0a7b31d79a1e75e9d4", 14000000 * COIN }, {"0401759c5f94f97f47e58a57bcb859b43e74bae0c480b302c797f4c39f0bbf58659befae52949612c63672f4385497d2841bb67db8bc3f662b96f2c94035977d69", 2000000 * COIN }, {"040f6bfaf569afd00fa6d1dca667aa08dfd8a8a49663454847942c1e02c178da0ddfb452e4426762fa099ee3cee28555b1a34a451ef455eb99287eaae8eababec4", 8000000 * COIN }, {"04e59d4b9f40e9c89c2f76d360e2afd178573c05f7038a4a92c61fc345456cc40f91a1861299f65bd9772d93bc57264ccb2656e9385e1447d1297191c55e404742", 5800000 * COIN }, {"04c7898d43f98c7c8cfb07e78e2a321348ae09057fc400f3849bb8870dc1f0e42add6a001ae68b48c22a52baa737d9b57a5a60a351c7f393cdeec703ec553abe20", 2400000 * COIN }, {"0469c995f39cb8decb7b0191d33077ba07fcc7dd9345901af5188d7daf877f2367a8b7dbe182bbc721f3db4868ffadf393ecbac95d46ce3ce3bd92030f55ce12fa", 2000000 * COIN }, {"04c08bc106795419af07d8cd7f868e6a1257d848b0f57aac28a2d4b9a0a143a699467f560dca42260c7751e664f547a8ff219f23ba15045d32e30247a77806477f", 2000000 * COIN }, {"0446737c3207a9c4817d0a51e00775529f46bddb060e73ef83115847bd71eb22155673ae0779059e3666bd64038c21c218c5fb99fd7d0e631eded85b517372255a", 18000000 * COIN }, {"04c068bc9b18ba49fa7209ab12d28da750e57230b284ae1fbc1eddbbf59842b37059678da96d2760eb30164dcdd199553e53b8e33cc393d81a46f32fc050511ed8", 4000000 * COIN }, {"04392e328b237c718ba8b63701258317ab10f0f0c695899c562691d25a6808c7097f205636b8decdd33d989ce2fd61c88915e4d6091bac5d3905ef1ff5fe27d297", 2160000 * COIN }, {"045a7949cf8eb95e415b3bae343ef89db7e8f61b3755a267061a54866ddff8f6ac4992e7f76a5f86416fe06fad8cf8fb636f03245b0a6fe6f620ea050dd939963f", 6000000 * COIN }, {"04d93ff3765a09b62a7f47c495577d722760b762141a0f86c60399d4a1155dc109b4483e803969a7b8b6514c444aeb154dea7fb2ac72dafe5125aa0736e785bb56", 8800000 * COIN }, {"04f748cd3d43f649e447d454c8f81755c6a0a5eb4a9e96bb26cbc43d2451ed961432ab6db9268903bee7cf17fd1c34202d0114248cdd10d2a6f711d3dedf77b3cc", 10000000 * COIN }, {"045c44d95c21b816b79608c870e6311618a08c75c9d4f9e6334626f63472d9927d6c1a67c00c3f9ce3fb2b0266ff5d57157a4046988ae413802e7ead541bfd70c0", 6600000 * COIN }, {"042ff1ba2fb4510e025b7813bc13d9efac567be7250eb97117e4945ece927d48a2ab8f96991c0f2ca6caca9b8985a37d9b423bc950301ddfd17dc6190f6607ecb2", 4000000 * COIN }, {"04a1bc774f81f0c34642e29deb038565d0974a3ee562ece5f73f996d1faeefa60d7bac8fb8163ad55143d52c1090babc1f3d4b5340d503b7ce8bfbdb23e8f5276e", 6000000 * COIN }, {"04342bd4c2de7ea8c7a8c5b15546a21d8cb54543d00a6ef4388ceac1248b62827334da2852f1edacf98e53e2c8afc54007f045664ca47324be97b40f7883ee5862", 2000000 * COIN }, {"043ae2cd70db41de6228113323962bf6ed6d5f94c9e6152130088d7bb810be3dc49d13c56703e0495a378f386240310348a54c503557cb0553532ff6b76762fdf6", 6000000 * COIN }, {"0454f6bdf5f07a34e427bd8609eb064036f2d8e63c34217b0c5b33cc440ef96be8932253e385ee31f0d01b4b063f285c7b5aea45ef00efd93edc6a606bfb35d71a", 6000000 * COIN }, {"04a0dd30794302711a21d631f849c635d407d5e9f44dbd5601b181cab70c6c9ce7598881a61029a9b126ed4e7e87f2ba345afab0a3e35f18af65396aff39c06e61", 20000000 * COIN }, {"047aa2ee0ab05fb86796fa93618fe8532657deaaf9df387588d5ebe4fa83388dbcf0a7b81f472f1cec837a75f1c6afe9421767c43d3966353b41b9635cde317b1b", 4999000 * COIN }, {"04c941b6471f96a9c163691f5f280727cc1dfa127c356965ee9b3183b117652db7bf5d3e415f1f4d7b133d6cbee5725f80d25f4d00fdcc49bc7e2fc5a6716a65b1", 20000000 * COIN }, {"042aa15debfb0ec3dd48855185b23ca2538a40cbdf8b682db4395fe4390fa730092b4efd79a031d702dd79ee499abd348e8f0a71ba44746b35655ba0fac1a9ddc7", 2000000 * COIN }, {"04355a27c6813f100a950c22a772d8d299050d4f5102c5410375a29f6c009315f7d12642cf1f8dae47c32ef2d6780d95591fd703d6d22a57be5cd8151e036226fd", 20000000 * COIN }, {"04ca040e39c5558ea5818c9572a4cd23f20e1af5eb372d681ecfbcbef63de9c0950fd509fd95f80ae0ea53d782bb892e6015aaeed948f83c4ba3a274796df0a144", 20000000 * COIN }, {"04a0db0b7ef48839dee72e0d6ca8d3540d4affab347d9926454c116a7a8b123977f41c7ba4e9b42db32d54332da33d2f9111e2d35f7f1a8b79f76999735cbebe8a", 10000000 * COIN }, //二期成功(一期转二期) {"04f7933ef8fa700139d289423d6a6370c3f28d9fcba85540262f8fff4f60ef876fc9b68ffd12a6560feba0b1f0d1f29cf778efe1bf870ec41dc0388d0a0661a557", 8800000 * COIN }, {"0487ca13740f5a84330c85142e1b54aa1c25d1dc9fd6880fd2806bd3e145e4362d8b8bc4ddee6e4aee188732551b00a5fd6921e0ed7ec37b332876f21f233dd749", 3840000 * COIN }, {"047e69470c6721e7deba5b29b9917e6cd28dfb8ad40fa69a200920e9eb4cf63c186df6f80a69108f3fee7927e873ffe97e9bbf572be252f21a67a59b5e054caf37", 2000000 * COIN }, {"048a5e11c3d37804937ed54519a6fb0e85c6ccf4f1c64270bc7dbf64050bedceec3f433fb93dc0c7999bd2432ba12bdfdfe186b9883b31404ad9502999344a3f99", 2000000 * COIN }, {"0408280792461bddd84a9716caeb2fb65b4f9b4d66518c3f43bc1e2b2e975b228ccdf4d29183fca6aca89161c98e5d40154221a52197c086089b0c130110f106e3", 2700000 * COIN }, {"04d690d398ed7b6ec624186aae8cebef4fdab7a47b08ef761502c7d697a9937cf34a6389d5b0c91a4ab770782ae8948b2724aeb267ffe2af3bb6bd6d05ba88b141", 6000000 * COIN }, {"044478b8233def18042e46d76abd530cb57f8dba7d2e762c8e5e18cb7608ad04262e0ce7bdee2286a618c42efa287ff5674f9e22994a6f6ab0d1a60db35592c2c0", 11000000 * COIN }, {"04fe87a11bf4b8e21151ce26218234247fbdee6f46f79e3d7867fc5c304d723aee7896c3999628447247d8c76aaeb93614b1e16d775e678355e8d99712b9f33f1e", 6600000 * COIN }, {"046e93cea94685955119e348057955ec414635dfcb687c937e80fff6cc01a2c1bc909a887ed29569345b683736247905d04a180439f0c9991036a95b86d70398a7", 10000000 * COIN }, {"04774fe69708f91e81fcf270093326e5426777ed3fbe6fb0d2611285b1a698afb759fd33a4f82a3c19269aab5c44b5382d296be4b5ead1edced41ed37ebbb3e344", 1000000 * COIN }, {"04b22c97dedd5a2d64e6e88879a17bfeaca710543b8016b44886ec4a6b680939ec5052db057f652c5f945b6c19ff3ed4dde4378e193763a3b6207af65c446cf27a", 2400000 * COIN }, {"049865e8fe21af23467dbf08e0c98be2b45d463a96c437ff89face03d8e7f4edc4fd2342bd1c9bf56c7e7c3eee6f6584bbb86ec8c123be0ff19d6e9e2202c59cb1", 11600000 * COIN }, {"04064021c92a72395c4bdcaa280242efcde22c85528f38d7aa83e63339f8eb5c4892b132bf6f5662dd131b36b3661ebd0db5dfa8274027354d6ce1cc6dc81aeb88", 4000000 * COIN }, {"0436daf9a1f50f79ff36fc7ff06bf985e3be57e31998a9ebffc218c69d914e006e1c9bdca79b20404bfc664cf4b4349c1ad3345858afc818954dbe9804b0cd32e2", 4000000 * COIN }, {"04ac6b3dcc4f17f94900d88312129d087d9ef89d7f4fdc477b78197e60bb93bc76e8f2a2cfa6da93001a3e66340daeeaa12c04ffbf1069cc55baee4191bca9dff3", 4000000 * COIN }, {"044ed82c411c5225e204a9842fad216c89e7439031090084bda3820017ee69793e3ce41470dd30a6aabad8e958e1a192c994498cc8cec9359cee65b8543d0dd8dc", 16000000 * COIN }, {"040249e23657fa732fb75ef5aac46d05560c17780c2f2a141dd281c993dd1bc3abb0f9f7f03b348dd4a6fe1804816c198f9d33f742a0ccc054ce813858c5cd6079", 1200000 * COIN }, {"049986bc7b27955d74e63b3fee21d123cbd4236229a103f49c476ec9bde7a3eb0af86d9ff4c93dd556c74810ee4e81bde7b3e243985ac8a9077a69a970a6b789cf", 1800000 * COIN }, {"04d7f440723dfe28bf8c21c79ebe18ac8fd837cda6ea42cad5b278cd751d309cf634463867fce3f2b42a71c794b080990ae7d021492237b3e1d7023d721f5d543d", 3000000 * COIN }, {"0435e1188a5c2c5056e1fcb3c4f50ef14309421a89b28befc2a9c6bedd1a2f861592a0ffdbe584b3d0ba95ed6fcecdf04211dadfe96ef7b414976472c2d2aa8c77", 10000000 * COIN }, {"049928737abee4a49e06854b64017b59e4c2b521f5ec925589fae52ba1e120f2681821bb70ebd77f4fc17ded71e8695c5c48d423e7159a7343f16cb61737160d47", 3800000 * COIN }, {"04bc78f80ec3d8ceb362bde8d3209e5f9c54bba0a54da1c33e322b27fcc223998912552a0d672e089545e815755fd89ce3bcaa8cb8b056404bdf7d65c235ce96fa", 1900000 * COIN }, {"049be3a3b0d5601a9e6215288c329d97f6fe9c6277acc2dd4cef9487b5285d69841b6b210d6d7bc3790fc1d407204c4a65ac950211974844c7acffd4ad87dcaa7f", 3000000 * COIN }, {"04cccad44510185ecbb5132a7b060b224452f37194868013a711cfee3dcdcf63d7c255c4493f044b46d1180ca5fa101ba8eb64344772a736789e3a103a193c54c1", 18000000 * COIN }, {"04cd22c930dbe91342f7c7518c4cbfb95e8192d6942e3b5a34fca279d28eda0e3cf6d3a7d20b4ac1f09cf73150d8ae5b84ea223b5891373835f98abb835ac13eec", 9800000 * COIN }, {"04609013e0363c4cc26591fdc350a962be97002b803d30b30ee33c8001eebcff303691f119cf73eb0d29652140e132fa6f9cf3521ef03716838e3bcc2bb98d9f3a", 1000000 * COIN }, //二期 {"04c5c547589620f5e853e83dd6b6937567216f7fbcf90001e54c96a33638f7e6b18cef3a6b47ebd219ae6e171a069c3e8648baec6a24232b214720a38fe4f4e098", 1666685 * COIN }, {"040488dae8f0ce65d413defd25e55e1332ef5b0c5c5465bd6377b7def5a422a6469d1ff1a5ef22771b0d62f1410d8db4dc768d84befbc1cd7e917f88a7ca086f44", 1666667 * COIN }, {"0420574fcaf9129ad5beea5f5286658c942f87138c3040d4a258d1a2435697da44f168844c6ef97af0984854a4f1a5b8845a48fb8f5b550321479a596c16ce9ac4", 1666667 * COIN }, {"0426e6bd6ae1b94ee6eaa1149ae2aecf57ba589a5002142ee0be0861e2e78dd082797c17c18c58bb05afa0aabca10df71ee7726af05081d8be9c68346b7432d752", 1666667 * COIN }, {"0414961040e11a8a5395a0a3cb1517dc3ca292d3d8b3fa27d2c99950123c6196dfbead7fa77eb9adeee252ad0240c3cdf2ffb4342bbe94c9bcf03d55770bfe9f99", 1666667 * COIN }, {"04ce1d3d264119b9baffa24a86888723ebf1fa1c3487c22904297376f251dd8bbdb1672abb2ed7431e8c86cc5c3a452e87bf1cc2cd4c85fe93e5be5bc2c5e38bf6", 1666667 * COIN }, {"04ffc04b789d86269b55a3cc18237f0141fbe68debd4e5e0a4a5af432b1ace0025602cbcd2607eef37fd64dd502d15ad09801601bd41dfa3711d6072d2ffe921f4", 1666667 * COIN }, {"0402d1ba4743e31a08ffd6b3af34a5f1bc0d74fe7aaef459ad1e50bdb014bcda406bf0e816ff03ca7803b582a081e6fc84fda75075b86a2c8702bf1ea48abf0f6a", 1666667 * COIN }, {"04d29028b81bd2450a796d2c969f678a57678107cb4cfa3339ffc1d346789513f341ebf78dea6fd1295a7563b915fda91c0e23f78ec037090b19e72a1a22693309", 1666667 * COIN }, {"042968a934585aded70180681cd604987b1147a6daad80c2ab3df4b3fb11a6495b3166995bad0debf74b88b5937ce1c5256aca3143e76a602c2ab19d33330f9db0", 1666667 * COIN }, {"04050847741e68c9a476d99b4c6800f07b5188049dba863b1997244ab4ad4118794497d9cf9a4c48a20b73b99066827b51ccbe8fd525bfef927a2d66f4b29d81ae", 1666667 * COIN }, {"043ac755210aaf1acbce6c17089510aa4fc11d38cd737ead27b97bd14ead2992002482f5ec42dc68bc3d2b8aa0fcb758fdfed9c2a995fbbf3473d86a57f9caf948", 1666667 * COIN }, {"042d598f1e7a7970f08b74cf4ddf00f80c440a7d38d25725f72ba9d3fe38dd3f3899413108b5ce8db7cea44af5f95e2286067a16db7fa240d7026eed68a3c79a1d", 1666667 * COIN }, {"04a77831f4de3f130923c186aa2a17ee037221e724a6d04a3305bb5ab7eaa69b546bd31024fcb30f4ae6bffeaa20df0d86198ee77be2853fae827373cde3c98ff1", 1666667 * COIN }, {"049fcac4ff171b2610def7d3d6b997da99f9921340a1dc9c9e394d74b9d8403446c4a54c5918c2244db19cda18edef3feae08c8213953fa77ab84293eef6a482d2", 1666667 * COIN }, {"04efef178130aef6e0469ab1c37d743852c8b21a990d432911aad0fd8e2614256c9c56010575d2094c68b0cc95ad8d2c3a0ac15d362daa8fc31834f66c76cff224", 1666667 * COIN }, {"04bd3b0ce18b259a9ddee52f29e07802dd72c22d988c7831a9e6a45899278ac600a58896a82561752a36ef4d53232c64f785be56c7b12c007875e6d94fb649ac43", 1666667 * COIN }, {"0446deef3da1d9689c218736ea4aa090ae2757f50d6286399b6732211b04a25049bc24e704ca4815f9f4089a80803081a907f47d2b4061ab871e266f625d83be18", 1666667 * COIN }, {"04a543ba65e8cc7e6a4b2afc72c0ed3b7e1ea6fb14bdbb8687252c9f497b337cc57788143f7cc1e012f1bb8e02a7e8a686d305c7ef296c1d42d9e4e6a740eb3bae", 1666667 * COIN }, {"0409ef66b0a3617edc47d536f3f607d1f7647aa4c02978a18ad423a7c0576e4d35359a9866a2b4f97c6ea15605ad2936441fd91a517ce745f062555269c6f6002b", 1666667 * COIN }, {"048491d73180236d0ba9633a1c788f370fb433c492d8f9a5c2e8a2b39f7e75c39eea96a425f7d995c717f07e2a7e4b96079e2b56acec2364dae81347c7addadf72", 1666667 * COIN }, {"04e552ef4e00bcab9e260736b9b04403df59296d75e7396444608fac22a2aeaf7bdc42776ff929cb243c4926e8a273ee80a07860fa535803d3a2dcbf3a2a218d56", 1666667 * COIN }, {"0448a128f5c23e463dd8a4c9aa8e16dd936c5f9ab7ecefc842321f0c98e73a49be6c59ad3b6752bc9a16157877bcc0320a5b775558cd072f1b8477ac92c42c9f15", 1666667 * COIN }, {"04a875b8e52210ea065723398513fc294a8a12bedc5b4d8fa4f9b08b479b0b34fe1b8c176cfd9cf9e30ac6e6d7d66df96655b49d4b7d06553030be51e2196e3603", 1666667 * COIN }, {"04b5ff289675f67a2d2ccb55df0534a133adba5f650b7ace5fc53a70ebf394895ed0f577d01241eda7f4c107f3ebf596fa2d9f6e41aa821875250087dff6dc4138", 1666667 * COIN }, {"043c1098c985105f062a7c2522fcaa4240ba535ac0147c8fff0442184d48494c6f487179c2e8eed269ef492754b41dec4e8eb75f91e291ecb2a90ed9d69847b215", 1666667 * COIN }, {"04f9812dc0f16949651c2679fa6201482a71a538eda61176bbcf42f948e1c2cef72b741114f965462eaa2628b9c9aed7105593dcf3cc826b39c5d6c3d3cf068d21", 1666667 * COIN }, {"04b6ed726f6ba5832480219ae0867c25427105104e3543c9f3fce0c78ecab35832fc5fbcaf53036b766ecdf8697b409e0118d089b0693906bcfd8b5ee94855433e", 1666667 * COIN }, {"047cdfc684ede83cd50d68e57b26cc73aa5a2d67d3ca70f007aa619b842a4a154ffe83ae16e78768f2643484da79c746f892660c8ac6758d6ac2f0916dd552c9ad", 1666667 * COIN }, {"040aed93051a3ceb2ef7b8d514199474a49d4325e26134cc36ee56d8f23508f219f07f2f5eb1583543e5838c83fda2a0513d5088d8a97528bd1b23da112b821713", 1666667 * COIN }, {"042e4ac1ba81a1d06d0e52559448f225b4adb903dd4bc868f112ed9fb6a8e7270230fb54ed1bf2ca87b7712bdee0bf852730350ac3a41368dfe7716bc68920a83c", 1666667 * COIN }, {"04f56f0cff84e2468dbc2c84e99b5191935460076e1d8b3e3898b95dac85741379fe59e1b2d52721c72959e446ef3d68d93cfa35e085337eb50248739974f70a1e", 1666667 * COIN }, {"045ce756be87c8c44669459400e725e621d59aa19fed35030b528c1d4d1c76cf0cbbe4349576305f965e50422fd5c668d3e2620d9fd9d1333f6d2ecad7779c0283", 1666667 * COIN }, {"04659139abae605d738d9d417a115ca781390548629f3356f788c651793a10a1a48814ebcbe2316c9be8eabc5dffff7c0f55e0e11e3c4a49dbb744f012f1402faf", 1666667 * COIN }, {"0499dd405093e4f3bd08a68a494df4027a89f9fa25c19504917fef78842df423fd37f5cb93a5a1e6d4f55dce2b60e15605546980116058480b6054a3b3c3d1a790", 1666667 * COIN }, {"04a42e3d5369662772655e04449e09a0ebcb86ca41d8e72175ba0603a9a5e106d447a4dc827232951c970c629ca4a8c33013799c2db03ee6b7ccc5d32b2909d64c", 1666667 * COIN }, {"04fc56b460cf87dfab90dbed763f32afe058ffc89cff48766ef1ba1ce0fd660431ac531034501f5a47528f798d61db8b5308f6f6e21cbd923fc4f0bfc66b54eb68", 1666667 * COIN }, {"04d37bb6ef026a87b4c8acb9cbb7f2458b5c54c774bf43e5337abc7652cdb1a87cbd5cfec14114786e33638314c5e21eb2c81148bc5399be23acd344d908ae191a", 1666667 * COIN }, {"0497b60a56b66da6d73339efefe429501144ab5d4a3240b2af9510982cfd9989b028556247f7c1e8950a1e2eda62c318c1110da2156d3e64b087b712070fc63fa8", 1666667 * COIN }, {"04d42bc44238add5fcb67f6f9ccab29061b9c364deb8758673f667b3fc45c99c73335b635399f9bb497b1e8019f8b9097be62b78f37c30aac9c2a1da139433f095", 1666667 * COIN }, {"041f7db2de9c6b006e21954403e441a8510cc32d5994c36d9eedcfd2fc81b6d7784a563b5584661060d89be1cc71ab5a329fe83c0f08381c01b989b73f6f172c63", 1666667 * COIN }, {"044191d9abf150d97d52f122caa8fd083e113928cb04bc321344a6de3ae687c083afbe785db803dd4a778d47ff1c7eefb7fa852d01a5bdcc614028a375b15889ce", 1666667 * COIN }, {"0406cd41200dd65326a7f5fda120fc910e1082a9e4426d6d2b588ec7f57a876e4f6f915180b7f1aaacd31571e7945d4bd3be9e294fe6b820aa50b471eebcaf2661", 1666667 * COIN }, {"0439640eacd72b8e15b685f5750b96b6b2613e67dedaa4cf56ee1056d539ecd8dcc97c96a0592b6fd6a0f949e7f8e1d04aa9c5bdd72fe28c1ad8c64099af90b5a2", 1666667 * COIN }, {"0428d8ea8c829d3ad93d23a3a80e46e9ada411f5e064ca7df8c1595cf7d35ca2ee3f338f9ad96b6b75eee4536849359564dc9f6f9a7dad479282f4c5b35739c23c", 1666667 * COIN }, {"0432bdf893954f47d4d784b02588286520c632c8543d1f2af717c61f0bdd286bfb6b0132a564eaf2485e635afd2ffccce6467e85ceaffd3b14eb44927f8f5ff5cf", 1666667 * COIN }, {"0429a8079de703cedde6043c698c32db0512b454c843c7dd83f201c1447116257356234d959fec833a8b477d6967fe53953c433b1b62e6a7c1aff3b30c1bd04587", 1666667 * COIN }, {"04073b6a26991063a5e523fc620bcbcaf78ee37b2851e87689f34eb11fa2a244325cbd1889906ee6bfe940c190c750719ede1f40d63c517c8a929d675f38e7fa3c", 1600000 * COIN }, {"0413be8a64d25109cf134d3d94f5269fc3b1ae8a5529b62ed051fc43a42bd8252429d24e92c03b9ea5c27ceb2978f52ead7dad3be880ce4fc70c0065eddf199ec8", 1416667 * COIN }, {"04bd714f205b9e2df07f0ae770d55ad9700da562f96d978d1c5e55e5e27e291ee2cd665aa8bc785de0cabd13eb9b56f0aacdb52fe0c647344f424931935e6e38b0", 833333 * COIN }, {"04f14f408a7da0626b179ea4ba468d8e8b913b088ac0275156a31a2163d12f2d87b5be20737d03e33d78816b67be7efd3791e6c370143cf5c81e9d9052df3c1d1e", 1666667 * COIN }, {"04c662ea55c7a01b6a4d91922e514ae97f5c2e551e72af3c54b46bdffd174a20976373860a24f245cb5339726f09297c3286db7c4f23b6410469079c8bfec64c91", 800000 * COIN }, {"04e031d6d65f8faa55e1c17cb8bc38827c3a1348d863f0fe5f2ec0a6efbc634e5dda20254167b302984bad620c2052dff830764b10f52d0472b24e2fe4c436bfb2", 1666722 * COIN }, {"04e2099dfb6f96be07824e6b1e193765c1d346baa0dbdde70ea94f6948896d93ea60f3a7a7b12ded3425c5ef5a2b65b28140c3f075594c76d16c632076354d8bba", 1666704 * COIN }, {"045b480780719ba41644e652479999afcb8aa033100451262e60041610252ef62ad7986ee1e2d77167cb78863cb6000bce4ed8bfdcdaac85d52b2f55e5e0aad070", 1666683 * COIN }, {"0496f402aaf1c71e11906e9c005f2457014766ef856592a388df7bd1bca793ed516ae5b80f64604029dfdef2c8fefa3efe7ee03e87de0f3b24cc6b531b94956aa7", 1666667 * COIN }, {"047d46a47ff08b219b3beff005ad2d2d26cd814a8f4b9dd9ae4819b319714c14daf19ba665fcc8bedd45dcf29c3a9e11bd9d14e8d0a851f9ba62db474806547860", 1666667 * COIN }, {"04df32d0808605f0db0c7aaf35fd9b46e73a6ab08081d8a8fb3d23ab457ec818d14ac69370ec17d6f4e85a47d678d9f2fba3b1a11d4d2b705b2f431b48b23728c6", 1666667 * COIN }, {"044d69a4472a0bb3d2fa1cf5192a102bf22a5025e36311da022ecd6f6c931fcc4f47a679ca94dcb8ebdb498a82e0136d2cc86090887649bc83714cb89c4965b658", 1666667 * COIN }, {"0438b93fe0347ebc38318783d4ef8c4c84627c980553ed50313f7093c293e05a3d08c4c0bccb41966390ca9be444dc72795ceda28070f9ed89b879974cf41195b8", 1666667 * COIN }, {"04d5ba3fdddb1f04bc4e42b69b0f5b72faada6c48c24c6735ff4d301033a4d867971c1e01849d3ce64922f7c716831778f6055fb2f54151226056bd31c8759f4ac", 1666667 * COIN }, {"04032c0014597ae5a48fb6b77b985d0d217a341986135fae91cf30ea9484c509b4608bdc72f6e131edf2fa7d3022271f2eb7362bed4c2d5cfd7b36f7da8116895e", 1666667 * COIN }, {"04f1d5bd0e9c7953107df326143140f84c4d45a8ceb847254cff8bb0830591f6ba87ede11f396f51c4b665a000edc1fd2f49fb20b0afe3e1e04d8056d13d3f2554", 1666667 * COIN }, {"042f776880d5ea125399dc8e697fa1ac203a43b232f4d60edf7b7d77943b4e7e85fed6a90760ab6ec0d10645a1fac0154408c15fdc35d35bf79dbdebe6d2d8540d", 1666667 * COIN }, {"0409995500ed6a2c260df55e5f6aec31601de7c655c653268ceff294f688294938e1b769d1a6327a437581fca4816e6edde483e511aec23fd988a4ad39fe7b5b61", 1666667 * COIN }, {"0471291d82a5776b50a4d0b9e7e3d22d7b266e426eea1521d36d97f4f3a11bfb2a688a7a19520d7345815881771d8a5e018b231fd266d2ad7f7647e4776e9775fc", 1666667 * COIN }, {"041e714e9584c384d41dc92ddf844e6841384d9ffc61a61ef81909bc4f99c15945d15d604f8a5d57bbbc99ffda4bff4e71d88e0a699458f359808529cd63698d10", 1666667 * COIN }, {"04ea91faf4063d8e30c48d3cd9b3f016b02b986a6ff46ae4f401f81e4127220012d2a52fccaa517affcae2f577d50f5f07fcfe5d339b5aacdae30b87291295f82f", 1666667 * COIN }, {"044ab940689808008d5272831375aef5d3ced38dea774009483f80cb9a842e0f53641999903929fc7838752acd33cc5d223fde5d64bbcd756f36d961ce784e2752", 1666667 * COIN }, {"04e876e52deaef9f11bc148414518e8cae3ed5332ef0b7d91e36b3dca690d5b1fe924ddbfb7e665c0cd8743ae524812139e942a063e4ffe72bb0c1a59b9c6cfb5b", 1666667 * COIN }, {"04ecffaab3ebffad6949f07b0312274f87ca93e86ec8c6545066ad00b298a993dc82afaab292641755ae5f5caf0656af8c1fe0d7f4d3802d7c8a475b89a4d35f48", 1666667 * COIN }, {"046bcc2af214ab28d37ec25bf09fc2e632b745acce4a77ed7fb1e1b54ddfca234d8d26d27dcacefce15ac3cc93956ceb19e2e8159a8dea7ab441590f568d40d74a", 1666667 * COIN }, {"04cabcf4475a7cbf05bc13524b9c6b42dd2a458e7034d1cc8a0f7063038dbcbf5c4cdf2c906c125abd4e28656c8f1b1c6c82b96971f2eb49a46d459fc0459ae6a7", 1666667 * COIN }, {"046bbf04ea449dd0d6e9fe731a7214b603a7f601ca91152d88960a62e9889755d221acbd1de3f91f2c2ff707ffe50538cbd902d379556a25379b3b4574f0f6a031", 1666667 * COIN }, {"04602e93fcca55c4f5e2d021b051f7e2ff86a9cf738e5a88d630d5500a533a6c048f38e9956ae3f670fff07ed0d8c667ab52014e2fa3aef62b02d5febb51ca2987", 1666667 * COIN }, {"0474d15f8cf6a9a4ea6fab8dfd32b721441c773c49d98c486c9673094f3b51ad63dca4b9bc8ae56e21c888cc1a2804759db193ff654f54fb808610481b9737476b", 1666667 * COIN }, {"04b52da018bf2e7d9d9a0259f6ab28ba1148d76b3acb54d8a37ae618bda48c82f17a69db9f053f1f4e81d38c1ac3991a7126d96f4f173a0fcd06d66bc19a8707a8", 1666667 * COIN }, {"0429bc34c08a5003132c276036f48e633e9b7cc969b74ba05d37dc074c75b1bfac09fe9ad51d6031a5f572d7747a2246bac0b54a1f2d492e2eab56564a8f67b3dc", 1666667 * COIN }, {"04bd7df56c56b45dee823dd6e2b93aee20b57425f9d02b42d805a9e2b9321d5e443618a44d0fc6a92ce55775aec71825161e0363e3cae1ef0d7f055d6e55ed5a69", 1666667 * COIN }, {"040af06631069eea6657c88d5a2c9d9edc32c098d2e3d352d23dbd7f1b668b7563595d8e037423369f2d5fc51c9d8daefe85647de0a9e4d284295b80f246755ffb", 1666667 * COIN }, {"04d1a5fe8b962d0ade706e47eb44c927d48c57c8c48855c95f9c9500cba3dcf60353244a0a3150d49d062eaa27c306e16b42b353b7648f548c89fcf41a8a3b6567", 1666667 * COIN }, {"04c905937e8f69138bfbede6ce46a1aa4492599d5dac037c7bd3a024bb3547b799bd490ea4d6738607c6108bb4a173ae421b897fd68a178397c7ea97bd89afeeb4", 1666667 * COIN }, {"041cc88a67faed67658ca148a1a8524da76ac5c99dadd1ba1d26de9d79a743ef8e98ace8e726b9e4e393e6ba9a77908cb7bd3ab69dcb07b6b00bcbddfe7521706f", 1666667 * COIN }, {"04a37b01922e442f417d6b663ebff4efabba49a7da838d8de279a07bdb0d888df277de399b51a79f47941a2b16e32204c7020b1786f0ef89ebd418dca22d21a410", 1666667 * COIN }, {"04e1d083721f5af5491808430d3b9b6ed5300bfd12772d6e7916656d0347494257cd8d4d5c0107b75ea992e7374e84ea7d9f8ac7a93ca05fb85644b6269c472255", 1666667 * COIN }, {"049a53cf2d990f738e1b6cc4161d66dee8e2f1c0f9cad695bf2ed93356bd3e3acf81ff2d30cef1c2e31fee406e290f72c7b59f3ac4d00b523722c40f9afbb504c0", 1666667 * COIN }, {"04bad04e17fa00b4538a535e1290e49829695cfb0864ffe1b9e8d0a68027cac9db5c12a074688c78f542e350773e1189ac5bc5e93310578bda7ccda48f4e10cf70", 1666667 * COIN }, {"047d9308689098a2b2b9a474392f687c0bcb4c169163d5b6a73257a59396cbdaeee261dd768c21d9769956f62612e81aa62558ac984c5b344e189ad9fe91ea77e5", 1666667 * COIN }, {"04cb128e211884157048e9941ac9a5af60d271494348c1187ed2fa695ebdfab5b0f641d6eccf27cf46fc8a296a02abd639a80851fffbf66f9db5f7c6bfd9f12ce5", 1666667 * COIN }, {"047b743ec9a7388245b1c649420acb1b98bd24105139b6bf27a046e26b257e020d1c57886fe5eb0dd923d7d52d46bf16f3a2828f622c030ebdb90096e1c57fe3b4", 1666667 * COIN }, {"047014cb81e19aec545ad464d5ea126b3d0b57b7730e3a16eb0daadef5e45a6fb843290e81fd6f6cb84a3340ea0770d17260bcef4210ce58b35eee3ad852dbcf76", 1666667 * COIN }, {"04bb5bae04718c380f352ab1faabd46de91cb65bae79cccf2ab05c419fdf8c803c59f370d4e34d510282a6b10260e4cfd286923c92a95d9ce739f1cbd830a79f59", 1666667 * COIN }, {"048809d128ef82b246d3bc2ca882f4c0f4b4d5be8666e1bc94cb8c00c71f82104836e62784112a6272ab57dd7954a199171c7f20330f13b445173fd6898b4eecf7", 1666667 * COIN }, {"04b5af2ade6281917774cd1a66b91f9cf6b2104c3350c328b9d6b248aa6be8218a78b72e224f567af38e872599ca5099a0c691f7209660debebc72731f3745a141", 1666667 * COIN }, {"04a6433660e87d12428a696c001c9d6fe169a7fde37488cc55b9f0ef8f729f735e271927b8765a5e968990605ea2511dc97f9a6636992c44857edbeb0af33cdf1b", 1666667 * COIN }, {"0413c4404c83c3b036234ea4041331902577dc25158075cd74b4c9cc546fbe0efecdc1d376dc6e5ab34f788cf3b2ed499951b5dc43a1fe98ac000cfd6d658796ac", 1666667 * COIN }, {"04540c08dcf4ec041efb4a3ab43bc7738cfc3d779418237b0217fc15d4361b23128e2cba52c76189018f84e7ae3dc6e1f74d520d076fe70f6f0fe45ccc1020dc45", 1666667 * COIN }, {"0498449fa857b6a1f0e2c22d80d7ea483a0b18f98217574efb9c9487287c0e90e6687b98fc28857455d8e942f4c2cd4e8fbd8e0c69655c77b5664ed267a78e8e53", 1666667 * COIN }, {"044ae9989d0fd3b651bab196c4560d53d6c32cc951f0ca2163ec00fb6d53444acb3bf1748943ef4ded4e125a8db3e5de25596242ab9f6f90fd5c8b6a7e97215acc", 1666667 * COIN }, {"04a735dd8ae66c9f1b5f75057b8fa1490c803a49808197b93f201e116c8682b3ffe3af48ffd224ed331124a6fb6d207ae8918e424b0d4b55e10254ba8780fe522a", 1666667 * COIN }, {"049cdd6179d25eb9c0922f8554362ca9150cccfde19506e5473109f57df495308186c9352f028b23e1bce4ded074d4f728d6fd059aa5c9d2e63077df0b57071b1b", 1666667 * COIN }, {"04b5d959e7af7c1dd287c1ebaeb134a127ed7b3f4e2567f4b6a32a786fbcadfb709ca829fd34286cc8d23422f337fb4cc26b435b8364265fd62633353893d281e4", 1666667 * COIN }, {"04c39f78f12a45580914b9cbad2845ecb5e194a7d1e9f35279b7a49ee3a87d331a3292a3b62210a1de7ef584212378a299152aee2dc6ddf8dbf1da2921f85c2e27", 1666667 * COIN }, {"04a9a102de2185216bb903240d57cfa622a55c51caac459e25b64b8b02224c76d94a8c4cf639747b5b3c84188795726ebed67774988999aba8741afb2e39c23b4f", 1666667 * COIN }, {"04cd0b9d19dea95e448b0e8fa6b9bb9dbd065b5350e85f46392e84932c65c1718209d77dcbac605bf537375ef7a240f0a1051e5668bf48ae2fb272ac3c26693d9a", 1666667 * COIN }, {"04b7827109e2ef3ed258f80a3f532d4ab810ef0db1ee2ede40e198ad1758f43cc6fc9c1d501087cc1e147e12f42bdf02be4747aff6d5fcd3d520463ab0e1e81c6c", 1666667 * COIN }, {"048192dda92b8ea520eae7b5c4f243cf0941ad79f0d5783d66797b6a49f5bb82144128786aa9e3c2ac459023789e2d3fec93604afe81603cb5f90dad3344b24eeb", 1666667 * COIN }, {"04ba6246996a413e090991ddd5c3d58dccd2ba3fbb0af8f670f69e1aab1f6ef48b6825df4aedda90e0e4fd8cae0429c95443124759f7a7dac387bf091d50d5a014", 1666667 * COIN }, {"0467eb0db208a4b52d388725728e69df2488e330ebca2dd25f7948e6f0a72b7ab2d11425e4239d0da0d7c0d27fbf4cdd23d7f6779600843f1e944c9856910f712b", 1666667 * COIN }, {"046fe9572ad27f9efdf34ba49bbf6937c4043de409b6bbe4eca782d35155b2cc81014e90b4a7ee075b95cf939c3e67aa7630de683ca72b615142439e6e723d0a30", 1666667 * COIN }, {"04c8eda631842b1e102c6b8088200596ec005740008e18cdb195081274731495599a123fbd1f9d0af87d6097e8da1276eb8b496038e203550785403b54a15e92a7", 1666667 * COIN }, {"04796f42cc8664dd42efd5fcffd23af4e25b71bec37885e87f636660a7ab7238de4a0d9a84c1b96d4800edcbfef888365d91789bbb0a74c7a4c1bfb7143be04d9a", 1666667 * COIN }, {"042d96912af92efbb904ffaae402e56cfd5148df4e544c8722a6c57450d481aca7adce1eeab247a2f951d117938f17ff1f42fffdf75ca3cf1a4c69e384628173d4", 1666667 * COIN }, {"0431e5ce3bc721ccf6c57ee29ac880ddaa53dc57fe8aa4a615ca4a183b49ac6460f2186df357fbf7862e11baae166a4ad56131378b9c1591db50b23a06e199fac6", 1666667 * COIN }, {"042ce5c1076f347454ebf85665a212bfad46c3a3689a86a372bd84b05edabfdfded62774db64b7c79a094a096ce81b845cfb6bb390d59327b2ca7ea5bb3963c767", 1666667 * COIN }, {"04cebaf0846e6a9f91a82c00fa2210c99cdb9fe227f84cc6061d5a5854f1bba939da2054f972b1b65dc959d96030f34b241d2a54457af20d8c72e2854b24489600", 1666667 * COIN }, {"045c958ed7c42d8c8b7ed792b5967ca529329b35ca831b6d45f4e16eccf857dd11e3f73b4e83ae577ccf7255deec520bf9f033e52e6455fb5ae2cab41938b73101", 1666667 * COIN }, {"040bb6d43c2dc555755f730c74a6cb6cca7d0ddba680c387389b80518424e38a1cb26d00f80bd6218d6aef51c1e520ecc81d7cd1fa5efe9f1925da1048e424d484", 1666667 * COIN }, {"04af1df572d2fea88e7dab80b4e03997f6db524ebea183ef4020129be753cbf3580a33aa08b7d4d7763643086490e609dad212b97c73876769e21522560fd886f7", 1600000 * COIN }, {"045be52e68147b0c45258c471aae0a5fa16a6283ee1ba1fee2e4a124c636d6f5f1ed47264214a9d742764d5f78599c2a9a6158d09f62f3b8ee049b1f1d10a9a375", 1600000 * COIN }, {"04147ff09603087323ec59cf6286144d2c1a51a59189d7a254f5a66bc4b4e0ae770c69e1be8536b0d1454ce131f7fca6342aefd32a2277c37c0ec05f9c846b5fd8", 1333333 * COIN }, {"04ab533eb7fd7143685e80e37b6f671522af44db6f2b0ec0374f6c3c47d6230a301d3a0cb8417e7762e20b39857bf499a62b89ed56259c078c4182d3e849906d93", 1250000 * COIN }, {"04f8cc12ceee9ee2d4a8e47e16e0b3871b8ff79155fafcb04e94b245f0e5c3a8b7fadb97fc7c17105d215b67445835b3ea4cb5d52d379b7d4566e58c48ad446bcb", 1225600 * COIN }, {"045aa52be87d1f08a2a1da158aefb0f6c3fdcb0fe8219f01227852e153b4c61583aef0f3fb886adb0285a8e77268470b8f05173c37ca24d8801e547f7f0a9d0d65", 1200000 * COIN }, {"04e754a08b396f97df6297ff3d29834e6a7b0cedf786e2419a6009bbbfd8d0c3d6b9b1d358cdf393f3e988de33052b285699afc17fbd689d38ca3e4dfb1c5d58fd", 1166667 * COIN }, {"048cd64435e4dc234206c2999a9fa3076ca4c9ac1ac3d3db7048c728b40e92effc427b28ccc8bbae422bba4b11e3be75222bcf25f1acf45f6a61673a8a361d18eb", 833333 * COIN }, {"04552848ffce509eadbf125c0319551f3f917620cdfeb2cb8c9e98e074497c1a7e22fc9494542890b76cb77cf8484e2768930f040c6328ef69d973aa00c957819b", 833333 * COIN }, {"042357cb2bca3d858da9204b5eac5a975d9959aa1a798fc219fb225be78251f9bc6962a93ec003529ba1f5458662be22dfad7a023747c21f11a7ebf6fe2c0782ed", 833333 * COIN }, {"041992ffa034c969680ae019f111ef342f386529ff789ccd9117dec47fa6dca1347b04d78f605d1d1d47f6581020e633bc0b24db445c0372dc519d2077b267d758", 833333 * COIN }, {"04d09e628ff7b1f72dc5ce1acaa07ab726dbe157bd4dd4b444694e99cc43ad666b6cf68f8e3910e7ed8da87dac874d499387d8ab456597fd6c4cf23aeaaade4de8", 833333 * COIN }, {"0466c6813b9635d1419475b8d00b190fb08cc7cde49caf658b1f450751e78ed9411d1b2b4e86865e2af98b207004fcccbd06b929187126c72d1fe8bfc8941c099a", 833333 * COIN }, {"04e1dd25aad0c816245fd9c2244a620d642206be5cd8f13e157a2298df92ce6a92bada0c3f8da395d278423b42bc970f3cbdec708c9b5869a8e84e8cbd96a14a19", 833333 * COIN }, {"047cc06a08a45383d171a2a051023ad1cf7c9df72878acc88d57c771d1d0a61265a194a20a2bc208116908a71c8c467594a4a42004b170309e0cd72762f4b57f50", 833333 * COIN }, {"04dd67067763e8eac8f065ca368d0410a12db9eb91efc8ff8b823ce2f2c58f9c289e616f58f26ab98eaeded93c7fcb3d440c1fef9a4c438f6c497b8433f9bbdf49", 800000 * COIN }, {"04aaedcce553ce2bc68dc91f80ef4dcd37ca70d2d38393b8ffe57d3289f353bc90f6388bb10e11297f2780356d2642908d522bd36155bd37532115bf05c98d514f", 666667 * COIN }, {"0469e621c9a21ff44858b24f104c364cf4d48dd1b647b01d343f6548a74dec738742d6308e030fe715166011db565e699e0e1afb7078deb7db4874b8e65438934c", 500000 * COIN }, {"04d1ef08c2650a8e6bf3cc89f8efbfcec07c812203feec935ab4be7dccc5133ec824014fd4672609bdb892ee875899b563182986718212410e827c1566f22c91dc", 416667 * COIN }, {"04f37086b18f1857415ec537f692d83a476e62fd77666026514498eed169ea6839b4edb713cb43c4b61fb6947dce3d089093790d4cffe7c0abc4c12877efc5a3e2", 405600 * COIN }, {"04573de32b309a785054a31dfe7c8d6bef2bef3909b99d51b7ea54f6658b35f87ae52cd94cb971bc9409c1af66e8413f2c4908cbf716f6e5c3f584075d4461408b", 333333 * COIN }, {"04ba43007105600b30dcb46093c4d7d4ae48cefbed776f7f4c76b3c55113b1c8ca829d29d05e4913b65f48c711b3ccff44d47b7515c45cf807fca66b3863e7d1f5", 250000 * COIN }, {"04df2e99120d69a46ec0f5303e0c94c979e369457aef53e0e30e5c12ef0f81a305fcb7f0e84f4eabf2ae5dc33022cdd815f88e0ea6348a7a37175f05e7fa1f7693", 216667 * COIN }, {"04a2eaa6ec6c544a8c957fc66728abe607968c3a362cff07943a11af04c92ba1a66875757bb1718987f4e4e223c811f22afb72e1909989b09aca14a6ed86eba541", 202800 * COIN }, {"04be2e6be9f36587ace2ca8b6febbd6727b92c69e1f181d075e403854ca250d39bf9bf94795928cfe36e11821dd7a0194fdcc22f3734d68dffab3c0486a621dc10", 40000 * COIN }, {"043078081ebbbbe45a1e5748aee0e96abdc4d21bf60a2e44e855e7f66a7052ee1826633667637b176e55691d9c87539acaff13bd245a281a2d3fb1f54a243bab15", 40000 * COIN }, {"04b7c7653ad1b354aca2c9298d0837eefec2cc84535588a4635a2984075e90ee060b2b2fd64587027b8b791c86345c07d2cdf21ea2555f89d5bc629d6ca94a34d3", 20000 * COIN }, {"0437975e0401a75a6c28a5933ce5b4b0f41208601b51f695ca3b3b29dfb0d0268b59ce2afa1b45dc895ec349deea8b14b3b6160c45f778ce9409bbef8c4ef2c07c", 1666667 * COIN }, {"041b2dbaa54c1d189d7379ee27a688e7dcb3fe07bedd624c2f9b5ba0dfeccc63056fd741bd1b4e1bed0095170cf87b313e18c6be8fb2f97993f5ddab3da37ea3e4", 1666667 * COIN }, {"04311286c7cc1d8ea24d74715d5767e806ff4a191d3a7562bc7733c85dd81cf6b2afa8770b0381957d44a82c5872650c16ba4092062eb05adf61fd733a3fb8eb48", 1666667 * COIN }, {"04a02bd704ff1b781448fc5ed1d007ad87d5839bedfffa1f2c536617ebf6afc60a3039ff1b344edeb1c4c035987bf243cc38843fbc06b0781938de96395460b310", 800000 * COIN }, {"0485d057b1448c11c9e17215ee340c0751d1922be4eebb6e3c7cb086e84f42f2d612df64343e1bf5415efcc529794747ba9fa4d65e5a14e294651d4349284f4dfa", 1666667 * COIN }, {"04c3799117635d1e5feb60834dc0ed7fc8e35232e453f4aebdc8d3c47ef7f028f22e15c91e9f561fc6c37617d5cc56defc2915f9fa89735325003f27493bc495e9", 1666667 * COIN }, {"0495cd06bd00bd67ec58a4fd9258ec13624b852d94181a394e15f4c48377724ccfc46e8c31f631486d1e82dafe3f59981e66788d5dc01a0edad334481a1af9052d", 1600000 * COIN }, {"046b54c2dc6b135af684986cafe01ab02d070afaa849814e66de73afa39a94103e966e687067eabeb70c5a5b198ddbba92484a6aedc3b9cf08e08a943b636dcad5", 1666667 * COIN }, {"0460b6d050d14f0dfcc5698cc68c4b87be1c9d2a482aa63808edd81afe95b225e525e7e436c474c7cff23628b1f122af75ddd6ad1eb2238b1381d036c951ee3c9f", 833333 * COIN }, {"040a74dfc7941fd76ed051c2c228b892868e9fff8bb2b64267def7aeb039ad906bc37516858a473f0e8b3f2c36cfc00636bc71956279d4db8843b11ad16deea945", 1666667 * COIN }, {"04c022db135361693f5f377ab77dcf4453c53586cea3ab121985d1837c4fc94b44528231fa6cc8de16c9640c68ec8bd5eec32f6386664c5df297fb2e98fb4d924f", 1666667 * COIN }, {"04488f811cb767333211db1605ecc1a45f54c7f5e1b2286e014f7d6c05033f55d1a76d103ab19f6142da3e41fa4a3cfbbf93219836b5ccacc72cb93e7944e93fc4", 1666667 * COIN }, {"04969bb5b4e33d24069f20ce91f64bf357c5cde3133760d5d4695cac7cf452440c1ffea2221b4b72ab3a6ad3d5ad19a6a72cb2f086061b8fd50e520c57c80f6aaf", 1666667 * COIN }, {"046010a37d25367f77ef840d1f370ed9de505d64cd20118a369a878a08359b7e79d30c18133afaa4e7fc48b5e296335ce1368e458535302c20d5f40ef47f02891c", 1666667 * COIN }, {"048e6e7d7117594495e8a3aa8889cc73279cd83d3c4b67462745b03f536e13a498b07ae70588fe75260d8ae0018dee625bdef33616b917c600074a17bb36e69e67", 1666667 * COIN }, {"04a0951c55ee0a1328395f3012ee7421a516a752e9695bd1d10519cc275d7f5474dc9a812e1333ad6bac865e053605bffb8c6d88e54b2f14bedc25d131d8e1d495", 833333 * COIN }, {"04ccde9c642780f08ed5645ad2fe4948da0eab3b8bce3ee962fc58686b1867aed0ff7bff78084964268b3d0d33af3d6c64dd759161e914006b26618fcf96c95a97", 1666667 * COIN }, {"04426a9af4bca0256f8cdad391f1e596a82dd6300c8ad83ac0db31ef32079e022afe84fd7b4988cc9a929595944921d3406c1ea3934d48eb76bd1719cf3fab7c31", 1666667 * COIN }, {"0484829f87595fc4295ffc501915d581057f20a7a7ec5816c4648347820cbb1c3543876b777761ec38be472b573110b7765eda9c8a5223fa87a491d919c6049c95", 1666667 * COIN }, {"04c42ec92e3e671533e13721b8b86be9bf017057c170ad98f00c2d0d05958aed85f789942ca0cac8ce08bb242bbaede5a301d8fc419aab551acd9d0a2a66004bf5", 1666667 * COIN }, {"0416fe8b4ff48748deb725ec4c2096837a1e945f53f5ef0c6c751804f9fc72e3dd6421815642ac5e2652c839021a9a653997c9cd427ff3df5f9d2a45cda0aef8ec", 1666667 * COIN }, {"041c18c3dd398989f4b46631320f1fa2f5f538e8fe6f773e4d0f442e7c512a351ba242768b5d67529703368041d8b23de5622ae223f705dc91ad5c2381cddf4a58", 1666667 * COIN }, {"049da55c86e6ffc06ec2c9440946d07659b92e079dbe69dda2875cc0a16302bbd64c7c98d8bad5b2e132f1fbe2246b11adcdbe3d678373af8b756d5c70ff0b0db7", 811200 * COIN }, {"04c325abf2381a1ae9ff3643b9ae1d12ac0fd0283cf0254738a4047d449959f0e6601a083b2d6f24dbfaf47169d1711c5b735b53ab498cc2acef165fe3d5a39087", 1666667 * COIN }, {"04ed232f93f9b748fd50b99dd5029290cb4219718cf86d7f9a65c75a0e94818e64699850c7bf7dcd108719f220eb9b7b559faa30faf02f7fb8cf07628a9dc23940", 1666667 * COIN }, {"04089d9188ad48b592ad1bf782c0f0fa929614e4394f06196d7a29c1279aa5d68d5804bb6a6126b121280aecb934953528bcd8cb430c2cea586b9442c1fd052d80", 1666667 * COIN }, {"0422f677fc7b6776990ab3d2c4e9c6d48b213fa438508ff10996958bc6d2e1944c7a6e8b7feac536c6862baf2c89c678da74dfe8ae99a2fc0e3a4d8d893e1c4115", 213333 * COIN }, {"045f3d6cbf30137ef3ad2fcc704916f013b0a96179fb50f51a8bd8ccaa7418304ce12774c9dd84034530c6b3b8c2ca64725d3673156a5900324ece060c5d878218", 1600000 * COIN }, {"0452cdc06c5ac4b27fc7a9a4449a32fdec51263e45c99888aa7b91a837587b250c5c7cb3633512ce7346582d888d766390332d91f518c429d6552203de917e3767", 1666667 * COIN }, {"040941c4c3d6c4453e02452ac2137551b58301f3541b3122d91c1e649a91f55af857ba1332f82767e50a400fb2ccc997df7b9e98bab80f9cd8dea235dd06e3bc4e", 1666667 * COIN }, {"0413c7619ec192b5e8eb0b368a60c7bd4a66ba3d15dcb4c103595187d26666439e8e47127522b7084edce5d0516dc2da9c202e91a973c9368893c18acd1a9ee55b", 833336 * COIN }, {"0475d26fcbbb4352d0eedf46ec3ab012afd35e45c570682a14b837bd06ca441bf0ea47e5888dfe5d5ac8e659449c321b4860e79a78fe42ccbb6007bd26b570609a", 1666667 * COIN }, {"042db9023941b1a0112321d636c0f4f50d3f499a397c77f4641b1c3f3db4683c41f0dde45f3bbdcd444d37c07cdb471a00c2b58bab290d3a430bde52648cf7fb2c", 800000 * COIN }, {"042190c9fd737eed0ec667fef9b3e1267f33be59c86fa849ac34f8789f8d9b9c07062e983fefae2e0b92eda2fb0e4fa7619baee7de0e625b6bd3e5d8d5da0ac630", 1666667 * COIN }, {"0445e590c3f7c7d5d49b0c396dd13a206ea1efa9ec478fca4efb97eb6ee6be6e5043ea7262a7d37dbd14793608e8b51f7f9b689328480d88f5874a48c728964b74", 1666667 * COIN }, {"04467e1cbb1e1626df78b0e133a279dfc9892cd6f41951dbfe72711209068bbeb44da2a63f4c9d496e365a91c285cad610de3eb0805e80907244a9f072b06526b9", 1666667 * COIN }, {"04ff9957fe86d8b2be08c6265c6e92dc3c2c7bb4e10d78c70584a90c93cf06fbebc4a393dcad6dd55ea2d92cdda9e475770ca35532f496e0958bf2da7cf8261e44", 1666667 * COIN }, {"0405b0ba12928a01ee4637247981efb9f9646e1bda12c0414055049c90b1497de52664b16a1a44e181cc06d06984fccc93fb8592814baa6632257905850019e68b", 1666667 * COIN }, {"0478cd3031ec5bc63c73fe7f8f74028cfd11aefb88c5174b2802ae69f2b4b19d909b299db8cfbfbd5c801f04fb2b1c35b13d1cdaa2b763a64e9fb65c84ba61ec86", 1666667 * COIN }, {"04d923072742fb976b4a6b443b14003d93465cd6fa9c4b254977adf9e50aed5b740b12cc4fbbf7e6f7487fca4cf449c47db10cf34b23c31fcdcb02e8db1cbad265", 1666667 * COIN }, {"040a565f12c0371eaa9ea7775bb2775606059fe9ac5780c447da40962e02b1cde73bd78533424320ed2de9137e53bd5d5b48ef953537d4cb76631338e6f7fd3b38", 1666667 * COIN }, {"04043f55c28c79edd6d856360af220586ee78c717ab2dc479f5cb25f0d1eb2dff348612b2274ab0b90dae01e4f2ff1d8b14c72cf386f4b209cd49a00c2d6b52300", 1666667 * COIN }, {"044c2f84097f7aeb39d18ecf02a58b6ff84eead9ac2e4f19e8b242b90b18be63548b09394dafa06b1682d29b6abfbf4ffa3c3ab7d42da8822e77e43335f94026cb", 1666667 * COIN }, {"045145690c9fe5fb1a9bfe700edf8eada830a4a0aa6b6830302632dbce3688a3bf5bf5166a3eb80da4ecc2ea4f7f101a81780e9795ecea18275f1ba41033a44c45", 1666667 * COIN } }; #define ARRAY_PREALLOC_SIZE(arr) (sizeof(arr) / sizeof((arr)[0])) double CoinFromAmount(const CAmount& amount) { return (double)amount / (double)COIN; } static CBlock CreatePreAllocGenesisBlock(uint32_t nTime, uint32_t nNonce, uint32_t nBits, int32_t nVersion) { const char* pszTimestamp = "The Source BlockChain, a leading economic collaboration platform."; CAmount amBaseAlloc = GENESIS_BASE_ALLOC * COIN; //巨额基础预分配 CAmount amTotalBatchAlloc = 0 * COIN; //小额批量预分配 总量 //计算小额批量预分配 总量 for(int i = 0; i <ARRAY_PREALLOC_SIZE(arrPreAlloc); i++) { amTotalBatchAlloc += arrPreAlloc[i].amAlloc; } assert(amTotalBatchAlloc < amBaseAlloc * 0.83); //小额批量预分配 总量, 不超过 Base 的70% assert(ARRAY_PREALLOC_SIZE(arrPreAlloc)); //巨额基础预分配, 扣除小额批量预分配 CMutableTransaction txNew; txNew.nVersion = 1; txNew.vin.resize(1); txNew.vout.resize(1+ARRAY_PREALLOC_SIZE(arrPreAlloc)); txNew.vin[0].scriptSig = CScript() << 486604799 << CScriptNum(4) << std::vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); txNew.vout[0].nValue = amBaseAlloc - amTotalBatchAlloc; txNew.vout[0].scriptPubKey = CScript() << ParseHex(BASE_ALLOC_ADDR) << OP_CHECKSIG; //小额批量预分配 for(int i = 0; i <ARRAY_PREALLOC_SIZE(arrPreAlloc); i++) { txNew.vout[i+1].nValue = arrPreAlloc[i].amAlloc; txNew.vout[i+1].scriptPubKey = CScript() << ParseHex(arrPreAlloc[i].ptrScriptPubKey) << OP_CHECKSIG; } CBlock genesis; genesis.nTime = nTime; genesis.nBits = nBits; genesis.nNonce = nNonce; genesis.nVersion = nVersion; genesis.hashPrevBlock.SetNull(); genesis.vtx.push_back(MakeTransactionRef(std::move(txNew))); genesis.hashMerkleRoot = BlockMerkleRoot(genesis); // fprintf(stderr, "%s %d|genesis create ok|amBaseAlloc=%f|amTotalBatchAlloc=%f|batAllocPercent=%f%%|BatchSize=%d|\n", __FILE__, __LINE__, // CoinFromAmount(amBaseAlloc), CoinFromAmount(amTotalBatchAlloc), CoinFromAmount(amTotalBatchAlloc)/CoinFromAmount(amBaseAlloc) *100.0, ARRAY_PREALLOC_SIZE(arrPreAlloc)); return genesis; } /** * Build the genesis block. Note that the output of its generation * transaction cannot be spent since it did not originally exist in the * database. * * CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1) * CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0) * CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73) * CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B) * vMerkleTree: 4a5e1e */ static CBlock CreateGenesisBlock(uint32_t nTime, uint32_t nNonce, uint32_t nBits, int32_t nVersion, const CAmount& genesisReward) { const char* pszTimestamp = "The Source BlockChain, a leading economic collaboration platform."; const CScript genesisOutputScript = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG; return CreateGenesisBlock(pszTimestamp, genesisOutputScript, nTime, nNonce, nBits, nVersion, genesisReward); } void CChainParams::UpdateVersionBitsParameters(Consensus::DeploymentPos d, int64_t nStartTime, int64_t nTimeout) { consensus.vDeployments[d].nStartTime = nStartTime; consensus.vDeployments[d].nTimeout = nTimeout; } /** * Main network */ /** * What makes a good checkpoint block? * + Is surrounded by blocks with reasonable timestamps * (no blocks before with a timestamp after, none after with * timestamp before) * + Contains no strange transactions */ class CMainParams : public CChainParams { public: CMainParams() { strNetworkID = "main"; consensus.nSubsidyHalvingInterval = 210000; consensus.BIP34Height = 227931; consensus.BIP34Hash = uint256S("0x000000000000024b89b42a942fe0d9fea3bb44ab7bd1b19115dd6a759c0808b8"); consensus.BIP65Height = 388381; // 000000000000000004c2b624ed5d7756c508d90fd0da2c7c679febfa6c4735f0 consensus.BIP66Height = 363725; // 00000000000000000379eaa19dce8c9b722d46ae6a57c2f1a988119488b50931 consensus.powLimit = uint256S("0000000fffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); consensus.nPowTargetTimespan = 14 * 24 * 60 * 60; // two weeks consensus.nPowTargetSpacing = 10 * 60; consensus.fPowAllowMinDifficultyBlocks = true; consensus.fPowNoRetargeting = false; consensus.nRuleChangeActivationThreshold = 1916; // 95% of 2016 consensus.nMinerConfirmationWindow = 2016; // nPowTargetTimespan / nPowTargetSpacing consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28; consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 1199145601; // January 1, 2008 consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 1230767999; // December 31, 2008 // Deployment of BIP68, BIP112, and BIP113. consensus.vDeployments[Consensus::DEPLOYMENT_CSV].bit = 0; consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 1462060800; // May 1st, 2016 consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = 1493596800; // May 1st, 2017 // Deployment of SegWit (BIP141, BIP143, and BIP147) consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].bit = 1; consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nStartTime = 1479168000; // November 15th, 2016. consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout = 1510704000; // November 15th, 2017. // The best chain should have at least this much work. consensus.nMinimumChainWork = uint256S("0x0000000000000000000000000000000000000000000000000000000000000010"); // By default assume that the signatures in ancestors of this block are valid. consensus.defaultAssumeValid = uint256S("0x0000000000000000003b9ce759c2a087d52abc4266f8f4ebd6d768b89defa50a"); //477890 /** * The message start string is designed to be unlikely to occur in normal data. * The characters are rarely used upper ASCII, not valid as UTF-8, and produce * a large 32-bit integer with any alignment. */ pchMessageStart[0] = 0xf9; pchMessageStart[1] = 0xbe; pchMessageStart[2] = 0xb4; pchMessageStart[3] = 0x02; nDefaultPort = 10666; nPruneAfterHeight = 100000; genesis = CreatePreAllocGenesisBlock(1516796486, 2018867506, 0x1d0fffff, 1); consensus.hashGenesisBlock = genesis.GetHash(); std::string strTmp = consensus.hashGenesisBlock.GetHex(); assert(consensus.hashGenesisBlock == uint256S("0x00000006941e463cf1cb6c74024228810dc81545c854ba5153b117d3bf602204")); strTmp = genesis.hashMerkleRoot.GetHex(); assert(genesis.hashMerkleRoot == uint256S("0x7b3e8f0a5371086cf000d11b5e6bd1f8779980af855623b6eb28c4d63d3b12a4")); vFixedSeeds.clear(); vSeeds.clear(); // Note that of those with the service bits flag, most only support a subset of possible options vSeeds.emplace_back("seed.hk1.genyuanlian.com", false); // Pieter Wuille, only supports x1, x5, x9, and xd vSeeds.emplace_back("seed.cn1.genyuanlian.com", false); // Matt Corallo, only supports x9 vSeeds.emplace_back("seed.hk1.rSTK.world" , false); // Pieter Wuille, only supports x1, x5, x9, and xd vSeeds.emplace_back("seed.cn1.rSTK.world" , false); // Matt Corallo, only supports x9 base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,0); base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,5); base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,128); base58Prefixes[EXT_PUBLIC_KEY] = {0x04, 0x88, 0xB2, 0x1E}; base58Prefixes[EXT_SECRET_KEY] = {0x04, 0x88, 0xAD, 0xE4}; vFixedSeeds = std::vector<SeedSpec6>(pnSeed6_main, pnSeed6_main + ARRAYLEN(pnSeed6_main)); fDefaultConsistencyChecks = false; fRequireStandard = true; fMineBlocksOnDemand = false; fMiningRequiresPeers = true; checkpointData = (CCheckpointData) { { { 0, uint256S("0x00000006941e463cf1cb6c74024228810dc81545c854ba5153b117d3bf602204")}, { 111, uint256S("0x0000000267a3a12da835680c963702dca940b1302883ea605669ad99881d06d4")}, { 3000, uint256S("0x000000016b6a454f4fef562024d4dbb822d1af76ce48352afc30b6892214394d")}, { 4600, uint256S("0x00000000e55dd5660ea3e64fa0bbcd2550369ac7f04479a3da94a29e44fe19a3")}, { 4642, uint256S("0x000000000ac5cb818dcdcf749e211962ec1effcbd5de83997f85ae9e02c5fa37")}, { 4650, uint256S("0x00000000120a2fdfe68d571f7c3eadaac1c1be8f18f15817e533e43eee32a120")}, { 5000, uint256S("0x00000000aa03beb092ea5ccbe9feac143b423db0795fa57eeb62c0e48ec2e4b7")}, {10000, uint256S("0x00000000f472ad3e5a80baa31a108b5d8de512a6aecea13e11be0e14a821698f")}, {30860, uint256S("0x0000000000c37b62fa7ba0f75c69d11bc9331fe4c6ad73b49deb36b06a256aa9")}, {35700, uint256S("0x00000000000ba7b5ed676ede4fcd685ac931135be9140f2de6eb4bcfc5675283")} } }; chainTxData = ChainTxData{ // Data as of block 000000000000000000d97e53664d17967bd4ee50b23abb92e54a34eb222d15ae (height 478913). 1501801925, // * UNIX timestamp of last known number of transactions 243756039, // * total number of transactions between genesis and that timestamp // (the tx=... number in the SetBestChain debug.log lines) 3.1 // * estimated number of transactions per second after that timestamp }; } }; /** * Testnet (v3) */ class CTestNetParams : public CChainParams { public: CTestNetParams() { strNetworkID = "test"; consensus.nSubsidyHalvingInterval = 210000; consensus.BIP34Height = 21111; consensus.BIP34Hash = uint256S("0x0000000023b3a96d3484e5abb3755c413e7d41500f8e2a5c3f0dd01299cd8ef8"); consensus.BIP65Height = 581885; // 00000000007f6655f22f98e72ed80d8b06dc761d5da09df0fa1dc4be4f861eb6 consensus.BIP66Height = 330776; // 000000002104c8c45e99a8853285a3b592602a3ccde2b832481da85e9e4ba182 consensus.powLimit = uint256S("0000000fffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); consensus.nPowTargetTimespan = 14 * 24 * 60 * 60; // two weeks consensus.nPowTargetSpacing = 10 * 60; consensus.fPowAllowMinDifficultyBlocks = true; consensus.fPowNoRetargeting = false; consensus.nRuleChangeActivationThreshold = 1512; // 75% for testchains consensus.nMinerConfirmationWindow = 2016; // nPowTargetTimespan / nPowTargetSpacing consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28; consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 1199145601; // January 1, 2008 consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 1230767999; // December 31, 2008 // Deployment of BIP68, BIP112, and BIP113. consensus.vDeployments[Consensus::DEPLOYMENT_CSV].bit = 0; consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 1456790400; // March 1st, 2016 consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = 1493596800; // May 1st, 2017 // Deployment of SegWit (BIP141, BIP143, and BIP147) consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].bit = 1; consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nStartTime = 1462060800; // May 1st 2016 consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout = 1493596800; // May 1st 2017 // The best chain should have at least this much work. consensus.nMinimumChainWork = uint256S("0x00000000000000000000000000000000000000000000002830dab7f76dbb7d63"); // By default assume that the signatures in ancestors of this block are valid. consensus.defaultAssumeValid = uint256S("0x0000000002e9e7b00e1f6dc5123a04aad68dd0f0968d8c7aa45f6640795c37b1"); //1135275 pchMessageStart[0] = 0x0b; pchMessageStart[1] = 0x11; pchMessageStart[2] = 0x09; pchMessageStart[3] = 0x02; nDefaultPort = 11666; nPruneAfterHeight = 1000; genesis = CreatePreAllocGenesisBlock(1516796487, 181868167, 0x1d0fffff, 1); consensus.hashGenesisBlock = genesis.GetHash(); std::string strTmp = consensus.hashGenesisBlock.GetHex(); assert(consensus.hashGenesisBlock == uint256S("0x00000007baad30c791cd877799429aa30e7f2a5e55b59a2a7af01ceecc9d7e38")); strTmp = genesis.hashMerkleRoot.GetHex(); assert(genesis.hashMerkleRoot == uint256S("0x7b3e8f0a5371086cf000d11b5e6bd1f8779980af855623b6eb28c4d63d3b12a4")); vFixedSeeds.clear(); vSeeds.clear(); // nodes with support for servicebits filtering should be at the top vSeeds.emplace_back("testnet-seed.srcchain.jonasschnelli.ch", true); vSeeds.emplace_back("seed.tSTK.petertodd.org", true); vSeeds.emplace_back("testnet-seed.bluematt.me", false); base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,111); base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,196); base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,239); base58Prefixes[EXT_PUBLIC_KEY] = {0x04, 0x35, 0x87, 0xCF}; base58Prefixes[EXT_SECRET_KEY] = {0x04, 0x35, 0x83, 0x94}; vFixedSeeds = std::vector<SeedSpec6>(pnSeed6_test, pnSeed6_test + ARRAYLEN(pnSeed6_test)); fDefaultConsistencyChecks = false; fRequireStandard = false; fMineBlocksOnDemand = false; fMiningRequiresPeers = true; checkpointData = (CCheckpointData) { { {0, uint256S("0x00000007baad30c791cd877799429aa30e7f2a5e55b59a2a7af01ceecc9d7e38")}, } }; chainTxData = ChainTxData{ // Data as of block 00000000000001c200b9790dc637d3bb141fe77d155b966ed775b17e109f7c6c (height 1156179) 1501802953, 14706531, 0.15 }; } }; /** * Regression test */ class CRegTestParams : public CChainParams { public: CRegTestParams() { strNetworkID = "regtest"; consensus.nSubsidyHalvingInterval = 150; consensus.BIP34Height = 100000000; // BIP34 has not activated on regtest (far in the future so block v1 are not rejected in tests) consensus.BIP34Hash = uint256(); consensus.BIP65Height = 1351; // BIP65 activated on regtest (Used in rpc activation tests) consensus.BIP66Height = 1251; // BIP66 activated on regtest (Used in rpc activation tests) consensus.powLimit = uint256S("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); consensus.nPowTargetTimespan = 14 * 24 * 60 * 60; // two weeks consensus.nPowTargetSpacing = 10 * 60; consensus.fPowAllowMinDifficultyBlocks = true; consensus.fPowNoRetargeting = true; consensus.nRuleChangeActivationThreshold = 108; // 75% for testchains consensus.nMinerConfirmationWindow = 144; // Faster than normal for regtest (144 instead of 2016) consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28; consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 0; consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 999999999999ULL; consensus.vDeployments[Consensus::DEPLOYMENT_CSV].bit = 0; consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 0; consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = 999999999999ULL; consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].bit = 1; consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nStartTime = 0; consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout = 999999999999ULL; // The best chain should have at least this much work. consensus.nMinimumChainWork = uint256S("0x00"); // By default assume that the signatures in ancestors of this block are valid. consensus.defaultAssumeValid = uint256S("0x00"); pchMessageStart[0] = 0xfa; pchMessageStart[1] = 0xbf; pchMessageStart[2] = 0xb5; pchMessageStart[3] = 0x02; nDefaultPort = 18444; nPruneAfterHeight = 1000; genesis = CreatePreAllocGenesisBlock(1516796486, 379702101, 0x207fffff, 1); consensus.hashGenesisBlock = genesis.GetHash(); std::string strTmp = consensus.hashGenesisBlock.GetHex(); assert(consensus.hashGenesisBlock == uint256S("0x3fbac91e81dfebffa593f51f4dbd11135522af0ef1f20ce74169745eb5a3b5ba")); strTmp = genesis.hashMerkleRoot.GetHex(); assert(genesis.hashMerkleRoot == uint256S("0xf334785fc2b91cf2e2c17cc72171f155acc523acc0d815a759203707716f2e35")); vFixedSeeds.clear(); //!< Regtest mode doesn't have any fixed seeds. vSeeds.clear(); //!< Regtest mode doesn't have any DNS seeds. fDefaultConsistencyChecks = true; fRequireStandard = false; fMineBlocksOnDemand = true; fMiningRequiresPeers = false; checkpointData = (CCheckpointData) { { {0, uint256S("0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206")}, } }; chainTxData = ChainTxData{ 0, 0, 0 }; base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,111); base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,196); base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,239); base58Prefixes[EXT_PUBLIC_KEY] = {0x04, 0x35, 0x87, 0xCF}; base58Prefixes[EXT_SECRET_KEY] = {0x04, 0x35, 0x83, 0x94}; } }; static std::unique_ptr<CChainParams> globalChainParams; const CChainParams &Params() { assert(globalChainParams); return *globalChainParams; } std::unique_ptr<CChainParams> CreateChainParams(const std::string& chain) { if (chain == CBaseChainParams::MAIN) return std::unique_ptr<CChainParams>(new CMainParams()); else if (chain == CBaseChainParams::TESTNET) return std::unique_ptr<CChainParams>(new CTestNetParams()); else if (chain == CBaseChainParams::REGTEST) return std::unique_ptr<CChainParams>(new CRegTestParams()); throw std::runtime_error(strprintf("%s: Unknown chain %s.", __func__, chain)); } void SelectParams(const std::string& network) { SelectBaseParams(network); globalChainParams = CreateChainParams(network); } void UpdateVersionBitsParameters(Consensus::DeploymentPos d, int64_t nStartTime, int64_t nTimeout) { globalChainParams->UpdateVersionBitsParameters(d, nStartTime, nTimeout); } /* *@brief 轮询 nonce, 创建自己的创世纪块,满足 POW */ int createMyGenesisBlock(const std::string& strPowLimit) { CBlock currGenesis; int bRet = false; srand((unsigned int) time(NULL)); uint32_t nNonce = rand(); std::string strTmp ; int iCount = 0; assert(strPowLimit.size() == 64); uint256 u256Target = uint256S(strPowLimit.c_str()); currGenesis = CreatePreAllocGenesisBlock(1516796487, nNonce, UintToArith256( u256Target).GetCompact(), 1); fprintf( stderr, "\n" ); for(; UintToArith256(currGenesis.GetHash()) > UintToArith256(u256Target); currGenesis.nNonce++) { if( 0 == currGenesis.nNonce % 900000) { fprintf( stderr, "%s %d|nNonce=%u|currGenesisHash=%s|targetPow=%s|targetPowNBits=0x%x|\n", __FILE__, __LINE__, currGenesis.nNonce, currGenesis.GetHash().GetHex().c_str(), UintToArith256( u256Target).GetHex().c_str(), UintToArith256( u256Target).GetCompact()); } } fprintf( stderr, "%s %d|pow check ok|nNonce=%d|bingoGenesisHash=%s|targetPow=%s|targetPowNBits=0x%x|hashMerkleRoot=%s|\n", __FILE__, __LINE__, currGenesis.nNonce, currGenesis.GetHash().GetHex().c_str(), UintToArith256( u256Target).GetHex().c_str(), UintToArith256( u256Target).GetCompact(), currGenesis.hashMerkleRoot.GetHex().c_str() ); abort(); return 0; }
87.806211
211
0.828801
[ "vector" ]
3849b2f1c55095ea6d2c8153b255c0fdd67a7d72
1,346
cpp
C++
aslam_cv/aslam_cv_backend/test/testReprojectionError.cpp
chengfzy/kalibr
fe9705b380b160dc939607135f7d30efa64ea2e9
[ "BSD-4-Clause" ]
null
null
null
aslam_cv/aslam_cv_backend/test/testReprojectionError.cpp
chengfzy/kalibr
fe9705b380b160dc939607135f7d30efa64ea2e9
[ "BSD-4-Clause" ]
null
null
null
aslam_cv/aslam_cv_backend/test/testReprojectionError.cpp
chengfzy/kalibr
fe9705b380b160dc939607135f7d30efa64ea2e9
[ "BSD-4-Clause" ]
null
null
null
// Bring in gtest #include <gtest/gtest.h> #include <sm/eigen/gtest.hpp> #include <aslam/CameraGeometryDesignVariableContainer.hpp> #include <aslam/backend/HomogeneousPoint.hpp> #include <aslam/backend/test/ErrorTermTestHarness.hpp> #include <aslam/cameras.hpp> TEST(CvBackendTestSuite, testReprojectionError) { using namespace aslam; using namespace aslam::backend; using namespace aslam::cameras; typedef DistortedOmniRsCameraGeometry camera_geometry_t; boost::shared_ptr<camera_geometry_t> geometry(new camera_geometry_t(camera_geometry_t::getTestGeometry())); boost::shared_ptr<CameraGeometryDesignVariableContainer> geometryDvc( new CameraGeometryDesignVariableContainer(geometry, true, true, true)); Eigen::Matrix2d invR; invR.setIdentity(); Eigen::Vector4d p = sm::kinematics::toHomogeneous(geometry->createRandomVisiblePoint()); boost::shared_ptr<aslam::backend::HomogeneousPoint> pt(new aslam::backend::HomogeneousPoint(p)); pt->setActive(true); pt->setBlockIndex(0); HomogeneousExpression hep(pt); Eigen::VectorXd y; geometry->homogeneousToKeypoint(p, y); boost::shared_ptr<aslam::ReprojectionError> re = geometryDvc->createReprojectionError(y, invR, hep); ErrorTermTestHarness<2> harness((aslam::backend::ErrorTerm*)re.get()); harness.testAll(); }
37.388889
111
0.76003
[ "geometry" ]
384a74637d6bede8180d3eac35d104a7a6d7f94e
7,745
cc
C++
quisp/modules/RoutingDaemon.cc
icepolarizer/quisp
242dada4f2f8100d5fc4b719e92a4e7c1cde81c3
[ "MIT" ]
null
null
null
quisp/modules/RoutingDaemon.cc
icepolarizer/quisp
242dada4f2f8100d5fc4b719e92a4e7c1cde81c3
[ "MIT" ]
null
null
null
quisp/modules/RoutingDaemon.cc
icepolarizer/quisp
242dada4f2f8100d5fc4b719e92a4e7c1cde81c3
[ "MIT" ]
null
null
null
/** \file RoutingDaemon.cc * \todo clean Clean code when it is simple. * \todo doc Write doxygen documentation. * \authors takaakimatsuo * * \brief RoutingDaemon */ #include <vector> #include <omnetpp.h> #include <classical_messages_m.h> #include "RoutingDaemon.h" using namespace omnetpp; namespace quisp { namespace modules { Define_Module(RoutingDaemon); /** * \todo Documentation of the class header. * * \brief RoutingDaemon * * The RoutingDaemon is one of the five key modules in the * software for a quantum repeater/router (qrsa). It will be responsible for * running dynamic routing protocols, such as qOSPF, qBGP, etc. * * It communicates with other RoutingDaemons, in other nodes on the network, * as in the classical Internet. Internally, its role is to keep track of the * QNICs and the links by communicating with the HardwareMonitor, and to provide * information to the ConnectionManager when requested. (There is also one * place where the RuleEngine needs access to information maintained by the RD.) * * The above is the intended design. * * \todo In fact, the RoutingDaemon as it exists today uses special, internal * OMNeT++ magic to directly access the network topology, as stored in the * simulator, rather than dynamically discovering it. That should be corrected. * * At the moment, the RD is independent of the end-to-end reservation of resources, * as dictated by the multiplexing (muxing) discpline in use. This means that * it always returns a single, best path to connect to the requested node. A * consequence is that ConnectionSetupRequest can fail if the resource management * discipline is fully blocking, as in circuit switching, which is the first * discipline we are implementing. * * \todo Also, this code is built as a Module, via the Define_Module call; * the other important modules are classes. That distinction needs to be * addressed. */ void RoutingDaemon::initialize(int stage) { EV<<"Routing Daemon booted\n"; EV<<"Routing table initialized \n"; myAddress = getParentModule()->par("address"); //Topology creation for routing table cTopology *topo = new cTopology("topo"); cMsgPar *yes = new cMsgPar(); yes->setStringValue("yes"); topo->extractByParameter("includeInTopo",yes->str().c_str());//Any node that has a parameter includeInTopo will be included in routing delete(yes); //EV << "cTopology found " << topo->getNumNodes() << " nodes\n"; if(topo->getNumNodes()==0 || topo==nullptr){//If no node with the parameter & value found, do nothing. return; } cTopology::Node *thisNode = topo->getNodeFor(getParentModule()->getParentModule());//The parent node with this specific router int number_of_links_total = 0; //Initialize channel weights for all existing links. for (int x = 0; x < topo->getNumNodes(); x++) {//Traverse through all nodes //For Bidirectional channels, parameters are stored in LinkOut not LinkIn. for (int j = 0; j < topo->getNode(x)->getNumOutLinks(); j++) {//Traverse through all links from a specific node. //thisNode->disable();//You can also disable nodes or channels accordingly to represent broken hardwares //EV<<"\n thisNode is "<< topo->getNode(x)->getModule()->getFullName() <<" has "<<topo->getNode(x)->getNumOutLinks()<<" links \n"; double channel_cost = topo->getNode(x)->getLinkOut(j)->getLocalGate()->getChannel()->par("cost");//Get assigned cost for each channel written in .ned file //EV<<topo->getNode(x)->getLinkOut(j)->getLocalGate()->getFullName()<<" =? "<<"QuantumChannel"<<"\n"; //if(strcmp(topo->getNode(x)->getLinkOut(j)->getLocalGate()->getChannel()->getFullName(),"QuantumChannel")==0){ if(strstr(topo->getNode(x)->getLinkOut(j)->getLocalGate()->getFullName(),"quantum")){ //Otherwise, keep the quantum channels and set the weight //EV<<"\n Quantum Channel!!!!!! cost is"<<channel_cost<<"\n"; topo->getNode(x)->getLinkOut(j)->setWeight(channel_cost);//Set channel weight }else{ //Ignore classical link in quantum routing table topo->getNode(x)->getLinkOut(j)->disable(); } } } for (int i = 0; i < topo->getNumNodes(); i++) {//Traverse through all the destinations from the thisNode if (topo->getNode(i) == thisNode) continue; // skip the node that is running this specific router app //Apply dijkstra to each node to find all shortest paths. topo->calculateWeightedSingleShortestPathsTo(topo->getNode(i));//Overwrites getNumPaths() and so on. //Check the number of shortest paths towards the target node. This may be more than 1 if multiple paths have the same minimum cost. //EV<<"\n Quantum....\n"; if (thisNode->getNumPaths() == 0){ error("Path not found. This means that a node is completely separated...Probably not what you want now"); continue; // not connected } cGate *parentModuleGate = thisNode->getPath(0)->getLocalGate();//Returns the next link/gate in the ith shortest paths towards the target node. int gateIndex = parentModuleGate->getIndex(); QNIC thisqnic; int destAddr = topo->getNode(i)->getModule()->par("address"); thisqnic.address = parentModuleGate->getPreviousGate()->getOwnerModule()->par("self_qnic_address"); thisqnic.type = (QNIC_type) (int) parentModuleGate->getPreviousGate()->getOwnerModule()->par("self_qnic_type"); thisqnic.index = parentModuleGate->getPreviousGate()->getOwnerModule()->getIndex();; thisqnic.pointer = parentModuleGate->getPreviousGate()->getOwnerModule(); qrtable[destAddr] = thisqnic;//Store gate index per destination from this node //EV<<"\n Quantum: "<<topo->getNode(i)->getModule()->getFullName()<<"\n"; //EV <<"\n Quantum: Towards node address " << destAddr << " use qnic with address = "<<parentModuleGate->getPreviousGate()->getOwnerModule()->getFullName()<<"\n"; if(!strstr(parentModuleGate->getFullName(),"quantum")){ error("Quantum routing table referring to classical gates..."); } } delete topo; } /** * This is the only routine, at the moment, with any outside contact. * Rather than exchanging a message with those who need this information (ConnectionManager, mainly, * and in one case RuleEngine), this is a direct call that they make. * * \todo Decide if this is really the right way to do this. Likely also * hooked up in the issue of module v. class. */ int RoutingDaemon::return_QNIC_address_to_destAddr(int destAddr){ Enter_Method("return_QNIC_address_to_destAddr"); RoutingTable::iterator it = qrtable.find(destAddr); if (it == qrtable.end()) { EV << "Quantum: address " << destAddr << " unreachable from this node  \n"; return -1; } return it->second.address; } /** * Once we begin using dynamic routing protocols, this is where the messages * will be handled. This perhaps will also be how we communicate with the * other important daemons in the qrsa. * \todo Handle dynamic routing protocol messages. **/ void RoutingDaemon::handleMessage(cMessage *msg){ } } // namespace modules } // namespace quisp
48.10559
179
0.650613
[ "vector" ]
384f76480ac436b3b2b37840f8ab59a9f9202a43
8,706
cpp
C++
sdk/core/azure-core/test/ut/client_options.cpp
kyle-patterson/azure-sdk-for-cpp
0c24db5a10eeea46840c3e8ee7089fd9857cd7b4
[ "MIT" ]
null
null
null
sdk/core/azure-core/test/ut/client_options.cpp
kyle-patterson/azure-sdk-for-cpp
0c24db5a10eeea46840c3e8ee7089fd9857cd7b4
[ "MIT" ]
null
null
null
sdk/core/azure-core/test/ut/client_options.cpp
kyle-patterson/azure-sdk-for-cpp
0c24db5a10eeea46840c3e8ee7089fd9857cd7b4
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. All rights reserved. // SPDX-License-Identifier: MIT #include <azure/core/context.hpp> #include <azure/core/http/http.hpp> #include <azure/core/http/policies/policy.hpp> #include <azure/core/http/transport.hpp> #include <azure/core/internal/client_options.hpp> #include <gtest/gtest.h> #include <memory> #include <vector> using namespace Azure::Core; using namespace Azure::Core::_internal; using namespace Azure::Core::Http; using namespace Azure::Core::Http::Policies; struct FakeTransport : public HttpTransport { std::unique_ptr<RawResponse> Send(Request& request, Context const& context) override { (void)request; (void)context; return nullptr; } }; struct PerCallPolicy : public HttpPolicy { std::unique_ptr<RawResponse> Send(Request& request, NextHttpPolicy policy, Context const& context) const override { (void)request; (void)policy; (void)context; return std::make_unique<RawResponse>(3, 3, HttpStatusCode::Gone, "IamAPerCallPolicy"); } std::unique_ptr<HttpPolicy> Clone() const override { return std::make_unique<PerCallPolicy>(*this); } }; struct PerRetryPolicy : public HttpPolicy { std::unique_ptr<RawResponse> Send(Request& request, NextHttpPolicy policy, Context const& context) const override { (void)request; (void)policy; (void)context; return std::make_unique<RawResponse>(6, 6, HttpStatusCode::ResetContent, "IamAPerRetryPolicy"); } std::unique_ptr<HttpPolicy> Clone() const override { return std::make_unique<PerRetryPolicy>(*this); } }; TEST(ClientOptions, copyWithOperator) { // client Options defines its own copy constructor which clones policies ClientOptions options; options.Retry.MaxRetries = 1; options.Telemetry.ApplicationId = "pleaseCopyMe"; options.Transport.Transport = std::make_shared<FakeTransport>(); options.PerOperationPolicies.emplace_back(std::make_unique<PerCallPolicy>()); options.PerRetryPolicies.emplace_back(std::make_unique<PerRetryPolicy>()); // Now Copy auto copyOptions = options; // Compare EXPECT_EQ(1, copyOptions.Retry.MaxRetries); EXPECT_EQ(std::string("pleaseCopyMe"), copyOptions.Telemetry.ApplicationId); Request r(HttpMethod::Get, Url("")); auto result = copyOptions.Transport.Transport->Send(r, Context::GetApplicationContext()); EXPECT_EQ(nullptr, result); EXPECT_EQ(1, copyOptions.PerOperationPolicies.size()); result = copyOptions.PerOperationPolicies[0]->Send( r, NextHttpPolicy(0, {}), Context::GetApplicationContext()); EXPECT_EQ(std::string("IamAPerCallPolicy"), result->GetReasonPhrase()); EXPECT_EQ(1, copyOptions.PerRetryPolicies.size()); result = copyOptions.PerRetryPolicies[0]->Send( r, NextHttpPolicy(0, {}), Context::GetApplicationContext()); EXPECT_EQ(std::string("IamAPerRetryPolicy"), result->GetReasonPhrase()); } TEST(ClientOptions, copyWithConstructor) { // client Options defines its own copy constructor which clones policies ClientOptions options; options.Retry.MaxRetries = 1; options.Telemetry.ApplicationId = "pleaseCopyMe"; options.Transport.Transport = std::make_shared<FakeTransport>(); options.PerOperationPolicies.emplace_back(std::make_unique<PerCallPolicy>()); options.PerRetryPolicies.emplace_back(std::make_unique<PerRetryPolicy>()); // Now Copy ClientOptions copyOptions(options); // Compare EXPECT_EQ(1, copyOptions.Retry.MaxRetries); EXPECT_EQ(std::string("pleaseCopyMe"), copyOptions.Telemetry.ApplicationId); Request r(HttpMethod::Get, Url("")); auto result = copyOptions.Transport.Transport->Send(r, Context::GetApplicationContext()); EXPECT_EQ(nullptr, result); EXPECT_EQ(1, copyOptions.PerOperationPolicies.size()); result = copyOptions.PerOperationPolicies[0]->Send( r, NextHttpPolicy(0, {}), Context::GetApplicationContext()); EXPECT_EQ(std::string("IamAPerCallPolicy"), result->GetReasonPhrase()); EXPECT_EQ(1, copyOptions.PerRetryPolicies.size()); result = copyOptions.PerRetryPolicies[0]->Send( r, NextHttpPolicy(0, {}), Context::GetApplicationContext()); EXPECT_EQ(std::string("IamAPerRetryPolicy"), result->GetReasonPhrase()); } TEST(ClientOptions, copyDerivedClassConstructor) { struct ServiceClientOptions : ClientOptions { std::string ApiVersion; }; // client Options defines its own copy constructor which clones policies ServiceClientOptions options; options.ApiVersion = "I am not real!"; options.Retry.MaxRetries = 1; options.Telemetry.ApplicationId = "pleaseCopyMe"; options.Transport.Transport = std::make_shared<FakeTransport>(); options.PerOperationPolicies.emplace_back(std::make_unique<PerCallPolicy>()); options.PerRetryPolicies.emplace_back(std::make_unique<PerRetryPolicy>()); // Now Copy ServiceClientOptions copyOptions(options); // Compare EXPECT_EQ("I am not real!", copyOptions.ApiVersion); EXPECT_EQ(1, copyOptions.Retry.MaxRetries); EXPECT_EQ(std::string("pleaseCopyMe"), copyOptions.Telemetry.ApplicationId); Request r(HttpMethod::Get, Url("")); auto result = copyOptions.Transport.Transport->Send(r, Context::GetApplicationContext()); EXPECT_EQ(nullptr, result); EXPECT_EQ(1, copyOptions.PerOperationPolicies.size()); result = copyOptions.PerOperationPolicies[0]->Send( r, NextHttpPolicy(0, {}), Context::GetApplicationContext()); EXPECT_EQ(std::string("IamAPerCallPolicy"), result->GetReasonPhrase()); EXPECT_EQ(1, copyOptions.PerRetryPolicies.size()); result = copyOptions.PerRetryPolicies[0]->Send( r, NextHttpPolicy(0, {}), Context::GetApplicationContext()); EXPECT_EQ(std::string("IamAPerRetryPolicy"), result->GetReasonPhrase()); } TEST(ClientOptions, copyDerivedClassOperator) { struct ServiceClientOptions : ClientOptions { std::string ApiVersion; }; // client Options defines its own copy constructor which clones policies ServiceClientOptions options; options.ApiVersion = "I am not real!"; options.Retry.MaxRetries = 1; options.Telemetry.ApplicationId = "pleaseCopyMe"; options.Transport.Transport = std::make_shared<FakeTransport>(); options.PerOperationPolicies.emplace_back(std::make_unique<PerCallPolicy>()); options.PerRetryPolicies.emplace_back(std::make_unique<PerRetryPolicy>()); // Now Copy auto copyOptions = options; // Compare EXPECT_EQ("I am not real!", copyOptions.ApiVersion); EXPECT_EQ(1, copyOptions.Retry.MaxRetries); EXPECT_EQ(std::string("pleaseCopyMe"), copyOptions.Telemetry.ApplicationId); Request r(HttpMethod::Get, Url("")); auto result = copyOptions.Transport.Transport->Send(r, Context::GetApplicationContext()); EXPECT_EQ(nullptr, result); EXPECT_EQ(1, copyOptions.PerOperationPolicies.size()); result = copyOptions.PerOperationPolicies[0]->Send( r, NextHttpPolicy(0, {}), Context::GetApplicationContext()); EXPECT_EQ(std::string("IamAPerCallPolicy"), result->GetReasonPhrase()); EXPECT_EQ(1, copyOptions.PerRetryPolicies.size()); result = copyOptions.PerRetryPolicies[0]->Send( r, NextHttpPolicy(0, {}), Context::GetApplicationContext()); EXPECT_EQ(std::string("IamAPerRetryPolicy"), result->GetReasonPhrase()); } TEST(ClientOptions, moveConstruct) { struct ServiceClientOptions : ClientOptions { std::string ApiVersion; }; // client Options defines its own copy constructor which clones policies ServiceClientOptions options; options.ApiVersion = "I am not real!"; options.Retry.MaxRetries = 1; options.Telemetry.ApplicationId = "pleaseCopyMe"; options.Transport.Transport = std::make_shared<FakeTransport>(); options.PerOperationPolicies.emplace_back(std::make_unique<PerCallPolicy>()); options.PerRetryPolicies.emplace_back(std::make_unique<PerRetryPolicy>()); // Now move ServiceClientOptions copyOptions(std::move(options)); // Compare EXPECT_EQ("I am not real!", copyOptions.ApiVersion); EXPECT_EQ(1, copyOptions.Retry.MaxRetries); EXPECT_EQ(std::string("pleaseCopyMe"), copyOptions.Telemetry.ApplicationId); Request r(HttpMethod::Get, Url("")); auto result = copyOptions.Transport.Transport->Send(r, Context::GetApplicationContext()); EXPECT_EQ(nullptr, result); EXPECT_EQ(1, copyOptions.PerOperationPolicies.size()); result = copyOptions.PerOperationPolicies[0]->Send( r, NextHttpPolicy(0, {}), Context::GetApplicationContext()); EXPECT_EQ(std::string("IamAPerCallPolicy"), result->GetReasonPhrase()); EXPECT_EQ(1, copyOptions.PerRetryPolicies.size()); result = copyOptions.PerRetryPolicies[0]->Send( r, NextHttpPolicy(0, {}), Context::GetApplicationContext()); EXPECT_EQ(std::string("IamAPerRetryPolicy"), result->GetReasonPhrase()); }
36.579832
100
0.748334
[ "vector" ]
3850060f2087809832d23972862621714da21752
7,286
hpp
C++
search/search.hpp
skiesel/search
b9bb14810a85d6a486d603b3d81444c9d0b246b0
[ "MIT" ]
null
null
null
search/search.hpp
skiesel/search
b9bb14810a85d6a486d603b3d81444c9d0b246b0
[ "MIT" ]
null
null
null
search/search.hpp
skiesel/search
b9bb14810a85d6a486d603b3d81444c9d0b246b0
[ "MIT" ]
null
null
null
// Copyright © 2013 the Search Authors under the MIT license. See AUTHORS for the list of authors. #pragma once #include <cstdio> #include <vector> #include <signal.h> #include "../structs/intpq.hpp" #include "../structs/binheap.hpp" #include "closedlist.hpp" double walltime(); double cputime(); void dfpair(FILE *f, const char *key, const char *fmt, ...); // A SearchStats structure contains statistical information // collected during a run of a search algorithm. class SearchStats { public: double wallstart, cpustart; double wallend, cpuend; unsigned long expd, gend, reopnd, dups; SearchStats(); // start must be called by the search in order to // begin collecting statistical information. void start(); // finish must be called by the search in order to // stop collecting information. void finish(); // output prints the statistical information to the given // file in datafile format. void output(FILE*); // add accumulated the statistical information from // the given search statistics in the receiver. void add(SearchStats &other) { expd += other.expd; gend += other.gend; reopnd += other.reopnd; dups += other.dups; double wt = wallend - wallstart; double ct = cpuend - cpustart; wallstart = cpustart = 0; wallend = wt + (other.wallend - other.wallstart); cpuend = ct + (other.cpuend - other.cpustart); } }; // A Limit structure contains information about when a // search algorithm should be stopped because it has // hit a user specified limit. class Limit { public: Limit(); Limit(int, const char*[]); // reached returns true when the given statistics // reports that the given limit has been reached. bool reached(SearchStats &r) { return timeup || (expd > 0 && r.expd >= expd) || (gend > 0 && r.gend >= gend); } // output prints the limit to the given file in datafile // format. void output(FILE*); // start must be called at the beginning of a search // that would like to use the limit. void start(); // finish must be called when a search, using the limit // has finished. void finish(); unsigned long expd, gend, mem, cputime, walltime; volatile sig_atomic_t timeup; private: void memlimit(const char*); void timelimit(const char*); }; // An OpenList holds nodes and returns them ordered by some // priority. The Ops class has a pred method which accepts // two Nodes and returns true if the 1st node is a predecessor // of the second. template <class Ops, class Node, class Cost> class OpenList { public: const char *kind() { return "binary heap"; } void push(Node *n) { heap.push(n); } Node *pop() { boost::optional<Node*> p = heap.pop(); if (!p) return NULL; return *p; } void pre_update(Node *n) { } void post_update(Node *n) { if (Ops::getind(n) < 0) heap.push(n); else heap.update(Ops::getind(n)); } bool empty() { return heap.empty(); } bool mem(Node *n) { return Ops::getind(n) != -1; } void clear() { heap.clear(); } private: struct Heapops { static bool pred(Node *a, Node *b) { return Ops::pred(a, b); } static void setind(Node *n, int i) { Ops::setind(n, i); } }; BinHeap<Heapops, Node*> heap; }; typedef int IntOpenCost; // The Ops struct has prio and tieprio methods, // both of which return ints. The list is sorted in increasing order // on the prio key then secondary sorted in decreasing order on // the tieprio key. template <class Ops, class Node> class OpenList <Ops, Node, IntOpenCost> { struct Maxq { Maxq() : fill(0), max(0), bkts(100) { } void push(Node *n, unsigned long p) { if (bkts.size() <= p) bkts.resize(p+1); if (p > max) max = p; Ops::setind(n, bkts[p].size()); bkts[p].push_back(n); fill++; } Node *pop() { for ( ; bkts[max].empty() && max > 0; max--) ; Node *n = bkts[max].back(); bkts[max].pop_back(); Ops::setind(n, -1); fill--; return n; } void rm(Node *n, unsigned long p) { assert (p < bkts.size()); std::vector<Node*> &bkt = bkts[p]; unsigned int i = Ops::getind(n); assert (i < bkt.size()); if (bkt.size() > 1) { bkt[i] = bkt[bkt.size() - 1]; Ops::setind(bkt[i], i); } bkt.pop_back(); Ops::setind(n, -1); fill--; } bool empty() { return fill == 0; } unsigned long fill; unsigned int max; std::vector< std::vector<Node*> > bkts; }; unsigned long fill; unsigned long min; std::vector<Maxq> qs; public: OpenList() : fill(0), min(0), qs(100) { } static const char *kind() { return "2d bucketed"; } void push(Node *n) { unsigned long p0 = Ops::prio(n); if (qs.size() <= p0) qs.resize(p0+1); if (p0 < min) min = p0; qs[p0].push(n, Ops::tieprio(n)); fill++; } Node *pop() { for ( ; min < qs.size() && qs[min].empty(); min++) ; fill--; auto n = qs[min].pop(); assert ((unsigned long) Ops::prio(n) == min); return n; } void pre_update(Node*n) { if (Ops::getind(n) < 0) return; assert ((unsigned long) Ops::prio(n) < qs.size()); qs[Ops::prio(n)].rm(n, Ops::tieprio(n)); fill--; } void post_update(Node *n) { assert (Ops::getind(n) < 0); push(n); } bool empty() { return fill == 0; } bool mem(Node *n) { return Ops::getind(n) >= 0; } void clear() { qs.clear(); min = 0; } }; // A Result is returned from a completed search. It contains // statistical information about the search along with the // solution cost and solution path if a goal was found. template <class D> class Result : public SearchStats { public: std::vector<typename D::State> path; std::vector<typename D::Oper> ops; Result() { } // output writes information to the given file in // datafile format. void output(FILE *f) { dfpair(f, "state size", "%u", sizeof(typename D::State)); dfpair(f, "packed state size", "%u", sizeof(typename D::PackedState)); dfpair(f, "final sol length", "%lu", (unsigned long) path.size()); SearchStats::output(f); } // add accumulates information from another Result // in the receiver. The path infromation is not accumulated. void add(Result<D> &other) { SearchStats::add(other); } }; // Solpath fills in the path and ops fields of the given search result // by walking back the parent pointers from the given node. // // The Node type must have a parent field pointing to the preceeding // node on the solution path, an op field containing the operator that // generated the node, and a state field containing the packed state // representation. template <class D, class Node> void solpath(D &d, Node *goal, Result<D> &res) { res.ops.clear(); res.path.clear(); for (Node *n = goal; n; n = n->parent) { typename D::State buf, &state = d.unpack(buf, n->state); res.path.push_back(state); if (n->parent) res.ops.push_back(n->op); } } template <class D> class SearchAlgorithm { public: SearchAlgorithm(int argc, const char *argv[]) : lim(argc, argv) { } virtual ~SearchAlgorithm() { } virtual void search(D &, typename D::State &) = 0; virtual void reset() { res = Result<D>(); } virtual void output(FILE *f) { lim.output(f); res.output(f); } void start() { res.start(); lim.start(); } void finish() { res.finish(); lim.finish(); } bool limit() { return lim.reached(res); } Result<D> res; Limit lim; };
21.304094
98
0.643151
[ "vector" ]
3854b447b9c6a2d0c80cb9796e565f0246ec7855
546
hpp
C++
src/ModelStructs.hpp
SuperManitu/AnnoModdingTool
045df4125e091c8a70a66b4b0693c41b17d6436f
[ "MIT" ]
1
2016-10-10T12:15:18.000Z
2016-10-10T12:15:18.000Z
src/ModelStructs.hpp
SuperManitu/AnnoModdingTool
045df4125e091c8a70a66b4b0693c41b17d6436f
[ "MIT" ]
null
null
null
src/ModelStructs.hpp
SuperManitu/AnnoModdingTool
045df4125e091c8a70a66b4b0693c41b17d6436f
[ "MIT" ]
null
null
null
#pragma once #include <vector> struct Vertex { float x, y, z; float nx, ny, nz; //Normal of vertex float u, v; Vertex() { } Vertex(float x, float y, float z, float nx, float ny, float nz, float u, float v) : x(x), y(y), z(z), nx(nx), ny(ny), nz(nz), u(u), v(v) { } }; struct Triangle { unsigned int a, b, c; //Indices of Vertexes Triangle() : a(-1), b(-1), c(-1) { } Triangle(unsigned int a, unsigned int b, unsigned int c) : a(a), b(b), c(c) { } }; struct Model { std::vector<Vertex> vertices; std::vector<Triangle> triangles; };
20.222222
141
0.602564
[ "vector", "model" ]
3855db0710c109bc2b673d7ce7635d196cf96ee2
55,534
cpp
C++
src/ems/clientagent/ClientAgent.cpp
shorton3/dashingplatforms
f461c967827b92c8bcf872c365afa64e56871aba
[ "Apache-2.0" ]
null
null
null
src/ems/clientagent/ClientAgent.cpp
shorton3/dashingplatforms
f461c967827b92c8bcf872c365afa64e56871aba
[ "Apache-2.0" ]
null
null
null
src/ems/clientagent/ClientAgent.cpp
shorton3/dashingplatforms
f461c967827b92c8bcf872c365afa64e56871aba
[ "Apache-2.0" ]
null
null
null
/****************************************************************************** * * File name: ClientAgent.cpp * Subsystem: EMS * Description: CORBA Enabled Agent for receiving and processing client commands * from the various client interfaces. * * Name Date Release * -------------------- ---------- --------------------------------------------- * Stephen Horton 01/01/2014 Initial release * * ******************************************************************************/ //----------------------------------------------------------------------------- // System include files, includes 3rd party libraries. //----------------------------------------------------------------------------- #include <iostream> #include <ace/Get_Opt.h> #include <ace/Sig_Adapter.h> #include <ace/Select_Reactor.h> #include <tao/ORB_Core.h> #include <orbsvcs/CosNamingC.h> #include <tao/Utils/ORB_Manager.h> //----------------------------------------------------------------------------- // Component includes, includes elements of our system. //----------------------------------------------------------------------------- #include "ClientAgent.h" #include "platform/datamgr/DataManager.h" #include "platform/datamgr/DbConnectionHandle.h" #include "platform/common/ConnectionSetNames.h" #include "platform/opm/OPM.h" #include "platform/common/MailboxNames.h" #include "platform/common/MessageIds.h" #include "platform/msgmgr/DistributedMailbox.h" #include "platform/msgmgr/MailboxProcessor.h" #include "platform/msgmgr/MessageFactory.h" #include "platform/msgmgr/TimerMessage.h" #include "platform/messages/AlarmEventMessage.h" #include "platform/logger/Logger.h" #include "platform/threadmgr/ThreadManager.h" #include "platform/utilities/SystemInfo.h" //----------------------------------------------------------------------------- // Static Declarations. //----------------------------------------------------------------------------- /* From the C++ FAQ, create a module-level identification string using a compile define - BUILD_LABEL must have NO spaces passed in from the make command line */ #define StrConvert(x) #x #define XstrConvert(x) StrConvert(x) static volatile char main_sccs_id[] __attribute__ ((unused)) = "@(#)Client Agent" "\n Build Label: " XstrConvert(BUILD_LABEL) "\n Compile Time: " __DATE__ " " __TIME__; // Static singleton instance ClientAgent::ClientAgent* ClientAgent::clientAgent_ = NULL; // Static Select Reactor instance ACE_Reactor* ClientAgent::selectReactor_ = NULL; //----------------------------------------------------------------------------- // PUBLIC methods. //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Method Type: Constructor // Description: // Design: //----------------------------------------------------------------------------- ClientAgent::ClientAgent() :clientAgentMailbox_(NULL), messageHandlerList_(NULL), sessionImplPtr_(NULL), platformConfigImplPtr_(NULL), localNEID_("000000000"), eventReportFileName_(""), fileCheckCounter_(0), numberKeptEventFiles_(0), sizeKeptEventFiles_(0) { // Populate the static single instance clientAgent_ = this; }//end constructor //----------------------------------------------------------------------------- // Method Type: Virtual Destructor // Description: // Design: //----------------------------------------------------------------------------- ClientAgent::~ClientAgent() { }//end virtual destructor //----------------------------------------------------------------------------- // Method Type: STATIC // Description: Catch the shutdown signal and prepare to graceful stop // Design: //----------------------------------------------------------------------------- void ClientAgent::catchShutdownSignal() { TRACELOG(DEBUGLOG, CLIENTAGENTLOG, "Requested ClientAgent shutdown",0,0,0,0,0,0); ClientAgent::getInstance()->shutdown(); }//end catchShutdownSignal //----------------------------------------------------------------------------- // Method Type: STATIC // Description: Retrieve the static singleton instance // Design: //----------------------------------------------------------------------------- ClientAgent* ClientAgent::getInstance() { if (clientAgent_ == NULL) { TRACELOG(ERRORLOG, CLIENTAGENTLOG, "Singleton instance is NULL",0,0,0,0,0,0); }//end if return clientAgent_; }//end getInstance //----------------------------------------------------------------------------- // Method Type: INSTANCE // Description: Gracefully shutdown the Application and all of its child threads // Design: //----------------------------------------------------------------------------- void ClientAgent::shutdown() { // Cancel the outstanding timers // Shutdown the Corba ORB and the event processing loop //TAO_ORB_Core_instance()->orb()->destroy(); // Here, we need to post a message to the local mailbox in order for the mailbox // to be deactivated and released from the owner thread. // // Deactivate the Mailbox //if (clientAgentMailbox_->deactivate() == ERROR) //{ // TRACELOG(ERRORLOG, CLIENTAGENTLOG, "Error deactivating Client Agent Mailbox for shutdown",0,0,0,0,0,0); //}//end if // // Release the Mailbox for cleanup //clientAgentMailbox_->release(); // Shutdown the reactor selectReactor_->owner (ACE_Thread::self ()); selectReactor_->end_reactor_event_loop(); // Exit this process ACE::terminate_process(getpid()); }//end shutdown //----------------------------------------------------------------------------- // Method Type: STATIC // Description: This method starts the reactor thread needed for signal handling, etc. // Design: //----------------------------------------------------------------------------- void ClientAgent::startReactor() { // Set Reactor thread ownership selectReactor_->owner (ACE_Thread::self ()); // Start the reactor processing loop while (selectReactor_->reactor_event_loop_done () == 0) { int result = selectReactor_->run_reactor_event_loop (); char errorBuff[200]; char* resultStr = strerror_r(errno, errorBuff, strlen(errorBuff)); if (resultStr == NULL) { TRACELOG(ERRORLOG, CLIENTAGENTLOG, "Error getting errno string for (%d)",errno,0,0,0,0,0); }//end if ostringstream ostr; ostr << "Reactor event loop returned with code (" << result << ") and errno (" << resultStr << ")" << ends; STRACELOG(ERRORLOG, CLIENTAGENTLOG, ostr.str().c_str()); }//end while }//end startReactor //----------------------------------------------------------------------------- // Method Type: INSTANCE // Description: Initialization method // Design: //----------------------------------------------------------------------------- int ClientAgent::initialize(bool dottedDecimalIORFlag, bool debugFlag, string& debugLevel, string& debugFilename, string& endPointString, string& initRef, string& defaultInitRef) { char* exceptionMessage = NULL; // Initialize the DataManager and activate database connections first! if (DataManager::initialize("./DataManager.conf") == ERROR) { TRACELOG(ERRORLOG, CLIENTAGENTLOG, "Error initializing Data manager",0,0,0,0,0,0); return ERROR; }//end if else { TRACELOG(DEBUGLOG, CLIENTAGENTLOG, "Successfully initialized Data Manager",0,0,0,0,0,0); }//end else // Retrieve our local NEID from the DataManager and store it localNEID_ = SystemInfo::getLocalNEID(); // Activate the Logger Connection Set if (DataManager::activateConnectionSet(CLIENT_AGENT_CONNECTION) == ERROR) { TRACELOG(ERRORLOG, CLIENTAGENTLOG, "Error activating Logger ConnectionSet",0,0,0,0,0,0); return ERROR; }//end if else { TRACELOG(DEBUGLOG, CLIENTAGENTLOG, "Successfully activated Logger ConnectionSet",0,0,0,0,0,0); // Use a database connection to read the loglevels from the database and set them into shared memory DbConnectionHandle* connectionHandle = DataManager::reserveConnection(CLIENT_AGENT_CONNECTION); if (connectionHandle == NULL) { TRACELOG(ERRORLOG, CLIENTAGENTLOG, "Error reserving connection",0,0,0,0,0,0); return ERROR; }//end if else { TRACELOG(DEBUGLOG, CLIENTAGENTLOG, "Successfully reserved Logger ConnectionSet Connection",0,0,0,0,0,0); }//end else // Run a query against the LogLevels table string logLevelQuery = "Select SubSystem,LogLevel from platform.LogLevels where NEID='" + localNEID_ + "'"; // Execute the query against the database if (connectionHandle->executeCommand(logLevelQuery) == ERROR) { TRACELOG(ERRORLOG, CLIENTAGENTLOG, "Log Level query execution failed",0,0,0,0,0,0); connectionHandle->closeCommandResult(); DataManager::releaseConnection(connectionHandle); return ERROR; }//end if TRACELOG(DEBUGLOG, CLIENTAGENTLOG, "Preparing to update shared memory log levels with database values",0,0,0,0,0,0); int columnCount = connectionHandle->getColumnCount(); int rowCount = connectionHandle->getRowCount(); // Do some checks to see if the number of columns returned is zero! This indicates a schema error! if (columnCount == 0) { TRACELOG(ERRORLOG, CLIENTAGENTLOG, "No columns returned in result set, possible schema error",0,0,0,0,0,0); connectionHandle->closeCommandResult(); DataManager::releaseConnection(connectionHandle); return ERROR; }//end if else if (rowCount == 0) { TRACELOG(ERRORLOG, CLIENTAGENTLOG, "No rows returned in result set, default datafill missing",0,0,0,0,0,0); connectionHandle->closeCommandResult(); DataManager::releaseConnection(connectionHandle); return ERROR; }//end if else { // Don't assume the subsystem type is field 0 and severity Level is field 1 int subSystemColumnIndex = connectionHandle->getColumnIndex("SubSystem"); int severityColumnIndex = connectionHandle->getColumnIndex("LogLevel"); for (int row = 0; row < rowCount; row++) { Logger::setSubsystemLogLevel((LogSubSystemType)connectionHandle->getShortValueAt(row,subSystemColumnIndex), (LogSeverityType)connectionHandle->getShortValueAt(row,severityColumnIndex)); }//end for }//end else // Close the results, release the connection connectionHandle->closeCommandResult(); DataManager::releaseConnection(connectionHandle); }//end else // Create the Distributed Mailbox Address MailboxAddress distributedAddress; distributedAddress.locationType = DISTRIBUTED_MAILBOX; distributedAddress.mailboxName = CLIENT_AGENT_MAILBOX_NAME; distributedAddress.inetAddress.set(CLIENT_AGENT_MAILBOX_PORT, LOCAL_IP_ADDRESS); distributedAddress.neid = SystemInfo::getLocalNEID(); // Setup the distributed Mailbox if (!setupMailbox(distributedAddress)) { TRACELOG(ERRORLOG, CLIENTAGENTLOG, "Unable to setup distributed mailbox",0,0,0,0,0,0); return ERROR; }//end if else { TRACELOG(DEBUGLOG, CLIENTAGENTLOG, "ClientAgent distributed mailbox setup successful",0,0,0,0,0,0); }//end else //TODO Move this hardcoded stuff elsewhere and set using command line parameters // Do some hardcoded initialization in order to write Event Reports to a file TRACELOG(DEBUGLOG, CLIENTAGENTLOG, "Opening /tmp/platform.EventReports for event reports",0,0,0,0,0,0); eventReportFileName_ = "/tmp/platform.EventReports"; numberKeptEventFiles_ = 5; sizeKeptEventFiles_ = 10000000; // 10 meg for now eventReportFileStream_.open (eventReportFileName_.c_str(), ios_base::out | ios_base::app); if (eventReportFileStream_.fail()) { TRACELOG(ERRORLOG, CLIENTAGENTLOG, "Failed to open Event Reports file",0,0,0,0,0,0); }//end if //End TODO // Create a new ACE_Select_Reactor for the signal handling, etc to use selectReactor_ = new ACE_Reactor (new ACE_Select_Reactor, 1); // Create an adapter to shutdown this service and all children signalAdapter_ = new ACE_Sig_Adapter((ACE_Sig_Handler_Ex) ClientAgent::catchShutdownSignal); // Specify which types of signals we want to trap signalSet_.sig_add (SIGINT); signalSet_.sig_add (SIGQUIT); signalSet_.sig_add (SIGTERM); // Register ourselves to receive signals so we can shut down gracefully. if (selectReactor_->register_handler (signalSet_, signalAdapter_) == ERROR) { TRACELOG(ERRORLOG, CLIENTAGENTLOG, "Error registering for OS signals",0,0,0,0,0,0); }//end if // Startup the Reactor processing loop in a dedicated thread. Here, returns the OS assigned // unique thread Id ThreadManager::createThread((ACE_THR_FUNC)ClientAgent::startReactor, (void*) 0, "ClientAgentReactor", true); try { exceptionMessage = "While ORB Manager init"; // Build the Orb.init arguments. This is necessary since there is some bug that prevents // the Orb from initializing properly after the arguments have been run through ACE::Get_Opt. int numbArgs = 0; char** orbArgs = new char *[20]; orbArgs[numbArgs++] = "ClientAgent"; orbArgs[numbArgs++] = "-ORBDottedDecimalAddresses"; if (dottedDecimalIORFlag == true) { TRACELOG(DEBUGLOG, CLIENTAGENTLOG, "Restricting IORs to use IP Addresses only",0,0,0,0,0,0); orbArgs[numbArgs++] = "1"; }//end if else { TRACELOG(DEBUGLOG, CLIENTAGENTLOG, "IORs allowed to contain Hostnames for DNS resolution",0,0,0,0,0,0); orbArgs[numbArgs++] = "0"; }//end else if (endPointString.empty() == false) { ostringstream ostr; ostr << "Orb instructed to use endpoints: " << endPointString << ends; STRACELOG(DEBUGLOG, CLIENTAGENTLOG, ostr.str().c_str()); orbArgs[numbArgs++] = "-ORBListenEndpoints"; orbArgs[numbArgs++] = (char*)endPointString.c_str(); }//end if if (initRef.empty() == false) { ostringstream ostr; ostr << "Orb instructed to use initial reference: " << initRef << ends; STRACELOG(DEBUGLOG, CLIENTAGENTLOG, ostr.str().c_str()); orbArgs[numbArgs++] = "-ORBInitRef"; orbArgs[numbArgs++] = (char*)initRef.c_str(); }//end if if (defaultInitRef.empty() == false) { ostringstream ostr; ostr << "Orb instructed to use default initial reference: " << defaultInitRef << ends; STRACELOG(DEBUGLOG, CLIENTAGENTLOG, ostr.str().c_str()); orbArgs[numbArgs++] = "-ORBDefaultInitRef"; orbArgs[numbArgs++] = (char*)defaultInitRef.c_str(); }//end if if (debugFlag == true) { ostringstream ostr; ostr << "Orb internal debug logs enabled to level " << debugLevel << ends; STRACELOG(DEBUGLOG, CLIENTAGENTLOG, ostr.str().c_str()); orbArgs[numbArgs++] = "-ORBDebug"; orbArgs[numbArgs++] = "-ORBDebugLevel"; orbArgs[numbArgs++] = (char*)debugLevel.c_str(); if (debugFilename.empty() == false) { ostringstream ostr; ostr << "Orb internal debug logs redirected to file " << debugFilename << ends; STRACELOG(DEBUGLOG, CLIENTAGENTLOG, ostr.str().c_str()); orbArgs[numbArgs++] = "-ORBLogFile"; orbArgs[numbArgs++] = (char*)debugFilename.c_str(); }//end if }//end if TRACELOG(DEBUGLOG, CLIENTAGENTLOG, "Calling orb init with %d arguments",numbArgs,0,0,0,0,0); // Initialize the Orb Manager - for GIOP 1.1, try: -ORBEndPoint iiop://1.1@<host>:<port> if (orbManager_.init (numbArgs, orbArgs) == ERROR) { TRACELOG(ERRORLOG, CLIENTAGENTLOG, "Error initializing the orb manager",0,0,0,0,0,0); return ERROR; }//end if // Obtain the RootPOA. It is created in holding state when the Orb is created, so // we need to activate it. CORBA::Object_var obj = orbManager_.orb()->resolve_initial_references("RootPOA"); // Get the POA_var object from Object_var. exceptionMessage = "While narrowing the root poa"; PortableServer::POA_var rootPOA = PortableServer::POA::_narrow(obj.in()); // Get the POAManager of the RootPOA. exceptionMessage = "While getting the POA Manager"; PortableServer::POAManager_var poaManager = rootPOA->the_POAManager(); // Activate the POA Manager before activating any sub-objects exceptionMessage = "While activating the POA Manager"; poaManager->activate(); // Create the IDL-specific objects and register them with the POA exceptionMessage = "While creating IDL objects"; createIDLObjects(rootPOA); // Perform initial resolution of the Naming Service. Then, bind our top level // objects into the Naming Service. exceptionMessage = "While initializing the Naming Service bindings"; initNamingService(); // Resolve client interface objects from the Naming Service exceptionMessage = "While resolving client objects from the Naming Service"; resolveClientObjects(); }//end try catch (CORBA::Exception &exception) { // See $TAO_ROOT/tao/Exception.h for additional fields and information that can be retrieved ostringstream ostr; ostr << "Application Level Exception - " << exceptionMessage << ". Corba Orb Level Exception - " << exception._info() << ends; STRACELOG(ERRORLOG, CLIENTAGENTLOG, ostr.str().c_str()); return ERROR; }//end catch // NOTE, TBD: We have not done a good job on retry semantics. If any of the above // throws an exception, then we simply error-out and the Orb will not get started. // Suggestion to improve above: Perhaps we should not return Errors in the initNamingService // and resolveClientObjects methods as these depend on external components. We need // some mechanism to periodically retry (or at least when we need / on application demand) // for those methods. // Start the TAO Orb event loop in its own dedicated thread. From there, // TAO will spawn additional threads and will handle its own thread / connection // management. Here, returns OS assigned unique thread Id // NOTE: In the examples, the Orb thread is created with THR_DETACHED thread option // so the OS will reclaim its resources and exit status is not known, but let's // -undo- that and make it THR_JOINABLE: ThreadManager::createThread((ACE_THR_FUNC)ClientAgent::runOrb, (void*) 0, "ClientAgentOrb", true); return OK; }//end initialize //----------------------------------------------------------------------------- // Method Type: INSTANCE // Description: Create the IDL-specific object interfaces // Design: //----------------------------------------------------------------------------- int ClientAgent::createIDLObjects(PortableServer::POA_var& rootPOA) { char* exceptionMessage = NULL; try { // Create an instance of the Session interface object. This object is // responsible for monitoring of agent/client communication ACE_NEW_RETURN (sessionImplPtr_, session_Session_I_i(), ERROR); PortableServer::ObjectId_var sessionOid = PortableServer::string_to_ObjectId ("AgentSession"); exceptionMessage = "While activating Agent Session"; rootPOA->activate_object_with_id (sessionOid.in(), sessionImplPtr_); // For debugging, here we get an Object reference for session object. // This verifies that the ORB is correctly managing the object. exceptionMessage = "While Session::_this"; session::Session_I* sessionVar = sessionImplPtr_->_this(); // Stringify the object reference and print it out exceptionMessage = "While object_to_string"; CORBA::String_var sessionIOR = this->orbManager_.orb()->object_to_string (sessionVar); // Print the IOR ostringstream ostr; ostr << "Agent Session IOR is " << sessionIOR.in() << ends; STRACELOG(DEBUGLOG, CLIENTAGENTLOG, ostr.str().c_str()); // Create an instance of the platformConfig interface object. This object is // responsible for handling configuration management requests ACE_NEW_RETURN (platformConfigImplPtr_, platformConfig_platformConfig_I_i(), ERROR); PortableServer::ObjectId_var platformConfigOid = PortableServer::string_to_ObjectId("PlatformConfig"); exceptionMessage = "While activating Platform Config"; rootPOA->activate_object_with_id (platformConfigOid.in(), platformConfigImplPtr_); // For debugging, here we get an Object reference for the platformConfig object. // This verifies that the ORB is correctly managing the object. exceptionMessage = "While PlatformConfig::_this"; platformConfig::platformConfig_I* platformConfigVar = platformConfigImplPtr_->_this(); // Stringify the object reference and print it out exceptionMessage = "While object_to_string"; CORBA::String_var platformConfigIOR = this->orbManager_.orb()->object_to_string (platformConfigVar); // Print the IOR ostringstream ostr2; ostr2 << "Platform Config IOR is " << platformConfigIOR.in() << ends; STRACELOG(DEBUGLOG, CLIENTAGENTLOG, ostr.str().c_str()); // Create an instance of the alarms interface object. This object is // responsible for handling alarm management requests ACE_NEW_RETURN (alarmImplPtr_, alarms_alarmInterface_i(), ERROR); PortableServer::ObjectId_var alarmOid = PortableServer::string_to_ObjectId("Alarms"); exceptionMessage = "While activating Alarms"; rootPOA->activate_object_with_id (alarmOid.in(), alarmImplPtr_); // For debugging, here we get an Object reference for the alarms object. // This verifies that the ORB is correctly managing the object. exceptionMessage = "While alarms::_this"; alarms::alarmInterface* alarmVar = alarmImplPtr_->_this(); // Stringify the object reference and print it out exceptionMessage = "While object_to_string"; CORBA::String_var alarmIOR = this->orbManager_.orb()->object_to_string (alarmVar); // Print the IOR ostringstream ostr3; ostr2 << "Alarms IOR is " << alarmIOR.in() << ends; STRACELOG(DEBUGLOG, CLIENTAGENTLOG, ostr.str().c_str()); // Create additional IDL interface objects here... }//end try catch (CORBA::Exception &exception) { // See $TAO_ROOT/tao/Exception.h for additional fields and information that can be retrieved ostringstream ostr; ostr << "Application Level Exception - " << exceptionMessage << ". Corba Orb Level Exception - " << exception._info() << ends; STRACELOG(ERRORLOG, CLIENTAGENTLOG, ostr.str().c_str()); return ERROR; }//end catch return OK; }//end createIDLObjects //----------------------------------------------------------------------------- // Method Type: INSTANCE // Description: Perform initial resolution of the Naming Service. Then, bind // our top level objects into the Naming Service. // Design: //----------------------------------------------------------------------------- int ClientAgent::initNamingService() { const char *exceptionMessage = NULL; try { TRACELOG(DEBUGLOG, CLIENTAGENTLOG, "Attempting to resolve the Naming Service",0,0,0,0,0,0); // Resolve the Naming Service generic reference - Success here depends on the value of // -ORBInitRef (or ORBDefaultInitRef) passed in to Orb.init from the argc/argv options to // specify the corbaloc/iiop target for Interoperable Naming Service lookup. The only // alternative to doing it this way is to actually have the root IOR of the Naming // Service (possibly exchanged via a URL or via database replication, file exchange, or whatever) exceptionMessage = "While resolving Naming Service"; CORBA::ORB_ptr orbPtr = TAO_ORB_Core_instance()->orb(); CORBA::Object_var namingObj = orbPtr->resolve_initial_references ("NameService"); // Check to see if the Naming Service reference is null if (CORBA::is_nil (namingObj.in ())) { TRACELOG(ERRORLOG, CLIENTAGENTLOG, "Unable to resolve Naming Service",0,0,0,0,0,0); // Need to implement retry semantics here!! return ERROR; }//end if exceptionMessage = "While narrowing Naming Service context"; namingContextVar_ = CosNaming::NamingContext::_narrow (namingObj.in()); // Check to see if there was a problem performing narrow if (CORBA::is_nil (namingContextVar_.in())) { TRACELOG(ERRORLOG, CLIENTAGENTLOG, "Naming Service Context reference is null",0,0,0,0,0,0); // Implement retry semantics here (if necessary)!! return ERROR; }//end if // Bind the Session IDL object into the naming service. This is the top level // interface from which all other interfaces should be retrieved. So, we should not // need to bind other interface objects to the Naming Service later. CosNaming::Name sessionName (1); sessionName.length (1); // TBD: This should be replaced with a unique identifier that distinguishes this // Client Agent from other possible client agents (or at least the redundant one). Needs discussion. sessionName[0].id = CORBA::string_dup ("AgentSession"); sessionName[0].kind = CORBA::string_dup ("server"); TRACELOG(DEBUGLOG, CLIENTAGENTLOG, "Client Agent Naming Service Bind Name is AgentSession", 0,0,0,0,0,0); exceptionMessage = "While using Session _this"; session::Session_I* sessionVar = sessionImplPtr_->_this(); exceptionMessage = "While rebinding Session"; namingContextVar_->rebind (sessionName, sessionVar); // For now, Bind the PlatformConfig configuration management interface object into the // Naming Service. Later, this can be modified so that all 'sub-interfaces' are retrievable // via the session interface by introspection. CosNaming::Name platformConfigName (1); platformConfigName.length (1); platformConfigName[0].id = CORBA::string_dup ("PlatformConfig"); platformConfigName[0].kind = CORBA::string_dup ("server"); TRACELOG(DEBUGLOG, CLIENTAGENTLOG, "Client Agent binding PlatformConfig to the Naming Service",0,0,0,0,0,0); exceptionMessage = "While using PlatformConfig _this"; platformConfig::platformConfig_I* platformConfigVar = platformConfigImplPtr_->_this(); exceptionMessage = "While rebinding PlatformConfig"; namingContextVar_->rebind (platformConfigName, platformConfigVar); // For now, Bind the Alarms management interface object into the Naming Service. // Later, this can be modified so that all 'sub-interfaces' are retrievable // via the session interface by introspection. CosNaming::Name alarmName (1); alarmName.length (1); alarmName[0].id = CORBA::string_dup ("Alarms"); alarmName[0].kind = CORBA::string_dup ("server"); TRACELOG(DEBUGLOG, CLIENTAGENTLOG, "Client Agent binding Alarms Interface to the Naming Service",0,0,0,0,0,0); exceptionMessage = "While using Alarms _this"; alarms::alarmInterface* alarmVar = alarmImplPtr_->_this(); exceptionMessage = "While rebinding Alarms"; namingContextVar_->rebind (alarmName, alarmVar); }//end try catch (CORBA::Exception &exception) { // See $TAO_ROOT/tao/Exception.h for additional fields and information that can be retrieved ostringstream ostr; ostr << "Application Level Exception - " << exceptionMessage << ". Corba Orb Level Exception - " << exception._info() << ends; STRACELOG(ERRORLOG, CLIENTAGENTLOG, ostr.str().c_str()); return ERROR; }//end catch return OK; }//end initNamingService //----------------------------------------------------------------------------- // Method Type: INSTANCE // Description: Resolve/retrieve our clients' top level interface objects from // the Naming Service // Design: //----------------------------------------------------------------------------- int ClientAgent::resolveClientObjects() { const char* exceptionMessage = NULL; try { // Resolve the Clients' Session reference which is the top level object reference. From // there we can get references to all of the other remote interfaces CosNaming::Name clientSessionContextName (1); clientSessionContextName.length (1); // NOTE, TBD: This needs to be replaced with a unique distinguishing string for // each client. For now, we only support 1 client!!!! clientSessionContextName[0].id = CORBA::string_dup ("ClientSession"); if (CORBA::is_nil (namingContextVar_.in())) { TRACELOG(ERRORLOG, CLIENTAGENTLOG, "Naming Service Context reference is NULL",0,0,0,0,0,0); return ERROR; }//end if TRACELOG(DEBUGLOG, CLIENTAGENTLOG, "Resolving Clients' Session Interfaces",0,0,0,0,0,0); exceptionMessage = "While resolving clients' session interfaces"; CORBA::Object_var clientSessionVar = namingContextVar_->resolve(clientSessionContextName); exceptionMessage = "While narrowing the NMS Session Interface"; session_I_ptr_ = session::Session_I::_narrow (clientSessionVar.in()); if (CORBA::is_nil (session_I_ptr_) || session_I_ptr_->_non_existent()) { TRACELOG(ERRORLOG, CLIENTAGENTLOG, "Failed to resolve Clients' Session Interfaces in Naming Service",0,0,0,0,0,0); return ERROR; }//end if // Display list of Clients and their IORs ostringstream ostr; ostr << "IOR of the Client Session object is " << this->orbManager_.orb()->object_to_string(session_I_ptr_) << ends; STRACELOG(DEBUGLOG, CLIENTAGENTLOG, ostr.str().c_str()); // Set the reference of the Client Session object into our own Session object // as the 'Associated Session' -- NOTE: This is a cheat to satisfy the IDL as it // only supports storing 1 client reference in the IDL. We need a way to store // references to all attached clients, but since we don't use it for now..... sessionImplPtr_->setAssociatedSession(session_I_ptr_); // Resolve other Client interfaces here... }//end try //catch NamingContext error catch (CosNaming::NamingContext::NotFound notFoundException) { ostringstream ostr; ostr << "CosNaming Naming Service Context not found " << exceptionMessage << ": " << notFoundException._info() << ends; STRACELOG(ERRORLOG, CLIENTAGENTLOG, ostr.str().c_str()); return ERROR; }//end catch catch (CosNaming::NamingContext::CannotProceed cannotProceed) { ostringstream ostr; ostr << "CosNaming Cannot proceed user exception " << exceptionMessage << ": " << cannotProceed._info() << ends; STRACELOG(ERRORLOG, CLIENTAGENTLOG, ostr.str().c_str()); return ERROR; }//end catch catch (CORBA::Exception &exception) { // See $TAO_ROOT/tao/Exception.h for additional fields and information that can be retrieved ostringstream ostr; ostr << "Application Level Exception - " << exceptionMessage << ". Corba Orb Level Exception - " << exception._info() << ends; STRACELOG(ERRORLOG, CLIENTAGENTLOG, ostr.str().c_str()); return ERROR; }//end catch return OK; }//end resolveClientObjects //----------------------------------------------------------------------------- // Method Type: INSTANCE // Description: Start the mailbox processing loop // Design: //----------------------------------------------------------------------------- void ClientAgent::processMailbox() { // Create the Mailbox Processor MailboxProcessor mailboxProcessor(messageHandlerList_, *clientAgentMailbox_); // Activate our Mailbox (here we start receiving messages into the Mailbox queue) if (clientAgentMailbox_->activate() == ERROR) { // Here we need to do some better error handling. If this fails, then we did NOT // connect to the remote side. Applications need to retry. TRACELOG(ERRORLOG, CLIENTAGENTLOG, "Failed to activate distributed mailbox",0,0,0,0,0,0); }//end if // Start processing messages from the Mailbox queue mailboxProcessor.processMailbox(); }//end processMailbox //----------------------------------------------------------------------------- // Method Type: INSTANCE // Description: Return the String'ized form of the class contents // Design: //----------------------------------------------------------------------------- string ClientAgent::toString() { string s = ""; return (s); }//end toString //----------------------------------------------------------------------------- // PROTECTED methods. //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // PRIVATE methods. //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Method Type: STATIC // Description: Method used to start the TAO Orb in its own dedicated thread // Design: //----------------------------------------------------------------------------- void ClientAgent::runOrb() { // Start the orb main event loop - THIS IS AN INFINITE BLOCKING CALL TAO_ORB_Core_instance()->orb()->run(); }//end runOrb //----------------------------------------------------------------------------- // Method Type: INSTANCE // Description: Handler to Process Alarm Event MsgMgr Messages // Design: //----------------------------------------------------------------------------- int ClientAgent::processAlarmEventMessage(MessageBase* message) { if (message == NULL) { TRACELOG(ERRORLOG, CLIENTAGENTLOG, "Received a null message",0,0,0,0,0,0); return ERROR; }//end if AlarmEventMessage* alarmEventMessage = (AlarmEventMessage*) message; //FOR NOW, SINCE WE ARE GOING TO MOVE THIS CODE INTO SOME OTHER CLASS... I SUGGEST MOVING THIS TO 2 NEW PROCESSES: // EmsAlarmMgr and EmsEventReportMgr (THEY CAN EVEN HAVE SEPARATE MAILBOXES FOR SCALABILITY)!! // NOTE: Each of the FaultManager processes on the respective cards already // checks for duplicate Alarms/Clears, so we SHOULD NOT need to check in the database // to see if these Alarms/Clears have already happened. Therefore, we just insert/delete // from the Database and send to the Clients/NOCs. // Figure out which type of message it is (Alarm, Clear, Event Report) if (alarmEventMessage->getMessageType() == CLEAR_ALARM_MESSAGE) { // Get access to a database connection DbConnectionHandle* connectionHandle = DataManager::reserveConnection(CLIENT_AGENT_CONNECTION); if (connectionHandle == NULL) { TRACELOG(ERRORLOG, CLIENTAGENTLOG, "Error reserving connection",0,0,0,0,0,0); return ERROR; }//end if else { TRACELOG(DEBUGLOG, CLIENTAGENTLOG, "Successfully reserved Connection for AlarmEvent Management",0,0,0,0,0,0); }//end else // Issue a debug log if the Alarm is being Cleared on behalf (by proxy) of another node if (alarmEventMessage->getSourceAddress().neid != alarmEventMessage->getNEID()) { ostringstream ostr; ostr << "Received Proxy Clear Alarm with id (" << alarmEventMessage->getAlarmCode() << ") raised on behalf of NEID (" << alarmEventMessage->getNEID() << ") by NEID (" << alarmEventMessage->getSourceAddress().neid << ")" << ends; STRACELOG(DEBUGLOG, CLIENTAGENTLOG, ostr.str().c_str()); }//end if else { ostringstream ostr; ostr << "Received Clear Alarm with id (" << alarmEventMessage->getAlarmCode() << ") from NEID (" << alarmEventMessage->getNEID() << ")" << ends; STRACELOG(DEBUGLOG, CLIENTAGENTLOG, ostr.str().c_str()); }//end else // Build an update statement to mark the alarm record as CLEARED in the system-wide outstanding // alarms table. We do not want to delete it since we must maintain a history of acknowledgements // NOTE: We need a strategy for when this table gets cleaned UP!! ostringstream outstandingAlarmsClear; outstandingAlarmsClear << "Update platform.AlarmsOutstanding set isCleared=true where " << "OriginatedByNEID=" << alarmEventMessage->getSourceAddress().neid << " and ApplicableToNEID=" << alarmEventMessage->getNEID() << " and AlarmCode=" << alarmEventMessage->getAlarmCode() << " and ManagedObject=" << alarmEventMessage->getManagedObject() << " and ManagedObjectInstance=" << alarmEventMessage->getManagedObjectInstance() << " and Pid=" << alarmEventMessage->getPid() << ";" << ends; // Execute the clear against the database if (connectionHandle->executeCommand(outstandingAlarmsClear.str().c_str()) == ERROR) { TRACELOG(ERRORLOG, CLIENTAGENTLOG, "AlarmsOutstanding clear alarm execution failed",0,0,0,0,0,0); DataManager::releaseConnection(connectionHandle); return ERROR; }//end if else { TRACELOG(DEBUGLOG, CLIENTAGENTLOG, "Successfully cleared alarm in outstanding alarms list",0,0,0,0,0,0); }//end else // Release the connection DataManager::releaseConnection(connectionHandle); // Send the Clear Alarm to the Clients/NOCs //TODO }//end if Clear Alarm // otherwise its an alarm to raise else if (alarmEventMessage->getMessageType() == ALARM_MESSAGE) { // Get access to a database connection DbConnectionHandle* connectionHandle = DataManager::reserveConnection(CLIENT_AGENT_CONNECTION); if (connectionHandle == NULL) { TRACELOG(ERRORLOG, CLIENTAGENTLOG, "Error reserving connection",0,0,0,0,0,0); return ERROR; }//end if else { TRACELOG(DEBUGLOG, CLIENTAGENTLOG, "Successfully reserved Connection for AlarmEvent Management",0,0,0,0,0,0); }//end else // Issue a debug log if the Alarm is being Raised on behalf (by proxy) of another node if (alarmEventMessage->getSourceAddress().neid != alarmEventMessage->getNEID()) { ostringstream ostr; ostr << "Received Proxy Raise Alarm with id (" << alarmEventMessage->getAlarmCode() << ") raised on behalf of NEID (" << alarmEventMessage->getNEID() << ") by NEID (" << alarmEventMessage->getSourceAddress().neid << ")" << ends; STRACELOG(DEBUGLOG, CLIENTAGENTLOG, ostr.str().c_str()); }//end if else { ostringstream ostr; ostr << "Received Raise Alarm with id (" << alarmEventMessage->getAlarmCode() << ") from NEID (" << alarmEventMessage->getNEID() << ")" << ends; STRACELOG(DEBUGLOG, CLIENTAGENTLOG, ostr.str().c_str()); }//end else // Massage the TimeStamp value to work in the database schema char timeBuffer[30]; time_t timeStamp = alarmEventMessage->getTimestamp(); strftime(timeBuffer, sizeof(timeBuffer), "%F %H:%M:%S.00%z", localtime(&timeStamp)); // Truncate the time zone to 2 characters timeBuffer[strlen(timeBuffer) - 2] = '\0'; ostringstream outstandingAlarmsInsert; // Build an insert statement to add the alarm record into the system-wide outstanding // alarms table. NOTE: Acknowledgement field is populated by the EMS operator, so not here outstandingAlarmsInsert << "Insert into platform.AlarmsOutstanding (OriginatedByNEID, ApplicableToNEID," << " AlarmCode, ManagedObject, ManagedObjectInstance, Pid, TimeStamp, IsCleared) " << "values (" << alarmEventMessage->getSourceAddress().neid << "," << alarmEventMessage->getNEID() << "," << alarmEventMessage->getAlarmCode() << "," << alarmEventMessage->getManagedObject() << "," << alarmEventMessage->getManagedObjectInstance() << "," << alarmEventMessage->getPid() << ",'" << timeBuffer << "',false);" << ends; // Execute the update/insert against the database if (connectionHandle->executeCommand(outstandingAlarmsInsert.str().c_str()) == ERROR) { TRACELOG(ERRORLOG, CLIENTAGENTLOG, "AlarmsOutstanding alarm insert execution failed",0,0,0,0,0,0); DataManager::releaseConnection(connectionHandle); return ERROR; }//end if else { TRACELOG(DEBUGLOG, CLIENTAGENTLOG, "Successfully raised alarm into outstanding alarms list",0,0,0,0,0,0); }//end else // Release the connection DataManager::releaseConnection(connectionHandle); // Send the Raised Alarm to the Clients/NOCs //TODO }//end else if Alarm // otherwise, its an event report, so we need to write it to our file else if (alarmEventMessage->getMessageType() == EVENT_REPORT_MESSAGE) { TRACELOG(DEBUGLOG, CLIENTAGENTLOG, "Received Event Report with id (%d)", alarmEventMessage->getEventCode(),0,0,0,0,0); //TODO: Move all of this code (including alarms/clears) somewhere else. We need to add command line parameters to // control how many event Report file are kept, the size of each one, and how many // event reports do we process in between checking the file size for rollover. // NOTE: One other option we could use is to send the event reports to the syslog // facility and have the OS write them to their own dedicated file. This would be // useful if someone wanted the Event Reports to be sent off-card automatically. // However, its less processing intensive for us to just write them to a file that // automatically rolls over. Then we can setup an httpd instance to allow users to // view the event reports with some sort of browser. // For now, we just duplicate the file rollover mechanism used in LogProcessor.cpp (for // when we are managing our own log files mode) //TODO: // Right now, we just write the BARE MsgMgr message to the file, but it DOES NOT contain // the event report description,etc. Upon initialization, we need to read all of the // Event Report Inventory Database Table out and store it in memory (some map container // or something). Then we will use those fields for writing to the file. eventReportFileStream_ << alarmEventMessage->toString() << endl << endl << flush; // For every nth event that we write to the file, we check the size of the file // If it exceeds the specified limit, then we rollover to the next file (and rename the existing ones) // NOTE: To tune the performance, this file size checking interval (every 10 events) may need changing. if ((numberKeptEventFiles_ != 0) && (fileCheckCounter_ == 10)) { off_t fileSize; struct stat fileStats; // Check the size of the file if (stat(eventReportFileName_.c_str(), &fileStats)) { TRACELOG(ERRORLOG, CLIENTAGENTLOG, "Error stat'ing event report file to get file size",0,0,0,0,0,0); }//end if fileSize = fileStats.st_size; // If we have exceeded the size, then rollover all of the files. NOTE: here, if the // file size option was specified, then we use that number; otherwise we use whatever // the default is as specified in the constructor initialization list. if (fileSize >= sizeKeptEventFiles_) { // Existing event file extensions get incremented, but not past the specified number // of 'kept' event files (after that they get deleted) ifstream eventFile; for (int i = (numberKeptEventFiles_ - 1); i > 0; i--) { // check to see if the file exists (perhaps we haven't been running long enough to // accumulate all of these files yet) ostringstream currentFileName; currentFileName << eventReportFileName_ << "." << i; // Test to see if the file exists if (!stat(currentFileName.str().c_str(), &fileStats)) { // So, the file exists. If its the last file in the 'kept' range, delete it if (i == (numberKeptEventFiles_ - 1)) { if (remove(currentFileName.str().c_str()) == ERROR) { TRACELOG(ERRORLOG, CLIENTAGENTLOG, "Event report file remove failed",0,0,0,0,0,0); }//end if }//end if // Increment the file name else { // Incremented file name ostringstream newFileName; newFileName << eventReportFileName_ << "." << (i + 1); // Rename the file if (rename(currentFileName.str().c_str(), newFileName.str().c_str()) == ERROR) { TRACELOG(ERRORLOG, CLIENTAGENTLOG, "Event report file rename failed",0,0,0,0,0,0); }//end if }//end else }//end if }//end for // If its the first/active event file, then close the active event file stream, move // it to a new filename (with .1 extension) and open a new file (this is the i==0 case above) // Flush and close eventReportFileStream_ << flush; eventReportFileStream_.close(); // Build the new filename ostringstream newFileName; newFileName << eventReportFileName_ << ".1"; // Rename the file if (rename(eventReportFileName_.c_str(), newFileName.str().c_str()) == ERROR) { TRACELOG(ERRORLOG, CLIENTAGENTLOG, "Active event report file rename failed",0,0,0,0,0,0); }//end if // Open the new/clean file eventReportFileStream_.open (eventReportFileName_.c_str(), ios_base::out | ios_base::app); // Check the new file stream if (eventReportFileStream_.fail()) { ostringstream ostr; ostr << " Failed to reopen file " << eventReportFileName_ << " for events following rollover" << ends; STRACELOG(ERRORLOG, CLIENTAGENTLOG, ostr.str().c_str()); }//end if }//end if // Reset the counter fileCheckCounter_ = 0; }//end if else { // Increment the counter fileCheckCounter_++; }//end else }//end else if Event Report else { TRACELOG(ERRORLOG, CLIENTAGENTLOG, "Unknown AlarmEvent Message Type received (%d)", alarmEventMessage->getMessageType(),0,0,0,0,0); return ERROR; }//end else return OK; }//end processAlarmEventMessage //----------------------------------------------------------------------------- // Method Type: INSTANCE // Description: Setup the Mailbox framework // Design: //----------------------------------------------------------------------------- bool ClientAgent::setupMailbox(const MailboxAddress& distributedAddress) { // Create the Local Mailbox clientAgentMailbox_ = DistributedMailbox::createMailbox(distributedAddress); if (!clientAgentMailbox_) { TRACELOG(ERRORLOG, CLIENTAGENTLOG, "Unable to create ClientAgent mailbox",0,0,0,0,0,0); return false; }//end if //TAKE OUT: clientAgentMailbox_->setDebugValue(10); // Create the message handlers and put them in the list messageHandlerList_ = new MessageHandlerList(); if (!messageHandlerList_) { TRACELOG(ERRORLOG, CLIENTAGENTLOG, "Unable to create message handler list",0,0,0,0,0,0); return false; }//end if // Create handlers for each message expected // Handler for AlarmEvent Messages MessageHandler alarmEventMessageHandler = makeFunctor((MessageHandler*)0, *this, &ClientAgent::processAlarmEventMessage); // Add the message handlers to the message handler list to be used by the MsgMgr // framework. Here, we use the MessageId - Note that we do not attempt to process // anymore messages of this type in the context of this mailbox processor messageHandlerList_->add(FAULT_MANAGER_ALARM_EVENT_MSG_ID, alarmEventMessageHandler); // Register support for distributed messages so that the DistributedMessageFactory // knows how to recreate them in 'MessageBase' form when they are received. // For receiving AlarmEventMessage notifications MessageBootStrapMethod alarmEventMessageBootStrapMethod = makeFunctor( (MessageBootStrapMethod*)0, AlarmEventMessage::deserialize); MessageFactory::registerSupport(FAULT_MANAGER_ALARM_EVENT_MSG_ID, alarmEventMessageBootStrapMethod); return true; }//end setupMailbox //----------------------------------------------------------------------------- // Nested Class Definitions: //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Function Type: main function for ClientAgent binary // Description: // Design: //----------------------------------------------------------------------------- int ACE_TMAIN (int argc, ACE_TCHAR *argv[]) { bool localLoggerMode = false; // Turn of OS limits and enable core file generation struct rlimit resourceLimit; resourceLimit.rlim_cur = RLIM_INFINITY; resourceLimit.rlim_max = RLIM_INFINITY; setrlimit(RLIMIT_CORE, &resourceLimit); // If this application does NOT need command line arguments, then uncomment (to // prevent compiler warning for unused variables): //int tmpInt __attribute__ ((unused)) = argc; //char** tmpChar __attribute__ ((unused)) = argv; // Create usage string ostringstream usageString; string str4spaces = " "; usageString << "Usage:\n ClientAgent\n" << str4spaces /* command line options */ << "-h Restrict the use of hostnames in IORs. Invokes -ORBDottedDecimalAddresses=1 on the Orb\n" << str4spaces << "-d Enable debug messages from within the Orb\n" << str4spaces << "-v <Debug Level> Controls the level of debug messages from within the Orb (Max is 10)\n" << str4spaces << "-f <log filename> Redirect Orb logs to a file instead of the default stdout\n" << str4spaces << "-e <Endpoint> Direct the Orb to listen for connections on the interface specified by the endpoint URL\n" << str4spaces << "-i <Initial Reference> URL the Orb uses for initial resolution of the NameService. Invokes -ORBInitRef\n" << str4spaces << "-r <Default Init Ref> URL the Orb uses for default initial resolution of the NameService. Invokes -ORBDefaultInitRef\n" << str4spaces << "-l Local Logger Mode only (do not enqueue logs to shared memory)" << str4spaces; usageString << ends; // Validate that the user passed some arguments if (argc < 1) { cout << "Minimum argument requirements not met." << endl << usageString << endl; exit(ERROR); }//end if // Perform our own arguments parsing -before- we pass args to the class ACE_Get_Opt get_opt (argc, argv, "lhdv:f:e:i:r:"); bool dottedDecimalIORFlag = false; bool debugFlag = false; string debugLevel = "0"; string debugFilename; string endPointString; string initRef; string defaultInitRef; int c; while ((c = get_opt ()) != ERROR) { switch (c) { case 'l': { // Set local logger mode command line option flag localLoggerMode = true; break; }//end case case 'h': { // Set flag for enabling Dotted Decimal Addresses inside IORs dottedDecimalIORFlag = true; break; }//end case case 'd': { // Set flag for enabling Debug logs within the Orb debugFlag = true; break; }//end case case 'v': { // Get the argument for setting the Debug Level within the Orb debugLevel = get_opt.optarg; break; }//end case case 'f': { // Get the argument for the file to redirect Orb Debug logs to debugFilename = get_opt.optarg; break; }//end case case 'e': { // Get the argument for setting the Orb Listener Endpoint endPointString = get_opt.optarg; break; }//end case case 'i': { // Get the argument for the Initial Reference String url initRef = get_opt.optarg; break; }//end case case 'r': { // Get the argument for the Default Initial Reference String url defaultInitRef = get_opt.optarg; break; }//end case default: { cout << "Misunderstood option: " << c << endl; cout << usageString.str() << endl; exit(ERROR); }//end default }//end switch }//end while // Initialize the Logger with output to the Log Processor shared memory queue // unless the local logger mode command line option was specified (usually for debugging // and sending logs to local stdout) Logger::getInstance()->initialize(localLoggerMode); if (localLoggerMode) { // Turn on/off All relevant Subsystem logging levels Logger::setSubsystemLogLevel(OPMLOG, DEVELOPERLOG); Logger::setSubsystemLogLevel(CLIENTAGENTLOG, DEVELOPERLOG); }//end if // Initialize the OPM OPM::initialize(); // Create the ClientAgent instance ClientAgent* clientAgent = new ClientAgent(); if (!clientAgent) { TRACELOG(ERRORLOG, CLIENTAGENTLOG, "Could not create ClientAgent instance",0,0,0,0,0,0); return ERROR; }//end if // Initialize the ClientAgent instance if (clientAgent->initialize(dottedDecimalIORFlag, debugFlag, debugLevel, debugFilename, endPointString, initRef, defaultInitRef) == ERROR) { TRACELOG(DEBUGLOG, CLIENTAGENTLOG, "ClientAgent failed initialization",0,0,0,0,0,0); exit(ERROR); }//end if else { TRACELOG(DEBUGLOG, CLIENTAGENTLOG, "ClientAgent successfully started with PID=%d", ACE_OS::getpid(),0,0,0,0,0); }//end else // Start ClientAgent's mailbox processing loop to handle notifications. Here we block // and run forever until we are shutdown by the SIGINT/SIGQUIT signal clientAgent->processMailbox(); TRACELOG(ERRORLOG, CLIENTAGENTLOG, "ClientAgent Main Method exiting",0,0,0,0,0,0); }//end main
42.360031
138
0.620899
[ "object" ]
ee30b2c15ad4a98dbfd67a6452222880355e663f
3,703
cpp
C++
Plugins/UERmlUI/Source/UERmlUI/Private/Render/RmlDrawer.cpp
ZhuRong-HomoStation/RmlUE4
6326cb0e4a54c69cea6ac13e74c9bd1bc397ee77
[ "MIT" ]
15
2020-12-28T08:41:31.000Z
2022-03-24T07:10:05.000Z
Plugins/UERmlUI/Source/UERmlUI/Private/Render/RmlDrawer.cpp
ZhuRong-HomoStation/RmlUE4
6326cb0e4a54c69cea6ac13e74c9bd1bc397ee77
[ "MIT" ]
6
2021-01-06T11:23:59.000Z
2021-01-08T04:01:40.000Z
Plugins/UERmlUI/Source/UERmlUI/Private/Render/RmlDrawer.cpp
ZhuRong-HomoStation/RmlUE4
6326cb0e4a54c69cea6ac13e74c9bd1bc397ee77
[ "MIT" ]
2
2021-01-05T19:16:11.000Z
2021-01-06T02:19:22.000Z
#include "RmlDrawer.h" #include "ClearQuad.h" #include "Logging.h" #include "RmlMesh.h" #include "RmlShader.h" #include "Render/TextureEntries.h" FRmlDrawer::FRmlDrawer(bool bUsing) : bIsFree(!bUsing) { } void FRmlDrawer::DrawRenderThread(FRHICommandListImmediate& RHICmdList, const void* RenderTarget) { // check thread check(IsInRenderingThread() || IsInParallelRenderingThread()); // early out if (DrawList.Num() == 0) { MarkFree(); return; } // get render target FTexture2DRHIRef* RT = (FTexture2DRHIRef*)RenderTarget; // begin pass FRHIRenderPassInfo RPInfo(*RT, ERenderTargetActions::Load_Store); RHICmdList.BeginRenderPass(RPInfo, TEXT("DrawRmlMesh")); // Get shader auto ShaderMap = GetGlobalShaderMap(ERHIFeatureLevel::SM5); TShaderMapRef<FRmlShaderVs> Vs(ShaderMap); TShaderMapRef<FRmlShaderPs> Ps(ShaderMap); TShaderMapRef<FRmlShaderPsNoTex> PsNoTex(ShaderMap); // Set PSO info FGraphicsPipelineStateInitializer PSOInitializer; RHICmdList.ApplyCachedRenderTargets(PSOInitializer); PSOInitializer.BoundShaderState.VertexDeclarationRHI = FRmlMesh::GetMeshDeclaration(); PSOInitializer.BoundShaderState.VertexShaderRHI = Vs.GetVertexShader(); PSOInitializer.BoundShaderState.PixelShaderRHI = Ps.GetPixelShader(); PSOInitializer.PrimitiveType = PT_TriangleList; PSOInitializer.BlendState = TStaticBlendState<CW_RGBA, BO_Add, BF_SourceAlpha, BF_InverseSourceAlpha>::GetRHI(); PSOInitializer.RasterizerState = TStaticRasterizerState<>::GetRHI(); PSOInitializer.DepthStencilState = TStaticDepthStencilState<false, CF_Always>::GetRHI(); FGraphicsPipelineStateInitializer PSOInitializerNoTex; RHICmdList.ApplyCachedRenderTargets(PSOInitializerNoTex); PSOInitializerNoTex.BoundShaderState.VertexDeclarationRHI = FRmlMesh::GetMeshDeclaration(); PSOInitializerNoTex.BoundShaderState.VertexShaderRHI = Vs.GetVertexShader(); PSOInitializerNoTex.BoundShaderState.PixelShaderRHI = PsNoTex.GetPixelShader(); PSOInitializerNoTex.PrimitiveType = PT_TriangleList; PSOInitializerNoTex.BlendState = TStaticBlendState<CW_RGBA, BO_Add, BF_SourceAlpha, BF_InverseSourceAlpha>::GetRHI(); PSOInitializerNoTex.RasterizerState = TStaticRasterizerState<>::GetRHI(); PSOInitializerNoTex.DepthStencilState = TStaticDepthStencilState<false, CF_Always, false, CF_Always>::GetRHI(); // Init pso TSharedPtr<FRmlTextureEntry, ESPMode::ThreadSafe> CurTexture = DrawList[0].BoundMesh->BoundTexture; { SetGraphicsPipelineState( RHICmdList, CurTexture.IsValid() ? PSOInitializer : PSOInitializerNoTex); if (CurTexture.IsValid()) Ps->SetParameters(RHICmdList, Ps.GetPixelShader(), CurTexture->GetTextureRHI()); } // Draw elements for (auto& DrawInfo : DrawList) { // Get new texture auto NewTexture = DrawInfo.BoundMesh->BoundTexture; // Change texture if (NewTexture != CurTexture) { // Change PSO if (CurTexture.IsValid() != NewTexture.IsValid()) { SetGraphicsPipelineState( RHICmdList, NewTexture.IsValid() ? PSOInitializer : PSOInitializerNoTex); } // Change texture if (NewTexture.IsValid()) Ps->SetParameters(RHICmdList, Ps.GetPixelShader(), NewTexture->GetTextureRHI()); // Update current texture CurTexture = NewTexture; } // Set transform Vs->SetParameters(RHICmdList, DrawInfo.RenderTransform); // Set scissor rect RHICmdList.SetScissorRect( true, DrawInfo.ScissorRect.Min.X, DrawInfo.ScissorRect.Min.Y, DrawInfo.ScissorRect.Max.X, DrawInfo.ScissorRect.Max.Y); // Render mesh DrawInfo.BoundMesh->DrawMesh(RHICmdList); } // Reset draw info DrawList.Reset(); // Mark free MarkFree(); RHICmdList.EndRenderPass(); }
32.482456
118
0.765325
[ "mesh", "render", "transform" ]
ee39b072ccc4b181e33d8bb1a37c7719bc9a764a
21,209
cpp
C++
extensions/framework/Vulkan/VulkanSwapchain.cpp
zann1x/FrameGraph
ea06e28147a51f6d7cab219b4d8f30428a539faa
[ "BSD-2-Clause" ]
null
null
null
extensions/framework/Vulkan/VulkanSwapchain.cpp
zann1x/FrameGraph
ea06e28147a51f6d7cab219b4d8f30428a539faa
[ "BSD-2-Clause" ]
null
null
null
extensions/framework/Vulkan/VulkanSwapchain.cpp
zann1x/FrameGraph
ea06e28147a51f6d7cab219b4d8f30428a539faa
[ "BSD-2-Clause" ]
null
null
null
// Copyright (c) 2018-2019, Zhirnov Andrey. For more information see 'LICENSE' #include "VulkanSwapchain.h" #include "stl/Algorithms/EnumUtils.h" #include "stl/Algorithms/ArrayUtils.h" #include "stl/Memory/MemUtils.h" #include "VulkanDevice.h" namespace FGC { /* ================================================= constructor ================================================= */ VulkanSwapchain::VulkanSwapchain () : _vkSwapchain{ VK_NULL_HANDLE }, _vkPhysicalDevice{ VK_NULL_HANDLE }, _vkDevice{ VK_NULL_HANDLE }, _vkSurface{ VK_NULL_HANDLE }, _currImageIndex{ UMax }, _colorFormat{ VK_FORMAT_UNDEFINED }, _colorSpace{ VK_COLOR_SPACE_MAX_ENUM_KHR }, _minImageCount{ 0 }, _preTransform{ VK_SURFACE_TRANSFORM_FLAG_BITS_MAX_ENUM_KHR }, _presentMode{ VK_PRESENT_MODE_MAX_ENUM_KHR }, _compositeAlpha{ VK_COMPOSITE_ALPHA_FLAG_BITS_MAX_ENUM_KHR }, _colorImageUsage{ 0 }, _lastFpsUpdateTime{ TimePoint_t::clock::now() }, _frameCounter{ 0 }, _currentFPS{ 0.0f } { } /* ================================================= constructor ================================================= */ VulkanSwapchain::VulkanSwapchain (VkPhysicalDevice physicalDev, VkDevice logicalDev, VkSurfaceKHR surface, const VulkanDeviceFn &fn) : VulkanSwapchain() { _vkPhysicalDevice = physicalDev; _vkDevice = logicalDev; _vkSurface = surface; CHECK( _vkPhysicalDevice and _vkDevice and _vkSurface ); VulkanDeviceFn_Init( fn ); } VulkanSwapchain::VulkanSwapchain (const VulkanDevice &dev) : VulkanSwapchain( dev.GetVkPhysicalDevice(), dev.GetVkDevice(), dev.GetVkSurface(), dev ) { } /* ================================================= destructor ================================================= */ VulkanSwapchain::~VulkanSwapchain () { CHECK( not _vkSwapchain ); } /* ================================================= ChooseColorFormat ================================================= */ bool VulkanSwapchain::ChooseColorFormat (INOUT VkFormat &colorFormat, INOUT VkColorSpaceKHR &colorSpace) const { CHECK_ERR( _vkPhysicalDevice and _vkSurface ); uint count = 0; Array< VkSurfaceFormatKHR > surf_formats; const VkFormat def_format = VK_FORMAT_B8G8R8A8_UNORM; const VkColorSpaceKHR def_space = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR; const VkFormat required_format = colorFormat; const VkColorSpaceKHR required_colorspace = colorSpace; VK_CHECK( vkGetPhysicalDeviceSurfaceFormatsKHR( _vkPhysicalDevice, _vkSurface, OUT &count, null )); CHECK_ERR( count > 0 ); surf_formats.resize( count ); VK_CHECK( vkGetPhysicalDeviceSurfaceFormatsKHR( _vkPhysicalDevice, _vkSurface, OUT &count, OUT surf_formats.data() )); if ( count == 1 and surf_formats[0].format == VK_FORMAT_UNDEFINED ) { colorFormat = required_format; colorSpace = surf_formats[0].colorSpace; } else { const size_t max_idx = UMax; size_t both_match_idx = max_idx; size_t format_match_idx = max_idx; size_t space_match_idx = max_idx; size_t def_format_idx = 0; size_t def_space_idx = 0; for (size_t i = 0; i < surf_formats.size(); ++i) { const auto& surf_fmt = surf_formats[i]; if ( surf_fmt.format == required_format and surf_fmt.colorSpace == required_colorspace ) { both_match_idx = i; } else // separate check if ( surf_fmt.format == required_format ) format_match_idx = i; else if ( surf_fmt.colorSpace == required_colorspace ) space_match_idx = i; // check with default if ( surf_fmt.format == def_format ) def_format_idx = i; if ( surf_fmt.colorSpace == def_space ) def_space_idx = i; } size_t idx = 0; if ( both_match_idx != max_idx ) idx = both_match_idx; else if ( format_match_idx != max_idx ) idx = format_match_idx; else if ( def_format_idx != max_idx ) idx = def_format_idx; // TODO: space_match_idx and def_space_idx are unused yet colorFormat = surf_formats[ idx ].format; colorSpace = surf_formats[ idx ].colorSpace; } return true; } /* ================================================= IsSupported ================================================= */ bool VulkanSwapchain::IsSupported (const uint imageArrayLayers, const VkSampleCountFlags samples, const VkPresentModeKHR presentMode, const VkFormat colorFormat, const VkImageUsageFlags colorImageUsage) const { CHECK_ERR( _vkPhysicalDevice and _vkSurface ); VkSurfaceCapabilitiesKHR surf_caps; VK_CHECK( vkGetPhysicalDeviceSurfaceCapabilitiesKHR( _vkPhysicalDevice, _vkSurface, OUT &surf_caps )); VkImageUsageFlags image_usage = 0; _GetImageUsage( OUT image_usage, presentMode, colorFormat, surf_caps ); if ( not EnumEq( image_usage, colorImageUsage ) ) return false; VkImageFormatProperties image_props = {}; VK_CALL( vkGetPhysicalDeviceImageFormatProperties( _vkPhysicalDevice, colorFormat, VK_IMAGE_TYPE_2D, VK_IMAGE_TILING_OPTIMAL, colorImageUsage, 0, OUT &image_props )); if ( not EnumEq( image_props.sampleCounts, samples ) ) return false; if ( imageArrayLayers < image_props.maxArrayLayers ) return false; return true; } /* ================================================= Create ================================================= */ bool VulkanSwapchain::Create (const uint2 &viewSize, const VkFormat colorFormat, const VkColorSpaceKHR colorSpace, const uint minImageCount, const VkPresentModeKHR presentMode, const VkSurfaceTransformFlagBitsKHR transform, const VkCompositeAlphaFlagBitsKHR compositeAlpha, const VkImageUsageFlags colorImageUsage, ArrayView<uint> queueFamilyIndices) { CHECK_ERR( _vkPhysicalDevice and _vkDevice and _vkSurface ); CHECK_ERR( not IsImageAcquired() ); VkSurfaceCapabilitiesKHR surf_caps; VK_CHECK( vkGetPhysicalDeviceSurfaceCapabilitiesKHR( _vkPhysicalDevice, _vkSurface, OUT &surf_caps )); VkSwapchainKHR old_swapchain = _vkSwapchain; VkSwapchainCreateInfoKHR swapchain_info = {}; swapchain_info.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR; swapchain_info.pNext = null; swapchain_info.surface = _vkSurface; swapchain_info.imageFormat = colorFormat; swapchain_info.imageColorSpace = colorSpace; swapchain_info.imageExtent = { viewSize.x, viewSize.y }; swapchain_info.imageArrayLayers = 1; swapchain_info.minImageCount = minImageCount; swapchain_info.oldSwapchain = old_swapchain; swapchain_info.clipped = VK_TRUE; swapchain_info.preTransform = transform; swapchain_info.presentMode = presentMode; swapchain_info.compositeAlpha = compositeAlpha; swapchain_info.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE; if ( queueFamilyIndices.size() > 1 ) { swapchain_info.queueFamilyIndexCount = uint(queueFamilyIndices.size()); swapchain_info.pQueueFamilyIndices = queueFamilyIndices.data(); swapchain_info.imageSharingMode = VK_SHARING_MODE_CONCURRENT; } _GetSurfaceImageCount( INOUT swapchain_info.minImageCount, surf_caps ); _GetSurfaceTransform( INOUT swapchain_info.preTransform, surf_caps ); _GetSwapChainExtent( INOUT swapchain_info.imageExtent, surf_caps ); _GetPresentMode( INOUT swapchain_info.presentMode ); CHECK_ERR( _GetImageUsage( OUT swapchain_info.imageUsage, swapchain_info.presentMode, colorFormat, surf_caps )); CHECK_ERR( _GetCompositeAlpha( INOUT swapchain_info.compositeAlpha, surf_caps )); swapchain_info.imageUsage &= colorImageUsage; VK_CHECK( vkCreateSwapchainKHR( _vkDevice, &swapchain_info, null, OUT &_vkSwapchain )); // destroy obsolete resources for (auto& buf : _imageBuffers) { vkDestroyImageView( _vkDevice, buf.view, null ); } _imageBuffers.clear(); if ( old_swapchain != VK_NULL_HANDLE ) vkDestroySwapchainKHR( _vkDevice, old_swapchain, null ); _colorFormat = colorFormat; _colorSpace = colorSpace; _minImageCount = swapchain_info.minImageCount; _preTransform = swapchain_info.preTransform; _presentMode = swapchain_info.presentMode; _compositeAlpha = swapchain_info.compositeAlpha; _colorImageUsage = swapchain_info.imageUsage; _surfaceSize.x = swapchain_info.imageExtent.width; _surfaceSize.y = swapchain_info.imageExtent.height; CHECK_ERR( _CreateColorAttachment() ); return true; } /* ================================================= _CreateColorAttachment ================================================= */ bool VulkanSwapchain::_CreateColorAttachment () { CHECK_ERR( _imageBuffers.empty() ); FixedArray< VkImage, MaxSwapchainLength > images; uint count = 0; VK_CHECK( vkGetSwapchainImagesKHR( _vkDevice, _vkSwapchain, OUT &count, null )); CHECK_ERR( count > 0 ); images.resize( count ); VK_CHECK( vkGetSwapchainImagesKHR( _vkDevice, _vkSwapchain, OUT &count, OUT images.data() )); _imageBuffers.resize( count ); for (size_t i = 0; i < _imageBuffers.size(); ++i) { VkImageViewCreateInfo view_info = {}; view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; view_info.pNext = null; view_info.viewType = VK_IMAGE_VIEW_TYPE_2D; view_info.flags = 0; view_info.image = images[i]; view_info.format = _colorFormat; view_info.components = { VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY }; view_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; view_info.subresourceRange.baseMipLevel = 0; view_info.subresourceRange.levelCount = 1; view_info.subresourceRange.baseArrayLayer = 0; view_info.subresourceRange.layerCount = 1; VkImageView img_view; VK_CHECK( vkCreateImageView( _vkDevice, &view_info, null, OUT &img_view ) ); _imageBuffers[i] = { images[i], img_view }; } return true; } /* ================================================= Recreate ---- warning: you must delete all command buffers that used swapchain images! ================================================= */ bool VulkanSwapchain::Recreate (const uint2 &size) { ASSERT( not IsImageAcquired() ); CHECK_ERR( Create( size, _colorFormat, _colorSpace, _minImageCount, _presentMode, _preTransform, _compositeAlpha, _colorImageUsage )); return true; } /* ================================================= AcquireNextImage ================================================= */ VkResult VulkanSwapchain::AcquireNextImage (VkSemaphore imageAvailable, VkFence fence) { CHECK_ERR( _vkDevice and _vkSwapchain and (imageAvailable or fence), VK_RESULT_MAX_ENUM ); CHECK_ERR( not IsImageAcquired(), VK_RESULT_MAX_ENUM ); _currImageIndex = UMax; return vkAcquireNextImageKHR( _vkDevice, _vkSwapchain, UMax, imageAvailable, fence, OUT &_currImageIndex ); } /* ================================================= Present ================================================= */ VkResult VulkanSwapchain::Present (VkQueue queue, ArrayView<VkSemaphore> renderFinished) { CHECK_ERR( queue and _vkSwapchain, VK_RESULT_MAX_ENUM ); CHECK_ERR( IsImageAcquired(), VK_RESULT_MAX_ENUM ); const VkSwapchainKHR swap_chains[] = { _vkSwapchain }; const uint image_indices[] = { _currImageIndex }; STATIC_ASSERT( CountOf(swap_chains) == CountOf(image_indices) ); VkPresentInfoKHR present_info = {}; present_info.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; present_info.swapchainCount = uint(CountOf( swap_chains )); present_info.pSwapchains = swap_chains; present_info.pImageIndices = image_indices; present_info.waitSemaphoreCount = uint(renderFinished.size()); present_info.pWaitSemaphores = renderFinished.data(); _currImageIndex = UMax; VkResult res = vkQueuePresentKHR( queue, &present_info ); _UpdateFPS(); return res; } /* ================================================= _UpdateFPS ================================================= */ void VulkanSwapchain::_UpdateFPS () { using namespace std::chrono; ++_frameCounter; TimePoint_t now = TimePoint_t::clock::now(); int64_t duration = duration_cast<milliseconds>(now - _lastFpsUpdateTime).count(); if ( duration > _fpsUpdateIntervalMillis ) { _currentFPS = float(_frameCounter) / float(duration) * 1000.0f; _lastFpsUpdateTime = now; _frameCounter = 0; } } /* ================================================= GetCurrentImage ================================================= */ VkImage VulkanSwapchain::GetCurrentImage () const { if ( _currImageIndex < _imageBuffers.size() ) return _imageBuffers[_currImageIndex].image; return VK_NULL_HANDLE; } /* ================================================= GetCurrentImageView ================================================= */ VkImageView VulkanSwapchain::GetCurrentImageView () const { if ( _currImageIndex < _imageBuffers.size() ) return _imageBuffers[_currImageIndex].view; return VK_NULL_HANDLE; } /* ================================================= Destroy ================================================= */ void VulkanSwapchain::Destroy () { ASSERT( not IsImageAcquired() ); if ( _vkDevice ) { for (auto& buf : _imageBuffers) { vkDestroyImageView( _vkDevice, buf.view, null ); } if ( _vkSwapchain != VK_NULL_HANDLE ) vkDestroySwapchainKHR( _vkDevice, _vkSwapchain, null ); } _imageBuffers.clear(); _vkPhysicalDevice = VK_NULL_HANDLE; _vkDevice = VK_NULL_HANDLE; _vkSurface = VK_NULL_HANDLE; _vkSwapchain = VK_NULL_HANDLE; _surfaceSize = uint2(); _currImageIndex = UMax; _colorFormat = VK_FORMAT_UNDEFINED; _colorSpace = VK_COLOR_SPACE_MAX_ENUM_KHR; _minImageCount = 0; _preTransform = VK_SURFACE_TRANSFORM_FLAG_BITS_MAX_ENUM_KHR; _presentMode = VK_PRESENT_MODE_MAX_ENUM_KHR; _compositeAlpha = VK_COMPOSITE_ALPHA_FLAG_BITS_MAX_ENUM_KHR; _colorImageUsage = 0; } /* ================================================= _GetCompositeAlpha ================================================= */ bool VulkanSwapchain::_GetCompositeAlpha (INOUT VkCompositeAlphaFlagBitsKHR &compositeAlpha, const VkSurfaceCapabilitiesKHR &surfaceCaps) const { const VkCompositeAlphaFlagBitsKHR composite_alpha_flags[] = { VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR, VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR, VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR, VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR, }; if ( EnumEq( surfaceCaps.supportedCompositeAlpha, compositeAlpha ) ) return true; // keep current compositeAlpha = VK_COMPOSITE_ALPHA_FLAG_BITS_MAX_ENUM_KHR; for (auto& flag : composite_alpha_flags) { if ( EnumEq( surfaceCaps.supportedCompositeAlpha, flag ) ) { compositeAlpha = flag; return true; } } RETURN_ERR( "no suitable composite alpha flags found!" ); } /* ================================================= _GetSwapChainExtent ================================================= */ void VulkanSwapchain::_GetSwapChainExtent (INOUT VkExtent2D &extent, const VkSurfaceCapabilitiesKHR &surfaceCaps) const { if ( surfaceCaps.currentExtent.width == UMax and surfaceCaps.currentExtent.height == UMax ) { // keep window size } else { extent.width = surfaceCaps.currentExtent.width; extent.height = surfaceCaps.currentExtent.height; } } /* ================================================= _GetPresentMode ================================================= */ void VulkanSwapchain::_GetPresentMode (INOUT VkPresentModeKHR &presentMode) const { uint count = 0; Array< VkPresentModeKHR > present_modes; VK_CALL( vkGetPhysicalDeviceSurfacePresentModesKHR( _vkPhysicalDevice, _vkSurface, OUT &count, null )); CHECK_ERR( count > 0, void() ); present_modes.resize( count ); VK_CALL( vkGetPhysicalDeviceSurfacePresentModesKHR( _vkPhysicalDevice, _vkSurface, OUT &count, OUT present_modes.data() )); bool required_mode_supported = false; bool fifo_mode_supported = false; bool mailbox_mode_supported = false; bool immediate_mode_supported = false; for (size_t i = 0; i < present_modes.size(); ++i) { required_mode_supported |= (present_modes[i] == presentMode); fifo_mode_supported |= (present_modes[i] == VK_PRESENT_MODE_FIFO_KHR); mailbox_mode_supported |= (present_modes[i] == VK_PRESENT_MODE_MAILBOX_KHR); immediate_mode_supported |= (present_modes[i] == VK_PRESENT_MODE_IMMEDIATE_KHR); } if ( required_mode_supported ) return; // keep current if ( mailbox_mode_supported ) presentMode = VK_PRESENT_MODE_MAILBOX_KHR; else if ( fifo_mode_supported ) presentMode = VK_PRESENT_MODE_FIFO_KHR; else if ( immediate_mode_supported ) presentMode = VK_PRESENT_MODE_IMMEDIATE_KHR; } /* ================================================= _GetSurfaceImageCount ================================================= */ void VulkanSwapchain::_GetSurfaceImageCount (INOUT uint &minImageCount, const VkSurfaceCapabilitiesKHR &surfaceCaps) const { if ( minImageCount < surfaceCaps.minImageCount ) { minImageCount = surfaceCaps.minImageCount; } if ( surfaceCaps.maxImageCount > 0 and minImageCount > surfaceCaps.maxImageCount ) { minImageCount = surfaceCaps.maxImageCount; } } /* ================================================= _GetSurfaceTransform ================================================= */ void VulkanSwapchain::_GetSurfaceTransform (INOUT VkSurfaceTransformFlagBitsKHR &transform, const VkSurfaceCapabilitiesKHR &surfaceCaps) const { if ( EnumEq( surfaceCaps.supportedTransforms, transform ) ) return; // keep current if ( EnumEq( surfaceCaps.supportedTransforms, VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR ) ) { transform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR; } else { transform = surfaceCaps.currentTransform; } } /* ================================================= _GetImageUsage ================================================= */ bool VulkanSwapchain::_GetImageUsage (OUT VkImageUsageFlags &imageUsage, const VkPresentModeKHR presentMode, const VkFormat colorFormat, const VkSurfaceCapabilitiesKHR &surfaceCaps) const { if ( presentMode == VK_PRESENT_MODE_IMMEDIATE_KHR or presentMode == VK_PRESENT_MODE_MAILBOX_KHR or presentMode == VK_PRESENT_MODE_FIFO_KHR or presentMode == VK_PRESENT_MODE_FIFO_RELAXED_KHR ) { imageUsage = surfaceCaps.supportedUsageFlags; } else if ( presentMode == VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR or presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR ) { VkPhysicalDeviceSurfaceInfo2KHR surf_info = {}; surf_info.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SURFACE_INFO_2_KHR; surf_info.surface = _vkSurface; VkSurfaceCapabilities2KHR surf_caps2; VK_CALL( vkGetPhysicalDeviceSurfaceCapabilities2KHR( _vkPhysicalDevice, &surf_info, OUT &surf_caps2 ) ); for (VkBaseInStructure const *iter = reinterpret_cast<VkBaseInStructure const *>(&surf_caps2); iter != null; iter = iter->pNext) { if ( iter->sType == VK_STRUCTURE_TYPE_SHARED_PRESENT_SURFACE_CAPABILITIES_KHR ) { imageUsage = reinterpret_cast<VkSharedPresentSurfaceCapabilitiesKHR const*>(iter)->sharedPresentSupportedUsageFlags; break; } } } else { //RETURN_ERR( "unsupported presentMode, can't choose imageUsage!" ); return false; } ASSERT( EnumEq( imageUsage, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT ) ); imageUsage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; // validation: VkFormatProperties format_props; vkGetPhysicalDeviceFormatProperties( _vkPhysicalDevice, colorFormat, OUT &format_props ); CHECK_ERR( EnumEq( format_props.optimalTilingFeatures, VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT ) ); ASSERT( EnumEq( format_props.optimalTilingFeatures, VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT ) ); if ( EnumEq( imageUsage, VK_IMAGE_USAGE_TRANSFER_SRC_BIT ) and (not EnumEq( format_props.optimalTilingFeatures, VK_FORMAT_FEATURE_TRANSFER_SRC_BIT ) or not EnumEq( format_props.optimalTilingFeatures, VK_FORMAT_FEATURE_BLIT_DST_BIT )) ) { imageUsage &= ~VK_IMAGE_USAGE_TRANSFER_SRC_BIT; } if ( EnumEq( imageUsage, VK_IMAGE_USAGE_TRANSFER_DST_BIT ) and not EnumEq( format_props.optimalTilingFeatures, VK_FORMAT_FEATURE_TRANSFER_DST_BIT ) ) { imageUsage &= ~VK_IMAGE_USAGE_TRANSFER_DST_BIT; } if ( EnumEq( imageUsage, VK_IMAGE_USAGE_STORAGE_BIT ) and not EnumEq( format_props.optimalTilingFeatures, VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT ) ) { imageUsage &= ~VK_IMAGE_USAGE_STORAGE_BIT; } if ( EnumEq( imageUsage, VK_IMAGE_USAGE_SAMPLED_BIT ) and not EnumEq( format_props.optimalTilingFeatures, VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT ) ) { imageUsage &= ~VK_IMAGE_USAGE_SAMPLED_BIT; } if ( EnumEq( imageUsage, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT ) and not EnumEq( format_props.optimalTilingFeatures, VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT ) ) { imageUsage &= ~VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; } return true; } } // FGC
31.052709
153
0.675751
[ "transform" ]
ee42c2a6881ebe884316c407a08bf6cf96744072
3,774
hpp
C++
src/include/XERenderer/Hlms/XEHlmsUnlit.hpp
devxkh/FrankE
72faca02759b54aaec842831f3c7a051e7cf5335
[ "MIT" ]
11
2017-01-17T15:02:25.000Z
2020-11-27T16:54:42.000Z
src/include/XERenderer/Hlms/XEHlmsUnlit.hpp
devxkh/FrankE
72faca02759b54aaec842831f3c7a051e7cf5335
[ "MIT" ]
9
2016-10-23T20:15:38.000Z
2018-02-06T11:23:17.000Z
src/include/XERenderer/Hlms/XEHlmsUnlit.hpp
devxkh/FrankE
72faca02759b54aaec842831f3c7a051e7cf5335
[ "MIT" ]
2
2019-08-29T10:23:51.000Z
2020-04-03T06:08:34.000Z
#ifndef _XEHlmsUnlit_H_ #define _XEHlmsUnlit_H_ #include <XESystem/SystemConfig.hpp> #include <Ogre/OgreMain/include/OgreMatrix4.h> #include <Ogre/Components/Hlms/Unlit/include/OgreHlmsUnlit.h> #include <Ogre/Components/Hlms/Unlit/include/OgreHlmsUnlitPrerequisites.h> #include "OgreHlmsBufferManager.h" #include "OgreConstBufferPool.h" #include "OgreHeaderPrefix.h" namespace Ogre { class CompositorShadowNode; struct QueuedRenderable; /** \addtogroup Component * @{ */ /** \addtogroup Material * @{ */ class XEHlmsUnlitDatablock; /** Implementation without lighting or skeletal animation specfically designed for OpenGL 3+, D3D11 and other RenderSystems which support uniform buffers. Useful for GUI, ParticleFXs, other misc objects that don't require lighting. */ class _OgreHlmsUnlitExport XEHlmsUnlit : public HlmsBufferManager, public ConstBufferPool { protected: typedef vector<HlmsDatablock*>::type HlmsDatablockVec; struct PassData { Matrix4 viewProjMatrix[2]; }; PassData mPreparedPass; ConstBufferPackedVec mPassBuffers; uint32 mCurrentPassBuffer; /// Resets every to zero every new frame. ConstBufferPool::BufferPool const *mLastBoundPool; uint32 mLastTextureHash; virtual const HlmsCache* createShaderCacheEntry(uint32 renderableHash, const HlmsCache &passCache, uint32 finalHash, const QueuedRenderable &queuedRenderable); virtual HlmsDatablock* createDatablockImpl(IdString datablockName, const HlmsMacroblock *macroblock, const HlmsBlendblock *blendblock, const HlmsParamVec &paramVec); void setTextureProperty(IdString propertyName, XEHlmsUnlitDatablock *datablock, uint8 texType); virtual void calculateHashForPreCreate(Renderable *renderable, PiecesMap *inOutPieces); virtual void calculateHashForPreCaster(Renderable *renderable, PiecesMap *inOutPieces); virtual void destroyAllBuffers(void); FORCEINLINE uint32 fillBuffersFor(const HlmsCache *cache, const QueuedRenderable &queuedRenderable, bool casterPass, uint32 lastCacheHash, CommandBuffer *commandBuffer, bool isV1); public: XEHlmsUnlit(Archive *dataFolder, ArchiveVec *libraryFolders); XEHlmsUnlit(Archive *dataFolder, ArchiveVec *libraryFolders, HlmsTypes type, const String &typeName); virtual ~XEHlmsUnlit(); virtual void _changeRenderSystem(RenderSystem *newRs); /// Not supported virtual void setOptimizationStrategy(OptimizationStrategy optimizationStrategy) {} virtual HlmsCache preparePassHash(const Ogre::CompositorShadowNode *shadowNode, bool casterPass, bool dualParaboloid, SceneManager *sceneManager); virtual uint32 fillBuffersFor(const HlmsCache *cache, const QueuedRenderable &queuedRenderable, bool casterPass, uint32 lastCacheHash, uint32 lastTextureHash); virtual uint32 fillBuffersForV1(const HlmsCache *cache, const QueuedRenderable &queuedRenderable, bool casterPass, uint32 lastCacheHash, CommandBuffer *commandBuffer); virtual uint32 fillBuffersForV2(const HlmsCache *cache, const QueuedRenderable &queuedRenderable, bool casterPass, uint32 lastCacheHash, CommandBuffer *commandBuffer); virtual void frameEnded(void); #if !OGRE_NO_JSON /// @copydoc Hlms::_loadJson virtual void _loadJson(const rapidjson::Value &jsonValue, const HlmsJson::NamedBlocks &blocks, HlmsDatablock *datablock) const; /// @copydoc Hlms::_saveJson virtual void _saveJson(const HlmsDatablock *datablock, String &outString) const; /// @copydoc Hlms::_collectSamplerblocks virtual void _collectSamplerblocks(set<const HlmsSamplerblock*>::type &outSamplerblocks, const HlmsDatablock *datablock) const; #endif }; /** @} */ /** @} */ } #include "OgreHeaderSuffix.h" #endif
29.952381
97
0.77716
[ "vector" ]
ee4300dcb70122254c4c97d54767883fd63e7732
5,667
cpp
C++
IntegrationProject/cpp/src/Function.cpp
caritherscw/integration-methods
bda9226a506e2bf407505a5c2385119ff26961c2
[ "Apache-2.0" ]
null
null
null
IntegrationProject/cpp/src/Function.cpp
caritherscw/integration-methods
bda9226a506e2bf407505a5c2385119ff26961c2
[ "Apache-2.0" ]
null
null
null
IntegrationProject/cpp/src/Function.cpp
caritherscw/integration-methods
bda9226a506e2bf407505a5c2385119ff26961c2
[ "Apache-2.0" ]
null
null
null
/* * Function.cpp * * Function - relation between a set of inputs and a set of * outputs. Each input is related to exactly one output. * * param <E> - coefficients * param <C> - exponents * * Created on: Dec 26, 2015 * Author: chris */ #include "Function.h" #include "Utilities.h" namespace MathFunctions { template <typename E, typename C> Function<E, C>::Function() { } template <typename E, typename C> Function<E, C>::Function(const std::vector<E> &exponents, const std::vector<C> &coefficients) { this->exponents = exponents; this->coefficients = coefficients; } template <typename E, typename C> void Function<E, C>::setCoefficient(const int index, const C coefficient) { this->coefficients[index] = coefficient; } template <typename E, typename C> void Function<E, C>::setExponent(const int index, const E exponent) { this->exponents[index] = exponent; } template <typename E, typename C> void Function<E, C>::setCoefficients(const std::vector<C> &coefficients) { this->coefficients = coefficients; } template <typename E, typename C> void Function<E, C>::setExponents(const std::vector<E> &exponents) { this->exponents = exponents; } template <typename E, typename C> C Function<E, C>::getCoefficient(const int index) const { return this->coefficients[index]; } template <typename E, typename C> E Function<E, C>::getExponent(const int index) const { return this->exponents[index]; } template <typename E, typename C> std::vector<C> Function<E, C>::getCoefficients() const { return this->coefficients; } template <typename E, typename C> std::vector<E> Function<E, C>::getExponents() const { return this->exponents; } template<typename E, typename C> E Function<E, C>::getDegree() const { return this->exponents[exponents.size() - 1]; } template <typename E, typename C> Function<E, C>::~Function() { } template <typename E, typename C> double Function<E, C>::evaluate(double x) {} template <typename E, typename C> std::ostream &operator <<(std::ostream &out, Function<E, C> &function) { // check for basic function of degree 0 if(function.getDegree() <= -1) { out << 0; return out; } else if(function.getDegree() == 0) { out << Utilities::fraction(function.getCoefficient(0), 0.00001); return out; } else { // do nothing and continue } // go up to the first nonzero coefficient int indexFirstNonZero = function.getCoefficients().size() - 1; while(function.getCoefficient(indexFirstNonZero) == 0) { indexFirstNonZero--; } // first coefficient will be different - is closer to number if(function.getCoefficient(indexFirstNonZero) < 0.0 && function.getCoefficient(indexFirstNonZero) != -1) { out << "-" << Utilities::fraction(std::abs(function.getCoefficient( indexFirstNonZero)), 0.00001); } else if(function.getCoefficient(indexFirstNonZero) > 0.0 && function.getCoefficient(indexFirstNonZero) != 1) { out << Utilities::fraction(function.getCoefficient(indexFirstNonZero), 0.00001); } else if(function.getCoefficient(indexFirstNonZero) < 0.0 && function.getCoefficient(indexFirstNonZero) == -1) { out << "-"; } else if(function.getCoefficient(indexFirstNonZero) > 0.0 && function.getCoefficient(indexFirstNonZero) == 1) { out << ""; } else { // coefficient is 0 do nothing } // exponent of 0 will not display. if 1 then display x otherwise x^exponent if(function.getExponent(indexFirstNonZero) == 0) { // exponent 0 do not print x } else if(function.getExponent(indexFirstNonZero) == 1) { out << "x"; } else { out << "x^" << Utilities::fraction(function.getExponent(indexFirstNonZero), 0.00001); } // add other terms to the out buffer for(int index = indexFirstNonZero - 1; index >= 0; index--) { if(function.getCoefficient(index) != 0) { if(function.getCoefficient(index) < 0.0 && function.getCoefficient(index) != -1) { out << " - " << Utilities::fraction(std::abs(function.getCoefficient(index)), 0.00001); } else if(function.getCoefficient(index) > 0.0 && function.getCoefficient(index) != 1) { out << " + " << Utilities::fraction(function.getCoefficient(index), 0.00001); } else if(function.getCoefficient(index) < 0.0 && function.getCoefficient(index) == -1 && index != 0) { out << " - "; } else if(function.getCoefficient(index) > 0.0 && function.getCoefficient(index) == 1 && index != 0) { out << " + "; } else if(function.getCoefficient(index) < 0.0 && function.getCoefficient(index) == -1 && index == 0) { out << " - 1"; } else { out << " + 1"; } if(function.getExponent(index) == 0) { // exponent 0 do not print x } else if(function.getExponent(index) == 1 && function.getCoefficient(index) != 0) { out << "x"; } else { out << "x^" << Utilities::fraction(function.getExponent(index), 0.00001); } } } return out; } }
31.137363
102
0.578789
[ "vector" ]
ee43c2e1e13c7771a77d31f39a45f4802e9bde88
39,207
cpp
C++
driver/support_library/src/cascading/CombinerDFS.cpp
ARM-software/ethos-n-driver-stack
9f652630c0ff94d8c8b51fd04f6e4dbc34a57e4b
[ "Apache-2.0" ]
25
2020-03-26T19:08:55.000Z
2022-03-14T07:25:44.000Z
driver/support_library/src/cascading/CombinerDFS.cpp
ARM-software/ethos-n-driver-stack
9f652630c0ff94d8c8b51fd04f6e4dbc34a57e4b
[ "Apache-2.0" ]
11
2021-01-13T14:37:10.000Z
2022-02-28T10:05:10.000Z
driver/support_library/src/cascading/CombinerDFS.cpp
ARM-software/ethos-n-driver-stack
9f652630c0ff94d8c8b51fd04f6e4dbc34a57e4b
[ "Apache-2.0" ]
12
2020-09-13T18:02:47.000Z
2022-03-04T17:00:45.000Z
// // Copyright © 2021 Arm Limited. // SPDX-License-Identifier: Apache-2.0 // #include "CombinerDFS.hpp" #include "../SramAllocator.hpp" #include "../Utils.hpp" #include "Cascading.hpp" #include "Estimation.hpp" #include "EstimationUtils.hpp" #include "Part.hpp" #include "Plan.hpp" #include <ethosn_utils/Filesystem.hpp> #include <fstream> namespace ethosn { namespace support_library { using namespace utils; namespace { void DumpDebugInfo(const GraphOfParts& parts, const Combinations& combs, std::vector<size_t> stats, const DebuggingContext& debuggingContext, const std::string folder) { using namespace ethosn::utils; if (debuggingContext.m_DebugInfo->m_DumpDebugFiles >= CompilationOptions::DebugLevel::High) { MakeDirectory(debuggingContext.GetAbsolutePathOutputFileName(folder).c_str()); if (!stats.empty()) { std::ofstream debugIterationStatsDumpFile( debuggingContext.GetAbsolutePathOutputFileName(folder + "/Stats.txt")); for (auto& val : stats) { debugIterationStatsDumpFile << "Val : " << val << std::endl; } } size_t combinationNumber = 0; for (const Combination& comb : combs) { std::string subfolder = folder + "/" + std::to_string(combinationNumber); MakeDirectory(debuggingContext.GetAbsolutePathOutputFileName(subfolder).c_str()); if (!comb.m_Elems.empty()) { debuggingContext.SaveCombinationToDot(CompilationOptions::DebugLevel::None, comb, parts, subfolder + "/Detailed.dot", DetailLevel::High); } ++combinationNumber; if (combinationNumber > debuggingContext.GetMaxNumDumps()) { break; } } } } bool MatchingBlocks(const Plan& planProducer, const Plan& planConsumer, Buffer* produced, Buffer* consumed) { ethosn::command_stream::BlockConfig producerBlockConfig = {}; size_t matching = 0; Op* opProducer = planProducer.m_OpGraph.GetProducer(produced); const MceOp* mceOpProd = dynamic_cast<const MceOp*>(opProducer); const PleOp* pleOpProd = dynamic_cast<const PleOp*>(opProducer); if (mceOpProd) { producerBlockConfig = mceOpProd->m_BlockConfig; } else if (pleOpProd) { producerBlockConfig = pleOpProd->m_BlockConfig; } else { // It's something else that does not have // the concept of block config return true; } auto consumers = planConsumer.m_OpGraph.GetConsumers(consumed); for (auto& consumer : consumers) { Op* opConsumer = consumer.first; ethosn::command_stream::BlockConfig consumerBlockConfig = {}; const PleOp* pleOpCons = dynamic_cast<const PleOp*>(opConsumer); const MceOp* mceOpCons = dynamic_cast<const MceOp*>(opConsumer); if (pleOpCons) { consumerBlockConfig = pleOpCons->m_BlockConfig; } else if (mceOpCons) { consumerBlockConfig = mceOpCons->m_BlockConfig; } else { // It's something else that does not have // the concept of block config ++matching; } // If here producerBlockConfig is not empty, while // consumerBlockConfig is empty if matching has been // already incremented in the else above, there is // no risk of incrementing matching twice if (producerBlockConfig == consumerBlockConfig) { ++matching; } } return matching == consumers.size(); } } // namespace void Combiner::UpdateStats(const StatsType type) { assert(type < StatsType::NumStats); ++m_Stats[static_cast<size_t>(type)]; } bool Combiner::IsPartInput(const Part& part) const { return (0 == part.GetInputs().size()); } bool Combiner::IsPartOutput(const Part& part) const { return (0 == part.GetOutputs().size()); } bool Combiner::IsPartSo(const Part& part) const { return (part.GetOutputs().size() == 1); } bool Combiner::IsPartMo(const Part& part) const { return (part.GetOutputs().size() > 1); } bool Combiner::IsPartSiso(const Part& part) const { return (part.GetInputs().size() == 1 && part.GetOutputs().size() == 1); } bool Combiner::IsPartSimo(const Part& part) const { return (part.GetInputs().size() == 1 && part.GetOutputs().size() > 1); } bool Combiner::IsPartMiso(const Part& part) const { return (part.GetInputs().size() > 1 && part.GetOutputs().size() == 1); } bool Combiner::IsPartMimo(const Part& part) const { return (part.GetInputs().size() > 1 && part.GetOutputs().size() > 1); } const Plan& Combiner::GetPlanForPartFromCombination(const Part& part, const Combination& comb) const { // Combination comb must contain part already auto elemIt = comb.m_Elems.find(part.m_PartId); assert(elemIt != comb.m_Elems.end()); // Get the plan for the part return part.GetPlan(elemIt->second.m_PlanId); } std::vector<std::pair<const Part*, const Edge*>> Combiner::GetSourceParts(const Part& part) const { std::vector<std::pair<const Part*, const Edge*>> result; for (const auto& edge : part.GetInputs()) { InPart sourcePart = m_GraphOfParts.GetOutputPart(*edge); if (sourcePart.first) { PartId id = sourcePart.second; result.push_back(std::make_pair(&m_GraphOfParts.GetPart(id), edge)); } } return result; } std::vector<std::pair<const Part*, const Edge*>> Combiner::GetDestinationParts(const Part& part) const { std::vector<std::pair<const Part*, const Edge*>> result; for (auto& edge : part.GetOutputs()) { InPart nextPart = m_GraphOfParts.GetInputPart(*edge); if (nextPart.first) { PartId id = nextPart.second; result.push_back(std::make_pair(&m_GraphOfParts.GetPart(id), edge)); } } return result; } bool Combiner::AreMceOperationsCompatible(const Buffer* plan1OutputBuffer, const Buffer* plan2InputBuffer, const Node* destination) const { const MceOperationNode* mceOperationNode = dynamic_cast<const MceOperationNode*>(destination); if ((mceOperationNode) && (plan1OutputBuffer->m_Location != Location::Dram)) { const TensorShape& inputBufferShape = plan2InputBuffer->m_TensorShape; const TensorShape& inputStripeShape = plan2InputBuffer->m_StripeShape; if ((mceOperationNode->GetOperation() == ethosn::command_stream::MceOperation::CONVOLUTION) || (mceOperationNode->GetOperation() == ethosn::command_stream::MceOperation::FULLY_CONNECTED)) { if (GetChannels(inputStripeShape) < GetChannels(inputBufferShape)) { return false; } } } return true; } bool Combiner::AreBlockConfigsCompatible(const Plan& plan1, const Plan& plan2, const Edge& edge) const { Buffer* bufferProduced = plan1.GetOutputBuffer(edge.GetSource()); Buffer* bufferConsumed = plan2.GetInputBuffer(&edge); const bool areBuffersInPleInputSram = bufferProduced->m_Location == Location::PleInputSram && bufferConsumed->m_Location == Location::PleInputSram; if (areBuffersInPleInputSram) { return MatchingBlocks(plan1, plan2, bufferProduced, bufferConsumed); } return true; } bool Combiner::ArePlansCompatibleImpl(const Plan& sPlan, const Plan& dPlan, const Edge& edge) const { const Buffer* planInputBuffer = dPlan.GetInputBuffer(&edge); const Buffer* sPlanOutputBuffer = sPlan.GetOutputBuffer(edge.GetSource()); // two plans should be connected along the edge we were told about. if (sPlanOutputBuffer == nullptr || planInputBuffer == nullptr) { return false; } // Note that m_QuantizationInfo does not need to match between the buffers, as it is possible to *reinterpret* the // quantisation of a buffer without having to insert any glue (i.e. it's a no-op). We will use this to implement the // ReinterpretQuantization Operation. // The same goes for shape, but only in limited circumstances (e.g. you can't reinterpret a 1x1x1x1 as a 1x100x100x100 // because there wouldn't be enough data, and there are probably additional limitations for non-linear formats like // NHWCB, FCAF). For now we are conservative and only allow this for simple NHWC cases where the full tensor is // reinterpreted with a different shape, which we use to implement "DRAM Reshape" Operations as a no-op. bool areShapesDifferent = sPlanOutputBuffer->m_TensorShape != planInputBuffer->m_TensorShape; bool isValidNhwcReinterpret = sPlanOutputBuffer->m_Format == CascadingBufferFormat::NHWC && planInputBuffer->m_Format == CascadingBufferFormat::NHWC && GetNumElements(sPlanOutputBuffer->m_TensorShape) == GetNumElements(planInputBuffer->m_TensorShape); bool areBuffersIncompatible = areShapesDifferent && !isValidNhwcReinterpret; if (areBuffersIncompatible) { return false; } // Check if the buffers on the boundary are compatible, i.e. the same (or similar enough that they can be reinterpreted), // such that the plans could be directly merged without any additional DMA ops required. Both locations must // be on SRAM. bool areBuffersEquivalent = sPlanOutputBuffer->m_Location == planInputBuffer->m_Location && planInputBuffer->m_Location != Location::Dram && sPlanOutputBuffer->m_Location != Location::Dram && sPlanOutputBuffer->m_Format == planInputBuffer->m_Format && sPlanOutputBuffer->m_StripeShape == planInputBuffer->m_StripeShape && sPlanOutputBuffer->m_Order == planInputBuffer->m_Order && sPlanOutputBuffer->m_SizeInBytes == planInputBuffer->m_SizeInBytes && sPlanOutputBuffer->m_NumStripes == planInputBuffer->m_NumStripes; if ((!areBuffersEquivalent) || !AreMceOperationsCompatible(sPlanOutputBuffer, planInputBuffer, edge.GetDestination()) || !AreBlockConfigsCompatible(sPlan, dPlan, edge)) { return false; } return true; } bool Combiner::ArePlansCompatible(const Plan& sPlan, const Plan& dPlan, const Edge& edge) { return ArePlansCompatibleImpl(sPlan, dPlan, edge); } // Check if there is sufficient SRAM for plan to fit // into the SRAM allocation for the combination that // is compatible with the plan bool Combiner::IsPlanAllocated(SramAllocator& alloc, const Plan& plan) const { // Get input and total SRAM sizes required for the plan const SizeInBytes sTotSize = GetTotSizeInBytes(plan); const SizeInBytes sInSize = GetInputsSizeInBytes(plan); using Allocated = std::pair<bool, uint32_t>; Allocated allocated; SramAllocator localAlloc = alloc; // We are not yet sure what could be a good userId here so we are using zero SramAllocator::UserId userId = 0; // Note this function assumes the plan can be merged with the combination // that is associated with the sram allocation. Therefore, the additional // sram usage of this plan is the total size - input size. allocated = localAlloc.Allocate(userId, (sTotSize.m_Tot - sInSize.m_Tot) / m_Caps.GetNumberOfSrams(), AllocationPreference::Start); if (allocated.first) { alloc = localAlloc; return true; } else { return false; } } bool Combiner::IsPlanInputGlueable(const Plan& plan) const { for (auto inputMapping : plan.m_InputMappings) { const Buffer* buf = inputMapping.first; switch (buf->m_Location) { case Location::Dram: case Location::Sram: continue; default: return false; } } return true; } bool Combiner::ArePlansAllowedToMerge(const Plan& reference, const Plan& current, const Edge& edge) const { Buffer* referenceOutBuffer = reference.GetOutputBuffer(edge.GetSource()); Buffer* currentInBuffer = current.GetInputBuffer(&edge); // Plans in a section must use the same block configuration if (!MatchingBlocks(reference, current, referenceOutBuffer, currentInBuffer)) { return false; } // Plans in a section must use the same streaming strategy for (auto inputMapping : reference.m_InputMappings) { const Buffer* referenceInBuffer = inputMapping.first; const bool refSplitH = GetHeight(referenceInBuffer->m_StripeShape) < GetHeight(referenceInBuffer->m_TensorShape); const bool refSplitW = GetWidth(referenceInBuffer->m_StripeShape) < GetWidth(referenceInBuffer->m_TensorShape); const bool refSplitC = GetChannels(referenceInBuffer->m_StripeShape) < GetChannels(referenceInBuffer->m_TensorShape); const bool currSplitH = GetHeight(currentInBuffer->m_StripeShape) < GetHeight(currentInBuffer->m_TensorShape); const bool currSplitW = GetWidth(currentInBuffer->m_StripeShape) < GetWidth(currentInBuffer->m_TensorShape); const bool currSplitC = GetChannels(currentInBuffer->m_StripeShape) < GetChannels(currentInBuffer->m_TensorShape); if (refSplitH != currSplitH || refSplitW != currSplitW || refSplitC != currSplitC) { return false; } } return true; } Combination Combiner::GetBestCombination(Combinations& combs) const { if (combs.size() > 0) { utils::Optional<Combination> result; NetworkPerformanceData refNetPerfData; for (const Combination& combination : combs) { if (!combination.m_Elems.empty()) { OpGraph combiOpGraph = GetOpGraphForCombination(combination, m_GraphOfParts); EstimatedOpGraph estimatedOpGraph = ethosn::support_library::EstimateOpGraph(combiOpGraph, m_Caps, m_EstOpt); if (!estimatedOpGraph.IsComplete()) { continue; } if (!result.has_value() || ComparePerformanceData(estimatedOpGraph.m_PerfData, refNetPerfData) == PerformanceComparisonResult::LeftBetter) { refNetPerfData = estimatedOpGraph.m_PerfData; result = combination; } } } if (!result.has_value()) { // If estimation failed, pick the first non empty combination for (const Combination& combination : combs) { if (!combination.m_Elems.empty()) { return combination; } } return combs.front(); } return result.value(); } return Combination{}; } Combination Combiner::GetBestCombination() const { return m_BestCombination; } CascadingBufferFormat Combiner::GetBestCascadingBufferDramFormat(const std::array<TensorShape, 2> inputOutputStripeShapes) const { using SupportedCompressedFormats = std::vector<CascadingBufferFormat>; constexpr size_t sramStripeShapesSize = inputOutputStripeShapes.size(); SupportedCompressedFormats cascadingBufferSupportedTypePerStripe[sramStripeShapesSize]; for (size_t sramStripeShapesIdx = 0; sramStripeShapesIdx < sramStripeShapesSize; sramStripeShapesIdx++) { const TensorShape& currentStripeShape = inputOutputStripeShapes[sramStripeShapesIdx]; SupportedCompressedFormats& currentCascadedSupportedTypeList = cascadingBufferSupportedTypePerStripe[sramStripeShapesIdx]; if (IsCompressionFormatCompatibleWithStripeAndShape(CompilerDataCompressedFormat::FCAF_DEEP, currentStripeShape)) { currentCascadedSupportedTypeList.push_back(CascadingBufferFormat::FCAF_DEEP); } if (IsCompressionFormatCompatibleWithStripeAndShape(CompilerDataCompressedFormat::FCAF_WIDE, currentStripeShape)) { currentCascadedSupportedTypeList.push_back(CascadingBufferFormat::FCAF_WIDE); } } SupportedCompressedFormats supportedTypes; static_assert(ETHOSN_ARRAY_SIZE(cascadingBufferSupportedTypePerStripe) == 2, ""); std::set_intersection(cascadingBufferSupportedTypePerStripe[0].begin(), cascadingBufferSupportedTypePerStripe[0].end(), cascadingBufferSupportedTypePerStripe[1].begin(), cascadingBufferSupportedTypePerStripe[1].end(), std::back_inserter(supportedTypes)); if (!supportedTypes.empty()) { return supportedTypes.front(); } return CascadingBufferFormat::NHWCB; } // This table shows all possible buffer location permutations // that requires glue. // // Entry | Out Plan Location || In Plan Location // =========================================================== // | || // 1 | SRAM || DRAM // | || // ----------------------------------------------------------- // | || // 2 | DRAM || SRAM // | || // ----------------------------------------------------------- // | || // 3 | SRAM || SRAM // | || // ----------------------------------------------------------- // // Entries 1 and 2 are pratically the same, there is a need // of a DMA operation to bring data from a given input to // an output, buffer in DRAM has been already allocated and // for that reason there is no choice to make about format. // std::unique_ptr<Glue> Combiner::GenerateGlueBetweenSramAndDram() const { auto result = std::make_unique<Glue>(); Glue* resultRaw = result.get(); auto dma = std::make_unique<DmaOp>(); DmaOp* dmaRaw = dma.get(); resultRaw->m_Graph.AddOp(std::move(dma)); resultRaw->m_InputSlot = { dmaRaw, 0 }; resultRaw->m_Output = dmaRaw; return result; } // For entry 3 (see table above) there are as many glues possible as the // number of buffer formats in DRAM i.e. : // - NHWCB // - FCAF_DEEP // - FCAF_WIDE // std::unique_ptr<Glue> Combiner::GenerateGlueBetweenSramAndSram(const Buffer* buffer, const CascadingBufferFormat cascadingBufferFormat) const { auto result = std::make_unique<Glue>(); Glue* resultRaw = result.get(); auto dramBuffer = std::make_unique<Buffer>( Lifetime::Atomic, Location::Dram, cascadingBufferFormat, buffer->m_TensorShape, TensorShape{ 0, 0, 0, 0 }, TraversalOrder::Xyz, utils::TotalSizeBytesNHWCB(buffer->m_TensorShape), buffer->m_QuantizationInfo); auto dma1 = std::make_unique<DmaOp>(); DmaOp* dma1Raw = dma1.get(); Buffer* dramBufferRaw = dramBuffer.get(); auto dma2 = std::make_unique<DmaOp>(); DmaOp* dma2Raw = dma2.get(); resultRaw->m_Graph.AddOp(std::move(dma1)); resultRaw->m_Graph.AddOp(std::move(dma2)); resultRaw->m_Graph.AddBuffer(std::move(dramBuffer)); resultRaw->m_Graph.SetProducer(dramBufferRaw, dma1Raw); resultRaw->m_Graph.AddConsumer(dramBufferRaw, dma2Raw, 0); resultRaw->m_InputSlot = { dma1Raw, 0 }; resultRaw->m_Output = dma2Raw; return result; } std::pair<bool, const Glue*> Combiner::GetGlue(const Buffer* outputBuffer, const Buffer* inputBuffer) { if ((outputBuffer->m_Location == Location::Sram && inputBuffer->m_Location == Location::Dram) || (outputBuffer->m_Location == Location::Dram && inputBuffer->m_Location == Location::Sram)) { m_GluesVector.push_back(GenerateGlueBetweenSramAndDram()); return std::make_pair(true, m_GluesVector.back().get()); } else if (outputBuffer->m_Location == Location::Sram && inputBuffer->m_Location == Location::Sram) { CascadingBufferFormat cascadingBufferFormat = GetBestCascadingBufferDramFormat({ outputBuffer->m_StripeShape, inputBuffer->m_StripeShape }); m_GluesVector.push_back(GenerateGlueBetweenSramAndSram(inputBuffer, cascadingBufferFormat)); return std::make_pair(true, m_GluesVector.back().get()); } else if (outputBuffer->m_Location == Location::Dram && inputBuffer->m_Location == Location::Dram) { // Provide an empty Glue in this case, there is nothing to do return std::make_pair(true, nullptr); } // If here it means that buffers are not glue-able // e.g. input buffer location is PleInputSram return std::make_pair(false, nullptr); } Combination Combiner::GluePartToCombination(const Part& part, const Combination& comb, const std::vector<std::pair<const Part*, const Edge*>>& sources) { Combination result = comb; // Get the plan for the part to be glued with all source parts const Plan& destPlan = GetPlanForPartFromCombination(part, comb); // Iterate on all the source parts i.e. edges for (const auto& source : sources) { // Find the source part in the combination, // it might happen that some branches haven't // been populated yet, that's fine, it will // just skip them auto elemIt = comb.m_Elems.find(source.first->m_PartId); if (elemIt != comb.m_Elems.end()) { const Plan& sourcePlan = source.first->GetPlan(elemIt->second.m_PlanId); // Sanity tests - make sure the two Plans are for adjacent Parts. // Note we lookup both buffers by the same Node, as the Graph does not explicitly store intermediate tensors - // they are implicitly attached to each Node (which are defined to have a single output). const Buffer* outputBuffer = sourcePlan.GetOutputBuffer(source.second->GetSource()); const Buffer* inputBuffer = destPlan.GetInputBuffer(source.second); assert(outputBuffer != nullptr && inputBuffer != nullptr); auto glueResult = GetGlue(outputBuffer, inputBuffer); if (!glueResult.first) { // This combination is not valid, clear it return Combination{}; } if (glueResult.second == nullptr) { continue; } result = result + Combination(*source.first, source.second, glueResult.second); } } return result; } // Try to merge plans from the given Part onto the given Combination. // This may not happen because: // - Plan cannot be merged e.g. different strategies // - Plan is not allowed // - Plan buffers do not fit in SRAM i.e. merged plans // in the seciton take up all the memory Combination Combiner::ContinueSection(const Part& part, const Combination& comb, const SramAllocator& alloc) { UpdateStats(StatsType::ContinueSection); // Get source part and plan from the combination const auto& sources = GetSourceParts(part); const Plan& sPlan = GetPlanForPartFromCombination(*sources.at(0).first, comb); // End the current section and start a new one. // There is a single edge between the combination comb and // and the current part Combination result = GluePartToCombination(part, comb + FindBestCombinationForPart(part), sources); if (IsPartSiso(part)) { // SISO part: // // Try to continue this section with next part. // Make sure that the chosen next plan is in the order: // - Compatible with the last plan in the section // - Allowed i.e. some restriction could be applied // to reduce the search space, for example it // could consider only plans that have identical // block configurations etc. // - Allocated i.e. there is space in SRAM to accomodate // all the buffers required by the plan // sanity check SISO is the only use case. assert(part.GetInputs().size() == 1 && part.GetOutputs().size() == 1 && sources.size() == 1); const Part& nextPart = *(GetDestinationParts(part).at(0).first); assert(GetDestinationParts(part).size() == 1); const Edge& edge = *sources.at(0).second; for (const auto& plan : part.m_Plans) { // Make a copy of the allocator since every plan needs to have its own, // each potential section won't allocate from the same allocator. SramAllocator tempAlloc = alloc; if (!ArePlansCompatible(sPlan, *plan.get(), edge)) { continue; } if (!IsPlanAllocated(tempAlloc, *plan.get())) { continue; } if (!ArePlansAllowedToMerge(sPlan, *plan.get(), edge)) { continue; } // Add current part and plan to the combination, // no glue is required. Current part is SISO and // has a single input/output Combination section = comb + Combination(part, *plan.get()); // Options to be estimated Combinations options = { result, ContinueSection(nextPart, section, tempAlloc) }; result = GetBestCombination(options); } } return result; } // This function finds the best combination from the current part // to the end of the graph. The resul is unique given the part. // // The retuned value of this function should be cached // // PART || COMBINATION // =================================== // partA || CombinationX // ----------------------------------- // partB || CombinationY // ----------------------------------- // ... || ... // ----------------------------------- // partN || CombinationW // ----------------------------------- // Combination Combiner::FindBestCombinationForPartImpl(const Part& part) { // This is going to be a new combination, so this // is empty initialized Combination result = {}; // There are some scenarios: // - Part is Single Input Single Output i.e. SISO // - Part is Single Input Multiple Output i.e. SIMO // - Part is Multiple Input Multiple Output i.e. MIMO // - Part is Multiple Input Sinlge Output i.e. MISO // - Part is Output i.e. no next part // - Part is Input i.e. SO or MO if (IsPartSo(part)) { // SISO and MISO are equivalent since what counts // is the number of output parts which in both cases // is one const Part& nextPart = *(GetDestinationParts(part).at(0).first); assert(GetDestinationParts(part).size() == 1); for (const auto& plan : part.m_Plans) { if (!IsPlanInputGlueable(*plan.get())) { continue; } // This is the start of a new section, reset the allocated Sram SramAllocator alloc(m_Caps.GetTotalSramSize() / m_Caps.GetNumberOfSrams()); Combination head(part, *plan.get()); Combinations options = { result, ContinueSection(nextPart, head, alloc) }; result = GetBestCombination(options); } } else { // ContinueSection operates only on SISO parts // so Output parts and Multiple Output parts // cannot be merged for now // Select best plan for the part for (const auto& plan : part.m_Plans) { if (!IsPlanInputGlueable(*plan.get())) { continue; } // Glue will be added later on Combination head(part, *plan.get()); Combinations options = { result, head }; result = GetBestCombination(options); } // SIMO part: // // It cannot create a section, it needs to start as // many new sections as the number of output parts // // MIMO part: // // This part is a lonely one, it needs to start // as many new sections as the number of output parts // Some of the ongoing sections might not be ended, the // recursion goes depth first and does not walk the parts // necessarily in a topological order that allows to end // all the input sections to a MIMO/MISO part. For exmaple // the input edge into a MISO part might come from a differnt // input of the whole graph. This should not be a concern for (const auto& destPart : GetDestinationParts(part)) { // Glue needs to be added here for each destination const auto& sources = GetSourceParts(*destPart.first); result = GluePartToCombination(*destPart.first, result + FindBestCombinationForPart(*destPart.first), sources); } } return result; } // TODO: This implement a caching mechanism on part // PartId -> Best Combination // // PART || COMBINATION // =================================== // partA || CombinationX // ----------------------------------- // partB || CombinationY // ----------------------------------- // ... || ... // ----------------------------------- // partN || CombinationW // ----------------------------------- // Combination Combiner::FindBestCombinationForPart(const Part& part) { Combination result; UpdateStats(StatsType::FindBestCombinationForPart); auto combIt = m_CombinationPerPartMap.find(&part); if (combIt != m_CombinationPerPartMap.end()) { result = combIt->second; } else { result = FindBestCombinationForPartImpl(part); m_CombinationPerPartMap.insert(std::make_pair(&part, result)); DumpDebugInfo(m_GraphOfParts, { result }, m_Stats, m_DebuggingContext, "FindBestCombinationForPart/Part" + std::to_string(part.m_PartId)); } return result; } Combiner::Combiner(const GraphOfParts& graphOfParts, const HardwareCapabilities& caps, const EstimationOptions& estOpt, const DebuggingContext& debuggingContext) : m_GraphOfParts(graphOfParts) , m_Caps(caps) , m_EstOpt(estOpt) , m_DebuggingContext(debuggingContext) {} void Combiner::Run() { using namespace ethosn::utils; if (m_DebuggingContext.m_DebugInfo->m_DumpDebugFiles >= CompilationOptions::DebugLevel::High) { MakeDirectory(m_DebuggingContext.GetAbsolutePathOutputFileName("FindBestCombinationForPart").c_str()); } for (auto&& part : m_GraphOfParts.m_Parts) { // Process only parts that have an input node if (!IsPartInput(*part.get())) { continue; } // Result combinations (each per input) can just be merged m_BestCombination = m_BestCombination + FindBestCombinationForPart(*part.get()); } } Combinations Cascading::Combine(const GraphOfParts& parts) { ETHOSN_UNUSED(parts); m_Combiner.Run(); return { m_Combiner.GetBestCombination() }; } // Take in input a combination and generate an OpGraph. // This is used in: // - Combiner logic: it needs to estimate the combination and this is done on an // OpGraph in order to select the best combination between two // or more // - Estimation logic: it can only estimate OpGraphs and not raw combinations. OpGraph GetOpGraphForCombination(const Combination& combination, const GraphOfParts& parts) { OpGraph result; // When adjacent plans are connected without any glue, the output buffer of one plan becomes the input buffer of the // next plan. In the merged graph representation that we are creating, we therefore need only one buffer object. // This map is used to get the buffer that we are using to represent two buffers that have been merged. std::map<Buffer*, Buffer*> mergedBuffers; auto getEffectiveBuffer = [&mergedBuffers](Buffer* b) { auto it = mergedBuffers.find(b); return it != mergedBuffers.end() ? it->second : b; }; // For each Edge connecting two Parts, which Buffer should the destination part connect to, in order to get that input. // A glue may also need to be inserted which connects to this buffer. // If there is no glue between two parts, then the source // part's output buffer should be re-used directly (as that buffer is then shared between the two plans). std::map<const Edge*, Buffer*> edgeConnectionBuffers; // For each outgoing edge from a plan, the glue that needs to be inserted there (if any) std::map<const Edge*, const Glue*> glues; // Add each Elem, one at a time. It is assumed that these are toplogically sorted, so we can assume that all // parts used as input to each part have already been processed. for (auto& elemIt : combination.m_Elems) { const Part& part = parts.GetPart(elemIt.first); const Plan& plan = part.GetPlan(elemIt.second.m_PlanId); // Add any glues for each incoming edge of this Part, and remember which Op we will need to connect the plan's // input buffers to std::map<const Edge*, Op*> incomingGlueOps; std::vector<const Edge*> inputEdges = part.GetInputs(); for (auto inputEdge : inputEdges) { auto glueIt = glues.find(inputEdge); const Glue* glue = glueIt != glues.end() ? glueIt->second : nullptr; if (glue != nullptr) { // Add Ops and Buffers from the glue, no connections yet. for (Buffer* b : glue->m_Graph.GetBuffers()) { result.AddBuffer(b); } for (Op* o : glue->m_Graph.GetOps()) { result.AddOp(o); } // Add internal connections within the glue for (Buffer* b : glue->m_Graph.GetBuffers()) { Op* producer = glue->m_Graph.GetProducer(b); if (producer) { result.SetProducer(b, producer); } for (auto consumer : glue->m_Graph.GetConsumers(b)) { result.AddConsumer(b, consumer.first, consumer.second); } } // Connect to the input plan result.AddConsumer(edgeConnectionBuffers.at(inputEdge), glue->m_InputSlot.first, glue->m_InputSlot.second); // Remember the output Op from this glue, to connect to our plan incomingGlueOps[inputEdge] = glue->m_Output; } } for (Buffer* b : plan.m_OpGraph.GetBuffers()) { // Don't add a buffer if its an input to the plan, and it is shared with the input plan // (i.e. no glue between them). // Instead, remap it to the one we already have Buffer* sharedBuffer = nullptr; auto inputEdgeIt = plan.m_InputMappings.find(b); if (inputEdgeIt != plan.m_InputMappings.end()) { Edge* inputEdge = inputEdgeIt->second; if (incomingGlueOps.find(inputEdge) == incomingGlueOps.end()) { sharedBuffer = edgeConnectionBuffers.find(inputEdge)->second; // This buffer itself may have been merged (e.g. for plans that have a single buffer for both // input and output, like reinterpret Dram) sharedBuffer = getEffectiveBuffer(sharedBuffer); } } if (sharedBuffer && result.Contains(sharedBuffer)) { // Record the fact that this buffer has been shared, so that when making connections (below), we // connect to the correct buffer. mergedBuffers[b] = sharedBuffer; } else { result.AddBuffer(b); } } // Add Ops from the Plan for (Op* o : plan.m_OpGraph.GetOps()) { result.AddOp(o); } // Add internal connections (within the Plan), noting that some buffers will have been merged and // that we need to make the connection to the correct one. for (Buffer* b : plan.m_OpGraph.GetBuffers()) { Op* producer = plan.m_OpGraph.GetProducer(b); if (producer) { result.SetProducer(getEffectiveBuffer(b), producer); } for (auto consumer : plan.m_OpGraph.GetConsumers(b)) { result.AddConsumer(getEffectiveBuffer(b), consumer.first, consumer.second); } } // Connect this Plan's inputs to the glues we take input from. // If we are instead connected to a plan directly (without any glue), then nothing needs to be done // because our input buffer will have been replaced by the output buffer from that plan, // so we are already connected for (auto input : plan.m_InputMappings) { Buffer* ourBuffer = input.first; Edge* inputEdge = input.second; auto glueOpIt = incomingGlueOps.find(inputEdge); if (glueOpIt != incomingGlueOps.end()) { result.SetProducer(ourBuffer, glueOpIt->second); } } // Store our output connections for future plans, and any glues on our outputs for (auto output : plan.m_OutputMappings) { for (Edge* outputEdge : output.second->GetOutputs()) { edgeConnectionBuffers[outputEdge] = output.first; auto glueIt = elemIt.second.m_Glues.find(outputEdge); if (glueIt != elemIt.second.m_Glues.end() && glueIt->second && !glueIt->second->m_Graph.GetOps().empty()) { glues[outputEdge] = glueIt->second; } } } } return result; } } // namespace support_library } // namespace ethosn
37.554598
125
0.606091
[ "object", "shape", "vector" ]
ee483779e4880406280412f01dad370a5b205bae
4,156
cpp
C++
src/core/csr/measures/allele_frequency.cpp
gmagoon/octopus
493643d8503239aead9c7e8a7f8bc19fb97b37d5
[ "MIT" ]
1
2018-08-21T23:34:28.000Z
2018-08-21T23:34:28.000Z
src/core/csr/measures/allele_frequency.cpp
gmagoon/octopus
493643d8503239aead9c7e8a7f8bc19fb97b37d5
[ "MIT" ]
null
null
null
src/core/csr/measures/allele_frequency.cpp
gmagoon/octopus
493643d8503239aead9c7e8a7f8bc19fb97b37d5
[ "MIT" ]
null
null
null
// Copyright (c) 2015-2018 Daniel Cooke // Use of this source code is governed by the MIT license that can be found in the LICENSE file. #include "allele_frequency.hpp" #include <algorithm> #include <iterator> #include <boost/variant.hpp> #include "core/tools/read_assigner.hpp" #include "core/types/allele.hpp" #include "io/variant/vcf_record.hpp" #include "io/variant/vcf_spec.hpp" #include "utils/genotype_reader.hpp" #include "../facets/samples.hpp" #include "../facets/read_assignments.hpp" namespace octopus { namespace csr { const std::string AlleleFrequency::name_ = "AF"; std::unique_ptr<Measure> AlleleFrequency::do_clone() const { return std::make_unique<AlleleFrequency>(*this); } namespace { bool is_canonical(const VcfRecord::NucleotideSequence& allele) noexcept { const static VcfRecord::NucleotideSequence deleted_allele {vcfspec::deletedBase}; return !(allele == vcfspec::missingValue || allele == deleted_allele); } bool has_called_alt_allele(const VcfRecord& call, const VcfRecord::SampleName& sample) { if (!call.has_genotypes()) return true; const auto& genotype = get_genotype(call, sample); return std::any_of(std::cbegin(genotype), std::cend(genotype), [&] (const auto& allele) { return allele != call.ref() && is_canonical(allele); }); } bool is_evaluable(const VcfRecord& call, const VcfRecord::SampleName& sample) { return has_called_alt_allele(call, sample); } } // namespace Measure::ResultType AlleleFrequency::do_evaluate(const VcfRecord& call, const FacetMap& facets) const { const auto& samples = get_value<Samples>(facets.at("Samples")); const auto& assignments = get_value<ReadAssignments>(facets.at("ReadAssignments")).support; std::vector<boost::optional<double>> result {}; result.reserve(samples.size()); for (const auto& sample : samples) { boost::optional<double> sample_result {}; if (is_evaluable(call, sample)) { const auto& sample_assignments = assignments.at(sample); std::vector<Allele> alleles; bool has_ref; std::tie(alleles, has_ref) = get_called_alleles(call, sample, true); assert(!alleles.empty()); std::size_t read_count {0}; std::vector<unsigned> allele_counts(alleles.size()); for (const auto& p : sample_assignments) { const auto& haplotype = p.first; const auto& reads = p.second; const auto haplotype_support_depth = count_overlapped(reads, call); if (haplotype_support_depth > 0) { std::transform(std::cbegin(alleles), std::cend(alleles), std::cbegin(allele_counts), std::begin(allele_counts), [&] (const auto& allele, auto count) { if (haplotype.includes(allele)) { count += haplotype_support_depth; } return count; }); read_count += haplotype_support_depth; } } if (read_count > 0) { auto first_called_count_itr = std::cbegin(allele_counts); if (has_ref) ++first_called_count_itr; assert(first_called_count_itr != std::cend(allele_counts)); const auto min_count_itr = std::min_element(first_called_count_itr, std::cend(allele_counts)); sample_result = static_cast<double>(*min_count_itr) / read_count; } } result.push_back(sample_result); } return result; } Measure::ResultCardinality AlleleFrequency::do_cardinality() const noexcept { return ResultCardinality::num_samples; } const std::string& AlleleFrequency::do_name() const { return name_; } std::string AlleleFrequency::do_describe() const { return "Minor allele frequency of ALT alleles"; } std::vector<std::string> AlleleFrequency::do_requirements() const { return {"Samples", "ReadAssignments"}; } } // namespace csr } // namespace octopus
35.827586
131
0.635948
[ "vector", "transform" ]
ee4a6fd618e41166bf449e9e7f7056fadb958932
10,074
cpp
C++
EngineTest/EngineTest/Source/Core/M5IniFile.cpp
mattCasanova/Mach5
0d98a092bee4c38816911c118fd6552a40850201
[ "MIT" ]
16
2017-06-30T12:49:24.000Z
2021-01-23T17:39:35.000Z
EngineTest/EngineTest/Source/Core/M5IniFile.cpp
mattCasanova/Mach5
0d98a092bee4c38816911c118fd6552a40850201
[ "MIT" ]
2
2017-03-09T20:35:26.000Z
2020-03-20T01:09:40.000Z
EngineTest/EngineTest/Source/Core/M5IniFile.cpp
mattCasanova/Mach5
0d98a092bee4c38816911c118fd6552a40850201
[ "MIT" ]
2
2018-10-21T01:33:17.000Z
2020-03-19T09:30:19.000Z
/******************************************************************************/ /*! file M5IniFile.cpp \author Matt Casanova \par email: lazersquad\@gmail.com \par Mach5 Game Engine \date 2016/08/16 Class to read from or write to an ini file */ /******************************************************************************/ #include "M5IniFile.h" #include <fstream> #include <ostream> /******************************************************************************/ /*! Default Constructor for M5IniFile */ /******************************************************************************/ M5IniFile::M5IniFile(void) { m_sections.insert(std::make_pair("", KeyValMap())); SetToSection(""); } /******************************************************************************/ /*! Reads an .ini file and stores the data for later searching. \param [in] fileName The name of the .ini file to read. */ /******************************************************************************/ void M5IniFile::ReadFile(const std::string& fileName) { //Clear old data m_currSection = 0; m_sections.clear(); std::ifstream inFile(fileName, std::ios::in); //check if the file was opened properly M5DEBUG_ASSERT(inFile.is_open(), "IniFile could not be opened"); StringMapPair currSection;//First section has no name, it's the global section std::string line; while (!inFile.eof()) { //Read a line if (!std::getline(inFile, line)) break; //Get end points size_t begin = 0, end = line.length(); RemoveLeadingSpaces(line, begin, end); //Ignore empty lines and ; comments if (begin >= (end) || line[begin] == ';') { continue; } else if (line[begin] == '[')//New section ParseSectionName(currSection, line, begin, end); else //Key/value ParseKeyValue(currSection, line, begin, end); }//end while //Add the last section m_sections.insert(currSection); inFile.close(); SetToSection(""); } /******************************************************************************/ /*! Sets the active search section to the specified sectionName of the ini file. \param [in] sectionName The name of the section to set active. */ /******************************************************************************/ void M5IniFile::SetToSection(const std::string& sectionName) { SectionMapItor itor = m_sections.find(sectionName); M5DEBUG_ASSERT(itor != m_sections.end(), "Section name could not be found!") m_currSection = &(itor->second); } /******************************************************************************/ /*! Takes a single string and separates the key and the value, then stores them in sPair. \param [out] sPair The storage for the key and the value. \param [in] line The line containing the key and the value \param [in, out] begin The logical beginning of the line \param [in, out] end The logical ending of the line */ /******************************************************************************/ void M5IniFile::SeperateKeyValueFromLine(StringPair& sPair, const std::string& line, size_t& begin, size_t& end) const { size_t firstEnd, secondBegin; //Find the equal sign firstEnd = secondBegin = line.find_first_of('=', begin); //if(begin >= firstEnd) M5DEBUG_ASSERT(firstEnd != std::string::npos, "There was no equal sign in key value"); //Remove spaces between key and = RemoveTrailingSpaces(line, begin, --firstEnd); //Remove spaces in front of value RemoveLeadingSpaces(line, ++secondBegin, end); //check for ; comments after value size_t commentEnd = line.find_first_of(';', secondBegin); if (commentEnd != std::string::npos) { end = commentEnd; } //Remove spaces after value RemoveTrailingSpaces(line, secondBegin, --end); //create my key and value sPair.first = line.substr(begin, firstEnd - begin + 1); sPair.second = line.substr(secondBegin, end - secondBegin + 1); } /******************************************************************************/ /*! Removes brackets and extra spaces around the section name \param [in, out] line The line to change \param [in, out] begin The logical beginning of the line. \param [in, out] end The logical ending of the line. */ /******************************************************************************/ void M5IniFile::GetSectionName(std::string& line, size_t& begin, size_t& end) const { ++begin;//We know the first character is [ RemoveLeadingSpaces(line, begin, end); //find start of name end = line.find_first_of(']');//find the end of section bracket //There is no ending ] character so the section name is invalid M5DEBUG_ASSERT(begin != end && static_cast<size_t>(end) != std::string::npos, "Invalid Section Name"); RemoveTrailingSpaces(line, begin, --end);//we know end is ] line = line.substr(begin, end - begin + 1); } /******************************************************************************/ /*! Removes leading spaces and tabs from a line. \param [in, out] line The line change. \param [in, out] begin The logical beginning of the line. \param [in, out] end The logical ending of the line. */ /******************************************************************************/ void M5IniFile::RemoveLeadingSpaces(const std::string& line, size_t& begin, size_t& end) const { //if line size is zero we are done if (begin >= end) return; //Start at the beginning and make sure there are no spaces or tabs; while (line[begin] == ' ' || line[begin] == '\t') { if (begin == std::string::npos) break; ++begin; } } /******************************************************************************/ /*! Removes trailing spaces and tabs from a line. \param [in] line The line change. \param [in, out] begin The logical beginning of the line. \param [in, out] end The logical ending of the line. */ /******************************************************************************/ void M5IniFile::RemoveTrailingSpaces(const std::string& line, size_t& begin, size_t& end) const { if (begin >= end) return; while (line[end] == ' ' || line[end] == '\t') --end; } /******************************************************************************/ /*! The function to extract a section name from a line. \param [in, out] currSection The previous section info that must be added and then cleared. \param [in, out] line The line change. \param [in, out] begin The logical beginning of the line. \param [in, out] end The logical ending of the line. */ /******************************************************************************/ void M5IniFile::ParseSectionName(StringMapPair& currSection, std::string& line, size_t& begin, size_t& end) { m_sections.insert(currSection);//We are on a new section, so insert previous GetSectionName(line, begin, end); //Start the new section here currSection.first = line; currSection.second.clear(); } /******************************************************************************/ /*! The function to extract a key and value from a line. \param [in, out] currSection The section to add this key and value to. \param [in, out] line The line change. \param [in, out] begin The logical beginning of the line. \param [in, out] end The logical ending of the line. */ /******************************************************************************/ void M5IniFile::ParseKeyValue(StringMapPair& currSection, std::string& line, size_t& begin, size_t& end) { StringPair sPair; SeperateKeyValueFromLine(sPair, line, begin, end); currSection.second.insert(sPair); } /******************************************************************************/ /*! Adds a section to the to M5IniFile. \attention This won't be added to any files until you call WriteFile \param [in] sectionName The section name to add. */ /******************************************************************************/ void M5IniFile::AddSection(const std::string& sectionName) { SectionMapCItor found = m_sections.find(sectionName); if (found == m_sections.end()) m_sections.insert(std::make_pair(sectionName, KeyValMap())); } /******************************************************************************/ /*! Writes the current contents of the M5IniFile class to a file. \param [in] fileName The file to create or overwrite */ /******************************************************************************/ void M5IniFile::WriteFile(const std::string& fileName) const { //Create out file and check if it can be opened. std::ofstream outFile(fileName, std::ios::out); M5DEBUG_ASSERT(outFile.is_open(), "IniFile Could not be opened."); //First see if empty section SectionMapCItor emptySection = m_sections.find(""); if (emptySection == m_sections.end()) { outFile << ";The IniFile object was empty when writing this file" << std::endl; outFile.close(); } //Alwasy write global section first KeyValMapCItor mapBegin = emptySection->second.begin(); KeyValMapCItor mapEnd = emptySection->second.end(); for (; mapBegin != mapEnd; ++mapBegin) outFile << mapBegin->first << " = " << mapBegin->second << std::endl; outFile << std::endl; //Then loop through the rest of the sections SectionMapCItor sectionBegin = m_sections.begin(); SectionMapCItor sectionEnd = m_sections.end(); for (; sectionBegin != sectionEnd; ++sectionBegin) { //If we find the global/empty section, just skip if (sectionBegin->first == "") continue; mapBegin = sectionBegin->second.begin(); mapEnd = sectionBegin->second.end(); //print section name then key/value pairs outFile << "[" << sectionBegin->first << "]" << std::endl; for (; mapBegin != mapEnd; ++mapBegin) outFile << mapBegin->first << " = " << mapBegin->second << std::endl; outFile << std::endl; } outFile.close(); }
29.629412
88
0.544074
[ "object" ]
ee4e40b378d24aa27ca284f1364a91f51e98ca83
2,543
hpp
C++
include/algolib/mathmat/primes.hpp
ref-humbold/AlgoLib_CPlusPlus
9c39138f4d4cd9a8a7db62a9e7495b63aefe069c
[ "Apache-2.0" ]
null
null
null
include/algolib/mathmat/primes.hpp
ref-humbold/AlgoLib_CPlusPlus
9c39138f4d4cd9a8a7db62a9e7495b63aefe069c
[ "Apache-2.0" ]
null
null
null
include/algolib/mathmat/primes.hpp
ref-humbold/AlgoLib_CPlusPlus
9c39138f4d4cd9a8a7db62a9e7495b63aefe069c
[ "Apache-2.0" ]
1
2021-04-05T12:11:38.000Z
2021-04-05T12:11:38.000Z
/**! * \file primes.hpp * \brief Algorithms for prime numbers */ #ifndef PRIMES_HPP_ #define PRIMES_HPP_ #include <cstdlib> #include <ctime> #include <algorithm> #include <vector> #include "algolib/mathmat/maths.hpp" namespace algolib::mathmat { #pragma region find_primes /*! * \brief Finds prime numbers inside a range of integers. * \param min_number minimal number in range, inclusive * \param max_number maximal number in range, exclusive * \return vector of prime numbers */ std::vector<size_t> find_primes(size_t min_number, size_t max_number); /*! * \brief Finds prime numbers inside a range of integers starting from 0. * \param max_number maximal number in range, exclusive * \return vector of prime numbers */ inline std::vector<size_t> find_primes(size_t max_number) { return find_primes(0, max_number); } #pragma endregion #pragma region test_fermat /*! * \brief Checks whether given number is prime running Fermat's prime test. * \param number number to be checked * \return \c true if the number is probably prime, otherwise \c false */ bool test_fermat(int number); /*! * \brief Checks whether given number is prime running Fermat's prime test. * \param number number to be checked * \return \c true if the number is probably prime, otherwise \c false */ bool test_fermat(long number); /*! * \brief Checks whether given number is prime running Fermat's prime test. * \param number number to be checked * \return \c true if the number is probably prime, otherwise \c false */ bool test_fermat(long long number); #pragma endregion #pragma region test_miller /*! * \brief Checks whether given number is prime running Miller-Rabin's prime test. * \param number number to be checked * \return \c true if the number is probably prime, otherwise \c false */ bool test_miller(int number); /*! * \brief Checks whether given number is prime running Miller-Rabin's prime test. * \param number number to be checked * \return \c true if the number is probably prime, otherwise \c false */ bool test_miller(long number); /*! * \brief Checks whether given number is prime running Miller-Rabin's prime test. * \param number number to be checked * \return \c true if the number is probably prime, otherwise \c false */ bool test_miller(long long number); #pragma endregion } #endif
28.897727
85
0.679119
[ "vector" ]
ee50b1571344cfc2f69f80e07638001f9d8500fd
29,239
cpp
C++
src/materials/CMaterial.cpp
Yung-Quant/elec490
09314b1c3f4f061effa396c104f094f28a0aabff
[ "BSD-3-Clause" ]
null
null
null
src/materials/CMaterial.cpp
Yung-Quant/elec490
09314b1c3f4f061effa396c104f094f28a0aabff
[ "BSD-3-Clause" ]
null
null
null
src/materials/CMaterial.cpp
Yung-Quant/elec490
09314b1c3f4f061effa396c104f094f28a0aabff
[ "BSD-3-Clause" ]
null
null
null
//============================================================================== /* Software License Agreement (BSD License) Copyright (c) 2003-2016, CHAI3D. (www.chai3d.org) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of CHAI3D 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. \author <http://www.chai3d.org> \author Francois Conti \version $MAJOR.$MINOR.$RELEASE $Rev: 1869 $ */ //============================================================================== //------------------------------------------------------------------------------ #include "materials/CMaterial.h" //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ namespace chai3d { //------------------------------------------------------------------------------ //============================================================================== /*! Constructor of cMaterial. */ //============================================================================== cMaterial::cMaterial() { // default graphic settings m_ambient.set(0.3f, 0.3f, 0.3f, 1.0f); m_diffuse.set(0.7f, 0.7f, 0.7f, 1.0f); m_specular.set(1.0f, 1.0f, 1.0f, 1.0f); m_emission.set(0.0f, 0.0f, 0.0f, 1.0f); m_shininess = 64; // default haptic settings m_viscosity = 0.0; m_stiffness = 0.0; m_damping = 0.0; m_staticFriction = 0.0; m_dynamicFriction = 0.0; m_textureLevel = 0.0; m_vibrationFrequency = 0.0; m_vibrationAmplitude = 0.0; m_stickSlipForceMax = 0.0; m_stickSlipStiffness = 0.0; m_useHapticFriction = false; m_useHapticTexture = false; m_useHapticShading = false; m_hapticFrontSideOfTriangles = true; m_hapticBackSideOfTriangles = false; m_audioImpactBuffer = NULL; m_audioFrictionBuffer = NULL; m_audioImpactGain = 0.0; m_audioFrictionGain = 0.0; m_audioFrictionPitchGain = 0.0; m_audioFrictionPitchOffset = 1.0; // set all modification flags to false setModificationFlags(false); } //============================================================================== /*! This method creates a copy of itself. \return Pointer to new instance. */ //============================================================================== cMaterialPtr cMaterial::copy() { // create new instance cMaterialPtr obj = create(); // copy material properties obj->m_ambient = m_ambient; obj->m_diffuse = m_diffuse; obj->m_specular = m_specular; obj->m_emission = m_emission; obj->m_shininess = m_shininess; obj->m_viscosity = m_viscosity; obj->m_stiffness = m_stiffness; obj->m_damping = m_damping; obj->m_staticFriction = m_staticFriction; obj->m_dynamicFriction = m_dynamicFriction; obj->m_textureLevel = m_textureLevel; obj->m_vibrationFrequency = m_vibrationFrequency; obj->m_vibrationAmplitude = m_vibrationAmplitude; obj->m_magnetMaxForce = m_magnetMaxForce; obj->m_magnetMaxDistance = m_magnetMaxDistance; obj->m_stickSlipForceMax = m_stickSlipForceMax; obj->m_stickSlipStiffness = m_stickSlipStiffness; obj->m_useHapticFriction = m_useHapticFriction; obj->m_useHapticTexture = m_useHapticTexture; obj->m_useHapticShading = m_useHapticShading; obj->m_hapticFrontSideOfTriangles = m_hapticFrontSideOfTriangles; obj->m_hapticBackSideOfTriangles = m_hapticBackSideOfTriangles; obj->m_audioImpactBuffer = m_audioImpactBuffer; obj->m_audioFrictionBuffer = m_audioFrictionBuffer; obj->m_audioImpactGain = m_audioImpactGain; obj->m_audioFrictionGain = m_audioFrictionGain; obj->m_audioFrictionPitchGain = m_audioFrictionPitchGain; obj->m_audioFrictionPitchOffset = m_audioFrictionPitchOffset; // reset all flags obj->setModificationFlags(false); // return return (obj); } //============================================================================== /*! This method sets the transparency level by setting the alpha value to all color members including __ambient__, __diffuse__, __specular__, and __emission__. \param a_levelTransparency Level of transparency. */ //============================================================================== void cMaterial::setTransparencyLevel(const float a_levelTransparency) { // check that value is within range [0.0 - 1.0] float level = cClamp(a_levelTransparency, 0.0f, 1.0f); // apply new value m_ambient.setA(level); m_diffuse.setA(level); m_specular.setA(level); m_emission.setA(level); } //============================================================================== /*! This method sets the level of shininess. The value is clamped to range from 0 to 128. \param a_shininess Level of shininess */ //============================================================================== void cMaterial::setShininess(const GLuint a_shininess) { // update value and check range m_shininess = cClamp(a_shininess, (GLuint)0, (GLuint)128); // mark variable as modified m_flag_shininess = true; } //============================================================================== /*! This method defines a color property for this material. \param a_red Red component \param a_green Green component \param a_blue Blue component \param a_alpha Alpha component */ //============================================================================== void cMaterial::setColorf(const GLfloat a_red, const GLfloat a_green, const GLfloat a_blue, const GLfloat a_alpha) { m_diffuse.set(a_red, a_green, a_blue, a_alpha); updateColors(); } //============================================================================== /*! This method defines a color property for this material. \param a_color Color. */ //============================================================================== void cMaterial::setColor(cColorf& a_color) { m_diffuse = a_color; updateColors(); } //============================================================================== /*! Define a color property for the material. \param a_color Color. */ //============================================================================== void cMaterial::setColor(cColorb& a_color) { m_diffuse = a_color.getColorf(); updateColors(); } //============================================================================== /*! When a new color is defined by calling methods such as \ref setColorf() or \ref setRed(), the selected color is first set to the diffuse component. This method updates the ambient component by setting it equal to 50% of the diffuse color. The specular color is finally set to pure white. */ //============================================================================== void cMaterial::updateColors() { float level = 0.5; m_ambient.setR(level * m_diffuse.getR()); m_ambient.setG(level * m_diffuse.getG()); m_ambient.setB(level * m_diffuse.getB()); m_ambient.setA(m_diffuse.getA()); m_specular.set(1.0, 1.0, 1.0, m_diffuse.getA()); } //============================================================================== /*! This method sets the level of stiffness for this material. The value is clamped to be a non-negative value. \param a_stiffness Level of stiffness. */ //============================================================================== void cMaterial::setStiffness(const double a_stiffness) { // update value m_stiffness = cClamp0(a_stiffness); // mark variable as modified m_flag_stiffness = true; } //============================================================================== /*! This method sets the level of damping. \param a_damping Level of damping. */ //============================================================================== void cMaterial::setDamping(const double a_damping) { // update value m_damping = a_damping; // mark variable as modified m_flag_damping = true; } //============================================================================== /*! This method sets the level of static friction. The value is clamped to be a non-negative value. \param a_friction Level of friction. */ //============================================================================== void cMaterial::setStaticFriction(const double a_friction) { // update value m_staticFriction = cClamp0(a_friction); // enable friction rendering if required if ((m_staticFriction > 0) || (m_dynamicFriction > 0)) { setUseHapticFriction(true); } else { setUseHapticFriction(false); } // mark variable as modified m_flag_staticFriction = true; } //============================================================================== /*! This method sets the level of dynamic friction. The value is clamped to be a non-negative value. \param a_friction Level of friction. */ //============================================================================== void cMaterial::setDynamicFriction(const double a_friction) { // update value m_dynamicFriction = cClamp0(a_friction); // enable friction rendering if required if ((m_staticFriction > 0) || (m_dynamicFriction > 0)) { setUseHapticFriction(true); } else { setUseHapticFriction(false); } // mark variable as modified m_flag_dynamicFriction = true; } //============================================================================== /*! This method sets the intensity at which the texture map of an object is perceived. \param a_textureLevel Intensity level. */ //============================================================================== void cMaterial::setTextureLevel(const double a_textureLevel) { // update value m_textureLevel = a_textureLevel; // enable texture rendering if required if (m_textureLevel > 0) { setUseHapticTexture(true); } else { setUseHapticTexture(false); } // mark variable as modified m_flag_textureLevel = true; } //============================================================================== /*! This method sets the level of viscosity. The value is clamped to be a non-negative value. \param a_viscosity Level of viscosity. */ //============================================================================== void cMaterial::setViscosity(const double a_viscosity) { // update value m_viscosity = cClamp0(a_viscosity); // mark variable as modified m_flag_viscosity = true; } //============================================================================== /*! This method sets the frequency of vibration. The value is clamped to be a non-negative value. \param a_vibrationFrequency Frequency of vibration [Hz]. */ //============================================================================== void cMaterial::setVibrationFrequency(const double a_vibrationFrequency) { // update value m_vibrationFrequency = cClamp0(a_vibrationFrequency); // mark variable as modified m_flag_vibrationFrequency = true; } //============================================================================== /*! This method set the amplitude of vibration. The value is clamped to be a non-negative value. \param a_vibrationAmplitude Amplitude of vibrations [N]. */ //============================================================================== void cMaterial::setVibrationAmplitude(const double a_vibrationAmplitude) { // update value m_vibrationAmplitude = cClamp0(a_vibrationAmplitude); // mark variable as modified m_flag_vibrationAmplitude = true; } //============================================================================== /*! This method sets the maximum force applied by the magnet [N]. The value is clamped to be a non-negative value. \param a_magnetMaxForce Maximum force of magnet. */ //============================================================================== void cMaterial::setMagnetMaxForce(const double a_magnetMaxForce) { // update value m_magnetMaxForce = cClamp0(a_magnetMaxForce); // mark variable as modified m_flag_magnetMaxForce = true; } //============================================================================== /*! This method sets the maximum distance from which the magnetic force can be perceived [m] \param a_magnetMaxDistance Maximum distance from object where magnet is active. */ //============================================================================== void cMaterial::setMagnetMaxDistance(const double a_magnetMaxDistance) { // update value m_magnetMaxDistance = cClamp0(a_magnetMaxDistance); // mark variable as modified m_flag_magnetMaxDistance = true; } //============================================================================== /*! This method sets the maximum force threshold for the stick and slip model [N]. The value is clamped to be a non-negative value. \param a_stickSlipForceMax Maximum force threshold. */ //============================================================================== void cMaterial::setStickSlipForceMax(const double a_stickSlipForceMax) { // update value m_stickSlipForceMax = cClamp0(a_stickSlipForceMax); // mark variable as modified m_flag_stickSlipForceMax = true; } //============================================================================== /*! This method sets the stiffness for the stick and slip model [N/m]. \param a_stickSlipStiffness Stiffness property. */ //============================================================================== void cMaterial::setStickSlipStiffness(const double a_stickSlipStiffness) { // update value m_stickSlipStiffness = cClamp0(a_stickSlipStiffness); // mark variable as modified m_flag_stickSlipStiffness = true; } //============================================================================== /*! This method enables or disables rendering of haptic friction. \param a_useHapticFriction If __true__, haptic friction rendering in enabled. */ //============================================================================== void cMaterial::setUseHapticFriction(const bool a_useHapticFriction) { // update value m_useHapticFriction = a_useHapticFriction; // mark variable as modified m_flag_useHapticFriction = true; } //============================================================================== /*! This method enables or disables haptic texture rendering. \param a_useHapticTexture If __true__, haptic texture rendering in enabled. */ //============================================================================== void cMaterial::setUseHapticTexture(const bool a_useHapticTexture) { // update value m_useHapticTexture = a_useHapticTexture; // mark variable as modified m_flag_useHapticTexture = true; } //============================================================================== /*! This method enables or disables haptic shading. \param a_useHapticShading If __true__, haptic shading in enabled. */ //============================================================================== void cMaterial::setUseHapticShading(const bool a_useHapticShading) { // update value m_useHapticShading = a_useHapticShading; // mark variable as modified m_flag_useHapticShading = true; } //============================================================================== /*! This method enables or disables __front__ side haptic rendering. \n If \p a_enabled is set to __true__, then haptic rendering occurs on front side of triangles. This option applies to mesh objects which are rendered using the proxy force algorithm. \param a_enabled If __true__, then haptic rendering is enabled. */ //============================================================================== void cMaterial::setHapticTriangleFrontSide(const bool a_enabled) { // update value m_hapticFrontSideOfTriangles = a_enabled; // mark variable as modified m_flag_hapticFrontSideOfTriangles = true; } //============================================================================== /*! This method enables or disables __back__ side haptic rendering. \n If \p a_enabled is set to __true__, then haptic rendering occurs on back side of triangles. This option applies to mesh objects which are rendered using the proxy force algorithm. \param a_enabled If __true__, then haptic rendering is enabled. */ //============================================================================== void cMaterial::setHapticTriangleBackSide(const bool a_enabled) { // update value m_hapticBackSideOfTriangles = a_enabled; // mark variable as modified m_flag_hapticBackSideOfTriangles = true; } //============================================================================== /*! This method defines which sides haptic rendering must occur with triangles. \param a_enableFrontSide If __true__, then haptic rendering is enabled for front sides. \param a_enableBackSide If __true__, then haptic rendering is enabled for back sides. */ //============================================================================== void cMaterial::setHapticTriangleSides(const bool a_enableFrontSide, const bool a_enableBackSide) { // update front side setHapticTriangleFrontSide(a_enableFrontSide); // update back side setHapticTriangleBackSide(a_enableBackSide); } //============================================================================== /*! This method sets an audio buffer associated with any impacts between a haptic tool and an object. \param a_audioImpactBuffer Audio buffer. */ //============================================================================== void cMaterial::setAudioImpactBuffer(cAudioBuffer* a_audioImpactBuffer) { // update value m_audioImpactBuffer = a_audioImpactBuffer; // mark variable as modified m_flag_audioImpactBuffer = true; } //============================================================================== /*! This method sets an audio buffer associated with any friction caused by a haptic tool touching an object. \param a_audioFrictionBuffer Audio buffer. */ //============================================================================== void cMaterial::setAudioFrictionBuffer(cAudioBuffer* a_audioFrictionBuffer) { // update value m_audioFrictionBuffer = a_audioFrictionBuffer; // mark variable as modified m_flag_audioFrictionBuffer = true; } //============================================================================== /*! This method sets the audio gain related to impact sounds. \param a_audioImpactGain Audio gain associated to impact. */ //============================================================================== void cMaterial::setAudioImpactGain(const double a_audioImpactGain) { // update value m_audioImpactGain = a_audioImpactGain; // mark variable as modified m_flag_audioImpactGain = true; } //============================================================================== /*! This method sets the audio gain related to friction sounds. \param a_audioFrictionGain Audio gain associated to friction. */ //============================================================================== void cMaterial::setAudioFrictionGain(const double a_audioFrictionGain) { // update value m_audioFrictionGain = a_audioFrictionGain; // mark variable as modified m_flag_audioFrictionGain = true; } //============================================================================== /*! This method sets the audio friction pitch gain. \param a_audioFrictionPitchGain Audio pitch gain associated to friction. */ //============================================================================== void cMaterial::setAudioFrictionPitchGain(const double a_audioFrictionPitchGain) { // update value m_audioFrictionPitchGain = a_audioFrictionPitchGain; // mark variable as modified m_flag_audioFrictionPitchGain = true; } //============================================================================== /*! This method sets the audio friction pitch offset. \param a_audioFrictionPitchOffset Audio pitch offset associated to friction. */ //============================================================================== void cMaterial::setAudioFrictionPitchOffset(const double a_audioFrictionPitchOffset) { // update value m_audioFrictionPitchOffset = a_audioFrictionPitchOffset; // mark variable as modified m_flag_audioFrictionPitchOffset = true; } //============================================================================== /*! This method renders this material using OpenGL. \param a_options Rendering options. */ //============================================================================== void cMaterial::render(cRenderOptions& a_options) { // check if materials should be rendered if (!a_options.m_render_materials) { return; } // render material #ifdef C_USE_OPENGL glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, (const float *)&m_ambient); glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, (const float *)&m_diffuse); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, (const float *)&m_specular); glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, (const float *)&m_emission); glMateriali(GL_FRONT_AND_BACK, GL_SHININESS, m_shininess); #endif } //============================================================================== /*! This method sets all the modification flags to a desired value. \param a_value Value to be assigned to modification flags. */ //============================================================================== void cMaterial::setModificationFlags(const bool a_value) { m_flag_shininess = a_value; m_flag_viscosity = a_value; m_flag_stiffness = a_value; m_flag_damping = a_value; m_flag_staticFriction = a_value; m_flag_dynamicFriction = a_value; m_flag_textureLevel = a_value; m_flag_vibrationFrequency = a_value; m_flag_vibrationAmplitude = a_value; m_flag_magnetMaxForce = a_value; m_flag_magnetMaxDistance = a_value; m_flag_stickSlipForceMax = a_value; m_flag_stickSlipStiffness = a_value; m_flag_useHapticTexture = a_value; m_flag_useHapticShading = a_value; m_flag_hapticFrontSideOfTriangles = a_value; m_flag_hapticBackSideOfTriangles = a_value; m_flag_audioImpactBuffer = a_value; m_flag_audioFrictionBuffer = a_value; m_flag_audioImpactGain = a_value; m_flag_audioFrictionGain = a_value; m_flag_audioFrictionPitchGain = a_value; m_flag_audioFrictionPitchOffset = a_value; m_ambient.setModificationFlags(a_value); m_diffuse.setModificationFlags(a_value); m_specular.setModificationFlags(a_value); m_emission.setModificationFlags(a_value); } //============================================================================== /*! This method copies all modified variables to material object passed as argument. \param a_material Destination material where values are copied to. */ //============================================================================== void cMaterial::copyTo(cMaterialPtr a_material) { if (m_flag_shininess) a_material->setShininess(m_shininess); if (m_flag_viscosity) a_material->setViscosity(m_viscosity); if (m_flag_stiffness) a_material->setStiffness(m_stiffness); if (m_flag_damping) a_material->setDamping(m_flag_damping); if (m_flag_staticFriction) a_material->setStaticFriction(m_staticFriction); if (m_flag_dynamicFriction) a_material->setDynamicFriction(m_dynamicFriction); if (m_flag_textureLevel) a_material->setTextureLevel(m_textureLevel); if (m_flag_vibrationFrequency) a_material->setVibrationFrequency(m_vibrationFrequency); if (m_flag_vibrationAmplitude) a_material->setVibrationAmplitude(m_vibrationAmplitude); if (m_flag_magnetMaxForce) a_material->setMagnetMaxForce(m_magnetMaxForce); if (m_flag_magnetMaxDistance) a_material->setMagnetMaxDistance(m_magnetMaxDistance); if (m_flag_stickSlipForceMax) a_material->setStickSlipForceMax(m_stickSlipForceMax); if (m_flag_stickSlipStiffness) a_material->setStickSlipStiffness(m_stickSlipStiffness); if (m_flag_hapticFrontSideOfTriangles) a_material->setHapticTriangleFrontSide(m_hapticFrontSideOfTriangles); if (m_flag_hapticBackSideOfTriangles) a_material->setHapticTriangleBackSide(m_hapticBackSideOfTriangles); if (m_flag_audioImpactBuffer) a_material->setAudioImpactBuffer(m_audioImpactBuffer); if (m_flag_audioFrictionBuffer) a_material->setAudioFrictionBuffer(m_audioFrictionBuffer); if (m_flag_audioImpactGain) a_material->setAudioImpactGain(m_audioImpactGain); if (m_flag_audioFrictionGain) a_material->setAudioFrictionGain(m_audioFrictionGain); if (m_flag_audioFrictionPitchGain) a_material->setAudioFrictionPitchGain(m_audioFrictionPitchGain); if (m_flag_audioFrictionPitchOffset) a_material->setAudioFrictionPitchOffset(m_audioFrictionPitchOffset); m_ambient.copyTo(a_material->m_ambient); m_diffuse.copyTo(a_material->m_diffuse); m_specular.copyTo(a_material->m_specular); m_emission.copyTo(a_material->m_emission); } //------------------------------------------------------------------------------ } // namespace chai3d //------------------------------------------------------------------------------
34.643365
94
0.528301
[ "mesh", "render", "object", "model" ]
ee5a0a89f18fa5156b93e7b02336ef54c452c088
5,341
cpp
C++
problemsets/Topcoder/SRM 453 (DIV2)/TheBasketballDivTwo.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
problemsets/Topcoder/SRM 453 (DIV2)/TheBasketballDivTwo.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
problemsets/Topcoder/SRM 453 (DIV2)/TheBasketballDivTwo.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
/** * * Author: Juarez Paulino(coderemite) * Email: juarez.paulino@gmail.com * */ // BEGIN CUT HERE // END CUT HERE #line 5 "TheBasketballDivTwo.cpp" #include <cstdio> #include <cstdlib> #include <ctime> #include <cctype> #include <cstring> #include <sstream> #include <iostream> #include <string> #include <vector> #include <set> #include <list> #include <map> #include <functional> #include <queue> #include <algorithm> using namespace std; int host[25]; int guest[25]; class TheBasketballDivTwo { public: int find( vector <string> table ) { int N = table.size(); int W[5] = {0}; int c = 0; for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) if (i != j) if (table[i][j]=='W') W[i]++; else if (table[i][j]=='L') W[j]++; else host[c] = i, guest[c] = j, c++; int ret = 1<<30; for (int k = 0; k < 1<<c; k++) { int U[5]; for (int j = 0; j < N; j++) U[j] = W[j]; for (int j = 0; j < c; j++) if (k&(1<<j)) U[host[j]]++; else U[guest[j]]++; ret = min(ret, *max_element(U, U+N)); } return ret; } }; // BEGIN CUT HERE namespace moj_harness { int run_test_case(int); void run_test(int casenum = -1, bool quiet = false) { if (casenum != -1) { if (run_test_case(casenum) == -1 && !quiet) { cerr << "Illegal input! Test case " << casenum << " does not exist." << endl; } return; } int correct = 0, total = 0; for (int i=0;; ++i) { int x = run_test_case(i); if (x == -1) { if (i >= 100) break; continue; } correct += x; ++total; } if (total == 0) { cerr << "No test cases run." << endl; } else if (correct < total) { cerr << "Some cases FAILED (passed " << correct << " of " << total << ")." << endl; } else { cerr << "All " << total << " tests passed!" << endl; } } int verify_case(int casenum, const int &expected, const int &received, clock_t elapsed) { cerr << "Example " << casenum << "... "; string verdict; vector<string> info; char buf[100]; if (elapsed > CLOCKS_PER_SEC / 200) { sprintf(buf, "time %.2fs", elapsed * (1.0/CLOCKS_PER_SEC)); info.push_back(buf); } if (expected == received) { verdict = "PASSED"; } else { verdict = "FAILED"; } cerr << verdict; if (!info.empty()) { cerr << " ("; for (int i=0; i<(int)info.size(); ++i) { if (i > 0) cerr << ", "; cerr << info[i]; } cerr << ")"; } cerr << endl; if (verdict == "FAILED") { cerr << " Expected: " << expected << endl; cerr << " Received: " << received << endl; } return verdict == "PASSED"; } int run_test_case(int casenum) { switch (casenum) { case 0: { string table[] = {"X?", "?X"}; int expected__ = 1; clock_t start__ = clock(); int received__ = TheBasketballDivTwo().find(vector <string>(table, table + (sizeof table / sizeof table[0]))); return verify_case(casenum, expected__, received__, clock()-start__); } case 1: { string table[] = {"XW", "LX"}; int expected__ = 2; clock_t start__ = clock(); int received__ = TheBasketballDivTwo().find(vector <string>(table, table + (sizeof table / sizeof table[0]))); return verify_case(casenum, expected__, received__, clock()-start__); } case 2: { string table[] = {"XWL", "?XW", "WLX"}; int expected__ = 2; clock_t start__ = clock(); int received__ = TheBasketballDivTwo().find(vector <string>(table, table + (sizeof table / sizeof table[0]))); return verify_case(casenum, expected__, received__, clock()-start__); } case 3: { string table[] = {"XW?", "LX?", "??X"}; int expected__ = 2; clock_t start__ = clock(); int received__ = TheBasketballDivTwo().find(vector <string>(table, table + (sizeof table / sizeof table[0]))); return verify_case(casenum, expected__, received__, clock()-start__); } // custom cases /* case 4: { string table[] = ; int expected__ = ; clock_t start__ = clock(); int received__ = TheBasketballDivTwo().find(vector <string>(table, table + (sizeof table / sizeof table[0]))); return verify_case(casenum, expected__, received__, clock()-start__); }*/ /* case 5: { string table[] = ; int expected__ = ; clock_t start__ = clock(); int received__ = TheBasketballDivTwo().find(vector <string>(table, table + (sizeof table / sizeof table[0]))); return verify_case(casenum, expected__, received__, clock()-start__); }*/ /* case 6: { string table[] = ; int expected__ = ; clock_t start__ = clock(); int received__ = TheBasketballDivTwo().find(vector <string>(table, table + (sizeof table / sizeof table[0]))); return verify_case(casenum, expected__, received__, clock()-start__); }*/ default: return -1; } } } int main(int argc, char *argv[]) { if (argc == 1) { moj_harness::run_test(); } else { for (int i=1; i<argc; ++i) moj_harness::run_test(atoi(argv[i])); } } // END CUT HERE
26.440594
124
0.538289
[ "vector" ]
ee6233e223926d3fb56fc59b3069bd96636143d9
519
cpp
C++
CodeForces/Complete/800-899/816B-KarenAndCoffee.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
36
2019-12-27T08:23:08.000Z
2022-01-24T20:35:47.000Z
CodeForces/Complete/800-899/816B-KarenAndCoffee.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
10
2019-11-13T02:55:18.000Z
2021-10-13T23:28:09.000Z
CodeForces/Complete/800-899/816B-KarenAndCoffee.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
53
2020-08-15T11:08:40.000Z
2021-10-09T15:51:38.000Z
#include <cstdio> #include <vector> int main(){ const long N = 200100; std::vector<long> a(N), b(N); long n, k, q; scanf("%ld %ld %ld", &n, &k, &q); for(long p = 0; p < n; p++){ long l, r; scanf("%ld %ld", &l, &r); ++a[l]; --a[r + 1]; } for(long p = 1; p < N; p++){a[p] += a[p - 1];} for(long p = 1; p < N; p++){b[p] += b[p - 1] + (a[p] >= k);} while(q--){ long l, r; scanf("%ld %ld", &l, &r); printf("%ld\n", b[r] - b[l - 1]); } return 0; }
21.625
64
0.38921
[ "vector" ]
ee63c7ec8cc9642967395c4ae3fa2ad4d3955ec2
3,273
cpp
C++
graphicsStuff/Agent.cpp
hariudkmr/zombie_project
70c88d59d687bbc73fb9c12bb921e59881d72cfb
[ "MIT" ]
null
null
null
graphicsStuff/Agent.cpp
hariudkmr/zombie_project
70c88d59d687bbc73fb9c12bb921e59881d72cfb
[ "MIT" ]
null
null
null
graphicsStuff/Agent.cpp
hariudkmr/zombie_project
70c88d59d687bbc73fb9c12bb921e59881d72cfb
[ "MIT" ]
null
null
null
#include "Agent.h" #include "Level.h" #include "../JEngine/ResourceManager.h" #include <algorithm> const unsigned char TILE_SIZE = 64; Agent::Agent() {} Agent::~Agent() {} bool Agent::collideWithLevel(const std::vector<std::string> &levelData) { std::vector<glm::vec2> cTilePoss; // check the 4 corners checkTileCollision(cTilePoss, levelData, _pos.x, _pos.y); checkTileCollision(cTilePoss, levelData, _pos.x + AGENT_WIDTH, _pos.y); checkTileCollision(cTilePoss, levelData, _pos.x, _pos.y + AGENT_WIDTH); checkTileCollision(cTilePoss, levelData, _pos.x + AGENT_WIDTH, _pos.y + AGENT_WIDTH); // no blocks collided if (cTilePoss.size() == 0) { return false; } for (int i = 0; i < cTilePoss.size(); i++) { // do the collision collideWithTile(cTilePoss[i]); } return true; } bool Agent::collideWithAgent(Agent *agent) { glm::vec2 centerPosA = _pos + glm::vec2(AGENT_RADIUS); glm::vec2 centerPosB = agent->getPosition() + glm::vec2(AGENT_RADIUS); glm::vec2 distVec = centerPosA - centerPosB; float distance = glm::length(distVec); float depth = AGENT_WIDTH - distance; if (depth > 0) { glm::vec2 collisionDepthVec = (glm::normalize(distVec) * depth) / 2.0f; _pos += collisionDepthVec; agent->_pos -= collisionDepthVec; return true; } return false; } void Agent::checkTileCollision(std::vector<glm::vec2> &cTiles, const std::vector<std::string> &data, float x, float y) { glm::vec2 cornerPos = glm::vec2(floor(x / (float)TILE_SIZE), floor(y / (float)TILE_SIZE)); // if out of bounds return /*if (cornerPos.x < 0 || cornerPos.x >= data[0].length() || cornerPos.y < 0 || cornerPos.y >= data.size()) { return; }*/ if (data[cornerPos.y][cornerPos.x] != '.') { cTiles.push_back(cornerPos * (float)TILE_SIZE + glm::vec2(TILE_SIZE / 2.0f, TILE_SIZE / 2.0f)); } } bool Agent::applyDamage(float damage) { _health -= damage; return (_health <= 0); } // AABB COLLISION! void Agent::collideWithTile(glm::vec2 tilePos) { // const float AGENT_RADIUS = (float)AGENT_WIDTH / 2.0f; const float TILE_RADIUS = (float)TILE_SIZE / 2.0f; const float MIN_DISTANCE = AGENT_RADIUS + TILE_RADIUS; glm::vec2 centerPlayerPos = _pos + glm::vec2(AGENT_RADIUS); glm::vec2 distVec = centerPlayerPos - tilePos; float xDepth = MIN_DISTANCE - abs(distVec.x); float yDepth = MIN_DISTANCE - abs(distVec.y); // LOL will always be true if (std::max(xDepth, 0.0f) || std::max(yDepth, 0.0f)) { if (xDepth < yDepth) { if (distVec.x < 0) { _pos.x -= xDepth; } else { _pos.x += xDepth; } } else { if (distVec.y < 0) { _pos.y -= yDepth; } else { _pos.y += yDepth; } } } } void Agent::draw(JEngine::SpriteBatch &sb) { const glm::vec4 uvRect(0.0f, 0.0f, 1.0f, 1.0f); glm::vec4 destRect; destRect.x = _pos.x; destRect.y = _pos.y; destRect.z = AGENT_WIDTH; destRect.w = AGENT_WIDTH; sb.draw(destRect, uvRect, _textureID, 0.0f, _color, _direction); }
27.275
78
0.599145
[ "vector" ]
ee683db56418c7acccc6cd0be9470da195e3f76a
2,700
cpp
C++
src/applications/tests/unit_tests/deserialize_and_run_test.cpp
Derecho-Project/derecho-unified
24c6175fcd33e60f7aab72aad69695f1ec187db2
[ "BSD-3-Clause" ]
50
2016-12-15T19:36:52.000Z
2019-03-27T21:21:10.000Z
src/applications/tests/unit_tests/deserialize_and_run_test.cpp
Derecho-Project/derecho-unified
24c6175fcd33e60f7aab72aad69695f1ec187db2
[ "BSD-3-Clause" ]
111
2017-07-21T17:16:26.000Z
2019-04-02T19:40:14.000Z
src/applications/tests/unit_tests/deserialize_and_run_test.cpp
Derecho-Project/derecho-unified
24c6175fcd33e60f7aab72aad69695f1ec187db2
[ "BSD-3-Clause" ]
26
2017-01-26T14:36:06.000Z
2019-02-01T16:36:57.000Z
#include <derecho/mutils-serialization/SerializationSupport.hpp> #include <cstdint> #include <functional> #include <iomanip> #include <iostream> #include <numeric> #include <vector> using callback_function_t = std::function<void(int64_t, const std::vector<int>&)>; int main(int argc, char** argv) { std::vector<int> vector_data(256); std::iota(vector_data.begin(), vector_data.end(), 1); int64_t int_data = 6666666; // Serialize an int64 and a std::vector into a buffer std::size_t buf_size = mutils::bytes_size(vector_data) + mutils::bytes_size(int_data); uint8_t* byte_buffer = new uint8_t[buf_size]; std::size_t buf_offset = 0; mutils::to_bytes(int_data, byte_buffer + buf_offset); buf_offset += mutils::bytes_size(int_data); mutils::to_bytes(vector_data, byte_buffer + buf_offset); buf_offset += mutils::bytes_size(vector_data); uint8_t const* const read_only_buf_ptr = byte_buffer; // Can we deserialize the vector normally? auto deserialized_vector = mutils::from_bytes<std::vector<int>>(nullptr, read_only_buf_ptr + mutils::bytes_size(int_data)); std::cout << "Vector after from_bytes: " << std::endl; for(const auto& e : *deserialized_vector) { std::cout << e << " "; } std::cout << std::endl; // Can we deserialize with from_bytes_noalloc? auto context_vector = mutils::from_bytes_noalloc<std::vector<int>>(nullptr, read_only_buf_ptr + mutils::bytes_size(int_data)); std::cout << "Vector after from_bytes_noalloc: " << std::endl; for(const auto& e : *context_vector) { std::cout << e << " "; } std::cout << std::endl; // What about from_bytes_noalloc with an explicit third argument? auto const_context_vector = mutils::from_bytes_noalloc<const std::vector<int>>(nullptr, read_only_buf_ptr + mutils::bytes_size(int_data), mutils::context_ptr<const std::vector<int>>{}); std::cout << "Vector after from_bytes_noalloc: " << std::endl; for(const auto& e : *const_context_vector) { std::cout << e << " "; } std::cout << std::endl; // Attempt to call a std::function with the integer and vector as arguments callback_function_t callback_fun = [](int64_t int_arg, const std::vector<int>& vector_arg) { std::cout << "Got callback with integer " << int_arg << " and vector: " << std::endl; for(std::size_t i = 0; i < vector_arg.size(); ++i) { std::cout << vector_arg[i] << " "; } std::cout << std::endl; }; mutils::deserialize_and_run(nullptr, read_only_buf_ptr, callback_fun); delete[] byte_buffer; }
44.262295
141
0.651111
[ "vector" ]
ee6ef49a5866531c7ae2cf29ba014735fda18cb1
27,260
cpp
C++
build/OneCutWithSeeds_v1.03/OneCut_Main.cpp
wilmeragsgh/pdi_project
69003747c65298858107b1e52daa8b4bb46bffc1
[ "MIT" ]
null
null
null
build/OneCutWithSeeds_v1.03/OneCut_Main.cpp
wilmeragsgh/pdi_project
69003747c65298858107b1e52daa8b4bb46bffc1
[ "MIT" ]
null
null
null
build/OneCutWithSeeds_v1.03/OneCut_Main.cpp
wilmeragsgh/pdi_project
69003747c65298858107b1e52daa8b4bb46bffc1
[ "MIT" ]
null
null
null
//Copyright (c) 2014, Lena Gorelick //All rights reserved. // //Redistribution and use in source and binary forms, with or without //modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of the University of Western Ontarior 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 <COPYRIGHT HOLDER> 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. // // //THIS SOFTWARE IMPLEMENTS THE OneCut ALGORITHM THAT USES SCRIBBLES AS HARD CONSTRAINTS. //PLEASE USE THE FOLLOWING CITATION: // //@inproceedings{iccv2013onecut, // title = {Grabcut in One Cut}, // author = {Tang, Meng and Gorelick, Lena and Veksler, Olga and Boykov, Yuri}, // booktitle={International Conference on Computer Vision}, // month = {December}, // year = {2013}} // //THIS SOFTWARE USES maxflow/min-cut CODE THAT WAS IMPLEMENTED BY VLADIMIR KOLMOGOROV, //THAT CAN BE DOWNLOADED FROM http://vision.csd.uwo.ca/code/. //PLEASE USE THE FOLLOWING CITATION: // //@ARTICLE{Boykov01anexperimental, // author = {Yuri Boykov and Vladimir Kolmogorov}, // title = {An Experimental Comparison of Min-Cut/Max-Flow Algorithms for Energy Minimization in Vision}, // journal = {IEEE TRANSACTIONS ON PATTERN ANALYSIS AND MACHINE INTELLIGENCE}, // year = {2001}, // volume = {26}, // pages = {359--374}} // // // //THIS SOFTWARE USES OpenCV 2.4.3 THAT CAN BE DOWNLOADED FROM http://opencv.org // // // // // // // // // //################################################################## // // USAGE INSTRUCTIONS // // In the command line type: // // OneCut <imageFileName> [<numBinsPerChannel> <colorSep_slope>] // // Default values: numBinsPerChannel=64 colorSep_slope= 0.1 // // Example: OneCut frida_small.jpg 64 0.1 // or OneCut frida_small.jpg // // // Once the image is opened you can scribble with left and right // mouse buttons on the object and the background in the // "Scribble Image" window. Once the scribbles are given you can // segment the image.You can keep repeatedly adding scribbles and // segmenting until the result is satisfactory. // // // "Use the following Short Keys: // 'q' - quit // 's' - segment // 'r' - reset (removes all strokes and clears all results) // 'k' - keep the scribbles and the segmentation // 'l' - load the scribbles // '+' - increase brush stroke radius // '-' - decrease brush stroke radius // 'right mouse button drag' - draw blue scribble // 'left mouse button drag' - draw red scribble // // #include <iostream> // for standard I/O #include <string> // for strings #include <iomanip> // for controlling float print precision #include <sstream> // string to number conversion #include <opencv2/imgproc/imgproc.hpp> // Gaussian Blur #include <opencv2/core/core.hpp> // Basic OpenCV structures (cv::Mat, Scalar) #include <opencv2/highgui/highgui.hpp> // OpenCV window I/O #include "graph.h" using namespace std; using namespace cv; // images Mat inputImg, showImg, binPerPixelImg, showEdgesImg, segMask, segShowImg; // mask Mat fgScribbleMask, bgScribbleMask, fgScribbleMaskAll, bgScribbleMaskAll; // user clicked mouse buttons flags bool rButtonDown = false; bool lButtonDown = false; int numUsedBins = 0; float varianceSquared = 0; int scribbleRadius = 10; // default arguments float bha_slope = 0.5f; int numBinsPerChannel = 16; float EDGE_STRENGTH_WEIGHT = 0.95f; const float INT32_CONST = 1000; const float HARD_CONSTRAINT_CONST = 1000; #define NEIGHBORHOOD_4_TYPE 1; const int NEIGHBORHOOD = NEIGHBORHOOD_4_TYPE; //************************************ // F u n c t i o n d e c l a r a t i o n s // init all images/vars int init(char * imgFileName); // clear everything before closing void destroyAll(); // mouse listener static void onMouse( int event, int x, int y, int, void* ); // set bin index for each image pixel, store it in binPerPixelImg void getBinPerPixel(Mat & binPerPixelImg, Mat & inputImg, int numBinsPerChannel, int & numUsedBins); // compute the variance of image edges between neighbors void getEdgeVariance(Mat & inputImg, Mat & showEdgesImg, float & varianceSquared); // keep the scribbles for later int keepScribbles(char * imgFileName, Mat & fgScribbleMaskAll, Mat & bgScribbleMaskAll, Mat & segMask, float colorSep, int numBinsPerChannel, float contrastSensitive); int loadScribbles(char * imgFileName, Mat & fgScribbleMask, Mat & bgScribbleMask); void getColorSepE(int & colorSep_E, int & hardConstraints_E); typedef Graph<int,int,int> GraphType; GraphType *myGraph; //*********************************** // M a i n int main(int argc, char *argv[]) { if( argc > 4 || argc < 2) { cout <<" Usage: OneCut ImageToSegment [numBinsPerChannel colorSep_slope]" << endl; return -1; } if (argc >= 3) { // get the second arg String numBinsStr(argv[2]); // convert to int numBinsPerChannel = atoi(numBinsStr.c_str()); cout << "Using " << numBinsPerChannel << " bins per channel " << endl; if (argc >=4) { //get third argument String bhaSlopeStr(argv[3]); bha_slope = (float)atof(bhaSlopeStr.c_str()); cout << "Using colorSep_slope = " << bha_slope << endl; } else cout << "Using default colorSep_slope = " << bha_slope << endl; } else { cout << "Using default " << numBinsPerChannel << " bins per channel " << endl; cout << "Using default colorSep_slope = " << bha_slope << endl; } // get img name parameter char * imgFileName = argv[1]; if (init(imgFileName)==-1) { cout << "Could not initialize" << endl ; return -1; } cout << "if there are scribbles from before, load them" << endl; if (loadScribbles(imgFileName, fgScribbleMask, bgScribbleMask)==-1) { cout << "could not load scribbles" << std::endl ; cout << "running without scribbles" << std::endl; } cout << "Use the following Short Keys:" << endl; cout << " 'q' - quit" << endl; cout << " 's' - segment" << endl; cout << " 'r' - reset (removes all strokes and clears all results)" << endl; cout << " 'k' - keep the scribbles and the segmentation" << endl; cout << " 'l' - load the scribbles" << endl; cout << " '+' - increase brush stroke radius" << endl; cout << " '-' - decrease brush stroke radius" << endl; cout << " 'right mouse button drag' - draw blue scribble" << endl; cout << " 'left mouse button drag' - draw red scribble" << endl; // Wait for a keystroke in the window for (;;) { char key = waitKey(0); switch (key) { case 'q': cout << "goodbye" << endl; destroyAll(); return 0; case '-': if (scribbleRadius > 2) scribbleRadius --; cout << "current radius is " << scribbleRadius << endl; break; case '+': if (scribbleRadius < 100) scribbleRadius ++; cout << "current radius is " << scribbleRadius << endl; break; case 's': { cout << "setting the hard constraints..." << endl; for(int i=0; i<inputImg.rows; i++) { for(int j=0; j<inputImg.cols; j++) { // this is the node id for the current pixel GraphType::node_id currNodeId = i * inputImg.cols + j; // add hard constraints based on scribbles if (fgScribbleMask.at<uchar>(i,j) == 255) myGraph->add_tweights(currNodeId,(int)ceil(INT32_CONST * HARD_CONSTRAINT_CONST + 0.5),0); else if (bgScribbleMask.at<uchar>(i,j) == 255) myGraph->add_tweights(currNodeId,0,(int)ceil(INT32_CONST * HARD_CONSTRAINT_CONST + 0.5)); } } cout << "maxflow..." << endl; int flow = myGraph -> maxflow(); cout << "done maxflow..." << flow << endl; int colorSep_E, hardConstraints_E; getColorSepE(colorSep_E, hardConstraints_E); cout << "Hard Constraints violation cost: " << hardConstraints_E << endl; cout << "Color Sep Term: " << colorSep_E << endl; cout << "Edge cost: " << flow - colorSep_E - hardConstraints_E << endl; // this is where we store the results segMask = 0; inputImg.copyTo(segShowImg); //inputImg.copyTo(showImg); // empty scribble masks are ready to record additional scribbles for additional hard constraints // to be used next time fgScribbleMask = 0; bgScribbleMask = 0; // copy the segmentation results on to the result images for (int i = 0; i<inputImg.rows * inputImg.cols; i++) { // if it is foreground - color blue if (myGraph->what_segment((GraphType::node_id)i ) == GraphType::SOURCE) { segMask.at<uchar>(i/inputImg.cols, i%inputImg.cols) = 255; (uchar)segShowImg.at<Vec3b>(i/inputImg.cols, i%inputImg.cols)[2] = 200; } // if it is background - color red else { segMask.at<uchar>(i/inputImg.cols, i%inputImg.cols) = 0; (uchar)segShowImg.at<Vec3b>(i/inputImg.cols, i%inputImg.cols)[0] = 200; } } imshow("Segmentation Mask", segMask); imshow("Segmentation Image", segShowImg); break; } case 'r': { cout << "resetting" << endl; destroyAll(); if (init(imgFileName)==-1) { cout << "could not initialize" << std::endl ; return -1; } break; } // keep the scribbles case 'k': { cout << "keeping scribbles for later" << endl; if (keepScribbles(imgFileName, fgScribbleMaskAll, bgScribbleMaskAll, segMask, bha_slope, numBinsPerChannel, EDGE_STRENGTH_WEIGHT)==-1) { cout << "could not save scribbles" << std::endl ; return -1; } break; } // load scribbles case 'l': { cout << "resetting" << endl; destroyAll(); if (init(imgFileName)==-1) { cout << "could not initialize" << std::endl ; return -1; } cout << "load scribbles from before" << endl; if (loadScribbles(imgFileName, fgScribbleMask, bgScribbleMask)==-1) { cout << "could not load scribbles" << std::endl ; cout << "running without scribbles" << std::endl ; } break; } } } return 0; } // mouse listener static void onMouse( int event, int x, int y, int, void* ) { //cout << "On Mouse: (" << x << "," << y << ")" <<endl; if (event == CV_EVENT_LBUTTONDOWN) { lButtonDown = true; } else if (event == CV_EVENT_RBUTTONDOWN) { rButtonDown = true; } else if (event == CV_EVENT_LBUTTONUP) { lButtonDown = false; } else if (event == CV_EVENT_RBUTTONUP) { rButtonDown = false; } else if (event == CV_EVENT_MOUSEMOVE) { if (rButtonDown) { // scribble the background circle(bgScribbleMask,Point(x,y),scribbleRadius, 255,-1); circle(bgScribbleMaskAll,Point(x,y),scribbleRadius, 255,-1); circle(showImg,Point(x,y),scribbleRadius, CV_RGB(0,0,255),-1); } else if (lButtonDown) { // scribble the foreground circle(fgScribbleMask,Point(x,y),scribbleRadius, 255,-1); circle(fgScribbleMaskAll,Point(x,y),scribbleRadius, 255,-1); circle(showImg,Point(x,y),scribbleRadius, CV_RGB(255,0,0),-1); //fgScribbleMask.at<char>(y,x)=(char)255; // set variables using mask //showImg.setTo(redColorElement,fgScribbleMask); //showImg.at<Vec3b>(y,x)[0] = 0; //showImg.at<Vec3b>(y,x)[1] = 0; //showImg.at<Vec3b>(y,x)[2] = 255; } } imshow("Scribble Image", showImg); imshow("fg mask", fgScribbleMask); imshow("bg mask", bgScribbleMask); } // clear everything before closing void destroyAll() { // destroy all windows destroyWindow("Input Image"); destroyWindow("Scribble Image"); destroyWindow("Bin Per Pixel"); destroyWindow("Edges"); destroyWindow("bg mask"); destroyWindow("fg mask"); destroyWindow("Segmentation Mask"); destroyWindow("Segmentation Image"); // clear all data fgScribbleMask.release(); bgScribbleMask.release(); inputImg.release(); showImg.release(); showEdgesImg.release(); binPerPixelImg.release(); segMask.release(); segShowImg.release(); delete myGraph; } // keep scirbbles for later int keepScribbles(char * imgFileName, Mat & fgScribbleMaskAll, Mat & bgScribbleMaskAll, Mat & segMask, float colorSep, int numBinsPerChannel, float contrastSensitive) { char buff[256]; buff[0] = '\0'; strncat(buff,imgFileName,(unsigned)(strlen(imgFileName)-4)); strcat(buff, "_fg.png"); imwrite(buff,fgScribbleMaskAll); buff[0] = '\0'; strncat(buff,imgFileName,(unsigned)(strlen(imgFileName)-4)); strcat(buff, "_bg.png"); imwrite(buff,bgScribbleMaskAll); buff[0] = '\0'; strncat(buff,imgFileName,(unsigned)(strlen(imgFileName)-4)); strcat(buff,"_"); char tempBuff[20]; int n = sprintf(tempBuff,"%4.2f",colorSep); strcat(buff, tempBuff); strcat(buff, "colorSep"); strcat(buff,"_"); strcat(buff, std::to_string(numBinsPerChannel).c_str()); strcat(buff, "bins"); strcat(buff,"_"); n = sprintf(tempBuff,"%4.2f",contrastSensitive); strcat(buff, tempBuff); strcat(buff, "contrast"); strcat(buff, "_mask.png"); imwrite(buff,segMask); return 0; } // load scirbbles int loadScribbles(char * imgFileName, Mat & fgScribbleMask, Mat & bgScribbleMask) { char buff[256]; buff[0] = '\0'; strncat(buff,imgFileName,(unsigned)(strlen(imgFileName)-4)); strcat(buff, "_fg.png"); fgScribbleMask = imread(buff,CV_LOAD_IMAGE_GRAYSCALE); if(!fgScribbleMask.data ) { cout << "Could not open or find the fg scribble image: " << buff << std::endl ; // this is the mask to keep the user scribbles fgScribbleMask.create(2,inputImg.size,CV_8UC1); fgScribbleMask = 0; bgScribbleMask.create(2,inputImg.size,CV_8UC1); bgScribbleMask = 0; return -1; } buff[0] = '\0'; strncat(buff,imgFileName,(unsigned)(strlen(imgFileName)-4)); strcat(buff, "_bg.png"); bgScribbleMask = imread(buff,CV_LOAD_IMAGE_GRAYSCALE); if(!bgScribbleMask.data ) { cout << "Could not open or find the bg scribble image: " << buff << std::endl ; // this is the mask to keep the user scribbles fgScribbleMask.create(2,inputImg.size,CV_8UC1); fgScribbleMask = 0; bgScribbleMask.create(2,inputImg.size,CV_8UC1); bgScribbleMask = 0; return -1; } fgScribbleMask.copyTo(fgScribbleMaskAll); bgScribbleMask.copyTo(bgScribbleMaskAll); showImg.setTo(Scalar(0,0,255),fgScribbleMask); showImg.setTo(Scalar(255,0,0),bgScribbleMask); imshow("Scribble Image", showImg); imshow("fg mask", fgScribbleMask); imshow("bg mask", bgScribbleMask); return 0; } // init all images/vars int init(char * imgFileName) { // Read the file inputImg = imread(imgFileName, CV_LOAD_IMAGE_COLOR); showImg = inputImg.clone(); segShowImg = inputImg.clone(); // Check for invalid input if(!inputImg.data ) { cout << "Could not open or find the image: " << imgFileName << std::endl ; return -1; } // this is the mask to keep the user scribbles fgScribbleMask.create(2,inputImg.size,CV_8UC1); fgScribbleMask = 0; bgScribbleMask.create(2,inputImg.size,CV_8UC1); bgScribbleMask = 0; fgScribbleMaskAll.create(2,inputImg.size,CV_8UC1); fgScribbleMaskAll = 0; bgScribbleMaskAll.create(2,inputImg.size,CV_8UC1); bgScribbleMaskAll = 0; segMask.create(2,inputImg.size,CV_8UC1); segMask = 0; showEdgesImg.create(2, inputImg.size, CV_32FC1); showEdgesImg = 0; binPerPixelImg.create(2, inputImg.size,CV_32F); // get bin index for each image pixel, store it in binPerPixelImg getBinPerPixel(binPerPixelImg, inputImg, numBinsPerChannel, numUsedBins); // compute the variance of image edges between neighbors getEdgeVariance(inputImg, showEdgesImg, varianceSquared); // Create a window for display. namedWindow( "Input Image", CV_WINDOW_AUTOSIZE ); namedWindow( "Scribble Image", CV_WINDOW_AUTOSIZE); namedWindow("Bin Per Pixel", CV_WINDOW_AUTOSIZE ); namedWindow("Edges", CV_WINDOW_AUTOSIZE ); namedWindow("Segmentation Mask",CV_WINDOW_AUTOSIZE); namedWindow("Segmentation Image",CV_WINDOW_AUTOSIZE); namedWindow( "fg mask", CV_WINDOW_AUTOSIZE ); namedWindow( "bg mask", CV_WINDOW_AUTOSIZE ); //namedWindow("Input Image", CV_WINDOW_NORMAL | CV_WINDOW_KEEPRATIO | CV_GUI_EXPANDED); // Show our image inside it. imshow( "Input Image", inputImg ); imshow( "Scribble Image", showImg ); imshow("Segmentation Mask", segMask); imshow("Segmentation Image", segShowImg); imshow("fg mask", fgScribbleMask); imshow("bg mask", bgScribbleMask); moveWindow("Scribble Image", 1,1); moveWindow("Input Image", inputImg.cols + 50,1); moveWindow("Bin Per Pixel", 2*(inputImg.cols + 50),1); moveWindow("Edges", 2*(inputImg.cols + 55),1); // set the callback on mouse setMouseCallback("Scribble Image", onMouse, 0); myGraph = new GraphType(/*estimated # of nodes*/ inputImg.rows * inputImg.cols + numUsedBins, /*estimated # of edges=11 spatial neighbors and one link to auxiliary*/ 12 * inputImg.rows * inputImg.cols); GraphType::node_id currNodeId = myGraph -> add_node((int)inputImg.cols * inputImg.rows + numUsedBins); for(int i=0; i<inputImg.rows; i++) { for(int j=0; j<inputImg.cols; j++) { // this is the node id for the current pixel GraphType::node_id currNodeId = i * inputImg.cols + j; // add hard constraints based on scribbles if (fgScribbleMask.at<uchar>(i,j) == 255) myGraph->add_tweights(currNodeId,(int)ceil(INT32_CONST * HARD_CONSTRAINT_CONST + 0.5),0); else if (bgScribbleMask.at<uchar>(i,j) == 255) myGraph->add_tweights(currNodeId,0,(int)ceil(INT32_CONST * HARD_CONSTRAINT_CONST + 0.5)); // You can now access the pixel value with cv::Vec3b float b = (float)inputImg.at<Vec3b>(i,j)[0]; float g = (float)inputImg.at<Vec3b>(i,j)[1]; float r = (float)inputImg.at<Vec3b>(i,j)[2]; // go over the neighbors for (int si = -NEIGHBORHOOD; si <= NEIGHBORHOOD; si++) { int ni = i+si; // outside the border - skip if ( ni < 0 || ni >= inputImg.rows) continue; for (int sj = 0; sj <= NEIGHBORHOOD; sj++) { int nj = j+sj; // outside the border - skip if ( nj < 0 || nj >= inputImg.cols) continue; // same pixel - skip // down pointed edge, this edge will be counted as an up edge for the other pixel if (si >= 0 && sj == 0) continue; // diagonal exceed the radius - skip if ((si*si + sj*sj) > NEIGHBORHOOD*NEIGHBORHOOD) continue; // this is the node id for the neighbor GraphType::node_id nNodeId = (i+si) * inputImg.cols + (j + sj); float nb = (float)inputImg.at<Vec3b>(i+si,j+sj)[0]; float ng = (float)inputImg.at<Vec3b>(i+si,j+sj)[1]; float nr = (float)inputImg.at<Vec3b>(i+si,j+sj)[2]; // ||I_p - I_q||^2 / 2 * sigma^2 float currEdgeStrength = exp(-((b-nb)*(b-nb) + (g-ng)*(g-ng) + (r-nr)*(r-nr))/(2*varianceSquared)); //float currEdgeStrength = 0; float currDist = sqrt((float)si*(float)si + (float)sj*(float)sj); // this is the edge between the current two pixels (i,j) and (i+si, j+sj) currEdgeStrength = ((float)EDGE_STRENGTH_WEIGHT * currEdgeStrength + (float)(1-EDGE_STRENGTH_WEIGHT)) /currDist; int edgeCapacity = /* capacities */ (int) ceil(INT32_CONST*currEdgeStrength + 0.5); //edgeCapacity = 0; myGraph -> add_edge(currNodeId, nNodeId, edgeCapacity , edgeCapacity); } } // add the adge to the auxiliary node int currBin = (int)binPerPixelImg.at<float>(i,j); myGraph -> add_edge(currNodeId, (GraphType::node_id)(currBin + inputImg.rows * inputImg.cols), /* capacities */ (int) ceil(INT32_CONST*bha_slope+ 0.5), (int)ceil(INT32_CONST*bha_slope + 0.5)); } } return 0; } // get bin index for each image pixel, store it in binPerPixelImg void getBinPerPixel(Mat & binPerPixelImg, Mat & inputImg, int numBinsPerChannel, int & numUsedBins) { // this vector is used to throw away bins that were not used vector<int> occupiedBinNewIdx((int)pow((double)numBinsPerChannel,(double)3),-1); // go over the image int newBinIdx = 0; for(int i=0; i<inputImg.rows; i++) for(int j=0; j<inputImg.cols; j++) { // You can now access the pixel value with cv::Vec3b float b = (float)inputImg.at<Vec3b>(i,j)[0]; float g = (float)inputImg.at<Vec3b>(i,j)[1]; float r = (float)inputImg.at<Vec3b>(i,j)[2]; // this is the bin assuming all bins are present int bin = (int)(floor(b/256.0 *(float)numBinsPerChannel) + (float)numBinsPerChannel * floor(g/256.0*(float)numBinsPerChannel) + (float)numBinsPerChannel * (float)numBinsPerChannel * floor(r/256.0*(float)numBinsPerChannel)); // if we haven't seen this bin yet if (occupiedBinNewIdx[bin]==-1) { // mark it seen and assign it a new index occupiedBinNewIdx[bin] = newBinIdx; newBinIdx ++; } // if we saw this bin already, it has the new index binPerPixelImg.at<float>(i,j) = (float)occupiedBinNewIdx[bin]; //cout << bin << endl; } double maxBin; minMaxLoc(binPerPixelImg,NULL,&maxBin); numUsedBins = (int) maxBin + 1; imshow("Bin Per Pixel", binPerPixelImg/maxBin); occupiedBinNewIdx.clear(); cout << "Num occupied bins:" << numUsedBins<< endl; } // compute the variance of image edges between neighbors void getEdgeVariance(Mat & inputImg, Mat & showEdgesImg, float & varianceSquared) { varianceSquared = 0; int counter = 0; for(int i=0; i<inputImg.rows; i++) { for(int j=0; j<inputImg.cols; j++) { // You can now access the pixel value with cv::Vec3b float b = (float)inputImg.at<Vec3b>(i,j)[0]; float g = (float)inputImg.at<Vec3b>(i,j)[1]; float r = (float)inputImg.at<Vec3b>(i,j)[2]; for (int si = -NEIGHBORHOOD; si <= NEIGHBORHOOD && si + i < inputImg.rows && si + i >= 0 ; si++) { for (int sj = 0; sj <= NEIGHBORHOOD && sj + j < inputImg.cols ; sj++) { if ((si == 0 && sj == 0) || (si == 1 && sj == 0) || (si == NEIGHBORHOOD && sj == 0)) continue; float nb = (float)inputImg.at<Vec3b>(i+si,j+sj)[0]; float ng = (float)inputImg.at<Vec3b>(i+si,j+sj)[1]; float nr = (float)inputImg.at<Vec3b>(i+si,j+sj)[2]; varianceSquared+= (b-nb)*(b-nb) + (g-ng)*(g-ng) + (r-nr)*(r-nr); counter ++; } } } } varianceSquared/=counter; // just for visualization for(int i=0; i<inputImg.rows; i++) { for(int j=0; j<inputImg.cols; j++) { float edgeStrength = 0; // You can now access the pixel value with cv::Vec3b float b = (float)inputImg.at<Vec3b>(i,j)[0]; float g = (float)inputImg.at<Vec3b>(i,j)[1]; float r = (float)inputImg.at<Vec3b>(i,j)[2]; for (int si = -NEIGHBORHOOD; si <= NEIGHBORHOOD && si + i < inputImg.rows && si + i >= 0; si++) { for (int sj = 0; sj <= NEIGHBORHOOD && sj + j < inputImg.cols ; sj++) { if ((si == 0 && sj == 0) || (si == 1 && sj == 0) || (si == NEIGHBORHOOD && sj == 0)) continue; float nb = (float)inputImg.at<Vec3b>(i+si,j+sj)[0]; float ng = (float)inputImg.at<Vec3b>(i+si,j+sj)[1]; float nr = (float)inputImg.at<Vec3b>(i+si,j+sj)[2]; // ||I_p - I_q||^2 / 2 * sigma^2 float currEdgeStrength = exp(-((b-nb)*(b-nb) + (g-ng)*(g-ng) + (r-nr)*(r-nr))/(2*varianceSquared)); float currDist = sqrt((float)si*(float)si + (float)sj * (float)sj); // this is the edge between the current two pixels (i,j) and (i+si, j+sj) edgeStrength = edgeStrength + ((float)0.95 * currEdgeStrength + (float)0.05) /currDist; } } // this is the avg edge strength for pixel (i,j) with its neighbors showEdgesImg.at<float>(i,j) = edgeStrength; } } double maxEdge; Point maxPoint; minMaxLoc(showEdgesImg,NULL,&maxEdge, NULL, &maxPoint); //cout << showEdgesImg.at<float>(maxPoint) << endl; imshow("Edges", showEdgesImg/maxEdge); } void getColorSepE(int & colorSep_E, int & hardConstraints_E) { colorSep_E = 0; hardConstraints_E = 0; // copy the segmentation results on to the result images for(int i=0; i<inputImg.rows; i++) { for(int j=0; j<inputImg.cols; j++) { // this is the node id for the current pixel GraphType::node_id currNodeId = i * inputImg.cols + j; // auxiliary node 1 int currBin = (int)binPerPixelImg.at<float>(i,j); int auxNodeId = currBin + inputImg.rows * inputImg.cols; // if it is foreground if (myGraph->what_segment((GraphType::node_id)currNodeId ) == GraphType::SOURCE) { // but has bg hard constraints if (bgScribbleMaskAll.at<uchar>(i,j) == 255) { hardConstraints_E+=(int)ceil(INT32_CONST * HARD_CONSTRAINT_CONST + 0.5); } if (myGraph->what_segment((GraphType::node_id)auxNodeId) == GraphType::SINK) colorSep_E += (int) ceil(INT32_CONST*bha_slope+ 0.5); } // if it is background - else { // but has fg hard constraints if (fgScribbleMaskAll.at<uchar>(i,j) == 255) { hardConstraints_E+=(int)ceil(INT32_CONST * HARD_CONSTRAINT_CONST + 0.5); } if (myGraph->what_segment((GraphType::node_id)auxNodeId) == GraphType::SOURCE) colorSep_E += (int) ceil(INT32_CONST*bha_slope+ 0.5); } } } } /* ******************************* Mat myMat(size(3, 3), CV_32FC2); myMat.ptr<float>(y)[2*x]; // first channel myMat.ptr<float>(y)[2*x+1]; // second channel */
30.837104
168
0.630778
[ "object", "vector" ]
ee70e40a5a4fb0b22faac4f3b8fe4f50c3a411da
3,605
cpp
C++
Vulkan-Pipeline-Assistant/Widgets/spvmatrixwidget.cpp
Untitled-Games/Vulkan-Pipeline-Assistant
e4b03148a51a716cfb668c197873b12525743592
[ "MIT" ]
5
2019-12-24T18:06:05.000Z
2020-02-10T01:41:36.000Z
Vulkan-Pipeline-Assistant/Widgets/spvmatrixwidget.cpp
Untitled-Games/Vulkan-Pipeline-Assistant
e4b03148a51a716cfb668c197873b12525743592
[ "MIT" ]
7
2019-12-28T12:06:07.000Z
2020-02-05T11:33:21.000Z
Vulkan-Pipeline-Assistant/Widgets/spvmatrixwidget.cpp
Untitled-Games/Vulkan-Pipeline-Assistant
e4b03148a51a716cfb668c197873b12525743592
[ "MIT" ]
null
null
null
#include "spvmatrixwidget.h" #include <QLineEdit> #include <QLayout> #include <QPushButton> #include <QCoreApplication> #include <QComboBox> #include <QMatrix4x4> #include "../Vulkan/spirvresource.h" #include "../Vulkan/descriptors.h" #include "descriptortree.h" #include "mainwindow.h" namespace vpa { SpvMatrixWidget::SpvMatrixWidget(SpvMatrixType* type, DescriptorNodeRoot* root) : SpvWidget(root), m_type(type) { QGridLayout* layout = new QGridLayout(this); layout->setAlignment(Qt::AlignTop); QPushButton* invBtn = new QPushButton("Inverse", this); connect(invBtn, SIGNAL(pressed()), this, SLOT(HandleInverse())); layout->addWidget(invBtn, 0, 0); if (m_type->rows == 4 && m_type->columns == 4) { QComboBox* defaultMatricesBox = MainWindow::MakeComboBox(this, { "Model", "View", "Projection", "MVP" }); layout->addWidget(defaultMatricesBox, 0, 1); QPushButton* defaultMatrixbutton = new QPushButton("Apply"); layout->addWidget(defaultMatrixbutton, 0, 2); QObject::connect(defaultMatrixbutton, &QPushButton::pressed, [this, defaultMatricesBox] { if (defaultMatricesBox->currentIndex() == 0) this->Fill(BYTE_CPTR(Descriptors::DefaultModelMatrix().data())); if (defaultMatricesBox->currentIndex() == 1) this->Fill(BYTE_CPTR(Descriptors::DefaultViewMatrix().data())); if (defaultMatricesBox->currentIndex() == 2) this->Fill(BYTE_CPTR(Descriptors::DefaultProjectionMatrix().data())); if (defaultMatricesBox->currentIndex() == 3) this->Fill(BYTE_CPTR(Descriptors::DefaultMVPMatrix().data())); }); } for (size_t row = 0; row < m_type->rows; ++row) { for (size_t col = 0; col < m_type->columns; ++col) { m_inputs[row][col] = new QLineEdit(this); layout->addWidget(m_inputs[row][col], int(row) + 1, int(col)); QObject::connect(m_inputs[row][col], &QLineEdit::textChanged, [this] { m_root->WriteDescriptorData(); }); } } setLayout(layout); } void SpvMatrixWidget::Data(unsigned char* dataPtr) const { float* floatPtr = reinterpret_cast<float*>(dataPtr); for (size_t row = 0; row < m_type->rows; ++row) { for (size_t col = 0; col < m_type->columns; ++col) { floatPtr[row * m_type->columns + col] = m_inputs[row][col]->text().toFloat(); } } } void SpvMatrixWidget::Fill(const unsigned char* data) { const float* floatPtr = reinterpret_cast<const float*>(data); for (size_t row = 0; row < m_type->rows; ++row) { for (size_t col = 0; col < m_type->columns; ++col) { m_inputs[row][col]->setText(QString::number(double(floatPtr[row * m_type->columns + col]))); } } } void SpvMatrixWidget::InitData() { Fill(BYTE_CPTR(DefaultData)); if (m_type->name == "mvp") { Fill(BYTE_CPTR(Descriptors::DefaultMVPMatrix().data())); } } void SpvMatrixWidget::HandleInverse() { float* data = new float[m_type->rows * m_type->columns]; for (size_t row = 0; row < m_type->rows; ++row) { for (size_t col = 0; col < m_type->columns; ++col) { data[row * m_type->columns + col] = m_inputs[row][col]->text().toFloat(); } } QMatrix4x4 mat(data, int(m_type->columns), int(m_type->rows)); mat = mat.inverted(); Fill(BYTE_CPTR(mat.data())); } }
41.918605
130
0.59473
[ "model" ]
ee7720cff95434544712e7d90883b2bde397e461
2,195
cpp
C++
src/Tap2ScreenApplication.cpp
kolayuk/Tap2Screen
824893bb84b8c81b8151a25b415ea2def610c4ba
[ "Apache-2.0" ]
3
2015-06-30T14:08:20.000Z
2020-04-27T03:19:58.000Z
src/Tap2ScreenApplication.cpp
kolayuk/Tap2Screen
824893bb84b8c81b8151a25b415ea2def610c4ba
[ "Apache-2.0" ]
null
null
null
src/Tap2ScreenApplication.cpp
kolayuk/Tap2Screen
824893bb84b8c81b8151a25b415ea2def610c4ba
[ "Apache-2.0" ]
null
null
null
/* ======================================================================== Name : Tap2ScreenApplication.cpp Author : Usanov-Kornilov Nikolay (aka Kolay) Copyright : Contacts: kolayuk@mail.ru http://kolaysoft.ru (c) KolaySoft, 2010 Description : ======================================================================== */ // [[[ begin generated region: do not modify [Generated System Includes] // ]]] end generated region [Generated System Includes] // [[[ begin generated region: do not modify [Generated Includes] #include "Tap2ScreenApplication.h" #include "Tap2ScreenDocument.h" #ifdef EKA2 #include <eikstart.h> #endif // ]]] end generated region [Generated Includes] /** * @brief Returns the application's UID (override from CApaApplication::AppDllUid()) * @return UID for this application (KUidTap2ScreenApplication) */ TUid CTap2ScreenApplication::AppDllUid() const { return KUidTap2ScreenApplication; } /** * @brief Creates the application's document (override from CApaApplication::CreateDocumentL()) * @return Pointer to the created document object (CTap2ScreenDocument) */ CApaDocument* CTap2ScreenApplication::CreateDocumentL() { return CTap2ScreenDocument::NewL( *this ); } #ifdef EKA2 /** * @brief Called by the application framework to construct the application object * @return The application (CTap2ScreenApplication) */ LOCAL_C CApaApplication* NewApplication() { return new CTap2ScreenApplication; } /** * @brief This standard export is the entry point for all Series 60 applications * @return error code */ GLDEF_C TInt E32Main() { return EikStart::RunApplication( NewApplication ); } #else // Series 60 2.x main DLL program code /** * @brief This standard export constructs the application object. * @return The application (CTap2ScreenApplication) */ EXPORT_C CApaApplication* NewApplication() { return new CTap2ScreenApplication; } /** * @brief This standard export is the entry point for all Series 60 applications * @return error code */ GLDEF_C TInt E32Dll(TDllReason /*reason*/) { return KErrNone; } #endif // EKA2
25.823529
96
0.663326
[ "object" ]
ee7a06993c8f059a1b2e43c90679517f18673713
1,281
cpp
C++
Simple_Game_Engine/Source/Map.cpp
HoloDev42/SimpleGameEngine
f8101781ab6705452d5edf0dacf85335d8b9f0c6
[ "MIT" ]
null
null
null
Simple_Game_Engine/Source/Map.cpp
HoloDev42/SimpleGameEngine
f8101781ab6705452d5edf0dacf85335d8b9f0c6
[ "MIT" ]
null
null
null
Simple_Game_Engine/Source/Map.cpp
HoloDev42/SimpleGameEngine
f8101781ab6705452d5edf0dacf85335d8b9f0c6
[ "MIT" ]
1
2018-09-15T00:41:19.000Z
2018-09-15T00:41:19.000Z
#include "Map.h" Map::Map() { m_ObjectsCount=0; m_Map = 0; } Map::Map(const Map& other) { } bool Map::Initialize(char* filename) { std::ifstream fin; char input; int i; // Open the model file. fin.open(filename); // If it could not open the file then exit. if(fin.fail()) { return false; } // Read up to the value of vertex count. fin.get(input); while(input != ':') { fin.get(input); } // Read in the vertex count. fin >> m_ObjectsCount; // Create the model using the vertex count that was read in. m_Map = new MapType[m_ObjectsCount]; if(!m_Map) { return false; } // Read up to the beginning of the data. fin.get(input); // Read in the vertex data. for(i=0; i<m_ObjectsCount; i++) { fin >> m_Map[i].objectfilename; fin >> m_Map[i].posx >> m_Map[i].posy >> m_Map[i].posz; } // Close the model file. fin.close(); return true; } void Map::Shutdown() { if(m_Map) { delete [] m_Map; m_Map = 0; m_ObjectsCount=0; } } std::string Map::GetObjectName(int index) { return m_Map[index].objectfilename; } DirectX::XMFLOAT3 Map::GetObjectMapData(int index) { return DirectX::XMFLOAT3(m_Map[index].posx,m_Map[index].posy,m_Map[index].posz); } int Map::GetObjectsCount() { return m_ObjectsCount; } Map::~Map() { }
13.34375
81
0.644809
[ "model" ]
ee7b55a5119f34f5cb8806c50a1965ad6c298f58
1,307
cpp
C++
src/AdventOfCode2019/Day24-PlanetOfDiscord/Day24-PlanetOfDiscord.cpp
dbartok/advent-of-code-cpp
c8c2df7a21980f8f3e42128f7bc5df8288f18490
[ "MIT" ]
null
null
null
src/AdventOfCode2019/Day24-PlanetOfDiscord/Day24-PlanetOfDiscord.cpp
dbartok/advent-of-code-cpp
c8c2df7a21980f8f3e42128f7bc5df8288f18490
[ "MIT" ]
null
null
null
src/AdventOfCode2019/Day24-PlanetOfDiscord/Day24-PlanetOfDiscord.cpp
dbartok/advent-of-code-cpp
c8c2df7a21980f8f3e42128f7bc5df8288f18490
[ "MIT" ]
null
null
null
#include "Day24-PlanetOfDiscord.h" #include "BugCellularAutomaton.h" #include <AdventOfCodeCommon/DisableLibraryWarningsMacros.h> __BEGIN_LIBRARIES_DISABLE_WARNINGS __END_LIBRARIES_DISABLE_WARNINGS namespace AdventOfCode { namespace Year2019 { namespace Day24 { Layout createLayout(const std::vector<std::string>& layoutLines) { Layout layout; for (int j = 0; j < layoutLines.size(); ++j) { for (int i = 0; i < layoutLines.at(j).size(); ++i) { if (layoutLines.at(j).at(i) == '#') { layout.emplace(0, Coordinates{i, j}); } } } return layout; } int biodiversityRatingOfFirstDuplicateLayout(const std::vector<std::string>& initialLayoutLines) { Layout initialLayout = createLayout(initialLayoutLines); BugCellularAutomaton automaton{initialLayout, GRID_SIZE}; automaton.simulateUntilFirstDuplicate(); return automaton.getCurrentBiodiversity(); } unsigned numBugsAfterSimulationRecursiveGrid(const std::vector<std::string>& initialLayoutLines, unsigned numSteps) { Layout initialLayout = createLayout(initialLayoutLines); BugCellularAutomaton automaton{initialLayout, GRID_SIZE}; automaton.simulateStepsRecursiveGrid(numSteps); return automaton.getNumBugs(); } } } }
21.783333
115
0.710023
[ "vector" ]
ee7c12f7da2967ea30a321a07248e5c0871e9915
8,380
cpp
C++
Blik2D/addon/openalpr-2.3.0_for_blik/src/openalpr/prewarp.cpp
BonexGu/Blik2D
8e0592787e5c8e8a28682d0e1826b8223eae5983
[ "MIT" ]
13
2017-02-22T02:20:06.000Z
2018-06-06T04:18:03.000Z
Blik2D/addon/openalpr-2.3.0_for_blik/src/openalpr/prewarp.cpp
BonexGu/Blik2D
8e0592787e5c8e8a28682d0e1826b8223eae5983
[ "MIT" ]
null
null
null
Blik2D/addon/openalpr-2.3.0_for_blik/src/openalpr/prewarp.cpp
BonexGu/Blik2D
8e0592787e5c8e8a28682d0e1826b8223eae5983
[ "MIT" ]
null
null
null
/* * Copyright (c) 2015 OpenALPR Technology, Inc. * Open source Automated License Plate Recognition [http://www.openalpr.com] * * This file is part of OpenALPR. * * OpenALPR is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License * version 3 as published by the Free Software Foundation * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include BLIK_OPENCV_V_opencv2__highgui__highgui_hpp //original-code:<opencv2/highgui/highgui.hpp> #include BLIK_OPENALPR_U_prewarp_h //original-code:"prewarp.h" using namespace std; using namespace cv; namespace alpr { PreWarp::PreWarp(Config* config) { this->config = config; initialize(config->prewarp); } void PreWarp::initialize(std::string prewarp_config) { timespec startTime; getTimeMonotonic(&startTime); // Do a cursory verification based on number of commas int commacount = count(prewarp_config.begin(), prewarp_config.end(), ','); if (prewarp_config.length() < 4) { // No config specified. ignore if (this->config->debugPrewarp) cout << "No prewarp configuration specified" << endl; this->valid = false; } else if (commacount != 9) { if (this->config->debugPrewarp) cout << "Invalid prewarp configuration" << endl; this->valid = false; } else { // Parse the warp_config int first_comma = prewarp_config.find(","); string name = prewarp_config.substr(0, first_comma); if (name != "planar") { this->valid = false; } else { stringstream ss(prewarp_config.substr(first_comma + 1, prewarp_config.length())); float w, h, rotationx, rotationy, rotationz, panX, panY, stretchX, dist; ss >> w; ss.ignore(); ss >> h; ss.ignore(); ss >> rotationx; ss.ignore(); // Ignore comma ss >> rotationy; ss.ignore(); // Ignore comma ss >> rotationz; ss.ignore(); // Ignore comma ss >> stretchX; ss.ignore(); // Ignore comma ss >> dist; ss.ignore(); // Ignore comma ss >> panX; ss.ignore(); // Ignore comma ss >> panY; setTransform(w, h, rotationx, rotationy, rotationz, panX, panY, stretchX, dist); } } timespec endTime; getTimeMonotonic(&endTime); if (config->debugTiming) cout << "Prewarp Initialization Time: " << diffclock(startTime, endTime) << "ms." << endl; } void PreWarp::clear() { this->valid = false; } PreWarp::~PreWarp() { } std::string PreWarp::toString() { if (!this->valid) return ""; stringstream sstream; sstream << "planar," << w << "," << h << "," << rotationx << "," << rotationy << "," << rotationz << "," << panX << "," << panY << "," << stretchX << "," << dist; return sstream.str(); } void PreWarp::setTransform(float w, float h, float rotationx, float rotationy, float rotationz, float panX, float panY, float stretchX, float dist) { this->w = w; this->h = h; this->rotationx = rotationx; this->rotationy = rotationy; this->rotationz = rotationz; this->panX = panX; this->panY = panY; this->stretchX = stretchX; this->dist = dist; this->valid = true; } cv::Mat PreWarp::warpImage(Mat image) { if (!this->valid) { if (this->config->debugPrewarp) cout << "prewarp skipped due to missing prewarp config" << endl; return image; } float width_ratio = w / ((float)image.cols); float height_ratio = h / ((float)image.rows); float rx = rotationx * width_ratio; float ry = rotationy * width_ratio; float px = panX / width_ratio; float py = panY / height_ratio; transform = getTransform(image.cols, image.rows, rx, ry, rotationz, px, py, stretchX, dist); Mat warped_image; warpPerspective(image, warped_image, transform, image.size(), INTER_CUBIC | WARP_INVERSE_MAP); if (this->config->debugPrewarp && this->config->debugShowImages) { imshow("Prewarp", warped_image); } return warped_image; } // Projects a "region of interest" into the new space // The rect needs to be converted to points, warped, then converted back into a // bounding rectangle vector<Rect> PreWarp::projectRects(vector<Rect> rects, int maxWidth, int maxHeight, bool inverse) { if (!this->valid) return rects; vector<Rect> projected_rects; for (unsigned int i = 0; i < rects.size(); i++) { Rect r = projectRect(rects[i], maxWidth, maxHeight, inverse); projected_rects.push_back(r); } return projected_rects; } Rect PreWarp::projectRect(Rect rect, int maxWidth, int maxHeight, bool inverse) { vector<Point2f> points; points.push_back(Point(rect.x, rect.y)); points.push_back(Point(rect.x + rect.width, rect.y)); points.push_back(Point(rect.x + rect.width, rect.y + rect.height)); points.push_back(Point(rect.x, rect.y + rect.height)); vector<Point2f> projectedPoints = projectPoints(points, inverse); Rect projectedRect = boundingRect(projectedPoints); projectedRect = expandRect(projectedRect, 0, 0, maxWidth, maxHeight); return projectedRect; } vector<Point2f> PreWarp::projectPoints(vector<Point2f> points, bool inverse) { if (!this->valid) return points; vector<Point2f> output; if (!inverse) perspectiveTransform(points, output, transform.inv()); else perspectiveTransform(points, output, transform); return output; } void PreWarp::projectPlateRegions(vector<PlateRegion>& plateRegions, int maxWidth, int maxHeight, bool inverse){ if (!this->valid) return; for (unsigned int i = 0; i < plateRegions.size(); i++) { vector<Rect> singleRect; singleRect.push_back(plateRegions[i].rect); vector<Rect> transformedRect = projectRects(singleRect, maxWidth, maxHeight, inverse); plateRegions[i].rect.x = transformedRect[0].x; plateRegions[i].rect.y = transformedRect[0].y; plateRegions[i].rect.width = transformedRect[0].width; plateRegions[i].rect.height = transformedRect[0].height; projectPlateRegions(plateRegions[i].children, maxWidth, maxHeight, inverse); } } cv::Mat PreWarp::getTransform(float w, float h, float rotationx, float rotationy, float rotationz, float panX, float panY, float stretchX, float dist) { float alpha = rotationx; float beta = rotationy; float gamma = rotationz; float f = 1.0; // Projection 2D -> 3D matrix Mat A1 = (Mat_<double>(4,3) << 1, 0, -w/2, 0, 1, -h/2, 0, 0, 0, 0, 0, 1); // Camera Intrisecs matrix 3D -> 2D Mat A2 = (Mat_<double>(3,4) << f, 0, w/2, 0, 0, f, h/2, 0, 0, 0, 1, 0); // Rotation matrices around the X axis Mat Rx = (Mat_<double>(4, 4) << 1, 0, 0, 0, 0, cos(alpha), -sin(alpha), 0, 0, sin(alpha), cos(alpha), 0, 0, 0, 0, 1); // Rotation matrices around the Y axis Mat Ry = (Mat_<double>(4, 4) << cos(beta), 0, sin(beta), 0, 0, 1, 0, 0, -sin(beta), 0, cos(beta), 0, 0, 0, 0, 1); // Rotation matrices around the Z axis Mat Rz = (Mat_<double>(4, 4) << cos(gamma), -sin(gamma), 0, 0, sin(gamma), cos(gamma), 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); Mat R = Rx*Ry*Rz; // Translation matrix on the Z axis Mat T = (Mat_<double>(4, 4) << stretchX, 0, 0, panX, 0, 1, 0, panY, 0, 0, 1, dist, 0, 0, 0, 1); return A2 * (T * (R * A1)); } }
27.656766
149
0.591885
[ "vector", "transform", "3d" ]
ee7d64b69dee21770ea6b103a633b92e47d0caec
8,576
cc
C++
test/apps/activity-loader.cc
zhiqiang-hu/cell-phone-ux-demo
80df27f47bdf3318b60fe327890f868c3fe28969
[ "Apache-2.0" ]
13
2017-12-17T16:18:44.000Z
2022-01-07T15:40:36.000Z
test/apps/activity-loader.cc
zhiqiang-hu/cell-phone-ux-demo
80df27f47bdf3318b60fe327890f868c3fe28969
[ "Apache-2.0" ]
null
null
null
test/apps/activity-loader.cc
zhiqiang-hu/cell-phone-ux-demo
80df27f47bdf3318b60fe327890f868c3fe28969
[ "Apache-2.0" ]
8
2018-07-07T03:08:33.000Z
2022-01-27T09:25:08.000Z
/////////////////////////////////////////////////////////////////////////////// // // IMPORTANT NOTICE // // The following open source license statement does not apply to any // entity in the Exception List published by FMSoft. // // For more information, please visit: // // https://www.fmsoft.cn/exception-list // ////////////////////////////////////////////////////////////////////////////// #ifndef WIN32 # include <sys/time.h> # include <sys/stat.h> # include <sys/types.h> #endif #include <time.h> #define protected public #include "global.h" #include "register.h" #include "apps/screen-lock/mshutterpiece.h" #include "Activity.hh" #include "ContentResolver.hh" #include "SimpleProviderFactory.hh" #include "apps/screen-lock/ScreenLockActivity.hh" #define BACK_GROUND_IMAGE "res/common/toptitle.png" #define IDC_STATIC_TIME 100 #define IDC_TIMER 150 #define TITLE_TEXT_POS_W 50 #define TITLE_TEXT_POS_H 12 #define TITLE_TEXT_POS_Y 2 #define TITLE_TEXT_POS_X ((SCREEN_W-TITLE_TEXT_POS_W)>>1) static BITMAP backGroundBmp; static CTRLDATA timeAndDate[] = { { "static", WS_VISIBLE, TITLE_TEXT_POS_X, TITLE_TEXT_POS_Y, TITLE_TEXT_POS_W, TITLE_TEXT_POS_H, IDC_STATIC_TIME, "", 0, WS_EX_TRANSPARENT, }, }; void SetTopBarInfo(HWND hWnd) { #ifdef WIN32 char time[]="12:00:00"; char year_month[]="2010-08"; char day[]="20"; #else struct timeval tv; gettimeofday(&tv, NULL); struct tm *tm = localtime(&tv.tv_sec); char time[10]; memset(time, 0, 8); if(tm->tm_hour >= 12) { sprintf(time, "%02d:%02d PM", tm->tm_hour, tm->tm_min); } else { sprintf(time, "%02d:%02d AM", tm->tm_hour, tm->tm_min); } #endif SetWindowText(GetDlgItem(hWnd, IDC_STATIC_TIME), time); } Activity *activity; static LRESULT InfoBarProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case MSG_CREATE: { mGEffInit(); if(!SetTimer(hWnd, IDC_TIMER, 100)) { printf("create timer failed\n"); assert(0); return -1; } if(0 != LoadBitmapFromFile(HDC_SCREEN, &backGroundBmp, BACK_GROUND_IMAGE)) { printf("load bitmap %s failed\n", BACK_GROUND_IMAGE); assert(0); return -1; } /* if(0 != LoadBitmapFromFile(HDC_SCREEN, &battery, BATTERY_IMAGE)) { printf("load bitmap %s failed\n", BATTERY_IMAGE); return -1; }*/ size_t i = 0; for(i = 0; i < sizeof(timeAndDate)/sizeof(CTRLDATA); i++) { HWND hstatic= CreateWindowEx(timeAndDate[i].class_name, timeAndDate[i].caption, timeAndDate[i].dwStyle, timeAndDate[i].dwExStyle, timeAndDate[i].id, timeAndDate[i].x, timeAndDate[i].y, timeAndDate[i].w, timeAndDate[i].h, hWnd, timeAndDate[i].dwAddData); if(HWND_INVALID == hstatic) { printf("create static for displaying date and time failed\n"); assert(0); return -1; } SetWindowElementAttr (hstatic, WE_FGC_WINDOW, 0xFFFFFFFF); //SetWindowElementAttr (GetDlgItem(hWnd, IDC_STATIC_DAY), WE_ATTR_TYPE_FONT, 1); } SetTopBarInfo(hWnd); } break; case MSG_TIMER: SetTopBarInfo(hWnd); break; case MSG_PAINT: { HDC hdc = BeginPaint(hWnd); FillBoxWithBitmap(hdc, 0, 0, SCREEN_W, ACTIVITY_Y, &backGroundBmp); //FillBoxWithBitmapPart(hdc, 181, 0, 0, 0, 0, 0, &battery, signal*BATTERY_ICON_WIDTH); EndPaint(hWnd, hdc); } return 0; case MSG_CLOSE: fprintf(stderr, "%s:%d.\n", __FUNCTION__, __LINE__); UnloadBitmap(&backGroundBmp); SendNotifyMessage(activity->hwnd(), MSG_CLOSE, 0, 0); DestroyMainWindow(hWnd); mGEffDeinit (); break; default: break; } return DefaultMainWinProc(hWnd, message, wParam, lParam); } static int MyMiniGUIMain(const char *activity_name) { MSG Msg; HWND hMainWnd; MAINWINCREATE CreateInfo; if (! getenv("SHOW_CURSOR")) { ShowCursor(FALSE); } #ifdef _MGRM_PROCESSES JoinLayer(NAME_DEF_LAYER , "CellPhone" , 0 , 0); #endif memset(&CreateInfo, 0, sizeof(CreateInfo)); CreateInfo.dwStyle = WS_VISIBLE; CreateInfo.dwExStyle = WS_EX_NONE; CreateInfo.spCaption = "Desktop"; CreateInfo.hMenu = 0; CreateInfo.hCursor = GetSystemCursor(0); CreateInfo.hIcon = 0; CreateInfo.MainWindowProc = InfoBarProc; CreateInfo.lx = 0; CreateInfo.ty = 0; CreateInfo.rx = SCREEN_W; CreateInfo.by = ACTIVITY_Y; CreateInfo.iBkColor = COLOR_black; CreateInfo.dwAddData = 0; CreateInfo.hHosting = HWND_DESKTOP; Init32MemDC(); ncsInitialize(); ncs4TouchInitialize(); REGISTER_NCS(); hMainWnd = CreateMainWindow (&CreateInfo); if (hMainWnd == HWND_INVALID) { assert(0); return -1; } // register system content provider GET_CONTENT_RESOLVER()->registerContentProvider( ProviderFactory::CreateSystemProvider(SETTINGS_PROVIDER)); GET_CONTENT_RESOLVER()->registerContentProvider( ProviderFactory::CreateSystemProvider(CONTACTS_PROVIDER)); GET_CONTENT_RESOLVER()->registerContentProvider( ProviderFactory::CreateSystemProvider(MEDIASTORE_PROVIDER)); GET_CONTENT_RESOLVER()->registerContentProvider( ProviderFactory::CreateSystemProvider(SMS_PROVIDER)); GET_CONTENT_RESOLVER()->registerContentProvider( ProviderFactory::CreateSystemProvider(CALLLOG_PROVIDER)); GET_CONTENT_RESOLVER()->registerContentProvider( ProviderFactory::CreateSystemProvider(APPSINFO_PROVIDER)); ActivityFactory* tmp = ActivityFactory::singleton(); activity = tmp->create(activity_name); if (! activity) { fprintf(stderr, "Failed to create %s\n", activity_name); tmp->list (); assert (0); exit(1); } activity->onStart(); ShowWindow(activity->hwnd(), SW_SHOW); while (GetMessage(&Msg, hMainWnd)) { TranslateMessage(&Msg); DispatchMessage(&Msg); } //activity->onStop(); GET_CONTENT_RESOLVER()->clearContentProvider(); delete GET_CONTENT_RESOLVER(); MainWindowThreadCleanup (hMainWnd); MGNCS_UNREG_COMPONENT(mContainerCtrl); MGNCS_UNREG_COMPONENT(mIconFlow); Release32MemDC(); ncs4TouchInitialize(); ncsUninitialize(); //delete activity; return 0; } int main(int argc, const char *argv[]) { int ret; std::vector<std::string> names; ActivityFactory::singleton()->queryNames(names); std::string activity_name; std::vector<std::string>::const_iterator i; if (argc == 1) { for (i=names.begin(); i!=names.end(); ++i) { if (strstr(argv[0], i->c_str())) { activity_name = i->c_str(); break; } } if (i==names.end()) { fprintf(stderr, "Usage: %s mklinks|rmlinks|<ClassName>\n", argv[0]); ActivityFactory::singleton()->list(); exit(1); } }else if (argc == 2) { if (strcmp(argv[1], "mklinks")==0) { for (i=names.begin(); i!=names.end(); ++i) { printf("mklink %s\n", i->c_str()); #ifndef WIN32 if (symlink(argv[0], i->c_str()) < 0) { printf("error on mklink %s\n", i->c_str()); } #endif } exit(0); }else if (strcmp(argv[1], "rmlinks") == 0) { for (i=names.begin(); i!=names.end(); ++i) { unlink(i->c_str()); } exit(0); }else{ activity_name = argv[1]; } } InitGUI(argc, argv); DO_REGISTER_ACTIVITY (ScreenLockActivity); ret = MyMiniGUIMain(activity_name.c_str()); TerminateGUI(0); return ret; }
29.47079
104
0.559585
[ "vector" ]
ee8865bea33c7dcaf1745db6c71d6cc82a089527
291
cpp
C++
Interview/code/code.cpp
xiaorancs/xr-Algorithm
4b522b2936b986f7891756fc610917b99864c534
[ "MIT" ]
7
2017-12-11T12:42:39.000Z
2019-11-17T15:10:26.000Z
Interview/code/code.cpp
xiaorancs/xr-Algorithm
4b522b2936b986f7891756fc610917b99864c534
[ "MIT" ]
1
2018-08-29T12:29:51.000Z
2018-08-29T12:29:51.000Z
Interview/code/code.cpp
xiaorancs/xr-Algorithm
4b522b2936b986f7891756fc610917b99864c534
[ "MIT" ]
2
2018-01-29T08:26:30.000Z
2018-08-10T01:30:44.000Z
/** *Author: xiaoran *座右铭:既来之,则安之 */ #include<iostream> #include<stdio.h> #include<algorithm> #include<math.h> #include<set> #include<map> #include<vector> #include<string> #include<string.h> using namespace std; typedef long long LL; const int MAXN = 1005; int main() { return 0; }
11.64
22
0.694158
[ "vector" ]
ee891388251f6bcb17d46b86a674f0a8cc8ff1c3
12,255
cpp
C++
samples/snippets/cpp/VS_Snippets_Remoting/System.Net.Sockets.UdpClient.JoinMulticastGroup/CPP/joinmulticastgroup.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
421
2018-04-01T01:57:50.000Z
2022-03-28T15:24:42.000Z
samples/snippets/cpp/VS_Snippets_Remoting/System.Net.Sockets.UdpClient.JoinMulticastGroup/CPP/joinmulticastgroup.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
5,797
2018-04-02T21:12:23.000Z
2022-03-31T23:54:38.000Z
samples/snippets/cpp/VS_Snippets_Remoting/System.Net.Sockets.UdpClient.JoinMulticastGroup/CPP/joinmulticastgroup.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
1,482
2018-03-31T11:26:20.000Z
2022-03-30T22:36:45.000Z
// File name:multicastOperations.cs // This example shows how to join a multicast group and perform a muticast // data exchange. The OriginatorClient Object* starts the conversation while // the TargetClient responds. The two helper objects Receive and Send // perform the actual data exchange. // Note. This program cannot be build with the current VS build version. // Build it via command line. Rubuild it in VS when a suitable version is // available. // <Snippet1> #using <System.dll> using namespace System; using namespace System::Net; using namespace System::Net::Sockets; using namespace System::Text; using namespace System::IO; using namespace System::Threading; // The following Receive class is used by both the ClientOriginator and // the ClientTarget class to receive data from one another.. public ref class Receive { public: // The following static method performs the actual data // exchange. In particular, it performs the following tasks: // 1)Establishes a communication endpoint. // 2)Receive data through this end point on behalf of the // caller. // 3) Returns the received data in ASCII format. static String^ ReceiveUntilStop( UdpClient^ c ) { String^ strData = ""; String^ Ret = ""; ASCIIEncoding^ ASCII = gcnew ASCIIEncoding; // Establish the communication endpoint. IPEndPoint^ endpoint = gcnew IPEndPoint( IPAddress::IPv6Any,50 ); while ( !strData->Equals( "Over" ) ) { array<Byte>^data = c->Receive( endpoint ); strData = ASCII->GetString( data ); Ret = String::Concat( Ret, strData, "\n" ); } return Ret; } }; // The following Send class is used by both the ClientOriginator and // ClientTarget classes to send data to one another. public ref class Send { private: static array<Char>^greetings = {'H','e','l','l','o',' ','T','a','r','g','e','t','->'}; static array<Char>^nice = {'H','a','v','e',' ','a',' ','n','i','c','e',' ','d','a','y','->'}; static array<Char>^eom = {'O','v','e','r'}; static array<Char>^tGreetings = {'H','e','l','l','o',' ','O','r','i','g','i','n','a','t','o','r','!'}; static array<Char>^tNice = {'Y','o','u',' ','t','o','o','->'}; public: // The following static method sends data to the ClientTarget on // behalf of the ClientOriginator. static void OriginatorSendData( UdpClient^ c, IPEndPoint^ ep ) { Console::WriteLine( gcnew String( greetings ) ); c->Send( GetByteArray( greetings ), greetings->Length, ep ); Thread::Sleep( 1000 ); Console::WriteLine( gcnew String( nice ) ); c->Send( GetByteArray( nice ), nice->Length, ep ); Thread::Sleep( 1000 ); Console::WriteLine( gcnew String( eom ) ); c->Send( GetByteArray( eom ), eom->Length, ep ); } // The following static method sends data to the ClientOriginator on // behalf of the ClientTarget. static void TargetSendData( UdpClient^ c, IPEndPoint^ ep ) { Console::WriteLine( gcnew String( tGreetings ) ); c->Send( GetByteArray( tGreetings ), tGreetings->Length, ep ); Thread::Sleep( 1000 ); Console::WriteLine( gcnew String( tNice ) ); c->Send( GetByteArray( tNice ), tNice->Length, ep ); Thread::Sleep( 1000 ); Console::WriteLine( gcnew String( eom ) ); c->Send( GetByteArray( eom ), eom->Length, ep ); } private: // Internal utility static array<Byte>^ GetByteArray( array<Char>^ChArray ) { array<Byte>^Ret = gcnew array<Byte>(ChArray->Length); for ( int i = 0; i < ChArray->Length; i++ ) Ret[ i ] = (Byte)ChArray[ i ]; return Ret; } }; // The ClientTarget class is the receiver of the ClientOriginator // messages. The StartMulticastConversation method contains the // logic for exchanging data between the ClientTarget and its // counterpart ClientOriginator in a multicast operation. public ref class ClientTarget { private: static UdpClient^ m_ClientTarget; static IPAddress^ m_GrpAddr; public: // The following StartMulticastConversation method connects the UDP // ClientTarget with the ClientOriginator. // It performs the following main tasks: // 1)Creates a UDP client to receive data on a specific port and using // IPv6 addresses. The port is the same one used by the ClientOriginator // to define its communication endpoint. // 2)Joins or creates a multicast group at the specified address. // 3)Defines the endpoint port to send data to the ClientOriginator. // 4)Receives data from the ClientOriginator until the end of the // communication. // 5)Sends data to the ClientOriginator. // Note this method is the counterpart of the // ClientOriginator::ConnectOriginatorAndTarget(). static void StartMulticastConversation() { String^ Ret; // Bind and listen on port 1000. Specify the IPv6 address family type. m_ClientTarget = gcnew UdpClient( 1000,AddressFamily::InterNetworkV6 ); // Join or create a multicast group m_GrpAddr = IPAddress::Parse( "FF01::1" ); // Use the overloaded JoinMulticastGroup method. // Refer to the ClientOriginator method to see how to use the other // methods. m_ClientTarget->JoinMulticastGroup( m_GrpAddr ); // Define the endpoint data port. Note that this port number // must match the ClientOriginator UDP port number which is the // port on which the ClientOriginator is receiving data. IPEndPoint^ ClientOriginatordest = gcnew IPEndPoint( m_GrpAddr,2000 ); // Receive data from the ClientOriginator. Ret = Receive::ReceiveUntilStop( m_ClientTarget ); Console::WriteLine( "\nThe ClientTarget received: \n\n {0}\n", Ret ); // Done receiving, now respond to the ClientOriginator. // Wait to make sure the ClientOriginator is ready to receive. Thread::Sleep( 2000 ); Console::WriteLine( "\nThe ClientTarget sent:\n" ); Send::TargetSendData( m_ClientTarget, ClientOriginatordest ); // Exit the multicast conversation. m_ClientTarget->DropMulticastGroup( m_GrpAddr ); } }; // The following ClientOriginator class starts the multicast conversation // with the ClientTarget class.. // It performs the following main tasks: // 1)Creates a socket and binds it to the port on which to communicate. // 2)Specifies that the connection must use an IPv6 address. // 3)Joins or create a multicast group. // Note that the multicast address ranges to use are specified // in the RFC#2375. // 4)Defines the endpoint to send the data to and starts the // client target (ClientTarget) thread. public ref class ClientOriginator { private: static UdpClient^ clientOriginator; static IPAddress^ m_GrpAddr; static IPEndPoint^ m_ClientTargetdest; static Thread^ m_t; public: // The ConnectOriginatorAndTarget method connects the // ClientOriginator with the ClientTarget. // It performs the following main tasks: // 1)Creates a UDP client to receive data on a specific port // using IPv6 addresses. // 2)Joins or create a multicast group at the specified address. // 3)Defines the endpoint port to send data to on the ClientTarget. // 4)Starts the ClientTarget thread that also creates the ClientTarget Object*. // Note this method is the counterpart of the // ClientTarget::StartMulticastConversation(). static bool ConnectOriginatorAndTarget() { try { // <Snippet3> // Bind and listen on port 2000. This constructor creates a socket // and binds it to the port on which to receive data. The family // parameter specifies that this connection uses an IPv6 address. clientOriginator = gcnew UdpClient( 2000,AddressFamily::InterNetworkV6 ); // Join or create a multicast group. The multicast address ranges // to use are specified in RFC#2375. You are free to use // different addresses. // Transform the String* address into the internal format. m_GrpAddr = IPAddress::Parse( "FF01::1" ); // Display the multicast address used. Console::WriteLine( "Multicast Address: [ {0}]", m_GrpAddr ); // <Snippet4> // Exercise the use of the IPv6MulticastOption. Console::WriteLine( "Instantiate IPv6MulticastOption(IPAddress)" ); // Instantiate IPv6MulticastOption using one of the // overloaded constructors. IPv6MulticastOption^ ipv6MulticastOption = gcnew IPv6MulticastOption( m_GrpAddr ); // Store the IPAdress multicast options. IPAddress^ group = ipv6MulticastOption->Group; __int64 interfaceIndex = ipv6MulticastOption->InterfaceIndex; // Display IPv6MulticastOption properties. Console::WriteLine( "IPv6MulticastOption::Group: [ {0}]", group ); Console::WriteLine( "IPv6MulticastOption::InterfaceIndex: [ {0}]", interfaceIndex ); // </Snippet4> // <Snippet5> // Instantiate IPv6MulticastOption using another // overloaded constructor. IPv6MulticastOption^ ipv6MulticastOption2 = gcnew IPv6MulticastOption( group,interfaceIndex ); // Store the IPAdress multicast options. group = ipv6MulticastOption2->Group; interfaceIndex = ipv6MulticastOption2->InterfaceIndex; // Display the IPv6MulticastOption2 properties. Console::WriteLine( "IPv6MulticastOption::Group: [ {0} ]", group ); Console::WriteLine( "IPv6MulticastOption::InterfaceIndex: [ {0} ]", interfaceIndex ); // Join the specified multicast group using one of the // JoinMulticastGroup overloaded methods. clientOriginator->JoinMulticastGroup( (int)interfaceIndex, group ); // </Snippet5> // Define the endpoint data port. Note that this port number // must match the ClientTarget UDP port number which is the // port on which the ClientTarget is receiving data. m_ClientTargetdest = gcnew IPEndPoint( m_GrpAddr,1000 ); // </Snippet3> // Start the ClientTarget thread so it is ready to receive. m_t = gcnew Thread( gcnew ThreadStart( ClientTarget::StartMulticastConversation ) ); m_t->Start(); // Make sure that the thread has started. Thread::Sleep( 2000 ); return true; } catch ( Exception^ e ) { Console::WriteLine( "[ClientOriginator::ConnectClients] Exception: {0}", e ); return false; } } // The SendAndReceive performs the data exchange // between the ClientOriginator and the ClientTarget classes. static String^ SendAndReceive() { String^ Ret = ""; // <Snippet2> // Send data to ClientTarget. Console::WriteLine( "\nThe ClientOriginator sent:\n" ); Send::OriginatorSendData( clientOriginator, m_ClientTargetdest ); // Receive data from ClientTarget Ret = Receive::ReceiveUntilStop( clientOriginator ); // Stop the ClientTarget thread m_t->Abort(); // Abandon the multicast group. clientOriginator->DropMulticastGroup( m_GrpAddr ); // </Snippet2> return Ret; } }; //This is the console application entry point. int main() { // Join the multicast group. if ( ClientOriginator::ConnectOriginatorAndTarget() ) { // Perform a multicast conversation with the ClientTarget. String^ Ret = ClientOriginator::SendAndReceive(); Console::WriteLine( "\nThe ClientOriginator received: \n\n {0}", Ret ); } else { Console::WriteLine( "Unable to Join the multicast group" ); } } // </Snippet1>
37.477064
106
0.639331
[ "object", "transform" ]
ee8b3b74c13eaf91f29168329bd905150960d7db
729
hpp
C++
include/verifyDriveGeometry.hpp
openbmc/estoraged
4906f4ef7e04ddbbf18a401a5b9963748270cce2
[ "Apache-2.0" ]
1
2021-11-23T19:22:16.000Z
2021-11-23T19:22:16.000Z
include/verifyDriveGeometry.hpp
openbmc/estoraged
4906f4ef7e04ddbbf18a401a5b9963748270cce2
[ "Apache-2.0" ]
1
2021-11-04T01:58:36.000Z
2021-11-04T01:58:36.000Z
include/verifyDriveGeometry.hpp
openbmc/estoraged
4906f4ef7e04ddbbf18a401a5b9963748270cce2
[ "Apache-2.0" ]
null
null
null
#pragma once #include "erase.hpp" #include "util.hpp" #include <string_view> namespace estoraged { class VerifyDriveGeometry : public Erase { public: /** @brief Creates a verifyDriveGeomentry erase object. * * @param[in] inDevPath - the linux device path for the block device. */ VerifyDriveGeometry(std::string_view inDevPath) : Erase(inDevPath) {} /** @brief Test if input is in between the max and min expected sizes, * and throws errors accordingly. * * @param[in] bytes - Size of the block device */ void geometryOkay() { geometryOkay(util::findSizeOfBlockDevice(devPath)); } void geometryOkay(uint64_t bytes); }; } // namespace estoraged
21.441176
74
0.663923
[ "object" ]
ee8c8d4bea3ce897bada9ef27214532a5c7aaf3e
2,051
cpp
C++
Natsu2D/RenderDevice/n2dVBOHelper.cpp
akemimadoka/Natsu2D
c1dd335642f3485470aebde165416a19a8751b4d
[ "WTFPL" ]
11
2016-01-26T09:49:56.000Z
2019-04-24T09:33:40.000Z
Natsu2D/RenderDevice/n2dVBOHelper.cpp
akemimadoka/Natsu2D
c1dd335642f3485470aebde165416a19a8751b4d
[ "WTFPL" ]
null
null
null
Natsu2D/RenderDevice/n2dVBOHelper.cpp
akemimadoka/Natsu2D
c1dd335642f3485470aebde165416a19a8751b4d
[ "WTFPL" ]
null
null
null
#include "n2dVBOHelper.h" #include <map> #include <algorithm> #ifdef max # undef max #endif #ifdef min # undef min #endif namespace n2dVBOHelper { struct PackedVertex { natVec3<> position; natVec2<> uv; natVec3<> normal; bool operator<(const PackedVertex& other) const { return memcmp(this, &other, sizeof(PackedVertex)) > 0; }; }; bool getSimilarVertexIndex(PackedVertex & packed, std::map<PackedVertex, unsigned short> & VertexToOutIndex, unsigned short & result) { auto it = VertexToOutIndex.find(packed); if (it == VertexToOutIndex.end()){ return false; } result = it->second; return true; } void indexVBO(std::vector<natVec3<>>& vertices, std::vector<natVec2<>>& uvs, std::vector<natVec3<>>& normals, std::vector<unsigned short>& out_indices) { out_indices.clear(); std::vector<natVec3<>> out_vertices(vertices); std::vector<natVec2<>> out_uvs(uvs); std::vector<natVec3<>> out_normals(normals); std::map<PackedVertex, nuShort> VertexToOutIndex; nuInt count = static_cast<nuInt>(std::min({ vertices.size(), uvs.size(), normals.size() })); for (nuInt i = 0u; i < count; ++i) { PackedVertex packed = { vertices[i], uvs[i], normals[i] }; // Try to find a similar vertex in out_XXXX nuShort index; if (getSimilarVertexIndex(packed, VertexToOutIndex, index)) { // A similar vertex is already in the VBO, use it instead ! out_indices.push_back(index); } else { // If not, it needs to be added in the output data. out_vertices.push_back(vertices[i]); out_uvs.push_back(uvs[i]); out_normals.push_back(normals[i]); unsigned short newindex = static_cast<unsigned short>(out_vertices.size()) - 1; out_indices.push_back(newindex); VertexToOutIndex[packed] = newindex; } } /*vertices.swap(out_vertices); uvs.swap(out_uvs); normals.swap(out_normals);*/ vertices.assign(out_vertices.begin(), out_vertices.end()); uvs.assign(out_uvs.begin(), out_uvs.end()); normals.assign(out_normals.begin(), out_normals.end()); } }
25.320988
152
0.685519
[ "vector" ]
ee8fa29fd47e4da4d399b40efcf38d40462dd08d
2,553
cpp
C++
src/Exercises/PyramidAnimation/pyramid.cpp
mjaglarz/3D-graphics-programming
636fb074a6e68caf0fa111d658d9e7594b88142d
[ "MIT" ]
null
null
null
src/Exercises/PyramidAnimation/pyramid.cpp
mjaglarz/3D-graphics-programming
636fb074a6e68caf0fa111d658d9e7594b88142d
[ "MIT" ]
null
null
null
src/Exercises/PyramidAnimation/pyramid.cpp
mjaglarz/3D-graphics-programming
636fb074a6e68caf0fa111d658d9e7594b88142d
[ "MIT" ]
null
null
null
#include <vector> #include "pyramid.h" Pyramid::Pyramid() { std::vector<GLfloat> vertices = { //Front of the pyramid 0.0f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, //Right side of the pyramid 0.0f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.0f, //Left side of the pyramid 0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 1.0f, //Back of the pyramid 0.0f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 1.0f, //Bottom of the pyramid -0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, -0.5f, -0.5f, 0.5f, 1.0f, 1.0f, 1.0f, 0.5f, -0.5f, 0.5f, 1.0f, 1.0f, 1.0f }; std::vector<GLushort> indices = { 2, 1, 0, 3, 4, 5, 8, 7, 6, 9, 10, 11, 12, 13, 14, 15, 14, 13 }; glGenBuffers(1, &buffer_[0]); glBindBuffer(GL_ARRAY_BUFFER, buffer_[0]); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(GLfloat), vertices.data(), GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); glGenBuffers(1, &buffer_[1]); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer_[1]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(GLushort), indices.data(), GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glGenVertexArrays(1, &vao_); glBindVertexArray(vao_); glBindBuffer(GL_ARRAY_BUFFER, buffer_[0]); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer_[1]); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), reinterpret_cast<GLvoid *>(0)); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), reinterpret_cast<GLvoid *>(3*sizeof(GLfloat))); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } Pyramid::~Pyramid() { glDeleteBuffers(2, buffer_); glDeleteVertexArrays(1, &vao_); } void Pyramid::draw() { glBindVertexArray(vao_); glEnable(GL_DEPTH_TEST); glDrawElements(GL_TRIANGLES, 18, GL_UNSIGNED_SHORT, reinterpret_cast<GLvoid *>(0)); glBindVertexArray(0); }
32.730769
120
0.560909
[ "vector" ]
ee90bf24382d3f6594fe950b180667b3827af1b6
1,014
cpp
C++
144.Binary Tree Preorder Traversal/main.cpp
Kingpie/leetcode
b5fd90a12f34f5baf24a3d4fa04c0914dd3e000f
[ "Apache-2.0" ]
null
null
null
144.Binary Tree Preorder Traversal/main.cpp
Kingpie/leetcode
b5fd90a12f34f5baf24a3d4fa04c0914dd3e000f
[ "Apache-2.0" ]
null
null
null
144.Binary Tree Preorder Traversal/main.cpp
Kingpie/leetcode
b5fd90a12f34f5baf24a3d4fa04c0914dd3e000f
[ "Apache-2.0" ]
null
null
null
/*Given a binary tree, return the preorder traversal of its nodes' values. Example: Input: [1,null,2,3] 1 \ 2 / 3 Output: [1,2,3] Follow up: Recursive solution is trivial, could you do it iteratively? 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/binary-tree-preorder-traversal 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。*/ /** * 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: vector<int> preorderTraversal(TreeNode* root) { stack<TreeNode*> stk; vector<int> ans; if(root) stk.push(root); while(!stk.empty()){ auto node = stk.top(); stk.pop(); ans.push_back(node->val); if(node->right) stk.push(node->right); if(node->left) stk.push(node->left); } return ans; } };
21.574468
74
0.557199
[ "vector" ]
ee91f57b1dd30cf229310cd5ff243cd242819ddd
3,341
cpp
C++
src/model.cpp
JeanCharlesNeboit/OpenGL
cf0365cb3c38a5f8cb9831607382e04d7112a642
[ "Apache-2.0" ]
null
null
null
src/model.cpp
JeanCharlesNeboit/OpenGL
cf0365cb3c38a5f8cb9831607382e04d7112a642
[ "Apache-2.0" ]
null
null
null
src/model.cpp
JeanCharlesNeboit/OpenGL
cf0365cb3c38a5f8cb9831607382e04d7112a642
[ "Apache-2.0" ]
null
null
null
#include "model.hpp" Model::Model(std::string path) { loadModel(path); } void Model::loadModel(std::string path) { Assimp::Importer importer; const aiScene *scene = importer.ReadFile(path, aiProcess_Triangulate | aiProcess_FlipUVs); if(!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) { std::cout << "ERROR:ASSIMP: " << importer.GetErrorString() << std::endl; return; } directory = path.substr(0, path.find_last_of('/')); processNode(scene->mRootNode, scene); } void Model::processNode(aiNode* node, const aiScene* scene) { for(unsigned int i = 0; i < node->mNumMeshes; ++i) { aiMesh *mesh = scene->mMeshes[node->mMeshes[i]]; meshes.push_back(processMesh(mesh, scene)); } for(unsigned int i = 0; i < node->mNumChildren; ++i) { processNode(node->mChildren[i], scene); } } Mesh Model::processMesh(aiMesh* mesh, const aiScene* scene) { std::vector<Vertex> vertices; std::vector<unsigned int> indices; std::vector<Texture> textures; for(unsigned int i = 0; i < mesh->mNumVertices; ++i) { Vertex vertex; glm::vec3 vector; vector.x = mesh->mVertices[i].x; vector.y = mesh->mVertices[i].y; vector.z = mesh->mVertices[i].z; vertex.position = vector; vector.x = mesh->mNormals[i].x; vector.y = mesh->mNormals[i].y; vector.z = mesh->mNormals[i].z; vertex.normal = vector; if(mesh->mTextureCoords[0]) { glm::vec2 vec; vec.x = mesh->mTextureCoords[0][i].x; vec.y = mesh->mTextureCoords[0][i].y; vertex.textureCoordinates = vec; } else { vertex.textureCoordinates = glm::vec2(0.0f, 0.0f); } vertices.push_back(vertex); } for(unsigned int i = 0; i < mesh->mNumFaces; ++i) { aiFace face = mesh->mFaces[i]; for(unsigned int j = 0; j < face.mNumIndices; j++) { indices.push_back(face.mIndices[j]); } } if(mesh->mMaterialIndex > 0) { aiMaterial *material = scene->mMaterials[mesh->mMaterialIndex]; std::vector<Texture> diffuseMaps = loadMaterialTextures(material, aiTextureType_DIFFUSE, Texture::Type::diffuse); textures.insert(textures.end(), diffuseMaps.begin(), diffuseMaps.end()); std::vector<Texture> specularMaps = loadMaterialTextures(material, aiTextureType_SPECULAR, Texture::Type::specular); textures.insert(textures.end(), specularMaps.begin(), specularMaps.end()); } return Mesh(vertices, indices, textures); } std::vector<Texture> Model::loadMaterialTextures(aiMaterial* material, aiTextureType aiType, Texture::Type type) { std::vector<Texture> textures; for(unsigned int i = 0; i < material->GetTextureCount(aiType); ++i) { aiString str; material->GetTexture(aiType, i, &str); bool skip = false; for(unsigned int j = 0; j < texturesLoaded.size(); ++j) { if(std::strcmp(texturesLoaded[j].path.data(), str.C_Str()) == 0) { textures.push_back(texturesLoaded[j]); skip = true; break; } } if(!skip) { Texture texture; texture.id = Texture::TextureFromFile(str.C_Str(), directory); texture.type = type; texture.path = str.C_Str(); textures.push_back(texture); texturesLoaded.push_back(texture); } } return textures; } void Model::draw(Shader shader) { for(auto mesh : meshes) { mesh.draw(shader); } }
29.830357
120
0.650703
[ "mesh", "vector", "model" ]
ee9776768608864befdefdf96fde32d5cca6bd35
2,796
cpp
C++
sdk/core/azure-core/test/ut/request_id_policy_test.cpp
RickWinter/azure-sdk-for-cpp
b4fe751310f53669a941e00aa93072f2d10a4eba
[ "MIT" ]
96
2020-03-19T07:49:39.000Z
2022-03-20T14:22:41.000Z
sdk/core/azure-core/test/ut/request_id_policy_test.cpp
RickWinter/azure-sdk-for-cpp
b4fe751310f53669a941e00aa93072f2d10a4eba
[ "MIT" ]
2,572
2020-03-18T22:54:53.000Z
2022-03-31T22:09:59.000Z
sdk/core/azure-core/test/ut/request_id_policy_test.cpp
RickWinter/azure-sdk-for-cpp
b4fe751310f53669a941e00aa93072f2d10a4eba
[ "MIT" ]
81
2020-03-19T09:42:00.000Z
2022-03-24T05:11:05.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // SPDX-License-Identifier: MIT #include <azure/core/http/policies/policy.hpp> #include <azure/core/internal/http/pipeline.hpp> #include <gtest/gtest.h> using namespace Azure::Core; using namespace Azure::Core::Http; using namespace Azure::Core::Http::Policies; using namespace Azure::Core::Http::Policies::_internal; namespace { class NoOpPolicy final : public HttpPolicy { public: std::unique_ptr<HttpPolicy> Clone() const override { return std::make_unique<NoOpPolicy>(*this); } std::unique_ptr<RawResponse> Send(Request&, NextHttpPolicy, Azure::Core::Context const&) const override { return nullptr; } }; constexpr char const* RequestIdHeaderName = "x-ms-client-request-id"; } // namespace TEST(RequestIdPolicy, Basic) { Request request(HttpMethod::Get, Url("https://www.microsoft.com")); { std::vector<std::unique_ptr<Azure::Core::Http::Policies::HttpPolicy>> policies; policies.emplace_back(std::make_unique<RequestIdPolicy>()); policies.emplace_back(std::make_unique<NoOpPolicy>()); Azure::Core::Http::_internal::HttpPipeline(policies).Send(request, Azure::Core::Context()); } auto const headers = request.GetHeaders(); auto const requestIdHeader = headers.find(RequestIdHeaderName); EXPECT_NE(requestIdHeader, headers.end()); EXPECT_EQ(requestIdHeader->second.length(), 36); } TEST(RequestIdPolicy, Unique) { std::string guid1; std::string guid2; { Request request(HttpMethod::Get, Url("https://www.microsoft.com")); { std::vector<std::unique_ptr<Azure::Core::Http::Policies::HttpPolicy>> policies; policies.emplace_back(std::make_unique<RequestIdPolicy>()); policies.emplace_back(std::make_unique<NoOpPolicy>()); Azure::Core::Http::_internal::HttpPipeline(policies).Send(request, Azure::Core::Context()); } auto const headers = request.GetHeaders(); auto const requestIdHeader = headers.find(RequestIdHeaderName); EXPECT_NE(requestIdHeader, headers.end()); guid1 = requestIdHeader->second; EXPECT_EQ(guid1.length(), 36); } { Request request(HttpMethod::Get, Url("https://www.microsoft.com")); { std::vector<std::unique_ptr<Azure::Core::Http::Policies::HttpPolicy>> policies; policies.emplace_back(std::make_unique<RequestIdPolicy>()); policies.emplace_back(std::make_unique<NoOpPolicy>()); Azure::Core::Http::_internal::HttpPipeline(policies).Send(request, Azure::Core::Context()); } auto const headers = request.GetHeaders(); auto const requestIdHeader = headers.find(RequestIdHeaderName); EXPECT_NE(requestIdHeader, headers.end()); guid2 = requestIdHeader->second; EXPECT_EQ(guid2.length(), 36); } EXPECT_NE(guid1, guid2); }
29.431579
100
0.712446
[ "vector" ]
ee9d1ee281ed3c0e0b5ae7dca6f4766e9c4e63ec
4,010
cc
C++
libs/render/src/render/compiledlines.cc
madeso/euphoria
59b72d148a90ae7a19e197e91216d4d42f194fd5
[ "MIT" ]
24
2015-07-27T14:32:18.000Z
2021-11-15T12:11:31.000Z
libs/render/src/render/compiledlines.cc
madeso/euphoria
59b72d148a90ae7a19e197e91216d4d42f194fd5
[ "MIT" ]
27
2021-07-09T21:18:40.000Z
2021-07-14T13:39:56.000Z
libs/render/src/render/compiledlines.cc
madeso/euphoria
59b72d148a90ae7a19e197e91216d4d42f194fd5
[ "MIT" ]
null
null
null
#include "render/compiledlines.h" #include <numeric> #include "core/lines.h" #include "core/cint.h" #include "render/shaderattribute3d.h" #include "render/attributebinder.h" #include "render/materialshader.h" #include "render/materialshadercache.h" namespace euphoria::render { void convert_lines_to_index_buffer ( const std::vector<core::Lines::FromToIndices>& lines, IndexBuffer* buffer ) { std::vector<unsigned int> data; data.reserve(lines.size() * 2); for(const auto& line: lines) { const auto [from, to] = line; data.emplace_back(from); data.emplace_back(to); } buffer->set_data(data); } void convert_points_to_vertex_buffer ( const std::vector<core::LinePoint>& points, const std::vector<ShaderAttribute>& attributes, VertexBuffer* vb ) { constexpr auto add_float3 = [](std::vector<float>* dst, const core::Vec3f& src) { dst->emplace_back(src.x); dst->emplace_back(src.y); dst->emplace_back(src.z); }; std::vector<float> data; const auto total_attributes = std::accumulate ( attributes.begin(), attributes.end(), 0, [](int count, const ShaderAttribute& att) -> int { return count + att.get_element_count(); } ); data.reserve(total_attributes * points.size()); for(const auto& point: points) { for(const auto& att: attributes) { switch(att.source) { case ShaderAttributeSource::vertex: ASSERT(att.type == ShaderAttributeType::float3); add_float3(&data, point.point); break; case ShaderAttributeSource::color: ASSERT(att.type == ShaderAttributeType::float3); add_float3 ( &data, core::Vec3f { point.color.r, point.color.g, point.color.b } ); break; default: DIE("Unhandled case"); } } } vb->set_data(data); } void CompiledLines::render ( const core::Mat4f& model_matrix, const core::Mat4f& projection_matrix, const core::Mat4f& view_matrix ) { shader->use_shader(); // set common constants shader->set_model(model_matrix); shader->set_projection(projection_matrix); shader->set_view(view_matrix); PointLayout::bind(&config); IndexBuffer::bind(&lines); lines.draw(RenderMode::lines, line_count); IndexBuffer::bind(nullptr); PointLayout::bind(nullptr); } std::shared_ptr<CompiledLines> compile(MaterialShaderCache* shader_cache, const core::Lines& lines) { std::shared_ptr<CompiledLines> ret {new CompiledLines {}}; ret->shader = shader_cache->get(core::vfs::FilePath{"~/default_line_shader"}); PointLayout::bind(&ret->config); VertexBuffer::bind(&ret->data); IndexBuffer::bind(&ret->lines); const auto attributes = std::vector<ShaderAttribute> { attributes3d::vertex(), attributes3d::color() }; convert_points_to_vertex_buffer(lines.points, attributes, &ret->data); bind_attributes(attributes, &ret->config); convert_lines_to_index_buffer(lines.indices, &ret->lines); ret->line_count = core::c_sizet_to_int(lines.indices.size()); IndexBuffer::bind(nullptr); VertexBuffer::bind(nullptr); PointLayout::bind(nullptr); return ret; } }
27.847222
87
0.534913
[ "render", "vector" ]
ee9d447a7c2970abe1f03eeb5caf6c40101be7bb
1,329
cpp
C++
rede_neural/main.cpp
NicolasCaous/ArduinoDrop
5aada476bddb208046e65add2e1393315492c1f8
[ "MIT" ]
null
null
null
rede_neural/main.cpp
NicolasCaous/ArduinoDrop
5aada476bddb208046e65add2e1393315492c1f8
[ "MIT" ]
null
null
null
rede_neural/main.cpp
NicolasCaous/ArduinoDrop
5aada476bddb208046e65add2e1393315492c1f8
[ "MIT" ]
null
null
null
#include "Net.h" int main() { srand (time(NULL)); std::vector<unsigned> topology; topology.push_back(2); topology.push_back(4); topology.push_back(1); Net myNet(topology); std::vector<double> inputVals; std::vector<double> targetVals; std::vector<double> resultVals; for(int i=0; i<1750; i++) { inputVals.clear(); targetVals.clear(); int r1 = rand(); int r2 = rand(); if(r1%2 && r2%2) { targetVals.push_back(1.0); } else { targetVals.push_back(0.0); } std::cout << "Teste: " << i + 1 << " R1: " << r1%2 * 1.0 << " R2: " << r2%2 * 1.0 << std::endl; std::cout << "Target: " << targetVals.back() << std::endl; inputVals.push_back(r1%2 * 1.0); inputVals.push_back(r2%2 * 1.0); myNet.feedForward(inputVals); myNet.backProp(targetVals); myNet.getResults(resultVals); if(resultVals[0] > 0.5) { resultVals[0] = 1; } else { resultVals[0] = 0; } std::cout << "Resposta: " << resultVals[0] << std::endl; std::cout << "Margem de erro: " << myNet.m_recentAverageError << std::endl; std::cout << std::endl; } return 0; }
24.611111
104
0.489842
[ "vector" ]
eea4c42221d778ace7567837a0755a9e76339449
1,389
cpp
C++
ARLogViewer/src/main.cpp
karstensensensen/AsciiRender
1eb61e655d679cc5833c96d96fab3ccf9672f91f
[ "MIT" ]
2
2021-07-24T14:42:15.000Z
2021-07-24T14:43:08.000Z
ARLogViewer/src/main.cpp
karstensensensen/AsciiRender
1eb61e655d679cc5833c96d96fab3ccf9672f91f
[ "MIT" ]
null
null
null
ARLogViewer/src/main.cpp
karstensensensen/AsciiRender
1eb61e655d679cc5833c96d96fab3ccf9672f91f
[ "MIT" ]
null
null
null
#include <Asciir.h> #include "LogViewer.h" class LogTerm : public Asciir::AREngine { public: Asciir::LogViewer logviewer; std::string m_log_dir; LogTerm(const std::string& log_dir) :logviewer(log_dir, { Asciir::WHITE8, // Info color White (Default terminal color) Asciir::IGREEN8, // Notify color Green Asciir::YELLOW8, // Warning color Yellow Asciir::IYELLOW8, // Critical color Orange Asciir::IRED8 // Error color Red }), m_log_dir(log_dir) {} ~LogTerm() { logviewer.close(); } void start() { Asciir::AREngine::getEngine()->getTerminal().getRenderer().setTitle(m_log_dir); Asciir::AREngine::getEngine()->getTerminal().getRenderer().update(); while (true) { if (std::filesystem::exists(m_log_dir)) { logviewer.open(); break; } } while (true) { if (logviewer.hasLogs()) logviewer.logLineOut(std::cout); else if (logviewer.pos() > logviewer.size()) { logviewer.reset(std::cout); std::cout << "\x1b[2J\x1b[H"; } } } }; Asciir::AREngine* Asciir::createEngine(std::vector<std::string> args) { std::string log_dir = AR_CORE_LOG_DIR; if (args.size() > 2) { std::cout << "Cannot take more than one commandline argument!\n"; throw std::runtime_error("Cannot take more than one commandline argument!\n"); } else if (args.size() == 2) { log_dir = args[1]; } return new LogTerm(log_dir); }
20.426471
81
0.655868
[ "vector" ]
eea70f3334f7c497b0b516d62f2198668344df39
8,349
hpp
C++
3rdParty/iresearch/core/formats/sparse_bitmap.hpp
usalko/arapy
204038e9a8301b16a6ec31e10a3289ca0c7ada91
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
3rdParty/iresearch/core/formats/sparse_bitmap.hpp
usalko/arapy
204038e9a8301b16a6ec31e10a3289ca0c7ada91
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
3rdParty/iresearch/core/formats/sparse_bitmap.hpp
usalko/arapy
204038e9a8301b16a6ec31e10a3289ca0c7ada91
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2021 ArangoDB GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Andrey Abramov //////////////////////////////////////////////////////////////////////////////// #ifndef IRESEARCH_SPARSE_BITMAP_H #define IRESEARCH_SPARSE_BITMAP_H #include "shared.hpp" #include "analysis/token_attributes.hpp" #include "search/cost.hpp" #include "search/score.hpp" #include "index/iterators.hpp" #include "utils/bit_utils.hpp" #include "utils/bitset.hpp" #include "utils/frozen_attributes.hpp" #include "utils/math_utils.hpp" #include "utils/range.hpp" #include "utils/type_limits.hpp" namespace iresearch { //////////////////////////////////////////////////////////////////////////////// /// @class sparse_bitmap_writer /// @note /// union { /// doc_id_t doc; /// struct { /// uint16_t block; /// uint16_t block_offset /// } /// }; //////////////////////////////////////////////////////////////////////////////// class sparse_bitmap_writer { public: using value_type = doc_id_t; // for compatibility with back_inserter static constexpr uint32_t kBlockSize = 1 << 16; static constexpr uint32_t kNumBlocks = kBlockSize / bits_required<size_t>(); static_assert(math::is_power2(kBlockSize)); struct block { doc_id_t index; uint32_t offset; }; explicit sparse_bitmap_writer(index_output& out) noexcept(noexcept(out.file_pointer())) : out_{&out}, origin_{out.file_pointer()} { } void push_back(doc_id_t value) { static_assert(math::is_power2(kBlockSize)); assert(doc_limits::valid(value)); assert(!doc_limits::eof(value)); const uint32_t block = value / kBlockSize; if (block != block_) { flush(block_); block_ = block; } set(value % kBlockSize); } bool erase(doc_id_t value) noexcept { if ((value / kBlockSize) < block_) { // value is already flushed return false; } reset(value % kBlockSize); return true; } void finish(); const std::vector<block>& index() const noexcept { return block_index_; } private: void flush(uint32_t next_block) { const uint32_t popcnt = static_cast<uint32_t>( math::math_traits<size_t>::pop(std::begin(bits_), std::end(bits_))); if (popcnt) { add_block(next_block); do_flush(popcnt); popcnt_ += popcnt; std::memset(bits_, 0, sizeof bits_); } } FORCE_INLINE void set(doc_id_t value) noexcept { assert(value < kBlockSize); irs::set_bit(bits_[value / bits_required<size_t>()], value % bits_required<size_t>()); } FORCE_INLINE void reset(doc_id_t value) noexcept { assert(value < kBlockSize); irs::unset_bit(bits_[value / bits_required<size_t>()], value % bits_required<size_t>()); } FORCE_INLINE void add_block(uint32_t block_id) { const uint64_t offset = out_->file_pointer() - origin_; assert(offset <= std::numeric_limits<uint32_t>::max()); uint32_t count = 1 + block_id - static_cast<uint32_t>(block_index_.size()); while (count) { block_index_.emplace_back(block{popcnt_, static_cast<uint32_t>(offset)}); --count; } } void do_flush(uint32_t popcnt); index_output* out_; uint64_t origin_; size_t bits_[kNumBlocks]{}; std::vector<block> block_index_; uint32_t popcnt_{}; uint32_t block_{}; // last flushed block }; // sparse_bitmap_writer //////////////////////////////////////////////////////////////////////////////// /// @struct value_index /// @brief denotes a position of a value associated with a document //////////////////////////////////////////////////////////////////////////////// struct value_index : document { static constexpr string_ref type_name() noexcept { return "value_index"; } }; // value_index //////////////////////////////////////////////////////////////////////////////// /// @class sparse_bitmap_iterator //////////////////////////////////////////////////////////////////////////////// class sparse_bitmap_iterator final : public resettable_doc_iterator { public: using block_index_t = range<const sparse_bitmap_writer::block>; struct options { //////////////////////////////////////////////////////////////////////////// /// @brief blocks index //////////////////////////////////////////////////////////////////////////// block_index_t blocks; //////////////////////////////////////////////////////////////////////////// /// @brief use per block index //////////////////////////////////////////////////////////////////////////// bool use_block_index{true}; }; // options explicit sparse_bitmap_iterator(index_input::ptr&& in, const options& opts) : sparse_bitmap_iterator{memory::to_managed<index_input>(std::move(in)), opts} { } explicit sparse_bitmap_iterator(index_input* in, const options& opts) : sparse_bitmap_iterator{memory::to_managed<index_input, false>(in), opts} { } template<typename Cost> sparse_bitmap_iterator(index_input::ptr&& in, const options& opts, Cost&& est) : sparse_bitmap_iterator{std::move(in), opts} { std::get<cost>(attrs_).reset(std::forward<Cost>(est)); } template<typename Cost> sparse_bitmap_iterator(index_input* in, const options& opts, Cost&& est) : sparse_bitmap_iterator{in, opts} { std::get<cost>(attrs_).reset(std::forward<Cost>(est)); } virtual attribute* get_mutable(irs::type_info::type_id type) noexcept override final { return irs::get_mutable(attrs_, type); } virtual doc_id_t seek(doc_id_t target) override final; virtual bool next() override final { return !doc_limits::eof(seek(value() + 1)); } virtual doc_id_t value() const noexcept override final { return std::get<document>(attrs_).value; } virtual void reset() override final; ////////////////////////////////////////////////////////////////////////////// /// @note the value is undefined for /// doc_limits::invalid() and doc_limits::eof() ////////////////////////////////////////////////////////////////////////////// doc_id_t index() const noexcept { return std::get<value_index>(attrs_).value; } private: using block_seek_f = bool(*)(sparse_bitmap_iterator*, doc_id_t); template<uint32_t> friend struct container_iterator; static bool initial_seek(sparse_bitmap_iterator* self, doc_id_t target); struct container_iterator_context { union { // We can also have an inverse sparse container (where we // most of values are 0). In this case only zeros can be // stored as an array. struct { const uint16_t* u16data; } sparse; struct { const size_t* u64data; doc_id_t popcnt; int32_t word_idx; uint32_t index_base; size_t word; union { const uint16_t* u16data; const byte_type* u8data; } index; } dense; struct { const void* ignore; doc_id_t missing; } all; const byte_type* u8data; }; }; explicit sparse_bitmap_iterator( memory::managed_ptr<index_input>&& in, const options& opts); void seek_to_block(doc_id_t block); void read_block_header(); container_iterator_context ctx_; std::tuple<document, value_index, cost, score> attrs_; memory::managed_ptr<index_input> in_; std::unique_ptr<byte_type[]> block_index_data_; block_seek_f seek_func_; block_index_t block_index_; uint64_t cont_begin_; uint64_t origin_; doc_id_t index_{}; doc_id_t index_max_{}; doc_id_t block_{}; bool use_block_index_; }; // sparse_bitmap_iterator } // iresearch #endif // IRESEARCH_SPARSE_BITMAP_H
29.501767
89
0.593724
[ "vector" ]
eea829e5825b599ff6b2429d12f3568d6673e292
24,145
cc
C++
.generated/gen/parser/parser-spec.cc
blutmond/danach
0cd3b27f03d2d2cf563f90a14628b8bf5bb36283
[ "Apache-2.0" ]
null
null
null
.generated/gen/parser/parser-spec.cc
blutmond/danach
0cd3b27f03d2d2cf563f90a14628b8bf5bb36283
[ "Apache-2.0" ]
null
null
null
.generated/gen/parser/parser-spec.cc
blutmond/danach
0cd3b27f03d2d2cf563f90a14628b8bf5bb36283
[ "Apache-2.0" ]
null
null
null
#include "parser/parser-support.h" #include "parser/ast-context.h" namespace production_spec { namespace tok { enum T {arrow, close_arr, close_brace, close_paran, colon, coloncolon, comma, dot, eof, equal, identifier, number, open_arr, open_brace, open_paran, percent, pipe, plus, semi, star, str}; const char* StringifyType(T t) { switch(t) { case arrow: return "arrow";case close_arr: return "close_arr";case close_brace: return "close_brace";case close_paran: return "close_paran";case colon: return "colon";case coloncolon: return "coloncolon";case comma: return "comma";case dot: return "dot";case eof: return "eof";case equal: return "equal";case identifier: return "identifier";case number: return "number";case open_arr: return "open_arr";case open_brace: return "open_brace";case open_paran: return "open_paran";case percent: return "percent";case pipe: return "pipe";case plus: return "plus";case semi: return "semi";case star: return "star";case str: return "str";} } struct Token { T type = tok::eof; string_view str; }; Token MakeToken(T t, const char* st, const char* ed) { return Token{t, string_view(st, ed - st)}; } void PrintToken(Token t) { std::cout << "tok::" << StringifyType(t.type) << " : \"" << t.str << "\"\n"; } void unexpected(char c) { fprintf(stderr, "unexpected: \"%c\"\n", c); exit(-1); } Token GetNext(const char*& cur) { const char* st; int c; start: st = cur; c = *cur; goto bb0; bb0: if (c ==0) { goto bb1; } if (c ==10) { ++cur; c = *cur; goto bb2; } if (c ==' ') { ++cur; c = *cur; goto bb3; } if (c =='"') { ++cur; c = *cur; goto bb4; } if (c =='%') { ++cur; c = *cur; goto bb5; } if (c =='(') { ++cur; c = *cur; goto bb6; } if (c ==')') { ++cur; c = *cur; goto bb7; } if (c =='*') { ++cur; c = *cur; goto bb8; } if (c =='+') { ++cur; c = *cur; goto bb9; } if (c ==',') { ++cur; c = *cur; goto bb10; } if (c =='-') { ++cur; c = *cur; goto bb11; } if (c =='.') { ++cur; c = *cur; goto bb12; } if (c >= '0' && c <= '9') { ++cur; c = *cur; goto bb13; } if (c ==':') { ++cur; c = *cur; goto bb14; } if (c ==';') { ++cur; c = *cur; goto bb15; } if (c =='<') { ++cur; c = *cur; goto bb16; } if (c =='=') { ++cur; c = *cur; goto bb17; } if (c =='>') { ++cur; c = *cur; goto bb18; } if (c >= 'A' && c <= 'Z') { ++cur; c = *cur; goto bb19; } if (c =='_') { ++cur; c = *cur; goto bb19; } if (c >= 'a' && c <= 'z') { ++cur; c = *cur; goto bb19; } if (c =='{') { ++cur; c = *cur; goto bb20; } if (c =='|') { ++cur; c = *cur; goto bb21; } if (c =='}') { ++cur; c = *cur; goto bb22; } unexpected(c); bb22: return MakeToken(tok::close_brace, st, cur); bb21: return MakeToken(tok::pipe, st, cur); bb20: return MakeToken(tok::open_brace, st, cur); bb19: if (c >= '0' && c <= '9') { ++cur; c = *cur; goto bb19; } if (c >= 'A' && c <= 'Z') { ++cur; c = *cur; goto bb19; } if (c =='_') { ++cur; c = *cur; goto bb19; } if (c >= 'a' && c <= 'z') { ++cur; c = *cur; goto bb19; } return MakeToken(tok::identifier, st, cur); bb18: return MakeToken(tok::close_arr, st, cur); bb17: return MakeToken(tok::equal, st, cur); bb16: return MakeToken(tok::open_arr, st, cur); bb15: return MakeToken(tok::semi, st, cur); bb14: if (c ==':') { ++cur; c = *cur; goto bb23; } return MakeToken(tok::colon, st, cur); bb23: return MakeToken(tok::coloncolon, st, cur); bb13: if (c >= '0' && c <= '9') { ++cur; c = *cur; goto bb13; } return MakeToken(tok::number, st, cur); bb12: return MakeToken(tok::dot, st, cur); bb11: if (c =='>') { ++cur; c = *cur; goto bb24; } unexpected(c); bb24: return MakeToken(tok::arrow, st, cur); bb10: return MakeToken(tok::comma, st, cur); bb9: return MakeToken(tok::plus, st, cur); bb8: return MakeToken(tok::star, st, cur); bb7: return MakeToken(tok::close_paran, st, cur); bb6: return MakeToken(tok::open_paran, st, cur); bb5: return MakeToken(tok::percent, st, cur); bb4: if (c >= ' ' && c <= '!') { ++cur; c = *cur; goto bb4; } if (c =='"') { ++cur; c = *cur; goto bb25; } if (c >= '#' && c <= '[') { ++cur; c = *cur; goto bb4; } if (c =='\\') { ++cur; c = *cur; goto bb26; } if (c >= ']' && c <= '~') { ++cur; c = *cur; goto bb4; } unexpected(c); bb26: if (c >= ' ' && c <= '~') { ++cur; c = *cur; goto bb4; } unexpected(c); bb25: return MakeToken(tok::str, st, cur); bb3: goto start; bb2: goto start; bb1: return MakeToken(tok::eof, st, cur); } } // namespace tok struct Tokenizer { explicit Tokenizer(ASTContext& ctx, const char* cursor_inp) : ctx_(ctx), cursor(cursor_inp) { start = cursor; current = tok::GetNext(cursor); } tok::Token peak() { return current; } tok::Token next() { auto res = current; current = tok::GetNext(cursor); return res; } tok::Token expect(tok::T t) { auto res = next(); if (t != res.type) { auto pos = GetLineInfo(start, res.str.data()); fprintf(stderr, "error:%d:%d: expected: tok::%s but got:", pos.line, pos.col, tok::StringifyType(t)); std::cerr << "tok::" << StringifyType(res.type) << " : \"" << res.str << "\"\n"; exit(-1); } return res; } tok::Token expect(const char* c) { auto res = next(); if (c != res.str) { auto pos = GetLineInfo(start, res.str.data()); fprintf(stderr, "error:%d:%d: expected: \"%s\" but got:", pos.line, pos.col, c); std::cerr << "tok::" << StringifyType(res.type) << " : \"" << res.str << "\"\n"; exit(-1); } return res; } bool peak_check_str(const char* str) { return peak().str == str; } bool peak_check(tok::T type) { return peak().type == type; } void unexpected() __attribute__ ((__noreturn__)) { unexpected(peak()); } void unexpected(tok::Token tok) __attribute__ ((__noreturn__)) { auto pos = GetLineInfo(start, tok.str.data()); fprintf(stderr, "error:%d:%d: unexpected:", pos.line, pos.col); std::cerr << "tok::" << StringifyType(tok.type) << " : \"" << tok.str << "\"\n"; exit(-1); } template <typename T> T* New() { return ctx_.New<T>(); } private: ASTContext& ctx_; const char* start; const char* cursor; tok::Token current; }; } // namespace production_spec namespace production_spec{ struct PatternStmt; struct CompoundPatternStmt; struct StringPatternStmt; struct AssignPatternStmt; struct PushPatternStmt; struct MergePatternStmt; struct ExprTailLoopPatternStmt; struct ConditionalPatternStmt; struct WrapPatternStmt; struct Decl; struct TypeDecl; struct ExprDecl; struct ProductionAndTypeDecl; struct ProductionDecl; struct PatternDecl; struct LeftAssocDecl; struct RightAssocDecl; struct DefineWithTypeDecl; struct DefineDecl; struct EntryDecl; struct TokenizerDecl; struct Module; struct PatternExpr; struct CommaConcatPatternExpr; struct ConcatPatternExpr; struct SelfPatternExpr; struct NewPatternExpr; struct PopPatternExpr; struct NamedPatternExpr; struct TypeLetDecl; struct TypeDeclExpr; struct ProductTypeDeclExpr; struct SumTypeDeclExpr; struct NamedTypeDeclExpr; struct ColonTypeDeclExpr; struct ParametricTypeDeclExpr; struct PatternStmt { enum class Kind { Compound, String, Assign, Push, Merge, ExprTailLoop, Conditional, Wrap, }; PatternStmt(Kind kind) : kind_(kind) {} Kind getKind() { return kind_; } private: Kind kind_; }; struct CompoundPatternStmt: public PatternStmt { CompoundPatternStmt() : PatternStmt(Kind::Compound) {} std::vector<PatternStmt*> items; }; struct StringPatternStmt: public PatternStmt { StringPatternStmt() : PatternStmt(Kind::String) {} tok::Token value; }; struct AssignPatternStmt: public PatternStmt { AssignPatternStmt() : PatternStmt(Kind::Assign) {} tok::Token name; PatternExpr* value; }; struct PushPatternStmt: public PatternStmt { PushPatternStmt() : PatternStmt(Kind::Push) {} PatternExpr* value; }; struct MergePatternStmt: public PatternStmt { MergePatternStmt() : PatternStmt(Kind::Merge) {} std::vector<PatternStmt*> items; }; struct ExprTailLoopPatternStmt: public PatternStmt { ExprTailLoopPatternStmt() : PatternStmt(Kind::ExprTailLoop) {} PatternExpr* base; TypeDeclExpr* type; PatternStmt* value; }; struct ConditionalPatternStmt: public PatternStmt { ConditionalPatternStmt() : PatternStmt(Kind::Conditional) {} PatternStmt* value; }; struct WrapPatternStmt: public PatternStmt { WrapPatternStmt() : PatternStmt(Kind::Wrap) {} PatternExpr* value; }; struct Decl { enum class Kind { Type, Expr, ProductionAndType, Production, Pattern, LeftAssoc, RightAssoc, DefineWithType, Define, Entry, Tokenizer, }; Decl(Kind kind) : kind_(kind) {} Kind getKind() { return kind_; } private: Kind kind_; }; struct TypeDecl: public Decl { TypeDecl() : Decl(Kind::Type) {} tok::Token name; TypeDeclExpr* type; }; struct ExprDecl: public Decl { ExprDecl() : Decl(Kind::Expr) {} tok::Token name; std::vector<Decl*> stmts; }; struct ProductionAndTypeDecl: public Decl { ProductionAndTypeDecl() : Decl(Kind::ProductionAndType) {} tok::Token name; TypeDeclExpr* type; std::vector<Decl*> stmts; }; struct ProductionDecl: public Decl { ProductionDecl() : Decl(Kind::Production) {} tok::Token name; std::vector<Decl*> stmts; }; struct PatternDecl: public Decl { PatternDecl() : Decl(Kind::Pattern) {} tok::Token name; PatternStmt* value; }; struct LeftAssocDecl: public Decl { LeftAssocDecl() : Decl(Kind::LeftAssoc) {} std::vector<Decl*> stmts; }; struct RightAssocDecl: public Decl { RightAssocDecl() : Decl(Kind::RightAssoc) {} std::vector<Decl*> stmts; }; struct DefineWithTypeDecl: public Decl { DefineWithTypeDecl() : Decl(Kind::DefineWithType) {} tok::Token name; TypeDeclExpr* type; PatternStmt* value; }; struct DefineDecl: public Decl { DefineDecl() : Decl(Kind::Define) {} tok::Token name; PatternStmt* value; }; struct EntryDecl: public Decl { EntryDecl() : Decl(Kind::Entry) {} tok::Token name; }; struct TokenizerDecl: public Decl { TokenizerDecl() : Decl(Kind::Tokenizer) {} tok::Token name; }; struct Module { tok::Token mod_name; std::vector<Decl*> decls; }; struct PatternExpr { enum class Kind { CommaConcat, Concat, Self, New, Pop, Named, }; PatternExpr(Kind kind) : kind_(kind) {} Kind getKind() { return kind_; } private: Kind kind_; }; struct CommaConcatPatternExpr: public PatternExpr { CommaConcatPatternExpr() : PatternExpr(Kind::CommaConcat) {} tok::Token comma; PatternStmt* element; }; struct ConcatPatternExpr: public PatternExpr { ConcatPatternExpr() : PatternExpr(Kind::Concat) {} PatternStmt* element; }; struct SelfPatternExpr: public PatternExpr { SelfPatternExpr() : PatternExpr(Kind::Self) {} }; struct NewPatternExpr: public PatternExpr { NewPatternExpr() : PatternExpr(Kind::New) {} TypeDeclExpr* type; PatternStmt* value; }; struct PopPatternExpr: public PatternExpr { PopPatternExpr() : PatternExpr(Kind::Pop) {} }; struct NamedPatternExpr: public PatternExpr { NamedPatternExpr() : PatternExpr(Kind::Named) {} tok::Token name; }; struct TypeLetDecl { tok::Token name; TypeDeclExpr* type; }; struct TypeDeclExpr { enum class Kind { Product, Sum, Named, Colon, Parametric, }; TypeDeclExpr(Kind kind) : kind_(kind) {} Kind getKind() { return kind_; } private: Kind kind_; }; struct ProductTypeDeclExpr: public TypeDeclExpr { ProductTypeDeclExpr() : TypeDeclExpr(Kind::Product) {} std::vector<TypeLetDecl*> decls; }; struct SumTypeDeclExpr: public TypeDeclExpr { SumTypeDeclExpr() : TypeDeclExpr(Kind::Sum) {} std::vector<TypeLetDecl*> decls; }; struct NamedTypeDeclExpr: public TypeDeclExpr { NamedTypeDeclExpr() : TypeDeclExpr(Kind::Named) {} tok::Token name; }; struct ColonTypeDeclExpr: public TypeDeclExpr { ColonTypeDeclExpr() : TypeDeclExpr(Kind::Colon) {} TypeDeclExpr* base; tok::Token name; }; struct ParametricTypeDeclExpr: public TypeDeclExpr { ParametricTypeDeclExpr() : TypeDeclExpr(Kind::Parametric) {} TypeDeclExpr* base; std::vector<TypeDeclExpr*> params; }; } // namespace production_spec namespace production_spec{ namespace parser { Module* DoParse(Tokenizer& tokens); TypeDeclExpr* _production_TypeDeclExpr_group_0(Tokenizer& tokens); TypeDeclExpr* _production_TypeDeclExpr_group_1(Tokenizer& tokens); TypeDeclExpr* _production_TypeDeclExpr(Tokenizer& tokens); PatternExpr* _production_PatternExpr(Tokenizer& tokens); PatternStmt* _production_CompoundPatternStmt(Tokenizer& tokens); PatternStmt* _production_PatternStmt(Tokenizer& tokens); std::vector<Decl*> _production_DeclList(Tokenizer& tokens); Decl* _production_Decl(Tokenizer& tokens); Module* _production_Module(Tokenizer& tokens); Module* DoParse(Tokenizer& tokens) { return _production_Module(tokens); } TypeDeclExpr* _production_TypeDeclExpr_group_0(Tokenizer& tokens) { if (tokens.peak_check_str("(")) { tokens.expect("("); auto result = ({ auto __current_self = tokens.New<ProductTypeDeclExpr>();__current_self->decls = ([&]{ std::vector<TypeLetDecl*> __current_vector__; if (!tokens.peak_check_str(")")) { while (true) { __current_vector__.push_back([&]{auto result = ({ auto __current_self = tokens.New<TypeLetDecl>();__current_self->name = tokens.expect(tok::identifier); tokens.expect(":"); __current_self->type = _production_TypeDeclExpr(tokens); __current_self; }); return result; }()); if (tokens.peak_check(tok::comma)) { tokens.expect(tok::comma); } else { break; } }}return __current_vector__; }()) ; tokens.expect(")"); __current_self; }); return result; } if (tokens.peak_check_str("{")) { tokens.expect("{"); auto result = ({ auto __current_self = tokens.New<SumTypeDeclExpr>();__current_self->decls = ([&]{ std::vector<TypeLetDecl*> __current_vector__; while (true) { if (tokens.peak_check_str("}")) { break; } __current_vector__.push_back([&]{auto result = ({ auto __current_self = tokens.New<TypeLetDecl>();__current_self->name = tokens.expect(tok::identifier); tokens.expect("="); __current_self->type = _production_TypeDeclExpr(tokens); tokens.expect(";"); __current_self; }); return result; }()); } return __current_vector__; }()) ; tokens.expect("}"); __current_self; }); return result; } if (tokens.peak_check(tok::identifier)) { auto _tmp_0 = tokens.expect(tok::identifier); auto result = ({ auto __current_self = tokens.New<NamedTypeDeclExpr>();__current_self->name = _tmp_0; __current_self; }); return result; } tokens.unexpected(); } TypeDeclExpr* _production_TypeDeclExpr_group_1(Tokenizer& tokens) { TypeDeclExpr* expr_result = _production_TypeDeclExpr_group_0(tokens); while (true) { auto _tmp_0 = expr_result;if (tokens.peak_check_str("::")) { tokens.expect("::"); auto result = ({ auto __current_self = tokens.New<ColonTypeDeclExpr>();__current_self->base = _tmp_0; __current_self->name = tokens.expect(tok::identifier); __current_self; }); expr_result = result; continue; } if (tokens.peak_check_str("<")) { tokens.expect("<"); auto result = ({ auto __current_self = tokens.New<ParametricTypeDeclExpr>();__current_self->base = _tmp_0; __current_self->params = ([&]{ std::vector<TypeDeclExpr*> __current_vector__; while (true) { if (tokens.peak_check_str(">")) { break; } __current_vector__.push_back([&]{auto result = _production_TypeDeclExpr(tokens); return result; }()); } return __current_vector__; }()) ; tokens.expect(">"); __current_self; }); expr_result = result; continue; } return expr_result; } tokens.unexpected(); } TypeDeclExpr* _production_TypeDeclExpr(Tokenizer& tokens) { auto result = _production_TypeDeclExpr_group_1(tokens); return result; } PatternExpr* _production_PatternExpr(Tokenizer& tokens) { if (tokens.peak_check_str("comma_array")) { tokens.expect("comma_array"); auto result = ({ auto __current_self = tokens.New<CommaConcatPatternExpr>();tokens.expect("("); __current_self->comma = tokens.expect(tok::identifier); tokens.expect(")"); __current_self->element = _production_CompoundPatternStmt(tokens); __current_self; }); return result; } if (tokens.peak_check_str("concat")) { tokens.expect("concat"); auto result = ({ auto __current_self = tokens.New<ConcatPatternExpr>();__current_self->element = _production_CompoundPatternStmt(tokens); __current_self; }); return result; } if (tokens.peak_check_str("_")) { tokens.expect("_"); auto result = ({ auto __current_self = tokens.New<SelfPatternExpr>();__current_self; }); return result; } if (tokens.peak_check_str("new")) { tokens.expect("new"); auto result = ({ auto __current_self = tokens.New<NewPatternExpr>();__current_self->type = _production_TypeDeclExpr(tokens); __current_self->value = _production_CompoundPatternStmt(tokens); __current_self; }); return result; } if (tokens.peak_check_str("pop")) { tokens.expect("pop"); auto result = ({ auto __current_self = tokens.New<PopPatternExpr>();__current_self; }); return result; } if (tokens.peak_check(tok::identifier)) { auto _tmp_0 = tokens.expect(tok::identifier); auto result = ({ auto __current_self = tokens.New<NamedPatternExpr>();__current_self->name = _tmp_0; __current_self; }); return result; } tokens.unexpected(); } PatternStmt* _production_CompoundPatternStmt(Tokenizer& tokens) { if (tokens.peak_check_str("{")) { tokens.expect("{"); auto result = ({ auto __current_self = tokens.New<CompoundPatternStmt>();__current_self->items = ([&]{ std::vector<PatternStmt*> __current_vector__; while (true) { if (tokens.peak_check_str("}")) { break; } __current_vector__.push_back([&]{auto result = _production_PatternStmt(tokens); return result; }()); } return __current_vector__; }()) ; tokens.expect("}"); __current_self; }); return result; } tokens.unexpected(); } PatternStmt* _production_PatternStmt(Tokenizer& tokens) { if (tokens.peak_check(tok::str)) { auto _tmp_0 = tokens.expect(tok::str); auto result = ({ auto __current_self = tokens.New<StringPatternStmt>();__current_self->value = _tmp_0; __current_self; }); return result; } if (tokens.peak_check_str("%")) { tokens.expect("%"); auto result = ({ auto __current_self = tokens.New<AssignPatternStmt>();__current_self->name = tokens.expect(tok::identifier); tokens.expect("="); __current_self->value = _production_PatternExpr(tokens); __current_self; }); return result; } if (tokens.peak_check_str("push")) { tokens.expect("push"); auto result = ({ auto __current_self = tokens.New<PushPatternStmt>();__current_self->value = _production_PatternExpr(tokens); __current_self; }); return result; } if (tokens.peak_check_str("merge")) { tokens.expect("merge"); auto result = ({ auto __current_self = tokens.New<MergePatternStmt>();tokens.expect("("); __current_self->items = ([&]{ std::vector<PatternStmt*> __current_vector__; if (!tokens.peak_check_str(")")) { while (true) { __current_vector__.push_back([&]{auto result = _production_PatternStmt(tokens); return result; }()); if (tokens.peak_check(tok::comma)) { tokens.expect(tok::comma); } else { break; } }}return __current_vector__; }()) ; tokens.expect(")"); __current_self; }); return result; } if (tokens.peak_check_str("expr_tail_loop")) { tokens.expect("expr_tail_loop"); auto result = ({ auto __current_self = tokens.New<ExprTailLoopPatternStmt>();tokens.expect("("); __current_self->base = _production_PatternExpr(tokens); tokens.expect(")"); tokens.expect(":"); __current_self->type = _production_TypeDeclExpr(tokens); __current_self->value = _production_CompoundPatternStmt(tokens); __current_self; }); return result; } if (tokens.peak_check_str("try")) { tokens.expect("try"); auto result = ({ auto __current_self = tokens.New<ConditionalPatternStmt>();__current_self->value = _production_CompoundPatternStmt(tokens); __current_self; }); return result; } auto _tmp_0 = _production_PatternExpr(tokens); auto result = ({ auto __current_self = tokens.New<WrapPatternStmt>();__current_self->value = _tmp_0; __current_self; }); return result; } std::vector<Decl*> _production_DeclList(Tokenizer& tokens) { tokens.expect("{"); auto result = ([&]{ std::vector<Decl*> __current_vector__; while (true) { if (tokens.peak_check_str("}")) { break; } __current_vector__.push_back([&]{auto result = _production_Decl(tokens); return result; }()); } return __current_vector__; }()) ; tokens.expect("}"); return result; } Decl* _production_Decl(Tokenizer& tokens) { if (tokens.peak_check_str("type")) { tokens.expect("type"); auto result = ({ auto __current_self = tokens.New<TypeDecl>();__current_self->name = tokens.expect(tok::identifier); tokens.expect("="); __current_self->type = _production_TypeDeclExpr(tokens); tokens.expect(";"); __current_self; }); return result; } if (tokens.peak_check_str("expr")) { tokens.expect("expr"); auto result = ({ auto __current_self = tokens.New<ExprDecl>();__current_self->name = tokens.expect(tok::identifier); __current_self->stmts = _production_DeclList(tokens); __current_self; }); return result; } if (tokens.peak_check_str("production")) { tokens.expect("production"); auto _tmp_0 = tokens.expect(tok::identifier); if (tokens.peak_check_str(":")) { tokens.expect(":"); auto result = ({ auto __current_self = tokens.New<ProductionAndTypeDecl>();__current_self->name = _tmp_0; __current_self->type = _production_TypeDeclExpr(tokens); __current_self->stmts = _production_DeclList(tokens); __current_self; }); return result; } auto _tmp_1 = _production_DeclList(tokens); auto result = ({ auto __current_self = tokens.New<ProductionDecl>();__current_self->name = _tmp_0; __current_self->stmts = _tmp_1; __current_self; }); return result; } if (tokens.peak_check_str("pattern")) { tokens.expect("pattern"); auto result = ({ auto __current_self = tokens.New<PatternDecl>();__current_self->name = tokens.expect(tok::identifier); __current_self->value = _production_CompoundPatternStmt(tokens); __current_self; }); return result; } if (tokens.peak_check_str("left")) { tokens.expect("left"); auto result = ({ auto __current_self = tokens.New<LeftAssocDecl>();__current_self->stmts = _production_DeclList(tokens); __current_self; }); return result; } if (tokens.peak_check_str("right")) { tokens.expect("right"); auto result = ({ auto __current_self = tokens.New<RightAssocDecl>();__current_self->stmts = _production_DeclList(tokens); __current_self; }); return result; } if (tokens.peak_check_str("define")) { tokens.expect("define"); auto _tmp_0 = tokens.expect(tok::identifier); if (tokens.peak_check_str(":")) { tokens.expect(":"); auto result = ({ auto __current_self = tokens.New<DefineWithTypeDecl>();__current_self->name = _tmp_0; __current_self->type = _production_TypeDeclExpr(tokens); __current_self->value = _production_CompoundPatternStmt(tokens); __current_self; }); return result; } auto _tmp_1 = _production_CompoundPatternStmt(tokens); auto result = ({ auto __current_self = tokens.New<DefineDecl>();__current_self->name = _tmp_0; __current_self->value = _tmp_1; __current_self; }); return result; } if (tokens.peak_check_str("entry")) { tokens.expect("entry"); auto result = ({ auto __current_self = tokens.New<EntryDecl>();__current_self->name = tokens.expect(tok::identifier); tokens.expect(";"); __current_self; }); return result; } if (tokens.peak_check_str("tokenizer")) { tokens.expect("tokenizer"); auto result = ({ auto __current_self = tokens.New<TokenizerDecl>();__current_self->name = tokens.expect(tok::identifier); tokens.expect(";"); __current_self; }); return result; } tokens.unexpected(); } Module* _production_Module(Tokenizer& tokens) { auto result = ({ auto __current_self = tokens.New<Module>();tokens.expect("module"); __current_self->mod_name = tokens.expect(tok::identifier); tokens.expect(";"); __current_self->decls = ([&]{ std::vector<Decl*> __current_vector__; while (true) { if (tokens.peak_check(tok::eof)) { break; } __current_vector__.push_back([&]{auto result = _production_Decl(tokens); return result; }()); } return __current_vector__; }()) ; __current_self; }); return result; } } // namespace parser } // namespace production_spec
25.151042
632
0.688797
[ "vector" ]
eeab9017ee82b5f7c07ce35032267a667bd9cf4e
955
hpp
C++
include/state_controller.hpp
GDC-WM/2DGame2021
cc36d6ea3709feeb295c82c498e2c19ca01ffd8b
[ "MIT" ]
1
2021-10-17T01:20:37.000Z
2021-10-17T01:20:37.000Z
include/state_controller.hpp
GDC-WM/2DGame2021
cc36d6ea3709feeb295c82c498e2c19ca01ffd8b
[ "MIT" ]
28
2021-10-07T05:07:00.000Z
2022-01-16T06:08:57.000Z
include/state_controller.hpp
GDC-WM/2DGame2021
cc36d6ea3709feeb295c82c498e2c19ca01ffd8b
[ "MIT" ]
2
2021-11-21T07:17:36.000Z
2021-11-22T01:39:28.000Z
#ifndef STATE_CONTROLLER_HPP #define STATE_CONTROLLER_HPP #include <SFML/Graphics.hpp> #include <memory> #include <stack> class State; /** * Manages states using a stack of states */ class StateController : public std::enable_shared_from_this<StateController> { public: StateController(); /** * @return The state stack */ std::stack<std::shared_ptr<State>> &states() { return _states; }; /** * @return The render window */ const sf::RenderWindow &window() { return _window; }; /** * @return whether the game is running */ const bool &running() { return _running; }; /** * Handles close event, delegate other events to the current state * Calls _state->update and _state->draw */ void update(); private: std::stack<std::shared_ptr<State>> _states; bool _running = true; sf::RenderWindow _window{sf::VideoMode(1280, 720, 32), "Best game", sf::Style::Titlebar | sf::Style::Close}; }; #endif
20.76087
78
0.671204
[ "render" ]
eeac65e8ae2d6c97b29518c236b7e5a1a3035e94
4,622
hh
C++
src/c++/include/variant/VariantReader.hh
nh13/hap.py
fd67904f7a68981e76c12301aa2add2718b30120
[ "BSL-1.0" ]
315
2015-07-21T13:53:30.000Z
2022-03-17T02:01:19.000Z
src/c++/include/variant/VariantReader.hh
nh13/hap.py
fd67904f7a68981e76c12301aa2add2718b30120
[ "BSL-1.0" ]
147
2015-11-26T03:06:24.000Z
2022-03-28T18:22:33.000Z
src/c++/include/variant/VariantReader.hh
nh13/hap.py
fd67904f7a68981e76c12301aa2add2718b30120
[ "BSL-1.0" ]
124
2015-07-21T13:55:14.000Z
2022-03-23T17:34:31.000Z
// -*- mode: c++; indent-tabs-mode: nil; -*- // // // Copyright (c) 2010-2015 Illumina, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /** * Reader for getting Variants from File * * \file VariantReader.hh * \author Peter Krusche * \email pkrusche@illumina.com * */ #pragma once #include "Variant.hh" #include <list> #include <string> namespace variant { /** * @brief read variants from a file * @details Wrapper for synced_bcf_reader */ struct VariantReaderImpl; class VariantReader { public: VariantReader(); VariantReader(VariantReader const &); ~VariantReader(); VariantReader const & operator=(VariantReader const &); /** * @brief Apply filters in the input VCF(s) * * Filters can be enabled / disabled globally (sample == -1) * or for each sample individually. * */ void setApplyFilters(bool filters=false, int sample = -1); bool getApplyFilters(int sample = -1) const; /** * @brief Return homref/no-calls * */ void setReturnHomref(bool homref=true); bool getReturnHomref() const; /** * @brief change GTs on chrX/Y to be diploid for matching * */ void setFixChrXGTs(bool fix=true); /** * @brief Validate reference alleles * */ void setValidateRef(const char * ref_fasta, bool validate=true); bool getValidateRef() const; /** * @brief Interface to htslib regions functionality * @param regions regions string, see synced_bcf_reader.h * @param isFile True if regions is a file * * Must be called before addSample! * */ void setRegions(const char * regions, bool isFile); /** * @brief Interface to htslib targets functionality * @param targets targets string, see synced_bcf_reader.h * @param isFile True if targets is a file * * Must be called before addSample! * */ void setTargets(const char * targets, bool isFile); /** * @brief Add a sample to read from * @param filename file name * @param sname name of sample to read from (or "" to use first sample in file / use "*" to add all samples in a file) * @return sample number to retrieve records in the calls vector in current() */ int addSample(const char * filename, const char * sname); /** return a list of filename/sample pairs */ void getSampleList(std::list< std::pair<std::string, std::string> > & files); /** * @brief Rewind / set region to read * * @param chr chromosome/contig name * @param startpos start position on chr (or -1 for entire chr) */ void rewind(const char * chr=NULL, int64_t startpos=-1); /** * @brief Return next variant and advance * * @param v Variant record to populate */ Variants & current(); /** * @brief Advance one position * @return true if a variant was retrieved, false otherwise */ bool advance(); /** * @brief Insert a Variants record into the stream * @details The next record returned will be this one * * @param s Variants to put on top of stack * @param back enqueue at back or front of buffer */ void enqueue(Variants const & v, bool back=false); private: friend class VariantWriter; VariantReaderImpl * _impl; }; }
29.253165
123
0.67222
[ "vector" ]
eeacd8b099f667d1abbe7a223aded1294ade30b0
20,625
cc
C++
tuplex/io/src/S3File.cc
rahulyesantharao/tuplex
03733a57ccb5a3770eecaf1c3adcfb520ed82138
[ "Apache-2.0" ]
null
null
null
tuplex/io/src/S3File.cc
rahulyesantharao/tuplex
03733a57ccb5a3770eecaf1c3adcfb520ed82138
[ "Apache-2.0" ]
null
null
null
tuplex/io/src/S3File.cc
rahulyesantharao/tuplex
03733a57ccb5a3770eecaf1c3adcfb520ed82138
[ "Apache-2.0" ]
null
null
null
//--------------------------------------------------------------------------------------------------------------------// // // // Tuplex: Blazing Fast Python Data Science // // // // // // (c) 2017 - 2021, Tuplex team // // Created by Leonhard Spiegelberg first on 1/1/2021 // // License: Apache 2.0 // //--------------------------------------------------------------------------------------------------------------------// #ifdef BUILD_WITH_AWS #include <S3File.h> #include <aws/s3/model/GetObjectRequest.h> #include <aws/s3/model/PutObjectRequest.h> #include <boost/interprocess/streams/bufferstream.hpp> #include <stdexcept> #include <aws/s3/model/CreateMultipartUploadRequest.h> #include <aws/s3/model/CompleteMultipartUploadRequest.h> #include <aws/s3/model/UploadPartRequest.h> #include <StringUtils.h> #include <Timer.h> // @TODO: use global allocator! // ==> make customizable // from https://github.com/TileDB-Inc/TileDB/blob/dev/tiledb/sm/filesystem/s3.cc /** * Return the exception name and error message from the given outcome object. * * @tparam R AWS result type * @tparam E AWS error type * @param outcome Outcome to retrieve error message from * @return Error message string */ template <typename R, typename E> std::string outcome_error_message(const Aws::Utils::Outcome<R, E>& outcome) { return std::string("\nException: ") + outcome.GetError().GetExceptionName().c_str() + std::string("\nError message: ") + outcome.GetError().GetMessage().c_str(); } namespace tuplex { void S3File::init() { _buffer = nullptr; _bufferPosition = 0; _bufferLength = 0; _fileSize = 0; _filePosition = 0; _partNumber = 0; // set to 0 // S3 files can only operate on read xor write mode if(_mode & VirtualFileMode::VFS_WRITE && _mode & VirtualFileMode::VFS_READ) throw std::runtime_error("S3 files can't be read/write at the same time"); _fileUploaded = false; #ifndef NDEBUG //debug: _requestTime = 0.0; #endif } bool S3File::is_open() const { return false; } void S3File::lazyUpload() { assert(_mode & VirtualFileMode::VFS_WRITE || _mode & VirtualFileMode::VFS_OVERWRITE); // check if buffer is valid, if so upload via PutRequest if(_buffer && !_fileUploaded) { // check if multipart upload (_partNumber != 0) if(_partNumber > 0) { // upload last part uploadPart(); // finish multipart upload completeMultiPartUpload(); } else { // simple put request // upload via simple putrequest Aws::S3::Model::PutObjectRequest put_req; put_req.SetBucket(_uri.s3Bucket().c_str()); put_req.SetKey(_uri.s3Key().c_str()); put_req.SetContentLength(_bufferLength); put_req.SetRequestPayer(_requestPayer); auto content_type = _uri.s3GetMIMEType(); if(!content_type.empty()) { put_req.SetContentType(content_type.c_str()); } // body auto stream = std::shared_ptr<Aws::IOStream>(new boost::interprocess::bufferstream((char*)_buffer, _bufferLength)); put_req.SetBody(stream); // perform upload request auto outcome = _s3fs.client().PutObject(put_req); _s3fs._putRequests++; if(!outcome.IsSuccess()) { MessageHandler& logger = Logger::instance().logger("s3fs"); logger.error(outcome_error_message(outcome)); throw std::runtime_error(outcome_error_message(outcome)); } _s3fs._bytesTransferred += _bufferLength; } _fileUploaded = true; } } VirtualFileSystemStatus S3File::close() { // in write mode? if(_mode & VirtualFileMode::VFS_WRITE || _mode & VirtualFileMode::VFS_OVERWRITE) lazyUpload(); return VirtualFileSystemStatus::VFS_OK; } void S3File::initMultiPartUpload() { MessageHandler& logger = Logger::instance().logger("s3fs"); Aws::S3::Model::CreateMultipartUploadRequest req; req.SetBucket(_uri.s3Bucket().c_str()); req.SetKey(_uri.s3Key().c_str()); req.SetRequestPayer(_requestPayer); auto content_type = _uri.s3GetMIMEType(); if(!content_type.empty()) { req.SetContentType(content_type.c_str()); } auto outcome = _s3fs.client().CreateMultipartUpload(req); _s3fs._multiPartPutRequests++; // count as put request if(!outcome.IsSuccess()) { logger.error(outcome_error_message(outcome)); throw std::runtime_error(outcome_error_message(outcome)); } _uploadID = outcome.GetResult().GetUploadId(); // use this to find out the abort date, issue warning if it is more than 3 days in the future! // outcome.GetResult().GetAbortDate() auto abort_date = outcome.GetResult().GetAbortDate(); auto now_data = Aws::Utils::DateTime::Now(); auto time_diff = Aws::Utils::DateTime::Diff(abort_date, now_data); std::chrono::hours warningThreshold{24 * 3}; // warn after 3 days if(time_diff > std::chrono::duration_cast<std::chrono::milliseconds>(warningThreshold)) { logger.warn(std::string("multipart upload requests will expire earliest on ") + abort_date.ToLocalTimeString(Aws::Utils::DateFormat::ISO_8601).c_str()); } _partNumber = 1; // set part number to 1 (first allowed AWS value) } void S3File::uploadPart() { MessageHandler& logger = Logger::instance().logger("s3fs"); assert(_partNumber > 0); // if this is zero, need to all init before! assert(_buffer); // skip empty buffer for second time if(_bufferLength == 0 && _partNumber > 1) return; Aws::S3::Model::UploadPartRequest req; //@Todo: what about content MD5??? req.SetBucket(_uri.s3Bucket().c_str()); req.SetKey(_uri.s3Key().c_str()); req.SetUploadId(_uploadID); req.SetPartNumber(_partNumber); req.SetContentLength(_bufferLength); req.SetRequestPayer(_requestPayer); auto stream = std::shared_ptr<Aws::IOStream>(new boost::interprocess::bufferstream((char*)_buffer, _bufferLength)); req.SetBody(stream); auto outcome = _s3fs.client().UploadPart(req); _s3fs._multiPartPutRequests++; _s3fs._bytesTransferred += _bufferLength; if(!outcome.IsSuccess()) { logger.error(outcome_error_message(outcome)); throw std::runtime_error(outcome_error_message(outcome)); } // record upload Aws::S3::Model::CompletedPart completed_part; completed_part.SetETag(outcome.GetResult().GetETag()); completed_part.SetPartNumber(_partNumber); _parts.emplace_back(completed_part); // reset buffer _bufferPosition = 0; _bufferLength = 0; _partNumber++; } void S3File::completeMultiPartUpload() { // use this here to list open multipart upload requests //aws s3api list-multipart-uploads --bucket <bucket name> MessageHandler& logger = Logger::instance().logger("s3fs"); // issue complete upload request Aws::S3::Model::CompleteMultipartUploadRequest req; req.SetBucket(_uri.s3Bucket().c_str()); req.SetKey(_uri.s3Key().c_str()); req.SetUploadId(_uploadID); req.SetRequestPayer(_requestPayer); Aws::S3::Model::CompletedMultipartUpload upld; for(auto part : _parts) upld.AddParts(part); req.SetMultipartUpload(std::move(upld)); auto outcome = _s3fs.client().CompleteMultipartUpload(req); _s3fs._closeMultiPartUploadRequests++; if(!outcome.IsSuccess()) { logger.error(outcome_error_message(outcome)); throw std::runtime_error(outcome_error_message(outcome)); } } VirtualFileSystemStatus S3File::write(const void *buffer, uint64_t bufferSize) { // make sure file is not yet uploaded if(_fileUploaded) { throw std::runtime_error("file has been already uploaded. Did you call write after close?"); } // two options: either buffer is empty OR full if(!_buffer) { // allocate new buffer with size & fill up with data _buffer = new uint8_t[_bufferSize]; memcpy(_buffer, buffer, bufferSize); _bufferLength += bufferSize; _bufferPosition += bufferSize; } else { // two cases: there is enough space left in buffer or buffer might run full if(_bufferSize - _bufferLength >= bufferSize) { memcpy(_buffer + _bufferPosition, buffer, bufferSize); _bufferPosition += bufferSize; _bufferLength += bufferSize; } else { // need to do multipart upload! // check if multipart was already initiated if(0 == _partNumber) { // init multipart upload and upload first part initMultiPartUpload(); // check if limit of 10,000 was reached. If so, abort! uploadPart(); } else { // append another multipart upload part uploadPart(); } } return VirtualFileSystemStatus::VFS_NOTYETIMPLEMENTED; } return VirtualFileSystemStatus::VFS_OK; } // fast tiny read VirtualFileSystemStatus S3File::readOnly(void *buffer, uint64_t nbytes, size_t *bytesRead) const { // short cut for empty read if(nbytes == 0) { if(bytesRead) *bytesRead = 0; return VirtualFileSystemStatus::VFS_OK; } // simply issue here one direct request size_t retrievedBytes = 0; // range header std::string range = "bytes=" + std::to_string(_filePosition) + "-" + std::to_string(_filePosition + nbytes - 1); // make AWS S3 part request to uri // check how to retrieve object in poarts Aws::S3::Model::GetObjectRequest req; req.SetBucket(_uri.s3Bucket().c_str()); req.SetKey(_uri.s3Key().c_str()); // retrieve byte range according to http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35 req.SetRange(range.c_str()); req.SetRequestPayer(_requestPayer); // Get the object ==> Note: this s3 client is damn slow, need to make it faster in the future... auto get_object_outcome = _s3fs.client().GetObject(req); _s3fs._getRequests++; if (get_object_outcome.IsSuccess()) { auto result = get_object_outcome.GetResultWithOwnership(); // extract extracted byte range + size // syntax is: start-inclend/fsize auto cr = result.GetContentRange(); auto idxSlash = cr.find_first_of('/'); auto idxMinus = cr.find_first_of('-'); // these are kind of weird, they are already requested range I presume size_t fileSize = std::strtoull(cr.substr(idxSlash + 1).c_str(), nullptr, 10); retrievedBytes = result.GetContentLength(); // Get an Aws::IOStream reference to the retrieved file auto &retrieved_file = result.GetBody(); // copy contents retrieved_file.read((char*)buffer, retrievedBytes); // note: for ascii files there might be an issue regarding the file ending!!! _s3fs._bytesReceived += retrievedBytes; } else { MessageHandler& logger = Logger::instance().logger("s3fs"); logger.error(outcome_error_message(get_object_outcome)); throw std::runtime_error(outcome_error_message(get_object_outcome)); } if(bytesRead) *bytesRead = retrievedBytes; return VirtualFileSystemStatus::VFS_OK; } VirtualFileSystemStatus S3File::read(void *buffer, uint64_t nbytes, size_t* outBytesRead) const { assert(buffer); // empty buffer? => fill! if(!_buffer) const_cast<S3File*>(this)->fillBuffer(_bufferSize); // try to request full buffer // check how many bytes are available in buffer assert(_bufferPosition <= _bufferLength); size_t bytesAvailable = _bufferLength - _bufferPosition; size_t bytesRead = 0; assert(_buffer); uint8_t* dest = (uint8_t*)buffer; // Todo: better condition is I think filePos < fileSize int64_t capacity = nbytes; // how many bytes can be written to buffer safely // bring capacity to 0 while(capacity > 0) { // there are more bytesAvailable than requested (capacity) => consume capacity if(capacity <= bytesAvailable) { memcpy(dest, _buffer + _bufferPosition, capacity); bytesRead += capacity; const_cast<S3File*>(this)->_bufferPosition += capacity; capacity = 0; } else { // there are less bytesAvailable than the capacity still to fill, // fill whatever is there & decrease capacity to fill by it memcpy(dest, _buffer + _bufferPosition, bytesAvailable); bytesRead += bytesAvailable; // move how many bytes were read dest += bytesAvailable; // move position where to copy things capacity -= bytesAvailable; // decrease capacity const_cast<S3File*>(this)->_bufferPosition += bytesAvailable; // move buffer to end (necessary to avoid infinity loop) // now there are two options: 1) file already exhausted, no need to refill // 2) still data left, refill buffer if(_filePosition >= _fileSize) // exhausted, leave loop break; // fill buffer up again // reset buffer pos & length (i.e. invalidate buffer) const_cast<S3File*>(this)->_bufferPosition = 0; const_cast<S3File*>(this)->_bufferLength = 0; const_cast<S3File*>(this)->fillBuffer(_bufferSize); // try to request full buffer bytesAvailable = _bufferLength - _bufferPosition; assert(bytesAvailable > 0); } assert(capacity >= 0); } // output if desired if(outBytesRead) *outBytesRead = bytesRead; return VirtualFileSystemStatus::VFS_OK; } size_t S3File::fillBuffer(size_t bytesToRequest) { bytesToRequest = std::min(_bufferSize - _bufferPosition, bytesToRequest); size_t retrievedBytes = 0; if(0 == bytesToRequest) return 0; // create buffer if not existing if(!_buffer) { _buffer = new uint8_t[_bufferSize]; _bufferPosition = 0; _bufferLength = 0; _fileSize = 0; } else { // shortcut: if eof reached, then do not perform request if(_filePosition >= _fileSize) return 0; } // range header std::string range = "bytes=" + std::to_string(_filePosition) + "-" + std::to_string(_filePosition + bytesToRequest - 1); // make AWS S3 part request to uri // check how to retrieve object in poarts Aws::S3::Model::GetObjectRequest req; req.SetBucket(_uri.s3Bucket().c_str()); req.SetKey(_uri.s3Key().c_str()); // retrieve byte range according to http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35 req.SetRange(range.c_str()); req.SetRequestPayer(_requestPayer); Timer timer; // Get the object // std::cout<<">> S3 read request..."; std::cout.flush(); auto get_object_outcome = _s3fs.client().GetObject(req); // std::cout<<" done!"<<std::endl; _s3fs._getRequests++; #ifndef NDEBUG _requestTime += timer.time(); #endif if (get_object_outcome.IsSuccess()) { auto result = get_object_outcome.GetResultWithOwnership(); // extract extracted byte range + size // syntax is: start-inclend/fsize auto cr = result.GetContentRange(); auto idxSlash = cr.find_first_of('/'); auto idxMinus = cr.find_first_of('-'); // these are kind of weird, they are already requested range I presume // size_t rangeStart = std::strtoull(cr.substr(0, idxMinus).c_str(), nullptr, 10); // size_t rangeEnd = std::strtoull(cr.substr(idxMinus + 1, idxSlash).c_str(), nullptr, 10); size_t fileSize = std::strtoull(cr.substr(idxSlash + 1).c_str(), nullptr, 10); retrievedBytes = result.GetContentLength(); _fileSize = fileSize; // Get an Aws::IOStream reference to the retrieved file auto &retrieved_file = result.GetBody(); // copy contents & move cursors assert(_bufferPosition + retrievedBytes <= _bufferSize); retrieved_file.read((char*)(_buffer + _bufferPosition), retrievedBytes); _bufferLength += retrievedBytes; _filePosition += retrievedBytes; // in bounds check assert(_bufferPosition + _bufferLength <= _bufferSize); // note: for ascii files there might be an issue regarding the file ending!!! _s3fs._bytesReceived += retrievedBytes; } else { MessageHandler& logger = Logger::instance().logger("s3fs"); logger.error(outcome_error_message(get_object_outcome)); throw std::runtime_error(outcome_error_message(get_object_outcome)); } return retrievedBytes; } size_t S3File::size() const { // check if buffer empty, if so fill initially if(!_buffer) // hack: use lazy buffer for requests const_cast<S3File*>(this)->fillBuffer(_bufferSize); // try to request full buffer // after the first time fillBuffer was called, fileSize is populated return _fileSize; } S3File::~S3File() { close(); if(_buffer) delete [] _buffer; _buffer = nullptr; // // print // std::cout<<"request Time on "<<_uri.toPath()<<": "<<_requestTime<<"s "<<std::endl; } bool S3File::eof() const { // note that buffer must be initialized, even for empty files! // when is end of file reached? // buffer is filled, filePos == fileSize and _bufferPosistion reached buffer Length return _buffer && _filePosition == _fileSize && _bufferLength == _bufferPosition; } VirtualFileSystemStatus S3File::seek(int64_t delta) { // check if buffer is valid if(_buffer) { } else { if(_fileSize == 0) { // buffer is not active yet & fileSize neither. => best effort jump on filePosition int64_t relativePos = ((int64_t)_filePosition) + delta; if(relativePos < 0) relativePos = 0; _filePosition = relativePos; } else { // try to move buffer posisition int64_t newPos = std::min((int64_t)_fileSize, std::max((int64_t)_filePosition + delta, (int64_t)0l)); EXCEPTION("nyimpl"); } } return VirtualFileSystemStatus::VFS_OK; } } #endif
38.915094
134
0.570861
[ "object", "model" ]
eeaea1a275c06e640ea7f02313e0a72c68f18c90
1,668
cpp
C++
source/lmi0_oracle.cpp
luk036/lmi-solver-cpp
e747d76740046af29e3b0746df4f9b829d24283c
[ "Unlicense" ]
null
null
null
source/lmi0_oracle.cpp
luk036/lmi-solver-cpp
e747d76740046af29e3b0746df4f9b829d24283c
[ "Unlicense" ]
null
null
null
source/lmi0_oracle.cpp
luk036/lmi-solver-cpp
e747d76740046af29e3b0746df4f9b829d24283c
[ "Unlicense" ]
null
null
null
#include <stddef.h> // for size_t #include <gsl/span> // for span, span<>::element_type #include <lmisolver/lmi0_oracle.hpp> // for lmi0_oracle::Arr, lmi0_oracle... #include <optional> // for optional #include <tuple> // for tuple #include <type_traits> // for move #include <xtensor/xarray.hpp> // for xarray_container #include <xtensor/xcontainer.hpp> // for xcontainer #include <xtensor/xlayout.hpp> // for layout_type, layout_type::row... #include <xtensor/xtensor_forward.hpp> // for xarray #include "lmisolver/ldlt_ext.hpp" // for ldlt_ext // #include <xtensor-blas/xlinalg.hpp> /** * @brief Construct a new lmi0 oracle object * * @param[in] F */ template <typename Arr036> lmi0_oracle<Arr036>::lmi0_oracle(gsl::span<const Arr036> F) : _F{F}, _n{F[0].shape()[0]}, _Q(_n) {} /** * @brief * * @param[in] x * @return auto */ template <typename Arr036> auto lmi0_oracle<Arr036>::operator()(const Arr036& x) -> std::optional<typename lmi0_oracle<Arr036>::Cut> { auto n = x.size(); auto getA = [&, this](size_t i, size_t j) -> double { auto a = 0.; for (auto k = 0U; k != n; ++k) { a += this->_F[k](i, j) * x(k); } return a; }; if (this->_Q.factor(getA)) { return {}; } auto ep = this->_Q.witness(); auto g = Arr036{xt::zeros<double>({n})}; for (auto i = 0U; i != n; ++i) { g(i) = -_Q.sym_quad(this->_F[i]); } return {{std::move(g), ep}}; } using Arr = xt::xarray<double, xt::layout_type::row_major>; template class lmi0_oracle<Arr>;
30.888889
86
0.569544
[ "object", "shape" ]
eeb4a1249a014ca99aca327f6ce9f28783eb39af
32,034
hpp
C++
library_examples/MCEuropeanEngine/include/xf_fintech/rng.hpp
vishnuchebrolu/Vitis_Accel_Examples
0f573c014efb0e385f4a7d9306821a111ebf2b74
[ "BSD-3-Clause" ]
1
2021-11-17T10:52:01.000Z
2021-11-17T10:52:01.000Z
library_examples/MCEuropeanEngine/include/xf_fintech/rng.hpp
chipet/Vitis_Accel_Examples
f72dff9eea45a76e9ee0713774589624e2b52c9f
[ "BSD-3-Clause" ]
null
null
null
library_examples/MCEuropeanEngine/include/xf_fintech/rng.hpp
chipet/Vitis_Accel_Examples
f72dff9eea45a76e9ee0713774589624e2b52c9f
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright 2019 Xilinx, Inc. * * 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. */ /** * @file rng.hpp * @brief This files includes normal random number generator and uniform random * number generator * */ #ifndef XF_FINTECH_PRNG_HPP #define XF_FINTECH_PRNG_HPP #include "ap_fixed.h" #include "ap_int.h" #include "hls_math.h" #include "utils.hpp" namespace xf { namespace fintech { namespace internal { // This version of cumulative normal distribution function assume its output // range is within [2^(-32), 1 - 2^(-32)]; // It's a specified version works with MT19937 since its output uniform // distributed value is [2^(-32), 1 - 2^(-32)]; template <typename mType> mType CumulativeNormal(mType input) { const mType a[9] = {2.2352520354606839287, 161.02823106855587881, 1067.6894854603709582, 18154.981253343561249, 0.065682337918207449113, 0, 0, 0, 0}; const mType b[8] = { 47.20258190468824187, 976.09855173777669322, 10260.932208618978205, 45507.789335026729956, 0, 0, 0, 0}; const mType c[9] = {0.39894151208813466764, 8.8831497943883759412, 93.506656132177855979, 597.27027639480026226, 2494.5375852903726711, 6848.1904505362823326, 11602.651437647350124, 9842.7148383839780218, 1.0765576773720192317e-8}; const mType d[8] = {22.266688044328115691, 235.38790178262499861, 1519.377599407554805, 6485.558298266760755, 18615.571640885098091, 34900.952721145977266, 38912.003286093271411, 19685.429676859990727}; #pragma HLS array_partition variable = a dim = 1 complete #pragma HLS array_partition variable = b dim = 1 complete #pragma HLS array_partition variable = c dim = 1 complete #pragma HLS array_partition variable = d dim = 1 complete const mType boundary = 0.67448975; const mType eps = 1.11022302462515655e-16; mType x, xsq, xnum, xden, temp, del, x_poly; if (input > 0) { x = input; } else { x = -input; } bool within_boundary = x < boundary; mType para_num[9]; mType para_den[8]; #pragma HLS array_partition variable = para_num dim = 1 complete #pragma HLS array_partition variable = para_den dim = 1 complete for (int i = 0; i < 9; i++) { if (within_boundary) { para_num[i] = a[i]; } else { para_num[i] = c[i]; } } for (int i = 0; i < 8; i++) { if (within_boundary) { para_den[i] = b[i]; } else { para_den[i] = d[i]; } } mType x_num_add[8]; mType x_num_mul[8]; mType x_den_add[8]; mType x_den_mul[8]; #pragma HLS array_partition variable = x_num_add dim = 1 complete #pragma HLS array_partition variable = x_num_mul dim = 1 complete #pragma HLS array_partition variable = x_den_add dim = 1 complete #pragma HLS array_partition variable = x_den_mul dim = 1 complete #ifdef DPRAGMA #pragma HLS resource variable = xsq core = DMul_meddsp #else #pragma HLS resource variable = xsq core = FMul_fulldsp #endif xsq = x * x; mType para_num_tmp; if (within_boundary) { para_num_tmp = para_num[4]; x_poly = xsq; } else { para_num_tmp = para_num[8]; x_poly = x; } mType tmp_x_num_mul_0; #ifdef DPRAGMA #pragma HLS resource variable = tmp_x_num_mul_0 core = DMul_meddsp #else #pragma HLS resource variable = tmp_x_num_mul_0 core = FMul_fulldsp #endif tmp_x_num_mul_0 = para_num_tmp * x_poly; x_num_mul[0] = tmp_x_num_mul_0; x_den_mul[0] = x_poly; for (int i = 1; i <= 7; i++) { mType local_x_num_add, local_x_num_mul, local_x_den_add, local_x_den_mul; #ifdef DPRAGMA #pragma HLS resource variable = local_x_num_add core = DAddSub_nodsp #else #pragma HLS resource variable = local_x_num_add core = FAddSub_nodsp #endif local_x_num_add = x_num_mul[i - 1] + para_num[i - 1]; x_num_add[i] = local_x_num_add; #ifdef DPRAGMA #pragma HLS resource variable = local_x_num_mul core = DMul_meddsp #else #pragma HLS resource variable = local_x_num_mul core = FMul_fulldsp #endif local_x_num_mul = x_num_add[i] * x_poly; x_num_mul[i] = local_x_num_mul; #ifdef DPRAGMA #pragma HLS resource variable = local_x_den_add core = DAddSub_nodsp #else #pragma HLS resource variable = local_x_den_add core = FAddSub_nodsp #endif local_x_den_add = x_den_mul[i - 1] + para_den[i - 1]; x_den_add[i] = local_x_den_add; #ifdef DPRAGMA #pragma HLS resource variable = local_x_den_mul core = DMul_meddsp #else #pragma HLS resource variable = local_x_den_mul core = FMul_fulldsp #endif local_x_den_mul = x_den_add[i] * x_poly; x_den_mul[i] = local_x_den_mul; } if (x < eps) { x_num_mul[3] = 0; x_den_mul[3] = 0; } mType add_para_num_tmp, add_para_den_tmp; mType add_x_num_tmp, add_x_den_tmp; if (within_boundary) { add_x_num_tmp = x_num_mul[3]; add_x_den_tmp = x_den_mul[3]; add_para_num_tmp = para_num[3]; add_para_den_tmp = para_den[3]; } else { add_x_num_tmp = x_num_mul[7]; add_x_den_tmp = x_den_mul[7]; add_para_num_tmp = para_num[7]; add_para_den_tmp = para_den[7]; } #ifdef DPRAGMA #pragma HLS resource variable = xnum core = DAddSub_nodsp #else #pragma HLS resource variable = xnum core = FAddSub_nodsp #endif xnum = add_x_num_tmp + add_para_num_tmp; #ifdef DPRAGMA #pragma HLS resource variable = xden core = DAddSub_nodsp #else #pragma HLS resource variable = xden core = FAddSub_nodsp #endif xden = add_x_den_tmp + add_para_den_tmp; temp = xnum / xden; mType tmp_temp_mul; if (within_boundary) { tmp_temp_mul = x; } else { tmp_temp_mul = FPExp(-xsq / 2); } #ifdef DPRAGMA #pragma HLS resource variable = temp core = DMul_meddsp #else #pragma HLS resource variable = temp core = FMul_fulldsp #endif temp *= tmp_temp_mul; mType result, res_1, res_2; if (within_boundary) { res_1 = 0.5; if (input > 0) { res_2 = temp; } else { res_2 = -temp; } } else { if (input > 0) { res_1 = 1; res_2 = -temp; } else { res_1 = 0; res_2 = temp; } } #ifdef DPRAGMA #pragma HLS resource variable = result core = DAddSub_nodsp #else #pragma HLS resource variable = result core = FAddSub_nodsp #endif result = res_1 + res_2; return result; } } // namespace internal /** * @brief Inverse Cumulative transform from random number to normal random number. * * Reference: Algorithm AS 241, The Percentage Points of the Normal Distribution * by Michael J. Wichura. * * @tparam mType data type. * @param input random number input. * @return normal random number. */ template <typename mType> mType inverseCumulativeNormalPPND7(mType input) { const mType a0 = 3.3871327179e+00; const mType a1 = 5.0434271938e+01; const mType a2 = 1.5929113202e+02; const mType a3 = 5.9109374720e+01; const mType b1 = 1.7895169469e+01; const mType b2 = 7.8757757664e+01; const mType b3 = 6.7187563600e+01; const mType c0 = 1.4234372777e+00; const mType c1 = 2.7568153900e+00; const mType c2 = 1.3067284816e+00; const mType c3 = 1.7023821103e-01; const mType d1 = 7.3700164250e-01; const mType d2 = 1.2021132975e-01; const mType e0 = 6.6579051150e+00; const mType e1 = 3.0812263860e+00; const mType e2 = 4.2868294337e-01; const mType e3 = 1.7337203997e-02; const mType f1 = 2.4197894225e-01; const mType f2 = 1.2258202635e-02; const mType x_low = 0.075e+00; const mType x_high = 0.925e+00; const mType split = 5.0e+00; const mType const1 = 0.180625e+00; const mType const2 = 1.6e+00; const mType half = 0.5e+00; const mType zero = 0; const mType one = 1; mType tmp, z, r, standard_value; mType p0, p1, p2, p3, q1, q2, q3, frac_a, frac_b; mType fa1, fa2, fa3, fa4, fa5, fa6, fa7; mType fb1, fb2, fb3, fb4, fb5, fb6; ap_uint<1> is_center, is_lower_tail, is_less_than_split; if (input < x_low || input > x_high) { is_center = 0; if (input < x_low) { z = input; is_lower_tail = 1; } else { z = internal::FPTwoSub(one, input); is_lower_tail = 0; } tmp = hls::sqrt(-hls::log(z)); if (tmp < split) { is_less_than_split = 1; r = internal::FPTwoSub(tmp, const2); p0 = c0; p1 = c1; p2 = c2; p3 = c3; q1 = one; q2 = d1; q3 = d2; } else { is_less_than_split = 0; r = internal::FPTwoSub(tmp, split); p0 = e0; p1 = e1; p2 = e2; p3 = e3; q1 = one; q2 = f1; q3 = f2; } } else { is_center = 1; p0 = a0; p1 = a1; p2 = a2; p3 = a3; q1 = b1; q2 = b2; q3 = b3; z = internal::FPTwoSub(input, half); mType z_sq = internal::FPTwoMul(z, z); r = internal::FPTwoSub(const1, z_sq); } fa1 = p3 * r; #pragma HLS resource variable = fa2 core = FAddSub_nodsp fa2 = fa1 + p2; fa3 = fa2 * r; #pragma HLS resource variable = fa4 core = FAddSub_nodsp fa4 = fa3 + p1; fa5 = fa4 * r; #pragma HLS resource variable = fa6 core = FAddSub_nodsp fa6 = fa5 + p0; fb1 = q3 * r; #pragma HLS resource variable = fb2 core = FAddSub_nodsp fb2 = fb1 + q2; fb3 = fb2 * r; #pragma HLS resource variable = fb4 core = FAddSub_nodsp fb4 = fb3 + q1; if (is_center) { fa7 = fa6 * z; fb5 = fb4 * r; #pragma HLS resource variable = fb6 core = FAddSub_nodsp fb6 = fb5 + one; } else { fa7 = fa6; fb6 = fb4; } frac_a = fa7; frac_b = fb6; standard_value = frac_a / frac_b; if ((!is_center) && (is_lower_tail)) { standard_value = -standard_value; } return standard_value; } /** * @brief Inverse CumulativeNormal using Acklam's approximation to transform * uniform random number to normal random number. * * Reference: Acklam's approximation: by Peter J. Acklam, University of Oslo, * Statistics Division. * * @tparam mType data type. * @param input input uniform random number * @return normal random number */ template <typename mType> mType inverseCumulativeNormalAcklam(mType input) { const mType a1 = -3.969683028665376e+01; const mType a2 = 2.209460984245205e+02; const mType a3 = -2.759285104469687e+02; const mType a4 = 1.383577518672690e+02; const mType a5 = -3.066479806614716e+01; const mType a6 = 2.506628277459239e+00; const mType b1 = -5.447609879822406e+01; const mType b2 = 1.615858368580409e+02; const mType b3 = -1.556989798598866e+02; const mType b4 = 6.680131188771972e+01; const mType b5 = -1.328068155288572e+01; const mType c1 = -7.784894002430293e-03; const mType c2 = -3.223964580411365e-01; const mType c3 = -2.400758277161838e+00; const mType c4 = -2.549732539343734e+00; const mType c5 = 4.374664141464968e+00; const mType c6 = 2.938163982698783e+00; const mType d1 = 7.784695709041462e-03; const mType d2 = 3.224671290700398e-01; const mType d3 = 2.445134137142996e+00; const mType d4 = 3.754408661907416e+00; const mType x_low = 0.02425; const mType x_high = 1.0 - x_low; mType standard_value, z, r, f1, f1_1, f2, tmp; mType p1, p2, p3, p4, p5, p6; mType q1, q2, q3, q4, q5; ap_uint<1> not_tail; ap_uint<1> upper_tail; mType t1, t2, t3, t4, t5, t6, t7, t8, t9, t10; mType t11, t12, t13, t14, t15, t16, t17, t18, t19; if (input < x_low || x_high < input) { if (input < x_low) { tmp = input; upper_tail = 0; } else { #pragma HLS resource variable = tmp core = DAddSub_nodsp tmp = mType(1.0) - input; upper_tail = 1; } #pragma HLS resource variable = t1 core = DLog_meddsp t1 = hls::log(tmp); #pragma HLS resource variable = t2 core = DMul_meddsp t2 = t1 * 2; t3 = -t2; z = hls::sqrt(t3); r = z; p1 = c1; p2 = c2; p3 = c3; p4 = c4; p5 = c5; p6 = c6; q1 = d1; q2 = d2; q3 = d3; q4 = d4; not_tail = 0; } else { #pragma HLS resource variable = z core = DAddSub_nodsp z = input - mType(0.5); #pragma HLS resource variable = r core = DMul_meddsp r = z * z; p1 = a1; p2 = a2; p3 = a3; p4 = a4; p5 = a5; p6 = a6; q1 = b1; q2 = b2; q3 = b3; q4 = b4; q5 = b5; not_tail = 1; } #pragma HLS resource variable = t4 core = DMul_meddsp t4 = p1 * r; #pragma HLS resource variable = t5 core = DAddSub_nodsp t5 = t4 + p2; #pragma HLS resource variable = t6 core = DMul_meddsp t6 = t5 * r; #pragma HLS resource variable = t7 core = DAddSub_nodsp t7 = t6 + p3; #pragma HLS resource variable = t8 core = DMul_meddsp t8 = t7 * r; #pragma HLS resource variable = t9 core = DAddSub_nodsp t9 = t8 + p4; #pragma HLS resource variable = t10 core = DMul_meddsp t10 = t9 * r; #pragma HLS resource variable = t11 core = DAddSub_nodsp t11 = t10 + p5; #pragma HLS resource variable = t12 core = DMul_meddsp t12 = t11 * r; #pragma HLS resource variable = f1_1 core = DAddSub_nodsp f1_1 = t12 + p6; if (not_tail) { #pragma HLS resource variable = f1 core = DMul_meddsp f1 = f1_1 * z; } else { f1 = f1_1; } #pragma HLS resource variable = t13 core = DMul_meddsp t13 = q1 * r; #pragma HLS resource variable = t14 core = DAddSub_nodsp t14 = t13 + q2; #pragma HLS resource variable = t15 core = DMul_meddsp t15 = t14 * r; #pragma HLS resource variable = t16 core = DAddSub_nodsp t16 = t15 + q3; #pragma HLS resource variable = t17 core = DMul_meddsp t17 = t16 * r; #pragma HLS resource variable = f2 core = DAddSub_nodsp f2 = t17 + q4; if (not_tail) { #pragma HLS resource variable = t18 core = DMul_meddsp t18 = f2 * r; #pragma HLS resource variable = f2 core = DAddSub_nodsp f2 = t18 + q5; } #pragma HLS resource variable = t19 core = DMul_meddsp t19 = f2 * r; #pragma HLS resource variable = f2 core = DAddSub_nodsp f2 = t19 + 1; standard_value = f1 / f2; if ((!not_tail) && (upper_tail)) { standard_value = -standard_value; } return standard_value; } /** * @brief Mersenne Twister to generate uniform random number. * * Reference:Mersenne Twister: A 623-Dimensionally Equidistributed Uniform * Pseudo-Random Number Generator */ class MT19937 { private: /// Bit width of element in state vector static const int W = 32; /// Number of elements in state vector static const int N = 624; /// Bias in state vector to calculate new state element static const int M = 397; /// Bitmask for lower R bits static const int R = 31; /// First right shift length static const int U = 11; /// First left shift length static const int S = 7; /// Second left shift length static const int T = 15; /// Second right shift length static const int L = 18; /// Right shift length in seed initilization static const int S_W = 30; /// Address width of state vector static const int A_W = 10; /// Use 1024 depth array to hold a 624 state vector static const int N_W = 1024; /// Array to store state vector ap_uint<W> mt_odd_0[N_W / 2]; /// Duplicate of array mt to solve limited memory port issue ap_uint<W> mt_odd_1[N_W / 2]; /// Array to store state vector ap_uint<W> mt_even_0[N_W / 2]; /// Duplicate of array mt to solve limited memory port issue ap_uint<W> mt_even_1[N_W / 2]; /// Element 0 of state vector ap_uint<W> x_k_p_0; /// Element 1 of state vector ap_uint<W> x_k_p_1; /// Element 2 of state vector ap_uint<W> x_k_p_2; /// Element m of state vector ap_uint<W> x_k_p_m; /// Address of head of state vector in array mt/mt_1 ap_uint<A_W> addr_head; public: /** * @brief initialize mt and mt_1 using seed * * @param seed initialization seed */ void seedInitialization(ap_uint<W> seed) { #pragma HLS inline off const ap_uint<W> start = 0xFFFFFFFF; const ap_uint<W> factor = 0x6C078965; const ap_uint<W> factor2 = 0x00010DCD; const ap_uint<W> factor3 = 0xffffffff - factor2; ap_uint<W * 2> tmp; ap_uint<W> mt_reg = seed; if (seed > factor3) { mt_reg = seed; } else { mt_reg = factor2 + seed; } mt_even_0[0] = mt_reg; mt_even_1[0] = mt_reg; SEED_INIT_LOOP: for (ap_uint<A_W> i = 1; i < N; i++) { #pragma HLS pipeline II = 3 tmp = factor * (mt_reg ^ (mt_reg >> S_W)) + i; mt_reg = tmp; ap_uint<A_W - 1> idx = i >> 1; if (i[0] == 0) { mt_even_0[idx] = tmp(W - 1, 0); mt_even_1[idx] = tmp(W - 1, 0); } else { mt_odd_0[idx] = tmp(W - 1, 0); mt_odd_1[idx] = tmp(W - 1, 0); } } x_k_p_0 = mt_even_0[0]; x_k_p_1 = mt_odd_0[0]; x_k_p_2 = mt_even_0[1]; x_k_p_m = mt_odd_0[M / 2]; addr_head = 0; } /** * @brief Default constructor */ MT19937() { #pragma HLS inline //#pragma HLS RESOURCE variable = mt_even_0 core = RAM_T2P_BRAM //#pragma HLS RESOURCE variable = mt_even_1 core = RAM_T2P_BRAM //#pragma HLS RESOURCE variable = mt_odd_0 core = RAM_T2P_BRAM //#pragma HLS RESOURCE variable = mt_odd_1 core = RAM_T2P_BRAM //#pragma HLS ARRAY_PARTITION variable=mt cyclic factor=2 } /** * @brief Constructor with seed * * @param seed initialization seed */ MT19937(ap_uint<W> seed) { #pragma HLS inline //#pragma HLS RESOURCE variable = mt_even_0 core = RAM_T2P_BRAM //#pragma HLS RESOURCE variable = mt_even_1 core = RAM_T2P_BRAM //#pragma HLS RESOURCE variable = mt_odd_0 core = RAM_T2P_BRAM //#pragma HLS RESOURCE variable = mt_odd_1 core = RAM_T2P_BRAM //#pragma HLS ARRAY_PARTITION variable=mt cyclic factor=2 seedInitialization(seed); } /** * @brief Setup status * * @param data array to store the initialization data */ void statusSetup(ap_uint<W> data[N]) { for (ap_uint<A_W> i = 0; i < N; i++) { ap_uint<A_W - 1> idx = i >> 1; if (i[0] == 0) { mt_even_0[idx] = data[i]; mt_even_1[idx] = data[i]; } else { mt_odd_0[idx] = data[i]; mt_odd_1[idx] = data[i]; } } // Initialize x_k_p_0, x_k_p_1 and head address of array mt x_k_p_0 = mt_even_0[0]; x_k_p_1 = mt_odd_0[0]; x_k_p_2 = mt_even_0[1]; x_k_p_m = mt_odd_0[M / 2]; addr_head = 0; } /** * @brief each call of next() generate a uniformly distributed random number * * @return a uniformly distributed random number */ ap_ufixed<W, 0> next() { #pragma HLS inline #pragma HLS DEPENDENCE variable = mt_even_0 inter false #pragma HLS DEPENDENCE variable = mt_even_1 inter false #pragma HLS DEPENDENCE variable = mt_odd_0 inter false #pragma HLS DEPENDENCE variable = mt_odd_1 inter false static const ap_uint<W> A = 0x9908B0DFUL; static const ap_uint<W> B = 0x9D2C5680UL; static const ap_uint<W> C = 0xEFC60000UL; ap_uint<W> tmp; ap_uint<1> tmp_0; ap_uint<A_W> addr_head_p_3; ap_uint<A_W> addr_head_p_m_p_1; ap_uint<A_W> addr_head_p_n; ap_uint<W> x_k_p_n; ap_uint<W> pre_result; ap_ufixed<W, 0> result; addr_head_p_3 = addr_head + 3; addr_head_p_m_p_1 = addr_head + M + 1; addr_head_p_n = addr_head + N; addr_head++; tmp(W - 1, R) = x_k_p_0(W - 1, R); tmp(R - 1, 0) = x_k_p_1(R - 1, 0); tmp_0 = tmp[0]; tmp >>= 1; if (tmp_0) { tmp ^= A; } x_k_p_n = x_k_p_m ^ tmp; x_k_p_0 = x_k_p_1; x_k_p_1 = x_k_p_2; ap_uint<A_W - 1> rd_addr_0 = addr_head_p_3 >> 1; ap_uint<A_W - 1> rd_addr_1 = addr_head_p_m_p_1 >> 1; ap_uint<A_W - 1> wr_addr = addr_head_p_n >> 1; if (addr_head_p_3[0] == 0) { x_k_p_2 = mt_even_0[rd_addr_0]; x_k_p_m = mt_odd_0[rd_addr_1]; mt_odd_0[wr_addr] = x_k_p_n; } else { x_k_p_2 = mt_odd_0[rd_addr_0]; x_k_p_m = mt_even_0[rd_addr_1]; mt_even_0[wr_addr] = x_k_p_n; } pre_result = x_k_p_n; pre_result ^= (pre_result >> U); pre_result ^= (pre_result << S) & B; pre_result ^= (pre_result << T) & C; pre_result ^= (pre_result >> L); result(W - 1, 0) = pre_result(W - 1, 0); return result; } /** * @brief each call of nextTwo() generate two uniformly distributed random numbers * @param result_l first random number * @param result_r second random number */ void nextTwo(ap_ufixed<W, 0>& result_l, ap_ufixed<W, 0>& result_r) { #pragma HLS inline #pragma HLS DEPENDENCE variable = mt_odd_0 inter false #pragma HLS DEPENDENCE variable = mt_odd_1 inter false #pragma HLS DEPENDENCE variable = mt_even_0 inter false #pragma HLS DEPENDENCE variable = mt_even_1 inter false static const ap_uint<W> A = 0x9908B0DFUL; static const ap_uint<W> B = 0x9D2C5680UL; static const ap_uint<W> C = 0xEFC60000UL; ap_uint<W> tmp_l, tmp_r; ap_uint<1> tmp_0_l, tmp_0_r; ap_uint<A_W> addr_head_p_3_l, addr_head_p_3_r; ap_uint<A_W> addr_head_p_m_p_1_l, addr_head_p_m_p_1_r; ap_uint<A_W> addr_head_p_n_l, addr_head_p_n_r; ap_uint<W> x_k_p_n_l, x_k_p_n_r; ap_uint<W> pre_result_l, pre_result_r; ap_ufixed<W, 0> out_l, out_r; addr_head_p_3_l = addr_head + 3; addr_head_p_m_p_1_l = addr_head + M + 1; addr_head_p_n_l = addr_head + N; addr_head_p_3_r = addr_head + 4; addr_head_p_m_p_1_r = addr_head + M + 2; addr_head_p_n_r = addr_head + N + 1; addr_head += 2; ap_uint<A_W - 1> rd_addr_l_0 = addr_head_p_3_l >> 1; ap_uint<A_W - 1> rd_addr_l_1 = addr_head_p_m_p_1_l >> 1; ap_uint<W> x_k_p_2_l = mt_odd_0[rd_addr_l_0]; ap_uint<W> x_k_p_m_l = mt_even_0[rd_addr_l_1]; ap_uint<A_W - 1> rd_addr_r_0 = addr_head_p_3_r >> 1; ap_uint<A_W - 1> rd_addr_r_1 = addr_head_p_m_p_1_r >> 1; ap_uint<W> x_k_p_2_r = mt_even_1[rd_addr_r_0]; ap_uint<W> x_k_p_m_r = mt_odd_1[rd_addr_r_1]; tmp_l(W - 1, R) = x_k_p_0(W - 1, R); tmp_l(R - 1, 0) = x_k_p_1(R - 1, 0); tmp_0_l = tmp_l[0]; tmp_l >>= 1; if (tmp_0_l) { tmp_l ^= A; } x_k_p_n_l = x_k_p_m ^ tmp_l; tmp_r(W - 1, R) = x_k_p_1(W - 1, R); tmp_r(R - 1, 0) = x_k_p_2(R - 1, 0); tmp_0_r = tmp_r[0]; tmp_r >>= 1; if (tmp_0_r) { tmp_r ^= A; } x_k_p_n_r = x_k_p_m_l ^ tmp_r; x_k_p_0 = x_k_p_2; x_k_p_1 = x_k_p_2_l; x_k_p_2 = x_k_p_2_r; x_k_p_m = x_k_p_m_r; pre_result_l = x_k_p_n_l; pre_result_l ^= (pre_result_l >> U); pre_result_l ^= (pre_result_l << S) & B; pre_result_l ^= (pre_result_l << T) & C; pre_result_l ^= (pre_result_l >> L); out_l(W - 1, 0) = pre_result_l(W - 1, 0); result_l = out_l; pre_result_r = x_k_p_n_r; pre_result_r ^= (pre_result_r >> U); pre_result_r ^= (pre_result_r << S) & B; pre_result_r ^= (pre_result_r << T) & C; pre_result_r ^= (pre_result_r >> L); out_r(W - 1, 0) = pre_result_r(W - 1, 0); result_r = out_r; ap_uint<A_W - 1> wr_addr_l = addr_head_p_n_l >> 1; ap_uint<A_W - 1> wr_addr_r = addr_head_p_n_r >> 1; mt_even_0[wr_addr_l] = x_k_p_n_l; mt_even_1[wr_addr_l] = x_k_p_n_l; mt_odd_0[wr_addr_r] = x_k_p_n_r; mt_odd_1[wr_addr_r] = x_k_p_n_r; } }; /** * @brief Normally distributed random number generator based on InverseCumulative * function * * @tparam mType data type supported including float and double */ template <typename mType> class MT19937IcnRng { public: /** * @brief Default constructor * */ MT19937IcnRng() { #pragma HLS inline } /** * @brief Constructor with seed * * @param seed initialization seed */ MT19937IcnRng(ap_uint<32> seed) { #pragma HLS inline } /** * @brief Initialization using seed * * @param seed initialization seed */ void seedInitialization(ap_uint<32> seed) {} /** * @brief Setup status * * @param data initialization data for setting up status */ void statusSetup(ap_uint<32> data[624]) {} /** * @brief Get next normally distributed random number * * @return a normally distributed random number */ mType next() {} /** * @brief Get next uniformly distributed random number * * @param uniformR return uniformly distributed random number */ void next(mType& uniformR) {} /** * @brief Get next normally distributed random number and its corresponding * uniformly distributed random number * * @param gaussianR return normally distributed random number * @param uniformR return uniformly distributed random number that * corrresponding to gaussianR */ void next(mType& uniformR, mType& gaussianR) {} /** * @brief Get next two normally distributed random numbers * * @param gaussR return first normally distributed random number. * @param gaussL return second normally distributed random number. */ void nextTwo(mType& gaussR, mType& gaussL) {} }; /** * @brief Normally distributed random number generator based on InverseCumulative * function, output datatype is double. */ template <> class MT19937IcnRng<double> { public: MT19937 uniformRNG; MT19937IcnRng(ap_uint<32> seed) : uniformRNG(seed) { #pragma HLS inline } MT19937IcnRng() { #pragma HLS inline } /** * @brief Initialization using seed * * @param seed initialization seed */ void seedInitialization(ap_uint<32> seed) { uniformRNG.seedInitialization(seed); } /** * @brief Setup status * * @param data initialization data for setting up status */ void statusSetup(ap_uint<32> data[624]) { uniformRNG.statusSetup(data); } /** * @brief Get next normally distributed random number * * @return a normally distributed random number */ double next() { #pragma HLS inline double tmp_uniform, result; tmp_uniform = uniformRNG.next(); result = inverseCumulativeNormalAcklam<double>(tmp_uniform); return result; } /** * @brief Get next normally distributed random number and its corresponding * uniformly distributed random number * * @param gaussianR return normally distributed random number. * @param uniformR return uniformly distributed random number that * corrresponding to gaussianR */ void next(double& uniformR, double& gaussianR) { #pragma HLS inline double tmp_uniform, result; tmp_uniform = uniformRNG.next(); result = inverseCumulativeNormalAcklam<double>(tmp_uniform); uniformR = tmp_uniform; gaussianR = result; } /** * @brief Get next uniformly distributed random number * * @param uniformR return uniformly distributed random number */ void next(double& uniformR) { #pragma HLS inline uniformR = uniformRNG.next(); } /** * @brief Get next two normally distributed random number * * @param gaussR return first normally distributed random number. * @param gaussL return second normally distributed random number. */ void nextTwo(double& gaussR, double& gaussL) { #pragma HLS inline ap_ufixed<32, 0> unifR, unifL; uniformRNG.nextTwo(unifR, unifL); gaussR = inverseCumulativeNormalAcklam<double>(unifR); gaussL = inverseCumulativeNormalAcklam<double>(unifL); } }; /** * @brief Normally distributed random number generator based on InverseCumulative * function, output datatype is float. */ template <> class MT19937IcnRng<float> { public: MT19937 uniformRNG; MT19937IcnRng(ap_uint<32> seed) : uniformRNG(seed) { #pragma HLS inline } MT19937IcnRng() { #pragma HLS inline } /** * @brief Initialization using seed * * @param seed initialization seed */ void seedInitialization(ap_uint<32> seed) { uniformRNG.seedInitialization(seed); } /** * @brief Setup status * * @param data initialization data for setting up status */ void statusSetup(ap_uint<32> data[624]) { uniformRNG.statusSetup(data); } /** * @brief Get next normally distributed random number * * @return a normally distributed random number */ float next() { #pragma HLS inline float tmp_uniform, result; tmp_uniform = uniformRNG.next(); result = inverseCumulativeNormalPPND7<float>(tmp_uniform); return result; } /** * @brief Get a normally distributed random number and its corresponding * uniformly distributed random number * * @param gaussianR return normally distributed random number. * @param uniformR return uniformly distributed random number that * corrresponding to gaussianR */ void next(float& uniformR, float& gaussianR) { #pragma HLS inline float tmp_uniform, result; tmp_uniform = uniformRNG.next(); result = inverseCumulativeNormalPPND7<float>(tmp_uniform); uniformR = tmp_uniform; gaussianR = result; } /** * @brief Get next uniformly distributed random number * * param uniformR return a uniformly distributed random number */ void next(float& uniformR) { #pragma HLS inline uniformR = uniformRNG.next(); } /** * @brief Get next two normally distributed random number * * @param gaussR return first normally distributed random number. * @param gaussL return second normally distributed random number. */ void nextTwo(float& gaussR, float& gaussL) { #pragma HLS inline ap_ufixed<32, 0> unifR, unifL; uniformRNG.nextTwo(unifR, unifL); gaussR = inverseCumulativeNormalPPND7<float>(unifR); gaussL = inverseCumulativeNormalPPND7<float>(unifL); } }; } // namespace fintech } // namespace xf #endif // ifndef XF_FINTECH_PRNG_H
29.854613
116
0.611975
[ "vector", "transform" ]
eeba0a519deebc0af2833e8e038a9e4e4c299038
4,714
cc
C++
src/tests/interpolation/test_interpolation_non_linear.cc
wdeconinck/atlas
8949d2b362b9b5431023a967bcf4ca84f6b8ce05
[ "Apache-2.0" ]
null
null
null
src/tests/interpolation/test_interpolation_non_linear.cc
wdeconinck/atlas
8949d2b362b9b5431023a967bcf4ca84f6b8ce05
[ "Apache-2.0" ]
null
null
null
src/tests/interpolation/test_interpolation_non_linear.cc
wdeconinck/atlas
8949d2b362b9b5431023a967bcf4ca84f6b8ce05
[ "Apache-2.0" ]
null
null
null
/* * (C) Copyright 1996- ECMWF. * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. * * In applying this licence, ECMWF does not waive the privileges and immunities * granted to it by virtue of its status as an intergovernmental organisation nor * does it submit to any jurisdiction. */ #include <algorithm> #include <limits> #include "atlas/array.h" #include "atlas/field/MissingValue.h" #include "atlas/functionspace.h" #include "atlas/grid.h" #include "atlas/interpolation.h" #include "atlas/interpolation/NonLinear.h" #include "atlas/mesh.h" #include "atlas/meshgenerator.h" #include "atlas/runtime/Exception.h" #include "tests/AtlasTestEnvironment.h" namespace atlas { namespace test { const double missingValue = 42.; const double missingValueEps = 1e-9; const double nan = std::numeric_limits<double>::quiet_NaN(); using field::MissingValue; using util::Config; CASE( "Interpolation with MissingValue" ) { /* Set input field full of 1's, with 9 nodes 1 ... 1 ... 1 : : : 1-----m ... 1 m: missing value |i i| : i: interpolation on two points, this quadrilateral only 1-----1 ... 1 */ RectangularDomain domain( {0, 2}, {0, 2}, "degrees" ); Grid gridA( "L90", domain ); const idx_t nbNodes = 9; ATLAS_ASSERT( gridA.size() == nbNodes ); Mesh meshA = MeshGenerator( "structured" ).generate( gridA ); functionspace::NodeColumns fsA( meshA ); Field fieldA = fsA.createField<double>( option::name( "A" ) ); fieldA.metadata().set( "missing_value", missingValue ); fieldA.metadata().set( "missing_value_epsilon", missingValueEps ); auto viewA = array::make_view<double, 1>( fieldA ); for ( idx_t j = 0; j < fsA.nodes().size(); ++j ) { viewA( j ) = 1; } // Set output field (2 points) functionspace::PointCloud fsB( {PointLonLat{0.1, 0.1}, PointLonLat{0.9, 0.9}} ); SECTION( "missing-if-all-missing" ) { Interpolation interpolation( Config( "type", "finite-element" ).set( "non_linear", "missing-if-all-missing" ), fsA, fsB ); for ( std::string type : {"equals", "approximately-equals", "nan"} ) { Field fieldB( "B", array::make_datatype<double>(), array::make_shape( fsB.size() ) ); auto viewB = array::make_view<double, 1>( fieldB ); fieldA.metadata().set( "missing_value_type", type ); viewA( 4 ) = type == "nan" ? nan : missingValue; EXPECT( MissingValue( fieldA ) ); interpolation.execute( fieldA, fieldB ); MissingValue mv( fieldB ); EXPECT( mv ); EXPECT( mv( viewB( 0 ) ) == false ); EXPECT( mv( viewB( 1 ) ) == false ); } } SECTION( "missing-if-any-missing" ) { Interpolation interpolation( Config( "type", "finite-element" ).set( "non_linear", "missing-if-any-missing" ), fsA, fsB ); for ( std::string type : {"equals", "approximately-equals", "nan"} ) { Field fieldB( "B", array::make_datatype<double>(), array::make_shape( fsB.size() ) ); auto viewB = array::make_view<double, 1>( fieldB ); fieldA.metadata().set( "missing_value_type", type ); viewA( 4 ) = type == "nan" ? nan : missingValue; EXPECT( MissingValue( fieldA ) ); interpolation.execute( fieldA, fieldB ); MissingValue mv( fieldB ); EXPECT( mv ); EXPECT( mv( viewB( 0 ) ) ); EXPECT( mv( viewB( 1 ) ) ); } } SECTION( "missing-if-heaviest-missing" ) { Interpolation interpolation( Config( "type", "finite-element" ).set( "non_linear", "missing-if-heaviest-missing" ), fsA, fsB ); for ( std::string type : {"equals", "approximately-equals", "nan"} ) { Field fieldB( "B", array::make_datatype<double>(), array::make_shape( fsB.size() ) ); auto viewB = array::make_view<double, 1>( fieldB ); fieldA.metadata().set( "missing_value_type", type ); viewA( 4 ) = type == "nan" ? nan : missingValue; EXPECT( MissingValue( fieldA ) ); interpolation.execute( fieldA, fieldB ); MissingValue mv( fieldB ); EXPECT( mv ); EXPECT( mv( viewB( 0 ) ) == false ); EXPECT( mv( viewB( 1 ) ) ); } } } } // namespace test } // namespace atlas int main( int argc, char** argv ) { return atlas::test::run( argc, argv ); }
32.068027
118
0.577641
[ "mesh" ]
eebc2ec6b2404c2df4baeb89c746fdd90e850017
2,546
cpp
C++
ClientDemo/DlgDynChanAbility.cpp
xiaocaovc/hkvs
569c57b03adf5723ccc1df0de6c96858062d23e1
[ "MIT" ]
2
2017-09-05T07:01:13.000Z
2019-07-16T17:18:28.000Z
ClientDemo/DlgDynChanAbility.cpp
xiaocaovc/hkvs
569c57b03adf5723ccc1df0de6c96858062d23e1
[ "MIT" ]
null
null
null
ClientDemo/DlgDynChanAbility.cpp
xiaocaovc/hkvs
569c57b03adf5723ccc1df0de6c96858062d23e1
[ "MIT" ]
3
2019-08-26T02:28:54.000Z
2020-11-04T04:29:19.000Z
// DlgDynChanAbility.cpp : implementation file // #include "stdafx.h" #include "clientdemo.h" #include "DlgDynChanAbility.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CDlgDynChanAbility dialog CDlgDynChanAbility::CDlgDynChanAbility(CWnd* pParent /*=NULL*/) : CDialog(CDlgDynChanAbility::IDD, pParent) { //{{AFX_DATA_INIT(CDlgDynChanAbility) m_dwChannelNO = 1; //}}AFX_DATA_INIT } void CDlgDynChanAbility::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CDlgDynChanAbility) DDX_Text(pDX, IDC_EDIT_CHANNEL_NO, m_dwChannelNO); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CDlgDynChanAbility, CDialog) //{{AFX_MSG_MAP(CDlgDynChanAbility) ON_BN_CLICKED(IDC_BTN_GET_ABILITY, OnBtnGetAbility) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CDlgDynChanAbility message handlers BOOL CDlgDynChanAbility::WirteBufToFile(char *pBuf, DWORD dwBufSize) { SYSTEMTIME t; GetLocalTime(&t); char chTime[128]; char cFilename[256] = {0}; sprintf(chTime,"%4.4d%2.2d%2.2d%2.2d%2.2d%2.2d%3.3d",t.wYear,t.wMonth,t.wDay,t.wHour,t.wMinute,t.wSecond,t.wMilliseconds); sprintf(cFilename, "%s\\DYNCHAN_%s.xml", g_struLocalParam.chPictureSavePath, chTime); HANDLE hFile = CreateFile(cFilename, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) { int nError = 0; nError = GetLastError(); return FALSE; } DWORD dwReturn = 0; WriteFile(hFile, pBuf, dwBufSize, &dwReturn, NULL); CloseHandle(hFile); hFile = NULL; return TRUE; } void CDlgDynChanAbility::OnBtnGetAbility() { // TODO: Add your control notification handler code here UpdateData(TRUE); m_pRecvBuf = new char[2*1024*1024]; memset(m_pRecvBuf,0,2*1024*1024); char sSendBuf[1024]; memset(sSendBuf, 0, 1024); sprintf(sSendBuf, "<DynChannelAbility><channelNO>%d</channelNO></DynChannelAbility>", m_dwChannelNO); if (NET_DVR_GetDeviceAbility(m_lServerID, DEVICE_DYNCHAN_ABILITY, sSendBuf, strlen(sSendBuf), m_pRecvBuf, 2*1024*1024)) { g_pMainDlg->AddLog(m_iDevIndex, OPERATION_SUCC_T, "DEVICE_DYNCHAN_ABILITY"); WirteBufToFile(m_pRecvBuf, strlen(m_pRecvBuf)); } else { g_pMainDlg->AddLog(m_iDevIndex, OPERATION_FAIL_T, "DEVICE_DYNCHAN_ABILITY"); } }
28.288889
126
0.681854
[ "3d" ]
eebd29aaa03c44e4aefcdccc146383710b4fdd39
17,886
hpp
C++
source/core/Module.hpp
FergusonAJ/MABE2
608c6dfcd6735c077594027d0e129084fc5ca830
[ "MIT" ]
null
null
null
source/core/Module.hpp
FergusonAJ/MABE2
608c6dfcd6735c077594027d0e129084fc5ca830
[ "MIT" ]
1
2021-06-30T17:57:51.000Z
2021-06-30T17:57:51.000Z
source/core/Module.hpp
FergusonAJ/MABE2
608c6dfcd6735c077594027d0e129084fc5ca830
[ "MIT" ]
null
null
null
/** * @note This file is part of MABE, https://github.com/mercere99/MABE2 * @copyright Copyright (C) Michigan State University, MIT Software license; see doc/LICENSE.md * @date 2019-2021. * * @file Module.hpp * @brief Base class for all MABE modules. * * Core module functionality is split between ModuleBase (which this class is derived from) and * Module (this class). The difference is that the main MABE controller has access only * to ModuleBase. Module, in turn, has access to the main MABE controller. So: * * ModuleBase <- MABE <- Module * * When you are developing a new class derived from Module, you will be able to access the * MABE controller and make any changes to it that you need to. The MABE controller will have * access to base Module functionality through this ModuleBase. * */ #ifndef MABE_MODULE_H #define MABE_MODULE_H #include <string> #include "emp/base/map.hpp" #include "emp/base/Ptr.hpp" #include "emp/base/vector.hpp" #include "emp/datastructs/map_utils.hpp" #include "emp/datastructs/reference_vector.hpp" #include "../config/Config.hpp" #include "MABE.hpp" #include "ModuleBase.hpp" #include "Population.hpp" #include "TraitInfo.hpp" namespace mabe { class Module : public ModuleBase { public: Module(MABE & in_control, const std::string & in_name, const std::string & in_desc="") : ModuleBase(in_control, in_name, in_desc) { error_man = &control.GetErrorManager(); } Module(const Module &) = delete; Module(Module &&) = delete; protected: // Specialized configuration links for MABE-specific modules. // (Other ways of linking variable to config file are in ConfigType.h) /// Link a single population to a parameter by name. ConfigEntry_Functions<std::string> & LinkPop(int & var, const std::string & name, const std::string & desc) { std::function<std::string()> get_fun = [this,&var](){ return control.GetPopulation(var).GetName(); }; std::function<void(std::string)> set_fun = [this,&var](const std::string & name){ var = control.GetPopID(name); if (var == -1) AddError("Trying to access population '", name, "'; does not exist."); }; return GetScope().LinkFuns<std::string>(name, get_fun, set_fun, desc); } /// Link one or more populations (or portions of a population) to a parameter. ConfigEntry_Functions<std::string> & LinkCollection(mabe::Collection & var, const std::string & name, const std::string & desc) { std::function<std::string()> get_fun = [this,&var](){ return control.ToString(var); }; std::function<void(std::string)> set_fun = [this,&var](const std::string & load_str){ var = control.FromString(load_str); }; return GetScope().LinkFuns<std::string>(name, get_fun, set_fun, desc); } /// Link another module to this one, by name (track using int ID) ConfigEntry_Functions<std::string> & LinkModule(int & var, const std::string & name, const std::string & desc) { std::function<std::string()> get_fun = [this,&var](){ return control.GetModule(var).GetName(); }; std::function<void(std::string)> set_fun = [this,&var](const std::string & name){ var = control.GetModuleID(name); if (var == -1) AddError("Trying to access module '", name, "'; does not exist."); }; return GetScope().LinkFuns<std::string>(name, get_fun, set_fun, desc); } /// Link a range of values with a start, stop, and step. ConfigEntry_Functions<std::string> & LinkRange(int & start_var, int & step_var, int & stop_var, const std::string & name, const std::string & desc) { std::function<std::string()> get_fun = [&start_var,&step_var,&stop_var]() { // If stop_var is -1, don't bother printing it (i.e. NO stop) if (stop_var == -1) return emp::to_string(start_var, ':', step_var); return emp::to_string(start_var, ':', step_var, ':', stop_var); }; std::function<void(std::string)> set_fun = [&start_var,&step_var,&stop_var](std::string name){ start_var = emp::from_string<int>(emp::string_pop(name, ':')); step_var = emp::from_string<int>(emp::string_pop(name, ':')); stop_var = name.size() ? emp::from_string<int>(name) : -1; // -1 indicates no stop. }; return GetScope().LinkFuns<std::string>(name, get_fun, set_fun, desc); } public: // ---== Trait management ==--- /// Add a new trait to this module, specifying its access method, its name, and its description /// AND its default value. template <typename T, typename... ALT_Ts> TraitInfo & AddTrait(TraitInfo::Access access, const std::string & name, const std::string & desc="", const T & default_val=T()) { return control.GetTraitManager().AddTrait<T,ALT_Ts...>(this, access, name, desc, default_val); } /// Add trait that this module can READ & WRITE this trait. Others cannot use it. /// Must provide name, description, and a default value to start at. template <typename T, typename... ALT_Ts> TraitInfo & AddPrivateTrait(const std::string & name, const std::string & desc, const T & default_val) { return AddTrait<T,ALT_Ts...>(TraitInfo::Access::PRIVATE, name, desc, default_val); } /// Add trait that this module can READ & WRITE to; other modules can only read. /// Must provide name, description, and a default value to start at. template <typename T, typename... ALT_Ts> TraitInfo & AddOwnedTrait(const std::string & name, const std::string & desc, const T & default_val) { return AddTrait<T,ALT_Ts...>(TraitInfo::Access::OWNED, name, desc, default_val); } /// Add trait that this module can READ & WRITE to; at least one other module MUST read it. /// Must provide name, description, and a default value to start at. template <typename T, typename... ALT_Ts> TraitInfo & AddGeneratedTrait(const std::string & name, const std::string & desc, const T & default_val) { return AddTrait<T,ALT_Ts...>(TraitInfo::Access::GENERATED, name, desc, default_val); } /// Add trait that this module can READ & WRITE; other modules can too. template <typename T, typename... ALT_Ts> TraitInfo & AddSharedTrait(const std::string & name, const std::string & desc, const T & default_val) { return AddTrait<T,ALT_Ts...>(TraitInfo::Access::SHARED, name, desc, default_val); } /// Add trait that this module can READ, but another module must WRITE to it. /// That other module should also provide the description for the trait. template <typename T, typename... ALT_Ts> TraitInfo & AddRequiredTrait(const std::string & name) { return AddTrait<T,ALT_Ts...>(TraitInfo::Access::REQUIRED, name); } // ---== Signal Handling ==--- // Functions to be called based on signals. Note that the existance of an overridden version // of each function is tracked by an associated bool value that we default to true until the // base version of the function is called indicating that it has NOT been overridden. // Format: BeforeUpdate(size_t update_ending) // Trigger: Update is ending; new one is about to start // Args: Update ID that is just finishing. void BeforeUpdate(size_t) override { has_signal[SIG_BeforeUpdate] = false; control.RescanSignals(); } // Format: OnUpdate(size_t new_update) // Trigger: New update has just started. // Args: Update ID just starting. void OnUpdate(size_t) override { has_signal[SIG_OnUpdate] = false; control.RescanSignals(); } // Format: BeforeRepro(OrgPosition parent_pos) // Trigger: Parent is about to reproduce. // Args: Position of organism about to reproduce. void BeforeRepro(OrgPosition) override { has_signal[SIG_BeforeRepro] = false; control.RescanSignals(); } // Format: OnOffspringReady(Organism & offspring, OrgPosition parent_pos, Population & target_pop) // Trigger: Offspring is ready to be placed. // Args: Offspring to be born, position of parent, population to place offspring in. void OnOffspringReady(Organism &, OrgPosition, Population &) override { has_signal[SIG_OnOffspringReady] = false; control.RescanSignals(); } // Format: OnInjectReady(Organism & inject_org, Population & target_pop) // Trigger: Organism to be injected is ready to be placed. // Args: Organism to be injected, population to inject into. void OnInjectReady(Organism &, Population &) override { has_signal[SIG_OnInjectReady] = false; control.RescanSignals(); } // Format: BeforePlacement(Organism & org, OrgPosition target_pos, OrgPosition parent_pos) // Trigger: Placement location has been identified (For birth or inject) // Args: Organism to be placed, placement position, parent position (if available) void BeforePlacement(Organism &, OrgPosition, OrgPosition) override { has_signal[SIG_BeforePlacement] = false; control.RescanSignals(); } // Format: OnPlacement(OrgPosition placement_pos) // Trigger: New organism has been placed in the poulation. // Args: Position new organism was placed. void OnPlacement(OrgPosition) override { has_signal[SIG_OnPlacement] = false; control.RescanSignals(); } // Format: BeforeMutate(Organism & org) // Trigger: Mutate is about to run on an organism. // Args: Organism about to mutate. void BeforeMutate(Organism &) override { has_signal[SIG_BeforeMutate] = false; control.RescanSignals(); } // Format: OnMutate(Organism & org) // Trigger: Organism has had its genome changed due to mutation. // Args: Organism that just mutated. void OnMutate(Organism &) override { has_signal[SIG_OnMutate] = false; control.RescanSignals(); } // Format: BeforeDeath(OrgPosition remove_pos) // Trigger: Organism is about to die. // Args: Position of organism about to die. void BeforeDeath(OrgPosition) override { has_signal[SIG_BeforeDeath] = false; control.RescanSignals(); } // Format: BeforeSwap(OrgPosition pos1, OrgPosition pos2) // Trigger: Two organisms' positions in the population are about to move. // Args: Positions of organisms about to be swapped. void BeforeSwap(OrgPosition, OrgPosition) override { has_signal[SIG_BeforeSwap] = false; control.RescanSignals(); } // Format: OnSwap(OrgPosition pos1, OrgPosition pos2) // Trigger: Two organisms' positions in the population have just swapped. // Args: Positions of organisms just swapped. void OnSwap(OrgPosition, OrgPosition) override { has_signal[SIG_OnSwap] = false; control.RescanSignals(); } // Format: BeforePopResize(Population & pop, size_t new_size) // Trigger: Full population is about to be resized. // Args: Population about to be resized, the size it will become. void BeforePopResize(Population &, size_t) override { has_signal[SIG_BeforePopResize] = false; control.RescanSignals(); } // Format: OnPopResize(Population & pop, size_t old_size) // Trigger: Full population has just been resized. // Args: Population just resized, previous size it was. void OnPopResize(Population &, size_t) override { has_signal[SIG_OnPopResize] = false; control.RescanSignals(); } // Format: OnError(const std::string & msg) // Trigger: An error has occurred and the user should be notified. // Args: Message associated with this error. void OnError(const std::string &) override { has_signal[SIG_OnError] = false; control.RescanSignals(); } // Format: OnWarning(const std::string & msg) // Trigger: A atypical condition has occurred and the user should be notified. // Args: Message associated with this warning. void OnWarning(const std::string &) override { has_signal[SIG_OnWarning] = false; control.RescanSignals(); } // Format: BeforeExit() // Trigger: Run immediately before MABE is about to exit. void BeforeExit() override { has_signal[SIG_BeforeExit] = false; control.RescanSignals(); } // Format: OnHelp() // Trigger: Run when the --help option is called at startup. void OnHelp() override { has_signal[SIG_OnHelp] = false; control.RescanSignals(); } // Format: TraceEval(Organism & trace_org, std::ostream & out_stream) // Trigger: Request to print a trace of the evaluation of an organism. // Args: Organism to be traces, stream to print trace to. void TraceEval(Organism &, std::ostream &) override { has_signal[SIG_TraceEval] = false; control.RescanSignals(); } // Functions to be called based on actions that need to happen. Each of these returns a // viable result or an invalid object if need to pass on to the next module. Modules will // be querried in order until one of them returns a valid result. // Function: Place a new organism about to be born. // Args: Organism that will be placed, position of parent, population to place. // Return: Position to place offspring or an invalid position if failed. OrgPosition DoPlaceBirth(Organism &, OrgPosition, Population &) override { has_signal[SIG_DoPlaceBirth] = false; control.RescanSignals(); return OrgPosition(); } // Function: Place a new organism about to be injected. // Args: Organism that will be placed, position to place. OrgPosition DoPlaceInject(Organism &, Population &) override { has_signal[SIG_DoPlaceInject] = false; control.RescanSignals(); return OrgPosition(); } // Function: Find a random neighbor to a designated position. // Args: Position to find neighbor of, position found. OrgPosition DoFindNeighbor(OrgPosition) override { has_signal[SIG_DoFindNeighbor] = false; control.RescanSignals(); return OrgPosition(); } /// Turn off all signals in this function. void Deactivate() override { has_signal.Clear(); control.RescanSignals(); } /// Turn on all signals in this function (unimplemented ones will turn off automatically) void Activate() override { has_signal.SetAll(); control.RescanSignals(); } bool BeforeUpdate_IsTriggered() override { return control.BeforeUpdate_IsTriggered(this); }; bool OnUpdate_IsTriggered() override { return control.OnUpdate_IsTriggered(this); }; bool BeforeRepro_IsTriggered() override { return control.BeforeRepro_IsTriggered(this); }; bool OnOffspringReady_IsTriggered() override { return control.OnOffspringReady_IsTriggered(this); }; bool OnInjectReady_IsTriggered() override { return control.OnInjectReady_IsTriggered(this); }; bool BeforePlacement_IsTriggered() override { return control.BeforePlacement_IsTriggered(this); }; bool OnPlacement_IsTriggered() override { return control.OnPlacement_IsTriggered(this); }; bool BeforeMutate_IsTriggered() override { return control.BeforeMutate_IsTriggered(this); }; bool OnMutate_IsTriggered() override { return control.OnMutate_IsTriggered(this); }; bool BeforeDeath_IsTriggered() override { return control.BeforeDeath_IsTriggered(this); }; bool BeforeSwap_IsTriggered() override { return control.BeforeSwap_IsTriggered(this); }; bool OnSwap_IsTriggered() override { return control.OnSwap_IsTriggered(this); }; bool BeforePopResize_IsTriggered() override { return control.BeforePopResize_IsTriggered(this); }; bool OnPopResize_IsTriggered() override { return control.OnPopResize_IsTriggered(this); }; bool OnError_IsTriggered() override { return control.OnError_IsTriggered(this); }; bool OnWarning_IsTriggered() override { return control.OnWarning_IsTriggered(this); }; bool BeforeExit_IsTriggered() override { return control.BeforeExit_IsTriggered(this); }; bool OnHelp_IsTriggered() override { return control.OnHelp_IsTriggered(this); }; bool TraceEval_IsTriggered() override { return control.TraceEval_IsTriggered(this); }; bool DoPlaceBirth_IsTriggered() override { return control.DoPlaceBirth_IsTriggered(this); }; bool DoPlaceInject_IsTriggered() override { return control.DoPlaceInject_IsTriggered(this); }; bool DoFindNeighbor_IsTriggered() override { return control.DoFindNeighbor_IsTriggered(this); }; }; /// Build a class that will automatically register modules when created (globally) template <typename T> struct ModuleRegistrar { ModuleRegistrar(const std::string & type_name, const std::string & desc) { ModuleInfo new_info; new_info.name = type_name; new_info.desc = desc; new_info.init_fun = [desc](MABE & control, const std::string & name) -> ConfigType & { return control.AddModule<T>(name, desc); }; GetModuleInfo().insert(new_info); } }; #define MABE_REGISTER_MODULE(TYPE, DESC) \ mabe::ModuleRegistrar<TYPE> MABE_ ## TYPE ## _Registrar(#TYPE, DESC) } #endif
42.995192
110
0.660517
[ "object", "vector" ]
eebd7dc095824080b4a6b7fe3f0199c07c5bc00a
6,247
cpp
C++
Firmware/Platform_NordicSDK/EPXPlatform_Runtime.cpp
harishsk/ExpressivePixels
db878e0f86c06a481fb073a70fee8368bbf3b53e
[ "MIT" ]
54
2020-09-04T12:02:30.000Z
2022-03-27T21:17:02.000Z
Firmware/Platform_NordicSDK/EPXPlatform_Runtime.cpp
harishsk/ExpressivePixels
db878e0f86c06a481fb073a70fee8368bbf3b53e
[ "MIT" ]
16
2020-09-04T14:36:14.000Z
2022-01-13T03:29:27.000Z
Firmware/Platform_NordicSDK/EPXPlatform_Runtime.cpp
harishsk/ExpressivePixels
db878e0f86c06a481fb073a70fee8368bbf3b53e
[ "MIT" ]
10
2020-09-04T22:54:57.000Z
2021-12-10T14:20:31.000Z
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. #include "app_util_platform.h" #include "nrf_drv_timer.h" #include "nrf_delay.h" #include "nrf_timer.h" #include "nrf_drv_wdt.h" #include <string.h> #include <ctype.h> #include "EPXPlatform_Runtime.h" #include "EPXPlatform_GPIO.h" extern "C" { #include "nrf_pwr_mgmt.h" } uint32_t g_AppTimerTick = 0; nrf_drv_timer_t g_appTimer; #define DFU_MAGIC_OTA_RESET 0xA8 #define DFU_MAGIC_SERIAL_ONLY_RESET 0x4e #define DFU_MAGIC_UF2_RESET 0x57 void _EPXPlatform_Runtime_InitializeAppTimer(); void EPXPlatform_Runtime_Reboot(uint8_t rebootType) { switch (rebootType) { case REBOOTTYPE_UF2: sd_power_gpregret_set(0, DFU_MAGIC_UF2_RESET); DEBUGLOGLN("System_Reboot DFU_MAGIC_UF2_RESET"); break; case REBOOTTYPE_OTA: sd_power_gpregret_set(0, DFU_MAGIC_OTA_RESET); DEBUGLOGLN("System_Reboot DFU_MAGIC_OTA_RESET"); break; case REBOOTTYPE_SERIAL: sd_power_gpregret_set(0, DFU_MAGIC_SERIAL_ONLY_RESET); DEBUGLOGLN("System_Reboot DFU_MAGIC_SERIAL_ONLY_RESET"); break; default: DEBUGLOGLN("System_Reboot NORMAL"); break; } delay(500); NVIC_SystemReset(); } static void _WatchdogEventHandler() { DEBUGLOGLN("*** WATCHDOG TRIGGERED ***"); NVIC_SystemReset(); } static bool g_bWatchdogInitialized = false; static nrfx_wdt_channel_id g_watchDogChannelID; void _EPXPlatform_Runtime_InitializeWatchdog() { nrf_drv_wdt_config_t config = NRF_DRV_WDT_DEAFULT_CONFIG; uint32_t err_code = nrf_drv_wdt_init(&config, _WatchdogEventHandler); APP_ERROR_CHECK(err_code); err_code = nrf_drv_wdt_channel_alloc(&g_watchDogChannelID); APP_ERROR_CHECK(err_code); nrf_drv_wdt_enable(); g_bWatchdogInitialized = true; } void _EPXPlatform_Runtime_WatchdogFeed() { if (g_bWatchdogInitialized) nrf_drv_wdt_channel_feed(g_watchDogChannelID); } extern "C" { char *stristr(const char *subject, const char *object) { int c = tolower(*object); if (c == 0x00) return (char *)subject; for (; *subject; subject++) { if (tolower(*subject) == c) { for (size_t i = 0;;) { if (object[++i] == 0x00) return (char *)subject; if (tolower(subject[i]) != tolower(object[i])) break; } } } return NULL; } int stricmp(const char *s1, const char *s2) { while (1) { char c1 = *s1++; char c2 = *s2++; int diff = tolower(c1) - tolower(c2); if (diff == 0) { if (c1 == 0) return 0; } else return diff; } return 0; } char *epx_strupr(char s[]) { char *p; for (p = s; *p; ++p) *p = toupper(*p); return (s); } /* END STRUPR */ uint32_t millis() { return g_AppTimerTick; } unsigned long micros() { return millis(); } #define OVERFLOWMILLIS ((uint32_t)(0xFFFFFFFF/32.768)) uint32_t millisPassed(uint32_t localMillis) { uint32_t currentMillis = millis(); if (currentMillis < localMillis) return currentMillis + OVERFLOWMILLIS + 1 - localMillis; else return currentMillis - localMillis; } void delay(uint32_t ms) { nrf_delay_ms(ms); } void delayMicroseconds(uint32_t us) { nrf_delay_us(us); } void EPXPlatform_Runtime_Initialize() { _EPXPlatform_Runtime_InitializeAppTimer(); #ifdef USEWATCHDOG _EPXPlatform_Runtime_InitializeWatchdog(); #endif } void EPXPlatform_Runtime_Process() { _EPXPlatform_Runtime_WatchdogFeed(); } } void _EPXPlatform_Runtime_AppTimerHandler(nrf_timer_event_t event_type, void* p_context) { g_AppTimerTick++; } void _EPXPlatform_Runtime_InitializeAppTimer() { g_appTimer.p_reg = NRF_TIMER1; g_appTimer.instance_id = NRFX_TIMER1_INST_IDX; g_appTimer.cc_channel_count = NRF_TIMER_CC_CHANNEL_COUNT(1); nrf_drv_timer_config_t timerConfig = NRF_DRV_TIMER_DEFAULT_CONFIG; timerConfig.p_context = NULL; timerConfig.frequency = NRF_TIMER_FREQ_31250Hz; uint32_t err_code = nrf_drv_timer_init(&g_appTimer, &timerConfig, _EPXPlatform_Runtime_AppTimerHandler); APP_ERROR_CHECK(err_code); nrf_drv_timer_extended_compare(&g_appTimer, NRF_TIMER_CC_CHANNEL0, nrf_drv_timer_ms_to_ticks(&g_appTimer, 1), NRF_TIMER_SHORT_COMPARE0_CLEAR_MASK, true); nrf_drv_timer_enable(&g_appTimer); } void EPXPlatform_Runtime_ControlAppTimer(bool on) { if (on) nrf_drv_timer_enable(&g_appTimer); else nrf_drv_timer_disable(&g_appTimer); } void EPXPlatform_Runtime_MCUSleep() { NRF_LOG_INFO("Sleeping..."); EPXPlatform_Runtime_ControlAppTimer(false); /* uint32_t err_code = sd_app_evt_wait(); APP_ERROR_CHECK(err_code);*/ nrf_pwr_mgmt_run(); NRF_LOG_INFO("Awake!!"); EPXPlatform_Runtime_ControlAppTimer(true); } void EPXPlatform_Runtime_MCUDeepSleep() { NRF_LOG_INFO("Deep Sleeping..."); EPXPlatform_Runtime_ControlAppTimer(false); int ret = sd_power_system_off(); NRF_LOG_INFO("Deep Sleep Awake!! %d", ret); EPXPlatform_Runtime_ControlAppTimer(true); } #ifdef FREERAM #ifdef ARDUINO_ARCH_SAMD extern "C" char *sbrk(int i); int freeRam() { char stack_dummy = 0; return &stack_dummy - sbrk(0); } #else void* _sbrk(ptrdiff_t incr) { extern uint32_t __HeapBase; extern uint32_t __HeapLimit; static char* heap = 0; if (heap == 0) heap = (char*)&__HeapBase; void* ret = heap; if (heap + incr >= (char*)&__HeapLimit) ret = (void*) - 1; else heap += incr; return ret; } #endif int freeRam() { char stack_dummy = 0; return (int)((uint64_t)((void*) &stack_dummy) - (uint64_t) _sbrk(0)); } #endif int freeRam() { return 0; } uint8_t HexToByte(char *hex, int len) { int i = len > 1 && hex[0] == '0' && (hex[1] == 'x' || hex[1] == 'X') ? 2 : 0; uint8_t value = 0; while (i < len) { uint8_t x = hex[i++]; if (x >= '0' && x <= '9') x = x - '0'; else if (x >= 'A' && x <= 'F') x = (x - 'A') + 10; else if (x >= 'a' && x <= 'f') x = (x - 'a') + 10; else return 0; value = 16 * value + x; } return value; } void BytesToHex(uint8_t *p, int cb, char *psz, int stringCB) { int stringOffset = 0; while (cb > 0 && stringCB >= 2) { sprintf(psz + stringOffset, "%02X", *p); p++; stringOffset += 2; cb--; stringCB--; } psz[stringOffset] = 0x00; }
17.899713
158
0.685609
[ "object" ]
eebd9790fb288e2fa7b1a8c2527cbddfde2dcfe7
977
cpp
C++
Matrix.cpp
DokanBoy/c_labs
abdbe073388a59320e21a4ab85ecab031abcf501
[ "Apache-2.0" ]
null
null
null
Matrix.cpp
DokanBoy/c_labs
abdbe073388a59320e21a4ab85ecab031abcf501
[ "Apache-2.0" ]
null
null
null
Matrix.cpp
DokanBoy/c_labs
abdbe073388a59320e21a4ab85ecab031abcf501
[ "Apache-2.0" ]
null
null
null
#include "Stack.cpp" #include <vector> #include <pbt.h> template<typename T> class Matrix { private: std::vector<std::vector<T>> *matrix{}; public: Matrix() { matrix = new std::vector<std::vector<T>>(); } std::vector<std::vector<T>> *getMatrix() { return matrix; } std::vector<std::vector<T>> getRowByIndex(unsigned int index) { return matrix->getByIndex(index); } void pushRow(std::vector<T> row) { matrix->push_back(row); } std::vector<std::vector<T>> topRow() { matrix->at(matrix->size() - 1); } std::vector<std::vector<T>> popRow() { matrix->pop_back(); } void print() { for (int i = 0; i < matrix->size(); ++i) { std::vector<T> vec = matrix->at(i); for (int j = 0; j < vec.size(); ++j) { std::cout << vec.at(j) << " "; } std::cout << std::endl; vec.clear(); } } };
21.711111
67
0.493347
[ "vector" ]
eed2aee901f95de53624267999fcee498c31a3af
2,623
cpp
C++
lib/Grid.cpp
pstefa1707/Conways-Game-Of-Life
41c40a65626e819109cdd5ccb030b7e33c60f6cb
[ "MIT" ]
null
null
null
lib/Grid.cpp
pstefa1707/Conways-Game-Of-Life
41c40a65626e819109cdd5ccb030b7e33c60f6cb
[ "MIT" ]
null
null
null
lib/Grid.cpp
pstefa1707/Conways-Game-Of-Life
41c40a65626e819109cdd5ccb030b7e33c60f6cb
[ "MIT" ]
null
null
null
#include "Grid.hpp" #include "SFML/Graphics.hpp" void Grid::populate() { for (int x = 0; x < this->_width; x++) { for (int y = 0; y < this->_height; y++) { if (rand()%100 < 20) { this->cells[y * this->_width + x] = status::alive; } else { this->cells[y * this->_width + x] = status::dead; } } } } int Grid::height() { return this->_height; } int Grid::width() { return this->_width; } sf::Vector2f Grid::cell_size() { return this->_cell_size; } int Grid::_get_neighbours(int& x_pos, int& y_pos) { unsigned int count = 0; for (int x = -1; x < 2; x++) { for (int y = -1; y < 2; y++) { int new_x = x_pos + x; int new_y = y_pos + y; if (new_x == x_pos && new_y == y_pos) continue; if (new_x < 0) new_x = this->_width + new_x; if (new_y < 0) new_y = this->_height + new_y; if (new_x >= this->_width) new_x = new_x % this->_width; if (new_y >= this->_height) new_y = new_y % this->_height; if (this->cells[new_y * this->_width + new_x] == status::alive) count++; } } return count; } std::vector<sf::Vector2i> Grid::step() { this->_temp = this->cells; std::vector<sf::Vector2i> changed; #pragma omp parallel { std::vector<sf::Vector2i> _changed; #pragma omp for nowait for (int x = 0; x < this->_width; x++) { for (int y = 0; y < this->_height; y++) { int index = y * this->_width + x; unsigned int neighbours = this->_get_neighbours(x, y); switch (this->cells[index]) { case status::alive: if (neighbours <= 1 || neighbours >= 4) { this->_temp[index] = status::dead; _changed.push_back(sf::Vector2i(x, y)); } break; default: if (neighbours == 3) { this->_temp[index] = status::alive; _changed.push_back(sf::Vector2i(x, y)); } break; } } } #pragma omp critical changed.insert(changed.end(), _changed.begin(), _changed.end()); } this->cells = this->_temp; return changed; }
26.765306
84
0.428898
[ "vector" ]
eedbb9360acdd526300f42aa800fa9c88193be93
460,569
cpp
C++
cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_ipv4_dhcpd_cfg.cpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
17
2016-12-02T05:45:49.000Z
2022-02-10T19:32:54.000Z
cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_ipv4_dhcpd_cfg.cpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
2
2017-03-27T15:22:38.000Z
2019-11-05T08:30:16.000Z
cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_ipv4_dhcpd_cfg.cpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
11
2016-12-02T05:45:52.000Z
2019-11-07T08:28:17.000Z
#include <sstream> #include <iostream> #include <ydk/entity_util.hpp> #include "bundle_info.hpp" #include "generated_entity_lookup.hpp" #include "Cisco_IOS_XR_ipv4_dhcpd_cfg.hpp" using namespace ydk; namespace cisco_ios_xr { namespace Cisco_IOS_XR_ipv4_dhcpd_cfg { Ipv4Dhcpd::Ipv4Dhcpd() : enable{YType::empty, "enable"}, outer_cos{YType::uint32, "outer-cos"}, allow_client_id_change{YType::empty, "allow-client-id-change"}, inner_cos{YType::uint32, "inner-cos"} , vrfs(std::make_shared<Ipv4Dhcpd::Vrfs>()) , profiles(std::make_shared<Ipv4Dhcpd::Profiles>()) , database(std::make_shared<Ipv4Dhcpd::Database>()) , interfaces(std::make_shared<Ipv4Dhcpd::Interfaces>()) , duplicate_mac_allowed(nullptr) // presence node , rate_limit(std::make_shared<Ipv4Dhcpd::RateLimit>()) { vrfs->parent = this; profiles->parent = this; database->parent = this; interfaces->parent = this; rate_limit->parent = this; yang_name = "ipv4-dhcpd"; yang_parent_name = "Cisco-IOS-XR-ipv4-dhcpd-cfg"; is_top_level_class = true; has_list_ancestor = false; is_presence_container = true; } Ipv4Dhcpd::~Ipv4Dhcpd() { } bool Ipv4Dhcpd::has_data() const { if (is_presence_container) return true; return enable.is_set || outer_cos.is_set || allow_client_id_change.is_set || inner_cos.is_set || (vrfs != nullptr && vrfs->has_data()) || (profiles != nullptr && profiles->has_data()) || (database != nullptr && database->has_data()) || (interfaces != nullptr && interfaces->has_data()) || (duplicate_mac_allowed != nullptr && duplicate_mac_allowed->has_data()) || (rate_limit != nullptr && rate_limit->has_data()); } bool Ipv4Dhcpd::has_operation() const { return is_set(yfilter) || ydk::is_set(enable.yfilter) || ydk::is_set(outer_cos.yfilter) || ydk::is_set(allow_client_id_change.yfilter) || ydk::is_set(inner_cos.yfilter) || (vrfs != nullptr && vrfs->has_operation()) || (profiles != nullptr && profiles->has_operation()) || (database != nullptr && database->has_operation()) || (interfaces != nullptr && interfaces->has_operation()) || (duplicate_mac_allowed != nullptr && duplicate_mac_allowed->has_operation()) || (rate_limit != nullptr && rate_limit->has_operation()); } std::string Ipv4Dhcpd::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-ipv4-dhcpd-cfg:ipv4-dhcpd"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (enable.is_set || is_set(enable.yfilter)) leaf_name_data.push_back(enable.get_name_leafdata()); if (outer_cos.is_set || is_set(outer_cos.yfilter)) leaf_name_data.push_back(outer_cos.get_name_leafdata()); if (allow_client_id_change.is_set || is_set(allow_client_id_change.yfilter)) leaf_name_data.push_back(allow_client_id_change.get_name_leafdata()); if (inner_cos.is_set || is_set(inner_cos.yfilter)) leaf_name_data.push_back(inner_cos.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "vrfs") { if(vrfs == nullptr) { vrfs = std::make_shared<Ipv4Dhcpd::Vrfs>(); } return vrfs; } if(child_yang_name == "profiles") { if(profiles == nullptr) { profiles = std::make_shared<Ipv4Dhcpd::Profiles>(); } return profiles; } if(child_yang_name == "database") { if(database == nullptr) { database = std::make_shared<Ipv4Dhcpd::Database>(); } return database; } if(child_yang_name == "interfaces") { if(interfaces == nullptr) { interfaces = std::make_shared<Ipv4Dhcpd::Interfaces>(); } return interfaces; } if(child_yang_name == "duplicate-mac-allowed") { if(duplicate_mac_allowed == nullptr) { duplicate_mac_allowed = std::make_shared<Ipv4Dhcpd::DuplicateMacAllowed>(); } return duplicate_mac_allowed; } if(child_yang_name == "rate-limit") { if(rate_limit == nullptr) { rate_limit = std::make_shared<Ipv4Dhcpd::RateLimit>(); } return rate_limit; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(vrfs != nullptr) { _children["vrfs"] = vrfs; } if(profiles != nullptr) { _children["profiles"] = profiles; } if(database != nullptr) { _children["database"] = database; } if(interfaces != nullptr) { _children["interfaces"] = interfaces; } if(duplicate_mac_allowed != nullptr) { _children["duplicate-mac-allowed"] = duplicate_mac_allowed; } if(rate_limit != nullptr) { _children["rate-limit"] = rate_limit; } return _children; } void Ipv4Dhcpd::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "enable") { enable = value; enable.value_namespace = name_space; enable.value_namespace_prefix = name_space_prefix; } if(value_path == "outer-cos") { outer_cos = value; outer_cos.value_namespace = name_space; outer_cos.value_namespace_prefix = name_space_prefix; } if(value_path == "allow-client-id-change") { allow_client_id_change = value; allow_client_id_change.value_namespace = name_space; allow_client_id_change.value_namespace_prefix = name_space_prefix; } if(value_path == "inner-cos") { inner_cos = value; inner_cos.value_namespace = name_space; inner_cos.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "enable") { enable.yfilter = yfilter; } if(value_path == "outer-cos") { outer_cos.yfilter = yfilter; } if(value_path == "allow-client-id-change") { allow_client_id_change.yfilter = yfilter; } if(value_path == "inner-cos") { inner_cos.yfilter = yfilter; } } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::clone_ptr() const { return std::make_shared<Ipv4Dhcpd>(); } std::string Ipv4Dhcpd::get_bundle_yang_models_location() const { return ydk_cisco_ios_xr_models_path; } std::string Ipv4Dhcpd::get_bundle_name() const { return "cisco_ios_xr"; } augment_capabilities_function Ipv4Dhcpd::get_augment_capabilities_function() const { return cisco_ios_xr_augment_lookup_tables; } std::map<std::pair<std::string, std::string>, std::string> Ipv4Dhcpd::get_namespace_identity_lookup() const { return cisco_ios_xr_namespace_identity_lookup; } bool Ipv4Dhcpd::has_leaf_or_child_of_name(const std::string & name) const { if(name == "vrfs" || name == "profiles" || name == "database" || name == "interfaces" || name == "duplicate-mac-allowed" || name == "rate-limit" || name == "enable" || name == "outer-cos" || name == "allow-client-id-change" || name == "inner-cos") return true; return false; } Ipv4Dhcpd::Vrfs::Vrfs() : vrf(this, {"vrf_name"}) { yang_name = "vrfs"; yang_parent_name = "ipv4-dhcpd"; is_top_level_class = false; has_list_ancestor = false; } Ipv4Dhcpd::Vrfs::~Vrfs() { } bool Ipv4Dhcpd::Vrfs::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<vrf.len(); index++) { if(vrf[index]->has_data()) return true; } return false; } bool Ipv4Dhcpd::Vrfs::has_operation() const { for (std::size_t index=0; index<vrf.len(); index++) { if(vrf[index]->has_operation()) return true; } return is_set(yfilter); } std::string Ipv4Dhcpd::Vrfs::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-ipv4-dhcpd-cfg:ipv4-dhcpd/" << get_segment_path(); return path_buffer.str(); } std::string Ipv4Dhcpd::Vrfs::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "vrfs"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Vrfs::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Vrfs::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "vrf") { auto ent_ = std::make_shared<Ipv4Dhcpd::Vrfs::Vrf>(); ent_->parent = this; vrf.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Vrfs::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : vrf.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Ipv4Dhcpd::Vrfs::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Ipv4Dhcpd::Vrfs::set_filter(const std::string & value_path, YFilter yfilter) { } bool Ipv4Dhcpd::Vrfs::has_leaf_or_child_of_name(const std::string & name) const { if(name == "vrf") return true; return false; } Ipv4Dhcpd::Vrfs::Vrf::Vrf() : vrf_name{YType::str, "vrf-name"} , profile(nullptr) // presence node { yang_name = "vrf"; yang_parent_name = "vrfs"; is_top_level_class = false; has_list_ancestor = false; } Ipv4Dhcpd::Vrfs::Vrf::~Vrf() { } bool Ipv4Dhcpd::Vrfs::Vrf::has_data() const { if (is_presence_container) return true; return vrf_name.is_set || (profile != nullptr && profile->has_data()); } bool Ipv4Dhcpd::Vrfs::Vrf::has_operation() const { return is_set(yfilter) || ydk::is_set(vrf_name.yfilter) || (profile != nullptr && profile->has_operation()); } std::string Ipv4Dhcpd::Vrfs::Vrf::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-ipv4-dhcpd-cfg:ipv4-dhcpd/vrfs/" << get_segment_path(); return path_buffer.str(); } std::string Ipv4Dhcpd::Vrfs::Vrf::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "vrf"; ADD_KEY_TOKEN(vrf_name, "vrf-name"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Vrfs::Vrf::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (vrf_name.is_set || is_set(vrf_name.yfilter)) leaf_name_data.push_back(vrf_name.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Vrfs::Vrf::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "profile") { if(profile == nullptr) { profile = std::make_shared<Ipv4Dhcpd::Vrfs::Vrf::Profile>(); } return profile; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Vrfs::Vrf::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(profile != nullptr) { _children["profile"] = profile; } return _children; } void Ipv4Dhcpd::Vrfs::Vrf::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "vrf-name") { vrf_name = value; vrf_name.value_namespace = name_space; vrf_name.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Vrfs::Vrf::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "vrf-name") { vrf_name.yfilter = yfilter; } } bool Ipv4Dhcpd::Vrfs::Vrf::has_leaf_or_child_of_name(const std::string & name) const { if(name == "profile" || name == "vrf-name") return true; return false; } Ipv4Dhcpd::Vrfs::Vrf::Profile::Profile() : vrf_profile_name{YType::str, "vrf-profile-name"}, mode{YType::enumeration, "mode"} { yang_name = "profile"; yang_parent_name = "vrf"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true; } Ipv4Dhcpd::Vrfs::Vrf::Profile::~Profile() { } bool Ipv4Dhcpd::Vrfs::Vrf::Profile::has_data() const { if (is_presence_container) return true; return vrf_profile_name.is_set || mode.is_set; } bool Ipv4Dhcpd::Vrfs::Vrf::Profile::has_operation() const { return is_set(yfilter) || ydk::is_set(vrf_profile_name.yfilter) || ydk::is_set(mode.yfilter); } std::string Ipv4Dhcpd::Vrfs::Vrf::Profile::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "profile"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Vrfs::Vrf::Profile::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (vrf_profile_name.is_set || is_set(vrf_profile_name.yfilter)) leaf_name_data.push_back(vrf_profile_name.get_name_leafdata()); if (mode.is_set || is_set(mode.yfilter)) leaf_name_data.push_back(mode.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Vrfs::Vrf::Profile::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Vrfs::Vrf::Profile::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Vrfs::Vrf::Profile::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "vrf-profile-name") { vrf_profile_name = value; vrf_profile_name.value_namespace = name_space; vrf_profile_name.value_namespace_prefix = name_space_prefix; } if(value_path == "mode") { mode = value; mode.value_namespace = name_space; mode.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Vrfs::Vrf::Profile::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "vrf-profile-name") { vrf_profile_name.yfilter = yfilter; } if(value_path == "mode") { mode.yfilter = yfilter; } } bool Ipv4Dhcpd::Vrfs::Vrf::Profile::has_leaf_or_child_of_name(const std::string & name) const { if(name == "vrf-profile-name" || name == "mode") return true; return false; } Ipv4Dhcpd::Profiles::Profiles() : profile(this, {"profile_name"}) { yang_name = "profiles"; yang_parent_name = "ipv4-dhcpd"; is_top_level_class = false; has_list_ancestor = false; } Ipv4Dhcpd::Profiles::~Profiles() { } bool Ipv4Dhcpd::Profiles::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<profile.len(); index++) { if(profile[index]->has_data()) return true; } return false; } bool Ipv4Dhcpd::Profiles::has_operation() const { for (std::size_t index=0; index<profile.len(); index++) { if(profile[index]->has_operation()) return true; } return is_set(yfilter); } std::string Ipv4Dhcpd::Profiles::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-ipv4-dhcpd-cfg:ipv4-dhcpd/" << get_segment_path(); return path_buffer.str(); } std::string Ipv4Dhcpd::Profiles::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "profiles"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "profile") { auto ent_ = std::make_shared<Ipv4Dhcpd::Profiles::Profile>(); ent_->parent = this; profile.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : profile.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Ipv4Dhcpd::Profiles::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Ipv4Dhcpd::Profiles::set_filter(const std::string & value_path, YFilter yfilter) { } bool Ipv4Dhcpd::Profiles::has_leaf_or_child_of_name(const std::string & name) const { if(name == "profile") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Profile() : profile_name{YType::str, "profile-name"} , modes(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes>()) { modes->parent = this; yang_name = "profile"; yang_parent_name = "profiles"; is_top_level_class = false; has_list_ancestor = false; } Ipv4Dhcpd::Profiles::Profile::~Profile() { } bool Ipv4Dhcpd::Profiles::Profile::has_data() const { if (is_presence_container) return true; return profile_name.is_set || (modes != nullptr && modes->has_data()); } bool Ipv4Dhcpd::Profiles::Profile::has_operation() const { return is_set(yfilter) || ydk::is_set(profile_name.yfilter) || (modes != nullptr && modes->has_operation()); } std::string Ipv4Dhcpd::Profiles::Profile::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-ipv4-dhcpd-cfg:ipv4-dhcpd/profiles/" << get_segment_path(); return path_buffer.str(); } std::string Ipv4Dhcpd::Profiles::Profile::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "profile"; ADD_KEY_TOKEN(profile_name, "profile-name"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (profile_name.is_set || is_set(profile_name.yfilter)) leaf_name_data.push_back(profile_name.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "modes") { if(modes == nullptr) { modes = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes>(); } return modes; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(modes != nullptr) { _children["modes"] = modes; } return _children; } void Ipv4Dhcpd::Profiles::Profile::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "profile-name") { profile_name = value; profile_name.value_namespace = name_space; profile_name.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "profile-name") { profile_name.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::has_leaf_or_child_of_name(const std::string & name) const { if(name == "modes" || name == "profile-name") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Modes() : mode(this, {"mode"}) { yang_name = "modes"; yang_parent_name = "profile"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::~Modes() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<mode.len(); index++) { if(mode[index]->has_data()) return true; } return false; } bool Ipv4Dhcpd::Profiles::Profile::Modes::has_operation() const { for (std::size_t index=0; index<mode.len(); index++) { if(mode[index]->has_operation()) return true; } return is_set(yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "modes"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "mode") { auto ent_ = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode>(); ent_->parent = this; mode.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : mode.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Ipv4Dhcpd::Profiles::Profile::Modes::set_filter(const std::string & value_path, YFilter yfilter) { } bool Ipv4Dhcpd::Profiles::Profile::Modes::has_leaf_or_child_of_name(const std::string & name) const { if(name == "mode") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Mode() : mode{YType::enumeration, "mode"}, enable{YType::empty, "enable"} , snoop(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Snoop>()) , base(nullptr) // presence node , server(nullptr) // presence node , relay(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay>()) , proxy(nullptr) // presence node { snoop->parent = this; relay->parent = this; yang_name = "mode"; yang_parent_name = "modes"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::~Mode() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::has_data() const { if (is_presence_container) return true; return mode.is_set || enable.is_set || (snoop != nullptr && snoop->has_data()) || (base != nullptr && base->has_data()) || (server != nullptr && server->has_data()) || (relay != nullptr && relay->has_data()) || (proxy != nullptr && proxy->has_data()); } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::has_operation() const { return is_set(yfilter) || ydk::is_set(mode.yfilter) || ydk::is_set(enable.yfilter) || (snoop != nullptr && snoop->has_operation()) || (base != nullptr && base->has_operation()) || (server != nullptr && server->has_operation()) || (relay != nullptr && relay->has_operation()) || (proxy != nullptr && proxy->has_operation()); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "mode"; ADD_KEY_TOKEN(mode, "mode"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (mode.is_set || is_set(mode.yfilter)) leaf_name_data.push_back(mode.get_name_leafdata()); if (enable.is_set || is_set(enable.yfilter)) leaf_name_data.push_back(enable.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "snoop") { if(snoop == nullptr) { snoop = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Snoop>(); } return snoop; } if(child_yang_name == "base") { if(base == nullptr) { base = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base>(); } return base; } if(child_yang_name == "server") { if(server == nullptr) { server = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server>(); } return server; } if(child_yang_name == "relay") { if(relay == nullptr) { relay = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay>(); } return relay; } if(child_yang_name == "proxy") { if(proxy == nullptr) { proxy = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy>(); } return proxy; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(snoop != nullptr) { _children["snoop"] = snoop; } if(base != nullptr) { _children["base"] = base; } if(server != nullptr) { _children["server"] = server; } if(relay != nullptr) { _children["relay"] = relay; } if(proxy != nullptr) { _children["proxy"] = proxy; } return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "mode") { mode = value; mode.value_namespace = name_space; mode.value_namespace_prefix = name_space_prefix; } if(value_path == "enable") { enable = value; enable.value_namespace = name_space; enable.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "mode") { mode.yfilter = yfilter; } if(value_path == "enable") { enable.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::has_leaf_or_child_of_name(const std::string & name) const { if(name == "snoop" || name == "base" || name == "server" || name == "relay" || name == "proxy" || name == "mode" || name == "enable") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Snoop::Snoop() : trusted{YType::empty, "trusted"} , relay_information_option(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Snoop::RelayInformationOption>()) { relay_information_option->parent = this; yang_name = "snoop"; yang_parent_name = "mode"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Snoop::~Snoop() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Snoop::has_data() const { if (is_presence_container) return true; return trusted.is_set || (relay_information_option != nullptr && relay_information_option->has_data()); } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Snoop::has_operation() const { return is_set(yfilter) || ydk::is_set(trusted.yfilter) || (relay_information_option != nullptr && relay_information_option->has_operation()); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Snoop::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "snoop"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Snoop::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (trusted.is_set || is_set(trusted.yfilter)) leaf_name_data.push_back(trusted.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Snoop::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "relay-information-option") { if(relay_information_option == nullptr) { relay_information_option = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Snoop::RelayInformationOption>(); } return relay_information_option; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Snoop::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(relay_information_option != nullptr) { _children["relay-information-option"] = relay_information_option; } return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Snoop::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "trusted") { trusted = value; trusted.value_namespace = name_space; trusted.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Snoop::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "trusted") { trusted.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Snoop::has_leaf_or_child_of_name(const std::string & name) const { if(name == "relay-information-option" || name == "trusted") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Snoop::RelayInformationOption::RelayInformationOption() : insert{YType::empty, "insert"}, allow_untrusted{YType::empty, "allow-untrusted"}, policy{YType::enumeration, "policy"} , remote_id(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Snoop::RelayInformationOption::RemoteId>()) { remote_id->parent = this; yang_name = "relay-information-option"; yang_parent_name = "snoop"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Snoop::RelayInformationOption::~RelayInformationOption() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Snoop::RelayInformationOption::has_data() const { if (is_presence_container) return true; return insert.is_set || allow_untrusted.is_set || policy.is_set || (remote_id != nullptr && remote_id->has_data()); } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Snoop::RelayInformationOption::has_operation() const { return is_set(yfilter) || ydk::is_set(insert.yfilter) || ydk::is_set(allow_untrusted.yfilter) || ydk::is_set(policy.yfilter) || (remote_id != nullptr && remote_id->has_operation()); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Snoop::RelayInformationOption::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "relay-information-option"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Snoop::RelayInformationOption::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (insert.is_set || is_set(insert.yfilter)) leaf_name_data.push_back(insert.get_name_leafdata()); if (allow_untrusted.is_set || is_set(allow_untrusted.yfilter)) leaf_name_data.push_back(allow_untrusted.get_name_leafdata()); if (policy.is_set || is_set(policy.yfilter)) leaf_name_data.push_back(policy.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Snoop::RelayInformationOption::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "remote-id") { if(remote_id == nullptr) { remote_id = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Snoop::RelayInformationOption::RemoteId>(); } return remote_id; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Snoop::RelayInformationOption::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(remote_id != nullptr) { _children["remote-id"] = remote_id; } return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Snoop::RelayInformationOption::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "insert") { insert = value; insert.value_namespace = name_space; insert.value_namespace_prefix = name_space_prefix; } if(value_path == "allow-untrusted") { allow_untrusted = value; allow_untrusted.value_namespace = name_space; allow_untrusted.value_namespace_prefix = name_space_prefix; } if(value_path == "policy") { policy = value; policy.value_namespace = name_space; policy.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Snoop::RelayInformationOption::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "insert") { insert.yfilter = yfilter; } if(value_path == "allow-untrusted") { allow_untrusted.yfilter = yfilter; } if(value_path == "policy") { policy.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Snoop::RelayInformationOption::has_leaf_or_child_of_name(const std::string & name) const { if(name == "remote-id" || name == "insert" || name == "allow-untrusted" || name == "policy") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Snoop::RelayInformationOption::RemoteId::RemoteId() : format_type{YType::uint32, "format-type"}, remote_id_value{YType::str, "remote-id-value"} { yang_name = "remote-id"; yang_parent_name = "relay-information-option"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Snoop::RelayInformationOption::RemoteId::~RemoteId() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Snoop::RelayInformationOption::RemoteId::has_data() const { if (is_presence_container) return true; return format_type.is_set || remote_id_value.is_set; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Snoop::RelayInformationOption::RemoteId::has_operation() const { return is_set(yfilter) || ydk::is_set(format_type.yfilter) || ydk::is_set(remote_id_value.yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Snoop::RelayInformationOption::RemoteId::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "remote-id"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Snoop::RelayInformationOption::RemoteId::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (format_type.is_set || is_set(format_type.yfilter)) leaf_name_data.push_back(format_type.get_name_leafdata()); if (remote_id_value.is_set || is_set(remote_id_value.yfilter)) leaf_name_data.push_back(remote_id_value.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Snoop::RelayInformationOption::RemoteId::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Snoop::RelayInformationOption::RemoteId::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Snoop::RelayInformationOption::RemoteId::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "format-type") { format_type = value; format_type.value_namespace = name_space; format_type.value_namespace_prefix = name_space_prefix; } if(value_path == "remote-id-value") { remote_id_value = value; remote_id_value.value_namespace = name_space; remote_id_value.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Snoop::RelayInformationOption::RemoteId::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "format-type") { format_type.yfilter = yfilter; } if(value_path == "remote-id-value") { remote_id_value.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Snoop::RelayInformationOption::RemoteId::has_leaf_or_child_of_name(const std::string & name) const { if(name == "format-type" || name == "remote-id-value") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Base() : enable{YType::empty, "enable"} , default_profile(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::DefaultProfile>()) , match(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match>()) , base_relay_opt(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseRelayOpt>()) , base_match(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch>()) { default_profile->parent = this; match->parent = this; base_relay_opt->parent = this; base_match->parent = this; yang_name = "base"; yang_parent_name = "mode"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::~Base() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::has_data() const { if (is_presence_container) return true; return enable.is_set || (default_profile != nullptr && default_profile->has_data()) || (match != nullptr && match->has_data()) || (base_relay_opt != nullptr && base_relay_opt->has_data()) || (base_match != nullptr && base_match->has_data()); } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::has_operation() const { return is_set(yfilter) || ydk::is_set(enable.yfilter) || (default_profile != nullptr && default_profile->has_operation()) || (match != nullptr && match->has_operation()) || (base_relay_opt != nullptr && base_relay_opt->has_operation()) || (base_match != nullptr && base_match->has_operation()); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "base"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (enable.is_set || is_set(enable.yfilter)) leaf_name_data.push_back(enable.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "default-profile") { if(default_profile == nullptr) { default_profile = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::DefaultProfile>(); } return default_profile; } if(child_yang_name == "match") { if(match == nullptr) { match = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match>(); } return match; } if(child_yang_name == "base-relay-opt") { if(base_relay_opt == nullptr) { base_relay_opt = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseRelayOpt>(); } return base_relay_opt; } if(child_yang_name == "base-match") { if(base_match == nullptr) { base_match = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch>(); } return base_match; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(default_profile != nullptr) { _children["default-profile"] = default_profile; } if(match != nullptr) { _children["match"] = match; } if(base_relay_opt != nullptr) { _children["base-relay-opt"] = base_relay_opt; } if(base_match != nullptr) { _children["base-match"] = base_match; } return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "enable") { enable = value; enable.value_namespace = name_space; enable.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "enable") { enable.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::has_leaf_or_child_of_name(const std::string & name) const { if(name == "default-profile" || name == "match" || name == "base-relay-opt" || name == "base-match" || name == "enable") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::DefaultProfile::DefaultProfile() : profile_name{YType::str, "profile-name"}, profile_mode{YType::uint32, "profile-mode"} { yang_name = "default-profile"; yang_parent_name = "base"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::DefaultProfile::~DefaultProfile() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::DefaultProfile::has_data() const { if (is_presence_container) return true; return profile_name.is_set || profile_mode.is_set; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::DefaultProfile::has_operation() const { return is_set(yfilter) || ydk::is_set(profile_name.yfilter) || ydk::is_set(profile_mode.yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::DefaultProfile::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "default-profile"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::DefaultProfile::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (profile_name.is_set || is_set(profile_name.yfilter)) leaf_name_data.push_back(profile_name.get_name_leafdata()); if (profile_mode.is_set || is_set(profile_mode.yfilter)) leaf_name_data.push_back(profile_mode.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::DefaultProfile::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::DefaultProfile::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::DefaultProfile::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "profile-name") { profile_name = value; profile_name.value_namespace = name_space; profile_name.value_namespace_prefix = name_space_prefix; } if(value_path == "profile-mode") { profile_mode = value; profile_mode.value_namespace = name_space; profile_mode.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::DefaultProfile::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "profile-name") { profile_name.yfilter = yfilter; } if(value_path == "profile-mode") { profile_mode.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::DefaultProfile::has_leaf_or_child_of_name(const std::string & name) const { if(name == "profile-name" || name == "profile-mode") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::Match() : option_filters(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::OptionFilters>()) , def_options(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::DefOptions>()) { option_filters->parent = this; def_options->parent = this; yang_name = "match"; yang_parent_name = "base"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::~Match() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::has_data() const { if (is_presence_container) return true; return (option_filters != nullptr && option_filters->has_data()) || (def_options != nullptr && def_options->has_data()); } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::has_operation() const { return is_set(yfilter) || (option_filters != nullptr && option_filters->has_operation()) || (def_options != nullptr && def_options->has_operation()); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "match"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "option-filters") { if(option_filters == nullptr) { option_filters = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::OptionFilters>(); } return option_filters; } if(child_yang_name == "def-options") { if(def_options == nullptr) { def_options = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::DefOptions>(); } return def_options; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(option_filters != nullptr) { _children["option-filters"] = option_filters; } if(def_options != nullptr) { _children["def-options"] = def_options; } return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::set_filter(const std::string & value_path, YFilter yfilter) { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::has_leaf_or_child_of_name(const std::string & name) const { if(name == "option-filters" || name == "def-options") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::OptionFilters::OptionFilters() : option_filter(this, {"matchoption", "pattern", "format"}) { yang_name = "option-filters"; yang_parent_name = "match"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::OptionFilters::~OptionFilters() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::OptionFilters::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<option_filter.len(); index++) { if(option_filter[index]->has_data()) return true; } return false; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::OptionFilters::has_operation() const { for (std::size_t index=0; index<option_filter.len(); index++) { if(option_filter[index]->has_operation()) return true; } return is_set(yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::OptionFilters::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "option-filters"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::OptionFilters::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::OptionFilters::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "option-filter") { auto ent_ = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::OptionFilters::OptionFilter>(); ent_->parent = this; option_filter.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::OptionFilters::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : option_filter.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::OptionFilters::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::OptionFilters::set_filter(const std::string & value_path, YFilter yfilter) { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::OptionFilters::has_leaf_or_child_of_name(const std::string & name) const { if(name == "option-filter") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::OptionFilters::OptionFilter::OptionFilter() : matchoption{YType::uint32, "matchoption"}, pattern{YType::str, "pattern"}, format{YType::uint32, "format"}, option_action{YType::enumeration, "option-action"} { yang_name = "option-filter"; yang_parent_name = "option-filters"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::OptionFilters::OptionFilter::~OptionFilter() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::OptionFilters::OptionFilter::has_data() const { if (is_presence_container) return true; return matchoption.is_set || pattern.is_set || format.is_set || option_action.is_set; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::OptionFilters::OptionFilter::has_operation() const { return is_set(yfilter) || ydk::is_set(matchoption.yfilter) || ydk::is_set(pattern.yfilter) || ydk::is_set(format.yfilter) || ydk::is_set(option_action.yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::OptionFilters::OptionFilter::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "option-filter"; ADD_KEY_TOKEN(matchoption, "matchoption"); ADD_KEY_TOKEN(pattern, "pattern"); ADD_KEY_TOKEN(format, "format"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::OptionFilters::OptionFilter::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (matchoption.is_set || is_set(matchoption.yfilter)) leaf_name_data.push_back(matchoption.get_name_leafdata()); if (pattern.is_set || is_set(pattern.yfilter)) leaf_name_data.push_back(pattern.get_name_leafdata()); if (format.is_set || is_set(format.yfilter)) leaf_name_data.push_back(format.get_name_leafdata()); if (option_action.is_set || is_set(option_action.yfilter)) leaf_name_data.push_back(option_action.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::OptionFilters::OptionFilter::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::OptionFilters::OptionFilter::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::OptionFilters::OptionFilter::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "matchoption") { matchoption = value; matchoption.value_namespace = name_space; matchoption.value_namespace_prefix = name_space_prefix; } if(value_path == "pattern") { pattern = value; pattern.value_namespace = name_space; pattern.value_namespace_prefix = name_space_prefix; } if(value_path == "format") { format = value; format.value_namespace = name_space; format.value_namespace_prefix = name_space_prefix; } if(value_path == "option-action") { option_action = value; option_action.value_namespace = name_space; option_action.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::OptionFilters::OptionFilter::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "matchoption") { matchoption.yfilter = yfilter; } if(value_path == "pattern") { pattern.yfilter = yfilter; } if(value_path == "format") { format.yfilter = yfilter; } if(value_path == "option-action") { option_action.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::OptionFilters::OptionFilter::has_leaf_or_child_of_name(const std::string & name) const { if(name == "matchoption" || name == "pattern" || name == "format" || name == "option-action") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::DefOptions::DefOptions() : def_option(this, {"def_matchoption"}) { yang_name = "def-options"; yang_parent_name = "match"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::DefOptions::~DefOptions() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::DefOptions::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<def_option.len(); index++) { if(def_option[index]->has_data()) return true; } return false; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::DefOptions::has_operation() const { for (std::size_t index=0; index<def_option.len(); index++) { if(def_option[index]->has_operation()) return true; } return is_set(yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::DefOptions::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "def-options"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::DefOptions::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::DefOptions::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "def-option") { auto ent_ = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::DefOptions::DefOption>(); ent_->parent = this; def_option.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::DefOptions::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : def_option.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::DefOptions::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::DefOptions::set_filter(const std::string & value_path, YFilter yfilter) { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::DefOptions::has_leaf_or_child_of_name(const std::string & name) const { if(name == "def-option") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::DefOptions::DefOption::DefOption() : def_matchoption{YType::uint32, "def-matchoption"}, def_matchaction{YType::enumeration, "def-matchaction"} { yang_name = "def-option"; yang_parent_name = "def-options"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::DefOptions::DefOption::~DefOption() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::DefOptions::DefOption::has_data() const { if (is_presence_container) return true; return def_matchoption.is_set || def_matchaction.is_set; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::DefOptions::DefOption::has_operation() const { return is_set(yfilter) || ydk::is_set(def_matchoption.yfilter) || ydk::is_set(def_matchaction.yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::DefOptions::DefOption::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "def-option"; ADD_KEY_TOKEN(def_matchoption, "def-matchoption"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::DefOptions::DefOption::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (def_matchoption.is_set || is_set(def_matchoption.yfilter)) leaf_name_data.push_back(def_matchoption.get_name_leafdata()); if (def_matchaction.is_set || is_set(def_matchaction.yfilter)) leaf_name_data.push_back(def_matchaction.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::DefOptions::DefOption::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::DefOptions::DefOption::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::DefOptions::DefOption::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "def-matchoption") { def_matchoption = value; def_matchoption.value_namespace = name_space; def_matchoption.value_namespace_prefix = name_space_prefix; } if(value_path == "def-matchaction") { def_matchaction = value; def_matchaction.value_namespace = name_space; def_matchaction.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::DefOptions::DefOption::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "def-matchoption") { def_matchoption.yfilter = yfilter; } if(value_path == "def-matchaction") { def_matchaction.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::Match::DefOptions::DefOption::has_leaf_or_child_of_name(const std::string & name) const { if(name == "def-matchoption" || name == "def-matchaction") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseRelayOpt::BaseRelayOpt() : remote_id{YType::str, "remote-id"}, authenticate{YType::uint32, "authenticate"} { yang_name = "base-relay-opt"; yang_parent_name = "base"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseRelayOpt::~BaseRelayOpt() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseRelayOpt::has_data() const { if (is_presence_container) return true; return remote_id.is_set || authenticate.is_set; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseRelayOpt::has_operation() const { return is_set(yfilter) || ydk::is_set(remote_id.yfilter) || ydk::is_set(authenticate.yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseRelayOpt::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "base-relay-opt"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseRelayOpt::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (remote_id.is_set || is_set(remote_id.yfilter)) leaf_name_data.push_back(remote_id.get_name_leafdata()); if (authenticate.is_set || is_set(authenticate.yfilter)) leaf_name_data.push_back(authenticate.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseRelayOpt::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseRelayOpt::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseRelayOpt::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "remote-id") { remote_id = value; remote_id.value_namespace = name_space; remote_id.value_namespace_prefix = name_space_prefix; } if(value_path == "authenticate") { authenticate = value; authenticate.value_namespace = name_space; authenticate.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseRelayOpt::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "remote-id") { remote_id.yfilter = yfilter; } if(value_path == "authenticate") { authenticate.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseRelayOpt::has_leaf_or_child_of_name(const std::string & name) const { if(name == "remote-id" || name == "authenticate") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::BaseMatch() : options(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::Options>()) { options->parent = this; yang_name = "base-match"; yang_parent_name = "base"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::~BaseMatch() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::has_data() const { if (is_presence_container) return true; return (options != nullptr && options->has_data()); } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::has_operation() const { return is_set(yfilter) || (options != nullptr && options->has_operation()); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "base-match"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "options") { if(options == nullptr) { options = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::Options>(); } return options; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(options != nullptr) { _children["options"] = options; } return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::set_filter(const std::string & value_path, YFilter yfilter) { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::has_leaf_or_child_of_name(const std::string & name) const { if(name == "options") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::Options::Options() : option(this, {"opt60", "opt60_hex_str", "format"}) { yang_name = "options"; yang_parent_name = "base-match"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::Options::~Options() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::Options::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<option.len(); index++) { if(option[index]->has_data()) return true; } return false; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::Options::has_operation() const { for (std::size_t index=0; index<option.len(); index++) { if(option[index]->has_operation()) return true; } return is_set(yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::Options::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "options"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::Options::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::Options::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "option") { auto ent_ = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::Options::Option>(); ent_->parent = this; option.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::Options::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : option.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::Options::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::Options::set_filter(const std::string & value_path, YFilter yfilter) { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::Options::has_leaf_or_child_of_name(const std::string & name) const { if(name == "option") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::Options::Option::Option() : opt60{YType::uint32, "opt60"}, opt60_hex_str{YType::str, "opt60-hex-str"}, format{YType::uint32, "format"} , option_profile(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::Options::Option::OptionProfile>()) { option_profile->parent = this; yang_name = "option"; yang_parent_name = "options"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::Options::Option::~Option() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::Options::Option::has_data() const { if (is_presence_container) return true; return opt60.is_set || opt60_hex_str.is_set || format.is_set || (option_profile != nullptr && option_profile->has_data()); } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::Options::Option::has_operation() const { return is_set(yfilter) || ydk::is_set(opt60.yfilter) || ydk::is_set(opt60_hex_str.yfilter) || ydk::is_set(format.yfilter) || (option_profile != nullptr && option_profile->has_operation()); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::Options::Option::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "option"; ADD_KEY_TOKEN(opt60, "opt60"); ADD_KEY_TOKEN(opt60_hex_str, "opt60-hex-str"); ADD_KEY_TOKEN(format, "format"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::Options::Option::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (opt60.is_set || is_set(opt60.yfilter)) leaf_name_data.push_back(opt60.get_name_leafdata()); if (opt60_hex_str.is_set || is_set(opt60_hex_str.yfilter)) leaf_name_data.push_back(opt60_hex_str.get_name_leafdata()); if (format.is_set || is_set(format.yfilter)) leaf_name_data.push_back(format.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::Options::Option::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "option-profile") { if(option_profile == nullptr) { option_profile = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::Options::Option::OptionProfile>(); } return option_profile; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::Options::Option::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(option_profile != nullptr) { _children["option-profile"] = option_profile; } return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::Options::Option::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "opt60") { opt60 = value; opt60.value_namespace = name_space; opt60.value_namespace_prefix = name_space_prefix; } if(value_path == "opt60-hex-str") { opt60_hex_str = value; opt60_hex_str.value_namespace = name_space; opt60_hex_str.value_namespace_prefix = name_space_prefix; } if(value_path == "format") { format = value; format.value_namespace = name_space; format.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::Options::Option::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "opt60") { opt60.yfilter = yfilter; } if(value_path == "opt60-hex-str") { opt60_hex_str.yfilter = yfilter; } if(value_path == "format") { format.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::Options::Option::has_leaf_or_child_of_name(const std::string & name) const { if(name == "option-profile" || name == "opt60" || name == "opt60-hex-str" || name == "format") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::Options::Option::OptionProfile::OptionProfile() : profile_name{YType::str, "profile-name"}, profile_mode{YType::uint32, "profile-mode"} { yang_name = "option-profile"; yang_parent_name = "option"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::Options::Option::OptionProfile::~OptionProfile() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::Options::Option::OptionProfile::has_data() const { if (is_presence_container) return true; return profile_name.is_set || profile_mode.is_set; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::Options::Option::OptionProfile::has_operation() const { return is_set(yfilter) || ydk::is_set(profile_name.yfilter) || ydk::is_set(profile_mode.yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::Options::Option::OptionProfile::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "option-profile"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::Options::Option::OptionProfile::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (profile_name.is_set || is_set(profile_name.yfilter)) leaf_name_data.push_back(profile_name.get_name_leafdata()); if (profile_mode.is_set || is_set(profile_mode.yfilter)) leaf_name_data.push_back(profile_mode.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::Options::Option::OptionProfile::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::Options::Option::OptionProfile::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::Options::Option::OptionProfile::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "profile-name") { profile_name = value; profile_name.value_namespace = name_space; profile_name.value_namespace_prefix = name_space_prefix; } if(value_path == "profile-mode") { profile_mode = value; profile_mode.value_namespace = name_space; profile_mode.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::Options::Option::OptionProfile::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "profile-name") { profile_name.yfilter = yfilter; } if(value_path == "profile-mode") { profile_mode.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Base::BaseMatch::Options::Option::OptionProfile::has_leaf_or_child_of_name(const std::string & name) const { if(name == "profile-name" || name == "profile-mode") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Server() : server_allow_move{YType::empty, "server-allow-move"}, enable{YType::empty, "enable"}, subnet_mask{YType::str, "subnet-mask"}, pool{YType::str, "pool"}, domain_name{YType::str, "domain-name"}, secure_arp{YType::empty, "secure-arp"}, arp_instal_skip_stdalone{YType::empty, "arp-instal-skip-stdalone"}, boot_filename{YType::str, "boot-filename"}, next_server{YType::str, "next-server"} , server_id_check(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::ServerIdCheck>()) , lease_limit(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::LeaseLimit>()) , requested_ip_address(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::RequestedIpAddress>()) , aaa_server(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::AaaServer>()) , default_routers(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DefaultRouters>()) , delete_binding_on_discover(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DeleteBindingOnDiscover>()) , net_bios_name_servers(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::NetBiosNameServers>()) , match(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match>()) , broadcast_flag(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::BroadcastFlag>()) , session(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Session>()) , classes(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes>()) , relay(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Relay>()) , lease(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Lease>()) , netbios_node_type(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::NetbiosNodeType>()) , dns_servers(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DnsServers>()) , dhcp_to_aaa(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DhcpToAaa>()) , option_codes(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::OptionCodes>()) { server_id_check->parent = this; lease_limit->parent = this; requested_ip_address->parent = this; aaa_server->parent = this; default_routers->parent = this; delete_binding_on_discover->parent = this; net_bios_name_servers->parent = this; match->parent = this; broadcast_flag->parent = this; session->parent = this; classes->parent = this; relay->parent = this; lease->parent = this; netbios_node_type->parent = this; dns_servers->parent = this; dhcp_to_aaa->parent = this; option_codes->parent = this; yang_name = "server"; yang_parent_name = "mode"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::~Server() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::has_data() const { if (is_presence_container) return true; return server_allow_move.is_set || enable.is_set || subnet_mask.is_set || pool.is_set || domain_name.is_set || secure_arp.is_set || arp_instal_skip_stdalone.is_set || boot_filename.is_set || next_server.is_set || (server_id_check != nullptr && server_id_check->has_data()) || (lease_limit != nullptr && lease_limit->has_data()) || (requested_ip_address != nullptr && requested_ip_address->has_data()) || (aaa_server != nullptr && aaa_server->has_data()) || (default_routers != nullptr && default_routers->has_data()) || (delete_binding_on_discover != nullptr && delete_binding_on_discover->has_data()) || (net_bios_name_servers != nullptr && net_bios_name_servers->has_data()) || (match != nullptr && match->has_data()) || (broadcast_flag != nullptr && broadcast_flag->has_data()) || (session != nullptr && session->has_data()) || (classes != nullptr && classes->has_data()) || (relay != nullptr && relay->has_data()) || (lease != nullptr && lease->has_data()) || (netbios_node_type != nullptr && netbios_node_type->has_data()) || (dns_servers != nullptr && dns_servers->has_data()) || (dhcp_to_aaa != nullptr && dhcp_to_aaa->has_data()) || (option_codes != nullptr && option_codes->has_data()); } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::has_operation() const { return is_set(yfilter) || ydk::is_set(server_allow_move.yfilter) || ydk::is_set(enable.yfilter) || ydk::is_set(subnet_mask.yfilter) || ydk::is_set(pool.yfilter) || ydk::is_set(domain_name.yfilter) || ydk::is_set(secure_arp.yfilter) || ydk::is_set(arp_instal_skip_stdalone.yfilter) || ydk::is_set(boot_filename.yfilter) || ydk::is_set(next_server.yfilter) || (server_id_check != nullptr && server_id_check->has_operation()) || (lease_limit != nullptr && lease_limit->has_operation()) || (requested_ip_address != nullptr && requested_ip_address->has_operation()) || (aaa_server != nullptr && aaa_server->has_operation()) || (default_routers != nullptr && default_routers->has_operation()) || (delete_binding_on_discover != nullptr && delete_binding_on_discover->has_operation()) || (net_bios_name_servers != nullptr && net_bios_name_servers->has_operation()) || (match != nullptr && match->has_operation()) || (broadcast_flag != nullptr && broadcast_flag->has_operation()) || (session != nullptr && session->has_operation()) || (classes != nullptr && classes->has_operation()) || (relay != nullptr && relay->has_operation()) || (lease != nullptr && lease->has_operation()) || (netbios_node_type != nullptr && netbios_node_type->has_operation()) || (dns_servers != nullptr && dns_servers->has_operation()) || (dhcp_to_aaa != nullptr && dhcp_to_aaa->has_operation()) || (option_codes != nullptr && option_codes->has_operation()); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "server"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (server_allow_move.is_set || is_set(server_allow_move.yfilter)) leaf_name_data.push_back(server_allow_move.get_name_leafdata()); if (enable.is_set || is_set(enable.yfilter)) leaf_name_data.push_back(enable.get_name_leafdata()); if (subnet_mask.is_set || is_set(subnet_mask.yfilter)) leaf_name_data.push_back(subnet_mask.get_name_leafdata()); if (pool.is_set || is_set(pool.yfilter)) leaf_name_data.push_back(pool.get_name_leafdata()); if (domain_name.is_set || is_set(domain_name.yfilter)) leaf_name_data.push_back(domain_name.get_name_leafdata()); if (secure_arp.is_set || is_set(secure_arp.yfilter)) leaf_name_data.push_back(secure_arp.get_name_leafdata()); if (arp_instal_skip_stdalone.is_set || is_set(arp_instal_skip_stdalone.yfilter)) leaf_name_data.push_back(arp_instal_skip_stdalone.get_name_leafdata()); if (boot_filename.is_set || is_set(boot_filename.yfilter)) leaf_name_data.push_back(boot_filename.get_name_leafdata()); if (next_server.is_set || is_set(next_server.yfilter)) leaf_name_data.push_back(next_server.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "server-id-check") { if(server_id_check == nullptr) { server_id_check = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::ServerIdCheck>(); } return server_id_check; } if(child_yang_name == "lease-limit") { if(lease_limit == nullptr) { lease_limit = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::LeaseLimit>(); } return lease_limit; } if(child_yang_name == "requested-ip-address") { if(requested_ip_address == nullptr) { requested_ip_address = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::RequestedIpAddress>(); } return requested_ip_address; } if(child_yang_name == "aaa-server") { if(aaa_server == nullptr) { aaa_server = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::AaaServer>(); } return aaa_server; } if(child_yang_name == "default-routers") { if(default_routers == nullptr) { default_routers = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DefaultRouters>(); } return default_routers; } if(child_yang_name == "delete-binding-on-discover") { if(delete_binding_on_discover == nullptr) { delete_binding_on_discover = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DeleteBindingOnDiscover>(); } return delete_binding_on_discover; } if(child_yang_name == "net-bios-name-servers") { if(net_bios_name_servers == nullptr) { net_bios_name_servers = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::NetBiosNameServers>(); } return net_bios_name_servers; } if(child_yang_name == "match") { if(match == nullptr) { match = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match>(); } return match; } if(child_yang_name == "broadcast-flag") { if(broadcast_flag == nullptr) { broadcast_flag = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::BroadcastFlag>(); } return broadcast_flag; } if(child_yang_name == "session") { if(session == nullptr) { session = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Session>(); } return session; } if(child_yang_name == "classes") { if(classes == nullptr) { classes = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes>(); } return classes; } if(child_yang_name == "relay") { if(relay == nullptr) { relay = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Relay>(); } return relay; } if(child_yang_name == "lease") { if(lease == nullptr) { lease = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Lease>(); } return lease; } if(child_yang_name == "netbios-node-type") { if(netbios_node_type == nullptr) { netbios_node_type = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::NetbiosNodeType>(); } return netbios_node_type; } if(child_yang_name == "dns-servers") { if(dns_servers == nullptr) { dns_servers = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DnsServers>(); } return dns_servers; } if(child_yang_name == "dhcp-to-aaa") { if(dhcp_to_aaa == nullptr) { dhcp_to_aaa = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DhcpToAaa>(); } return dhcp_to_aaa; } if(child_yang_name == "option-codes") { if(option_codes == nullptr) { option_codes = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::OptionCodes>(); } return option_codes; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(server_id_check != nullptr) { _children["server-id-check"] = server_id_check; } if(lease_limit != nullptr) { _children["lease-limit"] = lease_limit; } if(requested_ip_address != nullptr) { _children["requested-ip-address"] = requested_ip_address; } if(aaa_server != nullptr) { _children["aaa-server"] = aaa_server; } if(default_routers != nullptr) { _children["default-routers"] = default_routers; } if(delete_binding_on_discover != nullptr) { _children["delete-binding-on-discover"] = delete_binding_on_discover; } if(net_bios_name_servers != nullptr) { _children["net-bios-name-servers"] = net_bios_name_servers; } if(match != nullptr) { _children["match"] = match; } if(broadcast_flag != nullptr) { _children["broadcast-flag"] = broadcast_flag; } if(session != nullptr) { _children["session"] = session; } if(classes != nullptr) { _children["classes"] = classes; } if(relay != nullptr) { _children["relay"] = relay; } if(lease != nullptr) { _children["lease"] = lease; } if(netbios_node_type != nullptr) { _children["netbios-node-type"] = netbios_node_type; } if(dns_servers != nullptr) { _children["dns-servers"] = dns_servers; } if(dhcp_to_aaa != nullptr) { _children["dhcp-to-aaa"] = dhcp_to_aaa; } if(option_codes != nullptr) { _children["option-codes"] = option_codes; } return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "server-allow-move") { server_allow_move = value; server_allow_move.value_namespace = name_space; server_allow_move.value_namespace_prefix = name_space_prefix; } if(value_path == "enable") { enable = value; enable.value_namespace = name_space; enable.value_namespace_prefix = name_space_prefix; } if(value_path == "subnet-mask") { subnet_mask = value; subnet_mask.value_namespace = name_space; subnet_mask.value_namespace_prefix = name_space_prefix; } if(value_path == "pool") { pool = value; pool.value_namespace = name_space; pool.value_namespace_prefix = name_space_prefix; } if(value_path == "domain-name") { domain_name = value; domain_name.value_namespace = name_space; domain_name.value_namespace_prefix = name_space_prefix; } if(value_path == "secure-arp") { secure_arp = value; secure_arp.value_namespace = name_space; secure_arp.value_namespace_prefix = name_space_prefix; } if(value_path == "arp-instal-skip-stdalone") { arp_instal_skip_stdalone = value; arp_instal_skip_stdalone.value_namespace = name_space; arp_instal_skip_stdalone.value_namespace_prefix = name_space_prefix; } if(value_path == "boot-filename") { boot_filename = value; boot_filename.value_namespace = name_space; boot_filename.value_namespace_prefix = name_space_prefix; } if(value_path == "next-server") { next_server = value; next_server.value_namespace = name_space; next_server.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "server-allow-move") { server_allow_move.yfilter = yfilter; } if(value_path == "enable") { enable.yfilter = yfilter; } if(value_path == "subnet-mask") { subnet_mask.yfilter = yfilter; } if(value_path == "pool") { pool.yfilter = yfilter; } if(value_path == "domain-name") { domain_name.yfilter = yfilter; } if(value_path == "secure-arp") { secure_arp.yfilter = yfilter; } if(value_path == "arp-instal-skip-stdalone") { arp_instal_skip_stdalone.yfilter = yfilter; } if(value_path == "boot-filename") { boot_filename.yfilter = yfilter; } if(value_path == "next-server") { next_server.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::has_leaf_or_child_of_name(const std::string & name) const { if(name == "server-id-check" || name == "lease-limit" || name == "requested-ip-address" || name == "aaa-server" || name == "default-routers" || name == "delete-binding-on-discover" || name == "net-bios-name-servers" || name == "match" || name == "broadcast-flag" || name == "session" || name == "classes" || name == "relay" || name == "lease" || name == "netbios-node-type" || name == "dns-servers" || name == "dhcp-to-aaa" || name == "option-codes" || name == "server-allow-move" || name == "enable" || name == "subnet-mask" || name == "pool" || name == "domain-name" || name == "secure-arp" || name == "arp-instal-skip-stdalone" || name == "boot-filename" || name == "next-server") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::ServerIdCheck::ServerIdCheck() : check{YType::empty, "check"} { yang_name = "server-id-check"; yang_parent_name = "server"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::ServerIdCheck::~ServerIdCheck() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::ServerIdCheck::has_data() const { if (is_presence_container) return true; return check.is_set; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::ServerIdCheck::has_operation() const { return is_set(yfilter) || ydk::is_set(check.yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::ServerIdCheck::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "server-id-check"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::ServerIdCheck::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (check.is_set || is_set(check.yfilter)) leaf_name_data.push_back(check.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::ServerIdCheck::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::ServerIdCheck::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::ServerIdCheck::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "check") { check = value; check.value_namespace = name_space; check.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::ServerIdCheck::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "check") { check.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::ServerIdCheck::has_leaf_or_child_of_name(const std::string & name) const { if(name == "check") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::LeaseLimit::LeaseLimit() : lease_limit_value{YType::enumeration, "lease-limit-value"}, range{YType::uint32, "range"} { yang_name = "lease-limit"; yang_parent_name = "server"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::LeaseLimit::~LeaseLimit() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::LeaseLimit::has_data() const { if (is_presence_container) return true; return lease_limit_value.is_set || range.is_set; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::LeaseLimit::has_operation() const { return is_set(yfilter) || ydk::is_set(lease_limit_value.yfilter) || ydk::is_set(range.yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::LeaseLimit::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "lease-limit"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::LeaseLimit::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (lease_limit_value.is_set || is_set(lease_limit_value.yfilter)) leaf_name_data.push_back(lease_limit_value.get_name_leafdata()); if (range.is_set || is_set(range.yfilter)) leaf_name_data.push_back(range.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::LeaseLimit::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::LeaseLimit::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::LeaseLimit::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "lease-limit-value") { lease_limit_value = value; lease_limit_value.value_namespace = name_space; lease_limit_value.value_namespace_prefix = name_space_prefix; } if(value_path == "range") { range = value; range.value_namespace = name_space; range.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::LeaseLimit::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "lease-limit-value") { lease_limit_value.yfilter = yfilter; } if(value_path == "range") { range.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::LeaseLimit::has_leaf_or_child_of_name(const std::string & name) const { if(name == "lease-limit-value" || name == "range") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::RequestedIpAddress::RequestedIpAddress() : check{YType::empty, "check"} { yang_name = "requested-ip-address"; yang_parent_name = "server"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::RequestedIpAddress::~RequestedIpAddress() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::RequestedIpAddress::has_data() const { if (is_presence_container) return true; return check.is_set; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::RequestedIpAddress::has_operation() const { return is_set(yfilter) || ydk::is_set(check.yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::RequestedIpAddress::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "requested-ip-address"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::RequestedIpAddress::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (check.is_set || is_set(check.yfilter)) leaf_name_data.push_back(check.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::RequestedIpAddress::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::RequestedIpAddress::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::RequestedIpAddress::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "check") { check = value; check.value_namespace = name_space; check.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::RequestedIpAddress::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "check") { check.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::RequestedIpAddress::has_leaf_or_child_of_name(const std::string & name) const { if(name == "check") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::AaaServer::AaaServer() : dhcp_option(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::AaaServer::DhcpOption>()) { dhcp_option->parent = this; yang_name = "aaa-server"; yang_parent_name = "server"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::AaaServer::~AaaServer() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::AaaServer::has_data() const { if (is_presence_container) return true; return (dhcp_option != nullptr && dhcp_option->has_data()); } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::AaaServer::has_operation() const { return is_set(yfilter) || (dhcp_option != nullptr && dhcp_option->has_operation()); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::AaaServer::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "aaa-server"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::AaaServer::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::AaaServer::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "dhcp-option") { if(dhcp_option == nullptr) { dhcp_option = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::AaaServer::DhcpOption>(); } return dhcp_option; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::AaaServer::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(dhcp_option != nullptr) { _children["dhcp-option"] = dhcp_option; } return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::AaaServer::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::AaaServer::set_filter(const std::string & value_path, YFilter yfilter) { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::AaaServer::has_leaf_or_child_of_name(const std::string & name) const { if(name == "dhcp-option") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::AaaServer::DhcpOption::DhcpOption() : force_insert{YType::empty, "force-insert"} { yang_name = "dhcp-option"; yang_parent_name = "aaa-server"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::AaaServer::DhcpOption::~DhcpOption() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::AaaServer::DhcpOption::has_data() const { if (is_presence_container) return true; return force_insert.is_set; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::AaaServer::DhcpOption::has_operation() const { return is_set(yfilter) || ydk::is_set(force_insert.yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::AaaServer::DhcpOption::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "dhcp-option"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::AaaServer::DhcpOption::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (force_insert.is_set || is_set(force_insert.yfilter)) leaf_name_data.push_back(force_insert.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::AaaServer::DhcpOption::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::AaaServer::DhcpOption::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::AaaServer::DhcpOption::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "force-insert") { force_insert = value; force_insert.value_namespace = name_space; force_insert.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::AaaServer::DhcpOption::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "force-insert") { force_insert.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::AaaServer::DhcpOption::has_leaf_or_child_of_name(const std::string & name) const { if(name == "force-insert") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DefaultRouters::DefaultRouters() : default_router{YType::str, "default-router"} { yang_name = "default-routers"; yang_parent_name = "server"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DefaultRouters::~DefaultRouters() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DefaultRouters::has_data() const { if (is_presence_container) return true; for (auto const & leaf : default_router.getYLeafs()) { if(leaf.is_set) return true; } return false; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DefaultRouters::has_operation() const { for (auto const & leaf : default_router.getYLeafs()) { if(is_set(leaf.yfilter)) return true; } return is_set(yfilter) || ydk::is_set(default_router.yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DefaultRouters::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "default-routers"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DefaultRouters::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; auto default_router_name_datas = default_router.get_name_leafdata(); leaf_name_data.insert(leaf_name_data.end(), default_router_name_datas.begin(), default_router_name_datas.end()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DefaultRouters::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DefaultRouters::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DefaultRouters::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "default-router") { default_router.append(value); } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DefaultRouters::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "default-router") { default_router.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DefaultRouters::has_leaf_or_child_of_name(const std::string & name) const { if(name == "default-router") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DeleteBindingOnDiscover::DeleteBindingOnDiscover() : disable{YType::empty, "disable"} { yang_name = "delete-binding-on-discover"; yang_parent_name = "server"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DeleteBindingOnDiscover::~DeleteBindingOnDiscover() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DeleteBindingOnDiscover::has_data() const { if (is_presence_container) return true; return disable.is_set; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DeleteBindingOnDiscover::has_operation() const { return is_set(yfilter) || ydk::is_set(disable.yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DeleteBindingOnDiscover::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "delete-binding-on-discover"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DeleteBindingOnDiscover::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (disable.is_set || is_set(disable.yfilter)) leaf_name_data.push_back(disable.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DeleteBindingOnDiscover::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DeleteBindingOnDiscover::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DeleteBindingOnDiscover::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "disable") { disable = value; disable.value_namespace = name_space; disable.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DeleteBindingOnDiscover::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "disable") { disable.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DeleteBindingOnDiscover::has_leaf_or_child_of_name(const std::string & name) const { if(name == "disable") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::NetBiosNameServers::NetBiosNameServers() : net_bios_name_server{YType::str, "net-bios-name-server"} { yang_name = "net-bios-name-servers"; yang_parent_name = "server"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::NetBiosNameServers::~NetBiosNameServers() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::NetBiosNameServers::has_data() const { if (is_presence_container) return true; for (auto const & leaf : net_bios_name_server.getYLeafs()) { if(leaf.is_set) return true; } return false; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::NetBiosNameServers::has_operation() const { for (auto const & leaf : net_bios_name_server.getYLeafs()) { if(is_set(leaf.yfilter)) return true; } return is_set(yfilter) || ydk::is_set(net_bios_name_server.yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::NetBiosNameServers::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "net-bios-name-servers"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::NetBiosNameServers::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; auto net_bios_name_server_name_datas = net_bios_name_server.get_name_leafdata(); leaf_name_data.insert(leaf_name_data.end(), net_bios_name_server_name_datas.begin(), net_bios_name_server_name_datas.end()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::NetBiosNameServers::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::NetBiosNameServers::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::NetBiosNameServers::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "net-bios-name-server") { net_bios_name_server.append(value); } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::NetBiosNameServers::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "net-bios-name-server") { net_bios_name_server.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::NetBiosNameServers::has_leaf_or_child_of_name(const std::string & name) const { if(name == "net-bios-name-server") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::Match() : option_defaults(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::OptionDefaults>()) , options(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::Options>()) { option_defaults->parent = this; options->parent = this; yang_name = "match"; yang_parent_name = "server"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::~Match() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::has_data() const { if (is_presence_container) return true; return (option_defaults != nullptr && option_defaults->has_data()) || (options != nullptr && options->has_data()); } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::has_operation() const { return is_set(yfilter) || (option_defaults != nullptr && option_defaults->has_operation()) || (options != nullptr && options->has_operation()); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "match"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "option-defaults") { if(option_defaults == nullptr) { option_defaults = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::OptionDefaults>(); } return option_defaults; } if(child_yang_name == "options") { if(options == nullptr) { options = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::Options>(); } return options; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(option_defaults != nullptr) { _children["option-defaults"] = option_defaults; } if(options != nullptr) { _children["options"] = options; } return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::set_filter(const std::string & value_path, YFilter yfilter) { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::has_leaf_or_child_of_name(const std::string & name) const { if(name == "option-defaults" || name == "options") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::OptionDefaults::OptionDefaults() : option_default(this, {"matchoption"}) { yang_name = "option-defaults"; yang_parent_name = "match"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::OptionDefaults::~OptionDefaults() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::OptionDefaults::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<option_default.len(); index++) { if(option_default[index]->has_data()) return true; } return false; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::OptionDefaults::has_operation() const { for (std::size_t index=0; index<option_default.len(); index++) { if(option_default[index]->has_operation()) return true; } return is_set(yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::OptionDefaults::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "option-defaults"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::OptionDefaults::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::OptionDefaults::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "option-default") { auto ent_ = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::OptionDefaults::OptionDefault>(); ent_->parent = this; option_default.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::OptionDefaults::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : option_default.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::OptionDefaults::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::OptionDefaults::set_filter(const std::string & value_path, YFilter yfilter) { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::OptionDefaults::has_leaf_or_child_of_name(const std::string & name) const { if(name == "option-default") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::OptionDefaults::OptionDefault::OptionDefault() : matchoption{YType::enumeration, "matchoption"}, matchaction{YType::enumeration, "matchaction"} { yang_name = "option-default"; yang_parent_name = "option-defaults"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::OptionDefaults::OptionDefault::~OptionDefault() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::OptionDefaults::OptionDefault::has_data() const { if (is_presence_container) return true; return matchoption.is_set || matchaction.is_set; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::OptionDefaults::OptionDefault::has_operation() const { return is_set(yfilter) || ydk::is_set(matchoption.yfilter) || ydk::is_set(matchaction.yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::OptionDefaults::OptionDefault::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "option-default"; ADD_KEY_TOKEN(matchoption, "matchoption"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::OptionDefaults::OptionDefault::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (matchoption.is_set || is_set(matchoption.yfilter)) leaf_name_data.push_back(matchoption.get_name_leafdata()); if (matchaction.is_set || is_set(matchaction.yfilter)) leaf_name_data.push_back(matchaction.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::OptionDefaults::OptionDefault::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::OptionDefaults::OptionDefault::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::OptionDefaults::OptionDefault::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "matchoption") { matchoption = value; matchoption.value_namespace = name_space; matchoption.value_namespace_prefix = name_space_prefix; } if(value_path == "matchaction") { matchaction = value; matchaction.value_namespace = name_space; matchaction.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::OptionDefaults::OptionDefault::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "matchoption") { matchoption.yfilter = yfilter; } if(value_path == "matchaction") { matchaction.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::OptionDefaults::OptionDefault::has_leaf_or_child_of_name(const std::string & name) const { if(name == "matchoption" || name == "matchaction") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::Options::Options() : option(this, {"matchoption", "pattern", "format"}) { yang_name = "options"; yang_parent_name = "match"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::Options::~Options() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::Options::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<option.len(); index++) { if(option[index]->has_data()) return true; } return false; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::Options::has_operation() const { for (std::size_t index=0; index<option.len(); index++) { if(option[index]->has_operation()) return true; } return is_set(yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::Options::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "options"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::Options::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::Options::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "option") { auto ent_ = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::Options::Option>(); ent_->parent = this; option.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::Options::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : option.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::Options::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::Options::set_filter(const std::string & value_path, YFilter yfilter) { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::Options::has_leaf_or_child_of_name(const std::string & name) const { if(name == "option") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::Options::Option::Option() : matchoption{YType::enumeration, "matchoption"}, pattern{YType::str, "pattern"}, format{YType::uint32, "format"}, matchaction{YType::enumeration, "matchaction"} { yang_name = "option"; yang_parent_name = "options"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::Options::Option::~Option() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::Options::Option::has_data() const { if (is_presence_container) return true; return matchoption.is_set || pattern.is_set || format.is_set || matchaction.is_set; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::Options::Option::has_operation() const { return is_set(yfilter) || ydk::is_set(matchoption.yfilter) || ydk::is_set(pattern.yfilter) || ydk::is_set(format.yfilter) || ydk::is_set(matchaction.yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::Options::Option::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "option"; ADD_KEY_TOKEN(matchoption, "matchoption"); ADD_KEY_TOKEN(pattern, "pattern"); ADD_KEY_TOKEN(format, "format"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::Options::Option::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (matchoption.is_set || is_set(matchoption.yfilter)) leaf_name_data.push_back(matchoption.get_name_leafdata()); if (pattern.is_set || is_set(pattern.yfilter)) leaf_name_data.push_back(pattern.get_name_leafdata()); if (format.is_set || is_set(format.yfilter)) leaf_name_data.push_back(format.get_name_leafdata()); if (matchaction.is_set || is_set(matchaction.yfilter)) leaf_name_data.push_back(matchaction.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::Options::Option::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::Options::Option::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::Options::Option::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "matchoption") { matchoption = value; matchoption.value_namespace = name_space; matchoption.value_namespace_prefix = name_space_prefix; } if(value_path == "pattern") { pattern = value; pattern.value_namespace = name_space; pattern.value_namespace_prefix = name_space_prefix; } if(value_path == "format") { format = value; format.value_namespace = name_space; format.value_namespace_prefix = name_space_prefix; } if(value_path == "matchaction") { matchaction = value; matchaction.value_namespace = name_space; matchaction.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::Options::Option::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "matchoption") { matchoption.yfilter = yfilter; } if(value_path == "pattern") { pattern.yfilter = yfilter; } if(value_path == "format") { format.yfilter = yfilter; } if(value_path == "matchaction") { matchaction.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Match::Options::Option::has_leaf_or_child_of_name(const std::string & name) const { if(name == "matchoption" || name == "pattern" || name == "format" || name == "matchaction") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::BroadcastFlag::BroadcastFlag() : policy{YType::enumeration, "policy"} { yang_name = "broadcast-flag"; yang_parent_name = "server"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::BroadcastFlag::~BroadcastFlag() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::BroadcastFlag::has_data() const { if (is_presence_container) return true; return policy.is_set; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::BroadcastFlag::has_operation() const { return is_set(yfilter) || ydk::is_set(policy.yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::BroadcastFlag::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "broadcast-flag"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::BroadcastFlag::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (policy.is_set || is_set(policy.yfilter)) leaf_name_data.push_back(policy.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::BroadcastFlag::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::BroadcastFlag::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::BroadcastFlag::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "policy") { policy = value; policy.value_namespace = name_space; policy.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::BroadcastFlag::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "policy") { policy.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::BroadcastFlag::has_leaf_or_child_of_name(const std::string & name) const { if(name == "policy") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Session::Session() : throttle_type(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Session::ThrottleType>()) { throttle_type->parent = this; yang_name = "session"; yang_parent_name = "server"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Session::~Session() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Session::has_data() const { if (is_presence_container) return true; return (throttle_type != nullptr && throttle_type->has_data()); } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Session::has_operation() const { return is_set(yfilter) || (throttle_type != nullptr && throttle_type->has_operation()); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Session::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "session"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Session::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Session::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "throttle-type") { if(throttle_type == nullptr) { throttle_type = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Session::ThrottleType>(); } return throttle_type; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Session::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(throttle_type != nullptr) { _children["throttle-type"] = throttle_type; } return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Session::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Session::set_filter(const std::string & value_path, YFilter yfilter) { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Session::has_leaf_or_child_of_name(const std::string & name) const { if(name == "throttle-type") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Session::ThrottleType::ThrottleType() : mac_throttle(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Session::ThrottleType::MacThrottle>()) { mac_throttle->parent = this; yang_name = "throttle-type"; yang_parent_name = "session"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Session::ThrottleType::~ThrottleType() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Session::ThrottleType::has_data() const { if (is_presence_container) return true; return (mac_throttle != nullptr && mac_throttle->has_data()); } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Session::ThrottleType::has_operation() const { return is_set(yfilter) || (mac_throttle != nullptr && mac_throttle->has_operation()); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Session::ThrottleType::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "throttle-type"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Session::ThrottleType::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Session::ThrottleType::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "mac-throttle") { if(mac_throttle == nullptr) { mac_throttle = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Session::ThrottleType::MacThrottle>(); } return mac_throttle; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Session::ThrottleType::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(mac_throttle != nullptr) { _children["mac-throttle"] = mac_throttle; } return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Session::ThrottleType::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Session::ThrottleType::set_filter(const std::string & value_path, YFilter yfilter) { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Session::ThrottleType::has_leaf_or_child_of_name(const std::string & name) const { if(name == "mac-throttle") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Session::ThrottleType::MacThrottle::MacThrottle() : num_discover{YType::uint32, "num-discover"}, num_request{YType::uint32, "num-request"}, num_block{YType::uint32, "num-block"} { yang_name = "mac-throttle"; yang_parent_name = "throttle-type"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Session::ThrottleType::MacThrottle::~MacThrottle() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Session::ThrottleType::MacThrottle::has_data() const { if (is_presence_container) return true; return num_discover.is_set || num_request.is_set || num_block.is_set; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Session::ThrottleType::MacThrottle::has_operation() const { return is_set(yfilter) || ydk::is_set(num_discover.yfilter) || ydk::is_set(num_request.yfilter) || ydk::is_set(num_block.yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Session::ThrottleType::MacThrottle::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "mac-throttle"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Session::ThrottleType::MacThrottle::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (num_discover.is_set || is_set(num_discover.yfilter)) leaf_name_data.push_back(num_discover.get_name_leafdata()); if (num_request.is_set || is_set(num_request.yfilter)) leaf_name_data.push_back(num_request.get_name_leafdata()); if (num_block.is_set || is_set(num_block.yfilter)) leaf_name_data.push_back(num_block.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Session::ThrottleType::MacThrottle::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Session::ThrottleType::MacThrottle::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Session::ThrottleType::MacThrottle::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "num-discover") { num_discover = value; num_discover.value_namespace = name_space; num_discover.value_namespace_prefix = name_space_prefix; } if(value_path == "num-request") { num_request = value; num_request.value_namespace = name_space; num_request.value_namespace_prefix = name_space_prefix; } if(value_path == "num-block") { num_block = value; num_block.value_namespace = name_space; num_block.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Session::ThrottleType::MacThrottle::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "num-discover") { num_discover.yfilter = yfilter; } if(value_path == "num-request") { num_request.yfilter = yfilter; } if(value_path == "num-block") { num_block.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Session::ThrottleType::MacThrottle::has_leaf_or_child_of_name(const std::string & name) const { if(name == "num-discover" || name == "num-request" || name == "num-block") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Classes() : class_(this, {"class_name"}) { yang_name = "classes"; yang_parent_name = "server"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::~Classes() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<class_.len(); index++) { if(class_[index]->has_data()) return true; } return false; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::has_operation() const { for (std::size_t index=0; index<class_.len(); index++) { if(class_[index]->has_operation()) return true; } return is_set(yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "classes"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "class") { auto ent_ = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class>(); ent_->parent = this; class_.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : class_.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::set_filter(const std::string & value_path, YFilter yfilter) { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::has_leaf_or_child_of_name(const std::string & name) const { if(name == "class") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::Class() : class_name{YType::str, "class-name"}, subnet_mask{YType::str, "subnet-mask"}, pool{YType::str, "pool"}, enable{YType::empty, "enable"}, domain_name{YType::str, "domain-name"}, boot_filename{YType::str, "boot-filename"}, next_server{YType::str, "next-server"} , default_routers(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::DefaultRouters>()) , net_bios_name_servers(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::NetBiosNameServers>()) , class_match(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::ClassMatch>()) , lease(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::Lease>()) , netbios_node_type(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::NetbiosNodeType>()) , dns_servers(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::DnsServers>()) , option_codes(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::OptionCodes>()) { default_routers->parent = this; net_bios_name_servers->parent = this; class_match->parent = this; lease->parent = this; netbios_node_type->parent = this; dns_servers->parent = this; option_codes->parent = this; yang_name = "class"; yang_parent_name = "classes"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::~Class() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::has_data() const { if (is_presence_container) return true; return class_name.is_set || subnet_mask.is_set || pool.is_set || enable.is_set || domain_name.is_set || boot_filename.is_set || next_server.is_set || (default_routers != nullptr && default_routers->has_data()) || (net_bios_name_servers != nullptr && net_bios_name_servers->has_data()) || (class_match != nullptr && class_match->has_data()) || (lease != nullptr && lease->has_data()) || (netbios_node_type != nullptr && netbios_node_type->has_data()) || (dns_servers != nullptr && dns_servers->has_data()) || (option_codes != nullptr && option_codes->has_data()); } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::has_operation() const { return is_set(yfilter) || ydk::is_set(class_name.yfilter) || ydk::is_set(subnet_mask.yfilter) || ydk::is_set(pool.yfilter) || ydk::is_set(enable.yfilter) || ydk::is_set(domain_name.yfilter) || ydk::is_set(boot_filename.yfilter) || ydk::is_set(next_server.yfilter) || (default_routers != nullptr && default_routers->has_operation()) || (net_bios_name_servers != nullptr && net_bios_name_servers->has_operation()) || (class_match != nullptr && class_match->has_operation()) || (lease != nullptr && lease->has_operation()) || (netbios_node_type != nullptr && netbios_node_type->has_operation()) || (dns_servers != nullptr && dns_servers->has_operation()) || (option_codes != nullptr && option_codes->has_operation()); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "class"; ADD_KEY_TOKEN(class_name, "class-name"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (class_name.is_set || is_set(class_name.yfilter)) leaf_name_data.push_back(class_name.get_name_leafdata()); if (subnet_mask.is_set || is_set(subnet_mask.yfilter)) leaf_name_data.push_back(subnet_mask.get_name_leafdata()); if (pool.is_set || is_set(pool.yfilter)) leaf_name_data.push_back(pool.get_name_leafdata()); if (enable.is_set || is_set(enable.yfilter)) leaf_name_data.push_back(enable.get_name_leafdata()); if (domain_name.is_set || is_set(domain_name.yfilter)) leaf_name_data.push_back(domain_name.get_name_leafdata()); if (boot_filename.is_set || is_set(boot_filename.yfilter)) leaf_name_data.push_back(boot_filename.get_name_leafdata()); if (next_server.is_set || is_set(next_server.yfilter)) leaf_name_data.push_back(next_server.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "default-routers") { if(default_routers == nullptr) { default_routers = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::DefaultRouters>(); } return default_routers; } if(child_yang_name == "net-bios-name-servers") { if(net_bios_name_servers == nullptr) { net_bios_name_servers = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::NetBiosNameServers>(); } return net_bios_name_servers; } if(child_yang_name == "class-match") { if(class_match == nullptr) { class_match = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::ClassMatch>(); } return class_match; } if(child_yang_name == "lease") { if(lease == nullptr) { lease = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::Lease>(); } return lease; } if(child_yang_name == "netbios-node-type") { if(netbios_node_type == nullptr) { netbios_node_type = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::NetbiosNodeType>(); } return netbios_node_type; } if(child_yang_name == "dns-servers") { if(dns_servers == nullptr) { dns_servers = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::DnsServers>(); } return dns_servers; } if(child_yang_name == "option-codes") { if(option_codes == nullptr) { option_codes = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::OptionCodes>(); } return option_codes; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(default_routers != nullptr) { _children["default-routers"] = default_routers; } if(net_bios_name_servers != nullptr) { _children["net-bios-name-servers"] = net_bios_name_servers; } if(class_match != nullptr) { _children["class-match"] = class_match; } if(lease != nullptr) { _children["lease"] = lease; } if(netbios_node_type != nullptr) { _children["netbios-node-type"] = netbios_node_type; } if(dns_servers != nullptr) { _children["dns-servers"] = dns_servers; } if(option_codes != nullptr) { _children["option-codes"] = option_codes; } return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "class-name") { class_name = value; class_name.value_namespace = name_space; class_name.value_namespace_prefix = name_space_prefix; } if(value_path == "subnet-mask") { subnet_mask = value; subnet_mask.value_namespace = name_space; subnet_mask.value_namespace_prefix = name_space_prefix; } if(value_path == "pool") { pool = value; pool.value_namespace = name_space; pool.value_namespace_prefix = name_space_prefix; } if(value_path == "enable") { enable = value; enable.value_namespace = name_space; enable.value_namespace_prefix = name_space_prefix; } if(value_path == "domain-name") { domain_name = value; domain_name.value_namespace = name_space; domain_name.value_namespace_prefix = name_space_prefix; } if(value_path == "boot-filename") { boot_filename = value; boot_filename.value_namespace = name_space; boot_filename.value_namespace_prefix = name_space_prefix; } if(value_path == "next-server") { next_server = value; next_server.value_namespace = name_space; next_server.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "class-name") { class_name.yfilter = yfilter; } if(value_path == "subnet-mask") { subnet_mask.yfilter = yfilter; } if(value_path == "pool") { pool.yfilter = yfilter; } if(value_path == "enable") { enable.yfilter = yfilter; } if(value_path == "domain-name") { domain_name.yfilter = yfilter; } if(value_path == "boot-filename") { boot_filename.yfilter = yfilter; } if(value_path == "next-server") { next_server.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::has_leaf_or_child_of_name(const std::string & name) const { if(name == "default-routers" || name == "net-bios-name-servers" || name == "class-match" || name == "lease" || name == "netbios-node-type" || name == "dns-servers" || name == "option-codes" || name == "class-name" || name == "subnet-mask" || name == "pool" || name == "enable" || name == "domain-name" || name == "boot-filename" || name == "next-server") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::DefaultRouters::DefaultRouters() : default_router{YType::str, "default-router"} { yang_name = "default-routers"; yang_parent_name = "class"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::DefaultRouters::~DefaultRouters() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::DefaultRouters::has_data() const { if (is_presence_container) return true; for (auto const & leaf : default_router.getYLeafs()) { if(leaf.is_set) return true; } return false; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::DefaultRouters::has_operation() const { for (auto const & leaf : default_router.getYLeafs()) { if(is_set(leaf.yfilter)) return true; } return is_set(yfilter) || ydk::is_set(default_router.yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::DefaultRouters::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "default-routers"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::DefaultRouters::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; auto default_router_name_datas = default_router.get_name_leafdata(); leaf_name_data.insert(leaf_name_data.end(), default_router_name_datas.begin(), default_router_name_datas.end()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::DefaultRouters::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::DefaultRouters::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::DefaultRouters::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "default-router") { default_router.append(value); } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::DefaultRouters::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "default-router") { default_router.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::DefaultRouters::has_leaf_or_child_of_name(const std::string & name) const { if(name == "default-router") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::NetBiosNameServers::NetBiosNameServers() : net_bios_name_server{YType::str, "net-bios-name-server"} { yang_name = "net-bios-name-servers"; yang_parent_name = "class"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::NetBiosNameServers::~NetBiosNameServers() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::NetBiosNameServers::has_data() const { if (is_presence_container) return true; for (auto const & leaf : net_bios_name_server.getYLeafs()) { if(leaf.is_set) return true; } return false; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::NetBiosNameServers::has_operation() const { for (auto const & leaf : net_bios_name_server.getYLeafs()) { if(is_set(leaf.yfilter)) return true; } return is_set(yfilter) || ydk::is_set(net_bios_name_server.yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::NetBiosNameServers::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "net-bios-name-servers"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::NetBiosNameServers::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; auto net_bios_name_server_name_datas = net_bios_name_server.get_name_leafdata(); leaf_name_data.insert(leaf_name_data.end(), net_bios_name_server_name_datas.begin(), net_bios_name_server_name_datas.end()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::NetBiosNameServers::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::NetBiosNameServers::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::NetBiosNameServers::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "net-bios-name-server") { net_bios_name_server.append(value); } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::NetBiosNameServers::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "net-bios-name-server") { net_bios_name_server.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::NetBiosNameServers::has_leaf_or_child_of_name(const std::string & name) const { if(name == "net-bios-name-server") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::ClassMatch::ClassMatch() : l2_interface{YType::str, "l2-interface"}, vrf{YType::str, "vrf"} , class_options(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::ClassMatch::ClassOptions>()) { class_options->parent = this; yang_name = "class-match"; yang_parent_name = "class"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::ClassMatch::~ClassMatch() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::ClassMatch::has_data() const { if (is_presence_container) return true; return l2_interface.is_set || vrf.is_set || (class_options != nullptr && class_options->has_data()); } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::ClassMatch::has_operation() const { return is_set(yfilter) || ydk::is_set(l2_interface.yfilter) || ydk::is_set(vrf.yfilter) || (class_options != nullptr && class_options->has_operation()); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::ClassMatch::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "class-match"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::ClassMatch::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (l2_interface.is_set || is_set(l2_interface.yfilter)) leaf_name_data.push_back(l2_interface.get_name_leafdata()); if (vrf.is_set || is_set(vrf.yfilter)) leaf_name_data.push_back(vrf.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::ClassMatch::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "class-options") { if(class_options == nullptr) { class_options = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::ClassMatch::ClassOptions>(); } return class_options; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::ClassMatch::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(class_options != nullptr) { _children["class-options"] = class_options; } return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::ClassMatch::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "l2-interface") { l2_interface = value; l2_interface.value_namespace = name_space; l2_interface.value_namespace_prefix = name_space_prefix; } if(value_path == "vrf") { vrf = value; vrf.value_namespace = name_space; vrf.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::ClassMatch::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "l2-interface") { l2_interface.yfilter = yfilter; } if(value_path == "vrf") { vrf.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::ClassMatch::has_leaf_or_child_of_name(const std::string & name) const { if(name == "class-options" || name == "l2-interface" || name == "vrf") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::ClassMatch::ClassOptions::ClassOptions() : class_option(this, {"matchoption"}) { yang_name = "class-options"; yang_parent_name = "class-match"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::ClassMatch::ClassOptions::~ClassOptions() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::ClassMatch::ClassOptions::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<class_option.len(); index++) { if(class_option[index]->has_data()) return true; } return false; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::ClassMatch::ClassOptions::has_operation() const { for (std::size_t index=0; index<class_option.len(); index++) { if(class_option[index]->has_operation()) return true; } return is_set(yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::ClassMatch::ClassOptions::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "class-options"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::ClassMatch::ClassOptions::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::ClassMatch::ClassOptions::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "class-option") { auto ent_ = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::ClassMatch::ClassOptions::ClassOption>(); ent_->parent = this; class_option.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::ClassMatch::ClassOptions::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : class_option.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::ClassMatch::ClassOptions::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::ClassMatch::ClassOptions::set_filter(const std::string & value_path, YFilter yfilter) { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::ClassMatch::ClassOptions::has_leaf_or_child_of_name(const std::string & name) const { if(name == "class-option") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::ClassMatch::ClassOptions::ClassOption::ClassOption() : matchoption{YType::enumeration, "matchoption"}, pattern{YType::str, "pattern"}, bit_mask{YType::str, "bit-mask"} { yang_name = "class-option"; yang_parent_name = "class-options"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::ClassMatch::ClassOptions::ClassOption::~ClassOption() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::ClassMatch::ClassOptions::ClassOption::has_data() const { if (is_presence_container) return true; return matchoption.is_set || pattern.is_set || bit_mask.is_set; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::ClassMatch::ClassOptions::ClassOption::has_operation() const { return is_set(yfilter) || ydk::is_set(matchoption.yfilter) || ydk::is_set(pattern.yfilter) || ydk::is_set(bit_mask.yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::ClassMatch::ClassOptions::ClassOption::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "class-option"; ADD_KEY_TOKEN(matchoption, "matchoption"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::ClassMatch::ClassOptions::ClassOption::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (matchoption.is_set || is_set(matchoption.yfilter)) leaf_name_data.push_back(matchoption.get_name_leafdata()); if (pattern.is_set || is_set(pattern.yfilter)) leaf_name_data.push_back(pattern.get_name_leafdata()); if (bit_mask.is_set || is_set(bit_mask.yfilter)) leaf_name_data.push_back(bit_mask.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::ClassMatch::ClassOptions::ClassOption::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::ClassMatch::ClassOptions::ClassOption::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::ClassMatch::ClassOptions::ClassOption::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "matchoption") { matchoption = value; matchoption.value_namespace = name_space; matchoption.value_namespace_prefix = name_space_prefix; } if(value_path == "pattern") { pattern = value; pattern.value_namespace = name_space; pattern.value_namespace_prefix = name_space_prefix; } if(value_path == "bit-mask") { bit_mask = value; bit_mask.value_namespace = name_space; bit_mask.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::ClassMatch::ClassOptions::ClassOption::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "matchoption") { matchoption.yfilter = yfilter; } if(value_path == "pattern") { pattern.yfilter = yfilter; } if(value_path == "bit-mask") { bit_mask.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::ClassMatch::ClassOptions::ClassOption::has_leaf_or_child_of_name(const std::string & name) const { if(name == "matchoption" || name == "pattern" || name == "bit-mask") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::Lease::Lease() : infinite{YType::str, "infinite"}, days{YType::uint32, "days"}, hours{YType::uint32, "hours"}, minutes{YType::uint32, "minutes"} { yang_name = "lease"; yang_parent_name = "class"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::Lease::~Lease() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::Lease::has_data() const { if (is_presence_container) return true; return infinite.is_set || days.is_set || hours.is_set || minutes.is_set; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::Lease::has_operation() const { return is_set(yfilter) || ydk::is_set(infinite.yfilter) || ydk::is_set(days.yfilter) || ydk::is_set(hours.yfilter) || ydk::is_set(minutes.yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::Lease::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "lease"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::Lease::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (infinite.is_set || is_set(infinite.yfilter)) leaf_name_data.push_back(infinite.get_name_leafdata()); if (days.is_set || is_set(days.yfilter)) leaf_name_data.push_back(days.get_name_leafdata()); if (hours.is_set || is_set(hours.yfilter)) leaf_name_data.push_back(hours.get_name_leafdata()); if (minutes.is_set || is_set(minutes.yfilter)) leaf_name_data.push_back(minutes.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::Lease::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::Lease::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::Lease::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "infinite") { infinite = value; infinite.value_namespace = name_space; infinite.value_namespace_prefix = name_space_prefix; } if(value_path == "days") { days = value; days.value_namespace = name_space; days.value_namespace_prefix = name_space_prefix; } if(value_path == "hours") { hours = value; hours.value_namespace = name_space; hours.value_namespace_prefix = name_space_prefix; } if(value_path == "minutes") { minutes = value; minutes.value_namespace = name_space; minutes.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::Lease::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "infinite") { infinite.yfilter = yfilter; } if(value_path == "days") { days.yfilter = yfilter; } if(value_path == "hours") { hours.yfilter = yfilter; } if(value_path == "minutes") { minutes.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::Lease::has_leaf_or_child_of_name(const std::string & name) const { if(name == "infinite" || name == "days" || name == "hours" || name == "minutes") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::NetbiosNodeType::NetbiosNodeType() : broadcast_node{YType::str, "broadcast-node"}, hybrid_node{YType::str, "hybrid-node"}, mixed_node{YType::str, "mixed-node"}, peer_to_peer_node{YType::str, "peer-to-peer-node"}, hexadecimal{YType::str, "hexadecimal"} { yang_name = "netbios-node-type"; yang_parent_name = "class"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::NetbiosNodeType::~NetbiosNodeType() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::NetbiosNodeType::has_data() const { if (is_presence_container) return true; return broadcast_node.is_set || hybrid_node.is_set || mixed_node.is_set || peer_to_peer_node.is_set || hexadecimal.is_set; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::NetbiosNodeType::has_operation() const { return is_set(yfilter) || ydk::is_set(broadcast_node.yfilter) || ydk::is_set(hybrid_node.yfilter) || ydk::is_set(mixed_node.yfilter) || ydk::is_set(peer_to_peer_node.yfilter) || ydk::is_set(hexadecimal.yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::NetbiosNodeType::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "netbios-node-type"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::NetbiosNodeType::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (broadcast_node.is_set || is_set(broadcast_node.yfilter)) leaf_name_data.push_back(broadcast_node.get_name_leafdata()); if (hybrid_node.is_set || is_set(hybrid_node.yfilter)) leaf_name_data.push_back(hybrid_node.get_name_leafdata()); if (mixed_node.is_set || is_set(mixed_node.yfilter)) leaf_name_data.push_back(mixed_node.get_name_leafdata()); if (peer_to_peer_node.is_set || is_set(peer_to_peer_node.yfilter)) leaf_name_data.push_back(peer_to_peer_node.get_name_leafdata()); if (hexadecimal.is_set || is_set(hexadecimal.yfilter)) leaf_name_data.push_back(hexadecimal.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::NetbiosNodeType::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::NetbiosNodeType::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::NetbiosNodeType::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "broadcast-node") { broadcast_node = value; broadcast_node.value_namespace = name_space; broadcast_node.value_namespace_prefix = name_space_prefix; } if(value_path == "hybrid-node") { hybrid_node = value; hybrid_node.value_namespace = name_space; hybrid_node.value_namespace_prefix = name_space_prefix; } if(value_path == "mixed-node") { mixed_node = value; mixed_node.value_namespace = name_space; mixed_node.value_namespace_prefix = name_space_prefix; } if(value_path == "peer-to-peer-node") { peer_to_peer_node = value; peer_to_peer_node.value_namespace = name_space; peer_to_peer_node.value_namespace_prefix = name_space_prefix; } if(value_path == "hexadecimal") { hexadecimal = value; hexadecimal.value_namespace = name_space; hexadecimal.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::NetbiosNodeType::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "broadcast-node") { broadcast_node.yfilter = yfilter; } if(value_path == "hybrid-node") { hybrid_node.yfilter = yfilter; } if(value_path == "mixed-node") { mixed_node.yfilter = yfilter; } if(value_path == "peer-to-peer-node") { peer_to_peer_node.yfilter = yfilter; } if(value_path == "hexadecimal") { hexadecimal.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::NetbiosNodeType::has_leaf_or_child_of_name(const std::string & name) const { if(name == "broadcast-node" || name == "hybrid-node" || name == "mixed-node" || name == "peer-to-peer-node" || name == "hexadecimal") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::DnsServers::DnsServers() : dns_server{YType::str, "dns-server"} { yang_name = "dns-servers"; yang_parent_name = "class"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::DnsServers::~DnsServers() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::DnsServers::has_data() const { if (is_presence_container) return true; for (auto const & leaf : dns_server.getYLeafs()) { if(leaf.is_set) return true; } return false; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::DnsServers::has_operation() const { for (auto const & leaf : dns_server.getYLeafs()) { if(is_set(leaf.yfilter)) return true; } return is_set(yfilter) || ydk::is_set(dns_server.yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::DnsServers::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "dns-servers"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::DnsServers::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; auto dns_server_name_datas = dns_server.get_name_leafdata(); leaf_name_data.insert(leaf_name_data.end(), dns_server_name_datas.begin(), dns_server_name_datas.end()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::DnsServers::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::DnsServers::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::DnsServers::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "dns-server") { dns_server.append(value); } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::DnsServers::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "dns-server") { dns_server.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::DnsServers::has_leaf_or_child_of_name(const std::string & name) const { if(name == "dns-server") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::OptionCodes::OptionCodes() : option_code(this, {"option_code"}) { yang_name = "option-codes"; yang_parent_name = "class"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::OptionCodes::~OptionCodes() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::OptionCodes::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<option_code.len(); index++) { if(option_code[index]->has_data()) return true; } return false; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::OptionCodes::has_operation() const { for (std::size_t index=0; index<option_code.len(); index++) { if(option_code[index]->has_operation()) return true; } return is_set(yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::OptionCodes::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "option-codes"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::OptionCodes::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::OptionCodes::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "option-code") { auto ent_ = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::OptionCodes::OptionCode>(); ent_->parent = this; option_code.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::OptionCodes::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : option_code.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::OptionCodes::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::OptionCodes::set_filter(const std::string & value_path, YFilter yfilter) { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::OptionCodes::has_leaf_or_child_of_name(const std::string & name) const { if(name == "option-code") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::OptionCodes::OptionCode::OptionCode() : option_code{YType::uint32, "option-code"}, ascii_string{YType::str, "ascii-string"}, hex_string{YType::str, "hex-string"}, force_insert{YType::uint32, "force-insert"}, ip_address{YType::str, "ip-address"} { yang_name = "option-code"; yang_parent_name = "option-codes"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::OptionCodes::OptionCode::~OptionCode() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::OptionCodes::OptionCode::has_data() const { if (is_presence_container) return true; for (auto const & leaf : ip_address.getYLeafs()) { if(leaf.is_set) return true; } return option_code.is_set || ascii_string.is_set || hex_string.is_set || force_insert.is_set; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::OptionCodes::OptionCode::has_operation() const { for (auto const & leaf : ip_address.getYLeafs()) { if(is_set(leaf.yfilter)) return true; } return is_set(yfilter) || ydk::is_set(option_code.yfilter) || ydk::is_set(ascii_string.yfilter) || ydk::is_set(hex_string.yfilter) || ydk::is_set(force_insert.yfilter) || ydk::is_set(ip_address.yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::OptionCodes::OptionCode::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "option-code"; ADD_KEY_TOKEN(option_code, "option-code"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::OptionCodes::OptionCode::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (option_code.is_set || is_set(option_code.yfilter)) leaf_name_data.push_back(option_code.get_name_leafdata()); if (ascii_string.is_set || is_set(ascii_string.yfilter)) leaf_name_data.push_back(ascii_string.get_name_leafdata()); if (hex_string.is_set || is_set(hex_string.yfilter)) leaf_name_data.push_back(hex_string.get_name_leafdata()); if (force_insert.is_set || is_set(force_insert.yfilter)) leaf_name_data.push_back(force_insert.get_name_leafdata()); auto ip_address_name_datas = ip_address.get_name_leafdata(); leaf_name_data.insert(leaf_name_data.end(), ip_address_name_datas.begin(), ip_address_name_datas.end()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::OptionCodes::OptionCode::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::OptionCodes::OptionCode::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::OptionCodes::OptionCode::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "option-code") { option_code = value; option_code.value_namespace = name_space; option_code.value_namespace_prefix = name_space_prefix; } if(value_path == "ascii-string") { ascii_string = value; ascii_string.value_namespace = name_space; ascii_string.value_namespace_prefix = name_space_prefix; } if(value_path == "hex-string") { hex_string = value; hex_string.value_namespace = name_space; hex_string.value_namespace_prefix = name_space_prefix; } if(value_path == "force-insert") { force_insert = value; force_insert.value_namespace = name_space; force_insert.value_namespace_prefix = name_space_prefix; } if(value_path == "ip-address") { ip_address.append(value); } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::OptionCodes::OptionCode::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "option-code") { option_code.yfilter = yfilter; } if(value_path == "ascii-string") { ascii_string.yfilter = yfilter; } if(value_path == "hex-string") { hex_string.yfilter = yfilter; } if(value_path == "force-insert") { force_insert.yfilter = yfilter; } if(value_path == "ip-address") { ip_address.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Classes::Class::OptionCodes::OptionCode::has_leaf_or_child_of_name(const std::string & name) const { if(name == "option-code" || name == "ascii-string" || name == "hex-string" || name == "force-insert" || name == "ip-address") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Relay::Relay() : authenticate{YType::uint32, "authenticate"} { yang_name = "relay"; yang_parent_name = "server"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Relay::~Relay() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Relay::has_data() const { if (is_presence_container) return true; return authenticate.is_set; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Relay::has_operation() const { return is_set(yfilter) || ydk::is_set(authenticate.yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Relay::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "relay"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Relay::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (authenticate.is_set || is_set(authenticate.yfilter)) leaf_name_data.push_back(authenticate.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Relay::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Relay::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Relay::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "authenticate") { authenticate = value; authenticate.value_namespace = name_space; authenticate.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Relay::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "authenticate") { authenticate.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Relay::has_leaf_or_child_of_name(const std::string & name) const { if(name == "authenticate") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Lease::Lease() : infinite{YType::str, "infinite"}, days{YType::uint32, "days"}, hours{YType::uint32, "hours"}, minutes{YType::uint32, "minutes"} { yang_name = "lease"; yang_parent_name = "server"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Lease::~Lease() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Lease::has_data() const { if (is_presence_container) return true; return infinite.is_set || days.is_set || hours.is_set || minutes.is_set; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Lease::has_operation() const { return is_set(yfilter) || ydk::is_set(infinite.yfilter) || ydk::is_set(days.yfilter) || ydk::is_set(hours.yfilter) || ydk::is_set(minutes.yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Lease::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "lease"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Lease::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (infinite.is_set || is_set(infinite.yfilter)) leaf_name_data.push_back(infinite.get_name_leafdata()); if (days.is_set || is_set(days.yfilter)) leaf_name_data.push_back(days.get_name_leafdata()); if (hours.is_set || is_set(hours.yfilter)) leaf_name_data.push_back(hours.get_name_leafdata()); if (minutes.is_set || is_set(minutes.yfilter)) leaf_name_data.push_back(minutes.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Lease::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Lease::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Lease::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "infinite") { infinite = value; infinite.value_namespace = name_space; infinite.value_namespace_prefix = name_space_prefix; } if(value_path == "days") { days = value; days.value_namespace = name_space; days.value_namespace_prefix = name_space_prefix; } if(value_path == "hours") { hours = value; hours.value_namespace = name_space; hours.value_namespace_prefix = name_space_prefix; } if(value_path == "minutes") { minutes = value; minutes.value_namespace = name_space; minutes.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Lease::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "infinite") { infinite.yfilter = yfilter; } if(value_path == "days") { days.yfilter = yfilter; } if(value_path == "hours") { hours.yfilter = yfilter; } if(value_path == "minutes") { minutes.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::Lease::has_leaf_or_child_of_name(const std::string & name) const { if(name == "infinite" || name == "days" || name == "hours" || name == "minutes") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::NetbiosNodeType::NetbiosNodeType() : broadcast_node{YType::str, "broadcast-node"}, hybrid_node{YType::str, "hybrid-node"}, mixed_node{YType::str, "mixed-node"}, peer_to_peer_node{YType::str, "peer-to-peer-node"}, hexadecimal{YType::str, "hexadecimal"} { yang_name = "netbios-node-type"; yang_parent_name = "server"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::NetbiosNodeType::~NetbiosNodeType() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::NetbiosNodeType::has_data() const { if (is_presence_container) return true; return broadcast_node.is_set || hybrid_node.is_set || mixed_node.is_set || peer_to_peer_node.is_set || hexadecimal.is_set; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::NetbiosNodeType::has_operation() const { return is_set(yfilter) || ydk::is_set(broadcast_node.yfilter) || ydk::is_set(hybrid_node.yfilter) || ydk::is_set(mixed_node.yfilter) || ydk::is_set(peer_to_peer_node.yfilter) || ydk::is_set(hexadecimal.yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::NetbiosNodeType::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "netbios-node-type"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::NetbiosNodeType::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (broadcast_node.is_set || is_set(broadcast_node.yfilter)) leaf_name_data.push_back(broadcast_node.get_name_leafdata()); if (hybrid_node.is_set || is_set(hybrid_node.yfilter)) leaf_name_data.push_back(hybrid_node.get_name_leafdata()); if (mixed_node.is_set || is_set(mixed_node.yfilter)) leaf_name_data.push_back(mixed_node.get_name_leafdata()); if (peer_to_peer_node.is_set || is_set(peer_to_peer_node.yfilter)) leaf_name_data.push_back(peer_to_peer_node.get_name_leafdata()); if (hexadecimal.is_set || is_set(hexadecimal.yfilter)) leaf_name_data.push_back(hexadecimal.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::NetbiosNodeType::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::NetbiosNodeType::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::NetbiosNodeType::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "broadcast-node") { broadcast_node = value; broadcast_node.value_namespace = name_space; broadcast_node.value_namespace_prefix = name_space_prefix; } if(value_path == "hybrid-node") { hybrid_node = value; hybrid_node.value_namespace = name_space; hybrid_node.value_namespace_prefix = name_space_prefix; } if(value_path == "mixed-node") { mixed_node = value; mixed_node.value_namespace = name_space; mixed_node.value_namespace_prefix = name_space_prefix; } if(value_path == "peer-to-peer-node") { peer_to_peer_node = value; peer_to_peer_node.value_namespace = name_space; peer_to_peer_node.value_namespace_prefix = name_space_prefix; } if(value_path == "hexadecimal") { hexadecimal = value; hexadecimal.value_namespace = name_space; hexadecimal.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::NetbiosNodeType::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "broadcast-node") { broadcast_node.yfilter = yfilter; } if(value_path == "hybrid-node") { hybrid_node.yfilter = yfilter; } if(value_path == "mixed-node") { mixed_node.yfilter = yfilter; } if(value_path == "peer-to-peer-node") { peer_to_peer_node.yfilter = yfilter; } if(value_path == "hexadecimal") { hexadecimal.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::NetbiosNodeType::has_leaf_or_child_of_name(const std::string & name) const { if(name == "broadcast-node" || name == "hybrid-node" || name == "mixed-node" || name == "peer-to-peer-node" || name == "hexadecimal") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DnsServers::DnsServers() : dns_server{YType::str, "dns-server"} { yang_name = "dns-servers"; yang_parent_name = "server"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DnsServers::~DnsServers() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DnsServers::has_data() const { if (is_presence_container) return true; for (auto const & leaf : dns_server.getYLeafs()) { if(leaf.is_set) return true; } return false; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DnsServers::has_operation() const { for (auto const & leaf : dns_server.getYLeafs()) { if(is_set(leaf.yfilter)) return true; } return is_set(yfilter) || ydk::is_set(dns_server.yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DnsServers::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "dns-servers"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DnsServers::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; auto dns_server_name_datas = dns_server.get_name_leafdata(); leaf_name_data.insert(leaf_name_data.end(), dns_server_name_datas.begin(), dns_server_name_datas.end()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DnsServers::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DnsServers::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DnsServers::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "dns-server") { dns_server.append(value); } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DnsServers::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "dns-server") { dns_server.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DnsServers::has_leaf_or_child_of_name(const std::string & name) const { if(name == "dns-server") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DhcpToAaa::DhcpToAaa() : option(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DhcpToAaa::Option>()) { option->parent = this; yang_name = "dhcp-to-aaa"; yang_parent_name = "server"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DhcpToAaa::~DhcpToAaa() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DhcpToAaa::has_data() const { if (is_presence_container) return true; return (option != nullptr && option->has_data()); } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DhcpToAaa::has_operation() const { return is_set(yfilter) || (option != nullptr && option->has_operation()); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DhcpToAaa::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "dhcp-to-aaa"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DhcpToAaa::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DhcpToAaa::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "option") { if(option == nullptr) { option = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DhcpToAaa::Option>(); } return option; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DhcpToAaa::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(option != nullptr) { _children["option"] = option; } return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DhcpToAaa::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DhcpToAaa::set_filter(const std::string & value_path, YFilter yfilter) { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DhcpToAaa::has_leaf_or_child_of_name(const std::string & name) const { if(name == "option") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DhcpToAaa::Option::Option() : list(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DhcpToAaa::Option::List>()) { list->parent = this; yang_name = "option"; yang_parent_name = "dhcp-to-aaa"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DhcpToAaa::Option::~Option() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DhcpToAaa::Option::has_data() const { if (is_presence_container) return true; return (list != nullptr && list->has_data()); } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DhcpToAaa::Option::has_operation() const { return is_set(yfilter) || (list != nullptr && list->has_operation()); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DhcpToAaa::Option::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "option"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DhcpToAaa::Option::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DhcpToAaa::Option::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "list") { if(list == nullptr) { list = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DhcpToAaa::Option::List>(); } return list; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DhcpToAaa::Option::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(list != nullptr) { _children["list"] = list; } return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DhcpToAaa::Option::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DhcpToAaa::Option::set_filter(const std::string & value_path, YFilter yfilter) { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DhcpToAaa::Option::has_leaf_or_child_of_name(const std::string & name) const { if(name == "list") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DhcpToAaa::Option::List::List() : option_all{YType::uint32, "option-all"}, option_number{YType::uint32, "option-number"} { yang_name = "list"; yang_parent_name = "option"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DhcpToAaa::Option::List::~List() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DhcpToAaa::Option::List::has_data() const { if (is_presence_container) return true; for (auto const & leaf : option_number.getYLeafs()) { if(leaf.is_set) return true; } return option_all.is_set; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DhcpToAaa::Option::List::has_operation() const { for (auto const & leaf : option_number.getYLeafs()) { if(is_set(leaf.yfilter)) return true; } return is_set(yfilter) || ydk::is_set(option_all.yfilter) || ydk::is_set(option_number.yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DhcpToAaa::Option::List::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "list"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DhcpToAaa::Option::List::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (option_all.is_set || is_set(option_all.yfilter)) leaf_name_data.push_back(option_all.get_name_leafdata()); auto option_number_name_datas = option_number.get_name_leafdata(); leaf_name_data.insert(leaf_name_data.end(), option_number_name_datas.begin(), option_number_name_datas.end()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DhcpToAaa::Option::List::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DhcpToAaa::Option::List::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DhcpToAaa::Option::List::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "option-all") { option_all = value; option_all.value_namespace = name_space; option_all.value_namespace_prefix = name_space_prefix; } if(value_path == "option-number") { option_number.append(value); } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DhcpToAaa::Option::List::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "option-all") { option_all.yfilter = yfilter; } if(value_path == "option-number") { option_number.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::DhcpToAaa::Option::List::has_leaf_or_child_of_name(const std::string & name) const { if(name == "option-all" || name == "option-number") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::OptionCodes::OptionCodes() : option_code(this, {"option_code"}) { yang_name = "option-codes"; yang_parent_name = "server"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::OptionCodes::~OptionCodes() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::OptionCodes::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<option_code.len(); index++) { if(option_code[index]->has_data()) return true; } return false; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::OptionCodes::has_operation() const { for (std::size_t index=0; index<option_code.len(); index++) { if(option_code[index]->has_operation()) return true; } return is_set(yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::OptionCodes::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "option-codes"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::OptionCodes::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::OptionCodes::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "option-code") { auto ent_ = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::OptionCodes::OptionCode>(); ent_->parent = this; option_code.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::OptionCodes::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : option_code.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::OptionCodes::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::OptionCodes::set_filter(const std::string & value_path, YFilter yfilter) { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::OptionCodes::has_leaf_or_child_of_name(const std::string & name) const { if(name == "option-code") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::OptionCodes::OptionCode::OptionCode() : option_code{YType::uint32, "option-code"}, ascii_string{YType::str, "ascii-string"}, hex_string{YType::str, "hex-string"}, force_insert{YType::uint32, "force-insert"}, ip_address{YType::str, "ip-address"} { yang_name = "option-code"; yang_parent_name = "option-codes"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::OptionCodes::OptionCode::~OptionCode() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::OptionCodes::OptionCode::has_data() const { if (is_presence_container) return true; for (auto const & leaf : ip_address.getYLeafs()) { if(leaf.is_set) return true; } return option_code.is_set || ascii_string.is_set || hex_string.is_set || force_insert.is_set; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::OptionCodes::OptionCode::has_operation() const { for (auto const & leaf : ip_address.getYLeafs()) { if(is_set(leaf.yfilter)) return true; } return is_set(yfilter) || ydk::is_set(option_code.yfilter) || ydk::is_set(ascii_string.yfilter) || ydk::is_set(hex_string.yfilter) || ydk::is_set(force_insert.yfilter) || ydk::is_set(ip_address.yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::OptionCodes::OptionCode::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "option-code"; ADD_KEY_TOKEN(option_code, "option-code"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::OptionCodes::OptionCode::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (option_code.is_set || is_set(option_code.yfilter)) leaf_name_data.push_back(option_code.get_name_leafdata()); if (ascii_string.is_set || is_set(ascii_string.yfilter)) leaf_name_data.push_back(ascii_string.get_name_leafdata()); if (hex_string.is_set || is_set(hex_string.yfilter)) leaf_name_data.push_back(hex_string.get_name_leafdata()); if (force_insert.is_set || is_set(force_insert.yfilter)) leaf_name_data.push_back(force_insert.get_name_leafdata()); auto ip_address_name_datas = ip_address.get_name_leafdata(); leaf_name_data.insert(leaf_name_data.end(), ip_address_name_datas.begin(), ip_address_name_datas.end()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::OptionCodes::OptionCode::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::OptionCodes::OptionCode::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::OptionCodes::OptionCode::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "option-code") { option_code = value; option_code.value_namespace = name_space; option_code.value_namespace_prefix = name_space_prefix; } if(value_path == "ascii-string") { ascii_string = value; ascii_string.value_namespace = name_space; ascii_string.value_namespace_prefix = name_space_prefix; } if(value_path == "hex-string") { hex_string = value; hex_string.value_namespace = name_space; hex_string.value_namespace_prefix = name_space_prefix; } if(value_path == "force-insert") { force_insert = value; force_insert.value_namespace = name_space; force_insert.value_namespace_prefix = name_space_prefix; } if(value_path == "ip-address") { ip_address.append(value); } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::OptionCodes::OptionCode::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "option-code") { option_code.yfilter = yfilter; } if(value_path == "ascii-string") { ascii_string.yfilter = yfilter; } if(value_path == "hex-string") { hex_string.yfilter = yfilter; } if(value_path == "force-insert") { force_insert.yfilter = yfilter; } if(value_path == "ip-address") { ip_address.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Server::OptionCodes::OptionCode::has_leaf_or_child_of_name(const std::string & name) const { if(name == "option-code" || name == "ascii-string" || name == "hex-string" || name == "force-insert" || name == "ip-address") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Relay() : mac_mismatch_action{YType::enumeration, "mac-mismatch-action"} , gi_addr_policy(nullptr) // presence node , vrfs(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs>()) , relay_information_option(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::RelayInformationOption>()) , broadcast_policy(nullptr) // presence node { vrfs->parent = this; relay_information_option->parent = this; yang_name = "relay"; yang_parent_name = "mode"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::~Relay() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::has_data() const { if (is_presence_container) return true; return mac_mismatch_action.is_set || (gi_addr_policy != nullptr && gi_addr_policy->has_data()) || (vrfs != nullptr && vrfs->has_data()) || (relay_information_option != nullptr && relay_information_option->has_data()) || (broadcast_policy != nullptr && broadcast_policy->has_data()); } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::has_operation() const { return is_set(yfilter) || ydk::is_set(mac_mismatch_action.yfilter) || (gi_addr_policy != nullptr && gi_addr_policy->has_operation()) || (vrfs != nullptr && vrfs->has_operation()) || (relay_information_option != nullptr && relay_information_option->has_operation()) || (broadcast_policy != nullptr && broadcast_policy->has_operation()); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "relay"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (mac_mismatch_action.is_set || is_set(mac_mismatch_action.yfilter)) leaf_name_data.push_back(mac_mismatch_action.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "gi-addr-policy") { if(gi_addr_policy == nullptr) { gi_addr_policy = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::GiAddrPolicy>(); } return gi_addr_policy; } if(child_yang_name == "vrfs") { if(vrfs == nullptr) { vrfs = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs>(); } return vrfs; } if(child_yang_name == "relay-information-option") { if(relay_information_option == nullptr) { relay_information_option = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::RelayInformationOption>(); } return relay_information_option; } if(child_yang_name == "broadcast-policy") { if(broadcast_policy == nullptr) { broadcast_policy = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::BroadcastPolicy>(); } return broadcast_policy; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(gi_addr_policy != nullptr) { _children["gi-addr-policy"] = gi_addr_policy; } if(vrfs != nullptr) { _children["vrfs"] = vrfs; } if(relay_information_option != nullptr) { _children["relay-information-option"] = relay_information_option; } if(broadcast_policy != nullptr) { _children["broadcast-policy"] = broadcast_policy; } return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "mac-mismatch-action") { mac_mismatch_action = value; mac_mismatch_action.value_namespace = name_space; mac_mismatch_action.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "mac-mismatch-action") { mac_mismatch_action.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::has_leaf_or_child_of_name(const std::string & name) const { if(name == "gi-addr-policy" || name == "vrfs" || name == "relay-information-option" || name == "broadcast-policy" || name == "mac-mismatch-action") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::GiAddrPolicy::GiAddrPolicy() : policy{YType::enumeration, "policy"} { yang_name = "gi-addr-policy"; yang_parent_name = "relay"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::GiAddrPolicy::~GiAddrPolicy() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::GiAddrPolicy::has_data() const { if (is_presence_container) return true; return policy.is_set; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::GiAddrPolicy::has_operation() const { return is_set(yfilter) || ydk::is_set(policy.yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::GiAddrPolicy::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "gi-addr-policy"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::GiAddrPolicy::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (policy.is_set || is_set(policy.yfilter)) leaf_name_data.push_back(policy.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::GiAddrPolicy::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::GiAddrPolicy::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::GiAddrPolicy::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "policy") { policy = value; policy.value_namespace = name_space; policy.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::GiAddrPolicy::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "policy") { policy.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::GiAddrPolicy::has_leaf_or_child_of_name(const std::string & name) const { if(name == "policy") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::Vrfs() : vrf(this, {"vrf_name"}) { yang_name = "vrfs"; yang_parent_name = "relay"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::~Vrfs() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<vrf.len(); index++) { if(vrf[index]->has_data()) return true; } return false; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::has_operation() const { for (std::size_t index=0; index<vrf.len(); index++) { if(vrf[index]->has_operation()) return true; } return is_set(yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "vrfs"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "vrf") { auto ent_ = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::Vrf>(); ent_->parent = this; vrf.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : vrf.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::set_filter(const std::string & value_path, YFilter yfilter) { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::has_leaf_or_child_of_name(const std::string & name) const { if(name == "vrf") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::Vrf::Vrf() : vrf_name{YType::str, "vrf-name"} , helper_addresses(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::Vrf::HelperAddresses>()) { helper_addresses->parent = this; yang_name = "vrf"; yang_parent_name = "vrfs"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::Vrf::~Vrf() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::Vrf::has_data() const { if (is_presence_container) return true; return vrf_name.is_set || (helper_addresses != nullptr && helper_addresses->has_data()); } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::Vrf::has_operation() const { return is_set(yfilter) || ydk::is_set(vrf_name.yfilter) || (helper_addresses != nullptr && helper_addresses->has_operation()); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::Vrf::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "vrf"; ADD_KEY_TOKEN(vrf_name, "vrf-name"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::Vrf::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (vrf_name.is_set || is_set(vrf_name.yfilter)) leaf_name_data.push_back(vrf_name.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::Vrf::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "helper-addresses") { if(helper_addresses == nullptr) { helper_addresses = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::Vrf::HelperAddresses>(); } return helper_addresses; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::Vrf::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(helper_addresses != nullptr) { _children["helper-addresses"] = helper_addresses; } return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::Vrf::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "vrf-name") { vrf_name = value; vrf_name.value_namespace = name_space; vrf_name.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::Vrf::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "vrf-name") { vrf_name.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::Vrf::has_leaf_or_child_of_name(const std::string & name) const { if(name == "helper-addresses" || name == "vrf-name") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::Vrf::HelperAddresses::HelperAddresses() : helper_address(this, {"ip_address"}) { yang_name = "helper-addresses"; yang_parent_name = "vrf"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::Vrf::HelperAddresses::~HelperAddresses() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::Vrf::HelperAddresses::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<helper_address.len(); index++) { if(helper_address[index]->has_data()) return true; } return false; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::Vrf::HelperAddresses::has_operation() const { for (std::size_t index=0; index<helper_address.len(); index++) { if(helper_address[index]->has_operation()) return true; } return is_set(yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::Vrf::HelperAddresses::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "helper-addresses"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::Vrf::HelperAddresses::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::Vrf::HelperAddresses::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "helper-address") { auto ent_ = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::Vrf::HelperAddresses::HelperAddress>(); ent_->parent = this; helper_address.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::Vrf::HelperAddresses::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : helper_address.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::Vrf::HelperAddresses::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::Vrf::HelperAddresses::set_filter(const std::string & value_path, YFilter yfilter) { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::Vrf::HelperAddresses::has_leaf_or_child_of_name(const std::string & name) const { if(name == "helper-address") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::Vrf::HelperAddresses::HelperAddress::HelperAddress() : ip_address{YType::str, "ip-address"}, enable{YType::empty, "enable"}, gateway_address{YType::str, "gateway-address"} { yang_name = "helper-address"; yang_parent_name = "helper-addresses"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::Vrf::HelperAddresses::HelperAddress::~HelperAddress() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::Vrf::HelperAddresses::HelperAddress::has_data() const { if (is_presence_container) return true; return ip_address.is_set || enable.is_set || gateway_address.is_set; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::Vrf::HelperAddresses::HelperAddress::has_operation() const { return is_set(yfilter) || ydk::is_set(ip_address.yfilter) || ydk::is_set(enable.yfilter) || ydk::is_set(gateway_address.yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::Vrf::HelperAddresses::HelperAddress::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "helper-address"; ADD_KEY_TOKEN(ip_address, "ip-address"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::Vrf::HelperAddresses::HelperAddress::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (ip_address.is_set || is_set(ip_address.yfilter)) leaf_name_data.push_back(ip_address.get_name_leafdata()); if (enable.is_set || is_set(enable.yfilter)) leaf_name_data.push_back(enable.get_name_leafdata()); if (gateway_address.is_set || is_set(gateway_address.yfilter)) leaf_name_data.push_back(gateway_address.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::Vrf::HelperAddresses::HelperAddress::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::Vrf::HelperAddresses::HelperAddress::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::Vrf::HelperAddresses::HelperAddress::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "ip-address") { ip_address = value; ip_address.value_namespace = name_space; ip_address.value_namespace_prefix = name_space_prefix; } if(value_path == "enable") { enable = value; enable.value_namespace = name_space; enable.value_namespace_prefix = name_space_prefix; } if(value_path == "gateway-address") { gateway_address = value; gateway_address.value_namespace = name_space; gateway_address.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::Vrf::HelperAddresses::HelperAddress::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "ip-address") { ip_address.yfilter = yfilter; } if(value_path == "enable") { enable.yfilter = yfilter; } if(value_path == "gateway-address") { gateway_address.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::Vrfs::Vrf::HelperAddresses::HelperAddress::has_leaf_or_child_of_name(const std::string & name) const { if(name == "ip-address" || name == "enable" || name == "gateway-address") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::RelayInformationOption::RelayInformationOption() : vpn_mode{YType::enumeration, "vpn-mode"}, subscriber_id{YType::str, "subscriber-id"}, insert{YType::empty, "insert"}, check{YType::empty, "check"}, vpn{YType::empty, "vpn"}, allow_untrusted{YType::empty, "allow-untrusted"}, policy{YType::enumeration, "policy"} { yang_name = "relay-information-option"; yang_parent_name = "relay"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::RelayInformationOption::~RelayInformationOption() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::RelayInformationOption::has_data() const { if (is_presence_container) return true; return vpn_mode.is_set || subscriber_id.is_set || insert.is_set || check.is_set || vpn.is_set || allow_untrusted.is_set || policy.is_set; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::RelayInformationOption::has_operation() const { return is_set(yfilter) || ydk::is_set(vpn_mode.yfilter) || ydk::is_set(subscriber_id.yfilter) || ydk::is_set(insert.yfilter) || ydk::is_set(check.yfilter) || ydk::is_set(vpn.yfilter) || ydk::is_set(allow_untrusted.yfilter) || ydk::is_set(policy.yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::RelayInformationOption::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "relay-information-option"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::RelayInformationOption::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (vpn_mode.is_set || is_set(vpn_mode.yfilter)) leaf_name_data.push_back(vpn_mode.get_name_leafdata()); if (subscriber_id.is_set || is_set(subscriber_id.yfilter)) leaf_name_data.push_back(subscriber_id.get_name_leafdata()); if (insert.is_set || is_set(insert.yfilter)) leaf_name_data.push_back(insert.get_name_leafdata()); if (check.is_set || is_set(check.yfilter)) leaf_name_data.push_back(check.get_name_leafdata()); if (vpn.is_set || is_set(vpn.yfilter)) leaf_name_data.push_back(vpn.get_name_leafdata()); if (allow_untrusted.is_set || is_set(allow_untrusted.yfilter)) leaf_name_data.push_back(allow_untrusted.get_name_leafdata()); if (policy.is_set || is_set(policy.yfilter)) leaf_name_data.push_back(policy.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::RelayInformationOption::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::RelayInformationOption::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::RelayInformationOption::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "vpn-mode") { vpn_mode = value; vpn_mode.value_namespace = name_space; vpn_mode.value_namespace_prefix = name_space_prefix; } if(value_path == "subscriber-id") { subscriber_id = value; subscriber_id.value_namespace = name_space; subscriber_id.value_namespace_prefix = name_space_prefix; } if(value_path == "insert") { insert = value; insert.value_namespace = name_space; insert.value_namespace_prefix = name_space_prefix; } if(value_path == "check") { check = value; check.value_namespace = name_space; check.value_namespace_prefix = name_space_prefix; } if(value_path == "vpn") { vpn = value; vpn.value_namespace = name_space; vpn.value_namespace_prefix = name_space_prefix; } if(value_path == "allow-untrusted") { allow_untrusted = value; allow_untrusted.value_namespace = name_space; allow_untrusted.value_namespace_prefix = name_space_prefix; } if(value_path == "policy") { policy = value; policy.value_namespace = name_space; policy.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::RelayInformationOption::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "vpn-mode") { vpn_mode.yfilter = yfilter; } if(value_path == "subscriber-id") { subscriber_id.yfilter = yfilter; } if(value_path == "insert") { insert.yfilter = yfilter; } if(value_path == "check") { check.yfilter = yfilter; } if(value_path == "vpn") { vpn.yfilter = yfilter; } if(value_path == "allow-untrusted") { allow_untrusted.yfilter = yfilter; } if(value_path == "policy") { policy.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::RelayInformationOption::has_leaf_or_child_of_name(const std::string & name) const { if(name == "vpn-mode" || name == "subscriber-id" || name == "insert" || name == "check" || name == "vpn" || name == "allow-untrusted" || name == "policy") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::BroadcastPolicy::BroadcastPolicy() : policy{YType::enumeration, "policy"} { yang_name = "broadcast-policy"; yang_parent_name = "relay"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::BroadcastPolicy::~BroadcastPolicy() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::BroadcastPolicy::has_data() const { if (is_presence_container) return true; return policy.is_set; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::BroadcastPolicy::has_operation() const { return is_set(yfilter) || ydk::is_set(policy.yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::BroadcastPolicy::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "broadcast-policy"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::BroadcastPolicy::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (policy.is_set || is_set(policy.yfilter)) leaf_name_data.push_back(policy.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::BroadcastPolicy::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::BroadcastPolicy::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::BroadcastPolicy::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "policy") { policy = value; policy.value_namespace = name_space; policy.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::BroadcastPolicy::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "policy") { policy.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Relay::BroadcastPolicy::has_leaf_or_child_of_name(const std::string & name) const { if(name == "policy") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Proxy() : proxy_allow_move{YType::empty, "proxy-allow-move"}, secure_arp{YType::empty, "secure-arp"}, delayed_authen_proxy{YType::empty, "delayed-authen-proxy"}, enable{YType::empty, "enable"} , giaddr(nullptr) // presence node , classes(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes>()) , auth_username(nullptr) // presence node , relay_information(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::RelayInformation>()) , dhcp_to_aaa(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::DhcpToAaa>()) , vrfs(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs>()) , sessions(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Sessions>()) , limit_lease(nullptr) // presence node , lease_proxy(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::LeaseProxy>()) , broadcast_flag(nullptr) // presence node , match(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match>()) { classes->parent = this; relay_information->parent = this; dhcp_to_aaa->parent = this; vrfs->parent = this; sessions->parent = this; lease_proxy->parent = this; match->parent = this; yang_name = "proxy"; yang_parent_name = "mode"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::~Proxy() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::has_data() const { if (is_presence_container) return true; return proxy_allow_move.is_set || secure_arp.is_set || delayed_authen_proxy.is_set || enable.is_set || (giaddr != nullptr && giaddr->has_data()) || (classes != nullptr && classes->has_data()) || (auth_username != nullptr && auth_username->has_data()) || (relay_information != nullptr && relay_information->has_data()) || (dhcp_to_aaa != nullptr && dhcp_to_aaa->has_data()) || (vrfs != nullptr && vrfs->has_data()) || (sessions != nullptr && sessions->has_data()) || (limit_lease != nullptr && limit_lease->has_data()) || (lease_proxy != nullptr && lease_proxy->has_data()) || (broadcast_flag != nullptr && broadcast_flag->has_data()) || (match != nullptr && match->has_data()); } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::has_operation() const { return is_set(yfilter) || ydk::is_set(proxy_allow_move.yfilter) || ydk::is_set(secure_arp.yfilter) || ydk::is_set(delayed_authen_proxy.yfilter) || ydk::is_set(enable.yfilter) || (giaddr != nullptr && giaddr->has_operation()) || (classes != nullptr && classes->has_operation()) || (auth_username != nullptr && auth_username->has_operation()) || (relay_information != nullptr && relay_information->has_operation()) || (dhcp_to_aaa != nullptr && dhcp_to_aaa->has_operation()) || (vrfs != nullptr && vrfs->has_operation()) || (sessions != nullptr && sessions->has_operation()) || (limit_lease != nullptr && limit_lease->has_operation()) || (lease_proxy != nullptr && lease_proxy->has_operation()) || (broadcast_flag != nullptr && broadcast_flag->has_operation()) || (match != nullptr && match->has_operation()); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "proxy"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (proxy_allow_move.is_set || is_set(proxy_allow_move.yfilter)) leaf_name_data.push_back(proxy_allow_move.get_name_leafdata()); if (secure_arp.is_set || is_set(secure_arp.yfilter)) leaf_name_data.push_back(secure_arp.get_name_leafdata()); if (delayed_authen_proxy.is_set || is_set(delayed_authen_proxy.yfilter)) leaf_name_data.push_back(delayed_authen_proxy.get_name_leafdata()); if (enable.is_set || is_set(enable.yfilter)) leaf_name_data.push_back(enable.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "giaddr") { if(giaddr == nullptr) { giaddr = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Giaddr>(); } return giaddr; } if(child_yang_name == "classes") { if(classes == nullptr) { classes = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes>(); } return classes; } if(child_yang_name == "auth-username") { if(auth_username == nullptr) { auth_username = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::AuthUsername>(); } return auth_username; } if(child_yang_name == "relay-information") { if(relay_information == nullptr) { relay_information = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::RelayInformation>(); } return relay_information; } if(child_yang_name == "dhcp-to-aaa") { if(dhcp_to_aaa == nullptr) { dhcp_to_aaa = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::DhcpToAaa>(); } return dhcp_to_aaa; } if(child_yang_name == "vrfs") { if(vrfs == nullptr) { vrfs = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs>(); } return vrfs; } if(child_yang_name == "sessions") { if(sessions == nullptr) { sessions = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Sessions>(); } return sessions; } if(child_yang_name == "limit-lease") { if(limit_lease == nullptr) { limit_lease = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::LimitLease>(); } return limit_lease; } if(child_yang_name == "lease-proxy") { if(lease_proxy == nullptr) { lease_proxy = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::LeaseProxy>(); } return lease_proxy; } if(child_yang_name == "broadcast-flag") { if(broadcast_flag == nullptr) { broadcast_flag = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::BroadcastFlag>(); } return broadcast_flag; } if(child_yang_name == "match") { if(match == nullptr) { match = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match>(); } return match; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(giaddr != nullptr) { _children["giaddr"] = giaddr; } if(classes != nullptr) { _children["classes"] = classes; } if(auth_username != nullptr) { _children["auth-username"] = auth_username; } if(relay_information != nullptr) { _children["relay-information"] = relay_information; } if(dhcp_to_aaa != nullptr) { _children["dhcp-to-aaa"] = dhcp_to_aaa; } if(vrfs != nullptr) { _children["vrfs"] = vrfs; } if(sessions != nullptr) { _children["sessions"] = sessions; } if(limit_lease != nullptr) { _children["limit-lease"] = limit_lease; } if(lease_proxy != nullptr) { _children["lease-proxy"] = lease_proxy; } if(broadcast_flag != nullptr) { _children["broadcast-flag"] = broadcast_flag; } if(match != nullptr) { _children["match"] = match; } return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "proxy-allow-move") { proxy_allow_move = value; proxy_allow_move.value_namespace = name_space; proxy_allow_move.value_namespace_prefix = name_space_prefix; } if(value_path == "secure-arp") { secure_arp = value; secure_arp.value_namespace = name_space; secure_arp.value_namespace_prefix = name_space_prefix; } if(value_path == "delayed-authen-proxy") { delayed_authen_proxy = value; delayed_authen_proxy.value_namespace = name_space; delayed_authen_proxy.value_namespace_prefix = name_space_prefix; } if(value_path == "enable") { enable = value; enable.value_namespace = name_space; enable.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "proxy-allow-move") { proxy_allow_move.yfilter = yfilter; } if(value_path == "secure-arp") { secure_arp.yfilter = yfilter; } if(value_path == "delayed-authen-proxy") { delayed_authen_proxy.yfilter = yfilter; } if(value_path == "enable") { enable.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::has_leaf_or_child_of_name(const std::string & name) const { if(name == "giaddr" || name == "classes" || name == "auth-username" || name == "relay-information" || name == "dhcp-to-aaa" || name == "vrfs" || name == "sessions" || name == "limit-lease" || name == "lease-proxy" || name == "broadcast-flag" || name == "match" || name == "proxy-allow-move" || name == "secure-arp" || name == "delayed-authen-proxy" || name == "enable") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Giaddr::Giaddr() : policy{YType::enumeration, "policy"} { yang_name = "giaddr"; yang_parent_name = "proxy"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Giaddr::~Giaddr() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Giaddr::has_data() const { if (is_presence_container) return true; return policy.is_set; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Giaddr::has_operation() const { return is_set(yfilter) || ydk::is_set(policy.yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Giaddr::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "giaddr"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Giaddr::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (policy.is_set || is_set(policy.yfilter)) leaf_name_data.push_back(policy.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Giaddr::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Giaddr::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Giaddr::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "policy") { policy = value; policy.value_namespace = name_space; policy.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Giaddr::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "policy") { policy.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Giaddr::has_leaf_or_child_of_name(const std::string & name) const { if(name == "policy") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Classes() : class_(this, {"class_name"}) { yang_name = "classes"; yang_parent_name = "proxy"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::~Classes() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<class_.len(); index++) { if(class_[index]->has_data()) return true; } return false; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::has_operation() const { for (std::size_t index=0; index<class_.len(); index++) { if(class_[index]->has_operation()) return true; } return is_set(yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "classes"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "class") { auto ent_ = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class>(); ent_->parent = this; class_.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : class_.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::set_filter(const std::string & value_path, YFilter yfilter) { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::has_leaf_or_child_of_name(const std::string & name) const { if(name == "class") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Class() : class_name{YType::str, "class-name"}, enable{YType::empty, "enable"} , match(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Match>()) , vrfs(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs>()) { match->parent = this; vrfs->parent = this; yang_name = "class"; yang_parent_name = "classes"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::~Class() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::has_data() const { if (is_presence_container) return true; return class_name.is_set || enable.is_set || (match != nullptr && match->has_data()) || (vrfs != nullptr && vrfs->has_data()); } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::has_operation() const { return is_set(yfilter) || ydk::is_set(class_name.yfilter) || ydk::is_set(enable.yfilter) || (match != nullptr && match->has_operation()) || (vrfs != nullptr && vrfs->has_operation()); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "class"; ADD_KEY_TOKEN(class_name, "class-name"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (class_name.is_set || is_set(class_name.yfilter)) leaf_name_data.push_back(class_name.get_name_leafdata()); if (enable.is_set || is_set(enable.yfilter)) leaf_name_data.push_back(enable.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "match") { if(match == nullptr) { match = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Match>(); } return match; } if(child_yang_name == "vrfs") { if(vrfs == nullptr) { vrfs = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs>(); } return vrfs; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(match != nullptr) { _children["match"] = match; } if(vrfs != nullptr) { _children["vrfs"] = vrfs; } return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "class-name") { class_name = value; class_name.value_namespace = name_space; class_name.value_namespace_prefix = name_space_prefix; } if(value_path == "enable") { enable = value; enable.value_namespace = name_space; enable.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "class-name") { class_name.yfilter = yfilter; } if(value_path == "enable") { enable.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::has_leaf_or_child_of_name(const std::string & name) const { if(name == "match" || name == "vrfs" || name == "class-name" || name == "enable") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Match::Match() : vrf{YType::str, "vrf"} , option(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Match::Option>()) { option->parent = this; yang_name = "match"; yang_parent_name = "class"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Match::~Match() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Match::has_data() const { if (is_presence_container) return true; return vrf.is_set || (option != nullptr && option->has_data()); } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Match::has_operation() const { return is_set(yfilter) || ydk::is_set(vrf.yfilter) || (option != nullptr && option->has_operation()); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Match::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "match"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Match::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (vrf.is_set || is_set(vrf.yfilter)) leaf_name_data.push_back(vrf.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Match::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "option") { if(option == nullptr) { option = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Match::Option>(); } return option; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Match::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(option != nullptr) { _children["option"] = option; } return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Match::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "vrf") { vrf = value; vrf.value_namespace = name_space; vrf.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Match::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "vrf") { vrf.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Match::has_leaf_or_child_of_name(const std::string & name) const { if(name == "option" || name == "vrf") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Match::Option::Option() : option_type{YType::enumeration, "option-type"}, pattern{YType::str, "pattern"}, bit_mask{YType::str, "bit-mask"} { yang_name = "option"; yang_parent_name = "match"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Match::Option::~Option() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Match::Option::has_data() const { if (is_presence_container) return true; return option_type.is_set || pattern.is_set || bit_mask.is_set; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Match::Option::has_operation() const { return is_set(yfilter) || ydk::is_set(option_type.yfilter) || ydk::is_set(pattern.yfilter) || ydk::is_set(bit_mask.yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Match::Option::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "option"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Match::Option::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (option_type.is_set || is_set(option_type.yfilter)) leaf_name_data.push_back(option_type.get_name_leafdata()); if (pattern.is_set || is_set(pattern.yfilter)) leaf_name_data.push_back(pattern.get_name_leafdata()); if (bit_mask.is_set || is_set(bit_mask.yfilter)) leaf_name_data.push_back(bit_mask.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Match::Option::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Match::Option::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Match::Option::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "option-type") { option_type = value; option_type.value_namespace = name_space; option_type.value_namespace_prefix = name_space_prefix; } if(value_path == "pattern") { pattern = value; pattern.value_namespace = name_space; pattern.value_namespace_prefix = name_space_prefix; } if(value_path == "bit-mask") { bit_mask = value; bit_mask.value_namespace = name_space; bit_mask.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Match::Option::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "option-type") { option_type.yfilter = yfilter; } if(value_path == "pattern") { pattern.yfilter = yfilter; } if(value_path == "bit-mask") { bit_mask.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Match::Option::has_leaf_or_child_of_name(const std::string & name) const { if(name == "option-type" || name == "pattern" || name == "bit-mask") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::Vrfs() : vrf(this, {"vrf_name"}) { yang_name = "vrfs"; yang_parent_name = "class"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::~Vrfs() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<vrf.len(); index++) { if(vrf[index]->has_data()) return true; } return false; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::has_operation() const { for (std::size_t index=0; index<vrf.len(); index++) { if(vrf[index]->has_operation()) return true; } return is_set(yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "vrfs"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "vrf") { auto ent_ = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::Vrf>(); ent_->parent = this; vrf.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : vrf.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::set_filter(const std::string & value_path, YFilter yfilter) { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::has_leaf_or_child_of_name(const std::string & name) const { if(name == "vrf") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::Vrf::Vrf() : vrf_name{YType::str, "vrf-name"} , helper_addresses(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::Vrf::HelperAddresses>()) { helper_addresses->parent = this; yang_name = "vrf"; yang_parent_name = "vrfs"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::Vrf::~Vrf() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::Vrf::has_data() const { if (is_presence_container) return true; return vrf_name.is_set || (helper_addresses != nullptr && helper_addresses->has_data()); } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::Vrf::has_operation() const { return is_set(yfilter) || ydk::is_set(vrf_name.yfilter) || (helper_addresses != nullptr && helper_addresses->has_operation()); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::Vrf::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "vrf"; ADD_KEY_TOKEN(vrf_name, "vrf-name"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::Vrf::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (vrf_name.is_set || is_set(vrf_name.yfilter)) leaf_name_data.push_back(vrf_name.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::Vrf::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "helper-addresses") { if(helper_addresses == nullptr) { helper_addresses = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::Vrf::HelperAddresses>(); } return helper_addresses; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::Vrf::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(helper_addresses != nullptr) { _children["helper-addresses"] = helper_addresses; } return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::Vrf::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "vrf-name") { vrf_name = value; vrf_name.value_namespace = name_space; vrf_name.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::Vrf::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "vrf-name") { vrf_name.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::Vrf::has_leaf_or_child_of_name(const std::string & name) const { if(name == "helper-addresses" || name == "vrf-name") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::Vrf::HelperAddresses::HelperAddresses() : helper_address(this, {"server_address"}) { yang_name = "helper-addresses"; yang_parent_name = "vrf"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::Vrf::HelperAddresses::~HelperAddresses() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::Vrf::HelperAddresses::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<helper_address.len(); index++) { if(helper_address[index]->has_data()) return true; } return false; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::Vrf::HelperAddresses::has_operation() const { for (std::size_t index=0; index<helper_address.len(); index++) { if(helper_address[index]->has_operation()) return true; } return is_set(yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::Vrf::HelperAddresses::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "helper-addresses"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::Vrf::HelperAddresses::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::Vrf::HelperAddresses::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "helper-address") { auto ent_ = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::Vrf::HelperAddresses::HelperAddress>(); ent_->parent = this; helper_address.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::Vrf::HelperAddresses::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : helper_address.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::Vrf::HelperAddresses::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::Vrf::HelperAddresses::set_filter(const std::string & value_path, YFilter yfilter) { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::Vrf::HelperAddresses::has_leaf_or_child_of_name(const std::string & name) const { if(name == "helper-address") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::Vrf::HelperAddresses::HelperAddress::HelperAddress() : server_address{YType::str, "server-address"}, gateway_address{YType::str, "gateway-address"} { yang_name = "helper-address"; yang_parent_name = "helper-addresses"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::Vrf::HelperAddresses::HelperAddress::~HelperAddress() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::Vrf::HelperAddresses::HelperAddress::has_data() const { if (is_presence_container) return true; return server_address.is_set || gateway_address.is_set; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::Vrf::HelperAddresses::HelperAddress::has_operation() const { return is_set(yfilter) || ydk::is_set(server_address.yfilter) || ydk::is_set(gateway_address.yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::Vrf::HelperAddresses::HelperAddress::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "helper-address"; ADD_KEY_TOKEN(server_address, "server-address"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::Vrf::HelperAddresses::HelperAddress::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (server_address.is_set || is_set(server_address.yfilter)) leaf_name_data.push_back(server_address.get_name_leafdata()); if (gateway_address.is_set || is_set(gateway_address.yfilter)) leaf_name_data.push_back(gateway_address.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::Vrf::HelperAddresses::HelperAddress::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::Vrf::HelperAddresses::HelperAddress::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::Vrf::HelperAddresses::HelperAddress::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "server-address") { server_address = value; server_address.value_namespace = name_space; server_address.value_namespace_prefix = name_space_prefix; } if(value_path == "gateway-address") { gateway_address = value; gateway_address.value_namespace = name_space; gateway_address.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::Vrf::HelperAddresses::HelperAddress::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "server-address") { server_address.yfilter = yfilter; } if(value_path == "gateway-address") { gateway_address.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Classes::Class::Vrfs::Vrf::HelperAddresses::HelperAddress::has_leaf_or_child_of_name(const std::string & name) const { if(name == "server-address" || name == "gateway-address") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::AuthUsername::AuthUsername() : arg1{YType::enumeration, "arg1"}, arg2{YType::enumeration, "arg2"} { yang_name = "auth-username"; yang_parent_name = "proxy"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::AuthUsername::~AuthUsername() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::AuthUsername::has_data() const { if (is_presence_container) return true; return arg1.is_set || arg2.is_set; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::AuthUsername::has_operation() const { return is_set(yfilter) || ydk::is_set(arg1.yfilter) || ydk::is_set(arg2.yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::AuthUsername::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "auth-username"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::AuthUsername::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (arg1.is_set || is_set(arg1.yfilter)) leaf_name_data.push_back(arg1.get_name_leafdata()); if (arg2.is_set || is_set(arg2.yfilter)) leaf_name_data.push_back(arg2.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::AuthUsername::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::AuthUsername::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::AuthUsername::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "arg1") { arg1 = value; arg1.value_namespace = name_space; arg1.value_namespace_prefix = name_space_prefix; } if(value_path == "arg2") { arg2 = value; arg2.value_namespace = name_space; arg2.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::AuthUsername::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "arg1") { arg1.yfilter = yfilter; } if(value_path == "arg2") { arg2.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::AuthUsername::has_leaf_or_child_of_name(const std::string & name) const { if(name == "arg1" || name == "arg2") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::RelayInformation::RelayInformation() : option{YType::empty, "option"}, vpn{YType::empty, "vpn"}, allow_untrusted{YType::empty, "allow-untrusted"}, circuit_id{YType::empty, "circuit-id"}, policy{YType::enumeration, "policy"}, vpn_mode{YType::enumeration, "vpn-mode"}, remote_id_xr{YType::empty, "remote-id-xr"}, remote_id_suppress{YType::empty, "remote-id-suppress"}, check{YType::empty, "check"}, remote_id{YType::str, "remote-id"}, authenticate{YType::enumeration, "authenticate"} { yang_name = "relay-information"; yang_parent_name = "proxy"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::RelayInformation::~RelayInformation() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::RelayInformation::has_data() const { if (is_presence_container) return true; return option.is_set || vpn.is_set || allow_untrusted.is_set || circuit_id.is_set || policy.is_set || vpn_mode.is_set || remote_id_xr.is_set || remote_id_suppress.is_set || check.is_set || remote_id.is_set || authenticate.is_set; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::RelayInformation::has_operation() const { return is_set(yfilter) || ydk::is_set(option.yfilter) || ydk::is_set(vpn.yfilter) || ydk::is_set(allow_untrusted.yfilter) || ydk::is_set(circuit_id.yfilter) || ydk::is_set(policy.yfilter) || ydk::is_set(vpn_mode.yfilter) || ydk::is_set(remote_id_xr.yfilter) || ydk::is_set(remote_id_suppress.yfilter) || ydk::is_set(check.yfilter) || ydk::is_set(remote_id.yfilter) || ydk::is_set(authenticate.yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::RelayInformation::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "relay-information"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::RelayInformation::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (option.is_set || is_set(option.yfilter)) leaf_name_data.push_back(option.get_name_leafdata()); if (vpn.is_set || is_set(vpn.yfilter)) leaf_name_data.push_back(vpn.get_name_leafdata()); if (allow_untrusted.is_set || is_set(allow_untrusted.yfilter)) leaf_name_data.push_back(allow_untrusted.get_name_leafdata()); if (circuit_id.is_set || is_set(circuit_id.yfilter)) leaf_name_data.push_back(circuit_id.get_name_leafdata()); if (policy.is_set || is_set(policy.yfilter)) leaf_name_data.push_back(policy.get_name_leafdata()); if (vpn_mode.is_set || is_set(vpn_mode.yfilter)) leaf_name_data.push_back(vpn_mode.get_name_leafdata()); if (remote_id_xr.is_set || is_set(remote_id_xr.yfilter)) leaf_name_data.push_back(remote_id_xr.get_name_leafdata()); if (remote_id_suppress.is_set || is_set(remote_id_suppress.yfilter)) leaf_name_data.push_back(remote_id_suppress.get_name_leafdata()); if (check.is_set || is_set(check.yfilter)) leaf_name_data.push_back(check.get_name_leafdata()); if (remote_id.is_set || is_set(remote_id.yfilter)) leaf_name_data.push_back(remote_id.get_name_leafdata()); if (authenticate.is_set || is_set(authenticate.yfilter)) leaf_name_data.push_back(authenticate.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::RelayInformation::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::RelayInformation::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::RelayInformation::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "option") { option = value; option.value_namespace = name_space; option.value_namespace_prefix = name_space_prefix; } if(value_path == "vpn") { vpn = value; vpn.value_namespace = name_space; vpn.value_namespace_prefix = name_space_prefix; } if(value_path == "allow-untrusted") { allow_untrusted = value; allow_untrusted.value_namespace = name_space; allow_untrusted.value_namespace_prefix = name_space_prefix; } if(value_path == "circuit-id") { circuit_id = value; circuit_id.value_namespace = name_space; circuit_id.value_namespace_prefix = name_space_prefix; } if(value_path == "policy") { policy = value; policy.value_namespace = name_space; policy.value_namespace_prefix = name_space_prefix; } if(value_path == "vpn-mode") { vpn_mode = value; vpn_mode.value_namespace = name_space; vpn_mode.value_namespace_prefix = name_space_prefix; } if(value_path == "remote-id-xr") { remote_id_xr = value; remote_id_xr.value_namespace = name_space; remote_id_xr.value_namespace_prefix = name_space_prefix; } if(value_path == "remote-id-suppress") { remote_id_suppress = value; remote_id_suppress.value_namespace = name_space; remote_id_suppress.value_namespace_prefix = name_space_prefix; } if(value_path == "check") { check = value; check.value_namespace = name_space; check.value_namespace_prefix = name_space_prefix; } if(value_path == "remote-id") { remote_id = value; remote_id.value_namespace = name_space; remote_id.value_namespace_prefix = name_space_prefix; } if(value_path == "authenticate") { authenticate = value; authenticate.value_namespace = name_space; authenticate.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::RelayInformation::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "option") { option.yfilter = yfilter; } if(value_path == "vpn") { vpn.yfilter = yfilter; } if(value_path == "allow-untrusted") { allow_untrusted.yfilter = yfilter; } if(value_path == "circuit-id") { circuit_id.yfilter = yfilter; } if(value_path == "policy") { policy.yfilter = yfilter; } if(value_path == "vpn-mode") { vpn_mode.yfilter = yfilter; } if(value_path == "remote-id-xr") { remote_id_xr.yfilter = yfilter; } if(value_path == "remote-id-suppress") { remote_id_suppress.yfilter = yfilter; } if(value_path == "check") { check.yfilter = yfilter; } if(value_path == "remote-id") { remote_id.yfilter = yfilter; } if(value_path == "authenticate") { authenticate.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::RelayInformation::has_leaf_or_child_of_name(const std::string & name) const { if(name == "option" || name == "vpn" || name == "allow-untrusted" || name == "circuit-id" || name == "policy" || name == "vpn-mode" || name == "remote-id-xr" || name == "remote-id-suppress" || name == "check" || name == "remote-id" || name == "authenticate") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::DhcpToAaa::DhcpToAaa() : option(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::DhcpToAaa::Option>()) { option->parent = this; yang_name = "dhcp-to-aaa"; yang_parent_name = "proxy"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::DhcpToAaa::~DhcpToAaa() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::DhcpToAaa::has_data() const { if (is_presence_container) return true; return (option != nullptr && option->has_data()); } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::DhcpToAaa::has_operation() const { return is_set(yfilter) || (option != nullptr && option->has_operation()); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::DhcpToAaa::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "dhcp-to-aaa"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::DhcpToAaa::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::DhcpToAaa::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "option") { if(option == nullptr) { option = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::DhcpToAaa::Option>(); } return option; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::DhcpToAaa::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(option != nullptr) { _children["option"] = option; } return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::DhcpToAaa::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::DhcpToAaa::set_filter(const std::string & value_path, YFilter yfilter) { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::DhcpToAaa::has_leaf_or_child_of_name(const std::string & name) const { if(name == "option") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::DhcpToAaa::Option::Option() : list(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::DhcpToAaa::Option::List>()) { list->parent = this; yang_name = "option"; yang_parent_name = "dhcp-to-aaa"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::DhcpToAaa::Option::~Option() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::DhcpToAaa::Option::has_data() const { if (is_presence_container) return true; return (list != nullptr && list->has_data()); } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::DhcpToAaa::Option::has_operation() const { return is_set(yfilter) || (list != nullptr && list->has_operation()); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::DhcpToAaa::Option::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "option"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::DhcpToAaa::Option::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::DhcpToAaa::Option::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "list") { if(list == nullptr) { list = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::DhcpToAaa::Option::List>(); } return list; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::DhcpToAaa::Option::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(list != nullptr) { _children["list"] = list; } return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::DhcpToAaa::Option::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::DhcpToAaa::Option::set_filter(const std::string & value_path, YFilter yfilter) { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::DhcpToAaa::Option::has_leaf_or_child_of_name(const std::string & name) const { if(name == "list") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::DhcpToAaa::Option::List::List() : option_all{YType::uint32, "option-all"}, option{YType::uint32, "option"} { yang_name = "list"; yang_parent_name = "option"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::DhcpToAaa::Option::List::~List() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::DhcpToAaa::Option::List::has_data() const { if (is_presence_container) return true; for (auto const & leaf : option.getYLeafs()) { if(leaf.is_set) return true; } return option_all.is_set; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::DhcpToAaa::Option::List::has_operation() const { for (auto const & leaf : option.getYLeafs()) { if(is_set(leaf.yfilter)) return true; } return is_set(yfilter) || ydk::is_set(option_all.yfilter) || ydk::is_set(option.yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::DhcpToAaa::Option::List::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "list"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::DhcpToAaa::Option::List::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (option_all.is_set || is_set(option_all.yfilter)) leaf_name_data.push_back(option_all.get_name_leafdata()); auto option_name_datas = option.get_name_leafdata(); leaf_name_data.insert(leaf_name_data.end(), option_name_datas.begin(), option_name_datas.end()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::DhcpToAaa::Option::List::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::DhcpToAaa::Option::List::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::DhcpToAaa::Option::List::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "option-all") { option_all = value; option_all.value_namespace = name_space; option_all.value_namespace_prefix = name_space_prefix; } if(value_path == "option") { option.append(value); } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::DhcpToAaa::Option::List::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "option-all") { option_all.yfilter = yfilter; } if(value_path == "option") { option.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::DhcpToAaa::Option::List::has_leaf_or_child_of_name(const std::string & name) const { if(name == "option-all" || name == "option") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::Vrfs() : vrf(this, {"vrf_name"}) { yang_name = "vrfs"; yang_parent_name = "proxy"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::~Vrfs() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<vrf.len(); index++) { if(vrf[index]->has_data()) return true; } return false; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::has_operation() const { for (std::size_t index=0; index<vrf.len(); index++) { if(vrf[index]->has_operation()) return true; } return is_set(yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "vrfs"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "vrf") { auto ent_ = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::Vrf>(); ent_->parent = this; vrf.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : vrf.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::set_filter(const std::string & value_path, YFilter yfilter) { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::has_leaf_or_child_of_name(const std::string & name) const { if(name == "vrf") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::Vrf::Vrf() : vrf_name{YType::str, "vrf-name"} , helper_addresses(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::Vrf::HelperAddresses>()) { helper_addresses->parent = this; yang_name = "vrf"; yang_parent_name = "vrfs"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::Vrf::~Vrf() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::Vrf::has_data() const { if (is_presence_container) return true; return vrf_name.is_set || (helper_addresses != nullptr && helper_addresses->has_data()); } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::Vrf::has_operation() const { return is_set(yfilter) || ydk::is_set(vrf_name.yfilter) || (helper_addresses != nullptr && helper_addresses->has_operation()); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::Vrf::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "vrf"; ADD_KEY_TOKEN(vrf_name, "vrf-name"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::Vrf::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (vrf_name.is_set || is_set(vrf_name.yfilter)) leaf_name_data.push_back(vrf_name.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::Vrf::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "helper-addresses") { if(helper_addresses == nullptr) { helper_addresses = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::Vrf::HelperAddresses>(); } return helper_addresses; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::Vrf::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(helper_addresses != nullptr) { _children["helper-addresses"] = helper_addresses; } return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::Vrf::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "vrf-name") { vrf_name = value; vrf_name.value_namespace = name_space; vrf_name.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::Vrf::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "vrf-name") { vrf_name.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::Vrf::has_leaf_or_child_of_name(const std::string & name) const { if(name == "helper-addresses" || name == "vrf-name") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::Vrf::HelperAddresses::HelperAddresses() : helper_address(this, {"server_address"}) { yang_name = "helper-addresses"; yang_parent_name = "vrf"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::Vrf::HelperAddresses::~HelperAddresses() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::Vrf::HelperAddresses::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<helper_address.len(); index++) { if(helper_address[index]->has_data()) return true; } return false; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::Vrf::HelperAddresses::has_operation() const { for (std::size_t index=0; index<helper_address.len(); index++) { if(helper_address[index]->has_operation()) return true; } return is_set(yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::Vrf::HelperAddresses::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "helper-addresses"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::Vrf::HelperAddresses::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::Vrf::HelperAddresses::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "helper-address") { auto ent_ = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::Vrf::HelperAddresses::HelperAddress>(); ent_->parent = this; helper_address.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::Vrf::HelperAddresses::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : helper_address.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::Vrf::HelperAddresses::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::Vrf::HelperAddresses::set_filter(const std::string & value_path, YFilter yfilter) { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::Vrf::HelperAddresses::has_leaf_or_child_of_name(const std::string & name) const { if(name == "helper-address") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::Vrf::HelperAddresses::HelperAddress::HelperAddress() : server_address{YType::str, "server-address"}, gateway_address{YType::str, "gateway-address"} { yang_name = "helper-address"; yang_parent_name = "helper-addresses"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::Vrf::HelperAddresses::HelperAddress::~HelperAddress() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::Vrf::HelperAddresses::HelperAddress::has_data() const { if (is_presence_container) return true; return server_address.is_set || gateway_address.is_set; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::Vrf::HelperAddresses::HelperAddress::has_operation() const { return is_set(yfilter) || ydk::is_set(server_address.yfilter) || ydk::is_set(gateway_address.yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::Vrf::HelperAddresses::HelperAddress::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "helper-address"; ADD_KEY_TOKEN(server_address, "server-address"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::Vrf::HelperAddresses::HelperAddress::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (server_address.is_set || is_set(server_address.yfilter)) leaf_name_data.push_back(server_address.get_name_leafdata()); if (gateway_address.is_set || is_set(gateway_address.yfilter)) leaf_name_data.push_back(gateway_address.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::Vrf::HelperAddresses::HelperAddress::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::Vrf::HelperAddresses::HelperAddress::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::Vrf::HelperAddresses::HelperAddress::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "server-address") { server_address = value; server_address.value_namespace = name_space; server_address.value_namespace_prefix = name_space_prefix; } if(value_path == "gateway-address") { gateway_address = value; gateway_address.value_namespace = name_space; gateway_address.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::Vrf::HelperAddresses::HelperAddress::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "server-address") { server_address.yfilter = yfilter; } if(value_path == "gateway-address") { gateway_address.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Vrfs::Vrf::HelperAddresses::HelperAddress::has_leaf_or_child_of_name(const std::string & name) const { if(name == "server-address" || name == "gateway-address") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Sessions::Sessions() : proxy_throttle_type(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Sessions::ProxyThrottleType>()) { proxy_throttle_type->parent = this; yang_name = "sessions"; yang_parent_name = "proxy"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Sessions::~Sessions() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Sessions::has_data() const { if (is_presence_container) return true; return (proxy_throttle_type != nullptr && proxy_throttle_type->has_data()); } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Sessions::has_operation() const { return is_set(yfilter) || (proxy_throttle_type != nullptr && proxy_throttle_type->has_operation()); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Sessions::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "sessions"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Sessions::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Sessions::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "proxy-throttle-type") { if(proxy_throttle_type == nullptr) { proxy_throttle_type = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Sessions::ProxyThrottleType>(); } return proxy_throttle_type; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Sessions::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(proxy_throttle_type != nullptr) { _children["proxy-throttle-type"] = proxy_throttle_type; } return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Sessions::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Sessions::set_filter(const std::string & value_path, YFilter yfilter) { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Sessions::has_leaf_or_child_of_name(const std::string & name) const { if(name == "proxy-throttle-type") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Sessions::ProxyThrottleType::ProxyThrottleType() : proxy_mac_throttle(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Sessions::ProxyThrottleType::ProxyMacThrottle>()) { proxy_mac_throttle->parent = this; yang_name = "proxy-throttle-type"; yang_parent_name = "sessions"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Sessions::ProxyThrottleType::~ProxyThrottleType() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Sessions::ProxyThrottleType::has_data() const { if (is_presence_container) return true; return (proxy_mac_throttle != nullptr && proxy_mac_throttle->has_data()); } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Sessions::ProxyThrottleType::has_operation() const { return is_set(yfilter) || (proxy_mac_throttle != nullptr && proxy_mac_throttle->has_operation()); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Sessions::ProxyThrottleType::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "proxy-throttle-type"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Sessions::ProxyThrottleType::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Sessions::ProxyThrottleType::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "proxy-mac-throttle") { if(proxy_mac_throttle == nullptr) { proxy_mac_throttle = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Sessions::ProxyThrottleType::ProxyMacThrottle>(); } return proxy_mac_throttle; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Sessions::ProxyThrottleType::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(proxy_mac_throttle != nullptr) { _children["proxy-mac-throttle"] = proxy_mac_throttle; } return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Sessions::ProxyThrottleType::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Sessions::ProxyThrottleType::set_filter(const std::string & value_path, YFilter yfilter) { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Sessions::ProxyThrottleType::has_leaf_or_child_of_name(const std::string & name) const { if(name == "proxy-mac-throttle") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Sessions::ProxyThrottleType::ProxyMacThrottle::ProxyMacThrottle() : num_discover{YType::uint32, "num-discover"}, num_request{YType::uint32, "num-request"}, num_block{YType::uint32, "num-block"} { yang_name = "proxy-mac-throttle"; yang_parent_name = "proxy-throttle-type"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Sessions::ProxyThrottleType::ProxyMacThrottle::~ProxyMacThrottle() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Sessions::ProxyThrottleType::ProxyMacThrottle::has_data() const { if (is_presence_container) return true; return num_discover.is_set || num_request.is_set || num_block.is_set; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Sessions::ProxyThrottleType::ProxyMacThrottle::has_operation() const { return is_set(yfilter) || ydk::is_set(num_discover.yfilter) || ydk::is_set(num_request.yfilter) || ydk::is_set(num_block.yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Sessions::ProxyThrottleType::ProxyMacThrottle::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "proxy-mac-throttle"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Sessions::ProxyThrottleType::ProxyMacThrottle::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (num_discover.is_set || is_set(num_discover.yfilter)) leaf_name_data.push_back(num_discover.get_name_leafdata()); if (num_request.is_set || is_set(num_request.yfilter)) leaf_name_data.push_back(num_request.get_name_leafdata()); if (num_block.is_set || is_set(num_block.yfilter)) leaf_name_data.push_back(num_block.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Sessions::ProxyThrottleType::ProxyMacThrottle::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Sessions::ProxyThrottleType::ProxyMacThrottle::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Sessions::ProxyThrottleType::ProxyMacThrottle::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "num-discover") { num_discover = value; num_discover.value_namespace = name_space; num_discover.value_namespace_prefix = name_space_prefix; } if(value_path == "num-request") { num_request = value; num_request.value_namespace = name_space; num_request.value_namespace_prefix = name_space_prefix; } if(value_path == "num-block") { num_block = value; num_block.value_namespace = name_space; num_block.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Sessions::ProxyThrottleType::ProxyMacThrottle::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "num-discover") { num_discover.yfilter = yfilter; } if(value_path == "num-request") { num_request.yfilter = yfilter; } if(value_path == "num-block") { num_block.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Sessions::ProxyThrottleType::ProxyMacThrottle::has_leaf_or_child_of_name(const std::string & name) const { if(name == "num-discover" || name == "num-request" || name == "num-block") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::LimitLease::LimitLease() : limit_type{YType::enumeration, "limit-type"}, limit_lease_count{YType::uint32, "limit-lease-count"} { yang_name = "limit-lease"; yang_parent_name = "proxy"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::LimitLease::~LimitLease() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::LimitLease::has_data() const { if (is_presence_container) return true; return limit_type.is_set || limit_lease_count.is_set; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::LimitLease::has_operation() const { return is_set(yfilter) || ydk::is_set(limit_type.yfilter) || ydk::is_set(limit_lease_count.yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::LimitLease::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "limit-lease"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::LimitLease::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (limit_type.is_set || is_set(limit_type.yfilter)) leaf_name_data.push_back(limit_type.get_name_leafdata()); if (limit_lease_count.is_set || is_set(limit_lease_count.yfilter)) leaf_name_data.push_back(limit_lease_count.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::LimitLease::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::LimitLease::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::LimitLease::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "limit-type") { limit_type = value; limit_type.value_namespace = name_space; limit_type.value_namespace_prefix = name_space_prefix; } if(value_path == "limit-lease-count") { limit_lease_count = value; limit_lease_count.value_namespace = name_space; limit_lease_count.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::LimitLease::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "limit-type") { limit_type.yfilter = yfilter; } if(value_path == "limit-lease-count") { limit_lease_count.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::LimitLease::has_leaf_or_child_of_name(const std::string & name) const { if(name == "limit-type" || name == "limit-lease-count") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::LeaseProxy::LeaseProxy() : client_lease_time{YType::uint32, "client-lease-time"}, set_server_options{YType::empty, "set-server-options"} { yang_name = "lease-proxy"; yang_parent_name = "proxy"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::LeaseProxy::~LeaseProxy() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::LeaseProxy::has_data() const { if (is_presence_container) return true; return client_lease_time.is_set || set_server_options.is_set; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::LeaseProxy::has_operation() const { return is_set(yfilter) || ydk::is_set(client_lease_time.yfilter) || ydk::is_set(set_server_options.yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::LeaseProxy::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "lease-proxy"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::LeaseProxy::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (client_lease_time.is_set || is_set(client_lease_time.yfilter)) leaf_name_data.push_back(client_lease_time.get_name_leafdata()); if (set_server_options.is_set || is_set(set_server_options.yfilter)) leaf_name_data.push_back(set_server_options.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::LeaseProxy::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::LeaseProxy::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::LeaseProxy::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "client-lease-time") { client_lease_time = value; client_lease_time.value_namespace = name_space; client_lease_time.value_namespace_prefix = name_space_prefix; } if(value_path == "set-server-options") { set_server_options = value; set_server_options.value_namespace = name_space; set_server_options.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::LeaseProxy::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "client-lease-time") { client_lease_time.yfilter = yfilter; } if(value_path == "set-server-options") { set_server_options.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::LeaseProxy::has_leaf_or_child_of_name(const std::string & name) const { if(name == "client-lease-time" || name == "set-server-options") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::BroadcastFlag::BroadcastFlag() : policy{YType::enumeration, "policy"} { yang_name = "broadcast-flag"; yang_parent_name = "proxy"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::BroadcastFlag::~BroadcastFlag() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::BroadcastFlag::has_data() const { if (is_presence_container) return true; return policy.is_set; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::BroadcastFlag::has_operation() const { return is_set(yfilter) || ydk::is_set(policy.yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::BroadcastFlag::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "broadcast-flag"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::BroadcastFlag::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (policy.is_set || is_set(policy.yfilter)) leaf_name_data.push_back(policy.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::BroadcastFlag::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::BroadcastFlag::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::BroadcastFlag::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "policy") { policy = value; policy.value_namespace = name_space; policy.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::BroadcastFlag::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "policy") { policy.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::BroadcastFlag::has_leaf_or_child_of_name(const std::string & name) const { if(name == "policy") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::Match() : def_options(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::DefOptions>()) , option_filters(std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::OptionFilters>()) { def_options->parent = this; option_filters->parent = this; yang_name = "match"; yang_parent_name = "proxy"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::~Match() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::has_data() const { if (is_presence_container) return true; return (def_options != nullptr && def_options->has_data()) || (option_filters != nullptr && option_filters->has_data()); } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::has_operation() const { return is_set(yfilter) || (def_options != nullptr && def_options->has_operation()) || (option_filters != nullptr && option_filters->has_operation()); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "match"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "def-options") { if(def_options == nullptr) { def_options = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::DefOptions>(); } return def_options; } if(child_yang_name == "option-filters") { if(option_filters == nullptr) { option_filters = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::OptionFilters>(); } return option_filters; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(def_options != nullptr) { _children["def-options"] = def_options; } if(option_filters != nullptr) { _children["option-filters"] = option_filters; } return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::set_filter(const std::string & value_path, YFilter yfilter) { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::has_leaf_or_child_of_name(const std::string & name) const { if(name == "def-options" || name == "option-filters") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::DefOptions::DefOptions() : def_option(this, {"def_matchoption"}) { yang_name = "def-options"; yang_parent_name = "match"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::DefOptions::~DefOptions() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::DefOptions::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<def_option.len(); index++) { if(def_option[index]->has_data()) return true; } return false; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::DefOptions::has_operation() const { for (std::size_t index=0; index<def_option.len(); index++) { if(def_option[index]->has_operation()) return true; } return is_set(yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::DefOptions::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "def-options"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::DefOptions::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::DefOptions::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "def-option") { auto ent_ = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::DefOptions::DefOption>(); ent_->parent = this; def_option.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::DefOptions::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : def_option.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::DefOptions::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::DefOptions::set_filter(const std::string & value_path, YFilter yfilter) { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::DefOptions::has_leaf_or_child_of_name(const std::string & name) const { if(name == "def-option") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::DefOptions::DefOption::DefOption() : def_matchoption{YType::uint32, "def-matchoption"}, def_matchaction{YType::enumeration, "def-matchaction"} { yang_name = "def-option"; yang_parent_name = "def-options"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::DefOptions::DefOption::~DefOption() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::DefOptions::DefOption::has_data() const { if (is_presence_container) return true; return def_matchoption.is_set || def_matchaction.is_set; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::DefOptions::DefOption::has_operation() const { return is_set(yfilter) || ydk::is_set(def_matchoption.yfilter) || ydk::is_set(def_matchaction.yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::DefOptions::DefOption::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "def-option"; ADD_KEY_TOKEN(def_matchoption, "def-matchoption"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::DefOptions::DefOption::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (def_matchoption.is_set || is_set(def_matchoption.yfilter)) leaf_name_data.push_back(def_matchoption.get_name_leafdata()); if (def_matchaction.is_set || is_set(def_matchaction.yfilter)) leaf_name_data.push_back(def_matchaction.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::DefOptions::DefOption::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::DefOptions::DefOption::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::DefOptions::DefOption::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "def-matchoption") { def_matchoption = value; def_matchoption.value_namespace = name_space; def_matchoption.value_namespace_prefix = name_space_prefix; } if(value_path == "def-matchaction") { def_matchaction = value; def_matchaction.value_namespace = name_space; def_matchaction.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::DefOptions::DefOption::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "def-matchoption") { def_matchoption.yfilter = yfilter; } if(value_path == "def-matchaction") { def_matchaction.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::DefOptions::DefOption::has_leaf_or_child_of_name(const std::string & name) const { if(name == "def-matchoption" || name == "def-matchaction") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::OptionFilters::OptionFilters() : option_filter(this, {"matchoption", "pattern", "format"}) { yang_name = "option-filters"; yang_parent_name = "match"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::OptionFilters::~OptionFilters() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::OptionFilters::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<option_filter.len(); index++) { if(option_filter[index]->has_data()) return true; } return false; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::OptionFilters::has_operation() const { for (std::size_t index=0; index<option_filter.len(); index++) { if(option_filter[index]->has_operation()) return true; } return is_set(yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::OptionFilters::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "option-filters"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::OptionFilters::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::OptionFilters::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "option-filter") { auto ent_ = std::make_shared<Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::OptionFilters::OptionFilter>(); ent_->parent = this; option_filter.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::OptionFilters::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : option_filter.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::OptionFilters::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::OptionFilters::set_filter(const std::string & value_path, YFilter yfilter) { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::OptionFilters::has_leaf_or_child_of_name(const std::string & name) const { if(name == "option-filter") return true; return false; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::OptionFilters::OptionFilter::OptionFilter() : matchoption{YType::uint32, "matchoption"}, pattern{YType::str, "pattern"}, format{YType::uint32, "format"}, matchaction{YType::enumeration, "matchaction"} { yang_name = "option-filter"; yang_parent_name = "option-filters"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::OptionFilters::OptionFilter::~OptionFilter() { } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::OptionFilters::OptionFilter::has_data() const { if (is_presence_container) return true; return matchoption.is_set || pattern.is_set || format.is_set || matchaction.is_set; } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::OptionFilters::OptionFilter::has_operation() const { return is_set(yfilter) || ydk::is_set(matchoption.yfilter) || ydk::is_set(pattern.yfilter) || ydk::is_set(format.yfilter) || ydk::is_set(matchaction.yfilter); } std::string Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::OptionFilters::OptionFilter::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "option-filter"; ADD_KEY_TOKEN(matchoption, "matchoption"); ADD_KEY_TOKEN(pattern, "pattern"); ADD_KEY_TOKEN(format, "format"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::OptionFilters::OptionFilter::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (matchoption.is_set || is_set(matchoption.yfilter)) leaf_name_data.push_back(matchoption.get_name_leafdata()); if (pattern.is_set || is_set(pattern.yfilter)) leaf_name_data.push_back(pattern.get_name_leafdata()); if (format.is_set || is_set(format.yfilter)) leaf_name_data.push_back(format.get_name_leafdata()); if (matchaction.is_set || is_set(matchaction.yfilter)) leaf_name_data.push_back(matchaction.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::OptionFilters::OptionFilter::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::OptionFilters::OptionFilter::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::OptionFilters::OptionFilter::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "matchoption") { matchoption = value; matchoption.value_namespace = name_space; matchoption.value_namespace_prefix = name_space_prefix; } if(value_path == "pattern") { pattern = value; pattern.value_namespace = name_space; pattern.value_namespace_prefix = name_space_prefix; } if(value_path == "format") { format = value; format.value_namespace = name_space; format.value_namespace_prefix = name_space_prefix; } if(value_path == "matchaction") { matchaction = value; matchaction.value_namespace = name_space; matchaction.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::OptionFilters::OptionFilter::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "matchoption") { matchoption.yfilter = yfilter; } if(value_path == "pattern") { pattern.yfilter = yfilter; } if(value_path == "format") { format.yfilter = yfilter; } if(value_path == "matchaction") { matchaction.yfilter = yfilter; } } bool Ipv4Dhcpd::Profiles::Profile::Modes::Mode::Proxy::Match::OptionFilters::OptionFilter::has_leaf_or_child_of_name(const std::string & name) const { if(name == "matchoption" || name == "pattern" || name == "format" || name == "matchaction") return true; return false; } Ipv4Dhcpd::Database::Database() : proxy{YType::empty, "proxy"}, server{YType::empty, "server"}, snoop{YType::empty, "snoop"}, full_write_interval{YType::uint32, "full-write-interval"}, incremental_write_interval{YType::uint32, "incremental-write-interval"} { yang_name = "database"; yang_parent_name = "ipv4-dhcpd"; is_top_level_class = false; has_list_ancestor = false; } Ipv4Dhcpd::Database::~Database() { } bool Ipv4Dhcpd::Database::has_data() const { if (is_presence_container) return true; return proxy.is_set || server.is_set || snoop.is_set || full_write_interval.is_set || incremental_write_interval.is_set; } bool Ipv4Dhcpd::Database::has_operation() const { return is_set(yfilter) || ydk::is_set(proxy.yfilter) || ydk::is_set(server.yfilter) || ydk::is_set(snoop.yfilter) || ydk::is_set(full_write_interval.yfilter) || ydk::is_set(incremental_write_interval.yfilter); } std::string Ipv4Dhcpd::Database::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-ipv4-dhcpd-cfg:ipv4-dhcpd/" << get_segment_path(); return path_buffer.str(); } std::string Ipv4Dhcpd::Database::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "database"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Database::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (proxy.is_set || is_set(proxy.yfilter)) leaf_name_data.push_back(proxy.get_name_leafdata()); if (server.is_set || is_set(server.yfilter)) leaf_name_data.push_back(server.get_name_leafdata()); if (snoop.is_set || is_set(snoop.yfilter)) leaf_name_data.push_back(snoop.get_name_leafdata()); if (full_write_interval.is_set || is_set(full_write_interval.yfilter)) leaf_name_data.push_back(full_write_interval.get_name_leafdata()); if (incremental_write_interval.is_set || is_set(incremental_write_interval.yfilter)) leaf_name_data.push_back(incremental_write_interval.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Database::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Database::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Database::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "proxy") { proxy = value; proxy.value_namespace = name_space; proxy.value_namespace_prefix = name_space_prefix; } if(value_path == "server") { server = value; server.value_namespace = name_space; server.value_namespace_prefix = name_space_prefix; } if(value_path == "snoop") { snoop = value; snoop.value_namespace = name_space; snoop.value_namespace_prefix = name_space_prefix; } if(value_path == "full-write-interval") { full_write_interval = value; full_write_interval.value_namespace = name_space; full_write_interval.value_namespace_prefix = name_space_prefix; } if(value_path == "incremental-write-interval") { incremental_write_interval = value; incremental_write_interval.value_namespace = name_space; incremental_write_interval.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Database::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "proxy") { proxy.yfilter = yfilter; } if(value_path == "server") { server.yfilter = yfilter; } if(value_path == "snoop") { snoop.yfilter = yfilter; } if(value_path == "full-write-interval") { full_write_interval.yfilter = yfilter; } if(value_path == "incremental-write-interval") { incremental_write_interval.yfilter = yfilter; } } bool Ipv4Dhcpd::Database::has_leaf_or_child_of_name(const std::string & name) const { if(name == "proxy" || name == "server" || name == "snoop" || name == "full-write-interval" || name == "incremental-write-interval") return true; return false; } Ipv4Dhcpd::Interfaces::Interfaces() : interface(this, {"interface_name"}) { yang_name = "interfaces"; yang_parent_name = "ipv4-dhcpd"; is_top_level_class = false; has_list_ancestor = false; } Ipv4Dhcpd::Interfaces::~Interfaces() { } bool Ipv4Dhcpd::Interfaces::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<interface.len(); index++) { if(interface[index]->has_data()) return true; } return false; } bool Ipv4Dhcpd::Interfaces::has_operation() const { for (std::size_t index=0; index<interface.len(); index++) { if(interface[index]->has_operation()) return true; } return is_set(yfilter); } std::string Ipv4Dhcpd::Interfaces::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-ipv4-dhcpd-cfg:ipv4-dhcpd/" << get_segment_path(); return path_buffer.str(); } std::string Ipv4Dhcpd::Interfaces::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "interfaces"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Interfaces::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Interfaces::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "interface") { auto ent_ = std::make_shared<Ipv4Dhcpd::Interfaces::Interface>(); ent_->parent = this; interface.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Interfaces::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : interface.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Ipv4Dhcpd::Interfaces::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Ipv4Dhcpd::Interfaces::set_filter(const std::string & value_path, YFilter yfilter) { } bool Ipv4Dhcpd::Interfaces::has_leaf_or_child_of_name(const std::string & name) const { if(name == "interface") return true; return false; } Ipv4Dhcpd::Interfaces::Interface::Interface() : interface_name{YType::str, "interface-name"} , proxy_interface(std::make_shared<Ipv4Dhcpd::Interfaces::Interface::ProxyInterface>()) , base_interface(std::make_shared<Ipv4Dhcpd::Interfaces::Interface::BaseInterface>()) , relay_interface(std::make_shared<Ipv4Dhcpd::Interfaces::Interface::RelayInterface>()) , static_mode(std::make_shared<Ipv4Dhcpd::Interfaces::Interface::StaticMode>()) , profile(nullptr) // presence node , server_interface(std::make_shared<Ipv4Dhcpd::Interfaces::Interface::ServerInterface>()) , snoop_interface(std::make_shared<Ipv4Dhcpd::Interfaces::Interface::SnoopInterface>()) { proxy_interface->parent = this; base_interface->parent = this; relay_interface->parent = this; static_mode->parent = this; server_interface->parent = this; snoop_interface->parent = this; yang_name = "interface"; yang_parent_name = "interfaces"; is_top_level_class = false; has_list_ancestor = false; } Ipv4Dhcpd::Interfaces::Interface::~Interface() { } bool Ipv4Dhcpd::Interfaces::Interface::has_data() const { if (is_presence_container) return true; return interface_name.is_set || (proxy_interface != nullptr && proxy_interface->has_data()) || (base_interface != nullptr && base_interface->has_data()) || (relay_interface != nullptr && relay_interface->has_data()) || (static_mode != nullptr && static_mode->has_data()) || (profile != nullptr && profile->has_data()) || (server_interface != nullptr && server_interface->has_data()) || (snoop_interface != nullptr && snoop_interface->has_data()); } bool Ipv4Dhcpd::Interfaces::Interface::has_operation() const { return is_set(yfilter) || ydk::is_set(interface_name.yfilter) || (proxy_interface != nullptr && proxy_interface->has_operation()) || (base_interface != nullptr && base_interface->has_operation()) || (relay_interface != nullptr && relay_interface->has_operation()) || (static_mode != nullptr && static_mode->has_operation()) || (profile != nullptr && profile->has_operation()) || (server_interface != nullptr && server_interface->has_operation()) || (snoop_interface != nullptr && snoop_interface->has_operation()); } std::string Ipv4Dhcpd::Interfaces::Interface::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-ipv4-dhcpd-cfg:ipv4-dhcpd/interfaces/" << get_segment_path(); return path_buffer.str(); } std::string Ipv4Dhcpd::Interfaces::Interface::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "interface"; ADD_KEY_TOKEN(interface_name, "interface-name"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Interfaces::Interface::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (interface_name.is_set || is_set(interface_name.yfilter)) leaf_name_data.push_back(interface_name.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Interfaces::Interface::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "proxy-interface") { if(proxy_interface == nullptr) { proxy_interface = std::make_shared<Ipv4Dhcpd::Interfaces::Interface::ProxyInterface>(); } return proxy_interface; } if(child_yang_name == "base-interface") { if(base_interface == nullptr) { base_interface = std::make_shared<Ipv4Dhcpd::Interfaces::Interface::BaseInterface>(); } return base_interface; } if(child_yang_name == "relay-interface") { if(relay_interface == nullptr) { relay_interface = std::make_shared<Ipv4Dhcpd::Interfaces::Interface::RelayInterface>(); } return relay_interface; } if(child_yang_name == "static-mode") { if(static_mode == nullptr) { static_mode = std::make_shared<Ipv4Dhcpd::Interfaces::Interface::StaticMode>(); } return static_mode; } if(child_yang_name == "profile") { if(profile == nullptr) { profile = std::make_shared<Ipv4Dhcpd::Interfaces::Interface::Profile>(); } return profile; } if(child_yang_name == "server-interface") { if(server_interface == nullptr) { server_interface = std::make_shared<Ipv4Dhcpd::Interfaces::Interface::ServerInterface>(); } return server_interface; } if(child_yang_name == "snoop-interface") { if(snoop_interface == nullptr) { snoop_interface = std::make_shared<Ipv4Dhcpd::Interfaces::Interface::SnoopInterface>(); } return snoop_interface; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Interfaces::Interface::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(proxy_interface != nullptr) { _children["proxy-interface"] = proxy_interface; } if(base_interface != nullptr) { _children["base-interface"] = base_interface; } if(relay_interface != nullptr) { _children["relay-interface"] = relay_interface; } if(static_mode != nullptr) { _children["static-mode"] = static_mode; } if(profile != nullptr) { _children["profile"] = profile; } if(server_interface != nullptr) { _children["server-interface"] = server_interface; } if(snoop_interface != nullptr) { _children["snoop-interface"] = snoop_interface; } return _children; } void Ipv4Dhcpd::Interfaces::Interface::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "interface-name") { interface_name = value; interface_name.value_namespace = name_space; interface_name.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Interfaces::Interface::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "interface-name") { interface_name.yfilter = yfilter; } } bool Ipv4Dhcpd::Interfaces::Interface::has_leaf_or_child_of_name(const std::string & name) const { if(name == "proxy-interface" || name == "base-interface" || name == "relay-interface" || name == "static-mode" || name == "profile" || name == "server-interface" || name == "snoop-interface" || name == "interface-name") return true; return false; } Ipv4Dhcpd::Interfaces::Interface::ProxyInterface::ProxyInterface() : profile{YType::str, "profile"} , dhcp_circuit_id(nullptr) // presence node { yang_name = "proxy-interface"; yang_parent_name = "interface"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Interfaces::Interface::ProxyInterface::~ProxyInterface() { } bool Ipv4Dhcpd::Interfaces::Interface::ProxyInterface::has_data() const { if (is_presence_container) return true; return profile.is_set || (dhcp_circuit_id != nullptr && dhcp_circuit_id->has_data()); } bool Ipv4Dhcpd::Interfaces::Interface::ProxyInterface::has_operation() const { return is_set(yfilter) || ydk::is_set(profile.yfilter) || (dhcp_circuit_id != nullptr && dhcp_circuit_id->has_operation()); } std::string Ipv4Dhcpd::Interfaces::Interface::ProxyInterface::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "proxy-interface"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Interfaces::Interface::ProxyInterface::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (profile.is_set || is_set(profile.yfilter)) leaf_name_data.push_back(profile.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Interfaces::Interface::ProxyInterface::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "dhcp-circuit-id") { if(dhcp_circuit_id == nullptr) { dhcp_circuit_id = std::make_shared<Ipv4Dhcpd::Interfaces::Interface::ProxyInterface::DhcpCircuitId>(); } return dhcp_circuit_id; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Interfaces::Interface::ProxyInterface::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(dhcp_circuit_id != nullptr) { _children["dhcp-circuit-id"] = dhcp_circuit_id; } return _children; } void Ipv4Dhcpd::Interfaces::Interface::ProxyInterface::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "profile") { profile = value; profile.value_namespace = name_space; profile.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Interfaces::Interface::ProxyInterface::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "profile") { profile.yfilter = yfilter; } } bool Ipv4Dhcpd::Interfaces::Interface::ProxyInterface::has_leaf_or_child_of_name(const std::string & name) const { if(name == "dhcp-circuit-id" || name == "profile") return true; return false; } Ipv4Dhcpd::Interfaces::Interface::ProxyInterface::DhcpCircuitId::DhcpCircuitId() : circuit_id{YType::str, "circuit-id"}, format{YType::enumeration, "format"}, argument1{YType::enumeration, "argument1"}, argument2{YType::enumeration, "argument2"}, argument3{YType::enumeration, "argument3"}, argument4{YType::enumeration, "argument4"}, argument5{YType::enumeration, "argument5"}, argument6{YType::enumeration, "argument6"}, argument7{YType::enumeration, "argument7"}, argument8{YType::enumeration, "argument8"}, argument9{YType::enumeration, "argument9"}, argument10{YType::enumeration, "argument10"}, argument11{YType::enumeration, "argument11"}, argument12{YType::enumeration, "argument12"}, argument13{YType::enumeration, "argument13"}, argument14{YType::enumeration, "argument14"}, argument15{YType::enumeration, "argument15"}, argument16{YType::enumeration, "argument16"} { yang_name = "dhcp-circuit-id"; yang_parent_name = "proxy-interface"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true; } Ipv4Dhcpd::Interfaces::Interface::ProxyInterface::DhcpCircuitId::~DhcpCircuitId() { } bool Ipv4Dhcpd::Interfaces::Interface::ProxyInterface::DhcpCircuitId::has_data() const { if (is_presence_container) return true; return circuit_id.is_set || format.is_set || argument1.is_set || argument2.is_set || argument3.is_set || argument4.is_set || argument5.is_set || argument6.is_set || argument7.is_set || argument8.is_set || argument9.is_set || argument10.is_set || argument11.is_set || argument12.is_set || argument13.is_set || argument14.is_set || argument15.is_set || argument16.is_set; } bool Ipv4Dhcpd::Interfaces::Interface::ProxyInterface::DhcpCircuitId::has_operation() const { return is_set(yfilter) || ydk::is_set(circuit_id.yfilter) || ydk::is_set(format.yfilter) || ydk::is_set(argument1.yfilter) || ydk::is_set(argument2.yfilter) || ydk::is_set(argument3.yfilter) || ydk::is_set(argument4.yfilter) || ydk::is_set(argument5.yfilter) || ydk::is_set(argument6.yfilter) || ydk::is_set(argument7.yfilter) || ydk::is_set(argument8.yfilter) || ydk::is_set(argument9.yfilter) || ydk::is_set(argument10.yfilter) || ydk::is_set(argument11.yfilter) || ydk::is_set(argument12.yfilter) || ydk::is_set(argument13.yfilter) || ydk::is_set(argument14.yfilter) || ydk::is_set(argument15.yfilter) || ydk::is_set(argument16.yfilter); } std::string Ipv4Dhcpd::Interfaces::Interface::ProxyInterface::DhcpCircuitId::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "dhcp-circuit-id"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Interfaces::Interface::ProxyInterface::DhcpCircuitId::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (circuit_id.is_set || is_set(circuit_id.yfilter)) leaf_name_data.push_back(circuit_id.get_name_leafdata()); if (format.is_set || is_set(format.yfilter)) leaf_name_data.push_back(format.get_name_leafdata()); if (argument1.is_set || is_set(argument1.yfilter)) leaf_name_data.push_back(argument1.get_name_leafdata()); if (argument2.is_set || is_set(argument2.yfilter)) leaf_name_data.push_back(argument2.get_name_leafdata()); if (argument3.is_set || is_set(argument3.yfilter)) leaf_name_data.push_back(argument3.get_name_leafdata()); if (argument4.is_set || is_set(argument4.yfilter)) leaf_name_data.push_back(argument4.get_name_leafdata()); if (argument5.is_set || is_set(argument5.yfilter)) leaf_name_data.push_back(argument5.get_name_leafdata()); if (argument6.is_set || is_set(argument6.yfilter)) leaf_name_data.push_back(argument6.get_name_leafdata()); if (argument7.is_set || is_set(argument7.yfilter)) leaf_name_data.push_back(argument7.get_name_leafdata()); if (argument8.is_set || is_set(argument8.yfilter)) leaf_name_data.push_back(argument8.get_name_leafdata()); if (argument9.is_set || is_set(argument9.yfilter)) leaf_name_data.push_back(argument9.get_name_leafdata()); if (argument10.is_set || is_set(argument10.yfilter)) leaf_name_data.push_back(argument10.get_name_leafdata()); if (argument11.is_set || is_set(argument11.yfilter)) leaf_name_data.push_back(argument11.get_name_leafdata()); if (argument12.is_set || is_set(argument12.yfilter)) leaf_name_data.push_back(argument12.get_name_leafdata()); if (argument13.is_set || is_set(argument13.yfilter)) leaf_name_data.push_back(argument13.get_name_leafdata()); if (argument14.is_set || is_set(argument14.yfilter)) leaf_name_data.push_back(argument14.get_name_leafdata()); if (argument15.is_set || is_set(argument15.yfilter)) leaf_name_data.push_back(argument15.get_name_leafdata()); if (argument16.is_set || is_set(argument16.yfilter)) leaf_name_data.push_back(argument16.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Interfaces::Interface::ProxyInterface::DhcpCircuitId::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Interfaces::Interface::ProxyInterface::DhcpCircuitId::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Interfaces::Interface::ProxyInterface::DhcpCircuitId::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "circuit-id") { circuit_id = value; circuit_id.value_namespace = name_space; circuit_id.value_namespace_prefix = name_space_prefix; } if(value_path == "format") { format = value; format.value_namespace = name_space; format.value_namespace_prefix = name_space_prefix; } if(value_path == "argument1") { argument1 = value; argument1.value_namespace = name_space; argument1.value_namespace_prefix = name_space_prefix; } if(value_path == "argument2") { argument2 = value; argument2.value_namespace = name_space; argument2.value_namespace_prefix = name_space_prefix; } if(value_path == "argument3") { argument3 = value; argument3.value_namespace = name_space; argument3.value_namespace_prefix = name_space_prefix; } if(value_path == "argument4") { argument4 = value; argument4.value_namespace = name_space; argument4.value_namespace_prefix = name_space_prefix; } if(value_path == "argument5") { argument5 = value; argument5.value_namespace = name_space; argument5.value_namespace_prefix = name_space_prefix; } if(value_path == "argument6") { argument6 = value; argument6.value_namespace = name_space; argument6.value_namespace_prefix = name_space_prefix; } if(value_path == "argument7") { argument7 = value; argument7.value_namespace = name_space; argument7.value_namespace_prefix = name_space_prefix; } if(value_path == "argument8") { argument8 = value; argument8.value_namespace = name_space; argument8.value_namespace_prefix = name_space_prefix; } if(value_path == "argument9") { argument9 = value; argument9.value_namespace = name_space; argument9.value_namespace_prefix = name_space_prefix; } if(value_path == "argument10") { argument10 = value; argument10.value_namespace = name_space; argument10.value_namespace_prefix = name_space_prefix; } if(value_path == "argument11") { argument11 = value; argument11.value_namespace = name_space; argument11.value_namespace_prefix = name_space_prefix; } if(value_path == "argument12") { argument12 = value; argument12.value_namespace = name_space; argument12.value_namespace_prefix = name_space_prefix; } if(value_path == "argument13") { argument13 = value; argument13.value_namespace = name_space; argument13.value_namespace_prefix = name_space_prefix; } if(value_path == "argument14") { argument14 = value; argument14.value_namespace = name_space; argument14.value_namespace_prefix = name_space_prefix; } if(value_path == "argument15") { argument15 = value; argument15.value_namespace = name_space; argument15.value_namespace_prefix = name_space_prefix; } if(value_path == "argument16") { argument16 = value; argument16.value_namespace = name_space; argument16.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Interfaces::Interface::ProxyInterface::DhcpCircuitId::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "circuit-id") { circuit_id.yfilter = yfilter; } if(value_path == "format") { format.yfilter = yfilter; } if(value_path == "argument1") { argument1.yfilter = yfilter; } if(value_path == "argument2") { argument2.yfilter = yfilter; } if(value_path == "argument3") { argument3.yfilter = yfilter; } if(value_path == "argument4") { argument4.yfilter = yfilter; } if(value_path == "argument5") { argument5.yfilter = yfilter; } if(value_path == "argument6") { argument6.yfilter = yfilter; } if(value_path == "argument7") { argument7.yfilter = yfilter; } if(value_path == "argument8") { argument8.yfilter = yfilter; } if(value_path == "argument9") { argument9.yfilter = yfilter; } if(value_path == "argument10") { argument10.yfilter = yfilter; } if(value_path == "argument11") { argument11.yfilter = yfilter; } if(value_path == "argument12") { argument12.yfilter = yfilter; } if(value_path == "argument13") { argument13.yfilter = yfilter; } if(value_path == "argument14") { argument14.yfilter = yfilter; } if(value_path == "argument15") { argument15.yfilter = yfilter; } if(value_path == "argument16") { argument16.yfilter = yfilter; } } bool Ipv4Dhcpd::Interfaces::Interface::ProxyInterface::DhcpCircuitId::has_leaf_or_child_of_name(const std::string & name) const { if(name == "circuit-id" || name == "format" || name == "argument1" || name == "argument2" || name == "argument3" || name == "argument4" || name == "argument5" || name == "argument6" || name == "argument7" || name == "argument8" || name == "argument9" || name == "argument10" || name == "argument11" || name == "argument12" || name == "argument13" || name == "argument14" || name == "argument15" || name == "argument16") return true; return false; } Ipv4Dhcpd::Interfaces::Interface::BaseInterface::BaseInterface() : profile{YType::str, "profile"} , base_dhcp_circuit_id(nullptr) // presence node { yang_name = "base-interface"; yang_parent_name = "interface"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Interfaces::Interface::BaseInterface::~BaseInterface() { } bool Ipv4Dhcpd::Interfaces::Interface::BaseInterface::has_data() const { if (is_presence_container) return true; return profile.is_set || (base_dhcp_circuit_id != nullptr && base_dhcp_circuit_id->has_data()); } bool Ipv4Dhcpd::Interfaces::Interface::BaseInterface::has_operation() const { return is_set(yfilter) || ydk::is_set(profile.yfilter) || (base_dhcp_circuit_id != nullptr && base_dhcp_circuit_id->has_operation()); } std::string Ipv4Dhcpd::Interfaces::Interface::BaseInterface::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "base-interface"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Interfaces::Interface::BaseInterface::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (profile.is_set || is_set(profile.yfilter)) leaf_name_data.push_back(profile.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Interfaces::Interface::BaseInterface::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "base-dhcp-circuit-id") { if(base_dhcp_circuit_id == nullptr) { base_dhcp_circuit_id = std::make_shared<Ipv4Dhcpd::Interfaces::Interface::BaseInterface::BaseDhcpCircuitId>(); } return base_dhcp_circuit_id; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Interfaces::Interface::BaseInterface::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(base_dhcp_circuit_id != nullptr) { _children["base-dhcp-circuit-id"] = base_dhcp_circuit_id; } return _children; } void Ipv4Dhcpd::Interfaces::Interface::BaseInterface::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "profile") { profile = value; profile.value_namespace = name_space; profile.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Interfaces::Interface::BaseInterface::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "profile") { profile.yfilter = yfilter; } } bool Ipv4Dhcpd::Interfaces::Interface::BaseInterface::has_leaf_or_child_of_name(const std::string & name) const { if(name == "base-dhcp-circuit-id" || name == "profile") return true; return false; } Ipv4Dhcpd::Interfaces::Interface::BaseInterface::BaseDhcpCircuitId::BaseDhcpCircuitId() : circuit_id{YType::str, "circuit-id"}, format{YType::enumeration, "format"}, argument1{YType::enumeration, "argument1"}, argument2{YType::enumeration, "argument2"}, argument3{YType::enumeration, "argument3"}, argument4{YType::enumeration, "argument4"}, argument5{YType::enumeration, "argument5"}, argument6{YType::enumeration, "argument6"}, argument7{YType::enumeration, "argument7"}, argument8{YType::enumeration, "argument8"}, argument9{YType::enumeration, "argument9"}, argument10{YType::enumeration, "argument10"}, argument11{YType::enumeration, "argument11"}, argument12{YType::enumeration, "argument12"}, argument13{YType::enumeration, "argument13"}, argument14{YType::enumeration, "argument14"}, argument15{YType::enumeration, "argument15"}, argument16{YType::enumeration, "argument16"} { yang_name = "base-dhcp-circuit-id"; yang_parent_name = "base-interface"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true; } Ipv4Dhcpd::Interfaces::Interface::BaseInterface::BaseDhcpCircuitId::~BaseDhcpCircuitId() { } bool Ipv4Dhcpd::Interfaces::Interface::BaseInterface::BaseDhcpCircuitId::has_data() const { if (is_presence_container) return true; return circuit_id.is_set || format.is_set || argument1.is_set || argument2.is_set || argument3.is_set || argument4.is_set || argument5.is_set || argument6.is_set || argument7.is_set || argument8.is_set || argument9.is_set || argument10.is_set || argument11.is_set || argument12.is_set || argument13.is_set || argument14.is_set || argument15.is_set || argument16.is_set; } bool Ipv4Dhcpd::Interfaces::Interface::BaseInterface::BaseDhcpCircuitId::has_operation() const { return is_set(yfilter) || ydk::is_set(circuit_id.yfilter) || ydk::is_set(format.yfilter) || ydk::is_set(argument1.yfilter) || ydk::is_set(argument2.yfilter) || ydk::is_set(argument3.yfilter) || ydk::is_set(argument4.yfilter) || ydk::is_set(argument5.yfilter) || ydk::is_set(argument6.yfilter) || ydk::is_set(argument7.yfilter) || ydk::is_set(argument8.yfilter) || ydk::is_set(argument9.yfilter) || ydk::is_set(argument10.yfilter) || ydk::is_set(argument11.yfilter) || ydk::is_set(argument12.yfilter) || ydk::is_set(argument13.yfilter) || ydk::is_set(argument14.yfilter) || ydk::is_set(argument15.yfilter) || ydk::is_set(argument16.yfilter); } std::string Ipv4Dhcpd::Interfaces::Interface::BaseInterface::BaseDhcpCircuitId::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "base-dhcp-circuit-id"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Interfaces::Interface::BaseInterface::BaseDhcpCircuitId::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (circuit_id.is_set || is_set(circuit_id.yfilter)) leaf_name_data.push_back(circuit_id.get_name_leafdata()); if (format.is_set || is_set(format.yfilter)) leaf_name_data.push_back(format.get_name_leafdata()); if (argument1.is_set || is_set(argument1.yfilter)) leaf_name_data.push_back(argument1.get_name_leafdata()); if (argument2.is_set || is_set(argument2.yfilter)) leaf_name_data.push_back(argument2.get_name_leafdata()); if (argument3.is_set || is_set(argument3.yfilter)) leaf_name_data.push_back(argument3.get_name_leafdata()); if (argument4.is_set || is_set(argument4.yfilter)) leaf_name_data.push_back(argument4.get_name_leafdata()); if (argument5.is_set || is_set(argument5.yfilter)) leaf_name_data.push_back(argument5.get_name_leafdata()); if (argument6.is_set || is_set(argument6.yfilter)) leaf_name_data.push_back(argument6.get_name_leafdata()); if (argument7.is_set || is_set(argument7.yfilter)) leaf_name_data.push_back(argument7.get_name_leafdata()); if (argument8.is_set || is_set(argument8.yfilter)) leaf_name_data.push_back(argument8.get_name_leafdata()); if (argument9.is_set || is_set(argument9.yfilter)) leaf_name_data.push_back(argument9.get_name_leafdata()); if (argument10.is_set || is_set(argument10.yfilter)) leaf_name_data.push_back(argument10.get_name_leafdata()); if (argument11.is_set || is_set(argument11.yfilter)) leaf_name_data.push_back(argument11.get_name_leafdata()); if (argument12.is_set || is_set(argument12.yfilter)) leaf_name_data.push_back(argument12.get_name_leafdata()); if (argument13.is_set || is_set(argument13.yfilter)) leaf_name_data.push_back(argument13.get_name_leafdata()); if (argument14.is_set || is_set(argument14.yfilter)) leaf_name_data.push_back(argument14.get_name_leafdata()); if (argument15.is_set || is_set(argument15.yfilter)) leaf_name_data.push_back(argument15.get_name_leafdata()); if (argument16.is_set || is_set(argument16.yfilter)) leaf_name_data.push_back(argument16.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Interfaces::Interface::BaseInterface::BaseDhcpCircuitId::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Interfaces::Interface::BaseInterface::BaseDhcpCircuitId::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Interfaces::Interface::BaseInterface::BaseDhcpCircuitId::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "circuit-id") { circuit_id = value; circuit_id.value_namespace = name_space; circuit_id.value_namespace_prefix = name_space_prefix; } if(value_path == "format") { format = value; format.value_namespace = name_space; format.value_namespace_prefix = name_space_prefix; } if(value_path == "argument1") { argument1 = value; argument1.value_namespace = name_space; argument1.value_namespace_prefix = name_space_prefix; } if(value_path == "argument2") { argument2 = value; argument2.value_namespace = name_space; argument2.value_namespace_prefix = name_space_prefix; } if(value_path == "argument3") { argument3 = value; argument3.value_namespace = name_space; argument3.value_namespace_prefix = name_space_prefix; } if(value_path == "argument4") { argument4 = value; argument4.value_namespace = name_space; argument4.value_namespace_prefix = name_space_prefix; } if(value_path == "argument5") { argument5 = value; argument5.value_namespace = name_space; argument5.value_namespace_prefix = name_space_prefix; } if(value_path == "argument6") { argument6 = value; argument6.value_namespace = name_space; argument6.value_namespace_prefix = name_space_prefix; } if(value_path == "argument7") { argument7 = value; argument7.value_namespace = name_space; argument7.value_namespace_prefix = name_space_prefix; } if(value_path == "argument8") { argument8 = value; argument8.value_namespace = name_space; argument8.value_namespace_prefix = name_space_prefix; } if(value_path == "argument9") { argument9 = value; argument9.value_namespace = name_space; argument9.value_namespace_prefix = name_space_prefix; } if(value_path == "argument10") { argument10 = value; argument10.value_namespace = name_space; argument10.value_namespace_prefix = name_space_prefix; } if(value_path == "argument11") { argument11 = value; argument11.value_namespace = name_space; argument11.value_namespace_prefix = name_space_prefix; } if(value_path == "argument12") { argument12 = value; argument12.value_namespace = name_space; argument12.value_namespace_prefix = name_space_prefix; } if(value_path == "argument13") { argument13 = value; argument13.value_namespace = name_space; argument13.value_namespace_prefix = name_space_prefix; } if(value_path == "argument14") { argument14 = value; argument14.value_namespace = name_space; argument14.value_namespace_prefix = name_space_prefix; } if(value_path == "argument15") { argument15 = value; argument15.value_namespace = name_space; argument15.value_namespace_prefix = name_space_prefix; } if(value_path == "argument16") { argument16 = value; argument16.value_namespace = name_space; argument16.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Interfaces::Interface::BaseInterface::BaseDhcpCircuitId::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "circuit-id") { circuit_id.yfilter = yfilter; } if(value_path == "format") { format.yfilter = yfilter; } if(value_path == "argument1") { argument1.yfilter = yfilter; } if(value_path == "argument2") { argument2.yfilter = yfilter; } if(value_path == "argument3") { argument3.yfilter = yfilter; } if(value_path == "argument4") { argument4.yfilter = yfilter; } if(value_path == "argument5") { argument5.yfilter = yfilter; } if(value_path == "argument6") { argument6.yfilter = yfilter; } if(value_path == "argument7") { argument7.yfilter = yfilter; } if(value_path == "argument8") { argument8.yfilter = yfilter; } if(value_path == "argument9") { argument9.yfilter = yfilter; } if(value_path == "argument10") { argument10.yfilter = yfilter; } if(value_path == "argument11") { argument11.yfilter = yfilter; } if(value_path == "argument12") { argument12.yfilter = yfilter; } if(value_path == "argument13") { argument13.yfilter = yfilter; } if(value_path == "argument14") { argument14.yfilter = yfilter; } if(value_path == "argument15") { argument15.yfilter = yfilter; } if(value_path == "argument16") { argument16.yfilter = yfilter; } } bool Ipv4Dhcpd::Interfaces::Interface::BaseInterface::BaseDhcpCircuitId::has_leaf_or_child_of_name(const std::string & name) const { if(name == "circuit-id" || name == "format" || name == "argument1" || name == "argument2" || name == "argument3" || name == "argument4" || name == "argument5" || name == "argument6" || name == "argument7" || name == "argument8" || name == "argument9" || name == "argument10" || name == "argument11" || name == "argument12" || name == "argument13" || name == "argument14" || name == "argument15" || name == "argument16") return true; return false; } Ipv4Dhcpd::Interfaces::Interface::RelayInterface::RelayInterface() : relay_dhcp_circuit_id(nullptr) // presence node { yang_name = "relay-interface"; yang_parent_name = "interface"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Interfaces::Interface::RelayInterface::~RelayInterface() { } bool Ipv4Dhcpd::Interfaces::Interface::RelayInterface::has_data() const { if (is_presence_container) return true; return (relay_dhcp_circuit_id != nullptr && relay_dhcp_circuit_id->has_data()); } bool Ipv4Dhcpd::Interfaces::Interface::RelayInterface::has_operation() const { return is_set(yfilter) || (relay_dhcp_circuit_id != nullptr && relay_dhcp_circuit_id->has_operation()); } std::string Ipv4Dhcpd::Interfaces::Interface::RelayInterface::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "relay-interface"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Interfaces::Interface::RelayInterface::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Interfaces::Interface::RelayInterface::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "relay-dhcp-circuit-id") { if(relay_dhcp_circuit_id == nullptr) { relay_dhcp_circuit_id = std::make_shared<Ipv4Dhcpd::Interfaces::Interface::RelayInterface::RelayDhcpCircuitId>(); } return relay_dhcp_circuit_id; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Interfaces::Interface::RelayInterface::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(relay_dhcp_circuit_id != nullptr) { _children["relay-dhcp-circuit-id"] = relay_dhcp_circuit_id; } return _children; } void Ipv4Dhcpd::Interfaces::Interface::RelayInterface::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Ipv4Dhcpd::Interfaces::Interface::RelayInterface::set_filter(const std::string & value_path, YFilter yfilter) { } bool Ipv4Dhcpd::Interfaces::Interface::RelayInterface::has_leaf_or_child_of_name(const std::string & name) const { if(name == "relay-dhcp-circuit-id") return true; return false; } Ipv4Dhcpd::Interfaces::Interface::RelayInterface::RelayDhcpCircuitId::RelayDhcpCircuitId() : circuit_id{YType::str, "circuit-id"}, format{YType::enumeration, "format"}, argument1{YType::enumeration, "argument1"}, argument2{YType::enumeration, "argument2"}, argument3{YType::enumeration, "argument3"}, argument4{YType::enumeration, "argument4"}, argument5{YType::enumeration, "argument5"}, argument6{YType::enumeration, "argument6"}, argument7{YType::enumeration, "argument7"}, argument8{YType::enumeration, "argument8"}, argument9{YType::enumeration, "argument9"}, argument10{YType::enumeration, "argument10"}, argument11{YType::enumeration, "argument11"}, argument12{YType::enumeration, "argument12"}, argument13{YType::enumeration, "argument13"}, argument14{YType::enumeration, "argument14"}, argument15{YType::enumeration, "argument15"}, argument16{YType::enumeration, "argument16"} { yang_name = "relay-dhcp-circuit-id"; yang_parent_name = "relay-interface"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true; } Ipv4Dhcpd::Interfaces::Interface::RelayInterface::RelayDhcpCircuitId::~RelayDhcpCircuitId() { } bool Ipv4Dhcpd::Interfaces::Interface::RelayInterface::RelayDhcpCircuitId::has_data() const { if (is_presence_container) return true; return circuit_id.is_set || format.is_set || argument1.is_set || argument2.is_set || argument3.is_set || argument4.is_set || argument5.is_set || argument6.is_set || argument7.is_set || argument8.is_set || argument9.is_set || argument10.is_set || argument11.is_set || argument12.is_set || argument13.is_set || argument14.is_set || argument15.is_set || argument16.is_set; } bool Ipv4Dhcpd::Interfaces::Interface::RelayInterface::RelayDhcpCircuitId::has_operation() const { return is_set(yfilter) || ydk::is_set(circuit_id.yfilter) || ydk::is_set(format.yfilter) || ydk::is_set(argument1.yfilter) || ydk::is_set(argument2.yfilter) || ydk::is_set(argument3.yfilter) || ydk::is_set(argument4.yfilter) || ydk::is_set(argument5.yfilter) || ydk::is_set(argument6.yfilter) || ydk::is_set(argument7.yfilter) || ydk::is_set(argument8.yfilter) || ydk::is_set(argument9.yfilter) || ydk::is_set(argument10.yfilter) || ydk::is_set(argument11.yfilter) || ydk::is_set(argument12.yfilter) || ydk::is_set(argument13.yfilter) || ydk::is_set(argument14.yfilter) || ydk::is_set(argument15.yfilter) || ydk::is_set(argument16.yfilter); } std::string Ipv4Dhcpd::Interfaces::Interface::RelayInterface::RelayDhcpCircuitId::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "relay-dhcp-circuit-id"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Interfaces::Interface::RelayInterface::RelayDhcpCircuitId::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (circuit_id.is_set || is_set(circuit_id.yfilter)) leaf_name_data.push_back(circuit_id.get_name_leafdata()); if (format.is_set || is_set(format.yfilter)) leaf_name_data.push_back(format.get_name_leafdata()); if (argument1.is_set || is_set(argument1.yfilter)) leaf_name_data.push_back(argument1.get_name_leafdata()); if (argument2.is_set || is_set(argument2.yfilter)) leaf_name_data.push_back(argument2.get_name_leafdata()); if (argument3.is_set || is_set(argument3.yfilter)) leaf_name_data.push_back(argument3.get_name_leafdata()); if (argument4.is_set || is_set(argument4.yfilter)) leaf_name_data.push_back(argument4.get_name_leafdata()); if (argument5.is_set || is_set(argument5.yfilter)) leaf_name_data.push_back(argument5.get_name_leafdata()); if (argument6.is_set || is_set(argument6.yfilter)) leaf_name_data.push_back(argument6.get_name_leafdata()); if (argument7.is_set || is_set(argument7.yfilter)) leaf_name_data.push_back(argument7.get_name_leafdata()); if (argument8.is_set || is_set(argument8.yfilter)) leaf_name_data.push_back(argument8.get_name_leafdata()); if (argument9.is_set || is_set(argument9.yfilter)) leaf_name_data.push_back(argument9.get_name_leafdata()); if (argument10.is_set || is_set(argument10.yfilter)) leaf_name_data.push_back(argument10.get_name_leafdata()); if (argument11.is_set || is_set(argument11.yfilter)) leaf_name_data.push_back(argument11.get_name_leafdata()); if (argument12.is_set || is_set(argument12.yfilter)) leaf_name_data.push_back(argument12.get_name_leafdata()); if (argument13.is_set || is_set(argument13.yfilter)) leaf_name_data.push_back(argument13.get_name_leafdata()); if (argument14.is_set || is_set(argument14.yfilter)) leaf_name_data.push_back(argument14.get_name_leafdata()); if (argument15.is_set || is_set(argument15.yfilter)) leaf_name_data.push_back(argument15.get_name_leafdata()); if (argument16.is_set || is_set(argument16.yfilter)) leaf_name_data.push_back(argument16.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Interfaces::Interface::RelayInterface::RelayDhcpCircuitId::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Interfaces::Interface::RelayInterface::RelayDhcpCircuitId::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Interfaces::Interface::RelayInterface::RelayDhcpCircuitId::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "circuit-id") { circuit_id = value; circuit_id.value_namespace = name_space; circuit_id.value_namespace_prefix = name_space_prefix; } if(value_path == "format") { format = value; format.value_namespace = name_space; format.value_namespace_prefix = name_space_prefix; } if(value_path == "argument1") { argument1 = value; argument1.value_namespace = name_space; argument1.value_namespace_prefix = name_space_prefix; } if(value_path == "argument2") { argument2 = value; argument2.value_namespace = name_space; argument2.value_namespace_prefix = name_space_prefix; } if(value_path == "argument3") { argument3 = value; argument3.value_namespace = name_space; argument3.value_namespace_prefix = name_space_prefix; } if(value_path == "argument4") { argument4 = value; argument4.value_namespace = name_space; argument4.value_namespace_prefix = name_space_prefix; } if(value_path == "argument5") { argument5 = value; argument5.value_namespace = name_space; argument5.value_namespace_prefix = name_space_prefix; } if(value_path == "argument6") { argument6 = value; argument6.value_namespace = name_space; argument6.value_namespace_prefix = name_space_prefix; } if(value_path == "argument7") { argument7 = value; argument7.value_namespace = name_space; argument7.value_namespace_prefix = name_space_prefix; } if(value_path == "argument8") { argument8 = value; argument8.value_namespace = name_space; argument8.value_namespace_prefix = name_space_prefix; } if(value_path == "argument9") { argument9 = value; argument9.value_namespace = name_space; argument9.value_namespace_prefix = name_space_prefix; } if(value_path == "argument10") { argument10 = value; argument10.value_namespace = name_space; argument10.value_namespace_prefix = name_space_prefix; } if(value_path == "argument11") { argument11 = value; argument11.value_namespace = name_space; argument11.value_namespace_prefix = name_space_prefix; } if(value_path == "argument12") { argument12 = value; argument12.value_namespace = name_space; argument12.value_namespace_prefix = name_space_prefix; } if(value_path == "argument13") { argument13 = value; argument13.value_namespace = name_space; argument13.value_namespace_prefix = name_space_prefix; } if(value_path == "argument14") { argument14 = value; argument14.value_namespace = name_space; argument14.value_namespace_prefix = name_space_prefix; } if(value_path == "argument15") { argument15 = value; argument15.value_namespace = name_space; argument15.value_namespace_prefix = name_space_prefix; } if(value_path == "argument16") { argument16 = value; argument16.value_namespace = name_space; argument16.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Interfaces::Interface::RelayInterface::RelayDhcpCircuitId::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "circuit-id") { circuit_id.yfilter = yfilter; } if(value_path == "format") { format.yfilter = yfilter; } if(value_path == "argument1") { argument1.yfilter = yfilter; } if(value_path == "argument2") { argument2.yfilter = yfilter; } if(value_path == "argument3") { argument3.yfilter = yfilter; } if(value_path == "argument4") { argument4.yfilter = yfilter; } if(value_path == "argument5") { argument5.yfilter = yfilter; } if(value_path == "argument6") { argument6.yfilter = yfilter; } if(value_path == "argument7") { argument7.yfilter = yfilter; } if(value_path == "argument8") { argument8.yfilter = yfilter; } if(value_path == "argument9") { argument9.yfilter = yfilter; } if(value_path == "argument10") { argument10.yfilter = yfilter; } if(value_path == "argument11") { argument11.yfilter = yfilter; } if(value_path == "argument12") { argument12.yfilter = yfilter; } if(value_path == "argument13") { argument13.yfilter = yfilter; } if(value_path == "argument14") { argument14.yfilter = yfilter; } if(value_path == "argument15") { argument15.yfilter = yfilter; } if(value_path == "argument16") { argument16.yfilter = yfilter; } } bool Ipv4Dhcpd::Interfaces::Interface::RelayInterface::RelayDhcpCircuitId::has_leaf_or_child_of_name(const std::string & name) const { if(name == "circuit-id" || name == "format" || name == "argument1" || name == "argument2" || name == "argument3" || name == "argument4" || name == "argument5" || name == "argument6" || name == "argument7" || name == "argument8" || name == "argument9" || name == "argument10" || name == "argument11" || name == "argument12" || name == "argument13" || name == "argument14" || name == "argument15" || name == "argument16") return true; return false; } Ipv4Dhcpd::Interfaces::Interface::StaticMode::StaticMode() : statics(std::make_shared<Ipv4Dhcpd::Interfaces::Interface::StaticMode::Statics>()) { statics->parent = this; yang_name = "static-mode"; yang_parent_name = "interface"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Interfaces::Interface::StaticMode::~StaticMode() { } bool Ipv4Dhcpd::Interfaces::Interface::StaticMode::has_data() const { if (is_presence_container) return true; return (statics != nullptr && statics->has_data()); } bool Ipv4Dhcpd::Interfaces::Interface::StaticMode::has_operation() const { return is_set(yfilter) || (statics != nullptr && statics->has_operation()); } std::string Ipv4Dhcpd::Interfaces::Interface::StaticMode::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "static-mode"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Interfaces::Interface::StaticMode::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Interfaces::Interface::StaticMode::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "statics") { if(statics == nullptr) { statics = std::make_shared<Ipv4Dhcpd::Interfaces::Interface::StaticMode::Statics>(); } return statics; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Interfaces::Interface::StaticMode::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(statics != nullptr) { _children["statics"] = statics; } return _children; } void Ipv4Dhcpd::Interfaces::Interface::StaticMode::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Ipv4Dhcpd::Interfaces::Interface::StaticMode::set_filter(const std::string & value_path, YFilter yfilter) { } bool Ipv4Dhcpd::Interfaces::Interface::StaticMode::has_leaf_or_child_of_name(const std::string & name) const { if(name == "statics") return true; return false; } Ipv4Dhcpd::Interfaces::Interface::StaticMode::Statics::Statics() : static_(this, {"mac_address", "client_id", "layer"}) { yang_name = "statics"; yang_parent_name = "static-mode"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Interfaces::Interface::StaticMode::Statics::~Statics() { } bool Ipv4Dhcpd::Interfaces::Interface::StaticMode::Statics::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; index<static_.len(); index++) { if(static_[index]->has_data()) return true; } return false; } bool Ipv4Dhcpd::Interfaces::Interface::StaticMode::Statics::has_operation() const { for (std::size_t index=0; index<static_.len(); index++) { if(static_[index]->has_operation()) return true; } return is_set(yfilter); } std::string Ipv4Dhcpd::Interfaces::Interface::StaticMode::Statics::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "statics"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Interfaces::Interface::StaticMode::Statics::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Interfaces::Interface::StaticMode::Statics::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "static") { auto ent_ = std::make_shared<Ipv4Dhcpd::Interfaces::Interface::StaticMode::Statics::Static>(); ent_->parent = this; static_.append(ent_); return ent_; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Interfaces::Interface::StaticMode::Statics::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; count_ = 0; for (auto ent_ : static_.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void Ipv4Dhcpd::Interfaces::Interface::StaticMode::Statics::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Ipv4Dhcpd::Interfaces::Interface::StaticMode::Statics::set_filter(const std::string & value_path, YFilter yfilter) { } bool Ipv4Dhcpd::Interfaces::Interface::StaticMode::Statics::has_leaf_or_child_of_name(const std::string & name) const { if(name == "static") return true; return false; } Ipv4Dhcpd::Interfaces::Interface::StaticMode::Statics::Static::Static() : mac_address{YType::str, "mac-address"}, client_id{YType::uint32, "client-id"}, layer{YType::enumeration, "layer"}, static_address{YType::str, "static-address"} { yang_name = "static"; yang_parent_name = "statics"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Interfaces::Interface::StaticMode::Statics::Static::~Static() { } bool Ipv4Dhcpd::Interfaces::Interface::StaticMode::Statics::Static::has_data() const { if (is_presence_container) return true; return mac_address.is_set || client_id.is_set || layer.is_set || static_address.is_set; } bool Ipv4Dhcpd::Interfaces::Interface::StaticMode::Statics::Static::has_operation() const { return is_set(yfilter) || ydk::is_set(mac_address.yfilter) || ydk::is_set(client_id.yfilter) || ydk::is_set(layer.yfilter) || ydk::is_set(static_address.yfilter); } std::string Ipv4Dhcpd::Interfaces::Interface::StaticMode::Statics::Static::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "static"; ADD_KEY_TOKEN(mac_address, "mac-address"); ADD_KEY_TOKEN(client_id, "client-id"); ADD_KEY_TOKEN(layer, "layer"); return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Interfaces::Interface::StaticMode::Statics::Static::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (mac_address.is_set || is_set(mac_address.yfilter)) leaf_name_data.push_back(mac_address.get_name_leafdata()); if (client_id.is_set || is_set(client_id.yfilter)) leaf_name_data.push_back(client_id.get_name_leafdata()); if (layer.is_set || is_set(layer.yfilter)) leaf_name_data.push_back(layer.get_name_leafdata()); if (static_address.is_set || is_set(static_address.yfilter)) leaf_name_data.push_back(static_address.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Interfaces::Interface::StaticMode::Statics::Static::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Interfaces::Interface::StaticMode::Statics::Static::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Interfaces::Interface::StaticMode::Statics::Static::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "mac-address") { mac_address = value; mac_address.value_namespace = name_space; mac_address.value_namespace_prefix = name_space_prefix; } if(value_path == "client-id") { client_id = value; client_id.value_namespace = name_space; client_id.value_namespace_prefix = name_space_prefix; } if(value_path == "layer") { layer = value; layer.value_namespace = name_space; layer.value_namespace_prefix = name_space_prefix; } if(value_path == "static-address") { static_address = value; static_address.value_namespace = name_space; static_address.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Interfaces::Interface::StaticMode::Statics::Static::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "mac-address") { mac_address.yfilter = yfilter; } if(value_path == "client-id") { client_id.yfilter = yfilter; } if(value_path == "layer") { layer.yfilter = yfilter; } if(value_path == "static-address") { static_address.yfilter = yfilter; } } bool Ipv4Dhcpd::Interfaces::Interface::StaticMode::Statics::Static::has_leaf_or_child_of_name(const std::string & name) const { if(name == "mac-address" || name == "client-id" || name == "layer" || name == "static-address") return true; return false; } Ipv4Dhcpd::Interfaces::Interface::Profile::Profile() : profile_name{YType::str, "profile-name"}, mode{YType::enumeration, "mode"} { yang_name = "profile"; yang_parent_name = "interface"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true; } Ipv4Dhcpd::Interfaces::Interface::Profile::~Profile() { } bool Ipv4Dhcpd::Interfaces::Interface::Profile::has_data() const { if (is_presence_container) return true; return profile_name.is_set || mode.is_set; } bool Ipv4Dhcpd::Interfaces::Interface::Profile::has_operation() const { return is_set(yfilter) || ydk::is_set(profile_name.yfilter) || ydk::is_set(mode.yfilter); } std::string Ipv4Dhcpd::Interfaces::Interface::Profile::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "profile"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Interfaces::Interface::Profile::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (profile_name.is_set || is_set(profile_name.yfilter)) leaf_name_data.push_back(profile_name.get_name_leafdata()); if (mode.is_set || is_set(mode.yfilter)) leaf_name_data.push_back(mode.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Interfaces::Interface::Profile::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Interfaces::Interface::Profile::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Interfaces::Interface::Profile::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "profile-name") { profile_name = value; profile_name.value_namespace = name_space; profile_name.value_namespace_prefix = name_space_prefix; } if(value_path == "mode") { mode = value; mode.value_namespace = name_space; mode.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Interfaces::Interface::Profile::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "profile-name") { profile_name.yfilter = yfilter; } if(value_path == "mode") { mode.yfilter = yfilter; } } bool Ipv4Dhcpd::Interfaces::Interface::Profile::has_leaf_or_child_of_name(const std::string & name) const { if(name == "profile-name" || name == "mode") return true; return false; } Ipv4Dhcpd::Interfaces::Interface::ServerInterface::ServerInterface() : profile{YType::str, "profile"} , server_dhcp_circuit_id(nullptr) // presence node { yang_name = "server-interface"; yang_parent_name = "interface"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Interfaces::Interface::ServerInterface::~ServerInterface() { } bool Ipv4Dhcpd::Interfaces::Interface::ServerInterface::has_data() const { if (is_presence_container) return true; return profile.is_set || (server_dhcp_circuit_id != nullptr && server_dhcp_circuit_id->has_data()); } bool Ipv4Dhcpd::Interfaces::Interface::ServerInterface::has_operation() const { return is_set(yfilter) || ydk::is_set(profile.yfilter) || (server_dhcp_circuit_id != nullptr && server_dhcp_circuit_id->has_operation()); } std::string Ipv4Dhcpd::Interfaces::Interface::ServerInterface::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "server-interface"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Interfaces::Interface::ServerInterface::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (profile.is_set || is_set(profile.yfilter)) leaf_name_data.push_back(profile.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Interfaces::Interface::ServerInterface::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "server-dhcp-circuit-id") { if(server_dhcp_circuit_id == nullptr) { server_dhcp_circuit_id = std::make_shared<Ipv4Dhcpd::Interfaces::Interface::ServerInterface::ServerDhcpCircuitId>(); } return server_dhcp_circuit_id; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Interfaces::Interface::ServerInterface::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(server_dhcp_circuit_id != nullptr) { _children["server-dhcp-circuit-id"] = server_dhcp_circuit_id; } return _children; } void Ipv4Dhcpd::Interfaces::Interface::ServerInterface::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "profile") { profile = value; profile.value_namespace = name_space; profile.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Interfaces::Interface::ServerInterface::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "profile") { profile.yfilter = yfilter; } } bool Ipv4Dhcpd::Interfaces::Interface::ServerInterface::has_leaf_or_child_of_name(const std::string & name) const { if(name == "server-dhcp-circuit-id" || name == "profile") return true; return false; } Ipv4Dhcpd::Interfaces::Interface::ServerInterface::ServerDhcpCircuitId::ServerDhcpCircuitId() : circuit_id{YType::str, "circuit-id"}, format{YType::enumeration, "format"}, argument1{YType::enumeration, "argument1"}, argument2{YType::enumeration, "argument2"}, argument3{YType::enumeration, "argument3"}, argument4{YType::enumeration, "argument4"}, argument5{YType::enumeration, "argument5"}, argument6{YType::enumeration, "argument6"}, argument7{YType::enumeration, "argument7"}, argument8{YType::enumeration, "argument8"}, argument9{YType::enumeration, "argument9"}, argument10{YType::enumeration, "argument10"}, argument11{YType::enumeration, "argument11"}, argument12{YType::enumeration, "argument12"}, argument13{YType::enumeration, "argument13"}, argument14{YType::enumeration, "argument14"}, argument15{YType::enumeration, "argument15"}, argument16{YType::enumeration, "argument16"} { yang_name = "server-dhcp-circuit-id"; yang_parent_name = "server-interface"; is_top_level_class = false; has_list_ancestor = true; is_presence_container = true; } Ipv4Dhcpd::Interfaces::Interface::ServerInterface::ServerDhcpCircuitId::~ServerDhcpCircuitId() { } bool Ipv4Dhcpd::Interfaces::Interface::ServerInterface::ServerDhcpCircuitId::has_data() const { if (is_presence_container) return true; return circuit_id.is_set || format.is_set || argument1.is_set || argument2.is_set || argument3.is_set || argument4.is_set || argument5.is_set || argument6.is_set || argument7.is_set || argument8.is_set || argument9.is_set || argument10.is_set || argument11.is_set || argument12.is_set || argument13.is_set || argument14.is_set || argument15.is_set || argument16.is_set; } bool Ipv4Dhcpd::Interfaces::Interface::ServerInterface::ServerDhcpCircuitId::has_operation() const { return is_set(yfilter) || ydk::is_set(circuit_id.yfilter) || ydk::is_set(format.yfilter) || ydk::is_set(argument1.yfilter) || ydk::is_set(argument2.yfilter) || ydk::is_set(argument3.yfilter) || ydk::is_set(argument4.yfilter) || ydk::is_set(argument5.yfilter) || ydk::is_set(argument6.yfilter) || ydk::is_set(argument7.yfilter) || ydk::is_set(argument8.yfilter) || ydk::is_set(argument9.yfilter) || ydk::is_set(argument10.yfilter) || ydk::is_set(argument11.yfilter) || ydk::is_set(argument12.yfilter) || ydk::is_set(argument13.yfilter) || ydk::is_set(argument14.yfilter) || ydk::is_set(argument15.yfilter) || ydk::is_set(argument16.yfilter); } std::string Ipv4Dhcpd::Interfaces::Interface::ServerInterface::ServerDhcpCircuitId::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "server-dhcp-circuit-id"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Interfaces::Interface::ServerInterface::ServerDhcpCircuitId::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (circuit_id.is_set || is_set(circuit_id.yfilter)) leaf_name_data.push_back(circuit_id.get_name_leafdata()); if (format.is_set || is_set(format.yfilter)) leaf_name_data.push_back(format.get_name_leafdata()); if (argument1.is_set || is_set(argument1.yfilter)) leaf_name_data.push_back(argument1.get_name_leafdata()); if (argument2.is_set || is_set(argument2.yfilter)) leaf_name_data.push_back(argument2.get_name_leafdata()); if (argument3.is_set || is_set(argument3.yfilter)) leaf_name_data.push_back(argument3.get_name_leafdata()); if (argument4.is_set || is_set(argument4.yfilter)) leaf_name_data.push_back(argument4.get_name_leafdata()); if (argument5.is_set || is_set(argument5.yfilter)) leaf_name_data.push_back(argument5.get_name_leafdata()); if (argument6.is_set || is_set(argument6.yfilter)) leaf_name_data.push_back(argument6.get_name_leafdata()); if (argument7.is_set || is_set(argument7.yfilter)) leaf_name_data.push_back(argument7.get_name_leafdata()); if (argument8.is_set || is_set(argument8.yfilter)) leaf_name_data.push_back(argument8.get_name_leafdata()); if (argument9.is_set || is_set(argument9.yfilter)) leaf_name_data.push_back(argument9.get_name_leafdata()); if (argument10.is_set || is_set(argument10.yfilter)) leaf_name_data.push_back(argument10.get_name_leafdata()); if (argument11.is_set || is_set(argument11.yfilter)) leaf_name_data.push_back(argument11.get_name_leafdata()); if (argument12.is_set || is_set(argument12.yfilter)) leaf_name_data.push_back(argument12.get_name_leafdata()); if (argument13.is_set || is_set(argument13.yfilter)) leaf_name_data.push_back(argument13.get_name_leafdata()); if (argument14.is_set || is_set(argument14.yfilter)) leaf_name_data.push_back(argument14.get_name_leafdata()); if (argument15.is_set || is_set(argument15.yfilter)) leaf_name_data.push_back(argument15.get_name_leafdata()); if (argument16.is_set || is_set(argument16.yfilter)) leaf_name_data.push_back(argument16.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Interfaces::Interface::ServerInterface::ServerDhcpCircuitId::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Interfaces::Interface::ServerInterface::ServerDhcpCircuitId::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Interfaces::Interface::ServerInterface::ServerDhcpCircuitId::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "circuit-id") { circuit_id = value; circuit_id.value_namespace = name_space; circuit_id.value_namespace_prefix = name_space_prefix; } if(value_path == "format") { format = value; format.value_namespace = name_space; format.value_namespace_prefix = name_space_prefix; } if(value_path == "argument1") { argument1 = value; argument1.value_namespace = name_space; argument1.value_namespace_prefix = name_space_prefix; } if(value_path == "argument2") { argument2 = value; argument2.value_namespace = name_space; argument2.value_namespace_prefix = name_space_prefix; } if(value_path == "argument3") { argument3 = value; argument3.value_namespace = name_space; argument3.value_namespace_prefix = name_space_prefix; } if(value_path == "argument4") { argument4 = value; argument4.value_namespace = name_space; argument4.value_namespace_prefix = name_space_prefix; } if(value_path == "argument5") { argument5 = value; argument5.value_namespace = name_space; argument5.value_namespace_prefix = name_space_prefix; } if(value_path == "argument6") { argument6 = value; argument6.value_namespace = name_space; argument6.value_namespace_prefix = name_space_prefix; } if(value_path == "argument7") { argument7 = value; argument7.value_namespace = name_space; argument7.value_namespace_prefix = name_space_prefix; } if(value_path == "argument8") { argument8 = value; argument8.value_namespace = name_space; argument8.value_namespace_prefix = name_space_prefix; } if(value_path == "argument9") { argument9 = value; argument9.value_namespace = name_space; argument9.value_namespace_prefix = name_space_prefix; } if(value_path == "argument10") { argument10 = value; argument10.value_namespace = name_space; argument10.value_namespace_prefix = name_space_prefix; } if(value_path == "argument11") { argument11 = value; argument11.value_namespace = name_space; argument11.value_namespace_prefix = name_space_prefix; } if(value_path == "argument12") { argument12 = value; argument12.value_namespace = name_space; argument12.value_namespace_prefix = name_space_prefix; } if(value_path == "argument13") { argument13 = value; argument13.value_namespace = name_space; argument13.value_namespace_prefix = name_space_prefix; } if(value_path == "argument14") { argument14 = value; argument14.value_namespace = name_space; argument14.value_namespace_prefix = name_space_prefix; } if(value_path == "argument15") { argument15 = value; argument15.value_namespace = name_space; argument15.value_namespace_prefix = name_space_prefix; } if(value_path == "argument16") { argument16 = value; argument16.value_namespace = name_space; argument16.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Interfaces::Interface::ServerInterface::ServerDhcpCircuitId::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "circuit-id") { circuit_id.yfilter = yfilter; } if(value_path == "format") { format.yfilter = yfilter; } if(value_path == "argument1") { argument1.yfilter = yfilter; } if(value_path == "argument2") { argument2.yfilter = yfilter; } if(value_path == "argument3") { argument3.yfilter = yfilter; } if(value_path == "argument4") { argument4.yfilter = yfilter; } if(value_path == "argument5") { argument5.yfilter = yfilter; } if(value_path == "argument6") { argument6.yfilter = yfilter; } if(value_path == "argument7") { argument7.yfilter = yfilter; } if(value_path == "argument8") { argument8.yfilter = yfilter; } if(value_path == "argument9") { argument9.yfilter = yfilter; } if(value_path == "argument10") { argument10.yfilter = yfilter; } if(value_path == "argument11") { argument11.yfilter = yfilter; } if(value_path == "argument12") { argument12.yfilter = yfilter; } if(value_path == "argument13") { argument13.yfilter = yfilter; } if(value_path == "argument14") { argument14.yfilter = yfilter; } if(value_path == "argument15") { argument15.yfilter = yfilter; } if(value_path == "argument16") { argument16.yfilter = yfilter; } } bool Ipv4Dhcpd::Interfaces::Interface::ServerInterface::ServerDhcpCircuitId::has_leaf_or_child_of_name(const std::string & name) const { if(name == "circuit-id" || name == "format" || name == "argument1" || name == "argument2" || name == "argument3" || name == "argument4" || name == "argument5" || name == "argument6" || name == "argument7" || name == "argument8" || name == "argument9" || name == "argument10" || name == "argument11" || name == "argument12" || name == "argument13" || name == "argument14" || name == "argument15" || name == "argument16") return true; return false; } Ipv4Dhcpd::Interfaces::Interface::SnoopInterface::SnoopInterface() : snoop_circuit_id(std::make_shared<Ipv4Dhcpd::Interfaces::Interface::SnoopInterface::SnoopCircuitId>()) { snoop_circuit_id->parent = this; yang_name = "snoop-interface"; yang_parent_name = "interface"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Interfaces::Interface::SnoopInterface::~SnoopInterface() { } bool Ipv4Dhcpd::Interfaces::Interface::SnoopInterface::has_data() const { if (is_presence_container) return true; return (snoop_circuit_id != nullptr && snoop_circuit_id->has_data()); } bool Ipv4Dhcpd::Interfaces::Interface::SnoopInterface::has_operation() const { return is_set(yfilter) || (snoop_circuit_id != nullptr && snoop_circuit_id->has_operation()); } std::string Ipv4Dhcpd::Interfaces::Interface::SnoopInterface::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "snoop-interface"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Interfaces::Interface::SnoopInterface::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Interfaces::Interface::SnoopInterface::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == "snoop-circuit-id") { if(snoop_circuit_id == nullptr) { snoop_circuit_id = std::make_shared<Ipv4Dhcpd::Interfaces::Interface::SnoopInterface::SnoopCircuitId>(); } return snoop_circuit_id; } return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Interfaces::Interface::SnoopInterface::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; if(snoop_circuit_id != nullptr) { _children["snoop-circuit-id"] = snoop_circuit_id; } return _children; } void Ipv4Dhcpd::Interfaces::Interface::SnoopInterface::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void Ipv4Dhcpd::Interfaces::Interface::SnoopInterface::set_filter(const std::string & value_path, YFilter yfilter) { } bool Ipv4Dhcpd::Interfaces::Interface::SnoopInterface::has_leaf_or_child_of_name(const std::string & name) const { if(name == "snoop-circuit-id") return true; return false; } Ipv4Dhcpd::Interfaces::Interface::SnoopInterface::SnoopCircuitId::SnoopCircuitId() : format_type{YType::uint32, "format-type"}, circuit_id_value{YType::str, "circuit-id-value"} { yang_name = "snoop-circuit-id"; yang_parent_name = "snoop-interface"; is_top_level_class = false; has_list_ancestor = true; } Ipv4Dhcpd::Interfaces::Interface::SnoopInterface::SnoopCircuitId::~SnoopCircuitId() { } bool Ipv4Dhcpd::Interfaces::Interface::SnoopInterface::SnoopCircuitId::has_data() const { if (is_presence_container) return true; return format_type.is_set || circuit_id_value.is_set; } bool Ipv4Dhcpd::Interfaces::Interface::SnoopInterface::SnoopCircuitId::has_operation() const { return is_set(yfilter) || ydk::is_set(format_type.yfilter) || ydk::is_set(circuit_id_value.yfilter); } std::string Ipv4Dhcpd::Interfaces::Interface::SnoopInterface::SnoopCircuitId::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "snoop-circuit-id"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::Interfaces::Interface::SnoopInterface::SnoopCircuitId::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (format_type.is_set || is_set(format_type.yfilter)) leaf_name_data.push_back(format_type.get_name_leafdata()); if (circuit_id_value.is_set || is_set(circuit_id_value.yfilter)) leaf_name_data.push_back(circuit_id_value.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::Interfaces::Interface::SnoopInterface::SnoopCircuitId::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::Interfaces::Interface::SnoopInterface::SnoopCircuitId::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::Interfaces::Interface::SnoopInterface::SnoopCircuitId::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "format-type") { format_type = value; format_type.value_namespace = name_space; format_type.value_namespace_prefix = name_space_prefix; } if(value_path == "circuit-id-value") { circuit_id_value = value; circuit_id_value.value_namespace = name_space; circuit_id_value.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::Interfaces::Interface::SnoopInterface::SnoopCircuitId::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "format-type") { format_type.yfilter = yfilter; } if(value_path == "circuit-id-value") { circuit_id_value.yfilter = yfilter; } } bool Ipv4Dhcpd::Interfaces::Interface::SnoopInterface::SnoopCircuitId::has_leaf_or_child_of_name(const std::string & name) const { if(name == "format-type" || name == "circuit-id-value") return true; return false; } Ipv4Dhcpd::DuplicateMacAllowed::DuplicateMacAllowed() : duplicate_mac{YType::empty, "duplicate-mac"}, exclude_vlan{YType::empty, "exclude-vlan"}, include_giaddr{YType::empty, "include-giaddr"} { yang_name = "duplicate-mac-allowed"; yang_parent_name = "ipv4-dhcpd"; is_top_level_class = false; has_list_ancestor = false; is_presence_container = true; } Ipv4Dhcpd::DuplicateMacAllowed::~DuplicateMacAllowed() { } bool Ipv4Dhcpd::DuplicateMacAllowed::has_data() const { if (is_presence_container) return true; return duplicate_mac.is_set || exclude_vlan.is_set || include_giaddr.is_set; } bool Ipv4Dhcpd::DuplicateMacAllowed::has_operation() const { return is_set(yfilter) || ydk::is_set(duplicate_mac.yfilter) || ydk::is_set(exclude_vlan.yfilter) || ydk::is_set(include_giaddr.yfilter); } std::string Ipv4Dhcpd::DuplicateMacAllowed::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-ipv4-dhcpd-cfg:ipv4-dhcpd/" << get_segment_path(); return path_buffer.str(); } std::string Ipv4Dhcpd::DuplicateMacAllowed::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "duplicate-mac-allowed"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::DuplicateMacAllowed::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (duplicate_mac.is_set || is_set(duplicate_mac.yfilter)) leaf_name_data.push_back(duplicate_mac.get_name_leafdata()); if (exclude_vlan.is_set || is_set(exclude_vlan.yfilter)) leaf_name_data.push_back(exclude_vlan.get_name_leafdata()); if (include_giaddr.is_set || is_set(include_giaddr.yfilter)) leaf_name_data.push_back(include_giaddr.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::DuplicateMacAllowed::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::DuplicateMacAllowed::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::DuplicateMacAllowed::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "duplicate-mac") { duplicate_mac = value; duplicate_mac.value_namespace = name_space; duplicate_mac.value_namespace_prefix = name_space_prefix; } if(value_path == "exclude-vlan") { exclude_vlan = value; exclude_vlan.value_namespace = name_space; exclude_vlan.value_namespace_prefix = name_space_prefix; } if(value_path == "include-giaddr") { include_giaddr = value; include_giaddr.value_namespace = name_space; include_giaddr.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::DuplicateMacAllowed::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "duplicate-mac") { duplicate_mac.yfilter = yfilter; } if(value_path == "exclude-vlan") { exclude_vlan.yfilter = yfilter; } if(value_path == "include-giaddr") { include_giaddr.yfilter = yfilter; } } bool Ipv4Dhcpd::DuplicateMacAllowed::has_leaf_or_child_of_name(const std::string & name) const { if(name == "duplicate-mac" || name == "exclude-vlan" || name == "include-giaddr") return true; return false; } Ipv4Dhcpd::RateLimit::RateLimit() : num_period{YType::uint32, "num-period"}, num_discover{YType::uint32, "num-discover"} { yang_name = "rate-limit"; yang_parent_name = "ipv4-dhcpd"; is_top_level_class = false; has_list_ancestor = false; } Ipv4Dhcpd::RateLimit::~RateLimit() { } bool Ipv4Dhcpd::RateLimit::has_data() const { if (is_presence_container) return true; return num_period.is_set || num_discover.is_set; } bool Ipv4Dhcpd::RateLimit::has_operation() const { return is_set(yfilter) || ydk::is_set(num_period.yfilter) || ydk::is_set(num_discover.yfilter); } std::string Ipv4Dhcpd::RateLimit::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << "Cisco-IOS-XR-ipv4-dhcpd-cfg:ipv4-dhcpd/" << get_segment_path(); return path_buffer.str(); } std::string Ipv4Dhcpd::RateLimit::get_segment_path() const { std::ostringstream path_buffer; path_buffer << "rate-limit"; return path_buffer.str(); } std::vector<std::pair<std::string, LeafData> > Ipv4Dhcpd::RateLimit::get_name_leaf_data() const { std::vector<std::pair<std::string, LeafData> > leaf_name_data {}; if (num_period.is_set || is_set(num_period.yfilter)) leaf_name_data.push_back(num_period.get_name_leafdata()); if (num_discover.is_set || is_set(num_discover.yfilter)) leaf_name_data.push_back(num_discover.get_name_leafdata()); return leaf_name_data; } std::shared_ptr<ydk::Entity> Ipv4Dhcpd::RateLimit::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map<std::string, std::shared_ptr<ydk::Entity>> Ipv4Dhcpd::RateLimit::get_children() const { std::map<std::string, std::shared_ptr<ydk::Entity>> _children{}; char count_=0; return _children; } void Ipv4Dhcpd::RateLimit::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == "num-period") { num_period = value; num_period.value_namespace = name_space; num_period.value_namespace_prefix = name_space_prefix; } if(value_path == "num-discover") { num_discover = value; num_discover.value_namespace = name_space; num_discover.value_namespace_prefix = name_space_prefix; } } void Ipv4Dhcpd::RateLimit::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == "num-period") { num_period.yfilter = yfilter; } if(value_path == "num-discover") { num_discover.yfilter = yfilter; } } bool Ipv4Dhcpd::RateLimit::has_leaf_or_child_of_name(const std::string & name) const { if(name == "num-period" || name == "num-discover") return true; return false; } const Enum::YLeaf Matchaction::allow {0, "allow"}; const Enum::YLeaf Matchaction::drop {1, "drop"}; const Enum::YLeaf Dhcpv4AuthUsername::auth_username_mac {1, "auth-username-mac"}; const Enum::YLeaf Dhcpv4AuthUsername::auth_username_giaddr {2, "auth-username-giaddr"}; const Enum::YLeaf Policy::ignore {0, "ignore"}; const Enum::YLeaf Policy::check {1, "check"}; const Enum::YLeaf Policy::unicastalways {2, "unicastalways"}; const Enum::YLeaf Matchoption::circuitid {1, "circuitid"}; const Enum::YLeaf Matchoption::remoteid {2, "remoteid"}; const Enum::YLeaf Matchoption::Y_60 {60, "60"}; const Enum::YLeaf Matchoption::Y_77 {77, "77"}; const Enum::YLeaf Matchoption::Y_124 {124, "124"}; const Enum::YLeaf Matchoption::Y_125 {125, "125"}; const Enum::YLeaf BaseAction::allow {0, "allow"}; const Enum::YLeaf BaseAction::drop {1, "drop"}; const Enum::YLeaf Dhcpv4LimitLease1::interface {1, "interface"}; const Enum::YLeaf Dhcpv4LimitLease1::circuit_id {2, "circuit-id"}; const Enum::YLeaf Dhcpv4LimitLease1::remote_id {3, "remote-id"}; const Enum::YLeaf Dhcpv4LimitLease1::circuit_id_remote_id {4, "circuit-id-remote-id"}; const Enum::YLeaf Ipv4dhcpdLayer::layer2 {2, "layer2"}; const Enum::YLeaf Ipv4dhcpdLayer::layer3 {3, "layer3"}; const Enum::YLeaf Ipv4dhcpdGiaddrPolicy::giaddr_policy_keep {0, "giaddr-policy-keep"}; const Enum::YLeaf Ipv4dhcpdMode::base {0, "base"}; const Enum::YLeaf Ipv4dhcpdMode::relay {1, "relay"}; const Enum::YLeaf Ipv4dhcpdMode::snoop {2, "snoop"}; const Enum::YLeaf Ipv4dhcpdMode::server {3, "server"}; const Enum::YLeaf Ipv4dhcpdMode::proxy {4, "proxy"}; const Enum::YLeaf Ipv4dhcpdMode::base2 {5, "base2"}; const Enum::YLeaf Ipv4dhcpdFmtSpecifier::physical_chassis {1, "physical-chassis"}; const Enum::YLeaf Ipv4dhcpdFmtSpecifier::physical_slot {2, "physical-slot"}; const Enum::YLeaf Ipv4dhcpdFmtSpecifier::physical_sub_slot {3, "physical-sub-slot"}; const Enum::YLeaf Ipv4dhcpdFmtSpecifier::physical_port {4, "physical-port"}; const Enum::YLeaf Ipv4dhcpdFmtSpecifier::physical_sub_port {5, "physical-sub-port"}; const Enum::YLeaf Ipv4dhcpdFmtSpecifier::inner_vlan_id {6, "inner-vlan-id"}; const Enum::YLeaf Ipv4dhcpdFmtSpecifier::outer_vlan_id {7, "outer-vlan-id"}; const Enum::YLeaf Ipv4dhcpdFmtSpecifier::l2_interface {8, "l2-interface"}; const Enum::YLeaf Ipv4dhcpdFmtSpecifier::l3_interface {9, "l3-interface"}; const Enum::YLeaf Ipv4dhcpdFmtSpecifier::host_name {10, "host-name"}; const Enum::YLeaf Ipv4dhcpdRelayInfoOptionPolicy::replace {0, "replace"}; const Enum::YLeaf Ipv4dhcpdRelayInfoOptionPolicy::keep {1, "keep"}; const Enum::YLeaf Ipv4dhcpdRelayInfoOptionPolicy::drop {2, "drop"}; const Enum::YLeaf Ipv4dhcpdRelayInfoOptionPolicy::encapsulate {3, "encapsulate"}; const Enum::YLeaf MacMismatchAction::forward {0, "forward"}; const Enum::YLeaf MacMismatchAction::drop {1, "drop"}; const Enum::YLeaf Ipv4dhcpdBroadcastFlagPolicy::ignore {0, "ignore"}; const Enum::YLeaf Ipv4dhcpdBroadcastFlagPolicy::check {1, "check"}; const Enum::YLeaf Ipv4dhcpdBroadcastFlagPolicy::unicast_always {2, "unicast-always"}; const Enum::YLeaf Ipv4dhcpdFmt::no_format {0, "no-format"}; const Enum::YLeaf Ipv4dhcpdFmt::hex {1, "hex"}; const Enum::YLeaf Ipv4dhcpdFmt::ascii {2, "ascii"}; const Enum::YLeaf Ipv4dhcpdFmt::extended {3, "extended"}; const Enum::YLeaf Ipv4dhcpdRelayInfoOptionvpnMode::rfc {0, "rfc"}; const Enum::YLeaf Ipv4dhcpdRelayInfoOptionvpnMode::cisco {1, "cisco"}; const Enum::YLeaf ProxyAction::allow {0, "allow"}; const Enum::YLeaf ProxyAction::drop {1, "drop"}; const Enum::YLeaf ProxyAction::relay {2, "relay"}; const Enum::YLeaf LeaseLimitValue::per_interface {1, "per-interface"}; const Enum::YLeaf LeaseLimitValue::per_circuit_id {2, "per-circuit-id"}; const Enum::YLeaf LeaseLimitValue::per_remote_id {3, "per-remote-id"}; const Enum::YLeaf Dhcpv4MatchOption::Y_60__FWD_SLASH__60 {60, "60/60"}; const Enum::YLeaf Dhcpv4MatchOption::Y_77__FWD_SLASH__77 {77, "77/77"}; const Enum::YLeaf Dhcpv4MatchOption::Y_124__FWD_SLASH__124 {124, "124/124"}; const Enum::YLeaf Dhcpv4MatchOption::Y_125__FWD_SLASH__125 {125, "125/125"}; const Enum::YLeaf Ipv4dhcpdRelayInfoOptionAuthenticate::received {0, "received"}; const Enum::YLeaf Ipv4dhcpdRelayInfoOptionAuthenticate::inserted {1, "inserted"}; const Enum::YLeaf Ipv4dhcpdRelayGiaddrPolicy::replace {1, "replace"}; const Enum::YLeaf Ipv4dhcpdRelayGiaddrPolicy::drop {2, "drop"}; } }
33.013332
687
0.688629
[ "vector" ]
4abcef1347e813671009cc9e3411e4f813b9aea9
3,054
cpp
C++
Day_24/06_Kruskal_MST.cpp
premnaaath/SDE-180
6d7cc2404d310600a81adaa652049172f2e10ed8
[ "MIT" ]
null
null
null
Day_24/06_Kruskal_MST.cpp
premnaaath/SDE-180
6d7cc2404d310600a81adaa652049172f2e10ed8
[ "MIT" ]
null
null
null
Day_24/06_Kruskal_MST.cpp
premnaaath/SDE-180
6d7cc2404d310600a81adaa652049172f2e10ed8
[ "MIT" ]
null
null
null
// Problem Link: // https://practice.geeksforgeeks.org/problems/minimum-spanning-tree/1# // Priority Queue // TC: O(n*log(n) + n*(4*alpha)) // SC: O(n) #include <bits/stdc++.h> using namespace std; class disjointSet { private: vector<int> parent; vector<int> weight; public: disjointSet(int n) { for (int i = 0; i < n; ++i) { parent.push_back(i); weight.push_back(0); } } int collapsingFind(int node) { if (parent[node] == node) return node; parent[node] = collapsingFind(parent[node]); return parent[node]; } void weightedUnion(int node1, int node2) { int parent1 = collapsingFind(node1); int parent2 = collapsingFind(node2); if (weight[parent1] > weight[parent2]) parent[parent2] = parent1; else if (weight[parent2] > weight[parent2]) parent[parent1] = parent2; else { parent[parent2] = parent1; weight[parent1]++; } } }; class Graph { private: vector<vector<pair<int, int>>> List; public: Graph(int n); void addEdge(int u, int v, int w); void Display(); vector<pair<int, int>> kruskals(); void displayMST(vector<pair<int, int>> &mstEdges); }; Graph::Graph(int n) { List.resize(n); } void Graph::addEdge(int u, int v, int w) { List[u].push_back({v, w}); List[v].push_back({u, w}); } vector<pair<int, int>> Graph::kruskals() { int n = List.size(); vector<pair<int, int>> mstEdges{}; disjointSet ds(n); // Pushing negative weights so that max-heap behaves as a minheap priority_queue<pair<int, pair<int, int>>> minHeap; // Inserting all the edges to the heap for (int i = 0; i < n; ++i) for (auto j : List[i]) minHeap.push({-j.second, {i, j.first}}); while (!minHeap.empty()) { // Getting the current minimum auto curr = minHeap.top(); minHeap.pop(); int node1 = curr.second.first; int node2 = curr.second.second; // if both does not have the same parent, we can say that they wont form a cycle // hence can be considered for MST and weighted union should be performed if (ds.collapsingFind(node1) != ds.collapsingFind(node2)) { mstEdges.push_back({node1, node2}); ds.weightedUnion(node1, node2); } } return mstEdges; } void Graph::displayMST(vector<pair<int, int>> &mstEdges) { for (auto i : mstEdges) for (auto j : List[i.first]) if (j.first == i.second) cout << i.first << " to " << i.second << " - " << j.second << endl; } int main() { int n = 5; vector<int> U{0, 0, 1, 1, 1, 2}; vector<int> V{1, 3, 2, 4, 3, 4}; vector<int> W{2, 6, 3, 5, 8, 7}; Graph G(n); for (int i = 0; i < U.size(); ++i) G.addEdge(U[i], V[i], W[i]); vector<pair<int, int>> mstEdges = G.kruskals(); G.displayMST(mstEdges); return 0; }
22.455882
88
0.552063
[ "vector" ]
4abf0a5a3d2170142067f88d1d4eee175dd0053f
3,230
cpp
C++
src/recorder/joint_state.cpp
Pandhariix/naoqi_driver
460e778b60e48432aecb506e303db8ce64c8315e
[ "Apache-2.0" ]
38
2015-08-20T15:35:48.000Z
2022-03-23T13:43:06.000Z
src/recorder/joint_state.cpp
Pandhariix/naoqi_driver
460e778b60e48432aecb506e303db8ce64c8315e
[ "Apache-2.0" ]
109
2015-07-31T16:11:14.000Z
2022-03-17T14:08:23.000Z
src/recorder/joint_state.cpp
Pandhariix/naoqi_driver
460e778b60e48432aecb506e303db8ce64c8315e
[ "Apache-2.0" ]
78
2015-08-23T08:50:39.000Z
2022-03-07T11:05:39.000Z
/* * Copyright 2015 Aldebaran * * 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. * */ /* * LOCAL includes */ #include "joint_state.hpp" namespace naoqi { namespace recorder { JointStateRecorder::JointStateRecorder( const std::string& topic, float buffer_frequency ): topic_( topic ), buffer_duration_(helpers::recorder::bufferDefaultDuration), is_initialized_( false ), is_subscribed_( false ), buffer_frequency_(buffer_frequency), counter_(1) {} void JointStateRecorder::write( const sensor_msgs::JointState& js_msg, const std::vector<geometry_msgs::TransformStamped>& tf_transforms ) { if (!js_msg.header.stamp.isZero()) { gr_->write(topic_, js_msg, js_msg.header.stamp); } else { gr_->write(topic_, js_msg); } gr_->write("/tf", tf_transforms); } void JointStateRecorder::writeDump(const ros::Time& time) { boost::mutex::scoped_lock lock_write_buffer( mutex_ ); boost::circular_buffer< std::vector<geometry_msgs::TransformStamped> >::iterator it_tf; for (it_tf = bufferTF_.begin(); it_tf != bufferTF_.end(); it_tf++) { gr_->write("/tf", *it_tf); } for (boost::circular_buffer<sensor_msgs::JointState>::iterator it_js = bufferJoinState_.begin(); it_js != bufferJoinState_.end(); it_js++) { if (!it_js->header.stamp.isZero()) { gr_->write(topic_, *it_js, it_js->header.stamp); } else { gr_->write(topic_, *it_js); } } } void JointStateRecorder::reset(boost::shared_ptr<GlobalRecorder> gr, float conv_frequency) { gr_ = gr; conv_frequency_ = conv_frequency; if (buffer_frequency_ != 0) { max_counter_ = static_cast<int>(conv_frequency/buffer_frequency_); buffer_size_ = static_cast<size_t>(buffer_duration_*(conv_frequency/max_counter_)); } else { max_counter_ = 1; buffer_size_ = static_cast<size_t>(buffer_duration_*conv_frequency); } bufferJoinState_.resize(buffer_size_); bufferTF_.resize(buffer_size_); is_initialized_ = true; } void JointStateRecorder::bufferize( const sensor_msgs::JointState& js_msg, const std::vector<geometry_msgs::TransformStamped>& tf_transforms ) { boost::mutex::scoped_lock lock_bufferize( mutex_ ); if (counter_ < max_counter_) { counter_++; } else { counter_ = 1; bufferJoinState_.push_back(js_msg); bufferTF_.push_back(tf_transforms); } } void JointStateRecorder::setBufferDuration(float duration) { boost::mutex::scoped_lock lock_bufferize( mutex_ ); buffer_size_ = static_cast<size_t>(duration*(conv_frequency_/max_counter_)); buffer_duration_ = duration; bufferJoinState_.set_capacity(buffer_size_); bufferTF_.set_capacity(buffer_size_); } } //publisher } // naoqi
28.086957
99
0.713622
[ "vector" ]
4ac205973bc65e5a21f5b4becae9c8ec58dad48a
9,185
cpp
C++
src/CostModelPass.cpp
ferhaterata/etap
ce1953fbe058cb2a8e2d45fbdc28aa9e654fac0f
[ "MIT" ]
2
2022-02-27T11:41:57.000Z
2022-03-03T04:15:24.000Z
src/CostModelPass.cpp
ferhaterata/etap
ce1953fbe058cb2a8e2d45fbdc28aa9e654fac0f
[ "MIT" ]
null
null
null
src/CostModelPass.cpp
ferhaterata/etap
ce1953fbe058cb2a8e2d45fbdc28aa9e654fac0f
[ "MIT" ]
1
2022-02-28T20:15:03.000Z
2022-02-28T20:15:03.000Z
#include <fstream> #include <iostream> #include "llvm/ADT/MapVector.h" #include "llvm/IR/BasicBlock.h" #include "llvm/Passes/PassBuilder.h" #include "llvm/Support/raw_ostream.h" using CostPair = std::pair<std::string, std::string>; using BBCostMap = llvm::MapVector<llvm::BasicBlock*, CostPair>; struct CostModelPass : public llvm::ModulePass { static char ID; llvm::MapVector<llvm::Function*, BBCostMap> FunctionBBCosts; CostModelPass() : ModulePass(ID) {} // --------------------------------------------------------------------------- static CostPair parseCost(llvm::StringRef costs) { llvm::SmallVector<llvm::StringRef, 4> parsedStrings; costs.split(parsedStrings, ";"); return CostPair(parsedStrings[1], parsedStrings[3]); } // --------------------------------------------------------------------------- static CostPair addCostStrings(CostPair p1, const CostPair& p2) { p1.first = p1.first + "+" + p2.first; p1.second = p1.second + "+" + p2.second; return p1; } // --------------------------------------------------------------------------- static bool isTimingCost(llvm::StringRef mdStr) { return mdStr.contains_lower("timing"); } // --------------------------------------------------------------------------- static bool isEnergyCost(llvm::StringRef mdStr) { return mdStr.contains_lower("energy"); } // --------------------------------------------------------------------------- static bool isAboutCost(llvm::StringRef mdStr) { return (mdStr.contains_lower("cost") || mdStr.contains_lower("behaviour")); } // --------------------------------------------------------------------------- static void addCalledFunctionsCostToBBCost(llvm::MDNode* n, llvm::BasicBlock& BB, BBCostMap& BBCosts) { for (int i = 0; i < n->getNumOperands(); ++i) { if (!n->isDistinct()) { llvm::StringRef reliStr = llvm::cast<llvm::MDString>(n->getOperand(i))->getString(); CostPair costForThisBB = BBCosts[&BB]; if (isAboutCost(reliStr)) { std::string cost = reliStr.split(";").second.str(); if (isTimingCost(reliStr)) { costForThisBB.first += "+" + cost; } else if (isEnergyCost(reliStr)) { costForThisBB.second += "+" + cost; } BBCosts[&BB] = costForThisBB; } } } } // --------------------------------------------------------------------------- static void addOpcodeCostToBBCost(llvm::MDNode* n, llvm::BasicBlock& BB, BBCostMap& BBCosts) { if (!n->isDistinct()) { llvm::StringRef costStr = llvm::cast<llvm::MDString>(n->getOperand(0))->getString(); CostPair costForThisBB = BBCosts[&BB]; if (!costForThisBB.first.empty()) { CostPair parsedCostForThisInst = parseCost(costStr); costForThisBB = addCostStrings(costForThisBB, parsedCostForThisInst); } else { costForThisBB = parseCost(costStr); } BBCosts[&BB] = costForThisBB; } } // --------------------------------------------------------------------------- static void addExternalEventsBehaviourToBBCost(llvm::MDNode* n, llvm::BasicBlock& BB, BBCostMap& BBCosts) { for (int i = 0; i < n->getNumOperands(); ++i) { if (!n->isDistinct()) { llvm::StringRef probStr = llvm::cast<llvm::MDString>(n->getOperand(i))->getString(); CostPair costForThisBB = BBCosts[&BB]; if (isAboutCost(probStr)) { std::string cost = probStr.split(";").second.str(); costForThisBB.first += "+" + cost; BBCosts[&BB] = costForThisBB; } } } } // --------------------------------------------------------------------------- static BBCostMap findBBCost(llvm::Function& F) { BBCostMap BBCosts; for (auto& BB : F) { for (auto& I : BB) { // add Instruction's opcode cost to total basicblock cost if (llvm::MDNode* n = I.getMetadata("cost")) { addOpcodeCostToBBCost(n, BB, BBCosts); } // if its a call instruction, we need to add some different types of // cost like called function's total cost if (llvm::isa<llvm::CallInst>(I)) { // add external event behaviour cost to total basicblock cost like if // there is a called stdio scanf function, scanf function is going to // wait for user's input from keyboard to console. The behaviour cost // is how much it will wait for user if (llvm::MDNode* n = I.getMetadata("probability")) { addExternalEventsBehaviourToBBCost(n, BB, BBCosts); } // if called function's cost has already given to us from pragmas add // that if (llvm::MDNode* n = I.getMetadata("reliability")) { addCalledFunctionsCostToBBCost(n, BB, BBCosts); } llvm::SmallVector<std::pair<unsigned, llvm::MDNode*>, 5> callMDs; auto* callI = llvm::cast<llvm::CallInst>(&I); auto* calledFunc = callI->getCalledFunction(); calledFunc->getAllMetadata(callMDs); for (auto pair : callMDs) { for (int i = 0; i < pair.second->getNumOperands(); ++i) { addCalledFunctionsCostToBBCost(pair.second, BB, BBCosts); } } } } } return BBCosts; } // --------------------------------------------------------------------------- void insertCostsToTerminatorInst() { for (auto& FuncBBCostPair : FunctionBBCosts) { for (auto& BB : *FuncBBCostPair.first) { for (auto& I : BB) { if (I.isTerminator()) { BBCostMap BBCostsMap = FuncBBCostPair.second; if (!BBCostsMap[&BB].first.empty()) { llvm::LLVMContext& C = I.getContext(); llvm::SmallVector<llvm::Metadata*, 32> Ops; std::string timing = "timing ; " + BBCostsMap[&BB].first; std::string energy = "energy ; " + BBCostsMap[&BB].second; Ops.push_back(llvm::MDString::get(C, timing)); Ops.push_back(llvm::MDString::get(C, energy)); auto* node = llvm::MDTuple::get(C, Ops); I.setMetadata("block", node); } } } } } } // --------------------------------------------------------------------------- bool hasFunctionCostMetadata(llvm::Function& F) { llvm::SmallVector<std::pair<unsigned, llvm::MDNode*>, 5> MDs; F.getAllMetadata(MDs); for (auto pair : MDs) { llvm::MDNode* n = pair.second; for (int i = 0; i < n->getNumOperands(); ++i) { if (!n->isDistinct()) { llvm::StringRef mdStr = llvm::cast<llvm::MDString>(n->getOperand(i))->getString(); return isAboutCost(mdStr); } } } return false; } // --------------------------------------------------------------------------- void insertFunctionCost(llvm::Function& F) { if (F.getName() == "main") return; if (F.getBasicBlockList().empty()) return; if (hasFunctionCostMetadata(F)) return; llvm::LLVMContext& C = F.getContext(); std::string functTimingCost; std::string functEnergyCost; for (const auto& pair : FunctionBBCosts[&F]) { functTimingCost += pair.second.first; functEnergyCost += pair.second.second; } functTimingCost = "timing ; " + functTimingCost; functEnergyCost = "energy ; " + functEnergyCost; llvm::MDNode& NTiming = *llvm::MDNode::get(C, llvm::MDString::get(C, functTimingCost)); llvm::MDNode& NEnergy = *llvm::MDNode::get(C, llvm::MDString::get(C, functEnergyCost)); F.addMetadata("reliability", NTiming); F.addMetadata("reliability", NEnergy); } // --------------------------------------------------------------------------- void printBBCostsToFile() { std::ofstream File; for (const auto& FunctionBBCost : FunctionBBCosts) { if (FunctionBBCost.first->isDeclaration()) continue; File.open(".output/" + (std::string)FunctionBBCost.first->getName() + ".bbcost"); for (const auto& BBCost : FunctionBBCost.second) { File << "basicblock: " << (std::string)BBCost.first->getName() << "\n"; File << "timing: " << (std::string)BBCost.second.first << "\n"; File << "energy: " << (std::string)BBCost.second.second << "\n"; } File.close(); } } // --------------------------------------------------------------------------- bool runOnModule(llvm::Module& M) override { for (llvm::Function& F : M) { BBCostMap bbCostForThisFunction = findBBCost(F); FunctionBBCosts[&F] = bbCostForThisFunction; insertFunctionCost(F); } insertCostsToTerminatorInst(); printBBCostsToFile(); return false; } }; char CostModelPass::ID = 0; [[maybe_unused]] static llvm::RegisterPass<CostModelPass> X( "bb-cost-model", "Basic Block Cost Model");
40.285088
80
0.51497
[ "model" ]
4ac42f59af002bc2f829aafc0a2f0f821a83e8af
19,893
cc
C++
wrappers/8.1.1/vtkImageShrink3DWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
6
2016-02-03T12:48:36.000Z
2020-09-16T15:07:51.000Z
wrappers/8.1.1/vtkImageShrink3DWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
4
2016-02-13T01:30:43.000Z
2020-03-30T16:59:32.000Z
wrappers/8.1.1/vtkImageShrink3DWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
null
null
null
/* this file has been autogenerated by vtkNodeJsWrap */ /* editing this might proof futile */ #define VTK_WRAPPING_CXX #define VTK_STREAMS_FWD_ONLY #include <nan.h> #include "vtkThreadedImageAlgorithmWrap.h" #include "vtkImageShrink3DWrap.h" #include "vtkObjectBaseWrap.h" #include "../../plus/plus.h" using namespace v8; extern Nan::Persistent<v8::Object> vtkNodeJsNoWrap; Nan::Persistent<v8::FunctionTemplate> VtkImageShrink3DWrap::ptpl; VtkImageShrink3DWrap::VtkImageShrink3DWrap() { } VtkImageShrink3DWrap::VtkImageShrink3DWrap(vtkSmartPointer<vtkImageShrink3D> _native) { native = _native; } VtkImageShrink3DWrap::~VtkImageShrink3DWrap() { } void VtkImageShrink3DWrap::Init(v8::Local<v8::Object> exports) { Nan::SetAccessor(exports, Nan::New("vtkImageShrink3D").ToLocalChecked(), ConstructorGetter); Nan::SetAccessor(exports, Nan::New("ImageShrink3D").ToLocalChecked(), ConstructorGetter); } void VtkImageShrink3DWrap::ConstructorGetter( v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info) { InitPtpl(); info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction()); } void VtkImageShrink3DWrap::InitPtpl() { if (!ptpl.IsEmpty()) return; v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New); VtkThreadedImageAlgorithmWrap::InitPtpl( ); tpl->Inherit(Nan::New<FunctionTemplate>(VtkThreadedImageAlgorithmWrap::ptpl)); tpl->SetClassName(Nan::New("VtkImageShrink3DWrap").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(tpl, "AveragingOff", AveragingOff); Nan::SetPrototypeMethod(tpl, "averagingOff", AveragingOff); Nan::SetPrototypeMethod(tpl, "AveragingOn", AveragingOn); Nan::SetPrototypeMethod(tpl, "averagingOn", AveragingOn); Nan::SetPrototypeMethod(tpl, "GetAveraging", GetAveraging); Nan::SetPrototypeMethod(tpl, "getAveraging", GetAveraging); Nan::SetPrototypeMethod(tpl, "GetMaximum", GetMaximum); Nan::SetPrototypeMethod(tpl, "getMaximum", GetMaximum); Nan::SetPrototypeMethod(tpl, "GetMean", GetMean); Nan::SetPrototypeMethod(tpl, "getMean", GetMean); Nan::SetPrototypeMethod(tpl, "GetMedian", GetMedian); Nan::SetPrototypeMethod(tpl, "getMedian", GetMedian); Nan::SetPrototypeMethod(tpl, "GetMinimum", GetMinimum); Nan::SetPrototypeMethod(tpl, "getMinimum", GetMinimum); Nan::SetPrototypeMethod(tpl, "GetShift", GetShift); Nan::SetPrototypeMethod(tpl, "getShift", GetShift); Nan::SetPrototypeMethod(tpl, "GetShrinkFactors", GetShrinkFactors); Nan::SetPrototypeMethod(tpl, "getShrinkFactors", GetShrinkFactors); Nan::SetPrototypeMethod(tpl, "MaximumOff", MaximumOff); Nan::SetPrototypeMethod(tpl, "maximumOff", MaximumOff); Nan::SetPrototypeMethod(tpl, "MaximumOn", MaximumOn); Nan::SetPrototypeMethod(tpl, "maximumOn", MaximumOn); Nan::SetPrototypeMethod(tpl, "MeanOff", MeanOff); Nan::SetPrototypeMethod(tpl, "meanOff", MeanOff); Nan::SetPrototypeMethod(tpl, "MeanOn", MeanOn); Nan::SetPrototypeMethod(tpl, "meanOn", MeanOn); Nan::SetPrototypeMethod(tpl, "MedianOff", MedianOff); Nan::SetPrototypeMethod(tpl, "medianOff", MedianOff); Nan::SetPrototypeMethod(tpl, "MedianOn", MedianOn); Nan::SetPrototypeMethod(tpl, "medianOn", MedianOn); Nan::SetPrototypeMethod(tpl, "MinimumOff", MinimumOff); Nan::SetPrototypeMethod(tpl, "minimumOff", MinimumOff); Nan::SetPrototypeMethod(tpl, "MinimumOn", MinimumOn); Nan::SetPrototypeMethod(tpl, "minimumOn", MinimumOn); Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "SetAveraging", SetAveraging); Nan::SetPrototypeMethod(tpl, "setAveraging", SetAveraging); Nan::SetPrototypeMethod(tpl, "SetMaximum", SetMaximum); Nan::SetPrototypeMethod(tpl, "setMaximum", SetMaximum); Nan::SetPrototypeMethod(tpl, "SetMean", SetMean); Nan::SetPrototypeMethod(tpl, "setMean", SetMean); Nan::SetPrototypeMethod(tpl, "SetMedian", SetMedian); Nan::SetPrototypeMethod(tpl, "setMedian", SetMedian); Nan::SetPrototypeMethod(tpl, "SetMinimum", SetMinimum); Nan::SetPrototypeMethod(tpl, "setMinimum", SetMinimum); Nan::SetPrototypeMethod(tpl, "SetShift", SetShift); Nan::SetPrototypeMethod(tpl, "setShift", SetShift); Nan::SetPrototypeMethod(tpl, "SetShrinkFactors", SetShrinkFactors); Nan::SetPrototypeMethod(tpl, "setShrinkFactors", SetShrinkFactors); #ifdef VTK_NODE_PLUS_VTKIMAGESHRINK3DWRAP_INITPTPL VTK_NODE_PLUS_VTKIMAGESHRINK3DWRAP_INITPTPL #endif ptpl.Reset( tpl ); } void VtkImageShrink3DWrap::New(const Nan::FunctionCallbackInfo<v8::Value>& info) { if(!info.IsConstructCall()) { Nan::ThrowError("Constructor not called in a construct call."); return; } if(info.Length() == 0) { vtkSmartPointer<vtkImageShrink3D> native = vtkSmartPointer<vtkImageShrink3D>::New(); VtkImageShrink3DWrap* obj = new VtkImageShrink3DWrap(native); obj->Wrap(info.This()); } else { if(info[0]->ToObject() != vtkNodeJsNoWrap ) { Nan::ThrowError("Parameter Error"); return; } } info.GetReturnValue().Set(info.This()); } void VtkImageShrink3DWrap::AveragingOff(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageShrink3DWrap *wrapper = ObjectWrap::Unwrap<VtkImageShrink3DWrap>(info.Holder()); vtkImageShrink3D *native = (vtkImageShrink3D *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->AveragingOff(); } void VtkImageShrink3DWrap::AveragingOn(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageShrink3DWrap *wrapper = ObjectWrap::Unwrap<VtkImageShrink3DWrap>(info.Holder()); vtkImageShrink3D *native = (vtkImageShrink3D *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->AveragingOn(); } void VtkImageShrink3DWrap::GetAveraging(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageShrink3DWrap *wrapper = ObjectWrap::Unwrap<VtkImageShrink3DWrap>(info.Holder()); vtkImageShrink3D *native = (vtkImageShrink3D *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetAveraging(); info.GetReturnValue().Set(Nan::New(r)); } void VtkImageShrink3DWrap::GetMaximum(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageShrink3DWrap *wrapper = ObjectWrap::Unwrap<VtkImageShrink3DWrap>(info.Holder()); vtkImageShrink3D *native = (vtkImageShrink3D *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetMaximum(); info.GetReturnValue().Set(Nan::New(r)); } void VtkImageShrink3DWrap::GetMean(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageShrink3DWrap *wrapper = ObjectWrap::Unwrap<VtkImageShrink3DWrap>(info.Holder()); vtkImageShrink3D *native = (vtkImageShrink3D *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetMean(); info.GetReturnValue().Set(Nan::New(r)); } void VtkImageShrink3DWrap::GetMedian(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageShrink3DWrap *wrapper = ObjectWrap::Unwrap<VtkImageShrink3DWrap>(info.Holder()); vtkImageShrink3D *native = (vtkImageShrink3D *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetMedian(); info.GetReturnValue().Set(Nan::New(r)); } void VtkImageShrink3DWrap::GetMinimum(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageShrink3DWrap *wrapper = ObjectWrap::Unwrap<VtkImageShrink3DWrap>(info.Holder()); vtkImageShrink3D *native = (vtkImageShrink3D *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetMinimum(); info.GetReturnValue().Set(Nan::New(r)); } void VtkImageShrink3DWrap::GetShift(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageShrink3DWrap *wrapper = ObjectWrap::Unwrap<VtkImageShrink3DWrap>(info.Holder()); vtkImageShrink3D *native = (vtkImageShrink3D *)wrapper->native.GetPointer(); int const * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetShift(); Local<v8::ArrayBuffer> ab = v8::ArrayBuffer::New(v8::Isolate::GetCurrent(), 3 * sizeof(int)); Local<v8::Int32Array> at = v8::Int32Array::New(ab, 0, 3); memcpy(ab->GetContents().Data(), r, 3 * sizeof(int)); info.GetReturnValue().Set(at); } void VtkImageShrink3DWrap::GetShrinkFactors(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageShrink3DWrap *wrapper = ObjectWrap::Unwrap<VtkImageShrink3DWrap>(info.Holder()); vtkImageShrink3D *native = (vtkImageShrink3D *)wrapper->native.GetPointer(); int const * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetShrinkFactors(); Local<v8::ArrayBuffer> ab = v8::ArrayBuffer::New(v8::Isolate::GetCurrent(), 3 * sizeof(int)); Local<v8::Int32Array> at = v8::Int32Array::New(ab, 0, 3); memcpy(ab->GetContents().Data(), r, 3 * sizeof(int)); info.GetReturnValue().Set(at); } void VtkImageShrink3DWrap::MaximumOff(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageShrink3DWrap *wrapper = ObjectWrap::Unwrap<VtkImageShrink3DWrap>(info.Holder()); vtkImageShrink3D *native = (vtkImageShrink3D *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->MaximumOff(); } void VtkImageShrink3DWrap::MaximumOn(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageShrink3DWrap *wrapper = ObjectWrap::Unwrap<VtkImageShrink3DWrap>(info.Holder()); vtkImageShrink3D *native = (vtkImageShrink3D *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->MaximumOn(); } void VtkImageShrink3DWrap::MeanOff(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageShrink3DWrap *wrapper = ObjectWrap::Unwrap<VtkImageShrink3DWrap>(info.Holder()); vtkImageShrink3D *native = (vtkImageShrink3D *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->MeanOff(); } void VtkImageShrink3DWrap::MeanOn(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageShrink3DWrap *wrapper = ObjectWrap::Unwrap<VtkImageShrink3DWrap>(info.Holder()); vtkImageShrink3D *native = (vtkImageShrink3D *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->MeanOn(); } void VtkImageShrink3DWrap::MedianOff(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageShrink3DWrap *wrapper = ObjectWrap::Unwrap<VtkImageShrink3DWrap>(info.Holder()); vtkImageShrink3D *native = (vtkImageShrink3D *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->MedianOff(); } void VtkImageShrink3DWrap::MedianOn(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageShrink3DWrap *wrapper = ObjectWrap::Unwrap<VtkImageShrink3DWrap>(info.Holder()); vtkImageShrink3D *native = (vtkImageShrink3D *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->MedianOn(); } void VtkImageShrink3DWrap::MinimumOff(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageShrink3DWrap *wrapper = ObjectWrap::Unwrap<VtkImageShrink3DWrap>(info.Holder()); vtkImageShrink3D *native = (vtkImageShrink3D *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->MinimumOff(); } void VtkImageShrink3DWrap::MinimumOn(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageShrink3DWrap *wrapper = ObjectWrap::Unwrap<VtkImageShrink3DWrap>(info.Holder()); vtkImageShrink3D *native = (vtkImageShrink3D *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->MinimumOn(); } void VtkImageShrink3DWrap::NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageShrink3DWrap *wrapper = ObjectWrap::Unwrap<VtkImageShrink3DWrap>(info.Holder()); vtkImageShrink3D *native = (vtkImageShrink3D *)wrapper->native.GetPointer(); vtkImageShrink3D * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->NewInstance(); VtkImageShrink3DWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkImageShrink3DWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkImageShrink3DWrap *w = new VtkImageShrink3DWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkImageShrink3DWrap::SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageShrink3DWrap *wrapper = ObjectWrap::Unwrap<VtkImageShrink3DWrap>(info.Holder()); vtkImageShrink3D *native = (vtkImageShrink3D *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectBaseWrap::ptpl))->HasInstance(info[0])) { VtkObjectBaseWrap *a0 = ObjectWrap::Unwrap<VtkObjectBaseWrap>(info[0]->ToObject()); vtkImageShrink3D * r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->SafeDownCast( (vtkObjectBase *) a0->native.GetPointer() ); VtkImageShrink3DWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkImageShrink3DWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkImageShrink3DWrap *w = new VtkImageShrink3DWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); return; } Nan::ThrowError("Parameter mismatch"); } void VtkImageShrink3DWrap::SetAveraging(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageShrink3DWrap *wrapper = ObjectWrap::Unwrap<VtkImageShrink3DWrap>(info.Holder()); vtkImageShrink3D *native = (vtkImageShrink3D *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetAveraging( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkImageShrink3DWrap::SetMaximum(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageShrink3DWrap *wrapper = ObjectWrap::Unwrap<VtkImageShrink3DWrap>(info.Holder()); vtkImageShrink3D *native = (vtkImageShrink3D *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetMaximum( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkImageShrink3DWrap::SetMean(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageShrink3DWrap *wrapper = ObjectWrap::Unwrap<VtkImageShrink3DWrap>(info.Holder()); vtkImageShrink3D *native = (vtkImageShrink3D *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetMean( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkImageShrink3DWrap::SetMedian(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageShrink3DWrap *wrapper = ObjectWrap::Unwrap<VtkImageShrink3DWrap>(info.Holder()); vtkImageShrink3D *native = (vtkImageShrink3D *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetMedian( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkImageShrink3DWrap::SetMinimum(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageShrink3DWrap *wrapper = ObjectWrap::Unwrap<VtkImageShrink3DWrap>(info.Holder()); vtkImageShrink3D *native = (vtkImageShrink3D *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetMinimum( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkImageShrink3DWrap::SetShift(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageShrink3DWrap *wrapper = ObjectWrap::Unwrap<VtkImageShrink3DWrap>(info.Holder()); vtkImageShrink3D *native = (vtkImageShrink3D *)wrapper->native.GetPointer(); size_t i; if(info.Length() > 0 && info[0]->IsInt32Array()) { v8::Local<v8::Int32Array>a0(v8::Local<v8::Int32Array>::Cast(info[0]->ToObject())); if( a0->Length() < 3 ) { Nan::ThrowError("Array too short."); return; } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetShift( (int *)(a0->Buffer()->GetContents().Data()) ); return; } else if(info.Length() > 0 && info[0]->IsArray()) { v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject())); int b0[3]; if( a0->Length() < 3 ) { Nan::ThrowError("Array too short."); return; } for( i = 0; i < 3; i++ ) { if( !a0->Get(i)->IsInt32() ) { Nan::ThrowError("Array contents invalid."); return; } b0[i] = a0->Get(i)->Int32Value(); } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetShift( b0 ); return; } else if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() > 1 && info[1]->IsInt32()) { if(info.Length() > 2 && info[2]->IsInt32()) { if(info.Length() != 3) { Nan::ThrowError("Too many parameters."); return; } native->SetShift( info[0]->Int32Value(), info[1]->Int32Value(), info[2]->Int32Value() ); return; } } } Nan::ThrowError("Parameter mismatch"); } void VtkImageShrink3DWrap::SetShrinkFactors(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkImageShrink3DWrap *wrapper = ObjectWrap::Unwrap<VtkImageShrink3DWrap>(info.Holder()); vtkImageShrink3D *native = (vtkImageShrink3D *)wrapper->native.GetPointer(); size_t i; if(info.Length() > 0 && info[0]->IsInt32Array()) { v8::Local<v8::Int32Array>a0(v8::Local<v8::Int32Array>::Cast(info[0]->ToObject())); if( a0->Length() < 3 ) { Nan::ThrowError("Array too short."); return; } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetShrinkFactors( (int *)(a0->Buffer()->GetContents().Data()) ); return; } else if(info.Length() > 0 && info[0]->IsArray()) { v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject())); int b0[3]; if( a0->Length() < 3 ) { Nan::ThrowError("Array too short."); return; } for( i = 0; i < 3; i++ ) { if( !a0->Get(i)->IsInt32() ) { Nan::ThrowError("Array contents invalid."); return; } b0[i] = a0->Get(i)->Int32Value(); } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetShrinkFactors( b0 ); return; } else if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() > 1 && info[1]->IsInt32()) { if(info.Length() > 2 && info[2]->IsInt32()) { if(info.Length() != 3) { Nan::ThrowError("Too many parameters."); return; } native->SetShrinkFactors( info[0]->Int32Value(), info[1]->Int32Value(), info[2]->Int32Value() ); return; } } } Nan::ThrowError("Parameter mismatch"); }
29.040876
106
0.705072
[ "object" ]
4ac85dca08f5a221e7f4e56a349449ac0f3416c8
20,023
cpp
C++
graphics/meshlab/src/meshlabplugins/edit_quality/common/transferfunction.cpp
hlzz/dotfiles
0591f71230c919c827ba569099eb3b75897e163e
[ "BSD-3-Clause" ]
4
2016-03-30T14:31:52.000Z
2019-02-02T05:01:32.000Z
graphics/meshlab/src/meshlabplugins/edit_quality/common/transferfunction.cpp
hlzz/dotfiles
0591f71230c919c827ba569099eb3b75897e163e
[ "BSD-3-Clause" ]
null
null
null
graphics/meshlab/src/meshlabplugins/edit_quality/common/transferfunction.cpp
hlzz/dotfiles
0591f71230c919c827ba569099eb3b75897e163e
[ "BSD-3-Clause" ]
null
null
null
/**************************************************************************** * MeshLab o o * * A versatile mesh processing toolbox o o * * _ O _ * * Copyright(C) 2005 \/)\/ * * Visual Computing Lab /\/| * * ISTI - Italian National Research Council | * * \ * * All rights reserved. * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License (http://www.gnu.org/licenses/gpl.txt) * * for more details. * * * ****************************************************************************/ /**************************************************************************** History Revision 1.0 2008/02/20 Alessandro Maione, Federico Bellucci FIRST RELEASE ****************************************************************************/ #include "transferfunction.h" #include <QDir> #include <QFile> #include <QTextStream> #include <QFileDialog> #include <algorithm> //used just for testing //define NOW_TESTING macro to use some testing options #ifdef NOW_TESTING #include <cmath> #endif using namespace std; using namespace vcg; //function used to define < relations among TF_KEYs elements bool TfKeyPCompare(TF_KEY*k1, TF_KEY*k2) { return (k1->x < k2->x); } //TRANSFER FUNCTION CHANNEL CODE TfChannel::TfChannel() { #ifdef NOW_TESTING this->testInitChannel(); #endif } TfChannel::TfChannel(TF_CHANNELS type) : _type(type) { #ifdef NOW_TESTING this->testInitChannel(); #endif } TfChannel::~TfChannel(void) { //destroying TF_KEYs KEY_LISTiterator it; TF_KEY *k = 0; for (it=KEYS.begin(); it!=KEYS.end(); it++) { k = *it; delete k; k = 0; } //resetting keys list KEYS.clear(); } //sets the type of the channel (channel code, defined using a TF_CHANNELS list member) void TfChannel::setType(TF_CHANNELS type) { _type = type; } //returns the type of channel (channel code defined by TF_CHANNELS list) TF_CHANNELS TfChannel::getType() { return _type; } //adds to the keys list new_key //returns a pointer to the key just added TF_KEY* TfChannel::addKey(float xVal, float yVal) { assert(xVal>=0.0f); assert(yVal>=0.0f); return this->addKey(new TF_KEY(xVal, yVal)); } //adds to the keys list a new keys with fields passed to the method //returns a pointer to the key just added TF_KEY* TfChannel::addKey(TF_KEY *newKey) { assert(newKey->x>=0); assert(newKey->y>=0); //inserting the key in the correct position //x value order is kept for (KEY_LISTiterator it=KEYS.begin(); it!=KEYS.end(); it++) { if ( (*it)->x >= newKey->x ) { KEYS.insert(it, newKey); return newKey; } } //greatest x ever //adding new key at the end of the list KEYS.push_back(newKey); return newKey; } //removes from keys list the key at index keyIdx void TfChannel::removeKey(int keyIdx) { KEY_LISTiterator it = KEYS.begin(); if ((keyIdx >= 0) && (keyIdx<(int)KEYS.size())) { it += (keyIdx * TF_KEYsize); delete *it; KEYS.erase(it); } } //removes from keys list the key pointer is toRemoveKey void TfChannel::removeKey(TF_KEY *toRemoveKey) { //searching key in the list... for (KEY_LISTiterator it=KEYS.begin(); it!=KEYS.end(); it++) if ( (*it) == toRemoveKey ) { //found it. Deleting delete *it; KEYS.erase(it); break; } } //returns the value (as float) of the transfer function for a certain channel in a given point (xVal) //if the xVal value respond to the x of a key present in the list, the corresponding y value is returned, //else linear interpolation is effected and the resulting value is returned float TfChannel::getChannelValuef(float xVal) { float result = 0.0f; //if a x_position is known x, its key value is returned immediately for (KEY_LISTiterator it=KEYS.begin(); it!=KEYS.end(); it++) if ( (*it)->x >= xVal ) if ( (*it)->x == xVal ) return (*it)->y; else { //xVal is not the x of a key... //the returning value will be obtained through linear interpolation between closest x-value keys in the list //acquiring position of right key float x2 = (*it)->x; float y2 = (*it)->y; it--; //acquiring position of left key float x1 = (*it)->x; float y1 = (*it)->y; if (( x1 < xVal ) && ( x2 > xVal) ) { //applying linear interpolation between two keys values //angular coefficient for interpolating line float m = (y2-y1) / (x2-x1); //returning f(x) value for x in the interpolating line result = m * (xVal - x1) + y1; } break; } return result; } //returns the value (as unsigned char) of the transfer function for a certain channel in a given point (xVal) //if the xVal value respond to the x of a key present in the list, the corresponding y value is returned, //else linear interpolation is effected and the resulting value is returned UINT8 TfChannel::getChannelValueb(float xVal) { return (UINT8)relative2AbsoluteVali( this->getChannelValuef(xVal), 255.0f ); } //returns true if the key has x=0.0 bool TfChannel::isHead(TF_KEY *key) { assert(key!=0); return ( key->x == 0.0f ); } //returns true if the key has x=1.0 bool TfChannel::isTail(TF_KEY *key) { assert(key!=0); return ( key->x == 1.0f ); } //this method is called by TFHandle and is used to update the TfHandle position from graphics to logical level. //When the key value is updated, the keys list must be checked to restore the sorting and the right alternation of LEFT\RIGHT JUNCTION SIDE keys void TfChannel::updateKeysOrder() { sort(KEYS.begin(), KEYS.end(), TfKeyPCompare); } //operator redefinition. Returns the key in the key list whose x-value equals xVal TF_KEY* TfChannel::operator [](float xVal) { //looking in the list for the key with the proper x for (KEY_LISTiterator it=KEYS.begin(); it!=KEYS.end(); it++) if ( (*it)->x == xVal ) return (*it); return 0; } //operator redefinition. Returns the key in the key list whose index equals i TF_KEY* TfChannel::operator [](int i) { if ((i >= 0) && (i<(int)KEYS.size())) return KEYS[i]; return 0; } //CODE USED FOR TESTING (define NOW_TESTING macro to use it) #ifdef NOW_TESTING //addes random key to channel void TfChannel::testInitChannel() { int num_of_keys = (rand() % 10) + 1; float rand_x = 0.0f; float rand_y = 0.0f; float offset = 0.0f; //first node\key = 0 this->addKey(0.0f, 0.0f, 0.0f); for (int i=0; i<num_of_keys; i++) { rand_x = ((rand() % 100) + 1) / 100.0f; rand_y = ((rand() % 100) + 1) / 100.0f; offset = ((rand() % 100) + 1) / 100.0f; if (offset > (1.0f-rand_y)) offset = (1.0f-rand_y); this->addKey(rand_x, rand_y, rand_y + offset); } this->addKey(1.0f, 0.0f, 0.0f); } #endif //TRANSFER FUNCTION CODE //declaration of static member of TransferFunction class QString TransferFunction::defaultTFs[NUMBER_OF_DEFAULT_TF]; TransferFunction::TransferFunction(void) { this->initTF(); } //this overloaded constructor configures the Transfer Function object according to the transfer function code passed to it //(the code passed must be an item of the DEFAULT_TRANSFER_FUNCTIONS values list) TransferFunction::TransferFunction(DEFAULT_TRANSFER_FUNCTIONS code) { this->initTF(); switch(code) { case GREY_SCALE_TF: _channels[RED_CHANNEL].addKey(0.0f,0.0f); _channels[RED_CHANNEL].addKey(1.0f,1.0f); _channels[GREEN_CHANNEL].addKey(0.0f,0.0f); _channels[GREEN_CHANNEL].addKey(1.0f,1.0f); _channels[BLUE_CHANNEL].addKey(0.0f,0.0f); _channels[BLUE_CHANNEL].addKey(1.0f,1.0f); break; case MESHLAB_RGB_TF: _channels[RED_CHANNEL].addKey(0.0f,0.0f); _channels[RED_CHANNEL].addKey(0.125f,0.0f); _channels[RED_CHANNEL].addKey(0.375f,0.0f); _channels[RED_CHANNEL].addKey(0.625f,1.0f); _channels[RED_CHANNEL].addKey(0.875f,1.0f); _channels[RED_CHANNEL].addKey(1.0f,0.5f); _channels[GREEN_CHANNEL].addKey(0.0f,0.0f); _channels[GREEN_CHANNEL].addKey(0.125f,0.0f); _channels[GREEN_CHANNEL].addKey(0.375f,1.0f); _channels[GREEN_CHANNEL].addKey(0.625f,1.0f); _channels[GREEN_CHANNEL].addKey(0.875f,0.0f); _channels[GREEN_CHANNEL].addKey(1.0f,0.0f); _channels[BLUE_CHANNEL].addKey(0.0f,0.5f); _channels[BLUE_CHANNEL].addKey(0.125f,1.0f); _channels[BLUE_CHANNEL].addKey(0.375f,1.0f); _channels[BLUE_CHANNEL].addKey(0.625f,0.0f); _channels[BLUE_CHANNEL].addKey(0.875f,0.0f); _channels[BLUE_CHANNEL].addKey(1.0f,0.0f); break; case RGB_TF: _channels[RED_CHANNEL].addKey(0.0f,1.0f); _channels[RED_CHANNEL].addKey(0.5f,0.0f); _channels[RED_CHANNEL].addKey(1.0f,0.0f); _channels[GREEN_CHANNEL].addKey(0.0f,0.0f); _channels[GREEN_CHANNEL].addKey(0.5f,1.0f); _channels[GREEN_CHANNEL].addKey(1.0f,0.0f); _channels[BLUE_CHANNEL].addKey(0.0f,0.0f); _channels[BLUE_CHANNEL].addKey(0.5f,0.0f); _channels[BLUE_CHANNEL].addKey(1.0f,1.0f); break; case FRENCH_RGB_TF: _channels[RED_CHANNEL].addKey(0.0f,1.0f); _channels[RED_CHANNEL].addKey(0.5f,1.0f); _channels[RED_CHANNEL].addKey(1.0f,0.0f); _channels[GREEN_CHANNEL].addKey(0.0f,0.0f); _channels[GREEN_CHANNEL].addKey(0.5f,1.0f); _channels[GREEN_CHANNEL].addKey(1.0f,0.0f); _channels[BLUE_CHANNEL].addKey(0.0f,0.0f); _channels[BLUE_CHANNEL].addKey(0.5f,1.0f); _channels[BLUE_CHANNEL].addKey(1.0f,1.0f); break; case RED_SCALE_TF: _channels[RED_CHANNEL].addKey(0.0f,0.0f); _channels[RED_CHANNEL].addKey(1.0f,1.0f); _channels[GREEN_CHANNEL].addKey(0.0f,0.0f); _channels[GREEN_CHANNEL].addKey(1.0f,0.0f); _channels[BLUE_CHANNEL].addKey(0.0f,0.0f); _channels[BLUE_CHANNEL].addKey(1.0f,0.0f); break; case GREEN_SCALE_TF: _channels[RED_CHANNEL].addKey(0.0f,0.0f); _channels[RED_CHANNEL].addKey(1.0f,0.0f); _channels[GREEN_CHANNEL].addKey(0.0f,0.0f); _channels[GREEN_CHANNEL].addKey(1.0f,1.0f); _channels[BLUE_CHANNEL].addKey(0.0f,0.0f); _channels[BLUE_CHANNEL].addKey(1.0f,0.0f); break; case BLUE_SCALE_TF: _channels[RED_CHANNEL].addKey(0.0f,0.0f); _channels[RED_CHANNEL].addKey(1.0f,0.0f); _channels[GREEN_CHANNEL].addKey(0.0f,0.0f); _channels[GREEN_CHANNEL].addKey(1.0f,0.0f); _channels[BLUE_CHANNEL].addKey(0.0f,0.0f); _channels[BLUE_CHANNEL].addKey(1.0f,1.0f); break; case FLAT_TF: default: _channels[RED_CHANNEL].addKey(0.0f,0.5f); _channels[RED_CHANNEL].addKey(1.0f,0.5f); _channels[GREEN_CHANNEL].addKey(0.0f,0.5f); _channels[GREEN_CHANNEL].addKey(1.0f,0.5f); _channels[BLUE_CHANNEL].addKey(0.0f,0.5f); _channels[BLUE_CHANNEL].addKey(1.0f,0.5f); break; case SAW_4_TF: for(int i=0;i<4;++i) { _channels[RED_CHANNEL].addKey(0.25f*i, 0.0f); _channels[RED_CHANNEL].addKey(0.25f*(i+1)-0.0001,1.0f); _channels[GREEN_CHANNEL].addKey(0.25f*i, 0.0f); _channels[GREEN_CHANNEL].addKey(0.25f*(i+1)-0.0001,1.0f); _channels[BLUE_CHANNEL].addKey(0.25f*i, 0.0f); _channels[BLUE_CHANNEL].addKey(0.25f*(i+1)-0.0001,1.0f); } break; case SAW_8_TF: for(int i=0;i<8;++i) { _channels[RED_CHANNEL].addKey(0.125f*i, 0.0f); _channels[RED_CHANNEL].addKey(0.125f*(i+1)-0.0001,1.0f); _channels[GREEN_CHANNEL].addKey(0.125f*i, 0.0f); _channels[GREEN_CHANNEL].addKey(0.125f*(i+1)-0.0001,1.0f); _channels[BLUE_CHANNEL].addKey(0.125f*i, 0.0f); _channels[BLUE_CHANNEL].addKey(0.125f*(i+1)-0.0001,1.0f); } break; } } //this overloaded constructor configures the Transfer Function using the info present in an external CSV file TransferFunction::TransferFunction(QString fileName) { this->initTF(); QFile inFile( fileName ); if ( !inFile.open(QIODevice::ReadOnly | QIODevice::Text)) return; QTextStream inStream( &inFile ); QString line; QStringList splittedString; //each not-commented line of the file represent the values to build-up a channel int channel_code = 0; do { line = inStream.readLine(); //if a line is a comment, it's not processed. imply ignoring it! if ( !line.startsWith(CSV_FILE_COMMENT) ) { //a channel line found. Splitting it to find the values splittedString = line.split(CSV_FILE_SEPARATOR, QString::SkipEmptyParts); assert( (splittedString.size() % 2) == 0 ); //for each couple of values a key is built and added to the current channel for ( int i=0; i<splittedString.size(); i+=2 ) _channels[channel_code].addKey( splittedString[i].toFloat(), splittedString[i+1].toFloat() ); //trying to load data for the next channel channel_code ++; } } while( (!line.isNull()) && (channel_code < NUMBER_OF_CHANNELS) ); inFile.close(); } TransferFunction::~TransferFunction(void) { } //initializes the Transfer Function at startup void TransferFunction::initTF() { //Initializing channels types and pivoting indexes. //Each index in channel order has the same value of the enum for (int i=0; i<NUMBER_OF_CHANNELS; i++) { _channels[i].setType((TF_CHANNELS)i); _channels_order[i] = i; } //resetting color band value memset(_color_band,0,sizeof(_color_band)); //setting default transfer functions names defaultTFs[GREY_SCALE_TF] = "Grey Scale"; defaultTFs[MESHLAB_RGB_TF] = "Meshlab RGB"; defaultTFs[FRENCH_RGB_TF] = "Red-White-Blue Scale"; defaultTFs[RGB_TF] = "RGB"; defaultTFs[RED_SCALE_TF] = "Red Scale"; defaultTFs[GREEN_SCALE_TF] = "Green Scale"; defaultTFs[BLUE_SCALE_TF] = "Blue Scale"; defaultTFs[SAW_4_TF] = "SawTooth Gray 4"; defaultTFs[SAW_8_TF] = "SawTooth Gray 8"; defaultTFs[FLAT_TF] = "Flat"; } //returns the size of the TF. It's defined as the maximum size of each channel int TransferFunction::size() { int result = 0; for (int i=0; i<NUMBER_OF_CHANNELS; i++) if ( _channels[i].size() > result ) result = _channels[i].size(); return result; } //Builds the color band by setting the proper color for each item //returns a pointer to the color band built QColor* TransferFunction::buildColorBand() { float relative_pos = 0.0f; for (int i=0; i<COLOR_BAND_SIZE; i++) { //converting the index in relative TF x-coordinate relative_pos = absolute2RelativeValf((float)i, COLOR_BAND_SIZE); //setting the color of the color band with the color resulting by evaluation of the TF for each channel _color_band[i].setRgbF( _channels[RED_CHANNEL].getChannelValuef( relative_pos), _channels[GREEN_CHANNEL].getChannelValuef( relative_pos ), _channels[BLUE_CHANNEL].getChannelValuef( relative_pos ) ); } return _color_band; } //converts a quality percentage value into a color depending on the transfer function channels values Color4b TransferFunction::getColorByQuality (float percentageQuality) { return Color4b(_channels[RED_CHANNEL].getChannelValueb( percentageQuality ), _channels[GREEN_CHANNEL].getChannelValueb( percentageQuality ), _channels[BLUE_CHANNEL].getChannelValueb( percentageQuality ), 255 ); } //converts a quality value into a color depending on the transfer function channels values, min quality, max quality, mid quality and brightness Color4b TransferFunction::getColorByQuality (float absoluteQuality, float minQuality, float maxQuality, float midRelativeQuality, float brightness) { float percentageQuality; Color4b currentColor; if (absoluteQuality < minQuality) percentageQuality = 0.0f; else if (absoluteQuality > maxQuality) percentageQuality = 1.0f; else // calcultating relative quality and applying exponential function: rel(Q)^exp, exp=2*midHandleRelPos percentageQuality = pow( (absoluteQuality - minQuality) / (maxQuality - minQuality) , (float)(2.0f*midRelativeQuality)); currentColor = getColorByQuality(percentageQuality); if (brightness!=1.0f) //Applying brightness to each color channel, 0<brightness<2, 1=normale brightness, 0=white, 2=black if (brightness<1.0f) for (int i=0; i<NUMBER_OF_CHANNELS; i++) currentColor[i] = relative2AbsoluteVali(pow(absolute2RelativeValf(currentColor[i],255.0f),brightness), 255.0f); else for (int i=0; i<NUMBER_OF_CHANNELS; i++) currentColor[i] = relative2AbsoluteVali(1.0f-pow(1.0f-absolute2RelativeValf(currentColor[i],255.0f),2-brightness), 255.0f); return currentColor; } //saves the current color band onto an external file //moreover it saves info about the equalizer state //returns the name of the file QString TransferFunction::saveColorBand( QString fn, EQUALIZER_INFO& info ) { //acquiring save file QString fileName = QFileDialog::getSaveFileName( 0, "Save Transfer Function File", fn + CSV_FILE_EXSTENSION, QString("Quality Mapper File (*") + QString(CSV_FILE_EXSTENSION) + QString(")") ); QFile outFile( fileName ); if ( !outFile.open(QIODevice::WriteOnly | QIODevice::Text)) return fileName; QTextStream outStream( &outFile ); //writing file header (info about file structure) outStream << CSV_FILE_COMMENT << " COLOR BAND FILE STRUCTURE - first row: RED CHANNEL DATA - second row GREEN CHANNEL DATA - third row: BLUE CHANNEL DATA" << endl; outStream << CSV_FILE_COMMENT << " CHANNEL DATA STRUCTURE - the channel structure is grouped in many triples. The items of each triple represent respectively: X VALUE, Y_LOWER VALUE, Y_UPPER VALUE of each node-key of the transfer function" << endl; TF_KEY *val = 0; //for each channel... for ( int i=0; i<NUMBER_OF_CHANNELS; i++) { //...for each key of the channel... for (int j=0; j<_channels[i].size(); j++) { //saving the values couple val = _channels[i][j]; assert(val != 0); outStream << val->x << CSV_FILE_SEPARATOR << val->y << CSV_FILE_SEPARATOR; } //one channel-per-row outStream << endl; } //saving equalizer info too (only one line is needed) outStream << CSV_FILE_COMMENT << "THE FOLLOWING 4 VALUES REPRESENT EQUALIZER SETTINGS - the first and the third values represent respectively the minimum and the maximum quality values used in histogram, the second one represent the position (in percentage) of the middle quality, and the last one represent the level of brightness as a floating point number (0 copletely dark, 1 original brightness, 2 completely white)" << endl; outStream << info.minQualityVal << CSV_FILE_SEPARATOR << info.midQualityPercentage << CSV_FILE_SEPARATOR << info.maxQualityVal << CSV_FILE_SEPARATOR << info.brightness << CSV_FILE_SEPARATOR << endl; outFile.close(); return fileName; } //"moving" the channel identified by ch_code to first plane. //This operation simply implies the circular shift of the channel_order pivot indexes untill the selected channel code is in the last position of the array void TransferFunction::moveChannelAhead(TF_CHANNELS ch_code) { int ch_code_int = (int)ch_code; assert( (ch_code_int>=0) && (ch_code_int<NUMBER_OF_CHANNELS) ); if ( _channels_order[NUMBER_OF_CHANNELS-1] == ch_code_int ) return ; int tmp = 0; do { tmp = _channels_order[NUMBER_OF_CHANNELS-1]; for (int i=NUMBER_OF_CHANNELS-1; i>=1; i--) //_channels_order[i] = _channels_order[i-1] % (NUMBER_OF_CHANNELS -1); _channels_order[i] = _channels_order[i-1]; _channels_order[0] = tmp; } while( _channels_order[NUMBER_OF_CHANNELS-1] != ch_code_int ); }
33.095868
431
0.676372
[ "mesh", "object" ]
4ad087ba13a08a5d35f9dfb6aaa77dcd461cb71e
13,806
cpp
C++
sqlite.cpp
Deledrius/godot-sqlite
5fdb59570e7d85b9e8d469b77e72e730766bf587
[ "MIT" ]
2
2020-04-23T01:34:38.000Z
2020-10-16T10:31:06.000Z
sqlite.cpp
Deledrius/godot-sqlite
5fdb59570e7d85b9e8d469b77e72e730766bf587
[ "MIT" ]
null
null
null
sqlite.cpp
Deledrius/godot-sqlite
5fdb59570e7d85b9e8d469b77e72e730766bf587
[ "MIT" ]
1
2020-04-23T01:36:30.000Z
2020-04-23T01:36:30.000Z
#include "sqlite.h" #include "core/core_bind.h" #include "core/os/os.h" #include "editor/project_settings_editor.h" Array fast_parse_row(sqlite3_stmt *stmt) { Array result; // Get column count const int col_count = sqlite3_column_count(stmt); // Fetch all column for (int i = 0; i < col_count; i++) { // Value const int col_type = sqlite3_column_type(stmt, i); Variant value; // Get column value switch (col_type) { case SQLITE_INTEGER: value = Variant(sqlite3_column_int(stmt, i)); break; case SQLITE_FLOAT: value = Variant(sqlite3_column_double(stmt, i)); break; case SQLITE_TEXT: { int size = sqlite3_column_bytes(stmt, i); String str = String::utf8((const char *)sqlite3_column_text(stmt, i), size); value = Variant(str); break; } case SQLITE_BLOB: { PackedByteArray arr; int size = sqlite3_column_bytes(stmt, i); arr.resize(size); memcpy(arr.ptrw(), sqlite3_column_blob(stmt, i), size); value = Variant(arr); break; } case SQLITE_NULL: { // Nothing to do. } break; default: ERR_PRINT("This kind of data is not yet supported: " + itos(col_type)); break; } result.push_back(value); } return result; } SQLiteQuery::SQLiteQuery() { } SQLiteQuery::~SQLiteQuery() { finalize(); } void SQLiteQuery::init(SQLite *p_db, const String &p_query) { db = p_db; query = p_query; stmt = nullptr; } bool SQLiteQuery::is_ready() const { return stmt != nullptr; } String SQLiteQuery::get_last_error_message() const { ERR_FAIL_COND_V(db == nullptr, "Database is undefined."); return db->get_last_error_message(); } Variant SQLiteQuery::execute(const Array p_args) { if (is_ready() == false) { ERR_FAIL_COND_V(prepare() == false, Variant()); } // At this point stmt can't be null. CRASH_COND(stmt == nullptr); // Error occurred during argument binding if (!SQLite::bind_args(stmt, p_args)) { ERR_FAIL_V_MSG(Variant(), "Error during arguments set: " + get_last_error_message()); } // Execute the query. Array result; while (true) { const int res = sqlite3_step(stmt); if (res == SQLITE_ROW) { // Collect the result. result.append(fast_parse_row(stmt)); } else if (res == SQLITE_DONE) { // Nothing more to do. break; } else { // Error ERR_BREAK_MSG(true, "There was an error during an SQL execution: " + get_last_error_message()); } } if (SQLITE_OK != sqlite3_reset(stmt)) { finalize(); ERR_FAIL_V_MSG(result, "Was not possible to reset the query: " + get_last_error_message()); } return result; } Variant SQLiteQuery::batch_execute(Array p_rows) { Array res; for (int i = 0; i < p_rows.size(); i += 1) { ERR_FAIL_COND_V_MSG(p_rows[i].get_type() != Variant::ARRAY, Variant(), "An Array of Array is exepected."); Variant r = execute(p_rows[i]); if (unlikely(r.get_type() == Variant::NIL)) { // An error occurred, the error is already logged. return Variant(); } res.push_back(r); } return res; } Array SQLiteQuery::get_columns() { if (is_ready() == false) { ERR_FAIL_COND_V(prepare() == false, Array()); } // At this point stmt can't be null. CRASH_COND(stmt == nullptr); Array res; const int col_count = sqlite3_column_count(stmt); res.resize(col_count); // Fetch all column for (int i = 0; i < col_count; i++) { // Key name const char *col_name = sqlite3_column_name(stmt, i); res[i] = String(col_name); } return res; } bool SQLiteQuery::prepare() { ERR_FAIL_COND_V(stmt != nullptr, false); ERR_FAIL_COND_V(db == nullptr, false); ERR_FAIL_COND_V(query == "", false); // Prepare the statement int result = sqlite3_prepare_v2(db->get_handler(), query.utf8().ptr(), -1, &stmt, nullptr); // Cannot prepare query! ERR_FAIL_COND_V_MSG(result != SQLITE_OK, false, "SQL Error: " + db->get_last_error_message()); return true; } void SQLiteQuery::finalize() { if (stmt) { sqlite3_finalize(stmt); stmt = nullptr; } } void SQLiteQuery::_bind_methods() { ClassDB::bind_method(D_METHOD("get_last_error_message"), &SQLiteQuery::get_last_error_message); ClassDB::bind_method(D_METHOD("execute", "arguments"), &SQLiteQuery::execute, DEFVAL(Array())); ClassDB::bind_method(D_METHOD("batch_execute", "rows"), &SQLiteQuery::batch_execute); ClassDB::bind_method(D_METHOD("get_columns"), &SQLiteQuery::get_columns); } SQLite::SQLite() { db = nullptr; memory_read = false; } /* Open a database file. If this is running outside of the editor, databases under res:// are assumed to be packed. @param path The database resource path. @return status */ bool SQLite::open(String path) { if (!path.strip_edges().length()) return false; if (!Engine::get_singleton()->is_editor_hint() && path.begins_with("res://")) { Ref<_File> dbfile; dbfile.instance(); if (dbfile->open(path, _File::READ) != Error::OK) { print_error("Cannot open packed database!"); return false; } int64_t size = dbfile->get_len(); PackedByteArray buffer = dbfile->get_buffer(size); return open_buffered(path, buffer, size); } String real_path = ProjectSettings::get_singleton()->globalize_path(path.strip_edges()); int result = sqlite3_open(real_path.utf8().get_data(), &db); if (result != SQLITE_OK) { print_error("Cannot open database!"); return false; } return true; } bool SQLite::open_in_memory() { int result = sqlite3_open(":memory:", &db); ERR_FAIL_COND_V_MSG(result != SQLITE_OK, false, "Cannot open database in memory, error:" + itos(result)); return true; } /* Open the database and initialize memory buffer. @param name Name of the database. @param buffers The database buffer. @param size Size of the database; @return status */ bool SQLite::open_buffered(String name, PackedByteArray buffers, int64_t size) { if (!name.strip_edges().length()) { return false; } if (!buffers.size() || !size) { return false; } spmembuffer_t *p_mem = (spmembuffer_t *)calloc(1, sizeof(spmembuffer_t)); p_mem->total = p_mem->used = size; p_mem->data = (char *)malloc(size + 1); memcpy(p_mem->data, buffers.ptr(), size); p_mem->data[size] = '\0'; // spmemvfs_env_init(); int err = spmemvfs_open_db(&p_db, name.utf8().get_data(), p_mem); if (err != SQLITE_OK || p_db.mem != p_mem) { print_error("Cannot open buffered database!"); return false; } memory_read = true; return true; } void SQLite::close() { // Finalize all queries before close the DB. // Reverse order because I need to remove the not available queries. for (uint32_t i = queries.size(); i > 0; i -= 1) { SQLiteQuery *query = Object::cast_to<SQLiteQuery>(queries[i - 1]->get_ref()); if (query != nullptr) { query->finalize(); } else { memdelete(queries[i - 1]); queries.remove(i - 1); } } if (db) { // Cannot close database! if (sqlite3_close_v2(db) != SQLITE_OK) { print_error("Cannot close database: " + get_last_error_message()); } else { db = nullptr; } } if (memory_read) { // Close virtual filesystem database spmemvfs_close_db(&p_db); spmemvfs_env_fini(); memory_read = false; } } sqlite3_stmt *SQLite::prepare(const char *query) { // Get database pointer sqlite3 *dbs = get_handler(); ERR_FAIL_COND_V_MSG(dbs == nullptr, nullptr, "Cannot prepare query! Database is not opened."); // Prepare the statement sqlite3_stmt *stmt = nullptr; int result = sqlite3_prepare_v2(dbs, query, -1, &stmt, nullptr); // Cannot prepare query! ERR_FAIL_COND_V_MSG(result != SQLITE_OK, nullptr, "SQL Error: " + get_last_error_message()); return stmt; } bool SQLite::bind_args(sqlite3_stmt *stmt, Array args) { // Check parameter count int param_count = sqlite3_bind_parameter_count(stmt); if (param_count != args.size()) { print_error("SQLiteQuery failed; expected " + itos(param_count) + " arguments, got " + itos(args.size())); return false; } /** * SQLite data types: * - NULL * - INTEGER (signed, max 8 bytes) * - REAL (stored as a double-precision float) * - TEXT (stored in database encoding of UTF-8, UTF-16BE or UTF-16LE) * - BLOB (1:1 storage) */ for (int i = 0; i < param_count; i++) { int retcode; switch (args[i].get_type()) { case Variant::Type::NIL: retcode = sqlite3_bind_null(stmt, i + 1); break; case Variant::Type::BOOL: case Variant::Type::INT: retcode = sqlite3_bind_int(stmt, i + 1, (int)args[i]); break; case Variant::Type::FLOAT: retcode = sqlite3_bind_double(stmt, i + 1, (double)args[i]); break; case Variant::Type::STRING: retcode = sqlite3_bind_text(stmt, i + 1, String(args[i]).utf8().get_data(), -1, SQLITE_TRANSIENT); break; case Variant::Type::PACKED_BYTE_ARRAY: retcode = sqlite3_bind_blob(stmt, i + 1, PackedByteArray(args[i]).ptr(), PackedByteArray(args[i]).size(), SQLITE_TRANSIENT); break; default: print_error("SQLite was passed unhandled Variant with TYPE_* enum " + itos(args[i].get_type()) + ". Please serialize your object into a String or a PoolByteArray.\n"); return false; } if (retcode != SQLITE_OK) { print_error("SQLiteQuery failed, an error occured while binding argument" + itos(i + 1) + " of " + itos(args.size()) + " (SQLite errcode " + itos(retcode) + ")"); return false; } } return true; } bool SQLite::query_with_args(String query, Array args) { sqlite3_stmt *stmt = prepare(query.utf8().get_data()); // Failed to prepare the query ERR_FAIL_COND_V_MSG(stmt == nullptr, false, "SQLiteQuery preparation error: " + get_last_error_message()); // Error occurred during argument binding if (!bind_args(stmt, args)) { sqlite3_finalize(stmt); ERR_FAIL_V_MSG(false, "Error during arguments bind: " + get_last_error_message()); } // Evaluate the sql query sqlite3_step(stmt); sqlite3_finalize(stmt); return true; } Ref<SQLiteQuery> SQLite::create_query(String p_query) { Ref<SQLiteQuery> query; query.instance(); query->init(this, p_query); WeakRef *wr = memnew(WeakRef); wr->set_obj(query.ptr()); queries.push_back(wr); return query; } bool SQLite::query(String query) { return this->query_with_args(query, Array()); } Array SQLite::fetch_rows(String statement, Array args, int result_type) { Array result; // Empty statement if (!statement.strip_edges().length()) { return result; } // Cannot prepare query sqlite3_stmt *stmt = prepare(statement.strip_edges().utf8().get_data()); if (!stmt) { return result; } // Bind arguments if (!bind_args(stmt, args)) { sqlite3_finalize(stmt); return result; } // Fetch rows while (sqlite3_step(stmt) == SQLITE_ROW) { // Do a step result.append(parse_row(stmt, result_type)); } // Delete prepared statement sqlite3_finalize(stmt); // Return the result return result; } Dictionary SQLite::parse_row(sqlite3_stmt *stmt, int result_type) { Dictionary result; // Get column count int col_count = sqlite3_column_count(stmt); // Fetch all column for (int i = 0; i < col_count; i++) { // Key name const char *col_name = sqlite3_column_name(stmt, i); String key = String(col_name); // Value int col_type = sqlite3_column_type(stmt, i); Variant value; // Get column value switch (col_type) { case SQLITE_INTEGER: value = Variant(sqlite3_column_int(stmt, i)); break; case SQLITE_FLOAT: value = Variant(sqlite3_column_double(stmt, i)); break; case SQLITE_TEXT: { int size = sqlite3_column_bytes(stmt, i); String str = String::utf8((const char *)sqlite3_column_text(stmt, i), size); value = Variant(str); break; } case SQLITE_BLOB: { PackedByteArray arr; int size = sqlite3_column_bytes(stmt, i); arr.resize(size); memcpy((void *)arr.ptr(), sqlite3_column_blob(stmt, i), size); value = Variant(arr); break; } default: break; } // Set dictionary value if (result_type == RESULT_NUM) result[i] = value; else if (result_type == RESULT_ASSOC) result[key] = value; else { result[i] = value; result[key] = value; } } return result; } Array SQLite::fetch_array(String query) { return fetch_rows(query, Array(), RESULT_BOTH); } Array SQLite::fetch_array_with_args(String query, Array args) { return fetch_rows(query, args, RESULT_BOTH); } Array SQLite::fetch_assoc(String query) { return fetch_rows(query, Array(), RESULT_ASSOC); } Array SQLite::fetch_assoc_with_args(String query, Array args) { return fetch_rows(query, args, RESULT_ASSOC); } String SQLite::get_last_error_message() const { return sqlite3_errmsg(get_handler()); } SQLite::~SQLite() { // Close database close(); // Make sure to invalidate all associated queries. for (uint32_t i = 0; i < queries.size(); i += 1) { SQLiteQuery *query = Object::cast_to<SQLiteQuery>(queries[i]->get_ref()); if (query != nullptr) { query->init(nullptr, ""); } } } void SQLite::_bind_methods() { ClassDB::bind_method(D_METHOD("open", "path"), &SQLite::open); ClassDB::bind_method(D_METHOD("open_in_memory"), &SQLite::open_in_memory); ClassDB::bind_method(D_METHOD("open_buffered", "path", "buffers", "size"), &SQLite::open_buffered); ClassDB::bind_method(D_METHOD("close"), &SQLite::close); ClassDB::bind_method(D_METHOD("create_query", "statement"), &SQLite::create_query); ClassDB::bind_method(D_METHOD("query", "statement"), &SQLite::query); ClassDB::bind_method(D_METHOD("query_with_args", "statement", "args"), &SQLite::query_with_args); ClassDB::bind_method(D_METHOD("fetch_array", "statement"), &SQLite::fetch_array); ClassDB::bind_method(D_METHOD("fetch_array_with_args", "statement", "args"), &SQLite::fetch_array_with_args); ClassDB::bind_method(D_METHOD("fetch_assoc", "statement"), &SQLite::fetch_assoc); ClassDB::bind_method(D_METHOD("fetch_assoc_with_args", "statement", "args"), &SQLite::fetch_assoc_with_args); }
26.098299
171
0.684268
[ "object" ]
4ad3ee3b431adde83b7f2cea4e5aac0a8fb936b9
3,219
cpp
C++
d2mapapi/piped.cpp
liuyi1/D2RMH
43f5302a61d43a1038245e11a110d7dd5db1ac8b
[ "MIT" ]
null
null
null
d2mapapi/piped.cpp
liuyi1/D2RMH
43f5302a61d43a1038245e11a110d7dd5db1ac8b
[ "MIT" ]
null
null
null
d2mapapi/piped.cpp
liuyi1/D2RMH
43f5302a61d43a1038245e11a110d7dd5db1ac8b
[ "MIT" ]
null
null
null
/* * Copyright (c) 2021 Soar Qin<soarchin@gmail.com> * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ #include "d2map.h" #include "session.h" #include <windows.h> #include <unordered_map> #include <cstdint> enum { SessionsCacheSize = 8, }; int wmain(int argc, wchar_t *argv[]) { HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE); HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE); if ((hStdout == INVALID_HANDLE_VALUE) || (hStdin == INVALID_HANDLE_VALUE)) { ExitProcess(1); } int ret = 0; const auto *errstr = argc > 1 ? d2mapapi::d2Init(argv[1]) : "Usage: d2mapapi_piped <D2 Game Path>"; if (errstr) { do { HKEY key; if (RegOpenKeyExW(HKEY_CURRENT_USER, L"SOFTWARE\\Blizzard Entertainment\\Diablo II", 0, KEY_READ, &key) == ERROR_SUCCESS) { wchar_t path[MAX_PATH]; DWORD pathSize = sizeof(path); if (RegQueryValueExW(key, L"InstallPath", nullptr, nullptr, LPBYTE(path), &pathSize) == ERROR_SUCCESS) { errstr = d2mapapi::d2Init(path); if (!errstr) { RegCloseKey(key); break; } } RegCloseKey(key); } ret = -1; DWORD written; WriteFile(hStdout, &ret, sizeof(int), &written, nullptr); auto sz = strlen(errstr); WriteFile(hStdout, &sz, sizeof(uint32_t), &written, nullptr); WriteFile(hStdout, errstr, sz, &written, nullptr); return -1; } while (false); } DWORD written; WriteFile(hStdout, &ret, sizeof(int), &written, nullptr); std::unordered_map<uint64_t, std::unique_ptr<d2mapapi::Session>> sessions; std::vector<uint64_t> sessionsOrder; for (;;) { struct Req { uint32_t seed; uint32_t difficulty; uint32_t levelId; }; Req req = {}; DWORD bytesRead; if (!ReadFile(hStdin, &req, sizeof(uint32_t) * 3, &bytesRead, nullptr)) { break; } auto key = uint64_t(req.seed) | (uint64_t(req.difficulty) << 32); auto &session = sessions[key]; sessionsOrder.emplace_back(key); if (!session) { session = std::make_unique<d2mapapi::Session>(); session->update(req.seed, req.difficulty); if (sessionsOrder.size() > SessionsCacheSize) { auto oldKey = sessionsOrder[0]; sessionsOrder.erase(sessionsOrder.begin()); sessions.erase(oldKey); } } const auto *map = session->getMap(req.levelId); std::string str; if (map) { str = map->encode(); } else { str = R"({"error":"Invalid map id!"})"; } auto sz = uint32_t(str.size()); if (!WriteFile(hStdout, &sz, sizeof(uint32_t), &written, nullptr) || !WriteFile(hStdout, str.c_str(), sz, &written, nullptr)) { break; } } return 0; }
33.185567
120
0.542094
[ "vector" ]
4ad52cb9bf2b64d420f25c26d49013430fc692b5
2,327
hpp
C++
libs/boost_1_72_0/boost/python/object_protocol_core.hpp
henrywarhurst/matrix
317a2a7c35c1c7e3730986668ad2270dc19809ef
[ "BSD-3-Clause" ]
null
null
null
libs/boost_1_72_0/boost/python/object_protocol_core.hpp
henrywarhurst/matrix
317a2a7c35c1c7e3730986668ad2270dc19809ef
[ "BSD-3-Clause" ]
null
null
null
libs/boost_1_72_0/boost/python/object_protocol_core.hpp
henrywarhurst/matrix
317a2a7c35c1c7e3730986668ad2270dc19809ef
[ "BSD-3-Clause" ]
null
null
null
// Copyright David Abrahams 2002. // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef OBJECT_PROTOCOL_CORE_DWA2002615_HPP #define OBJECT_PROTOCOL_CORE_DWA2002615_HPP #include <boost/python/detail/prefix.hpp> #include <boost/python/handle_fwd.hpp> namespace boost { namespace python { namespace api { class object; BOOST_PYTHON_DECL object getattr(object const &target, object const &key); BOOST_PYTHON_DECL object getattr(object const &target, object const &key, object const &default_); BOOST_PYTHON_DECL void setattr(object const &target, object const &key, object const &value); BOOST_PYTHON_DECL void delattr(object const &target, object const &key); // These are defined for efficiency, since attributes are commonly // accessed through literal strings. BOOST_PYTHON_DECL object getattr(object const &target, char const *key); BOOST_PYTHON_DECL object getattr(object const &target, char const *key, object const &default_); BOOST_PYTHON_DECL void setattr(object const &target, char const *key, object const &value); BOOST_PYTHON_DECL void delattr(object const &target, char const *key); BOOST_PYTHON_DECL object getitem(object const &target, object const &key); BOOST_PYTHON_DECL void setitem(object const &target, object const &key, object const &value); BOOST_PYTHON_DECL void delitem(object const &target, object const &key); BOOST_PYTHON_DECL object getslice(object const &target, handle<> const &begin, handle<> const &end); BOOST_PYTHON_DECL void setslice(object const &target, handle<> const &begin, handle<> const &end, object const &value); BOOST_PYTHON_DECL void delslice(object const &target, handle<> const &begin, handle<> const &end); } // namespace api using api::delattr; using api::getattr; using api::setattr; using api::delitem; using api::getitem; using api::setitem; using api::delslice; using api::getslice; using api::setslice; } // namespace python } // namespace boost #endif // OBJECT_PROTOCOL_CORE_DWA2002615_HPP
36.936508
78
0.699183
[ "object" ]
4adaa4592acac1969ad5511692f5d81ad607c2d2
427
hpp
C++
Main/include/GUI/HealthGauge.hpp
Kylemc1413/unnamed-sdvx-clone
1380ee50b9f5990ddcbbaed4089dec85f46b1ae8
[ "MIT" ]
2
2018-03-21T14:48:54.000Z
2018-05-28T19:28:21.000Z
Main/include/GUI/HealthGauge.hpp
Kylemc1413/unnamed-sdvx-clone
1380ee50b9f5990ddcbbaed4089dec85f46b1ae8
[ "MIT" ]
6
2018-05-28T16:57:25.000Z
2019-10-04T05:52:54.000Z
Main/include/GUI/HealthGauge.hpp
Kylemc1413/unnamed-sdvx-clone
1380ee50b9f5990ddcbbaed4089dec85f46b1ae8
[ "MIT" ]
1
2019-05-10T11:19:50.000Z
2019-05-10T11:19:50.000Z
#pragma once class HealthGauge { public: HealthGauge(); void Render(Mesh m, float deltaTime); Vector2 GetDesiredSize(); // The fill rate of the gauge float rate = 0.5f; float colorBorder = 0.7f; Color upperColor = Colori(255, 102, 255); Color lowerColor = Colori(0, 204, 255); Material fillMaterial; Material baseMaterial; Texture frontTexture; Texture fillTexture; Texture backTexture; Texture maskTexture; };
19.409091
42
0.740047
[ "mesh", "render" ]
4adbfd7192a049b9b5f3f6075ed0f4c2af1131e4
2,391
cpp
C++
tests/src/svm/test_svm_poly.cpp
codeplaysoftware/SYCL-ML
7a5d5baf4191a6eacefcbfd0628f56ff6d7bd643
[ "Apache-2.0" ]
56
2017-12-20T14:57:13.000Z
2022-02-08T06:12:23.000Z
tests/src/svm/test_svm_poly.cpp
codeplaysoftware/SYCL-ML
7a5d5baf4191a6eacefcbfd0628f56ff6d7bd643
[ "Apache-2.0" ]
4
2017-12-26T16:37:57.000Z
2020-01-06T16:54:31.000Z
tests/src/svm/test_svm_poly.cpp
codeplaysoftware/SYCL-ML
7a5d5baf4191a6eacefcbfd0628f56ff6d7bd643
[ "Apache-2.0" ]
3
2017-12-22T09:58:08.000Z
2022-01-08T02:51:08.000Z
/** * Copyright (C) Codeplay Software Limited. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <iostream> #include "ml/classifiers/svm/svm.hpp" #include "utils/utils.hpp" template <class DataT, class LabelT> void test_svm_poly() { /* * Solves the XOR problem, kernel has to be at least polynomial or more * complex. y 0 1 * x * 0 0 1 * 1 1 0 */ std::array<DataT, 8> host_data{0, 0, 0, 1, 1, 0, 1, 1}; std::vector<LabelT> host_labels{0, 1, 1, 0}; std::vector<DataT> host_alphas; DataT host_rho; { cl::sycl::queue& q = create_queue(); ml::matrix_t<DataT> sycl_data(host_data.data(), cl::sycl::range<2>(4, 2)); using KernelType = ml::svm_polynomial_kernel<DataT>; ml::svm<KernelType, LabelT> svm(1000, KernelType(1, 1, 2), 2, 1E-6); svm.train_binary(q, sycl_data, host_labels); auto smo_out = svm.get_smo_outs().front(); assert_eq(smo_out.alphas.data_range[0], 4LU); host_alphas.resize(smo_out.alphas.get_kernel_size()); auto event = ml::sycl_copy_device_to_host(q, smo_out.alphas, host_alphas.data()); event.wait_and_throw(); host_rho = smo_out.rho; sycl_data.set_final_data(nullptr); clear_eigen_device(); } /* std::cout << "alphas:\n"; ml::print(host_alphas.data(), 1, 4); std::cout << "\nrho: " << host_rho << std::endl; */ std::array<DataT, 4> expected_alphas{-3.332425, 2.665940, 2.665940, -1.999455}; assert_vec_almost_eq(host_alphas.data(), expected_alphas.data(), expected_alphas.size(), DataT(1E-3)); assert_almost_eq(host_rho, DataT(-0.999728), DataT(1E-3)); } int main() { try { test_svm_poly<float, uint8_t>(); #ifdef SYCLML_TEST_DOUBLE test_svm_poly<double, uint8_t>(); #endif } catch (cl::sycl::exception e) { std::cerr << e.what(); } return 0; }
29.8875
78
0.654538
[ "vector" ]
4ae2a16e445901935222dcd9223768865571c4d3
3,631
cpp
C++
tests/core/ScriptTestController.cpp
cybergarage/round-cc
13fb5c39e9bc14a4ad19f9a63d8d97ddda475ca1
[ "BSD-3-Clause" ]
null
null
null
tests/core/ScriptTestController.cpp
cybergarage/round-cc
13fb5c39e9bc14a4ad19f9a63d8d97ddda475ca1
[ "BSD-3-Clause" ]
null
null
null
tests/core/ScriptTestController.cpp
cybergarage/round-cc
13fb5c39e9bc14a4ad19f9a63d8d97ddda475ca1
[ "BSD-3-Clause" ]
null
null
null
/****************************************************************** * * Round for C++ * * Copyright (C) Satoshi Konno 2015 * * This is licensed under BSD-style license, see file COPYING. * ******************************************************************/ #include <boost/test/unit_test.hpp> #include <boost/lexical_cast.hpp> #include <sstream> #include <string.h> #include <round/Round.h> #include <round/core/Method.h> #include "TestNode.h" #include "TestScript.h" using namespace std; using namespace Round; void Round::Test::ScriptTestController::runEchoMethodTest(Round::ScriptManager *scriptMgr) { std::vector<std::string> params; // FIXME Script Error only of SpiderMonkey #23 // params.push_back(""); params.push_back("1"); params.push_back("\"1\""); params.push_back("\"Hello\""); params.push_back("[]"); params.push_back("[0]"); params.push_back("[0,1]"); params.push_back("[0,1,2]"); params.push_back("[\"0\"]"); params.push_back("[\"0\",\"1\"]"); params.push_back("[\"0\",\"1\",\"2\"]"); params.push_back("{}"); params.push_back("{\"key\":0}"); params.push_back("{\"key0\":0,\"key1\":1}"); params.push_back("{\"key0\":0,\"key1\":1,\"key2\":2}"); params.push_back("{\"key0\":\"value0\"}"); params.push_back("{\"key0\":\"value0\",\"key1\":\"value1\"}"); params.push_back("{\"key0\":\"value0\",\"key1\":\"value1\",\"key2\":\"value2\"}"); std::string results; Error error; for (std::vector<std::string>::iterator echoParamIt = params.begin(); echoParamIt != params.end(); echoParamIt++) { std::string &echoParam = *echoParamIt; BOOST_CHECK(scriptMgr->execMethod(Test::SCRIPT_ECHO_NAME, echoParam, &results, &error)); BOOST_CHECK_EQUAL(echoParam.compare(results), 0); } } void Round::Test::ScriptTestController::runSumMethodTest(Round::ScriptManager *scriptMgr) { std::vector<std::string> params; std::vector<std::string> results; params.push_back("[1]"); results.push_back("1"); params.push_back("[1,2]"); results.push_back("3"); params.push_back("[1,2,3]"); results.push_back("6"); params.push_back("[0,1,2,3,4,5,6,7,8,9]"); results.push_back("45"); params.push_back("[10,20,30]"); results.push_back("60"); params.push_back("[10,20]"); results.push_back("30"); params.push_back("[10,20,30]"); results.push_back("60"); params.push_back("[0,10,20,30,40,50,60,70,80,90]"); results.push_back("450"); size_t nParams = params.size(); for (size_t n = 0; n < nParams; n++) { std::string result; Error error; BOOST_CHECK(scriptMgr->execMethod(Test::SCRIPT_SUM_NAME, params[n], &result, &error)); BOOST_CHECK_EQUAL(result.compare(results[n]), 0); } } void Round::Test::ScriptTestController::runCounterMethodTest(Round::ScriptManager *scriptMgr) { std::string result; Error error; const size_t TEST_LOOP_COUNT = 10; // set_counter, get_counter for (size_t n=0; n<=TEST_LOOP_COUNT; n++) { BOOST_CHECK(scriptMgr->execMethod(Test::SCRIPT_SETCOUNTER_NAME, boost::lexical_cast<std::string>(n), &result, &error)); BOOST_CHECK(scriptMgr->execMethod(Test::SCRIPT_GETCOUNTER_NAME, "", &result, &error)); BOOST_CHECK_EQUAL(boost::lexical_cast<int>(result), n); } // set_counter, inc_counter, get_counter for (size_t n=0; n<=TEST_LOOP_COUNT; n++) { BOOST_CHECK(scriptMgr->execMethod(Test::SCRIPT_INCCOUNTER_NAME, "", &result, &error)); BOOST_CHECK(scriptMgr->execMethod(Test::SCRIPT_GETCOUNTER_NAME, "", &result, &error)); BOOST_CHECK_EQUAL(boost::lexical_cast<int>(result), (n + TEST_LOOP_COUNT + 1)); } }
29.520325
123
0.632333
[ "vector" ]
4ae42b2abfdb04684ed00e220ac41a3f4fae9205
4,013
cpp
C++
IfcPlusPlus/src/ifcpp/IFC4/IfcSpatialZoneTypeEnum.cpp
linsipese/ifcppstudy
e09f05d276b5e129fcb6be65800472979cd4c800
[ "MIT" ]
1
2018-10-23T09:43:07.000Z
2018-10-23T09:43:07.000Z
IfcPlusPlus/src/ifcpp/IFC4/IfcSpatialZoneTypeEnum.cpp
linsipese/ifcppstudy
e09f05d276b5e129fcb6be65800472979cd4c800
[ "MIT" ]
null
null
null
IfcPlusPlus/src/ifcpp/IFC4/IfcSpatialZoneTypeEnum.cpp
linsipese/ifcppstudy
e09f05d276b5e129fcb6be65800472979cd4c800
[ "MIT" ]
null
null
null
/* -*-c++-*- IfcPlusPlus - www.ifcplusplus.com - Copyright (C) 2011 Fabian Gerold * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * 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 * OpenSceneGraph Public License for more details. */ #include <sstream> #include <limits> #include <map> #include "ifcpp/reader/ReaderUtil.h" #include "ifcpp/writer/WriterUtil.h" #include "ifcpp/model/shared_ptr.h" #include "ifcpp/model/IfcPPException.h" #include "include/IfcSpatialZoneTypeEnum.h" // TYPE IfcSpatialZoneTypeEnum = ENUMERATION OF (CONSTRUCTION ,FIRESAFETY ,LIGHTING ,OCCUPANCY ,SECURITY ,THERMAL ,TRANSPORT ,VENTILATION ,USERDEFINED ,NOTDEFINED); IfcSpatialZoneTypeEnum::IfcSpatialZoneTypeEnum() {} IfcSpatialZoneTypeEnum::~IfcSpatialZoneTypeEnum() {} shared_ptr<IfcPPObject> IfcSpatialZoneTypeEnum::getDeepCopy( IfcPPCopyOptions& options ) { shared_ptr<IfcSpatialZoneTypeEnum> copy_self( new IfcSpatialZoneTypeEnum() ); copy_self->m_enum = m_enum; return copy_self; } void IfcSpatialZoneTypeEnum::getStepParameter( std::stringstream& stream, bool is_select_type ) const { if( is_select_type ) { stream << "IFCSPATIALZONETYPEENUM("; } if( m_enum == ENUM_CONSTRUCTION ) { stream << ".CONSTRUCTION."; } else if( m_enum == ENUM_FIRESAFETY ) { stream << ".FIRESAFETY."; } else if( m_enum == ENUM_LIGHTING ) { stream << ".LIGHTING."; } else if( m_enum == ENUM_OCCUPANCY ) { stream << ".OCCUPANCY."; } else if( m_enum == ENUM_SECURITY ) { stream << ".SECURITY."; } else if( m_enum == ENUM_THERMAL ) { stream << ".THERMAL."; } else if( m_enum == ENUM_TRANSPORT ) { stream << ".TRANSPORT."; } else if( m_enum == ENUM_VENTILATION ) { stream << ".VENTILATION."; } else if( m_enum == ENUM_USERDEFINED ) { stream << ".USERDEFINED."; } else if( m_enum == ENUM_NOTDEFINED ) { stream << ".NOTDEFINED."; } if( is_select_type ) { stream << ")"; } } shared_ptr<IfcSpatialZoneTypeEnum> IfcSpatialZoneTypeEnum::createObjectFromSTEP( const std::wstring& arg ) { // read TYPE if( arg.compare( L"$" ) == 0 ) { return shared_ptr<IfcSpatialZoneTypeEnum>(); } else if( arg.compare( L"*" ) == 0 ) { return shared_ptr<IfcSpatialZoneTypeEnum>(); } shared_ptr<IfcSpatialZoneTypeEnum> type_object( new IfcSpatialZoneTypeEnum() ); if( boost::iequals( arg, L".CONSTRUCTION." ) ) { type_object->m_enum = IfcSpatialZoneTypeEnum::ENUM_CONSTRUCTION; } else if( boost::iequals( arg, L".FIRESAFETY." ) ) { type_object->m_enum = IfcSpatialZoneTypeEnum::ENUM_FIRESAFETY; } else if( boost::iequals( arg, L".LIGHTING." ) ) { type_object->m_enum = IfcSpatialZoneTypeEnum::ENUM_LIGHTING; } else if( boost::iequals( arg, L".OCCUPANCY." ) ) { type_object->m_enum = IfcSpatialZoneTypeEnum::ENUM_OCCUPANCY; } else if( boost::iequals( arg, L".SECURITY." ) ) { type_object->m_enum = IfcSpatialZoneTypeEnum::ENUM_SECURITY; } else if( boost::iequals( arg, L".THERMAL." ) ) { type_object->m_enum = IfcSpatialZoneTypeEnum::ENUM_THERMAL; } else if( boost::iequals( arg, L".TRANSPORT." ) ) { type_object->m_enum = IfcSpatialZoneTypeEnum::ENUM_TRANSPORT; } else if( boost::iequals( arg, L".VENTILATION." ) ) { type_object->m_enum = IfcSpatialZoneTypeEnum::ENUM_VENTILATION; } else if( boost::iequals( arg, L".USERDEFINED." ) ) { type_object->m_enum = IfcSpatialZoneTypeEnum::ENUM_USERDEFINED; } else if( boost::iequals( arg, L".NOTDEFINED." ) ) { type_object->m_enum = IfcSpatialZoneTypeEnum::ENUM_NOTDEFINED; } return type_object; }
32.104
165
0.693745
[ "model" ]
4ae65594fc54c49cd816fa87067872afbd51b9d1
1,769
cpp
C++
codeforces/496_3/f.cpp
sidgairo18/Programming-Practice
348ad38452fa9fa7b7302161455d3b3f697734da
[ "MIT" ]
2
2018-06-26T09:52:14.000Z
2018-07-12T15:02:01.000Z
codeforces/496_3/f.cpp
sidgairo18/Programming-Practice
348ad38452fa9fa7b7302161455d3b3f697734da
[ "MIT" ]
null
null
null
codeforces/496_3/f.cpp
sidgairo18/Programming-Practice
348ad38452fa9fa7b7302161455d3b3f697734da
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main(){ int n,m,k; scanf("%d%d%d", &n, &m ,&k); vector<int> G[n]; vector<int> a(m); vector<int> b(m); vector<int> inc[n]; vector<int> f(n, 0); for(int i = 0; i<m; i++){ scanf("%d%d", &a[i], &b[i]); a[i]--, b[i]--; G[a[i]].push_back(b[i]); G[b[i]].push_back(a[i]); } vector<int> d(n, INT_MAX); vector<int> visited(n, -1); d[0] = 0; queue<int> q; q.push(0); visited[0] = 1; while(!q.empty()){ int curr = q.front(); q.pop(); int sz = G[curr].size(); for(int i = 0; i<sz; i++){ int neigh = G[curr][i]; if(visited[neigh] == 1) continue; if(d[neigh] > d[curr] +1) d[neigh] = d[curr]+1; q.push(neigh); visited[neigh] = 1; } } for(int i = 0; i<m; i++){ if(d[a[i]] + 1 == d[b[i]]) inc[b[i]].push_back(i); if(d[b[i]] + 1 == d[a[i]]) inc[a[i]].push_back(i); } vector<string> result; for(int i = 0; i<k; i++){ string s(m, '0'); for(int j = 0; j<n; j++) if(f[j] < inc[j].size()) s[inc[j][f[j]]] = '1'; int flag = 0; for(int j = 0; j<n; j++){ if(f[j] + 1 < inc[j].size()){ f[j]++; flag = 1; break; } else{ f[j] = 0; } } result.push_back(s); if(flag == 0) break; } int sz = result.size(); printf("%d\n", (int)sz); for(int i = 0; i<sz; i++) cout<<result[i]<<endl; return 0; }
16.847619
41
0.362352
[ "vector" ]
4ae6e8bdfa8bc6e9ba56da1b151b258b794b33b0
7,470
cpp
C++
CPP/GraphicComputation/class6/code/main.cpp
paulolima18/ProgrammingMesh
2b91085fa5010e73a3bc1f3d9f02c20ce46eb8df
[ "MIT" ]
3
2021-02-15T11:36:52.000Z
2021-06-27T14:21:01.000Z
CPP/GraphicComputation/class6/code/main.cpp
paulolima18/ProgrammingMesh
2b91085fa5010e73a3bc1f3d9f02c20ce46eb8df
[ "MIT" ]
null
null
null
CPP/GraphicComputation/class6/code/main.cpp
paulolima18/ProgrammingMesh
2b91085fa5010e73a3bc1f3d9f02c20ce46eb8df
[ "MIT" ]
null
null
null
#include<stdio.h> #include<stdlib.h> #define _USE_MATH_DEFINES #include <math.h> #include <vector> #include <IL/il.h> #ifdef __APPLE__ #include <GLUT/glut.h> #else #include <GL/glew.h> #include <GL/glut.h> #include <iostream> #endif using namespace std; //--------------------------------------------------------------------------- float camX = 00, camY = 0, camZ = 40, radius = 100.0f; int startX, startY, tracking = 0; int alfa = 0, beta = 45, r = 50; int alpha = 0; //--------------------------------------------------------------------------- //Image properties and pixel density array unsigned int t, tw, th; unsigned char *imageData; //Grid vertices float* gridVertices; //VBOs GLuint buffers[1]; //--------------------------------------------------------------------------- void changeSize(int w, int h) { // Prevent a divide by zero, when window is too short // (you cant make a window with zero width). if(h == 0) h = 1; // compute window's aspect ratio float ratio = w * 1.0 / h; // Reset the coordinate system before modifying glMatrixMode(GL_PROJECTION); glLoadIdentity(); // Set the viewport to be the entire window glViewport(0, 0, w, h); // Set the correct perspective gluPerspective(45,ratio,1,1000); // return to the model view matrix mode glMatrixMode(GL_MODELVIEW); } //Colocar aqui o código de desenho do terreno usando VBOs com TRIANGLE_STRIPS void drawTerrain() { for (int i = 0; i < th - 1 ; i++) { glDrawArrays(GL_TRIANGLE_STRIP, (tw) * 2 * i, (tw) * 2); } } void renderScene(void) { float pos[4] = {-1.0, 1.0, 1.0, 0.0}; glClearColor(1.0f,1.0f,1.0f,1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); gluLookAt(camX, camY, camZ, 0.0,0.0,0.0, 0.0f,1.0f,0.0f); //Desenhar o terreno glPushMatrix(); glColor3f(0.2,0.2,0.2); drawTerrain(); glPopMatrix(); // just so that it renders something before the terrain is built // to erase when the terrain is ready //glutWireTeapot(2.0); // End of frame glutSwapBuffers(); } void spherical2Cartesian() { camX = radius * cos(beta) * sin(alfa); camY = radius * sin(beta); camZ = radius * cos(beta) * cos(alfa); } void processSpecialKeys(int key, int xx, int yy) { switch (key) { case GLUT_KEY_RIGHT: alpha -= 0.1; break; case GLUT_KEY_LEFT: alpha += 0.1; break; case GLUT_KEY_UP: beta += 0.1f; if (beta > 1.5f) beta = 1.5f; break; case GLUT_KEY_DOWN: beta -= 0.1f; if (beta < -1.5f) beta = -1.5f; break; case GLUT_KEY_PAGE_DOWN: radius -= 1.0f; if (radius < 1.0f) radius = 1.0f; break; case GLUT_KEY_PAGE_UP: radius += 1.0f; break; } spherical2Cartesian(); glutPostRedisplay(); } void processKeys(unsigned char key, int xx, int yy) { switch(key) { case 'f': glPolygonMode(GL_FRONT, GL_FILL); break; case 'l': glPolygonMode(GL_FRONT, GL_LINE); break; } } void processMouseButtons(int button, int state, int xx, int yy) { if (state == GLUT_DOWN) { startX = xx; startY = yy; if (button == GLUT_LEFT_BUTTON) tracking = 1; else if (button == GLUT_RIGHT_BUTTON) tracking = 2; else tracking = 0; } else if (state == GLUT_UP) { if (tracking == 1) { alpha += (xx - startX); beta += (yy - startY); } else if (tracking == 2) { r -= yy - startY; if (r < 3) r = 3.0; } tracking = 0; } } void processMouseMotion(int xx, int yy) { int deltaX, deltaY; int alphaAux, betaAux; int rAux; if (!tracking) return; deltaX = xx - startX; deltaY = yy - startY; if (tracking == 1) { alphaAux = alpha + deltaX; betaAux = beta + deltaY; if (betaAux > 85.0) betaAux = 85.0; else if (betaAux < -85.0) betaAux = -85.0; rAux = r; } else if (tracking == 2) { alphaAux = alpha; betaAux = beta; rAux = r - deltaY; if (rAux < 3) rAux = 3; } camX = rAux * sin(alphaAux * 3.14 / 180.0) * cos(betaAux * 3.14 / 180.0); camZ = rAux * cos(alphaAux * 3.14 / 180.0) * cos(betaAux * 3.14 / 180.0); camY = rAux * sin(betaAux * 3.14 / 180.0); } void init() { //--------------------------------------------------------- //Load the height map "terreno.jpg" //Num = nr of images to load ilGenImages(1, &t); ilBindImage(t); ilLoadImage((ILstring) "terreno.jpg"); ilConvertImage(IL_LUMINANCE, IL_UNSIGNED_BYTE); tw = ilGetInteger(IL_IMAGE_WIDTH); th = ilGetInteger(IL_IMAGE_HEIGHT); //imageData = linear array with the pixel values imageData = ilGetData(); //--------------------------------------------------------- //Build the vertex arrays gridVertices = (float*) malloc(sizeof(float) * tw * th * 2 * 3); int off_x = 0, off_z = 0; float half = (float) tw / 2; for (int vert = 0; vert < (tw * th * 2 * 3);) { //---------------------------------------------------- //P0 //Px gridVertices[vert++] = -half + 0.5 + off_x; //Py gridVertices[vert++] = ((int)imageData[off_x + off_z]) - 50; //Pz gridVertices[vert++] = -half + 0.5 + off_z; //---------------------------------------------------- //P1 //Px gridVertices[vert++] = -half + 0.5 + off_x; //Py gridVertices[vert++] = ((int)imageData[off_x + off_z * tw]) - 50; //Pz gridVertices[vert++] = -half + 0.5 + off_z + 1; //---------------------------------------------------- off_x++; if (off_x == tw) { off_x = 0; off_z++; } } //--------------------------------------------------------- //OpenGL settings glEnable(GL_DEPTH_TEST); //glEnable(GL_CULL_FACE); //glEnable(GL_LINE_SMOOTH); //--------------------------------------------------------- //VBO initialization glEnableClientState(GL_VERTEX_ARRAY); glGenBuffers(1, buffers); glBindBuffer(GL_ARRAY_BUFFER,buffers[0]); glBufferData(GL_ARRAY_BUFFER, tw * th * 2 * 3 * sizeof(float), gridVertices, GL_STATIC_DRAW); glVertexPointer(3, GL_FLOAT,0,0); } int main(int argc, char **argv) { system("clear"); // init GLUT and the window glutInit(&argc, argv); glutInitDisplayMode(GLUT_DEPTH|GLUT_DOUBLE|GLUT_RGBA); glutInitWindowPosition(100,100); glutInitWindowSize(320,320); glutCreateWindow("CG@DI-UM"); // Required callback registry glutDisplayFunc(renderScene); glutIdleFunc(renderScene); glutReshapeFunc(changeSize); // Callback registration for keyboard processing glutKeyboardFunc(processKeys); glutMouseFunc(processMouseButtons); glutMotionFunc(processMouseMotion); glutSpecialFunc(processSpecialKeys); //Ver melhor glewInit(); //Init DevIL ilInit(); //load image, array pixels, ... init(); // enter GLUT's main cycle glutMainLoop(); return 0; }
21.778426
98
0.514056
[ "vector", "model" ]
4aeaf58e6f0d864f234ca08e00c1df219599480a
11,273
cpp
C++
Sources/Modules/Renderer/Settings.cpp
benkaraban/anima-games-engine
8aa7a5368933f1b82c90f24814f1447119346c3b
[ "BSD-3-Clause" ]
2
2015-04-16T01:05:53.000Z
2019-08-26T07:38:43.000Z
Sources/Modules/Renderer/Settings.cpp
benkaraban/anima-games-engine
8aa7a5368933f1b82c90f24814f1447119346c3b
[ "BSD-3-Clause" ]
null
null
null
Sources/Modules/Renderer/Settings.cpp
benkaraban/anima-games-engine
8aa7a5368933f1b82c90f24814f1447119346c3b
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2010, Anima Games, Benjamin Karaban, Laurent Schneider, * Jérémie Comarmond, Didier Colin. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * - Neither the name of the copyright holder 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. */ #include <Renderer/Settings.h> namespace Renderer { //----------------------------------------------------------------------------- FogSettings::FogSettings() : color(0.0, 0.0, 0.0, 0.0), start(0.0), end(1000.0), skyFogOpacity(0.0) { } //----------------------------------------------------------------------------- FogSettings::FogSettings(const Core::Vector4f & color, float start, float end, float skyFogOpacity) : color(color), start(start), end(end), skyFogOpacity(skyFogOpacity) { } //----------------------------------------------------------------------------- WindSettings::WindSettings() : direction(1.0, 0.0, 0.0), waveLength(1.0), period(1.0), phase(0.0), intensity(0.0) { } //----------------------------------------------------------------------------- MainLightSettings::MainLightSettings() : globalFade(1.0f), sunAngleToZenith(0.25f * f_PI_DIV_2), sunAngleToNorth(0.125f * f_PI), ambient(0.05f, 0.05f, 0.05f, 0.05f), diffuse0(0.8f, 0.8f, 0.8f, 1.0f), diffuse1(0.0f, 0.0f, 0.0f, 1.0f), diffuse2(0.2f, 0.2f, 0.4f, 1.0f), specular(0.8f, 0.8f, 0.8f, 1.0f), mulIntensity(1.0f), staticShadowBias(0.001f), staticShadowOpacity(0.6f), staticShadowDiffusion(0.05f), dynamicShadowOpacity(0.6f), dynamicShadowMiddle(12.0f), dynamicShadowMiddleBlend(2.0f), dynamicShadowEnd(50.0f), dynamicShadowEndBlend(10.0f), bloomThreshold(0.0f), bloomFactor(0.0f), occlusionContrast(0.0f), occlusionLuminosity(0.0f) { } //----------------------------------------------------------------------------- Core::Vector3f MainLightSettings::getLightDirection() const { float teta = f_PI_DIV_2 + sunAngleToNorth; float phi = sunAngleToZenith; float cosPhi, sinPhi; float cosTeta, sinTeta; Core::L_sincos(phi, &sinPhi, &cosPhi); Core::L_sincos(teta, &sinTeta, &cosTeta); float y = cosPhi; float x = sinPhi * cosTeta; float z = sinPhi * sinTeta; return Core::Vector3f(-x, -y, -z); } //----------------------------------------------------------------------------- bool MainLightSettings::operator == (const MainLightSettings & s) const { return (globalFade == s.globalFade && sunAngleToZenith == s.sunAngleToZenith && sunAngleToNorth == s.sunAngleToNorth && ambient == s.ambient && diffuse0 == s.diffuse0 && diffuse1 == s.diffuse1 && diffuse2 == s.diffuse2 && specular == s.specular && mulIntensity == s.mulIntensity && staticShadowBias == s.staticShadowBias && staticShadowOpacity == s.staticShadowOpacity && staticShadowDiffusion == s.staticShadowDiffusion && dynamicShadowOpacity == s.dynamicShadowOpacity && dynamicShadowMiddle == s.dynamicShadowMiddle && dynamicShadowMiddleBlend == s.dynamicShadowMiddleBlend && dynamicShadowEnd == s.dynamicShadowEnd && dynamicShadowEndBlend == s.dynamicShadowEndBlend && bloomThreshold == s.bloomThreshold && bloomFactor == s.bloomFactor && occlusionContrast == s.occlusionContrast && occlusionLuminosity == s.occlusionLuminosity); } //----------------------------------------------------------------------------- bool MainLightSettings::operator != (const MainLightSettings & s) const { return !(*this == s); } //----------------------------------------------------------------------------- RendererSettings::RendererSettings() { fullscreen = false; vsync = false; width = 1; height = 1; setGlobalLevel(GLOBAL_MEDIUM); } //----------------------------------------------------------------------------- RendererSettings::RendererSettings(EGlobalLevel level) { fullscreen = false; vsync = false; width = 1; height = 1; setGlobalLevel(level); } //----------------------------------------------------------------------------- bool RendererSettings::operator == (const RendererSettings & rs) const { return (shaderLevel == rs.shaderLevel && shadowLevel == rs.shadowLevel && textureLevel == rs.textureLevel && reflecLevel == rs.reflecLevel && refracLevel == rs.refracLevel && filterLevel == rs.filterLevel && msaaLevel == rs.msaaLevel && glowOn == rs.glowOn && postFXOn == rs.postFXOn && fullscreen == rs.fullscreen && width == rs.width && height == rs.height && vsync == rs.vsync); } //----------------------------------------------------------------------------- bool RendererSettings::operator != (const RendererSettings & rs) const { return !(*this == rs); } //----------------------------------------------------------------------------- DebugSettings::DebugSettings() : renderMode(RDR_NORMAL), polyMode(POLY_SOLID) { } //----------------------------------------------------------------------------- void RendererSettings::setGlobalLevel(EGlobalLevel level) { switch(level) { case GLOBAL_VERY_LOW: shaderLevel = SHADER_NONE; shadowLevel = SHADOW_NONE; textureLevel = TEXTURE_LOW; reflecLevel = REFLEC_NONE; refracLevel = REFRAC_NONE; filterLevel = FILTER_BILINEAR; msaaLevel = MSAA_NONE; glowOn = false; postFXOn = false; break; case GLOBAL_LOW: shaderLevel = SHADER_LOW; shadowLevel = SHADOW_NONE; textureLevel = TEXTURE_LOW; reflecLevel = REFLEC_LOW; refracLevel = REFRAC_LOW; filterLevel = FILTER_TRILINEAR; msaaLevel = MSAA_NONE; glowOn = true; postFXOn = true; break; case GLOBAL_MEDIUM: shaderLevel = SHADER_MEDIUM; shadowLevel = SHADOW_LOW; textureLevel = TEXTURE_MEDIUM; reflecLevel = REFLEC_MEDIUM; filterLevel = FILTER_ANISO_2X; refracLevel = REFRAC_MEDIUM; msaaLevel = MSAA_NONE; glowOn = true; postFXOn = true; break; case GLOBAL_HIGH: shaderLevel = SHADER_HIGH; shadowLevel = SHADOW_MEDIUM; textureLevel = TEXTURE_HIGH; reflecLevel = REFLEC_HIGH; refracLevel = REFRAC_MEDIUM; filterLevel = FILTER_ANISO_4X; msaaLevel = MSAA_2X; glowOn = true; postFXOn = true; break; case GLOBAL_VERY_HIGH: shaderLevel = SHADER_HIGH; shadowLevel = SHADOW_HIGH; textureLevel = TEXTURE_HIGH; reflecLevel = REFLEC_HIGH; refracLevel = REFRAC_HIGH; filterLevel = FILTER_ANISO_8X; msaaLevel = MSAA_4X; glowOn = true; postFXOn = true; break; }; } //----------------------------------------------------------------------------- SkysphereSettings::SkysphereSettings() : horizon(0.0), color(1.0, 1.0, 1.0, 1.0), glow(0.0, 0.0, 0.0, 0.0), yaw(0.0), isProcedural(false), model(LIGHTING_MODEL_CLEAR_SKY), sunColor(1.0f, 1.0f, 1.0f, 1.0f), skyColor(0.25f, 0.25f, 0.5f, 1.0f), intensity(1.0f), skyRoof(1000.0f), sphericity(1.0f), isAtInfinity(true) {}; //----------------------------------------------------------------------------- bool SkysphereSettings::operator != (const SkysphereSettings & s) const { return !(*this == s); } //----------------------------------------------------------------------------- bool SkysphereSettings::operator == (const SkysphereSettings & s) const { return (pSkyBox == s.pSkyBox && pTexture == s.pTexture && horizon == s.horizon && color == s.color && glow == s.glow && yaw == s.yaw && isProcedural == s.isProcedural && model == s.model && sunColor == s.sunColor && skyColor == s.skyColor && intensity == s.intensity && skyRoof == s.skyRoof && sphericity == s.sphericity && isAtInfinity == s.isAtInfinity); } //----------------------------------------------------------------------------- SkysphereSettings::SkysphereSettings(const Ptr<ITextureMap> & pTexture, float horizon) : pTexture(pTexture), horizon(horizon), color(1.0, 1.0, 1.0, 1.0), glow(0.0, 0.0, 0.0, 0.0), yaw(0.0), isProcedural(false), model(LIGHTING_MODEL_CLEAR_SKY), sunColor(1.0f, 1.0f, 1.0f, 1.0f), skyColor(0.25f, 0.25f, 0.5f, 1.0f), intensity(1.0f), skyRoof(200.0f), sphericity(1.0f), isAtInfinity(true) {}; //----------------------------------------------------------------------------- ConfigProfile::ConfigProfile() : textureVRAMRatio(0.5f), msaaLevel(MSAA_NONE), minWidth(0), minHeight(0) {}; //----------------------------------------------------------------------------- PostFX::PostFX() : blurDir1(0.0f, 0.0f), blurDir2(0.0f, 0.0f), radialBlurCenter(0.5f, 0.5f), radialBlurFactor(0.0f), fadeColor(Core::Vector4f::ZERO), saturation(1.0f) { } //----------------------------------------------------------------------------- }
36.482201
105
0.520536
[ "model" ]
4af024b3f1b073177b9f2e53d2630de8dbb8df19
7,266
hpp
C++
irohad/ordering/impl/batches_cache.hpp
erromu/iroha
48d62d0b522d829179ed1c08d3fcf553abc35cdf
[ "Apache-2.0" ]
null
null
null
irohad/ordering/impl/batches_cache.hpp
erromu/iroha
48d62d0b522d829179ed1c08d3fcf553abc35cdf
[ "Apache-2.0" ]
null
null
null
irohad/ordering/impl/batches_cache.hpp
erromu/iroha
48d62d0b522d829179ed1c08d3fcf553abc35cdf
[ "Apache-2.0" ]
1
2022-03-11T10:28:21.000Z
2022-03-11T10:28:21.000Z
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #ifndef IROHA_BATCHES_CACHE_HPP #define IROHA_BATCHES_CACHE_HPP #include "ordering/on_demand_ordering_service.hpp" #include <map> #include <memory> #include <numeric> #include <set> #include <shared_mutex> #include <type_traits> #include <unordered_map> #include "common/common.hpp" #include "consensus/round.hpp" #include "ordering/ordering_types.hpp" namespace shared_model::interface { class TransactionBatch; } // namespace shared_model::interface namespace iroha::ordering { /** * Contains additional information about batches. */ class BatchesContext { public: using BatchesSetType = std::set<std::shared_ptr<shared_model::interface::TransactionBatch>, shared_model::interface::BatchHashLess>; BatchesContext(BatchesContext const &) = delete; BatchesContext &operator=(BatchesContext const &) = delete; BatchesContext(); private: /// Save this value in additional field to avoid batches iteration on /// request. uint64_t tx_count_; BatchesSetType batches_; static uint64_t count(BatchesSetType const &src); public: uint64_t getTxsCount() const; BatchesSetType &getBatchesSet(); bool insert(std::shared_ptr<shared_model::interface::TransactionBatch> const &batch); bool removeBatch( std::shared_ptr<shared_model::interface::TransactionBatch> const &batch); void merge(BatchesContext &from); template <typename _Predic> void remove(_Predic &&pred) { bool process_iteration = true; for (auto it = batches_.begin(); process_iteration && it != batches_.end();) if (std::forward<_Predic>(pred)(*it, process_iteration)) { auto const erased_size = (*it)->transactions().size(); it = batches_.erase(it); assert(tx_count_ >= erased_size); tx_count_ -= erased_size; } else ++it; assert(count(batches_) == tx_count_); } }; /** * Contains information about all and used batches. Thread-safe. */ class BatchesCache { public: using BatchesSetType = BatchesContext::BatchesSetType; using TimeType = shared_model::interface::types::TimestampType; private: struct BatchInfo { std::shared_ptr<shared_model::interface::TransactionBatch> batch; shared_model::interface::types::TimestampType timestamp; BatchInfo( std::shared_ptr<shared_model::interface::TransactionBatch> const &b, shared_model::interface::types::TimestampType const &t = 0ull) : batch(b), timestamp(t) {} }; using MSTBatchesSetType = std::unordered_map<shared_model::interface::types::HashType, BatchInfo, shared_model::crypto::Hash::Hasher>; using MSTExpirationSetType = std::map<shared_model::interface::types::TimestampType, std::shared_ptr<shared_model::interface::TransactionBatch>>; struct MSTState { MSTBatchesSetType mst_pending_; MSTExpirationSetType mst_expirations_; std::tuple<size_t, size_t> batches_and_txs_counter; void operator-=( std::shared_ptr<shared_model::interface::TransactionBatch> const &batch) { assert(std::get<0>(batches_and_txs_counter) >= 1ull); assert(std::get<1>(batches_and_txs_counter) >= batch->transactions().size()); std::get<0>(batches_and_txs_counter) -= 1ull; std::get<1>(batches_and_txs_counter) -= batch->transactions().size(); } void operator+=( std::shared_ptr<shared_model::interface::TransactionBatch> const &batch) { std::get<0>(batches_and_txs_counter) += 1ull; std::get<1>(batches_and_txs_counter) += batch->transactions().size(); } template <typename Iterator, std::enable_if_t< std::is_same<Iterator, MSTBatchesSetType::iterator>::value, bool> = true> MSTBatchesSetType::iterator operator-=(Iterator const &it) { *this -= it->second.batch; mst_expirations_.erase(it->second.timestamp); return mst_pending_.erase(it); } template < typename Iterator, std::enable_if_t< std::is_same<Iterator, MSTExpirationSetType::iterator>::value, bool> = true> MSTExpirationSetType::iterator operator-=(Iterator const &it) { *this -= it->second; mst_pending_.erase(it->second->reducedHash()); return mst_expirations_.erase(it); } }; mutable std::shared_mutex batches_cache_cs_; BatchesContext batches_cache_, used_batches_cache_; std::shared_ptr<utils::ReadWriteObject<MSTState, std::mutex>> mst_state_; /** * MST functions */ void insertMSTCache( std::shared_ptr<shared_model::interface::TransactionBatch> const &batch); void removeMSTCache( std::shared_ptr<shared_model::interface::TransactionBatch> const &batch); void removeMSTCache(OnDemandOrderingService::HashesSetType const &hashes); public: BatchesCache(BatchesCache const &) = delete; BatchesCache &operator=(BatchesCache const &) = delete; BatchesCache(std::chrono::minutes const &expiration_range = std::chrono::minutes(24 * 60)); uint64_t insert( std::shared_ptr<shared_model::interface::TransactionBatch> const &batch); void remove(const OnDemandOrderingService::HashesSetType &hashes); bool isEmpty(); uint64_t txsCount() const; uint64_t availableTxsCount() const; void forCachedBatches(std::function<void(BatchesSetType &)> const &f); template <typename IsProcessedFunc> void getTransactions( size_t requested_tx_amount, std::vector<std::shared_ptr<shared_model::interface::Transaction>> &collection, BloomFilter256 &bf, IsProcessedFunc &&is_processed) { collection.clear(); collection.reserve(requested_tx_amount); bf.clear(); std::unique_lock lock(batches_cache_cs_); uint32_t depth_counter = 0ul; batches_cache_.remove([&](auto &batch, bool &process_iteration) { if (std::forward<IsProcessedFunc>(is_processed)(batch)) return true; auto const txs_count = batch->transactions().size(); if (collection.size() + txs_count > requested_tx_amount) { ++depth_counter; process_iteration = (depth_counter < 8ull); return false; } for (auto &tx : batch->transactions()) tx->storeBatchHash(batch->reducedHash()); collection.insert(std::end(collection), std::begin(batch->transactions()), std::end(batch->transactions())); bf.set(batch->reducedHash()); used_batches_cache_.insert(batch); return true; }); } void processReceivedProposal( OnDemandOrderingService::CollectionType batches); }; } // namespace iroha::ordering #endif // IROHA_BATCHES_CACHE_HPP
31.591304
80
0.645059
[ "vector" ]
4af155624e86945df059581dbe4ef0258f1352c2
7,236
cpp
C++
src/lapack_like/reflect/Householder.cpp
sg0/Elemental
614f02509690449b553451e36bc78e7e132ea517
[ "BSD-3-Clause" ]
1
2015-12-08T22:54:37.000Z
2015-12-08T22:54:37.000Z
src/lapack_like/reflect/Householder.cpp
sg0/Elemental
614f02509690449b553451e36bc78e7e132ea517
[ "BSD-3-Clause" ]
null
null
null
src/lapack_like/reflect/Householder.cpp
sg0/Elemental
614f02509690449b553451e36bc78e7e132ea517
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (C) 1992-2008 The University of Tennessee All rights reserved. Copyright (c) 2009-2015, Jack Poulson All rights reserved. This file is loosely based upon the LAPACK routines dlarfg.f and zlarfg.f. This file is part of Elemental and is under the BSD 2-Clause License, which can be found in the LICENSE file in the root directory, or at http://opensource.org/licenses/BSD-2-Clause */ #include "El.hpp" #include "./Householder/Col.hpp" #include "./Householder/Row.hpp" namespace El { // // The LAPACK convention defines tau such that // // H = I - tau [1; v] [1, v'], // // but adjoint(H) [chi; x] = [beta; 0]. // // Elemental simply uses H [chi; x] = [beta; 0]. // // On exit, chi is overwritten with beta, and x is overwritten with v. // // Another major difference from LAPACK is in the treatment of the special case // of x=0, where LAPACK would put H := I, which is not a valid Householder // reflector. We instead use the valid Householder reflector: // H [chi; 0] = [-chi; 0], // which is accomplished by setting tau=2, and v=0. // // TODO: Switch to 1/tau to be simplify discussions of UT transforms template<typename F> F LeftReflector( F& chi, Matrix<F>& x ) { DEBUG_ONLY( CallStackEntry cse("LeftReflector"); if( x.Height() != 1 && x.Width() != 1 ) LogicError("x must be a vector"); ) typedef Base<F> Real; Real norm = Nrm2( x ); F alpha = chi; if( norm == Real(0) && ImagPart(alpha) == Real(0) ) { chi = -chi; return F(2); } Real beta; if( RealPart(alpha) <= 0 ) beta = lapack::SafeNorm( alpha, norm ); else beta = -lapack::SafeNorm( alpha, norm ); // Rescale if the vector is too small const Real safeMin = lapack::MachineSafeMin<Real>(); const Real epsilon = lapack::MachineEpsilon<Real>(); const Real safeInv = safeMin/epsilon; Int count = 0; if( Abs(beta) < safeInv ) { Real invOfSafeInv = Real(1)/safeInv; do { ++count; Scale( invOfSafeInv, x ); alpha *= invOfSafeInv; beta *= invOfSafeInv; } while( Abs(beta) < safeInv ); norm = Nrm2( x ); if( RealPart(alpha) <= 0 ) beta = lapack::SafeNorm( alpha, norm ); else beta = -lapack::SafeNorm( alpha, norm ); } F tau = (beta-Conj(alpha)) / beta; Scale( Real(1)/(alpha-beta), x ); // Undo the scaling for( Int j=0; j<count; ++j ) beta *= safeInv; chi = beta; return tau; } template<typename F> F LeftReflector( Matrix<F>& chi, Matrix<F>& x ) { DEBUG_ONLY(CallStackEntry cse("LeftReflector")) F alpha = chi.Get( 0, 0 ); const F tau = LeftReflector( alpha, x ); chi.Set( 0, 0, alpha ); return tau; } template<typename F> F LeftReflector( AbstractDistMatrix<F>& chi, AbstractDistMatrix<F>& x ) { DEBUG_ONLY( CallStackEntry cse("LeftReflector"); AssertSameGrids( chi, x ); if( chi.Height() != 1 || chi.Width() != 1 ) LogicError("chi must be a scalar"); if( x.Width() != 1 ) LogicError("x must be a column vector"); if( chi.Root() != x.Root() ) LogicError("Roots must be the same"); ) F tau; if( x.CrossRank() == x.Root() ) { if( x.RowRank() == x.RowAlign() ) tau = reflector::Col( chi, x ); mpi::Broadcast( tau, x.RowAlign(), x.RowComm() ); } mpi::Broadcast( tau, x.Root(), x.CrossComm() ); return tau; } template<typename F> F LeftReflector( F& chi, AbstractDistMatrix<F>& x ) { DEBUG_ONLY( CallStackEntry cse("LeftReflector"); if( x.Width() != 1 ) LogicError("x must be a column vector"); ) F tau; if( x.CrossRank() == x.Root() ) { if( x.RowRank() == x.RowAlign() ) tau = reflector::Col( chi, x ); mpi::Broadcast( tau, x.RowAlign(), x.RowComm() ); } mpi::Broadcast( tau, x.Root(), x.CrossComm() ); return tau; } // // Defines tau and v such that // // H = I - tau [1; v] [1, v'], // // and [chi x] H = [beta 0] // template<typename F> F RightReflector( Matrix<F>& chi, Matrix<F>& x ) { DEBUG_ONLY( CallStackEntry cse("RightReflector"); if( chi.Height() != 1 || chi.Width() != 1 ) LogicError("chi must be a scalar"); if( x.Height() != 1 && x.Width() != 1 ) LogicError("x must be a vector"); ) const F tau = LeftReflector( chi, x ); // There is no need to conjugate chi, it should be real now Conjugate( x ); return tau; } template<typename F> F RightReflector( F& chi, Matrix<F>& x ) { DEBUG_ONLY( CallStackEntry cse("RightReflector"); if( x.Height() != 1 && x.Width() != 1 ) LogicError("x must be a vector"); ) const F tau = LeftReflector( chi, x ); // There is no need to conjugate chi, it should be real now Conjugate( x ); return tau; } template<typename F> F RightReflector( AbstractDistMatrix<F>& chi, AbstractDistMatrix<F>& x ) { DEBUG_ONLY( CallStackEntry cse("RightReflector"); AssertSameGrids( chi, x ); if( chi.Height() != 1 || chi.Width() != 1 ) LogicError("chi must be a scalar"); if( x.Height() != 1 ) LogicError("x must be a row vector"); if( chi.Root() != x.Root() ) LogicError("Roots must be the same"); ) F tau; if( x.CrossRank() == x.Root() ) { if( x.ColRank() == x.ColAlign() ) tau = reflector::Row( chi, x ); mpi::Broadcast( tau, x.ColAlign(), x.ColComm() ); } mpi::Broadcast( tau, x.Root(), x.CrossComm() ); return tau; } template<typename F> F RightReflector( F& chi, AbstractDistMatrix<F>& x ) { DEBUG_ONLY( CallStackEntry cse("RightReflector"); if( x.Height() != 1 ) LogicError("x must be a row vector"); ) F tau; if( x.CrossRank() == x.Root() ) { if( x.ColRank() == x.ColAlign() ) tau = reflector::Row( chi, x ); mpi::Broadcast( tau, x.ColAlign(), x.ColComm() ); } mpi::Broadcast( tau, x.Root(), x.CrossComm() ); return tau; } #define PROTO(F) \ template F LeftReflector( F& chi, Matrix<F>& x ); \ template F LeftReflector( F& chi, AbstractDistMatrix<F>& x ); \ template F LeftReflector( Matrix<F>& chi, Matrix<F>& x ); \ template F LeftReflector \ ( AbstractDistMatrix<F>& chi, AbstractDistMatrix<F>& x ); \ template F RightReflector( F& chi, Matrix<F>& x ); \ template F RightReflector( F& chi, AbstractDistMatrix<F>& x ); \ template F RightReflector( Matrix<F>& chi, Matrix<F>& x ); \ template F RightReflector \ ( AbstractDistMatrix<F>& chi, AbstractDistMatrix<F>& x ); \ template F reflector::Col( F& chi, AbstractDistMatrix<F>& x ); \ template F reflector::Col \ ( AbstractDistMatrix<F>& chi, AbstractDistMatrix<F>& x ); \ template F reflector::Row( F& chi, AbstractDistMatrix<F>& x ); \ template F reflector::Row \ ( AbstractDistMatrix<F>& chi, AbstractDistMatrix<F>& x ); #define EL_NO_INT_PROTO #include "El/macros/Instantiate.h" } // namespace El
28.046512
80
0.576562
[ "vector" ]
4af759cf10dee63ba1758f200e73175b3ef29621
22,850
cpp
C++
src/gaiarpcaux.cpp
mkaguilera/yesquel
950e499d98b4671e082244ef84d3b5f7233b0220
[ "MIT" ]
46
2016-01-30T10:34:22.000Z
2021-11-30T02:35:30.000Z
src/gaiarpcaux.cpp
mkaguilera/yesquel
950e499d98b4671e082244ef84d3b5f7233b0220
[ "MIT" ]
null
null
null
src/gaiarpcaux.cpp
mkaguilera/yesquel
950e499d98b4671e082244ef84d3b5f7233b0220
[ "MIT" ]
8
2016-05-23T00:54:52.000Z
2019-04-02T03:17:52.000Z
// // gaiarpcaux.cpp // // Data structures and marshalling/demarshalling of RPCs // /* Original code: Copyright (c) 2014 Microsoft Corporation Modified code: Copyright (c) 2015-2016 VMware, Inc All rights reserved. Written by Marcos K. Aguilera MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <stdio.h> #include <assert.h> #include <string.h> #include <stdlib.h> #include <math.h> #include <sys/uio.h> #include <map> #include <list> #include "tmalloc.h" #include "debug.h" #include "gaiarpcaux.h" #include "pendingtx.h" // -------------------------------- WRITE RPC ---------------------------------- int WriteRPCData::marshall(iovec *bufs, int maxbufs){ assert(maxbufs >= 1+niovs); bufs[0].iov_base = (char*) data; bufs[0].iov_len = sizeof(WriteRPCParm); memcpy(bufs+1, iov, sizeof(iovec) * niovs); return niovs+1; } void WriteRPCData::demarshall(char *buf){ data = (WriteRPCParm*) buf; data->buf = buf + sizeof(WriteRPCParm); // the following is not used by server, but we might fill them anyways niovs=1; iov = new iovec; iov->iov_base = data->buf; iov->iov_len = data->len; } int WriteRPCRespData::marshall(iovec *bufs, int maxbufs){ assert(maxbufs >= 1); bufs[0].iov_base = (char*) data; bufs[0].iov_len = sizeof(WriteRPCResp); return 1; } void WriteRPCRespData::demarshall(char *buf){ data = (WriteRPCResp*) buf; } // --------------------------------- READ RPC ---------------------------------- int ReadRPCData::marshall(iovec *bufs, int maxbufs){ assert(maxbufs >= 1); bufs[0].iov_base = (char*) data; bufs[0].iov_len = sizeof(ReadRPCParm); return 1; } void ReadRPCData::demarshall(char *buf){ data = (ReadRPCParm*) buf; } int ReadRPCRespData::marshall(iovec *bufs, int maxbufs){ assert(maxbufs >= 2); bufs[0].iov_base = (char*) data; bufs[0].iov_len = sizeof(ReadRPCResp); bufs[1].iov_base = data->buf; bufs[1].iov_len = data->len; return 2; } void ReadRPCRespData::demarshall(char *buf){ data = (ReadRPCResp*) buf; data->buf = buf + sizeof(ReadRPCResp); // Note: if changing this, change // clientFreeReceiveBuffer below } // static void ReadRPCRespData::clientFreeReceiveBuffer(char *data){ // extract the incoming buffer from the data buffer and free it free(data-sizeof(ReadRPCResp)); } char *ReadRPCRespData::clientAllocReceiveBuffer(int size){ char *buf; buf = (char*) malloc(size + sizeof(ReadRPCResp)); assert(buf); return buf + sizeof(ReadRPCResp); } // -------------------------------- PREPARE RPC -------------------------------- int PrepareRPCData::marshall(iovec *bufs, int maxbufs){ assert(maxbufs >= 1); int nbufs=0; bufs[nbufs].iov_base = (char*) data; bufs[nbufs].iov_len = sizeof(PrepareRPCParm); ++nbufs; if (data->piggy_buf){ bufs[nbufs].iov_base = (char*) data->piggy_buf; bufs[nbufs].iov_len = data->piggy_len; ++nbufs; } if (data->readset_len){ bufs[nbufs].iov_base = (char*) data->readset; bufs[nbufs].iov_len = data->readset_len * sizeof(COid); ++nbufs; } return nbufs; } void PrepareRPCData::demarshall(char *buf){ data = (PrepareRPCParm*) buf; data->piggy_buf = (char*)(buf + sizeof(PrepareRPCParm)); data->readset = (COid*)(data->piggy_buf + data->piggy_len); } int PrepareRPCRespData::marshall(iovec *bufs, int maxbufs){ assert(maxbufs >= 1); bufs[0].iov_base = (char*) data; bufs[0].iov_len = sizeof(PrepareRPCResp); return 1; } void PrepareRPCRespData::demarshall(char *buf){ data = (PrepareRPCResp*) buf; } // -------------------------------- COMMIT RPC --------------------------------- int CommitRPCData::marshall(iovec *bufs, int maxbufs){ assert(maxbufs >= 1); bufs[0].iov_base = (char*) data; bufs[0].iov_len = sizeof(CommitRPCParm); return 1; } void CommitRPCData::demarshall(char *buf){ data = (CommitRPCParm*) buf; } int CommitRPCRespData::marshall(iovec *bufs, int maxbufs){ assert(maxbufs >= 1); bufs[0].iov_base = (char*) data; bufs[0].iov_len = sizeof(CommitRPCResp); return 1; } void CommitRPCRespData::demarshall(char *buf){ data = (CommitRPCResp*) buf; } // ------------------------------- SUBTRANS RPC -------------------------------- int SubtransRPCData::marshall(iovec *bufs, int maxbufs){ assert(maxbufs >= 1); bufs[0].iov_base = (char*) data; bufs[0].iov_len = sizeof(SubtransRPCParm); return 1; } void SubtransRPCData::demarshall(char *buf){ data = (SubtransRPCParm*) buf; } int SubtransRPCRespData::marshall(iovec *bufs, int maxbufs){ assert(maxbufs >= 1); bufs[0].iov_base = (char*) data; bufs[0].iov_len = sizeof(SubtransRPCResp); return 1; } void SubtransRPCRespData::demarshall(char *buf){ data = (SubtransRPCResp*) buf; } // ------------stuff for marshalling/demarshalling RcKeyInfo objects ----------- // converts a CollSeq into a byte static u8 EncodeCollSeqAsByte(CollSeq *cs){ if (strcmp(cs->zName, "BINARY")==0){ switch(cs->enc){ case SQLITE_UTF8: return 1; case SQLITE_UTF16BE: return 2; case SQLITE_UTF16LE: return 3; default: assert(0); } } if (strcmp(cs->zName, "RTRIM")==0){ if (cs->enc == SQLITE_UTF8) return 4; else assert(0); } if (strcmp(cs->zName, "NOCASE")==0){ if (cs->enc == SQLITE_UTF8) return 5; else assert(0); } assert(0); return 1; } // do the reverse conversion static CollSeq *DecodeByteAsCollSeq(u8 b){ static CollSeq CollSeqs[] = {{(char*)"BINARY", SQLITE_UTF8, SQLITE_COLL_BINARY, 0, binCollFunc, 0}, {(char*)"BINARY", SQLITE_UTF16BE, SQLITE_COLL_BINARY, 0, binCollFunc, 0}, {(char*)"BINARY", SQLITE_UTF16LE, SQLITE_COLL_BINARY, 0, binCollFunc, 0}, {(char*)"RTRIM", SQLITE_UTF8, SQLITE_COLL_USER, (void*)1, binCollFunc, 0}, {(char*)"NOCASE", SQLITE_UTF8, SQLITE_COLL_NOCASE, 0, nocaseCollatingFunc, 0}}; assert(1 <= b && b <= 5); return &CollSeqs[b-1]; } struct RcKeyInfoSerialize { u8 enc; u8 nsortorder; // number of sort order values u8 ncoll; // number of collating sequence values // must have nsortorder==0 or nsortorder == ncoll }; // serialize a RcKeyInfo object. // Returns the number of iovecs used, and sets *retbuf to a newly allocated // buffer (using malloc) that the caller should later free() after the // serialized data is no longer needed. // The RcKeyInfo is serialized as follows: // [haskey] whether there is a key. If 0, this indicates a null RcKeyInfo // object and the serialization ends here. // [KeyInfoSerialize struct] // [sortorder byte array with KeyInfoSerialize.nsortorder entries, possibly 0] // [coll byte array with KeyInfoSerialize.ncoll entries, possibly 0] // The ncoll byte array has a byte per collating sequence value. The map is // obtained from EncodeCollSeqAsByte(). int marshall_keyinfo(Ptr<RcKeyInfo> prki, iovec *bufs, int maxbufs, char **retbuf){ RcKeyInfoSerialize *kis; char *buf; char *ptr; int i; assert(maxbufs >= 1); if (!prki.isset()){ // null prki buf = (char*) malloc(sizeof(int)); assert(buf); *(int*)buf = 0; bufs[0].iov_base = buf; bufs[0].iov_len = sizeof(int); *retbuf = buf; return 1; // 1 iovec used } // nField*2 reserves space for aSortOrder and aColl. This is conservative, // since aSortOrder may be null (meaning it needs no space) ptr = buf = (char*) malloc(sizeof(int) + sizeof(RcKeyInfoSerialize) + prki->nField*2); assert(ptr); *(int*)ptr = 1; ptr += sizeof(int); // marshall KeyInfoSerialize part kis = (RcKeyInfoSerialize*) ptr; kis->enc = prki->enc; // if aSortOrder is non-null, nField indicates its size kis->nsortorder = prki->aSortOrder ? prki->nField : 0; kis->ncoll = (u8)prki->nField; // append entries in aSortOrder (if it is non-null) ptr += sizeof(RcKeyInfoSerialize); // marshall nsortorder if (kis->nsortorder){ assert(kis->nsortorder <= prki->nField); memcpy(ptr, prki->aSortOrder, kis->nsortorder); ptr += kis->nsortorder; } // marshall collating sequences for (i=0; i < prki->nField; ++i) ptr[i] = EncodeCollSeqAsByte(prki->aColl[i]); ptr += prki->nField; // add entry to iovecs bufs[0].iov_base = buf; bufs[0].iov_len = (int)(ptr - buf); *retbuf = buf; return 1; // only 1 iovec used } static int Ioveclen(iovec *bufs, int nbufs){ int len=0; for (int i=0; i < nbufs; ++i){ len += bufs[i].iov_len; } return len; } static void Iovecmemcpy(char *dest, iovec *bufs, int nbufs){ for (int i=0; i < nbufs; ++i){ memcpy((void*) dest, (void*) bufs[i].iov_base, bufs[i].iov_len); dest += bufs[i].iov_len; } } // marshalls a keyinfo into a single buffer, which is returned. // Caller should later free buffer with free() char *marshall_keyinfo_onebuf(Ptr<RcKeyInfo> prki, int &retlen){ iovec bufs[10]; int nbuf; int len; char *tmpbuf, *retval; nbuf = marshall_keyinfo(prki, bufs, sizeof(bufs)/sizeof(iovec), &tmpbuf); len = Ioveclen(bufs, nbuf); retval = (char*) malloc(len); Iovecmemcpy(retval, bufs, nbuf); free(tmpbuf); retlen = len; return retval; } // Demarshall a RcKeyInfo object. *buf is a pointer to the serialized buffer. // Returns a pointer to the demarshalled object, and modifies *buf to point // after the demarshalled buffer. Ptr<RcKeyInfo> demarshall_keyinfo(char **buf){ char *ptr; Ptr<RcKeyInfo> prki; RcKeyInfoSerialize *kis; int i; CollSeq **collseqs; int haskeyinfo; ptr = *buf; haskeyinfo = *(int*)ptr; ptr += sizeof(int); if (!haskeyinfo){ // null RcKeyInfo *buf = ptr; Ptr<RcKeyInfo> empty; return empty; } kis = (RcKeyInfoSerialize*) ptr; prki = new(kis->ncoll, kis->nsortorder) RcKeyInfo; assert(prki.isset()); // fill out KeyInfo fields stored in KeyInfoSerialize prki->db = 0; prki->enc = kis->enc; prki->nField = kis->ncoll; ptr += sizeof(RcKeyInfoSerialize); // fill out aSortOrder if present if (kis->nsortorder){ // copy sortorder array // where to copy: after RcKeyInfo and its array of CollSeq pointers char *copydest = (char*)&*prki + sizeof(RcKeyInfo) + kis->ncoll*sizeof(CollSeq*); memcpy(copydest, ptr, kis->nsortorder); prki->aSortOrder = (u8*) copydest; // point to where we copied ptr += kis->nsortorder; } else prki->aSortOrder = 0; // fill out collseq pointers collseqs = &prki->aColl[0]; for (i=0; i < kis->ncoll; ++i) collseqs[i] = DecodeByteAsCollSeq(ptr[i]); ptr += kis->ncoll; *buf = ptr; return prki; } // -------------------------------- LISTADD RPC -------------------------------- int ListAddRPCData::marshall(iovec *bufs, int maxbufs){ int nbufs=0; bufs[0].iov_base = (char*) data; bufs[0].iov_len = sizeof(ListAddRPCParm); ++nbufs; // nbufs==1 // serialize RcKeyInfo if (serializeKeyinfoBuf) free(serializeKeyinfoBuf); nbufs += marshall_keyinfo(data->prki, bufs+1, maxbufs-1, &serializeKeyinfoBuf); // serialize the data in pKey (if any) if (data->cell.pKey){ bufs[nbufs].iov_base = data->cell.pKey; bufs[nbufs].iov_len = (unsigned) data->cell.nKey; ++nbufs; } return nbufs; } void ListAddRPCData::demarshall(char *buf){ char *ptr; data = (ListAddRPCParm*) buf; ptr = buf + sizeof(ListAddRPCParm); // demarshall RcKeyInfo data->prki.init(); data->prki = demarshall_keyinfo(&ptr); // deserialize the data in pKey (if any) if (data->cell.pKey) // reading pointer from another machine; we only care // if it is zero or not; zero indicates no pKey data // (key is integer), non-zero indicates data { data->cell.pKey = ptr; // actual data is at the end ptr += data->cell.nKey; } } int ListAddRPCRespData::marshall(iovec *bufs, int maxbufs){ assert(maxbufs >= 1); bufs[0].iov_base = (char*) data; bufs[0].iov_len = sizeof(ListAddRPCResp); return 1; } void ListAddRPCRespData::demarshall(char *buf){ data = (ListAddRPCResp*) buf; } // ----------------------------- LISTDELRANGE RPC ------------------------------ int ListDelRangeRPCData::marshall(iovec *bufs, int maxbufs){ int nbufs=0; bufs[0].iov_base = (char*) data; bufs[0].iov_len = sizeof(ListDelRangeRPCParm); ++nbufs; // nbufs==1 // serialize RcKeyInfo if (serializeKeyinfoBuf) free(serializeKeyinfoBuf); nbufs += marshall_keyinfo(data->prki, bufs+1, maxbufs-1, &serializeKeyinfoBuf); // serialize the data in pKey1 (if any) if (data->cell1.pKey){ bufs[nbufs].iov_base = data->cell1.pKey; bufs[nbufs].iov_len = (unsigned) data->cell1.nKey; ++nbufs; } if (data->cell2.pKey){ bufs[nbufs].iov_base = data->cell2.pKey; bufs[nbufs].iov_len = (unsigned) data->cell2.nKey; ++nbufs; } return nbufs; } void ListDelRangeRPCData::demarshall(char *buf){ char *ptr; data = (ListDelRangeRPCParm*) buf; ptr = buf + sizeof(ListDelRangeRPCParm); // demarshall RcKeyInfo data->prki.init(); data->prki = demarshall_keyinfo(&ptr); // deserialize the data in pKey1 (if any) if (data->cell1.pKey){ data->cell1.pKey = ptr; ptr += data->cell1.nKey; } // deserialize the data in pKey2 (if any) if (data->cell2.pKey){ data->cell2.pKey = ptr; ptr += data->cell2.nKey; } } int ListDelRangeRPCRespData::marshall(iovec *bufs, int maxbufs){ assert(maxbufs >= 1); bufs[0].iov_base = (char*) data; bufs[0].iov_len = sizeof(ListDelRangeRPCResp); return 1; } void ListDelRangeRPCRespData::demarshall(char *buf){ data = (ListDelRangeRPCResp*) buf; } // -------------------------------- ATTRSET RPC -------------------------------- int AttrSetRPCData::marshall(iovec *bufs, int maxbufs){ assert(maxbufs >= 1); bufs[0].iov_base = (char*) data; bufs[0].iov_len = sizeof(AttrSetRPCParm); return 1; } void AttrSetRPCData::demarshall(char *buf){ data = (AttrSetRPCParm*) buf; } int AttrSetRPCRespData::marshall(iovec *bufs, int maxbufs){ assert(maxbufs >= 1); bufs[0].iov_base = (char*) data; bufs[0].iov_len = sizeof(AttrSetRPCResp); return 1; } void AttrSetRPCRespData::demarshall(char *buf){ data = (AttrSetRPCResp*) buf; } // -------------------------------- ATTRGET RPC -------------------------------- int AttrGetRPCData::marshall(iovec *bufs, int maxbufs){ assert(maxbufs >= 1); bufs[0].iov_base = (char*) data; bufs[0].iov_len = sizeof(AttrGetRPCParm); return 1; } void AttrGetRPCData::demarshall(char *buf){ data = (AttrGetRPCParm*) buf; } int AttrGetRPCRespData::marshall(iovec *bufs, int maxbufs){ assert(maxbufs >= 1); bufs[0].iov_base = (char*) data; bufs[0].iov_len = sizeof(AttrGetRPCResp); return 1; } void AttrGetRPCRespData::demarshall(char *buf){ data = (AttrGetRPCResp*) buf; } // ------------------------------- FULLREAD RPC -------------------------------- int FullReadRPCData::marshall(iovec *bufs, int maxbufs){ int nbufs=0; bufs[0].iov_base = (char*) data; bufs[0].iov_len = sizeof(FullReadRPCParm); ++nbufs; // nbufs==1 // serialize RcKeyInfo if (serializeKeyinfoBuf) free(serializeKeyinfoBuf); nbufs += marshall_keyinfo(data->prki, bufs+1, maxbufs-1, &serializeKeyinfoBuf); assert(nbufs < maxbufs); // serialize the data in pKey (if any) if (data->cell.pKey){ bufs[nbufs].iov_base = data->cell.pKey; bufs[nbufs].iov_len = (unsigned) data->cell.nKey; ++nbufs; } return nbufs; } void FullReadRPCData::demarshall(char *buf){ char *ptr; data = (FullReadRPCParm*) buf; ptr = buf + sizeof(FullReadRPCParm); // demarshall RcKeyInfo data->prki.init(); data->prki = demarshall_keyinfo(&ptr); // deserialize the data in pKey (if any) if (data->cell.pKey) // reading pointer from another machine; we only care if // it is zero or not; zero indicates no pKey data (key // is integer), non-zero indicates data { data->cell.pKey = ptr; // actual data is at the end ptr += data->cell.nKey; } } FullReadRPCRespData::~FullReadRPCRespData(){ if (deletecelloids) delete [] deletecelloids; if (freedata && data) delete data; if (twsvi) delete twsvi; if (tmpprkiserializebuf) free(tmpprkiserializebuf); } int FullReadRPCRespData::marshall(iovec *bufs, int maxbufs){ assert(maxbufs >= 3); int nbufs=0; char *tofree; bufs[nbufs].iov_base = (char*) data; bufs[nbufs++].iov_len = sizeof(FullReadRPCResp); bufs[nbufs].iov_base = (char*) data->attrs; bufs[nbufs++].iov_len = sizeof(u64) * data->nattrs; bufs[nbufs].iov_base = (char*) data->celloids; bufs[nbufs++].iov_len = data->lencelloids; nbufs += marshall_keyinfo(data->prki, bufs+nbufs, maxbufs-nbufs, &tofree); if (tmpprkiserializebuf) free(tmpprkiserializebuf); tmpprkiserializebuf = tofree; return nbufs; } void FullReadRPCRespData::demarshall(char *buf){ data = (FullReadRPCResp*) buf; buf += sizeof(FullReadRPCResp); data->attrs = (u64*) buf; // attrs follows buffer buf += data->nattrs * sizeof(u64); data->celloids = buf; // celloids follows attrs buf += data->lencelloids; data->prki.init(); data->prki = demarshall_keyinfo(&buf); } // ------------------------------- FULLWRITE RPC ------------------------------- // converts serialized celloids into items put inside skiplist of cells void CelloidsToListCells(char *celloids, int ncelloids, int celltype, SkipListBK<ListCellPlus,int> &cells, Ptr<RcKeyInfo> *pprki){ char *ptr = celloids; ListCellPlus *lc; for (int i=0; i < ncelloids; ++i){ lc = new ListCellPlus(pprki); // extract nkey u64 nkey; ptr += myGetVarint((unsigned char*) ptr, &nkey); lc->nKey = nkey; if (celltype == 0) lc->pKey = 0; // integer cell, set pKey=0 else { // non-integer key, so extract pKey (nkey has its length) lc->pKey = new char[(unsigned) nkey]; memcpy(lc->pKey, ptr, (size_t)nkey); ptr += nkey; } // extract childOid lc->value = *(Oid*)ptr; ptr += sizeof(u64); // space for 64-bit value in cell // add ListCell to cells cells.insert(lc,0); } } int CellSize(ListCellPlus *lc){ int len = myVarintLen(lc->nKey); if (lc->pKey == 0) ; // integer key (no pkey) else len += (int) lc->nKey; // space for pkey len += sizeof(u64); // spave for 64-bit value in cell return len; } int ListCellsSize(SkipListBK<ListCellPlus,int> &cells){ SkipListNodeBK<ListCellPlus,int> *ptr; int len = 0; // iterate to calculate length for (ptr = cells.getFirst(); ptr != cells.getLast(); ptr = cells.getNext(ptr)){ len += CellSize(ptr->key); } return len; } // converts a skiplist of cells into a buffer with celloids. // Returns: // - a pointer to an allocated buffer (allocated with new), // - the number of celloids in variable ncelloids // - the length of the buffer in variable lencelloids char *ListCellsToCelloids(SkipListBK<ListCellPlus,int> &cells, int &ncelloids, int &lencelloids){ SkipListNodeBK<ListCellPlus,int> *ptr; int len; char *buf, *p; int ncells=0; // first find length of listcells to determine length of buffer to allocate len = ListCellsSize(cells); ncells = cells.getNitems(); p = buf = new char[len]; // now iterate to serialize for (ptr = cells.getFirst(); ptr != cells.getLast(); ptr = cells.getNext(ptr)){ p += myPutVarint((unsigned char *)p, ptr->key->nKey); if (ptr->key->pKey == 0) ; // integer key else { memcpy(p, ptr->key->pKey, (int)ptr->key->nKey); p += ptr->key->nKey; } memcpy(p, &ptr->key->value, sizeof(u64)); p += sizeof(u64); } assert(p-buf == len); lencelloids = len; ncelloids = ncells; return buf; } TxWriteSVItem *fullWriteRPCParmToTxWriteSVItem(FullWriteRPCParm *data){ TxWriteSVItem *twsvi; COid coid; coid.cid = data->cid; coid.oid = data->oid; twsvi = new TxWriteSVItem(coid, data->level); twsvi->nattrs = GAIA_MAX_ATTRS; twsvi->celltype = data->celltype; //twsvi->ncelloids = data->ncelloids; twsvi->attrs = new u64[GAIA_MAX_ATTRS]; assert(twsvi->nattrs <= GAIA_MAX_ATTRS); memcpy(twsvi->attrs, data->attrs, data->nattrs * sizeof(u64)); // fill any missing attributes with 0 memset(twsvi->attrs + data->nattrs, 0, (GAIA_MAX_ATTRS-data->nattrs) * sizeof(u64)); twsvi->prki = data->prki; CelloidsToListCells(data->celloids, data->ncelloids, data->celltype, twsvi->cells, &twsvi->prki); return twsvi; } int FullWriteRPCData::marshall(iovec *bufs, int maxbufs){ assert(maxbufs >= 1); int nbufs=0; bufs[nbufs].iov_base = (char*) data; bufs[nbufs++].iov_len = sizeof(FullWriteRPCParm); bufs[nbufs].iov_base = (char*) data->attrs; bufs[nbufs++].iov_len = sizeof(u64) * data->nattrs; bufs[nbufs].iov_base = (char*) data->celloids; bufs[nbufs++].iov_len = data->lencelloids; if (serializeKeyinfoBuf) free(serializeKeyinfoBuf); nbufs += marshall_keyinfo(data->prki, bufs+nbufs, maxbufs-nbufs, &serializeKeyinfoBuf); return nbufs; } void FullWriteRPCData::demarshall(char *buf){ char *ptr = buf; data = (FullWriteRPCParm*) ptr; ptr += sizeof(FullWriteRPCParm); data->attrs = (u64*) ptr; // attrs follows buffer ptr += data->nattrs * sizeof(u64); data->celloids = ptr; // celloids follows attrs ptr += data->lencelloids; data->prki.init(); data->prki = demarshall_keyinfo(&ptr); } int FullWriteRPCRespData::marshall(iovec *bufs, int maxbufs){ assert(maxbufs >= 1); bufs[0].iov_base = (char*) data; bufs[0].iov_len = sizeof(FullWriteRPCResp); return 1; } void FullWriteRPCRespData::demarshall(char *buf){ data = (FullWriteRPCResp*) buf; }
28.924051
80
0.643195
[ "object" ]
4affc4852233bbac42a9294b55a5ac5d9d191ab8
4,106
hpp
C++
wsi.hpp
frankyeh/WSRecognizer
40f1715d01cb8484ce802a614f55e87c93b0051e
[ "BSD-3-Clause" ]
1
2018-02-05T17:06:48.000Z
2018-02-05T17:06:48.000Z
wsi.hpp
frankyeh/WSRecognizer
40f1715d01cb8484ce802a614f55e87c93b0051e
[ "BSD-3-Clause" ]
null
null
null
wsi.hpp
frankyeh/WSRecognizer
40f1715d01cb8484ce802a614f55e87c93b0051e
[ "BSD-3-Clause" ]
null
null
null
#ifndef WSI_HPP #define WSI_HPP #include "tipl/tipl.hpp" #include <string> #include "train_model.hpp" typedef struct _openslide openslide_t; const unsigned int tma_feature_count = 3; const char tma_feature_list[tma_feature_count][10] = {"count","area","intensity"}; class wsi { public: openslide_t* handle; std::string file_name; tipl::geometry<2> dim; float pixel_size; // in micron; unsigned int level; public: tipl::color_image rawI; public: bool intensity_normalization = false; float intensity_norm_value = 0; public: bool is_tma; tipl::image<int,2> tma_map; tipl::image<int,2> tma_array; public: std::vector<std::vector<float> > tma_results; public: tipl::color_image map_image; tipl::grayscale_image intensity_map; tipl::grayscale_image map_mask; public: std::vector<std::string> property_name; std::vector<std::string> property_value; public: std::vector<std::string> associated_image_name; std::vector<tipl::image<tipl::rgb,2> > associated_image; public: wsi(); ~wsi(); bool open(const char* file_name); void process_mask(void); public: bool read(openslide_t*& cur_handle,tipl::color_image& main_image,int x,int y,unsigned int level); bool read(tipl::color_image& main_image,int x,int y,unsigned int level) { return read(handle,main_image,x,y,level); } private: std::vector<tipl::geometry<2> > dim_at_level; std::vector<double> r_at_level; public: double get_r(int level) const { if(level < 0) return get_r(level+1)*0.5; return r_at_level[level]; } int get_height(int level) const { if(level < 0) return get_height(level+1)*2; return dim_at_level[level][1]; } int get_width(int level) const { if(level < 0) return get_width(level+1)*2; return dim_at_level[level][0]; } float get_pixel_size(int level) const { return pixel_size*get_r(level); } template<typename value_type> void map_coordinate_to_level(value_type& x,value_type& y,int level) { x = (float)x/(float)map_image.width()*(float)dim_at_level[level][0]; y = (float)y/(float)map_image.height()*(float)dim_at_level[level][1]; } template<typename value_type> void level_coordinate_to_map(value_type& x,value_type& y,int level) { x = (float)x*(float)map_image.width()/(float)dim_at_level[level][0]; y = (float)y*(float)map_image.height()/(float)dim_at_level[level][1]; } public: std::mutex add_data_mutex; bool is_adding_mutex; train_model ml; std::vector<std::vector<float> > output; unsigned int progress; bool finished; void push_result(std::vector<std::vector<float> >& features); void run(bool* terminated,unsigned int thread_count = std::thread::hardware_concurrency()); void save_recognition_result(const char* file_name); void save_tma_result(const char* file_name,bool label_on_right); bool load_recognition_result(const char* file_name); bool load_text_reco_result(const char* file_name); void get_distribution_image(tipl::image<float,2>& feature_mapping, tipl::image<unsigned char,2>& contour, float resolution_mm,float band_width_mm,bool feature); bool get_picture(tipl::color_image& I,int x,int y,unsigned int dim); bool get_picture(std::vector<float>& I,int x,int y,unsigned int dim); public: // color profile tipl::vector<3> color1_v,color2_v; tipl::matrix<3,3,float> color_m,color_m_inv; // [v0 v1 v2] tipl::rgb color1,color2; int color1_code,color2_code; void read_profile(const tipl::color_image& I); public: bool stain_scale = false; tipl::matrix<3,3,float> stain_scale_transform; void set_stain_scale(float stain1_scale,float stain2_scale); public: // report std::string report; float mean_value; float max_value; float q1_value,q3_value; public: static bool can_open(const char* file_name); }; #endif // WSI_HPP
31.584615
101
0.677302
[ "geometry", "vector" ]
ab0044e2c2c8c3d526a4dd489bc30ccaadb33af3
1,391
cpp
C++
View/SDL/Viewer.cpp
Sander-Zeeman/MyPhysicsEngine
7f2a54d1bd4a6655dfd9de73f889aaec3448e53d
[ "MIT" ]
null
null
null
View/SDL/Viewer.cpp
Sander-Zeeman/MyPhysicsEngine
7f2a54d1bd4a6655dfd9de73f889aaec3448e53d
[ "MIT" ]
null
null
null
View/SDL/Viewer.cpp
Sander-Zeeman/MyPhysicsEngine
7f2a54d1bd4a6655dfd9de73f889aaec3448e53d
[ "MIT" ]
null
null
null
#include "Viewer.h" Viewer::Viewer(uint32_t width, uint32_t height) : m_width(width) , m_height(height) { if (SDL_CreateWindowAndRenderer( m_width, m_height, SDL_WINDOW_RESIZABLE, &window, &renderer ) < 0) { SDL_Log("SDL could not create a window/renderer!: %s", SDL_GetError()); exit(1); }; SDL_SetWindowTitle(window, "PhysicsEngine"); } Viewer::~Viewer() { SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); } void Viewer::resize(uint32_t n_width, uint32_t n_height) { m_width = n_width; m_height = n_height; } void Viewer::draw_square(Square s) { SDL_Rect rect = { static_cast<int32_t>(s.x()), static_cast<int32_t>(s.y()), static_cast<int32_t>(s.w()), static_cast<int32_t>(s.h()), }; SDL_RenderFillRect(renderer, &rect); } void Viewer::draw(World & world) { SDL_SetRenderDrawColor(renderer, 0x00, 0xAA, 0x55, 0xFF); SDL_RenderClear(renderer); SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF); for (Object *o : world.objects()) { assert(e_SIZE == 1); switch(o->type()) { case e_SQUARE: draw_square(*static_cast<Square*>(o)); break; default: assert(false); } } SDL_RenderPresent(renderer); }
21.4
79
0.585909
[ "object" ]
ab0692d2ca8e735a804bfd4da68ba1f90f82ef01
4,110
cpp
C++
src/lib/server/SourcesControllerCommands.cpp
gerickson/openhlx
f23a825ca56ee226db393da14d81a7d4e9ae0b33
[ "Apache-2.0" ]
1
2021-05-21T21:10:09.000Z
2021-05-21T21:10:09.000Z
src/lib/server/SourcesControllerCommands.cpp
gerickson/openhlx
f23a825ca56ee226db393da14d81a7d4e9ae0b33
[ "Apache-2.0" ]
12
2021-06-12T16:42:30.000Z
2022-02-01T18:44:42.000Z
src/lib/server/SourcesControllerCommands.cpp
gerickson/openhlx
f23a825ca56ee226db393da14d81a7d4e9ae0b33
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2020-2021 Grant Erickson * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS * IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language * governing permissions and limitations under the License. * */ /** * @file * This file implements objects for HLX server source data * model commands and their constituent requests and responses. * */ #include "SourcesControllerCommands.hpp" #include <OpenHLX/Utilities/Assert.hpp> using namespace HLX::Common; using namespace HLX::Model; namespace HLX { namespace Server { namespace Command { namespace Sources { static const char * const kSourceObject = "I"; // MARK: Mutator Requests, Responses, and Commands // MARK: Name Mutator Requests, Responses, and Commands /** * @brief * This is the class default initializer. * * This initializes the set name command request regular expression. * * @retval kStatus_Success If successful. * */ Status SetNameRequest :: Init(void) { return (NameRegularExpressionBasis::Init(*this)); } /** * @brief * This is the class initializer. * * This initializes the source name command response buffer. * * @param[in] aSourceIdentifier An immutable reference * for the source identifier * for which to form the name * response. * @param[in] aName A pointer to the null- * terminated C string of the * source name for * which to form the * response. * * @retval kStatus_Success If successful. * @retval -ENOMEM If memory could not be allocated. * @retval kError_InitializationFailed If initialization otherwise failed. * */ Status NameResponse :: Init(const Model::SourceModel::IdentifierType &aSourceIdentifier, const char * aName) { return (NameSetResponseBasis::Init(kSourceObject, aSourceIdentifier, aName)); } /** * @brief * This is the class initializer. * * This initializes the source name command response buffer. * * @param[in] aSourceIdentifier An immutable reference * for the source * identifier for which to * form the name response. * @param[in] aName A pointer to the null- * terminated C string of the * source name for * which to form the * response. * @param[in] aNameLength An immutable reference to * the length, in bytes, of * @a aName. * * @retval kStatus_Success If successful. * @retval -ENOMEM If memory could not be allocated. * @retval kError_InitializationFailed If initialization otherwise failed. * */ Status NameResponse :: Init(const Model::SourceModel::IdentifierType &aSourceIdentifier, const char * aName, const size_t &aNameLength) { return (NameSetResponseBasis::Init(kSourceObject, aSourceIdentifier, aName, aNameLength)); } }; // namespace Sources }; // namespace Command }; // namespace Server }; // namespace HLX
29.357143
81
0.560097
[ "model" ]
ab07cd124899ee1a6cff78c98e6c7e147c6179a0
2,755
cpp
C++
src/Omega_h_vector.cpp
joshia5/ayj-omega_h
8b65215013df29af066fa076261ba897d64a72c2
[ "BSD-2-Clause-FreeBSD" ]
44
2019-01-23T03:37:18.000Z
2021-08-24T02:20:29.000Z
src/Omega_h_vector.cpp
joshia5/ayj-omega_h
8b65215013df29af066fa076261ba897d64a72c2
[ "BSD-2-Clause-FreeBSD" ]
67
2019-01-29T15:35:42.000Z
2021-08-17T20:42:40.000Z
src/Omega_h_vector.cpp
joshia5/ayj-omega_h
8b65215013df29af066fa076261ba897d64a72c2
[ "BSD-2-Clause-FreeBSD" ]
29
2019-01-14T21:33:32.000Z
2021-08-10T11:35:24.000Z
#include "Omega_h_vector.hpp" #include "Omega_h_fail.hpp" #include "Omega_h_for.hpp" namespace Omega_h { template <Int dim> Reals get_vector_norms_tmpl(Reals vs) { auto n = divide_no_remainder(vs.size(), dim); auto out = Write<Real>(n); auto f = OMEGA_H_LAMBDA(LO i) { out[i] = norm(get_vector<dim>(vs, i)); }; parallel_for(n, f, "get_vector_norms"); return out; } Reals get_vector_norms(Reals vs, Int dim) { switch (dim) { case 3: return get_vector_norms_tmpl<3>(vs); case 2: return get_vector_norms_tmpl<2>(vs); } OMEGA_H_NORETURN(Reals()); } template <Int dim> Reals normalize_vectors_tmpl(Reals vs) { auto n = divide_no_remainder(vs.size(), dim); auto out = Write<Real>(vs.size()); auto f = OMEGA_H_LAMBDA(LO i) { set_vector<dim>(out, i, normalize(get_vector<dim>(vs, i))); }; parallel_for(n, f, "normalize_vectors"); return out; } Reals normalize_vectors(Reals vs, Int dim) { switch (dim) { case 3: return normalize_vectors_tmpl<3>(vs); case 2: return normalize_vectors_tmpl<2>(vs); } OMEGA_H_NORETURN(Reals()); } template <Int dim> Reals dot_vectors_dim(Reals a, Reals b) { OMEGA_H_CHECK(a.size() == b.size()); auto n = divide_no_remainder(a.size(), dim); auto out = Write<Real>(n); auto f = OMEGA_H_LAMBDA(LO i) { out[i] = get_vector<dim>(a, i) * get_vector<dim>(b, i); }; parallel_for(n, f, "dot_vectors"); return out; } Reals dot_vectors(Reals a, Reals b, Int dim) { if (dim == 3) return dot_vectors_dim<3>(a, b); if (dim == 2) return dot_vectors_dim<2>(a, b); if (dim == 1) return dot_vectors_dim<1>(a, b); OMEGA_H_NORETURN(Reals()); } Reals resize_vectors(Reals old_vectors, Int old_dim, Int new_dim) { if (old_dim == new_dim) return old_vectors; auto nv = divide_no_remainder(old_vectors.size(), old_dim); Write<Real> new_vectors(nv * new_dim); auto min_dim = min2(old_dim, new_dim); auto f = OMEGA_H_LAMBDA(Int i) { for (Int j = 0; j < min_dim; ++j) { new_vectors[i * new_dim + j] = old_vectors[i * old_dim + j]; } for (Int j = min_dim; j < new_dim; ++j) { new_vectors[i * new_dim + j] = 0.0; } }; parallel_for(nv, f, "resize_vectors"); return new_vectors; } template <Int dim> Reals repeat_vector(LO n, Vector<dim> v) { Write<Real> vs(n * dim); auto f = OMEGA_H_LAMBDA(LO i) { set_vector(vs, i, v); }; parallel_for(n, f, "repeat_vector"); return vs; } template Reals repeat_vector(LO n, Vector<1> v); template Reals repeat_vector(LO n, Vector<2> v); template Reals repeat_vector(LO n, Vector<3> v); template Reals repeat_vector(LO n, Vector<4> v); template Reals repeat_vector(LO n, Vector<6> v); template Reals repeat_vector(LO n, Vector<9> v); } // end namespace Omega_h
27.828283
75
0.664973
[ "vector" ]
ab08ea21203963698f5240f17da0c836cd2bd3df
6,158
cpp
C++
lib/image/format/JPEG.cpp
paperdash/device-epd
660a95d6c176c3e8074f242588f8a201db986d0e
[ "MIT" ]
25
2021-01-24T16:49:03.000Z
2022-02-13T12:57:14.000Z
lib/image/format/JPEG.cpp
paperdash/device-epd
660a95d6c176c3e8074f242588f8a201db986d0e
[ "MIT" ]
null
null
null
lib/image/format/JPEG.cpp
paperdash/device-epd
660a95d6c176c3e8074f242588f8a201db986d0e
[ "MIT" ]
8
2021-03-22T13:58:38.000Z
2022-02-17T18:08:11.000Z
#include <Arduino.h> #include <SPIFFS.h> #include <JPEGDecoder.h> #include "JPEG.h" #include "display.h" File tmpFileBuffer; void renderMcuBlock(int16_t x, int16_t y, uint16_t w, uint16_t h, uint16_t *bitmap); static uint8_t BLOCK_SIZE = 16; // max MCU block size int16_t *blockDelta; uint16_t displayWidth; uint16_t blockDeltaSize; #define minimum(a, b) (((a) < (b)) ? (a) : (b)) void setupImageJPEG() { Serial.println("setupJPEG"); // create working buffer displayWidth = displayGetWidth(); blockDeltaSize = BLOCK_SIZE * displayWidth + 1; blockDelta = new int16_t[blockDeltaSize]; } void jpegOpenFramebuffer() { SPIFFS.remove("/tmp.jpeg"); tmpFileBuffer = SPIFFS.open("/tmp.jpeg", FILE_WRITE); if (!tmpFileBuffer) { Serial.println("Failed to open file for writing"); } memset(blockDelta, 0, sizeof(blockDelta[0]) * blockDeltaSize); } void jpegWriteFramebuffer(int offset, uint8_t bitmap[], int c) { Serial.print("."); if (tmpFileBuffer) { tmpFileBuffer.write(bitmap, c); } } void jpegInfo() { Serial.println(F("===============")); Serial.println(F("JPEG image info")); Serial.println(F("===============")); Serial.print(F("Width :")); Serial.println(JpegDec.width); Serial.print(F("Height :")); Serial.println(JpegDec.height); Serial.print(F("Components :")); Serial.println(JpegDec.comps); Serial.print(F("MCU / row :")); Serial.println(JpegDec.MCUSPerRow); Serial.print(F("MCU / col :")); Serial.println(JpegDec.MCUSPerCol); Serial.print(F("Scan type :")); Serial.println(JpegDec.scanType); Serial.print(F("MCU width :")); Serial.println(JpegDec.MCUWidth); Serial.print(F("MCU height :")); Serial.println(JpegDec.MCUHeight); Serial.println(F("===============")); } void renderJPEG(int xpos, int ypos) { GFXcanvas1 *canvas = displayGetCanvas(); // retrieve infomration about the image uint16_t *pImg; uint16_t mcu_w = JpegDec.MCUWidth; uint16_t mcu_h = JpegDec.MCUHeight; uint32_t max_x = JpegDec.width; uint32_t max_y = JpegDec.height; // Jpeg images are draw as a set of image block (tiles) called Minimum Coding Units (MCUs) // Typically these MCUs are 16x16 pixel blocks // Determine the width and height of the right and bottom edge image blocks uint32_t min_w = minimum(mcu_w, max_x % mcu_w); uint32_t min_h = minimum(mcu_h, max_y % mcu_h); // save the current image block size uint32_t win_w = mcu_w; uint32_t win_h = mcu_h; // record the current time so we can measure how long it takes to draw an image uint32_t drawTime = millis(); // save the coordinate of the right and bottom edges to assist image cropping // to the screen size max_x += xpos; max_y += ypos; // read each MCU block until there are no more while (JpegDec.read()) { // save a pointer to the image block pImg = JpegDec.pImage; // calculate where the image block should be drawn on the screen int mcu_x = JpegDec.MCUx * mcu_w + xpos; int mcu_y = JpegDec.MCUy * mcu_h + ypos; // check if the image block size needs to be changed for the right and bottom edges if (mcu_x + mcu_w <= max_x) win_w = mcu_w; else win_w = min_w; if (mcu_y + mcu_h <= max_y) win_h = mcu_h; else win_h = min_h; // draw image block if it will fit on the screen if ((mcu_x + win_w) <= canvas->width() && (mcu_y + win_h) <= canvas->height()) { renderMcuBlock(mcu_x, mcu_y, win_w, win_h, pImg); } // stop drawing blocks if the bottom of the screen has been reached // the abort function will close the file else if ((mcu_y + win_h) >= canvas->height()) { JpegDec.abort(); } } // calculate how long it took to draw the image drawTime = millis() - drawTime; // Calculate the time it took // print the results to the serial port Serial.print("Total render time was : "); Serial.print(drawTime); Serial.println(" ms"); Serial.println("====================================="); } void jpegFlushFramebuffer() { if (tmpFileBuffer) { tmpFileBuffer.close(); if (!SPIFFS.exists("/tmp.jpeg")) { Serial.println("=== /tmp.jpeg missing"); } // initialise the decoder to give access to image information int ret = JpegDec.decodeFile("/tmp.jpeg"); if (ret == 1) { // print information about the image to the serial port //jpegInfo(); if (JpegDec.width > displayGetWidth() || JpegDec.height > displayGetHeight()) { Serial.println("image resolution to big! skip rendering"); } else { // render the image onto the screen at coordinate 0,0 renderJPEG(0, 0); } } else { Serial.println("!!!! unkown jpeg format !!!!"); } // reset decoder JpegDec.abort(); } } void renderMcuBlockPixel(uint16_t x, uint16_t y, uint16_t color) { // collect all mcu blocks for current row uint16_t blockPageY = y - ((y / JpegDec.MCUHeight) * JpegDec.MCUHeight); blockDelta[(blockPageY * displayWidth) + x] = color; // full mcu row is complete now if (x == JpegDec.width - 1 && (y + 1) % JpegDec.MCUHeight == 0) { // MCU block sizes: 8x8, 16x8 or 16x16 uint16_t originOffsetY = ((y / JpegDec.MCUHeight) * JpegDec.MCUHeight); for (uint16_t _y = 0; _y < JpegDec.MCUHeight; _y++) { for (uint16_t _x = 0; _x < JpegDec.width; _x++) { uint16_t originX = _x; uint16_t originY = originOffsetY + _y; uint16_t originColor = blockDelta[(_y * displayWidth) + _x]; uint8_t r = ((((originColor >> 11) & 0x1F) * 527) + 23) >> 6; uint8_t g = ((((originColor >> 5) & 0x3F) * 259) + 33) >> 6; uint8_t b = (((originColor & 0x1F) * 527) + 23) >> 6; uint8_t rgba[4] = {r, g, b, 0}; ImageProcessPixel(originX, originY, rgba); } } // clean buffer memset(blockDelta, 0, sizeof(blockDelta[0]) * blockDeltaSize); } } void renderMcuBlock(int16_t x, int16_t y, uint16_t w, uint16_t h, uint16_t *bitmap) { GFXcanvas1 *canvas = displayGetCanvas(); // Stop further decoding as image is running off bottom of screen if (y >= canvas->height()) { Serial.println("y is out of display range!"); return; } int16_t _y = y; for (int16_t j = 0; j < h; j++, _y++) { for (int16_t i = 0; i < w; i++) { renderMcuBlockPixel(x + i, _y, bitmap[j * w + i]); } } }
25.76569
91
0.658006
[ "render" ]
ab0a9532b6e97a4b547ebce2744c070f3fe88ea5
855
cpp
C++
aws-cpp-sdk-iotsitewise/source/model/UpdateAssetRequest.cpp
lintonv/aws-sdk-cpp
15e19c265ffce19d2046b18aa1b7307fc5377e58
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-iotsitewise/source/model/UpdateAssetRequest.cpp
lintonv/aws-sdk-cpp
15e19c265ffce19d2046b18aa1b7307fc5377e58
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-iotsitewise/source/model/UpdateAssetRequest.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/iotsitewise/model/UpdateAssetRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::IoTSiteWise::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; UpdateAssetRequest::UpdateAssetRequest() : m_assetIdHasBeenSet(false), m_assetNameHasBeenSet(false), m_clientToken(Aws::Utils::UUID::RandomUUID()), m_clientTokenHasBeenSet(true) { } Aws::String UpdateAssetRequest::SerializePayload() const { JsonValue payload; if(m_assetNameHasBeenSet) { payload.WithString("assetName", m_assetName); } if(m_clientTokenHasBeenSet) { payload.WithString("clientToken", m_clientToken); } return payload.View().WriteReadable(); }
19
69
0.734503
[ "model" ]
ab0c069ddc1f77f5b8dafe74988753622225d496
3,176
cc
C++
tools/data_spliter_ext.cc
lemonviv/Pivot
585b39e54cea3450221521e452f2e89ad5ac990a
[ "Apache-2.0" ]
4
2021-08-04T08:25:53.000Z
2021-08-11T17:04:26.000Z
tools/data_spliter_ext.cc
lemonviv/Pivot
585b39e54cea3450221521e452f2e89ad5ac990a
[ "Apache-2.0" ]
3
2021-07-18T11:25:28.000Z
2021-07-18T11:25:28.000Z
tools/data_spliter_ext.cc
lemonviv/Pivot
585b39e54cea3450221521e452f2e89ad5ac990a
[ "Apache-2.0" ]
1
2022-02-19T15:37:33.000Z
2022-02-19T15:37:33.000Z
#include <fstream> #include <iostream> #include <sstream> #include <string> #include <vector> #include <iomanip> using namespace std; #define MAX_CLIENT 10 int main(int argc, char* argv[]) { if (argc < 3) { cout << "Args: file_path" << endl; return 0; } auto file = argv[1]; int num_client = atoi(argv[2]); ifstream ifs(file); string line; vector<vector<string>> table; while (getline(ifs, line)) { stringstream ss(line); string data; vector<string> sample; while (getline(ss, data, ',')) { // if (data == "0") data = "0.00001"; // temporarily fix zero value issue sample.push_back(data); } table.push_back(sample); } int n_samples = table.size(); int n_attributes = table[0].size(); cout << "number of samples: " << n_samples << endl << "number of attributes (including label): " << n_attributes << endl; int n_attr_per_client = n_attributes / num_client; std::vector<std::string> files; ofstream outs[MAX_CLIENT]; for (int i = 0; i < num_client; i++) { std::string f = "client_" + to_string(i) + ".txt"; files.push_back(f); outs[i].open(f); outs[i].precision(6); } int threshold_index[MAX_CLIENT]; for (int i = num_client - 1; i >= 0; i--) { int threshold = n_attr_per_client * (num_client - i); threshold_index[i] = threshold; } threshold_index[num_client] = 0; threshold_index[0] = threshold_index[0] + 1; // include label for (auto entry : table) { for (int i = 0; i < n_attributes; ++i) { for (int client_id = num_client - 1; client_id >= 0; client_id --) { if (i < threshold_index[client_id] && i >= threshold_index[client_id + 1]) { double d = std::stod(entry[i]); outs[client_id] << fixed << d; if (i == threshold_index[client_id] - 1) { outs[client_id] << endl; } else { outs[client_id] << ","; } } } } } /* string f1 = "client_0.txt", f2 = "client_1.txt", f3 = "client_2.txt"; ofstream out1(f1), out2(f2), out3(f3); out1.precision(6); out2.precision(6); out3.precision(6); //out1 << std::fixed << std::setprecision(6); //out2 << std::fixed << std::setprecision(6); //out3 << std::fixed << std::setprecision(6); for (auto entry : table) { // out1 << "1.0,"; // x0 for regression for (int i = 0; i < n_attributes; ++i) { if (i < n_attr_per_client) { double d = std::stod(entry[i]); out3 << fixed << d; if (i == n_attr_per_client - 1) { out3 << endl; } else { out3 << ","; } } else if (i < n_attr_per_client * 2) { double d = std::stod(entry[i]); out2 << fixed << d; if (i == n_attr_per_client * 2 - 1) { out2 << endl; } else { out2 << ","; } } else { double d = std::stod(entry[i]); out1 << fixed << d; if (i == n_attributes - 1) { out1 << endl; } else { out1 << ","; } } } } */ return 0; }
27.859649
90
0.522985
[ "vector" ]
ab0f3e50b114e4c42ad2867603c1edc27571a0ac
3,516
hpp
C++
core/include/Array.hpp
Damien-Ginesy/Projet_S8
475e348c23110459495a9ccfb3cd0a374dd5f601
[ "MIT" ]
3
2022-03-12T14:11:56.000Z
2022-03-21T00:48:06.000Z
core/include/Array.hpp
Damien-Ginesy/Projet_S8
475e348c23110459495a9ccfb3cd0a374dd5f601
[ "MIT" ]
2
2022-03-22T21:28:05.000Z
2022-03-22T21:28:06.000Z
core/include/Array.hpp
Damien-Ginesy/Projet_S8
475e348c23110459495a9ccfb3cd0a374dd5f601
[ "MIT" ]
null
null
null
#pragma once #include <string.h> #include <iostream> namespace Basalt{ template<typename T> struct Array { using val_t = T; using ref_t = T&; using ptr_t = T*; /* A local view other the Array object */ struct View { private: const ptr_t _start, _end; public: View(const ptr_t start, const ptr_t end): _start(start), _end(end){} const ref_t operator[] (size_t i) const { return _start[i]; } ref_t operator[] (size_t i) = delete; const ptr_t begin() const { return _start; } ptr_t begin() = delete; const ptr_t end() const { return _end; } ptr_t end() = delete; size_t size() const { return _end - _start; } const ptr_t at(size_t n) const { return _start + n; } ptr_t at(size_t n) = delete; View sub(size_t start) const { return View(_start+start, _end); } View sub(size_t start, size_t size) const { return View(_start+start, _start+size); } }; protected: ptr_t _data = nullptr; ptr_t _end = nullptr; public: Array() {} Array(size_t size){ _data = new val_t[size]; _end = _data + size; } Array(size_t size, ptr_t data){ _data = new val_t[size]; _end = _data + size; for(size_t i=0; i<size; ++i) _data[i] = data[i]; } Array(size_t size, const val_t& val){ _data = new val_t[size]; _end = _data + size; for(ptr_t p=_data; p<_end; ++p) *p = val; } Array(const Array<T>& other){ size_t size = other._end - other._data; _data = new val_t[size]; _end = _data + size; for(size_t i=0; i<size; ++i) _data[i] = other._data[i]; } Array(Array<T>&& other): _data(other._data), _end(other._end){ other._data = other._end = nullptr; } void operator=(const Array<T>& other){ delete[] _data; size_t size = other._end - other._data; _data = new val_t[size]; _end = _data + size; for(size_t i=0; i<size; ++i) _data[i] = other._data[i]; } void operator=(Array<T>&& other){ std::swap(this->_data, other._data); std::swap(this->_end, other._end); } template<typename... Arg_t> val_t& emplace(size_t index, Arg_t... args) { _data[index] = val_t(std::forward<Arg_t>(args)...); return _data[index]; } ref_t operator[](size_t i){ return _data[i]; } const ref_t operator[] (size_t i) const { return _data[i]; } ptr_t begin() { return _data; } ptr_t end() { return _end; } const ptr_t begin() const { return _data; } const ptr_t end() const { return _end; } size_t size() const { return _end - _data; } ptr_t at(size_t n) { return _data + n; } View view() const { return View(_data, _end); } View sub(size_t start, size_t size) const { return View(_data+start, _data+start+size); } View sub(size_t start) const { return View(_data+start, _end); } virtual ~Array() { delete[] _data; } }; }
36.247423
98
0.496871
[ "object" ]
ab191c17b44b00f107a0bb5a49ec1fbdc97b43b1
2,883
cpp
C++
src/main.cpp
silhavyj/Simple-hash-function
5b7f007d955d4650d20ae3fcb3175f2848b43528
[ "MIT" ]
null
null
null
src/main.cpp
silhavyj/Simple-hash-function
5b7f007d955d4650d20ae3fcb3175f2848b43528
[ "MIT" ]
null
null
null
src/main.cpp
silhavyj/Simple-hash-function
5b7f007d955d4650d20ae3fcb3175f2848b43528
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <iomanip> #include <fstream> #include "cxxopts.hpp" #define F1(B,C) ((B & C) ^ (~B & C)) #define F2(B,C) ((B | C) & (B ^ C)) #define A 0 #define B 1 #define C 2 #define D 3 #define INIT_VECTOR {0x2EC0, 0xE3BC, 0xFD17, 0xA13F} #define DEBUG(msg) (arg["verbose"].as<bool>() && std::cout << msg << std::flush) cxxopts::ParseResult arg; cxxopts::Options options("./hash_BIT <input>", "KIV/BIT task 5 - implementation of a simple hash function"); std::vector<uint16_t> inputData; void printState(int iteration, uint16_t *prev, uint16_t *next) { std::cout << std::dec << "iteration (" << iteration << "):\n"; std::cout << "prev: "; for (int i = 0; i < 4; i++) std::cout << std::setfill('0') << std::setw(4) << std::right << std::hex << prev[i] << " "; std::cout << "\nnext: "; for (int i = 0; i < 4; i++) std::cout << std::setfill('0') << std::setw(4) << std::right << std::hex << next[i] << " "; std::cout << "\n\n"; } void calculateHash() { DEBUG("starting calculating the hash value...\n"); uint16_t prev[4] = INIT_VECTOR; uint16_t next[4]; uint16_t f; for (int i = 0; i < (int)inputData.size(); i++) { f = i & 1 ? F2(prev[B], prev[C]) : F1(prev[B], prev[C]); next[A] = f ^ prev[D]; next[B] = prev[D]; next[C] = (prev[A] ^ prev[B]) ^ inputData[i]; next[D] = prev[C]; if (arg["verbose"].as<bool>()) printState(i, prev, next); memcpy(prev, next, sizeof(next)); } for (int i = 0; i < 4; i++) std::cout << std::setfill('0') << std::setw(4) << std::right << std::hex << next[i]; std::cout << "\n"; } int readInputFile(std::string fileName) { DEBUG("loading the input file..."); std::ifstream input(fileName, std::ios::binary); if (input.fail()) { return 1; } std::vector<uint8_t> buffer(std::istreambuf_iterator<char>(input), {}); input.close(); for (int i = 0; i < (int)buffer.size(); i++) { if (i & 1) *inputData.rbegin() |= buffer[i]; else inputData.push_back(buffer[i] << 8); } DEBUG("OK\n"); return 0; } int main(int argc, char **argv) { options.add_options() ("v,verbose", "print out info as the program proceeds", cxxopts::value<bool>()->default_value("false")) ("h,help", "print help") ; arg = options.parse(argc, argv); if (arg.count("help")) { std::cout << options.help() << std::endl; return 0; } if (argc < 2) { std::cout << "ERR: The input file is not specified!\n"; std::cout << " Run './hash_BIT --help'\n"; return 1; } if (readInputFile(argv[1]) != 0) { std::cout << "ERR: Input file does not exists!\n"; return 1; } calculateHash(); return 0; }
28.544554
111
0.53035
[ "vector" ]
ab1982d3b4bb920664f3ae5e9abbeca0ae4d8178
24,001
cpp
C++
makepad/ChakraCore/lib/Jsrt/JsrtDebugUtils.cpp
makepaddev/makepad
25d2f18c8a7c190fd1b199762817b6514118e045
[ "MIT" ]
1
2018-01-20T09:59:26.000Z
2018-01-20T09:59:26.000Z
makepad/ChakraCore/lib/Jsrt/JsrtDebugUtils.cpp
makepaddev/makepad
25d2f18c8a7c190fd1b199762817b6514118e045
[ "MIT" ]
null
null
null
makepad/ChakraCore/lib/Jsrt/JsrtDebugUtils.cpp
makepaddev/makepad
25d2f18c8a7c190fd1b199762817b6514118e045
[ "MIT" ]
1
2019-01-19T00:00:10.000Z
2019-01-19T00:00:10.000Z
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #include "JsrtPch.h" #ifdef ENABLE_SCRIPT_DEBUGGING #include "JsrtDebugUtils.h" #include "RuntimeDebugPch.h" #include "screrror.h" // For CompileScriptException void JsrtDebugUtils::AddScriptIdToObject(Js::DynamicObject* object, Js::Utf8SourceInfo* utf8SourceInfo) { JsrtDebugUtils::AddPropertyToObject(object, JsrtDebugPropertyId::scriptId, utf8SourceInfo->GetSourceInfoId(), utf8SourceInfo->GetScriptContext()); Js::Utf8SourceInfo* callerUtf8SourceInfo = utf8SourceInfo->GetCallerUtf8SourceInfo(); if (callerUtf8SourceInfo != nullptr) { JsrtDebugUtils::AddPropertyToObject(object, JsrtDebugPropertyId::parentScriptId, callerUtf8SourceInfo->GetSourceInfoId(), callerUtf8SourceInfo->GetScriptContext()); } } void JsrtDebugUtils::AddFileNameOrScriptTypeToObject(Js::DynamicObject* object, Js::Utf8SourceInfo* utf8SourceInfo) { if (utf8SourceInfo->IsDynamic()) { AssertMsg(utf8SourceInfo->GetSourceContextInfo()->url == nullptr, "How come dynamic code have a url?"); Js::FunctionBody* anyFunctionBody = utf8SourceInfo->GetAnyParsedFunction(); LPCWSTR sourceName = (anyFunctionBody != nullptr) ? anyFunctionBody->GetSourceName() : Js::Constants::UnknownScriptCode; JsrtDebugUtils::AddPropertyToObject(object, JsrtDebugPropertyId::scriptType, sourceName, wcslen(sourceName), utf8SourceInfo->GetScriptContext()); } else { // url can be nullptr if JsParseScript/JsRunScript didn't passed any const char16* url = utf8SourceInfo->GetSourceContextInfo()->url == nullptr ? _u("") : utf8SourceInfo->GetSourceContextInfo()->url; JsrtDebugUtils::AddPropertyToObject(object, JsrtDebugPropertyId::fileName, url, wcslen(url), utf8SourceInfo->GetScriptContext()); } } void JsrtDebugUtils::AddLineColumnToObject(Js::DynamicObject* object, Js::FunctionBody* functionBody, int byteCodeOffset) { if (functionBody != nullptr) { ULONG line = 0; LONG col = 0; if (functionBody->GetLineCharOffset(byteCodeOffset, &line, &col, false)) { JsrtDebugUtils::AddPropertyToObject(object, JsrtDebugPropertyId::line, (uint32) line, functionBody->GetScriptContext()); JsrtDebugUtils::AddPropertyToObject(object, JsrtDebugPropertyId::column, (int32) col, functionBody->GetScriptContext()); } } } void JsrtDebugUtils::AddSourceLengthAndTextToObject(Js::DynamicObject* object, Js::FunctionBody* functionBody, int byteCodeOffset) { Js::FunctionBody::StatementMap* statementMap = functionBody->GetEnclosingStatementMapFromByteCode(byteCodeOffset); Assert(statementMap != nullptr); LPCUTF8 source = functionBody->GetStartOfDocument(_u("Source for debugging")); size_t cbLength = functionBody->GetUtf8SourceInfo()->GetCbLength(); size_t startByte = utf8::CharacterIndexToByteIndex(source, cbLength, (const charcount_t)statementMap->sourceSpan.begin); size_t endByte = utf8::CharacterIndexToByteIndex(source, cbLength, (const charcount_t)statementMap->sourceSpan.end); int cch = statementMap->sourceSpan.end - statementMap->sourceSpan.begin; JsrtDebugUtils::AddPropertyToObject(object, JsrtDebugPropertyId::sourceLength, (double)cch, functionBody->GetScriptContext()); AutoArrayPtr<char16> sourceContent(HeapNewNoThrowArray(char16, cch + 1), cch + 1); if (sourceContent != nullptr) { LPCUTF8 pbStart = source + startByte; LPCUTF8 pbEnd = pbStart + (endByte - startByte); utf8::DecodeOptions options = functionBody->GetUtf8SourceInfo()->IsCesu8() ? utf8::doAllowThreeByteSurrogates : utf8::doDefault; utf8::DecodeUnitsIntoAndNullTerminate(sourceContent, pbStart, pbEnd, options); JsrtDebugUtils::AddPropertyToObject(object, JsrtDebugPropertyId::sourceText, sourceContent, cch, functionBody->GetScriptContext()); } else { JsrtDebugUtils::AddPropertyToObject(object, JsrtDebugPropertyId::sourceText, _u(""), 1, functionBody->GetScriptContext()); } } void JsrtDebugUtils::AddLineCountToObject(Js::DynamicObject * object, Js::Utf8SourceInfo * utf8SourceInfo) { utf8SourceInfo->EnsureLineOffsetCache(); Assert(utf8SourceInfo->GetLineCount() < UINT32_MAX); JsrtDebugUtils::AddPropertyToObject(object, JsrtDebugPropertyId::lineCount, (uint32)utf8SourceInfo->GetLineCount(), utf8SourceInfo->GetScriptContext()); } void JsrtDebugUtils::AddSourceToObject(Js::DynamicObject * object, Js::Utf8SourceInfo * utf8SourceInfo) { int32 cchLength = utf8SourceInfo->GetCchLength(); AutoArrayPtr<char16> sourceContent(HeapNewNoThrowArray(char16, cchLength + 1), cchLength + 1); if (sourceContent != nullptr) { LPCUTF8 source = utf8SourceInfo->GetSource(); size_t cbLength = utf8SourceInfo->GetCbLength(); utf8::DecodeOptions options = utf8SourceInfo->IsCesu8() ? utf8::doAllowThreeByteSurrogates : utf8::doDefault; utf8::DecodeUnitsIntoAndNullTerminate(sourceContent, source, source + cbLength, options); JsrtDebugUtils::AddPropertyToObject(object, JsrtDebugPropertyId::source, sourceContent, cchLength, utf8SourceInfo->GetScriptContext()); } else { JsrtDebugUtils::AddPropertyToObject(object, JsrtDebugPropertyId::source, _u(""), 1, utf8SourceInfo->GetScriptContext()); } } void JsrtDebugUtils::AddSourceMetadataToObject(Js::DynamicObject * object, Js::Utf8SourceInfo * utf8SourceInfo) { JsrtDebugUtils::AddFileNameOrScriptTypeToObject(object, utf8SourceInfo); JsrtDebugUtils::AddLineCountToObject(object, utf8SourceInfo); JsrtDebugUtils::AddPropertyToObject(object, JsrtDebugPropertyId::sourceLength, utf8SourceInfo->GetCchLength(), utf8SourceInfo->GetScriptContext()); if (utf8SourceInfo->HasDebugDocument()) { // Only add the script ID in cases where a debug document exists JsrtDebugUtils::AddScriptIdToObject(object, utf8SourceInfo); } } void JsrtDebugUtils::AddVarPropertyToObject(Js::DynamicObject * object, const char16 * propertyName, Js::Var value, Js::ScriptContext * scriptContext) { const Js::PropertyRecord* propertyRecord; // propertyName is the DEBUGOBJECTPROPERTY from JsrtDebugPropertiesEnum so it can't have embedded null, ok to use wcslen scriptContext->GetOrAddPropertyRecord(propertyName, static_cast<int>(wcslen(propertyName)), &propertyRecord); Js::Var marshaledObj = Js::CrossSite::MarshalVar(scriptContext, value); if (FALSE == Js::JavascriptOperators::InitProperty(object, propertyRecord->GetPropertyId(), marshaledObj)) { Assert("Failed to add property to debugger object"); } } void JsrtDebugUtils::AddPropertyType(Js::DynamicObject * object, Js::IDiagObjectModelDisplay* objectDisplayRef, Js::ScriptContext * scriptContext, bool forceSetValueProp) { Assert(objectDisplayRef != nullptr); Assert(scriptContext != nullptr); bool addDisplay = false; bool addValue = false; Js::Var varValue = objectDisplayRef->GetVarValue(FALSE); Js::IDiagObjectAddress* varAddress = objectDisplayRef->GetDiagAddress(); if (varValue != nullptr) { Js::TypeId typeId = Js::JavascriptOperators::GetTypeId(varValue); switch (typeId) { case Js::TypeIds_Undefined: JsrtDebugUtils::AddPropertyToObject(object, JsrtDebugPropertyId::type, scriptContext->GetLibrary()->GetUndefinedDisplayString(), scriptContext); JsrtDebugUtils::AddPropertyToObject(object, JsrtDebugPropertyId::value, scriptContext->GetLibrary()->GetUndefined(), scriptContext); addDisplay = true; break; case Js::TypeIds_Null: JsrtDebugUtils::AddPropertyToObject(object, JsrtDebugPropertyId::type, scriptContext->GetLibrary()->GetObjectTypeDisplayString(), scriptContext); JsrtDebugUtils::AddPropertyToObject(object, JsrtDebugPropertyId::value, scriptContext->GetLibrary()->GetNull(), scriptContext); addDisplay = true; break; case Js::TypeIds_Boolean: JsrtDebugUtils::AddPropertyToObject(object, JsrtDebugPropertyId::type, scriptContext->GetLibrary()->GetBooleanTypeDisplayString(), scriptContext); JsrtDebugUtils::AddPropertyToObject(object, JsrtDebugPropertyId::value, Js::JavascriptBoolean::FromVar(varValue)->GetValue() == TRUE ? true : false, scriptContext); break; case Js::TypeIds_Integer: JsrtDebugUtils::AddPropertyToObject(object, JsrtDebugPropertyId::type, scriptContext->GetLibrary()->GetNumberTypeDisplayString(), scriptContext); JsrtDebugUtils::AddPropertyToObject(object, JsrtDebugPropertyId::value, Js::TaggedInt::ToDouble(varValue), scriptContext); break; case Js::TypeIds_Number: { JsrtDebugUtils::AddPropertyToObject(object, JsrtDebugPropertyId::type, scriptContext->GetLibrary()->GetNumberTypeDisplayString(), scriptContext); double numberValue = Js::JavascriptNumber::GetValue(varValue); JsrtDebugUtils::AddPropertyToObject(object, JsrtDebugPropertyId::value, numberValue, scriptContext); // If number is not finite (NaN, Infinity, -Infinity) or is -0 add display as well so that we can display special strings if (!Js::NumberUtilities::IsFinite(numberValue) || Js::JavascriptNumber::IsNegZero(numberValue)) { addDisplay = true; } break; } case Js::TypeIds_Int64Number: JsrtDebugUtils::AddPropertyToObject(object, JsrtDebugPropertyId::type, scriptContext->GetLibrary()->GetNumberTypeDisplayString(), scriptContext); JsrtDebugUtils::AddPropertyToObject(object, JsrtDebugPropertyId::value, (double)Js::JavascriptInt64Number::FromVar(varValue)->GetValue(), scriptContext); break; case Js::TypeIds_UInt64Number: JsrtDebugUtils::AddPropertyToObject(object, JsrtDebugPropertyId::type, scriptContext->GetLibrary()->GetNumberTypeDisplayString(), scriptContext); JsrtDebugUtils::AddPropertyToObject(object, JsrtDebugPropertyId::value, (double)Js::JavascriptUInt64Number::FromVar(varValue)->GetValue(), scriptContext); break; case Js::TypeIds_String: JsrtDebugUtils::AddPropertyToObject(object, JsrtDebugPropertyId::type, scriptContext->GetLibrary()->GetStringTypeDisplayString(), scriptContext); JsrtDebugUtils::AddPropertyToObject(object, JsrtDebugPropertyId::value, Js::JavascriptString::FromVar(varValue), scriptContext); break; case Js::TypeIds_Symbol: JsrtDebugUtils::AddPropertyToObject(object, JsrtDebugPropertyId::type, scriptContext->GetLibrary()->GetSymbolTypeDisplayString(), scriptContext); addDisplay = true; break; case Js::TypeIds_Function: JsrtDebugUtils::AddPropertyToObject(object, JsrtDebugPropertyId::type, scriptContext->GetLibrary()->GetFunctionTypeDisplayString(), scriptContext); addDisplay = true; break; #ifdef ENABLE_SIMDJS case Js::TypeIds_SIMDFloat32x4: JsrtDebugUtils::AddPropertyToObject(object, JsrtDebugPropertyId::type, scriptContext->GetLibrary()->GetSIMDFloat32x4DisplayString(), scriptContext); addDisplay = true; break; case Js::TypeIds_SIMDFloat64x2: JsrtDebugUtils::AddPropertyToObject(object, JsrtDebugPropertyId::type, scriptContext->GetLibrary()->GetSIMDFloat64x2DisplayString(), scriptContext); addDisplay = true; break; case Js::TypeIds_SIMDInt32x4: JsrtDebugUtils::AddPropertyToObject(object, JsrtDebugPropertyId::type, scriptContext->GetLibrary()->GetSIMDInt32x4DisplayString(), scriptContext); addDisplay = true; break; case Js::TypeIds_SIMDInt8x16: JsrtDebugUtils::AddPropertyToObject(object, JsrtDebugPropertyId::type, scriptContext->GetLibrary()->GetSIMDInt8x16DisplayString(), scriptContext); addDisplay = true; break; #endif // #ifdef ENABLE_SIMDJS case Js::TypeIds_Enumerator: case Js::TypeIds_HostDispatch: case Js::TypeIds_WithScopeObject: case Js::TypeIds_UndeclBlockVar: case Js::TypeIds_EngineInterfaceObject: case Js::TypeIds_WinRTDate: AssertMsg(false, "Not valid types"); break; case Js::TypeIds_ModuleRoot: case Js::TypeIds_HostObject: case Js::TypeIds_ActivationObject: AssertMsg(false, "Are these valid types for debugger?"); break; case Js::TypeIds_NativeIntArray: #if ENABLE_COPYONACCESS_ARRAY case Js::TypeIds_CopyOnAccessNativeIntArray: #endif case Js::TypeIds_NativeFloatArray: case Js::TypeIds_ES5Array: case Js::TypeIds_CharArray: case Js::TypeIds_BoolArray: case Js::TypeIds_ArrayIterator: case Js::TypeIds_MapIterator: case Js::TypeIds_SetIterator: case Js::TypeIds_StringIterator: case Js::TypeIds_VariantDate: case Js::TypeIds_Object: case Js::TypeIds_Array: case Js::TypeIds_Date: case Js::TypeIds_RegEx: case Js::TypeIds_Error: case Js::TypeIds_BooleanObject: case Js::TypeIds_NumberObject: case Js::TypeIds_StringObject: case Js::TypeIds_Arguments: case Js::TypeIds_ArrayBuffer: case Js::TypeIds_Int8Array: case Js::TypeIds_Uint8Array: case Js::TypeIds_Uint8ClampedArray: case Js::TypeIds_Int16Array: case Js::TypeIds_Uint16Array: case Js::TypeIds_Int32Array: case Js::TypeIds_Uint32Array: case Js::TypeIds_Float32Array: case Js::TypeIds_Float64Array: case Js::TypeIds_Int64Array: case Js::TypeIds_Uint64Array: case Js::TypeIds_DataView: case Js::TypeIds_Map: case Js::TypeIds_Set: case Js::TypeIds_WeakMap: case Js::TypeIds_WeakSet: case Js::TypeIds_SymbolObject: case Js::TypeIds_Generator: case Js::TypeIds_Promise: case Js::TypeIds_GlobalObject: case Js::TypeIds_SpreadArgument: #ifdef ENABLE_WASM case Js::TypeIds_WebAssemblyModule: case Js::TypeIds_WebAssemblyInstance: case Js::TypeIds_WebAssemblyMemory: case Js::TypeIds_WebAssemblyTable: #endif case Js::TypeIds_Proxy: { JsrtDebugUtils::AddPropertyToObject(object, JsrtDebugPropertyId::type, scriptContext->GetLibrary()->GetObjectTypeDisplayString(), scriptContext); addDisplay = true; const char16* className = JsrtDebugUtils::GetClassName(typeId); JsrtDebugUtils::AddPropertyToObject(object, JsrtDebugPropertyId::className, className, wcslen(className), scriptContext); break; } default: AssertMsg(false, "Unhandled type"); break; } } else { if (objectDisplayRef->HasChildren()) { JsrtDebugUtils::AddPropertyToObject(object, JsrtDebugPropertyId::type, scriptContext->GetLibrary()->GetObjectTypeDisplayString(), scriptContext); addDisplay = true; const char16* className = JsrtDebugUtils::GetClassName(Js::TypeIds_Object); JsrtDebugUtils::AddPropertyToObject(object, JsrtDebugPropertyId::className, className, wcslen(className), scriptContext); } else { JsrtDebugUtils::AddPropertyToObject(object, JsrtDebugPropertyId::type, scriptContext->GetLibrary()->GetStringTypeDisplayString(), scriptContext); addValue = true; } } if (addDisplay || addValue) { LPCWSTR value = nullptr; // Getting value might call getter which can throw so wrap in try catch try { value = objectDisplayRef->Value(10); } catch (const Js::JavascriptException& err) { err.GetAndClear(); // discard exception object value = _u(""); } JsrtDebugUtils::AddPropertyToObject(object, addDisplay ? JsrtDebugPropertyId::display : JsrtDebugPropertyId::value, value, wcslen(value), scriptContext); } if (forceSetValueProp && varValue != nullptr && !JsrtDebugUtils::HasProperty(object, JsrtDebugPropertyId::value, scriptContext)) { JsrtDebugUtils::AddPropertyToObject(object, JsrtDebugPropertyId::value, varValue, scriptContext); } DBGPROP_ATTRIB_FLAGS dbPropAttrib = objectDisplayRef->GetTypeAttribute(); JsrtDebugPropertyAttribute propertyAttributes = JsrtDebugPropertyAttribute::NONE; if ((dbPropAttrib & DBGPROP_ATTRIB_VALUE_READONLY) == DBGPROP_ATTRIB_VALUE_READONLY) { propertyAttributes |= JsrtDebugPropertyAttribute::READ_ONLY_VALUE; } if (objectDisplayRef->HasChildren()) { propertyAttributes |= JsrtDebugPropertyAttribute::HAVE_CHILDRENS; } if (varAddress != nullptr && varAddress->IsInDeadZone()) { propertyAttributes |= JsrtDebugPropertyAttribute::IN_TDZ; } JsrtDebugUtils::AddPropertyToObject(object, JsrtDebugPropertyId::propertyAttributes, (UINT)propertyAttributes, scriptContext); } void JsrtDebugUtils::AddVarPropertyToObject(Js::DynamicObject * object, JsrtDebugPropertyId propertyId, Js::Var value, Js::ScriptContext * scriptContext) { JsrtDebugUtils::AddVarPropertyToObject(object, JsrtDebugUtils::GetDebugPropertyName(propertyId), value, scriptContext); } void JsrtDebugUtils::AddPropertyToObject(Js::DynamicObject * object, JsrtDebugPropertyId propertyId, double value, Js::ScriptContext * scriptContext) { JsrtDebugUtils::AddVarPropertyToObject(object, propertyId, Js::JavascriptNumber::ToVarNoCheck(value, scriptContext), scriptContext); } void JsrtDebugUtils::AddPropertyToObject(Js::DynamicObject * object, JsrtDebugPropertyId propertyId, uint32 value, Js::ScriptContext * scriptContext) { JsrtDebugUtils::AddVarPropertyToObject(object, propertyId, Js::JavascriptNumber::ToVarNoCheck(value, scriptContext), scriptContext); } void JsrtDebugUtils::AddPropertyToObject(Js::DynamicObject * object, JsrtDebugPropertyId propertyId, int32 value, Js::ScriptContext * scriptContext) { JsrtDebugUtils::AddVarPropertyToObject(object, propertyId, Js::JavascriptNumber::ToVarNoCheck(value, scriptContext), scriptContext); } void JsrtDebugUtils::AddPropertyToObject(Js::DynamicObject * object, JsrtDebugPropertyId propertyId, const char16 * value, size_t len, Js::ScriptContext * scriptContext) { charcount_t charCount = static_cast<charcount_t>(len); Assert(charCount == len); if (charCount == len) { JsrtDebugUtils::AddVarPropertyToObject(object, propertyId, Js::JavascriptString::NewCopyBuffer(value, charCount, scriptContext), scriptContext); } } void JsrtDebugUtils::AddPropertyToObject(Js::DynamicObject * object, JsrtDebugPropertyId propertyId, Js::JavascriptString* jsString, Js::ScriptContext * scriptContext) { JsrtDebugUtils::AddPropertyToObject(object, propertyId, jsString->GetSz(), jsString->GetLength(), scriptContext); } void JsrtDebugUtils::AddPropertyToObject(Js::DynamicObject * object, JsrtDebugPropertyId propertyId, bool value, Js::ScriptContext * scriptContext) { JsrtDebugUtils::AddVarPropertyToObject(object, propertyId, Js::JavascriptBoolean::ToVar(value, scriptContext), scriptContext); } void JsrtDebugUtils::AddPropertyToObject(Js::DynamicObject * object, JsrtDebugPropertyId propertyId, Js::Var value, Js::ScriptContext * scriptContext) { JsrtDebugUtils::AddVarPropertyToObject(object, propertyId, value, scriptContext); } bool JsrtDebugUtils::HasProperty(Js::DynamicObject * object, JsrtDebugPropertyId propertyId, Js::ScriptContext * scriptContext) { const char16* propertyName = GetDebugPropertyName(propertyId); const Js::PropertyRecord* propertyRecord; scriptContext->FindPropertyRecord(propertyName, static_cast<int>(wcslen(propertyName)), &propertyRecord); if (propertyRecord == nullptr) { // No property record exists, there must be no property with that name in the script context. return false; } return !!Js::JavascriptOperators::HasProperty(object, propertyRecord->GetPropertyId()); } const char16 * JsrtDebugUtils::GetClassName(Js::TypeId typeId) { switch (typeId) { case Js::TypeIds_Object: case Js::TypeIds_ArrayIterator: case Js::TypeIds_MapIterator: case Js::TypeIds_SetIterator: case Js::TypeIds_StringIterator: return _u("Object"); case Js::TypeIds_Proxy: return _u("Proxy"); case Js::TypeIds_Array: case Js::TypeIds_NativeIntArray: #if ENABLE_COPYONACCESS_ARRAY case Js::TypeIds_CopyOnAccessNativeIntArray: #endif case Js::TypeIds_NativeFloatArray: case Js::TypeIds_ES5Array: case Js::TypeIds_CharArray: case Js::TypeIds_BoolArray: return _u("Array"); case Js::TypeIds_Date: case Js::TypeIds_VariantDate: return _u("Date"); case Js::TypeIds_RegEx: return _u("RegExp"); case Js::TypeIds_Error: return _u("Error"); case Js::TypeIds_BooleanObject: return _u("Boolean"); case Js::TypeIds_NumberObject: return _u("Number"); case Js::TypeIds_StringObject: return _u("String"); case Js::TypeIds_Arguments: return _u("Object"); case Js::TypeIds_ArrayBuffer: return _u("ArrayBuffer"); case Js::TypeIds_Int8Array: return _u("Int8Array"); case Js::TypeIds_Uint8Array: return _u("Uint8Array"); case Js::TypeIds_Uint8ClampedArray: return _u("Uint8ClampedArray"); case Js::TypeIds_Int16Array: return _u("Int16Array"); case Js::TypeIds_Uint16Array: return _u("Uint16Array"); case Js::TypeIds_Int32Array: return _u("Int32Array"); case Js::TypeIds_Uint32Array: return _u("Uint32Array"); case Js::TypeIds_Float32Array: return _u("Float32Array"); case Js::TypeIds_Float64Array: return _u("Float64Array"); case Js::TypeIds_Int64Array: return _u("Int64Array"); case Js::TypeIds_Uint64Array: return _u("Uint64Array"); case Js::TypeIds_DataView: return _u("DataView"); case Js::TypeIds_Map: return _u("Map"); case Js::TypeIds_Set: return _u("Set"); case Js::TypeIds_WeakMap: return _u("WeakMap"); case Js::TypeIds_WeakSet: return _u("WeakSet"); case Js::TypeIds_SymbolObject: return _u("Symbol"); case Js::TypeIds_Generator: return _u("Generator"); case Js::TypeIds_Promise: return _u("Promise"); case Js::TypeIds_GlobalObject: return _u("Object"); case Js::TypeIds_SpreadArgument: return _u("Spread"); #ifdef ENABLE_WASM case Js::TypeIds_WebAssemblyModule: return _u("WebAssembly.Module"); case Js::TypeIds_WebAssemblyInstance:return _u("WebAssembly.Instance"); case Js::TypeIds_WebAssemblyMemory: return _u("WebAssembly.Memory"); case Js::TypeIds_WebAssemblyTable: return _u("WebAssembly.Table"); #endif default: Assert(false); } return _u(""); } const char16 * JsrtDebugUtils::GetDebugPropertyName(JsrtDebugPropertyId propertyId) { switch (propertyId) { #define DEBUGOBJECTPROPERTY(name) case JsrtDebugPropertyId::##name: return _u(###name); #include "JsrtDebugPropertiesEnum.h" } Assert(false); return _u(""); } #endif
46.244701
176
0.703929
[ "object" ]