blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 247 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2 values | repo_name stringlengths 4 111 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 58 | visit_date timestamp[ns]date 2015-07-25 18:16:41 2023-09-06 10:45:08 | revision_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | committer_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | github_id int64 3.89k 689M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 25 values | gha_event_created_at timestamp[ns]date 2012-06-07 00:51:45 2023-09-14 21:58:52 ⌀ | gha_created_at timestamp[ns]date 2008-03-27 23:40:48 2023-08-24 19:49:39 ⌀ | gha_language stringclasses 159 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 7 10.5M | extension stringclasses 111 values | filename stringlengths 1 195 | text stringlengths 7 10.5M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7fd51305c5444f3347d671289ed5f978ca959a4e | ab80d88b354db83585acc72e36fe9f3f4a1c7e54 | /Test/src/TestPrognoser.cpp | 0db688a68060acd949cb7e949186b3ce8dab55fb | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | zhengbenchang/GSAP | a1ecedaf502e184827148cee4bd27b44315c6a2f | 68a33f4df375d8144ffe10f6c90ad2d57204a6c9 | refs/heads/master | 2020-04-13T08:35:24.905767 | 2018-11-30T22:21:20 | 2018-12-04T22:37:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,112 | cpp | TestPrognoser.cpp | //
// TestPrognoser.cpp
// Generic Infrastructure Example
//
// Created by Chris Teubert on 4/18/16.
// Copyright © 2018 United States Government as represented by the Administrator of the National Aeronautics and Space Administration. All Rights Reserved.
//
#include <string>
#include "TestPrognoser.h"
#include "GSAPConfigMap.h"
using namespace PCOE;
const std::string MODULE_NAME = "TestPrognoser";
TestPrognoser::TestPrognoser(PCOE::GSAPConfigMap & paramMap):
CommonPrognoser(paramMap) {
log.WriteLine(LOG_DEBUG, MODULE_NAME, "Creating");
if (paramMap.includes("futureLoading")) {
log.FormatLine(LOG_DEBUG, MODULE_NAME, "Received Future Loading: %s", paramMap["futureLoading"][0].c_str());
}
}
void TestPrognoser::step() {
}
void TestPrognoser::setHistory(const ProgData&) {
log.WriteLine(LOG_INFO, MODULE_NAME, "Received History");
}
void TestPrognoser::checkResultValidity() {
log.WriteLine(LOG_INFO, MODULE_NAME, "Checking Result Validity");
}
void TestPrognoser::checkInputValidity() {
log.WriteLine(LOG_INFO, MODULE_NAME, "Checking Input Validity");
}
|
3f65cb053c24342cf55af0621cb1068ca237940b | 7535316048271589da7c5af7792e94c818fbbcb3 | /MPHY0022CW2/Testing/ccmpiPiSeriesOMPTest.cpp | 6e64e3b8bfcbfbf014eadea548155cb523a07b51 | [
"BSD-3-Clause"
] | permissive | uceclz0/cpp_CW | 97d53b11a755d8574b995c48e29a6e204d905895 | 3860f26d0d87f7cf91bbcb4ec8fd836357d56b9a | refs/heads/master | 2022-04-24T02:25:47.602315 | 2020-04-18T09:07:36 | 2020-04-18T09:07:36 | 256,700,795 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,245 | cpp | ccmpiPiSeriesOMPTest.cpp | /*=============================================================================
CMAKECATCHMPI: A software package to demo MPI with CMake, CTest and Catch.
Copyright (c) University College London (UCL). All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.
See LICENSE.txt in the top level directory for details.
=============================================================================*/
#include "catch.hpp"
#include "ccmpiCatchMain.h"
#include "ccmpiMyFunctions.h"
#include <omp.h>
static int fcmp(double a, double b, double eps) { /* floating point compare, returns -1, 0, 1*/
return (a < b - eps) - (a > b + eps);
}
TEST_CASE( "4. OpenMP Pi Test", "[CW2]" ) {
omp_set_num_threads(4);
double result = ccmpi::EvaluatePiUsingOpenMP(100);
double pi = acos(-1.0);
REQUIRE(fcmp(result, pi, 1e-2) == 0);
}
TEST_CASE( "4. OpenMP Pi Test, can't get the right answer when threads > the total numberOfElements", "[CW2]" ) {
omp_set_num_threads(104);
double result = ccmpi::EvaluatePiUsingOpenMP(100);
double pi = acos(-1.0);
REQUIRE(fcmp(result, pi, 1e-2) != 0);
}
|
05fcb7023a8042e8388d007a22d344e8b5e24097 | b9432721a49e260e892906ab108c00a528d43727 | /Ruleta/Ruleta de la Fortuna .ino | 0ba0ab9bc5086e27affdbaf303a649d7e193e9d1 | [
"MIT"
] | permissive | jdamador/Arduino | eca6a9b278e2b7150ccd4dfb48ec999e25df17ac | 072fd945b6ad3fdc10af56a6e066fe1a524152e1 | refs/heads/master | 2020-05-02T02:58:09.223775 | 2019-07-03T14:25:08 | 2019-07-03T14:25:08 | 177,716,105 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,054 | ino | Ruleta de la Fortuna .ino | // Declaración de pines.
int zumbador=10;
int pulsador=11;
int leds[]={5,6,7,8,9};
// Variable para recorrer el array.
int n=0;
int tiempo=200;
void setup (){
// Establecer los pines de los leds como salida.
for(n=0;n<5;n++) {
pinMode(leds[n],OUTPUT);
}
// Pin zumbador como salida.
pinMode(zumbador,OUTPUT);
// Pin pulsador como entrada.
pinMode(pulsador,INPUT);
}
// Función para comprobar si se acerto.
void compruebaacierto(){
// Si hay pulsación y esta en el led del pin 7.
if(digitalRead(pulsador)==HIGH && n==2) {
digitalWrite(zumbador,HIGH); // Sonar.
delay (1000); // Esperar un segundo.
digitalWrite(zumbador,LOW); // Apagar.
tiempo=tiempo-20; // Aumentar la velocidad.
// Reiniciar el tiempo si esta por debajo de 10ms.
if(tiempo<10){
tiempo=200;
}
}
}
void loop () {
// Recorrer los leds par ir encendiendolos uno a uno.
for(n=0;n<5;n++) {
digitalWrite(leds[n],HIGH);
delay(tiempo);
compruebaacierto();
digitalWrite(leds[n],LOW);
delay(tiempo);
}
} |
8b083d290afd5ebc3734e7bdc04d2323566f0c99 | 58b141228a7caf70239b0e5c1df4267458432689 | /SOLVER/src/shared/data_structure/RTreeND.hpp | f60de4f85f8d736983c2719f499e27b84ca6190c | [
"MIT"
] | permissive | syzeng-duduxi/AxiSEM-3D | 2185facfd8347a50a283214b16703549f87d1575 | 043cabbb9661787222fcdb0ea5ba1e25467481f7 | refs/heads/master | 2023-04-13T15:21:15.702818 | 2021-04-05T14:13:56 | 2021-04-05T14:13:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,005 | hpp | RTreeND.hpp | //
// RTreeND.hpp
// AxiSEM3D
//
// Created by Kuangdai Leng on 9/7/19.
// Copyright © 2019 Kuangdai Leng. All rights reserved.
//
// boost RTree for searching nearest points
#ifndef RTreeND_hpp
#define RTreeND_hpp
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Weverything"
#include <boost/geometry.hpp>
#pragma clang diagnostic pop
#include "NetCDF_Reader.hpp"
#include "mpi.hpp"
#include "io.hpp"
#include "timer.hpp"
#include "eigen_tools.hpp"
// D: dimensions, must be 1 or 2 or 3
// V: number of variables
// T: type of variables
template <int D, int V, typename T>
class RTreeND {
///////////// typedef /////////////
// coordinates
typedef typename std::conditional<D == 1,
Eigen::Matrix<double, Eigen::Dynamic, D>,
Eigen::Matrix<double, Eigen::Dynamic, D, Eigen::RowMajor>>::type DMatXD_RM;
// data
typedef typename std::conditional<V == 1,
Eigen::Matrix<T, Eigen::Dynamic, V>,
Eigen::Matrix<T, Eigen::Dynamic, V, Eigen::RowMajor>>::type TMatXV_RM;
// data unit
typedef Eigen::Matrix<T, 1, V> TRowV;
typedef Eigen::Matrix<double, 1, V> DRowV;
// location
typedef boost::geometry::model::point<double, D,
boost::geometry::cs::cartesian> RTreeLoc;
// leaf
typedef std::pair<RTreeLoc, TRowV> RTreeLeaf;
///////////// cs array to RTreeLoc /////////////
// 1D
template <int R = D, typename ArrayCS>
static typename std::enable_if<R == 1,
RTreeLoc>::type toRTreeLoc(const ArrayCS &loc) {
return RTreeLoc(loc[0]);
}
// 2D
template <int R = D, typename ArrayCS>
static typename std::enable_if<R == 2,
RTreeLoc>::type toRTreeLoc(const ArrayCS &loc) {
return RTreeLoc(loc[0], loc[1]);
}
// 3D
template <int R = D, typename ArrayCS>
static typename std::enable_if<R == 3,
RTreeLoc>::type toRTreeLoc(const ArrayCS &loc) {
return RTreeLoc(loc[0], loc[1], loc[2]);
}
///////////// public /////////////
public:
// constructor
RTreeND() = default;
// constructor
RTreeND(const std::string &ncFile, const std::string &coordVarName,
const std::array<std::pair<std::string, double>, V> &varInfo) {
// read data
DMatXD_RM ctrlCrds;
TMatXV_RM ctrlVals;
timer::gPreloopTimer.begin("Reading control-point data");
timer::gPreloopTimer.message("data file: " + io::popInputDir(ncFile));
if (mpi::root()) {
// open
NetCDF_Reader reader(io::popInputDir(ncFile));
// read coords
reader.readMatrixDouble(coordVarName, ctrlCrds);
// read data
ctrlVals.resize(ctrlCrds.rows(), V);
for (int ivar = 0; ivar < V; ivar++) {
// read to double
eigen::DColX ctrlVal;
reader.readMatrixDouble(varInfo[ivar].first, ctrlVal);
ctrlVal *= varInfo[ivar].second;
// round
if (std::is_integral<T>::value) {
ctrlVal = ctrlVal.array().round();
}
// cast to Ts
ctrlVals.col(ivar) = ctrlVal.template cast<T>();
}
}
timer::gPreloopTimer.ended("Reading control-point data");
// broadcast
timer::gPreloopTimer.begin("Broadcasting control-point data");
mpi::bcastEigen(ctrlCrds);
mpi::bcastEigen(ctrlVals);
// memory info
timer::gPreloopTimer.message
(eigen_tools::memoryInfo(ctrlCrds, "coordinates at control points"));
timer::gPreloopTimer.message
(eigen_tools::memoryInfo(ctrlVals, "values at control points"));
timer::gPreloopTimer.ended("Broadcasting control-point data");
// build RTree
timer::gPreloopTimer.begin("Building R-tree");
addLeafs(ctrlCrds, ctrlVals);
timer::gPreloopTimer.ended("Building R-tree");
}
// add a leaf
template <typename ArrayCS>
void addLeaf(const ArrayCS &loc, const TRowV &val) {
mRTree.insert({toRTreeLoc(loc), val});
}
// add scalar, only for V = 1
template <int VN = V, typename ArrayCS>
typename std::enable_if<VN == 1, void>::type
addLeaf(const ArrayCS &loc, T val) {
static TRowV oneVal;
oneVal(0) = val;
addLeaf(loc, oneVal);
}
// add leafs
void addLeafs(const DMatXD_RM &locs, const TMatXV_RM &vals) {
for (int ir = 0; ir < locs.rows(); ir++) {
mRTree.insert({toRTreeLoc(locs.row(ir)), vals.row(ir)});
}
}
// query
// difficult to make this collective
template <typename ArrayCS>
void query(const ArrayCS &loc, int count,
std::vector<double> &dists, std::vector<TRowV> &vals) const {
// location
const RTreeLoc &rloc = toRTreeLoc(loc);
// KNN query
std::vector<RTreeLeaf> leafs;
mRTree.query(boost::geometry::index::nearest(rloc, count),
std::back_inserter(leafs));
// get distance
dists.clear();
dists.reserve(count);
std::transform(leafs.begin(), leafs.end(), std::back_inserter(dists),
[&rloc](const auto &leaf) {
return boost::geometry::distance(leaf.first, rloc);});
// get values
vals.clear();
vals.reserve(count);
std::transform(leafs.begin(), leafs.end(), std::back_inserter(vals),
[](const auto &leaf) {return leaf.second;});
}
// compute
template <typename ArrayCS>
TRowV compute(const ArrayCS &loc, int count, double maxDistInRange,
const TRowV &valOutOfRange, double distTolExact) const {
// query
static std::vector<double> dists;
static std::vector<TRowV> vals;
query(loc, count, dists, vals);
// average vaules by inverse distance
double invDistSum = 0.;
static DRowV valTarget;
valTarget.setZero();
int numInRange = 0;
for (int ip = 0; ip < dists.size(); ip++) {
// exactly on a leaf
if (dists[ip] < distTolExact) {
return vals[ip];
}
// out of range
if (dists[ip] > maxDistInRange) {
continue;
}
// weight by inverse distance
invDistSum += 1. / dists[ip];
valTarget += vals[ip].template cast<double>() / dists[ip];
numInRange++;
}
// out of range
if (numInRange == 0) {
return valOutOfRange;
}
// average and round
valTarget /= invDistSum;
if (std::is_integral<T>::value) {
valTarget = valTarget.array().round();
}
return valTarget.template cast<T>();
}
// compute scalar, only for V = 1
template <int VN = V, typename ArrayCS>
typename std::enable_if<VN == 1, T>::type
compute(const ArrayCS &loc, int count, double maxDistInRange,
T valOutOfRange, double distTolExact) const {
static TRowV oneVal;
oneVal(0) = valOutOfRange;
return compute(loc, count, maxDistInRange, oneVal, distTolExact)(0);
}
// size
int size() const {
return (int)mRTree.size();
}
// get all values
TMatXV_RM getAllValues() const {
// get values
std::vector<TRowV> vals;
std::transform(mRTree.begin(), mRTree.end(), std::back_inserter(vals),
[](const auto &leaf) {return leaf.second;});
// cast to matrix
TMatXV_RM mat(vals.size(), V);
for (int ip = 0; ip < vals.size(); ip++) {
mat.row(ip) = vals[ip];
}
return mat;
}
private:
// rtree
boost::geometry::index::rtree<RTreeLeaf,
boost::geometry::index::quadratic<16>> mRTree;
};
#endif /* RTreeND_hpp */
|
1a7f57fe458310623754eaffc9417f876e02c6c6 | 466f4cf9ed0a9535774d1d2e6fb7d3c53b53481a | /TP1/tests/MicroTest/Main.cpp | 94ad4cc6fcd77664b51d485051be233a55f29905 | [] | no_license | phtroa/LOG6302 | 70a504ee67abb5d741b60f3d1aa58ef77ac6cd7a | 27fdab7174a1c564af88eb46c4266dc1c31f4af6 | refs/heads/master | 2021-01-11T17:12:06.939925 | 2017-04-14T22:29:09 | 2017-04-14T22:29:09 | 79,737,781 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 622 | cpp | Main.cpp | /**************************************************
* Titre: Travail pratique #1 - Main.cpp
* Date: 25 aout 2012
* Auteur:
**************************************************/
#include "Infirmier.h"
int main()
{
//1- Creez un objet du type Infirmier à l'aide du constructeur par défaut
Infirmier infirmier;
//2- Modifiez le nom, le prenom et le nbChambre de cet objet à l'aide des méthodes de modification
infirmier.modifierNom('t');
infirmier.modifierPrenom('e');
infirmier.modifierNbChambre(10);
//3- constructeur par paramètre
Infirmier infirmier1('s', 't', 2);
return 0;
}
|
9ae786c8133e3e34e82e3f74076fce19415f7ab2 | 1e7a8245ee431fc33b96d071943cc0fce813a040 | /수학13 (baekjoon1652 - 누울 자리를 찾아라) .cpp | 9b18953728d96ab066e125a00dc3e710935e845a | [] | no_license | dlgkrwns213/algorithm | f3b685acb6e7e67b938154ee6f48ae69be45fc0a | 63951838356e09239d0a00155a981351d49a353a | refs/heads/master | 2020-11-28T08:43:18.955403 | 2020-03-06T14:40:52 | 2020-03-06T14:40:52 | 229,759,722 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 654 | cpp | 수학13 (baekjoon1652 - 누울 자리를 찾아라) .cpp | #include <iostream>
#include <cmath>
using namespace std;
int main()
{
int n;
cin >> n;
char room[n][n];
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
cin >> room[i][j];
int fcount = 0;
for(int i=0;i<n;i++)
{
bool x = true;
for(int j=1;j<n;j++)
{
if(room[i][j-1]=='.'&&room[i][j]=='.'&&x)
{
fcount++;
x = false;
}
if(room[i][j]=='X')
x = true;
}
}
int scount = 0;
for(int j=0;j<n;j++)
{
bool x = true;
for(int i=1;i<n;i++)
{
if(room[i-1][j]=='.'&&room[i][j]=='.'&&x)
{
scount++;
x = false;
}
if(room[i][j]=='X')
x = true;
}
}
cout << fcount << " " << scount;
return 0;
}
|
92af7fd385d0767296da3dff2d1290d6648e1554 | 6f57539fe08b91718fd1978aece1b44108b8ce6b | /E-HEALTH/build-Smart-med-Desktop_Qt_5_15_1_MinGW_32_bit-Debug/ui_modifier_visite.h | 6b67c35f6d6e86e19b32bd12db15806429785c4b | [] | no_license | mootez-gam/e-health-application-2a5 | 79eca54e7c4ed0bad781e5ee7fceb5bbfd8ac9a5 | 3798611c2b8aa10f37844a16278a527cc9fc0c72 | refs/heads/master | 2023-02-11T17:30:00.570272 | 2021-01-05T23:41:45 | 2021-01-05T23:41:45 | 317,281,588 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,683 | h | ui_modifier_visite.h | /********************************************************************************
** Form generated from reading UI file 'modifier_visite.ui'
**
** Created by: Qt User Interface Compiler version 5.15.1
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_MODIFIER_VISITE_H
#define UI_MODIFIER_VISITE_H
#include <QtCore/QVariant>
#include <QtWidgets/QApplication>
#include <QtWidgets/QDateEdit>
#include <QtWidgets/QDialog>
#include <QtWidgets/QLabel>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QTextEdit>
QT_BEGIN_NAMESPACE
class Ui_modifier_visite
{
public:
QLabel *label_10;
QDateEdit *date_naiss_patient;
QLineEdit *nom_patient_2;
QLineEdit *prenom_patient;
QLabel *label_11;
QLabel *label_14;
QTextEdit *diagnostic;
QLabel *label_9;
QLabel *label_13;
QTextEdit *observation;
QLabel *label;
QPushButton *pushButton;
QPushButton *pushButton_2;
QLineEdit *id;
QLabel *label_15;
void setupUi(QDialog *modifier_visite)
{
if (modifier_visite->objectName().isEmpty())
modifier_visite->setObjectName(QString::fromUtf8("modifier_visite"));
modifier_visite->resize(973, 822);
modifier_visite->setStyleSheet(QString::fromUtf8("background-color: rgb(29, 30, 48);"));
label_10 = new QLabel(modifier_visite);
label_10->setObjectName(QString::fromUtf8("label_10"));
label_10->setGeometry(QRect(20, 200, 131, 20));
date_naiss_patient = new QDateEdit(modifier_visite);
date_naiss_patient->setObjectName(QString::fromUtf8("date_naiss_patient"));
date_naiss_patient->setGeometry(QRect(270, 250, 221, 41));
date_naiss_patient->setStyleSheet(QString::fromUtf8("QDateEdit{\n"
"background-color:#25283b;\n"
"\n"
"border:1px solid rgb(61, 70, 86);\n"
"color:rgb(255, 255, 255);\n"
"padding-left:16px;\n"
"border:1px solid rgb(61, 70, 86);\n"
"border-top-right-radius:10px;\n"
"border-down-right-radius:10px;\n"
"}\n"
"QDateEdit:focus{\n"
"border: 1px solid rgb(180, 180, 180);\n"
"}"));
date_naiss_patient->setCalendarPopup(true);
nom_patient_2 = new QLineEdit(modifier_visite);
nom_patient_2->setObjectName(QString::fromUtf8("nom_patient_2"));
nom_patient_2->setGeometry(QRect(270, 130, 221, 41));
nom_patient_2->setStyleSheet(QString::fromUtf8("QLineEdit{\n"
"background-color:#25283b;\n"
"\n"
"border:1px solid rgb(61, 70, 86);\n"
"color:rgb(255, 255, 255);\n"
"padding-left:16px;\n"
"border:1px solid rgb(61, 70, 86);\n"
"border-top-right-radius:10px;\n"
"border-down-right-radius:10px;\n"
"}\n"
"QLineEdit:focus{\n"
"border: 1px solid rgb(180, 180, 180);\n"
"}"));
prenom_patient = new QLineEdit(modifier_visite);
prenom_patient->setObjectName(QString::fromUtf8("prenom_patient"));
prenom_patient->setGeometry(QRect(270, 190, 221, 41));
prenom_patient->setStyleSheet(QString::fromUtf8("QLineEdit{\n"
"background-color:#25283b;\n"
"\n"
"border:1px solid rgb(61, 70, 86);\n"
"color:rgb(255, 255, 255);\n"
"padding-left:16px;\n"
"border:1px solid rgb(61, 70, 86);\n"
"border-top-right-radius:10px;\n"
"border-down-right-radius:10px;\n"
"}\n"
"QLineEdit:focus{\n"
"border: 1px solid rgb(180, 180, 180);\n"
"}"));
label_11 = new QLabel(modifier_visite);
label_11->setObjectName(QString::fromUtf8("label_11"));
label_11->setGeometry(QRect(20, 260, 231, 20));
label_14 = new QLabel(modifier_visite);
label_14->setObjectName(QString::fromUtf8("label_14"));
label_14->setGeometry(QRect(30, 570, 131, 20));
diagnostic = new QTextEdit(modifier_visite);
diagnostic->setObjectName(QString::fromUtf8("diagnostic"));
diagnostic->setGeometry(QRect(270, 570, 621, 161));
diagnostic->setStyleSheet(QString::fromUtf8("QTextEdit{\n"
"background-color:#25283b;\n"
"\n"
"border:1px solid rgb(61, 70, 86);\n"
"color:rgb(255, 255, 255);\n"
"padding-left:16px;\n"
"border:1px solid rgb(61, 70, 86);\n"
"border-top-right-radius:10px;\n"
"border-down-right-radius:10px;\n"
"}\n"
"QTextEdit:focus{\n"
"border: 1px solid rgb(180, 180, 180);\n"
"}"));
label_9 = new QLabel(modifier_visite);
label_9->setObjectName(QString::fromUtf8("label_9"));
label_9->setGeometry(QRect(20, 140, 131, 20));
label_13 = new QLabel(modifier_visite);
label_13->setObjectName(QString::fromUtf8("label_13"));
label_13->setGeometry(QRect(20, 370, 131, 20));
observation = new QTextEdit(modifier_visite);
observation->setObjectName(QString::fromUtf8("observation"));
observation->setGeometry(QRect(270, 360, 621, 141));
observation->setStyleSheet(QString::fromUtf8("QTextEdit{\n"
"background-color:#25283b;\n"
"\n"
"border:1px solid rgb(61, 70, 86);\n"
"color:rgb(255, 255, 255);\n"
"padding-left:16px;\n"
"border:1px solid rgb(61, 70, 86);\n"
"border-top-right-radius:10px;\n"
"border-down-right-radius:10px;\n"
"}\n"
"QTextEdit:focus{\n"
"border: 1px solid rgb(180, 180, 180);\n"
"}"));
label = new QLabel(modifier_visite);
label->setObjectName(QString::fromUtf8("label"));
label->setGeometry(QRect(230, 20, 461, 31));
pushButton = new QPushButton(modifier_visite);
pushButton->setObjectName(QString::fromUtf8("pushButton"));
pushButton->setGeometry(QRect(310, 750, 121, 41));
pushButton->setStyleSheet(QString::fromUtf8("QPushButton { \n"
"border:none;\n"
"background-color:#0000FF;\n"
" background-position: left center;\n"
"\n"
" background-repeat: no-repeat;\n"
"\n"
" border-radius: 5px;\n"
"border:1px solid transparent;\n"
"color:rgb(255, 255, 255);\n"
" text-align: center;\n"
"\n"
"border-left:4px solid #0000FF;\n"
" \n"
"}\n"
"QPushButton:hover {\n"
" background-color:rgb(0, 0, 128);\n"
" \n"
"}\n"
"QPushButton:pressed {\n"
"border:2px solid rgb(0, 0, 128);\n"
"\n"
"\n"
"}\n"
""));
pushButton_2 = new QPushButton(modifier_visite);
pushButton_2->setObjectName(QString::fromUtf8("pushButton_2"));
pushButton_2->setGeometry(QRect(450, 750, 121, 41));
pushButton_2->setStyleSheet(QString::fromUtf8("QPushButton { \n"
"border:none;\n"
"background-color:#0000FF;\n"
" background-position: left center;\n"
"\n"
" background-repeat: no-repeat;\n"
"\n"
" border-radius: 5px;\n"
"border:1px solid transparent;\n"
"color:rgb(255, 255, 255);\n"
" text-align: center;\n"
"\n"
"border-left:4px solid #0000FF;\n"
" \n"
"}\n"
"QPushButton:hover {\n"
" background-color:rgb(0, 0, 128);\n"
" \n"
"}\n"
"QPushButton:pressed {\n"
"border:2px solid rgb(0, 0, 128);\n"
"\n"
"\n"
"}\n"
""));
id = new QLineEdit(modifier_visite);
id->setObjectName(QString::fromUtf8("id"));
id->setEnabled(false);
id->setGeometry(QRect(270, 80, 221, 31));
id->setStyleSheet(QString::fromUtf8("QLineEdit{\n"
"background-color:#25283b;\n"
"\n"
"border:1px solid rgb(61, 70, 86);\n"
"color:rgb(255, 255, 255);\n"
"padding-left:16px;\n"
"border:1px solid rgb(61, 70, 86);\n"
"border-top-right-radius:10px;\n"
"border-down-right-radius:10px;\n"
"}\n"
"QLineEdit:focus{\n"
"border: 1px solid rgb(180, 180, 180);\n"
"}"));
label_15 = new QLabel(modifier_visite);
label_15->setObjectName(QString::fromUtf8("label_15"));
label_15->setGeometry(QRect(20, 80, 131, 20));
retranslateUi(modifier_visite);
QMetaObject::connectSlotsByName(modifier_visite);
} // setupUi
void retranslateUi(QDialog *modifier_visite)
{
modifier_visite->setWindowTitle(QCoreApplication::translate("modifier_visite", "Modfier visite", nullptr));
label_10->setText(QCoreApplication::translate("modifier_visite", "<html><head/><body><p><span style=\" font-size:10pt; font-weight:600; color:#ffffff;\">Pr\303\250nom patient</span></p></body></html>", nullptr));
label_11->setText(QCoreApplication::translate("modifier_visite", "<html><head/><body><p><span style=\" font-size:10pt; font-weight:600; color:#ffffff;\">Date naissance du patient</span></p></body></html>", nullptr));
label_14->setText(QCoreApplication::translate("modifier_visite", "<html><head/><body><p><span style=\" font-size:10pt; font-weight:600; color:#ffffff;\">Diagnostic</span></p></body></html>", nullptr));
label_9->setText(QCoreApplication::translate("modifier_visite", "<html><head/><body><p><span style=\" font-size:10pt; font-weight:600; color:#ffffff;\">Nom patient</span></p></body></html>", nullptr));
label_13->setText(QCoreApplication::translate("modifier_visite", "<html><head/><body><p><span style=\" font-size:10pt; font-weight:600; color:#ffffff;\">Observation</span></p></body></html>", nullptr));
label->setText(QCoreApplication::translate("modifier_visite", "<html><head/><body><p align=\"center\"><span style=\" font-size:16pt; font-weight:600; text-decoration: underline; color:#ffffff;\">Modifier Visite</span></p></body></html>", nullptr));
pushButton->setText(QCoreApplication::translate("modifier_visite", "Valider ", nullptr));
pushButton_2->setText(QCoreApplication::translate("modifier_visite", "Annuler", nullptr));
label_15->setText(QCoreApplication::translate("modifier_visite", "<html><head/><body><p><span style=\" font-size:10pt; font-weight:600; color:#ffffff;\">ID_Visite</span></p></body></html>", nullptr));
} // retranslateUi
};
namespace Ui {
class modifier_visite: public Ui_modifier_visite {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_MODIFIER_VISITE_H
|
b9cc94213489339224052a9d09055f69bea70e1e | cc6c3efbdfe5879045ec472b56ca85ecf6b13dc4 | /recueil_d_exercices_inf2/chapitre_07/exercice_03/pays.cpp | 35cbe22e5f18ad504aad730c064db2c0948bc3a3 | [] | no_license | hakimbalestrieri/INF2 | 04ce0249ae0b38c861cb1a2b7f85249839274769 | bcb4ce6badbbd037b29eaf806b5b583ad583630b | refs/heads/master | 2020-04-28T11:09:29.413763 | 2018-06-22T08:38:33 | 2018-06-22T08:38:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 422 | cpp | pays.cpp | #include "pays.h"
Pays::Pays(string nom, double habitant, unsigned superficie)
:m_nom(nom), m_nbr_habitant(habitant), m_superficie(superficie){
}
const string &Pays::getNom() const {
return m_nom;
}
double Pays::getHabitant() const {
return m_nbr_habitant;
}
unsigned Pays::getSuperficie() const {
return m_superficie;
}
double Pays::densitePop() const {
return m_nbr_habitant/m_superficie;
}
|
e9712f82aa42016adf83d4afe8bf22c51d766ad8 | 4491ad1ff35de21f7c005d5035010b52d97e1e72 | /src/Behaviours/Rainy.h | c24f601b6f45378fc331d4c80ba4eb3a7873a773 | [] | no_license | dreac0nic/nimbus | fbdec6ec3c73a2490916d2b9a89c2e0e8becd036 | 0a0535a2b2455d3fb4f8b24b7eb6ac316e959f37 | refs/heads/master | 2021-01-13T01:37:20.088410 | 2014-05-16T16:13:03 | 2014-05-16T16:13:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,466 | h | Rainy.h | #ifndef NIMBUS_BEHAVIOUR_RAINY_H
#define NIMBUS_BEHAVIOUR_RAINY_H
#include "Behaviour.h"
namespace Nimbus
{
/** Rainy is a behaviour that will cause the applied
to an entity that will cause the entity to rain down
on the tiles below it.
*/
class Rainy:
public Behaviour
{
private:
/** Called by the constructors to initialize the behaviour. Anything that needs to
be duplicated among constructors should be put in here.
*/
void init();
public:
/** Default constructor, taking a world pointer.
@param type The type of Behaviour being constructed.
@param world A pointer to the game world.
@param eventSystem A pointer to the parent entity's event system.
*/
Rainy(BehaviourType type, World* world, EventSystem* eventSystem);
/** Constructor based of a set of initial settings.
@param type The type of Behaviour being constructed.
@param world A pointer to the game world.
@param intitializingSettings A map of settings used to construct the intial entity.
@param eventSystem A pointer to the parent entity's event system.
*/
Rainy(BehaviourType type, World* world, Ogre::ConfigFile::SettingsMultiMap* initializingSettings, EventSystem* eventSystem);
/** Constructor based on another Rainy behaviour.
@param other A pointer to the other Rainy behaviour.
@param world A pointer to the game world.
@param id The id of the parent entity holding this behaviour.
@param eventSystem A pointer to the parent entity's event system.
*/
Rainy(Rainy* other, World* world, int id, EventSystem* eventSystem);
/** Virtual destructor for destroying things. */
virtual ~Rainy(void);
// From: Behaviour
/** !! STUBBED !! Starts up the initial behaviour.*/
virtual void startup(void);
/** !! STUBBED !! Updates the behaviour, influencing the entity. */
virtual void update(void);
/** !! STUBBED !! Shuts down the behaviour, taking care of any major cleanup. */
virtual void shutdown(void);
/** Duplicates the entity using the settings given.
Currently merely returns a pointer given by the constructor.
*/
virtual Behaviour* clone(Ogre::ConfigFile::SettingsMultiMap* initializingSettings, EventSystem* eventSystem);
/** Duplicates the entity based on the current copy.
This is used to enable use of the prototype pattern.
*/
virtual Behaviour* clone(int id, EventSystem* eventSystem);
};
}
#endif |
90e953b78839a03a90728767687e3275e087acbf | b84a38aad619acf34c22ed6e6caa0f7b00ebfa0a | /Code/TootleCore/TTransform.h | 4fa3671a500a53a59818d75741e58e8ae84b6668 | [] | no_license | SoylentGraham/Tootle | 4ae4e8352f3e778e3743e9167e9b59664d83b9cb | 17002da0936a7af1f9b8d1699d6f3e41bab05137 | refs/heads/master | 2021-01-24T22:44:04.484538 | 2010-11-03T22:53:17 | 2010-11-03T22:53:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,334 | h | TTransform.h | /*
* TTransform.h
* TootleCore
*
* Created by Duane Bradbury on 27/10/2009.
* Copyright 2009 Tootle. All rights reserved.
*
*/
#pragma once
#include "TLTypes.h"
#include "TQuaternion.h"
#include "TLMaths.h"
#include "TArray.h"
#include "TRef.h"
// forward declarations
class TBinaryTree;
namespace TLMaths
{
class TTransform; // Transform class - encapsulates common usage of position, rotation and scale
}
class TLMaths::TTransform
{
public:
struct Properties
{
enum
{
Translation = TRef_Static(T,r,a,n,s),
ZTranslation = TRef_Static(Z,T,r,a,n),
Rotation = TRef_Static(R,o,t,a,t),
Scale = TRef_Static(S,c,a,l,e),
};
};
public:
TTransform() : m_Valid ( 0x0 ) { }
FORCEINLINE void SetScale(const float3& Scale) { m_Scale = Scale; SetScaleValid(); }
FORCEINLINE void SetTranslate(const float3& Translate) { m_Translate = Translate; SetTranslateValid(); }
FORCEINLINE void SetRotation(const TQuaternion& Rotation) { m_Rotation = Rotation; SetRotationValid(); }
FORCEINLINE u8 SetHasChanged(const TLMaths::TTransform& NewTransform); // set all elements and return what bits have changed
FORCEINLINE u8 SetScaleHasChanged(const float3& Scale); // set scale, return's the Transform bit that has changed
FORCEINLINE u8 SetTranslateHasChanged(const float3& Translate); // set translation, return's the Transform bit that has changed
FORCEINLINE u8 SetTranslateHasChanged(const float3& Translate,float MinChange); // set translation, return's the Transform bit that has changed
FORCEINLINE u8 SetRotationHasChanged(const TQuaternion& Rotation); // set rotation, return's the Transform bit that has changed
FORCEINLINE u8 SetRotationHasChanged(const TQuaternion& Rotation,float MinChange); // set rotation, return's the Transform bit that has changed
FORCEINLINE float3& GetTranslate() { return m_Translate; } // only use if HasTranslate()
FORCEINLINE float3& GetScale() { return m_Scale; } // only use if HasScale()
FORCEINLINE TQuaternion& GetRotation() { return m_Rotation; } // only use if HasRotation()
FORCEINLINE const float3& GetTranslate() const { Debug_Assert( HasTranslate(), "Translate accessed but is invalid"); return m_Translate; }
FORCEINLINE const float3& GetScale() const { Debug_Assert( HasScale(), "Scale accessed but is invalid"); return m_Scale; }
FORCEINLINE const TQuaternion& GetRotation() const { Debug_Assert( HasRotation(), "Rotation accessed but is invalid"); return m_Rotation; }
FORCEINLINE void SetInvalid() { m_Valid = 0x0; }
FORCEINLINE void SetTranslateInvalid() { m_Valid &= ~TLMaths_TransformBitTranslate; /*m_Translate.Set( 0.f, 0.f, 0.f );*/ }
FORCEINLINE void SetScaleInvalid() { m_Valid &= ~TLMaths_TransformBitScale; /*m_Scale.Set( 1.f, 1.f, 1.f );*/ }
FORCEINLINE void SetRotationInvalid() { m_Valid &= ~TLMaths_TransformBitRotation; /*m_Rotation.SetIdentity();*/ }
FORCEINLINE void SetTranslateValid() { m_Valid |= TLMaths_TransformBitTranslate; }
FORCEINLINE void SetTranslateValid(Bool Valid) { if ( Valid ) SetTranslateValid(); else SetTranslateInvalid(); }
FORCEINLINE void SetScaleValid() { m_Valid |= TLMaths_TransformBitScale; }
FORCEINLINE void SetRotationValid() { m_Valid |= TLMaths_TransformBitRotation; }
FORCEINLINE Bool HasAnyTransform() const { return (m_Valid != 0x0); }
FORCEINLINE Bool HasTranslate() const { return (m_Valid & TLMaths_TransformBitTranslate) != 0x0; }
FORCEINLINE Bool HasScale() const { return (m_Valid & TLMaths_TransformBitScale) != 0x0; }
FORCEINLINE Bool HasRotation() const { return (m_Valid & TLMaths_TransformBitRotation) != 0x0; }
FORCEINLINE u8 GetHasTransformBits() const { return m_Valid; }
// these Transform()'s are like matrix multiplies
void Transform(const TLMaths::TTransform& Trans); // transform this by another transform, this is like a local tranform, if Trans says "move right", it will move right, relative to the rotation. dumb faster method which doesn't do checks
u8 Transform_HasChanged(const TLMaths::TTransform& Trans); // transform this by another transform, this is like a local tranform, if Trans says "move right", it will move right, relative to the rotation. returns elements that have changed (slightly slower, but if your caller does much LESS work if nothing changed then use this)
void Transform(float3& Vector) const; // transform vector
void Transform(float2& Vector) const; // transform vector
void Untransform(float3& Vector) const; // untransform vector
void Untransform(float2& Vector) const; // untransform vector
void Invert(); // make an "untransform" from this transform. (inverts rotation, scale, trans)
template<typename TYPE> void Transform(TArray<TYPE>& VectorArray) const { for ( u32 i=0; i<VectorArray.GetSize(); i++ ) Transform( VectorArray[i] ); }
template<typename TYPE> void Untransform(TArray<TYPE>& VectorArray) const { for ( u32 i=0; i<VectorArray.GetSize(); i++ ) Untransform( VectorArray[i] ); }
// matrix style "adds"
void AddTransform(const TLMaths::TTransform& Trans); // Modify the transform values by another transform, Translates the translate, scales the scale, rotates the rotation. Doesn't multiply and rotate the translate etc
u8 AddTransform_HasChanged(const TLMaths::TTransform& Trans); // Modify the transform values by another transform, Translates the translate, scales the scale, rotates the rotation. Doesn't multiply and rotate the translate etc. returns elements that have changed (slightly slower, but if your caller does much LESS work if nothing changed then use this)
u8 ImportData(TBinaryTree& Data); // import transform data from binary data/message/etc- returns bitmask of the attributes that have changed
u8 ExportData(TBinaryTree& Data,u8 TransformBits=TLMaths_TransformBitAll) const; // export all our valid data to this binary data- can optionally make it only write certain attributes. Returns bits of the attributes written.
u8 ReplaceData(TBinaryTree& Data,u8 TransformBits=TLMaths_TransformBitAll) const; // export all our valid data to this binary data- can optionally make it only write certain attributes. Returns bits of the attributes written.
Bool operator==(const TLMaths::TTransform& Transform) const; // see if transforms are same
Bool operator!=(const TLMaths::TTransform& Transform) const; // see if transforms are different
private:
#ifdef _DEBUG
FORCEINLINE void Debug_Assert(Bool Condition,const char* pString) const { if ( !Condition ) Debug_Assert( pString ); }
#else
FORCEINLINE void Debug_Assert(Bool Condition,const char* pString) const { }
#endif
void Debug_Assert(const char* pString) const;
protected:
float3 m_Translate; // simple translation
float3 m_Scale; // scale
TQuaternion m_Rotation; // human-usable rotation
u8 m_Valid; // bit mask of validity. TRANSFORM_BIT_XXX - last for byte alignment
};
//--------------------------------------------------
// set all elements and return what bits have changed
//--------------------------------------------------
FORCEINLINE u8 TLMaths::TTransform::SetHasChanged(const TLMaths::TTransform& NewTransform)
{
u8 Changes = 0x0;
if ( NewTransform.HasScale() )
Changes |= SetScaleHasChanged( NewTransform.GetScale() );
if ( NewTransform.HasRotation() )
Changes |= SetRotationHasChanged( NewTransform.GetRotation() );
if ( NewTransform.HasTranslate() )
Changes |= SetTranslateHasChanged( NewTransform.GetTranslate() );
return Changes;
}
//--------------------------------------------------
// set scale, return's the Transform bit that has changed
//--------------------------------------------------
FORCEINLINE u8 TLMaths::TTransform::SetScaleHasChanged(const float3& Scale)
{
if ( !HasScale() || Scale != m_Scale )
{
SetScale( Scale );
return TLMaths_TransformBitScale;
}
else
return 0x0;
}
//--------------------------------------------------
// set translation, return's the Transform bit that has changed
//--------------------------------------------------
FORCEINLINE u8 TLMaths::TTransform::SetTranslateHasChanged(const float3& Translate)
{
if ( !HasTranslate() || Translate != m_Translate )
{
SetTranslate( Translate );
return TLMaths_TransformBitTranslate;
}
else
return 0x0;
}
//--------------------------------------------------
// set translation, return's the Transform bit that has changed
//--------------------------------------------------
FORCEINLINE u8 TLMaths::TTransform::SetTranslateHasChanged(const float3& Translate,float MinChange)
{
if ( !HasTranslate() )
{
SetTranslate( Translate );
return TLMaths_TransformBitTranslate;
}
else
{
if ( m_Translate.HasDifferenceMin( Translate, MinChange ) )
{
SetTranslate( Translate );
return TLMaths_TransformBitTranslate;
}
else
{
// very minor change - don't apply
return 0x0;
}
}
}
//--------------------------------------------------
// set rotation, return's the Transform bit that has changed
//--------------------------------------------------
FORCEINLINE u8 TLMaths::TTransform::SetRotationHasChanged(const TLMaths::TQuaternion& Rotation,float MinChange)
{
if ( !HasRotation() )
{
SetRotation( Rotation );
return TLMaths_TransformBitRotation;
}
else
{
if ( m_Rotation.GetData().HasDifferenceMin( Rotation.GetData(), MinChange ) )
{
SetRotation( Rotation );
return TLMaths_TransformBitRotation;
}
else
{
// very minor change - don't apply
return 0x0;
}
}
}
//--------------------------------------------------
// set rotation, return's the Transform bit that has changed
//--------------------------------------------------
FORCEINLINE u8 TLMaths::TTransform::SetRotationHasChanged(const TLMaths::TQuaternion& Rotation)
{
if ( !HasRotation() || Rotation != m_Rotation )
{
SetRotation( Rotation );
return TLMaths_TransformBitRotation;
}
else
return 0x0;
}
|
fb93bc6ddd5e67e7df8a5569b83ce0857a71d751 | e5aa88b3edf74ee36911828bbded9a8fcef61ef9 | /render.h | 94a9a1a48eedc2499dc5db27206cc57745d69544 | [
"MIT"
] | permissive | miklhh/mandelbrot3 | af78f2fa02d32a6952ad87830dbc9a9e32c4ce65 | bf4d3734a4a255f1b71624f4848c41b37ac6d1fb | refs/heads/master | 2020-04-10T19:11:52.665834 | 2018-12-11T03:42:07 | 2018-12-11T03:42:07 | 161,226,582 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,011 | h | render.h | /*
* Note: The filter function used for rendering the complex image has to be
* threadsafe. The renderer will perform multiple parallel calls to the filter
* function when rendering the image.
*/
#ifndef _RENDER_H
#define _RENDER_H
#include "threadpool/threadpool.h"
#include "mpfrc++/mpreal.h"
#include <complex>
#include <functional>
#include <string>
#include <SFML/Graphics/Image.hpp>
class Render
{
using Real = mpfr::mpreal;
using Complex = std::complex<Real>;
using Filter = std::function<sf::Color(Complex)>;
public:
Render(unsigned width, unsigned height, std::size_t threads, Filter filter);
// Rendering methods.
void store(const std::string &filename) const;
bool testComplete() const noexcept;
std::size_t getRemainingSegments() const noexcept;
void applyFilter(const Complex ¢er, Real width, Real height);
private:
sf::Image fractalImage{};
unsigned imageWidth;
unsigned imageHeight;
ThreadPool pool;
Filter filter;
};
#endif
|
0a293f7e687a0043309ed209db650f177a867efb | 08369613577450af45fca5d68e11df03a0ed2999 | /library/tools/commandlineconverter/source/main.cpp | 2f03c6196c23e7273a1d81641ed31ea887aa3e9d | [] | no_license | IreNox/tiki3 | 50e81a4a0dd120a37063f8cd6ea3045528350a5a | 2f29b3d7ab30217b3bd46d85ce8ec9032c1c1d54 | refs/heads/master | 2020-04-12T06:34:00.290425 | 2018-05-24T09:37:35 | 2018-05-24T09:37:35 | 12,142,108 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,069 | cpp | main.cpp |
#include "tiki/base/types.hpp"
#include "tiki/base/platform.hpp"
#include "tiki/toollibraries/iassetconverter.hpp"
int tiki::mainEntryPoint()
{
int retValue = 0;
//debug::breakOnAlloc( 1449 );
{
AssetConverterParamter parameters;
parameters.sourcePath = "../../../../../../content";
parameters.outputPath = "../../../../../../gamebuild";
parameters.forceRebuild = platform::hasArgument( "--rebuild" );
for( uint i = 0u; i < platform::getArguments().getCount(); ++i )
{
const string arg = platform::getArguments()[ i ];
if( arg.startsWith( "--content-dir=" ) )
{
parameters.sourcePath = arg.subString( getStringSize( "--content-dir=" ) );
}
else if( arg.startsWith( "--target-dir=" ) )
{
parameters.outputPath = arg.subString( getStringSize( "--target-dir=" ) );
}
}
IAssetConverter* pConverter = createAssetConverter();
pConverter->create( parameters );
retValue = pConverter->convertAll();
pConverter->dispose();
disposeAssetConverter( pConverter );
}
debug::dumpMemoryStats();
return retValue;
} |
82061f8605209a47f0aa98fd97266d43f0eac183 | 2f585eb12866e51ae19ab2d1e713138c7359de3f | /Lane_recognition/houghlines_curveransac.cpp | 7b88bcad5911f28414a77e7c996496b4495d3b0e | [] | no_license | Hitdahit/Opencv_project | a2dad8ac4d7e683c52bc0124af85adc509aac5d4 | 1220fb9a372038ecd1032bc1be0850e1bcb4a6d3 | refs/heads/master | 2020-12-12T21:23:41.038146 | 2020-02-27T12:02:01 | 2020-02-27T12:02:01 | 234,230,763 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,046 | cpp | houghlines_curveransac.cpp | //tried to capture lanes' points with HoughLinesP, since hsv sometimes cannot capture lane with inRange function.
//it captured points not so bad but failed to implement curve ransac
#include <opencv2/opencv.hpp>
#include <ctime>
#include <cmath>
using namespace std;
using namespace cv;
vector <Vec4i> lines;
vector<Point> curve;
vector<Point> left_line;
vector<Point> right_line;
Mat roi(Mat src)
{
Mat mask;
Scalar color;
int width = src.cols;
int height = src.rows;
Point vertices[1][4];
vertices[0][0] = Point(0, height);
vertices[0][1] = Point(0, height*2/5+10);
vertices[0][2] = Point(width, height*2/5+10);
vertices[0][3] = Point(width, height);
const Point* ppt[1] = { vertices[0] };
int npt[] = { 4 };
if (src.channels() == 3) {
mask = Mat::zeros(src.rows, src.cols, CV_8UC3);
color = Scalar(255, 255, 255);
}
else {
mask = Mat::zeros(src.rows, src.cols, CV_8UC1);
color = 255;
}
fillPoly(mask, ppt, npt, 1, color);
Mat ROI = mask & src;
return ROI;
}
Mat hough_lines(Mat src, int threshold=10)
{
src = roi(src);
Mat grayImg;
cvtColor(src, grayImg, COLOR_BGR2GRAY);
Mat gaussImg;
GaussianBlur(grayImg, gaussImg, Size(9, 9), 0.7);
Mat cannyImg;
Canny(gaussImg, cannyImg, 130, 400);
imshow("realcannyImg", cannyImg);
//threshold: r,세타 평면에서 몇개의 곡선이 한점에서 만날 때 직선으로 판단할지에 대한 최소값
HoughLinesP(cannyImg, lines, 1, CV_PI/180, threshold, 0.01, 40);
Mat dst = src.clone(); //오 이거 찾고 있었는데 개꿀팁
for (size_t i = 0; i < lines.size(); i++) {
Vec4i l = lines[i];
if (l[0] == l[2])continue;
double slope = (l[1] - l[3]) / double(l[0] - l[2]);
if (slope < 0.3 && slope>-0.4)continue;
else {
curve.push_back(Point(l[0], l[1]));
curve.push_back(Point(l[2], l[3]));
line(dst, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 1);
}
}
imshow("hough", dst);
return dst;
}
void cluster(int mid)
{
for (int i = 0; i < curve.size(); i++) {
if (curve[i].x < mid) left_line.push_back(curve[i]);
else right_line.push_back(curve[i]);
}
}
int* find_param(vector<Point> x, int p1, int p2, int p3)
{
float param[] = { //long long.....
x[p1].y * x[p1].y, x[p1].y, 1,
x[p2].y * x[p2].y, x[p2].y, 1,
x[p3].y * x[p3].y, x[p3].y, 1
};
float ans[] = {
x[p1].x,
x[p2].x,
x[p3].x
};
Mat param_mat = Mat(Size(3, 3), CV_32FC1, param);
Mat ans_mat = Mat(Size(1, 3), CV_32FC1, ans);
Mat new_param = param_mat.inv();
Mat answer = param_mat * ans_mat;
int a[3] = { answer.at<float>(0, 0), answer.at<float>(1, 0), answer.at<float>(2, 0) };
return a;
}
int* convex_ransac(vector<Point> x, int n, int t)
{
srand((unsigned int)time(NULL));
int c_max = 0;
int* param_max = NULL;
for (int i = 0; i < n; i++) {
int p1 = rand() % x.size(), p2 = rand() % x.size(), p3 = rand() % x.size();
int* param = find_param(x, p1, p2, p3);
//rm
//cout << param[0] << " " << param[1] << " " << param[2] << endl;
int c = 0;
for (int j = 0; j < x.size(); j++) {
//cout << abs(param[0] * x[j].y * x[j].y + param[1] * x[j].y + param[2] - x[j].x) << endl;
if (abs(param[0] * x[j].y * x[j].y - param[1] * x[j].y - param[2] - x[j].x) < t) {
c++;
}
//cout << c_max << endl;
if (c_max < c) {
c_max = c;
param_max = param;
}
}
}
return param_max;
}
void test_ransac(Mat src, int* param, int t)
{
cout << "Tlqkf";
for (int i = 0; i < src.rows; i++) {
for (int j = 0; j < src.cols; j++) {
if (param[0] * i * i + param[1]*i + param[3] <= j + t && param[0] * i * i + param[1] * i + param[3] >= j - t) {
//cout << "Tlqkf";
src.at<Vec3b>(i, j)[0] = 0;
src.at<Vec3b>(i, j)[1] = 0;
src.at<Vec3b>(i, j)[2] = 255;
}
}
}
imshow("ransac", src);
}
int main()
{
//경계선(contour)들을 찾는 과정.
Mat srcImg = imread("road13.jpg");
Mat res = srcImg.clone();
Mat hough = hough_lines(res);
cluster(srcImg.cols / 2);
int *left_fun = convex_ransac(left_line, 20, 1000);
int *right_fun = convex_ransac(right_line, 20, 1000);
test_ransac(res, left_fun, 1000);
//res = mask_roi(res, houghImg);
imshow("res", res);
waitKey();
return 0;
}
/*
Mat mask_roi(Mat src, Mat mask) //분리해낸 영상->mask 즉, 원본이미지에 분리할 영상을 시각화하는 함수
{
for (int i = src.rows / 2; i < src.rows; i++) { //roi로 자른 부분은 무시해도 됨.
//for(int i = 0; i < src.rows; i++){ //이거쓰면 더 멀리까지 보일순 있음 근데 엄한 흰색도 잡게됨.
for (int j = 0; j < src.cols; j++) {
if (mask.at<uchar>(i, j) > 200 || src.at<Vec3b>(i, j)[0] > 200
&& src.at<Vec3b>(i, j)[1] > 200
&&src.at<Vec3b>(i, j)[2] > 200) {
src.at<Vec3b>(i, j)[0] = 0;
src.at<Vec3b>(i, j)[1] = 0;
src.at<Vec3b>(i, j)[2] = 255;
}
}
}
return src;
}
/*
srcImg = roi(srcImg);
imshow("srcimg", srcImg);
int width = srcImg.cols;
int height = srcImg.rows;
Mat grayImg;
//color 이미지는 세세하게는 볼 수 있지만 불필요한 것까지 계산하게됨.
cvtColor(srcImg, grayImg, COLOR_BGR2GRAY);
imshow("grayImg", grayImg);
Mat gaussImg;
//blur는 이미지의 노이즈와 불필요한 gradient를 없애기 위해서 사용한다.
GaussianBlur(grayImg, gaussImg, Size(9, 9), 0.7);
imshow("gaussImg", gaussImg);
Mat cannyImg;
//1:3은 징그러운데..? 값을 키우니까 되네
//Canny(gaussImg, cannyImg, (gaussImg.rows + gaussImg.cols) / 4, (gaussImg.rows + gaussImg.cols) / 2);
Canny(gaussImg, cannyImg, 130, 400);
imshow("cannyImg", cannyImg);
//hough transform함수를 이용하여 contour들 중 직선을 검출
/*
hough공간이란 한마디로 image space위의 직선에 대하여
원점에서 수선의 발을 내렸을 때, 원점~ 수직의 발:p, :수선과 x축이 이루는 각:세타로
두어서 이를 2차원 평면의 점으로 표현한 것.
(직선의 파라미터를 사용하는 parameter space는 직선의 기울기가 무한대인 경우 표현할 수없기에 만듬.)/
*/
|
1425c10736cb34b884efd7e1acf97a1ac9579b11 | 1d3006443bdaeddb92a31908fddd61cd8bd04244 | /04_day/sp/sp.cpp | f6f49d6a62de439cfb8f188dcceca5a4c5caea45 | [] | no_license | ioacademy-jikim/android_framwork | ffa51e4aa47a4ef14d2ec36d49e371df3319ff14 | bf9c155a6d0d19852c102857705a73e7b904e1af | refs/heads/master | 2020-03-19T20:18:23.660633 | 2018-06-15T08:08:52 | 2018-06-15T08:08:52 | 136,895,520 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,425 | cpp | sp.cpp | #if 1
#include <stdio.h>
class RefBase
{
int mRefs;
public:
RefBase():mRefs(0) { printf("RefBase::RefBase()\n"); }
virtual ~RefBase() { printf("RefBase::~RefBase()\n"); }
void incStrong() {
printf("RefBase::incStrong() : mRefs=%d\n", ++mRefs);
}
void decStrong()
{
--mRefs;
printf("RefBase::decStrong() : mRefs=%d\n", mRefs);
if( mRefs == 0 )
delete this;
}
};
class AAA : public virtual RefBase
{
public:
AAA(){ printf("AAA::AAA()\n"); }
~AAA() { printf("AAA::~AAA()\n"); }
void foo() { printf("AAA::foo()\n"); }
};
template < typename T >
class sp
{
T *mPtr;
public:
sp( T *ptr):mPtr(ptr) {
printf("sp::sp(T)\n");
mPtr->incStrong();
}
sp( const sp<T> &r ) : mPtr(r.mPtr) {
printf("sp::sp(sp<T>)\n");
mPtr->incStrong();
}
~sp() {
printf("sp::~sp()\n");
mPtr->decStrong();
}
T * operator->()
{
return mPtr;
}
T operator*()
{
return *mPtr;
}
};
int main()
{
{
sp<AAA> p1 = new AAA;
sp<AAA> p2 = p1;
p1->foo();
p2->foo();
}
return 0;
}
#endif
#if 0
#include <stdio.h>
class AAA
{
int mRefs;
public:
AAA():mRefs(0) { printf("AAA::AAA()\n"); }
~AAA() { printf("AAA::~AAA()\n"); }
void foo() { printf("AAA::foo()\n"); }
void incStrong() {
printf("AAA::incStrong() : mRefs=%d\n", ++mRefs);
}
void decStrong()
{
--mRefs;
printf("AAA::decStrong() : mRefs=%d\n", mRefs);
if( mRefs == 0 )
delete this;
}
};
template < typename T >
class sp
{
T *mPtr;
public:
sp( T *ptr):mPtr(ptr) {
printf("sp::sp(T)\n");
mPtr->incStrong();
}
sp( const sp<T> &r ) : mPtr(r.mPtr) {
printf("sp::sp(sp<T>)\n");
mPtr->incStrong();
}
~sp() {
printf("sp::~sp()\n");
mPtr->decStrong();
}
T * operator->()
{
return mPtr;
}
T operator*()
{
return *mPtr;
}
};
int main()
{
{
sp<AAA> p1 = new AAA;
sp<AAA> p2 = p1;
p1->foo();
p2->foo();
}
return 0;
}
#endif
#if 0
#include <stdio.h>
class AAA
{
public:
AAA() { printf("AAA::AAA()\n"); }
~AAA() { printf("AAA::~AAA()\n"); }
void foo() { printf("AAA::foo()\n"); }
};
template < typename T >
class sp
{
T *mPtr;
static int mRefs;
public:
sp( T *ptr):mPtr(ptr) {
mRefs=1;
printf("sp::sp(T), mRefs=%d\n", mRefs);
}
sp( const sp<T> &r ) {
mRefs++;
printf("sp::sp(sp<T>), mRefs=%d\n", mRefs);
}
~sp() {
printf("sp::~sp()\n");
if( --mRefs == 0 )
delete mPtr;
}
T * operator->()
{
return mPtr;
}
T operator*()
{
return *mPtr;
}
};
template < typename T >
int sp<T>::mRefs = 0;
int main()
{
{
sp<AAA> p1 = new AAA;
sp<AAA> p2 = p1;
p1->foo();
p2->foo();
}
return 0;
}
#endif
#if 0
#include <stdio.h>
class AAA
{
public:
AAA() { printf("AAA::AAA()\n"); }
~AAA() { printf("AAA::~AAA()\n"); }
void foo() { printf("AAA::foo()\n"); }
};
template < typename T >
class sp
{
T *mPtr;
public:
sp( T *ptr):mPtr(ptr) { printf("sp::sp()\n"); }
~sp() {
printf("sp::~sp()\n");
delete mPtr;
}
T * operator->()
{
return mPtr;
}
T operator*()
{
return *mPtr;
}
};
int main()
{
{
sp<AAA> p1 = new AAA;
sp<AAA> p2 = p1;
p1->foo();
p2->foo();
}
return 0;
}
#endif
#if 0
#include <stdio.h>
class AAA
{
public:
AAA() { printf("AAA::AAA()\n"); }
~AAA() { printf("AAA::~AAA()\n"); }
void foo() { printf("AAA::foo()\n"); }
};
class BBB
{
public:
BBB() { printf("BBB::BBB()\n"); }
~BBB() { printf("BBB::~BBB()\n"); }
void foo() { printf("BBB::foo()\n"); }
};
template < typename T >
class sp
{
T *mPtr;
public:
sp( T *ptr):mPtr(ptr) { printf("sp::sp()\n"); }
~sp() {
printf("sp::~sp()\n");
delete mPtr;
}
T * operator->()
{
return mPtr;
}
T operator*()
{
return *mPtr;
}
};
int main()
{
{
sp<AAA> pa = new AAA;
pa->foo();
sp<BBB> pb = new BBB;
pb->foo();
}
return 0;
}
#endif
#if 0
#include <stdio.h>
class AAA
{
public:
AAA() { printf("AAA::AAA()\n"); }
~AAA() { printf("AAA::~AAA()\n"); }
void foo() { printf("AAA::foo()\n"); }
};
class sp
{
AAA *mPtr;
public:
sp( AAA *ptr):mPtr(ptr) { printf("sp::sp()\n"); }
~sp() {
printf("sp::~sp()\n");
delete mPtr;
}
AAA * operator->()
{
return mPtr;
}
AAA operator*()
{
return *mPtr;
}
};
int main()
{
{
sp pa = new AAA;
pa->foo(); // pa.operator->()->foo();
(*pa).foo();
}
return 0;
}
#endif
#if 0
#include <stdio.h>
class AAA
{
public:
AAA() { printf("AAA::AAA()\n"); }
~AAA() { printf("AAA::~AAA()\n"); }
void foo() { printf("AAA::foo()\n"); }
};
class sp
{
AAA *mPtr;
public:
sp( AAA *ptr):mPtr(ptr) { printf("sp::sp()\n"); }
~sp() {
printf("sp::~sp()\n");
delete mPtr;
}
};
int main()
{
{
//AAA* pa = new AAA;
//pa->foo();
sp pa = new AAA;
pa->foo(); // pa.operator->()->foo();
}
return 0;
}
#endif
#if 0
#include <stdio.h>
class AAA
{
public:
AAA() { printf("AAA::AAA()\n"); }
~AAA() { printf("AAA::~AAA()\n"); }
};
int main()
{
AAA *pa = new AAA;
//...
return 0;
}
#endif
#if 0
#include <stdio.h>
class AAA
{
public:
AAA() { printf("AAA::AAA()\n"); }
~AAA() { printf("AAA::~AAA()\n"); }
};
int main()
{
AAA *pa = new AAA;
delete pa;
//...
return 0;
}
#endif
#if 0
#include <stdio.h>
class AAA
{
public:
AAA() { printf("AAA::AAA()\n"); }
~AAA() { printf("AAA::~AAA()\n"); }
};
int main()
{
AAA aaa;
return 0;
}
#endif
|
cd9e859bb5f90dc06bdb0186758147e8ff9ebc83 | 5c7c80c2db94c3f33c9e0f388b75f8098dd64dfb | /MJMITSelection/src/ElectronLoader.cc | 29434c63f0c49d0cab1ad573cf00dd15d0b72281 | [] | no_license | violatingcp/BaconAnalyzer | 32bb9dc9348e60fe8a51e40ba6e08f56341d2ff7 | 56fd239dc28db5a2e439375f3419d8ec76b7bd6d | refs/heads/master | 2020-05-30T13:46:02.144704 | 2018-12-14T20:05:54 | 2018-12-14T20:05:54 | 23,576,559 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 9,771 | cc | ElectronLoader.cc | #include "../include/ElectronLoader.hh"
#include <cmath>
#include <iostream>
using namespace baconhep;
#define ELE_REFERENCE_IDMVA_CUT_BIN0 0.470 // pT<10, |eta|<0.8
#define ELE_REFERENCE_IDMVA_CUT_BIN1 0.004 // pT<10, 0.8<|eta|<1.479
#define ELE_REFERENCE_IDMVA_CUT_BIN2 0.295 // pT<10, |eta|>1.479
#define ELE_REFERENCE_IDMVA_CUT_BIN3 -0.340 // pT>10, |eta|<0.8
#define ELE_REFERENCE_IDMVA_CUT_BIN4 -0.650 // pT>10, 0.8<|eta|<1.479
#define ELE_REFERENCE_IDMVA_CUT_BIN5 0.600 // pT>10, |eta|>1.479
ElectronLoader::ElectronLoader(TTree *iTree) {
fElectrons = new TClonesArray("baconhep::TElectron");
iTree->SetBranchAddress("Electron", &fElectrons);
fElectronBr = iTree->GetBranch("Electron");
}
ElectronLoader::~ElectronLoader() {
delete fElectrons;
delete fElectronBr;
}
void ElectronLoader::reset() {
fNElectrons = 0;
fSelElectrons.clear();
}
void ElectronLoader::setupTree(TTree *iTree) {
reset();
fTree = iTree;
fTree->Branch("nelectrons",&fNElectrons,"fNElectrons/I");
}
void ElectronLoader::load(int iEvent) {
fElectrons ->Clear();
fElectronBr ->GetEntry(iEvent);
}
void ElectronLoader::fillVetoes(std::vector<TLorentzVector> &iVec) {
for(unsigned int i0 = 0; i0 < fSelElectrons.size(); i0++) {
TLorentzVector pVec;
pVec.SetPtEtaPhiM(fSelElectrons[i0]->pt,fSelElectrons[i0]->eta,fSelElectrons[i0]->phi,0.000511);
iVec.push_back(pVec);
}
}
bool ElectronLoader::selectElectrons(float iRho,std::vector<TLorentzVector> &iVetoes) {
reset();
int lCount = 0;
for (int i0 = 0; i0 < fElectrons->GetEntriesFast(); i0++) {
TElectron *pElectron = (TElectron*)((*fElectrons)[i0]);
if(pElectron->pt < 10) continue;
if(!passVeto(pElectron,iRho)) continue;
bool pMatch = false;
for(unsigned int i1 = 0; i1 < iVetoes.size(); i1++) {
double pDEta = pElectron->eta - iVetoes[i1].Eta();
double pDPhi = fabs(pElectron->phi - iVetoes[i1].Phi());
if(fabs(pDPhi) > 2.*TMath::Pi()-fabs(pDPhi)) pDPhi = 2.*TMath::Pi()-fabs(pDPhi);
if(sqrt(pDPhi*pDPhi+pDEta*pDEta) > 0.3) continue;
pMatch = true;
}
if(pMatch) continue;
bool lFill = false;
for( std::vector<TElectron*>::iterator pElectronIter = fSelElectrons.begin(); pElectronIter != fSelElectrons.end(); pElectronIter++) {
if((*pElectronIter)->pt > pElectron->pt) continue;
fSelElectrons.insert(pElectronIter,pElectron);
lFill = true;
break;
}
if(!lFill) fSelElectrons.push_back(pElectron);
//Limit this to the top 4 Jets
//if(fSelElectrons.size() > 3) fSelElectrons.pop_back();
lCount++;
}
fNElectrons = lCount;
if(fSelElectrons.size() == 0) return false;
return true;
}
bool ElectronLoader::vetoEle(float iRho) {
for (int i0 = 0; i0 < fElectrons->GetEntriesFast(); i0++) {
TElectron *pElectron = (TElectron*)((*fElectrons)[i0]);
if(passVeto(pElectron,iRho)) return true;
}
return false;
}
//POG based veto id
bool ElectronLoader::passVeto(const TElectron *electron, const float iRho) {
const double ECAL_GAP_LOW = 1.4442;
const double ECAL_GAP_HIGH = 1.566;
if((fabs(electron->scEta)>ECAL_GAP_LOW) && (fabs(electron->scEta)<ECAL_GAP_HIGH)) return false;
if(!(electron->typeBits & kEcalDriven)) return false;
if(fabs(electron->d0) > 0.02) return false;
if(fabs(electron->dz) > 0.1) return false;
// conversion rejection
if(electron->nMissingHits > 1) return false;
if(electron->isConv) return false;
double ea = getEffArea(electron->scEta);
// barrel/endcap dependent requirments
if(fabs(electron->scEta)<=ECAL_GAP_LOW) {
// barrel
double iso = electron->chHadIso03 + TMath::Max(electron->neuHadIso03 + electron->gammaIso03 - iRho*ea, 0.);
if(iso > 0.15*(electron->pt)) return false;
if(electron->sieie > 0.01) return false;
if(fabs(electron->dPhiIn) < 0.06) return false;
if(fabs(electron->dEtaIn) < 0.004) return false;
if(electron->hovere > 0.12) return false;
if(fabs(1.0-electron->eoverp) > 0.05*(electron->ecalEnergy)) return false;
} else {
// endcap
Double_t iso = electron->chHadIso03 + TMath::Max(electron->neuHadIso03 + electron->gammaIso03 - iRho*ea, 0.);
if(iso > 0.15*(electron->pt)) return false;
if(electron->sieie > 0.03) return false;
if(fabs(electron->dPhiIn) < 0.03) return false;
if(fabs(electron->dEtaIn) < 0.007) return false;
if(electron->hovere > 0.10) return false;
if(fabs(1.0-electron->eoverp) > 0.05*(electron->ecalEnergy)) return false;
}
return kTRUE;
}
//H=>ZZ Ele Id
bool ElectronLoader::passLoose(const TElectron *ele,float iRho) {
// missing hits cut for conversion rejection
if(ele->nMissingHits > 1) return false;
// impact parameters cuts
if(fabs(ele->sip3d) >= 100) return false;
if(fabs(ele->d0) >= 0.5) return false;
if(fabs(ele->dz) >= 1.0) return false;
int ptBin = (ele->ptHZZ4l > 10) ? 1 : 0;
int etaBin = -1;
if (fabs(ele->scEta) < 0.8) etaBin = 0;
else if(fabs(ele->scEta) < 1.479) etaBin = 1;
else etaBin = 2;
if(ptBin == 0 && etaBin == 0) return (ele->mva > ELE_REFERENCE_IDMVA_CUT_BIN0);
if(ptBin == 0 && etaBin == 1) return (ele->mva > ELE_REFERENCE_IDMVA_CUT_BIN1);
if(ptBin == 0 && etaBin == 2) return (ele->mva > ELE_REFERENCE_IDMVA_CUT_BIN2);
if(ptBin == 1 && etaBin == 0) return (ele->mva > ELE_REFERENCE_IDMVA_CUT_BIN3);
if(ptBin == 1 && etaBin == 1) return (ele->mva > ELE_REFERENCE_IDMVA_CUT_BIN4);
if(ptBin == 1 && etaBin == 2) return (ele->mva > ELE_REFERENCE_IDMVA_CUT_BIN5);
double lIso = ele->chHadIso04 + TMath::Max(ele->gammaIso04 + ele->neuHadIso04 - iRho*getEffArea(ele->scEta), 0.);
if(lIso/ele->pt > 0.4) return kFALSE;
return true;
}
//VBTF95? really?
bool ElectronLoader::passVBTF95(const TElectron *iEle) {
const double ECAL_GAP_LOW = 1.4442;
const double ECAL_GAP_HIGH = 1.566;
if((fabs(iEle->scEta)>ECAL_GAP_LOW) && (fabs(iEle->scEta)<ECAL_GAP_HIGH)) return false;
if(!(iEle->typeBits & kEcalDriven)) return false;
if(fabs(iEle->d0) > 0.02) return false;
if(fabs(iEle->dz) > 0.1) return false;
// conversion rejection
if(iEle->nMissingHits > 1) return false;
if(iEle->isConv) return false;
double lIso = iEle->chHadIso03 + iEle->neuHadIso03 + iEle->gammaIso03;
//std::cout << " here : " << iEle->pt << " -- " << lIso/iEle->pt << " - " << std::endl;
if(fabs(iEle->scEta) < ECAL_GAP_LOW && lIso/iEle->pt > 0.13) return false;
if(fabs(iEle->scEta) > ECAL_GAP_LOW && lIso/iEle->pt > 0.09) return false;
if(fabs(iEle->scEta) < ECAL_GAP_LOW && iEle->hovere > 0.15) return false;
if(fabs(iEle->scEta) > ECAL_GAP_LOW && iEle->hovere > 0.07) return false;
if(fabs(iEle->scEta) < ECAL_GAP_LOW && iEle->sieie > 0.01) return false;
if(fabs(iEle->scEta) > ECAL_GAP_LOW && iEle->sieie > 0.03) return false;
if(fabs(iEle->scEta) < ECAL_GAP_LOW && fabs(iEle->dPhiIn) > 0.8) return false;
if(fabs(iEle->scEta) > ECAL_GAP_LOW && fabs(iEle->dPhiIn) > 0.7) return false;
if(fabs(iEle->scEta) < ECAL_GAP_LOW && fabs(iEle->dEtaIn) > 0.007) return false;
if(fabs(iEle->scEta) > ECAL_GAP_LOW && fabs(iEle->dEtaIn) > 0.009) return false;
return true;
}
double ElectronLoader::getEffArea(double eta) {
if (fabs(eta) < 1.0) return 0.19;
else if(fabs(eta) < 1.479) return 0.25;
else if(fabs(eta) < 2.0) return 0.12;
else if(fabs(eta) < 2.2) return 0.21;
else if(fabs(eta) < 2.3) return 0.27;
else if(fabs(eta) < 2.4) return 0.44;
else return 0.52;
return 0.52;
}
std::vector<TLorentzVector> ElectronLoader::conversions() {
std::vector<TLorentzVector> lConv;
for (int i0 = 0; i0 < fElectrons->GetEntriesFast(); i0++) {
TElectron *pElectron = (TElectron*)((*fElectrons)[i0]);
if(pElectron->nMissingHits == 0) continue;
if(!pElectron->isConv) continue;
TLorentzVector pVec;
pVec.SetPtEtaPhiM(pElectron->scEt,pElectron->scEta,pElectron->scPhi,0.000511);
lConv.push_back(pVec);
}
return lConv;
}
std::vector<TLorentzVector> ElectronLoader::nonConversions() {
std::vector<TLorentzVector> lConv;
for (int i0 = 0; i0 < fElectrons->GetEntriesFast(); i0++) {
TElectron *pElectron = (TElectron*)((*fElectrons)[i0]);
if(pElectron->nMissingHits != 0 || pElectron->isConv) continue;
TLorentzVector pVec;
pVec.SetPtEtaPhiM(pElectron->scEt,pElectron->scEta,pElectron->scPhi,0.000511);
lConv.push_back(pVec);
}
return lConv;
}
//bool ElectronLoader::passTight(TElectron *iElectron) {
// return kTRUE;
//}
|
c3a362424be9506cab240fe4e641fe9c18cec219 | a5a99f646e371b45974a6fb6ccc06b0a674818f2 | /DetectorDescription/Core/src/Sphere.cc | 32c167f7eb86bb55405fe5288c30239c8752e443 | [
"Apache-2.0"
] | permissive | cms-sw/cmssw | 4ecd2c1105d59c66d385551230542c6615b9ab58 | 19c178740257eb48367778593da55dcad08b7a4f | refs/heads/master | 2023-08-23T21:57:42.491143 | 2023-08-22T20:22:40 | 2023-08-22T20:22:40 | 10,969,551 | 1,006 | 3,696 | Apache-2.0 | 2023-09-14T19:14:28 | 2013-06-26T14:09:07 | C++ | UTF-8 | C++ | false | false | 1,822 | cc | Sphere.cc | #include "DetectorDescription/Core/interface/Sphere.h"
#include "DataFormats/Math/interface/GeantUnits.h"
#include <cmath>
#include <ostream>
#include <vector>
#include "DetectorDescription/Core/interface/DDSolidShapes.h"
#include "DetectorDescription/Core/interface/Solid.h"
using namespace geant_units;
using namespace geant_units::operators;
DDI::Sphere::Sphere(
double innerRadius, double outerRadius, double startPhi, double deltaPhi, double startTheta, double deltaTheta)
: Solid(DDSolidShape::ddsphere) {
p_.emplace_back(innerRadius);
p_.emplace_back(outerRadius);
p_.emplace_back(startPhi);
p_.emplace_back(deltaPhi);
p_.emplace_back(startTheta);
p_.emplace_back(deltaTheta);
}
void DDI::Sphere::stream(std::ostream& os) const {
os << " innerRadius=" << convertMmToCm(p_[0]) << " outerRadius=" << convertMmToCm(p_[1])
<< " startPhi=" << convertRadToDeg(p_[2]) << " deltaPhi=" << convertRadToDeg(p_[3])
<< " startTheta=" << convertRadToDeg(p_[4]) << " deltaTheta=" << convertRadToDeg(p_[5]);
}
double DDI::Sphere::volume() const {
double volume(0.);
if (std::fabs(p_[3]) <= 2._pi && std::fabs(p_[5]) <= piRadians) {
volume = std::fabs((p_[1] * p_[1] * p_[1] - p_[0] * p_[0] * p_[0]) / 3. *
(std::cos(p_[4] + p_[5]) - std::cos(p_[4])) * p_[3]);
} else if (std::fabs(p_[3]) <= 2._pi && std::fabs(p_[5]) > piRadians) {
volume = std::fabs((p_[1] * p_[1] * p_[1] - p_[0] * p_[0] * p_[0]) / 3. *
(std::cos(p_[4] + p_[5] - 180._deg) - std::cos(p_[4])) * p_[3]);
} else if (std::fabs(p_[3]) > 2._pi && std::fabs(p_[5]) <= piRadians) {
volume = std::fabs((p_[1] * p_[1] * p_[1] - p_[0] * p_[0] * p_[0]) / 3. *
(std::cos(p_[4] + p_[5]) - std::cos(p_[4])) * (p_[3] - p_[2]));
}
return volume;
}
|
83bfe1821357d674d6f4220f689f39fa4ce915b4 | ee2fc30bde48b274142340ce2aae8caccdf6b3b3 | /sling/nlp/wiki/wiki.h | b8f973a1302077647951053b4e064542057ab4ce | [
"Apache-2.0"
] | permissive | savkov/sling | 54c97ce44a1bc1842f353d719aee612147daae91 | f4e51c8077833205cb5786721dc0a9e85cf890a2 | refs/heads/master | 2020-04-08T16:26:09.915319 | 2018-11-26T14:02:13 | 2018-11-26T14:02:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,015 | h | wiki.h | // Copyright 2017 Google 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.
#ifndef SLING_NLP_WIKI_WIKI_H_
#define SLING_NLP_WIKI_WIKI_H_
#include <string>
#include "sling/base/types.h"
#include "sling/frame/object.h"
#include "sling/frame/store.h"
namespace sling {
namespace nlp {
// Wikidata object types.
enum WikidataType {
WIKIDATA_ITEM = 0,
WIKIDATA_PROPERTY = 1,
WIKIDATA_LEXEME = 2,
};
// Wikipedia name spaces.
enum WikipediaNamespace {
WIKIPEDIA_NAMESPACE_MAIN = 0,
WIKIPEDIA_NAMESPACE_USER = 2,
WIKIPEDIA_NAMESPACE_WIKIPEDIA = 4,
WIKIPEDIA_NAMESPACE_FILE = 6,
WIKIPEDIA_NAMESPACE_MEDIAWIKI = 8,
WIKIPEDIA_NAMESPACE_TEMPLATE = 10,
WIKIPEDIA_NAMESPACE_HELP = 12,
WIKIPEDIA_NAMESPACE_CATEGORY = 14,
};
// Alias sources.
enum AliasSource {
SRC_GENERIC = 0,
SRC_WIKIDATA_LABEL = 1,
SRC_WIKIDATA_ALIAS = 2,
SRC_WIKIPEDIA_TITLE = 3,
SRC_WIKIPEDIA_REDIRECT = 4,
SRC_WIKIPEDIA_ANCHOR = 5,
SRC_WIKIPEDIA_DISAMBIGUATION = 6,
SRC_WIKIDATA_FOREIGN = 7,
SRC_WIKIDATA_NATIVE = 8,
SRC_WIKIDATA_DEMONYM = 9,
};
static const int kNumAliasSources = 10;
extern const char *kAliasSourceName[kNumAliasSources];
// Utility functions for Wikidata and Wikipedia.
class Wiki {
public:
// Split title into name and disambiguation.
static void SplitTitle(const string &title,
string *name,
string *disambiguation);
// Return id for Wikipedia page.
static string Id(const string &lang, const string &title);
static string Id(const string &lang,
const string &prefix,
const string &title);
// Return URL for Wikipedia page.
static string URL(const string &lang, const string &title);
// Language priority order.
static const char *language_priority[];
};
// Filter for auxiliary items. The auxiliary items in the knowledge base are
// items that are used infrequently and are stored in a separate knowledge
// base store.
class AuxFilter {
public:
// Initialize auxiliary item filter.
void Init(Store *store);
// Check if item is an auxiliary item.
bool IsAux(const Frame &frame);
private:
// Auxiliary item types.
HandleSet aux_types_;
// Names.
Names names_;
Name n_wikipedia_{names_, "/w/item/wikipedia"};
Name n_instanceof_{names_, "P31"};
};
} // namespace nlp
} // namespace sling
#endif // SLING_NLP_WIKI_WIKI_H_
|
fcdf1406878d3d5070ff08d7448f5b234e0f1f79 | bffb5982a832677386a198732bb486b874bda302 | /ATCCSOrm/src/at60plan.cpp | e11b6d2b44fa705bada7f52fbcb26ff9df8616c8 | [] | no_license | iamgeniuswei/ATCCS | 4e28b6f0063c1f4089b447fa3d00299350c1e416 | 5261b26fbf99cebd0909f06a7bb1bcf9e47cb5e2 | refs/heads/master | 2021-01-24T07:42:10.596733 | 2017-06-05T01:34:40 | 2017-06-05T01:34:40 | 93,351,146 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 399 | cpp | at60plan.cpp | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: at60plan.cpp
* Author: lenovo
*
* Created on May 15, 2017, 5:06 PM
*/
#include "at60plan.h"
at60plan::at60plan() {
}
at60plan::at60plan(const at60plan& orig) {
}
at60plan::~at60plan() {
}
|
6d219b23c841b3a09a99b57de21837432a6b9924 | 8528860bfa4e51d5fb5d35464a321fa88b27abc3 | /meta-heuristics-1.2/lib/edaFitContinue.cpp | b6c71326c2c1bf2f06e2a16b109aa52a56e50f24 | [] | no_license | mohcicin/metaheuristics | d9fd28bac54f401d89cd0800136b9a7c65a6fd32 | a112870b98626e35545f89a44898baadf0dba43d | refs/heads/master | 2021-05-01T07:54:56.274119 | 2016-04-26T00:51:17 | 2016-04-26T00:51:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 874 | cpp | edaFitContinue.cpp | #include "edaFitContinue.h"
edaFitContinue::edaFitContinue() {}
edaFitContinue::~edaFitContinue() {}
edaFitContinue::edaFitContinue(double _fitness)
: fitness (_fitness)
{
}
edaContinue *edaFitContinue::clone() const
{
return new edaFitContinue(fitness);
}
void edaFitContinue::init() {
edaContinue::init();
}
bool edaFitContinue::check(const edaSolutionList &list)
{
edaContinue::check(list);
// double best = -1e10;
// list.evaluate()
// for(unsigned int i = 0; i <list.size(); i++) {
// double value = list[i]->evaluate();
// best = value > best ? value : best;
// if( best > fitness )
// return false;
// }
return list.evaluate() < fitness;
}
void edaFitContinue::Serialize(edaBuffer &buf, bool pack)
{
edaContinue::Serialize(buf, pack);
if (pack)
{
buf.Pack(&fitness, 1);
}
else
{
buf.UnPack(&fitness, 1);
}
}
|
887595f215d7fc84b8e68a37dfa3b5c298692a0a | 36b9decf14d266d6babaf1c44085c2ba869c03ce | /Remnant-main/Remnant/SDK/Widget_ItemInfo_RangedWeapon_parameters.h | 92d0be65fd3d56614dfbfbde04e5a7ae6bdb3b3e | [] | no_license | RoryGlenn/RemnantLootSwitcher | 6e309a7b2b7bac88a166b552b640c830b863eb2d | 85c4cb6839b7c0f60cf8143c571d64ca12439a63 | refs/heads/master | 2022-12-29T08:47:15.713546 | 2020-10-23T22:01:45 | 2020-10-23T22:01:45 | 305,910,400 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,934 | h | Widget_ItemInfo_RangedWeapon_parameters.h | #pragma once
// Name: Remnant, Version: 6
#include "../SDK.h"
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
/*!!HELPER_DEF!!*/
/*!!DEFINE!!*/
namespace UFT
{
//---------------------------------------------------------------------------
// Parameters
//---------------------------------------------------------------------------
// Function Widget_ItemInfo_RangedWeapon.Widget_ItemInfo_RangedWeapon_C.CheckPulseUpgrade
struct UWidget_ItemInfo_RangedWeapon_C_CheckPulseUpgrade_Params
{
};
// Function Widget_ItemInfo_RangedWeapon.Widget_ItemInfo_RangedWeapon_C.HasInputFocus
struct UWidget_ItemInfo_RangedWeapon_C_HasInputFocus_Params
{
bool Out; // (Parm, OutParm, ZeroConstructor, IsPlainOldData, NoDestructor)
};
// Function Widget_ItemInfo_RangedWeapon.Widget_ItemInfo_RangedWeapon_C.EndEquipMod
struct UWidget_ItemInfo_RangedWeapon_C_EndEquipMod_Params
{
};
// Function Widget_ItemInfo_RangedWeapon.Widget_ItemInfo_RangedWeapon_C.BeginEquipMod
struct UWidget_ItemInfo_RangedWeapon_C_BeginEquipMod_Params
{
};
// Function Widget_ItemInfo_RangedWeapon.Widget_ItemInfo_RangedWeapon_C.OnSetItem
struct UWidget_ItemInfo_RangedWeapon_C_OnSetItem_Params
{
};
// Function Widget_ItemInfo_RangedWeapon.Widget_ItemInfo_RangedWeapon_C.Construct
struct UWidget_ItemInfo_RangedWeapon_C_Construct_Params
{
};
// Function Widget_ItemInfo_RangedWeapon.Widget_ItemInfo_RangedWeapon_C.OnSelectItem_Event_1
struct UWidget_ItemInfo_RangedWeapon_C_OnSelectItem_Event_1_Params
{
int ItemID; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
struct FInspectInfo InspectInfo; // (BlueprintVisible, BlueprintReadOnly, Parm)
bool Comparing; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
struct FInspectInfo InspectInfoCompare; // (BlueprintVisible, BlueprintReadOnly, Parm)
bool ShowIngredients; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor)
struct FRecipeInfo Recipe; // (BlueprintVisible, BlueprintReadOnly, Parm)
class UClass* ItemBP; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
};
// Function Widget_ItemInfo_RangedWeapon.Widget_ItemInfo_RangedWeapon_C.OnItemAction_Event_1
struct UWidget_ItemInfo_RangedWeapon_C_OnItemAction_Event_1_Params
{
TEnumAsByte<EInventoryAction> Action; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
int ItemID; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
};
// Function Widget_ItemInfo_RangedWeapon.Widget_ItemInfo_RangedWeapon_C.BndEvt__Widget_ButtonEx_K2Node_ComponentBoundEvent_0_OnAdvButtonClickedEvent__DelegateSignature
struct UWidget_ItemInfo_RangedWeapon_C_BndEvt__Widget_ButtonEx_K2Node_ComponentBoundEvent_0_OnAdvButtonClickedEvent__DelegateSignature_Params
{
class UWidget* Widget; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
};
// Function Widget_ItemInfo_RangedWeapon.Widget_ItemInfo_RangedWeapon_C.EndInputFocus
struct UWidget_ItemInfo_RangedWeapon_C_EndInputFocus_Params
{
};
// Function Widget_ItemInfo_RangedWeapon.Widget_ItemInfo_RangedWeapon_C.BndEvt__ModList_K2Node_ComponentBoundEvent_1_OnUpdateCustomEquipment__DelegateSignature
struct UWidget_ItemInfo_RangedWeapon_C_BndEvt__ModList_K2Node_ComponentBoundEvent_1_OnUpdateCustomEquipment__DelegateSignature_Params
{
};
// Function Widget_ItemInfo_RangedWeapon.Widget_ItemInfo_RangedWeapon_C.DoAction
struct UWidget_ItemInfo_RangedWeapon_C_DoAction_Params
{
};
// Function Widget_ItemInfo_RangedWeapon.Widget_ItemInfo_RangedWeapon_C.BndEvt__Button_137_K2Node_ComponentBoundEvent_2_OnButtonClickedEvent__DelegateSignature
struct UWidget_ItemInfo_RangedWeapon_C_BndEvt__Button_137_K2Node_ComponentBoundEvent_2_OnButtonClickedEvent__DelegateSignature_Params
{
};
// Function Widget_ItemInfo_RangedWeapon.Widget_ItemInfo_RangedWeapon_C.BndEvt__Button_137_K2Node_ComponentBoundEvent_3_OnButtonHoverEvent__DelegateSignature
struct UWidget_ItemInfo_RangedWeapon_C_BndEvt__Button_137_K2Node_ComponentBoundEvent_3_OnButtonHoverEvent__DelegateSignature_Params
{
};
// Function Widget_ItemInfo_RangedWeapon.Widget_ItemInfo_RangedWeapon_C.BndEvt__Button_137_K2Node_ComponentBoundEvent_4_OnButtonHoverEvent__DelegateSignature
struct UWidget_ItemInfo_RangedWeapon_C_BndEvt__Button_137_K2Node_ComponentBoundEvent_4_OnButtonHoverEvent__DelegateSignature_Params
{
};
// Function Widget_ItemInfo_RangedWeapon.Widget_ItemInfo_RangedWeapon_C.Init
struct UWidget_ItemInfo_RangedWeapon_C_Init_Params
{
};
// Function Widget_ItemInfo_RangedWeapon.Widget_ItemInfo_RangedWeapon_C.ApplySizeModifier
struct UWidget_ItemInfo_RangedWeapon_C_ApplySizeModifier_Params
{
int Mod; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
};
// Function Widget_ItemInfo_RangedWeapon.Widget_ItemInfo_RangedWeapon_C.ExecuteUbergraph_Widget_ItemInfo_RangedWeapon
struct UWidget_ItemInfo_RangedWeapon_C_ExecuteUbergraph_Widget_ItemInfo_RangedWeapon_Params
{
int EntryPoint; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
};
// Function Widget_ItemInfo_RangedWeapon.Widget_ItemInfo_RangedWeapon_C.OnSubAction__DelegateSignature
struct UWidget_ItemInfo_RangedWeapon_C_OnSubAction__DelegateSignature_Params
{
struct FText ActionLabel; // (BlueprintVisible, BlueprintReadOnly, Parm)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
|
ba95bec892ce0d2060a4554e1daf03fd52d881d2 | c33f21036e8aeae3962e790b126ac5393a1ed441 | /AHOI2013-difference.cpp | 6d86f1c03c0ce6cf8129b57c2fb84de04d1f8785 | [] | no_license | BillYang2016/Codes | c840b310d0127421dae96c42f6e826b26ce8cd7f | 47e7c3ad2caa1ef1f62e56cd146a684309868e27 | refs/heads/master | 2021-01-24T12:04:26.562717 | 2021-01-11T11:32:45 | 2021-01-11T11:32:45 | 123,115,120 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,930 | cpp | AHOI2013-difference.cpp | #include<algorithm>
#include<iostream>
#include<iomanip>
#include<cstring>
#include<cstdlib>
#include<climits>
#include<vector>
#include<cstdio>
#include<cmath>
#include<queue>
using namespace std;
typedef long long LL;
inline const int Get_Int() {
int num=0,bj=1;
char x=getchar();
while(x<'0'||x>'9') {
if(x=='-')bj=-1;
x=getchar();
}
while(x>='0'&&x<='9') {
num=num*10+x-'0';
x=getchar();
}
return num*bj;
}
const int maxn=500005,maxc=26;
int n;
struct SuffixAutomaton {
int cnt,root,last;
int next[maxn*2],Max[maxn*2],end_pos[maxn*2],Bucket[maxn*2],top[maxn*2];
int child[maxn*2][maxc];
SuffixAutomaton() {
cnt=0;
root=last=newnode(0);
}
int newnode(int val) {
cnt++;
next[cnt]=0;
Max[cnt]=val;
memset(child[cnt],0,sizeof(child[cnt]));
return cnt;
}
void insert(int data) {
int p=last,u=newnode(Max[last]+1);
last=u;
end_pos[u]=1;
for(; p&&!child[p][data]; p=next[p])child[p][data]=u;
if(!p)next[u]=root;
else {
int old=child[p][data];
if(Max[old]==Max[p]+1)next[u]=old;
else {
int New=newnode(Max[p]+1);
copy(child[old],child[old]+maxc,child[New]);
next[New]=next[old];
next[u]=next[old]=New;
for(; child[p][data]==old; p=next[p])child[p][data]=New;
}
}
}
void build(string s) {
for(auto x:s)insert(x-'a');
}
void topsort() {
for(int i=1; i<=cnt; i++)Bucket[Max[i]]++;
for(int i=1; i<=cnt; i++)Bucket[i]+=Bucket[i-1];
for(int i=1; i<=cnt; i++)top[Bucket[Max[i]]--]=i;
}
LL dp() {
LL ans=(LL)(n-1)*n*(n+1)/2;
for(int i=cnt; i>=1; i--) {
int now=top[i],fa=next[now];
ans-=2ll*end_pos[now]*end_pos[fa]*Max[fa];
if(fa)end_pos[fa]+=end_pos[now];
}
return ans;
}
} sam;
char s[maxn];
int main() {
scanf("%s",s);
n=strlen(s);
reverse(s,s+n);
sam.build(s);
sam.topsort();
printf("%lld\n",sam.dp());
return 0;
} |
87a9d5547785ffe4eed579e89f058912c9a5e8dc | f06394eb49f055ce3a51c93eb56249350d64ddbb | /tests/generation-tests/xpand3/expression/RealLiteral.cpp | 01710900d7c23b1512ff97d6177ca52b24202ac0 | [] | no_license | happyj/e4c | a3c6eb523cf1d346a73b138c45a6cdfc83766710 | 59646a43d50749ddfc983e9a1f3a3c70fc5eb218 | refs/heads/master | 2020-03-26T05:15:09.814976 | 2014-02-22T11:20:12 | 2014-02-22T11:20:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 676 | cpp | RealLiteral.cpp |
#include "RealLiteral.hpp"
#include <xpand3/expression/ExpressionPackage.hpp>
using namespace xpand3::expression;
/*PROTECTED REGION ID(xpand3::expression::RealLiteral include) START*/
/*PROTECTED REGION END*/
RealLiteral::RealLiteral()
{
/*PROTECTED REGION ID(RealLiteral constructor) START*/
/*PROTECTED REGION END*/
}
RealLiteral::~RealLiteral()
{
/*PROTECTED REGION ID(RealLiteral destructor) START*/
/*PROTECTED REGION END*/
}
/*PROTECTED REGION ID(xpand3::expression::RealLiteral implementation) START*/
/*PROTECTED REGION END*/
ecore::EClass_ptr RealLiteral::eClassImpl() const
{
return ExpressionPackage::_instance()->getRealLiteral();
}
|
aa651337075d1c6bd9ecb25d5ffd029e66babec7 | c69321e4bc0a15fdfed31ed96a5ca7ea05701063 | /ViennaTool/src/TSelectionAnalyzer.cc | 6bbfb74f4bd677a0da26137c8d336ac02aed11d9 | [] | no_license | jandrejk/FakeFactor | 1a49ebb7911e0dca1b641a2b59637983be0989c3 | f31f45d010e6f98b990c93adc1f81bd2f7f925c7 | refs/heads/FF_DeepTau_2016_v15 | 2022-10-30T09:55:59.965845 | 2020-03-25T10:07:28 | 2020-03-25T10:07:28 | 160,835,469 | 0 | 3 | null | 2020-06-25T09:12:04 | 2018-12-07T14:41:03 | C++ | UTF-8 | C++ | false | false | 6,993 | cc | TSelectionAnalyzer.cc | #include "ViennaTool/interface/TSelectionAnalyzer.h"
#include <iostream>
#include <sstream>
using namespace std;
TSelectionAnalyzer::TSelectionAnalyzer()
{
}
TSelectionAnalyzer::~TSelectionAnalyzer()
{
}
void TSelectionAnalyzer::calcBgEstSim(const TString preselection,const Int_t mode,const Int_t categoryMode,const TString output, const Int_t cuts)
{
TH1D *tightSR,*looseSR;//,*allSR;
TString suff="";
if (mode & _SS ) suff=" (SS) ";
if (mode & MT) {
tightSR = new TH1D("hh_t_mt","Tight events in SR"+suff,nbins_mt,hist_min_mt,hist_max_mt);
looseSR = new TH1D("hh_l_mt","Loose events in SR"+suff,nbins_mt,hist_min_mt,hist_max_mt);
}
else if (mode & MVIS && mode & _AI) {
tightSR = new TH1D("hh_t_mvis","Tight events in SR"+suff,w_mvis_n,w_mvis_v);
looseSR = new TH1D("hh_l_mvis","Loose events in SR"+suff,w_mvis_n,w_mvis_v);
}
else if (mode & MVIS) {
tightSR = new TH1D("hh_t_mvis","Tight events in SR"+suff,nbins_mvis,hist_min_mvis,hist_max_mvis);
looseSR = new TH1D("hh_l_mvis","Loose events in SR"+suff,nbins_mvis,hist_min_mvis,hist_max_mvis);
}
else if (mode & PT) {
tightSR = new TH1D("hh_t_pt","Tight events in SR"+suff,nbins_pt,hist_min_pt,hist_max_pt);
looseSR = new TH1D("hh_l_pt","Loose events in SR"+suff,nbins_pt,hist_min_pt,hist_max_pt);
}
else if (mode & ETA2) {
tightSR = new TH1D("hh_t_eta","Tight events in SR"+suff,nbins_eta,hist_min_eta,hist_max_eta);
looseSR = new TH1D("hh_l_eta","Loose events in SR"+suff,nbins_eta,hist_min_eta,hist_max_eta);
}
else if (mode & SVFIT) {
tightSR = new TH1D("hh_t_svfit","Tight events in SR"+suff,nbins_svfit,hist_min_svfit,hist_max_svfit);
looseSR = new TH1D("hh_l_svfit","Loose events in SR"+suff,nbins_svfit,hist_min_svfit,hist_max_svfit);
}
else if (mode & LEPPT) {
tightSR = new TH1D("hh_t_lepPt","Tight events in SR"+suff,w_lepPt_n,w_lepPt_v);
looseSR = new TH1D("hh_l_lepPt","Loose events in SR"+suff,w_lepPt_n,w_lepPt_v);
}
else {
std::cout<<"ERROR: no valid mode given. Exiting TNtupleAnalyzer::calcBgEstSim..."<<std::endl;
return;
}
loadFile(preselection,"Events");
TString cutstring = this->getSRCutString(mode, categoryMode);
if ( DEBUG ) std::cout << "SR CUT STRING: " << cutstring << endl;
TString s_selval, s_histoname = "";
if (mode & MVIS) { s_selval = "alltau_mvis[tau_iso_ind]"; s_histoname = "mvis"; }
else if (mode & PT) { s_selval = "alltau_pt[tau_iso_ind]"; s_histoname = "pt"; }
else if (mode & MT) { s_selval = "alltau_mt[tau_iso_ind]"; s_histoname = "mt"; }
else if (mode & ETA2) { s_selval = "alltau_eta[tau_iso_ind]"; s_histoname = "eta"; }
else if (mode & LEPPT) {s_selval = "lep_pt"; s_histoname = "lepPt"; }
else if (mode & SVFIT) {s_selval = "alltau_svfit[tau_iso_ind]"; s_histoname = "svfit"; }
event_s->fChain->Draw(s_selval + ">>hh_t_"+s_histoname+"", "weight_sf * "+cutstring + "*" + this->getWPCutString("tight"), "goff");
if ( DEBUG ) {
cout << "hh_t_"<<s_histoname << " DONE " << endl;
cout << "full cut string tight region : "<<"weight_sf * " << cutstring << "*" << this->getWPCutString("tight") <<endl;
}
event_s->fChain->Draw(s_selval + ">>hh_l_"+s_histoname+"", "weight_sf * "+cutstring + "*" + this->getWPCutString("loose"), "goff");
if ( DEBUG ) {
cout << "hh_l_"<<s_histoname << " DONE " << endl;
cout << "full cut string loose region : " <<"weight_sf * " <<cutstring << "*" << this->getWPCutString("loose") <<endl;
}
TFile f(output,"recreate");
if (DEBUG) {
std::cout<<"output: "<<output<<std::endl;
std::cout << "***************** SR HISTO STATS ********************" << std::endl;
std::cout << "No of events passing tight criteria: " << tightSR->GetEntries() << std::endl;
std::cout << "No of events passing loose criteria: " << looseSR->GetEntries() << std::endl;
}
tightSR->Write();
looseSR->Write();
f.Close();
delete tightSR;delete looseSR;
delete tchain;delete event_s;
}
void TSelectionAnalyzer::getCRHisto(TString preselection,Int_t mode,TString output)
{
loadFile(preselection,"Events");
const Int_t FI=1;
TH1D* tightCR,*looseCR;
if (mode & MT) {
tightCR = new TH1D("hh_t_mt","",FI*nbins_mt,hist_min_mt,hist_max_mt);
looseCR = new TH1D("hh_l_mt","",FI*nbins_mt,hist_min_mt,hist_max_mt);
}
else if (mode & MVIS) {
tightCR = new TH1D("hh_t_mvis","",w_mvis_n,w_mvis_v);
looseCR = new TH1D("hh_l_mvis","",w_mvis_n,w_mvis_v);
}
else if (mode & PT) {
tightCR = new TH1D("hh_t_pt","",FI*nbins_pt,hist_min_pt,hist_max_pt);
looseCR = new TH1D("hh_l_pt","",FI*nbins_pt,hist_min_pt,hist_max_pt);
}
else if (mode & ETA2) {
tightCR = new TH1D("hh_t_eta","",FI*nbins_eta,hist_min_eta,hist_max_eta);
looseCR = new TH1D("hh_l_eta","",FI*nbins_eta,hist_min_eta,hist_max_eta);
}
else if (mode & MUISO) {
tightCR = new TH1D("hh_t_muiso","",w_muiso_n,w_muiso_v);
looseCR = new TH1D("hh_l_muiso","",w_muiso_n,w_muiso_v);
}
else if (mode & LEPPT) {
tightCR = new TH1D("hh_t_lepPt","",w_lepPt_n,w_lepPt_v);
looseCR = new TH1D("hh_l_lepPt","",w_lepPt_n,w_lepPt_v);
}
else {
std::cout<<"ERROR: no valid mode given. Exiting TNtupleAnalyzer::getCRHisto..."<<std::endl;
return;
}
TString cutstring = this->getCRCutString(mode);
if ( DEBUG ) std::cout << "CR CUT STRING: " << cutstring << endl;
TString s_selval, s_histoname = "";
if (mode & MVIS) { s_selval = "alltau_mvis[0]"; s_histoname = "mvis"; }
else if (mode & MUISO) {s_selval = "lep_iso"; s_histoname = "muiso"; }
else if (mode & PT) { s_selval = "alltau_pt[0]"; s_histoname = "pt"; }
else if (mode & MT) { s_selval = "alltau_mt[0]"; s_histoname = "mt"; }
else if (mode & ETA2) { s_selval = "alltau_eta[0]"; s_histoname = "eta"; }
else if (mode & LEPPT) {s_selval = "lep_pt"; s_histoname = "lepPt"; }
event_s->fChain->Draw(s_selval + ">>hh_t_"+s_histoname+"", "weight_sf * "+cutstring + "*" + this->getWPCutString("tight"), "goff");
if ( DEBUG ) cout << "hh_t_"<<s_histoname << " DONE " << endl;
event_s->fChain->Draw(s_selval + ">>hh_l_"+s_histoname+"", "weight_sf * "+cutstring + "*" + this->getWPCutString("loose"), "goff");
if ( DEBUG ) cout << "hh_l_"<<s_histoname << " DONE " << endl;
if (DEBUG) {
std::cout << "***************** CR HISTO STATS ********************" << std::endl;
std::cout << "No of events passing tight criteria: " << tightCR->GetEntries() << std::endl;
std::cout << "No of events passing loose criteria: " << looseCR->GetEntries() << std::endl;
}
TFile f1(output,"recreate");
tightCR->Write();
looseCR->Write();
if (DEBUG) {std::cout<<"WRITING output: " << output << std::endl;}
f1.Close();
delete tightCR;delete looseCR;
delete event_s;delete tchain;
}
|
362110ea059a59cc5f183c59bab56ded76a02a57 | 717eed82b6c2301f670444cea24abbe9efa87818 | /mywidget.h | 19db62128176446c16fe03547572fe20ef590df1 | [] | no_license | xiehii/PlayControl | dc3ce53d72c2d670db0c40d24e95152492f6af12 | 7c1870fbdf217e87f21e47c424f36967771bd2b4 | refs/heads/master | 2022-11-05T23:15:31.716021 | 2020-06-18T01:32:15 | 2020-06-18T01:32:15 | 270,562,863 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 391 | h | mywidget.h | #ifndef MYWIDGET_H
#define MYWIDGET_H
#include <QWidget>
#include <QKeyEvent>
class MyWidget : public QWidget
{
Q_OBJECT
public:
explicit MyWidget(QWidget *parent = nullptr);
signals:
public slots:
void mouseDoubleClickEvent(QMouseEvent *event);
void keyPressEvent(QKeyEvent *event);
void keyReleaseEvent(QKeyEvent *e);
};
#endif // MYWIDGET_H
|
20d1f1fd498a3a8ce7dc47abd1b5c032c55336d3 | 22d862f350920a884187c60b6db2f953b05087f1 | /directed_graph_algorithms.cpp | dd846d01466d1b25cb77aae79fd80994ee2d4549 | [] | no_license | Initiator-Z/Directed-Graph | 3ed82b7109fa0619564f391f3ff554b7a31517c0 | ab326523646af469b5034ae558aa2137880309a9 | refs/heads/main | 2023-06-15T04:04:35.095750 | 2021-07-10T03:51:22 | 2021-07-10T03:51:22 | 312,147,987 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,624 | cpp | directed_graph_algorithms.cpp | #include <iostream>
#include <vector>
#include <queue>
#include <stack>
#include <unordered_set>
#include <unordered_map>
#include <set>
#include <array>
#include <list>
#include <forward_list>
#include <deque>
#include <map>
#include <cstddef>
#include <string>
#include <utility>
#include <algorithm>
#include <limits>
#include <optional>
#include <exception>
#include <stdexcept>
#include "directed_graph.h"
using namespace std;
template <typename T>
void test_topo(directed_graph<T>& g){
vector<vertex<T>> result = topological_sort(g);
for(vertex<T> vt : result){
cout << vt.id << endl;
}
}
/*
* Computes the shortest distance from u to v in graph g.
* The shortest path corresponds to a sequence of vertices starting from u and ends at v,
* which has the smallest total weight of edges among all possible paths from u to v.
*/
template <typename T>
vector<vertex<T>> shortest_path(directed_graph<T>& g, int& u_id, int& v_id) {
vector<vertex<T>> path;
T inf = 99999;
int size = g.max_id();
// Store vertices with its predecessor in the path
// predecessor of i is predecessor[i]
int predecessor[size];
// contain remaining vertices' id and edge weights
vector<pair<T, int>> remain;
// Initialise vertices' costs to reach
for(int i = 0; i <= size; i++){
if(i != u_id && g.contains(i)){
if(g.adjacent(u_id, i)){
remain.push_back(make_pair(g.get_edge(u_id, i), i));
predecessor[i] = u_id;
}
else{
remain.push_back(make_pair(inf, i));
}
}
}
int current = u_id;
path.push_back(g.retrieve(current));
// Continuously set each vertices as current to update costs until all vertices were set
while(!remain.empty()){
T current_weight;
// find vertex in the remaining vector with smallest distance and select as current
sort(remain.begin(), remain.end());
current = remain[0].second;
current_weight = remain[0].first;
remain.erase(remain.begin());
// Update weights
for(int i = 0; i < remain.size(); i++){
if(g.adjacent(current, remain[i].second)){
if(remain[i].first > current_weight + g.get_edge(current, remain[i].second)){
remain[i].first = current_weight + g.get_edge(current, remain[i].second);
predecessor[remain[i].second] = current;
}
}
}
}
// Starting from destination vertex, trace back to source vertex
int last = v_id;
while(last != u_id){
path.emplace(path.begin()+1, g.retrieve(last));
last = predecessor[last];
}
return path;
}
/*
* Computes the strongly connected components of the graph.
* A strongly connected component is a subset of the vertices
* such that for every pair u, v of vertices in the subset,
* v is reachable from u and u is reachable from v.
*/
// Stack keep track of visited vertices
stack<int> s;
// Attributes of vertices to trace visiting order and low values
int dfn[999] = {0}, low[999], dfn_cnt = 0;
// Check if a vertex is in stack
set<int> in_stack;
// Resulting SCCs
set<set<int>> all_scc;
template <typename T>
vector<vector<vertex<T>>> strongly_connected_components(directed_graph<T>& g) {
vector<vector<vertex<T>>> results;
vector<vertex<T>> vertices = g.get_vertices();
// Perform Tarjans' algorithm on all vertices in the graph if not included in a SCC already
for(vertex<T> vt : vertices){
if(!dfn[vt.id]){
tarjan(vt.id, g);
}
}
for(set<int> st : all_scc){
vector<vertex<T>> vector;
for(int i : st){
vector.push_back(g.retrieve(i));
}
results.push_back(vector);
}
return results;
}
template <typename T>
void tarjan(int u, directed_graph<T>& g){
low[u] = dfn[u] = ++dfn_cnt;
s.push(u); // Add u to stack
in_stack.insert(u); // mark u as visited
vector<vertex<T>> neighbours = g.get_neighbours(u);
for(vertex<T> vt : neighbours){
if(!dfn[vt.id]){// v not visited
tarjan(vt.id, g);
low[u] = min(low[u], low[vt.id]);
}
else if(in_stack.find(vt.id) != in_stack.end()){// v visited and in stack
low[u] = min(low[u], dfn[vt.id]);
}
}
if(dfn[u] == low[u]){// u is root of a scc
set<int> scc;
while(s.top() != u){// add all vertices above u in stack to a scc
scc.insert(s.top());
in_stack.erase(s.top());
s.pop();
}
scc.insert(s.top());
in_stack.erase(s.top());
s.pop();
all_scc.insert(scc);
}
}
/*
* Computes a topological ordering of the vertices.
* For every vertex u in the order, and any of its
* neighbours v, v appears later in the order than u.
* You will be given a DAG as the argument.
*/
// Stack keep track of topological orders
stack<int> topo_order;
// Set marking visited vertices
set<int> marked;
template <typename T>
vector<vertex<T>> topological_sort(directed_graph<T>& g) {
vector<vertex<T>> vertices = g.get_vertices();
// Visit vertices if not marked already
for(vertex<T> vt : vertices){
while(marked.find(vt.id) == marked.end()){
visit(vt.id, g);
}
}
vector<vertex<T>> order;
while(!topo_order.empty()){
order.push_back(g.retrieve(topo_order.top()));
topo_order.pop();
}
return order;
}
template <typename T>
void visit(int u, directed_graph<T>& g){
// If u already marked, return
if(marked.find(u) != marked.end()){
return;
}
// If u not marked, recursively visit its neighbours
vector<vertex<T>> neighbours = g.get_neighbours(u);
for(vertex<T> vt : neighbours){
visit(vt.id, g);
}
// Mark u and push to the stack
marked.insert(u);
topo_order.push(u);
}
/*
* Computes the lowest cost-per-person for delivery over the graph.
* u is the source vertex, which send deliveries to all other vertices.
* vertices denote cities; vertex weights denote cities' population;
* edge weights denote the fixed delivery cost between cities, which is irrelevant to
* the amount of goods being delivered.
*/
template <typename T>
T low_cost_delivery(directed_graph<T>& g, int& u_id) {
T population = 0;
T cost = 0;
vector<vertex<T>> vertices = g.get_vertices();
// set containing vertices already delivered goods to.
set<int> delivered;
// Calculate total populations of cities to be delivered
for(vertex<T> vt : vertices){
if(vt.id != u_id && g.reachable(u_id, vt.id)){
population += vt.weight;
}
}
// set contains cities been considered in planning next delivery.
// If this set is identical with 'delivered' set at certain step,
// dynamic programming for planning deliveries is completed.
set<int> considered;
// Store potential cities to be delivered along with costs.
vector<pair<T, int>> neighbour_weights;
// Initialise dynamic programming by adding source city to delivered set.
delivered.insert(u_id);
// Continue planning for optimum delivery cost while not all
// cities are considered as departure.
while(considered.size() != delivered.size()){
for(int ct_del : delivered){
// Get neighbours of current departure city.
// next lowest cost destination must by one of the neighbours.
considered.insert(ct_del);
vector<vertex<T>> neighbours = g.get_neighbours(ct_del);
// If a neighbour is never delivered to, deliver to that city.
for(vertex<T> vt : neighbours){
if(delivered.find(vt.id) == delivered.end()){
neighbour_weights.push_back(make_pair(g.get_edge(ct_del, vt.id), vt.id));
}
// If a neighbour has been delivered to, check if the new route offers lower cost, and also
// whether the neighbour comes earlier than current city in topological sequence(if yes cannot replace route).
else{
for(int i = 0; i < neighbour_weights.size(); i++){
if(neighbour_weights[i].second == vt.id && neighbour_weights[i].first > g.get_edge(ct_del, vt.id) && !g.reachable(neighbour_weights[i].second, ct_del)){
cost -= neighbour_weights[i].first;
delivered.erase(neighbour_weights[i].second);
neighbour_weights.push_back(make_pair(g.get_edge(ct_del, vt.id), vt.id));
}
}
}
}
// Sort all possible cities to be delivered and deliver to destination with lowest cost.
sort(neighbour_weights.begin(), neighbour_weights.end());
for(int i = 0; i < neighbour_weights.size(); i++){
if(delivered.find(neighbour_weights[i].second) == delivered.end()){
delivered.insert(neighbour_weights[i].second);
cost += neighbour_weights[i].first;
break;
}
}
}
}
return cost / population;
} |
9263d1b3614082c0fedf67d87814b70724c181ee | 988c8499c97c83099f193e6c0450636716fe685d | /question/cpp/include/main.cpp | 65ab3086eb7be19eda5bb5f2f6b1f50ef07ca89f | [] | no_license | ueumd/clang | febfd9b1567eaf021b69f4c807afafa6228f6b2a | a98a6eddb41647a22b5d148c2dd523ef13985885 | refs/heads/master | 2021-02-22T16:50:30.072296 | 2020-04-24T12:41:22 | 2020-04-24T12:41:22 | 247,006,609 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 414 | cpp | main.cpp | #include<iostream>
using namespace std;
/*
cpp 从上往下编译,要提前使用类,就要先声明类
类的声明,拓展作用域,只能创建指针或引用
A *p;
A &p;
A p;错误
*/
class A;
class B;
A *p;
void go(A &a) {
}
class A {
public:
//B b; //要先声明
B *b; //只能是指针或引用
};
class B {
public:
// 正确 A类在B类前定义
A *a;
A aa;
};
void main() {
cin.get();
} |
23eda59e5bf565ae428950e37e49b7495de8a71f | 697ece97d86013137f38b6049a6755a7fec6e693 | /code/tools/editor/DAE2Nebula3Writer.cc | c2f48d27cc92b10d66d28c8030d1afe450766b6f | [] | no_license | Chinamming/nebuladevice3 | 6ace3c9fd97632ed43743e8eb7fce151f976a906 | 1180cec07aff77da1e9f97cedbcfbf5b56c3630d | refs/heads/master | 2021-01-10T18:17:09.958301 | 2012-11-23T19:55:13 | 2012-11-23T19:55:13 | 47,537,441 | 3 | 2 | null | null | null | null | GB18030 | C++ | false | false | 18,595 | cc | DAE2Nebula3Writer.cc | //------------------------------------------------------------------------------
// DAE2NebulaWriter.cc
// (C) 2010 Dengwenyi
//------------------------------------------------------------------------------
#include "stdneb.h"
#include "DAE2Nebula3Writer.h"
#include "COLLADASaxFWLLoader.h"
#include "COLLADAFWRoot.h"
#include "COLLADAFWGeometry.h"
#include "COLLADAFWNode.h"
#include "COLLADAFWVisualScene.h"
#include "COLLADAFWInstanceGeometry.h"
#include "COLLADAFWMesh.h"
#include "COLLADAFWRotate.h"
#include "COLLADAFWScale.h"
#include "COLLADAFWTranslate.h"
#include "COLLADAFWMatrix.h"
#include "COLLADAFWSkinControllerData.h"
#include "Math/COLLADABUMathMatrix4.h"
#include "io/ioserver.h"
#include "io/stream.h"
#include "modelnodewriter.h"
namespace Models
{
using namespace COLLADAFW;
using namespace IO;
using namespace ToolkitUtil;
using namespace Characters;
//--------------------------------------------------------------------
Nebula3Writer::Nebula3Writer( const COLLADABU::URI& inputFile, const COLLADABU::URI& outputFile )
: mInputFile(inputFile)
, mOutputFile(outputFile)
{
}
//--------------------------------------------------------------------
Nebula3Writer::~Nebula3Writer()
{
}
//--------------------------------------------------------------------
bool Nebula3Writer::write()
{
COLLADASaxFWL::Loader loader;
COLLADAFW::Root root(&loader, this);
// Load scene graph
if ( !root.loadDocument(mInputFile.toNativePath()) )
return false;
return true;
}
//--------------------------------------------------------------------
void Nebula3Writer::cancel( const String& errorMessage )
{
}
//--------------------------------------------------------------------
void Nebula3Writer::start()
{
}
//--------------------------------------------------------------------
void Nebula3Writer::finish()
{
this->makeDirectXFriendly();
Util::String modelFilename = MODEL_PRE_FIXED;
IoServer::Instance()->CreateDirectory(URI(modelFilename));
modelFilename.Append(mOutputFile.getPathFile().c_str());
this->writeModel(modelFilename);
}
//--------------------------------------------------------------------
bool Nebula3Writer::isCoords()
{
return this->mUpAxisType == COLLADAFW::FileInfo::Y_UP;
}
//--------------------------------------------------------------------
bool Nebula3Writer::writeGlobalAsset( const COLLADAFW::FileInfo* asset )
{
//n_printf("writeGlobalAsset......\n");
const COLLADAFW::FileInfo::Unit& unit = asset->getUnit ();
mUpAxisType = asset->getUpAxisType ();
mUnit = unit.getLinearUnitUnit ();
return true;
}
//--------------------------------------------------------------------
bool Nebula3Writer::writeVisualScene( const COLLADAFW::VisualScene* visualScene )
{
this->importVisualScene(visualScene);
return true;
}
//--------------------------------------------------------------------
bool Nebula3Writer::writeScene( const COLLADAFW::Scene* scene )
{
//n_printf("writeScene......\n");
return true;
}
//--------------------------------------------------------------------
bool Nebula3Writer::writeLibraryNodes( const COLLADAFW::LibraryNodes* libraryNodes )
{
//n_printf("writeLibraryNodes......\n");
return true;
}
//--------------------------------------------------------------------
bool Nebula3Writer::writeMaterial( const COLLADAFW::Material* material )
{
// Check if the current material is already imported.
const COLLADAFW::UniqueId& materialId = material->getUniqueId ();
const COLLADAFW::UniqueId& effectId = material->getInstantiatedEffect();
this->mMaterialDatas.Add(materialId,effectId);
return true;
}
//--------------------------------------------------------------------
bool Nebula3Writer::writeEffect( const COLLADAFW::Effect* effect )
{
// Check if the current effect is already imported.
const COLLADAFW::UniqueId& effectId = effect->getUniqueId ();
const COLLADAFW::CommonEffectPointerArray& commonEffects = effect->getCommonEffects ();
size_t numCommonEffects = commonEffects.getCount ();
if( numCommonEffects !=1) return false;
COLLADAFW::EffectCommon* commonEffect = commonEffects [0];
const COLLADAFW::EffectCommon::ShaderType& shaderType = commonEffect->getShaderType ();
EffectData effectData;
switch ( shaderType )
{
case COLLADAFW::EffectCommon::SHADER_BLINN:
case COLLADAFW::EffectCommon::SHADER_CONSTANT:
case COLLADAFW::EffectCommon::SHADER_PHONG:
case COLLADAFW::EffectCommon::SHADER_LAMBERT:
{
const COLLADAFW::ColorOrTexture& diffuse = commonEffect->getDiffuse ();
if ( diffuse.isTexture () )
{
// Get the texure and the current shader attribute.
const COLLADAFW::Texture& texture = diffuse.getTexture ();
effectData.diffMapId = texture.getTextureMapId();
effectData.diffSamplerId = texture.getSamplerId();
}
const COLLADAFW::ColorOrTexture& emission = commonEffect->getEmission ();
if ( emission.isTexture () )
{
const COLLADAFW::Texture& texture = emission.getTexture ();
effectData.emsvMapId = texture.getTextureMapId();
effectData.emsvSamplerId = texture.getSamplerId();
}
const COLLADAFW::ColorOrTexture& specular = commonEffect->getSpecular();
if ( specular.isTexture () )
{
const COLLADAFW::Texture& texture = specular.getTexture ();
effectData.specMapId = texture.getTextureMapId();
effectData.specSamplerId = texture.getSamplerId();
}
}
break;
case COLLADAFW::EffectCommon::SHADER_UNKNOWN:
default:
// Import as a lambert shader.
n_warning("Unknown shader type!\n");
break;
}
const COLLADAFW::SamplerPointerArray& samplers = commonEffect->getSamplerPointerArray ();
size_t numSamplers = samplers.getCount ();
for ( size_t samplerId=0; samplerId<numSamplers; ++samplerId )
{
COLLADAFW::Sampler* sampler = samplers [samplerId];
const COLLADAFW::UniqueId& imageId = sampler->getSourceImage ();
COLLADAFW::Sampler::SamplerType samplerType = sampler->getSamplerType ();
if( samplerType !=COLLADAFW::Sampler::SAMPLER_TYPE_2D ) continue;
if( effectData.diffSamplerId == samplerId)
effectData.diffImageUniqueId = imageId;
if( effectData.emsvSamplerId == samplerId)
effectData.emsvImageUniqueId = imageId;
if( effectData.emsvSamplerId == samplerId)
effectData.specImageUniqueId = imageId;
if( effectData.bumpSamplerId == samplerId)
effectData.bumpImageUniqueId = imageId;
}
mEffectDatas.Add(effectId,effectData);
return true;
}
//--------------------------------------------------------------------
bool Nebula3Writer::writeCamera( const COLLADAFW::Camera* camera )
{
//n_printf("writeCamera......\n");
return true;
}
//--------------------------------------------------------------------
bool Nebula3Writer::writeImage( const COLLADAFW::Image* image )
{
const COLLADAFW::UniqueId& imageId = image->getUniqueId ();
const COLLADABU::URI& imageURI = image->getImageURI ();
Util::String fileTextureName(imageURI.toNativePath ().c_str());
//fileTextureName = fileTextureName.ExtractFileName();
this->mImageDatas.Add(imageId,fileTextureName);
return true;
}
//--------------------------------------------------------------------
bool Nebula3Writer::writeTextureData(const COLLADAFW::UniqueId& imageId,Util::String& newTextureName)
{
static const Util::String newTextureDir = TEXTURE_PRE_FIXED;
if( !IoServer::Instance()->DirectoryExists(URI(newTextureDir)))
IoServer::Instance()->CreateDirectory( URI(newTextureDir));
Util::String fileTextureName = this->mImageDatas[imageId];
if( IoServer::Instance()->FileExists(URI(fileTextureName)))
{
newTextureName = newTextureDir;
newTextureName.Append(fileTextureName.ExtractFileName());
if( !IoServer::Instance()->FileExists(URI(newTextureName)))
IoServer::Instance()->CopyFile(URI(fileTextureName),URI(newTextureName));
}
else
{
n_warning("texture not exist [%s]\n",fileTextureName.AsCharPtr());
return false;
}
return true;
}
//--------------------------------------------------------------------
bool Nebula3Writer::writeMaterialData( const NodeData& instanceNodeData,GeometryData& geometryData,IndexT groupIndex,const Ptr<ModelNode>& modelNode )
{
GeometryData::MeshData& meshData = geometryData.mMeshDatas[groupIndex];
const COLLADAFW::MaterialId& materialId = meshData.materialId;
const Ptr<StateNode>& shapeNode = modelNode.downcast<StateNode>();
bool useDefaultMaterial = true;
/// 找不到材质
if( instanceNodeData.materialDatas.Contains(materialId) )
{
const MaterialData& materialData = instanceNodeData.materialDatas[materialId];
if( this->mMaterialDatas.Contains(materialData.materialUniqueId) )
{
const COLLADAFW::UniqueId& effectId = this->mMaterialDatas[materialData.materialUniqueId];
if( this->mEffectDatas.Contains(effectId) )
{
const EffectData& effectData = this->mEffectDatas[effectId];
if( materialData.textureDatas.Contains(effectData.diffMapId) )
{
/// 找到diffuse贴图坐标和贴图纹理
const MaterialData::TextureCoordData& textureData = materialData.textureDatas[effectData.diffMapId];
GeometryData::TextureData& uvData = meshData.uvDatas[textureData.uvSetIndex];
const Util::Array<Math::vector>& uvs = geometryData.mUvs[uvData.uvSetname];
const Util::Array<IndexT>& uvIndices = uvData.uvIndices;
n_assert(meshData.mDiffMapIndices.IsEmpty());
n_assert(meshData.mDiffMapUVs.IsEmpty());
meshData.mDiffMapUVs.AppendArray(uvs);
meshData.mDiffMapIndices.AppendArray(uvIndices);
Util::String newTexturename;
if( effectData.diffImageUniqueId.isValid() && this->writeTextureData(effectData.diffImageUniqueId,newTexturename))
meshData.mDiffTextureName = newTexturename;
if( effectData.emsvImageUniqueId.isValid() && this->writeTextureData(effectData.emsvImageUniqueId,newTexturename))
meshData.mEmsvTextureName = newTexturename;
if( effectData.specImageUniqueId.isValid() && this->writeTextureData(effectData.specImageUniqueId,newTexturename))
meshData.mSpecTextureName = newTexturename;
if( effectData.bumpImageUniqueId.isValid() && this->writeTextureData(effectData.bumpImageUniqueId,newTexturename))
meshData.mBumpTextureName = newTexturename;
useDefaultMaterial = false;
}///end if
}///end if
}///end if
}
/// 默认材质
shapeNode->SetShader("shd:static");
shapeNode->AddShaderParam("DiffMap0",meshData.mDiffTextureName);
shapeNode->AddShaderParam("EmsvMap0",meshData.mEmsvTextureName);
shapeNode->AddShaderParam("SpecMap0",meshData.mSpecTextureName);
shapeNode->AddShaderParam("BumpMap0",meshData.mBumpTextureName);
return useDefaultMaterial;
}
//--------------------------------------------------------------------
bool Nebula3Writer::writeLight( const COLLADAFW::Light* light )
{
//n_printf("writeLight......\n");
return true;
}
//--------------------------------------------------------------------
bool Nebula3Writer::writeAnimation( const COLLADAFW::Animation* animation )
{
const COLLADAFW::UniqueId& animationId = animation->getUniqueId ();
if( mAnimationDatas.Contains(animationId) ) return false;
// Import the animation data.
const COLLADAFW::Animation::AnimationType& animationType = animation->getAnimationType ();
switch ( animationType )
{
case COLLADAFW::Animation::ANIMATION_CURVE:
{
AnimationData animData;
COLLADAFW::AnimationCurve* animationCurve = ( COLLADAFW::AnimationCurve* ) animation;
importAnimationCurve ( animationCurve ,animData);
mAnimationDatas.Add(animationId,animData);
break;
}
case COLLADAFW::Animation::ANIMATION_FORMULA:
break;
default:
break;
}
return true;
}
//--------------------------------------------------------------------
bool Nebula3Writer::writeAnimationList( const COLLADAFW::AnimationList* animationList )
{
this->importAnimationList(animationList);
return true;
}
//--------------------------------------------------------------------
bool Nebula3Writer::writeSkinControllerData( const COLLADAFW::SkinControllerData* skinControllerData )
{
this->importSkinControllerData(skinControllerData);
return true;
}
//--------------------------------------------------------------------
bool Nebula3Writer::writeController( const COLLADAFW::Controller* Controller )
{
const COLLADAFW::UniqueId& controllerId = Controller->getUniqueId ();
COLLADAFW::Controller::ControllerType controllerType = Controller->getControllerType ();
switch ( controllerType )
{
case COLLADAFW::Controller::CONTROLLER_TYPE_SKIN:
this->importSkinController(Controller);
break;
case COLLADAFW::Controller::CONTROLLER_TYPE_MORPH:
default:
std::cerr << "Unknown controller type!" << std::endl;
break;
}
return true;
}
//--------------------------------------------------------------------
Math::matrix44 Nebula3Writer::toMatrix44(const COLLADABU::Math::Matrix4& matMatrix)
{
Math::matrix44 matTemp;
matTemp.setrow0(Math::float4((float)matMatrix.getElement(0,0),(float)matMatrix.getElement(0,1),(float)matMatrix.getElement(0,2),(float)matMatrix.getElement(0,3)));
matTemp.setrow1(Math::float4((float)matMatrix.getElement(1,0),(float)matMatrix.getElement(1,1),(float)matMatrix.getElement(1,2),(float)matMatrix.getElement(1,3)));
matTemp.setrow2(Math::float4((float)matMatrix.getElement(2,0),(float)matMatrix.getElement(2,1),(float)matMatrix.getElement(2,2),(float)matMatrix.getElement(2,3)));
matTemp.setrow3(Math::float4((float)matMatrix.getElement(3,0),(float)matMatrix.getElement(3,1),(float)matMatrix.getElement(3,2),(float)matMatrix.getElement(3,3)));
return matTemp;
}
//--------------------------------------------------------------------
Math::matrix44 Nebula3Writer::toDirectXMatrix(const Math::matrix44& matrix44)
{
//Math::vector outTranslate;Math::quaternion outRotate;Math::vector outScale;
//Math::vector outAxis;Math::scalar outAngle;
Math::matrix44 matTemp = Math::matrix44::transpose(matrix44);
//matTemp.decompose(outScale,outRotate,outTranslate);
//matTemp = Math::matrix44::scaling(outScale.x(),outScale.z(),outScale.y());
//Math::quaternion::to_axisangle(outRotate,outAxis,outAngle);
//if( outAxis.y()!=0.0f || outAxis.z()!=0.0f)
//{
// outRotate = Math::quaternion::rotationaxis(Math::vector(outAxis.x(),outAxis.z(),outAxis.y()),-outAngle);
//}
//matTemp = Math::matrix44::multiply(matTemp,Math::matrix44::rotationquaternion(outRotate));
//matTemp = Math::matrix44::multiply(matTemp,Math::matrix44::translation(outTranslate.x(),outTranslate.z(),outTranslate.y()));
return matTemp;
}
//--------------------------------------------------------------------
void Nebula3Writer::makeDirectXFriendly()
{
Util::Array<COLLADAFW::UniqueId> keys = this->mNodeMaps.KeysAsArray();
for (int i=0;i< keys.Size();i++)
{
NodeData& nodeData =this->mNodeMaps[keys[i]];
nodeData.bind_matrix = this->toDirectXMatrix(nodeData.bind_matrix);
}///end for
keys = this->mSkinDatas.KeysAsArray();
for (int i=0;i< keys.Size();i++ )
{
SkinData& skinData = this->mSkinDatas[keys[i]];
skinData.bindShapeMatrix = this->toDirectXMatrix(skinData.bindShapeMatrix);
for (int j=0;j<skinData.inverseMatirxs.Size();j++)
{
skinData.inverseMatirxs[j] = this->toDirectXMatrix(skinData.inverseMatirxs[j]);
}///end for
}///end for
keys = this->mAnimationListDatas.KeysAsArray();
for (int i=0;i< keys.Size();i++)
{
Util::Array<Math::matrix44>& animationKeys = this->mAnimationListDatas[keys[i]];
for (int j=0;j<animationKeys.Size();j++)
{
animationKeys[j] = this->toDirectXMatrix(animationKeys[j]);
}///end for
}///end for
}
//--------------------------------------------------------------------
void Nebula3Writer::writeModel(Util::String& modelFilename)
{
Ptr<Model> model = Model::Create();
if( !this->mControllerNodeMaps.IsEmpty())
{
const Util::Array<COLLADAFW::UniqueId>& keys = this->mControllerNodeMaps.KeysAsArray();
const COLLADAFW::UniqueId controllerUniqueId = keys[0];
if( this->mCharacterDatas.Contains(controllerUniqueId))
{
const COLLADAFW::UniqueId& instanceNodeId = this->mControllerNodeMaps[controllerUniqueId];
if( this->mNodeMaps.Contains(instanceNodeId))
{
CharacterData& characterData = this->mCharacterDatas[controllerUniqueId];
const NodeData& instanceNodeData = this->mNodeMaps[instanceNodeId];
Ptr<CharacterNode> characterNode = this->writeCharacterData(instanceNodeData,characterData);
model->AttachNode(characterNode.upcast<ModelNode>());
}
}///end if
}
else if( !this->mGeometryNodeMaps.IsEmpty())
{
Ptr<TransformNode> rootNode = TransformNode::Create();
const Util::Array<COLLADAFW::UniqueId>& keys = this->mGeometryNodeMaps.KeysAsArray();
for (int i=0;i< keys.Size();i++ )
{
const COLLADAFW::UniqueId geometryUniqueId = keys[i];
if( !this->mGeometryDatas.Contains(geometryUniqueId)) continue;
const COLLADAFW::UniqueId& instanceNodeId = this->mGeometryNodeMaps[geometryUniqueId];
if( !this->mNodeMaps.Contains(instanceNodeId)) continue;
GeometryData& geometryData = this->mGeometryDatas[geometryUniqueId];
const NodeData& instanceNodeData = this->mNodeMaps[instanceNodeId];
Ptr<TransformNode> transformNode = this->writeGeometryData(instanceNodeData,geometryData);
rootNode->AddChild(transformNode.upcast<ModelNode>());
}///end for
rootNode->SetName("model");
model->AttachNode(rootNode.upcast<ModelNode>());
}
else
{
n_printf("no model export!");
return;
}
Ptr<Stream> stream = IoServer::Instance()->CreateStream(URI(modelFilename));
Ptr<Editor::ModelNodeWriter> writer = Editor::ModelNodeWriter::Create();
writer->SetStream(stream);
if (writer->Open())
{
writer->WriteModel("model",model);
writer->Close();
}
model = 0;
writer = 0;
}
} // namespace DAE2Ogre
|
500b50e8aeaaf10f0dd02ed77baf90cd7ea1de1c | e64317112ee970376062736c86ae0c09aea4ed61 | /BalancedParenthesis.cpp | b351a9c89eec5193f0b3f1b38447cf40d4afa5ef | [] | no_license | TheTypo36/c-BASIC-AND-DSA | 7af6652bf673c54d1162328682e2bb4eee5773fa | 2daa2deac16f39118f34367859888850c0f4a14d | refs/heads/master | 2022-12-26T23:03:08.470974 | 2020-09-22T04:18:07 | 2020-09-22T04:18:07 | 257,876,316 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,088 | cpp | BalancedParenthesis.cpp | #include <bits/stdc++.h>
using namespace std;
bool checkBalanced(char *exp)
{
stack<int> s;
int i = 0;
while (exp[i] != '\0')
{
if (exp[i] == '{' || exp[i] == '(' || exp[i] == '[')
{
s.push(exp[i]);
}
else if (exp[i] == '}' || exp[i] == ')' || exp[i] == ']')
{
if (s.empty())
{
return false;
}
else if (exp[i] =='}' &&s.top()=='{')
{
s.pop();
}
else if (exp[i] ==']' &&s.top()=='[')
{
s.pop();
}
else if (exp[i] ==')' &&s.top()=='(')
{
s.pop();
}
else
{
return false;
}
}
i++;
}
return s.empty();
}
int main()
{
char input[100000];
cin.getline(input, 100000);
// cin >> input;
if (checkBalanced(input))
{
cout << "true" << endl;
}
else
{
cout << "false" << endl;
}
} |
c253b668e3e83cc27642df7b28d5d77df478c866 | e469bb4d5833340dd63b3dcd7748081cd8c89120 | /Lucuma/code/lucuma/utils/allocator.h | ea5755cdd1cf3e731a20d6a34943cc175b2291c9 | [] | no_license | bitnenfer/Lucuma | 440fcfa23aa9749b73398eb1c9d18be732b5829c | 7e4230f4bda6b55e46156f54f58389fab3379052 | refs/heads/master | 2020-04-26T07:25:57.155061 | 2019-03-17T02:15:36 | 2019-03-17T02:15:36 | 50,359,578 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 407 | h | allocator.h | #pragma once
#include "../types.h"
namespace lu
{
struct IAllocator
{
virtual void* allocate(uint64_t size) = 0;
virtual void* allocateAligned(uint64_t size, uint32_t alignment) = 0;
virtual void deallocate(void* p) = 0;
virtual void reset() = 0;
virtual uint64_t getCapacityInBytes() = 0;
virtual uint64_t getUsedSpaceInBytes() = 0;
virtual uint64_t getAvailableSpaceInBytes() = 0;
};
}
|
04a6885d67ced77a700d4f169745c7bae29f662d | c0438cae3adfb762c87d2c43bc1095bc0c123627 | /Linked List/Delete nth node from end.cpp | bef147e075d71a7c6fffc876af94f1f47737bcb3 | [] | no_license | SubhradeepSS/dsa | 6705ae2c27e73dd8b9eb3557fa5c255b54e6c746 | 3d4cf60c298e1c93ce458690f3e01940232d5099 | refs/heads/master | 2023-08-14T18:14:09.254692 | 2021-10-06T18:13:13 | 2021-10-06T18:13:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 650 | cpp | Delete nth node from end.cpp | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *t=head;
if(head->next==NULL)
return NULL;
while(n--)
t=t->next;
ListNode *node=head,*prev=NULL;
while(t){
t=t->next;
prev=node;
node=node->next;
}
if(prev)
prev->next=node->next;
else
head=node->next;
delete node;
return head;
}
};
|
528910e6d0f97a462fa3d943fc5c8b24026602e1 | 97c63d5416761fd3ec8ab9080f28fac27be29fbe | /randompartition_test.cc | 73791cd1f941f1ce8b2af31fb589eecf231bd5ce | [] | no_license | megangoodland/PHY1610_4 | 0d1bc3d70847a6530d5dc1067aa1b7d919249eb0 | c06f6069786871ea9e4cd578245b2b5cc0e42f26 | refs/heads/master | 2020-04-22T07:00:21.855847 | 2019-02-14T23:33:27 | 2019-02-14T23:33:27 | 170,191,906 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,265 | cc | randompartition_test.cc | // Megan Goodland, University of Toronto
// February 2019
// Tests for the randompartition module, which performs:
// Implementation of the function to randomly divide a number 'total'
// into a set of 'numdivision' numbers that add up to 'total'. Uses
// c++11 random library to generate the randomness.
// >>> Want a test for rand_partition that partitions 100 into 10 parts.
// Run this 10 times, each time checking that the parts add up to 100.
#include "randompartition.h"
#include <iostream>
#include <fstream>
#define BOOST_TEXT_DYN_LINK
#define BOOST_TEST_MODULE randompartition_test
#include <boost/test/included/unit_test.hpp>
BOOST_AUTO_TEST_CASE(splitting_100){
int total = 100;
int nparts = 10;
size_t seed = 11;
rarray<int,1> nperpart(10);
int sum = 0; // sum will store the sum of the values from nperpart
for (int i=0; i<10; i++){ // we want to do this test 10 times
rand_partition(total, nparts, nperpart, seed);
// loop to sum up components of nperpart
for (int n=0; n<nparts; n++){
sum = sum + nperpart[n];
}
BOOST_CHECK_MESSAGE(sum == total, "randomly partitioned 100");
// zeroing values that loop
sum = 0;
nperpart.fill(0);
}
}
|
b944fc7347f5c17662e354289304c15eb784139a | cc3eb9fa166df91a4ed3b3b90c705a57b5bab2da | /HtmlParser.h | de46e2dfd2da64776314e41f4158778094030d42 | [] | no_license | ljxcript/my-tiny-rendering-engine | f9df788ecb40eecaf2b5d1425cfec17b062a119a | fbe189905bb46f3ad1ed49b521b91835b9e82c62 | refs/heads/master | 2021-07-09T21:20:02.058212 | 2020-08-14T10:13:30 | 2020-08-14T10:13:30 | 181,303,905 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 554 | h | HtmlParser.h | //
// HtmlParser.h
// my-tiny-browser
//
// Created by marco.liao on 2019/4/18.
// Copyright © 2019年 marco.liao. All rights reserved.
//
#ifndef HTMLPARSER_H
#define HTMLPARSER_H
#include <string>
#include "HtmlTagNode.h"
class HtmlParser
{
private:
std::string htmlText;
HtmlTagNode* root;
public:
HtmlParser(const char *filename);
HtmlTagNode* parse(const char *filename);
std::string get_file_contents(const char *filename);
std::string getHtmlText();
HtmlTagNode* getRoot();
void visitByLayer();
};
#endif
|
9e2a7a149584d5c2afcb7f011af9346ec10b902e | e7a39a0c555e01d692a3d41eed3a95f1f1babec5 | /code/server/lua_service_origin/lua_libs/try_use_lualib/try_use_lualib.cpp | 9dfe34b9b8cfa5939cac4631d8cb65ab1a3029ee | [
"MIT"
] | permissive | UtopiaCoder/utopia_origin | 0181f34a0ad2788690206ce021681c08668cb5f6 | e9ce25193c21264b1d896d18ae8a472e3d54370c | refs/heads/master | 2020-04-14T01:12:23.569426 | 2019-03-21T06:40:38 | 2019-03-21T06:40:38 | 163,554,708 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 762 | cpp | try_use_lualib.cpp | #include "try_use_lualib.h"
#include <stdio.h>
static int log_msg(lua_State* L)
{
printf("execute log_msg\n");
return 0;
}
static const struct luaL_Reg mylib[] =
{
{ "log_msg", log_msg },
{ NULL, NULL }
};
static int do_openlib(lua_State *L)
{
luaL_newlib(L, mylib);
return 1;
}
static int other_log_msg(lua_State* L)
{
printf("execute other_log_msg\n");
return 0;
}
static const struct luaL_Reg other_mylib[] =
{
{ "log_msg", other_log_msg },
{ NULL, NULL }
};
static int other_do_openlib(lua_State *L)
{
luaL_newlib(L, other_mylib);
return 1;
}
int luaopen_tryuselualib(lua_State *L)
{
printf("luaopen_tryuselualib\n");
luaL_requiref(L, "tryuselualib", do_openlib, 1);
luaL_requiref(L, "othertryuselualib", other_do_openlib, 1);
return 0;
}
|
873367cdcf55bf3d07733120f9c8630496edc717 | 2124d0b0d00c3038924f5d2ad3fe14b35a1b8644 | /source/SEAL_Foundation/PluginManager/src/PluginManager.cc | 689510981261cebd83f644ddc71d54b80b0c2717 | [] | no_license | arceciemat/GAMOS | 2f3059e8b0992e217aaf98b8591ef725ad654763 | 7db8bd6d1846733387b6cc946945f0821567662b | refs/heads/master | 2023-07-08T13:31:01.021905 | 2023-06-26T10:57:43 | 2023-06-26T10:57:43 | 21,818,258 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,154 | cc | PluginManager.cc | //<<<<<< INCLUDES >>>>>>
#include "PluginManager/PluginManager.h"
#include "PluginManager/PluginInfo.h"
#include "PluginManager/PluginFactoryBase.h"
#include "PluginManager/ModuleCache.h"
#include "PluginManager/Module.h"
#include "debug.h"
#include "PluginManager/ModuleDescriptor.h"
#include "SealBase/SystemError.h"
#include "SealBase/Log.h"
#include <algorithm>
#include <functional>
#include <typeinfo>
namespace seal {
//<<<<<< PRIVATE DEFINES >>>>>>
//<<<<<< PRIVATE CONSTANTS >>>>>>
//<<<<<< PRIVATE TYPES >>>>>>
/// Locate a #ModuleCache by it's file name.
class DirectoryByName {
Filename m_which;
public:
DirectoryByName (Filename name) : m_which (name) {}
bool operator() (const ModuleCache *dir) {
return dir->directory () == m_which;
}
};
/// Simple class to configure optional destruction of plug-in manager on exit.
class PluginManagerDestructor {
PluginManager *m_manager;
bool m_destroy;
public:
PluginManagerDestructor (void) : m_manager (0), m_destroy (false) {}
~PluginManagerDestructor (void)
{
if (m_destroy && m_manager)
{
LOG (0, trace, LFplugin_manager, "destroying plug-in manager\n" << indent);
delete m_manager;
m_manager = 0;
LOG (0, trace, LFplugin_manager, undent);
}
}
void policy (bool destroy) { m_destroy = destroy; }
void object (PluginManager *manager) { m_manager = manager; }
};
//<<<<<< PRIVATE VARIABLE DEFINITIONS >>>>>>
static PluginManagerDestructor s_destructor;
//<<<<<< PUBLIC VARIABLE DEFINITIONS >>>>>>
//<<<<<< CLASS STRUCTURE INITIALIZATION >>>>>>
//<<<<<< PRIVATE FUNCTION DEFINITIONS >>>>>>
//<<<<<< PUBLIC FUNCTION DEFINITIONS >>>>>>
//<<<<<< MEMBER FUNCTION DEFINITIONS >>>>>>
/** Get the plug-in manager. This retrieves a pointer to a global
plug-in manager object. The manager is automatically created on
first call to this function, and initialised to use @c SEAL_PLUGINS
environment variable as the search path. The manager is not fully
initialised until someone calls #initialise() method. That is, it
is functional but will not scan for plug-ins until #initialise() is
called. Otherwise the manager is fully functional. Once the init
has been done, the manager also knows about the plug-ins. */
PluginManager *
PluginManager::get (void)
{
// FIXME: Thread safety
static PluginManager *s_db = 0;
if (! s_db)
{
const char *path = getenv ("SEAL_PLUGINS");
if (! path) path = "";
LOG (0, trace, LFplugin_manager,
"initialising plugin manager with path <" << path << ">");
s_db = new PluginManager (SearchPath (path ? path : ""));
s_destructor.object (s_db);
}
return s_db;
}
/** Configure the destruction of the plug-in manager. By default the
manager isn't destructed. This function allows the application to
set the destruction policy, either to force the destruction or to
prevent it. In general, it would be a good idea to destroy the
manager, but you will want to ensure your compiler and language
run-times are implementing correct destruction mechanism before
enabling the functionality.
Note that this method only sets the destruction policy @em if a
#PluginManager is constructed. The method itself neither creates
nor destroys the manager. */
void
PluginManager::destroyOnExit (bool destroy)
{ s_destructor.policy (destroy); }
/** Construct a plug-in manager using the @a path as the list of module
definition directories. This constructor is private; use #get()
instead. */
PluginManager::PluginManager (const SearchPath &path)
: m_initialised (false),
m_searchPath (path)
{
/* // std::cout << " PluginManager::PluginMa PATH " ; //GDEB
SearchPath::const_iterator dir = m_searchPath.begin ();
std::cout << *dir;
while (++dir != m_searchPath.end ())
std::cout << " " << SearchPath::separator () << *dir;
*/
// std::cout << "ZZ " << std::endl; //GDEB
}
/** Destroy the plug-in manager. Frees all module caches. */
PluginManager::~PluginManager (void)
{
// Zap all the module cache directories
DirectoryIterator dir = beginDirectories ();
for ( ; dir != endDirectories (); ++dir)
delete *dir;
// Zap any factories that still remain. The ones we still have must
// be dynamically allocated and thus delete is safe -- otherwise the
// global destructors would have already destructed them, causing
// them to unregistered themselves from me. (This assumes correct
// library dependency linkage.)
while (! m_factories.empty ())
delete *m_factories.begin ();
}
/** Initialise the plug-in manager. This causes all the plug-in
directories determined by #get() (from $SEAL_PLUGINS environment
variable) to be scanned, and new plug-ins potentially be queried.
It is safe to call this method several times, only the first time
counts. The first call should happen at a time when it is safe
to load and unload libraries: when the program is in sufficiently
stable state. If you don't like spending hours of debugging odd
bugs or don't want to be vulnerable to strange and fragile error
conditions, translate that to "never call this method from a
global constructor, directly or indirectly".
Causes a #ModuleCache to be created for every directory mentioned
in the search path. Directories that don't exist or for which
caching fails for some other reason are ignored (see logging output
for details). */
void
PluginManager::initialise (void)
{
if (m_initialised) return;
m_initialised = true;
SearchPath::const_iterator dir = m_searchPath.begin ();
for ( ; dir != m_searchPath.end (); ++dir)
{
// Ignore directories that do not exist. Also ignore
// empty directory components ("foo::bar") as they are
// unlikely to be intended. This is unlike normal unix
// behaviour where "::" really means ":.:", but avoids
// a common problem from appending to SEAL_PLUGINS as
// $SEAL_PLUGINS:foo when SEAL_PLUGINS is not set. If
// user really wants to have "." in the path -- and that
// is exceedingly unlikely -- they can always do so
// explicitly.
if (! dir->empty ())
{
try {
m_directories.push_back (new ModuleCache (this, *dir));
} catch (Error &error) {
LOG (0, warning, LFplugin_manager, undent << undent
<< "directory " << *dir << " ignored: "
<< typeid(error).name () << " ("
<< error.explain ().c_str () << ")\n");
continue;
}
}
}
rebuild ();
}
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/** Route a new plug-in info object to the appropriate factory. */
void
PluginManager::addInfo (PluginInfo *info)
{
// This method is called by #Module when it receives a new info
// object. We find the factory that matches the info object's
// category, and then route the call to the factory so it can
// add the info object to its list of available plug-ins.
//
// #Module is notified in turn by #PluginInfo constructors, or
// more specifically, the finish() method that is called by the
// PluginInfo subclass at the end of its constructor. The
// module just routes the call to us.
//
// The #PluginInfo can come into existence in one of two ways:
// created by the module query, or reincarnated from a cache by
// request of the factory when it is being constructed.
//
// The factory matching the info object must already exist, there
// is no way to get here without that being the case. However it
// may still be under construction, which is one reason why the
// call is propagated through base classes and not directly to the
// factory from the PluginInfo derived class; another reason is
// to keep knowledge about factories in the plug-in manager and
// out of #Module.
PluginFactoryBase *factory = findFactory (info->category ());
ASSERT (factory);
factory->addInfo (info);
}
/* Route a dying plug-in info notification to the appropriate factory. */
void
PluginManager::removeInfo (PluginInfo *info)
{
// This method is called by #Module when a #PluginInfo object is
// being destructed, with some processing in #Module first. We
// find the factory matching the info object category, and route
// the call to the factory so it can remove the info from it's
// list. Knowledge about the info object remains in raw cached
// form in #Module unless the purpose is to purge the cache.
//
// #PluginInfo objects die in one of two ways: either because the
// factory is going out of scope -- for instance because it itself
// was in a dynamically loaded module that is getting unloaded --
// or because the #Module object deletes it. The latter can
// happen for a variety reasons, for example when re-querying a
// module, when module is marked bad, or when the module object
// is deleted as a part of a cache refresh.
//
// By definition the factory already exists, info objects can be
// created only with the factory present, and the factory deletes
// its info objects before dying itself. The call is routed here
// in order to keep knowledge about factories here, as well as
// for symmetry with the other info-related registration methods.
PluginFactoryBase *factory = findFactory (info->category ());
ASSERT (factory);
factory->removeInfo (info);
}
/* Route a request to restore an info object from raw cached form to
the appropriate factory. The info item's category, the first token
in the cached data, is expected to be the factory registration name. */
void
PluginManager::restore (Module *module, ModuleDescriptor *from)
{
// This method is called by #Module when reading back a cache
// to inform a factory to create a #PluginInfo from cached form.
// We look for a factory matching the info object category; the
// convention is that the first token of the cached info object
// data must be the category of the info object and the name of
// the factory. If such a factory is registered, we pass it the
// cache data; it will instantiate an appropriate info object
// from it, which will then end up calling #addInfo().
//
// If no factory is currently registered, the call is ignored.
// In that case, #Module will retain the raw cached data, and
// when the factory is instantiated, it will rebuild the info
// objects from that (see #PluginFactoryBase::rebuild()). In
// that case the calls will not go through this method; only
// #addInfo() is used as the info objects are instantiated.
ASSERT (from);
ASSERT (from->tokens () >= 2);
if (PluginFactoryBase *factory = findFactory (from->token (0)))
factory->restore (module, from);
}
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/** Add the @a factory to the plugin manager. This makes the factory
participate in the internal cache management scheme to allow data
about modules and plug-ins to to be cached and restored. This
method is called by the #PluginFactoryBase constructor. */
void
PluginManager::addFactory (PluginFactoryBase *factory)
{
// FIXME: allow factories to be registered to the database, then
// notify them on each refresh (and when they are added). The
// factories should be accessed via XyzDB::get () which gets the
// global database and registers an instance of the factory into it.
m_factories.push_back (factory);
}
/** Remove a @a factory from the plug-in manager. This method is
be called from the #PluginFactoryBase destructor so that the
manager will not try to notify factories that have already been
unloaded from the program. */
void
PluginManager::removeFactory (PluginFactoryBase *factory)
{
FactoryIterator pos = std::find (m_factories.begin (), m_factories.end (), factory);
ASSERT (pos != m_factories.end ());
m_factories.erase (pos);
}
/** Find a factory that matches category label @a name. Internal
method used to match info item categories to factories. Returns
pointer to the matching factory, or null if none is found. */
PluginFactoryBase *
PluginManager::findFactory (const std::string &name)
{
FactoryIterator pos = m_factories.begin ();
while (pos != m_factories.end () && (*pos)->category () != name)
++pos;
return pos != m_factories.end () ? *pos : 0;
}
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/** Internal method to rebuild the module table. Collects all modules
currently in all the caches into a map that can be iterated over
by the clients. The modules are added in the order seen in the
search path: a module earlier in the path will hide identically
named module later in the path. This allows for instance a module
in a developer area to override one in a base release area. */
void
PluginManager::rebuild (void)
{
ModuleMap modules;
ModuleCache::Iterator module;
DirectoryIterator dir;
// Collect modules into a map
for (dir = beginDirectories (); dir != endDirectories (); ++dir)
for (module = (*dir)->begin (); module != (*dir)->end (); ++module)
if (! modules.count ((*module)->libraryName ()))
modules [(*module)->libraryName ()] = *module;
// Put the information back
m_modules.swap (modules);
// There's no need to update custom factories. Refreshing the modules
// caused them to be re-queried, which caused each module to blast
// away their caches and existing infos, which caused all factories to
// remove their database of those infos, plus the re-query caused
// all necessary new infos to be created.
}
/** Refresh the plug-in database. Rescans all module directories,
re-querying all new or updated modules. This method can take a
substantial amount of time to run as it may load and unload a
large number of modules. Do not call this method in a program
that is already running and has loaded some modules in memory --
they may get unloaded or worse, reloaded with a new, incompatible
version of the module (if the modules are updated on disk). In
general plug-in factories may change their contents considerably,
and will certainly change somewhat, so beware of invalidating
outstanding object references. */
void
PluginManager::refresh (void)
{
DirectoryIterator dir = beginDirectories ();
for ( ; dir != endDirectories (); ++dir)
(*dir)->refresh ();
rebuild ();
}
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/** Get an iterator over all the module definition directories. */
PluginManager::DirectoryIterator
PluginManager::beginDirectories (void) const
{ return m_directories.begin (); }
/** Get an iterator over all the module definition directories. */
PluginManager::DirectoryIterator
PluginManager::endDirectories (void) const
{ return m_directories.end (); }
/** Get an iterator to a module definition directory @a name. */
PluginManager::DirectoryIterator
PluginManager::locateDirectory (const Filename &name) const
{
return std::find_if (beginDirectories (), endDirectories (),
DirectoryByName (name));
}
/** Locate a module definition directory @a name. Returns the
pointer to the matching #ModuleCache if one is found, null
otherwise. */
ModuleCache *
PluginManager::directory (const Filename &name) const
{
DirectoryIterator pos = locateDirectory (name);
return pos != endDirectories () ? *pos : 0;
}
//////////////////////////////////////////////////////////////////////
/** Return an iterator over all the modules currently known about.
Note that several module directories can define a module with the
same name; only the first is visible in the plug-in manager. */
PluginManager::ModuleIterator
PluginManager::beginModules (void) const
{ return ModuleIterator (m_modules.begin ()); }
/** Return an iterator over all the modules currently known about.
Note that several module directories can define a module with the
same name; only the first is visible in the plug-in manager. */
PluginManager::ModuleIterator
PluginManager::endModules (void) const
{ return ModuleIterator (m_modules.end ()); }
/** Return an iterator to a module with shared library @a libraryName.
Note that several module directories can define a module with the
same name; only the first is visible in the plug-in manager. */
PluginManager::ModuleIterator
PluginManager::locateModule (const Filename &libraryName) const
{ return ModuleIterator (m_modules.find (libraryName)); }
/** Locate a module with shared library @a libraryName. Returns the
pointer to the matching #Module if one is found, null otherwise.
Note that several module directories can define a module with the
same name; only the first is visible in the plug-in manager. */
Module *
PluginManager::module (const Filename &libraryName) const
{
ModuleIterator pos = locateModule (libraryName);
return pos != endModules () ? *pos : 0;
}
//////////////////////////////////////////////////////////////////////
/** Add a feedback target. */
void
PluginManager::addFeedback (FeedbackCB callback)
{ m_feedbacks.push_back (callback); }
/** Remove a feedback target. */
void
PluginManager::removeFeedback (FeedbackCB callback)
{ m_feedbacks.remove (callback); }
/** Send a feedback notification to all registered targets. */
void
PluginManager::feedback (FeedbackData data)
{
FeedbackIterator i;
for (i = m_feedbacks.begin (); i != m_feedbacks.end (); ++i)
(*i) (data);
}
/** Send a feedback notification to all registered targets. */
void
PluginManager::feedback (FeedbackCode code,
const Filename &scope,
Error *error /* = 0 */)
{ feedback (FeedbackData (code, (std::string) scope, error)); }
/** Send a feedback notification to all registered targets. */
void
PluginManager::feedback (FeedbackCode code,
const std::string &scope,
Error *error /* = 0 */)
{ feedback (FeedbackData (code, scope, error)); }
} // namespace seal
|
5de3cde9cd88517fc8e5546d9dec4c5e3818d50e | e0e300cf28f9a40010c3d906c42c63aa1c1e230d | /cpp-module/test/AdjacencyListGraphTest.cpp | b8562b29e764d568009f902dc734c254b699b501 | [] | no_license | girone/forestmaps | 88170ece1858ff042365826123036b1b7a29cb62 | 52852ba6eacbb665898f25c490df80c6c1a7c069 | refs/heads/master | 2021-03-19T16:37:24.668219 | 2015-04-26T21:06:16 | 2015-04-26T21:06:16 | 27,169,437 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,439 | cpp | AdjacencyListGraphTest.cpp | // Copyright 2013: Jonas Stegraphisko
#include <gtest/gtest.h>
#include <gtest/gtest_prod.h>
#include <string>
#include <vector>
#include "../src/AdjacencyGraph.h"
#include "../src/GraphConverter.h"
#include "../src/GraphSimplificator.h"
#include "../src/Util.h"
using std::string;
using std::vector;
// A test node.
class TestNode {
public:
void from_stream(std::istream& is) { // NOLINT
is >> value;
}
string to_string() const {
std::stringstream ss;
ss << value;
return ss.str();
}
float value;
};
// A test arc.
class TestArc {
public:
// TestArc() : source(-1), target(-1), cost(0) { }
// TestArc(int s, int t, int c) : source(s), target(t), cost(c) { }
void from_stream(std::istream& is) { // NOLINT
is >> source >> target >> cost;
}
string to_string() const {
std::stringstream ss;
ss << "(" << source << "," << target << "," << cost << ")";
return ss.str();
}
int source;
int target;
int cost;
};
typedef AdjacencyListGraph<TestNode, TestArc> TestGraph;
// _____________________________________________________________________________
TEST(AdjacencyListGraphTest, to_string) {
{
TestGraph graph;
ASSERT_EQ("[0,0,]", graph.to_string());
graph._nodes.assign(3, TestGraph::Node_t());
graph._arcs = vector<vector<TestGraph::Arc_t> >(3);
EXPECT_EQ("[3,0,{},{},{}]", graph.to_string());
}
}
/*
// _____________________________________________________________________________
TEST(AdjacencyListGraphTest, from_string) {
{
OffsetListGraph<SourceTargetCostArc> graph;
graph.from_string("[3,2,{(1,3)},{},{(2,5)}]");
ASSERT_EQ(3, graph.size());
ASSERT_EQ(2, graph.num_arcs());
EXPECT_EQ(1, graph.arcs(0).begin()->target);
EXPECT_EQ(3, graph.arcs(0).begin()->cost);
EXPECT_EQ(0, graph.arcs(1).size());
EXPECT_EQ(2, graph.arcs(2).begin()->target);
EXPECT_EQ(5, graph.arcs(2).begin()->cost);
}
{
TestGraph graph;
graph.from_string("[3,2,{(1,3)},{},{(2,5)}]");
EXPECT_EQ("[3,2,{(1,3)},{},{(2,5)}]", graph.to_string());
ASSERT_EQ(3, graph.size());
ASSERT_EQ(2, graph.num_arcs());
EXPECT_EQ(1, graph.arcs(0).begin()->target);
EXPECT_EQ(3, graph.arcs(0).begin()->cost);
EXPECT_EQ(0, graph.arcs(1).size());
EXPECT_EQ(2, graph.arcs(2).begin()->target);
EXPECT_EQ(5, graph.arcs(2).begin()->cost);
}
}
// _____________________________________________________________________________
TEST(AdjacencyListGraphTest, one_more_test) {
{
OffsetListGraph<SourceTargetCostArc> graph;
graph.from_string("[4,2,{},{(1,3)(2,5)},{},{}]");
EXPECT_EQ(4, graph.num_nodes());
EXPECT_EQ(2, graph.num_arcs());
EXPECT_EQ("[4,2,{},{(1,3)(2,5)},{},{}]", graph.to_string());
}
{
TestGraph graph;
graph.from_string("[4,2,{},{(1,3)(2,5)},{},{}]");
EXPECT_EQ("[4,2,{},{(1,3)(2,5)},{},{}]", graph.to_string());
}
}*/
// _____________________________________________________________________________
TEST(AdjacencyListGraphTest, read_in) {
{
// Check nodes
std::stringstream ss;
ss << "12 " << std::endl;
TestGraph::Node_t n;
n.from_stream(ss);
EXPECT_EQ(12, n.value);
EXPECT_EQ("12", n.to_string());
}
{
// Check arcs
std::stringstream ss;
ss << "5 7 42";
TestGraph::Arc_t arc;
arc.from_stream(ss);
EXPECT_EQ(5, arc.source);
EXPECT_EQ(7, arc.target);
EXPECT_EQ(42, arc.cost);
EXPECT_EQ("(5,7,42)", arc.to_string());
}
{
string filename = "from_stream.tmp.txt";
std::ofstream ofs(filename);
ofs << "9" << std::endl;
ofs << "10" << std::endl;
// Nodes
ofs << "42 42" << std::endl;
ofs << "42 42" << std::endl;
ofs << "42 42" << std::endl;
ofs << "42 42" << std::endl;
ofs << "42 42" << std::endl;
ofs << "42 42" << std::endl;
ofs << "42 42" << std::endl;
ofs << "42 42" << std::endl;
ofs << "42 42" << std::endl;
// Arcs
ofs << "0 7 0" << std::endl;
ofs << "0 8 0" << std::endl;
ofs << "0 10 0" << std::endl;
ofs << "1 3 0 99 55 77" << std::endl; // Works with unregular input?
ofs << "1 10 0" << std::endl;
ofs << "2 9 0" << std::endl;
ofs << "2 9 0" << std::endl;
ofs << "2 4 0" << std::endl;
ofs << "5 8 0" << std::endl;
ofs << "7 8 0" << std::endl;
}
{
TestGraph graph;
graph.read_in("from_stream.tmp.txt");
EXPECT_EQ("[9,10,{(0,7,0)(0,8,0)(0,10,0)},{(1,3,0)(1,10,0)},{(2,4,0)(2,9,0)"
"(2,9,0)},{},{},{(5,8,0)},{},{(7,8,0)},{}]",
graph.to_string());
}
}
// _____________________________________________________________________________
// These arcs store also an FIDs (reference to the original shape in ArcGIS).
TEST(AdjacencyListGraphTest, forest_graph_from_file_with_fids) {
const string filename = "test.forest_graph_from_file.tmp.txt";
{
std::ofstream ofs(filename);
using std::endl;
ofs << "3" << endl
<< "5" << endl
<< "4.5 4.2 " << endl
<< "5.5 5.2" << endl
<< "6.5 6.2" << endl
<< "0 1 10.1 1 1" << endl
<< "1 0 5.5 5 2" << endl
<< "1 2 4.2 0 3" << endl
<< "2 1 4.2 10 4" << endl
<< "0 2 4.2 45 5" << endl;
}
{
SimplificationGraph fg;
fg.read_in(filename);
EXPECT_EQ(
"[3,5,{(0,1,[10,1,1])(0,2,[4,45,5])},{(1,0,[5,5,2])(1,2,[4,0,3])},"
"{(2,1,[4,10,4])}]",
fg.to_string());
}
}
|
548d20d95adbfbf0eb2e92fffff08836d1176bd7 | e3297b5bb8e039be8819a17fe3e1949dbc889bd7 | /03 - August 25/I/I.cpp | e03304b4c72386fdb5cdb03b0145337efd6b73b8 | [] | no_license | thomasokubo/MC621 | 3111ebf8573bd4fc58cc3256ed48e9ae7bd250b3 | ad4979f42c952cf78550823583a123e3f7d33003 | refs/heads/master | 2020-03-24T05:32:47.819445 | 2018-10-06T19:10:49 | 2018-10-06T19:10:49 | 142,493,048 | 0 | 0 | null | 2018-10-06T19:10:50 | 2018-07-26T20:54:11 | C++ | UTF-8 | C++ | false | false | 1,880 | cpp | I.cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef map<int, int> mii;
ll _sieve_size;
bitset<10000005> bs;
vi primes;
void sieve(ll upperbound) {
_sieve_size = upperbound +1;
bs.set();
bs[0] = bs[1] = 0;
for (ll i = 2; i <= _sieve_size; i++)
if (bs[i]) {
for (ll j = i * i; j<= _sieve_size; j+=i) bs[j] = 0;
primes.push_back((int) i);
}
}
set<int> primeFactors(int n) {
set<int> factors;
ll pf_idx = 0;
ll pf = primes[pf_idx];
while (n != 1 && (pf * pf <= n)) {
while (n % pf == 0) {
n /= pf;
factors.insert(pf);
}
pf = primes[++pf_idx];
}
if (n != 1) {
factors.insert(n);
}
return factors;
}
int pai[1000006];
void modifyPai(int node, int dad) {
if (pai[node] != node) modifyPai(pai[node], dad);
pai[node] = dad;
}
int main() {
int t;
scanf ("%d", &t);
sieve((long)1e6+5);
for (int i = 1; i <= t; i++) {
int n, aux, cont = 0;
scanf ("%d", &n);
set<int> values;
for (int j = 0; j < (int) 1e6+3; j++) {
pai[j] = j;
}
bitset<1000006> visit;
visit.set();
for (int j = 0; j < n; j++) {
scanf ("%d", &aux);
if (aux == 1) cont++;
else {
visit[aux] = 0;
values.insert(aux);
}
}
for (set<int>::iterator it = values.begin(); it != values.end(); it++) {
set<int> vi = primeFactors(*it);
for (set<int>::iterator it2 = vi.begin(); it2 != vi.end(); it2++) {
modifyPai(*it2, *it);
}
}
for (int i = 0; i < (int) 1e6+3; i++) {
if (visit[i] == 0 && pai[i] == i) cont++;
}
printf("Case %lld: %lld\n", i, cont);
}
return 0;
}
|
4758e67137712cc480c525167b435ab223c4da06 | b2584bc3c232dde6660b4116dc6e2666714c0984 | /VirtualKeyboard_Key.cpp | 784b6c0ca4e1d6f62a1e7970cc07dc685c331d01 | [
"Apache-2.0"
] | permissive | pl17/VirtualKeyboard | f6d7a004ebf442730029d6983d9463e6a400b364 | 419454f2d8923522f435ba0f9ec6dd2e4f503292 | refs/heads/master | 2020-03-29T01:25:47.712834 | 2018-09-19T03:52:19 | 2018-09-19T03:52:19 | 149,388,443 | 0 | 0 | Apache-2.0 | 2018-09-19T03:54:52 | 2018-09-19T03:41:14 | C++ | UTF-8 | C++ | false | false | 3,503 | cpp | VirtualKeyboard_Key.cpp | #include "VirtualKeyboard_Key.h"
VirtualKeyboard_Key::VirtualKeyboard_Key()
:Button_Square(NULL, 0, 0, 0, 0, NULL, 0)
{
this->_Init(FALSE, FALSE, TRUE, FALSE);
}
VirtualKeyboard_Key::VirtualKeyboard_Key( HWND hParent, int left, int top, int width, int height, int id, BOOL bPush, BOOL bControl, BOOL bFullDisplay, BOOL bSwap )
:Button_Square(NULL, left, top, width, height, hParent, id)
{
this->_Init(bControl, bPush, bFullDisplay, bSwap);
}
void VirtualKeyboard_Key::_Init(BOOL bControl, BOOL bPush, BOOL bFullDisplay, BOOL bSwap)
{
this->m_nIndexActive=0;
this->m_nMaxIndex=0;
this->m_lpszDisplay[0]=NULL;
this->m_lpszDisplay[1]=NULL;
this->m_bPush=bPush;
this->m_bControlKey=bControl;
this->m_bFullDisplay=bFullDisplay;
this->m_bShowMask=FALSE;
this->m_bSwap=bSwap;
}
VirtualKeyboard_Key::~VirtualKeyboard_Key()
{
for (int i=0; i<2; i++)
{
if (this->m_lpszDisplay[i])
{
LocalFree(this->m_lpszDisplay[i]);
this->m_lpszDisplay[i]=NULL;
}
}
}
void VirtualKeyboard_Key::SetText( char *lpszValue, char **lppszDisplay, int size )
{
int len;
if (lpszValue && lppszDisplay)
{
this->m_nMaxIndex=size;
for (int i=0; i<size; i++)
{
this->m_lpszValue[i]=lpszValue[i];
if (this->m_lpszDisplay[i])
{
LocalFree(this->m_lpszDisplay[i]);
this->m_lpszDisplay[i]=NULL;
}
if (lppszDisplay[i])
{
len=strlen(lppszDisplay[i]);
this->m_lpszDisplay[i]=(char*)LocalAlloc(LMEM_FIXED, len+1);
CopyMemory(this->m_lpszDisplay[i], lppszDisplay[i], len+1);
}
}
}
}
void VirtualKeyboard_Key::ShowMask(BOOL bShowMask)
{
this->m_bShowMask=bShowMask;
this->Invalidate();
}
void VirtualKeyboard_Key::_OnPaintText( HDC hdc, COLORREF color )
{
SetBkMode(hdc, TRANSPARENT);
if (this->m_bShowMask)
{
SetTextColor(hdc, color);
DrawTextA(hdc, "*", -1, &this->m_rcContent, DT_SINGLELINE|DT_CENTER|DT_VCENTER);
}
else if (this->m_bFullDisplay)
{
if (this->m_nIndexActive==0)
{
SetTextColor(hdc, color);
}
else
{
SetTextColor(hdc, RGB(110, 110, 116));
}
DrawTextA(hdc, this->m_lpszDisplay[0], -1, &this->m_rcContent, DT_RIGHT|DT_SINGLELINE|DT_BOTTOM);
if (this->m_nIndexActive==1)
{
SetTextColor(hdc, color);
}
else
{
SetTextColor(hdc, RGB(110, 110, 116));
}
DrawTextA(hdc, this->m_lpszDisplay[1], -1, &this->m_rcContent, DT_LEFT|DT_SINGLELINE|DT_TOP);
}
else
{
SetTextColor(hdc, color);
DrawTextA(hdc, this->m_lpszDisplay[this->m_nIndexActive], -1, &this->m_rcContent, DT_CENTER|DT_SINGLELINE|DT_VCENTER);
}
}
int VirtualKeyboard_Key::GetIndexActive()
{
return this->m_nIndexActive;
}
void VirtualKeyboard_Key::SetIndexActive( int index )
{
int old;
if (this->m_nMaxIndex<2) return;
old=this->m_nIndexActive;
this->m_nIndexActive=index;
if (old!=index)
this->Invalidate();
}
void VirtualKeyboard_Key::SwitchActive()
{
if (this->m_nMaxIndex>1)
{
this->m_nIndexActive=1-this->m_nIndexActive;
this->Invalidate();
}
}
BOOL VirtualKeyboard_Key::IsControl()
{
return this->m_bControlKey;
}
int VirtualKeyboard_Key::GetMaxIndex()
{
return this->m_nMaxIndex;
}
BOOL VirtualKeyboard_Key::IsFulLDisplay()
{
return this->m_bFullDisplay;
}
BOOL VirtualKeyboard_Key::IsSwap()
{
return this->m_bSwap;
}
char VirtualKeyboard_Key::GetValue()
{
if (this->m_nMaxIndex>0)
{
return this->m_lpszValue[this->m_nIndexActive];
}
return 0;
}
char* VirtualKeyboard_Key::GetName()
{
if (this->m_nMaxIndex>0)
{
return this->m_lpszDisplay[this->m_nIndexActive];
}
return NULL;
}
|
ada440a605ecbeced7ed2b56bfb719e64bd21700 | 004b80d4a27868f8248e17aad226b19861f3dc55 | /keyboard_multitone.ino | 531203a52389ba392b0c6bf8e0ed943ef667f25f | [] | no_license | mit-mit-randomprojectlab/keyboard_multitone | a73998637cd95be994f3e0016f93a684aeb79b3c | db467e82948b3326a84224e80628fa9aded40473 | refs/heads/master | 2021-01-11T01:32:59.831341 | 2016-10-12T11:16:02 | 2016-10-12T11:16:02 | 70,691,674 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 10,645 | ino | keyboard_multitone.ino | /*
keyboard_multitone - sketch to test basic keyboard matrix using teensy
and using a custom implementation of "Tone" (square-wave generation) that uses
all four PIT timers to generate up to four simultaneous tones.
Code for PIT timers largely derived and simplified from Teensy "IntervalTimer.cpp" in
hardware/teensy/avr/cores/teensy3/IntervalTimer.cpp
By mit-mit
*/
#include "kinetis.h"
#include "core_pins.h"
#include "pins_arduino.h"
#include "HardwareSerial.h"
#include "pitches.h"
// Multi-tone Stuff
static uint32_t tone_toggle_count0;
static uint32_t tone_toggle_count1;
static uint32_t tone_toggle_count2;
static uint32_t tone_toggle_count3;
static volatile uint8_t *tone_reg0;
static volatile uint8_t *tone_reg1;
static volatile uint8_t *tone_reg2;
static volatile uint8_t *tone_reg3;
static uint8_t tone_state0=0;
static uint8_t tone_state1=0;
static uint8_t tone_state2=0;
static uint8_t tone_state3=0;
static float tone_usec0=0.0;
static float tone_usec1=0.0;
static float tone_usec2=0.0;
static float tone_usec3=0.0;
static uint32_t tone_new_count0=0;
static uint32_t tone_new_count1=0;
static uint32_t tone_new_count2=0;
static uint32_t tone_new_count3=0;
#define TONE_CLEAR_PIN0 tone_reg0[0] = 1
#define TONE_CLEAR_PIN1 tone_reg1[0] = 1
#define TONE_CLEAR_PIN2 tone_reg2[0] = 1
#define TONE_CLEAR_PIN3 tone_reg3[0] = 1
#define TONE_TOGGLE_PIN0 tone_reg0[128] = 1
#define TONE_TOGGLE_PIN1 tone_reg1[128] = 1
#define TONE_TOGGLE_PIN2 tone_reg2[128] = 1
#define TONE_TOGGLE_PIN3 tone_reg3[128] = 1
#define TONE_OUTPUT_PIN0 tone_reg0[384] = 1
#define TONE_OUTPUT_PIN1 tone_reg1[384] = 1
#define TONE_OUTPUT_PIN2 tone_reg2[384] = 1
#define TONE_OUTPUT_PIN3 tone_reg3[384] = 1
uint8_t soundpins[] = {8,17,18,19};
//uint8_t soundpins[] = {19,8,8,8};
static bool PIT_enabled = false;
void enable_PIT() {
SIM_SCGC6 |= SIM_SCGC6_PIT;
PIT_MCR = 0;
PIT_enabled = true;
}
typedef volatile uint32_t* reg;
reg PIT_LDVAL;
reg PIT_TCTRL;
uint8_t IRQ_PIT_CH;
void start_PIT(uint8_t PIT_id, uint32_t newValue) {
// point to the correct registers
PIT_LDVAL = &PIT_LDVAL0 + PIT_id * 4;
PIT_TCTRL = &PIT_TCTRL0 + PIT_id * 4;
// write value to register and enable interrupt
*PIT_TCTRL = 0;
*PIT_LDVAL = newValue;
*PIT_TCTRL = 3;
IRQ_PIT_CH = IRQ_PIT_CH0 + PIT_id;
NVIC_SET_PRIORITY(IRQ_PIT_CH, 128);
NVIC_ENABLE_IRQ(IRQ_PIT_CH);
}
// Interupt functions
void pit0_isr() {
PIT_TFLG0 = 1;
TONE_TOGGLE_PIN0; // toggle
tone_toggle_count0--;
if (tone_toggle_count0 == 0xFFFFFFFB) tone_toggle_count0 = 0xFFFFFFFD;
}
void pit1_isr() {
PIT_TFLG1 = 1;
TONE_TOGGLE_PIN1; // toggle
tone_toggle_count1--;
if (tone_toggle_count1 == 0xFFFFFFFB) tone_toggle_count1 = 0xFFFFFFFD;
}
void pit2_isr() {
PIT_TFLG2 = 1;
TONE_TOGGLE_PIN2; // toggle
tone_toggle_count2--;
if (tone_toggle_count2 == 0xFFFFFFFB) tone_toggle_count2 = 0xFFFFFFFD;
}
void pit3_isr() {
PIT_TFLG3 = 1;
TONE_TOGGLE_PIN3; // toggle
tone_toggle_count3--;
if (tone_toggle_count3 == 0xFFFFFFFB) tone_toggle_count3 = 0xFFFFFFFD;
}
void tone_multi(uint8_t channel, uint16_t frequency, uint32_t duration)
{
uint32_t count;
volatile uint32_t *config;
float usec;
uint32_t newValue;
uint8_t pin = soundpins[channel];
if (pin >= CORE_NUM_DIGITAL) return;
if (duration > 0) {
count = (frequency * duration / 1000) * 2;
if (!(count & 1)) count++; // always full waveform cycles
} else {
count = 0xFFFFFFFD;
}
usec = (float)500000.0 / (float)frequency;
config = portConfigRegister(pin);
__disable_irq();
if (channel == 0) {
if (0) { //(tone_state0 == 1) {
tone_usec0 = usec;
tone_new_count0 = count;
tone_toggle_count0 = (tone_toggle_count0 & 1);
}
else {
//TONE_CLEAR_PIN0;
tone_state0 = 1;
tone_reg0 = portClearRegister(pin);
TONE_CLEAR_PIN0; // clear pin
TONE_OUTPUT_PIN0; // output mode;
*config = PORT_PCR_SRE | PORT_PCR_DSE | PORT_PCR_MUX(1);
tone_toggle_count0 = count;
tone_usec0 = usec;
newValue = (float)(F_BUS / 1000000) * usec - 0.5;
if (!PIT_enabled) enable_PIT();
start_PIT(channel,newValue);
}
}
else if (channel == 1) {
if (0) { //(tone_state1 == 1) {
tone_usec1 = usec;
tone_new_count1 = count;
tone_toggle_count1 = (tone_toggle_count1 & 1);
}
else {
//TONE_CLEAR_PIN1;
tone_state1 = 1;
tone_reg1 = portClearRegister(pin);
TONE_CLEAR_PIN1; // clear pin
TONE_OUTPUT_PIN1; // output mode;
*config = PORT_PCR_SRE | PORT_PCR_DSE | PORT_PCR_MUX(1);
tone_toggle_count1 = count;
tone_usec1 = usec;
newValue = (float)(F_BUS / 1000000) * usec - 0.5;
if (!PIT_enabled) enable_PIT();
start_PIT(channel,newValue);
}
}
else if (channel == 2) {
if (0) { //(tone_state2 == 1) {
tone_usec2 = usec;
tone_new_count2 = count;
tone_toggle_count2 = (tone_toggle_count2 & 1);
}
else {
//TONE_CLEAR_PIN2;
tone_state2 = 1;
tone_reg2 = portClearRegister(pin);
TONE_CLEAR_PIN2; // clear pin
TONE_OUTPUT_PIN2; // output mode;
*config = PORT_PCR_SRE | PORT_PCR_DSE | PORT_PCR_MUX(1);
tone_toggle_count2 = count;
tone_usec2 = usec;
newValue = (float)(F_BUS / 1000000) * usec - 0.5;
if (!PIT_enabled) enable_PIT();
start_PIT(channel,newValue);
}
}
else {
if (0) { //(tone_state3 == 1) {
tone_usec3 = usec;
tone_new_count3 = count;
tone_toggle_count3 = (tone_toggle_count3 & 1);
}
else {
//TONE_CLEAR_PIN3;
tone_state3 = 1;
tone_reg3 = portClearRegister(pin);
TONE_CLEAR_PIN3; // clear pin
TONE_OUTPUT_PIN3; // output mode;
*config = PORT_PCR_SRE | PORT_PCR_DSE | PORT_PCR_MUX(1);
tone_toggle_count3 = count;
tone_usec3 = usec;
newValue = (float)(F_BUS / 1000000) * usec - 0.5;
if (!PIT_enabled) enable_PIT();
start_PIT(channel,newValue);
}
}
__enable_irq();
}
void noTone_multi(uint8_t channel)
{
uint8_t pin = soundpins[channel];
if (pin >= CORE_NUM_DIGITAL) return;
__disable_irq();
PIT_TCTRL = &PIT_TCTRL0 + channel * 4;
IRQ_PIT_CH = IRQ_PIT_CH0 + channel;
*PIT_TCTRL = 0;
NVIC_DISABLE_IRQ(IRQ_PIT_CH);
if (channel == 0) {
if (tone_state0 == 1) {
TONE_CLEAR_PIN0; // clear
tone_state0 = 0;
}
}
else if (channel == 1) {
if (tone_state1 == 1) {
TONE_CLEAR_PIN1; // clear
tone_state1 = 0;
}
}
else if (channel == 2) {
if (tone_state2 == 1) {
TONE_CLEAR_PIN2; // clear
tone_state2 = 0;
}
}
else {
if (tone_state3 == 1) {
TONE_CLEAR_PIN3; // clear
tone_state3 = 0;
}
}
__enable_irq();
}
// Stuff for running keyboard
char keystate[49] = {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,0,0,0,0,0,
0,0,0,0,0,0,
0,0,0,0,0,0,
0};
char keystate_prev[49] = {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,0,0,0,0,0,
0,0,0,0,0,0,
0,0,0,0,0,0,
0};
char keystate_channel[49] = {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,0,0,0,0,0,
0,0,0,0,0,0,
0,0,0,0,0,0,
0};
char pins_rows[6] = {5,4,3,2,1,0};
char pins_cols[9] = {11,14,16,6,7,10,12,15,9};
char current_channel = 0;
char channel_keyids[4] = {255,255,255,255};
char channel_keyids_prev[4] = {255,255,255,255};
void init_keys() {
for (int i = 0; i < 6; i++) {
pinMode(pins_rows[i], OUTPUT);
digitalWrite(pins_rows[i], LOW);
}
for (int i = 0; i < 9; i++) {
pinMode(pins_cols[i], OUTPUT);
digitalWrite(pins_cols[i], HIGH);
}
}
// read_keys - Implements switch matrix
void read_keys() {
int k = 0;
// Read bottom C
digitalWrite(pins_cols[0], LOW);
pinMode(pins_rows[5], INPUT_PULLUP);
delayMicroseconds(10);
if (digitalRead(pins_rows[5])) {
keystate[k] = 0;
}
else {
keystate[k] = 1;
}
pinMode(pins_rows[5], OUTPUT);
digitalWrite(pins_rows[5], LOW);
k++;
digitalWrite(pins_cols[0], HIGH);
// Read remaining keys
for (int i = 1; i < 9; i++) {
digitalWrite(pins_cols[i], LOW);
for (int j = 0; j < 6; j++) {
pinMode(pins_rows[j], INPUT_PULLUP);
delayMicroseconds(10);
if (digitalRead(pins_rows[j])) {
keystate[k] = 0;
}
else {
keystate[k] = 1;
}
pinMode(pins_rows[j], OUTPUT);
digitalWrite(pins_rows[j], LOW);
k++;
delayMicroseconds(50);
}
digitalWrite(pins_cols[i], HIGH);
}
}
void setup() {
//Serial.begin(9600);
// setup pin 13 LED for when keys pressed
pinMode(13, OUTPUT);
// Initialise all pins ready for cycling through reading
init_keys();
// initialise key/channel data
for (int i = 0; i < 49; i++) {
keystate_channel[i] = 255;
}
}
void loop() {
// read keys
read_keys();
// assign notes on multiple channels
int played_note = 0;
for (int i = 0; i < 49; i++) {
if (keystate[i] == 1) {
digitalWrite(13, HIGH);
played_note = 1;
if ( (keystate_prev[i] == 0) || (keystate_channel[i] == 255) ) { // start up a key
for (int channel = 0; channel < 3; channel++) { // look for a channel
if (channel_keyids[channel] == 255) { // was free
keystate_channel[i] = channel;
channel_keyids[channel] = i;
break;
}
else if (channel_keyids[channel] < i) { // was taken by a lower key, grab it
keystate_channel[(int)channel_keyids[channel]] = 255; // tell other key it no longer has channel
keystate_channel[i] = channel;
channel_keyids[channel] = i;
break;
}
}
}
}
else if (keystate_prev[i] == 1) { // key just got turned off
if (keystate_channel[i] < 255) { // has a channel, need to turn off
channel_keyids[(int)keystate_channel[i]] = 255;
keystate_channel[i] = 255;
}
}
}
// fire up tones/turn off tones
for (int i = 0; i < 3; i++) {
if (channel_keyids[i] != channel_keyids_prev[i]) { // key assigned to channel changed
if (channel_keyids[i] == 255) {
noTone_multi(i);
}
else {
tone_multi(i, pitches[channel_keyids[i]+25], 0);
}
}
}
// Update previous states
for (int i = 0; i < 49; i++) {
keystate_prev[i] = keystate[i];
}
for (int i = 0; i < 3; i++) {
channel_keyids_prev[i] = channel_keyids[i];
}
if (played_note == 0) { // light up keyboard
digitalWrite(13, LOW);
}
}
|
524dc2ac79b318863422f4c245288054fce3c4b3 | da09c47cd83e1b5a7870c454dd4c73fe4a9aa6e4 | /hello_world.cpp | 4e5938564a416b011cc0d7185877b1410643dfe3 | [] | no_license | myk7hackon/SystemC-Introduction | f30e84dc70ed69868da07b958f5213444f04c1db | 1dd6d2bfb2cb08e42dc71cadfaf1afcecc5c2a00 | refs/heads/master | 2020-03-31T04:49:25.259818 | 2018-10-07T08:34:29 | 2018-10-07T08:34:29 | 151,921,102 | 0 | 0 | null | 2018-10-07T08:33:13 | 2018-10-07T08:33:13 | null | UTF-8 | C++ | false | false | 555 | cpp | hello_world.cpp | #include "systemc.h"
#include <iostream>
SC_MODULE(simple_process_ex) {
sc_time t;
void my_thread_process(void);
SC_CTOR(simple_process_ex) {
t = sc_time(10, SC_NS);
//SC_THREAD(my_thread_process);
}
};
void simple_process_ex::my_thread_process(void) {
std::cout << "MY THREAD EXECUTED\n"<<name()<<std::endl;
}
int sc_main(int i, char* c[]) {
std::cout << sc_time_stamp()<<std::endl;
sc_simulation_time(10,SC_SEC);
std::cout << sc_time_stamp() << std::endl;
simple_process_ex obj("igh");
sc_start(10,SC_SEC);
return 0;
} |
098f07ade366d2382b9ba593428ec8bb344afacf | a33aac97878b2cb15677be26e308cbc46e2862d2 | /program_data/PKU_raw/103/798.c | 40678f9863e9fb2fe8d7547ed810da4c864e85ae | [] | no_license | GabeOchieng/ggnn.tensorflow | f5d7d0bca52258336fc12c9de6ae38223f28f786 | 7c62c0e8427bea6c8bec2cebf157b6f1ea70a213 | refs/heads/master | 2022-05-30T11:17:42.278048 | 2020-05-02T11:33:31 | 2020-05-02T11:33:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 436 | c | 798.c | int main()
{
char str[1010], mark;
int i, j, sum;
cin >> str;
i = j = 0;
do{
sum = 0;
do{
j++;
sum++;
}while(str[i] - 'A' == str[j] - 'A'
|| str[i] - 'A' == str[j] - 'a'
|| str[i] - 'a' == str[j] - 'A');
if (str[i] >= 'a' && str[i] <= 'z')
mark = str[i] - 'a' + 'A';
else
mark = str[i];
cout << "(" << mark << "," << sum << ")";
i = j;
}while(str[i] != '\0');
return 0;
} |
a8554d256b4ee48e0be5da9b53414276762c3ca4 | d82bf080ddd6caadf252f40d204d46e3f7fae42f | /kursova/basemanager.cpp | 195476f53585d8a99f31479f15d3b70e0b4ebf36 | [] | no_license | asofter/kpz-university | c190d620317bcbf99d29e085b3da22e177290a6f | 39acf69728c6921e11861e1b487f13baf0c9251d | refs/heads/master | 2020-06-05T22:34:26.199105 | 2014-05-29T08:36:01 | 2014-05-29T08:36:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,033 | cpp | basemanager.cpp | #include "basemanager.h"
BaseManager::BaseManager(QObject *parent) :
QObject(parent)
{
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("catalog.sqlite");
bool ok = db.open();
qDebug()<<ok;
// Init models
categoryModel = new CategoryModel();
subcategoryModel = new SubcategoryModel();
companyModel = new CompanyModel();
}
void BaseManager::createBase()
{
categoryModel->createTable();
subcategoryModel->createTable();
companyModel->createTable();
}
void BaseManager::addCategory(QString name)
{
categoryModel->add(name);
}
void BaseManager::addSubcategory(QString name, QString catName)
{
QString catId = categoryModel->catIdByName(catName);
subcategoryModel->add(name, catId);
}
void BaseManager::addCompany(QStringList data, QString subName)
{
QString subCategoryId = subcategoryModel->subcatIdByName(subName);
companyModel->add(data, subCategoryId);
}
void BaseManager::delCategory(QString name)
{
categoryModel->del(name);
}
void BaseManager::delSubcategory(QString name)
{
subcategoryModel->del(name);
}
void BaseManager::delCompany(QString name)
{
companyModel->del(name);
}
QStringList BaseManager::categoryList()
{
return categoryModel->list();
}
QStringList BaseManager::subcategoryList(QString name)
{
QString catId = categoryModel->catIdByName(name);
return subcategoryModel->list(catId);
}
QStringList BaseManager::companyList(QString name)
{
QString subCategoryId = subcategoryModel->subcatIdByName(name);
return companyModel->list(subCategoryId);
}
QStringList BaseManager::companyDataByName(QString name)
{
return companyModel->dataByName(name);
}
void BaseManager::updateCompany(QStringList list)
{
companyModel->update(list);
}
void BaseManager::updateCategory(QString newName, QString oldName)
{
categoryModel->update(newName, oldName);
}
void BaseManager::updateSubcategory(QString newName, QString oldName)
{
subcategoryModel->update(newName, oldName);
}
|
484688d6346af87170c7cd9f04ce46aad943a3b7 | 091afb7001e86146209397ea362da70ffd63a916 | /inst/include/nt2/include/functions/scalar/function_index.hpp | 3980a16d1fe4f47ca7ce1e6ea06d06f80222984c | [] | no_license | RcppCore/RcppNT2 | f156b58c08863243f259d1e609c9a7a8cf669990 | cd7e548daa2d679b6ccebe19744b9a36f1e9139c | refs/heads/master | 2021-01-10T16:15:16.861239 | 2016-02-02T22:18:25 | 2016-02-02T22:18:25 | 50,460,545 | 15 | 1 | null | 2019-11-15T22:08:50 | 2016-01-26T21:29:34 | C++ | UTF-8 | C++ | false | false | 203 | hpp | function_index.hpp | #ifndef NT2_INCLUDE_FUNCTIONS_SCALAR_FUNCTION_INDEX_HPP_INCLUDED
#define NT2_INCLUDE_FUNCTIONS_SCALAR_FUNCTION_INDEX_HPP_INCLUDED
#include <nt2/core/include/functions/scalar/function_index.hpp>
#endif
|
a658983dd44b114873ff2c7e680074218c2ec8f9 | 6467bb08e02e7bb47a59ad7d512926d70da3c5f5 | /tags/http_v4_committed/themis/modules/HTMLParser/DeclarationParser.hpp | 173d03ee4831be3e658d501600d25237cd403300 | [] | no_license | svn2github/Themis | 1ed26434317a30c61e751eb9800ea96077b6c73c | 20be549491930fe86246ff748c55139201ead7a8 | refs/heads/master | 2020-12-25T15:28:53.785606 | 2018-03-12T21:55:53 | 2018-03-12T21:55:53 | 61,454,928 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 921 | hpp | DeclarationParser.hpp | /* DeclarationParser
Provides the base functionality for declaration parsers
Mark Hellegers (M.H.Hellegers@stud.tue.nl)
12-04-2003
*/
#ifndef DECLARATIONPARSER_HPP
#define DECLARATIONPARSER_HPP
// Standard C++ headers
#include <map>
#include <string>
// SGMLParser headers
#include "BaseParser.hpp"
#include "Position.hpp"
// Namespaces used
using namespace std;
class DeclarationParser : public BaseParser {
public:
DeclarationParser( SGMLTextPtr aDocText, TDocumentPtr aDTD );
virtual ~DeclarationParser();
void setDocText( SGMLTextPtr aDocText );
void setDTD( TDocumentPtr aDTD );
bool parse( const map<string, Position> & aEntityTexts );
bool parse(); // If you don't need entities
virtual bool processDeclaration();
bool processExtEntitySpec( TElementPtr & entity );
bool processExternalId( TElementPtr & entity );
string processPublicId();
string processSystemId();
};
#endif
|
66b38268e819def1a0d735aee4283de32d13aa8d | b960608c94682165cb8e5c7674b614601152d396 | /com_meigSmart_RecoveryMp4_MainActivity.cpp | 29efdecc49aaba82702aa537d1e95e93ddafa1d5 | [] | no_license | BestAndroider/mp4-recovery-untrack-with-no-moov | e21ede17c9981889c4f2b1acbb26481e77008e54 | ccb85373795f791299a92cb57a9ccff1e323cb5c | refs/heads/master | 2021-01-05T16:33:35.614274 | 2018-05-29T06:15:54 | 2018-05-29T06:15:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,892 | cpp | com_meigSmart_RecoveryMp4_MainActivity.cpp | #include <jni.h>
#include "mp4.h"
#include "atom.h"
#include "com_meigSmart_RecoveryMp4_MainActivity.h"
using namespace std;
//将const char类型转换成jstring类型
jstring CStr2Jstring0(JNIEnv* env, const char* pat )
{
// 定义java String类 strClass
jclass strClass = (env)->FindClass("java/lang/String;");
// 获取java String类方法String(byte[],String)的构造器,用于将本地byte[]数组转换为一个新String
jmethodID ctorID = (env)->GetMethodID(strClass, "<init>", "([BLjava/lang/String;)V");
// 建立byte数组
jbyteArray bytes = (env)->NewByteArray((jsize)strlen(pat));
// 将char* 转换为byte数组
(env)->SetByteArrayRegion(bytes, 0, (jsize)strlen(pat), (jbyte*)pat);
//设置String, 保存语言类型,用于byte数组转换至String时的参数
jstring encoding = (env)->NewStringUTF("GB2312");
//将byte数组转换为java String,并输出
return (jstring)(env)->NewObject(strClass, ctorID, bytes, encoding);
}
char * Jstring2CStr0( JNIEnv * env, jstring jstr )
{
char * rtn = NULL;
jclass clsstring = env->FindClass("java/lang/String");
jstring strencode = env->NewStringUTF("GB2312");
jmethodID mid = env->GetMethodID(clsstring, "getBytes", "(Ljava/lang/String;)[B");
jbyteArray barr= (jbyteArray)env->CallObjectMethod(jstr,mid,strencode);
jsize alen = env->GetArrayLength(barr);
jbyte * ba = env->GetByteArrayElements(barr,JNI_FALSE);
if(alen > 0)
{
rtn = (char*)malloc(alen+1); //new char[alen+1];
memcpy(rtn,ba,alen);
rtn[alen]=0;
}
env->ReleaseByteArrayElements(barr,ba,0);
return rtn;
}
jstring CharTojstring0(JNIEnv* env, char* str)
{
jsize len = strlen(str);
jclass clsstring = env->FindClass("java/lang/String");
jstring strencode = env->NewStringUTF("GB2312");
jmethodID mid = env->GetMethodID(clsstring,"<init>","([BLjava/lang/String;)V");
jbyteArray barr = env-> NewByteArray(len);
env-> SetByteArrayRegion(barr,0,len,(jbyte*)str);
return (jstring)env-> NewObject(clsstring,mid,barr,strencode);
}
std::string jstring2str(JNIEnv* env, jstring jstr)
{
char* rtn = NULL;
jclass clsstring = env->FindClass("java/lang/String");
jstring strencode = env->NewStringUTF("GB2312");
jmethodID mid = env->GetMethodID(clsstring, "getBytes", "(Ljava/lang/String;)[B");
jbyteArray barr= (jbyteArray)env->CallObjectMethod(jstr,mid,strencode);
jsize alen = env->GetArrayLength(barr);
jbyte* ba = env->GetByteArrayElements(barr,JNI_FALSE);
if(alen > 0){
rtn = (char*)malloc(alen+1);
memcpy(rtn,ba,alen);
rtn[alen]=0;
}
env->ReleaseByteArrayElements(barr,ba,0);
std::string
stemp(rtn);
free(rtn);
return stemp;
}
void doExecuteRepairResult(JNIEnv * env, jobject obj, jstring sdp) {
// 1.找到java的MainActivity的class
jclass clazz = env->FindClass("com/meigSmart/RecoveryMp4/MainAcitivity");
if (clazz == 0) {
LOG("can't find clazz");
}
LOG(" find clazz");
//2 找到class 里面的方法定义
jmethodID methodid = env->GetMethodID(clazz, "NotifyRepairResult", "(Ljava/lang/String;)V");
if (methodid == 0) {
LOG("can't find methodid");
}
LOG(" find methodid");
//3 .调用方法
env->CallVoidMethod(clazz, methodid, sdp);
}
JNIEXPORT jint JNICALL Java_com_meigSmart_RecoveryMp4_MainActivity_RepairFile(JNIEnv *env, jobject obj, jstring ok_file, jstring broken_file )
{
//own_env = env;
string ok = jstring2str(env,ok_file);
string corrupt = jstring2str(env,broken_file);
LOG(" ok path=%s,broken_path=%s",ok.c_str(),corrupt.c_str());
Mp4 mp4;
mp4.open(ok);
if(corrupt.size()) {
mp4.repair(corrupt);
mp4.saveVideo(corrupt + "_fixed.mp4");
}
//doExecuteRepairResult(CStr2Jstring0("OK"));
return 0;
}
|
94ca4570fd7187394867e5b54fe904248595356b | 174d618939a1218b18d87bffa1f139e98b40cae7 | /src/plugins/detector/LumiGEM/LumiGEMlib/clustering/cClusterFinder.cxx | 6668e9b5cc21ce56a0d1e874098bef2c73d7de17 | [] | no_license | bishoyDHD/museMiniCkr | 5188183af70a67f75bc48802a3d7d2607e20b7b4 | d40f3978376bb760d80edb23249ca9e124a4efb3 | refs/heads/master | 2020-07-24T12:10:08.697014 | 2019-09-13T19:15:38 | 2019-09-13T19:15:38 | 207,921,163 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,745 | cxx | cClusterFinder.cxx | #include "TGraph.h"
#include "TMath.h"
#include "math.h"
#include "cClusterFinder.h"
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
cClusterFinder::cClusterFinder(int nx, int ny)
//! Constructor for the GEM Hit Finder
//! nx, ny are the number of samples in x and y.
{
nsa[0] = nx;
nsa[1] = ny;
verbosity = 0;
preprocessMethod = ppNone;
clusteringMethod = mGaussFit;
for (int i=0; i<NUMAXES; i++)
{
data[i] = new int[nx];
validdata[i] = false;
locmaxlist[i] = new int[100];
nlocmax[i] = 0;
locmaxmindist[i] = 5;
locmaxthreshold[i] = 100;
clusterminsigma[i] = 0.45;
clustermaxsigma[i] = 1.10;
};
refgauss = new TF1("refgauss", "gaus");
refgauss->SetParameters(1.0, 0.0, 1.0);
refgaussarray = new double[11];
refgaussarray += 5;
for (int i=-5; i<=+5; i++)
refgaussarray[i] = refgauss->Eval(double(i));
}
cClusterFinder::~cClusterFinder()
//! Destructor for the GEM Hit Finder
{
printf("d'tor\n");
delete[] data[0];
delete[] data[1];
delete refgaussarray;
delete refgauss;
}
////////////////////////////////////////////////////////////
int cClusterFinder::UseGEMData(cGEM *gem)
//! Get x and y data from cGEM object.
{
if (gem==NULL)
return 1;
if (gem->GetXdata(data[0])) validdata[0] = true;
if (gem->GetYdata(data[1])) validdata[1] = true;
return 0;
}
int cClusterFinder::UseXData(int *datax)
//! Copy data provided in array datax to internal x dataset.
{
if (datax==NULL)
return 1;
for (int i=0; i<nsa[0]; i++)
data[0][i] = datax[i];
validdata[0] = true;
return 0;
}
int cClusterFinder::UseYData(int *datay)
//! Copy data provided in array datay to internal y dataset.
{
if (datay==NULL)
return 1;
for (int i=0; i<nsa[1]; i++)
data[1][i] = datay[i];
validdata[1] = true;
return 0;
}
int cClusterFinder::SetPreProcessMethod(ePreProcess m, char *options)
{
preprocessMethod = m;
return m;
}
int cClusterFinder::SetClusteringMethod(eClustMethod m, char *options)
{
clusteringMethod = m;
return m;
}
int cClusterFinder::PreProcess()
//! Preprocess the data.
{
switch(preprocessMethod)
{
case ppNone:
break;
case ppRemoveLinearBaseline:
if (validdata[0]) RemoveLinearBaseLine(nsa[0], data[0]);
if (validdata[1]) RemoveLinearBaseLine(nsa[1], data[1]);
break;
default:
if (verbosity) printf(" cClusterFinder::PreProcess(): Unknown method %d!\n", preprocessMethod);
return 1;
};
return 0;
}
int cClusterFinder::Clustering()
//! Locate local maxima in the datasets and perform selected
//! clustering algorithm on local maxima.
{
if (validdata[0]) FindLocalMaxima(nsa[0], data[0], locmaxlist[0], nlocmax[0], locmaxmindist[0], locmaxthreshold[0]);
if (validdata[1]) FindLocalMaxima(nsa[1], data[1], locmaxlist[1], nlocmax[1], locmaxmindist[1], locmaxthreshold[1]);
switch(clusteringMethod)
{
case mGaussFit:
//CheckClusterCandidate();
break;
case mGaussTemplate:
break;
default:
if (verbosity) printf(" cClusterFinder::Clustering(): Unknown method %d!\n", clusteringMethod);
return 1;
};
return 0;
}
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
int cClusterFinder::RemoveLinearBaseLine(int n, int *dat)
//!
//! Fit equation of a line f=mx+b to the APV frame samples
//! and subtract the fit function from the data then.
//!
{
return 0;
// dump data into a TGraph object:
int *index = new int[n];
for (int i=0; i<n; i++)
index[i] = (int)i;
TGraph *gtmp = new TGraph(n, index, dat);
// fit linear baseline:
TF1 *fpol1 = new TF1("fpol1", "pol1", 0, n-1);
gtmp->Fit(fpol1, "QN", "");
// get parameters of fpol1(x) = m*x + b
double b = fpol1->GetParameter(0);
double m = fpol1->GetParameter(1);
// remove linear baseline from data array:
for (int i=0; i<n; i++)
{
double baseline = m*double(index[i])+b;
dat[i] -= baseline;
};
// clean up a bit:
delete fpol1;
delete gtmp;
delete[] index;
return 0;
}
int cClusterFinder::FindLocalMaxima(int n, int *dat, int *list, int nmaxima, int mindist, int threshold)
//! Method to find local maxima in a data array.
//! n: number of data points in array
//! dat: data array
//! list: list with local maxima positions found
//! nmaxima: max. number of local maxima to serach for
//! mindist: minimum distance between two local maxima
//! threshold: minimum amplitude of local maximum to be accepted
//! verbosity: 0=quiet, 1=some output, 2=more debugging output
//! The method returns the number of local maxima that were found in the
//! data. Alternatively the user can as well loop over the list and stop
//! when the terminating "-1" is found to determine the number of list
//! elements.
{
int lmcnt=0;
for (int nlm=0; nlm<nmaxima; nlm++)
{
int loc = -1;
int amp = -1;
// Loop over data array:
for (int i=0; i<n; i++)
{
// Sample higher than the previous highest one?
if (dat[i]>amp)
{
// Check if we're not in the vicinity of any previously found local maximum:
bool isolated=true;
for (int j=0; j<lmcnt; j++)
if (abs(i-list[j])<mindist)
{
isolated=false;
break;
};
// Only if the candidate is not close to a previously found l.m.:
if (isolated)
{
amp = dat[i];
loc = i;
};
};
};
// If new local maximum is below threshold we can stop here:
if (amp<threshold) break;
// Otherwise we have found another local maximum:
list[lmcnt] = loc;
lmcnt++;
};
// Put termination mark at the end of the list:
list[lmcnt] = -1;
return lmcnt;
}
double cClusterFinder::ChiGauss(int n, int *data, int pos, double *pedestalval, TGraph *peakgraph)
//!
//! Calculate sum of squares normalized to amplitude of a
//! peak candidate assuming a typical Gaussian.
//! Parameters needed:
//! width of peak window
//! width of pedestal side windows (around peak window)
//!
//! If pedestalval is not NULL it will be used to store the
//! value of the pedestal.
//! If peakgraph is not NULL it will be used to return a
//! graph of the "testpeak".
//!
{
double pedestal = 0.0;
int pedfrom = 3;
int pedto = 5;
int xsafrom = 0;
int xsato = n;
int cnt=0;
if (verbosity>2) printf("cHitFinder::ChiGauss(): calculating pedestal...\n");
for (int x=pos-pedto; x<=pos+pedto; x++)
{
if ((x<pos-pedfrom)||(x>pos+pedfrom))
if ((x>=xsafrom)&&(x<=xsato))
{
pedestal += double(data[x]);
cnt++;
};
};
pedestal /= cnt;
if (verbosity)
printf(" est ped = %.1lf\n", pedestal);
// guess the amplitude from entries at supposed position
// and pedestal:
double ampl = double(data[pos])-pedestal;
double chisqr = 0.0;
if (verbosity)
printf(" est ampl = %.1lf\n", ampl);
int peakpoints=9;
if (peakgraph)
peakgraph->Set(peakpoints);
if (verbosity>2) printf("cHitFinder::ChiGauss(): calculating chisquare from refgauss...\n");
for (int x=pos-peakpoints/2; x<=pos+peakpoints/2; x++)
{
//double val = refgauss->Eval(double(x-pos))*ampl;
double val = refgaussarray[x-pos]*ampl;
chisqr += pow( double(data[x])
- pedestal
- val
, 2.0);
if (peakgraph)
peakgraph->SetPoint(x-(pos-peakpoints/2), double(x), val + pedestal);
};
// Instead of a reduced chisquare we return the chisquare,
// normalized to the peak amplitude:
if (pedestalval) *pedestalval = pedestal;
gampl = ampl;
gped = pedestal;
if (ampl<40.)
return 99999.9;
return chisqr/pow(ampl, 2.0);
}
int cClusterFinder::CheckClusterCandidate(int locmax, int threshold, int *dat, int *rawdat, int nsamples, LumiGEMhit *hit)
//! Check a cluster candidate by comparing it to a reference cluster waveform.
//! A localmaximum "locmax" from the data array "dat" needs to be provided.
{
double maxchisqr = 1.0;
if (threshold<=0.) return -1;
if (verbosity>2) printf("cHitFinder::CheckClusterCandidate() checking locmax at %d\n", locmax);
// Let's check if the vicinity looks Gaussian or not:
if (verbosity>1) printf("cHitFinder::FindHitCandidate(): calculating chisquare\n");
gchisqr = ChiGauss(nsamples, dat, locmax, NULL, NULL);
if (verbosity>1)
printf("cHitFinder::CheckClusterCandidate(): Candidate @%d has chisqr=%lf\n", locmax, gchisqr);
if (gchisqr>maxchisqr)
return -1;
//
// Explicitly fit a Gaussian to the candidate:
double ampl = dat[locmax];
double mean = locmax;
double sigma = 0.;
TF1 *fpeak = new TF1("fpeak", "pol0(0)+gaus(1)", 0., 1000.);
fpeak->SetParameters(600., ampl, mean, 1.5);
fpeak->SetParLimits(1, ampl/4., ampl*4.);
fpeak->SetParLimits(2, mean-5., mean+5.);
TH1I *dath = new TH1I("dath", "dath", nsamples, -0.5, nsamples-0.5);
for (int sa=0; sa<nsamples; sa++)
{
dath->SetBinContent(sa+1, rawdat[sa]);
dath->SetBinError(sa+1, 1.);
};
dath->Fit(fpeak, "Q", "", mean-5., mean+5.);
ampl = fpeak->GetParameter(1);
mean = fpeak->GetParameter(2);
sigma = fabs(fpeak->GetParameter(3));
delete dath;
if ( (sigma>=clusterminsigma[0])&&(sigma<=clustermaxsigma[0]))
{
if (hit)
{
hit->ampl = ampl;
hit->xl = mean;
hit->yl = -1;
hit->sigma = sigma;
hit->chisquare = fpeak->GetChisquare()/fpeak->GetNDF();
hit->charge = 0;
hit->quality = 1;
};
delete fpeak;
return locmax;
}
else
{
delete fpeak;
return -1;
};
}
|
409fa47e017fd2dae83c26960a0c047f9d7b1ddf | 0c0af780e498f93c700b06f649b864d3e75fd56f | /src/Pleiades_panel.hpp | 5debd5b1aa76f82ae1c9d8325709fbc806a72c9f | [] | no_license | wlaub/vcv | fdb338b69fcfd33c1a1f011837b6bb831864254f | 9d52e49ba0a92a51b733218e02202549b7fb4bf2 | refs/heads/main | 2022-12-22T19:35:36.824217 | 2022-12-18T21:54:59 | 2022-12-18T21:54:59 | 117,328,087 | 10 | 4 | null | 2022-02-06T17:54:06 | 2018-01-13T08:41:12 | C++ | UTF-8 | C++ | false | false | 4,355 | hpp | Pleiades_panel.hpp |
ParamWidget* param;
PortWidget* input;
PortWidget* output;
LightWidget* light;
input = createInputCentered<PJ301MPort>(
Vec(240.362745,45.429099), module, Pleiades::INPUT_CLOCK
);
addInput(input);
input = createInputCentered<PJ301MPort>(
Vec(87.6372525,45.429097), module, Pleiades::INPUT_ANALOG
);
addInput(input);
output = createOutputCentered<PJ301MPort>(
Vec(163.999995,72.0), module, Pleiades::OUTPUT_OUT+3
);
addOutput(output);
output = createOutputCentered<PJ301MPort>(
Vec(60.36812268943471,122.24161106769014), module, Pleiades::OUTPUT_OUT+2
);
addOutput(output);
output = createOutputCentered<PJ301MPort>(
Vec(35.30944304481176,233.3724479082614), module, Pleiades::OUTPUT_OUT+1
);
addOutput(output);
output = createOutputCentered<PJ301MPort>(
Vec(106.72794023571953,322.92817473240893), module, Pleiades::OUTPUT_OUT
);
addOutput(output);
output = createOutputCentered<PJ301MPort>(
Vec(267.6318836444233,122.2416232683049), module, Pleiades::OUTPUT_OUT+4
);
addOutput(output);
output = createOutputCentered<PJ301MPort>(
Vec(292.69055682760586,233.37245373895388), module, Pleiades::OUTPUT_OUT+5
);
addOutput(output);
output = createOutputCentered<PJ301MPort>(
Vec(221.27206326740173,322.9281749333919), module, Pleiades::OUTPUT_OUT+6
);
addOutput(output);
output = createOutputCentered<PJ301MPort>(
Vec(302.1758432674017,313.0111349333919), module, Pleiades::OUTPUT_OUT+7
);
addOutput(output);
addParam(createParamCentered<TTTEncoder>(
Vec(163.999995, 204.0),
module, Pleiades::PARAM_CENTER
));
addParam(createParamCentered<TTTEncoder>(
Vec(163.999995, 116.0),
module, Pleiades::PARAM_STEP+3
));
addParam(createParamCentered<TTTEncoder>(
Vec(233.08792499999998, 149.49441000000002),
module, Pleiades::PARAM_STEP+4
));
addParam(createParamCentered<TTTEncoder>(
Vec(249.793705, 223.58164),
module, Pleiades::PARAM_STEP+5
));
addParam(createParamCentered<TTTEncoder>(
Vec(202.181375, 283.28545),
module, Pleiades::PARAM_STEP+6
));
addParam(createParamCentered<TTTEncoder>(
Vec(125.818625, 283.28545),
module, Pleiades::PARAM_STEP
));
addParam(createParamCentered<TTTEncoder>(
Vec(78.20629600000001, 223.58163000000002),
module, Pleiades::PARAM_STEP+1
));
addParam(createParamCentered<TTTEncoder>(
Vec(94.912082, 149.49440000000004),
module, Pleiades::PARAM_STEP+2
));
addParam(createParamCentered<ITTTEncoder>(
Vec(60.369806, 285.75405),
module, Pleiades::PARAM_MODE+2
));
addParam(createParamCentered<TTTEncoder>(
Vec(25.824171000000003, 313.01119),
module, Pleiades::PARAM_CONFIG
));
addParam(createParamCentered<ITTTEncoder>(
Vec(267.63358500000004, 285.75403),
module, Pleiades::PARAM_MODE+4
));
addParam(createParamCentered<ITTTEncoder>(
Vec(164.00169499999998, 335.99563),
module, Pleiades::PARAM_MODE+3
));
addParam(createParamCentered<ITTTEncoder>(
Vec(292.692285, 174.62319000000002),
module, Pleiades::PARAM_MODE+5
));
addParam(createParamCentered<ITTTEncoder>(
Vec(35.31114600000001, 174.62318),
module, Pleiades::PARAM_MODE+1
));
addParam(createParamCentered<RoundTinyBlackKnob>(
Vec(283.261275, 55.215543),
module, Pleiades::PARAM_CONFIG+2
));
addParam(createParamCentered<ITTTEncoder>(
Vec(221.273775, 85.06745699999999),
module, Pleiades::PARAM_MODE+6
));
addParam(createParamCentered<ITTTEncoder>(
Vec(106.729635, 85.0674405),
module, Pleiades::PARAM_MODE
));
addParam(createParamCentered<ITTTEncoder>(
Vec(44.7421, 55.21555600000001),
module, Pleiades::PARAM_CONFIG+1
));
|
ff26e2b65b644ddc3295601997afef8f74b4d557 | 580f51a5344f94a5a31b2a19943e60ad973e96bc | /sora_test/free_list_block_pool_test.cpp | 94066008f33f71df892a941c58bb1fe2f9ab253d | [] | no_license | weimingtom/sora_old | e22b844d71b99e73fba33309977cca51e7f93d2c | 45f842b3d40948542b859a6e21bed898ab542b6f | refs/heads/master | 2021-01-16T19:11:07.138568 | 2012-05-21T15:46:14 | 2012-05-21T15:46:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,183 | cpp | free_list_block_pool_test.cpp | // Ŭnicode please
#include "sora_test_stdafx.h"
#include "free_list_block_pool.h"
#include <cmath>
using namespace sora;
class KarenBlockTestObj {
public:
KarenBlockTestObj() : a(1) { cnt++; }
~KarenBlockTestObj() { cnt--;}
public:
int a;
static int cnt;
};
int KarenBlockTestObj::cnt = 0;
TEST(FreeListBlockPool, test) {
FreeListBlockPool pool(3, sizeof(KarenBlockTestObj));
EXPECT_EQ(0, KarenBlockTestObj::cnt); //constructor is not called
void *ptr1 = pool.Malloc();
EXPECT_TRUE(ptr1 != NULL);
void *ptr2 = pool.Malloc();
EXPECT_TRUE(ptr2 != NULL);
void *ptr3 = pool.Malloc();
EXPECT_TRUE(ptr3 != NULL);
//KarenTestObj *ptr4 = pool.malloc(); //dead point (too may request)
pool.Free(ptr2);
pool.Free(ptr3);
void *ptr4 = pool.Malloc();
EXPECT_TRUE(ptr4 != NULL);
EXPECT_EQ(ptr4, ptr3); //free list management is stack based;
void *ptr5 = pool.Malloc();
EXPECT_TRUE(ptr5 != NULL);
EXPECT_EQ(ptr5, ptr2);
}
TEST(FreeListBlockPool, blockSize) {
FreeListBlockPool pool(3, sizeof(KarenBlockTestObj));
void *ptr1 = pool.Malloc();
void *ptr2 = pool.Malloc();
EXPECT_EQ(sizeof(KarenBlockTestObj), abs((int)ptr1 - (int)ptr2));
}
|
fafb1a079f1875aa34ab15db10d48367a07a7df9 | 1645ae1285223039cada7f6d436febc4f0e223ad | /Step4_tmva/src/Histograms.cc | dcb59d1acf82fbaec27ef17bbf5a8c1d3147bdb2 | [] | no_license | jordix/analysis-case-study | 2116a6afa9d39788abeb76f054ceb6b36c15820b | 22b3fd1a53d3b624d3bd5ae93eba6e326f3d20cb | refs/heads/master | 2021-01-01T20:35:45.031007 | 2017-08-30T09:03:34 | 2017-08-30T09:03:34 | 98,889,175 | 0 | 0 | null | 2017-07-31T13:00:13 | 2017-07-31T13:00:13 | null | UTF-8 | C++ | false | false | 1,786 | cc | Histograms.cc | #include "TCanvas.h"
#include "TStyle.h"
#include "TH1.h"
#include "TH1F.h"
#include "TGaxis.h"
#include "TRandom.h"
#include "TFile.h"
#include "TTree.h"
#include "TBranch.h"
#include "TTreeReader.h"
#include "TTreeReaderValue.h"
#include "TTreeReaderArray.h"
#include "TString.h"
void Histograms()
{
//variables used to store the data
Int_t totalSize1, totalSize2 = 0;
TString fnameMC = "MC_D2PiMuMu12_MagUp_NTuples_fin.root";
TString fnameRD = "Ntuples/D2hMuMu12_MagU_2PiMuMuOS_NTuple_Reduced.root";
TFile *f1 = TFile::Open( fnameMC );
TFile *f2 = TFile::Open( fnameRD );
if (f1 == 0) { printf("error with MC"); return; }
if (f2 == 0) { printf("error with RD"); return; }
TTreeReader myReader1 ("D2PimumuOSTuple/DecayTree", f1);
TTreeReader myReader2 ("D2PimumuOSTuple/DecayTree", f2);
TCanvas *myCan = new TCanvas();
Int_t varNum=7;
TString variables[] = { "D_PT", "D_DIRA_OWNPV", "D_IPCHI2_OWNPV", "piplus_PT", "piplus_P", "D_P", "D_FDCHI2_OWNPV" };
//myCan->Divide(1,varNum);
TH1F* mcHist;
Int_t it=6;
//myCan -> cd (it);
TTreeReaderArray<Double_t> pt1(myReader1, variables[it]);
TTreeReaderArray<Double_t> pt2(myReader2, variables[it]);
//D_IPCHI2_OWNPV mcHist = new TH1F ("","",150,0,40);
// piplus_PT mcHist = new TH1F (variables[it],variables[it],150,0,11000);
mcHist = new TH1F (variables[it],variables[it],150,0,150000);
//mcHist -> SetMaximum(1.1);
mcHist->SetLineColor(kBlue);
while (myReader1.Next()) {
for (int i =0; i< pt1.GetSize(); ++i){
mcHist->Fill(pt1[i]);
}
}
mcHist->DrawNormalized();
mcHist->SetLineColor(kRed);
while (myReader2.Next()) {
for (int i =0; i< pt2.GetSize(); ++i){
mcHist->Fill(pt2[i]);
}
}
mcHist->DrawNormalized("SAME");
//myCan->Update();
//myCan->Print("h2D.pdf");
}
|
28d7e74bf1365c015b30479e7d249e1ecc20bab3 | 8e25b8ade9e4b6e076fcb2a1a7cb31326bc66526 | /src/lower-bound.h | a489821583b769c22d8fba406b21566b57dad585 | [
"MIT"
] | permissive | yvs314/dp-monster | 5aa3f87cacc17d5130d62f31f8ebe729151c7975 | 15addeb4a4dd8c66302f92a719b849ac99cfbefc | refs/heads/master | 2023-07-17T13:04:22.540700 | 2021-08-17T23:00:41 | 2021-08-17T23:00:41 | 179,075,428 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,639 | h | lower-bound.h | /*
(c) Yaroslav Salii & the Parliament of Owls, 2019+
License:sort of CC---if you go commercial, contact me
lower-bound v.1.0 2019-01-24;
v.1.1 2019-01-28; added el-Cheapo LB; TODO: replace + with ExtMt or whatever
compute lower bounds on problem instances
NB! v.1.0 is TSP(-PC)-only, might not handle BTSP etc.
=TODO:dumb Edmonds/Chu--Liu LB: MSAP with prohibited arcs that directly contradict PCs
*/
#ifndef LB_H_
#define LB_H_
#include"instance.h"
#include<forward_list>
//=====AUX==DATA==STRUCTURES=ETC.================/
using t_arc //I'd rather have its fields immutable, but const fields wreak havok in some programming patterns
= struct t_arc
{
ptag vxFrom;
ptag vxTo;
t_cost arcCost;
std::string to_string() const
{
std::ostringstream tmp; auto colSep = ";";
tmp << vxFrom << colSep << vxTo << colSep << arcCost;
return tmp.str();
}
};
//forward_list: minimum overhead
using t_flArcs = std::forward_list<t_arc>;
std::string dumpArcs(const t_flArcs& inp)
{
std::string out="";
for (auto arc : inp)
{
out += arc.to_string(); out += '\n';
}
out.pop_back();//suppress the dangling newline
return out;
}
const t_arc dummyArc {0,0,INF};
//initialize all to dummyArc
t_flArcs mkDummyV_Arcs(ptag arcNumber)
{
return t_flArcs(arcNumber, dummyArc);
}
//-------------------------------------------/
//=====elCheapo-LB===========================/
/*
CAVEAT: non-GTSP
not even MSAP: just a node-greedy solution; still a valid lower bound, and blazingly fast
0. do not take the precedence-proscribed edges; either cost=INF or direct consideration of who sends where
1. ignore the terminal for now; that's still a lower bound in most cases
2. think about solution output / through Boost.Graph
3. direction. FWD: path root r-->\trm; BWD: path base 0-->r;
BOTH: r=x, V= \rgn\setminus K
*/
/*
* REFIT scenario:
* 1. Kill GTSP-like foreach_point, for convenience. GTSP-compatible LBs are a totally different matter anyway
* 2. Add transparent BWD support (might decrease performance
* 3. Remove failsafe test (r\notin V)
* NOTE: varying direction in elCheapo. If there's no time/seq-dependence,
* the direction of MSAP traversal is irrelevant, so we can just choose the best one
*/
//this is the production version; doesn't retain solution, only its value (dummy .second)
inline std::pair<t_cost,t_flArcs> elCheapoLB(const ptag r //MSAP root; not in V
, const t_bin& V // cities to be spanned by the MSAP
, const t_Instance& p
, const t_Direction& D) //FWD/BWD
{
assert(!V.test(r)); // root is never in V
ptag startPt,endPt;
t_bin V_Min=getMin(V,p.ord,p.wkOrd); //can receive arcs directed from startPt
t_bin V_Max=getMax(V,p.ord,p.wkOrd);//can be the source of arcs directed to endPt
if(D == FWD)//this is for proper direction, which could yield proper KCvH traveling deliveryman costs
{// it's FWD:
startPt=r;//start at the given vertex
endPt=p.dim+1;//end at the terminal
}
else// D == BWD
{//it's BWD:
startPt=0;//start at the base
endPt=r;//end at r
}
//we'll have one arc into every vertex from V and one into endPt, V.count()+1
static const t_flArcs sln {dummyArc}; //only dummy solution for production runs
t_cost out=0;//
//find least-cost arcs into each city x in V_Min, which may start at V\setminus\{v\}\cup\{startPt\}
foreach_elt(x, V,p.dim )
{
t_cost minCost_y_to_x = INF;
t_bin V_from = setMinus(V, BIT0 << x);
foreach_elt(y, V_from, p.dim)
{
if (p.cost[y][x] < minCost_y_to_x)
minCost_y_to_x = p.cost[y][x];
}
//must be separate since 0 is never iterated through by foreach_elt (0 is startPt in BWD)
if(V_Min.test(x) //if x is minimal in V, also test startPt-->x;
&& p.cost[startPt][x] < minCost_y_to_x)
minCost_y_to_x = p.cost[startPt][x];
//now we've got the minimal arc from y to x; record it
out=p.f.cAgr(out,minCost_y_to_x);
}
//finally, find and add the min-arc to endPt
t_cost minCost_x_to_endPt=INF;
foreach_elt(x, V_Max, p.dim)
{
if (p.cost[x][endPt] < minCost_x_to_endPt)
minCost_x_to_endPt =p.cost[x][endPt];
}
//now we've got the minimal arc from y to x; record it
out=p.f.cAgr(out,minCost_x_to_endPt);
return std::make_pair(out,sln);
}
//this version remembers the solution (arcs and all), not just its value
inline std::pair<t_cost,t_flArcs> elCheapoLB_dbg(const ptag r //MSAP root; not in V
, const t_bin& V // cities to be spanned by the MSAP
, const t_Instance& p
, const t_Direction& D) //FWD/BWD
{
assert(!V.test(r)); // root is never in V
ptag startPt,endPt;
t_bin V_Min=getMin(V,p.ord,p.wkOrd); //can receive arcs directed from startPt
t_bin V_Max=getMax(V,p.ord,p.wkOrd);//can be the source of arcs directed to endPt
if(D == FWD)//this is for proper direction, which could yield proper KCvH traveling deliveryman costs
{// it's FWD:
startPt=r;//start at the given vertex
endPt=p.dim+1;//end at the terminal
}
else// D == BWD
{//it's BWD:
startPt=0;//start at the base
endPt=r;//end at r
}
//we'll have one arc into every vertex from V and one into endPt, V.count()+1
t_flArcs sln {}; //start as empty solution list
t_cost out=0;//
//find least-cost arcs into each city x in V_Min, which may start at V\setminus\{v\}\cup\{startPt\}
foreach_elt(x, V,p.dim )
{
t_arc minArc_y_to_x = dummyArc;
t_bin V_from = setMinus(V, BIT0 << x);
foreach_elt(y, V_from, p.dim)
{
if (p.cost[y][x] < minArc_y_to_x.arcCost)
minArc_y_to_x = t_arc{y, x, p.cost[y][x]};
}
//must be separate since 0 is never iterated through by foreach_elt (0 is startPt in BWD)
if(V_Min.test(x) //if x is minimal in V, also test startPt-->x;
&& p.cost[startPt][x] < minArc_y_to_x.arcCost)
minArc_y_to_x = t_arc{startPt, x, p.cost[startPt][x]};
//now we've got the minimal arc from y to x; record it
sln.push_front(minArc_y_to_x);
out=p.f.cAgr(out,minArc_y_to_x.arcCost);
}
//finally, find and add the min-arc to endPt
t_arc minArc_x_to_endPt=dummyArc;
foreach_elt(x, V_Max, p.dim)
{
if (p.cost[x][endPt] < minArc_x_to_endPt.arcCost)
minArc_x_to_endPt = t_arc{x, endPt, p.cost[x][endPt]};
}
//now we've got the minimal arc from y to x; record it
sln.push_front(minArc_x_to_endPt);
out=p.f.cAgr(out,minArc_x_to_endPt.arcCost);
return std::make_pair(out,sln);
}
//---------------------------------------------------/
//=========NAMECALLING,=CODES,=ETC.===============/
//getLowerBoundCode
//say, elCheapo is CHP; would extend later
//---------------------------------------------------/
#endif
//====BIT=====BUCKET===========//
/* computes Edmonds-MSAP LB; MSAP is Minimum Spanning Arborescence P
1. ignore the terminal for now; that's still a lower bound in most cases
2. think about solution output
3. direction. FWD: path *from* root r; BWD: path *to* root r;
BOTH: r=x, V= \rgn\setminus K
*/
//compute Edmonds-MSAP LB: wrapper;
// inline t_cost edmLB(const ptag x //agent's position; interface into K
// , const t_bin& K // agent's task set
// , const t_Instance& p
// , const t_Direction D) //FWD/BWD
// {
// if (! (D == FWD)) exit(EXIT_FAILURE); //crash if not FWD; STOPGAP
// /* OK, we're going forward now. Find MSAP with root x over the set \rgn\setminus K
// */
//
//
// return 0; // "undefined" STOPGAP
// }
/*
std::tuple <mtag, ptag, t_cost> bestArcFromRoot (0,0,INF);
//mtag best_m; ptag best_x; t_cost fromRoot_to_x=INF;// x\in V, for r--> x arc
//m\in \Min[V], x\in M_m; and a poor man's min-fold directly below
foreach_elt(m, getMin(V,p.ord,p.wkOrd),p.dim )
foreach_point(x, p.popInfo[m].pfirst, p.popInfo[m].plast)
{
(p.cost[r][x]< std::get<2>(bestArcFromRoot))?(bestArcFromRoot={m,x,p.cost[r][x]});
}
const auto V1 = setMinus(V,BIT0 << std::get<0>(bestArcFromRoot));*/
//const auto V1 = setMinus(V, BIT0 << p.cityof[sln.front().vxTo]);
|
236dcba2332a668bf884a77574d488b01e38927e | ec82fa3d4094b5113b10bc9d21877e82c0fe4244 | /src/ssp_gui_3d/dlgsaveviewpoint.cpp | f9cf9e73745083b8814894232cacc20ef11c4533 | [] | no_license | song-kang/SSP01_tag20190423 | 512f547fee29b648c11ba57e2a5db320a57cba8f | ca0bb4155a5907a8f1551e887dcaa0172ac7e80d | refs/heads/master | 2023-06-27T14:06:28.872089 | 2021-07-26T03:19:27 | 2021-07-26T03:19:27 | 280,988,265 | 1 | 2 | null | null | null | null | GB18030 | C++ | false | false | 6,804 | cpp | dlgsaveviewpoint.cpp | #include "dlgsaveviewpoint.h"
#include <QMessageBox>
#define COLUMN_SCENE_ID 0
#define COLUMN_VP_ID 1
#define COLUMN_DEFAULT 2
#define COLUMN_NAME 3
DlgSaveViewPoint::DlgSaveViewPoint(QWidget *parent)
: QDialog(parent)
{
ui.setupUi(this);
init();
connect(ui.pushButton_ok,SIGNAL(clicked()),this,SLOT(slotOk()));
connect(ui.pushButton_cancel,SIGNAL(clicked()),this,SLOT(close()));
connect(ui.radioButton_add,SIGNAL(clicked()),this,SLOT(slotRadioButtonAdd()));
connect(ui.radioButton_replace,SIGNAL(clicked()),this,SLOT(slotRadioButtonReplace()));
connect(ui.tableWidget,SIGNAL(itemClicked(QTableWidgetItem*)),this,SLOT(slotItemClicked(QTableWidgetItem*)));
}
DlgSaveViewPoint::~DlgSaveViewPoint()
{
}
void DlgSaveViewPoint::init()
{
row = 0;
initTableWidget();
ui.lineEdit->setEnabled(ui.radioButton_add->isChecked());
ui.tableWidget->setEnabled(ui.radioButton_replace->isChecked());
}
void DlgSaveViewPoint::initTableWidget()
{
ui.tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows); //整行选择模式
ui.tableWidget->setSelectionMode(QAbstractItemView::SingleSelection); //单选模式
ui.tableWidget->setFocusPolicy(Qt::NoFocus); //去除焦点,无虚框
ui.tableWidget->horizontalHeader()->setStretchLastSection(true); //设置充满表宽度
ui.tableWidget->setStyleSheet("selection-background-color:lightblue;"); //设置选中背景色
ui.tableWidget->verticalHeader()->setDefaultSectionSize(25); //设置行高
ui.tableWidget->horizontalHeader()->setHighlightSections(false); //点击表时不对表头行光亮
ui.tableWidget->setAlternatingRowColors(true); //设置交替行色
ui.tableWidget->verticalHeader()->setVisible(false); //去除最前列
ui.tableWidget->setColumnWidth(COLUMN_SCENE_ID,80);
ui.tableWidget->setColumnWidth(COLUMN_VP_ID,80);
ui.tableWidget->setColumnWidth(COLUMN_DEFAULT,80);
}
void DlgSaveViewPoint::start()
{
setDefaultEnable();
unsigned long pos = 0;
CSsp3DSceneViewPoint *v = m_3DModel->m_SceneViewPoints.FetchFirst(pos);
while (v)
{
if (v->m_iSceneId == m_sceneId)
{
unsigned long pos1 = 0;
t_ssp_3d_scene_viewpoint *p = v->m_ViewPoints.FetchFirst(pos1);
while (p)
{
ui.tableWidget->setRowCount(++row);
QTableWidgetItem *item = new QTableWidgetItem(tr("%1").arg(p->scene_id));
item->setTextAlignment(Qt::AlignCenter);
item->setFlags(item->flags() & (~Qt::ItemIsEditable));
ui.tableWidget->setItem(row-1,COLUMN_SCENE_ID,item);
item = new QTableWidgetItem(tr("%1").arg(p->vpoint_id));
item->setTextAlignment(Qt::AlignCenter);
item->setFlags(item->flags() & (~Qt::ItemIsEditable));
ui.tableWidget->setItem(row-1,COLUMN_VP_ID,item);
item = new QTableWidgetItem(tr("%1").arg(p->def_vpoint == 1 ? tr("默认") : tr("非默认")));
item->setTextAlignment(Qt::AlignCenter);
item->setFlags(item->flags() & (~Qt::ItemIsEditable));
ui.tableWidget->setItem(row-1,COLUMN_DEFAULT,item);
item = new QTableWidgetItem(tr("%1").arg(p->vpoint_name));
item->setTextAlignment(Qt::AlignCenter);
//item->setFlags(item->flags() & (~Qt::ItemIsEditable));
ui.tableWidget->setItem(row-1,COLUMN_NAME,item);
p = v->m_ViewPoints.FetchNext(pos1);
}
}
v = m_3DModel->m_SceneViewPoints.FetchNext(pos);
}
m_viewPointId = 0;
m_viewPointDefault = 0;
}
void DlgSaveViewPoint::slotItemClicked(QTableWidgetItem *item)
{
m_sceneId = ui.tableWidget->item(item->row(),COLUMN_SCENE_ID)->text().toInt();
m_viewPointId = ui.tableWidget->item(item->row(),COLUMN_VP_ID)->text().toInt();
m_viewPointDefault = ui.tableWidget->item(item->row(),COLUMN_DEFAULT)->text() == tr("默认") ? 1 : 0;
m_viewPointName = ui.tableWidget->item(item->row(),COLUMN_NAME)->text().toStdString().data();
}
void DlgSaveViewPoint::slotOk()
{
if (ui.radioButton_add->isChecked())
{
if (ui.lineEdit->text().isEmpty())
{
QMessageBox::warning(this,tr("告警"),tr("请输入视点名称。"));
return;
}
int maxVPId = getMaxViewPointId();
if (maxVPId == -1)
return;
SString sql;
sql.sprintf("insert into t_ssp_3d_scene_viewpoint"
"(scene_id,vpoint_id,vpoint_name,def_vpoint,eye_x,eye_y,eye_z,eye_forw_x,eye_forw_y,eye_forw_z,cent2eye,x_angle,z_angle) values"
"(%d,%d,'%s',%d,%f,%f,%f,%f,%f,%f,%f,%f,%f)",m_sceneId,++maxVPId,ui.lineEdit->text().toStdString().data(),m_viewPointDefault,
eyeX,eyeY,eyeZ,centerX,centerY,centerZ,eye2center,xAngle,zAngle);
if (!DB->ExecuteSQL(sql))
{
QMessageBox::warning(this,tr("告警"),tr("实时库增加视点失败。"));
return;
}
else
{
QMessageBox::information(this,tr("提示"),tr("实时库增加视点成功。"));
if (!MDB->ExecuteSQL(sql))
QMessageBox::information(this,tr("提示"),tr("内存库增加视点失败。"));
}
}
else if (ui.radioButton_replace->isChecked())
{
if (!m_sceneId || !m_viewPointId)
{
QMessageBox::warning(this,tr("告警"),tr("请选择需要替换的视点。"));
return;
}
SString sql;
sql.sprintf("update t_ssp_3d_scene_viewpoint set "
"vpoint_name='%s',eye_x=%f,eye_y=%f,eye_z=%f,eye_forw_x=%f,eye_forw_y=%f,eye_forw_z=%f,cent2eye=%f,x_angle=%f,z_angle=%f "
"where scene_id=%d and vpoint_id=%d and def_vpoint=%d",m_viewPointName.data(),eyeX,eyeY,eyeZ,centerX,centerY,centerZ,eye2center,xAngle,zAngle,
m_sceneId,m_viewPointId,m_viewPointDefault);
if (!DB->ExecuteSQL(sql))
{
QMessageBox::warning(this,tr("告警"),tr("实时库替换视点失败。"));
return;
}
else
{
QMessageBox::information(this,tr("提示"),tr("实时库替换视点成功。"));
if (!MDB->ExecuteSQL(sql))
QMessageBox::information(this,tr("提示"),tr("内存库替换视点失败。"));
}
}
accept();
}
void DlgSaveViewPoint::slotRadioButtonAdd()
{
ui.lineEdit->setEnabled(true);
ui.tableWidget->setEnabled(false);
setDefaultEnable();
}
void DlgSaveViewPoint::slotRadioButtonReplace()
{
ui.lineEdit->setEnabled(false);
ui.checkBox->setEnabled(false);
ui.tableWidget->setEnabled(true);
}
void DlgSaveViewPoint::setDefaultEnable()
{
SRecordset rs;
int cnt = DB->Retrieve(SString::toFormat("select count(*) from t_ssp_3d_scene_viewpoint where scene_id=%d and def_vpoint=1",m_sceneId),rs);
if (cnt <= 0)
{
ui.pushButton_ok->setEnabled(false);
return;
}
else
{
int count = rs.GetValue(0,0).toInt();
if (count)
ui.checkBox->setEnabled(false);
else
ui.checkBox->setEnabled(true);
}
}
int DlgSaveViewPoint::getMaxViewPointId()
{
SRecordset rs;
int cnt = DB->Retrieve(SString::toFormat("select max(vpoint_id) from t_ssp_3d_scene_viewpoint where scene_id=%d",m_sceneId),rs);
if (cnt <= 0)
{
QMessageBox::warning(this,tr("告警"),tr("获取场景中最大视点编号失败。"));
return -1;
}
return rs.GetValue(0,0).toInt();
}
|
cdb23af85eb765907c039c8213119f3d3eb45642 | bb04f391bb0a0bd5f7e146d35241744b9a09bd79 | /entities/StraightDownEnemy.h | 4cce2e797494aa5879d57dea97a9afd2eda2c0eb | [] | no_license | scurvysteve/galaga-esque | e4dcb475e10eaff64a30eaab336903847ac15fd3 | 3447430eea665a9ce8d3b8e34da71d7f755d98df | refs/heads/master | 2020-12-25T11:05:51.883875 | 2013-09-09T04:55:21 | 2013-09-09T04:55:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 427 | h | StraightDownEnemy.h | /*
* StraightDownEnemy.h
*
* Created on: Feb 25, 2013
* Author: joe
*/
#ifndef STRAIGHTDOWNENEMY_H_
#define STRAIGHTDOWNENEMY_H_
#include "GenericEnemy.h"
class StraightDownEnemy : public GenericEnemy {
public:
StraightDownEnemy();
StraightDownEnemy(int initialX, int initialY);
virtual ~StraightDownEnemy();
void handleLogic();
protected:
static const int SPEED = 2;
};
#endif /* STRAIGHTDOWNENEMY_H_ */
|
b75a460a6f19b746bdc48b20e71dbce93e64725e | a769885b3343d7072ecf25b8d2afe3f351369bf6 | /linked-list/node.cpp | 56e8e70ed462e4657869481cc2329ebe183ce3fd | [
"MIT"
] | permissive | rohitkhilnani/cpp-And-Me | caa38f9133526a5684b4140f0c46f11954657611 | 826611fb78b63d25cc7cac19425fd55749e169b6 | refs/heads/master | 2021-01-10T05:15:17.112605 | 2016-02-07T04:43:58 | 2016-02-07T04:43:58 | 49,747,925 | 0 | 0 | null | 2016-02-07T04:43:58 | 2016-01-15T22:12:55 | C++ | UTF-8 | C++ | false | false | 473 | cpp | node.cpp | /*
Definition for node.h
*/
#include "node.h"
// constructs Node with specified value
Node::Node(int val){
value = val;
}
// constructs Node with default values
Node::Node(){
}
// sets value
void Node::setValue(int val){
value = val;
}
// sets next pointer
void Node::setNext(Node* n){
next = n;
}
// Returns value
int Node::getValue(){
return value;
}
// Returns next pointer
Node* Node::getNext(){
return next;
}
|
917b62f95f7ec3d561493c22a7cb5f101cf249c5 | 24830dd6470819417a56cfa3d419569d942ceaf1 | /Day30/day30.ino | b954beb6f03abe5da77eb468ccfd8f5383316d7f | [
"MIT"
] | permissive | stevelyons/31DaysOfArduino | 693a95c10b5a1519eab4c1a84df93f45302ccd42 | 1041556e51f08d67d2e83314568fe502c18be159 | refs/heads/master | 2016-09-05T10:46:10.337333 | 2015-10-25T03:06:07 | 2015-10-25T03:06:07 | 34,935,207 | 0 | 1 | null | 2015-10-24T01:06:52 | 2015-05-02T04:09:33 | Arduino | UTF-8 | C++ | false | false | 42 | ino | day30.ino | // Steve Lyons
// Day 30 - May 30th, 2015
|
62d522cab3041b2b0eb8062dd702de65fb1b3cd2 | a6bdc5008be5c5f9fb624a1fa8eea4a95753ae06 | /Graph Power Library.cpp | 001b72322e52ae44d0cbfcbfc30bef1ada0e558f | [] | no_license | phpduke/Algorithms-Notebook | b6a9a5f83d5fd95624d04d8e1fcf12f46e487718 | ff34384bdd970fa6bf44b4a7e042aca25af900f7 | refs/heads/master | 2023-05-30T01:13:15.099728 | 2023-05-21T12:21:42 | 2023-05-21T12:21:42 | 161,853,573 | 6 | 4 | null | 2023-05-25T11:20:50 | 2018-12-15T00:06:46 | C++ | UTF-8 | C++ | false | false | 5,213 | cpp | Graph Power Library.cpp | #include <bits/stdc++.h>
using namespace std;
//COPY THE BLACKBOX, there is no need to change anything in it.
//Check the main function at bottom for USAGE
//****************BLACKBOX START*****************
//START COPYING FROM HERE
typedef int ll;
class Graph {
bool is_directed;
public:
vector<vector<pair<int,ll>>>adj;
int n,N=2000000;
Graph(int n_, bool is_directed_){
n=n_; is_directed = is_directed_;
adj.resize(N,vector<pair<int,ll>>());
}
int hash(int u, int v){
return u*1873+v;
}
int hash(int u, int v, int k){
return k*1873*1873+u*1873+v;
}
bool node_has_edges(int u) {
return (adj[u].size()!=0);
}
bool node_has_edges(int u, int v) {
int x = hash(u,v);
return (adj[x].size()!=0);
}
bool node_has_edges(int u, int v, int k) {
int x = hash(u,v,k);
return (adj[x].size()!=0);
}
void add_edge(int u, int v, ll c=0){
add_edge_weighted_undirected(u,v,c);
if(!is_directed)
add_edge_weighted_undirected(v,u,c);
}
void add_edge(int ui, int uj, int vi, int vj, ll c=0){
int u=hash(ui,uj), v=hash(vi,vj);
add_edge_weighted_undirected(u,v,c);
if(!is_directed)
add_edge_weighted_undirected(v,u,c);
}
void add_edge(int ui, int uj,int uk, int vi, int vj, int vk, ll c=0){
int u=hash(ui,uj,uk), v=hash(vi,vj,vk);
add_edge_weighted_undirected(u,v,c);
if(!is_directed)
add_edge_weighted_undirected(v,u,c);
}
private :
void add_edge_weighted_undirected(int u, int v, ll c) {
pair<int,ll>p = make_pair(v,c);
adj[u].push_back(p);
}
};
class BFS {
vector<ll>min_dist_from_source;
vector<bool> visited;
public:
BFS(Graph *g_) {
g = g_;
min_dist_from_source.resize(g->N,-1);
visited.resize(g->N, false);
}
Graph *g;
void run(int source) {
queue<int> q;
q.push(source);
visited[source] = true;
min_dist_from_source[source] = 0;
while(!q.empty()) {
int cur_node = q.front();
for (unsigned int i = 0; i < (g->adj[cur_node]).size(); ++i) {
int adj_node = (g->adj[cur_node])[i].first;
if (visited[adj_node] == false) {
visited[adj_node] = true;
min_dist_from_source[adj_node] = min_dist_from_source[cur_node] + 1;
q.push(adj_node);
}
}
q.pop();
}
return;
}
void run(int sourcei, int sourcej){
int source = (g->hash)(sourcei, sourcej);
run(source);
}
void run(int sourcei, int sourcej, int sourcek){
int source = (g->hash)(sourcei, sourcej, sourcek);
run(source);
}
int min_dist(int targeti, int targetj){
int target = (g->hash)(targeti,targetj);
return min_dist_from_source[target];
}
int min_dist(int targeti,int targetj,int targetk){
int target = (g->hash)(targeti,targetj,targetk);
return min_dist_from_source[target];
}
int min_dist(int target){
return min_dist_from_source[target];
}
bool is_visisted(int targeti,int targetj){
int target = (g->hash)(targeti,targetj);
return visited[target];
}
bool is_visisted(int targeti,int targetj,int targetk){
int target = (g->hash)(targeti,targetj,targetk);
return visited[target];
}
bool is_visisted(int target){
return visited[target];
}
};
//END COPYING HERE
//********************BLACKBOX END******************
int main() {
// initaitise a directed graph with 4 nodes, nodes are 0-indexed
Graph g(4, true);
// initaitise an un-directed graph with 4 nodes, nodes are 0-indexed
Graph g(4, false);
//DIRECTED GRAPH : add edges `Node 0 -> Node 4` and `Node 1 -> Node 3`
g.add_edge(0,4);
g.add_edge(1,3);
//UNDIRECT GRAPH : add edges between `Node 0 -- Node 4` and `Node 1 -- Node 3`
g.add_edge(0,4);
g.add_edge(1,3);
//DIRECTED GRAPH 2D (useful for grid problems): add edges `Node {0,1} -> Node {2,4}` and `Node {3,1} -> Node {3,3}`
g.add_edge(0,1,2,4);
g.add_edge(3,1,3,1);
//UNDIRECT GRAPH 2D (useful for grid problems): add edges between `Node {0,1} -- Node {2,4}` and `Node {3,1} -- Node {3,3}`
g.add_edge(0,1,2,4);
g.add_edge(3,1,3,1);
//*Do BFS on the graph g*
BFS bfs(&g);
//BFS on 1D Graph
//start bfs on `Node 2`
bfs.run(2);
//get minimum distance of `Node 4` from source node (minimum distance is -1 if `Node 4` is unreacable from soure node)
int min_d = bfs.min_dist(4);
//check if `Node 4` is visited aka reachable from source node
bool is_reachable = bfs.is_visisted(4);
//BFS on 2D Graph
//start bfs on `Node {1,4}`
bfs.run(1,4);
//get minimum distance of `Node {2,3}` from source node (minimum distance is -1 if `Node {2,3}` is unreacable from soure node)
int min_d = bfs.min_dist(2,3);
//check if `Node {2,3}` is visited aka reachable from source node
bool is_reachable = bfs.is_visisted(2,3);
return 0;
}
/*NOTES
1. [IMP for P2 & P4] If you call bfs.run again (even with a different source node), the previous run's minimum distance and visited is maintained
2. The Nodes are 0-indexed.
*/
|
00104ef662f98d14e988f9d69dedb1a504f83201 | b1aed5e3c9249c4c4eee3ddc548681f95d7c6754 | /fixed report/src/a39/endPoint.cc | 28d976cddd45a27dfe57a9df0c49ff3e0179d6f9 | [] | no_license | franksnightmare/c-2week6 | 46e54d232e3af06e3379e1d3973b0a340cbbb98a | b72dd0d7ce16e649dbd1132f918766c87dac0fb0 | refs/heads/master | 2021-01-11T10:32:57.223297 | 2016-12-21T21:14:14 | 2016-12-21T21:14:14 | 76,350,443 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 93 | cc | endPoint.cc | #include "main.ih"
void watch::endPoint()
{
d_end = std::chrono::system_clock::now();
}
|
3fe68626e4d9b389b0a97608a13c18ba9e855891 | 11c17e0f68e2769521efb4568ed848e0c541afff | /SP1Framework/combatRender.h | 2779d229d2ae5b1edcdffe05748883ec6f51e722 | [] | no_license | X3RO101/SP01T11 | 369541a77089104ef48f70d22d342b315865a393 | 0c1e4db5488289bf10ce073268c83298474249c4 | refs/heads/Master | 2020-03-26T03:43:21.200889 | 2018-08-29T01:12:45 | 2018-08-29T01:12:45 | 144,468,127 | 0 | 0 | null | 2018-08-23T09:36:13 | 2018-08-12T13:16:57 | C++ | UTF-8 | C++ | false | false | 1,175 | h | combatRender.h | #pragma once
#ifndef COMBAT_H
#define COMBAT_H
#include <iostream>
#include <string>
#include <fstream>
#include <random>
#include <ctime>
#include "Framework/console.h"
#include "Container.h"
using namespace std;
// functions in the combatRender.cpp are the logic and initialisations
// rendering text shall be in game.cpp
struct Text
{
string monsterQn;
};
extern Console g_Console;
extern bool moveAllow;
extern enum EGAMESTATES g_eGameState;
extern bool isdead;
extern bool g_abKeyPressed[K_COUNT];
extern void getInput();
extern struct SGameChar g_sChar;
extern struct monstatus monster[7];
//functions that render combat text/store and initialise text
void initMobText(Text * mobNo, ifstream* mobFile); // to be used in intialise
void textPicker();
void spamPrint();
void inputAns();
void checkAns();
void ansWrong();
void combatlogic();
void printCOrW();
void stopPrintingCOrW(double dt);
void combatlogic(); // inputAns checkAns and ansWrong all in here
void printCOrW();
void stopPrintingCOrW(double dt);
void duration(EGAMESTATES * gameState, double dt); // timer for the mob encounters
void COMBAT(); // textPicker and spamPrint inside
#endif // !COMBAT_H
|
96c8ec74e6f64b457d1c62c1e9aa3ba0f368ca42 | f1144b64dba3b30168065030ac0f017a655555d0 | /Source/Enlight/ReactiveMonologStruct.h | e4f9a7487c529b44dbc307763adf614df942efe4 | [] | no_license | V41U/Enlight | 4d9ee0fa79e2fb07cf3092e2aa0cf27ab4115c4c | 558efd614d50b0eec264f4df0a70e58918242eaf | refs/heads/master | 2023-01-02T14:40:42.199073 | 2020-10-27T18:10:54 | 2020-10-27T18:10:54 | 302,003,580 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,093 | h | ReactiveMonologStruct.h | // Enlight Game 2019
#pragma once
#include "CoreMinimal.h"
#include "Containers/Set.h"
#include "Containers/Array.h"
#include "MonologStruct.h"
#include "ReactiveMonologStruct.generated.h"
/**
*
*/
USTRUCT(BlueprintType)
struct FReactiveMonologStruct
{
GENERATED_USTRUCT_BODY()
public:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Monolog")
TSet<TSubclassOf<class AActor>> ReactionActors;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Monolog")
TArray<FMonologStruct> MonologOrder;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Monolog")
int32 FirstMonologCounter;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Monolog")
int32 MonologCounterInterval;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Monolog")
int32 MaxMonologReactions;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Monolog")
bool bInfiniteMonologReactions;
// Default Constructor
FReactiveMonologStruct()
{
FirstMonologCounter = 1;
MonologCounterInterval = 1;
MaxMonologReactions = 1;
bInfiniteMonologReactions = false;
}
}; |
99cb66cfb2329a41874ab7a6293449d45eb07bdf | 6b40e9dccf2edc767c44df3acd9b626fcd586b4d | /NT/inetcore/connectionwizard/icwutil/server.h | d8ddf0939e3ef149ddaf7ae2305a63ade46efc06 | [] | no_license | jjzhang166/WinNT5_src_20201004 | 712894fcf94fb82c49e5cd09d719da00740e0436 | b2db264153b80fbb91ef5fc9f57b387e223dbfc2 | refs/heads/Win2K3 | 2023-08-12T01:31:59.670176 | 2021-10-14T15:14:37 | 2021-10-14T15:14:37 | 586,134,273 | 1 | 0 | null | 2023-01-07T03:47:45 | 2023-01-07T03:47:44 | null | UTF-8 | C++ | false | false | 1,521 | h | server.h | //**********************************************************************
// File name: server.h
//
//
//
// Copyright (c) 1993-1996 Microsoft Corporation. All rights reserved.
//**********************************************************************
#if !defined(SERVER_H)
#define SERVER_H
// String Macros.
#define ABOUT_TITLE_STR "DLLSERVE: OLE Tutorial Code Sample"
// Dialog IDs.
#define IDD_ABOUTBOX 1000
// Error-related String Identifiers.
#define IDS_ASSERT_FAIL 2200
#ifdef __cplusplus
//**********************************************************************
// Class: CServer
//
// Summary: Class to encapsulate control of this COM server (eg, handle
// Lock and Object counting, encapsulate otherwise global data).
//
// Methods: none
//**********************************************************************
class CServer
{
public:
CServer(void);
~CServer(void);
void Lock(void);
void Unlock(void);
void ObjectsUp(void);
void ObjectsDown(void);
// A place to store the handle to loaded instance of this DLL module.
HINSTANCE m_hDllInst;
// Global DLL Server living Object count.
LONG m_cObjects;
// Global DLL Server Client Lock count.
LONG m_cLocks;
};
#endif // __cplusplus
// Allow other internal ICWUTIL modules to get at the globals.
extern CServer* g_pServer;
#endif // SERVER_H
|
e35e826d114b569e7b6e6dada60b3f39aa400f93 | 8df11d7ea4ba95bd580795756a723b69e041d133 | /esp8fachrelaisnodemcu_win_V1.ino | 4a51667cc05567d9c5815f0f27a07c9d2c712d40 | [] | no_license | gitWeissenburger/ESP-8Kanal-Relais-MQTT | 22b39f9678d1a0b76ed3f16b7a978c4785f268dc | 856873639c286f096b4b656c260daf980fd089b3 | refs/heads/master | 2022-12-21T23:14:13.213081 | 2020-09-26T17:35:04 | 2020-09-26T17:35:04 | 289,476,085 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 10,558 | ino | esp8fachrelaisnodemcu_win_V1.ino |
#include <ESP8266WiFi.h>
#include <EEPROM.h>
#include <PubSubClient.h>
const char* ssid = "Deine SSID";
const char* password = "Dein WLAN Passwort";
const char* mqtt_server = "IP Adresse deines Brokers";
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
// Client ID, outTopic, inTopic1 und deviceName zum Publish und Subscribe für das MQTT Protokoll
const char* clientID = "ESP8_Relais";
const char* outTopic = "/Topic/Terrasse";
const char* inTopic1 = "/Topic/Terrasse/Relais";
const char* deviceName = "ESP8_Relais";
int relay_pin1 = 5;
int relay_pin2 = 4;
int relay_pin3 = 0;
int relay_pin4 = 2;
int relay_pin5 = 14;
int relay_pin6 = 12;
int relay_pin7 = 13;
int relay_pin8 = 15;
// Dient zur Verbindungsanzeige bei erfolgreicher Brokerverbindung
int LED_pIN = 16;
bool relayState1 = LOW;
bool relayState2 = LOW;
bool relayState3 = LOW;
bool relayState4 = LOW;
bool relayState5 = LOW;
bool relayState6 = LOW;
bool relayState7 = LOW;
bool relayState8 = LOW;
// IPAddresse des ESP
IPAddress ip(192,168,178,122);
// IPAddresse des gateways
IPAddress gateway(192,168,178,1);
IPAddress subnet(255,255,255,0);
void setup_wifi() {
delay(10000);
// Connect to WiFi network
WiFi.mode(WIFI_STA);
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.hostname(deviceName); // DHCP Hostname (useful for finding device for static lease)
WiFi.config(ip, gateway, subnet); // (DNS not required)
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
// Auswertung der empfangenen Daten,
// erste Ziffer = Relaisnummer
// zweite Ziffer = 0 für LOW, 1 für High
if ((char)payload[0] == '1') {
if ((char)payload[1] == '0') {
digitalWrite(relay_pin1, LOW);
Serial.println("relay_pin1 -> LOW");
client.publish(outTopic, "relay_pin1 -> LOW");
relayState1 = LOW;
EEPROM.write(0, relayState1);
EEPROM.commit();
} else if ((char)payload[1] == '1') {
digitalWrite(relay_pin1, HIGH);
Serial.println("relay_pin1 -> HIGH");
client.publish(outTopic, "relay_pin1 -> HIGH");
relayState1 = HIGH;
EEPROM.write(0, relayState1);
EEPROM.commit();}
} else if ((char)payload[0] == '2') {
if ((char)payload[1] == '0') {
digitalWrite(relay_pin2, LOW);
Serial.println("relay_pin2 -> LOW");
client.publish(outTopic, "relay_pin2 -> LOW");
relayState2 = LOW;
EEPROM.write(1, relayState2);
EEPROM.commit();
} else if ((char)payload[1] == '1') {
digitalWrite(relay_pin2, HIGH);
Serial.println("relay_pin2 -> HIGH");
client.publish(outTopic, "relay_pin2 -> HIGH");
relayState2 = HIGH;
EEPROM.write(1, relayState2);
EEPROM.commit();}
} else if ((char)payload[0] == '3') {
if ((char)payload[1] == '0') {
digitalWrite(relay_pin3, LOW);
Serial.println("relay_pin3 -> LOW");
client.publish(outTopic, "relay_pin3 -> LOW");
relayState3 = LOW;
EEPROM.write(2, relayState3);
EEPROM.commit();
} else if ((char)payload[1] == '1') {
digitalWrite(relay_pin3, HIGH);
Serial.println("relay_pin3 -> HIGH");
client.publish(outTopic, "relay_pin3 -> HIGH");
relayState3 = HIGH;
EEPROM.write(2, relayState3);
EEPROM.commit();}
} else if ((char)payload[0] == '4') {
if ((char)payload[1] == '0') {
digitalWrite(relay_pin4, LOW);
Serial.println("relay_pin4 -> LOW");
client.publish(outTopic, "relay_pin4 -> LOW");
relayState4 = LOW;
EEPROM.write(3, relayState4);
EEPROM.commit();
} else if ((char)payload[1] == '1') {
digitalWrite(relay_pin4, HIGH);
Serial.println("relay_pin4 -> HIGH");
client.publish(outTopic, "relay_pin4 -> HIGH");
relayState4 = HIGH;
EEPROM.write(3, relayState4);
EEPROM.commit();}
} else if ((char)payload[0] == '5') {
if ((char)payload[1] == '0') {
digitalWrite(relay_pin5, LOW);
Serial.println("relay_pin5 -> LOW");
client.publish(outTopic, "relay_pin5 -> LOW");
relayState5 = LOW;
EEPROM.write(4, relayState5);
EEPROM.commit();
} else if ((char)payload[1] == '1') {
digitalWrite(relay_pin5, HIGH);
Serial.println("relay_pin5 -> HIGH");
client.publish(outTopic, "relay_pin5 -> HIGH");
relayState5 = HIGH;
EEPROM.write(4, relayState5);
EEPROM.commit();}
} else if ((char)payload[0] == '6') {
if ((char)payload[1] == '0') {
digitalWrite(relay_pin6, LOW);
Serial.println("relay_pin6 -> LOW");
client.publish(outTopic, "relay_pin6 -> LOW");
relayState6 = LOW;
EEPROM.write(5, relayState6);
EEPROM.commit();
} else if ((char)payload[1] == '1') {
digitalWrite(relay_pin6, HIGH);
Serial.println("relay_pin6 -> HIGH");
client.publish(outTopic, "relay_pin6 -> HIGH");
relayState6 = HIGH;
EEPROM.write(5, relayState6);
EEPROM.commit();}
} else if ((char)payload[0] == '7') {
if ((char)payload[1] == '0') {
digitalWrite(relay_pin7, LOW);
Serial.println("relay_pin7 -> LOW");
client.publish(outTopic, "relay_pin7 -> LOW");
relayState7 = LOW;
EEPROM.write(6, relayState7);
EEPROM.commit();
} else if ((char)payload[1] == '1') {
digitalWrite(relay_pin7, HIGH);
Serial.println("relay_pin7 -> HIGH");
client.publish(outTopic, "relay_pin7 -> HIGH");
relayState7 = HIGH;
EEPROM.write(6, relayState7);
EEPROM.commit();}
} else if ((char)payload[0] == '8') {
if ((char)payload[1] == '0') {
digitalWrite(relay_pin8, LOW);
Serial.println("relay_pin8 -> LOW");
client.publish(outTopic, "relay_pin8 -> LOW");
relayState8 = LOW;
EEPROM.write(7, relayState8);
EEPROM.commit();
} else if ((char)payload[1] == '1') {
digitalWrite(relay_pin8, HIGH);
Serial.println("relay_pin8 -> HIGH");
client.publish(outTopic, "relay_pin8 -> HIGH");
relayState8 = HIGH;
EEPROM.write(7, relayState8);
EEPROM.commit();}
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
Serial.print("WIFI Status: ");
Serial.println(WiFi.status());
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect(clientID)) {
Serial.println("connected");
Serial.println();
Serial.print(clientID);
// Once connected, publish an announcement...
client.publish(outTopic, "Relais bootet");
// ... and resubscribe
client.subscribe(inTopic1);
digitalWrite(LED_pIN, LOW); // Turn the LED on by making the voltage LOW
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 10 seconds");
// Wait 5 seconds before retrying
for(int i = 0; i<10; i++){
digitalWrite(LED_pIN, LOW);
delay(500);
digitalWrite(LED_pIN, HIGH);
delay(500);
}
}
}
}
void setup() {
Serial.begin(115200);
EEPROM.begin(1024); // Begin eeprom to store on/off state
pinMode(relay_pin1, OUTPUT); // Initialize the relay pin as an output
pinMode(relay_pin2, OUTPUT); // Initialize the relay pin as an output
pinMode(relay_pin3, OUTPUT); // Initialize the relay pin as an output
pinMode(relay_pin4, OUTPUT); // Initialize the relay pin as an output
pinMode(relay_pin5, OUTPUT); // Initialize the relay pin as an output
pinMode(relay_pin6, OUTPUT); // Initialize the relay pin as an output
pinMode(relay_pin7, OUTPUT); // Initialize the relay pin as an output
pinMode(relay_pin8, OUTPUT); // Initialize the relay pin as an output
pinMode(LED_pIN, OUTPUT); // Initialize the LED_BUILTIN pin as an output
Serial.println(" Setup set output pin end");
// setzen der Relaiszustände die zuletzt gespeichert wurden
relayState1 = EEPROM.read(0);
digitalWrite(relay_pin1,relayState1);
Serial.print(relayState1);
Serial.println(": set output pin 1 end: ");
relayState2 = EEPROM.read(1);
digitalWrite(relay_pin2,relayState2);
Serial.print(relayState2);
Serial.println(": set output pin 2 end: ");
relayState3 = EEPROM.read(2);
digitalWrite(relay_pin3,relayState3);
Serial.print(relayState3);
Serial.println(": set output pin 3 end: ");
relayState4 = EEPROM.read(3);
digitalWrite(relay_pin4,relayState4);
Serial.print(relayState4);
Serial.println(": set output pin 4 end: ");
relayState5 = EEPROM.read(4);
digitalWrite(relay_pin5,relayState5);
Serial.print(relayState5);
Serial.println(": set output pin 5 end: ");
relayState6 = EEPROM.read(5);
digitalWrite(relay_pin6,relayState6);
Serial.print(relayState6);
Serial.println(": set output pin 6 end: ");
relayState7 = EEPROM.read(6);
digitalWrite(relay_pin7,relayState7);
Serial.print(relayState7);
Serial.println(": set output pin 7 end: ");
relayState8 = EEPROM.read(7);
digitalWrite(relay_pin8,relayState8);
Serial.print(relayState8);
Serial.println(": set output pin 8 end: ");
digitalWrite(LED_pIN, HIGH); // Turn the LED off by making the voltage HIGH
setup_wifi(); // Connect to wifi
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}
|
564d3aba27b74e405dd9a2b4536e9119d3a58b0c | ddc01ee5b3bd1da787af82e295bbb99a7df768e9 | /Modules/Numerics/Statistics/test/itkUniformRandomSpatialNeighborSubsamplerTest.cxx | 4c8a1e0302619eeb553060c9ec78c58d16b74ac4 | [
"Apache-2.0",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-unknown-license-reference",
"SMLNJ",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"libtiff",
"MIT",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"IJG",
"Zlib",
"BSD-4.3TAHOE",
"NTP",
"GPL-1.0-or-later",
"MPL-2.0",
"LicenseRef-scancode-hdf5",
"LicenseRef-scancode-mit-old-style",
"FSFUL",
"Libpng",
"Spencer-86",
"LicenseRef-scancode-llnl",
"LicenseRef-scancode-other-permissive"
] | permissive | Pandinosaurus/ITK | 6e8139fe54163aaa8df65faaf61eff2deb0c08d9 | f7504ec17a6606736a05b572a4da2b8cdd88c6fa | refs/heads/master | 2023-08-31T16:07:53.282289 | 2021-04-23T00:41:35 | 2021-04-23T00:41:35 | 180,342,894 | 1 | 0 | Apache-2.0 | 2021-04-23T13:31:22 | 2019-04-09T10:29:33 | C++ | UTF-8 | C++ | false | false | 4,051 | cxx | itkUniformRandomSpatialNeighborSubsamplerTest.cxx | /*=========================================================================
*
* Copyright NumFOCUS
*
* 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.txt
*
* 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 "itkWin32Header.h"
#include <fstream>
#include "itkImageToNeighborhoodSampleAdaptor.h"
#include "itkSubsample.h"
#include "itkImageFileWriter.h"
#include "itkZeroFluxNeumannBoundaryCondition.h"
#include "itkUniformRandomSpatialNeighborSubsampler.h"
#include "itkTestingMacros.h"
int
itkUniformRandomSpatialNeighborSubsamplerTest(int argc, char * argv[])
{
if (argc < 2)
{
std::cerr << "Missing Parameters." << std::endl;
std::cerr << "Usage: " << itkNameOfTestExecutableMacro(argv) << " useClockForSeed [outFileName]" << std::endl;
return EXIT_FAILURE;
}
using FloatImage = itk::Image<float, 2>;
using RegionType = FloatImage::RegionType;
using IndexType = FloatImage::IndexType;
using SizeType = FloatImage::SizeType;
using BoundaryCondition = itk::ZeroFluxNeumannBoundaryCondition<FloatImage>;
using AdaptorType = itk::Statistics::ImageToNeighborhoodSampleAdaptor<FloatImage, BoundaryCondition>;
using SamplerType = itk::Statistics::UniformRandomSpatialNeighborSubsampler<AdaptorType, RegionType>;
using WriterType = itk::ImageFileWriter<FloatImage>;
FloatImage::Pointer inImage = FloatImage::New();
SizeType sz;
sz.Fill(35);
IndexType idx;
idx.Fill(0);
RegionType region;
region.SetSize(sz);
region.SetIndex(idx);
inImage->SetRegions(region);
inImage->Allocate(true); // initialize buffer
// to zero
AdaptorType::Pointer sample = AdaptorType::New();
sample->SetImage(inImage);
SamplerType::Pointer sampler_orig = SamplerType::New();
ITK_EXERCISE_BASIC_OBJECT_METHODS(sampler_orig, UniformRandomSpatialNeighborSubsampler, SpatialNeighborSubsampler);
sampler_orig->SetSample(sample);
sampler_orig->SetSampleRegion(region);
sampler_orig->SetRadius(20);
sampler_orig->SetNumberOfResultsRequested(50);
sampler_orig->SetSeed(100);
sampler_orig->CanSelectQueryOff();
auto useClockForSeed = static_cast<bool>(std::stoi(argv[1]));
ITK_TEST_SET_GET_BOOLEAN(sampler_orig, UseClockForSeed, useClockForSeed);
// Test clone mechanism
SamplerType::Pointer sampler = sampler_orig->Clone().GetPointer();
ITK_TEST_SET_GET_VALUE(sampler_orig->GetSample(), sampler->GetSample());
ITK_TEST_SET_GET_VALUE(sampler_orig->GetSampleRegion(), sampler->GetSampleRegion());
ITK_TEST_SET_GET_VALUE(sampler_orig->GetRadius(), sampler->GetRadius());
ITK_TEST_SET_GET_VALUE(sampler_orig->GetNumberOfResultsRequested(), sampler->GetNumberOfResultsRequested());
ITK_TEST_SET_GET_VALUE(sampler_orig->GetSeed(), sampler->GetSeed());
ITK_TEST_SET_GET_VALUE(sampler_orig->GetCanSelectQuery(), sampler->GetCanSelectQuery());
SamplerType::SubsamplePointer subsample = SamplerType::SubsampleType::New();
sampler->Search(612, subsample);
for (SamplerType::SubsampleConstIterator sIt = subsample->Begin(); sIt != subsample->End(); ++sIt)
{
IndexType index;
index = sIt.GetMeasurementVector()[0].GetIndex();
inImage->SetPixel(index, 255);
}
if (argc > 2)
{
const std::string outFileName(argv[2]);
WriterType::Pointer writer = WriterType::New();
writer->SetFileName(outFileName);
writer->SetInput(inImage);
ITK_TRY_EXPECT_NO_EXCEPTION(writer->Update());
}
std::cout << "Test passed." << std::endl;
return EXIT_SUCCESS;
}
|
b741cd2fbe26a0010d575b8cd44c308ce5dd9c25 | acb26867f7425c166a74eab8c607815161a42365 | /gameof31.cpp | 12d6744dbfab18ed9a1fcee54d99ea84a3df5a4f | [] | no_license | Abdullah-Sheikh/Hacktoberfest-2021 | fa93424835e812d4565fbc6a3a96ca58d42a4b51 | 510ac063675096aefaf14ba53a3f28419d96980e | refs/heads/master | 2023-08-20T00:49:02.842193 | 2021-10-29T15:20:48 | 2021-10-29T15:20:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,958 | cpp | gameof31.cpp | /*
**** Written in Cpp. *****
** By Muhammad Abdullah (github.com/Abdullah-Sheikh) **
* contact me: abdullahsh123@hotmail.com *
**!! Feel free to updqate and enchance this game !!**
*******In this Game the user has two two options whether he is playing with computer or with second player.******
"31" is a card game played by 2 or more people
players. Generally each player's goal is to collect a number from
playing cards whose sum is as close as possible to 31. If
the sum of one player is greater than 31 then he automatically exits
toy ("burned"). The winner is the player with the highest total that is
less than or equal to 31.
*/
#include <iostream>
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
using namespace std;
// functions
void printCard(int card);
void printdeck(int deck[]);
void shuffledDeck(int deck[]);
int playerTurn(int deck[], int p_head[], int next_card);
int dealerTurn(int deck[], int d_head[], int next_card);
int sumHead(int hand[]);
int decideWinner(int p_sum, int d_sum);
bool isBurned(int sum);
void resethand(int hand[]);
void playGame(int deck[]);
//main program
int main()
{
int deck[52];
// initialize the deck
for (int i = 0; i < 52; i++)
{
int x = i + 1;
deck[i] = i + 1;
}
cout << "Initial deck :\n";
printdeck(deck);
cout << " ----------------\n";
cout << "| The Game of 31 |\n";
cout << " ----------------\n";
playGame(deck);
system("pause");
return 0;
}
void playGame(int deck[])
{
int input; // this variable would the get the decision of user to play game or not
int p_count = 0; // this variable is count the number of matches player wins
int d_count = 0; // ------------------------------------------- dealer ----
int p_hand[25] = { 0 };
int d_hand[25] = { 0 };
// the above two array would save the cards of player or dealer and initialize with zero
cout << "Would you like to Play (1 for 'Yes' , 0 for 'NO') : ";
cin >> input;
while (input == 1)
{
int next_card = 4; // next Card means the next index of the player or dealer card
// it will initialize with four because we will assign first four cards to the player and dealer at the begining of game
int w = 4;
int p_sum = 0; // sum of player cards
int d_sum = 0; // ------- dealer ----
shuffledDeck(deck);
cout << "Shufffled deck :\n";
printdeck(deck);
// default assign two cards to the player and dealer -----
p_hand[0] = deck[0];
p_hand[1] = deck[1];
d_hand[0] = deck[2];
d_hand[1] = deck[4];
//---------------------------------------------------------
while (w == 4) // while loop will continue until the player or dealer or the match will draw. w==4 means the loop will continue
{
if (!isBurned(p_sum))
{
cout << "----->Player's Turn<-----\n";
int select = 1;
while (select == 1 && !isBurned(p_sum))
{
cout << "Player Hand: ";
for (int i = 0; p_hand[i] != 0; i++) // print the player hand until 0 will arrives (0 means empty slots)
{
printCard(p_hand[i]);
}
cout << endl;
p_sum = sumHead(p_hand);
cout << "Card sum so far: " << p_sum << endl;
if (isBurned(p_sum))
{
cout << "*PLayer burned with sum " << p_sum << " !!*\n";
}
if (!isBurned(p_sum)){
cout << "Do you want a new card? (1-yes 0-no)";
cin >> select;
}
if (select == 1 && !isBurned(p_sum))
{
next_card = playerTurn(deck, p_hand, next_card);
}
}
}
if (!isBurned(d_sum))
{
cout << "----->Dealer Turn<-------\n";
while (d_sum < 25)
{
cout << "Dealer Hand: ";
for (int i = 0; d_hand[i] != 0; i++) // print the player hand until 0 will arrives (0 means empty slots)
{
printCard(d_hand[i]);
}
cout << endl;
d_sum = sumHead(d_hand);
cout << "Card sum so far: " << d_sum << endl;
if (isBurned(d_sum))
{
cout << "*Dealer burned with sum " << d_sum << " !!*\n";
cout << "Dealer Hand: ";
for (int i = 0; d_hand[i] != 0; i++)
{
printCard(d_hand[i]);
}
cout << endl;
}
next_card = dealerTurn(deck, d_hand, next_card);
}
}
w = decideWinner(p_sum, d_sum);
if (w == 1)
{
cout << "\n* Player Wins ! *\n";
p_count++;
}
if (w == 2)
{
cout << "\n* Dealer Wins ! *\n";
d_count++;
}
if (w == 0)
{
cout << "\n* This Round was draw *\n";
}
}
cout << "********************\n";
cout << " * SCORE *\n";
cout << "********************\n";
cout << "Player | Dealer \n";
cout << p_count << "\t| " << d_count << endl;
cout << "********************\n";
cout << "-> End of Round <-\n";
cout << "Would you like to Play (1 for 'Yes' , 0 for 'NO') : ";
cin >> input;
// if player wants to play more than we will remove the data in player and dealer hands (initialize with zero)
if (input == 1)
{
resethand(p_hand);
resethand(d_hand);
}
}
}
void printCard(int card)
{
// print 13 cards (A,2,3,---,k) --------------------------
if (card % 13 == 1)
{
cout << "| A";
}
else if (card % 13 == 11)
{
cout << "| J";
}
else if (card % 13 == 12)
{
cout << "| Q";
}
else if (card % 13 == 0)
{
cout << "| K";
}
else
{
cout << "| " << card % 13;
}
//---------------------------------------------
// print each tribe (Diamonds, hearts,clubs,spades) --------------------------
if (card / 13 == 0 && card % 13 != 0)
{
cout << "D |";
}
if (card / 13 == 1 && card % 13 != 0)
{
cout << "H |";
}
if (card / 13 == 2 && card % 13 != 0)
{
cout << "C |";
}
if (card / 13 == 3 && card % 13 != 0)
{
cout << "S |";
}
if (card / 13 == 1 && card % 13 == 0)
{
cout << "D |";
}
if (card / 13 == 2 && card % 13 == 0)
{
cout << "H |";
}
if (card / 13 == 3 && card % 13 == 0)
{
cout << "C |";
}
if (card / 13 == 4 && card % 13 == 0)
{
cout << "S |";
}
//--------------------------------------------------------------------------------
}
void printdeck(int deck[])
{
for (int i = 0; i < 52; i++)
{
printCard(deck[i]);
if (i == 12 || i == 25 || i == 38 || i == 51) //for print 13 cards in a row
{
cout << endl;
}
}
}
void shuffledDeck(int deck[])
{
bool check = true;
for (int i = 0; i < 52; i++)
{
check = true;
/* initialize random seed: */
srand(time(NULL));
while (check == true)
{
/* generate secret number between 1 and 10: */
int x = rand() % 52 + 1;
for (int j = 0; j <= i; j++)
{
if (deck[j] == x && i != j)
{
break;
}
if (i == j)
{
deck[i] = x;
check = false;
}
}
}
}
}
int playerTurn(int deck[], int p_head[], int next_card)
{
int i = 0;
while (p_head[i] != 0)
{
i++;
}
p_head[i] = deck[next_card];
return ++next_card;
}
int dealerTurn(int deck[], int d_head[], int next_card)
{
int i = 0;
while (d_head[i] != 0)
{
i++;
}
d_head[i] = deck[next_card];
return ++next_card;
}
int sumHead(int hand[])
{
int sum = 0;
for (int i = 0; hand[i] != 0; i++)
{
if (hand[i] % 13 == 1)
{
sum = sum + 1;
}
else if (hand[i] % 13 == 10 || hand[i] % 13 == 11 || hand[i] % 13 == 12 || hand[i] % 13 == 0)
{
sum = sum + 10;
}
else if (hand[i] % 13 > 1 && hand[i] % 13<10)
{
sum = sum + hand[i] % 13;
}
}
return sum;
}
int decideWinner(int p_sum, int d_sum)
{
if (d_sum > 31 && p_sum <= 31)
{
return 1;
}
else if (d_sum <=31 && p_sum > 31)
{
return 2;
}
else if (p_sum == d_sum)
{
return 0;
}
else if (p_sum > 31 && d_sum > 31)
{
return 0;
}
else
{
return 4; // to continue the game .....
}
}
bool isBurned(int sum)
{
if (sum > 31)
{
return true;
}
else
{
return false;
}
}
void resethand(int hand[])
{
for (int i = 0; i < 25; i++)
{
hand[i] = 0;
}
}
|
f02670a3bb909591adf918965deb94731fe3a326 | 79dd7d57e2cac14e8a948268605e1be0e74a7d25 | /collider/src/collider.cpp | 58aa474d8244090bd34ea4c03dea43fca82d443f | [] | no_license | shaun-edwards/arm_navigation_experimental | 2f473a6683a2dd9b38f7b1765f6e0bb2ddf5cb7e | f4ccaf716962fe8e356c87c00984cf6510a1783b | refs/heads/master | 2021-01-24T23:01:17.125537 | 2014-09-04T04:01:15 | 2014-09-04T04:01:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 48,567 | cpp | collider.cpp | /*********************************************************************
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Willow Garage, 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 the Willow Garage 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 Adam Harmat, Gil E. Jones, Kai M. Wurm, Armin Hornung
*********************************************************************/
#include "collider/collider.h"
#include <planning_environment/monitors/monitor_utils.h>
#include <octomap_msgs/conversions.h>
Collider::Collider(): root_handle_(""), pruning_counter_(0), transparent_freespace_(false) {
ros::NodeHandle priv("~");
cm_ = new planning_environment::CollisionModels("robot_description");
fixed_frame_ = cm_->getWorldFrameId();
attached_color_.a = 0.5;
attached_color_.r = 0.6;
attached_color_.g = 0.4;
attached_color_.b = 0.3;
priv.param<double>("resolution", resolution_, 0.1);
priv.param<double>("max_range", max_range_, -1.0); // default: full beam length
priv.param<int>("pruning_period", pruning_period_, 5);
priv.param<bool>("publish_static_over_dynamic_map", publish_over_dynamic_map_, false);
// bounds of collision map in fixed frame
priv.param<double>("dimension_x", workspace_box_.dimensionX, 0.0);
priv.param<double>("dimension_y", workspace_box_.dimensionY, 0.0);
priv.param<double>("dimension_z", workspace_box_.dimensionZ, 0.0);
// origin of collision map in the fixed frame
priv.param<double>("origin_x", workspace_box_.originX, 0.0);
priv.param<double>("origin_y", workspace_box_.originY, 0.0);
priv.param<double>("origin_z", workspace_box_.originZ, 0.0);
// compute some useful values
workspace_box_.real_minX = -workspace_box_.dimensionX + workspace_box_.originX;
workspace_box_.real_maxX = workspace_box_.dimensionX + workspace_box_.originX;
workspace_box_.real_minY = -workspace_box_.dimensionY + workspace_box_.originY;
workspace_box_.real_maxY = workspace_box_.dimensionY + workspace_box_.originY;
workspace_box_.real_minZ = -workspace_box_.dimensionZ + workspace_box_.originZ;
workspace_box_.real_maxZ = workspace_box_.dimensionZ + workspace_box_.originZ;
// stereo cam params for sensor cone:
priv.param<int>("camera_stereo_offset_left", camera_stereo_offset_left_, 128);
priv.param<int>("camera_stereo_offset_right", camera_stereo_offset_right_, 0);
collision_octree_ = new OcTreeType(resolution_);
double probHit = 0.7;
double probMiss = 0.4;
double thresMin = 0.12;
double thresMax = 0.97;
priv.param("sensor_model_hit", probHit, probHit);
priv.param("sensor_model_miss", probMiss, probMiss);
priv.param("sensor_model_min", thresMin, thresMin);
priv.param("sensor_model_max", thresMax, thresMax);
collision_octree_->setProbHit(probHit);
collision_octree_->setProbMiss(probMiss);
collision_octree_->setClampingThresMin(thresMin);
collision_octree_->setClampingThresMax(thresMax);
marker_pub_ = root_handle_.advertise<visualization_msgs::Marker>("visualization_marker", 10);
octomap_visualization_pub_ = root_handle_.advertise<visualization_msgs::Marker>("occupied_cells", 10);
octomap_visualization_free_pub_ = root_handle_.advertise<visualization_msgs::Marker>("free_cells", 10);
octomap_visualization_attached_pub_ = root_handle_.advertise<visualization_msgs::Marker>("attached_objects", 10);
octomap_visualization_attached_array_pub_ = root_handle_.advertise<visualization_msgs::MarkerArray>("attached_objects_array", 10);
cmap_publisher_ = root_handle_.advertise<arm_navigation_msgs::CollisionMap>("collision_map_out", 1, true);
static_map_publisher_ = root_handle_.advertise<arm_navigation_msgs::CollisionMap>("collision_map_occ_static", 1);
pointcloud_publisher_ = root_handle_.advertise<sensor_msgs::PointCloud2>("point_cloud_out", 1, true);
color_occupied_.r = 0;
color_occupied_.g = 0;
color_occupied_.b = 1.0;
color_occupied_.a = 0.5;
color_free_.r = 0;
color_free_.g = 1.0;
color_free_.b = 0.0;
color_free_.a = 0.5;
// create a self mask with links: (see self_see_filter.h)
double default_padding, default_scale;
priv.param<double> ("self_see_default_padding", default_padding, .01);
priv.param<double> ("self_see_default_scale", default_scale, 1.0);
priv.param<double> ("min_sensor_dist", self_filter_min_dist_, 0.05);
std::vector<robot_self_filter::LinkInfo> links;
if (!priv.hasParam ("self_see_links"))
{
ROS_WARN ("No links specified for self filtering.");
}
else
{
XmlRpc::XmlRpcValue ssl_vals;;
priv.getParam ("self_see_links", ssl_vals);
if (ssl_vals.getType () != XmlRpc::XmlRpcValue::TypeArray)
{
ROS_WARN ("Self see links need to be an array");
}
else
{
if (ssl_vals.size () == 0)
{
ROS_WARN ("No values in self see links array");
}
else
{
for (int i = 0; i < ssl_vals.size (); ++i)
{
robot_self_filter::LinkInfo li;
if (ssl_vals[i].getType() != XmlRpc::XmlRpcValue::TypeStruct)
{
ROS_WARN ("Self see links entry %d is not a structure. Stopping processing of self see links", i);
break;
}
if (!ssl_vals[i].hasMember ("name"))
{
ROS_WARN ("Self see links entry %d has no name. Stopping processing of self see links", i);
break;
}
li.name = std::string (ssl_vals[i]["name"]);
if (!ssl_vals[i].hasMember ("padding"))
{
ROS_DEBUG ("Self see links entry %d has no padding. Assuming default padding of %g", i, default_padding);
li.padding = default_padding;
}
else
{
li.padding = ssl_vals[i]["padding"];
}
if (!ssl_vals[i].hasMember ("scale"))
{
ROS_DEBUG ("Self see links entry %d has no scale. Assuming default scale of %g", i, default_scale);
li.scale = default_scale;
}
else
{
li.scale = ssl_vals[i]["scale"];
}
links.push_back (li);
}
}
}
}
robot_mask_right_ = new robot_self_filter::SelfMask(tf_, links);
robot_mask_left_ = new robot_self_filter::SelfMask(tf_, links);
ROS_INFO_STREAM("Robot self mask initialized with " << links.size() << " links");
cam_model_initialized_ = false;
camera_info_subscriber_ = new ros::Subscriber;
std::string camera_info_topic;
priv.getParam("camera_info_topic", camera_info_topic);
(*camera_info_subscriber_) = root_handle_.subscribe( camera_info_topic , 10,
&Collider::cameraInfoCallback, this);
if(!priv.hasParam("cloud_sources")) {
//ROS_WARN("No sensor sources specified, please set config correctly (e.g., config/sources.yaml)");
//return;
}
else
{
XmlRpc::XmlRpcValue cloud_sources;
priv.getParam("cloud_sources", cloud_sources);
if(cloud_sources.getType() != XmlRpc::XmlRpcValue::TypeArray) {
ROS_WARN("Cloud sources needs to be an array");
}
else
{
for(int i = 0; i < cloud_sources.size(); ++i)
{
CloudInfo cinfo;
if(cloud_sources[i].getType() != XmlRpc::XmlRpcValue::TypeStruct)
{
ROS_WARN("Cloud source entry %d is not a structure. Stopping processing of cloud sources",i);
break;
}
if(!cloud_sources[i].hasMember("name"))
{
ROS_WARN("Cloud sources entry %d has no name. Stopping processing of cloud sources",i);
break;
}
if(cloud_sources[i].hasMember("raw_name"))
{
cinfo.raw_cloud_name_ = std::string(cloud_sources[i]["raw_name"]);
if (!cloud_sources[i].hasMember("sensor_stereo_other_frame")){
ROS_WARN("Cloud sources entry %d has a raw_name but no sensor_stereo_other_frame. Stopping processing of cloud sources",i);
break;
} else{
cinfo.sensor_stereo_other_frame_ = std::string(cloud_sources[i]["sensor_stereo_other_frame"]);
}
}
if(!cloud_sources[i].hasMember("sensor_frame"))
{
ROS_WARN("Cloud sources entry %d has no sensor_frame. Stopping processing of cloud sources",i);
break;
}
cinfo.cloud_name_ = std::string(cloud_sources[i]["name"]);
cinfo.sensor_frame_ = std::string(cloud_sources[i]["sensor_frame"]);
if(!cloud_sources[i].hasMember("frame_subsample"))
{
ROS_DEBUG("Cloud sources entry %d has no frame subsample. Assuming default subsample of %g",i,1.0);
cinfo.frame_subsample_ = 1.0;;
}
else
{
cinfo.frame_subsample_ = cloud_sources[i]["frame_subsample"];
}
if(!cloud_sources[i].hasMember("point_subsample"))
{
ROS_DEBUG("Cloud sources entry %d has no point subsample. Assuming default subsample of %g",i,1.0);
cinfo.point_subsample_ = 1.0;;
}
else
{
cinfo.point_subsample_ = cloud_sources[i]["point_subsample"];
}
if(cloud_sources[i].hasMember("dynamic_buffer_size"))
cinfo.dynamic_buffer_size_ = static_cast<unsigned int>(int(cloud_sources[i]["dynamic_buffer_size"]));
if(cloud_sources[i].hasMember("static_buffer_size"))
cinfo.static_buffer_size_ = static_cast<unsigned int>(int(cloud_sources[i]["static_buffer_size"]));
if(cloud_sources[i].hasMember("dynamic_buffer_duration"))
cinfo.dynamic_buffer_duration_ = ros::Duration(int(cloud_sources[i]["dynamic_buffer_duration"]));
if(cloud_sources[i].hasMember("static_buffer_duration"))
cinfo.static_buffer_duration_ = ros::Duration(int(cloud_sources[i]["static_buffer_duration"]));
if(cloud_sources[i].hasMember("dynamic_publish"))
cinfo.dynamic_publish_ = cloud_sources[i]["dynamic_publish"];
if(cloud_sources[i].hasMember("static_publish"))
cinfo.static_publish_ = cloud_sources[i]["static_publish"];
if(cloud_sources[i].hasMember("dynamic_until_static_publish")) {
cinfo.dynamic_until_static_publish_ = cloud_sources[i]["dynamic_until_static_publish"];
}
if(cloud_sources_.find(cinfo.cloud_name_) != cloud_sources_.end())
{
ROS_WARN_STREAM("Already have a cloud defined with name " << cinfo.cloud_name_ << ", using prior values");
}
else
{
message_filters::Subscriber<sensor_msgs::PointCloud2>* sub = new message_filters::Subscriber<sensor_msgs::PointCloud2>();
sub->subscribe(root_handle_, cinfo.cloud_name_, 3);
sub_filtered_clouds_.push_back(sub);
if(cinfo.raw_cloud_name_ != "") {
message_filters::Subscriber<sensor_msgs::PointCloud2>* sub_raw = new message_filters::Subscriber<sensor_msgs::PointCloud2>();
sub_raw->subscribe(root_handle_,cinfo.raw_cloud_name_, 3);
message_filters::Synchronizer<message_filters::sync_policies::ApproximateTime<sensor_msgs::PointCloud2, sensor_msgs::PointCloud2> >* sync =
new message_filters::Synchronizer<message_filters::sync_policies::ApproximateTime<sensor_msgs::PointCloud2, sensor_msgs::PointCloud2> >(3);
sub_raw_clouds_.push_back(sub_raw);
sync->connectInput (*sub, *sub_raw);
sync->registerCallback(bind (&Collider::cloudCombinedCallback, this, _1, _2, cinfo.cloud_name_));
sync_vector_.push_back(sync);
ROS_INFO_STREAM("Adding synced callback for cloud " << cinfo.cloud_name_ << " raw " << cinfo.raw_cloud_name_);
} else {
sub->registerCallback(boost::bind(&Collider::cloudCallback, this, _1, cinfo.cloud_name_));
ROS_INFO_STREAM("Adding callback for " << cinfo.cloud_name_);
}
cloud_sources_[cinfo.cloud_name_] = cinfo;
}
}
}
}
attached_collision_object_subscriber_ = new message_filters::Subscriber<arm_navigation_msgs::AttachedCollisionObject>(root_handle_, "attached_collision_object", 1024);
attached_collision_object_subscriber_->registerCallback(boost::bind(&Collider::attachedObjectCallback, this, _1));
collision_object_subscriber_ = new message_filters::Subscriber<arm_navigation_msgs::CollisionObject>(root_handle_, "collision_object", 1024);
collision_object_subscriber_->registerCallback(boost::bind(&Collider::objectCallback, this, _1));
reset_service_ = priv.advertiseService("reset", &Collider::reset, this);
dummy_reset_service_ = priv.advertiseService("dummy_reset", &Collider::dummyReset, this);
action_server_.reset( new actionlib::SimpleActionServer<arm_navigation_msgs::MakeStaticCollisionMapAction>(root_handle_, "make_static_collision_map", boost::bind(&Collider::makeStaticCollisionMap, this, _1), false));
action_server_->start();
// queries on the map:
get_octomap_service_ = root_handle_.advertiseService("octomap_binary", &Collider::octomapSrv, this);
occupancy_point_service_ = root_handle_.advertiseService("occupancy_point", &Collider::occupancyPointSrv, this);
occupancy_bbx_service_ = root_handle_.advertiseService("occupancy_in_bbx", &Collider::occupancyBBXSrv, this);
occupancy_bbx_size_service_ = root_handle_.advertiseService("occupancy_in_bbx_size", &Collider::occupancyBBXSizeSrv, this);
}
Collider::~Collider() {
delete collision_octree_;
delete robot_mask_right_;
delete robot_mask_left_;
delete attached_collision_object_subscriber_;
delete collision_object_subscriber_;
for(unsigned int i = 0; i < sub_filtered_clouds_.size(); ++i){
delete sub_filtered_clouds_[i];
}
for(unsigned int i = 0; i < sub_raw_clouds_.size(); ++i) {
delete sub_raw_clouds_[i];
}
for(unsigned int i = 0; i < sync_vector_.size(); ++i) {
delete sync_vector_[i];
}
}
void Collider::attachedObjectCallback(const arm_navigation_msgs::AttachedCollisionObjectConstPtr& attached_object) {
planning_environment::processAttachedCollisionObjectMsg(attached_object, tf_, cm_);
}
void Collider::objectCallback(const arm_navigation_msgs::CollisionObjectConstPtr& object) {
planning_environment::processCollisionObjectMsg(object, tf_, cm_);
}
void Collider::cameraInfoCallback(const sensor_msgs::CameraInfo::ConstPtr &cam_info){
ROS_DEBUG("Got camera info: %d x %d\n", cam_info->height, cam_info->width);
cam_model_.fromCameraInfo(*cam_info);
cam_size_ = cam_model_.fullResolution();
cam_model_initialized_ = true;
delete camera_info_subscriber_;
}
void Collider::cloudCombinedCallback(const sensor_msgs::PointCloud2::ConstPtr &cloud,
const sensor_msgs::PointCloud2::ConstPtr &cloud_raw,
const std::string topic_name) {
CloudInfo settings = cloud_sources_[topic_name];
ros::WallTime begin_cb = ros::WallTime::now();
if (!cam_model_initialized_) {
ROS_INFO ("ERROR: camera model not initialized.");
return;
}
// Use old callback with cloud (filtered)
// cloudCallback (cloud, "full_cloud_filtered");
// For clearing use cloud_raw to check projections
// (cloud_raw.{width,height})
// transform pointcloud from sensor frame to fixed_frame_
if (!tf_.waitForTransform(fixed_frame_, cloud_raw->header.frame_id, cloud->header.stamp, ros::Duration(1.0))) {
ROS_WARN_STREAM( "Timed out waiting for transform from " << cloud_raw->header.frame_id
<< " to " << fixed_frame_ << ", quitting callback");
return;
}
// transform pointcloud from sensor frame to fixed_frame_
if (!tf_.waitForTransform(fixed_frame_, cloud->header.frame_id, cloud->header.stamp, ros::Duration(1.0))) {
ROS_WARN_STREAM( "Timed out waiting for transform from " << cloud->header.frame_id
<< " to " << fixed_frame_ << ", quitting callback");
return;
}
tf::StampedTransform trans;
tf_.lookupTransform (fixed_frame_, cloud->header.frame_id, cloud->header.stamp, trans);
tf::Transform to_world = trans;
ros::WallTime begin_transform = ros::WallTime::now();
Eigen::Matrix4f eigen_transform;
sensor_msgs::PointCloud2 transformed_cloud;
// // cturtle:
// pcl::transformAsMatrix (to_world, eigen_transform);
// pcl::transformPointCloud (eigen_transform, *cloud, transformed_cloud);
// // dturtle:
pcl_ros::transformAsMatrix (to_world, eigen_transform);
pcl_ros::transformPointCloud (eigen_transform, *cloud, transformed_cloud);
pcl::PointCloud<pcl::PointXYZ> pcl_cloud;
pcl::fromROSMsg (transformed_cloud, pcl_cloud);
pcl_cloud.header.frame_id = cm_->getWorldFrameId();
pcl_cloud.header.stamp = cloud->header.stamp;
std::vector<int> inside_mask;
//filtering out attached object inside points
if(planning_environment::computeAttachedObjectPointCloudMask(pcl_cloud,
cm_->getWorldFrameId(),
cm_,
tf_,
inside_mask)) {
pcl::PointCloud<pcl::PointXYZ>::iterator it = pcl_cloud.points.begin();
unsigned int i = 0;
unsigned int count = 0;
while(it != pcl_cloud.points.end()) {
if(inside_mask[i++] == robot_self_filter::INSIDE) {
it = pcl_cloud.points.erase(it);
count++;
} else {
it++;
}
}
ROS_DEBUG_STREAM("Filtering " << count << " points");
}
{
planning_models::KinematicState state(cm_->getKinematicModel());
state.setKinematicStateToDefault();
planning_environment::updateAttachedObjectBodyPoses(cm_,
state,
tf_);
visualization_msgs::MarkerArray arr;
cm_->getAttachedCollisionObjectMarkers(state,
arr,
"filter_attached",
attached_color_,
ros::Duration(.2));
octomap_visualization_attached_array_pub_.publish(arr);
}
std_msgs::Header global_header = cloud->header;
global_header.frame_id = fixed_frame_;
// pcl::transformPointCloud (fixed_frame_, *cloud, transformed_cloud, tf_);
// pcl::PointCloud<pcl::PointXYZ> pcl_cloud;
// pcl::fromROSMsg (transformed_cloud, pcl_cloud);
pcl::PointCloud<pcl::PointXYZ> pcl_cloud_raw;
pcl::fromROSMsg (*cloud_raw, pcl_cloud_raw);
// copy data to octomap pointcloud
octomap::Pointcloud octo_pointcloud;
octomap::pointcloudPCLToOctomap(pcl_cloud, octo_pointcloud);
double elapsed_transform = (ros::WallTime::now() - begin_transform).toSec();
octomap::point3d sensor_origin = getSensorOrigin(cloud->header);
tf::Point sensor_origin_tf = octomap::pointOctomapToTf(sensor_origin);
// integrate pointcloud into map
ros::WallTime begin_insert = ros::WallTime::now();
// make use of lazy update
collision_octree_->insertScan(octo_pointcloud, sensor_origin, max_range_, false, true);
collision_octree_->updateInnerOccupancy();
double elapsed_insert = (ros::WallTime::now() - begin_insert).toSec();
// remove outdated occupied nodes -----
ros::WallTime begin_degrade = ros::WallTime::now();
degradeOutdatedRaw(cloud->header, sensor_origin_tf, settings.sensor_stereo_other_frame_, pcl_cloud_raw);
double elapsed_degrade = (ros::WallTime::now() - begin_degrade).toSec();
// get all occupied nodes from map
octomap::point3d_list node_centers;
ros::WallTime begin_get_occupied = ros::WallTime::now();
std::vector<geometry_msgs::Point> pointlist;
getOccupiedPoints(pointlist);
//collision_octree_->getOccupied(node_centers);
double elapsed_get_occupied = (ros::WallTime::now() - begin_get_occupied).toSec();
// publish occupied cells
ros::WallTime begin_send = ros::WallTime::now();
if (settings.dynamic_publish_ && cmap_publisher_.getNumSubscribers() > 0) {
publishCollisionMap(pointlist, global_header, cmap_publisher_);
}
if (pointcloud_publisher_.getNumSubscribers() > 0) {
publishPointCloud(pointlist, global_header, pointcloud_publisher_);
}
if (octomap_visualization_pub_.getNumSubscribers() > 0){
publishMarkerArray(pointlist, global_header, color_occupied_, octomap_visualization_pub_);
}
if (octomap_visualization_free_pub_.getNumSubscribers() > 0){
std::vector<geometry_msgs::Point> freelist;
getFreePoints(freelist);
publishMarkerArray(freelist, global_header, color_free_, octomap_visualization_free_pub_);
}
double elapsed_send = (ros::WallTime::now() - begin_send).toSec();
double total_elapsed = (ros::WallTime::now() - begin_cb).toSec();
ROS_DEBUG("Total cloudCombinedCB %d pts: %f (transf: %f, update: %f, clear: %f, get occ: %f, send map: %f)",
int(pcl_cloud.size()), total_elapsed, elapsed_transform, elapsed_insert, elapsed_degrade, elapsed_get_occupied, elapsed_send);
}
void Collider::cloudCallback(const sensor_msgs::PointCloud2::ConstPtr &cloud, const std::string topic_name) {
ros::WallTime begin_cb = ros::WallTime::now();
CloudInfo settings = cloud_sources_[topic_name];
// transform pointcloud from sensor frame to fixed_frame_
if (!tf_.waitForTransform(fixed_frame_, cloud->header.frame_id, cloud->header.stamp, ros::Duration(1.0))) {
ROS_WARN_STREAM( "Timed out waiting for transform from " << cloud->header.frame_id
<< " to " << fixed_frame_ << ", quitting callback");
return;
}
// sensor_msgs::PointCloud2 transformed_cloud;
// pcl::transformPointCloud (fixed_frame_, *cloud, transformed_cloud, tf_);
// // tf::StampedTransform transform;
// // tf_.lookupTransform (fixed_frame_, cloud->header.frame_id, cloud->header.stamp, transform);
// // pcl::transformPointCloud (*cloud, transformed_cloud, transform);
// pcl::PointCloud<pcl::PointXYZ> pcl_cloud;
// pcl::fromROSMsg (transformed_cloud, pcl_cloud);
tf::StampedTransform trans;
tf_.lookupTransform (fixed_frame_, cloud->header.frame_id, cloud->header.stamp, trans);
tf::Transform to_world = trans;
Eigen::Matrix4f eigen_transform;
sensor_msgs::PointCloud2 transformed_cloud;
// // cturtle:
// pcl::transformAsMatrix (to_world, eigen_transform);
// pcl::transformPointCloud (eigen_transform, *cloud, transformed_cloud);
// // dturtle:
pcl_ros::transformAsMatrix (to_world, eigen_transform);
pcl_ros::transformPointCloud (eigen_transform, *cloud, transformed_cloud);
pcl::PointCloud<pcl::PointXYZ> pcl_cloud;
pcl::fromROSMsg (transformed_cloud, pcl_cloud);
transformed_cloud.header.frame_id = fixed_frame_;
std::vector<int> inside_mask;
//filtering out attached object inside points
if(planning_environment::computeAttachedObjectPointCloudMask(pcl_cloud,
cm_->getWorldFrameId(),
cm_,
tf_,
inside_mask)) {
pcl::PointCloud<pcl::PointXYZ>::iterator it = pcl_cloud.points.begin();
unsigned int i = 0;
while(it != pcl_cloud.end()) {
if(inside_mask[i++] == robot_self_filter::INSIDE) {
it = pcl_cloud.points.erase(it);
} else {
it++;
}
}
}
{
planning_models::KinematicState state(cm_->getKinematicModel());
state.setKinematicStateToDefault();
planning_environment::updateAttachedObjectBodyPoses(cm_,
state,
tf_);
visualization_msgs::MarkerArray arr;
cm_->getAttachedCollisionObjectMarkers(state,
arr,
"filter_attached",
attached_color_,
ros::Duration(.2));
octomap_visualization_attached_array_pub_.publish(arr);
}
// copy data to octomap pointcloud
octomap::Pointcloud octo_pointcloud;
octomap::pointcloudPCLToOctomap(pcl_cloud, octo_pointcloud);
// // retrieve sensor pose from tf
// tf::StampedTransform trans;
// tf_.lookupTransform (fixed_frame_, settings.sensor_frame_, cloud->header.stamp, trans);
// tf::Vector3 orig = trans.getOrigin();
// octomap::pose6d sensor_pose(orig.x(), orig.y(), orig.z(), 0, 0, 0);
// octomap::point3d sensor_origin(orig.x(), orig.y(), orig.z());
octomap::point3d sensor_origin = getSensorOrigin(cloud->header);
octomap::pose6d sensor_pose(sensor_origin.x(), sensor_origin.y(), sensor_origin.z(), 0, 0, 0);
/*
fprintf(stderr, "sensor origin: %.2f , %.2f , %.2f\n (frame: %s)",
sensor_origin.x(), sensor_origin.y(), sensor_origin.z(),
cloud->header.frame_id.c_str());
*/
// integrate pointcloud into map
ros::WallTime begin_insert = ros::WallTime::now();
collision_octree_->insertScan(octo_pointcloud, sensor_origin, max_range_, false);
double elapsed_insert = (ros::WallTime::now() - begin_insert).toSec();
ros::WallTime begin_degrade = ros::WallTime::now();
// remove outdated occupied nodes
//degradeOutdatedRaycasting(cloud->header, sensor_origin, *collision_octree_);
// remove single voxels with no neighbors (probably noise)
degradeSingleSpeckles();
double elapsed_degrade = (ros::WallTime::now() - begin_degrade).toSec();
// get all occupied nodes from map
octomap::point3d_list node_centers;
ros::WallTime begin_get_occupied = ros::WallTime::now();
std::vector<geometry_msgs::Point> pointlist;
getOccupiedPoints(pointlist);
double elapsed_get_occupied = (ros::WallTime::now() - begin_get_occupied).toSec();
// publish occupied cells
ros::WallTime begin_send = ros::WallTime::now();
if (settings.dynamic_publish_ && cmap_publisher_.getNumSubscribers() > 0) {
publishCollisionMap(pointlist, transformed_cloud.header, cmap_publisher_);
}
if (pointcloud_publisher_.getNumSubscribers() > 0) {
publishPointCloud(pointlist, transformed_cloud.header, pointcloud_publisher_);
}
if (octomap_visualization_pub_.getNumSubscribers() > 0){
publishMarkerArray(pointlist, transformed_cloud.header, color_occupied_, octomap_visualization_pub_);
}
double elapsed_send = (ros::WallTime::now() - begin_send).toSec();
double total_elapsed = (ros::WallTime::now() - begin_cb).toSec();
ROS_DEBUG("Total cloudCB: %f (Update %d pnts: %f, clearing: %f, get occupied: %f, send map: %f)",
total_elapsed, int(pcl_cloud.size()), elapsed_insert, elapsed_degrade, elapsed_get_occupied, elapsed_send);
}
void Collider::degradeOutdatedRaw(const std_msgs::Header& sensor_header, const tf::Point& sensor_origin,
const std::string& other_stereo_frame, const pcl::PointCloud<pcl::PointXYZ>& pcl_cloud_raw) {
tf::StampedTransform trans;
// tf_.lookupTransform (fixed_frame_, sensor_header.frame_id, sensor_header.stamp, trans);
// tf::Transform to_world = trans;
tf_.lookupTransform (sensor_header.frame_id, fixed_frame_, sensor_header.stamp, trans);
tf::Transform to_sensor = trans;
robot_mask_right_->assumeFrame(fixed_frame_, sensor_header.stamp, sensor_header.frame_id, self_filter_min_dist_);
robot_mask_left_->assumeFrame(fixed_frame_, sensor_header.stamp, other_stereo_frame, self_filter_min_dist_);
tf::Vector3 sensor_pos_right, sensor_pos_left;
planning_models::KinematicState state(cm_->getKinematicModel());
planning_environment::configureForAttachedBodyMask(state,
cm_,
tf_,
sensor_header.frame_id,
sensor_header.stamp,
sensor_pos_right);
planning_environment::configureForAttachedBodyMask(state,
cm_,
tf_,
other_stereo_frame,
sensor_header.stamp,
sensor_pos_left);
octomap::point3d min;
octomap::point3d max;
computeBBX(sensor_header, min, max);
unsigned query_time = time(NULL);
unsigned max_update_time = 3;
for(OcTreeType::leaf_bbx_iterator it = collision_octree_->begin_leafs_bbx(min,max),
end=collision_octree_->end_leafs_bbx(); it!= end; ++it)
{
if (collision_octree_->isNodeOccupied(*it) &&
((query_time - it->getTimestamp()) > max_update_time))
{
tf::Point pos(it.getX(), it.getY(), it.getZ());
tf::Point posRel = to_sensor(pos);
cv::Point2d uv = cam_model_.project3dToPixel(cv::Point3d(posRel.x(), posRel.y(), posRel.z()));
// ignore point if not in sensor cone
if (!inSensorCone(uv))
continue;
// ignore point if it is occluded in the map
if (isOccludedRaw(uv, pos.distance(sensor_origin), pcl_cloud_raw))
continue;
// ignore point if it is in the shadow of the robot or attached object
if (robot_mask_right_->getMaskIntersection(pos) == robot_self_filter::SHADOW
|| robot_mask_left_->getMaskIntersection(pos) == robot_self_filter::SHADOW
|| planning_environment::computeAttachedObjectPointMask(cm_, pos, sensor_pos_right) == robot_self_filter::SHADOW
|| planning_environment::computeAttachedObjectPointMask(cm_, pos, sensor_pos_left) == robot_self_filter::SHADOW)
{
continue;
}
// otherwise: degrade node
collision_octree_->integrateMissNoTime(&*it);
}
}
// // query map for occupied leafs within a given BBX and time frame
// std::list<std::pair<octomap::point3d, octomap::OcTreeNodeStamped*> > nodes;
// tree.getOccupiedNodesUpdateTimeBBX(nodes, 3, time(NULL), min, max);
//
//
//
// std::list<std::pair<octomap::point3d, octomap::OcTreeNodeStamped*> >::iterator it = nodes.begin();
// for ( ; it != nodes.end(); ++it) {
//
//
// // ignore point if not in sensor cone
// if (!inSensorCone(to_sensor, it->first))
// continue;
//
// // ignore point if it is occluded in the map
// if (isOccludedRaw(to_sensor, sensor_origin, it->first, pcl_cloud_raw))
// continue;
//
// // ignore point if it is in the shadow of the robot:
// if (robot_mask_right_->getMaskIntersection(octomap::pointOctomapToTf(it->first)) == robot_self_filter::SHADOW
// || robot_mask_left_->getMaskIntersection(octomap::pointOctomapToTf(it->first)) == robot_self_filter::SHADOW
// || planning_environment::computeAttachedObjectPointMask(cm_, octomap::pointOctomapToTf(it->first), sensor_pos_right) == robot_self_filter::SHADOW
// || planning_environment::computeAttachedObjectPointMask(cm_, octomap::pointOctomapToTf(it->first), sensor_pos_left) == robot_self_filter::SHADOW)
// {
// continue;
// }
//
// // degrade node
// collision_octree_->integrateMissNoTime(it->second);
// }
/* std_msgs::Header marker_header = sensor_header;
marker_header.frame_id = fixed_frame_;
publishMarkerArray(shadow_voxels, marker_header, octomap_debug_pub_);*/
}
void Collider::degradeOutdatedRaycasting(const std_msgs::Header& sensor_header, const octomap::point3d& sensor_origin,
octomap::OcTreeStamped& tree) {
tf::StampedTransform trans;
tf_.lookupTransform (sensor_header.frame_id, fixed_frame_, sensor_header.stamp, trans);
tf::Transform to_sensor = trans;
// compute bbx from sensor cone
octomap::point3d min;
octomap::point3d max;
computeBBX(sensor_header, min, max);
unsigned query_time = time(NULL);
unsigned max_update_time = 1;
for(OcTreeType::leaf_bbx_iterator it = collision_octree_->begin_leafs_bbx(min,max),
end=collision_octree_->end_leafs_bbx(); it!= end; ++it)
{
if (collision_octree_->isNodeOccupied(*it) &&
((query_time - it->getTimestamp()) > max_update_time))
{
tf::Point pos(it.getX(), it.getY(), it.getZ());
tf::Point posRel = to_sensor(pos);
cv::Point2d uv = cam_model_.project3dToPixel(cv::Point3d(posRel.x(), posRel.y(), posRel.z()));
// ignore point if not in sensor cone
if (!inSensorCone(uv))
continue;
// ignore point if it is occluded in the map
if (isOccludedMap(sensor_origin, it.getCoordinate()))
continue;
// otherwise: degrade node
collision_octree_->integrateMissNoTime(&*it);
}
}
}
void Collider::degradeSingleSpeckles(){
for(OcTreeType::leaf_iterator it = collision_octree_->begin_leafs(),
end=collision_octree_->end_leafs(); it!= end; ++it)
{
if (collision_octree_->isNodeOccupied(*it)){
octomap::OcTreeKey nKey = it.getKey();
octomap::OcTreeKey key;
bool neighborFound = false;
for (key[2] = nKey[2] - 1; !neighborFound && key[2] <= nKey[2] + 1; ++key[2]){
for (key[1] = nKey[1] - 1; !neighborFound && key[1] <= nKey[1] + 1; ++key[1]){
for (key[0] = nKey[0] - 1; !neighborFound && key[0] <= nKey[0] + 1; ++key[0]){
if (key != nKey){
OcTreeType::NodeType* node = collision_octree_->search(key);
if (node && collision_octree_->isNodeOccupied(node)){
// we have a neighbor => break!
neighborFound = true;
}
}
}
}
}
// done with search, see if found and degrade otherwise:
if (!neighborFound){
ROS_DEBUG("Degrading single speckle at (%f,%f,%f)", it.getX(), it.getY(), it.getZ());
collision_octree_->integrateMissNoTime(&*it);
}
}
}
}
octomap::point3d Collider::getSensorOrigin(const std_msgs::Header& sensor_header) {
geometry_msgs::PointStamped stamped_in;
geometry_msgs::PointStamped stamped_out;
stamped_in.header = sensor_header;
// HACK: laser origin
if (sensor_header.frame_id == "base_footprint") {
stamped_in.header.frame_id = "laser_tilt_link";
}
geometry_msgs::Point p;
p.x=p.y=p.z=0;
try {
tf_.transformPoint(fixed_frame_, stamped_in, stamped_out);
} catch(tf::TransformException& ex) {
ros::Time t;
std::string err_string;
ROS_INFO_STREAM("Transforming sensor origin using latest common time because there's a tf problem");
if (tf_.getLatestCommonTime(fixed_frame_, stamped_in.header.frame_id, stamped_in.header.stamp, &err_string) == tf::NO_ERROR) {
try {
tf_.transformPoint(fixed_frame_, stamped_in, stamped_out);
} catch(...) {
ROS_WARN_STREAM("Still can't transform sensor origin between " << fixed_frame_ << " and " << stamped_in.header.frame_id);
}
} else {
ROS_WARN_STREAM("No common time between " << fixed_frame_ << " and " << stamped_in.header.frame_id);
}
}
octomap::point3d retval (stamped_out.point.x, stamped_out.point.y, stamped_out.point.z);
return retval;
}
void Collider::computeBBX(const std_msgs::Header& sensor_header, octomap::point3d& bbx_min, octomap::point3d& bbx_max) {
std::string sensor_frame = sensor_header.frame_id;
// transform sensor FOV
geometry_msgs::PointStamped stamped_in;
geometry_msgs::PointStamped stamped_out;
stamped_in.header = sensor_header;
stamped_in.header.frame_id = sensor_frame;
// get max 3d points from camera at 0.5m and 5m.
geometry_msgs::Point p[8];
// define min/max 2d points
cv::Point2d uv [4];
uv[0].x = camera_stereo_offset_left_;
uv[0].y = 0;
uv[1].x = cam_size_.width + camera_stereo_offset_right_;
uv[1].y = 0;
uv[2].x = cam_size_.width + camera_stereo_offset_right_;
uv[2].y = cam_size_.height;
uv[3].x = camera_stereo_offset_left_;
uv[3].y = cam_size_.height;
// transform to 3d space
cv::Point3d xyz [4];
for (int i=0;i<4;i++) {
xyz[i] = cam_model_.projectPixelTo3dRay(uv[i]);
cv::Point3d xyz_05 = xyz[i] * 0.5;
xyz[i] *= 5.; // 5meters
p[i].x = xyz[i].x;
p[i].y = xyz[i].y;
p[i].z = xyz[i].z;
p[i+4].x = xyz_05.x;
p[i+4].y = xyz_05.y;
p[i+4].z = xyz_05.z;
}
// transform to world coodinates and find axis-aligned bbx
bbx_min.x() = bbx_min.y() = bbx_min.z() = 1e6;
bbx_max.x() = bbx_max.y() = bbx_max.z() = -1e6;
for (int i=0; i<8; i++) {
stamped_in.point = p[i];
tf_.transformPoint(fixed_frame_, stamped_in, stamped_out);
p[i].x = stamped_out.point.x;
p[i].y = stamped_out.point.y;
p[i].z = stamped_out.point.z;
if (p[i].x < bbx_min.x()) bbx_min.x() = p[i].x;
if (p[i].y < bbx_min.y()) bbx_min.y() = p[i].y;
if (p[i].z < bbx_min.z()) bbx_min.z() = p[i].z;
if (p[i].x > bbx_max.x()) bbx_max.x() = p[i].x;
if (p[i].y > bbx_max.y()) bbx_max.y() = p[i].y;
if (p[i].z > bbx_max.z()) bbx_max.z() = p[i].z;
}
// // visualize axis-aligned querying bbx
visualization_msgs::Marker bbx;
bbx.header.frame_id = fixed_frame_;
bbx.header.stamp = ros::Time::now();
bbx.ns = "collider";
bbx.id = 1;
bbx.action = visualization_msgs::Marker::ADD;
bbx.type = visualization_msgs::Marker::CUBE;
bbx.pose.orientation.w = 1.0;
bbx.pose.position.x = (bbx_min.x() + bbx_max.x()) / 2.;
bbx.pose.position.y = (bbx_min.y() + bbx_max.y()) / 2.;
bbx.pose.position.z = (bbx_min.z() + bbx_max.z()) / 2.;
bbx.scale.x = bbx_max.x()-bbx_min.x();
bbx.scale.y = bbx_max.y()-bbx_min.y();
bbx.scale.z = bbx_max.z()-bbx_min.z();
bbx.color.g = 1;
bbx.color.a = 0.3;
marker_pub_.publish(bbx);
// visualize sensor cone
visualization_msgs::Marker bbx_points;
bbx_points.header.frame_id = fixed_frame_;
bbx_points.header.stamp = ros::Time::now();
bbx_points.ns = "collider";
bbx_points.id = 2;
bbx_points.action = visualization_msgs::Marker::ADD;
bbx_points.type = visualization_msgs::Marker::LINE_STRIP;
bbx_points.pose.orientation.w = 1.0;
bbx_points.scale.x = 0.02;
bbx_points.scale.y = 0.02;
bbx_points.color.g = 1;
bbx_points.color.a = 0.3;
bbx_points.points.push_back(p[0]);
bbx_points.points.push_back(p[1]);
bbx_points.points.push_back(p[2]);
bbx_points.points.push_back(p[3]);
bbx_points.points.push_back(p[0]);
bbx_points.points.push_back(p[4]);
bbx_points.points.push_back(p[5]);
bbx_points.points.push_back(p[6]);
bbx_points.points.push_back(p[7]);
bbx_points.points.push_back(p[4]);
bbx_points.points.push_back(p[7]);
bbx_points.points.push_back(p[3]);
bbx_points.points.push_back(p[2]);
bbx_points.points.push_back(p[6]);
bbx_points.points.push_back(p[5]);
bbx_points.points.push_back(p[1]);
marker_pub_.publish(bbx_points);
}
bool Collider::inSensorCone(const cv::Point2d& uv) const {
// Check if projected 2D coordinate in pixel range.
// This check is a little more restrictive than it should be by using
// 1 pixel less to account for rounding / discretization errors.
// Otherwise points on the corner are accounted to be in the sensor cone.
return ( (uv.x > camera_stereo_offset_left_+1)
&& (uv.x < cam_size_.width + camera_stereo_offset_right_ - 2)
&& (uv.y > 1)
&& (uv.y < cam_size_.height-2) );
}
bool Collider::isOccludedRaw(const cv::Point2d& uv, double range, const pcl::PointCloud<pcl::PointXYZ>& pcl_cloud_raw) {
// out of image range?
if ((uv.x < 0) || (uv.y < 0) || (uv.x > cam_size_.width) || (uv.y > cam_size_.height))
return false;
double sensor_range = pcl_cloud_raw(uv.x, uv.y).z;
return (sensor_range < range);
}
bool Collider::isOccludedMap(const octomap::point3d& sensor_origin, const octomap::point3d& p) const {
octomap::point3d direction (p-sensor_origin);
octomap::point3d obstacle;
double range = direction.norm() - resolution_;
if (collision_octree_->castRay(sensor_origin, direction, obstacle, true, range)) {
// fprintf(stderr, "<%.2f , %.2f , %.2f> -> <%.2f , %.2f , %.2f> // obs at: <%.2f , %.2f , %.2f>, range: %.2f\n",
// sensor_origin.x(), sensor_origin.y(), sensor_origin.z(),
// p.x(), p.y(), p.z(),
// obstacle.x(), obstacle.y(), obstacle.z(), (obstacle-p).norm());
return true;
}
return false;
}
// publish map ----------------------------------------------------------------------
void Collider::publishCollisionMap(const std::vector<geometry_msgs::Point>& pointlist,
const std_msgs::Header &header, ros::Publisher &pub) {
if(pointlist.size() <= 1)
return;
arm_navigation_msgs::CollisionMap cmap;
cmap.header = header;
arm_navigation_msgs::OrientedBoundingBox box;
box.extents.x = box.extents.y = box.extents.z = collision_octree_->getResolution();
box.axis.x = box.axis.y = 0.0; box.axis.z = 1.0;
box.angle = 0.0;
cmap.boxes.reserve(pointlist.size());
for (std::vector<geometry_msgs::Point>::const_iterator it = pointlist.begin(); it != pointlist.end(); ++it) {
box.center.x = it->x;
box.center.y = it->y;
box.center.z = it->z;
cmap.boxes.push_back(box);
}
pub.publish(cmap);
}
void Collider::publishPointCloud(const std::vector<geometry_msgs::Point>& pointlist,
const std_msgs::Header &header, ros::Publisher &pub) {
if(pointlist.size() <= 1)
return;
pcl::PointCloud<pcl::PointXYZ> pcl_cloud;
pcl_cloud.points.reserve (pointlist.size ());
for (std::vector<geometry_msgs::Point>::const_iterator it = pointlist.begin(); it != pointlist.end(); ++it) {
pcl::PointXYZ point;
point.x = it->x;
point.y = it->y;
point.z = it->z;
pcl_cloud.points.push_back (point);
}
sensor_msgs::PointCloud2 cloud;
pcl::toROSMsg (pcl_cloud, cloud);
cloud.header = header;
pub.publish (cloud);
}
void Collider::publishMarkerArray(const std::vector<geometry_msgs::Point>& pointlist,
const std_msgs::Header &header, const std_msgs::ColorRGBA& color,
ros::Publisher &pub) {
if(pointlist.size() <= 1)
return;
visualization_msgs::Marker occupiedCellsVis;
occupiedCellsVis.header = header;
occupiedCellsVis.ns = "map";
occupiedCellsVis.id = 0;
occupiedCellsVis.type = visualization_msgs::Marker::CUBE_LIST;
occupiedCellsVis.scale.x = collision_octree_->getResolution();
occupiedCellsVis.scale.y = collision_octree_->getResolution();
occupiedCellsVis.scale.z = collision_octree_->getResolution();
occupiedCellsVis.color = color;
occupiedCellsVis.points = pointlist;
pub.publish (occupiedCellsVis);
}
// action server --------------------------------------------------------------------
bool Collider::reset(std_srvs::Empty::Request &req, std_srvs::Empty::Response &res) {
delete collision_octree_;
collision_octree_ = new OcTreeType(resolution_);
return true;
}
bool Collider::dummyReset(std_srvs::Empty::Request &req, std_srvs::Empty::Response &res) {
// Dummy function that doesn't actually reset anything. Needed because some
// parts of the grasping pipeline want to reset the collision map
// on occasion, but with the octomap we don't want other nodes resetting the map sporadically.
return true;
}
void Collider::makeStaticCollisionMap(const arm_navigation_msgs::MakeStaticCollisionMapGoalConstPtr& goal) {
std_msgs::Header head;
head.stamp = ros::Time::now();
head.frame_id = fixed_frame_;
ROS_INFO("Making static collision map");
//we first publish whatever we got
std::vector<geometry_msgs::Point> pointlist;
getOccupiedPoints(pointlist);
if (pointcloud_publisher_.getNumSubscribers() > 0) {
publishPointCloud(pointlist, head, pointcloud_publisher_);
}
if(publish_over_dynamic_map_)
{
if (cmap_publisher_.getNumSubscribers() > 0) {
publishCollisionMap(pointlist, head, cmap_publisher_);
}
// loop through cloud_source_map, set dynamic publish to false on all sources to preserve behavior of older collision_map_self_occ
for(std::map<std::string,CloudInfo>::iterator it = cloud_sources_.begin();
it != cloud_sources_.end();
it++)
{
it->second.dynamic_publish_ = false;
}
ROS_INFO("Should stop publishing dynamic map");
} else {
publishCollisionMap(pointlist, head, static_map_publisher_);
}
action_server_->setSucceeded();
}
bool Collider::octomapSrv(octomap_msgs::GetOctomap::Request &req, octomap_msgs::GetOctomap::Response &res){
ROS_DEBUG("Sending map data on service request");
res.map.header.frame_id = fixed_frame_;
res.map.header.stamp = ros::Time::now();
octomap::octomapMapToMsg(*collision_octree_, res.map);
return true;
}
bool Collider::occupancyPointSrv(collider::OccupancyPointQuery::Request &req,
collider::OccupancyPointQuery::Response &res){
octomap::OcTreeNodeStamped* node = collision_octree_->search(req.point.x, req.point.y, req.point.z);
if (node){
if (collision_octree_->isNodeOccupied(node))
res.occupancy=collider::OccupancyPointQueryResponse::OCCUPIED;
else
res.occupancy=collider::OccupancyPointQueryResponse::FREE;
} else{
res.occupancy = collider::OccupancyPointQueryResponse::UNKNOWN;
}
return true;
}
bool Collider::occupancyBBXSrv(collider::OccupancyBBXQuery::Request &req,
collider::OccupancyBBXQuery::Response &res){
OcTreeType::leaf_bbx_iterator it = collision_octree_->begin_leafs_bbx(octomap::pointMsgToOctomap(req.min),
octomap::pointMsgToOctomap(req.max));
OcTreeType::leaf_bbx_iterator end = collision_octree_->end_leafs_bbx();
geometry_msgs::Point pt;
for(; it!= end; ++it){
pt.x = it.getX();
pt.y = it.getY();
pt.z = it.getZ();
if (collision_octree_->isNodeOccupied(*it)){
res.occupied.push_back(pt);
} else {
res.free.push_back(pt);
}
}
res.resolution = collision_octree_->getResolution();
return true;
}
bool Collider::occupancyBBXSizeSrv(collider::OccupancyBBXSizeQuery::Request &req,
collider::OccupancyBBXSizeQuery::Response &res){
octomap::point3d center = octomap::pointMsgToOctomap(req.center);
octomap::point3d size = octomap::pointMsgToOctomap(req.size);
OcTreeType::leaf_bbx_iterator it = collision_octree_->begin_leafs_bbx(center - (size*0.5), center + (size*0.5));
OcTreeType::leaf_bbx_iterator end = collision_octree_->end_leafs_bbx();
geometry_msgs::Point pt;
for(; it!= end; ++it){
pt.x = it.getX();
pt.y = it.getY();
pt.z = it.getZ();
if (collision_octree_->isNodeOccupied(*it)){
res.occupied.push_back(pt);
} else {
res.free.push_back(pt);
}
}
res.resolution = collision_octree_->getResolution();
return true;
}
|
c0de6e7a308b8e0e9d16b760ee994e46a7d62d27 | 0034c069d5815c71c4252ff7cb4e755712425eaf | /src/Interfaces/RankDataContext.h | 580c144574026758c7558f64d4e4292238ea35ca | [
"Apache-2.0"
] | permissive | niuchenglei/rankextor | 3f3c912cf0c872509a35a67ebd4c636b080003e1 | 342e39dda8347b0986f6d2be9968ee72a90b16c2 | refs/heads/master | 2020-12-03T11:34:17.113500 | 2020-01-02T03:29:20 | 2020-01-02T03:29:20 | 231,300,419 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,336 | h | RankDataContext.h | #ifndef RANK_DATA_CONTEXT_H
#define RANK_DATA_CONTEXT_H
#include <time.h>
#include <mutex>
#include <thread>
#include <unordered_map>
#include "json/json.h"
#include "Interfaces/CommonType.h"
#include "Interfaces/ConfigurationSettings.h"
#include "Interfaces/PredictContext.h"
#include "Interfaces/RedisManager.h"
#include "Interfaces/Service.h"
#include "Interfaces/Util.h"
#include "Utilities/AdUtil.h"
#include "Interfaces/rank_interface.pb.h"
using std::make_pair;
using std::vector;
namespace rank {
enum StatsInfoType {
kPreStrategy,
kFeature,
kExtractor,
kModel,
kPostStrategy
};
class RankDataContext {
public:
RankDataContext() {
resource_manager = NULL;
}
/*bool init(const std::string& redis_group_config) {
return redis_handler.Initialize(redis_group_config);
}*/
void set_resource(ResourceManager* _resource_manager, int _worker_id) {
resource_manager = _resource_manager;
worker_idx = _worker_id;
//Service<ConfigurationSettings> pSetting;
//string _name = pSetting->getSetting("main/plugin_name");
}
inline void resize(size_t size) {
std::vector<Features>().swap(features);
features.resize(size);
std::vector<ad_item_pair_t>().swap(rank_order);
}
long reset(const RankRequest& fisher_request,
std::vector<RankAdInfo>& ad_list,
std::vector<RankItemInfo>& item_list) {
size_t ad_size = ad_list.size();
size_t item_size = item_list.size();
struct timespec start, end;
long sum = 0;
#ifdef PROF
clock_gettime(CLOCK_MONOTONIC, &start);
#endif
resize(item_size);
#ifdef PROF
clock_gettime(CLOCK_MONOTONIC, &end);
sum = (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_nsec - start.tv_nsec) / 1000;
FATAL(LOGNAME, "reset resize: %ld us (%d,%d)", sum, ad_size, item_size);
#endif
#ifdef PROF
clock_gettime(CLOCK_MONOTONIC, &start);
#endif
error_code = 0;
error_msg = "";
// 初始化特征数据
//boost::unordered_map<int64_t, Features::Item> empty_map;
//boost::unordered_map<int64_t, Features::Item>().swap(empty_map);
for (int i = 0; i < item_size; i++) {
if (item_list[i].filter_strategy != 10000 && item_list[i].filter_strategy != 0)
continue;
features[i].id = item_list[i].item_id;
boost::unordered_map<std::string, boost::unordered_map<int64_t, Features::Item> >().swap(features[i].features_group);
boost::unordered_map<int64_t, Features::Item>& empty_map = features[i].features_group["begin"];
}
for (int i = 0; i < ad_size; i++) {
ad_list[i].ctr = 0;
ad_list[i].score = 0;
ad_list[i].cost = ad_list[i].bid_price * 0.8;
//if (ad_list[i].bid_price <= 0 && ad_list[i].is_garanteed_delivery == 0)
// FATAL(LOGNAME, "fatal error: adid=%ld, bid_price=%ld", ad_list[i].ad_id, ad_list[i].bid_price);
if (ad_list[i].filter_strategy != 10000 && ad_list[i].filter_strategy != 0)
continue;
boost::unordered_map<int64_t, int>& ava_items = ad_list[i].available_items;
for (boost::unordered_map<int64_t, int>::iterator iter=ava_items.begin(); iter!=ava_items.end(); iter++) {
if (iter->second >= item_list.size()) continue;
if (item_list[iter->second].filter_strategy != 10000 &&
item_list[iter->second].filter_strategy != 0)
continue;
ad_item_pair_t _t; _t.ad_id = ad_list[i].ad_id; _t.ad_idx = i; _t.item_id = iter->first; _t.item_idx = iter->second; _t.score = 0; _t.filter_strategy = 10000; _t.cost = 0;
rank_order.push_back(_t);
}
// 初始化adlist里面的extend内容,目前包括:filter、tuning
//ad_list[i].extend.insert(make_pair("filter_reason", "0"));
//ad_list[i].extend.insert(make_pair("tuning", ""));
//v = boost::lexical_cast<string>(i);
//ad_list[i].extend.insert(make_pair("pre_sort_index", v));
//ad_list[i].extend.insert(make_pair("aft_sort_index", "0"));
}
#ifdef PROF
clock_gettime(CLOCK_MONOTONIC, &end);
sum = (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_nsec - start.tv_nsec) / 1000;
FATAL(LOGNAME, "reset adlist foreach: %ld us", sum);
#endif
#ifdef PROF
clock_gettime(CLOCK_MONOTONIC, &start);
#endif
/*// 获取redis数据
if (!redis_handler.Check(resource_manager, this->worker_idx)) {
FATAL(LOGNAME,
"RedisHandler initialize error (fetch instance from resource "
"manager with NULL)");
return 0;
}*/
//redis_handler.Clear();
//redis_handler.AddAdidRealTimeKey(ad_list);
clock_gettime(CLOCK_MONOTONIC, &start);
//bool ret = redis_handler.Fetch(fisher_request.rank_user_data);
//redis_fail_data[0] = (ret == true) ? 0 : 1;
clock_gettime(CLOCK_MONOTONIC, &end);
this->timeuse = (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_nsec - start.tv_nsec) / 1000;
#ifdef PROF
clock_gettime(CLOCK_MONOTONIC, &end);
sum = (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_nsec - start.tv_nsec) / 1000;
FATAL(LOGNAME, "reset redis: %ld us", sum);
#endif
#ifdef PROF
clock_gettime(CLOCK_MONOTONIC, &start);
#endif
//fillUserFeatureFromRedis(fisher_request);
//fillAdInfoFromRedis(ad_list);
#ifdef PROF
clock_gettime(CLOCK_MONOTONIC, &end);
sum = (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_nsec - start.tv_nsec) / 1000;
FATAL(LOGNAME, "reset fill data: %ld us", sum);
#endif
return this->timeuse;
}
bool SetRuningStrategy(const string& runing_strategy) {
return reader.parse(runing_strategy, strategy_json);
}
int worker_idx, max_queue_length;
UserInfo user; // 用户特征
//std::vector<AdsFeatures> ads_trace_data; // 广告特征
//std::vector<RealtimeData> realtime_data; // 广告的实时特征
Features common_features; // 共享特征
std::vector<Features> features; // 特征(gbdt编码等)
// RedisManager* redis_manager;
//RedisHandler redis_handler;
ResourceManager* resource_manager;
long timeuse;
int error_code;
std::string error_msg;
std::vector<ad_item_pair_t> rank_order;
Json::Value strategy_json; // 上游模块下发的动态配置策略信息, json,配置了需要运行的模块名称
Json::Reader reader;
};
} // namespace rank
#endif
|
8d2322bb7de0a07d3b9bdfe58b20ac094869111b | 0ba1f65704a4b678f9705c5632daf32a9c67990d | /NC/NC166A.cpp | e18c8d34f0ce61fa1b9d1fe7b3fe56092bb6e9d9 | [] | no_license | Challestend/challestends-code-set | 7f9e3a239ca32bc6424ac2a68ad46fb60b55ee43 | bd7d6935216d56f3667a6f939298eb84fe44fa6a | refs/heads/master | 2020-03-26T15:59:18.440653 | 2020-01-06T09:22:30 | 2020-01-06T09:22:30 | 145,075,894 | 0 | 0 | null | 2018-08-17T05:44:32 | 2018-08-17T05:30:09 | null | UTF-8 | C++ | false | false | 205 | cpp | NC166A.cpp | #include<cstdio>
#include<cmath>
#define re register
#define Pi acos(-1.0)
int r;
int main(){
scanf("%d",&r);
double a=Pi/17,ans=17.0*r*r*cos(a)*sin(a);
printf("%0.6lf",ans);
return 0;
}
|
a9fb12c3973955a91264fd5f1a1c74df759445b2 | e23eaec0adcce9069c19c6cca072785776f1ddfb | /Interview Play CPP/a692TopKFrequentWords.cpp | 7e80178ce0cce586eca62ff29ffa7ccc30390a25 | [] | no_license | rjtsdl/CPlusPlus | a4703ba11bcd4a918fa9b20d4de44cf9e021ebf6 | a5e8f14716dc1edf975039393fa3a653b406a8c5 | refs/heads/master | 2021-09-08T07:49:47.998796 | 2021-09-03T18:05:01 | 2021-09-03T18:05:01 | 33,706,235 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,207 | cpp | a692TopKFrequentWords.cpp | //
// a692TopKFrequentWords.cpp
// Interview Play CPP
//
// Created by Jingtao Ren on 11/11/20.
// Copyright © 2020 Jingtao Ren. All rights reserved.
//
#include <stdio.h>
#include <string>
#include <unordered_map>
#include <queue>
#include <utility>
#include <vector>
using namespace std;
class Solution {
public:
vector<string> topKFrequent(vector<string>& words, int k) {
unordered_map<string, int> wordCount;
for (string s: words) {
wordCount[s]++;
}
auto comp = [](const pair<int, string>& a, const pair<int, string>& b) {
return a.first > b.first || (a.first == b.first && a.second < b.second);
};
priority_queue<pair<int, string>, vector<pair<int, string>>, decltype(comp)> pq(comp);
for (auto kv: wordCount) {
pq.push(make_pair(kv.second, kv.first));
while (pq.size() > k) {
pq.pop();
}
}
vector<string> ret;
while (!pq.empty()) {
ret.push_back(pq.top().second);
pq.pop();
}
reverse(ret.begin(), ret.end());
return ret;
}
};
|
268dd8f400037d7b6453d0d390d455155e911b87 | dbbcae6490abfb4ea937e3db575461623eb00d25 | /Uhunt_problems/Others/UVA_902_passwordsearch.cpp | e809bc5b2e437e4928f8030a8d559a6695af1536 | [] | no_license | danielvallejo237/Advanced-Programming | 20ca78dfc1ee79f043efba315f766574939047b2 | 199bce1060622385d2b738e5c67e63e64d6a7eaa | refs/heads/main | 2023-05-21T12:09:56.130991 | 2021-06-10T17:01:27 | 2021-06-10T17:01:27 | 344,992,130 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 691 | cpp | UVA_902_passwordsearch.cpp | #include <bits/stdc++.h>
using namespace std;
string find_password(int size, string encoded)
{
map<string,int> freqs;
int max=0;
string argmax;
for(int i=0;i<encoded.size()-size;i++)
{
string aux=encoded.substr(i,size);
if(freqs.find(aux)==freqs.end())
{
freqs[aux]=1;
}
else
{
freqs[aux]+=1;
}
if(freqs[aux]>max)
{
max=freqs[aux];
argmax=aux;
}
}
return argmax;
}
int main()
{
string codigo;
int tamano;
while(cin>>tamano>>codigo && tamano)
{
cout<<find_password(tamano,codigo)<<endl;
}
return 0;
} |
279682222b21f52ca07402c2fa7df2e847ed7780 | c8438f31721efd2fed3ce0c5752ff033b1e71d72 | /c64/vice-2.4/src/resid-fp/sid.cc | 16278c1fd1e8e11076119015d83a10490083f465 | [
"GPL-2.0-only",
"MIT",
"GPL-2.0-or-later",
"GPL-1.0-or-later"
] | permissive | century-arcade/src | 8c9151d9847dd0f6d6b92f662444c70064b6845d | b6abba2679f5eaa5a71871b916459aab7ae50d1c | refs/heads/master | 2022-06-21T09:50:06.176276 | 2022-06-15T23:00:41 | 2022-06-15T23:00:47 | 13,259,218 | 4 | 1 | MIT | 2022-06-16T14:24:17 | 2013-10-02T00:18:36 | C | UTF-8 | C++ | false | false | 26,533 | cc | sid.cc | // ---------------------------------------------------------------------------
// This file is part of reSID, a MOS6581 SID emulator engine.
// Copyright (C) 2004 Dag Lem <resid@nimrod.no>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// ---------------------------------------------------------------------------
#include "sid.h"
#include <math.h>
extern float convolve(const float *a, const float *b, int n);
extern float convolve_sse(const float *a, const float *b, int n);
enum host_cpu_feature {
HOST_CPU_MMX=1, HOST_CPU_SSE=2, HOST_CPU_SSE2=4, HOST_CPU_SSE3=8
};
#ifdef _MSC_VER
# ifndef _WIN64
# define USE_ASM
# endif
#else
# if defined(__x86_64__) || defined(__i386__)
# define USE_ASM
# endif
#endif
#if (RESID_USE_SSE==1)
/* This code is appropriate for 32-bit and 64-bit x86 CPUs. */
#ifdef USE_ASM
struct cpu_x86_regs_s {
unsigned int eax;
unsigned int ebx;
unsigned int ecx;
unsigned int edx;
};
typedef struct cpu_x86_regs_s cpu_x86_regs_t;
static cpu_x86_regs_t get_cpuid_regs(unsigned int index)
{
cpu_x86_regs_t retval;
#if defined(_MSC_VER) /* MSVC assembly */
__asm {
mov eax, [index]
cpuid
mov [retval.eax], eax
mov [retval.ebx], ebx
mov [retval.ecx], ecx
mov [retval.edx], edx
}
#else /* GNU assembly */
asm("movl %4, %%eax; cpuid; movl %%eax, %0; movl %%ebx, %1; movl %%ecx, %2; movl %%edx, %3;"
: "=m" (retval.eax),
"=m" (retval.ebx),
"=m" (retval.ecx),
"=m" (retval.edx)
: "r" (index)
: "eax", "ebx", "ecx", "edx");
#endif
return retval;
}
static int host_cpu_features_by_cpuid(void)
{
cpu_x86_regs_t regs = get_cpuid_regs(1);
int features = 0;
if (regs.edx & (1 << 23))
features |= HOST_CPU_MMX;
if (regs.edx & (1 << 25))
features |= HOST_CPU_SSE;
if (regs.edx & (1 << 26))
features |= HOST_CPU_SSE2;
if (regs.ecx & (1 << 0))
features |= HOST_CPU_SSE3;
return features;
}
static int host_cpu_features(void)
{
static int features = 0;
static int features_detected = 0;
/* 32-bit only */
#if defined(__i386__) || (defined(_MSC_VER) && defined(_WIN32))
unsigned long temp1, temp2;
#endif
if (features_detected)
return features;
features_detected = 1;
#if defined(_MSC_VER) && defined(_WIN32) /* MSVC compatible assembly appropriate for 32-bit Windows */
/* see if we are dealing with a cpu that has the cpuid instruction */
__asm {
pushf
pop eax
mov [temp1], eax
xor eax, 0x200000
push eax
popf
pushf
pop eax
mov [temp2], eax
push [temp1]
popf
}
#endif
#if defined(__i386__) /* GNU assembly */
asm("pushfl; popl %%eax; movl %%eax, %0; xorl $0x200000, %%eax; pushl %%eax; popfl; pushfl; popl %%eax; movl %%eax, %1; pushl %0; popfl "
: "=r" (temp1),
"=r" (temp2)
:
: "eax");
# endif
#if defined(__i386__) || (defined(_MSC_VER) && defined(_WIN32))
temp1 &= 0x200000;
temp2 &= 0x200000;
if (temp1 == temp2) {
/* no cpuid support, so we can't test for SSE availability -> false */
return 0;
}
#endif
/* find the highest supported cpuid function, returned in %eax */
if (get_cpuid_regs(0).eax < 1) {
/* no cpuid 1 function, we can't test for features -> no features */
return 0;
}
features = host_cpu_features_by_cpuid();
return features;
}
#else /* !__x86_64__ && !__i386__ && !_MSC_VER */
static int host_cpu_features(void)
{
return 0;
}
#endif /* USE_ASM */
#endif /* RESID_USE_SSE */
/* tables used by voice/wavegen/envgen */
float dac[12];
float env_dac[256];
float wftable[11][4096];
/* nonlinear DAC support, set 1 for 8580 / no effect, about 0.96 otherwise */
void SIDFP::set_voice_nonlinearity(float nl)
{
voice[0].envelope.set_nonlinearity(nl);
voice[0].wave.set_nonlinearity(nl);
voice[0].wave.rebuild_wftable();
filter.set_nonlinearity(nl);
}
float SIDFP::kinked_dac(const int x, const float nonlinearity, const int max)
{
float value = 0.f;
int bit = 1;
float weight = 1.f;
const float dir = 2.0f * nonlinearity;
for (int i = 0; i < max; i ++) {
if (x & bit)
value += weight;
bit <<= 1;
weight *= dir;
}
return value / (weight / nonlinearity / nonlinearity) * (1 << max);
}
// ----------------------------------------------------------------------------
// Constructor.
// ----------------------------------------------------------------------------
SIDFP::SIDFP()
{
#if (RESID_USE_SSE==1)
can_use_sse = (host_cpu_features() & HOST_CPU_SSE) != 0;
#else
can_use_sse = false;
#endif
// Initialize pointers.
sample = 0;
fir = 0;
set_sampling_parameters(985248, SAMPLE_INTERPOLATE, 44100);
bus_value = 0;
bus_value_ttl = 0;
input(0);
}
// ----------------------------------------------------------------------------
// Destructor.
// ----------------------------------------------------------------------------
SIDFP::~SIDFP()
{
delete[] sample;
delete[] fir;
}
// ----------------------------------------------------------------------------
// Set chip model.
// ----------------------------------------------------------------------------
void SIDFP::set_chip_model(chip_model model)
{
this->model = model;
for (int i = 0; i < 3; i++) {
voice[i].set_chip_model(model);
}
voice[0].wave.rebuild_wftable();
filter.set_chip_model(model);
}
// ----------------------------------------------------------------------------
// SID reset.
// ----------------------------------------------------------------------------
void SIDFP::reset()
{
for (int i = 0; i < 3; i++) {
voice[i].reset();
}
filter.reset();
extfilt.reset();
bus_value = 0;
bus_value_ttl = 0;
}
// ----------------------------------------------------------------------------
// Write 16-bit sample to audio input.
// NB! The caller is responsible for keeping the value within 16 bits.
// Note that to mix in an external audio signal, the signal should be
// resampled to 1MHz first to avoid sampling noise.
// ----------------------------------------------------------------------------
void SIDFP::input(int sample)
{
// Voice outputs are 20 bits. Scale up to match three voices in order
// to facilitate simulation of the MOS8580 "digi boost" hardware hack.
ext_in = static_cast<float>((sample << 4) * 3);
}
float SIDFP::output()
{
/* Oscillators go from 0 to 4095, envelope from 0 to 255, volume goes to 1
* and there are 3 voices. With strong resonance, it's still possible to
* exceed the max (Drum Fool, for instance). So extra 50 % is allocated.
*
* Output range is -32768 to 32767. */
const float range = 1 << 15;
return extfilt.output() / (2047.f * 255.f * 3.f * 2.0f / range);
}
// ----------------------------------------------------------------------------
// Read registers.
//
// Reading a write only register returns the last byte written to any SID
// register. The individual bits in this value start to fade down towards
// zero after a few cycles. All bits reach zero within approximately
// $2000 - $4000 cycles.
// It has been claimed that this fading happens in an orderly fashion, however
// sampling of write only registers reveals that this is not the case.
// NB! This is not correctly modeled.
// The actual use of write only registers has largely been made in the belief
// that all SID registers are readable. To support this belief the read
// would have to be done immediately after a write to the same register
// (remember that an intermediate write to another register would yield that
// value instead). With this in mind we return the last value written to
// any SID register for $2000 cycles without modeling the bit fading.
// ----------------------------------------------------------------------------
reg8 SIDFP::read(reg8 offset)
{
switch (offset) {
case 0x19:
return potx.readPOT();
case 0x1a:
return poty.readPOT();
case 0x1b:
return model == MOS6581FP
? voice[2].wave.readOSC6581(voice[0].wave)
: voice[2].wave.readOSC8580(voice[0].wave);
case 0x1c:
return voice[2].envelope.readENV();
default:
return bus_value;
}
}
// ----------------------------------------------------------------------------
// Write registers.
// ----------------------------------------------------------------------------
void SIDFP::write(reg8 offset, reg8 value)
{
bus_value = value;
bus_value_ttl = 34000;
switch (offset) {
case 0x00:
voice[0].wave.writeFREQ_LO(value);
break;
case 0x01:
voice[0].wave.writeFREQ_HI(value);
break;
case 0x02:
voice[0].wave.writePW_LO(value);
break;
case 0x03:
voice[0].wave.writePW_HI(value);
break;
case 0x04:
voice[0].writeCONTROL_REG(voice[1].wave, value);
break;
case 0x05:
voice[0].envelope.writeATTACK_DECAY(value);
break;
case 0x06:
voice[0].envelope.writeSUSTAIN_RELEASE(value);
break;
case 0x07:
voice[1].wave.writeFREQ_LO(value);
break;
case 0x08:
voice[1].wave.writeFREQ_HI(value);
break;
case 0x09:
voice[1].wave.writePW_LO(value);
break;
case 0x0a:
voice[1].wave.writePW_HI(value);
break;
case 0x0b:
voice[1].writeCONTROL_REG(voice[2].wave, value);
break;
case 0x0c:
voice[1].envelope.writeATTACK_DECAY(value);
break;
case 0x0d:
voice[1].envelope.writeSUSTAIN_RELEASE(value);
break;
case 0x0e:
voice[2].wave.writeFREQ_LO(value);
break;
case 0x0f:
voice[2].wave.writeFREQ_HI(value);
break;
case 0x10:
voice[2].wave.writePW_LO(value);
break;
case 0x11:
voice[2].wave.writePW_HI(value);
break;
case 0x12:
voice[2].writeCONTROL_REG(voice[0].wave, value);
break;
case 0x13:
voice[2].envelope.writeATTACK_DECAY(value);
break;
case 0x14:
voice[2].envelope.writeSUSTAIN_RELEASE(value);
break;
case 0x15:
filter.writeFC_LO(value);
break;
case 0x16:
filter.writeFC_HI(value);
break;
case 0x17:
filter.writeRES_FILT(value);
break;
case 0x18:
filter.writeMODE_VOL(value);
break;
default:
break;
}
}
// ----------------------------------------------------------------------------
// Constructor.
// ----------------------------------------------------------------------------
SIDFP::State::State()
{
int i;
for (i = 0; i < 0x20; i++) {
sid_register[i] = 0;
}
bus_value = 0;
bus_value_ttl = 0;
for (i = 0; i < 3; i++) {
accumulator[i] = 0;
shift_register[i] = 0x7ffff8;
rate_counter[i] = 0;
rate_counter_period[i] = 9;
exponential_counter[i] = 0;
exponential_counter_period[i] = 1;
envelope_counter[i] = 0;
envelope_state[i] = EnvelopeGeneratorFP::RELEASE;
hold_zero[i] = true;
}
}
// ----------------------------------------------------------------------------
// Read state.
// ----------------------------------------------------------------------------
SIDFP::State SIDFP::read_state()
{
State state;
int i, j;
for (i = 0, j = 0; i < 3; i++, j += 7) {
WaveformGeneratorFP& wave = voice[i].wave;
EnvelopeGeneratorFP& envelope = voice[i].envelope;
state.sid_register[j + 0] = wave.freq & 0xff;
state.sid_register[j + 1] = wave.freq >> 8;
state.sid_register[j + 2] = wave.pw & 0xff;
state.sid_register[j + 3] = wave.pw >> 8;
state.sid_register[j + 4] =
(wave.waveform << 4)
| (wave.test ? 0x08 : 0)
| (wave.ring ? 0x04 : 0)
| (wave.sync ? 0x02 : 0)
| (envelope.gate ? 0x01 : 0);
state.sid_register[j + 5] = (envelope.attack << 4) | envelope.decay;
state.sid_register[j + 6] = (envelope.sustain << 4) | envelope.release;
}
state.sid_register[j++] = filter.fc & 0x007;
state.sid_register[j++] = filter.fc >> 3;
state.sid_register[j++] = (filter.res << 4) | filter.filt;
state.sid_register[j++] =
(filter.voice3off ? 0x80 : 0)
| (filter.hp_bp_lp << 4)
| filter.vol;
// These registers are superfluous, but included for completeness.
for (; j < 0x1d; j++) {
state.sid_register[j] = read(j);
}
for (; j < 0x20; j++) {
state.sid_register[j] = 0;
}
state.bus_value = bus_value;
state.bus_value_ttl = bus_value_ttl;
return state;
}
// ----------------------------------------------------------------------------
// Write state.
// ----------------------------------------------------------------------------
void SIDFP::write_state(const State& state)
{
reset();
int i;
for (i = 0; i <= 0x18; i++) {
write(i, state.sid_register[i]);
}
bus_value = state.bus_value;
bus_value_ttl = state.bus_value_ttl;
}
// ----------------------------------------------------------------------------
// Enable filter.
// ----------------------------------------------------------------------------
void SIDFP::enable_filter(bool enable)
{
filter.enable_filter(enable);
}
// ----------------------------------------------------------------------------
// I0() computes the 0th order modified Bessel function of the first kind.
// This function is originally from resample-1.5/filterkit.c by J. O. Smith.
// ----------------------------------------------------------------------------
double SIDFP::I0(double x)
{
// Max error acceptable in I0 could be 1e-6, which gives that 96 dB already.
// I'm overspecify these errors to get a beautiful FFT dump of the FIR.
const double I0e = 1e-10;
double sum, u, halfx, temp;
int n;
sum = u = n = 1;
halfx = x/2.0;
do {
temp = halfx/n++;
u *= temp*temp;
sum += u;
} while (u >= I0e*sum);
return sum;
}
// ----------------------------------------------------------------------------
// Setting of SID sampling parameters.
//
// Use a clock freqency of 985248Hz for PAL C64, 1022730Hz for NTSC C64.
// The default end of passband frequency is pass_freq = 0.9*sample_freq/2
// for sample frequencies up to ~ 44.1kHz, and 20kHz for higher sample
// frequencies.
//
// For resampling, the ratio between the clock frequency and the sample
// frequency is limited as follows:
// 125*clock_freq/sample_freq < 16384
// E.g. provided a clock frequency of ~ 1MHz, the sample frequency can not
// be set lower than ~ 8kHz. A lower sample frequency would make the
// resampling code overfill its 16k sample ring buffer.
//
// The end of passband frequency is also limited:
// pass_freq <= 0.9*sample_freq/2
// E.g. for a 44.1kHz sampling rate the end of passband frequency is limited
// to slightly below 20kHz. This constraint ensures that the FIR table is
// not overfilled.
// ----------------------------------------------------------------------------
bool SIDFP::set_sampling_parameters(float clock_freq, sampling_method method,
float sample_freq, float pass_freq)
{
filter.set_clock_frequency(clock_freq);
extfilt.set_clock_frequency(clock_freq);
cycles_per_sample = clock_freq/sample_freq;
sample_offset = 0;
sample_prev = 0;
// FIR initialization is only necessary for resampling.
if (method != SAMPLE_RESAMPLE_INTERPOLATE)
{
sampling = method;
delete[] sample;
delete[] fir;
sample = 0;
fir = 0;
return true;
}
const int bits = 16;
if (pass_freq > 20000)
pass_freq = 20000;
if (2*pass_freq/sample_freq > 0.9)
pass_freq = 0.9f*sample_freq/2;
// 16 bits -> -96dB stopband attenuation.
const double A = -20*log10(1.0/(1 << bits));
// A fraction of the bandwidth is allocated to the transition band, which we double
// because we design the filter to transition halfway at nyquist.
double dw = (1 - 2*pass_freq / sample_freq) * M_PI * 2;
// For calculation of beta and N see the reference for the kaiserord
// function in the MATLAB Signal Processing Toolbox:
// http://www.mathworks.com/access/helpdesk/help/toolbox/signal/kaiserord.html
const double beta = 0.1102*(A - 8.7);
const double I0beta = I0(beta);
// Since we clock the filter at half the rate, we need to design the FIR
// with the reduced rate in mind.
double f_samples_per_cycle = sample_freq/(clock_freq);
double f_cycles_per_sample = (clock_freq)/sample_freq;
{
/* Filter order according to Kaiser's paper. */
int N = (int) ((A - 7.95)/(2.285 * dw) + 0.5);
N += N & 1;
// The filter length is equal to the filter order + 1.
// The filter length must be an odd number (sinc is symmetric about x = 0).
fir_N = int(N*f_cycles_per_sample) + 1;
fir_N |= 1;
// Check whether the sample ring buffer would overfill.
if (fir_N > RINGSIZE - 1)
return false;
/* Error is bound by 1.234 / L^2 */
fir_RES = (int) (sqrt(1.234 * (1 << bits)) / f_cycles_per_sample + 0.5);
}
sampling = method;
// Allocate memory for FIR tables.
delete[] fir;
fir = new float[fir_N*fir_RES];
// The cutoff frequency is midway through the transition band, in effect the same as nyquist.
double wc = M_PI;
// Calculate fir_RES FIR tables for linear interpolation.
for (int i = 0; i < fir_RES; i++) {
double j_offset = double(i)/fir_RES;
// Calculate FIR table. This is the sinc function, weighted by the
// Kaiser window.
for (int j = 0; j < fir_N; j ++) {
double jx = j - fir_N/2. - j_offset;
double wt = wc*jx/f_cycles_per_sample;
double temp = jx/(fir_N/2);
double Kaiser =
fabs(temp) <= 1 ? I0(beta*sqrt(1 - temp*temp))/I0beta : 0;
double sincwt =
fabs(wt) >= 1e-8 ? sin(wt)/wt : 1;
fir[i * fir_N + j] = (float) (f_samples_per_cycle*wc/M_PI*sincwt*Kaiser);
}
}
// Allocate sample buffer.
if (!sample) {
sample = new float[RINGSIZE*2];
}
// Clear sample buffer.
for (int j = 0; j < RINGSIZE*2; j++) {
sample[j] = 0;
}
sample_index = 0;
return true;
}
void SIDFP::age_bus_value(cycle_count n) {
if (bus_value_ttl != 0) {
bus_value_ttl -= n;
if (bus_value_ttl <= 0) {
bus_value = 0;
bus_value_ttl = 0;
}
}
}
// ----------------------------------------------------------------------------
// SID clocking - 1 cycle.
// ----------------------------------------------------------------------------
void SIDFP::clock()
{
int i;
// Clock waveform and envelope generators
for (i = 0; i < 3; i++) {
voice[i].envelope.clock();
voice[i].wave.clock();
}
// Emulate SYNC bit
voice[0].wave.synchronize(voice[1].wave, voice[2].wave);
voice[1].wave.synchronize(voice[2].wave, voice[0].wave);
voice[2].wave.synchronize(voice[0].wave, voice[1].wave);
extfilt.clock(filter.clock(
voice[0].output(voice[2].wave),
voice[1].output(voice[0].wave),
voice[2].output(voice[1].wave),
ext_in
));
}
// ----------------------------------------------------------------------------
// SID clocking with audio sampling.
// Fixpoint arithmetics is used.
//
// The example below shows how to clock the SID a specified amount of cycles
// while producing audio output:
//
// while (delta_t) {
// bufindex += sid.clock(delta_t, buf + bufindex, buflength - bufindex);
// write(dsp, buf, bufindex*2);
// bufindex = 0;
// }
//
// ----------------------------------------------------------------------------
int SIDFP::clock(cycle_count& delta_t, short* buf, int n, int interleave)
{
/* XXX I assume n is generally large enough for delta_t here... */
age_bus_value(delta_t);
int res;
switch (sampling) {
default:
case SAMPLE_INTERPOLATE:
res = clock_interpolate(delta_t, buf, n, interleave);
break;
case SAMPLE_RESAMPLE_INTERPOLATE:
res = clock_resample_interpolate(delta_t, buf, n, interleave);
break;
}
filter.nuke_denormals();
extfilt.nuke_denormals();
return res;
}
// ----------------------------------------------------------------------------
// SID clocking with audio sampling - cycle based with linear sample
// interpolation.
//
// Here the chip is clocked every cycle. This yields higher quality
// sound since the samples are linearly interpolated, and since the
// external filter attenuates frequencies above 16kHz, thus reducing
// sampling noise.
// ----------------------------------------------------------------------------
RESID_INLINE
int SIDFP::clock_interpolate(cycle_count& delta_t, short* buf, int n,
int interleave)
{
int s = 0;
int i;
for (;;) {
float next_sample_offset = sample_offset + cycles_per_sample;
int delta_t_sample = static_cast<int>(next_sample_offset);
if (delta_t_sample > delta_t) {
break;
}
if (s >= n) {
return s;
}
for (i = 0; i < delta_t_sample - 1; i++) {
clock();
}
if (i < delta_t_sample) {
sample_prev = output();
clock();
}
delta_t -= delta_t_sample;
sample_offset = next_sample_offset - delta_t_sample;
float sample_now = output();
int v = static_cast<int>(sample_prev + (sample_offset * (sample_now - sample_prev)));
// Saturated arithmetics to guard against 16 bit sample overflow.
const int half = 1 << 15;
if (v >= half) {
v = half - 1;
}
else if (v < -half) {
v = -half;
}
buf[s++*interleave] = v;
sample_prev = sample_now;
}
for (i = 0; i < delta_t - 1; i++) {
clock();
}
if (i < delta_t) {
sample_prev = output();
clock();
}
sample_offset -= delta_t;
delta_t = 0;
return s;
}
// ----------------------------------------------------------------------------
// SID clocking with audio sampling - cycle based with audio resampling.
//
// This is the theoretically correct (and computationally intensive) audio
// sample generation. The samples are generated by resampling to the specified
// sampling frequency. The work rate is inversely proportional to the
// percentage of the bandwidth allocated to the filter transition band.
//
// This implementation is based on the paper "A Flexible Sampling-Rate
// Conversion Method", by J. O. Smith and P. Gosset, or rather on the
// expanded tutorial on the "Digital Audio Resampling Home Page":
// http://www-ccrma.stanford.edu/~jos/resample/
//
// By building shifted FIR tables with samples according to the
// sampling frequency, this implementation dramatically reduces the
// computational effort in the filter convolutions, without any loss
// of accuracy. The filter convolutions are also vectorizable on
// current hardware.
//
// Further possible optimizations are:
// * An equiripple filter design could yield a lower filter order, see
// http://www.mwrf.com/Articles/ArticleID/7229/7229.html
// * The Convolution Theorem could be used to bring the complexity of
// convolution down from O(n*n) to O(n*log(n)) using the Fast Fourier
// Transform, see http://en.wikipedia.org/wiki/Convolution_theorem
// * Simply resampling in two steps can also yield computational
// savings, since the transition band will be wider in the first step
// and the required filter order is thus lower in this step.
// Laurent Ganier has found the optimal intermediate sampling frequency
// to be (via derivation of sum of two steps):
// 2 * pass_freq + sqrt [ 2 * pass_freq * orig_sample_freq
// * (dest_sample_freq - 2 * pass_freq) / dest_sample_freq ]
//
// NB! the result of right shifting negative numbers is really
// implementation dependent in the C++ standard.
// ----------------------------------------------------------------------------
RESID_INLINE
int SIDFP::clock_resample_interpolate(cycle_count& delta_t, short* buf, int n,
int interleave)
{
int s = 0;
for (;;) {
float next_sample_offset = sample_offset + cycles_per_sample;
/* full clocks left to next sample */
int delta_t_sample = static_cast<int>(next_sample_offset);
if (delta_t_sample > delta_t || s >= n)
break;
/* clock forward delta_t_sample samples */
for (int i = 0; i < delta_t_sample; i++) {
clock();
sample[sample_index] = sample[sample_index + RINGSIZE] = output();
++ sample_index;
sample_index &= RINGSIZE - 1;
}
delta_t -= delta_t_sample;
/* Phase of the sample in terms of clock, [0 .. 1[. */
sample_offset = next_sample_offset - static_cast<float>(delta_t_sample);
/* find the first of the nearest fir tables close to the phase */
float fir_offset_rmd = sample_offset * fir_RES;
int fir_offset = static_cast<int>(fir_offset_rmd);
/* [0 .. 1[ */
fir_offset_rmd -= static_cast<float>(fir_offset);
/* find fir_N most recent samples, plus one extra in case the FIR wraps. */
float* sample_start = sample + sample_index - fir_N + RINGSIZE - 1;
float v1 =
#if (RESID_USE_SSE==1)
can_use_sse ? convolve_sse(sample_start, fir + fir_offset*fir_N, fir_N) :
#endif
convolve(sample_start, fir + fir_offset*fir_N, fir_N);
// Use next FIR table, wrap around to first FIR table using
// the next sample.
if (++ fir_offset == fir_RES) {
fir_offset = 0;
++ sample_start;
}
float v2 =
#if (RESID_USE_SSE==1)
can_use_sse ? convolve_sse(sample_start, fir + fir_offset*fir_N, fir_N) :
#endif
convolve(sample_start, fir + fir_offset*fir_N, fir_N);
// Linear interpolation between the sinc tables yields good approximation
// for the exact value.
int v = static_cast<int>(v1 + fir_offset_rmd * (v2 - v1));
// Saturated arithmetics to guard against 16 bit sample overflow.
const int half = 1 << 15;
if (v >= half) {
v = half - 1;
}
else if (v < -half) {
v = -half;
}
buf[s ++ * interleave] = v;
}
/* clock forward delta_t samples */
for (int i = 0; i < delta_t; i++) {
clock();
sample[sample_index] = sample[sample_index + RINGSIZE] = output();
++ sample_index;
sample_index &= RINGSIZE - 1;
}
sample_offset -= static_cast<float>(delta_t);
delta_t = 0;
return s;
}
|
9cf44931aef8820ae0c9eeeff206cefe9e3d430d | 6419d4c3dad0bea706191b8e75cdb1a8f6ceb201 | /codeforces/cf #401 B.cpp | f13b199f1a7aaa9ac1a85258c909b3c880116b47 | [] | no_license | jsphLim/algorithms | a4a836566a4dd06948681604cfdb1c855173f9d2 | a00620128346cefca1f9b6effec9cdc5b9b96519 | refs/heads/master | 2021-04-06T10:25:08.461580 | 2018-12-11T17:01:32 | 2018-12-11T17:01:32 | 124,760,752 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 365 | cpp | cf #401 B.cpp | #include<bits/stdc++.h>
using namespace std;
const int N = 1e3 + 10;
char a[N], b[N];
int main ()
{
int n, i;
scanf("%d %s %s", &n, a, b);
sort(a, a+n); sort(b, b+n);
i = 0;
for(int j = 0; j < n; j++){
if(b[j] >= a[i])
i++;
}
printf("%d\n", n-i);
i = 0;
for(int j = 0; j < n; j++){
if(b[j] > a[i])
i++;
}
printf("%d\n", i);
return 0;
}
|
d412716d13b637d9e39ffac4493151a6cfa452a5 | 9d05b7de75680d6f79edc7042da9fdd92817064c | /src/FormsLoader.cpp | a2bb24c80d177e0c0d49f81433e0363036f33358 | [] | no_license | OrCo27/InexactSearch | e2fa4c0833d6a7c378528065cba9cb398a8db7bd | 31567b225266d606f56da112cc401eeaf1970db7 | refs/heads/master | 2022-06-08T11:03:50.786444 | 2020-05-05T10:48:21 | 2020-05-05T10:48:21 | 258,728,719 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,011 | cpp | FormsLoader.cpp | #include "FormsLoader.h"
void FormsLoader::AddFormManually(const string& form)
{
this->form_data.push_back(form);
}
void FormsLoader::LoadFromFile(const string& file)
{
vector<string> file_lines = Utils::GetFileLines(file);
string final_form, form_extracted;
unsigned int i = 0;
for (string& line : file_lines)
{
// check if it fits to template of form file
if (line[0] == '>')
{
vector<string> line_tokens = Utils::SplitLineByDelimeter(line, '\t');
// extract the form with spaces
form_extracted = line_tokens[1];
// remove all spaces in form
form_extracted.erase(remove(form_extracted.begin(), form_extracted.end(), ' '), form_extracted.end());
// get the form size
unsigned int form_size = form_extracted[ARRAY_FORM_SIZE] - '0';
// cut only relevant part of form
final_form = form_extracted.substr(0, form_size);
this->AddFormManually(final_form);
i++;
}
}
}
vector<string>& FormsLoader::GetFormData()
{
return this->form_data;
} |
a22053207b4e0d911187a957959022a5a4a877ed | 8878071b2e73220de8d5407c16af657902e4aae1 | /GitTest_01/GitTest_01/main.cpp | 4a02f24fc704543e3cbe2dccd457885a10d5e25a | [] | no_license | liujun1994/ZTSS- | 0462f64015a602ac29180b53d1089d336bff3346 | 9fe28636bb1a513a59907e4b18eb164dede0fd72 | refs/heads/master | 2021-07-17T21:54:44.969781 | 2017-10-25T07:09:28 | 2017-10-25T07:09:28 | 108,227,746 | 0 | 0 | null | 2017-10-25T07:09:53 | 2017-10-25T06:15:10 | C++ | UTF-8 | C++ | false | false | 392 | cpp | main.cpp | //
// main.cpp
// GitTest_01
//
// Created by Admin on 17/10/25.
// Copyright © 2017年 Admin. All rights reserved.
//
#include <iostream>
using namespace std;
int main(int argc, const char * argv[]) {
// insert code here...
cout << "Hello, World!\n";
cout<<"这是分支一的皂搓"<<endl;
//删除分支1
//合拼分支1
//啦啦啦吕老师
return 0;
}
|
ec7469e62accf79979577abe28b94783d62e9aec | c25fa228e19f6ef4d63dc11d59baaae4981101c0 | /src_smartcontract_db/trx/session/ddl_alter/UndoAlterAddIndexLog.h | 92efa8bbe8adee4dc325c6384efe839d2fec05a7 | [
"MIT"
] | permissive | alinous-core/codablecash | b994e710144af3f6b69bda2f3d1dff080b2fd2b0 | 030fa9ee2e79ae2cade33aa80e80fb532c5b66ee | refs/heads/master | 2023-08-31T04:30:14.333123 | 2023-08-12T11:33:06 | 2023-08-12T11:33:06 | 129,185,961 | 11 | 4 | MIT | 2023-08-13T14:10:25 | 2018-04-12T03:14:00 | C++ | UTF-8 | C++ | false | false | 964 | h | UndoAlterAddIndexLog.h | /*
* UndoAlterAddIndexLog.h
*
* Created on: 2023/07/24
* Author: iizuka
*/
#ifndef TRX_SESSION_DDL_ALTER_UNDOALTERADDINDEXLOG_H_
#define TRX_SESSION_DDL_ALTER_UNDOALTERADDINDEXLOG_H_
#include "trx/session/base/AbstractUndoLog.h"
namespace codablecash {
class UndoAlterAddIndexLog : public AbstractUndoLog {
public:
UndoAlterAddIndexLog(const UndoAlterAddIndexLog& inst);
UndoAlterAddIndexLog();
virtual ~UndoAlterAddIndexLog();
virtual int binarySize() const;
virtual void toBinary(ByteBuffer* out) const;
virtual void fromBinary(ByteBuffer* in);
virtual IBlockObject* copyData() const noexcept;
virtual void execute(CdbTransactionManager* trxManager, UndoLogPartsRepo* partsRepo, UndoLogsIdkey* key);
void setNewIndexOid(uint64_t oid) noexcept;
void setTableOid(uint64_t oid) noexcept;
private:
uint64_t tableOid;
uint64_t newIndexOid;
};
} /* namespace codablecash */
#endif /* TRX_SESSION_DDL_ALTER_UNDOALTERADDINDEXLOG_H_ */
|
48313da32f8e9ef06d892cb7160708e4a9f4bf81 | bcdf3476ef8ffbb9aa41efcdd3a83afcb85f9951 | /Programming Task 6/ps6.cpp | a79c81375bc9cca904e9ebd069b17cbfba42933d | [] | no_license | alextzik/ProgrammingTechniques-2017 | 6edc31521568de54eff6b37df24c427196e5a6cc | 462e3a731bad3c07bdaf20d2ebe4633f1f48ee0e | refs/heads/master | 2020-04-27T18:53:49.345474 | 2019-03-08T19:06:28 | 2019-03-08T19:06:28 | 174,592,110 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,881 | cpp | ps6.cpp | #include <sys/ioctl.h>
#include <iostream>
#include <stdlib.h>
#include <vector>
#include <utility>
#include "ps6.h"
using std::vector;
using std::pair;
// ############################################################
// YOUR IMPLEMENTATION //
// ############################################################
namespace tui {
class color {
private:
byte code=0;
color(byte code) {
this->code = code;
};
public:
byte get_code() const {
return code;
}
static const color black;
static const color red;
static const color green;
static const color yellow;
static const color blue;
static const color magenta;
static const color white;
static const color system_default;
};
const color color::black(0);
const color color::red(1);
const color color::green(2);
const color color::yellow(3);
const color color::blue(4);
const color color::magenta(5);
const color color::white(7);
const color color::system_default(9);
class pen {
private:
char _c;
color _foreground;
color _background;
bool _bright;
public:
pen(color color_code, color bg_color_code, char ch, bool bright)
:_foreground(color_code), _background(bg_color_code), _c(ch), _bright(bright) {
}
point pen_to_point() const {
point p;
p._color_code=_foreground.get_code();
p._bright=_bright;
p._ch=_c;
p._bg_color_code=_background.get_code();
return p;
}
};
class shape {
private:
public:
virtual void draw(screen &scr, const pen &p) const=0;
virtual ~shape(){};
};
// all correct
class rectangle : public shape {
private:
int _width;
int _length;
int _x0;
int _y0;
int _x1;
int _y1;
public:
rectangle(int x0, int y0, int width, int length)
:_x0(x0),_y0(y0),_width(width),_length(length){
}
~rectangle(){};
int getwidth(){
return _width;
}
int getlength(){
return _length;
}
int get_x0(){
return _x0;
}
int get_y0(){
return _y0;
}
int get_x1(){
return _x1;
}
int get_y1(){
return _y1;
}
void draw(screen &scr, const pen &p) const{
scr.set_rect(_x0, _y0, _x0+_width, _y0+_length, p.pen_to_point());
}
};
class circle : public shape {
private:
int _x;
int _y;
int _rad;
public:
circle(int x, int y, int rad)
:_x(x),_y(y),_rad(rad)
{}
~circle(){};
int get_rad(){
return _rad;
}
int get_x(){
return _x;
}
int get_y(){
return _y;
}
void draw(screen &scr, const pen &p) const{
scr.set_circle(_x, _y, _rad, p.pen_to_point());
}
};
class canvas {
screen &_scr;
std::vector< std::pair<shape*, pen> > _v;
std::vector< std::pair<shape*, pen> >::iterator it;
public:
canvas(screen & _screen) : _scr(_screen) { }
void add(shape* s, pen p){
std::pair<shape*, pen> p1=std::make_pair(s, p);
_v.push_back(p1);
};
void clear(){
while (!_v.empty()) {
_v.pop_back();
}
_scr.clear();
}
void show(){
_scr.clear();
for (it = _v.begin(); it != _v.end(); it++){
std::pair<shape*, pen> c=*it;
shape* shape_pointer=c.first;
pen pen_ref=c.second;
(c.first)->draw(_scr, pen_ref);
}
_scr.render();
};
};
}
// ############################################################
// ! ! ! DON'T CHANGE ANYTHING BELOW ! ! !
// ############################################################
using namespace tui;
int main() {
int cols;
int rows;
cin >> cols >> rows;
screen scr(cols, rows);
canvas canv(scr);
// -- creating a few pens ------------------------------------------------
pen pen_magenta(color::magenta, color::system_default, '&', true);
pen pen_red(color::yellow, color::red, '@', true);
pen pen_green(color::white, color::green, '$', false);
pen pen_blue(color::blue, color::blue, '*', true);
pen pen_white(color::black, color::white, 'O', true);
// -- drawing shapes -----------------------------------------------------
rectangle rect1(0, 0, scr.ncols(), scr.nrows());
canv.add(&rect1, pen_magenta);
// keeping addresses of objects created using placement new (such objects
// need to be _explicitly_ destructed)
vector<shape*> trash;
// creating a list of pens, for convenience
vector<pen> pens;
pens.push_back(pen_red);
pens.push_back(pen_green);
pens.push_back(pen_blue);
pens.push_back(pen_white);
// filling the left part of window with nested rectangles
int width = (scr.ncols() - 2) / 2;
int height = scr.nrows() - 2;
for(int i = 1; i <= (scr.ncols() - 2) / 8; i++) {
shape* addr = (shape*)alloca(sizeof(rectangle));
trash.push_back(addr);
new (addr) rectangle(i, i, width, height);
canv.add(addr, pens[i % pens.size()]);
width -= 2;
height -= 2;
if(width <= 0 || height <= 0)
break;
}
// filling the right part of the window with nested circles
int x = 1 + 3 * (scr.ncols() - 2) / 4;
int y = (scr.nrows() - 2) / 2;
for(int rad = ((scr.ncols() - 2) >> 3) - 2; rad > 0; rad -= 2) {
shape* addr = (shape*)alloca(sizeof(circle));
trash.push_back(addr);
new (addr) circle(x, y, rad);
canv.add(addr, pens[(rad >> 1) % pens.size()]);
}
// -- updating screen -----------------------------------------------------
canv.show();
// -- manually destructing objects created using placement new ------------
for(int i = 0; i < (int)trash.size(); i++)
trash[i]->~shape();
// !notice these objects have been allocated on the stack, so
// there is no need to manually release the memory the objects
// have occupied (it is done automatically). But destructors are
// not called automatically when we use placement new.
return 0;
}
|
2935749c315ed5f254ccfb96cb24c69997a190c5 | dca7b2b06c9fc5e1e1274bbfca6ec8ab81e5ad12 | /Simulation/scheduler.cpp | 194f162f8717415e240b4a54b772be3b8411872c | [] | no_license | Vignesh-Sairaj/Operating-Systems | d7ef7e8e18de96edea95711f1b396bd8960896e6 | 19e90b98c26428b4ff3065f0a6e1fc355a0ec05d | refs/heads/master | 2020-07-26T07:10:50.452862 | 2016-12-01T11:53:24 | 2016-12-01T11:53:24 | 208,564,444 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,331 | cpp | scheduler.cpp | #include <iostream>
#include <fstream>
#include <string>
#include <exception>
#include <vector>
#include <stdexcept>
#include <algorithm>
#include <queue>
class Process {
public:
/*
aTime --- Arrival Time
bTime --- Burst Time
sTime --- Start Time
wTime --- Wait Time = fTime - aTime - bTime
fTime --- Finish Time
rTime --- Remaining Time
*/
int id;
int aTime;
int bTime;
int wTime;
int sTime;
int fTime;
int rTime;
};
bool cmpByArrTime_lt (Process p1, Process p2);
bool cmpByJobTime_gt (Process p1, Process p2);
bool cmpByRemTime_gt (Process p1, Process p2);
bool cmpByArrTime_lt (Process p1, Process p2) {
return p1.aTime < p2.aTime;
}
bool cmpByJobTime_gt (Process p1, Process p2) {
if (p1.bTime == p2.bTime) {
return p1.aTime > p2.aTime;
}
return p1.bTime > p2.bTime;
}
bool cmpByRemTime_gt (Process p1, Process p2) {
if (p1.rTime == p2.rTime) {
return p1.aTime > p2.aTime;
}
return p1.rTime > p2.rTime;
}
int main(int argc, char* argv[]) {
if(argc != 3) {
throw std::runtime_error("Incorrect number of arguments; expected 3.");
}
// First arg -- numProcesses
int numProc;
{ //To scope temp tightly
std::string temp (argv[1]);
numProc = std::stoi(temp);
}
std::cout << "Here\n";
std::ifstream inFile;
inFile.open(argv[2]);
/*
The input csv file fields:
Process_id, arrival_time, burst_time
*/
std::vector<Process> list;
std::vector<Process> fcfsList;
std::vector<Process> sjfList;
for (int i = 0; i < numProc; i++) {
char dlmtr;
Process temp;
inFile >> temp.id >> dlmtr >> temp.aTime >> dlmtr >> temp.bTime;
//inFile >> temp.id >> temp.aTime >> temp.bTime;
list.push_back(temp);
fcfsList.push_back(temp);
sjfList.push_back(temp);
}
inFile.close();
for (int i = 0; i < numProc; ++i) {
list[i].wTime = -1; list[i].sTime = -1; list[i].fTime = -1;
fcfsList[i].wTime = -1; fcfsList[i].sTime = -1; fcfsList[i].fTime = -1;
sjfList[i].wTime = -1; sjfList[i].sTime = -1; sjfList[i].fTime = -1;
list[i].rTime = list[i].bTime;
fcfsList[i].rTime = fcfsList[i].bTime;
sjfList[i].rTime = sjfList[i].bTime;
}
std::sort(list.begin(), list.end(), cmpByArrTime_lt);
//================================= <FCFS> ==================================//
{ // Tight scoping
std::sort(fcfsList.begin(), fcfsList.end(), cmpByArrTime_lt);
int currTime = 0;
for (int i = 0; i < numProc; ++i) {
if(currTime < fcfsList[i].aTime) { //More timeto wait for arrival
currTime = fcfsList[i].aTime;
fcfsList[i].sTime = fcfsList[i].aTime;
fcfsList[i].wTime = 0; //Started as immediately on arrival
}
else {
fcfsList[i].sTime = currTime;
fcfsList[i].wTime = currTime - fcfsList[i].aTime; //Waited after arrival to start
}
currTime += fcfsList[i].bTime;
fcfsList[i].fTime = currTime;
}
}
//================================= </FCFS> ===================================//
//---------------------------------------------------------------------------------//
//================================== <SJF> ====================================//
std::vector<Process> sjfDone;
{ //Tight Scope
std::sort(sjfList.begin(), sjfList.end(), cmpByArrTime_lt);
std::vector<Process> heap;
int currTime = 0;
int i = 0;
while ( (i < numProc) or not(heap.empty()) ) {
if(heap.empty() and currTime < sjfList[i].aTime) { //Wait and fast forward to when it arrives
currTime = sjfList[i].aTime;
}
while( (i < numProc) and (sjfList[i].aTime <= currTime) ) {
heap.push_back(sjfList[i]);
push_heap(heap.begin(), heap.end(), cmpByJobTime_gt);
++i;
}
pop_heap(heap.begin(), heap.end(), cmpByJobTime_gt);
Process current = heap.back();
heap.pop_back();
current.sTime = currTime;
current.wTime = current.sTime - current.aTime;
current.fTime = current.sTime + current.bTime;
currTime = current.fTime;
sjfDone.push_back(current);
}
}
//================================== </SJF> ====================================//
//---------------------------------------------------------------------------------//
//================================== <RRB> ====================================//
std::vector<Process> rrbList;
{ //Tignt scope
int timeQuant = 2;
std::queue<Process> queue;
int currTime = 0;
int i = 0;
std::cout << "\n\nExecuting Round Robin, timeQuant = " << timeQuant << std::endl;
while ( (i < numProc) or not(queue.empty()) ) {
if(queue.empty() and currTime < list[i].aTime) { //Wait and fast forward to when it arrives
currTime = list[i].aTime;
}
//Add all available proc
while( (i < numProc) and (list[i].aTime <= currTime) ) {
queue.push(list[i]);
++i;
}
Process current = queue.front();
queue.pop();
std::cout << "Starting/Resuming Process " << current.id << " currTime: " << currTime
<< " Remaining Time: " << current.rTime << std::endl;
//First time
if(current.sTime < 0) current.sTime = currTime;
if (current.rTime > timeQuant) {
current.rTime -= timeQuant;
currTime += timeQuant;
//Add all available
while( (i < numProc) and (list[i].aTime <= currTime) ) {
queue.push(list[i]);
++i;
}
queue.push(current);
}
else { //Finish process
currTime += current.rTime;
current.rTime = 0;
current.fTime = currTime;
current.wTime = current.fTime - current.aTime - current.bTime;
rrbList.push_back(current);
}
}
}
//================================== </RRB> ====================================//
//---------------------------------------------------------------------------------//
//================================== <SRT> ====================================//
std::vector<Process> srtList;
{ //Tight Scope
std::sort(list.begin(), list.end(), cmpByArrTime_lt);
std::vector<Process> heap;
int currTime = 0;
int i = 0;
while ( (i < numProc) or not(heap.empty()) ) {
if(heap.empty() and currTime < list[i].aTime) { //Wait and fast forward to when it arrives
currTime = list[i].aTime;
}
while( (i < numProc) and (list[i].aTime <= currTime) ) {
heap.push_back(list[i]);
push_heap(heap.begin(), heap.end(), cmpByRemTime_gt);
++i;
}
pop_heap(heap.begin(), heap.end(), cmpByRemTime_gt);
Process current = heap.back();
heap.pop_back();
//First time
if(current.sTime < 0) current.sTime = currTime;
//If another process is available before current ends
if (i < numProc and list[i].aTime < currTime + current.rTime) {
//subtract by time untill arrival; process run till arrival of next
current.rTime -= list[i].aTime - currTime;
currTime = list[i].aTime;
//Reinsert
heap.push_back(current);
push_heap(heap.begin(), heap.end(), cmpByRemTime_gt);
}
else {
currTime += current.rTime;
current.rTime = 0;
current.fTime = currTime;
current.wTime = current.fTime - current.aTime - current.bTime;
srtList.push_back(current);
}
}
}
//================================== </SRT> ====================================//
std::ofstream fcfsOut;
fcfsOut.open("fcfs.csv");
for (int i = 0; i < numProc; i++) {
fcfsOut << fcfsList[i].id << ',' << fcfsList[i].aTime << ',' << fcfsList[i].bTime
<< ',' << fcfsList[i].wTime << ',' << fcfsList[i].sTime << ',' << fcfsList[i].fTime << std::endl;
}
fcfsOut.close();
std::ofstream sjfOut;
sjfOut.open("sjf.csv");
for (int i = 0; i < numProc; i++) {
sjfOut << sjfDone[i].id << ',' << sjfDone[i].aTime << ',' << sjfDone[i].bTime
<< ',' << sjfDone[i].wTime << ',' << sjfDone[i].sTime << ',' << sjfDone[i].fTime << std::endl;
}
sjfOut.close();
std::ofstream rrbOut;
rrbOut.open("rrb.csv");
for (int i = 0; i < numProc; i++) {
rrbOut << rrbList[i].id << ',' << rrbList[i].aTime << ',' << rrbList[i].bTime
<< ',' << rrbList[i].wTime << ',' << rrbList[i].sTime << ',' << rrbList[i].fTime << std::endl;
}
rrbOut.close();
std::ofstream srtOut;
srtOut.open("srt.csv");
for (int i = 0; i < numProc; i++) {
srtOut << srtList[i].id << ',' << srtList[i].aTime << ',' << srtList[i].bTime
<< ',' << srtList[i].wTime << ',' << srtList[i].sTime << ',' << srtList[i].fTime << std::endl;
}
srtOut.close();
return 0;
} |
8ed02fa7b0939211a041174893af666237fcd142 | 1d928c3f90d4a0a9a3919a804597aa0a4aab19a3 | /c++/ClickHouse/2015/4/BlockIO.h | 6c3c83a63bdb5227ffab69917a1b0d13b914a198 | [] | no_license | rosoareslv/SED99 | d8b2ff5811e7f0ffc59be066a5a0349a92cbb845 | a062c118f12b93172e31e8ca115ce3f871b64461 | refs/heads/main | 2023-02-22T21:59:02.703005 | 2021-01-28T19:40:51 | 2021-01-28T19:40:51 | 306,497,459 | 1 | 1 | null | 2020-11-24T20:56:18 | 2020-10-23T01:18:07 | null | UTF-8 | C++ | false | false | 1,232 | h | BlockIO.h | #pragma once
#include <DB/DataStreams/IBlockInputStream.h>
#include <DB/DataStreams/IBlockOutputStream.h>
#include <DB/Interpreters/ProcessList.h>
namespace DB
{
struct BlockIO
{
/** process_list_entry должен уничтожаться позже, чем in и out,
* так как внутри in и out есть ссылка на объект внутри process_list_entry
* (MemoryTracker * current_memory_tracker),
* которая может использоваться до уничтожения in и out.
*/
ProcessList::EntryPtr process_list_entry;
BlockInputStreamPtr in;
BlockOutputStreamPtr out;
Block in_sample; /// Пример блока, который будет прочитан из in.
Block out_sample; /// Пример блока, которого нужно писать в out.
BlockIO & operator= (const BlockIO & rhs)
{
/// Обеспечиваем правильный порядок уничтожения.
out = nullptr;
in = nullptr;
process_list_entry = nullptr;
process_list_entry = rhs.process_list_entry;
in = rhs.in;
out = rhs.out;
in_sample = rhs.in_sample;
out_sample = rhs.out_sample;
return *this;
}
};
}
|
ca2eebed16ebde8cb146342053e3f2e8846c1f78 | 3c5c616b0337056375c11f6a01fc6b8eb58bb6d7 | /tests/threading.cpp | 538f7163ee117ea6204648fcdb774b2b2cbc346b | [
"LicenseRef-scancode-stlport-4.5"
] | permissive | tm9k1/comet | a146158bf290d119b1d57963cb12156594aab07d | 3f4418cb860105404011a0ad1709d703de2e467e | refs/heads/master | 2022-02-01T06:32:30.932166 | 2019-06-19T16:50:45 | 2019-06-19T16:50:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 936 | cpp | threading.cpp | #include <boost/test/unit_test.hpp>
#define COMET_ASSERT_THROWS_ALWAYS
#include <comet/lw_lock.h> // lw_lock, auto_reader_lock, auto_writer_lock
#include <comet/threading.h> // thread
using comet::auto_reader_lock;
using comet::auto_writer_lock;
using comet::lw_lock;
using comet::thread;
BOOST_AUTO_TEST_SUITE( threading_tests )
BOOST_AUTO_TEST_CASE( lock )
{
struct MyThread : public thread
{
const lw_lock& lock_;
MyThread(const lw_lock& lock)
: lock_(lock)
{}
DWORD thread_main()
{
auto_reader_lock arl(lock_);
Sleep(100);
return 0;
}
};
lw_lock lock;
MyThread t(lock);
t.start();
{
auto_writer_lock awl(lock);
Sleep(100);
}
if (WaitForSingleObject(t.handle(), 5000) != WAIT_OBJECT_0)
throw std::runtime_error("class thread is broken");
}
BOOST_AUTO_TEST_SUITE_END() |
f6addb726b5fa06cb6b79f7122b34198e049e9ed | f83c4f606d3ed04c0a4be916bd989c9fddac41eb | /TornadoEngine/Source/Developer/ShareDev/Destructor/DestructorGameObject.cpp | af7cc9971e27cd0ee71a9ff9b3e41a87436dfe88 | [] | no_license | xubingyue/MMO-Framework | ee10acb2a0bec1b766079762c4cf7516cd338954 | 620a337b7597dcff81ba4448d610f4e449bb369f | refs/heads/master | 2021-01-13T12:01:40.189028 | 2016-12-30T19:26:21 | 2016-12-30T19:26:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,210 | cpp | DestructorGameObject.cpp | /*
Author: Gudakov Ramil Sergeevich a.k.a. Gauss
Гудаков Рамиль Сергеевич
Contacts: [ramil2085@mail.ru, ramil2085@gmail.com]
See for more information License.h.
*/
#include "DestructorGameObject.h"
TDestructorGameObject::TDestructorGameObject()
{
}
//-------------------------------------------------------------------
TDestructorGameObject::~TDestructorGameObject()
{
}
//-------------------------------------------------------------------
void TDestructorGameObject::Init( /*TPreDestructor::TVectorTypeTask& vec*/ )
{
}
//-------------------------------------------------------------------
bool TDestructorGameObject::DesctructObject( std::list<TGameObject*>& pListObject )
{
return false;
}
//-------------------------------------------------------------------
TDestructorGameObject::State TDestructorGameObject::GetState()
{
return mState;
}
//-------------------------------------------------------------------
void TDestructorGameObject::DestructFromThread_Ogre()
{
}
//-------------------------------------------------------------------
void TDestructorGameObject::DestructFromThread_Bullet()
{
}
//-------------------------------------------------------------------
|
5b4acd9b733fcf54dd146148d869f08f647579d2 | 5d3404096286830fab472bdf9f30842f0f13a6b6 | /Contest/CodeForce/170731/D/main.cpp | b2a76dc48fbdb3f4e4c31afef3b350a26a2f85dc | [] | no_license | YeongjinOh/Algorithm-practice | 0d4b2ed00e6eebc46667435c3fdc47f8fb1ae886 | 871428eed1158ef85ff31930588aaeb3d69661d2 | refs/heads/master | 2021-01-23T13:42:54.361325 | 2018-03-17T12:47:38 | 2018-03-17T12:47:38 | 54,641,868 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,740 | cpp | main.cpp | #include <iostream>
#include <cstring>
#include <cmath>
#include <ctime>
#include <queue>
#include <set>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long ll;
typedef double db;
typedef pair<int,int> pii;
typedef vector<int> vi;
#define de(x) cout << #x << "=" << x << endl
#define rep(i,a,b) for(int i=a;i<(b);++i)
#define all(x) (x).begin(),(x).end()
#define sz(x) (int)(x).size()
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define INF 5e18
#define LEN 5005
string str;
bool p[LEN][LEN];
int kp[LEN][LEN];
int main() {
cin >> str;
int n = str.size();
memset(p, 0, sizeof(p));
memset(kp, 0, sizeof(kp));
vector<int> cnt(n, 0);
// build pal
for (int i = 0; i < n; ++i) {
p[i][i] = true;
kp[i][i] = 1;
cnt[0]++;
}
for (int i = 0; i < n-1; ++i)
if (str[i] == str[i+1]) {
p[i][i+1] = true;
kp[i][i+1] = 1;
cnt[0]++;
}
for (int len=3; len<=n; len++) {
for (int i=0; i+len-1<n; i++) {
int j = i+len-1;
if (p[i+1][j-1] && str[i] == str[j]) {
p[i][j] = true;
kp[i][j] = 1;
cnt[0]++;
}
}
}
// build k-pal
for (int len=1; len<=n; ++len) {
for (int i=0; i+len-1<n; ++i) {
int j = i+len-1;
if (!p[i][j]) continue;
int t = len/2;
int k = min(kp[i][i+t-1], kp[j-t+1][j])+1;
for (int s=1; s<k; s++)
cnt[s]++;
kp[i][j] = k;
}
}
// print result
for (int i=0; i<n; i++)
printf("%d ", cnt[i]);
cout<<endl;
return 0;
}
|
c12055c4c1c8bc8c40649b78dbec0e2bf6a7a713 | 0d0cd7b2bf59c532269395c27dc312840cf6d541 | /src/Draw/Draw.cpp | ee2bdc5b2737167e74e9e698c84267325c94532b | [] | no_license | sshklifov/hardestgame | 18d868c4478b021e055d72898c573138c56e51f0 | ae2d271f2ce7b0bc2c9bc413233fab456ae916ce | refs/heads/master | 2020-09-27T18:29:54.707545 | 2019-12-22T12:33:22 | 2019-12-22T12:33:22 | 226,579,590 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,878 | cpp | Draw.cpp | #include <HardestGame.h>
#include "Draw.h"
#include "Movement.h" // Clamp
#include <cassert>
#include <cmath>
static float SmoothStep(float edge0, float edge1, float x)
{
assert (edge1 > edge0 && fabs(edge1-edge0) > fabs(edge1)*1e-5);
float t = Clamp((x-edge0) / (edge1-edge0), 0.f, 1.f);
return t * t * (3.f - 2.f*t);
}
const Color pink{1.f, 0.75f, 0.75f};
static bool IsPink(const Color& c)
{
return c.r==pink.r && c.g==pink.g && c.b==pink.b;
}
static void Clear(Color* fb)
{
int index = 0;
for (int i = 0; i < pixels; ++i)
{
fb[index++] = pink;
}
}
static void Fill(Color* fb, const Color& c)
{
int index = 0;
for (int i = 0; i < pixels; ++i)
{
if (IsPink(fb[index]))
{
fb[index] = c;
}
++index;
}
}
template <typename Func>
void DrawRectangle(Color* fb, const IBox& b, bool forceBorder, const Func& Sample)
{
const int borderSize = 2;
const Color border {0.f, 0.f, 0.f};
assert(b.xmin >= 0 && b.xmax < width);
assert(b.ymin >= 0 && b.ymax < height);
int dy = b.ymax - b.ymin;
int dx = b.xmax - b.xmin;
for (int yoff = -borderSize; yoff <= dy+borderSize; ++yoff)
{
int xoff = -borderSize;
int index = width*(b.ymin+yoff) + b.xmin+xoff;
for (; xoff <= dx+borderSize; ++xoff)
{
if (!(xoff < 0 || xoff > dx || yoff < 0 || yoff > dy))
{
fb[index] = Sample(xoff, yoff);
}
else if (forceBorder || IsPink(fb[index])) fb[index] = border;
++index;
}
}
}
static void DrawSafezone(Color* fb, const IBox& b)
{
const Color green {0.7f, 1.f, 0.f};
return DrawRectangle(fb, b, false, [&green](int, int){return green;});
}
static void DrawDangerzone(Color* fb, const IBox& b)
{
return DrawRectangle(fb, b, false, [&b](int x, int y)
{
const Color pos1{1.f, 1.f, 1.f};
const Color pos2{0.8, 0.8, 0.8};
int bitx = ((x+b.xmin) / checkerLen) & 1;
int bity = ((y+b.ymin) / checkerLen) & 1;
if (bitx ^ bity) return pos2;
else return pos1;
});
}
void DrawPlayer(Color* fb, const IBox& player, float red)
{
assert(red >= -1e-5f && red <= 1+1e-5f);
Color color{red, 0.f, 0.f};
return DrawRectangle(fb, player, true, [&color](int, int){return color;});
}
void DrawEnemy(Color* fb, IPoint p)
{
const Color enemy {0.3f, 0.3f, 0.3f};
const int rad = enemyRad;
const int edge = enemyRad+1;
assert(p.x >= rad && p.x < width-rad);
assert(p.y >= rad && p.y < height-rad);
const int rad2 = rad*rad;
const int edge2 = edge*edge;
for (int yoff = -edge; yoff <= edge; ++yoff)
{
int xoff = -edge;
int index = (p.y+yoff)*width + (p.x+xoff);
for (; xoff <= edge; ++xoff)
{
int dist2 = yoff*yoff + xoff*xoff;
if (dist2 < rad2)
{
fb[index] = enemy;
}
else if (dist2 < edge2)
{
assert(index>=0 && index<pixels);
float t = SmoothStep(rad2, edge2, dist2);
fb[index].r = fb[index].r*t + enemy.r*(1.f-t);
fb[index].g = fb[index].g*t + enemy.g*(1.f-t);
fb[index].b = fb[index].b*t + enemy.b*(1.f-t);
}
index++;
}
}
}
void DrawLevel(Color* fb, const LevelDscr& lvl)
{
Clear(fb);
for (int i = 0; i < (int)lvl.area.size(); ++i)
{
if (i != lvl.startIdx && i != lvl.endIdx)
DrawDangerzone(fb, lvl.area[i]);
}
if (lvl.startIdx>=0 && lvl.startIdx<(int)lvl.area.size())
DrawSafezone(fb, lvl.area[lvl.startIdx]);
if (lvl.endIdx>=0 && lvl.endIdx<(int)lvl.area.size())
DrawSafezone(fb, lvl.area[lvl.endIdx]);
Fill(fb, Color{0.5, 0.5f, 0.5f});
}
|
fd810ce4e413d059b534e49dc3b4f0a9ad2bbaa1 | 0bf0c508e18557941ae0f1480779145f56fa19fa | /Resampler.h | 6e5b42f4edb1c79dde8de41e97ef8b367138c024 | [] | no_license | PaulStoffregen/Audio | 3b63c293f58951e3f8eedc2d527e3f53ba866103 | 4cee15b6d008dd9237ac413a946d84f1030790c0 | refs/heads/master | 2023-08-17T16:42:10.254817 | 2023-07-05T12:44:37 | 2023-07-05T12:44:37 | 15,644,096 | 926 | 468 | null | 2023-06-28T15:58:12 | 2014-01-05T02:31:09 | C++ | UTF-8 | C++ | false | false | 10,323 | h | Resampler.h | /* Audio Library for Teensy 3.X
* Copyright (c) 2019, Paul Stoffregen, paul@pjrc.com
*
* Development of this audio library was funded by PJRC.COM, LLC by sales of
* Teensy and Audio Adaptor boards. Please support PJRC's efforts to develop
* open source software by purchasing Teensy or other PJRC products.
*
* 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, development funding 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.
*/
/*
by Alexander Walch
*/
#ifndef resampler_h_
#define resampler_h_
#include "Arduino.h"
//#define DEBUG_RESAMPLER //activates debug output
#define MAX_FILTER_SAMPLES 40961 //=1024*20 +1
#define NO_EXACT_KAISER_SAMPLES 1025
#define MAX_HALF_FILTER_LENGTH 80
#define MAX_NO_CHANNELS 8
class Resampler {
public:
struct StepAdaptionParameters {
StepAdaptionParameters(){}
double alpha =0.2; //exponential smoothing parameter
double maxAdaption = 0.01; //maximum relative allowed adaption of resampler step 0.01 = 1%
double kp= 0.6;
double ki=0.00012;
double kd= 1.8;
};
Resampler(float attenuation=100, int32_t minHalfFilterLength=20, int32_t maxHalfFilterLength=80, StepAdaptionParameters settings=StepAdaptionParameters());
void reset();
///@param attenuation target attenuation [dB] of the anti-aliasing filter. Only used if newFs<fs. The attenuation can't be reached if the needed filter length exceeds 2*MAX_FILTER_SAMPLES+1
///@param minHalfFilterLength If newFs >= fs, the filter length of the resampling filter is 2*minHalfFilterLength+1. If fs y newFs the filter is maybe longer to reach the desired attenuation
void configure(float fs, float newFs);
///@param input0 first input array/ channel
///@param input1 second input array/ channel
///@param inputLength length of each input array
///@param processedLength number of samples of the input that were resampled to fill the output array
///@param output0 first output array/ channel
///@param output1 second output array/ channel
///@param outputLength length of each output array
///@param outputCount number of samples of each output array, that were filled with data
void resample(float* input0, float* input1, uint16_t inputLength, uint16_t& processedLength, float* output0, float* output1,uint16_t outputLength, uint16_t& outputCount);
bool addToSampleDiff(double diff);
double getXPos() const;
double getStep() const;
void addToPos(double val);
void fixStep();
bool initialized() const;
double getAttenuation() const;
int32_t getHalfFilterLength() const;
//resampling NOCHANNELS channels. Performance is increased a lot if the number of channels is known at compile time -> the number of channels is a template argument
template <uint8_t NOCHANNELS>
inline void resample(float** inputs, uint16_t inputLength, uint16_t& processedLength, float** outputs, uint16_t outputLength, uint16_t& outputCount){
outputCount=0;
int32_t successorIndex=(int32_t)(ceil(_cPos)); //negative number -> currently the _buffer0 of the last iteration is used
float* ip[NOCHANNELS];
float* fPtr;
float si0[NOCHANNELS];
float* si0Ptr;
float si1[NOCHANNELS];
float* si1Ptr;
while (floor(_cPos + _halfFilterLength) < inputLength && outputCount < outputLength){
float dist=successorIndex-_cPos;
float distScaled=dist*_overSamplingFactor;
int32_t rightIndex=abs((int32_t)(ceilf(distScaled))-_overSamplingFactor*_halfFilterLength);
const int32_t indexData=successorIndex-_halfFilterLength;
if (indexData>=0){
for (uint8_t i =0; i< NOCHANNELS; i++){
ip[i]=inputs[i]+indexData;
}
}
else {
for (uint8_t i =0; i< NOCHANNELS; i++){
ip[i]=_buffer[i]+indexData+_filterLength;
}
}
fPtr=filter+rightIndex;
memset(si0, 0, NOCHANNELS*sizeof(float));
if (rightIndex==_overSamplingFactor*_halfFilterLength){
si1Ptr=si1;
for (uint8_t i=0; i< NOCHANNELS; i++){
*(si1Ptr++)=*ip[i]++**fPtr;
}
fPtr-=_overSamplingFactor;
rightIndex=(int32_t)(ceilf(distScaled))+_overSamplingFactor; //needed below
}
else {
memset(si1, 0, NOCHANNELS*sizeof(float));
rightIndex=(int32_t)(ceilf(distScaled)); //needed below
}
for (uint16_t i =0 ; i<_halfFilterLength; i++){
if(ip[0]==_endOfBuffer[0]){
for (uint8_t i =0; i< NOCHANNELS; i++){
ip[i]=inputs[i];
}
}
const float fPtrSucc=*(fPtr+1);
si0Ptr=si0;
si1Ptr=si1;
for (uint8_t i =0; i< NOCHANNELS; i++){
*(si0Ptr++)+=*ip[i]*fPtrSucc;
*(si1Ptr++)+=*ip[i]**fPtr;
++ip[i];
}
fPtr-=_overSamplingFactor;
}
fPtr=filter+rightIndex-1;
for (uint16_t i =0 ; i<_halfFilterLength; i++){
if(ip[0]==_endOfBuffer[0]){
for (uint8_t i =0; i< NOCHANNELS; i++){
ip[i]=inputs[i];
}
}
const float fPtrSucc=*(fPtr+1);
si0Ptr=si0;
si1Ptr=si1;
for (uint8_t i =0; i< NOCHANNELS; i++){
*(si0Ptr++)+=*ip[i]**fPtr;
*(si1Ptr++)+=*ip[i]*fPtrSucc;
++ip[i];
}
fPtr+=_overSamplingFactor;
}
const float w0=ceilf(distScaled)-distScaled;
const float w1=1.0f-w0;
si0Ptr=si0;
si1Ptr=si1;
for (uint8_t i =0; i< NOCHANNELS; i++){
*outputs[i]++=*(si0Ptr++)*w0 + *(si1Ptr++)*w1;
}
outputCount++;
_cPos+=_stepAdapted;
while (_cPos >successorIndex){
successorIndex++;
}
}
if(outputCount < outputLength){
//ouput vector not full -> we ran out of input samples
processedLength=inputLength;
}
else{
processedLength=min(inputLength, (int16_t)floor(_cPos + _halfFilterLength));
}
//fill _buffer
const int32_t indexData=processedLength-_filterLength;
if (indexData>=0){
const unsigned long long bytesToCopy= _filterLength*sizeof(float);
float** inPtr=inputs;
for (uint8_t i =0; i< NOCHANNELS; i++){
memcpy((void *)_buffer[i], (void *)((*inPtr)+indexData), bytesToCopy);
++inPtr;
}
}
else {
float** inPtr=inputs;
for (uint8_t i =0; i< NOCHANNELS; i++){
float* b=_buffer[i];
float* ip=b+indexData+_filterLength;
for (uint16_t j =0; j< _filterLength; j++){
if(ip==_endOfBuffer[i]){
ip=*inPtr;
}
*b++ = *ip++;
}
++inPtr;
}
}
_cPos-=processedLength;
if (_cPos < -_halfFilterLength){
_cPos=-_halfFilterLength;
}
}
private:
void getKaiserExact(double beta);
void setKaiserWindow(double beta, int32_t noSamples);
void setFilter(int32_t halfFiltLength,int32_t overSampling, double cutOffFrequ, double kaiserBeta);
float filter[MAX_FILTER_SAMPLES];
double kaiserWindowSamples[NO_EXACT_KAISER_SAMPLES];
double tempRes[NO_EXACT_KAISER_SAMPLES-1];
double kaiserWindowXsq[NO_EXACT_KAISER_SAMPLES-1];
float _buffer[MAX_NO_CHANNELS][MAX_HALF_FILTER_LENGTH*2];
float* _endOfBuffer[MAX_NO_CHANNELS];
int32_t _minHalfFilterLength;
int32_t _maxHalfFilterLength;
int32_t _overSamplingFactor;
int32_t _halfFilterLength;
int32_t _filterLength;
bool _initialized=false;
const double _settledThrs = 1e-6;
StepAdaptionParameters _settings;
double _configuredStep;
double _step;
double _stepAdapted;
double _cPos;
double _sum;
double _oldDiffs[2];
double _attenuation=0;
float _targetAttenuation=100;
};
#endif |
ceb528a75218d4d103424c1b95aecafd46b42f82 | aeb0367615f6d73757e8a9f43990b87a1eacc2b9 | /hackerrank/q3.cpp | 4b21a39aaa54b543d9f4a46ae6e538c41b08e9a9 | [] | no_license | jai-singhal/dsa | b003c216f436a05ebac3babb24e5a20af17bc456 | 10c8a69958e5587a930f3c65b0993e905d18d301 | refs/heads/master | 2021-01-24T11:44:56.624307 | 2020-09-16T10:15:47 | 2020-09-16T10:15:47 | 123,097,497 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 788 | cpp | q3.cpp | // https://www.hackerrank.com/contests/bppc14/challenges/string-and-performing-queries
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;
int main(){
int a, b, Q;
string r, s;
bool is_rev = false;
cin >> s;
cin >> Q;
for(int i = 0; i < Q; i++){
cin >> a;
if (a == 1)
is_rev = true;
else{
cin >> b;
cin >> r;
if(is_rev){
if(b == 2) b = 1;
else b = 2;
is_rev = false;
}
if (b == 1)
s = r + s;
else if(b == 2)
s = s + r;
}
}
if(is_rev)
reverse(s.begin(), s.end());
cout << s;
return 0;
}
|
7df78dc2847103565ec353a6f68894c1b655c19e | f057b7a68b08725471797425d2ab76adde86beb7 | /source/windows/brvertexbufferdirextx9.cpp | ed60433074cae5a4105e40af5678844bbfc4caf5 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"LicenseRef-scancode-warranty-disclaimer",
"Zlib"
] | permissive | amir-padan/burgerlib | af550ef20076cf0329af610101d1371d031e4652 | fb2fc9ae0db206de2249f72a5a2ca850549baeae | refs/heads/master | 2021-06-01T04:20:06.779383 | 2016-04-17T03:35:39 | 2016-04-17T03:35:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,912 | cpp | brvertexbufferdirextx9.cpp | /***************************************
Vertex buffer class for DirectX9
Copyright (c) 1995-2016 by Rebecca Ann Heineman <becky@burgerbecky.com>
It is released under an MIT Open Source license. Please see LICENSE
for license details. Yes, you can use it in a
commercial title without paying anything, just give me a credit.
Please? It's not like I'm asking you for money!
***************************************/
#include "brvertexbufferdirectx9.h"
#if defined(BURGER_WINDOWS) || defined(DOXYGEN)
#include "brglobalmemorymanager.h"
#include "brstringfunctions.h"
#include "brdisplaydirectx9.h"
#include <windows.h>
#include <d3dx9.h>
BURGER_CREATE_STATICRTTI_PARENT(Burger::VertexBufferDirectX9,Burger::VertexBuffer);
Burger::VertexBufferDirectX9::VertexBufferDirectX9() :
m_pVertexBuffer(NULL),
m_pDescription(NULL),
m_uStride(0),
m_uArrayEntryCount(0)
{
}
Burger::VertexBufferDirectX9::~VertexBufferDirectX9()
{
VertexBufferDirectX9::ReleaseData();
}
Word Burger::VertexBufferDirectX9::LoadData(Display *pDisplay,const VertexAoS_t *pDescription)
{
VertexBufferDirectX9::ReleaseData();
Word uResult = 0;
if (pDescription) {
uResult = 10;
IDirect3DDevice9 *pDevice = static_cast<DisplayDirectX9 *>(pDisplay)->GetDirect3DDevice9();
HRESULT hr = pDevice->CreateVertexBuffer(static_cast<UINT>(pDescription->m_uVertexArraySize),D3DUSAGE_WRITEONLY,
0,D3DPOOL_MANAGED,&m_pVertexBuffer,NULL);
if (hr==D3D_OK) {
void *pVertices = NULL;
hr = m_pVertexBuffer->Lock(0,static_cast<UINT>(pDescription->m_uVertexArraySize),&pVertices,0);
if (hr==D3D_OK) {
MemoryCopy(pVertices,pDescription->m_pVertexArray,pDescription->m_uVertexArraySize);
m_pVertexBuffer->Unlock();
//
// Get the number of members in the array of structures
//
const Word *pMembers = pDescription->m_pMembers;
// It's not an error to have no declaration
uResult = 0;
if (pMembers) {
Word uMember = pMembers[0];
if (uMember) {
// Anything larger than 32 entries is totally INSANE!
D3DVERTEXELEMENT9 TempElement[32];
D3DVERTEXELEMENT9 *pDest = TempElement;
Word uOffset = 0;
do {
pDest->Stream = 0;
pDest->Offset = static_cast<WORD>(uOffset);
Word uType = (uMember&0x30);
Word uEntryCount = (uMember&USAGE_COUNTMASK);
if (uType==USAGE_FLOAT) {
BURGER_ASSERT(uEntryCount>=1 && uEntryCount<5);
uOffset += uEntryCount*4;
pDest->Type = static_cast<BYTE>((D3DDECLTYPE_FLOAT1-1)+uEntryCount);
} else {
BURGER_ASSERT(uType!=USAGE_FLOAT);
uResult = 10;
break;
}
pDest->Method = D3DDECLMETHOD_DEFAULT;
// Convert to D3D usage type
pDest->Usage = static_cast<BYTE>((uMember>>8)&0xF);
pDest->UsageIndex = 0;
++pMembers;
// Buffer overflow?
if (++pDest>=&TempElement[32]) {
// Force error
uResult = 10;
break;
}
uMember = pMembers[0];
} while (uMember);
m_uStride = uOffset;
m_uArrayEntryCount = static_cast<Word>(pDescription->m_uVertexArraySize/uOffset);
if (!uResult) {
// Mark the end of the array
pDest->Stream = 0xFF;
pDest->Offset = 0;
pDest->Type = D3DDECLTYPE_UNUSED;
pDest->Method = 0;
pDest->Usage = 0;
pDest->UsageIndex = 0;
hr = pDevice->CreateVertexDeclaration(TempElement,&m_pDescription);
if (hr!=D3D_OK) {
uResult = static_cast<Word>(hr);
}
}
}
}
} else {
uResult = static_cast<Word>(hr);
}
} else {
uResult = static_cast<Word>(hr);
}
}
return uResult;
}
void Burger::VertexBufferDirectX9::ReleaseData(void)
{
m_uStride = 0;
if (m_pVertexBuffer) {
m_pVertexBuffer->Release();
m_pVertexBuffer = NULL;
}
if (m_pDescription) {
m_pDescription->Release();
m_pDescription = NULL;
}
}
#endif
|
644881f2ac15623bce8205b32d1211c076397a5e | bc3e9839f91525ed2c8f02bcb84a718b46075534 | /test1/test1/Palindrome.cpp | 7c7304a0da82c9919d0d595f7f26a1de6a689e05 | [] | no_license | fopmania/CPP | a4346979e67e032d69eea0474376e1d4270bdaed | 66c2f369948f973cd8570ec72ae9a5c5bcb01c1e | refs/heads/master | 2020-03-17T04:01:52.518570 | 2018-05-28T23:37:03 | 2018-05-28T23:37:03 | 133,259,826 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,764 | cpp | Palindrome.cpp | #include "stdafx.h"
#include "Palindrome.h"
#include <ctype.h>
#include <string>
#include <iostream>
#include <algorithm>
#include <utility> // std::pair, std::make_pair
using namespace std;
pair<int,int> getPalindrome(string s, int offset) {
int s_cnt = min((int)s.length() - offset, offset + 1);
int offset1 = 0, leng1 = 1;
int offset2 = 0, leng2 = 0;
for (int i = 1; i < s_cnt; i++) {
if (s.at(offset - i) == s.at(offset + i) ){
offset1 = offset - i;
leng1 = i*2 + 1;
}else break;
}
s_cnt = min((int)s.length() - offset - 1, offset + 1);
for (int i = 0; i < s_cnt; i++) {
if (s.at(offset - i) == s.at(offset + i + 1)) {
offset2 = offset - i;
leng2 = (i+1)*2;
}else break;
}
pair<int, int> r;
if (leng1 > leng2) r = make_pair(offset1, leng1);
else r = make_pair(offset2, leng2);
return r;
}
string longestPalindrome(string s) {
int start = 0, end = 0;
pair<int, int> result = make_pair(0, 1);
int ln = min((int)s.length(), 1000);
for (int i = 0; i < s.length(); i++) {
pair<int, int> temp = getPalindrome(s, i);
if (temp.second > result.second) {
result = temp;
}
}
return s.substr(result.first, result.second );
}
bool isPalindrome(string& word)
{
for (int i = 0; i < word.length() / 2; i++) {
if (tolower(word.at(i)) != tolower(word.at(word.length() - i - 1))) {
return false;
}
}
return true;
}
bool isPalindrome(int x) {
if( x < 0 )
return false;
int r = 0, t = x;
while (t) {
r = r * 10 + t % 10;
t /= 10;
}
return x == r;
}
void run_Palindrome() {
//cout << longestPalindrome("cbbd") << endl;
//cout << longestPalindrome("bb") << endl;
//cout << longestPalindrome("a") << endl;
//cout << longestPalindrome("babad") << endl;
cout << isPalindrome(121) << endl;
}
|
27a8e487b458424686ca57dc5f7759db22e5c6e8 | 7b0c2c09be723ecb8014c8e9a8d3b79a19bb6677 | /Harkkatyo_3_etsi_lajittele/Harkkatyo_3_etsi_lajittele/ListQ.cpp | dbf64f69f35fb16029b4f90ad61bb08abae579db | [] | no_license | AhoiJ/Tietorakenteet-ja-algoritmit | 0433df746dc7a943a6741914c1ed41f5854354b6 | f86c6b724ff43d4f3ec0238539529ef8adfcfe9f | refs/heads/master | 2020-04-25T05:29:48.171604 | 2018-12-15T10:48:33 | 2018-12-15T10:48:33 | 172,545,335 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,238 | cpp | ListQ.cpp | #include "ListQ.h"
template <class ListQ_entry>
ListQ::ListQ()
{
}
template <class ListQ_entry>
ListQ::~ListQ()
{
}
template <class ListQ_entry>
int ListQ<ListQ_entry>::size() const
/*
Post: The function returns the number of entries in the List.
*/
{
return count;
}
template <class ListQ_entry>
Error_code ListQ<ListQ_entry>::insert(int position, const ListQ_entry &x)
/*
Post: If the List is not full and 0 <= position <= n,
where n is the number of entries in the List, the function succeeds:
Any entry formerly at position and all later entries have their
position numbers increased by 1 and x is inserted at position of the List.
Else: The function fails with a diagnostic error code.
*/
{
if (full())
return overflow;
if (position < 0 || position > count)
return range_error;
for (int i = count - 1; i >= position; i--)
entry[i + 1] = entry[i];
entry[position] = x;
count++;
return success;
}
template <class ListQ_entry>
void ListQ<ListQ_entry>::traverse(void(*visit)(ListQ_entry &))
/*
Post: The action specified by function (*visit) has been performed on every
entry of the List, beginning at position 0 and doing each in turn.
*/
{
for (int i = 0; i < count; i++)
(*visit)(entry[i]);
}
|
d0846fefa1c06b7d7e52851d3b5e38c0710e58fe | 9c451121eaa5e0131110ad0b969d75d9e6630adb | /Codeforces/Educational Codeforces Round 37/920E.cpp | 010b8a71261201f488e342294f2904d503d6087c | [] | no_license | tokitsu-kaze/ACM-Solved-Problems | 69e16c562a1c72f2a0d044edd79c0ab949cc76e3 | 77af0182401904f8d2f8570578e13d004576ba9e | refs/heads/master | 2023-09-01T11:25:12.946806 | 2023-08-25T03:26:50 | 2023-08-25T03:26:50 | 138,472,754 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,695 | cpp | 920E.cpp | #include <bits/stdc++.h>
#pragma comment(linker, "/STACK:1024000000,1024000000")
#define mem(a,b) memset((a),(b),sizeof(a))
#define MP make_pair
#define pb push_back
#define fi first
#define se second
#define sz(x) x.size()
#define all(x) x.begin(),x.end()
using namespace std;
#define _GLIBCXX_PERMIT_BACKWARD_HASH
#include <ext/hash_map>
using namespace __gnu_cxx;
struct str_hash{size_t operator()(const string& str)const{return __stl_hash_string(str.c_str());}};
typedef long long ll;
typedef unsigned long long ull;
#define PII pair<int,int>
#define PLL pair<ll,ll>
#define PDD pair<double,double>
const int INF=0x3f3f3f3f;
const ll LLINF=0x3f3f3f3f3f3f3f3f;
const double PI=acos(-1.0);
const double eps=1e-6;
const int MAX=2e5+10;
const ll mod=1e9+7;
int ban[MAX];
vector<int> mp[MAX];
int flag[MAX],n;
set<int> s;
set<int> ::iterator it;
int bfs(int x)
{
int i,t,res=0;
queue<int> q;
q.push(x);
flag[x]=1;
while(!q.empty())
{
t=q.front();
q.pop();
res++;
for(i=0;i<sz(mp[t]);i++) ban[mp[t][i]]=1;
for(it=s.begin();it!=s.end();)
{
if(*it==t) s.erase(it++);
else if(!ban[*it])
{
flag[*it]=1;
q.push(*it);
s.erase(it++);
}
else it++;
}
for(i=0;i<sz(mp[t]);i++) ban[mp[t][i]]=0;
}
return res;
}
int main()
{
int m,a,b,i;
while(~scanf("%d%d",&n,&m))
{
s.clear();
for(i=1;i<=n;i++)
{
mp[i].clear();
s.insert(i);
}
mem(flag,0);
mem(ban,0);
while(m--)
{
scanf("%d%d",&a,&b);
mp[a].pb(b);
mp[b].pb(a);
}
vector<int> ans;
for(i=1;i<=n;i++)
{
if(!flag[i]) ans.pb(bfs(i));
}
sort(all(ans));
printf("%d\n",sz(ans));
for(i=0;i<sz(ans);i++) printf("%d%c",ans[i]," \n"[i==sz(ans)-1]);
}
return 0;
} |
a6df2bd7d46d7cb84129e4b122f88e2a9844c7e0 | dc6de4fa6a0943e61e8371c8d6047fbdefa8be2d | /inc/ER.h | 498de1c514a3a37210c75194de4db248ff307d54 | [
"MIT"
] | permissive | webstorage119/Scene-text-recognition | ff6d117a69c1b71be131d0ec8f12face0cbe5eac | 1025d09161cb75d06f858b14df7187ee2247219e | refs/heads/master | 2023-03-16T00:50:18.625273 | 2020-05-10T19:18:05 | 2020-05-11T14:00:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,679 | h | ER.h | #ifndef __ERTREMAL_REGION__
#define __ERTREMAL_REGION__
#include <stdio.h>
#include <string.h>
#include <string>
#include <math.h>
#include <algorithm>
#include <iostream>
#include <iterator>
#include <fstream>
#include <vector>
#include <forward_list>
#include <chrono>
#include <omp.h>
#include <memory>
#include <opencv2/opencv.hpp>
#include "adaboost.h"
#include "OCR.h"
#include "SpellingCorrector.h"
#define DO_OCR
//#define GET_ALL_ER
//#define USE_STROKE_WIDTH
using namespace std;
using namespace cv;
struct plist
{
plist() :p(0), next(nullptr) {};
plist(int _p) :p(_p), next(nullptr) {};
plist(plist *_next) :p(0), next(_next) {};
plist(int _p, plist *_next) :p(_p), next(_next) {};
int p;
plist *next;
};
struct ER
{
public:
//! Constructor
ER() {};
ER(const int level_, const int pixel_, const int x_, const int y_);
//! seed point and threshold (max grey-level value)
int pixel;
int level;
int x;
int y;
plist *p;
//! feature
int area;
Rect bound;
Point center;
double color1;
double color2;
double color3;
double stkw;
// for non maximal supression
bool done;
double stability;
//! pointers preserving the tree structure of the component tree
ER* parent;
ER* child;
ER* next;
ER *sibling_L;
ER *sibling_R;
//! for OCR
int ch;
char letter;
double prob;
};
typedef vector<ER *> ERs;
struct Text
{
Text(){};
Text(ER *x, ER *y, ER *z)
{
ers.push_back(x);
ers.push_back(y);
ers.push_back(z);
};
ERs ers;
double slope;
Rect box;
string word;
};
struct GraphNode
{
GraphNode(ER *v, const int i) : vertex(v), index(i){};
ER* vertex;
int index;
vector<GraphNode> adj_list;
vector<double> edge_prob;
};
typedef vector<GraphNode> Graph;
class ERFilter
{
public:
ERFilter(int thresh_step = 2, int min_area = 100, int max_area = 100000, int stability_t = 2, double overlap_coef = 0.7, double min_ocr_prob = 0.01);
~ERFilter() {}
//! modules
AdaBoost *stc; // strong text classifier
AdaBoost *wtc; // weak text classifier
OCR *ocr; // text ocr model, base on libsvm
SpellingCorrector corrector;
//! functions
vector<double> text_detect(Mat src, ERs &root, vector<ERs> &all, vector<ERs> &pool, vector<ERs> &strong, vector<ERs> &weak, ERs &tracked, vector<Text> &text);
void compute_channels(Mat &src, Mat &YCrcb, vector<Mat> &channels);
ER* er_tree_extract(Mat input);
void non_maximum_supression(ER *er, ERs &all, ERs &pool, Mat input);
void classify(ERs &pool, ERs &strong, ERs &weak, Mat input);
void er_delete(ER *er);
void er_track(vector<ERs> &strong, vector<ERs> &weak, ERs &all_er, vector<Mat> &channel, Mat Ycrcb);
void er_grouping(ERs &all_er, vector<Text> &text, bool overlap_sup = false, bool inner_sup = false);
void er_ocr(ERs &all_er, vector<Mat> &channel, vector<Text> &text);
vector<double> make_LBP_hist(Mat input, const int N = 2, const int normalize_size = 24);
bool load_tp_table(const char* filename);
Mat calc_LBP(Mat input, const int size = 24);
void set_thresh_step(int t);
void set_min_area(int m);
private:
//! Parameters
int THRESH_STEP;
int MIN_AREA;
int MAX_AREA;
int STABILITY_T;
double OVERLAP_COEF;
double MIN_OCR_PROB;
enum { right, bottom, left, top };
//! ER operation functions
inline void er_accumulate(ER *er, const int ¤t_pixel, const int &x, const int &y);
void er_merge(ER *parent, ER *child);
void process_stack(const int new_pixel_grey_level, ERs &er_stack);
// Gouping operation functions
inline bool is_neighboring(ER *a, ER *b);
inline bool is_overlapping(ER *a, ER *b);
void inner_suppression(ERs &pool);
void overlap_suppression(ERs &pool);
// OCR operation functions
void build_graph(Text &text, Graph &graph);
void solve_graph(Text &text, Graph &graph);
void spell_check(Text &text);
// feature extract
Vec3d color_hist(Mat input);
double tp[65][65];
};
class StrokeWidth
{
public:
double SWT(Mat input);
private:
struct SWTPoint2d {
SWTPoint2d(int _x, int _y) : x(_x), y(_y) {};
int x;
int y;
float SWT;
};
struct Ray {
Ray(SWTPoint2d _p, SWTPoint2d _q, vector<SWTPoint2d> _points) : p(_p), q(_q), points(_points){};
SWTPoint2d p;
SWTPoint2d q;
vector<SWTPoint2d> points;
};
};
class ColorHist
{
public:
ColorHist() { }
inline void calc_hist(Mat img);
inline double compare_hist(ColorHist ch);
double c1[256];
double c2[256];
double c3[256];
};
double fitline_LSE(const vector<Point> &p);
double fitline_LMS(const vector<Point> &p);
double fitline_avgslope(const vector<Point> &p);
void calc_color(ER* er, Mat mask_channel, Mat color_img);
vector<vector<int> > comb(int N, int K);
double standard_dev(vector<double> arr, bool normalize);
#endif |
dff56ef68d8a92888b3318eee9982cab7ea9d2ef | 549516d423efe412508e9d336665cf54c7990920 | /src/ccsubmatlib.cpp | 6ad30617166b2d829f1976a9cab42f21f5a27865 | [] | no_license | mmorse1217/blendsurf | 801a961234f2a0973c1db5db86f3f753526c2d60 | f13344873ec97650f9a1d43cffa5892a41570130 | refs/heads/master | 2022-04-09T17:00:08.629668 | 2020-03-27T15:45:00 | 2020-03-27T15:45:00 | 246,194,542 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 6,088 | cpp | ccsubmatlib.cpp | #include "ccsubmatlib.hpp"
// ----------------------------------------------------------------------
int CCSubMatLib::setup(istream& fin)
{
assert(fin.good());
_interior.resize(MAXVALENCE);
_boundary.resize(MAXVALENCE);
_cornerconvex.resize(MAXVALENCE);
_cornerconcave.resize(MAXVALENCE);
char tmp[100];
fin>>tmp;
while(fin.eof()==false) {
// cout<<tmp<<endl;
assert(strcmp(tmp, "interior")==0 || strcmp(tmp, "boundary")== 0 ||
strcmp(tmp, "cornerconvex") == 0 || strcmp(tmp, "cornerconcave") == 0);
if (strcmp(tmp, "interior") == 0){
vector<Entry>& cur = _interior;
//get valence
int k;
fin>>k; assert(k>=3 && k<=MAXVALENCE );
Entry& entry = cur[k];
//get size
int size;
fin>>size; assert(size == 6*k+1);
//read in SM : subdivision matrix
NumMatrix& sm = entry.SM();
sm.resize(size,size);
for(int i=0; i<size; i++)
for(int j=0; j<size; j++)
fin>>sm(i,j); //read row by row
//read in IV: inverse of eigen vectors
NumMatrix& iv = entry.IV();
iv.resize(size,size);
for(int i=0; i<size; i++)
for(int j=0; j<size; j++)
fin>>iv(i,j); //read row by row
//read in V : eigen vector matrix
NumMatrix& v = entry.V();
v.resize(size,size);
for(int i=0; i<size; i++)
for(int j=0; j<size; j++)
fin>>v(i,j); //read row by row
//read in D : eigen values
NumVector& d = entry.D();
d.resize(size);
for(int i=0; i<size; i++)
fin>>d(i);
}
else if (strcmp(tmp, "boundary") == 0){
vector<Entry>& cur = _boundary;
//get valence
int k;
fin>>k; assert(k>=2 && k<MAXVALENCE);
Entry& entry = cur[k];
//get size
int size;
fin>>size; assert(size == 6*k+3);
//read in SM : subdivision matrix
NumMatrix& sm = entry.SM();
sm.resize(size,size);
for(int i=0; i<size; i++)
for(int j=0; j<size; j++)
fin>>sm(i,j); //read row by row
//read in IV: inverse of eigen vectors
NumMatrix& iv = entry.IV();
iv.resize(size,size);
for(int i=0; i<size; i++)
for(int j=0; j<size; j++)
fin>>iv(i,j); //read row by row
//read in V : eigen vector matrix
NumMatrix& v = entry.V();
v.resize(size,size);
for(int i=0; i<size; i++)
for(int j=0; j<size; j++)
fin>>v(i,j); //read row by row
//read in D : eigen values
NumVector& d = entry.D();
d.resize(size);
for(int i=0; i<size; i++)
fin>>d(i);
}
else if (strcmp(tmp, "cornerconvex") == 0){
vector<Entry>& cur = _cornerconvex;
//get valence
int k;
fin>>k; assert(k>=1 && k<MAXVALENCE);
Entry& entry = cur[k];
//get size
int size;
fin>>size; assert(size == 6*k+3);
//read in SM : subdivision matrix
NumMatrix& sm = entry.SM();
sm.resize(size,size);
for(int i=0; i<size; i++)
for(int j=0; j<size; j++)
fin>>sm(i,j); //read row by row
//read in IV: inverse of eigen vectors
NumMatrix& iv = entry.IV();
iv.resize(size,size);
for(int i=0; i<size; i++)
for(int j=0; j<size; j++)
fin>>iv(i,j); //read row by row
//read in V : eigen vector matrix
NumMatrix& v = entry.V();
v.resize(size,size);
for(int i=0; i<size; i++)
for(int j=0; j<size; j++)
fin>>v(i,j); //read row by row
//read in D : eigen values
NumVector& d = entry.D();
d.resize(size);
for(int i=0; i<size; i++)
fin>>d(i);
}
else if (strcmp(tmp, "cornerconcave") == 0){
vector<Entry>& cur = _cornerconcave;
//get valence
int k;
fin>>k; assert(k>=2 && k<MAXVALENCE);
Entry& entry = cur[k];
//get size
int size;
fin>>size; assert(size == 6*k+3);
//read in SM : subdivision matrix
NumMatrix& sm = entry.SM();
sm.resize(size,size);
for(int i=0; i<size; i++)
for(int j=0; j<size; j++)
fin>>sm(i,j); //read row by row
//read in IV: inverse of eigen vectors
NumMatrix& iv = entry.IV();
iv.resize(size,size);
for(int i=0; i<size; i++)
for(int j=0; j<size; j++)
fin>>iv(i,j); //read row by row
//read in V : eigen vector matrix
NumMatrix& v = entry.V();
v.resize(size,size);
for(int i=0; i<size; i++)
for(int j=0; j<size; j++)
fin>>v(i,j); //read row by row
//read in D : eigen values
NumVector& d = entry.D();
d.resize(size);
for(int i=0; i<size; i++)
fin>>d(i);
}
fin>>tmp;
}
return 0;
}
CCSubMatLib::Entry& CCSubMatLib::chooseMatrix(int flag, int k)
{
if(flag==INTERIOR)
return _interior[k];
else if(flag==BOUNDARY)
return _boundary[k];
else if (flag==CORNERCONVEX)
return _cornerconvex[k];
else if (flag == CORNERCONCAVE)
return _cornerconcave[k];
else assert(0);
//control can not reach here anyway
return _interior[k];
}
|
f08cc0d7cf3f9f7532c6497fa5e5424bdd5b3d49 | ae57d5c8cb3ebcfd66dca4b10ceedc8a656496a0 | /src/Player.cpp | 2f384ac4796327fe4251713e2cb2e42723cb958f | [] | no_license | NullStudio/NoNameGame | f1a1c81148581e09178ef1dda5efddf0b253401f | 310a32f82f0fd6c9ca6302c99793ac9696ed33cc | refs/heads/master | 2020-05-20T01:08:26.191101 | 2011-09-05T10:56:53 | 2011-09-05T10:56:53 | 2,172,375 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 469 | cpp | Player.cpp |
#include "Player.hpp"
Player::Player(Animation* animation, b2Body* body) :
mAnimation(animation), mBody(body)
{
}
Player::~Player()
{
delete mAnimation;
}
b2Body* Player::GetBody()
{
return mBody;
}
b2Vec2 Player::GetPosition()
{
return mBody->GetPosition();
}
Animation* Player::GetAnimation()
{
return mAnimation;
}
float Player::GetMaxWalkVelocity() const
{
return 10.0f;
}
float Player::GetJumpVelocity() const
{
return 2.0f;
}
|
dd3e596c2db0f3814cdcb63a041636a9643af312 | ed1b498ee0417b5b5f97daf7d9686a5e9f7a094a | /inc/Plaszczyzna.hh | 9b19cef1c481dbce0e2da724494f096e2584989c | [
"MIT"
] | permissive | Kordziu/Dron_podwodny | fe84c7cc1b703ec490f4454503a4c5e543350c1d | 4a32b345ab648e65bd8dc6a409d0268e7d8f2ed9 | refs/heads/master | 2022-09-29T12:03:51.441747 | 2020-06-07T18:54:06 | 2020-06-07T18:54:06 | 262,001,521 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 401 | hh | Plaszczyzna.hh | #ifndef PLASZCZYZNA_HH
#define PLASZCZYZNA_HH
#include "IObiektRysowalny.hh"
using std::vector;
class Plaszczyzna : public IObiektRysowalny {
protected:
SWektor<double,3> p[49];
public:
Plaszczyzna(drawNS::APIGnuPlot3D * Obiekt, SWektor<double,3> * tab): IObiektRysowalny(Obiekt)
{
for(int i = 0; i < 49; i++)
{
p[i] = tab[i];
}
};
virtual void rysuj() = 0;
};
#endif
|
db1dc005fbff3345c25161ef96293c5a6fb3b5c4 | 50cecd926c4ff36db6213fa5f100f416d2a410a9 | /ranade/ch10/turtleLessTree.cpp | 79cf7f2a3745e567a98857b71266d6201bafe751 | [] | no_license | anant348/problems | 031152ddd6be2f0ca2fd371bd4348097e9825ba8 | 21ed6131a37f67f30fdf0db4a7a6de58acb62e2d | refs/heads/master | 2022-07-19T19:39:25.118015 | 2020-05-22T03:53:24 | 2020-05-22T03:53:24 | 266,009,563 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 551 | cpp | turtleLessTree.cpp | #include <simplecpp>
using namespace std;
void tree(int h,float width,float height,float x,float y){
static int i=1;
if(h == 0){
Text t1(x-5,y,i);
t1.imprint();i++;
return;
}
Line lLine(x,y,x-width/4,y-height/2);lLine.imprint();
Line rLine(x,y,x+width/4,y-height/2);rLine.imprint();
tree(h-1,width/2,height/2,x-width/4,y-height/2);
Text t(x-5,y,i);i++;t.imprint();
tree(h-1,width/2,height/2,x+width/4,y-height/2);
}
main_program{
initCanvas("tree",550,550);
tree(5,500,500,250,500);
getClick();
}
|
cc4febf3da3b231f2245d581cdd50de7f2acd215 | fc6955cf9db78ce5b13e7303fb7a674d7daa8f9f | /n后问题/n后问题-180021104728-王思铠.cpp | daf46a6bf5f0fc1ddc5808b5329df60f20eb77c2 | [] | no_license | wang0769/algorithm_code | 4375b83f3a9e8365c43e28fd79754c3bfda39309 | 126f5c3f9001257207029bb393fe1a18b3b7a87a | refs/heads/master | 2020-09-07T00:58:06.449162 | 2019-12-15T14:10:28 | 2019-12-15T14:10:28 | 220,609,176 | 0 | 0 | null | 2019-11-09T07:48:05 | 2019-11-09T07:48:04 | null | GB18030 | C++ | false | false | 648 | cpp | n后问题-180021104728-王思铠.cpp | #include<iostream>
#define N 1000
using namespace std;
int n;
int x[N];
int sum;
int abs(int a )
{
return a>0?a:-a;
}
int Place(int k)
{
int j,a=0;
for(j=1;j<k;j++){
if((abs(k-j)==abs(x[k]-x[j])) || (x[j]==x[k]))
return 0;
}
return 1;
}
backtrack(){
int k=1;
x[1]=0;
while(k>0){
x[k]+=1;
while((x[k]<=n)&&!(Place[k]))
x[k]+=1;
if(x[k]<=n)
if(k==n)
sum++;
else{
k++;
x[k]=0;
}
else k--;
}
}
int nQueen(){
int i ;
sum=0;
for(i=0;i<n;i++)
x[i]=0;
backtrack();
return sum;
}
int main(){
int a;
cout<<"请输入女王的数量:"<<endl;
cin>>n;
a=nQueen();
cout<<"共找到"<<a<<"组解"<<endl;
}
|
f311e232d04f872fabd40f5e27aaefa0d841200b | 34143cd84540d99cef21fd5edd468c7cd40ac335 | /AOJ/1090.cc | 8b4d4637704232a1d12303f8b3e09ca2d380cb08 | [] | no_license | osak/Contest | 0094f87c674d24ebfc0d764fca284493ab90df99 | 22c9edb994b6506b1a4f65b53a6046145a6cce41 | refs/heads/master | 2023-03-06T02:23:53.795410 | 2023-02-26T11:32:11 | 2023-02-26T11:32:11 | 5,219,104 | 8 | 9 | null | 2015-02-09T06:09:14 | 2012-07-29T01:16:42 | C++ | UTF-8 | C++ | false | false | 8,431 | cc | 1090.cc | //Name: Sports Days
//Level: 5
//Category: グラフ,Graph,k-最短路
//Note:
/*
* 問題を整理すると以下のようになる.
* ・負辺,閉路を含み得る有向グラフが与えられる.
* ・各頂点にはラベルが付けられており,特定の順序でラベルを辿ることは禁止される.
* ・スタートからゴールまでのパスを短い方から最大K本見つける.
* ・最短パスがいくらでもコストを下げられる場合も検出する.
*
* まず,禁止順序の処理はKMP法と同様のオートマトンを作成することで可能である.
* オートマトンのある状態からの失敗遷移は,文字列を1文字遅れで読んでいくカーソルからの失敗遷移と等しくなる(証明略).
*
* 次に,最初に与えられた頂点vをオートマトンの頂点数pと同じだけ複製し,頂点(v,p)に関してグラフを作成する.
* 以降はこのグラフに関して問題を考えれば良くなる.
*
* 最短パスがいくらでもコストを下げられる状態は,負閉路が存在してかつゴールまで到達可能な場合である.
* Bellman-Fordを使い,最初に頂点数の回数だけrelaxしてから更に同じ回数だけrelaxしたとき,ゴールのコストが更新された場合は
* ゴールに到達可能な負閉路があるとしてよい.
*
* 最後にk-最短路を求める.
* これは各頂点に対し,最もコストの低いK個のコストだけを覚えておき,これ以上のコストで遷移してきた場合は弾くようにすることで達成できる.
* ただし通常のBellman-Fordでは直前に更新された状態とそれより前のメモの区別が付けられないので,適宜工夫する.
*
* オーダーは禁止パターンの長さをPとして
* ・頂点数が |V| = N * P
* ・辺数が |E| = O(MP)
* ・Bellman-Fordが O(|V||E|) = O(NMP^2)
* ・Bellman-Fordの更新1回につき O(P)
* より,全体では O(NMP^3) となる.
*/
//#define _GLIBCXX_DEBUG
#include <iostream>
#include <vector>
#include <string>
#include <queue>
#include <deque>
#include <algorithm>
#include <cassert>
using namespace std;
#define FOREACH(it,c) for(__typeof((c).begin()) it = (c).begin(); it != (c).end(); ++it)
#define TIMES(i,n) for(int i = 0; i < (n); ++i)
typedef long long Cost;
const long long INF = 1000*1000*10*10*2*10LL;
struct Edge {
int from, to;
Cost cost;
Edge() {}
Edge(int f, int t, Cost c) : from(f), to(t), cost(c) {}
};
struct DistTag {
int size;
deque<Cost> buf, newbie;
DistTag(int size) : size(size), buf(size, INF) {
//newbie.reserve(size);
}
bool insert(Cost val) {
if(buf.back() <= val) return false;
deque<Cost>::iterator ins_pos = upper_bound(newbie.begin(), newbie.end(), val);
newbie.insert(ins_pos, val);
if(static_cast<int>(newbie.size()) > size) newbie.pop_back();
return true;
}
bool has(Cost val) {
return buf.back() >= val;
}
void flush() {
FOREACH(it, newbie) {
deque<Cost>::iterator ins_pos = upper_bound(buf.begin(), buf.end(), *it);
buf.insert(ins_pos, *it);
}
buf.resize(size);
newbie.clear();
}
};
struct State {
int pos;
Cost cost;
State() {}
State(int p, Cost c) : pos(p), cost(c) {}
bool operator <(const State &other) const {
return cost > other.cost; // Reversed
}
};
typedef vector<Edge> EdgeList;
void check_reachable(int start, const vector<EdgeList> &graph, vector<unsigned char> &reachable) {
queue<int> q;
q.push(start);
reachable[start] = 1;
while(!q.empty()) {
int cur = q.front();
q.pop();
FOREACH(it, graph[cur]) {
if(!reachable[it->to]) {
reachable[it->to] = 1;
q.push(it->to);
}
}
}
}
bool relax(const vector<EdgeList> &graph, vector<Cost> &dist) {
bool updated = false;
FOREACH(list_it, graph) {
FOREACH(it, *list_it) {
const Cost cost = dist[it->from] + it->cost;
if(dist[it->to] > cost) {
dist[it->to] = cost;
updated = true;
}
}
}
return updated;
}
pair<int,Cost> search(int start, const vector<EdgeList> &graph, int N, int P, int K) {
vector<DistTag> dist(graph.size(), DistTag(K));
dist[start].insert(0);
TIMES(_, static_cast<int>(graph.size())*K) {
TIMES(i, static_cast<int>(graph.size())) {
DistTag &dt = dist[i];
if(dt.newbie.size() == 0) continue;
vector<int> tmp;
FOREACH(it, graph[i]) {
assert(it->from == i);
// Corner case: loop edge
if(it->to == i) {
FOREACH(nit, dt.newbie) {
tmp.push_back(*nit + it->cost);
}
} else {
FOREACH(nit, dt.newbie) {
//cout << "insert " << i << ' ' << it->to << endl;
dist[it->to].insert(*nit + it->cost);
}
}
}
dt.flush();
FOREACH(tit, tmp) {
dt.insert(*tit);
}
}
}
pair<int,Cost> res(0, 0);
vector<Cost> costs;
TIMES(i, P) {
FOREACH(it, dist[(N-1)*P+i].buf) {
costs.push_back(*it);
}
}
sort(costs.begin(), costs.end());
TIMES(i, min(K, static_cast<int>(costs.size()))) {
if(costs[i] == INF) break;
res.first++;
res.second += costs[i];
}
return res;
}
pair<int,Cost> solve(int N) {
vector<int> color_of(N);
TIMES(i, N) {
cin >> color_of[i];
--color_of[i];
}
int M;
cin >> M;
vector<Edge> edges(M);
TIMES(i, M) {
Edge &e = edges[i];
cin >> e.from >> e.to >> e.cost;
--e.from; --e.to;
}
int K;
cin >> K;
vector<int> prohibited;
{
string str;
cin >> str;
FOREACH(it, str) {
prohibited.push_back(*it - '0' - 1);
}
}
const int P = prohibited.size();
vector<vector<int> > next_prohibited_pos(P, vector<int>(4, 0));
{
int shadow = 0;
TIMES(i, P) {
next_prohibited_pos[i][prohibited[i]] = i+1;
if(i > 0) {
TIMES(j, 4) {
if(j != prohibited[i]) next_prohibited_pos[i][j] = next_prohibited_pos[shadow][j];
}
shadow = next_prohibited_pos[shadow][prohibited[i]];
}
}
}
const int start = 0+next_prohibited_pos[0][color_of[0]];
vector<EdgeList> graph(N*P);
FOREACH(it, edges) {
TIMES(i, P) {
// Cannot reach this state.
if(i > 0 && prohibited[i-1] != color_of[it->from]) continue;
int np = next_prohibited_pos[i][color_of[it->to]];
if(np < P) {
graph[it->from*P+i].push_back(Edge(it->from*P+i, it->to*P+np, it->cost));
//cout << it->from << ' ' << i << ' ' << it->to << ' ' << np << endl;
}
}
}
// Remove all unreachable nodes.
// It causes fake negative loop detection.
vector<unsigned char> reachable(N*P, 0);
check_reachable(start, graph, reachable);
TIMES(i, N*P) {
if(!reachable[i]) graph[i].clear();
}
// Check if it has negative loop
vector<Cost> dist(N*P, INF);
dist[start] = 0;
TIMES(_, N*P) {
relax(graph, dist);
}
vector<Cost> tmp_last(P);
TIMES(i, P) {
tmp_last[i] = dist[(N-1)*P+i];
}
TIMES(_, N*P) {
relax(graph, dist);
TIMES(i, P) {
if(dist[(N-1)*P+i] != tmp_last[i]) return make_pair(-1, -1);
}
}
// Corner case: cannot start
if(P == 1 && prohibited[0] == color_of[0]) return make_pair(0, 0);
pair<int,Cost> res = search(start, graph, N, P, K);
return res;
}
int main() {
cin.tie(0);
ios::sync_with_stdio(0);
int N;
while(cin >> N) {
if(!N) break;
pair<int,Cost> ans = solve(N);
if(ans.first == -1) cout << -1 << endl;
else cout << ans.first << ' ' << ans.second << endl;
}
return 0;
}
|
936ec22e90db74b0120c6523a39531698b3e995e | a9632951e36cab2b823a9d160cd69dd26f6c19b6 | /rotate.cpp | d6158055c31da6b78e03d20fdeb63c164fe36b03 | [] | no_license | abhishek03-cs/onlinepractice | 2e9326a76cb7e5f9c899d2ffde519e5a8fd6f827 | f338c18b8840ee0eb3ffa397ec481c3acbe72cc2 | refs/heads/main | 2023-01-21T21:42:29.455949 | 2020-12-01T07:01:32 | 2020-12-01T07:01:32 | 304,698,973 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 772 | cpp | rotate.cpp | #include<iostream>
#include<algorithm>
using namespace std;
int main(){
int n;
cin>>n;
int arr[n][n];
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
cin>>arr[i][j];
int start_row=0,start_col=0,end_col=n-1;
while(start_row<n){
start_col=0;
end_col=n-1;
while(start_col<end_col){
swap(arr[start_row][start_col],arr[start_row][end_col]);
start_col++;
end_col--;
}
start_row++;
}
start_row=0;
start_col=0;
end_col=n-1;
while(start_row<n){
for(int j=start_col;j<=end_col;j++)
swap(arr[start_row][j],arr[j][start_row]);
start_row++;
start_col++;
}
cout<<endl;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++)
cout<<arr[i][j]<<" ";
cout<<endl;
}
return 0;
} |
94326ccdc827b4b981fe070dc1e33391bd5b3631 | d3e189cc988e3cb6cbf86d56f263f3f0a37daa69 | /library/FenwickTree.cpp | 54d3034b9abe741d2a07956ad94605876a388b99 | [] | no_license | kThieb/Data-Structures-in-CPP | 3f227b2b7fc9a9efb06a731900a0e4ad4fea7fae | 5b9a2cb74c546b8c6b3cbf6e8a6b5b4422c7925c | refs/heads/master | 2022-12-13T22:12:55.885196 | 2020-09-07T12:43:14 | 2020-09-07T12:43:14 | 279,624,039 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,103 | cpp | FenwickTree.cpp | #include<bits/stdc++.h>
using namespace std;
class FenwickTree {
vector<int> BITree;
int n;
public:
FenwickTree(vector<int> arr, int _n) {
n = _n;
BITree.assign(n + 1, 0);
for (int i = 0; i < n; ++i) {
update(i, arr[i]);
}
}
int get_sum_from_0(int index) {
++index;
int sum = 0;
for (; index > 0; index -= (index & (-index))) {
sum += BITree[index];
}
return sum;
}
int get_sum(int i, int j) {
return get_sum_from_0(j) - get_sum_from_0(i);
}
void update(int index, int val) {
++index;
for (; index <= n; index += (index & (-index))) {
BITree[index] += val;
}
}
};
int main() {
vector<int> freq = {2, 1, 1, 3, 2, 3, 4, 5, 6, 7, 8, 9};
int n = freq.size();
FenwickTree ft(freq, n);
cout << "Sum of elements in arr[0..5] is " << ft.get_sum(0, 5);
freq[3] += 6;
ft.update(3, 6);
cout << "\nSum of elements in arr[0..5] after update is " << ft.get_sum(0, 5);
return 0;
} |
9310b9a3f2dddc27ed35a0496d6c9c0d9f6e5fb4 | 36006487fbed2c19a2367e968afc11e76a55bb95 | /Spoj/GERGOVIA-Wine_trading_in_Gergovia.cpp | 19ccad94efa3093af84d6692ffc424c53c1a5837 | [] | no_license | AkVaya/CP_Solutions | 99bd280470997f048ca2ee9b9dda83488d19ca7e | 60fd900aad28caf34b15b75ce736141dbc074d9f | refs/heads/master | 2021-09-27T13:57:38.897747 | 2021-09-16T16:43:55 | 2021-09-16T16:43:55 | 232,780,223 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 573 | cpp | GERGOVIA-Wine_trading_in_Gergovia.cpp | #include<bits/stdc++.h>
using namespace std;
const int nax = 69;
using ll = long long;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int t = 1;
//cin>>t;
while(1){
int n;
cin>>n;
if(!n)
break;
int a[n];
for (int i = 0; i < n; ++i)
{
cin>>a[i];
}
ll res = 0, curr = a[0];
for (int i = 1; i < n; ++i)
{
res+=abs(curr);
curr+=a[i];
}
cout<<res<<'\n';
}
return 0;
} |
c09a090f63609f752c82627fcf061d6bb798aafe | 1ec838a1a7b944da9044ccccae388f5c7acc5c6f | /VirtualDataView/include/wx/VirtualDataView/Table/VirtualDataTableRowHeader.h | 68bd84919166f5a381fb283316af1937163bfd2b | [] | no_license | seb-dub/wxVirtualDataView | 541f1825aed6d1f8b1946adfa0e7d98cd513a070 | 96b2bc2663b877ac6bc7d2bcc3bc098d1f7fca5b | refs/heads/master | 2021-01-12T01:17:55.280900 | 2017-01-22T22:15:25 | 2017-01-22T22:15:25 | 78,369,100 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,565 | h | VirtualDataTableRowHeader.h | /**********************************************************************/
/** FILE : VirtualDataTableRowHeader.h **/
/** PROJECT : wxVirtualDataViewCtrl **/
/** LICENSE : wxWindows Library Licence **/
/** PURPOSE : header control for rows for wxVirtualDataTableCtrl **/
/**********************************************************************/
#ifndef _VIRTUAL_DATA_TABLE_ROW_HEADER_H_
#define _VIRTUAL_DATA_TABLE_ROW_HEADER_H_
#include <wx/VirtualDataView/Table/VirtualDataTableHeader.h>
/** \class wxVirtualDataTableRowHeader : header control for rows for wxVirtualDataView
*/
class WXDLLIMPEXP_VDV wxVirtualDataTableRowHeader : public wxVirtualDataTableHeader
{
public:
//constructors & destructor
wxVirtualDataTableRowHeader(void); ///< \brief default constructor
wxVirtualDataTableRowHeader(wxWindow *pParent,
wxWindowID id = wxID_ANY,
const wxPoint &ptPos = wxDefaultPosition,
const wxSize &size = wxDefaultSize,
long lStyle = WX_VDV_DEFAULT_STYLE,
const wxString &sName = wxVDVTableHeaderCtrlNameStr); ///< \brief constructor
virtual ~wxVirtualDataTableRowHeader(void); ///< \brief destructor
};
#endif //_VIRTUAL_DATA_TABLE_ROW_HEADER_H_
|
0f106212bedb2cc25f8076c7b80f24a343f1c298 | ebe0c5741b63b0d175549986e7288b9529775218 | /calc/dataCenterClientModule/soapStub.h | 9628ff2f6e61f55561da5cd795d959b19346d6c5 | [] | no_license | zhk/TileMapEditor | bd4a59e5fefcdbef55af98ac610606a8d3f446c5 | 9616c90028d6e0bad04859c30cc7cb4f91ed1940 | refs/heads/master | 2022-11-18T04:18:01.594780 | 2020-07-19T13:02:35 | 2020-07-19T13:02:35 | 280,866,249 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,310 | h | soapStub.h | /* soapStub.h
Generated by gSOAP 2.8.0 from DataCenter.h
Copyright(C) 2000-2010, Robert van Engelen, Genivia Inc. All Rights Reserved.
The generated code is released under one of the following licenses:
GPL, the gSOAP public license, or Genivia's license for commercial use.
*/
#ifndef soapStub_H
#define soapStub_H
#include <vector>
#define SOAP_NAMESPACE_OF_ns2 "urn:DataCenter"
#include "stdsoap2.h"
/******************************************************************************\
* *
* Enumerations *
* *
\******************************************************************************/
/******************************************************************************\
* *
* Types with Custom Serializers *
* *
\******************************************************************************/
/******************************************************************************\
* *
* Classes and Structs *
* *
\******************************************************************************/
#if 0 /* volatile type: do not declare here, declared elsewhere */
#endif
#if 0 /* volatile type: do not declare here, declared elsewhere */
#endif
#ifndef SOAP_TYPE_BlockKeyType
#define SOAP_TYPE_BlockKeyType (10)
/* BlockKeyType */
struct BlockKeyType
{
public:
std::string appKey; /* required element of type xsd:string */
std::string regionKey; /* required element of type xsd:string */
std::string dataType; /* required element of type xsd:string */
std::string dataKey; /* required element of type xsd:string */
};
#endif
#ifndef SOAP_TYPE_BlockDataType
#define SOAP_TYPE_BlockDataType (11)
/* BlockDataType */
struct BlockDataType
{
public:
std::string dataCheckSum; /* required element of type xsd:string */
std::string data; /* required element of type xsd:string */
};
#endif
#ifndef SOAP_TYPE_ns2__setData
#define SOAP_TYPE_ns2__setData (16)
/* ns2:setData */
struct ns2__setData
{
public:
struct BlockKeyType *key; /* optional element of type BlockKeyType */
struct BlockDataType *blockdata; /* optional element of type BlockDataType */
};
#endif
#ifndef SOAP_TYPE_ns2__getDataResponse
#define SOAP_TYPE_ns2__getDataResponse (19)
/* ns2:getDataResponse */
struct ns2__getDataResponse
{
public:
std::string data; /* SOAP 1.2 RPC return element (when namespace qualified) */ /* required element of type xsd:string */
};
#endif
#ifndef SOAP_TYPE_ns2__getData
#define SOAP_TYPE_ns2__getData (20)
/* ns2:getData */
struct ns2__getData
{
public:
struct BlockKeyType *key; /* optional element of type BlockKeyType */
};
#endif
#ifndef SOAP_TYPE_ns2__getDataCheckSumResponse
#define SOAP_TYPE_ns2__getDataCheckSumResponse (22)
/* ns2:getDataCheckSumResponse */
struct ns2__getDataCheckSumResponse
{
public:
std::string checkSum; /* SOAP 1.2 RPC return element (when namespace qualified) */ /* required element of type xsd:string */
};
#endif
#ifndef SOAP_TYPE_ns2__getDataCheckSum
#define SOAP_TYPE_ns2__getDataCheckSum (23)
/* ns2:getDataCheckSum */
struct ns2__getDataCheckSum
{
public:
struct BlockKeyType *key; /* optional element of type BlockKeyType */
};
#endif
#ifndef SOAP_TYPE_ns2__addResponse
#define SOAP_TYPE_ns2__addResponse (27)
/* ns2:addResponse */
struct ns2__addResponse
{
public:
double result; /* SOAP 1.2 RPC return element (when namespace qualified) */ /* required element of type xsd:double */
};
#endif
#ifndef SOAP_TYPE_ns2__add
#define SOAP_TYPE_ns2__add (28)
/* ns2:add */
struct ns2__add
{
public:
double a; /* required element of type xsd:double */
double b; /* required element of type xsd:double */
};
#endif
#ifndef SOAP_TYPE_SOAP_ENV__Header
#define SOAP_TYPE_SOAP_ENV__Header (29)
/* SOAP Header: */
struct SOAP_ENV__Header
{
#ifdef WITH_NOEMPTYSTRUCT
private:
char dummy; /* dummy member to enable compilation */
#endif
};
#endif
#ifndef SOAP_TYPE_SOAP_ENV__Code
#define SOAP_TYPE_SOAP_ENV__Code (30)
/* SOAP Fault Code: */
struct SOAP_ENV__Code
{
public:
char *SOAP_ENV__Value; /* optional element of type xsd:QName */
struct SOAP_ENV__Code *SOAP_ENV__Subcode; /* optional element of type SOAP-ENV:Code */
};
#endif
#ifndef SOAP_TYPE_SOAP_ENV__Detail
#define SOAP_TYPE_SOAP_ENV__Detail (32)
/* SOAP-ENV:Detail */
struct SOAP_ENV__Detail
{
public:
int __type; /* any type of element <fault> (defined below) */
void *fault; /* transient */
char *__any;
};
#endif
#ifndef SOAP_TYPE_SOAP_ENV__Reason
#define SOAP_TYPE_SOAP_ENV__Reason (34)
/* SOAP-ENV:Reason */
struct SOAP_ENV__Reason
{
public:
char *SOAP_ENV__Text; /* optional element of type xsd:string */
};
#endif
#ifndef SOAP_TYPE_SOAP_ENV__Fault
#define SOAP_TYPE_SOAP_ENV__Fault (35)
/* SOAP Fault: */
struct SOAP_ENV__Fault
{
public:
char *faultcode; /* optional element of type xsd:QName */
char *faultstring; /* optional element of type xsd:string */
char *faultactor; /* optional element of type xsd:string */
struct SOAP_ENV__Detail *detail; /* optional element of type SOAP-ENV:Detail */
struct SOAP_ENV__Code *SOAP_ENV__Code; /* optional element of type SOAP-ENV:Code */
struct SOAP_ENV__Reason *SOAP_ENV__Reason; /* optional element of type SOAP-ENV:Reason */
char *SOAP_ENV__Node; /* optional element of type xsd:string */
char *SOAP_ENV__Role; /* optional element of type xsd:string */
struct SOAP_ENV__Detail *SOAP_ENV__Detail; /* optional element of type SOAP-ENV:Detail */
};
#endif
/******************************************************************************\
* *
* Typedefs *
* *
\******************************************************************************/
#ifndef SOAP_TYPE__QName
#define SOAP_TYPE__QName (5)
typedef char *_QName;
#endif
#ifndef SOAP_TYPE__XML
#define SOAP_TYPE__XML (6)
typedef char *_XML;
#endif
#ifndef SOAP_TYPE_xsd__string
#define SOAP_TYPE_xsd__string (9)
typedef std::string xsd__string;
#endif
/******************************************************************************\
* *
* Externals *
* *
\******************************************************************************/
#endif
/* End of soapStub.h */
|
32f71faae3e37c773a578f7e40d0e85d36471d28 | ce86401672dc6ddbe6552de3d05630418c869a68 | /classify.cpp | e25a62185fed5136d177ce638a400188932be1b7 | [] | no_license | jbasta/codesnippets | 829e0a09045c3086ab74e851f527969d2597d7ad | 9068ce0b5b34a70bcf2f1763ea0b81dda35f4828 | refs/heads/master | 2023-07-12T02:50:51.998064 | 2021-08-05T18:38:18 | 2021-08-05T18:38:18 | 298,416,919 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,952 | cpp | classify.cpp | #include <map>
#include <string>
#include <iostream>
#include <set>
#include <utility>
#include <math.h>
#include "csvstream.h"
using namespace std;
class Label {
public:
Label();
private:
int numWLabel;
};
class Post {
public:
//returns set of unique words
std::set<string> getWords() {
return uniqueWords;
}
//adds word to set if word is not already in there
void addWords(string content) {
ogContent = content;
stringstream ss(content);
string in;
while (ss >> in) {
uniqueWords.insert(in);
}
}
void setCorrectLabel(string label) {
correctLabel = label;
}
string getCorrectLabel() {
return correctLabel;
}
string getOgContent() {
return ogContent;
}
void setProb(double probability) {
prob = probability;
}
double getProbability() {
return prob;
}
private:
std::set<string> uniqueWords;
string correctLabel;
string ogContent;
double prob;
};
class Classifier {
public:
Classifier(string train_file, string test_file, bool buggy) : totalPosts(0),
tester(test_file), trainer(train_file), bug(buggy) { };
bool train() {
map<string, string> junk;
string sendToPost;
vector<Post> localVector;
try {
csvstream csv_train(trainer);
while (csv_train >> junk ) {
auto content = junk.find("content");
auto tag = junk.find("tag");
Post newPost;
newPost.addWords(content->second);
newPost.setCorrectLabel(tag->second);
localVector.push_back(newPost);
junk.clear();
}
} catch (csvstream_exception e) {
cout << e.what() << endl;
return 0;
}
//iterates through local vector to analyze data
for (int i = 0; i < (int)localVector.size(); ++i) {
//current post
Post thisPost = localVector[i];
//current post's unique words
std::set<string> thisPostsWords = thisPost.getWords();
//current post's label
string thisPostsLabel = localVector[i].getCorrectLabel();
//iterates through current post's unique words
for (string w : thisPostsWords) {
//adds words for this post to big list of all unique words
++postWord[w];
//add words to unique words for that post
++(labelPosts[thisPostsLabel])[w];
}
//adds label to label map or increments label count
++label[thisPostsLabel];
}
totalPosts = (int)localVector.size();
uniqueWords = (int)postWord.size();
return 1;
}
double computeLogPrior(string C) {
int numPostsC;
double logPrior;
auto r = label.find(C);
numPostsC = r->second;
logPrior = log((double)numPostsC / totalPosts);
return logPrior;
}
double computeLogLike(string w, string C) {
double numPostsC;
double numWordC;
double logLike;
auto i = labelPosts.find(C);
auto q = (i->second).find(w);
if (q == (i->second).end()) {
numWordC = 0;
}
else {
numWordC = q->second;
}
auto r = label.find(C);
numPostsC = r->second;
auto l = postWord.find(w);
if (numWordC == 0 && l == postWord.end()) {
logLike = log(1.0 / totalPosts);
}
else if (numWordC == 0 && l != postWord.end()) {
logLike = log((double)l->second / (double)totalPosts);
}
else {
logLike = log((double)numWordC / numPostsC);
}
return logLike;
}
//needs to have builder for Post object set
bool buildPosts() {
map<string, string> junk;
string sendToPost;
try {
csvstream csv_test(tester);
while (csv_test >> junk ) {
auto content = junk.find("content");
auto tag = junk.find("tag");
Post newPost;
newPost.addWords(content->second);
newPost.setCorrectLabel(tag->second);
testPosts.push_back(newPost);
junk.clear();
}
} catch (csvstream_exception e) {
cout << e.what() << endl;
return 1;
}
return 0;
}
//Function that takes in a post object and label to compute likelihood of
//that label given that post
//"computeLikelihood"
double computeProbability(Post myPost, string label) {
set<string> words = myPost.getWords();
double sum = computeLogPrior(label);
for(auto i : words) {
sum += computeLogLike(i, label);
}
return sum;
}
//calls function computeLikelihood, then takes the max of those results to
//return prediction,
//let's call it "computePrediction"
string computePrediction(Post &myPost) {
double max = -10000000;
string prediction = "error";
for (auto i : label) {
double llHood = computeProbability(myPost, i.first);
if (llHood > max) {
max = llHood;
prediction = i.first;
}
}
myPost.setProb(max);
return prediction;
}
//calls "computePrediction" on each post object in vector and prints out
//prediction
bool testData() {
int numCorrect = 0;
if (buildPosts()) {
return 0;
}
if (bug == true) {
debug();
}
else {
cout << "trained on " << totalPosts << " examples" << endl;
}
cout << endl;
if (bug == true) {
cout << "classes:" << endl;
for (auto i : label){
cout << " " << i.first << ", " << i.second
<< " examples, log-prior = " << computeLogPrior(i.first)
<< endl;
}
cout << "classifier parameters:" << endl;
for (auto i : labelPosts) {
for (auto w : i.second) {
cout << " " << i.first << ":" << w.first << ", count = " <<
w.second << ", log-likelihood = " <<
computeLogLike(w.first, i.first) << endl;
}
}
cout << endl;
}
cout << "test data:" << endl;
for (int i = 0; i < (int)testPosts.size(); ++i) {
string correctLabel = testPosts[i].getCorrectLabel();
string myLabel = computePrediction(testPosts[i]);
double logProb = testPosts[i].getProbability();
cout << " correct = " << correctLabel << ", predicted = "
<< myLabel << ", log-probability score = "
<< logProb << endl;
cout << " content = " << testPosts[i].getOgContent() << endl
<< endl;
if (correctLabel == myLabel) numCorrect++;
}
cout << "performance: " << numCorrect << " / " << testPosts.size() <<
" posts predicted correctly" << endl;
return 1;
}
void debug() {
csvstream csv_train(trainer);
cout << "training data:" << endl;
map<string, string> row;
while (csv_train >> row) {
string key = row["tag"];
string content = row["content"];
cout << " label = " << key << ", content = " << content << endl;
}
cout << "trained on " << totalPosts << " examples" << endl;
cout << "vocabulary size = " << uniqueWords << endl;
}
private:
int totalPosts;
int uniqueWords;
map<string, int> postWord;
map<string, int> label;
map<string, vector<string> > wordsInLabel;
//first is lable, second is a map of unique words in that label and num
//occurrences
map<string, map<string, int > > labelPosts;
string tester;
string trainer;
bool bug;
vector<Post> testPosts;
};
int printError();
int main (int argc, char ** argv) {
cout.precision(3);
string trainFile = argv[1];
string testFile = argv[2];
bool bug = false;
string debug;
if (argc == 4) debug = argv[3];
if (argc < 3 || argc > 4) {
printError();
}
if (argc == 4 && debug != "--debug") {
printError();
}
if (argc == 4) {
bug = true;
}
Classifier classify(trainFile, testFile, bug);
if (!classify.train()) {
return 1;
}
if (!classify.testData()) {
return 1;
}
}
int printError() {
cout << "Usage: main.exe TRAIN_FILE TEST_FILE [--debug]" << endl;
return 1;
}
|
eb616a80d2010cba45dbd02c2e01699e9193e5e4 | f845a87f3a58d6fef5af9d8f391e7df3e15a4c25 | /159.cpp | 9fc84f98425f239a526db74dc2b54da4df935b8f | [
"MIT"
] | permissive | jinxinwangstd/LeetCode | 352f5ef7a81e33c9a9434f25a3653be5944a30ca | c8d09e86cee52648f84ca2afed8dd0f13e51ab58 | refs/heads/master | 2022-04-03T12:52:45.079347 | 2022-03-26T16:39:35 | 2022-03-26T16:39:35 | 173,209,742 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 993 | cpp | 159.cpp | #include <bits/stdc++.h>
using namespace std;
using ull = uint64_t;
using ll = int64_t;
using ld = long double;
typedef vector<int> vi;
typedef pair<int, int> ii;
typedef vector<ii> vii;
class Solution
{
public:
int lengthOfLongestSubstringTwoDistinct(string s)
{
map<char, int> record;
int ret = 0, num = s.size();
int start = 0, end = 0;
while (end < num)
{
char c = s[end];
if (record.count(c))
{
record[c] = end;
}
else
{
if (record.size() < 2)
{
record[c] = end;
}
else
{
ret = max(ret, end - start);
char removed;
int new_start = INT_MAX;
for (map<char, int>::iterator iter = record.begin(); iter != record.end(); ++iter)
{
if (iter->second < new_start)
{
new_start = iter->second;
removed = iter->first;
}
}
start = new_start + 1;
record.erase(removed);
record[c] = end;
}
}
end++;
}
ret = max(ret, end - start);
return ret;
}
};
|
3ae281ebb2d1b0f64dde5b153bc4679ad30b1915 | 97e6a86106c611ccaa4724c7f2b0a03da7bbcdd3 | /server/tables/EmployeeQuestTable.cpp | b4673a61dcfec847b6f8fb577d6324d59fc9bb21 | [] | no_license | daxingyou/mlbb | 69ac11a7cc5928a82de10163e8c454bc5c24bb78 | f2d1cba16f7800a2d2914f87bb42ea5ed45f42a1 | refs/heads/master | 2022-02-26T12:01:03.782205 | 2019-09-02T06:26:02 | 2019-09-02T06:26:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,892 | cpp | EmployeeQuestTable.cpp | #include "config.h"
#include "CSVParser.h"
#include "itemtable.h"
#include "EmployeeQuestTable.h"
std::map<int32,std::vector<int32> > EmployeeSkill::data_;
bool EmployeeSkill::load(char const* fn){
if(NULL == fn)
SRV_ASSERT(0);
if(strlen(fn) == 0)
SRV_ASSERT(0);
ACE_DEBUG( ( LM_INFO, ACE_TEXT("Loading from file \"%s\"...\n"), fn ) );
CSVParser csv;
if(csv.load_table_file(fn) == false)
{
SRV_ASSERT(0);
}
if(csv.get_records_counter() == 0)
SRV_ASSERT(0);
for(size_t row=0; row<csv.get_records_counter(); ++row){
int32 skillId = csv.get_int(row,"SkillID");
SRV_ASSERT(data_.find(skillId)==data_.end());
data_[skillId].resize(EKT_Max);
for (int32 ekt=EKT_GroupDamage; ekt < EKT_Max; ++ekt){
int32 n = csv.get_int(row,ENUM(EmployeeSkillType).getItemName(ekt));
data_[skillId][ekt] = n;
}
}
return true;
}
int32 EmployeeSkill::getRestrain(int32 skillId, EmployeeSkillType type){
if(data_.find(skillId) == data_.end())
return 0;
if(type < 0 || type >= data_[skillId].size() ){
return 0;
}
return data_[skillId][type];
}
std::map<int32, EmployeeMonster*> EmployeeMonster::data_;
bool EmployeeMonster::load(char const* fn){
if(NULL == fn)
SRV_ASSERT(0);
if(strlen(fn) == 0)
SRV_ASSERT(0);
ACE_DEBUG( ( LM_INFO, ACE_TEXT("Loading from file \"%s\"...\n"), fn ) );
CSVParser csv;
if(csv.load_table_file(fn) == false)
{
SRV_ASSERT(0);
}
if(csv.get_records_counter() == 0)
SRV_ASSERT(0);
for(size_t row=0; row<csv.get_records_counter(); ++row){
int32 id = csv.get_int(row,"ID");
SRV_ASSERT(data_.find(id)==data_.end());
EmployeeMonster *p = new EmployeeMonster();
SRV_ASSERT(p);
p->id_ = id;
std::string strSkill = csv.get_string(row,"Skill");
if(!strSkill.empty()){
std::vector<std::string> vStrSkill = String::Split(strSkill,";");
for(size_t i=0; i<vStrSkill.size(); ++i){
if(vStrSkill[i].empty())
continue;
int32 iType = ENUM(EmployeeSkillType).getItemId(vStrSkill[i]);
SRV_ASSERT(iType!=-1);
SRV_ASSERT(iType >= EKT_GroupDamage);
SRV_ASSERT(iType < EKT_Max);
p->skills_.push_back((EmployeeSkillType)iType);
}
}
data_[id] = p;
}
return true;
}
EmployeeMonster const* EmployeeMonster::find(int32 id){
return data_[id];
}
std::vector< std::vector<int32> > EmployeeQuest::colors_;
std::map<int32, EmployeeQuest*> EmployeeQuest::data_;
bool EmployeeQuest::load(char const* fn){
if(NULL == fn)
SRV_ASSERT(0);
if(strlen(fn) == 0)
SRV_ASSERT(0);
ACE_DEBUG( ( LM_INFO, ACE_TEXT("Loading from file \"%s\"...\n"), fn ) );
CSVParser csv;
if(csv.load_table_file(fn) == false)
{
SRV_ASSERT(0);
}
if(csv.get_records_counter() == 0)
SRV_ASSERT(0);
colors_.resize(EQC_Max);
for(size_t row=0; row<csv.get_records_counter(); ++row){
int32 id = csv.get_int(row,"EQID");
SRV_ASSERT(data_.find(id)==data_.end());
EmployeeQuest*p = new EmployeeQuest();
p->id_ = id;
{
std::string strMonsters = csv.get_string(row,"EmployeeMonster");
if(!strMonsters.empty()){
std::vector<std::string> vStrMonsters = String::Split(strMonsters,";");
for(size_t i=0; i<vStrMonsters.size(); ++i){
if(vStrMonsters[i].empty()){
continue;
}
p->monsters_.push_back(atoi(vStrMonsters[i].c_str()));
}
}
SRV_ASSERT(!(p->monsters_.empty()));
}
{
std::string strEmployeeQuestColor = csv.get_string(row,"EmployeeQuestColor");
SRV_ASSERT(!strEmployeeQuestColor.empty());
int32 iEmployeeQuestColor = ENUM(EmployeeQuestColor).getItemId(strEmployeeQuestColor);
SRV_ASSERT(iEmployeeQuestColor != -1);
SRV_ASSERT(iEmployeeQuestColor >= EQC_White);
SRV_ASSERT(iEmployeeQuestColor < EQC_Max);
p->color_ = (EmployeeQuestColor)iEmployeeQuestColor;
}
p->timeRequier_ = csv.get_float(row,"TimeRequier") * 60 * 60;
SRV_ASSERT(p->timeRequier_ > 0);
p->employeeRequier_ = csv.get_int(row,"EmployeeRequier");
SRV_ASSERT(p->employeeRequier_ > 0);
p->successRate_ = csv.get_int(row,"SuccessRate");
SRV_ASSERT(p->successRate_ >= 0);
{
int32 itemId = csv.get_int(row,"award1");
if(itemId != 0){
p->rewards_.push_back(itemId);
}
}
{
int32 itemId = csv.get_int(row,"award2");
if(itemId != 0){
p->rewards_.push_back(itemId);
}
}
{
int32 itemId = csv.get_int(row,"award3");
if(itemId != 0){
p->rewards_.push_back(itemId);
}
}
SRV_ASSERT(!(p->rewards_.empty()));
p->cost_ = csv.get_int(row,"cost");
data_[id] = p;
colors_[p->color_].push_back(id);
}
return true;
}
bool EmployeeQuest::check(){
for(std::map<int32, EmployeeQuest*>::iterator i=data_.begin(); i!=data_.end(); ++i){
for(size_t j=0; j<i->second->monsters_.size(); ++j){
SRV_ASSERT(EmployeeMonster::find(i->second->monsters_[j]));
}
for(size_t j=0; j<i->second->rewards_.size(); ++j){
SRV_ASSERT(ItemTable::getItemById(i->second->rewards_[j]));
}
}
return true;
} |
33c8581f97e17d3de749a823284ec12b26e273e4 | a8628ff4113c7c919a85b1c1e81d16f018377210 | /2017-11-13-final-submission/ex1.cpp | e32d990f103fe038bc6a4686b27aff07ccb042e5 | [
"LicenseRef-scancode-public-domain",
"CC0-1.0"
] | permissive | gnanakeethan/cpp | 1429546149be31ec774a63da7212752ac2775e51 | 51f779d9981eb4644f6a5e6e923ba68585be7988 | refs/heads/master | 2021-01-15T23:59:16.032719 | 2017-11-18T00:57:16 | 2017-11-18T00:57:16 | 99,944,861 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,255 | cpp | ex1.cpp | #include <iostream>
#include <iomanip>
using namespace std;
void inputValues(double&,double&,double&,int);
double calculateSubtotal(double,double);
void printOutput(double[],double[],double[],double[]);
const int items=5;
const int width=80;
int main(){
//defining arrays for storing values for items
double qtyArray[items]={},priceArray[items]={},subTotals[items]={},discountArray[items]={};
// temporary placeholder for quantity,price,and discount
double qty=0.0,price=0.0,disc=0.0;
for(int i=0; i<items;i++){
inputValues(price, qty, disc, i+1);
//appending values to arrays
subTotals[i] = calculateSubtotal(price,qty);
qtyArray[i] = qty;
priceArray[i] = price;
discountArray[i]= disc;
}
printOutput(subTotals,qtyArray,priceArray,discountArray);
return 0;
}
void inputValues(double &price, double &qty,double &discount, int i){
cout << "Enter Price of the Item " <<i<<":";
cin >> price;
cout << "Enter Quantity for the Item "<<i<<":";
cin >> qty;
cout << "Enter Discount for the Item "<<i<<":";
cin >> discount;
}
double calculateSubtotal(double price,double qty){
double total = 0.0;
total = price*qty;
return total;
}
void printOutput(double subTotals[], double qtyArray[], double priceArray[], double discountArray[]){
// final calculation values
double discount = 0.0,total=0.0,itemDiscount=0.0,payable=0.0;
// discount values
double discountValues[]={};
//prints dashes to a variable width
cout << setfill('-') << setw(width) << "" << endl;
//prints the title of table
cout << setw(3) << setfill(' ')<< setiosflags(ios::left) << "ITEM" << setw(10) << setiosflags(ios::right)<< "PRICE" << setw(10) << "QTY" << setw(16) << "SubTotal"<< setw(16) << "DISCOUNT" << setw(24) << "AMOUNT" << endl;
//prints dashes to a variable width
cout << setfill('-') << setw(width) << "" << endl;
for (int i=0;i<items;i++){
total += subTotals[i];
itemDiscount = discountArray[i]*subTotals[i]/100;
discount += itemDiscount;
payable += subTotals[i]-itemDiscount;
// printing each column in the table with a preset width
cout << setw(3) << setfill('0') << i+1 << ".";
cout << setw(10) << setfill(' ') << setiosflags(ios::fixed) << setprecision(2) << priceArray[i];
cout << setw(10) << setiosflags(ios::fixed) << setprecision(2) << qtyArray[i];
cout << setw(16) << setiosflags(ios::fixed) << setprecision(2) << subTotals[i];
cout << setw(16) << setiosflags(ios::fixed) << setprecision(2) << itemDiscount;
cout << "(" << setw(5) << setfill(' ') << discountArray[i] <<"%)";
cout << setw(16) << setfill(' ') << setiosflags(ios::fixed) << setprecision(2) << subTotals[i]-itemDiscount <<endl;
}
cout << setfill('-') << setw(width) << "" << endl;
cout << setfill(' ') << "TOTALS " << setw(33) << setiosflags(ios::right) << total;
cout << setw(16) << setiosflags(ios::right) << discount;
cout << setw(24) << setiosflags(ios::right) << payable << endl;
cout << setfill('-') << setw(width) << "" << endl;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.