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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
841115a51c67c70793a991c3a74466f1d44fe7c4 | 6e882a3a0819b6257f602058b3913cf65376668a | /CNK/samsung/02_16234_main.cpp | 0223d78de4fc752582381338eef28c39a3d84c8c | [] | no_license | hyperpace/study_algo_gangnam | 79e4ffda3306cdd2d7572bd722a5b5ece5469eb5 | 34b017bcd68c67fffcae85a14a17baa4f2e4eb74 | refs/heads/master | 2021-06-12T12:37:31.694167 | 2021-03-20T09:58:54 | 2021-03-20T09:58:54 | 164,384,323 | 0 | 5 | null | 2021-03-20T09:58:54 | 2019-01-07T05:50:18 | Jupyter Notebook | UTF-8 | C++ | false | false | 2,391 | cpp | 02_16234_main.cpp | /*
인구 이동
https://www.acmicpc.net/problem/16234
*/
#include <algorithm>
#include <iostream>
#include <stack>
using namespace std;
int flag_val[2501];
int directions[4][2] = {{0, 1}, {0, -1}, {-1, 0}, {1, 0}};
int diff(int num1, int num2) {
if (num1 > num2)
return num1 - num2;
else
return num2 - num1;
}
void assign_arr(int n, int flag_num, int **arr, int **check) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
arr[i][j] = flag_val[check[i][j]];
}
}
}
int solve(int x, int y, int n, int l, int r, int flag_num, int **arr,
int **check) {
stack<pair<int, int>> stk;
int tot = arr[x][y];
int cnt = 1;
check[x][y] = flag_num;
stk.push(make_pair(x, y));
while (!stk.empty()) {
int idx_x = stk.top().first;
int idx_y = stk.top().second;
stk.pop();
for(int i = 0; i < 4; i++) {
int j = idx_x + directions[i][0];
int k = idx_y + directions[i][1];
if(0 <= j && j < n && 0 <= k && k < n && check[j][k] == 0) {
int diff_num = diff(arr[idx_x][idx_y], arr[j][k]);
if (diff_num >= l && diff_num <= r) {
tot += arr[j][k];
cnt++;
check[j][k] = flag_num;
stk.push(make_pair(j, k));
}
}
}
}
return tot / cnt;
}
int main(int argc, char const *argv[]) {
int n, l, r;
cin >> n >> l >> r;
int **arr = new int *[n];
int **check = new int *[n];
for (int i = 0; i < n; i++) {
arr[i] = new int[n];
check[i] = new int[n];
fill_n(check[i], n, 0);
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> arr[i][j];
}
}
int flag_num = 0;
int cnt = 0;
while (true) {
flag_num = 0;
cnt++;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (check[i][j] == 0) {
flag_num++;
flag_val[flag_num] = solve(i, j, n, l, r, flag_num, arr, check);
}
}
}
assign_arr(n, flag_num, arr, check);
// cout << "cnt :: " << cnt << " flag_num :: " << flag_num << "\n";
// for (int i = 0; i < n; i++) {
// for (int j = 0; j < n; j++) {
// cout << arr[i][j] << " ";
// }
// cout << "\n";
// }
// cout << "\n";
if (flag_num == (n * n)) break;
for (int i = 0; i < n; i++) {
fill_n(check[i], n, 0);
}
}
cout << cnt - 1;
return 0;
} |
effb86b2521c923c915406d8b065ebe7aa322f86 | c218f85ea0c3f8be36d733a0466cc1ecc54f5c9b | /Classes/ItemBridgeStartPos.h | 04125618c1edad3902dc4be7df3fe5a6579a0e45 | [] | no_license | chengqian1521/Mario | 0dac856ea32823e481188395a284af01f3a6eaf2 | faad1159208b782d51d6ab7125f589c1d5d2ee32 | refs/heads/master | 2020-12-24T09:38:42.510735 | 2018-05-01T08:23:29 | 2018-05-01T08:23:29 | 73,275,809 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 282 | h | ItemBridgeStartPos.h | #ifndef __ItemBridgeStartPos_H__
#define __ItemBridgeStartPos_H__
#include "Common.h"
#include "Item.h"
class ItemBridgeStartPos :public Item
{
public:
static ItemBridgeStartPos* create(ValueMap& map);
bool init(ValueMap& map);
virtual void collisionCheck(float dt);
};
#endif
|
3e59f1580ff66aff20a50484d506947684823490 | 4f088087a3c3d2745d2a7011ef34dda4f84f1d4f | /language/_template/template_name_resolution1.cpp | 524b47b905425de3f0a3d49e47bbe74fd3c532ae | [] | no_license | krisai/cppandstl | fcd7834da6740304a938e2589798ef9def9069f0 | 90eeb2ba4f59a57b5e4005dd3dde04e9e62856fe | refs/heads/master | 2021-01-23T09:01:28.533694 | 2017-10-08T17:44:20 | 2017-10-08T17:44:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 374 | cpp | template_name_resolution1.cpp | #include <stdio.h>
template <class T> class X
{
public:
void f(typename T::myType* mt) {
mt->p();
}
};
class Yarg
{
public:
struct myType {
void p()
{
printf("%s\n", "asdsadasdasd");
}
};
};
int main()
{
X<Yarg> x;
x.f(new Yarg::myType());
printf("Name resolved by using typename keyword.\n");
} |
72e8118bc046ad871f44dd2ec976e0d45da162ba | 6e8dbcf3a86abfb8f631b222ee910f43623a832e | /week1/Sieve of Eratosthenes.cpp | 8ab2ceb3863d96353694a550d9e960090e3e21fc | [] | no_license | Yegizbayev/Algorithmtracking | 81694bc3581219cff1d5cde9c22cb4e5d06670b2 | e87aeb5fde61ea44677bd30ef9baa3b445360cdf | refs/heads/master | 2021-01-13T13:32:49.851307 | 2016-11-08T05:54:48 | 2016-11-08T05:54:48 | 72,587,438 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 391 | cpp | Sieve of Eratosthenes.cpp | #include <iostream>
#include<algorithm>
using namespace std;
void erotos( int n,int m ){
int i,j;
bool was[m];
for ( i=n; i<=m;i++ )
was[i]=false;
for ( i=n; i<=m; i++ )
{
if ( was[i]==false )
for ( j=i*i; j<=m; j+=i )
{
was[j]=true;
}
}
for ( i=n; i<m; i++ )
{
if ( !was[i] )
cout<<i<<" ";
}
}
int main()
{
int n,m;
cin >>n>>m;
erotos(n,m);
return 0;
}
|
f626b36a7a50b92701b1577e855daf3b1b17739d | cf6e5d4176fcc491de1a4143a1fe662f1eb5ed85 | /src/qt/passion/subscription/subrow.h | 7b92fca5c3732a88d539822668d2486747ea53ba | [
"MIT"
] | permissive | PassionCash/PassionCashCoin | 58b5190a655e8c0643b2df65a48ff3bc362cff4e | 389a2fce7458cb400b900b0e816ed24db90f3c92 | refs/heads/master | 2023-06-03T12:19:19.191633 | 2021-05-08T19:19:15 | 2021-05-08T19:19:15 | 308,874,915 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 664 | h | subrow.h | //Copyright (c) 2021 The PASSION CORE developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef SUBROW_H
#define SUBROW_H
#include <QWidget>
namespace Ui {
class SubRow;
}
class SubRow : public QWidget
{
Q_OBJECT
public:
explicit SubRow(QWidget *parent = nullptr);
~SubRow();
void updateView(QString domain, QString key, QString expire, QString paymentaddress, QString sitefee, QString registeraddress, QString registeraddressbalance, QString status);
Q_SIGNALS:
void onMenuClicked();
private:
Ui::SubRow *ui;
};
#endif // SUBROW_H
|
33bd499e1df59d54a9226b89084eed8e07dbc734 | 7b85d5e9763acde7405d9738bafe82f735ce19a5 | /ScrabbleGame/main_window.h | f103e7c6b58d48adf15c8bd0345a766cff510e85 | [] | no_license | sepoquro/Public-Projects | 808b0b420c577d81467970663503965ac871e3e2 | 0260530647be9bdc32c6fd54ea4162672cf03e4a | refs/heads/master | 2021-01-22T19:48:43.701810 | 2017-05-29T11:31:22 | 2017-05-29T11:31:22 | 85,241,449 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,723 | h | main_window.h | #include <QWidget>
#include <QVBoxLayout>
#include <QLabel>
#include <QLineEdit>
#include <QTextEdit>
#include <QPushButton>
#include <QListWidget>
#include <QSpinBox>
#include <QMessageBox>
#include <string>
#include <vector>
#include "Dictionary.h"
#include "Board.h"
#include "Bag.h"
#include "Player.h"
#include "Tile.h"
class MainWindow : public QWidget
{
Q_OBJECT
public:
MainWindow();
~MainWindow();
void initialize(std::vector<std::string> n, Dictionary* a, Board* b, Bag* c, int nt);
void displayBoard();
private slots:
void place();
void exchange();
void pass();
void position();
void endTurnProcess();
void showPopup();
void postgameReport();
private:
QHBoxLayout* overallLayout;
QGridLayout* boardGridLayout;
QVBoxLayout* boardLayout;
QLabel* playerTurnLabel;
QLabel* directionLabel;
QLabel* positionLabel;
QLabel* scoreboardLabel;
QVBoxLayout* menuLayout;
QVBoxLayout* scoreboardLayout;
QGridLayout* sbPlayersLayout;
QVBoxLayout* actionLayout;
QGridLayout* tilesLayout;
QHBoxLayout* buttonsLayout;
QLineEdit* tileInput;
QPushButton* placeButton;
QPushButton* exchangeButton;
QPushButton* passButton;
std::vector <QPushButton*> playerTiles;
std::vector < std::vector<QPushButton*> > boardButtons;
std::vector <QLabel*> nameLabels;
std::vector <QLabel*> scoreLabels;
int numPlayers;
std::vector<std::string> names;
std::vector<int> scores;
Dictionary* dict;
Board* board;
Bag* bag;
int numTiles;
int startx;
int starty;
std::string msg; //message to display in the message box
//for running the game
std::string dir;
int row;
int col;
int currPlayerNum;
int numPassed;
Player players[8];
std::string command;
bool validPlay;
bool gameOver;
}; |
d164b99d1fa7681ef876e4b2a0777a6be8972be8 | d5328e2f5c2817cf8e558119f7084528a9ab75eb | /src/Common/Errors.cpp | 2598db91125cd4591d8d12da0e9b90c5ba39fe82 | [
"MIT"
] | permissive | arudei-dev/Feral | a0e31517fd809533b5b1b8836c69fb991cf0d1c1 | 44c0254f9f85dbf0f11f8cc1f86dc106f6a16d92 | refs/heads/master | 2023-06-09T11:24:00.851064 | 2021-06-29T13:21:59 | 2021-06-29T13:22:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,055 | cpp | Errors.cpp | /*
MIT License
Copyright (c) 2020 Feral Language repositories
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.
*/
#include "Common/Errors.hpp"
#include <cstdarg>
#include <cstring>
namespace err
{
size_t &code()
{
static size_t ecode = E_OK;
return ecode;
}
size_t &val()
{
static size_t _val = 0;
return _val;
}
std::string &str()
{
static std::string estr = "";
return estr;
}
void set(const size_t &err_code, const size_t &err_val, const char *msg, ...)
{
static char err[2048];
memset(err, 0, sizeof(err));
va_list vargs;
va_start(vargs, msg);
vsprintf(err, msg, vargs);
va_end(vargs);
code() = err_code;
val() = err_val;
str() = std::string(err);
}
} // namespace err
|
e88cc1c6a0fe56b37ff7454ac56b0a44310e454f | 82a2be8e2f9ee82aae96d0a82bf77aa1a4db3a46 | /plugins/Substance/Source/SubstanceCore/Private/SubstanceCallbacks.h | 86b4aa0885c9cb986df6cdf243bf1c3e5cce51cd | [] | no_license | JoelWaterworth/Mice | 38d35d4a4e9f71b3f5288a8982d326b2c8bd50b4 | c19cf172ee0fe88c2dbdf9e72a8dbb3265b967b4 | refs/heads/master | 2021-09-14T04:04:38.670168 | 2018-05-08T03:42:10 | 2018-05-08T03:42:10 | 106,102,739 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,445 | h | SubstanceCallbacks.h | // Copyright 2016 Allegorithmic Inc. All rights reserved.
// File: SubstanceCallbacks.h
#pragma once
#include "substance/framework/typedefs.h"
#include "substance/framework/callbacks.h"
namespace Substance
{
class GraphInstance;
class OutputInstance;
struct RenderCallbacks : public SubstanceAir::RenderCallbacks
{
public:
/** Call back which is called when a substance has been computed and outputs are ready to be read */
virtual void outputComputed(SubstanceAir::UInt Uid, size_t userData, const SubstanceAir::GraphInstance*, SubstanceAir::OutputInstance*) override;
virtual void outputComputed(SubstanceAir::UInt runUid, const SubstanceAir::GraphInstance* graphInstance, SubstanceAir::OutputInstance* outputInstance) override;
/** Returns the computed outputs from the framework */
TArray<SubstanceAir::OutputInstance*> getComputedOutputs(bool throttleOutputGrab = true);
/** Clears a computed output instance stored within the framework */
void clearComputedOutputs(SubstanceAir::OutputInstance* Output);
/** Clears all computed outputs */
void clearAllComputedOutputs();
/** Checks the queue to determine if more outputs are to be computed */
bool isOutputQueueEmpty()
{
return mOutputQueue.Num() == 0;
}
protected:
/** The queue that stores the OutputInstances */
TArray<SubstanceAir::OutputInstance*> mOutputQueue;
/** Lock for thread safe operations */
FCriticalSection mMutex;
};
}// Substance Namespace
|
18a04a871956486942bc86b9b6f166ac91c2f911 | 06a761b58f775e48aee48aeb372d4d8255e5c7cc | /lib/class_hmr.cpp | fea08198c4b218a8ce1173bc179d50d5935603cc | [] | no_license | zoom1539/pb_hmr | c70e24f93387ca4aefc347236abcd4a6ab6ecf6e | 7bbf8bef39a762c0959a17296625511308d31f62 | refs/heads/master | 2023-07-26T12:24:50.282847 | 2021-08-28T07:44:22 | 2021-08-28T07:44:22 | 377,339,215 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,225 | cpp | class_hmr.cpp | #include "class_hmr.h"
#include "class_hmr_.h"
class HMR::Impl
{
public:
_HMR _hmr;
};
HMR::HMR() : _impl(new HMR::Impl())
{
}
HMR::~HMR()
{
delete _impl;
_impl = NULL;
}
bool HMR::serialize(const std::string &wts_path_, const std::string &engine_path_)
{
return _impl->_hmr.serialize(wts_path_, engine_path_);
}
bool HMR::init(const std::string &engine_path_)
{
return _impl->_hmr.init(engine_path_);
}
bool HMR::run(const std::vector<cv::Mat> &imgs_,
std::vector<std::vector<cv::Vec3f> > &poses_,
std::vector<std::vector<float> > &shapes_)
{
return _impl->_hmr.run(imgs_, poses_, shapes_);
}
bool HMR::init_joints(const std::string &engine_path_, std::string &smpl_male_json_path_)
{
return _impl->_hmr.init_joints(engine_path_, smpl_male_json_path_);
}
bool HMR::run_joints(const std::vector<cv::Mat> &imgs_,
std::vector<std::vector<cv::Vec3f> > &poses_,
std::vector<std::vector<float> > &shapes_,
std::vector<std::vector<cv::Vec3f> > &vec_3djoints_,
std::vector<std::vector<cv::Vec3f> > &vec_vertices_)
{
return _impl->_hmr.run_joints(imgs_,poses_,shapes_, vec_3djoints_, vec_vertices_);
}
|
58e127cbb26c49077c53d22e12489e224390f966 | 3fdd5833b04cd9bd1a9250d582da10727c6600fd | /College projects/Sistemas Interaccion Persona Computador (C++ y Diseño Web)/ReconocimientoGestos/ReconocimientoGestos/MyBGSubtractorColor.cpp | 66d87389be1cc285cc7c632abc9cb96d53005ec1 | [
"MIT"
] | permissive | clooney2007/Dev | b3bbec5cebb01d11717fbcaa41763d5327049bcf | d080e040a2b1205b7b15f5ada82fb759e3cd2869 | refs/heads/master | 2023-03-24T13:47:34.611185 | 2020-07-29T19:32:00 | 2020-07-29T19:32:00 | null | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 3,883 | cpp | MyBGSubtractorColor.cpp | #include "MyBGSubtractorColor.hpp"
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/video/background_segm.hpp>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
using namespace cv;
using namespace std;
MyBGSubtractorColor::MyBGSubtractorColor(VideoCapture vc) {
cap = vc;
max_samples = MAX_HORIZ_SAMPLES * MAX_VERT_SAMPLES;
lower_bounds = vector<Scalar>(max_samples);
upper_bounds = vector<Scalar>(max_samples);
means = vector<Scalar>(max_samples);
h_low = 12;
h_up = 7;
l_low = 30;
l_up = 40;
s_low = 80;
s_up = 80;
namedWindow("Trackbars");
createTrackbar("H low:", "Trackbars", &h_low, 100, &MyBGSubtractorColor::Trackbar_func);
createTrackbar("H high:", "Trackbars", &h_up, 100, &MyBGSubtractorColor::Trackbar_func);
createTrackbar("L low:", "Trackbars", &l_low, 100, &MyBGSubtractorColor::Trackbar_func);
createTrackbar("L high:", "Trackbars", &l_up, 100, &MyBGSubtractorColor::Trackbar_func);
createTrackbar("S low:", "Trackbars", &s_low, 100, &MyBGSubtractorColor::Trackbar_func);
createTrackbar("S high:", "Trackbars", &s_up, 100, &MyBGSubtractorColor::Trackbar_func);
}
void MyBGSubtractorColor::Trackbar_func(int, void*)
{
}
void MyBGSubtractorColor::LearnModel() {
Mat frame, tmp_frame, hls_frame;
std::vector<cv::Point> samples_positions;
cap >> frame;
//almacenamos las posiciones de las esquinas de los cuadrados
Point p;
for (int i = 0; i < MAX_HORIZ_SAMPLES; i++) {
for (int j = 0; j < MAX_VERT_SAMPLES; j++) {
p.x = frame.cols / 2 + (-MAX_HORIZ_SAMPLES / 2 + i)*(SAMPLE_SIZE + DISTANCE_BETWEEN_SAMPLES);
p.y = frame.rows / 2 + (-MAX_VERT_SAMPLES / 2 + j)*(SAMPLE_SIZE + DISTANCE_BETWEEN_SAMPLES);
samples_positions.push_back(p);
}
}
namedWindow("Cubre los cuadrados con la mano y pulsa espacio");
for (;;) {
flip(frame, frame, 1);
frame.copyTo(tmp_frame);
//dibujar los cuadrados
for (int i = 0; i < max_samples; i++) {
rectangle(tmp_frame, Rect(samples_positions[i].x, samples_positions[i].y,
SAMPLE_SIZE, SAMPLE_SIZE), Scalar(0, 255, 0), 2);
}
imshow("Cubre los cuadrados con la mano y pulsa espacio", tmp_frame);
int c = cvWaitKey(40);
if (c == ' ')
{
break;
}
cap >> frame;
}
// CODIGO 1.1
// Obtener las regiones de interés y calcular la media de cada una de ellas
// almacenar las medias en la variable means
// ...
cvtColor(frame, hls_frame, CV_BGR2HLS);
for (int i = 0; i < max_samples; i++) {
Mat roi = hls_frame(Rect(samples_positions[i].x, samples_positions[i].y,
SAMPLE_SIZE, SAMPLE_SIZE));
means[i] = mean(roi);
}
destroyWindow("Cubre los cuadrados con la mano y pulsa espacio");
}
void MyBGSubtractorColor::ObtainBGMask(cv::Mat frame, cv::Mat &bgmask) {
// CODIGO 1.2
// Definir los rangos máximos y mínimos para cada canal (HLS)
// umbralizar las imágenes para cada rango y sumarlas para
// obtener la máscara final con el fondo eliminado
//...
Mat dst;
Mat acc(frame.rows, frame.cols, CV_8U, Scalar(0));
Mat hls_frame;
cvtColor(frame, hls_frame, CV_BGR2HLS);
for (int i = 0; i < max_samples; i++) {
int tmp_h_low = means[i][0] - h_low;
int tmp_h_up = means[i][0] + h_up;
int tmp_l_low = means[i][1] - l_low;
int tmp_l_up = means[i][1] + l_up;
int tmp_s_low = means[i][2] - s_low;
int tmp_s_up = means[i][2] + s_up;
if (tmp_h_low < 0) {
tmp_h_low = 0;
}
if (tmp_l_low < 0) {
tmp_l_low = 0;
}
if (tmp_s_low < 0) {
tmp_s_low = 0;
}
if (tmp_h_up > 255) {
tmp_h_up = 255;
}
if (tmp_s_up > 255) {
tmp_s_up = 255;
}
if (tmp_l_up > 255) {
tmp_l_up = 255;
}
Scalar low(tmp_h_low, tmp_l_low, tmp_s_low);
Scalar up(tmp_h_up, tmp_l_up, tmp_s_up);
cv::inRange(hls_frame, low, up, dst);
acc += dst;
}
acc.copyTo(bgmask);
}
|
9050b11e5405cea98bd728824d62ca3ce330d429 | 9a3f8c3d4afe784a34ada757b8c6cd939cac701d | /InterviewBit/Heaps And Maps/waysToFormMaxHeap.cpp | 69f7f11cba7ad51ae13b7e79293f6ad481937dfa | [] | no_license | madhav-bits/Coding_Practice | 62035a6828f47221b14b1d2a906feae35d3d81a8 | f08d6403878ecafa83b3433dd7a917835b4f1e9e | refs/heads/master | 2023-08-17T04:58:05.113256 | 2023-08-17T02:00:53 | 2023-08-17T02:00:53 | 106,217,648 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,394 | cpp | waysToFormMaxHeap.cpp | /*
*
//*************************************************************Ways to form Max Heap.*****************************************************
https://www.interviewbit.com/problems/ways-to-form-max-heap/
*******************************************************************TEST CASES:************************************************************
//These are the examples I had created, tweaked and worked on.
80
100
20
23
1
7
8
// Time Complexity: O((l^2*k)+logn base l*k). // k=#internal nodes in heap.
// Space Complexity: O((l^2*k)+logn base l*k). // l=mod value.
//********************************************************THIS IS LEET ACCEPTED CODE.***************************************************
*/
//************************************************************Solution 1:************************************************************
//*****************************************************THIS IS LEET ACCEPTED CODE.***********************************************
// Time Complexity: O((l^2*k)+logn base l*k). // k=#internal nodes in heap.
// Space Complexity: O((l^2*k)+logn base l*k). // l=mod value.
// This algorithm is recursion based. To form a Complete Bin. Tree Max. heap of certain size, the structure would be the same, it's just the values
// filling the nodes would be different. Here, we calcualate #nodes in left child and right child, and find #combinations of digits each child
// would contribute recursively and also get #ways to choose values into both childs and multiply these 3 values to get overall #combinations and
// return the result.
// Here, the main issue would arise with overflowing of int values while calcualating factorial values. For that we employ Lucas Theorem, which
// defines method to calculate factorial with mod value.
// The theory is form this post.
// https://www.geeksforgeeks.org/compute-ncr-p-set-2-lucas-theorem/
int nCrModpDP(int n, int r, int p) // Calculates fact. value for each digit in base p/mod representation.
{
int C[r+1];
memset(C, 0, sizeof(C));
C[0] = 1; // Top row of Pascal Triangle
for (int i = 1; i <= n; i++)
{
for (int j = min(i, r); j > 0; j--)
C[j] = (C[j] + C[j-1])%p;
}
return C[r];
}
int nCrModpLucas(int n, int r, int p) // Gets base p/mod repre. of two digits and pass them to calc. fn.
{
if (r==0)
return 1;
int ni = n%p, ri = r%p;
return (nCrModpLucas(n/p, r/p, p) * // Last digits of n and r
nCrModpDP(ni, ri, p)) % p; // Remaining digits
}
long long int comb(int num, int den){ // Fn. to calcualate factorial values.
long long int res=1;
long long int mod=1000000007;
res=nCrModpLucas(num, den, mod);
// cout<<"Inside combi with num: "<<num<<" and den: "<<den<<" val: "<<res<<endl;
return res;
}
long long int formTree(int num){
if(num<=1) return 1;
long int mod=1000000007;
int lt, rt;
int ht=ceil(log2(num+1)); // Height of the tree.
long long int lastRow=pow(2,ht-1); // Max. possible nodes in last row.
long long int lr=num-lastRow+1; // #nodes in last row of this Tree.
// cout<<"ht: "<<ht<<" lastRow: "<<lastRow<<" lr: "<<lr<<endl;
lt=min(lastRow/2,lr)+(lastRow-2)/2; // #nodes in left child.
rt=num-1-lt; // #nodes in right child.
long long int combi=comb(num-1,lt);
// cout<<"num: "<<num<<" and combi: "<<combi<<endl;
long long int res=1;
// cout<<"num: "<<num<<" and lt: "<<lt<<" and rt: "<<rt<<endl;
res=(res*combi)%mod; // Multiply #ways to choose nums. into child.
long long int ltRes=formTree(lt); // #Ways to form Max. Heap with given #elem. in it.
long long int rtRes=formTree(rt);
res=(res*ltRes)%mod; // Multiply #ways obtained from both child.
res=(res*rtRes)%mod;
// cout<<"num: "<<num<<" combi: "<<combi<<" and ltRes: "<<ltRes<<" and rtRes: "<<rtRes<<endl;
// cout<<"Num: "<<num<<" and res: "<<res<<endl;
return res; // Returning #ways to form Max. heap with given #elem in it.
}
int Solution::solve(int num) {
int res=0;
res=formTree(num); // Call fn. to get #ways to form Max. Heap.
return res; // Return the #Ways to form Max. Heap.
}
|
7886174138e7aa8271596ec9b4d2d686cd35f062 | 0149ed842327e3133fc2fe7b49d6ee2e27c22021 | /shared/test/unit_test/gen11/icllp/excludes_gen11_icllp.cpp | e2bdb191e3691b59095f1ce5d9a623d36780eb9a | [
"MIT"
] | permissive | intel/compute-runtime | 17f1c3dd3e1120895c6217b1e6c311d88a09902e | 869e3ec9f83a79ca4ac43a18d21847183c63e037 | refs/heads/master | 2023-09-03T07:28:16.591743 | 2023-09-02T02:04:35 | 2023-09-02T02:24:33 | 105,299,354 | 1,027 | 262 | MIT | 2023-08-25T11:06:41 | 2017-09-29T17:26:43 | C++ | UTF-8 | C++ | false | false | 602 | cpp | excludes_gen11_icllp.cpp | /*
* Copyright (C) 2021-2022 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "shared/test/common/test_macros/hw_test_base.h"
HWTEST_EXCLUDE_PRODUCT(ProductHelperTest, givenProductHelperWhenAskedIfAdditionalMediaSamplerProgrammingIsRequiredThenFalseIsReturned, IGFX_ICELAKE_LP)
HWTEST_EXCLUDE_PRODUCT(ProductHelperTest, givenProductHelperWhenAskedIfInitialFlagsProgrammingIsRequiredThenFalseIsReturned, IGFX_ICELAKE_LP)
HWTEST_EXCLUDE_PRODUCT(ProductHelperTest, givenProductHelperWhenAskedIfReturnedCmdSizeForMediaSamplerAdjustmentIsRequiredThenFalseIsReturned, IGFX_ICELAKE_LP)
|
9bcddbb25f68207233f716e6b68d70ba15feb9a1 | 09f0d4908bb4a5ca51fa617205d789f2a398eb0e | /Freecell/include/PokerCardFreeCell.h | 74f19272383a5b1f5388b78a93052ca068eede98 | [] | no_license | zhous20/memorableAssignments | c9257db29d9ca06991def5e6f4b78fc69f21b5c8 | 7f6c538731cb411d5edc503916ab30cac97ce362 | refs/heads/master | 2023-02-23T14:12:43.847882 | 2021-01-19T06:39:31 | 2021-01-19T06:39:31 | 330,874,912 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,862 | h | PokerCardFreeCell.h | ///
/// \file PokerCardFreeCell.h
/// \author Shengchen Zhou
/// \brief The PokerCardFreeCell module (header)
/// \date 6 Apr 2018
///
#ifndef _POKERCARDFREECELL_H_
#define _POKERCARDFREECELL_H_
#include "PokerCardSeq.h"
class PokerCardPile;
class PokerCardFoundation;
///
/// PokerCardFreeCell type
///
class PokerCardFreeCell {
private:
PokerCardSeq S; ///< The sequence of pokercards
public:
///
/// \brief PokerCardFreeCell constructor
///
PokerCardFreeCell();
///
/// \brief Determine if the input pokercard can be appended to cell
/// \param c The input pokercard
/// \return True for an appendable input pokercard, false if not
///
bool canAppendCard(PokerCard c);
///
/// \brief Append the input pokercard to cell
/// \param c The input pokercard
/// \exception AddCardOp_Illegal if operation is illegal
/// \return True for successful append operation, false if not
///
void appendCard(PokerCard c);
///
/// \brief Obtain the pokercard in cell
/// \exception GetCardOp_Illegal if operation is illegal
/// \return A pokercard
///
PokerCard card();
///
/// \brief Remove the pokercard from cell
/// \exception RemoveCardOp_Illegal if operation is illegal
///
void removeCard();
///
/// \brief Obtain number of cards in cell
/// \return a number
///
unsigned int size();
///
/// \brief Determine if able to move a pokercard to a freecell
/// \param c The input freecell to recieve the pokercard
/// \return True for possible move operation, false if not
///
bool canMoveCard2(PokerCardFreeCell* c);
///
/// \brief Move a pokercard to a freecell
/// \param c The input freecell to recieve the pokercard
/// \return True for successful move operation, false if not
///
bool moveCard2(PokerCardFreeCell* c);
///
/// \brief Determine if able to move a pokercard to a pile
/// \param p The input pile to recieve the pokercard
/// \return True for possible move operation, false if not
///
bool canMoveCard2(PokerCardPile* p);
///
/// \brief Move a pokercard to a pile
/// \param p The input pile to recieve the pokercard
/// \return True for successful move operation, false if not
///
bool moveCard2(PokerCardPile* p);
///
/// \brief Determine if able to move a pokercard to a foundation
/// \param f The input foundation to recieve the pokercard
/// \return True for possible move operation, false if not
///
bool canMoveCard2(PokerCardFoundation* f);
///
/// \brief Move a pokercard to a foundation
/// \param f The input foundation to recieve the pokercard
/// \return True for successful move operation, false if not
///
bool moveCard2(PokerCardFoundation* f);
};
#endif
|
df8eb89407eb97380e1517e7a3d60c4e249e3276 | bfb085fb890f22ed55f575ae42704878afc4a77b | /buble_sort/buble_sort.cpp | f2e5a244edbe2f076f90503c436b67166fa3aadd | [] | no_license | hikarido/sorts | b64af7fecc55f23c2135f99ae8690a18679e568d | 17c32baccec54796ef67669c4f1cb4a9473b0764 | refs/heads/master | 2020-05-28T08:52:20.962122 | 2017-07-11T20:49:06 | 2017-07-11T20:49:06 | 93,986,499 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,630 | cpp | buble_sort.cpp | #include "buble_sort.h"
void buble_sort(int * array, const int size)
{
//int tmp = 0;
for(int i = 0; i < size; i++)
{
for(int j = 0; j < size; j++)
{
if(array[j] > array[i])
{
//tmp = array[i];
//array[i] = array[j];
//array[j] = tmp;
std::swap(array[i], array[j]);
}
}
}
}
int buble_sort_test()
{
qDebug() << "buble sort test start";
const unsigned int size = 10;
const int min = -10;
const int max = 10;
int * array = make_random_array(size, min, max);
if(array == nullptr)
{
qFatal("nullptr from \"make_random_array\"");
}
qDebug() << "unsorted";
print_array(array, size);
buble_sort(array, size);
qDebug() << "sorted";
print_array(array, size);
qDebug() << "buble sort test end";
delete[] array;
return 0;
}
/**
* @brief no_stupid_buble_sort
* j начинает проход с конца масива array
* и декрементируется до текущего положения i,
* тем самым искючая проход по уже отсртированной
* бласти
* @param array
* @param size
*/
void no_stupid_buble_sort(int *array, const int size)
{
for(int i = 0; i < size - 1; i++)
{
for(int j = size - 1; j > i; j--)
{
if(array[i] > array[j])
{
std::swap(array[i], array[j]);
}
}
}
}
int no_stupid_buble_sort_test()
{
const int min = -10;
const unsigned int max = 10;
const unsigned int size = 10;
int * array = make_random_array(size, min, max);
if(array == nullptr)
{
qFatal("nullptr from \"make_random_array\"");
}
qDebug() << "unsorted";
print_array(array, size);
no_stupid_buble_sort(array, size);
qDebug() << "sorted";
print_array(array, size);
qDebug() << "no stupid buble sort test end";
delete[] array;
return 0;
}
void canonical_buble_sort(int *array, const unsigned int size)
{
for(unsigned int i = 0; i < size; i++)
{
for(unsigned int j = size - 1; j > i; j--)
{
if(array[j] < array[j - 1])
{
std::swap(array[j], array[j - 1]);
}
}
}
}
int canonical_buble_sort_test()
{
const int min = -10;
const unsigned int max = 10;
const unsigned int size = 10;
int * array = make_random_array(size, min, max);
if(array == nullptr)
{
qFatal("nullptr from \"make_random_array\"");
}
qDebug() << "unsorted";
print_array(array, size);
canonical_buble_sort(array, size);
qDebug() << "sorted";
print_array(array, size);
qDebug() << "canonical buble sort test end";
delete[] array;
return 0;
}
void shacker_sort(int *array, const unsigned int size)
{
bool was_swapped = false;
unsigned int last_swap_index_forward = 0;
unsigned int last_swap_index_backward = size - 1;
for(unsigned int i = 0; i < size; i++)
{
//forward pass
for(unsigned int j = last_swap_index_backward;
j > i; j--)
{
if(array[j] < array[j-1])
{
std::swap(array[j], array[j-1]);
was_swapped = true;
last_swap_index_forward = j;
}
}
qDebug() << "forward <-";
print_array(array, size);
if(was_swapped == false)
{
return;
}
was_swapped = false;
//backward pass
for(unsigned int j = last_swap_index_forward;
j < size - 1;j++)
{
if(array[j] > array[j+1])
{
std::swap(array[j], array[j+1]);
last_swap_index_backward = j + 1;
was_swapped = true;
}
}
qDebug() << "back ->";
print_array(array, size);
if(was_swapped == false)
{
return;
}
was_swapped = false;
}
}
int shacker_sort_test()
{
qDebug() << "shacker sort test start";
const unsigned int size = 10;
const int min = -10;
const int max = 10;
int * array = make_random_array(size, min, max);
if(array == nullptr)
{
qFatal("nullptr from \"make_random_array\"");
}
qDebug() << "unsorted";
print_array(array, size);
shacker_sort(array, size);
qDebug() << "sorted";
print_array(array, size);
qDebug() << "shacker sort test end";
delete[] array;
return 0;
}
|
7b4186f4be9fd197f1e503c255f8419b42a34fdf | 9d1260f544bda8bf8705ac122bbb8402536502fe | /Source/Game/Asciimon/asciimon_evolver.h | f65da014ec0f3ce1b05f1ac3a01c801975f8b77a | [
"MIT"
] | permissive | Hopson97/ASCIImonClassic | d9cfa47ab20bed589318ee99416fc7cb865b1b99 | a20d0e7272c512434f767d128642a057b5b20ca5 | refs/heads/master | 2022-06-26T10:54:11.326829 | 2018-04-03T12:03:59 | 2018-04-03T12:03:59 | 64,428,967 | 1 | 1 | MIT | 2022-06-18T17:38:31 | 2016-07-28T21:20:25 | C++ | UTF-8 | C++ | false | false | 358 | h | asciimon_evolver.h | #ifndef ASCIIMON_EVOLVER_H
#define ASCIIMON_EVOLVER_H
#include "asciimon.h"
class Asciimon_Evolver
{
public:
Asciimon_Evolver( Asciimon& asciimon, unsigned id );
void evolve ();
private:
Asciimon getEvolvingInto ();
Asciimon& m_asciimon;
unsigned m_evolveIntoId;
};
#endif // ASCIIMON_EVOLVER_H
|
435937a8946692a955647cd550747ade0107e3c9 | b96092a1d83dfbd0543abcd90a45d849b969fd6d | /include/tasks/task.h | 4615ee883b09ea073c9a4aa98566c0bc2dc1d961 | [
"MIT"
] | permissive | wizehun/CNN-on-flash | a022d0282bfd2c3065fd5d95cf31a4fce88af240 | c76c0fd13a7fdb05711662953b7ead741e500c28 | refs/heads/master | 2022-03-26T12:39:48.852812 | 2019-11-26T13:11:16 | 2019-11-26T13:11:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,685 | h | task.h | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
#pragma once
#include <atomic>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "logger.h"
#include "pointers/pointer.h"
namespace flash {
extern std::atomic<FBLAS_UINT> global_task_counter;
// Different states of a Task
enum TaskStatus {
Wait, // task not yet started
AllocReady, // task is ready to be alloc'ed, but not alloc'ed
Alloc, // task has been alloc'ed, but not compute-ready
ComputeReady, // task has been alloc'ed, AND compute-ready
Compute, // task is in compute
Complete // task has finished compute
};
// Task interface
class BaseTask {
protected:
// I/O list
// <ptr, strides, R|W>
std::vector<std::pair<flash_ptr<void>, StrideInfo>> read_list;
std::vector<std::pair<flash_ptr<void>, StrideInfo>> write_list;
std::vector<FBLAS_UINT> parents;
std::unordered_map<flash_ptr<void>, void*, FlashPtrHasher, FlashPtrEq>
in_mem_ptrs;
// Status of Task
std::atomic<TaskStatus> st;
// Continuation
BaseTask* next;
// Unique Task ID
FBLAS_UINT task_id;
public:
BaseTask() {
this->st.store(Wait);
this->next = nullptr;
this->task_id = global_task_counter.fetch_add(1);
}
virtual ~BaseTask() {
}
// NOTE :: Make sure all reads are done
// before invoking ::execute()
virtual void execute() = 0;
void add_read(flash_ptr<void> fptr, StrideInfo& sinfo) {
GLOG_DEBUG("adding read=", std::string(sinfo));
GLOG_ASSERT_LT(sinfo.len_per_stride, ((FBLAS_UINT) 1 << 31)); // ori: 35
this->read_list.push_back(std::make_pair(fptr, sinfo));
}
void add_write(flash_ptr<void> fptr, StrideInfo& sinfo) {
GLOG_DEBUG("adding write=", std::string(sinfo));
GLOG_ASSERT_LT(sinfo.len_per_stride, ((FBLAS_UINT) 1 << 31)); // ori: 35
this->write_list.push_back(std::make_pair(fptr, sinfo));
}
virtual FBLAS_UINT size() = 0;
void add_parent(FBLAS_UINT id) {
this->parents.push_back(id);
}
std::vector<FBLAS_UINT>& get_parents() {
return this->parents;
}
void add_next(BaseTask* nxt) {
this->next = nxt;
}
BaseTask* get_next() {
return this->next;
}
virtual TaskStatus get_status() {
return this->st.load();
}
virtual void set_status(TaskStatus sts) {
this->st.store(sts);
}
FBLAS_UINT get_id() {
return this->task_id;
}
friend class Scheduler;
friend class Cache;
friend class Prioritizer;
};
} // namespace flash
|
97489f82ba41d37105314bec0e81e30bba6be377 | d670e1b3608f3b0d9db3715d3822c28c2db95e06 | /src/roomsfromimage.h | f21b56f05cf0c1065811ee209ee56396bef8f209 | [] | no_license | pdJeeves/MapEditor | d576e5aa2c66e3d59e326454250c309d2c8272c3 | 9309067b4d9b21e0658aeda7c017f2d4cb91a4f5 | refs/heads/master | 2020-07-27T14:28:09.070687 | 2017-04-14T16:50:50 | 2017-04-14T16:50:50 | 77,937,553 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 732 | h | roomsfromimage.h | #ifndef ROOMS_FROM_IMAGE_H
#define ROOMS_FROM_IMAGE_H
#include "verticies.h"
#include "room.h"
class RoomsFromImage
{
static std::list<Verticies> getInverseVerts(const std::list<Verticies> & vertex_data);
static void insertVertex(std::list<Verticies> & vertex_data, uint16_t color, uint16_t color2, int x, int y, int _y);
static std::list<Verticies> GenerateEdges(const QImage & image);
static void optimizeEdges(std::list<Verticies> & vertex_data);
static std::list<Room> getRoomsFromVertexData(std::list<Verticies> vertex_data);
static uint16_t getBottomOfRun(const QImage & image, uint8_t color, uint16_t x, uint16_t y);
public:
static std::list<Room> getRoomsFromImage(const QImage & image);
};
#endif // VERTICIES_H
|
3c0b20082f55aaa43a28eeab9f4555cecf9ab591 | a689ecf7fa37fc4710ee4e95782ecf2a2c86535a | /tirateima.cpp | 9536decd781ed0449fd70c9ee7a8e954af621223 | [] | no_license | GabrielMM123/CodCad | 2fb6d2bd128e106fb69bedddc9e75c06964200d3 | ab2e955cd87cc95a9a49d862a28180f898750494 | refs/heads/master | 2021-09-09T05:30:28.327547 | 2018-03-14T01:20:35 | 2018-03-14T01:20:35 | 125,135,995 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 212 | cpp | tirateima.cpp | #include <iostream>
using namespace std;
int main(){
int x,y;
cin>>x>>y;
if(x < 0 or y < 0 or x > 432 or y > 468){
cout << "Fora";
} else{
cout << "Dentro";
}
}
|
ee980befa83f91e1ca755c7def687413e03811ab | 16b19fde836c7deb9b3d1e50682dbca23e010166 | /50.Manager/09.TileMgr/TileMgr.cpp | 6de24f08dbb1265b8ab56f70da6aa293aec5ed05 | [] | no_license | js7217/Win32API_MapleStory | 8fe898140b5dc7be93405f13dfc3f2f90fc97bc2 | 1aa18cbd608d988a9e0d5195eca8faaed10d67ed | refs/heads/master | 2021-05-19T05:47:33.273520 | 2020-03-31T09:16:36 | 2020-03-31T09:16:36 | 251,553,337 | 2 | 0 | null | null | null | null | UHC | C++ | false | false | 3,442 | cpp | TileMgr.cpp | #include "stdafx.h"
#include "TileMgr.h"
#include "Player.h"
#include "Tile.h"
#include "Scene.h"
#include "SceneMgr.h"
#include "AbstractFactory.h"
IMPLEMENT_SINGLETON(CTileMgr)
CTileMgr::CTileMgr()
{
}
CTileMgr::~CTileMgr()
{
Release();
}
void CTileMgr::TileCollision(CObj* pDst, CScene* pScene)
{
RECT rc = {};
float fMoveX = 0.f, fMoveY = 0.f;
for (auto& rTileObj : m_listTile)
{
int iOption = dynamic_cast<CTile*>(rTileObj)->Get_Option();
if (CheckRect(pDst, rTileObj, &fMoveX, &fMoveY))
{
if (iOption == 0)
{
float x = pDst->Get_Info().fX;
float y = pDst->Get_Info().fY;
if (fMoveX > fMoveY)
{
if (y < rTileObj->Get_Info().fY)
fMoveY *= -1.f;
pDst->Set_Pos(x, y + fMoveY);
}
else
{
if (x < rTileObj->Get_Info().fX)
fMoveX *= -1.f;
pDst->Set_Pos(x + fMoveX, y);
}
}
if (iOption == 1 || iOption == 2)
{
if(CKeyMgr::Get_Instance()->KeyDown(VK_UP))
pScene->Set_Option(iOption);
}
if (iOption == 3)
{
if (CKeyMgr::Get_Instance()->KeyPressing(VK_UP) && pDst->Get_PosY() > rTileObj->Get_PosY())
{
pDst->Set_FrameKey(L"Player_LOPE");
pDst->Set_State(CObj::LOPE);
pDst->Set_Pos(rTileObj->Get_PosX(), pDst->Get_PosY());
dynamic_cast<CPlayer*>(pDst)->Set_Lope(true);
}
if(CKeyMgr::Get_Instance()->KeyPressing(VK_DOWN) && pDst->Get_PosY() < rTileObj->Get_PosY())
{
pDst->Set_FrameKey(L"Player_LOPE");
pDst->Set_State(CObj::LOPE);
pDst->Set_Pos(rTileObj->Get_PosX(), pDst->Get_PosY());
dynamic_cast<CPlayer*>(pDst)->Set_Lope(true);
}
}
}
}
}
bool CTileMgr::CheckRect(CObj * pDst, CObj * pSrc, float * pMoveX, float * pMoveY)
{
float fRadSumX = (pDst->Get_Info().fCX + pSrc->Get_Info().fCX) * 0.2f;
float fRadSumY = (pDst->Get_Info().fCY + pSrc->Get_Info().fCY) * 0.5f;
float fDistX = fabs(pDst->Get_Info().fX - pSrc->Get_Info().fX);
float fDistY = fabs(pDst->Get_Info().fY - pSrc->Get_Info().fY);
if (fRadSumX >= fDistX && fRadSumY >= fDistY)
{
*pMoveX = fRadSumX - fDistX;
*pMoveY = fRadSumY - fDistY;
return true;
}
return false;
}
void CTileMgr::Initialize()
{
}
void CTileMgr::Update()
{
}
void CTileMgr::LateUpdate()
{
}
void CTileMgr::Render(HDC hDC)
{
for (auto& pTile : m_listTile)
pTile->Render(hDC);
}
void CTileMgr::Release()
{
for_each(m_listTile.begin(), m_listTile.end(), Safe_Delete<CObj*>);
m_listTile.clear();
}
void CTileMgr::LoadData(TCHAR * pSaveKey)
{
HANDLE hFile = CreateFile(pSaveKey, GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (INVALID_HANDLE_VALUE == hFile)
{
//MessageBox(g_hWnd, L"실패!", L"로드 실패창!", MB_OK);
return;
}
INFO tInfo = {};
int iDrawID = 0, iOption = 0;
DWORD dwByte = 0;
while (true)
{
ReadFile(hFile, &tInfo, sizeof(INFO), &dwByte, nullptr);
ReadFile(hFile, &iDrawID, sizeof(int), &dwByte, nullptr);
ReadFile(hFile, &iOption, sizeof(int), &dwByte, nullptr);
if (0 == dwByte)
break;
CObj* pTile = CAbstractFactory<CTile>::Create(tInfo.fX, tInfo.fY);
dynamic_cast<CTile*>(pTile)->Set_DrawID(iDrawID);
dynamic_cast<CTile*>(pTile)->Set_Option(iOption);
m_listTile.emplace_back(pTile);
}
CloseHandle(hFile);
//MessageBox(g_hWnd, L"성공!", L"로드 성공창!", MB_OK);
}
|
8edccf18247595d785ae4bd93f72e7614bb54c3f | 83cc38e86db979610d3b07de13a13b728154de65 | /Программирование встроенных систем управления/03_lab/03_lab/07_Keyboard/07_Keyboard.ino | 4d4f5431e046f314075d76050488cbad05427ffd | [] | no_license | Murad255/Sharaga_ | ffa412f0f5ae4dd4cc7f8bec2329e075026389fb | 3ba1ff62c0933b942e6fbbbb370e7e18ee49a682 | refs/heads/master | 2023-04-02T02:28:57.289478 | 2023-03-22T12:44:16 | 2023-03-22T12:44:16 | 178,941,358 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,749 | ino | 07_Keyboard.ino | /*
* Все кнопки подключены к одному аналоговому входу «A0» используя цепочку резисторов, которые выдают разное опорное напряжение для «А0» при нажатии любой кнопки.
* Eсли кнопки не нажаты напряжение на «A0» через резистор R2 (2кОм) будет 5В. Другие резисторы не влияют на схему, а при чтении аналогового вывода «A0» будет
* параметр на верхнем приделе 1023 (или приблизительно). Теперь рассмотрим, что произойдет, если будет нажата кнопка «Вниз». На выводе «А0» будет напряжением,
* которое разделено между резистором R2 (2кОм) которое подтянуто к +5В и резисторами R3 (330ОМ) и R4 (620Ом) общий суммой 950Ом, которые пытаются тянуть его вниз
* к 0В. Напряжения на «A0» будет составлять порядка 1.61В, это означает, что если выполнить команду analogRead () на A0, будет возвращено значение около 306,
* что означает нажатие кнопки «Вниз»
* Напряжением и значение analogRead
* RIGNT: 0.00В: 0 — 8 bit; 0 — 10 bit
* UP: 0.71В: 36 — 8 bit; 145 — 10 bit
* DOWN: 1.61В: 82 — 8 bit; 306 — 10 bit
* LEFT: 2.47В: 126 — 8 bit; 505 — 10 bit
* SELECT: 3.62В: 185 — 8 bit; 741 — 10 bit
*
* Это позволяет сэкономить целый набор выводов и использовать их для более нужного использования.
*/
#include <LiquidCrystal.h> // Подключяем библиотеку
LiquidCrystal lcd( 8, 9, 4, 5, 6, 7 ); // Указываем ноги индикатора
#define NUM_LAB 3 // Номер лабораторной работы
// Функция вывода стартового экрана
// Входной параметр - номер примера
void msgStart(uint8_t ex)
{
Serial.print(F("\n"));
Serial.print(F("Laboratory work "));Serial.println(NUM_LAB);
Serial.print(F("Example "));Serial.println(ex);
Serial.print(F("Build firmware "));Serial.print(__TIME__); Serial.print(" ");Serial.println(__DATE__);
Serial.print(F("Microcontroller frequency [Mhz] "));Serial.println(F_CPU/1000000);
extern int __heap_start, *__brkval;
int v;
int fr = (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
Serial.print(F("Free ram: ")); Serial.println(fr);
Serial.print(F("Start code ----->\n"));
}
void setup()
{
lcd.begin(16, 2); // Инициализируем LCD 16x2
lcd.setCursor(0,0); // Установить курсор на первую строку
lcd.print("LCD1602"); // Вывести текст
lcd.setCursor(0,1); // Установить курсор на вторую строку
lcd.print("Key press"); // Вывести текст
Serial.begin(115200); // Включаем последовательный порт
msgStart(7);
}
void loop() {
int x; // Создаем переменную x
x = analogRead (0); // Задаем номер порта с которого производим считывание
lcd.setCursor(10,1); // Установить курсор на вторую строку
if (x < 100) { // Если x меньше 100 перейти на следующею строк
lcd.print ("Right "); // Вывести текст
Serial.print("Value A0 ‘Right’ is :"); // Вывести текст
Serial.println(x,DEC); // Вывести значение переменной x
}
else if (x < 200) { // Если х меньше 200 перейти на следующию строку
lcd.print ("Up "); // Вывести текст
Serial.print("Value A0 ‘UP’ is :"); // Вывести текст
Serial.println(x,DEC); // Вывести значение переменной x
}
else if (x < 400){ // Если х меньше 400 перейти на следующию строку
lcd.print ("Down "); // Вывести текст
Serial.print("Value A0 ‘Down’ is :"); // Вывести текст
Serial.println(x,DEC); // Вывести значение переменной x
}
else if (x < 600){ // Если х меньше 600 перейти на следующию строку
lcd.print ("Left "); // Вывести текст
Serial.print("Value A0 ‘Left’ is :"); // Вывести текст
Serial.println(x,DEC); // Вывести значение переменной x
}
else if (x < 800){ // Если х меньше 800 перейти на следующию строку
lcd.print ("Select"); // Вывести текст
Serial.print("Value A0 ‘Select’ is :");// Вывести текст
Serial.println(x,DEC); // Вывести значение переменной x
}
}
|
504a29b61480eb58bab81f022879ea8640d3a490 | c2e431f2ea8b7ea819b67e1e81952f0471359721 | /FMCW_Radar/Scripts/RFCalculator/RFCalculator.cpp | 2f3799543e548ec8127fb9a81808993322787b5c | [] | no_license | Matt-Santos/CircuitProjects | 7e2424c1189a85cba6f5b6a18599e68fbac46391 | 5ad0be7a630b01645bea09ae90aade39af1678c3 | refs/heads/master | 2021-09-15T22:38:33.910161 | 2018-06-11T21:36:35 | 2018-06-11T21:36:35 | 115,241,715 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 516 | cpp | RFCalculator.cpp | // Program for RF Reflection Calculations
// Written by Matthew Santos
// ID: 103103503
#include <string>
#include <iostream>
#include <list>
#include <iterator>
using namespace std;
#define MAX_DISTANCE 100 // meters
#define MIN_DISTANCE 1 // meters
#define DISTANCE_INC 0.1 // meters
int main(){
//Create Distance Array
int distance[MAX_DISTANCE];
for (int i=MIN_DISTANCE;i<MAX_DISTANCE;i+DISTANCE_INC){
distance[i]=i;
}
//Get Material Array
//get material properties from spreadsheet file
}
|
270a141d5d022e74e7b8738e85ec350d3b7d5b7b | b219519f94e6c6782f641a5a9d2dcf22537fac3b | /normal/CF/ED_121/C.cpp | 7954c0dc7b6decc784c4655101603dafb3d603b8 | [] | no_license | liangsheng/ACM | 71a37a85b13aa7680a095cf0710c50acb5457641 | 0e80385b51e622b2b97431ac650b8121ecd56e51 | refs/heads/master | 2023-06-01T06:37:51.727779 | 2023-05-14T03:16:18 | 2023-05-14T03:16:18 | 9,337,661 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,391 | cpp | C.cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long LL;
int main() {
// ios::sync_with_stdio(false);
// cin.tie(0);
int T, n;
cin >> T;
while (T--) {
cin >> n;
vector<int> k(n + 1), h(n + 1), L(n + 1), p(n + 1);
for (int i = 1; i <= n; i++) cin >> k[i];
for (int i = 1; i <= n; i++) cin >> h[i];
L[n] = k[n] - h[n] + 1, p[n] = n;
for (int i = n - 1; i >= 1; i--) {
if (k[i] - h[i] + 1 < L[i + 1]) L[i] = k[i] - h[i] + 1, p[i] = i;
else L[i] = L[i + 1], p[i] = p[i + 1];
}
// for (int i = 1; i <= n; i++) {
// printf("i= %d, p[i]= %d, L[i]= %d\n", i, p[i], L[i]);
// }
LL ans = (1LL + h[p[1]]) * h[p[1]] / 2, nowp = p[1], nowh = h[p[1]];
// cout << "ans= " << ans << " nowp= " << nowp << " nowh= " << nowh << '\n';
for (int i = nowp + 1; i <= n; i++) {
// cout << "i= " << i << " " << L[i] << " " << k[nowp] << '\n';
if (L[i] <= k[nowp]) {
int d = k[p[i]] - k[nowp];
ans += (nowh + 1LL + nowh + d) * d / 2;
nowp = p[i], nowh = nowh + d;
} else {
ans += (1LL + h[p[i]]) * h[p[i]] / 2;
nowp = p[i], nowh = h[p[i]];
}
i = p[i];
}
cout << ans << '\n';
}
return 0;
} |
7b9d225fac6940f7ba206bf9f0af8a59b1e87077 | 0d3a8b4082f3d62d3bb406e86dff0747b6d40706 | /include/unirender/vulkan/PipelineCache.h | 2b2bb77372d302bff83fa13122c743fdd4741584 | [
"MIT"
] | permissive | xzrunner/unirender | 8eef1049d1db435650b5e19ef8a2db0d096fbd18 | b6273c560a53650780f0211f7715ebb2467744ab | refs/heads/master | 2022-09-04T16:29:44.001102 | 2022-08-15T22:49:27 | 2022-08-15T22:49:27 | 259,783,656 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 449 | h | PipelineCache.h | #pragma once
#include "unirender/noncopyable.h"
#include <vulkan/vulkan.h>
#include <memory>
namespace ur
{
namespace vulkan
{
class LogicalDevice;
class PipelineCache : noncopyable
{
public:
PipelineCache(const std::shared_ptr<LogicalDevice>& device);
~PipelineCache();
auto GetHandler() const { return m_handle; }
private:
std::shared_ptr<LogicalDevice> m_device = VK_NULL_HANDLE;
VkPipelineCache m_handle;
}; // PipelineCache
}
} |
12210a134a968d7f2e4a7bf2cf81c7c6054ee56f | 8668491d9ed32921de147c093445d48b4166d9f5 | /Lab 6/lab 6.2/Source.cpp | fdbd7b364cde533af1888aed024a6a2c98b1a4af | [] | no_license | ToniPaltus/Labs_Cpp | 8f972ddea6b490cb3347d6a6814694c98a491912 | c2123d3405efc7d7d63057040823c2e5f586fdc4 | refs/heads/main | 2023-08-15T19:59:34.217565 | 2021-10-12T21:11:24 | 2021-10-12T21:11:24 | 416,497,367 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 5,021 | cpp | Source.cpp | /*
* Выполнить задания для текстового и бинарного файлов. Задания выпол-
нить через функции. Размер файлов <= 64GiB.
3. Компоненты файла f – целые числа, четных чисел столько же, сколько нечет-
ных. Получить файл g из чисел исходного файла, в котором не было бы двух со-
седних чисел одинаковой четности.
*/
#include "Functions.h"
int main()
{
setlocale(LC_ALL, "ru");
srand(time(NULL));
bool FLAG_BIN = false;
int size = Rand_even_size();
int max_even = size / 2;
int max_not_even = size / 2;
int count_even = 0;
int count_not_even = 0;
string fileF = "FileF.txt";
ofstream foutF;
foutF.open(fileF);
if (!foutF.is_open())
{
cout << "Ошибка открытия файла F для записи" << endl;
return 1;
}
else
{
//cout << "файл F открыт для записи" << endl;
Recording_in_file(FLAG_BIN, count_even, count_not_even, max_even, max_not_even, foutF);
int difference = count_even - count_not_even;
if (difference > 0)
{
Recording_not_even_values(FLAG_BIN, difference, foutF);
}
if (difference < 0)
{
Recording_even_values(FLAG_BIN, difference, foutF);
}
}
//cout << "Файл F закрыт для записи" << endl;
foutF.close();
ifstream finF_even;
ifstream finF_not_even;
finF_even.open(fileF);
finF_not_even.open(fileF);
if (!finF_even.is_open() && finF_not_even.is_open())
{
cout << "Не удалось открыть файл F для чтения even и not_even" << endl;
return 2;
}
else
{
//cout << "Файл F для чтения even и not_even открыт" << endl;
string fileG = "FileG.txt";
ofstream foutG;
foutG.open(fileG);
if (!foutG.is_open())
{
cout << "Ошибка открытия файла G для записи" << endl;
return 3;
}
else
{
//cout << "Файл G открыт для записи" << endl;
string even = "";
string not_even = "";
int count_even = 0;
int count_not_even = 0;
while (!finF_even.eof() && !finF_not_even.eof())
{
Recording_in_fileG_even(finF_even, even, foutG, count_even);
Recording_in_fileG_not_even(finF_not_even, not_even, foutG, count_not_even);
}
}
//cout << "Файл G закрыт для записи" << endl;
foutG.close();
}
//cout << "Файл F even и not_even закрыт для чтения" << endl;
finF_even.close();
finF_not_even.close();
//__________________________________________________________________________________________________________Bin
count_even = 0;
count_not_even = 0;
FLAG_BIN = true;
string fileBinF = "FileBinF.bin";
ofstream foutBinF(fileBinF, ios::binary);
if (!foutBinF.is_open())
{
cout << "ошибка открытия файла BinF для записи" << endl;
return 1;
}
else
{
//cout << "Файл BinF открыт для записи" << endl;
Recording_in_file(FLAG_BIN, count_even, count_not_even, max_even, max_not_even, foutBinF);
int difference = count_even - count_not_even;
if (difference > 0)
{
Recording_not_even_values(FLAG_BIN, difference, foutBinF);
}
if (difference < 0)
{
Recording_even_values(FLAG_BIN, difference, foutBinF);
}
}
//cout << "Файл BinF закрыт для записи" << endl;
foutBinF.close();
string fileBinG = "FileBinG.bin";
ifstream finBinF_even(fileBinF, ios::binary);
ifstream finBinF_not_even(fileBinF, ios::binary);
ifstream finBinG(fileBinG, ios::binary);
ifstream finBinF(fileBinF, ios::binary);
if (!finBinF_even.is_open() && !finBinF_not_even.is_open())
{
cout << "Ошибка открытия файлов finBinF_even и finBinF_not_even для чтения" << endl;
return 2;
}
else
{
//cout << "Файлы finBinF_even и finBinF_not_even открыты для чтения" << endl;
ofstream foutBinG(fileBinG, ios::binary);
if (!foutBinG.is_open())
{
cout << "Ошибка открытия файла BinG для записи" << endl;
return 3;
}
else
{
//cout << "Файл BinG открыт для записи" << endl;
int Bin_even = 0;
int Bin_not_even = 0;
int Bin_count_even = 0;
int Bin_count_not_even = 0;
while (!finBinF_even.eof() && !finBinF_not_even.eof())
{
Recording_in_fileBinG_even(finBinF_even, Bin_even, foutBinG, Bin_count_even);
Recording_in_fileBinG_not_even(finBinF_not_even, Bin_not_even, foutBinG, Bin_count_not_even);
}
}
//cout << "Файл BinG закрыт для записи" << endl;
foutBinG.close();
}
//cout << "Файлы finBinF_even и finBinF_not_even закрыты для чтения" << endl;
finBinF_even.close();
finBinF_not_even.close();
cout << "fileBinF:" << endl;
Showfile(finBinF, fileBinF);
cout << "\nfileBinG:" << endl;
Showfile(finBinG, fileBinG);
return 0;
} |
f342a9c7aee11f7d76d2bc09433963a96ffb20c4 | cdf54f698b3482862710a2b206dedda52ecc7522 | /src/xor_game.cpp | b9efcdaf743b8a15d7e0ab27e2992bda5873ecbe | [] | no_license | ygshuwu/note | 5bd5758c2740094e509db8e514bf6f600e91799a | 4a8e361eedc3eb5a4a749a5672b7f21f88abeb39 | refs/heads/master | 2020-04-19T09:31:22.289190 | 2019-02-06T16:53:54 | 2019-02-06T16:53:54 | 152,205,535 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 775 | cpp | xor_game.cpp | //leetcode:810
#include <iostream>
#include <vector>
#define N 1500
using namespace std;
vector<bool> tag(N,false);
bool xor_game(vector<int> &num)
{
//1.female first.
//2.assume the initial x=0 and the start is for(int &a:num){x^=a}
//3.if x==0,then female will failed,if x!=0 female always could find two different number and delete one of them because x!=0 could result all elemet is no equal
//4.if x!=0 and num.size()%2!=0.if female delete one number result x=0,then female will failed,if delete one number result x!=0,then male can use stratage 2 it courlf result female failed.
int x=0;
for(int &a:num) x^=a;
return x==0||num.size()%2==0;
}
int main()
{
vector<int> list={3,4,56,4,6,8,7,2,1,3,5,45};
cout<<boolalpha<<xor_game(list)<<endl;
return 0;
}
|
36b532f3bb39468c5b1ed1317a4641f371502ec6 | cdb011163d6bd08c9fd5ad23dbf234636107a28d | /tests/CppUTest/AllocationInCppFile.h | 6246cf13e3dd1e2fb9f772f2d116753deb7f8a74 | [
"BSD-3-Clause"
] | permissive | basvodde/cpputest | 438736398fd39a5847450d31ac1f3d6a120880ce | 52949320d24d61792084a5fed0cc6c8a01fc400c | refs/heads/master | 2022-09-16T05:46:41.855627 | 2022-08-26T14:10:14 | 2022-08-26T14:10:14 | 22,344,404 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 359 | h | AllocationInCppFile.h | #ifndef ALLOCATIONINCPPFILE_H
#define ALLOCATIONINCPPFILE_H
char* newAllocation();
char* newArrayAllocation();
char* newAllocationWithoutMacro();
char* newArrayAllocationWithoutMacro();
#if CPPUTEST_USE_STD_CPP_LIB
class ClassThatThrowsAnExceptionInTheConstructor
{
public:
_no_return_ ClassThatThrowsAnExceptionInTheConstructor();
};
#endif
#endif
|
5a9d007c6a73ab2c26d0aeb5f2d7c86393f163a8 | 97ce80e44d5558cad2ca42758e2d6fb1805815ce | /Source/Foundation/bsfEngine/GUI/BsGUIScrollBarHorz.h | b9d6d1195783b6e17f48def86ee87d1bb9bd6349 | [
"MIT"
] | permissive | cwmagnus/bsf | ff83ca34e585b32d909b3df196b8cf31ddd625c3 | 36de1caf1f7532d497b040d302823e98e7b966a8 | refs/heads/master | 2020-12-08T00:53:11.021847 | 2020-03-23T22:05:24 | 2020-03-23T22:05:24 | 232,839,774 | 3 | 0 | MIT | 2020-01-09T15:26:22 | 2020-01-09T15:26:21 | null | UTF-8 | C++ | false | false | 2,971 | h | BsGUIScrollBarHorz.h | //************************************ bs::framework - Copyright 2018 Marko Pintera **************************************//
//*********** Licensed under the MIT license. See LICENSE.md for full terms. This notice is not to be removed. ***********//
#pragma once
#include "BsPrerequisites.h"
#include "GUI/BsGUIScrollBar.h"
namespace bs
{
/** @addtogroup GUI
* @{
*/
/** Specialization of a GUIScrollBar for horizontal scrolling. */
class BS_EXPORT GUIScrollBarHorz : public GUIScrollBar
{
public:
/** Returns type name of the GUI element used for finding GUI element styles. */
static const String& getGUITypeName(bool resizable);
/**
* Creates a new horizontal scroll bar.
*
* @param[in] styleName Optional style to use for the element. Style will be retrieved from GUISkin of the
* GUIWidget the element is used on. If not specified default style is used.
*/
static GUIScrollBarHorz* create(const String& styleName = StringUtil::BLANK);
/**
* Creates a new horizontal scroll bar.
*
* @param[in] resizeable If true the scrollbar will have additional handles that allow the scroll handle to
* be resized. This allows you to adjust the size of the visible scroll area.
* @param[in] styleName Optional style to use for the element. Style will be retrieved from GUISkin of the
* GUIWidget the element is used on. If not specified default style is used.
*/
static GUIScrollBarHorz* create(bool resizeable, const String& styleName = StringUtil::BLANK);
/**
* Creates a new horizontal scroll bar.
*
* @param[in] options Options that allow you to control how is the element positioned and sized.
* This will override any similar options set by style.
* @param[in] styleName Optional style to use for the element. Style will be retrieved from GUISkin of the
* GUIWidget the element is used on. If not specified default style is used.
*/
static GUIScrollBarHorz* create(const GUIOptions& options, const String& styleName = StringUtil::BLANK);
/**
* Creates a new horizontal scroll bar.
*
* @param[in] resizeable If true the scrollbar will have additional handles that allow the scroll handle to
* be resized. This allows you to adjust the size of the visible scroll area.
* @param[in] options Options that allow you to control how is the element positioned and sized.
* This will override any similar options set by style.
* @param[in] styleName Optional style to use for the element. Style will be retrieved from GUISkin of the
* GUIWidget the element is used on. If not specified default style is used.
*/
static GUIScrollBarHorz* create(bool resizeable, const GUIOptions& options,
const String& styleName = StringUtil::BLANK);
protected:
GUIScrollBarHorz(bool resizeable, const String& styleName, const GUIDimensions& dimensions);
~GUIScrollBarHorz() = default;
};
/** @} */
}
|
d81433dc60e1384d6a72bc6e8448c0dfbf5c3df4 | eb4efd4adf1677568b81624fb46312a6e4d18a6a | /include/rt1w/rng.hpp | c1bdaf364e7811d6750245387b49b24bf48f5fe0 | [
"MIT"
] | permissive | guerarda/rt1w | 61c82c903d0c9184080dff3c7f518b18046dcebc | 2fa13326e0a745214fb1a9fdc49a345c1407b6f3 | refs/heads/master | 2020-09-10T16:59:40.963361 | 2020-05-19T01:18:24 | 2020-05-19T01:18:24 | 67,761,401 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 343 | hpp | rng.hpp | #include "rt1w/sptr.hpp"
constexpr float OneMinusEpsilon_f32 = 0.99999994f;
constexpr double OneMinusEpsilon_f64 = 0.99999999999999989;
struct RNG : Object {
static uptr<RNG> create();
virtual uint32_t u32() = 0;
virtual float f32() = 0;
virtual uint32_t u32(uint32_t bound) = 0;
virtual float f32(float bound) = 0;
};
|
28537f2ffa533ed83a4c8f842a6176449f8a8ddd | dcdbd888828f7d2b4f7cdad0c0bccf812679c22b | /Bankers_Algorithm/Owen_Zachary_Bankers.cc | 475743a50c2843ee684d03b922fee3f812640c09 | [] | no_license | HackyZach/OS-Concepts-CPSC-351 | 2b6b3e469a03b9fb156996fb12304ade97629604 | 8b05e241f9e403964e2af5e714a9420d1bfabde2 | refs/heads/master | 2020-03-19T08:27:59.838241 | 2018-06-07T05:56:41 | 2018-06-07T05:56:41 | 136,206,653 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,130 | cc | Owen_Zachary_Bankers.cc | /*
Owen, Zachary
CPSC 351: OS Concepts
Professor McCarthy
Banker's Algorithm
*/
#include <iostream>
#include <cstdlib>
#include <thread>
#include <mutex>
#include <chrono> // embedded system, real-time
#include <random>
using namespace std;
#define NUMBER_OF_REQUESTS 10
#define NUMBER_OF_RELEASES 5
#define REQUEST_AND_RELEASE_CAPACITY 5
#define NUMBER_OF_CUSTOMERS 5 // value must be >= 0
#define NUMBER_OF_RESOURCES 3 // value must be >= 0
mutex mutualExclude;
mutex releasing;
int available[NUMBER_OF_RESOURCES] = { 0 };
int maximum[NUMBER_OF_CUSTOMERS][NUMBER_OF_RESOURCES] = { 5, 5, 5,
5, 5, 5,
5, 5, 5,
5, 5, 5,
5, 5, 5 };
int allocation[NUMBER_OF_CUSTOMERS][NUMBER_OF_RESOURCES] = { 0 };
int need[NUMBER_OF_CUSTOMERS][NUMBER_OF_RESOURCES] = { 0 };
int request_resources(int customer_num, int request[]);
int release_resources(int customer_num, int release[]);
bool safetyAlgorithm(int customerID, int request[]);
void calculateNeed();
void customer(int customerID, bool req);
void print(int arr[], int size);
void print(int arr[NUMBER_OF_CUSTOMERS][NUMBER_OF_RESOURCES]);
int main(int argc, char* argv[])
{
srand(time(NULL));
/* User passes the amount of instances each resource has as arguments. */
for (int i = 0; i < NUMBER_OF_RESOURCES; i++)
available[i] = atoi(argv[i + 1]);
/* Creates an ID number for all customers. */
int customerID[NUMBER_OF_CUSTOMERS];
for (int id = 0; id < NUMBER_OF_CUSTOMERS; id++)
customerID[id] = id;
/* Sets need = maximum - allocation */
calculateNeed();
thread* customerCall[NUMBER_OF_REQUESTS];
int idNum = 0, requestNum = 0;
while (requestNum < NUMBER_OF_REQUESTS)
{
if (idNum == NUMBER_OF_CUSTOMERS)
idNum = 0;
thread* newThread = new thread(customer, customerID[idNum], true);
/* Store memory location of threads to join main after loop*/
customerCall[requestNum] = newThread;
requestNum++;
idNum++;
}
/* Where threads join parent. */
for (int i = 0; i < NUMBER_OF_REQUESTS; i++)
customerCall[i]->join();
/* Struggled with executing request and release concurrently (so separated). I think I need chapter 5 algorithm to accomplish that. */
printf("\nNow Releasing:\n");
printf("Current Available: ");
print(available, NUMBER_OF_RESOURCES);
printf("Current Allocation:\n");
print(allocation);
thread* customerRelease[NUMBER_OF_RELEASES];
int releaseNum = 0;
idNum = 0;
while (releaseNum < NUMBER_OF_RELEASES)
{
if (idNum == NUMBER_OF_CUSTOMERS)
idNum = 0;
thread* newThread = new thread(customer, customerID[idNum], false);
customerRelease[releaseNum] = newThread;
releaseNum++;
idNum++;
}
for (int i = 0; i < NUMBER_OF_RELEASES; i++)
customerRelease[i]->join();
cout << endl;
system("pause");
return 0;
}
void customer(int customerID, bool req)
{
/* Random number generation*/
random_device rd;
mt19937 mt(rd());
uniform_int_distribution<int> distribution(0, REQUEST_AND_RELEASE_CAPACITY);
/* Creates a customer request and release. */
int request[NUMBER_OF_RESOURCES], release[NUMBER_OF_RESOURCES];
for (int i = 0; i < NUMBER_OF_RESOURCES; i++)
{
request[i] = distribution(mt);
release[i] = distribution(mt);
}
int pass = 0;
/* If requesting or releasing */
if (req)
pass = request_resources(customerID, request);
else
pass = release_resources(customerID, release);
}
int request_resources(int customer_num, int request[]) // Request Algorithm
{
bool pass = true;
int i = 0;
while (pass && i < NUMBER_OF_RESOURCES) { // Step 1
if (request[i] <= need[customer_num][i])
i++;
else
pass = false;
}
if (pass) { // Step 2
i = 0;
while (pass && i < NUMBER_OF_RESOURCES) {
if (request[i] <= available[i])
i++;
else
pass = false;
}
}
if (pass) {
mutualExclude.lock();
if (safetyAlgorithm(customer_num, request)) { // Mutual exclusion to prevent race conditions
for (int resource = 0; resource < NUMBER_OF_RESOURCES; resource++) {
available[resource] -= request[resource];
allocation[customer_num][resource] += request[resource];
need[customer_num][resource] -= request[resource];
}
printf("Request Granted for customer %d: ", customer_num);
print(request, NUMBER_OF_RESOURCES);
printf("Available: ");
print(available, NUMBER_OF_RESOURCES);
printf("Allocation:\n");
print(allocation);
printf("Need:\n");
print(need);
printf("\n");
} else {
printf("Request for customer %d would create an unsafe state: ", customer_num);
print(request, NUMBER_OF_RESOURCES);
pass = false;
}
mutualExclude.unlock();
}
return (pass - 1); // return 0 if granting request, -1 if rejecting.
}
bool safetyAlgorithm(int customerID, int request[])
{
int allocationTest[NUMBER_OF_CUSTOMERS][NUMBER_OF_RESOURCES];
int needTest[NUMBER_OF_CUSTOMERS][NUMBER_OF_RESOURCES];
bool Finish[NUMBER_OF_CUSTOMERS] = { false }; // Step 1: Create work and finish. Let work = available
int work[NUMBER_OF_RESOURCES];
for (int resource = 0; resource < NUMBER_OF_RESOURCES; resource++) { // Pretend by storing into new arrays, so not to modify actual arrays.
work[resource] = available[resource] - request[resource];
for (int customer = 0; customer < NUMBER_OF_CUSTOMERS; customer++) {
allocationTest[customer][resource] = allocation[customer][resource];
needTest[customer][resource] = need[customer][resource];
}
allocationTest[customerID][resource] += request[resource];
needTest[customerID][resource] -= request[resource];
}
bool unsafe = false, safe = false; // Prepration for Step 2
int idx = 0, amountFreed = 0, prevFreed = 0;
bool needLessThanWork = true;
while (!unsafe && !safe) {
if (!Finish[idx]) { // Step 2 a
int numOfInstances = 0;
while (numOfInstances < NUMBER_OF_RESOURCES && needLessThanWork) {
if (needTest[idx][numOfInstances] > work[numOfInstances])
needLessThanWork = false;
else
numOfInstances++;
}
if (needLessThanWork) {
for (int resource = 0; resource < NUMBER_OF_RESOURCES; resource++)
work[resource] += allocationTest[idx][resource];
amountFreed++;
Finish[idx] = true;
}
else
needLessThanWork = true;
}
idx++;
if (amountFreed == NUMBER_OF_CUSTOMERS)
safe = true;
if (idx == NUMBER_OF_CUSTOMERS) { // After checking each process.
idx = 0;
if (amountFreed - prevFreed == 0)
unsafe = true;
prevFreed = amountFreed;
}
}
return safe;
}
int release_resources(int customer_num, int release[])
{
bool releaseLessThanOrEqualToAllocation = true; // Prevents allocation from being less than zero.
int i = 0;
while (releaseLessThanOrEqualToAllocation && i < NUMBER_OF_RESOURCES) {
if (release[i] <= allocation[customer_num][i])
i++;
else
releaseLessThanOrEqualToAllocation = false;
}
if (releaseLessThanOrEqualToAllocation) {
for (int resource = 0; resource < NUMBER_OF_RESOURCES; resource++) {
available[resource] += release[resource];
allocation[customer_num][resource] -= release[resource];
need[customer_num][resource] += release[resource];
}
releasing.lock();
printf("RELEASE Granted for customer %d: ", customer_num);
print(release, NUMBER_OF_RESOURCES);
printf("Available now: ");
print(available, NUMBER_OF_RESOURCES);
printf("Allocation now:\n");
print(allocation);
releasing.unlock();
}
return (releaseLessThanOrEqualToAllocation - 1); // return 0 if granting release. -1 if not.
}
void calculateNeed()
{
for (int customer = 0; customer < NUMBER_OF_CUSTOMERS; customer++) {
for (int resource = 0; resource < NUMBER_OF_RESOURCES; resource++) {
need[customer][resource] = maximum[customer][resource] - allocation[customer][resource];
}
}
}
void print(int arr[], int size)
{
for (int i = 0; i < size; i++){
printf("%d ", arr[i]);
}
printf("\n");
}
void print(int arr[NUMBER_OF_CUSTOMERS][NUMBER_OF_RESOURCES])
{
for (int row = 0; row < NUMBER_OF_CUSTOMERS; row++) {
printf("\t");
for (int col = 0; col < NUMBER_OF_RESOURCES; col++) {
printf("%d ", arr[row][col]);
}
printf("\n");
}
} |
f42f3aeecc0d482c0e97f6b817668f6aab13d2c5 | 507691a83a58d87aae1cabefcad8ab0d5c9434ae | /engine/src/RulesOfGameInstances.cpp | 4319063f75e957343dba1171e0c77a3f5ed2f2da | [] | no_license | VicNumber21/checkers | f17640e9a14a8049fd935705fa258ee3b10d74b4 | e240d82cc2d615b708d91bffad4681a1656f1ded | refs/heads/master | 2021-01-20T07:03:09.258992 | 2012-08-03T16:09:29 | 2012-08-03T16:09:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,257 | cpp | RulesOfGameInstances.cpp | #include "RulesOfGameInstances.h"
#include "AmericanCheckersBoardTraits.h"
#include "AmericanCheckersPositionAnalyser.h"
using namespace Checkers::Engine;
template <class BOARD_TRAITS, class POSITION_ANALYSER>
void RulesOfGameInstanceTemplate<BOARD_TRAITS, POSITION_ANALYSER>::activate()
{
m_objects.reset(new RulesOfGameObjects);
}
template <class BOARD_TRAITS, class POSITION_ANALYSER>
void RulesOfGameInstanceTemplate<BOARD_TRAITS, POSITION_ANALYSER>::deactivate()
{
m_objects.reset();
}
template <class BOARD_TRAITS, class POSITION_ANALYSER>
const BoardTraits & RulesOfGameInstanceTemplate<BOARD_TRAITS, POSITION_ANALYSER>::boardTraits() const
{
throwIfNotActive();
return m_objects->m_board_traits;
}
template <class BOARD_TRAITS, class POSITION_ANALYSER>
PositionAnalyser & RulesOfGameInstanceTemplate<BOARD_TRAITS, POSITION_ANALYSER>::positionAnalyser()
{
throwIfNotActive();
return m_objects->m_position_analyser;
}
template <class BOARD_TRAITS, class POSITION_ANALYSER>
void RulesOfGameInstanceTemplate<BOARD_TRAITS, POSITION_ANALYSER>::throwIfNotActive() const
{
if(!m_objects)
throw RulesOfGameInstanceError();
}
template class RulesOfGameInstanceTemplate<AmericanCheckersBoardTraits, AmericanCheckersPositionAnalyser>;
|
463bdf28d7af1a4a81141239680b5dc6badc0acc | bff3d3026b49eb7bad880f6a8daca12e6ea19c03 | /lena-x2-test.cc | 0659ff724b5653c0c160ba8322cc05202ea05981 | [] | no_license | ahmadhassandebugs/lte_simulation_ns3 | 377765f6044850b3efd87556b66434331cf3fe2b | ccb499e7bd64ffbf53638d653a70bc7eb9f04678 | refs/heads/master | 2022-06-20T09:07:41.427892 | 2019-05-30T12:07:18 | 2019-05-30T12:07:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,181 | cc | lena-x2-test.cc | #include "ns3/core-module.h"
#include "ns3/network-module.h"
#include "ns3/internet-module.h"
#include "ns3/mobility-module.h"
#include "ns3/lte-module.h"
#include "ns3/applications-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/config-store-module.h"
#include "ns3/flow-monitor-helper.h"
#include "ns3/flow-monitor-module.h"
#include "ns3/radio-environment-map-helper.h"
#include <stdlib.h>
#include <fstream>
#include <string>
#include <iostream>
using namespace ns3;
NS_LOG_COMPONENT_DEFINE("LENAX2HANDOVERTEST");
// setup parameters for threshold and cwnd calculations
static bool firstSshThr = true;
static bool firstCwnd = true;
static Ptr<OutputStreamWrapper> ssThreshStream;
static Ptr<OutputStreamWrapper> cWndStream;
static uint32_t ssThreshValue;
static uint32_t cWndValue;
// Flow Monitor Throughput Monitor
void ThroughputMonitor (FlowMonitorHelper *flowHelper, Ptr<FlowMonitor> flowMonitor)
{
std::map<FlowId, FlowMonitor::FlowStats> flowStats = flowMonitor->GetFlowStats();
Ptr<Ipv4FlowClassifier> classing = DynamicCast<Ipv4FlowClassifier> (flowHelper->GetClassifier());
for (std::map<FlowId, FlowMonitor::FlowStats>::const_iterator stats = flowStats.begin (); stats != flowStats.end (); ++stats)
{
Ipv4FlowClassifier::FiveTuple fiveTuple = classing->FindFlow (stats->first);
std::cout<<"Flow ID : " << stats->first <<"; "<< fiveTuple.sourceAddress <<" -----> "<<fiveTuple.destinationAddress<<std::endl;
std::cout<<"Tx Packets = " << stats->second.txPackets<<std::endl;
std::cout<<"Tx Bytes = " << stats->second.txBytes<<std::endl;
std::cout<<"Rx Packets = " << stats->second.rxPackets<<std::endl;
std::cout<<"Rx Bytes = " << stats->second.rxBytes<<std::endl;
std::cout<<"Duration : "<<stats->second.timeLastTxPacket.GetSeconds()-stats->second.timeFirstTxPacket.GetSeconds()<<std::endl;
std::cout<<"Last Received Packet : "<< stats->second.timeLastTxPacket.GetSeconds()<<" Seconds"<<std::endl;
std::cout<<"Lost Packet : "<< stats->second.lostPackets<<std::endl;
std::cout<<"Throughput: " << stats->second.rxBytes*1.0/(stats->second.timeLastRxPacket.GetSeconds()-stats->second.timeFirstRxPacket.GetSeconds()) << " B/s"<<std::endl;
std::cout<<"---------------------------------------------------------------------------"<<std::endl;
}
Simulator::Schedule(Seconds(1.0),&ThroughputMonitor, flowHelper, flowMonitor);
}
static void
CwndTracer (uint32_t oldval, uint32_t newval)
{
if (firstCwnd)
{
*cWndStream->GetStream () << "0.0 " << oldval << std::endl;
firstCwnd = false;
}
*cWndStream->GetStream () << Simulator::Now ().GetSeconds () << " " << newval << std::endl;
cWndValue = newval;
if (!firstSshThr)
{
*ssThreshStream->GetStream () << Simulator::Now ().GetSeconds () << " " << ssThreshValue << std::endl;
}
}
static void
SsThreshTracer (uint32_t oldval, uint32_t newval)
{
if (firstSshThr)
{
*ssThreshStream->GetStream () << "0.0 " << oldval << std::endl;
firstSshThr = false;
}
*ssThreshStream->GetStream () << Simulator::Now ().GetSeconds () << " " << newval << std::endl;
ssThreshValue = newval;
if (!firstCwnd)
{
*cWndStream->GetStream () << Simulator::Now ().GetSeconds () << " " << cWndValue << std::endl;
}
}
static void
TraceCwnd (std::string cwnd_tr_file_name)
{
AsciiTraceHelper ascii;
cWndStream = ascii.CreateFileStream (cwnd_tr_file_name.c_str ());
Config::ConnectWithoutContext ("/NodeList/1/$ns3::TcpL4Protocol/SocketList/0/CongestionWindow", MakeCallback (&CwndTracer));
}
static void
TraceSsThresh (std::string ssthresh_tr_file_name)
{
AsciiTraceHelper ascii;
ssThreshStream = ascii.CreateFileStream (ssthresh_tr_file_name.c_str ());
Config::ConnectWithoutContext ("/NodeList/1/$ns3::TcpL4Protocol/SocketList/0/SlowStartThreshold", MakeCallback (&SsThreshTracer));
}
int main(int argc, char *argv[])
{
LogLevel logLevel = (LogLevel)(LOG_PREFIX_FUNC | LOG_PREFIX_TIME | LOG_LEVEL_ALL);
LogComponentEnable ("EpcX2", logLevel);
LogComponentEnable ("LteUeNetDevice", logLevel);
// LogComponentEnable ("EpcEnbApplication", logLevel);
// Simulation Setup
//uint16_t numberOfNodes = 3;
std::string prefix_file_name = "CalculateCwnd";
uint16_t numberOfUes = 1;
uint16_t numberOfEnbs = 2;
uint16_t numberOfBearersPerUe = 2;
double distance = 400.0;
double speed = 40.0;
double yForUe = 200.0;
double enbTxPowerDbm = 46.0;
//double simTime = 2.000;
double simTime = (double) (numberOfEnbs + 1) * distance / speed;
// Change default attributes so that they are reasonable for our scenario.
Config::SetDefault("ns3::UdpClient::Interval" , TimeValue(MilliSeconds(10)));
Config::SetDefault("ns3::UdpClient::MaxPackets" , UintegerValue(1000000));
Config::SetDefault("ns3::LteHelper::UseIdealRrc" , BooleanValue(false));
// Command line arguments
CommandLine cmd;
cmd.AddValue ("simTime", "Total duration of the simulation (in seconds)", simTime);
cmd.AddValue ("speed", "Speed of the UE (default = 20 m/s)", speed);
cmd.AddValue ("enbTxPowerDbm", "TX power [dBm] used by HeNBs (default = 46.0)", enbTxPowerDbm);
cmd.Parse (argc, argv);
// ConfigStore config;
// config.ConfigureDefaults ();
// Initialize LTE Helper for our Simulation
Ptr<LteHelper> lteHelper = CreateObject<LteHelper> ();
Ptr<PointToPointEpcHelper> epcHelper = CreateObject<PointToPointEpcHelper> ();
lteHelper->SetEpcHelper (epcHelper);
lteHelper->SetSchedulerType ("ns3::RrFfMacScheduler");
//lteHelper->SetHandoverAlgorithmType ("ns3::NoOpHandoverAlgorithm");
// Set A3RSRP Handover Algorithm
lteHelper->SetHandoverAlgorithmType("ns3::A3RsrpHandoverAlgorithm");
lteHelper->SetHandoverAlgorithmAttribute ("Hysteresis",
DoubleValue (0.0));
lteHelper->SetHandoverAlgorithmAttribute ("TimeToTrigger",
TimeValue (MilliSeconds (256)));
// Propagation Loss Model
lteHelper->SetAttribute ("PathlossModel", StringValue ("ns3::FriisPropagationLossModel"));
// Fading Traces
// lteHelper->SetFadingModel("ns3::TraceFadingLossModel");
// lteHelper->SetFadingModelAttribute ("TraceFilename", StringValue ("src/lte/model/fading-traces/fading_trace_EPA_3kmph.fad"));
// lteHelper->SetFadingModelAttribute ("TraceLength", TimeValue (Seconds (simTime)));
// lteHelper->SetFadingModelAttribute ("SamplesNum", UintegerValue (10000));
// lteHelper->SetFadingModelAttribute ("WindowSize", TimeValue (Seconds (0.5)));
// lteHelper->SetFadingModelAttribute ("RbNum", UintegerValue (100));
// Get the PGW node
Ptr<Node> pgw = epcHelper->GetPgwNode ();
// Create a single remote host
NodeContainer remoteHostContainer;
remoteHostContainer.Create (1);
Ptr<Node> remoteHost = remoteHostContainer.Get (0);
InternetStackHelper internet;
internet.Install (remoteHostContainer);
// Create the Internet
PointToPointHelper p2ph;
p2ph.SetDeviceAttribute ("DataRate" , DataRateValue (DataRate ("100Gb/s")));
p2ph.SetDeviceAttribute ("Mtu" , UintegerValue(1500));
p2ph.SetChannelAttribute ("Delay" , TimeValue (Seconds (0.010) ) );
// InternetStackHelper stack;
// stack.InstallAll ();
NetDeviceContainer internetDevices = p2ph.Install (pgw , remoteHost);
Ipv4AddressHelper ipv4h;
ipv4h.SetBase ("1.0.0.0" , "255.0.0.0");
Ipv4InterfaceContainer internetIpIfaces = ipv4h.Assign (internetDevices);
Ipv4Address remoteHostAddr = internetIpIfaces.GetAddress (1);
// Routing of the Internet Host (towards the LTE network)
Ipv4StaticRoutingHelper ipv4RoutingHelper;
Ptr<Ipv4StaticRouting> remoteHostStaticRouting = ipv4RoutingHelper.GetStaticRouting (remoteHost->GetObject<Ipv4> ());
// interface 0 is localhost , 1 is the p2p device
remoteHostStaticRouting->AddNetworkRouteTo (Ipv4Address ("7.0.0.0") , Ipv4Mask ("255.0.0.0") , 1);
// Initialize UE and ENB nodes
NodeContainer ueNodes;
NodeContainer enbNodes;
enbNodes.Create (numberOfEnbs);
ueNodes.Create (numberOfUes);
// Install mobility model for stationary eNB nodes
Ptr<ListPositionAllocator> enbPositionAlloc = CreateObject<ListPositionAllocator> ();
for(uint16_t i = 0 ; i < numberOfEnbs ; i++)
{
enbPositionAlloc->Add (Vector (distance * (i+1), distance , 0 ));
}
MobilityHelper enbMobility;
enbMobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel");
enbMobility.SetPositionAllocator (enbPositionAlloc);
enbMobility.Install (enbNodes);
// Install mobility model for mobile UE nodes
MobilityHelper ueMobility;
ueMobility.SetMobilityModel ("ns3::ConstantVelocityMobilityModel");
ueMobility.Install (ueNodes);
ueNodes.Get (0)->GetObject<MobilityModel> ()-> SetPosition (Vector (0,yForUe,0));
ueNodes.Get (0)->GetObject<ConstantVelocityMobilityModel> ()->SetVelocity (Vector (speed , 0 , 0));
// Install LTE Devices in UEs and eNBs
Config::SetDefault ("ns3::LteEnbPhy::TxPower" , DoubleValue (enbTxPowerDbm));
NetDeviceContainer enbLteDevs = lteHelper->InstallEnbDevice (enbNodes);
NetDeviceContainer ueLteDevs = lteHelper->InstallUeDevice (ueNodes);
// Install the IP stack on UEs
internet.Install (ueNodes);
Ipv4InterfaceContainer ueIpIfaces;
ueIpIfaces = epcHelper->AssignUeIpv4Address (NetDeviceContainer (ueLteDevs));
// Attach all UEs to the first eNodeB
for(uint16_t i = 0; i < numberOfUes ; i++)
{
lteHelper->Attach (ueLteDevs.Get (i) , enbLteDevs.Get (0));
}
NS_LOG_LOGIC ("setting up applications");
// Install and Start applications on UE and remote host
uint16_t dlPort = 10000;
uint16_t ulPort = 20000;
// randomize a bit start times to avoid simulations artifacts
Ptr<UniformRandomVariable> startTimeSeconds = CreateObject<UniformRandomVariable> ();
startTimeSeconds->SetAttribute ("Min", DoubleValue (0));
startTimeSeconds->SetAttribute ("Max", DoubleValue (0.010));
for(uint16_t i = 0 ; i < numberOfUes ; i++)
{
// Extract the UE node
Ptr<Node> ue = ueNodes.Get (i);
// Set the default gateway for the UE
Ptr<Ipv4StaticRouting> ueStaticRouting = ipv4RoutingHelper.GetStaticRouting (ue->GetObject<Ipv4> ());
ueStaticRouting->SetDefaultRoute (epcHelper->GetUeDefaultGatewayAddress () , 1);
for(uint32_t j = 0 ; j < numberOfBearersPerUe ; j++)
{
++dlPort;
++ulPort;
ApplicationContainer clientApps;
ApplicationContainer serverApps;
// NS_LOG_LOGIC ("installing UDP DL app for UE" << i);
// UdpClientHelper dlClientHelper (ueIpIfaces.GetAddress (i) , dlPort);
// clientApps.Add (dlClientHelper.Install (remoteHost));
// PacketSinkHelper dlPacketSinkHelper ("ns3::UdpSocketFactory" , InetSocketAddress (Ipv4Address::GetAny () , dlPort));
// serverApps.Add (dlPacketSinkHelper.Install (ue));
// NS_LOG_LOGIC ("installing UDP UL app for UE" << i);
// UdpClientHelper ulClientHelper (remoteHostAddr , ulPort);
// clientApps.Add (ulClientHelper.Install (ue));
// PacketSinkHelper ulPacketSinkHelper ("ns3::UdpSocketFactory" , InetSocketAddress (Ipv4Address::GetAny () , ulPort));
// serverApps.Add (ulPacketSinkHelper.Install (remoteHost));
BulkSendHelper dlClientHelper ("ns3::TcpSocketFactory", InetSocketAddress (ueIpIfaces.GetAddress (i), dlPort));
dlClientHelper.SetAttribute ("MaxBytes", UintegerValue (0));
clientApps.Add (dlClientHelper.Install (remoteHost));
PacketSinkHelper dlPacketSinkHelper ("ns3::TcpSocketFactory",
InetSocketAddress (Ipv4Address::GetAny (), dlPort));
serverApps.Add (dlPacketSinkHelper.Install (ue));
BulkSendHelper ulClientHelper ("ns3::TcpSocketFactory",
InetSocketAddress (remoteHostAddr, ulPort));
ulClientHelper.SetAttribute ("MaxBytes", UintegerValue (0));
clientApps.Add (ulClientHelper.Install (ue));
PacketSinkHelper ulPacketSinkHelper ("ns3::TcpSocketFactory",
InetSocketAddress (Ipv4Address::GetAny (), ulPort));
serverApps.Add (ulPacketSinkHelper.Install (ue));
Ptr<EpcTft> tft = Create<EpcTft> ();
EpcTft::PacketFilter dlpf;
dlpf.localPortStart = dlPort;
dlpf.localPortEnd = dlPort;
tft->Add (dlpf);
EpcTft::PacketFilter ulpf;
ulpf.remotePortStart = ulPort;
ulpf.remotePortEnd = ulPort;
tft->Add (ulpf);
EpsBearer bearer (EpsBearer::NGBR_VIDEO_TCP_DEFAULT);
lteHelper->ActivateDedicatedEpsBearer (ueLteDevs.Get (i), bearer, tft);
Time startTime = Seconds (startTimeSeconds->GetValue ());
serverApps.Start (startTime);
clientApps.Start (startTime);
}
}
// Add X2 Interface
lteHelper->AddX2Interface (enbNodes);
// X2-based Handover
//lteHelper->HandoverRequest (Seconds (1.000) , ueLteDevs.Get (0) , enbLteDevs.Get (0) , enbLteDevs.Get (1));
//lteHelper->HandoverRequest (Seconds (3.000) , ueLteDevs.Get (0) , enbLteDevs.Get (1) , enbLteDevs.Get (0));
// Trace Configurations
lteHelper->EnableTraces ();
// lteHelper->EnablePhyTraces ();
// lteHelper->EnableMacTraces ();
// lteHelper->EnableRlcTraces ();
// lteHelper->EnablePdcpTraces ();
// Ptr<RadioBearerStatsCalculator> rlcStats = lteHelper->GetRlcStats ();
// rlcStats->SetAttribute ("EpochDuration", TimeValue (Seconds (1.0)));
// Ptr<RadioBearerStatsCalculator> pdcpStats = lteHelper->GetPdcpStats ();
// pdcpStats->SetAttribute ("EpochDuration", TimeValue (Seconds (1.0)));
std::ofstream ascii;
Ptr<OutputStreamWrapper> ascii_wrap;
ascii.open ((prefix_file_name + "-ascii").c_str ());
ascii_wrap = new OutputStreamWrapper ((prefix_file_name + "-ascii").c_str (),
std::ios::out);
internet.EnableAsciiIpv4All (ascii_wrap);
Simulator::Schedule (Seconds (0.00001), &TraceCwnd, prefix_file_name + "-cwnd.data");
Simulator::Schedule (Seconds (0.00001), &TraceSsThresh, prefix_file_name + "-ssth.data");
Ptr<FlowMonitor> flowMonitor;
FlowMonitorHelper flowHelper;
flowMonitor = flowHelper.Install (ueNodes);
flowMonitor = flowHelper.Install (remoteHostContainer);
flowMonitor->CheckForLostPackets ();
flowMonitor->SerializeToXmlFile("Handover_Stats.xml", true, true);
// Simulator::Schedule(Seconds(1) , &ThroughputMonitor, &flowHelper , flowMonitor);
Simulator::Stop (Seconds (simTime));
Simulator::Run();
// flowMonitor->CheckForLostPackets ();
// Ptr<Ipv4FlowClassifier> classifier = DynamicCast<Ipv4FlowClassifier> (flowHelper.GetClassifier ());
// std::map<FlowId , FlowMonitor::FlowStats> stats = flowMonitor->GetFlowStats ();
// for (std::map<FlowId , FlowMonitor::FlowStats>::const_iterator iter = stats.begin (); iter != stats.end ();iter++)
// {
// Ipv4FlowClassifier::FiveTuple t = classifier->FindFlow (iter->first);
// NS_LOG_UNCOND("Flow ID: " << iter->first << " Src Addr " << t.sourceAddress << " Dst Addr " << t.destinationAddress);
// NS_LOG_UNCOND("Tx Packets = " << iter->second.txPackets);
// NS_LOG_UNCOND("Rx Packets = " << iter->second.rxPackets);
// NS_LOG_UNCOND("Throughput: " << iter->second.rxBytes * 8.0 / (iter->second.timeLastRxPacket.GetSeconds()-iter->second.timeFirstTxPacket.GetSeconds()) / 1024 << " Kbps");
// }
flowMonitor->SerializeToXmlFile("Handover_Stats.xml", true, true);
Simulator::Destroy();
return 0;
} |
244edb46adc615f74f851d4e9a01836405a844a1 | 17fa41df54e1b6f03564b139d875267f72a470b3 | /server/Source/FluidOscServer.h | e4c15ba263f206af41eb20837d863f630b44c809 | [] | no_license | anattolia/fluid-music | 038295d40aab173bba087bd222221b86869de41d | fc25160d79871c00ce3cea05613e9d8c9c470a88 | refs/heads/main | 2023-02-13T06:33:36.661038 | 2021-01-23T06:30:48 | 2021-01-23T06:30:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,782 | h | FluidOscServer.h | /*
==============================================================================
FluidOscServer.h
Created: 18 Nov 2019 5:50:15pm
Author: Charles Holbrow
==============================================================================
*/
#pragma once
#include <iostream>
#include "../JuceLibraryCode/JuceHeader.h"
#include "cybr_helpers.h"
#include "CybrEdit.h"
#include "CybrSearchPath.h"
typedef void (*OscHandlerFunc)(const juce::OSCMessage&);
struct SelectedObjects {
te::Track* audioTrack = nullptr;
te::Clip* clip = nullptr;
te::Plugin* plugin = nullptr;
};
class FluidOscServer :
public juce::OSCReceiver,
private juce::OSCReceiver::Listener<juce::OSCReceiver::MessageLoopCallback>
{
public:
FluidOscServer();
virtual void oscMessageReceived (const juce::OSCMessage& message) override;
virtual void oscBundleReceived (const juce::OSCBundle& bundle) override;
juce::OSCBundle handleOscBundle(const juce::OSCBundle& bundle, SelectedObjects parentSelection);
juce::OSCMessage handleOscMessage(const juce::OSCMessage& message);
// message handlers
juce::OSCMessage selectAudioTrack(const juce::OSCMessage& message);
juce::OSCMessage selectSubmixTrack(const juce::OSCMessage& message);
juce::OSCMessage removeAudioTrackClips(const juce::OSCMessage& message);
juce::OSCMessage removeAudioTrackAutomation(const juce::OSCMessage& message);
juce::OSCMessage selectReturnTrack(const juce::OSCMessage& message);
juce::OSCMessage selectMidiClip(const juce::OSCMessage& message);
juce::OSCMessage selectPlugin(const juce::OSCMessage& message);
juce::OSCMessage setPluginParam(const juce::OSCMessage& message);
juce::OSCMessage setPluginParamAt(const juce::OSCMessage& message);
juce::OSCMessage setTrackWidth(const juce::OSCMessage& message);
juce::OSCMessage setPluginSideChainInput(const juce::OSCMessage& message);
juce::OSCMessage getPluginReport(const juce::OSCMessage& message);
juce::OSCMessage getPluginParameterReport(const juce::OSCMessage& message);
juce::OSCMessage getPluginParametersReport(const juce::OSCMessage& message);
juce::OSCMessage savePluginPreset(const juce::OSCMessage& message);
juce::OSCMessage loadPluginPreset(const juce::OSCMessage& message);
juce::OSCMessage loadPluginTrkpreset(const juce::OSCMessage& message);
juce::OSCMessage ensureSend(const juce::OSCMessage& message);
juce::OSCMessage clearMidiClip(const juce::OSCMessage& message);
juce::OSCMessage insertMidiNote(const juce::OSCMessage& message);
juce::OSCMessage insertWaveSample(const juce::OSCMessage& message);
juce::OSCMessage saveActiveEdit(const juce::OSCMessage& message);
juce::OSCMessage activateEditFile(const juce::OSCMessage& message);
juce::OSCMessage changeWorkingDirectory(const juce::OSCMessage& message);
juce::OSCMessage handleSamplerMessage(const juce::OSCMessage& message);
juce::OSCMessage handleTransportMessage(const juce::OSCMessage& message);
juce::OSCMessage setTrackGain(const juce::OSCMessage& message);
juce::OSCMessage setTrackPan(const juce::OSCMessage& message);
juce::OSCMessage renderRegion(const juce::OSCMessage& message);
juce::OSCMessage renderClip(const juce::OSCMessage& message);
juce::OSCMessage setClipLength(const juce::OSCMessage& message);
juce::OSCMessage trimClipBySeconds(const juce::OSCMessage& message);
juce::OSCMessage selectClip(const juce::OSCMessage& message);
juce::OSCMessage offsetClipSourceInSeconds(const juce::OSCMessage& message);
juce::OSCMessage audioClipFadeInOutSeconds(const juce::OSCMessage& message);
juce::OSCMessage setClipDb(const juce::OSCMessage& message);
juce::OSCMessage setTempo(const juce::OSCMessage& message);
juce::OSCMessage clearContent(const juce::OSCMessage& message);
juce::OSCMessage getAudioFileReport(const juce::OSCMessage& message);
// everything else
juce::OSCMessage muteTrack(bool mute);
juce::OSCMessage reverseAudioClip(bool reverse);
juce::OSCMessage activateEditFile(juce::File file, bool forceEmptyEdit = false);
std::unique_ptr<CybrEdit> activeCybrEdit = nullptr;
SelectedObjects getSelectedObjects();
private:
/** Recursively handle all messages and nested bundles, reseting the
selection state to parentSelection after each bundle. This should ensure
that nested bundles do not leave behind a selection after they have been
handled. */
void constructReply(juce::OSCMessage &reply, int error, juce::String message);
void constructReply(juce::OSCMessage &reply, juce::String message);
te::Track* selectedTrack = nullptr;
te::Clip* selectedClip = nullptr;
te::Plugin* selectedPlugin = nullptr;
};
|
e99b16a334f0f892adcc930aafc9563b055b548c | 4cb12e2e1f202ac8cb96bcca6b3518d73f2bdebb | /lab6/funcs.h | 39fe002eb706fbf543eae5a1fed8b0902dce9197 | [] | no_license | Kushendra1/135-Labs | 35b980177b74c7c8fdc59e8b39aaa1136611185c | 8eab72480f9a830a43e50a9dc5b0b1447495292c | refs/heads/master | 2021-06-19T17:46:37.202332 | 2019-09-05T22:59:00 | 2019-09-05T22:59:00 | 206,665,423 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 511 | h | funcs.h | #pragma once
#include <iostream>
// sample signature
void test_ascii(std::string sentence);
char shiftChar(char c, int rshift);
std::string encryptCaesar(std::string plaintext, int rshift);
std::string encryptVigenre(std::string text, std::string keyword);
char shiftLeft(char c, int lshift);
char shiftRight(char c, int rightShift);
std::string decryptCaesar(std::string text, int rshift);
std::string decryptVigenere(std::string text, std::string key);
// Write your function signatures / prototypes here
|
2f8c53edfac813e5dafdc00deaaf8255508ff04f | 087de73d56e71aa5e939af09933cdc12405892bf | /codechef/Mathison_and_pangrams.cpp | b64a4054d8599c08bb0ffdf8bab5a1729e549d45 | [] | no_license | dineshmakkar079/My-DS-Algo-code | 4b7330a62e4f615c239d08af50e4dc5f66aebf00 | 52dbb641d13a2e132fb9b61bd2f34b5b00da1143 | refs/heads/master | 2021-03-30T17:14:05.512323 | 2017-10-22T05:14:48 | 2017-10-22T05:14:48 | 93,957,454 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,426 | cpp | Mathison_and_pangrams.cpp | /*
Time : Sat Aug 26 2017 19:40:18 GMT+0530 (IST)
URL : https://www.codechef.com/LTIME51/problems/MATPAN
Read problems statements in mandarin chinese, russian and vietnamese as well.
Mathison recently
inherited an ancient papyrus that contained some text. Unfortunately, the text was not a PANGRAM.
Now, Mathison has a particular liking for holoalphabetic strings and the text bothers him. The good
news is that Mathison can buy letters from the local store in order to turn his text into a pangram.
However,
each letter has a price and Mathison is not very rich. Can you help Mathison find the cheapest way
to obtain a pangram?
Input
The first line of the input file will contain one integer, T, representing
the number of tests.
Each test will be formed from two lines. The first one contains 26 space-separated
integers, representing the prices of all letters. The second will contain Mathison's initial text
(a string of N lowercase letters).
Output
The output file will contain T lines, one for each test.
Each line will contain the answer for the corresponding test.
Constraints and notes
1 ≤ T ≤ 10
1
≤ N ≤ 50,000
All prices are natural numbers between 1 and 1,000,000 (i.e. 106).
A pangram is a string
that contains every letter of the Latin alphabet at least once.
All purchased letters are added
to the end of the string.
Subtaks
Subtask #1 (30 points):
N = 1
Subtask #2 (70 points):
Original
constraints
Example
Input:
2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
abcdefghijklmopqrstuvwz
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
thequickbrownfoxjumpsoverthelazydog
Output:
63
0
Explanation
First
test
There are three letters missing from the original string: n (price 14), x (price 24), and y
(price 25).
Therefore the answer is 14 24 25 = 63.
Second test
No letter is missing so there
is no point in buying something. The answer is 0.
*/
#include <bits/stdc++.h>
using namespace std;
int main(){
int t;
cin >> t;
vector<int> cost(26);
vector<bool> present(26);
while(t--){
for (int i = 0; i < 26; i++)
{
cin >> cost[i];
present[i]= false;
}
string in;
cin >> in;
int l = in.length();
int ans = 0;
for (int i = 0; i < l; i++)
{
present[(int)in[i] - (int)'a'] = true;
}
for (int i = 0; i < 26; i++)
{
ans += present[i] ? 0 : cost[i];
}
cout << ans << endl;
}
return 0;
}
|
492a3c4266e86ee888a45f41741ff51df9c30938 | d18b939f416737da54419d9b1e91d0c761cbb677 | /src/domain/log/AircraftLog.cpp | 500d78da66141bd6796c7482c4f45d4b53751ec8 | [] | no_license | wellington3110/AirportSimulation | fd10dee3f3ec48dd3b92db1e30730bfdeb734fe5 | 6f7b72710ff8295ce6fe88f9966b24dab5391b64 | refs/heads/master | 2021-01-19T16:04:55.861716 | 2017-09-13T16:15:53 | 2017-09-13T16:15:53 | 100,984,391 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,256 | cpp | AircraftLog.cpp | #include "AircraftLog.h"
static Log* instance;
Log* AircraftLog::getInstance()
{
if(!instance)
instance= new AircraftLog;
return instance;
}
void AircraftLog::generateMessages()
{
messages[REQUESTING_LANDING ]= "Aircraft Log: Avião [x] solicitando pouso";
messages[RECEIVE_PERMISSION_TOLAND ]= "Aircraft Log: Avião [x] recebeu permissão para pouso";
messages[STARTING_LANDING ]= "Aircraft Log: Avião [x] iniciando pouso";
messages[CONFIRMING_LANDING ]= "Aircraft Log: Avião [x] confirmando pouso";
messages[REQUESTING_TAKEOFF ]= "Aircraft Log: Avião [x] solicitando decolagem";
messages[RECEIVE_PERMISSION_TOTAKEOFF ]= "Aircraft Log: Avião [x] recebeu permissão para decolagem";
messages[STARTING_TAKEOFF ]= "Aircraft Log: Avião [x] iniciando decolagem";
messages[CONFIRMING_TAKEOFF ]= "Aircraft Log: Avião [x] confirmando decolagem";
messages[RECEIVE_REQUEST_TODRIVE_TO_ANOTHER_AIRPORT]= "Aircraft Log: Avião [x] recebeu o comando para se dirigir a outro aeroporto";
}
|
d388ef0260f3e881ad36ca282924a12abc0e4cbb | 1749bc75e1a9f2622b4240331bf2ce0bd2082e01 | /compiled/interface/trainData.h | 9b9d90202abc35326afeaafb98b2be1f95880232 | [
"Apache-2.0"
] | permissive | schoef/DeepJetCore | cdd6c33b7e16c9b5f58a6fe9eb523be41e2c3244 | 70508d34bac0b7e0d07b65984c70816c48a53f19 | refs/heads/master | 2023-02-25T20:33:56.512602 | 2021-01-27T09:45:52 | 2021-01-27T09:45:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 22,762 | h | trainData.h | /*
* trainDataInterface.h
*
* Created on: 5 Nov 2019
* Author: jkiesele
*/
#ifndef DEEPJETCORE_COMPILED_INTERFACE_TRAINDATAINTERFACE_H_
#define DEEPJETCORE_COMPILED_INTERFACE_TRAINDATAINTERFACE_H_
//#define DJC_DATASTRUCTURE_PYTHON_BINDINGS//DEBUG
#ifdef DJC_DATASTRUCTURE_PYTHON_BINDINGS
#include <boost/python.hpp>
#include "boost/python/numpy.hpp"
#include "boost/python/list.hpp"
#include <boost/python/exception_translator.hpp>
#include "helper.h"
#endif
#include "simpleArray.h"
#include <stdio.h>
#include "IO.h"
#include <iostream>
namespace djc{
/*
* The idea is to make this a fixed size array class, that is filled with data and then written out once full.
* a truncate function will allow to truncate arrays at a given position.
* This is memory intense, but can be written out in small pieces and then merged
*
* No checks on the first dimension because of possibly ragged arrays
*/
template<class T>
class trainData{
public:
//takes ownership
int storeFeatureArray( simpleArray<T>&);
int storeTruthArray( simpleArray<T>&);
int storeWeightArray( simpleArray<T>&);
const simpleArray<T> & featureArray(size_t idx) const {
return feature_arrays_.at(idx);
}
const simpleArray<T> & truthArray(size_t idx) const {
return truth_arrays_.at(idx);
}
const simpleArray<T> & weightArray(size_t idx) const {
return weight_arrays_.at(idx);
}
simpleArray<T> & featureArray(size_t idx) {
return feature_arrays_.at(idx);
}
simpleArray<T> & truthArray(size_t idx) {
return truth_arrays_.at(idx);
}
simpleArray<T> & weightArray(size_t idx) {
return weight_arrays_.at(idx);
}
int nFeatureArrays()const{return feature_arrays_.size();}
int nTruthArrays()const{return truth_arrays_.size();}
int nWeightArrays()const{return weight_arrays_.size();}
/*
* truncate all along first axis
*/
void truncate(size_t position);
/*
* append along first axis
*/
void append(const trainData<T>& );
/*
* split along first axis
* Returns the second part, leaves the first.
*/
trainData<T> split(size_t splitindex);
trainData<T> getSlice(size_t splitindex_begin, size_t splitindex_end)const;
trainData<T> shuffle(const std::vector<size_t>& shuffle_idxs)const;
bool validSlice(size_t splitindex_begin, size_t splitindex_end)const ;
/*
*
*/
size_t nElements()const{
if(feature_shapes_.size() && feature_shapes_.at(0).size())
return feature_shapes_.at(0).at(0);
else
return 0;
}
int nTotalElements()const{
if(feature_shapes_.size() && feature_shapes_.at(0).size()){
int ntotalelems=0;
for(size_t i=0;i< feature_shapes_.at(0).size(); i++){
ntotalelems = feature_shapes_.at(0).at(i);
if(i>0 && ntotalelems<0)
return std::abs(ntotalelems);
else if(i>0)
return feature_shapes_.at(0).at(0);
}
}
else
return 0;
return 0;
}
const std::vector<std::vector<int> > & featureShapes()const{return feature_shapes_;}
const std::vector<std::vector<int> > & truthShapes()const{return truth_shapes_;}
const std::vector<std::vector<int> > & weightShapes()const{return weight_shapes_;}
void writeToFile(std::string filename)const;
void readFromFile(std::string filename){
priv_readFromFile(filename,false);
}
void readFromFileBuffered(std::string filename){
priv_readFromFile(filename,true);
}
//could use a readshape or something!
void readShapesFromFile(const std::string& filename);
std::vector<int64_t> getFirstRowsplits()const;
std::vector<int64_t> readShapesAndRowSplitsFromFile(const std::string& filename, bool checkConsistency=true);
void clear();
trainData<T> copy()const {return *this;}
//from python
void skim(size_t batchelement);
#ifdef DJC_DATASTRUCTURE_PYTHON_BINDINGS
boost::python::list getKerasFeatureShapes()const;
boost::python::list getKerasFeatureDTypes()const;
// not needed boost::python::list getKerasTruthShapes()const;
// not needed boost::python::list getKerasWeightShapes()const;
//data generator interface get back numpy arrays / tf.tensors here for keras feeding!
boost::python::list getTruthRaggedFlags()const;
boost::python::list featureList();
boost::python::list truthList();
boost::python::list weightList();
//has ragged support
boost::python::list transferFeatureListToNumpy();
//has ragged support
boost::python::list transferTruthListToNumpy();
//no ragged support
boost::python::list transferWeightListToNumpy();
/*
* the following ones can be improved w.r.t. performance
*/
//has ragged support
boost::python::list copyFeatureListToNumpy(){
auto td = *this;
return td.transferFeatureListToNumpy(); //fast hack
}
//has ragged support
boost::python::list copyTruthListToNumpy(){
auto td = *this;
return td.transferTruthListToNumpy(); //fast hack
}
//no ragged support
boost::python::list copyWeightListToNumpy(){
auto td = *this;
return td.transferWeightListToNumpy(); //fast hack
}
#endif
private:
void priv_readFromFile(std::string filename, bool memcp);
void checkFile(FILE *& f, const std::string& filename="")const;
void writeArrayVector(const std::vector<simpleArray<T> >&, FILE *&) const;
std::vector<simpleArray<T> > readArrayVector(FILE *&) const;
void readRowSplitArray(FILE *&, std::vector<int64_t> &rs, bool check)const;
std::vector<std::vector<int> > getShapes(const std::vector<simpleArray<T> >& a)const;
template <class U>
void writeNested(const std::vector<std::vector<U> >& v, FILE *&)const;
template <class U>
void readNested( std::vector<std::vector<U> >& v, FILE *&)const;
void updateShapes();
std::vector<simpleArray<T> > feature_arrays_;
std::vector<simpleArray<T> > truth_arrays_;
std::vector<simpleArray<T> > weight_arrays_;
std::vector<std::vector<int> > feature_shapes_;
std::vector<std::vector<int> > truth_shapes_;
std::vector<std::vector<int> > weight_shapes_;
};
template<class T>
int trainData<T>::storeFeatureArray(simpleArray<T> & a){
size_t idx = feature_arrays_.size();
feature_arrays_.push_back(std::move(a));
a.clear();
updateShapes();
return idx;
}
template<class T>
int trainData<T>::storeTruthArray(simpleArray<T>& a){
size_t idx = truth_arrays_.size();
truth_arrays_.push_back(std::move(a));
a.clear();
updateShapes();
return idx;
}
template<class T>
int trainData<T>::storeWeightArray(simpleArray<T> & a){
size_t idx = weight_arrays_.size();
weight_arrays_.push_back(std::move(a));
a.clear();
updateShapes();
return idx;
}
/*
* truncate all along first axis
*/
template<class T>
void trainData<T>::truncate(size_t position){
*this = split(position);
}
/*
* append along first axis
*/
template<class T>
void trainData<T>::append(const trainData<T>& td) {
//allow empty append
if (!feature_arrays_.size() && !truth_arrays_.size()
&& !weight_arrays_.size()) {
*this = td;
return;
}
if(!td.feature_arrays_.size() && !td.truth_arrays_.size()
&& !td.weight_arrays_.size()){
return ; //nothing to do
}
if (feature_arrays_.size() != td.feature_arrays_.size()
|| truth_arrays_.size() != td.truth_arrays_.size()
|| weight_arrays_.size() != td.weight_arrays_.size()) {
std::cout << "nfeat " << feature_arrays_.size() << "-" << td.feature_arrays_.size() <<'\n'
<< "ntruth " << truth_arrays_.size() << "-" << td.truth_arrays_.size()<<'\n'
<< "nweights " << weight_arrays_.size() << "-" << td.weight_arrays_.size() <<std::endl;
throw std::out_of_range("trainData<T>::append: format not compatible.");
}
for(size_t i=0;i<feature_arrays_.size();i++)
feature_arrays_.at(i).append(td.feature_arrays_.at(i));
for(size_t i=0;i<truth_arrays_.size();i++)
truth_arrays_.at(i).append(td.truth_arrays_.at(i));
for(size_t i=0;i<weight_arrays_.size();i++)
weight_arrays_.at(i).append(td.weight_arrays_.at(i));
updateShapes();
}
/*
* split along first axis
* Returns the first part, leaves the second.
*
* Can use some performance improvements
*/
template<class T>
trainData<T> trainData<T>::split(size_t splitindex) {
trainData<T> out;
for (auto& a : feature_arrays_)
out.feature_arrays_.push_back(a.split(splitindex));
for (auto& a : truth_arrays_)
out.truth_arrays_.push_back(a.split(splitindex));
for (auto& a : weight_arrays_)
out.weight_arrays_.push_back(a.split(splitindex));
updateShapes();
out.updateShapes();
return out;
}
template<class T>
trainData<T> trainData<T>::getSlice(size_t splitindex_begin, size_t splitindex_end)const{
trainData<T> out;
for (const auto& a : feature_arrays_)
out.feature_arrays_.push_back(a.getSlice(splitindex_begin,splitindex_end));
for (const auto& a : truth_arrays_)
out.truth_arrays_.push_back(a.getSlice(splitindex_begin,splitindex_end));
for (const auto& a : weight_arrays_)
out.weight_arrays_.push_back(a.getSlice(splitindex_begin,splitindex_end));
out.updateShapes();
return out;
}
template<class T>
trainData<T> trainData<T>::shuffle(const std::vector<size_t>& shuffle_idxs)const{
trainData<T> out;
for (const auto& a : feature_arrays_)
out.feature_arrays_.push_back(a.shuffle(shuffle_idxs));
for (const auto& a : truth_arrays_)
out.truth_arrays_.push_back(a.shuffle(shuffle_idxs));
for (const auto& a : weight_arrays_)
out.weight_arrays_.push_back(a.shuffle(shuffle_idxs));
out.updateShapes();
return out;
}
template<class T>
bool trainData<T>::validSlice(size_t splitindex_begin, size_t splitindex_end)const{
for (const auto& a : feature_arrays_)
if(! a.validSlice(splitindex_begin,splitindex_end))
return false;
for (const auto& a : truth_arrays_)
if(! a.validSlice(splitindex_begin,splitindex_end))
return false;
for (const auto& a : weight_arrays_)
if(! a.validSlice(splitindex_begin,splitindex_end))
return false;
return true;
}
template<class T>
void trainData<T>::writeToFile(std::string filename)const{
FILE *ofile = fopen(filename.data(), "wb");
float version = DJCDATAVERSION;
io::writeToFile(&version, ofile);
//shape infos only
writeNested(getShapes(feature_arrays_), ofile);
writeNested(getShapes(truth_arrays_), ofile);
writeNested(getShapes(weight_arrays_), ofile);
//data
writeArrayVector(feature_arrays_, ofile);
writeArrayVector(truth_arrays_, ofile);
writeArrayVector(weight_arrays_, ofile);
fclose(ofile);
}
template<class T>
void trainData<T>::priv_readFromFile(std::string filename, bool memcp){
clear();
FILE *ifile = fopen(filename.data(), "rb");
char *buf = 0;
if(memcp){
FILE *diskfile = ifile;
//check if exists before trying to memcp.
checkFile(ifile, filename); //not set at start but won't be used
fseek(diskfile, 0, SEEK_END);
size_t fsize = ftell(diskfile);
fseek(diskfile, 0, SEEK_SET); /* same as rewind(f); */
buf = new char[fsize];
int ret = fread(buf, 1, fsize, diskfile);
if(!ret){
delete buf;
throw std::runtime_error("trainData<T>::readFromFile: could not read file in memcp mode");
}
fclose(diskfile);
ifile = fmemopen(buf,fsize,"r");
}
checkFile(ifile, filename);
readNested(feature_shapes_, ifile);
readNested(truth_shapes_, ifile);
readNested(weight_shapes_, ifile);
feature_arrays_ = readArrayVector(ifile);
truth_arrays_ = readArrayVector(ifile);
weight_arrays_ = readArrayVector(ifile);
fclose(ifile);
//std::cout << "read done, free"<<std::endl;
if(buf){
delete buf;
}
}
template<class T>
void trainData<T>::readShapesFromFile(const std::string& filename){
FILE *ifile = fopen(filename.data(), "rb");
checkFile(ifile,filename);
readNested(feature_shapes_, ifile);
readNested(truth_shapes_, ifile);
readNested(weight_shapes_, ifile);
fclose(ifile);
}
template<class T>
std::vector<int64_t> trainData<T>::getFirstRowsplits()const{
for (auto& a : feature_arrays_)
if(a.rowsplits().size())
return a.rowsplits();
for (auto& a : truth_arrays_)
if(a.rowsplits().size())
return a.rowsplits();
return std::vector<int64_t>();
}
template<class T>
std::vector<int64_t> trainData<T>::readShapesAndRowSplitsFromFile(const std::string& filename, bool checkConsistency){
std::vector<int64_t> rowsplits;
FILE *ifile = fopen(filename.data(), "rb");
checkFile(ifile,filename);
//shapes
std::vector<std::vector<int> > dummy;
readNested(feature_shapes_, ifile);
readNested(truth_shapes_, ifile);
readNested(weight_shapes_, ifile);
//features
readRowSplitArray(ifile,rowsplits,checkConsistency);
if(!checkConsistency && rowsplits.size()){
fclose(ifile);
return rowsplits;
}
//truth
readRowSplitArray(ifile,rowsplits,checkConsistency);
if(!checkConsistency && rowsplits.size()){
fclose(ifile);
return rowsplits;
}
//weights
readRowSplitArray(ifile,rowsplits,checkConsistency);
fclose(ifile);
return rowsplits;
}
template<class T>
void trainData<T>::clear() {
feature_arrays_.clear();
truth_arrays_.clear();
weight_arrays_.clear();
updateShapes();
}
template<class T>
void trainData<T>::checkFile(FILE *& ifile, const std::string& filename)const{
if(!ifile)
throw std::runtime_error("trainData<T>::readFromFile: file "+filename+" could not be opened.");
float version = 0;
io::readFromFile(&version, ifile);
if(version != DJCDATAVERSION)
throw std::runtime_error("trainData<T>::readFromFile: wrong format version");
}
template<class T>
void trainData<T>::writeArrayVector(const std::vector<simpleArray<T> >& v, FILE *& ofile) const{
size_t size = v.size();
io::writeToFile(&size, ofile);
for(const auto& a: v)
a.addToFileP(ofile);
}
template<class T>
std::vector<simpleArray<T> > trainData<T>::readArrayVector(FILE *& ifile) const{
std::vector<simpleArray<T> > out;
size_t size = 0;
io::readFromFile(&size, ifile);
for(size_t i=0;i<size;i++)
out.push_back(simpleArray<T> (ifile));
return out;
}
template<class T>
void trainData<T>::readRowSplitArray(FILE *& ifile, std::vector<int64_t> &rowsplits, bool check)const{
size_t size = 0;
io::readFromFile(&size, ifile);
for(size_t i=0;i<size;i++){
auto frs = simpleArray<T>::readRowSplitsFromFileP(ifile, true);
if(frs.size()){
if(check){
if(rowsplits.size() && rowsplits != frs)
throw std::runtime_error("trainData<T>::readShapesAndRowSplitsFromFile: row splits inconsistent");
}
rowsplits=frs;
}
}
}
template<class T>
std::vector<std::vector<int> > trainData<T>::getShapes(const std::vector<simpleArray<T> >& a)const{
std::vector<std::vector<int> > out;
for(const auto& arr: a)
out.push_back(arr.shape());
return out;
}
template<class T>
template <class U>
void trainData<T>::writeNested(const std::vector<std::vector<U> >& v, FILE *& ofile)const{
size_t size = v.size();
io::writeToFile(&size, ofile);
for(size_t i=0;i<size;i++){
size_t nsize = v.at(i).size();
io::writeToFile(&nsize, ofile);
if(nsize==0)
continue;
io::writeToFile(&(v.at(i).at(0)),ofile,nsize);
}
}
template<class T>
template <class U>
void trainData<T>::readNested(std::vector<std::vector<U> >& v, FILE *& ifile)const{
size_t size = 0;
io::readFromFile(&size, ifile);
v.resize(size,std::vector<U>(0));
for(size_t i=0;i<size;i++){
size_t nsize = 0;
io::readFromFile(&nsize, ifile);
v.at(i).resize(nsize);
if(nsize==0)
continue;
io::readFromFile(&(v.at(i).at(0)),ifile,nsize);
}
}
template<class T>
void trainData<T>::updateShapes(){
feature_shapes_ = getShapes(feature_arrays_);
truth_shapes_ = getShapes(truth_arrays_);
weight_shapes_ = getShapes(weight_arrays_);
}
template<class T>
void trainData<T>::skim(size_t batchelement){
if(batchelement > nElements())
throw std::out_of_range("trainData<T>::skim: batch element out of range");
for(auto & a : feature_arrays_){
a.split(batchelement);
a=a.split(1);
}
for(auto & a : truth_arrays_){
a.split(batchelement);
a=a.split(1);
}
for(auto & a : weight_arrays_){
a.split(batchelement);
a=a.split(1);
}
updateShapes();
}
#ifdef DJC_DATASTRUCTURE_PYTHON_BINDINGS
template<class T>
boost::python::list trainData<T>::getKerasFeatureShapes()const{
boost::python::list out;
for(const auto& a: feature_shapes_){
boost::python::list nlist;
bool wasragged=false;
for(size_t i=1;i<a.size();i++){
if(a.at(i)<0){
nlist = boost::python::list();//ignore everything before
wasragged=true;
}
else
nlist.append(std::abs(a.at(i)));
}
out.append(nlist);
if(wasragged){
boost::python::list rslist;
rslist.append(1);
out.append(rslist);
}
}
return out;
}
template<class T>
boost::python::list trainData<T>::getKerasFeatureDTypes()const{
boost::python::list out;
for(const auto& a: feature_shapes_){
bool isragged=false;
for(size_t i=0;i<a.size();i++){
if(a.at(i)<0){
isragged=true;
break;
}
}
out.append("float32");//FIXME for real templated types!
if(isragged)
out.append("int64");
}
return out;
}
//template<class T>
//boost::python::list trainData<T>::getKerasTruthShapes()const{
// boost::python::list out;
// for(const auto& a: truth_arrays_){
// size_t start=1;
// if(a.isRagged())
// start=2;
// for(size_t i=start;i<a.shape().size();i++)
// out.append(std::abs(a.shape().at(i)));
// }
// return out;
//}
//template<class T>
//boost::python::list trainData<T>::getKerasWeightShapes()const{
// boost::python::list out;
// for(const auto& a: weight_shapes_){
// for(size_t i=1;i<a.size();i++){
// if(a.at(i)<0){
// out = boost::python::list();//igonre everything before
// }
// out.append(std::abs(a.at(i)));
// }
// }
// return out;
//}
template<class T>
boost::python::list trainData<T>::getTruthRaggedFlags()const{
boost::python::list out;
for(const auto& a: truth_shapes_){
bool isragged = false;
for(const auto & s: a)
if(s<0){
isragged=true;
break;
}
if(isragged)
out.append(true);
else
out.append(false);
}
return out;
}
template<class T>
boost::python::list trainData<T>::featureList(){
boost::python::list out;
for(auto &a: feature_arrays_)
out.append(a);
return out;
}
template<class T>
boost::python::list trainData<T>::truthList(){
boost::python::list out;
for(auto &a: truth_arrays_)
out.append(a);
return out;
}
template<class T>
boost::python::list trainData<T>::weightList(){
boost::python::list out;
for(auto &a: weight_arrays_)
out.append(a);
return out;
}
template<class T>
boost::python::list trainData<T>::transferFeatureListToNumpy(){
namespace p = boost::python;
namespace np = boost::python::numpy;
p::list out;
for( auto& a: feature_arrays_){
if(a.isRagged()){
auto arrt = a.transferToNumpy(true);//pad row splits
out.append(arrt[0]);//data
np::ndarray rs = boost::python::extract<np::ndarray>(arrt[1]);
out.append(rs.reshape(p::make_tuple(-1,1)));//row splits
}
else
out.append(a.transferToNumpy(true)[0]);
}
return out;
}
template<class T>
boost::python::list trainData<T>::transferTruthListToNumpy(){
namespace p = boost::python;
namespace np = boost::python::numpy;
boost::python::list out;
for( auto& a: truth_arrays_){
if(a.isRagged()){
//auto arrt = a.transferToNumpy(false);
//boost::python::list subl;
//subl.append(arrt[0]);
//subl.append(arrt[1]);
//out.append(subl);
auto arrt = a.transferToNumpy(true);//pad row splits
out.append(arrt[0]);//data
np::ndarray rs = boost::python::extract<np::ndarray>(arrt[1]);
out.append(rs.reshape(p::make_tuple(-1,1)));//row splits
}
else{
out.append(a.transferToNumpy(false)[0]);}
}
return out;
}
template<class T>
boost::python::list trainData<T>::transferWeightListToNumpy(){
boost::python::list out;
for( auto& a: weight_arrays_){
out.append(a.transferToNumpy()[0]);
}
return out;
}
#endif
/*
* Array storage:
* length, shape, length row splits, [row splits] ? numpy doesn't like ragged... maybe just return row splits?
* (shape is int. negative entries provoke row splits, only splits in one dimension supported)
*
* all data is float32. only row splits and shapes should be int (not size_t) for simple python conversion
*
* make it a traindata object
*
* interface:
*
* writeToFile(vector< float * > c_arrays (also pointers to first vec element), vector< vector<int> > shapes, (opt) vector< vector<int> > row_splits, filename)
*
* readFromFile
*
*/
/*
*
* Make a write CPP interface that does not need boost whatsoever!
* Then wrap it for python-numpy bindings externally
*
*
*/
/*
* uncompressed header with all shape infos
* compressed x,y,w lists or arrays?
*
*
*/
}//namespace
#endif /* DJCDEV_DEEPJETCORE_COMPILED_INTERFACE_TRAINDATAINTERFACE_H_ */
|
1345814654cc96f02cf3b78faf9006b76a53212d | 1579910d094db659fd55f72225a4cf9f9a69e0da | /SinglyLinkedList/SinglyLinkedList.cpp | 8a951ec43f518c7bf5e469c92d61552ab2841d7a | [] | no_license | zincxenon/DataStructures | 850662a30851942a5c626887eb96c749b013e441 | 70cd892dc26ae22dbd8a9b6f9016f17c53cb3fa9 | refs/heads/master | 2020-12-24T22:29:27.169403 | 2014-05-23T05:59:33 | 2014-05-23T05:59:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,675 | cpp | SinglyLinkedList.cpp | #include "SinglyLinkedList.h"
SinglyLinkedList::SinglyLinkedList() {
head = new ListNode;
it = new ListIterator(head);
}
/* TODO: Finish these methods */
// SinglyLinkedListList::SinglyLinkedList(int * arr) {
// head = new ListNode;
// it = new ListIterator(head);
// //
// }
// SinglyLinkedList::SinglyLinkedListList(const SinglyLinkedListList& source) {
// head=new ListNode;
// tail=new ListNode;
// head->next=tail;
// tail->previous=head;
// count=0;
// ListItr iter(source.head->next);
// while (!iter.isPastEnd()) { // deep copy of the list
// insertAtTail(iter.retrieve());
// iter.moveForward();
// }
// }
// SinglyLinkedList& SinglyLinkedList::operator=(const List& source) {
// if (this == &source)
// return *this;
// else {
// makeEmpty();
// ListItr iter(source.head->next);
// while (!iter.isPastEnd()) {
// insertAtTail(iter.retrieve());
// iter.moveForward();
// }
// }
// return *this;
// }
SinglyLinkedList::~SinglyLinkedList() {
delete head;
}
void SinglyLinkedList::insert_after(int prev, int v) {
it->current = find(head,prev);
if (it->current == NULL) {
insert_at_head(v);
return;
}
ListNode * n = new ListNode(v);
if (it->current->next != NULL) {
n->next = it->current->next;
}
it->current->next = n;
size++;
}
void SinglyLinkedList::insert_at_head(int v) {
it->current = head;
ListNode * n = new ListNode(v);
if (it->current->next != NULL) {
n->next = it->current->next;
}
it->current->next = n;
size++;
}
bool SinglyLinkedList::find(int v) {
return (find(head, v) != NULL ? true : false);
}
ListNode * SinglyLinkedList::find(ListNode*& node, int v) {
it->current = node;
while (it->current != NULL) {
if (it->current->value == v) {
return it->current;
}
it->move_forward();
}
return NULL;
}
void SinglyLinkedList::remove(int v) {
int i = 0;
bool found = false;
it->current = head;
while (it->current != NULL) {
if (it->current->value == v) {
found = true;
break;
}
it->move_forward();
i++;
}
if (found) {
ListIterator * tmp = new ListIterator(head);
for (int j = 0; j < i-1; j++) {
tmp->move_forward();
}
tmp->current->next = it->current->next;
it->current->next = NULL;
delete it->current;
size--;
}
}
void SinglyLinkedList::print_list() {
it->current = head;
cout << "[";
while (it->current != NULL) {
cout << std::to_string(it->current->value);
if (it->current->next != NULL) {
cout << " -> ";
}
it->move_forward();
}
cout << "]\n";
}
SinglyLinkedList * reverse(SinglyLinkedList * input) {
return NULL;
} |
b7369efa5e79095a1b61daa58287a90d41b052fb | cf7a3bade6974469dfad25ab006ca7ffd3a20576 | /ibrdtnd-0.12.0/src/routing/breadcrumb/BreadcrumbRoutingExtension.cpp | 6151f21c4c121ad01201662d05bbfb6824a95f7b | [
"Apache-2.0"
] | permissive | tkalbar/ibrdtn | 2e8053a42df74f96a26255e2808e2f636f0675fc | 7107a308ca8aa63f41c0b1ae4444beb58f0527c6 | refs/heads/master | 2020-12-31T03:34:29.392723 | 2014-07-08T14:44:07 | 2014-07-08T14:44:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 35,223 | cpp | BreadcrumbRoutingExtension.cpp | /*
* BreadcrumbRoutingExtension.cpp
*
*/
#include "routing/breadcrumb/BreadcrumbRoutingExtension.h"
#include "routing/QueueBundleEvent.h"
#include "routing/NodeHandshakeEvent.h"
#include "net/TransferCompletedEvent.h"
#include "net/TransferAbortedEvent.h"
#include "core/NodeEvent.h"
#include "core/Node.h"
#include "net/ConnectionEvent.h"
#include "net/ConnectionManager.h"
#include "Configuration.h"
#include "core/BundleCore.h"
#include "core/EventDispatcher.h"
#include "core/BundleEvent.h"
#include "net/BundleReceivedEvent.h"
#include "core/TimeEvent.h"
#include <ibrdtn/data/MetaBundle.h>
#include <ibrcommon/thread/MutexLock.h>
#include <ibrcommon/Logger.h>
#include <ibrdtn/utils/Clock.h>
#include <functional>
#include <list>
#include <algorithm>
#include <cmath>
#include <iomanip>
#include <ios>
#include <iostream>
#include <set>
#include <memory>
#include <stdlib.h>
#include <typeinfo>
#include <time.h>
namespace dtn
{
namespace routing
{
const std::string BreadcrumbRoutingExtension::TAG = "BreadcrumbRoutingExtension";
/*class Location
{
public:
double _latitude;
double _longitude;
Location() : _latitude(0.0), _longitude(0.0) {};
Location(double latitude, double longitude) : _latitude(latitude), _longitude(longitude) {};
~Location(){};
};
Location nodeLocation;*/
BreadcrumbRoutingExtension::BreadcrumbRoutingExtension() : _next_exchange_timeout(60), _next_exchange_timestamp(0), _next_loc_update_interval(15), _next_loc_update_timestamp(0)
{
// write something to the syslog
IBRCOMMON_LOGGER_TAG(BreadcrumbRoutingExtension::TAG, info) << "BreadcrumbRoutingExtension()" << IBRCOMMON_LOGGER_ENDL;
//srand(time(NULL));
//float latitude = (rand() % 1000000)/100000;
//float longitude = (rand() % 1000000)/100000;
//_location._geopoint.set(latitude, longitude);
updateMyLocation();
IBRCOMMON_LOGGER_TAG(BreadcrumbRoutingExtension::TAG, info) << "Setting dummy location: " << _location << IBRCOMMON_LOGGER_ENDL;
_next_exchange_timestamp = dtn::utils::Clock::getMonotonicTimestamp() + _next_exchange_timeout;
_next_loc_update_timestamp = dtn::utils::Clock::getMonotonicTimestamp() + _next_loc_update_interval;
}
BreadcrumbRoutingExtension::~BreadcrumbRoutingExtension()
{
//delete &nodeLocation;
join();
}
void BreadcrumbRoutingExtension::responseHandshake(const dtn::data::EID& neighbor, const NodeHandshake& request, NodeHandshake& response)
{
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "responseHandshake()" << IBRCOMMON_LOGGER_ENDL;
if (request.hasRequest(GeoLocation::identifier))
{
ibrcommon::MutexLock l(_location);
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "addItem(): " << _location << " to response" << IBRCOMMON_LOGGER_ENDL;
response.addItem(new GeoLocation(_location));
}
}
void BreadcrumbRoutingExtension::processHandshake(const dtn::data::EID& neighbor, NodeHandshake& response)
{
/* ignore neighbors, that have our EID */
//if (neighbor.sameHost(dtn::core::BundleCore::local)) return;
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "processHandshake()" << IBRCOMMON_LOGGER_ENDL;
try {
const GeoLocation& neighbor_location = response.get<GeoLocation>();
// strip possible application part off the neighbor EID
const dtn::data::EID neighbor_node = neighbor.getNode();
try {
NeighborDatabase &db = (**this).getNeighborDB();
NeighborDataset ds(new GeoLocation(neighbor_location));
ibrcommon::MutexLock l(db);
db.get(neighbor_node).putDataset(ds);
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Putting in database: [" << neighbor_node.getString() << "," << neighbor_location << "]" << IBRCOMMON_LOGGER_ENDL;
} catch (const NeighborNotAvailableException&) { };
/* update predictability for this neighbor */
//updateNeighbor(neighbor_node, neighbor_dp_map);
} catch (std::exception&) { }
}
void BreadcrumbRoutingExtension::requestHandshake(const dtn::data::EID&, NodeHandshake &request) const
{
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "requestHandshake()" << IBRCOMMON_LOGGER_ENDL;
request.addRequest(GeoLocation::identifier);
request.addRequest(BloomFilterSummaryVector::identifier);
}
void BreadcrumbRoutingExtension::eventTransferCompleted(const dtn::data::EID &peer, const dtn::data::MetaBundle &meta) throw ()
{
//IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "eventTransferCompleted()" << IBRCOMMON_LOGGER_ENDL;
if (dtn::core::BundleCore::getInstance().getStorage().contains(meta)) {
if (meta.hasgeoroute) {
dtn::core::BundleCore::getInstance().getStorage().remove(meta);
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "eventTransferCompleted(): bundle removed" << IBRCOMMON_LOGGER_ENDL;
}
}
}
void BreadcrumbRoutingExtension::eventDataChanged(const dtn::data::EID &peer) throw ()
{
// transfer the next bundle to this destination
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "eventDataChanged()" << IBRCOMMON_LOGGER_ENDL;
_taskqueue.push( new SearchNextBundleTask( peer ) );
}
void BreadcrumbRoutingExtension::eventBundleQueued(const dtn::data::EID &peer, const dtn::data::MetaBundle &meta) throw ()
{
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "eventBundleQueued()" << IBRCOMMON_LOGGER_ENDL;
class UpdateBundleFilter : public dtn::storage::BundleSelector {
public:
UpdateBundleFilter(const GeoLocation &myloc) : _myloc(myloc) {};
virtual ~UpdateBundleFilter() {};
virtual dtn::data::Size limit() const throw () { return dtn::core::BundleCore::getInstance().getStorage().size(); };
virtual bool shouldAdd(const dtn::data::MetaBundle &meta) const throw (dtn::storage::BundleSelectorException) {
if (meta.reacheddest) {
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "UpdateFilter: Destination reached" << IBRCOMMON_LOGGER_ENDL;
return false;
}
if (meta.hasgeoroute) {
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "UpdateFilter: MetaBundle has georoute" << IBRCOMMON_LOGGER_ENDL;
// check if the new location is the next hop to see if it's worth going through the bundle
if (checkMargin(_myloc, meta.nextgeohop)) {
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "UpdateFilter: Location match found, adding to list" << IBRCOMMON_LOGGER_ENDL;
return true;
} else {
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "UpdateFilter: No location match found" << IBRCOMMON_LOGGER_ENDL;
return false;
}
}
return false;
}
private:
const GeoLocation &_myloc;
};
if (meta.hasgeoroute) {
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "eventBundleQueued(): has geo route" << IBRCOMMON_LOGGER_ENDL;
//if (peer.getNode() != dtn::core::BundleCore::local) {
//IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "eventBundleQueued(): not local," << peer.getHost() << IBRCOMMON_LOGGER_ENDL;
//IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Peer: " << peer.getHost() << IBRCOMMON_LOGGER_ENDL;
//IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Local: " << dtn::core::BundleCore::local.getHost() << IBRCOMMON_LOGGER_ENDL;
try {
const UpdateBundleFilter updateFilter(_location);
dtn::storage::BundleResultList updateList;
updateList.clear();
(**this).getSeeker().get(updateFilter, updateList); // use the filter to acquire all bundles that need updates
updateBundleList(_location, updateList);
} catch (const dtn::storage::NoBundleFoundException &ex) {
IBRCOMMON_LOGGER_DEBUG_TAG(TAG, 10) << "NoBundleFound from filter" << IBRCOMMON_LOGGER_ENDL;
}
/*dtn::data::Bundle bundle = dtn::core::BundleCore::getInstance().getStorage().get(meta);
dtn::data::GeoRoutingBlock &grblock = bundle.find<dtn::data::GeoRoutingBlock>();
if (grblock.getRoute().empty()) {
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "eventBundleQueued(): The geo route block should not be empty!" << IBRCOMMON_LOGGER_ENDL;
} else {
grblock.getRoute().pop_back();
dtn::core::BundleCore::getInstance().getStorage().remove(meta);
dtn::core::BundleCore::getInstance().getStorage().store(bundle);
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "eventBundleQueued(): Popped off the last entry upon receive" << IBRCOMMON_LOGGER_ENDL;
}*/
//}
}
// new bundles trigger a recheck for all neighbors
const std::set<dtn::core::Node> nl = dtn::core::BundleCore::getInstance().getConnectionManager().getNeighbors();
for (std::set<dtn::core::Node>::const_iterator iter = nl.begin(); iter != nl.end(); ++iter)
{
//IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Current peer string: "+peer.getString() << IBRCOMMON_LOGGER_ENDL;
//IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Current peer host: "+peer.getHost() << IBRCOMMON_LOGGER_ENDL;
const dtn::core::Node &n = (*iter);
//IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Current n string: "+n.getEID().getString() << IBRCOMMON_LOGGER_ENDL;
//IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Current n host: "+n.getEID().getHost() << IBRCOMMON_LOGGER_ENDL;
if (n.getEID() != peer)
{
// trigger all routing modules to search for bundles to forward
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Trigger: eventDataChanged()" << IBRCOMMON_LOGGER_ENDL;
eventDataChanged(n.getEID());
}
}
}
void BreadcrumbRoutingExtension::raiseEvent(const dtn::core::Event *evt) throw ()
{
//IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Received Event: "+(*evt).getName() << IBRCOMMON_LOGGER_ENDL;
try {
const dtn::core::TimeEvent &time = dynamic_cast<const dtn::core::TimeEvent&>(*evt);
ibrcommon::MutexLock l_ex(_next_exchange_mutex);
const dtn::data::Timestamp now = dtn::utils::Clock::getMonotonicTimestamp();
if ((_next_exchange_timestamp > 0) && (_next_exchange_timestamp < now))
{
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Push: NextExchangeTask()" << IBRCOMMON_LOGGER_ENDL;
_taskqueue.push( new NextExchangeTask() );
// define the next exchange timestamp
_next_exchange_timestamp = now + _next_exchange_timeout;
}
ibrcommon::MutexLock l_loc(_next_loc_update_mutex);
if ((_next_loc_update_timestamp > 0) && (_next_loc_update_timestamp < now))
{
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Push: UpdateMyLocationTask()" << IBRCOMMON_LOGGER_ENDL;
_taskqueue.push( new UpdateMyLocationTask() );
// define the next location update timestamp
_next_loc_update_timestamp = now + _next_loc_update_interval;
}
return;
} catch (const std::bad_cast&) { };
try {
const NodeHandshakeEvent &handshake = dynamic_cast<const NodeHandshakeEvent&>(*evt);
if (handshake.state == NodeHandshakeEvent::HANDSHAKE_REPLIED)
{
// transfer the next bundle to this destination
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Event: handshake replied" << IBRCOMMON_LOGGER_ENDL;
//_taskqueue.push( new SearchNextBundleTask( handshake.peer ) );
}
else if (handshake.state == NodeHandshakeEvent::HANDSHAKE_UPDATED)
{
// transfer the next bundle to this destination
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Event: handshake updated" << IBRCOMMON_LOGGER_ENDL;
_taskqueue.push( new SearchNextBundleTask( handshake.peer ) );
}
else if (handshake.state == NodeHandshakeEvent::HANDSHAKE_COMPLETED)
{
// transfer the next bundle to this destination
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Event: handshake completed" << IBRCOMMON_LOGGER_ENDL;
_taskqueue.push( new SearchNextBundleTask( handshake.peer ) );
}
return;
} catch (const std::bad_cast&) { };
/*try {
const BundleReceivedEvent &bundleEvent = dynamic_cast<const BundleReceivedEvent&>(*evt);
const dtn::data::MetaBundle m = dtn::data::MetaBundle::create(bundleEvent.bundle);
dtn::data::Bundle bundle = bundleEvent.bundle;
if (m.hasgeoroute) {
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Event: received geo route bundle" << IBRCOMMON_LOGGER_ENDL;
dtn::data::GeoRoutingBlock &grblock = bundle.find<dtn::data::GeoRoutingBlock>();
if (grblock.getRoute().empty()) {
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Event: The geo route block should not be empty!" << IBRCOMMON_LOGGER_ENDL;
return;
}
grblock.getRoute().pop_back();
dtn::core::BundleCore::getInstance().getStorage().remove(m);
dtn::core::BundleCore::getInstance().getStorage().store(bundle);
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Event: Popped off the last entry upon receive" << IBRCOMMON_LOGGER_ENDL;
}
} catch (const std::bad_cast&) { };*/
}
void BreadcrumbRoutingExtension::componentUp() throw ()
{
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "componentUp()" << IBRCOMMON_LOGGER_ENDL;
dtn::core::EventDispatcher<dtn::routing::NodeHandshakeEvent>::add(this);
dtn::core::EventDispatcher<dtn::core::TimeEvent>::add(this);
//dtn::core::EventDispatcher<dtn::net::BundleReceivedEvent>::add(this);
// reset the task queue
_taskqueue.reset();
// routine checked for throw() on 15.02.2013
try {
// run the thread
start();
} catch (const ibrcommon::ThreadException &ex) {
IBRCOMMON_LOGGER_TAG(BreadcrumbRoutingExtension::TAG, error) << "componentUp failed: " << ex.what() << IBRCOMMON_LOGGER_ENDL;
}
}
void BreadcrumbRoutingExtension::componentDown() throw ()
{
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "componentDown()" << IBRCOMMON_LOGGER_ENDL;
dtn::core::EventDispatcher<dtn::routing::NodeHandshakeEvent>::remove(this);
dtn::core::EventDispatcher<dtn::core::TimeEvent>::remove(this);
//dtn::core::EventDispatcher<dtn::net::BundleReceivedEvent>::remove(this);
try {
// stop the thread
stop();
join();
} catch (const ibrcommon::ThreadException &ex) {
IBRCOMMON_LOGGER_TAG(BreadcrumbRoutingExtension::TAG, error) << "componentDown failed: " << ex.what() << IBRCOMMON_LOGGER_ENDL;
}
}
void BreadcrumbRoutingExtension::__cancellation() throw ()
{
_taskqueue.abort();
}
void BreadcrumbRoutingExtension::run() throw ()
{
class BundleFilter : public dtn::storage::BundleSelector
{
public:
BundleFilter(const NeighborDatabase::NeighborEntry &entry, const std::set<dtn::core::Node> &neighbors, const GeoLocation &peerloc, const GeoLocation &myloc)
: _entry(entry), _neighbors(neighbors), _peerloc(peerloc), _myloc(myloc)
{};
virtual ~BundleFilter() {};
virtual dtn::data::Size limit() const throw () { return _entry.getFreeTransferSlots(); };
virtual bool shouldAdd(const dtn::data::MetaBundle &meta) const throw (dtn::storage::BundleSelectorException)
{
// check Scope Control Block - do not forward bundles with hop limit == 0
if (meta.hopcount == 0)
{
return false;
}
// do not forward local bundles
if ((meta.destination.getNode() == dtn::core::BundleCore::local)
&& meta.get(dtn::data::PrimaryBlock::DESTINATION_IS_SINGLETON)
)
{
return false;
}
// check Scope Control Block - do not forward non-group bundles with hop limit <= 1
if ((meta.hopcount <= 1) && (meta.get(dtn::data::PrimaryBlock::DESTINATION_IS_SINGLETON)))
{
return false;
}
// do not forward bundles addressed to this neighbor,
// because this is handled by neighbor routing extension
if (_entry.eid == meta.destination.getNode())
{
return false;
}
// if this is a singleton bundle ...
if (meta.get(dtn::data::PrimaryBlock::DESTINATION_IS_SINGLETON))
{
const dtn::core::Node n(meta.destination.getNode());
// do not forward the bundle if the final destination is available
if (_neighbors.find(n) != _neighbors.end())
{
return false;
}
}
// do not forward bundles already known by the destination
// throws BloomfilterNotAvailableException if no filter is available or it is expired
try {
if (_entry.has(meta, true))
{
return false;
}
} catch (const dtn::routing::NeighborDatabase::BloomfilterNotAvailableException&) {
throw dtn::storage::BundleSelectorException();
}
if (meta.reacheddest) {
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Destination reached" << IBRCOMMON_LOGGER_ENDL;
return false;
}
// block is a GeoRoutingBlock
if (meta.hasgeoroute)
{
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "MetaBundle has georoute" << IBRCOMMON_LOGGER_ENDL;
// send if closer
float peerLat = (_peerloc._geopoint.getLatitude() - meta.nextgeohop.geopoint.getLatitude());
float peerLong = (_peerloc._geopoint.getLongitude() - meta.nextgeohop.geopoint.getLongitude());
float myLat = (_myloc._geopoint.getLatitude() - meta.nextgeohop.geopoint.getLatitude());
float myLong = (_myloc._geopoint.getLongitude() - meta.nextgeohop.geopoint.getLongitude());
if ( sqrt(peerLat*peerLat + peerLong*peerLong) < sqrt(myLat*myLat + myLong*myLong) ) {
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Peer is closer: Adding bundle with geo route to send list" << IBRCOMMON_LOGGER_ENDL;
return true;
}
if (checkMargin(_peerloc, meta.nextgeohop)) {
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Peer is at location: Adding bundle with geo route to send list" << IBRCOMMON_LOGGER_ENDL;
return true;
} else {
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Not adding bundle with geo route to send list" << IBRCOMMON_LOGGER_ENDL;
return false;
}
}
// if entry's (i.e., the potential destination) location does not match,
return true;
};
private:
const NeighborDatabase::NeighborEntry &_entry;
const std::set<dtn::core::Node> &_neighbors;
const dtn::routing::GeoLocation &_peerloc;
const dtn::routing::GeoLocation &_myloc;
};
class UpdateBundleFilter : public dtn::storage::BundleSelector {
public:
UpdateBundleFilter(const GeoLocation &myloc) : _myloc(myloc) {};
virtual ~UpdateBundleFilter() {};
virtual dtn::data::Size limit() const throw () { return dtn::core::BundleCore::getInstance().getStorage().size(); };
virtual bool shouldAdd(const dtn::data::MetaBundle &meta) const throw (dtn::storage::BundleSelectorException) {
if (meta.reacheddest) {
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "UpdateFilter: Destination reached" << IBRCOMMON_LOGGER_ENDL;
return false;
}
if (meta.hasgeoroute) {
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "UpdateFilter: MetaBundle has georoute" << IBRCOMMON_LOGGER_ENDL;
// check if the new location is the next hop to see if it's worth going through the bundle
if (checkMargin(_myloc, meta.nextgeohop)) {
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "UpdateFilter: Location match found, adding to list" << IBRCOMMON_LOGGER_ENDL;
return true;
} else {
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "UpdateFilter: No location match found" << IBRCOMMON_LOGGER_ENDL;
return false;
}
}
return false;
}
private:
const GeoLocation &_myloc;
};
// list for bundles
dtn::storage::BundleResultList list;
// set of known neighbors
std::set<dtn::core::Node> neighbors;
while (true)
{
try {
Task *t = _taskqueue.getnpop(true);
std::auto_ptr<Task> killer(t);
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Processing: " << t->toString() << IBRCOMMON_LOGGER_ENDL;
try {
/**
* SearchNextBundleTask triggers a search for a bundle to transfer
* to another host. This Task is generated by TransferCompleted, TransferAborted
* and node events.
*/
try {
SearchNextBundleTask &task = dynamic_cast<SearchNextBundleTask&>(*t);
// lock the neighbor database while searching for bundles
try {
NeighborDatabase &db = (**this).getNeighborDB();
ibrcommon::MutexLock l(db);
NeighborDatabase::NeighborEntry &entry = db.get(task.eid, true);
// check if enough transfer slots available (threshold reached)
if (!entry.isTransferThresholdReached())
throw NeighborDatabase::NoMoreTransfersAvailable();
if (dtn::daemon::Configuration::getInstance().getNetwork().doPreferDirect()) {
// get current neighbor list
//IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "get neighbor list" << IBRCOMMON_LOGGER_ENDL;
neighbors = dtn::core::BundleCore::getInstance().getConnectionManager().getNeighbors();
} else {
// "prefer direct" option disabled - clear the list of neighbors
neighbors.clear();
}
// GeoLocation query
const GeoLocation &gl = entry.getDataset<GeoLocation>();
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Found location: [" << task.eid.getString() << "," << gl << "]" << IBRCOMMON_LOGGER_ENDL;
// get the bundle filter of the neighbor
const BundleFilter filter(entry, neighbors, gl, _location);
// query some unknown bundle from the storage
list.clear();
(**this).getSeeker().get(filter, list);
if (list.empty()) {
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "List is empty!" << IBRCOMMON_LOGGER_ENDL;
}
} catch (const NeighborDatabase::DatasetNotAvailableException&) {
// if there is no GeoLocation for this peer do handshake with them
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "No GeoLocation available from " << task.eid.getString() << ", triggering doHandshake()" << IBRCOMMON_LOGGER_ENDL;
(**this).doHandshake(task.eid);
} catch (const dtn::storage::BundleSelectorException&) {
// query a new summary vector from this neighbor
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "No summary vector available from " << task.eid.getString() << ", triggering doHandshake()" << IBRCOMMON_LOGGER_ENDL;
(**this).doHandshake(task.eid);
}
// send the bundles as long as we have resources
for (std::list<dtn::data::MetaBundle>::const_iterator iter = list.begin(); iter != list.end(); ++iter)
{
try {
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Transfer bundle" << IBRCOMMON_LOGGER_ENDL;
/*if ((*iter).hasgeoroute) {
dtn::data::Bundle bundle = dtn::core::BundleCore::getInstance().getStorage().get(*iter);
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Updating bundle at transfer point" << IBRCOMMON_LOGGER_ENDL;
try {
dtn::data::GeoRoutingBlock &grblock = bundle.find<dtn::data::GeoRoutingBlock>();
// check if there are entries left
if (grblock.getRoute().empty()) {
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Transfer: No more georoute entries for this bundle, but there should be!" << IBRCOMMON_LOGGER_ENDL;
continue;
}
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Transfer: Popping last entry prior to transfer" << IBRCOMMON_LOGGER_ENDL;
grblock.getRoute().pop_back();
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Transfer: Removing outdated bundle and replacing it in storage" << IBRCOMMON_LOGGER_ENDL;
dtn::core::BundleCore::getInstance().getStorage().remove(*iter);
dtn::core::BundleCore::getInstance().getStorage().store(bundle);
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Transfer: Successfully updated bundle" << IBRCOMMON_LOGGER_ENDL;
} catch (const dtn::data::Bundle::NoSuchBlockFoundException&) {
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Transfer: No georouting block, but flag is set. Should not be here!" << IBRCOMMON_LOGGER_ENDL;
}
}*/
// transfer the bundle to the neighbor
transferTo(task.eid, *iter);
} catch (const NeighborDatabase::AlreadyInTransitException&) { };
}
} catch (const NeighborDatabase::NoMoreTransfersAvailable &ex) {
IBRCOMMON_LOGGER_DEBUG_TAG(TAG, 10) << "task " << t->toString() << " aborted: " << ex.what() << IBRCOMMON_LOGGER_ENDL;
} catch (const NeighborDatabase::NeighborNotAvailableException &ex) {
IBRCOMMON_LOGGER_DEBUG_TAG(TAG, 10) << "task " << t->toString() << " aborted: " << ex.what() << IBRCOMMON_LOGGER_ENDL;
} catch (const dtn::storage::NoBundleFoundException &ex) {
IBRCOMMON_LOGGER_DEBUG_TAG(TAG, 10) << "task " << t->toString() << " aborted: " << ex.what() << IBRCOMMON_LOGGER_ENDL;
} catch (const std::bad_cast&) { };
try {
NextExchangeTask &task = dynamic_cast<NextExchangeTask&>(*t);
std::set<dtn::core::Node> neighbors = dtn::core::BundleCore::getInstance().getConnectionManager().getNeighbors();
std::set<dtn::core::Node>::const_iterator it;
for(it = neighbors.begin(); it != neighbors.end(); ++it)
{
try{
(**this).doHandshake(it->getEID());
} catch (const ibrcommon::Exception &ex) { }
}
} catch (const std::bad_cast&) { }
try {
UpdateMyLocationTask &task = dynamic_cast<UpdateMyLocationTask&>(*t);
updateMyLocation();
const UpdateBundleFilter updateFilter(_location);
dtn::storage::BundleResultList updateList;
updateList.clear();
(**this).getSeeker().get(updateFilter, updateList); // use the filter to acquire all bundles that need updates
updateBundleList(_location, updateList);
} catch (const dtn::storage::NoBundleFoundException &ex) {
IBRCOMMON_LOGGER_DEBUG_TAG(TAG, 10) << "NoBundleFound from filter" << IBRCOMMON_LOGGER_ENDL;
} catch (const std::bad_cast&) { }
} catch (const ibrcommon::Exception &ex) {
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 20) << "task failed: " << ex.what() << IBRCOMMON_LOGGER_ENDL;
}
} catch (const std::exception &ex) {
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 15) << "terminated due to " << ex.what() << IBRCOMMON_LOGGER_ENDL;
return;
}
yield();
}
}
void BreadcrumbRoutingExtension::updateBundleList(GeoLocation myloc, dtn::storage::BundleResultList bundleList) {
for (std::list<dtn::data::MetaBundle>::const_iterator iter = bundleList.begin(); iter != bundleList.end(); ++iter) {
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Update bundle based on location" << IBRCOMMON_LOGGER_ENDL;
if ((*iter).hasgeoroute) {
dtn::data::Bundle bundle = dtn::core::BundleCore::getInstance().getStorage().get(*iter);
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Updating bundle during location update" << IBRCOMMON_LOGGER_ENDL;
try {
dtn::data::GeoRoutingBlock &grblock = bundle.find<dtn::data::GeoRoutingBlock>();
bool donePruningEntries = false;
// NOTE: in this case the first lookup is redundant since the bundle would not be in this list if it did not need at least 1 pop
while (!donePruningEntries) {
// look at the last entry
dtn::data::GeoRoutingBlock::GeoRoutingEntry nextgeohop = grblock.getRoute().back();
if (checkMargin(myloc,nextgeohop)) {
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Update: Popping entry" << IBRCOMMON_LOGGER_ENDL;
grblock.getRoute().pop_back();
} else {
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Update: Done popping entries" << IBRCOMMON_LOGGER_ENDL;
donePruningEntries = true;
}
if (grblock.getRoute().empty()) {
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Update: No more entries, done popping" << IBRCOMMON_LOGGER_ENDL;
donePruningEntries = true;
} else {
dtn::data::GeoRoutingBlock::GeoRoutingEntry nextgeohop = grblock.getRoute().back();
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Update: Iterating to nextgeohop" << IBRCOMMON_LOGGER_ENDL;
}
}
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Update: Removing outdated bundle and replacing it in storage" << IBRCOMMON_LOGGER_ENDL;
dtn::core::BundleCore::getInstance().getStorage().remove(*iter);
dtn::core::BundleCore::getInstance().getStorage().store(bundle);
} catch (const dtn::data::Bundle::NoSuchBlockFoundException&) {
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Update: No georouting block, but flag is set. Should not be here!" << IBRCOMMON_LOGGER_ENDL;
}
}
}
}
bool BreadcrumbRoutingExtension::checkMargin(const dtn::routing::GeoLocation &base_location, const dtn::data::GeoRoutingBlock::GeoRoutingEntry &bundle_location)
{
float margin = bundle_location.getMargin();
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Current location: (" << base_location._geopoint.getLatitude() << "," << base_location._geopoint.getLongitude() << ")"<< IBRCOMMON_LOGGER_ENDL;
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Bundle location: (" << bundle_location.geopoint.getLatitude() << "," << bundle_location.geopoint.getLongitude() << ")"<< IBRCOMMON_LOGGER_ENDL;
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Margin: " << margin << IBRCOMMON_LOGGER_ENDL;
if ((abs(base_location._geopoint.getLatitude() - bundle_location.geopoint.getLatitude()) < margin)
&& (abs(base_location._geopoint.getLongitude() - bundle_location.geopoint.getLongitude()) < margin)) {
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "New location is in appropriate range of entry" << IBRCOMMON_LOGGER_ENDL;
return true;
} else {
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Peer NOT in range" << IBRCOMMON_LOGGER_ENDL;
return false;
}
}
void BreadcrumbRoutingExtension::updateMyLocation() {
std::string filename = "/usr/local/etc/vmt_gps_coord.txt";
std::ifstream ifs;
ifs.open("/usr/local/etc/vmt_gps_coord.txt");
if (!ifs.is_open()) {
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Could not open vmt_gps_coord file" << IBRCOMMON_LOGGER_ENDL;
return;
}
ifs.seekg(-1,ios_base::end);
char cur = '\0';
while( cur==EOF || cur=='\0' || cur=='\n' ) {
if ((int)ifs.tellg() <= 1) {
//IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "File has no location entries" << IBRCOMMON_LOGGER_ENDL;
return;
}
ifs.get(cur);
ifs.seekg(-2,ios_base::cur);
}
int end = (int)ifs.tellg()+1;
ifs.seekg(0,ios_base::beg);
while( cur!='\n' ) {
if ((int)ifs.tellg() <= 0) {
ifs.seekg(0,ios_base::beg);
break;
}
ifs.get(cur);
//IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Pos2: " << (int)ifs.tellg() << IBRCOMMON_LOGGER_ENDL;
//IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Cur2: " << cur << IBRCOMMON_LOGGER_ENDL;
ifs.seekg(-2,ios_base::cur);
}
int start = ifs.tellg();
char *entry = new char[end-start+1];
if (cur==EOF || cur=='\0' || cur=='\n') {
ifs.seekg(1,ios_base::cur);
}
ifs.read(entry,end-start); // read last line from file
entry[end-start] = 0x00;
std::string s(entry);
delete [] entry;
ifs.close();
//IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "full string to start: "+s << IBRCOMMON_LOGGER_ENDL;
s = s.substr(0,s.size()-1); // strip off EOF char from string
size_t pos = 0;
std::string latitude;
std::string longitude;
std::string tstamp;
std::string delim = ";";
// prune timestamp
pos = s.find(delim);
tstamp = s.substr(0,pos);
s.erase(0,pos+delim.length());
// get latitude
pos = s.find(delim);
latitude = s.substr(0,pos);
// get longitude
s.erase(0,pos+delim.length());
longitude = s;
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "GPS timestamp: "+tstamp << IBRCOMMON_LOGGER_ENDL;
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Updated latitude: "+latitude << IBRCOMMON_LOGGER_ENDL;
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Updated longitude: "+longitude << IBRCOMMON_LOGGER_ENDL;
//IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Updated latitude(as float): " << ::atof(latitude.c_str()) << IBRCOMMON_LOGGER_ENDL;
//IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Updated longitude(as float): " << ::atof(longitude.c_str()) << IBRCOMMON_LOGGER_ENDL;
_location._geopoint.set(::atof(latitude.c_str()), ::atof(longitude.c_str()));
IBRCOMMON_LOGGER_DEBUG_TAG(BreadcrumbRoutingExtension::TAG, 1) << "Updated location (as float): " << _location << IBRCOMMON_LOGGER_ENDL;
}
/****************************************/
BreadcrumbRoutingExtension::SearchNextBundleTask::SearchNextBundleTask(const dtn::data::EID &e)
: eid(e)
{ }
BreadcrumbRoutingExtension::SearchNextBundleTask::~SearchNextBundleTask()
{ }
std::string BreadcrumbRoutingExtension::SearchNextBundleTask::toString()
{
return "SearchNextBundleTask: " + eid.getString();
}
BreadcrumbRoutingExtension::NextExchangeTask::NextExchangeTask()
{
}
BreadcrumbRoutingExtension::NextExchangeTask::~NextExchangeTask()
{
}
std::string BreadcrumbRoutingExtension::NextExchangeTask::toString()
{
return "NextExchangeTask";
}
BreadcrumbRoutingExtension::UpdateMyLocationTask::UpdateMyLocationTask()
{
}
BreadcrumbRoutingExtension::UpdateMyLocationTask::~UpdateMyLocationTask()
{
}
std::string BreadcrumbRoutingExtension::UpdateMyLocationTask::toString()
{
return "UpdateMyLocationTask";
}
}
}
|
7cc4a973991e43986da84c691bcefebeb8062de7 | afa02ca05aa63d7ba7d752d4c80080c238c3959d | /src/Player.h | b83ba793428f2f208546223702058e48d4b9de00 | [] | no_license | nattfv/SabrePlusPlus | 512a4ae1321a651d24fc0b0ef88fb5d25536184c | 568080b5dd27c07d328569637f357773b4324690 | refs/heads/master | 2021-05-09T01:53:33.635140 | 2014-06-02T20:19:47 | 2014-06-02T20:19:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 871 | h | Player.h | /*
* Player.h
*
* Created on: Jan 27, 2014
* Author: sarniakjr
*/
#ifndef PLAYER_H_
#define PLAYER_H_
#include "Board.h"
#include "TileBag.h"
#include "Move.h"
#include <vector>
class Player {
public:
Player(std::string n, Board *b, TileBag *tb) :
name(n), board(b), move(b), points(0) {
}
virtual ~Player() {
}
std::string getName() const;
bool canUseField(Field *) const;
bool canRemoveTileFrom(Field *) const;
void putTile(Tile *, Field *);
void removeTile(Field *);
void takeTile(TileBag *);
int getHandSize() const;
std::vector<Tile *>::iterator handBegin();
std::vector<Tile *>::iterator handEnd();
Tile *pickTile(int idx) const;
Move *getMove();
int getPoints() const;
void addPoints(int);
private:
std::string name;
Board *board;
TileBag *bag;
std::vector<Tile *> hand;
Move move;
int points;
};
#endif /* PLAYER_H_ */
|
b7f0fdec395e15875a60e4e7e0767b975b447544 | 821b0cd7db54c96de5d4e24deb6f6d20952a1054 | /main.cpp | 4395f8a821207df450af382d21f6536fc88ff657 | [] | no_license | kornerr/lua-research | f7e4f67aefbca952d694d137f1ebca341f946013 | 1b149a9db9acbfd6a37ba18e200c088fd5139767 | refs/heads/master | 2021-01-01T19:31:15.976561 | 2017-07-29T05:46:34 | 2017-07-29T05:46:34 | 98,598,683 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,057 | cpp | main.cpp |
#include "colors.h"
#include "function.h"
bool loadLuaFile(lua_State *L, const char *fileName)
{
if (luaL_loadfile(L, fileName) || lua_pcall(L, 0, 0, 0))
{
printf(
"ERROR. Cannot load Lua file '%s': '%s'\n",
fileName,
lua_tostring(L, -1));
lua_pop(L, 1);
return false;
}
return true;
}
void readWidthHeight(lua_State *L, int *width, int *height)
{
// Width.
lua_getglobal(L, "width");
if (!lua_isnumber(L, -1))
{
printf("readWidthHeight. 'width' should be a number\n");
}
else
{
*width = (int)lua_tonumber(L, -1);
}
lua_pop(L, 1);
// Height.
lua_getglobal(L, "height");
if (!lua_isnumber(L, -1))
{
printf("readWidthHeight. 'height' should be a number\n");
}
else
{
*height = (int)lua_tonumber(L, -1);
}
lua_pop(L, 1);
}
int main(int argc, char *argv[])
{
if (argc != 2) {
printf("Usage: %s /path/to/cfg.lua\n", argv[0]);
return 1;
}
const char *fileName = argv[1];
// Create lua state.
lua_State *L = luaL_newstate();
luaL_openlibs(L);
// Register mylib.
luaopen_mylib(L);
setupPredefinedColors(L);
if (loadLuaFile(L, fileName))
{
// Read width and height.
int width = 0;
int height = 0;
readWidthHeight(L, &width, &height);
printf("main. width: '%d' height: '%d'\n", width, height);
// Read background color.
unsigned char r = 0;
unsigned char g = 0;
unsigned char b = 0;
readColor(L, "background", &r, &g, &b);
printf("main. background: '%d, %d, %d'\n", r, g, b);
readColor(L, "foreground", &r, &g, &b);
printf("main. foreground: '%d, %d, %d'\n", r, g, b);
// Execute function.
double x = 20;
double y = 3;
double f = functionF(L, x, y);
printf("main. '%f' = functionF(%f, %f)\n", f, x, y);
}
// Close lua state.
lua_close(L);
return 0;
}
|
3b4e6da06ceadfae8dbc259395b67cbecc8fb438 | ea7d278a54b88e45f414ca1f091de173da2951fc | /Proffy/DebugEventCallbacks.cpp | 69ee4c08805000b2748a9a0f6333a7998d9a5b0c | [
"ISC"
] | permissive | pauldoo/proffy | 191e2600178aaaea30f926a5509443810f8416fc | bd0494422073610f75e9768f7bd90d992a34ca31 | refs/heads/master | 2020-03-27T03:40:12.826532 | 2016-01-22T21:17:42 | 2016-01-22T21:17:42 | 568,783 | 24 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 10,901 | cpp | DebugEventCallbacks.cpp | /*
Copyright (c) 2008, 2009, 2012 Paul Richards <paul.richards@gmail.com>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "stdafx.h"
#include "DebugEventCallbacks.h"
#include "Assert.h"
#include "ConsoleColor.h"
#include "Exception.h"
#include "Utilities.h"
namespace Proffy {
DebugEventCallbacks::DebugEventCallbacks(SymbolCache* const cache) :
fSymbolCache(cache)
{
}
DebugEventCallbacks::~DebugEventCallbacks()
{
}
HRESULT __stdcall DebugEventCallbacks::QueryInterface(REFIID interfaceId, PVOID* result)
{
ConsoleColor c(Color_Yellow);
std::cout << __FUNCTION__ << "\n";
*result = NULL;
if (IsEqualIID(interfaceId, __uuidof(IUnknown)) ||
IsEqualIID(interfaceId, __uuidof(IDebugEventCallbacks))) {
*result = this;
AddRef();
return S_OK;
} else {
return E_NOINTERFACE;
}
}
ULONG __stdcall DebugEventCallbacks::AddRef(void)
{
return 1;
}
ULONG __stdcall DebugEventCallbacks::Release(void)
{
return 0;
}
HRESULT __stdcall DebugEventCallbacks::GetInterestMask(ULONG* mask)
{
*mask =
//DEBUG_EVENT_BREAKPOINT |
//DEBUG_EVENT_EXCEPTION |
//DEBUG_EVENT_CREATE_THREAD |
//DEBUG_EVENT_EXIT_THREAD |
//DEBUG_EVENT_CREATE_PROCESS |
//DEBUG_EVENT_EXIT_PROCESS |
//DEBUG_EVENT_LOAD_MODULE |
//DEBUG_EVENT_UNLOAD_MODULE |
//DEBUG_EVENT_SYSTEM_ERROR |
//DEBUG_EVENT_SESSION_STATUS |
//DEBUG_EVENT_CHANGE_DEBUGGEE_STATE |
//DEBUG_EVENT_CHANGE_ENGINE_STATE |
DEBUG_EVENT_CHANGE_SYMBOL_STATE |
0;
return S_OK;
}
HRESULT __stdcall DebugEventCallbacks::ChangeEngineState(
ULONG flags,
ULONG64 argument)
{
ConsoleColor c(Color_Cyan);
std::cout << __FUNCTION__ ": Begin.\n";
if (flags & DEBUG_CES_CURRENT_THREAD) {
flags &= ~DEBUG_CES_CURRENT_THREAD;
std::cout << "The current thread has changed, which implies that the current target and current process might also have changed.\n";
}
if (flags & DEBUG_CES_EFFECTIVE_PROCESSOR) {
flags &= ~DEBUG_CES_EFFECTIVE_PROCESSOR;
std::cout << "The effective processor has changed.\n";
}
if (flags & DEBUG_CES_BREAKPOINTS) {
flags &= ~DEBUG_CES_BREAKPOINTS;
std::cout << "One or more breakpoints have changed.\n";
}
if (flags & DEBUG_CES_CODE_LEVEL) {
flags &= ~DEBUG_CES_CODE_LEVEL;
std::cout << "The code interpretation level has changed.\n";
}
if (flags & DEBUG_CES_EXECUTION_STATUS) {
flags &= ~DEBUG_CES_EXECUTION_STATUS;
std::cout << "The execution status has changed.\n";
const bool insideWait = (argument & DEBUG_STATUS_INSIDE_WAIT) != 0;
std::cout << " Inside wait: " << insideWait << "\n";
std::cout << " Status: " << Utilities::DebugStatusReportToString(argument & ~DEBUG_STATUS_INSIDE_WAIT) << "\n";
}
if (flags & DEBUG_CES_ENGINE_OPTIONS) {
flags &= ~DEBUG_CES_ENGINE_OPTIONS;
std::cout << "The engine options have changed.\n";
}
if (flags & DEBUG_CES_LOG_FILE) {
flags &= ~DEBUG_CES_LOG_FILE;
std::cout << "The log file has been opened or closed.\n";
}
if (flags & DEBUG_CES_RADIX) {
flags &= ~DEBUG_CES_RADIX;
std::cout << "The default radix has changed.\n";
}
if (flags & DEBUG_CES_EVENT_FILTERS) {
flags &= ~DEBUG_CES_EVENT_FILTERS;
std::cout << "The event filters have changed.\n";
}
if (flags & DEBUG_CES_PROCESS_OPTIONS) {
flags &= ~DEBUG_CES_PROCESS_OPTIONS;
std::cout << "The process options for the current process have changed.\n";
}
if (flags & DEBUG_CES_EXTENSIONS) {
flags &= ~DEBUG_CES_EXTENSIONS;
std::cout << "Extension DLLs have been loaded or unloaded. (For more information, see Loading Debugger Extension DLLs.)\n";
}
if (flags & DEBUG_CES_SYSTEMS) {
flags &= ~DEBUG_CES_SYSTEMS;
std::cout << "A target has been added or removed.\n";
}
if (flags & DEBUG_CES_ASSEMBLY_OPTIONS) {
flags &= ~DEBUG_CES_ASSEMBLY_OPTIONS;
std::cout << "The assemble options have changed.\n";
}
if (flags & DEBUG_CES_EXPRESSION_SYNTAX) {
flags &= ~DEBUG_CES_EXPRESSION_SYNTAX;
std::cout << "The default expression syntax has changed.\n";
}
if (flags & DEBUG_CES_TEXT_REPLACEMENTS) {
flags &= ~DEBUG_CES_TEXT_REPLACEMENTS;
std::cout << "Text replacements have changed.\n";
}
if (flags != 0) {
std::ostringstream message;
message << "Unknown flag: " << flags;
throw Proffy::Exception(message.str());
}
std::cout << __FUNCTION__ ": End.\n";
return S_OK;
}
HRESULT __stdcall DebugEventCallbacks::Breakpoint(IDebugBreakpoint* /*breakpoint*/)
{
ASSERT(false);
ConsoleColor c(Color_Cyan);
std::cout << __FUNCTION__ << "\n";
return S_OK;
}
HRESULT __stdcall DebugEventCallbacks::Exception(
EXCEPTION_RECORD64* exception,
ULONG firstChance)
{
ASSERT(false);
exception;
firstChance;
ConsoleColor c(Color_Cyan);
std::cout << __FUNCTION__ << "\n";
return DEBUG_STATUS_GO_HANDLED;
}
HRESULT __stdcall DebugEventCallbacks::CreateThread(
ULONG64 /*handle*/,
ULONG64 /*dataOffset*/,
ULONG64 /*startOffset*/)
{
ASSERT(false);
ConsoleColor c(Color_Cyan);
std::cout << __FUNCTION__ << "\n";
return S_OK;
}
HRESULT __stdcall DebugEventCallbacks::ChangeSymbolState(
ULONG flags,
ULONG64 /*argument*/)
{
/*
ConsoleColor c(Color_Cyan);
std::cout << __FUNCTION__ << "\n";
*/
switch (flags) {
case DEBUG_CSS_SCOPE:
// Ignore
break;
case DEBUG_CSS_LOADS:
case DEBUG_CSS_UNLOADS:
case DEBUG_CSS_PATHS:
case DEBUG_CSS_SYMBOL_OPTIONS:
case DEBUG_CSS_TYPE_OPTIONS:
{
ConsoleColor c(Color_Cyan);
std::cout << __FUNCTION__ ": Clearing symbol cache.\n";
fSymbolCache->clear();
break;
}
default:
ASSERT(false);
}
return S_OK;
}
HRESULT __stdcall DebugEventCallbacks::ChangeDebuggeeState(
ULONG flags,
ULONG64 /*argument*/)
{
ConsoleColor c(Color_Cyan);
std::cout << __FUNCTION__ << "\n";
switch (flags) {
case DEBUG_CDS_ALL:
std::cout << " All\n";
break;
case DEBUG_CDS_REGISTERS:
std::cout << " Registers\n";
break;
case DEBUG_CDS_DATA:
std::cout << " Data\n";
break;
default:
std::cout << " " << flags << "\n";
}
return S_OK;
}
HRESULT __stdcall DebugEventCallbacks::SessionStatus(
ULONG status)
{
ConsoleColor c(Color_Cyan);
std::cout << __FUNCTION__ << ": " << Utilities::DebugSessionStatusToString(status) << "\n";
return S_OK;
}
HRESULT __stdcall DebugEventCallbacks::SystemError(
ULONG error,
ULONG level)
{
ASSERT(false);
error;
level;
ConsoleColor c(Color_Cyan);
std::cout << __FUNCTION__ << "\n";
__debugbreak();
return S_OK;
}
HRESULT __stdcall DebugEventCallbacks::UnloadModule(
PCSTR /*imageBaseName*/,
ULONG64 /*baseOffset*/)
{
ASSERT(false);
ConsoleColor c(Color_Cyan);
std::cout << __FUNCTION__ << "\n";
return S_OK;
}
HRESULT __stdcall DebugEventCallbacks::LoadModule(
ULONG64 imageFileHandle,
ULONG64 baseOffset,
ULONG moduleSize,
PCSTR moduleName,
PCSTR imageName,
ULONG checkSum,
ULONG timeDateStamp)
{
ASSERT(false);
imageFileHandle;
baseOffset;
moduleSize;
moduleName;
imageName;
checkSum;
timeDateStamp;
ConsoleColor c(Color_Cyan);
std::cout << __FUNCTION__ << "\n";
return S_OK;
}
HRESULT __stdcall DebugEventCallbacks::ExitProcess(
ULONG /*exitCode*/)
{
ASSERT(false);
ConsoleColor c(Color_Cyan);
std::cout << __FUNCTION__ << "\n";
return S_OK;
}
HRESULT __stdcall DebugEventCallbacks::CreateProcess(
ULONG64 /*imageFileHandle*/,
ULONG64 /*handle*/,
ULONG64 /*baseOffset*/,
ULONG /*moduleSize*/,
PCSTR /*moduleName*/,
PCSTR /*imageName*/,
ULONG /*checkSum*/,
ULONG /*timeDateStamp*/,
ULONG64 /*initialThreadHandle*/,
ULONG64 /*threadDataOffset*/,
ULONG64 /*startOffset*/)
{
ASSERT(false);
ConsoleColor c(Color_Cyan);
std::cout << __FUNCTION__ << "\n";
return S_OK;
}
HRESULT __stdcall DebugEventCallbacks::ExitThread(
ULONG /*exitCode*/)
{
ASSERT(false);
ConsoleColor c(Color_Cyan);
std::cout << __FUNCTION__ << "\n";
return S_OK;
}
}
|
b12603d44378d2589ae9c9fb7688c36217fae76b | 9cd52e90be49244a525e15a7790f574747f3ea3b | /Collector.h | 32190ff504574ae93eb7d56201d1184f1744cbb8 | [] | no_license | achicu/mycompiler | 0a4fe5da0de3f2efb60c22ad5a0cf798dc0c3841 | e4d10f363c0c89c622e96e9a95134849924796ee | refs/heads/master | 2021-01-01T16:05:03.368462 | 2009-09-17T15:01:51 | 2009-09-17T15:01:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,741 | h | Collector.h | /*
* Collector.h
* lex
*
* Created by Alexandru Chiculita on 9/14/09.
*
*/
#ifndef COLLECTOR_H
#define COLLECTOR_H
#include <vector>
#include "RefCounted.h"
class RegisterFile;
template<size_t bytesPerWord> struct CellSize;
template<> struct CellSize<sizeof(uint32_t)> { static const size_t m_value = 64; }; // 32-bit
template<> struct CellSize<sizeof(uint64_t)> { static const size_t m_value = 128; }; // 64-bit
const size_t BLOCK_SIZE = 16 * 4096; // 64k
const size_t BLOCK_OFFSET_MASK = BLOCK_SIZE - 1;
const size_t BLOCK_MASK = ~BLOCK_OFFSET_MASK;
const size_t MINIMUM_CELL_SIZE = CellSize<sizeof(void*)>::m_value;
const size_t CELL_ARRAY_LENGTH = (MINIMUM_CELL_SIZE / sizeof(double)) + (MINIMUM_CELL_SIZE % sizeof(double) != 0 ? sizeof(double) : 0);
const size_t CELL_SIZE = CELL_ARRAY_LENGTH * sizeof(double);
const size_t CELL_MASK = CELL_SIZE - 1;
const size_t CELL_ALIGN_MASK = ~CELL_MASK;
const size_t CELLS_PER_BLOCK = (BLOCK_SIZE * 8 - sizeof(uint32_t) * 8 - sizeof(void *) * 8 - 2 * (7 + 3 * 8)) / (CELL_SIZE * 8 + 2);
const size_t BITMAP_SIZE = (CELLS_PER_BLOCK + 7) / 8;
const size_t BITMAP_WORDS = (BITMAP_SIZE + 3) / sizeof(uint32_t);
struct CollectorBitmap {
uint32_t bits[BITMAP_WORDS];
bool Get(size_t n) const { return !!(bits[n >> 5] & (1 << (n & 0x1F))); }
void Set(size_t n) { bits[n >> 5] |= (1 << (n & 0x1F)); }
void Clear(size_t n) { bits[n >> 5] &= ~(1 << (n & 0x1F)); }
void ClearAll() { memset(bits, 0, sizeof(bits)); }
};
struct CollectorCell {
union {
double memory[CELL_ARRAY_LENGTH];
struct {
void* zeroIfFree; // this will actually contain the virtual table
ptrdiff_t next;
} freeCell;
} u;
};
class Heap;
class CollectorBlock {
public:
CollectorCell cells[CELLS_PER_BLOCK];
uint32_t usedCells;
CollectorCell* freeList;
CollectorBitmap marked;
Heap* heap;
};
class Type;
class CollectorRef
{
public:
virtual ~CollectorRef();
virtual void Mark();
bool IsMarked() const;
void* operator new(size_t size);
virtual Type* GetType() const = 0;
};
class GlobalData;
class Heap: public RefCounted
{
public:
Heap(GlobalData* globalData)
: m_globalData(globalData)
{
s_currentHeap = this;
}
virtual ~Heap();
void* Allocate(size_t size);
bool Collect();
static CollectorBlock* CellBlock(const CollectorRef* cell);
static size_t CellOffset(const CollectorRef* cell);
static bool IsCellMarked(const CollectorRef*);
static void MarkCell(CollectorRef*);
static Heap* CurrentHeap() { return s_currentHeap; }
GlobalData* GetGlobalData() const { return m_globalData; }
private:
void MarkRegisterFile();
bool CreateNewBlock();
GlobalData* m_globalData;
std::vector<CollectorBlock*> m_blocks;
static Heap* s_currentHeap;
};
inline CollectorBlock* Heap::CellBlock(const CollectorRef* cell)
{
return reinterpret_cast<CollectorBlock*>(reinterpret_cast<uintptr_t>(cell) & BLOCK_MASK);
}
inline size_t Heap::CellOffset(const CollectorRef* cell)
{
return (reinterpret_cast<uintptr_t>(cell) & BLOCK_OFFSET_MASK) / CELL_SIZE;
}
inline bool Heap::IsCellMarked(const CollectorRef* cell)
{
return CellBlock(cell)->marked.Get(CellOffset(cell));
}
inline void Heap::MarkCell(CollectorRef* cell)
{
CellBlock(cell)->marked.Set(CellOffset(cell));
}
inline bool CollectorRef::IsMarked() const
{
return Heap::IsCellMarked(this);
}
inline void CollectorRef::Mark()
{
assert(!Heap::IsCellMarked(this));
Heap::MarkCell(this);
}
inline void* CollectorRef::operator new(size_t size)
{
return Heap::CurrentHeap()->Allocate(size);
}
#endif // COLLECTOR_H |
1351fbfadaa9b900e3c5af0871c863bf9d76b9ef | c5fea32065e03070d1543a4eb580aaa41851412d | /linearregression.cpp | 19ab001f5ef83b1949226fb73bcfd3ecb87da492 | [
"Unlicense"
] | permissive | kyosheek/multidimensional_linear_regression | 2d27ba4fc4c31f7054d818e51cac1ec4e0bf8697 | 7c13e7db36bdf52202593f3054947c1ce856c51e | refs/heads/master | 2021-09-02T04:59:14.427827 | 2017-12-30T15:13:58 | 2017-12-30T15:13:58 | 115,803,834 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,089 | cpp | linearregression.cpp | #include <iostream>
#include "linearregression.h"
using namespace std;
LinearRegression::LinearRegression(double x[], double y[], int m) {
this->x = x;
this->y = y;
this->m = m;
}
void LinearRegression::train(double alpha, int iter) {
auto *J = new double[iter];
this->t = graident_descent(x, y, alpha, J, iter, m);
cout << "J = ";
for (int i = 0; i < iter; ++i) {
cout << J[i] << ' ';
}
cout << endl;
cout << "Theta: " << t[0] << ' ' << t[1] << endl;
}
double LinearRegression::predict(double x) {
return h(x, t);
}
double LinearRegression::calc_cost(double x[], double y[], double t[], int m) {
double *preds = calc_pred(x, t, m);
auto *diff = new double[m];
for (int i = 0; i < m; ++i) { diff[i] = preds[i] - y[i]; }
auto *sq_errors = new double[m];
for (int i = 0; i < m; ++i) { sq_errors[i] = pow(diff[i], 2); }
double s = 0;
for (int i = 0; i < m; ++i) { s += sq_errors[i]; }
return ((1.0 / (2 * m)) * s);
}
double LinearRegression::h(double x, double t[]) {
return t[0] + x * t[1];
}
double *LinearRegression::calc_pred(double x[], double t[], int m) {
auto *pred = new double[m];
//calculate h for each training data set
for (int i = 0; i < m; ++i) { pred[i] = LinearRegression::h(x[i], t); }
return pred;
}
double *LinearRegression::graident_descent(double x[], double y[], double alpha, double *J, int iter, int m) {
auto t = new double[2];
t[0] = 1; t[1] = 1;
for (int i = 0; i < iter; ++i) {
auto *pred = LinearRegression::calc_pred(x, t, m);
auto *diff = new double[m];
for (int j = 0; j < m; ++j) { diff[j] = pred[j] - y[j]; }
auto *errors_x1 = diff;
auto *errors_x2 = new double[m];
for (int j = 0; j < m; ++j) { errors_x2[j] = diff[j] * x[j]; }
double sum = 0;
for (int j = 0; j < m; ++j) { sum += errors_x1[j]; }
t[0] = t[0] - alpha * (1.0 / m) * sum;
sum = 0;
for (int j = 0; j < m; ++j) { sum += errors_x2[j]; }
t[1] = t[1] - alpha * (1.0 / m) * sum;
J[i] = LinearRegression::calc_cost(x, y, t, m);
}
return t;
} |
3fedc965ebe59e01ab320e36cc0c04fd2a71839b | 1ef7b2a0fbcab871896b05c358de903c011b2473 | /casbin/rbac_api.cpp | 5ab2d3d392cbfab9b0b5371e848f4f3a4323ec62 | [
"Apache-2.0"
] | permissive | casbin/casbin-cpp | 88d6fc2f9ea0e17d8efbdf212c83dc81c2175de7 | 3e4241300808d72ba56bf6139c5339c7ce16beb2 | refs/heads/master | 2023-09-04T09:05:14.545386 | 2023-08-08T05:33:02 | 2023-08-08T05:33:02 | 243,148,805 | 221 | 90 | Apache-2.0 | 2023-09-11T18:28:29 | 2020-02-26T02:22:05 | C++ | UTF-8 | C++ | false | false | 9,313 | cpp | rbac_api.cpp | /*
* Copyright 2020 The casbin Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "casbin/pch.h"
#ifndef RBAC_API_CPP
#define RBAC_API_CPP
#include "casbin/enforcer.h"
#include "casbin/exception/casbin_enforcer_exception.h"
#include "casbin/util/util.h"
namespace casbin {
// GetRolesForUser gets the roles that a user has.
std::vector<std::string> Enforcer ::GetRolesForUser(const std::string& name, const std::vector<std::string>& domain) {
std::vector<std::string> res = m_model->m["g"].assertion_map["g"]->rm->GetRoles(name, domain);
return res;
}
// GetUsersForRole gets the users that has a role.
std::vector<std::string> Enforcer ::GetUsersForRole(const std::string& name, const std::vector<std::string>& domain) {
std::vector<std::string> res = m_model->m["g"].assertion_map["g"]->rm->GetUsers(name, domain);
return res;
}
// HasRoleForUser determines whether a user has a role.
bool Enforcer ::HasRoleForUser(const std::string& name, const std::string& role) {
std::vector<std::string> domain;
std::vector<std::string> roles = this->GetRolesForUser(name, domain);
bool has_role = false;
for (int i = 0; i < roles.size(); i++) {
if (roles[i] == role) {
has_role = true;
break;
}
}
return has_role;
}
// AddRoleForUser adds a role for a user.
// Returns false if the user already has the role (aka not affected).
bool Enforcer ::AddRoleForUser(const std::string& user, const std::string& role) {
std::vector<std::string> params{user, role};
return this->AddGroupingPolicy(params);
}
// AddRolesForUser adds roles for a user.
// Returns false if the user already has the roles (aka not affected).
bool Enforcer ::AddRolesForUser(const std::string& user, const std::vector<std::string>& roles) {
bool f = false;
for (int i = 0; i < roles.size(); i++) {
bool b = this->AddGroupingPolicy({user, roles[i]});
if (b)
f = true;
}
return f;
}
// DeleteRoleForUser deletes a role for a user.
// Returns false if the user does not have the role (aka not affected).
bool Enforcer ::DeleteRoleForUser(const std::string& user, const std::string& role) {
std::vector<std::string> params{user, role};
return this->RemoveGroupingPolicy(params);
}
// DeleteRolesForUser deletes all roles for a user.
// Returns false if the user does not have any roles (aka not affected).
bool Enforcer ::DeleteRolesForUser(const std::string& user) {
std::vector<std::string> field_values{user};
return this->RemoveFilteredGroupingPolicy(0, field_values);
}
// DeleteUser deletes a user.
// Returns false if the user does not exist (aka not affected).
bool Enforcer ::DeleteUser(const std::string& user) {
std::vector<std::string> field_values{user};
bool res1 = this->RemoveFilteredGroupingPolicy(0, field_values);
bool res2 = this->RemoveFilteredPolicy(0, field_values);
return res1 || res2;
}
// DeleteRole deletes a role.
// Returns false if the role does not exist (aka not affected).
bool Enforcer ::DeleteRole(const std::string& role) {
std::vector<std::string> field_values{role};
bool res1 = this->RemoveFilteredGroupingPolicy(1, field_values);
bool res2 = this->RemoveFilteredPolicy(0, field_values);
return res1 || res2;
}
// DeletePermission deletes a permission.
// Returns false if the permission does not exist (aka not affected).
bool Enforcer ::DeletePermission(const std::vector<std::string>& permission) {
std::vector<std::string> field_values{permission};
return this->RemoveFilteredPolicy(1, field_values);
}
// AddPermissionForUser adds a permission for a user or role.
// Returns false if the user or role already has the permission (aka not affected).
bool Enforcer ::AddPermissionForUser(const std::string& user, const std::vector<std::string>& permission) {
return this->AddPolicy(JoinSlice(user, permission));
}
// DeletePermissionForUser deletes a permission for a user or role.
// Returns false if the user or role does not have the permission (aka not affected).
bool Enforcer ::DeletePermissionForUser(const std::string& user, const std::vector<std::string>& permission) {
return this->RemovePolicy(JoinSlice(user, permission));
}
// DeletePermissionsForUser deletes permissions for a user or role.
// Returns false if the user or role does not have any permissions (aka not affected).
bool Enforcer ::DeletePermissionsForUser(const std::string& user) {
std::vector<std::string> field_values{user};
return this->RemoveFilteredPolicy(0, field_values);
}
// GetPermissionsForUser gets permissions for a user or role.
std::vector<std::vector<std::string>> Enforcer ::GetPermissionsForUser(const std::string& user) {
std::vector<std::string> field_values{user};
return this->GetFilteredPolicy(0, field_values);
}
// HasPermissionForUser determines whether a user has a permission.
bool Enforcer ::HasPermissionForUser(const std::string& user, const std::vector<std::string>& permission) {
return this->HasPolicy(JoinSlice(user, permission));
}
// GetImplicitRolesForUser gets implicit roles that a user has.
// Compared to GetRolesForUser(), this function retrieves indirect roles besides direct roles.
// For example:
// g, alice, role:admin
// g, role:admin, role:user
//
// GetRolesForUser("alice") can only get: ["role:admin"].
// But GetImplicitRolesForUser("alice") will get: ["role:admin", "role:user"].
std::vector<std::string> Enforcer ::GetImplicitRolesForUser(const std::string& name, const std::vector<std::string>& domain) {
std::vector<std::string> res;
std::unordered_map<std::string, bool> role_set;
role_set[name] = true;
std::vector<std::string> q;
q.push_back(name);
while (q.size() > 0) {
std::string name = q[0];
q.erase(q.begin());
std::vector<std::string> roles = rm->GetRoles(name, domain);
for (int i = 0; i < roles.size(); i++) {
if (!(role_set.find(roles[i]) != role_set.end())) {
res.push_back(roles[i]);
q.push_back(roles[i]);
role_set[roles[i]] = true;
}
}
}
return res;
}
// GetImplicitPermissionsForUser gets implicit permissions for a user or role.
// Compared to GetPermissionsForUser(), this function retrieves permissions for inherited roles.
// For example:
// p, admin, data1, read
// p, alice, data2, read
// g, alice, admin
//
// GetPermissionsForUser("alice") can only get: [["alice", "data2", "read"]].
// But GetImplicitPermissionsForUser("alice") will get: [["admin", "data1", "read"], ["alice", "data2", "read"]].
std::vector<std::vector<std::string>> Enforcer ::GetImplicitPermissionsForUser(const std::string& user, const std::vector<std::string>& domain) {
std::vector<std::string> roles = this->GetImplicitRolesForUser(user, domain);
roles.insert(roles.begin(), user);
bool with_domain = false;
if (domain.size() == 1)
with_domain = true;
else if (domain.size() > 1)
throw CasbinEnforcerException("Domain should be 1 parameter");
std::vector<std::vector<std::string>> res;
std::vector<std::vector<std::string>> permissions;
for (int i = 0; i < roles.size(); i++) {
if (with_domain)
permissions = this->GetPermissionsForUserInDomain(roles[i], domain[0]);
else
permissions = this->GetPermissionsForUser(roles[i]);
for (int i = 0; i < permissions.size(); i++)
res.push_back(permissions[i]);
}
return res;
}
// GetImplicitUsersForPermission gets implicit users for a permission.
// For example:
// p, admin, data1, read
// p, bob, data1, read
// g, alice, admin
//
// GetImplicitUsersForPermission("data1", "read") will get: ["alice", "bob"].
// Note: only users will be returned, roles (2nd arg in "g") will be excluded.
std::vector<std::string> Enforcer ::GetImplicitUsersForPermission(const std::vector<std::string>& permission) {
std::vector<std::string> p_subjects = this->GetAllSubjects();
std::vector<std::string> g_inherit = m_model->GetValuesForFieldInPolicyAllTypes("g", 1);
std::vector<std::string> g_subjects = m_model->GetValuesForFieldInPolicyAllTypes("g", 0);
std::vector<std::string> subjects(p_subjects);
subjects.insert(subjects.end(), g_subjects.begin(), g_subjects.end());
ArrayRemoveDuplicates(subjects);
std::vector<std::string> res;
for (int i = 0; i < subjects.size(); i++) {
bool allowed = this->Enforce({subjects[i], permission[0], permission[1]});
if (allowed) {
res.push_back(subjects[i]);
}
}
res = SetSubtract(res, g_inherit);
return res;
}
} // namespace casbin
#endif // RBAC_API_CPP
|
eda6d9264fd5e4cedc64d0b140ea109544a89846 | 75593770082f839c23d9aaac7fb1e32d97c18a7b | /Core/Core.h | 197010e01c3dbee7e47ef6667462a64c0373921f | [] | no_license | cn1504/Core | 51aa96ec802efe61c16d854e7a9e4024abf69236 | 11fbc8acfecc0eaeb69de3195f2823c26a8bb00e | refs/heads/master | 2020-04-05T23:07:34.178914 | 2014-06-18T19:45:11 | 2014-06-18T19:45:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,407 | h | Core.h | // Standard Engine Includes
#pragma comment(linker, "/SUBSYSTEM:windows /ENTRY:mainCRTStartup") // Hides the console window
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <list>
#include <deque>
#include <unordered_map>
#include <iomanip>
#include <memory>
#include <functional>
#include <chrono>
#include <stdexcept>
#include <thread>
#include <future>
#define GLEW_STATIC
#include <GL/glew.h>
#pragma comment(lib, "glew32s.lib")
#pragma comment(lib, "opengl32.lib")
#include <CL/cl.hpp>
#pragma comment(lib, "OpenCL.lib")
#include <AL/al.h>
#include <AL/alc.h>
#include <AL/alext.h>
#pragma comment(lib, "libOpenAL32.dll.a")
#include <sndfile.h>
#pragma comment(lib, "libsndfile-1.lib")
#include <GLFW/glfw3.h>
#pragma comment(lib, "glfw3.lib")
#include <glm/glm.hpp>
#include <glm/ext.hpp>
//#include <glm/gtx/quaternion.hpp>
#include <libtexture.h>
#pragma comment(lib, "libtexture.lib")
#include <Bullet/btBulletDynamicsCommon.h>
#include <Bullet/BulletSoftBody/btSoftRigidDynamicsWorld.h>
#include <Bullet/BulletSoftBody/btSoftBodyRigidBodyCollisionConfiguration.h>
#include <Bullet/BulletSoftBody/btSoftBodyHelpers.h>
#pragma comment(lib, "Bullet.lib")
#include "Exceptions.h"
#include "Settings.h"
#include "Debug.h"
#include "Time.h"
namespace Core
{
// Forward Declarations
class Entity;
class Component;
class Renderable;
}
|
20c42da52a25d87ff2ce986e4609941a92acd6b9 | 8f03c97d56a4de714ce4c91e7450f28eb1d14d49 | /SD_write_test/SD_write_test.ino | 4ce167df4e4c7913dc24314826472399b125f9c7 | [] | no_license | MichaelDouglass/hand_tracking_device | 7b2233937d590967264fbe4e946feba9d072727a | b847b10c7caf924c32c086c99a2c88d694d3e976 | refs/heads/master | 2020-05-18T03:13:32.643620 | 2019-05-08T07:18:09 | 2019-05-08T07:18:09 | 184,138,770 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,938 | ino | SD_write_test.ino | #include <SD.h>
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BNO055.h>
#include <utility/imumaths.h>
Adafruit_BNO055 bno = Adafruit_BNO055(55);
File myFile;
void setup()
{
Serial.begin(9600);
Serial.print("Initializing SD card...");
// On the Ethernet Shield, CS is pin 4. It's set as an output by default.
// Note that even if it's not used as the CS pin, the hardware SS pin
// (10 on most Arduino boards, 53 on the Mega) must be left as an output
// or the SD library functions will not work.
pinMode(10, OUTPUT);
if (!SD.begin(10)) {
Serial.println("initialization failed!");
return;
}
if(!bno.begin())
{
/* There was a problem detecting the BNO055 ... check your connections */
Serial.print("Ooops, no BNO055 detected ... Check your wiring or I2C ADDR!");
while(1);
}
delay(1000);
bno.setExtCrystalUse(true);
Serial.println("initialization done.");
// open the file. note that only one file can be open at a time,
// so you have to close this one before opening another.
}
void loop()
{
myFile = SD.open("gyro.txt", FILE_WRITE);
sensors_event_t event;
bno.getEvent(&event);
int x = int(event.orientation.x);
int y = int(event.orientation.y);
int z = int(event.orientation.z);
/* Display the floating point data */
Serial.print("X: ");
Serial.print(x);
Serial.print("\tY: ");
Serial.print(y);
Serial.print("\tZ: ");
Serial.print(z);
Serial.println("");
// if the file opened okay, write to it:
if (myFile) {
Serial.print("Writing to gyro.txt...");
myFile.print(x);
myFile.print("\t");
myFile.print(y);
myFile.print("\t");
myFile.print(z);
myFile.print("\t");
myFile.println(millis());
// close the file:
myFile.close();
Serial.println("done.");
} else {
// if the file didn't open, print an error:
Serial.println("error opening gyro.txt");
}
delay(750);
}
|
c379d72d7283da899da571ede10708df45c6b9b6 | 4173182847aeefa4e075b87a0f76feb07b4e2221 | /lab-3/lab-3-cpp/src/dpa_definition.cpp | 4df0d464022d0253d7b5c0011103a156f5bc2a17 | [] | no_license | hermanzdosilovic/utr | 4a5ecbbb7e4e867c29b4be6fa3655dbc1b2954f8 | c4ac9d4e305f271dd50bb5d5cd9246d16ff9e4e8 | refs/heads/master | 2020-07-19T10:31:45.969864 | 2015-05-31T12:42:04 | 2015-05-31T12:42:04 | 32,258,922 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,111 | cpp | dpa_definition.cpp | #include "dpa_definition.h"
DPADefinition::DPADefinition() {
}
void DPADefinition::Read() {
states_ = ReadStates();
alphabet_ = ReadAlphabet();
stack_symbols_ = ReadStackSymbols();
acceptable_states_ = ReadAcceptableStates();
initial_state_ = ReadInitialState();
initial_stack_symbol_ = ReadInitialStackSymbol();
}
vector<State> DPADefinition::ReadStates() {
vector<State> states;
string line;
cin >> line;
for (string state_name : Split(line, ","))
states.push_back(State(state_name));
return states;
}
vector<Symbol> DPADefinition::ReadAlphabet() {
vector<Symbol> alphabet;
string line;
cin >> line;
for (string symbol_name : Split(line, ","))
alphabet.push_back(Symbol(symbol_name));
return alphabet;
}
vector<Symbol> DPADefinition::ReadStackSymbols() {
return ReadAlphabet();
}
vector<State> DPADefinition::ReadAcceptableStates() {
return ReadStates();
}
State DPADefinition::ReadInitialState() {
string line;
cin >> line;
return State(line);
}
Symbol DPADefinition::ReadInitialStackSymbol() {
string line;
cin >> line;
return Symbol(line);
}
|
a67798c0b79fd0b7fa8774a6008c306ff65e359f | a524ec3e87c62c6db1c7859b79b0730ff3ffe7fc | /lib/shmem/src/concurrentsync/semaphore.cpp | 937d670e8e965c64b2361f7141d58330fe96ab04 | [
"BSD-3-Clause"
] | permissive | nickeskov/AdvCpp_hw | cb1fcce67dbbf59d68d3b3c76eca0b95140e4cf5 | 304dc53b34843aed4b618887af196c51e7d7b2bf | refs/heads/master | 2023-05-25T23:34:42.874858 | 2023-05-11T22:51:22 | 2023-05-11T22:51:22 | 248,765,497 | 0 | 0 | BSD-3-Clause | 2023-05-11T22:51:23 | 2020-03-20T13:43:35 | C++ | UTF-8 | C++ | false | false | 1,373 | cpp | semaphore.cpp | #include "shmem/concurrentsync/semaphore.h"
#include "shmem/errors.h"
#include <cerrno>
#include <utility>
namespace shmem::concurrentsync {
Semaphore::Semaphore(bool is_process_semaphore, unsigned int value): is_empty_(false) {
if (::sem_init(&semaphore_, static_cast<int>(is_process_semaphore), value) < 0) {
throw errors::SemaphoreInitError("cannot init unix semaphore");
}
}
Semaphore::Semaphore(Semaphore &&other) noexcept {
swap(other);
}
Semaphore &Semaphore::operator=(Semaphore &&other) noexcept {
if (this == &other) {
return *this;
}
Semaphore().swap(*this);
swap(other);
return *this;
}
void Semaphore::swap(Semaphore &other) noexcept {
std::swap(semaphore_, other.semaphore_);
std::swap(is_empty_, other.is_empty_);
}
void Semaphore::wait() {
if (::sem_wait(&semaphore_)) {
throw errors::SemaphoreWaitError("semaphore wait error");
}
}
bool Semaphore::try_wait() {
if (::sem_trywait(&semaphore_) < 0) {
if (errno != EAGAIN) {
throw errors::SemaphoreTryWaitError("semaphore try_wait error");
}
return false;
}
return true;
}
void Semaphore::post() {
if (::sem_post(&semaphore_)) {
throw errors::SemaphorePostError("semaphore post error");
}
}
Semaphore::~Semaphore() noexcept {
::sem_destroy(&semaphore_);
}
}
|
ee9028ce7e658cb6d15234c2c8e8e90a6d5a1517 | a3d6556180e74af7b555f8d47d3fea55b94bcbda | /components/omnibox/browser/inline_autocompletion_util_unittest.cc | f533f324eb0e854314f0496ac9f9e1a62a38715c | [
"BSD-3-Clause"
] | permissive | chromium/chromium | aaa9eda10115b50b0616d2f1aed5ef35d1d779d6 | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | refs/heads/main | 2023-08-24T00:35:12.585945 | 2023-08-23T22:01:11 | 2023-08-23T22:01:11 | 120,360,765 | 17,408 | 7,102 | BSD-3-Clause | 2023-09-10T23:44:27 | 2018-02-05T20:55:32 | null | UTF-8 | C++ | false | false | 832 | cc | inline_autocompletion_util_unittest.cc | // Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/omnibox/browser/inline_autocompletion_util.h"
#include <stddef.h>
#include "base/strings/utf_string_conversions.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
TEST(InlineAutocompletionUtilTest, FindAtWordbreak) {
// Should find the first wordbreak occurrence.
EXPECT_EQ(FindAtWordbreak(u"prefixmatch wordbreak_match", u"match"), 22u);
// Should return npos when no occurrences exist.
EXPECT_EQ(FindAtWordbreak(u"prefixmatch", u"match"), std::string::npos);
// Should skip occurrences before |search_start|.
EXPECT_EQ(FindAtWordbreak(u"match match", u"match", 1), 6u);
}
} // namespace
|
97c98b2af65ccf571724957a11ef5b5ad401e0cb | 548b5edfa38f557878cc71ecd93d5441fdc1b73e | /Площадь n-угольника на плоскости/main.cpp | 67a302ad79abdcc67a13ab60464d1649f9767465 | [] | no_license | pmpu-133/general | 63ecfed396c6d561abfe7c87bc448ce6a0a581ef | b86f3e5107857ec94555c523f8c4892f3b7a613b | refs/heads/master | 2020-04-25T04:23:57.447159 | 2019-11-17T19:07:24 | 2019-11-17T19:07:24 | 172,509,018 | 1 | 2 | null | 2019-11-17T19:07:25 | 2019-02-25T13:15:43 | C++ | UTF-8 | C++ | false | false | 1,005 | cpp | main.cpp | #include <bits/stdc++.h>
using namespace std;
struct Vector{
double x, y;
Vector (double _x=0, double _y=0) {
x = _x;
y = _y;
}
Vector operator * (double a) {
return Vector (a * x, a * y);
}
double operator ^ (Vector a) {
return x * a.y - a.x * y;
}
Vector operator / (double a) {
return Vector (x / a, y / a);
}
Vector operator + (Vector a) {
return Vector (a.x + x, a.y + y);
}
Vector operator - (Vector a) {
return Vector (x - a.x, y - a.y);
}
};
int main()
{
// freopen("square.in", "r", stdin);
//freopen("square.out", "w", stdout);
double ans = 0, n;
Vector a, b, first;
cin >> n;
cin >> first.x >> first.y;
a = first;
for (int i = 1; i < n; i++)
{
cin >> b.x >> b.y;
ans = ans + (b ^ a);
a = b;
}
ans = ans + (first ^ a);
cout.precision(5);
cout << fixed << abs(ans / 2);
return 0;
}
|
912f8dd17cd519a948f5356b8d6cdf53e8287e9a | f0f1063b5e6917ab6450d35b7bf5ffba4255c29b | /source/SensorData/main.cpp | 15feb0a3d3b228149bdb0dfcafec8cd71fe048ea | [] | no_license | zerohachiko/SensorData | a1462e114690b44a3a408dec46e01d316dc6069c | e277d60d246502cdec02ca3a7635bf785b4759f3 | refs/heads/master | 2020-07-04T02:13:57.104908 | 2016-11-26T03:29:08 | 2016-11-26T03:29:08 | 74,219,080 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,772 | cpp | main.cpp | #include "HttpPost.h"
#include <QApplication>
#include "QDir"
#include <QDebug>
#include <QDate>
#include <QTime>
#include <QTextCodec>
void customMessageHandler(QtMsgType type, const char *msg)
{
QString txt;
switch (type) {
//调试信息提示
case QtDebugMsg:
txt = QString("Debug: %1").arg(msg);
break;
//一般的warning提示
case QtWarningMsg:
txt = QString("Warning: %1").arg(msg);
break;
//严重错误提示
case QtCriticalMsg:
txt = QString("Critical: %1").arg(msg);
break;
//致命错误提示
case QtFatalMsg:
txt = QString("Fatal: %1").arg(msg);
abort();
}
QFile outFile1("./debuglog1.txt");
QFile outFile2("./debuglog2.txt");
QDateTime current_date_time = QDateTime::currentDateTime();
QString current_date = current_date_time.toString("yyyy-MM-dd hh:mm:ss ddd");
QString txt2 = txt.append("(").append(current_date).append(")");
outFile1.open(QIODevice::WriteOnly | QIODevice::Append);
if(outFile1.size() >= 1024*1000 )
{
outFile1.close();
outFile2.remove();
QFile::copy("./debuglog1.txt","./debuglog2.txt");
outFile1.remove();
QFile outFile3("./debuglog1.txt");
outFile3.open(QIODevice::WriteOnly | QIODevice::Append);
QTextStream ts(&outFile3);
ts << txt2 << endl;
}
else
{
QTextStream ts(&outFile1);
ts << txt2 << endl;
}
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QDir dir;
QTextCodec *codec = QTextCodec::codecForName("UTF-8");
QTextCodec::setCodecForTr(codec);
QTextCodec::setCodecForLocale(codec);
QTextCodec::setCodecForCStrings(codec);
qInstallMsgHandler(customMessageHandler);
qDebug() << dir.currentPath();
HttpPost post;
post.show();
return app.exec();
} |
8d4947b2e6d5c8e00423e600a2a76f246688512e | 4eddea9fee782e0d5ae1f9ca43326fd5de9cb053 | /Charts/WidgetCharts/piechart/donutbreakdown/donutbreakdownchart.h | 006dc37e1b3074f35c5b35ff349a399eb09d6b84 | [] | no_license | joesGit15/Qt | b4bc1d6ad89958ad740dd0e6fcb85d6ad67b0f41 | 373679af75e3d2fc38512ed0c34dd6f6c5b947d7 | refs/heads/master | 2022-01-25T17:24:33.763192 | 2022-01-06T15:01:23 | 2022-01-06T15:01:23 | 100,150,203 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 528 | h | donutbreakdownchart.h | #ifndef DONUTBREAKDOWNCHART_H
#define DONUTBREAKDOWNCHART_H
#include <QtCharts/QChart>
namespace QtCharts {
class QPieSeries;
}
using namespace QtCharts;
class DonutBreakdownChart : public QChart
{
public:
DonutBreakdownChart(QGraphicsItem *parent = 0, Qt::WindowFlags wFlags = 0);
void addBreakdownSeries(QPieSeries *series, QColor color);
private:
void recalculateAngles();
void updateLegendMarkers();
private:
QPieSeries *_mainSeries;
};
#endif // DONUTBREAKDOWNCHART_H
|
977d2309cb1f6867af6e92092e903cdaac4242a8 | 7f8ad1557d8aff2fb67738f4b8a7830642203fbc | /src/core/pinhole_camera_info.cpp | f381d5a6cd452cb76285fc7ed28603f6f95797e7 | [
"BSD-3-Clause"
] | permissive | Lab-RoCoCo/fps_mapper | c8afb9533edbecb9c9fe47a3cd4c4928dee2b8eb | 376e557c8f5012e05187fe85ee3f4044f99f944a | refs/heads/master | 2021-01-10T18:47:13.211881 | 2015-07-25T14:14:53 | 2015-07-25T14:14:53 | 35,717,494 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,156 | cpp | pinhole_camera_info.cpp | #include "pinhole_camera_info.h"
namespace fps_mapper {
using namespace std;
PinholeCameraInfo::PinholeCameraInfo(const std::string& topic_,
const std::string& frame_id,
const Eigen::Matrix3f& camera_matrix,
const Eigen::Isometry3f&offset_,
float depth_scale_,
int id,
boss::IdContext* context):
BaseCameraInfo(topic_, frame_id, offset_, depth_scale_, id,context){
_camera_matrix = camera_matrix;
}
BaseCameraInfo* PinholeCameraInfo::scale(float s) {
PinholeCameraInfo* shrunk_cam=new PinholeCameraInfo(_topic,
_frame_id,
_camera_matrix,
_offset,
_depth_scale);
shrunk_cam->_camera_matrix.block<2,3>(0,0)*=s;
return shrunk_cam;
}
void PinholeCameraInfo::serialize(boss::ObjectData& data, boss::IdContext& context){
BaseCameraInfo::serialize(data,context);
_camera_matrix.toBOSS(data, "camera_matrix");
}
void PinholeCameraInfo::deserialize(boss::ObjectData& data, boss::IdContext& context){
BaseCameraInfo::deserialize(data,context);
_camera_matrix.fromBOSS(data, "camera_matrix");
}
BOSS_REGISTER_CLASS(PinholeCameraInfo);
}
|
74e9009f92c2982fecfa31a6b6d40d10773b1a26 | bc84ffab49351bed0cd4edaf4f55be2ef8fe8da5 | /NQueensProblem/NQueensProblem/main.cpp | c92e0e4539da87646631ddea47a8748c637d1943 | [] | no_license | jjhartmann/strident-octo-weasel | 8b81682d621e48a0e9725fc1586e507a3a80baf1 | d7489b5362547a8b913e459db0254a9de7c5eca8 | refs/heads/master | 2020-04-12T02:31:17.091513 | 2018-02-21T20:21:47 | 2018-02-21T20:21:47 | 45,711,022 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,008 | cpp | main.cpp | //////////////////////////////////////////////////////////////
// Main - N Queens Problem
#include <iostream>
#include <vector>
using namespace std;
typedef pair<int, int> Point;
////////////////////////////////////////////////////////////////
// Chessboard Class
class ChessBoard
{
public:
ChessBoard(int n) :
mDim(n),
mBoard(n*n, "-")
{
;
}
int getDimensions()
{
return mDim;
}
void mark(Point p, string id = "+")
{
if (p.first >= mDim || p.second >= mDim) return;
mBoard[p.second * mDim + p.first] = id;
}
void printBoard()
{
for (int i = 0; i < mDim; ++i)
{
for (int j = 0; j < mDim; ++j)
{
string tmp = mBoard[i * mDim + j] + " ";
cout << tmp.c_str();
}
cout << endl;
}
cout << endl;
}
bool isFree(Point p)
{
if (p.first >= mDim || p.second >= mDim) return false;
return mBoard[p.second * mDim + p.first] == "-";
}
// Is in range
bool isInRange(Point p)
{
return p.first < mDim && p.second < mDim;
}
// Reset the board;
void reset()
{
for (int i = 0; i < mBoard.size(); ++i)
{
mBoard[i] = "-";
}
}
private:
vector<string> mBoard;
int mDim;
};
////////////////////////////////////////////////////////////////
// Queen Class
class Queen
{
public:
Queen() :
mPlacement(-1, -1)
{}
bool isPlaced()
{
if (mPlacement.first >= 0)
return true;
return false;
}
// Place and mark chess board
void place(Point p, ChessBoard &b)
{
mPlacement = p;
int dim = b.getDimensions();
Point diag1(p.first, p.second);
for (int i = 0; i < dim; i++)
{
if (diag1.first - 1 < 0 || diag1.second - 1 < 0)
break;
diag1.first--;
diag1.second--;
}
Point diag2(p.first, p.second);
for (int i = 0; i < dim; i++)
{
if (diag2.first - 1 < 0 || diag2.second >= dim)
break;
diag2.first--;
diag2.second++;
}
for (int i = 0; i < dim; ++i)
{
// Column
b.mark(Point(p.first, i));
// Row
b.mark(Point(i, p.second));
// Diagonal one
if (diag1.first < dim && diag1.second < dim);
{
b.mark(diag1);
diag1.first++;
diag1.second++;
}
// Diagonal two
if (diag2.first< dim && diag2.second >= 0)
{
b.mark(diag2);
diag2.first++;
diag2.second--;
}
}
// Mark Queen
string id = "X";
b.mark(mPlacement, id);
}
// Reset placement
void reset()
{
mPlacement.first = -1;
mPlacement.second = -1;
}
private:
Point mPlacement;
};
/////////////////////////////////////////////////////////////
// Game:
class Game
{
public:
Game(int mDim, int nQueens) :
mQueen(nQueens),
mBoard(mDim)
{
;
}
~Game()
{
;
}
// Find Configurations for n Queens
bool Process()
{
Point start(0, 0);
int qIndex = 0;
while (mBoard.isInRange(start))
{
while (mBoard.isInRange(start))
{
// Place first Queen
mQueen[0].place(start, mBoard);
// Try all queens
for (int i = 1; i < mQueen.size(); ++i)
{
Point p(0,0);
bool placed = false;
while (mBoard.isInRange(p) && !placed)
{
while (mBoard.isInRange(p) && !placed)
{
if (mBoard.isFree(p))
{
mQueen[i].place(p, mBoard);
placed = true;
}
// INcrement col
p.first++;
}
// Set col to 0
p.first = 0;
// Increment row
p.second++;
}
}
// Print Board
mBoard.printBoard();
// Check for all queens passsing.
bool allPassed = true;
for (int i = 0; i < mQueen.size(); ++i)
{
if (!mQueen[i].isPlaced())
allPassed = false;
}
if (allPassed)
return true;
// Reset queens
Reset();
start.first++;
}
start.first = 0;
start.second++;
}
return false;
}
// Print game Board;
void print()
{
mBoard.printBoard();
}
// Reset Queens
void Reset()
{
// Pick up all queens
for (int i = 0; i < mQueen.size(); ++i)
{
mQueen[i].reset();
}
// Reset the board;
mBoard.reset();
}
private:
vector<Queen> mQueen;
ChessBoard mBoard;
};
int main()
{
cout << "The N-Queens Problem" << endl;
//ChessBoard b(20);
//b.printBoard();
//Queen firstQ;
//firstQ.place(Point(10, 3), b);
//b.printBoard();
// Game
Game game(10,10);
game.print();
bool res = game.Process();
if (res) {
cout << "SOLUTION:" << endl;
}
else
{
cout << "NO SOLUTION:" << endl;
}
game.print();
return 0;
} |
0891d2d193e25160eac12e9e7c0ffbd05be4f43b | fa313b319b030d5e07ea9c715174674d0ce14dc6 | /hw6/copy.cc | 3d07bea48d63873b8e39821d2041cf8fdc37a7c0 | [] | no_license | fengshi99/homework | bae88d1eabfd0ca9b48fc7752a1a3f5500ff05f1 | 941c14a3dcc1b84b82963c9b40ddaf1cf73e9123 | refs/heads/master | 2020-04-16T10:02:21.603248 | 2019-01-17T07:41:25 | 2019-01-17T07:41:25 | 165,487,355 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 641 | cc | copy.cc | #include <iostream>
using std::cout;
using std::endl;
using std::cin;
class Point
{
private:
int _x;
int _y;
public:
Point() = default;
Point(int x,int y):_x(x),_y(y){}
~Point(){}
Point(const Point& P){
_x = P._x;
_y = P._y;
cout << "calling copy constructor! " << endl;
}
Point& operator=(const Point&);
void print()
{
cout << _x << "." << _y << endl;
}
};
Point& Point::operator=(const Point& P)
{
cout << "calling operator= " << endl;
_x = P._x;
_y = P._y;
return (*this);
}
int main()
{
Point p1(2,6);
Point p2 = p1;
p2.print();
Point p3 = Point(3,4);
p3.print();
p3 = p2;
p3.print();
return 0;
}
|
911d0e84253b9574c2e76c42e862673bf4be254e | 2b984e87cc5239bda08a9de7ddd31ad2a18774d5 | /baekjoon/11097.cpp | 4197a4cb9539b6a814ba0517289b4f26aff51a63 | [] | no_license | pce913/Algorithm | f862d0f450471c3b910bcf50e684caf856ec4165 | 1cb695972ea6804c8d669a9b606f1aaf87360af6 | refs/heads/master | 2022-02-08T06:51:39.537054 | 2022-01-31T16:20:03 | 2022-01-31T16:20:03 | 110,357,251 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 4,909 | cpp | 11097.cpp | #include<stdio.h>
#include<vector>
#include<cstring>
using namespace std;
int M[305][305];
int adj[305][305];
int parent[305];
int sccCnt;
bool check[305];
int Find(int x){
if (x == parent[x])
return x;
else
return parent[x] = Find(parent[x]);
}
void Union(int x,int y){
x = Find(x);
y = Find(y);
if (x != y){
parent[y] = x;
sccCnt++;
}
}
void solve(){
memset(adj, 0, sizeof(adj));
memset(check, false, sizeof(check));
int n;
scanf(" %d",&n);
for (int i = 1; i <= n; i++){
parent[i] = i;
}
for (int i = 1; i <= n; i++){
for (int j = 1; j <= n; j++){
scanf("%1d",&M[i][j]);
}
}
for (int i = 1; i <= n; i++){ //SCC를 n^2만에 만든다.
for (int j = 1; j <= n; j++){
if (M[i][j] && M[j][i]){
Union(i, j);
}
}
}
for (int i = 1; i <= n; i++){ //SCC간의 연결 그래프 생성
for (int j = 1; j <= n; j++){
if (M[i][j] && Find(i) != Find(j)){
adj[Find(i)][Find(j)] = 1;
}
}
}
for (int k = 1; k <= n; k++){
for (int i = 1; i <= n; i++){ //불필요한 간선 제거
for (int j = 1; j <= n; j++){
if (adj[Find(i)][Find(j)] && adj[Find(i)][Find(k)] && adj[Find(k)][Find(j)]){
adj[Find(i)][Find(j)] = 0;
}
}
}
}
vector< pair<int,int> > ans;
for (int i = 1; i <= n; i++){
int before = i;
for (int j = i + 1; j <= n; j++){
if (!check[i] && !check[j] && Find(i) == Find(j)){
check[j] = true;
ans.push_back({ before, j });
before = j;
}
}
if (before != i){
ans.push_back({ before, i });
}
check[i] = true;
}
for (int i = 1; i <= n; i++){
for (int j = 1; j <= n; j++){
if (adj[Find(i)][Find(j)]){
ans.push_back({ i, j });
adj[Find(i)][Find(j)] = 0;
}
}
}
printf("%d\n",ans.size());
for (int i = 0; i < ans.size(); i++){
printf("%d %d\n",ans[i].first,ans[i].second);
}
printf("\n");
}
int main(){
int T;
scanf("%d",&T);
for (int test = 1; test <= T; test++){
solve();
}
return 0;
}
//#include <stdio.h>
//#include<vector>
//using namespace std;
//#define REP(i,a,b) for(int i=a;i<=b;++i)
//#define FOR(i,n) for(int i=0;i<n;++i)
//#define pb push_back
//#define all(v) (v).begin(),(v).end()
//#define sz(v) ((int)(v).size())
//#define inp1(a) scanf("%d",&a)
//#define inp2(a,b) scanf("%d%d",&a,&b)
//#define inp3(a,b,c) scanf("%d%d%d",&a,&b,&c)
//#define inp4(a,b,c,d) scanf("%d%d%d%d",&a,&b,&c,&d)
//#define inp5(a,b,c,d,e) scanf("%d%d%d%d%d",&a,&b,&c,&d,&e)
//using namespace std;
//typedef long long ll;
//typedef pair<ll, ll> pll;
//typedef vector<int> vi;
//typedef vector<ll> vl;
//typedef pair<int, int> pii;
//typedef vector<pii> vii;
//typedef vector<pll> vll;
//typedef vector<vector<int> > vvi;
//typedef pair<int, pair<int, int> > piii;
//typedef vector<piii> viii;
//const double EPSILON = 1e-9;
//const double PI = acos(-1);
//const int MOD = 1e9 + 7;
//const int INF = 0x3c3c3c3c;
//const long long INFL = 0x3c3c3c3c3c3c3c3c;
//const int MAX_N = 102;
//
//int cango[303][303];
//int sccId[303];
//int N, T, sccCnt;
//int adj[303][303];
//vi sccMem[303];
//int main() {
// inp1(T);
// while (T--){
// sccCnt = 0;
// memset(sccId, -1, sizeof(sccId));
// memset(cango, 0, sizeof(cango));
// memset(adj, 0, sizeof(adj));
// FOR(i, 303) sccMem[i].clear();
// getchar();
// inp1(N);
// for (int i = 0; i < N; i++){
// for (int j = 0; j < N; j++){
// scanf("%1d", &cango[i][j]);
// }
// }
// for (int i = 0; i < N; i++){ //n^2 만에 SCC를 만든다.
// if (sccId[i] == -1)
// sccId[i] = sccCnt++, sccMem[sccId[i]].pb(i);
// for (int j = i + 1; j < N; j++){
// if (sccId[j] != -1) //이미 j 노드가 다른 scc에 포함되어 있다면 continue
// continue;
// if (cango[i][j] && cango[j][i])
// sccId[j] = sccId[i],sccMem[sccId[j]].pb(j);
// }
// }
//
// for (int i = 0; i < N; i++){
// for (int j = 0; j < N; j++){
// if (cango[i][j] && sccId[i] != sccId[j]) //i에서 j로 갈 수 있는데 서로 다른 그룹이면
// adj[sccId[i]][sccId[j]] = 1; //i에서 j로 가는 길목 하나를 놓아준다.
// }
// }
//
// for (int k = 0; k < sccCnt; k++){
// for (int i = 0; i < sccCnt; i++){
// for (int j = 0; j < sccCnt; j++){
// if (adj[i][j] && adj[i][k] && adj[k][j]) //불필요한 간선 제거.
// adj[i][j] = 0;
// }
// }
// }
//
// vii ans;
// for (int i = 0; i < sccCnt; i++){
// if (sccMem[i].size() <= 1)
// continue;
// for (int j = 0; j < sccMem[i].size(); j++){
// ans.pb({ sccMem[i][j], sccMem[i][(j + 1) % sccMem[i].size()] });
// }
// }
//
// for (int i = 0; i < sccCnt; i++){
// for (int j = 0; j < sccCnt; j++){
// if (adj[i][j])
// ans.pb({ sccMem[i][0], sccMem[j][0] }); //각 SCC 의 대표를 정해서 답으로 출력한다.
// }
// }
//
// printf("%d\n", ans.size());
// for (auto p : ans){
// printf("%d %d\n", p.first + 1, p.second + 1);
// }
// printf("\n");
// }
// return 0;
//} |
606997923ceee802b63217886c55b3927ae92e91 | e6148031b471d952dbf1615d05eb47013591216f | /code/Nowcoder2019/day2/H_zayin.cpp | ceab50bfdfabf534faa8e342280c142a628a0321 | [] | no_license | Dafenghh/Training_Summary | 1bdc2a3efaf5dd8e71f9c4a566c4245727769c57 | c38f8d2062a87ead98cf65f3255a5960351f6002 | refs/heads/master | 2021-06-03T11:49:03.488574 | 2020-02-09T16:19:53 | 2020-02-09T16:19:53 | 144,736,350 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,590 | cpp | H_zayin.cpp | #include<bits/stdc++.h>
#define maxn 1050
using namespace std;
int n,m;
char s[maxn];
int h[maxn];
int stk[maxn],tp;
int L[maxn],R[maxn];
int cnt[maxn][maxn];
int main() {
scanf("%d%d",&n,&m);
int ans=0;
for (int i=1;i<=n;++i) {
scanf("%s",s+1);
for (int j=1;j<=m;++j)
if (s[j]=='1')
++h[j];
else
h[j]=0;
stk[tp=0]=0;
for (int j=1;j<=m;++j) {
while (tp&&h[j]<h[stk[tp]]) --tp;
L[j]=stk[tp];
stk[++tp]=j;
}
stk[tp=0]=m+1;
for (int j=m;j;--j) {
while (tp&&h[j]<=h[stk[tp]]) --tp;
R[j]=stk[tp];
stk[++tp]=j;
}
for (int j=1;j<=m;++j)
// cout<<i<<" "<<j<<":"<<h[j]<<"*"<<R[j]-L[j]-1<<" "<<L[j]<<" "<<R[j]<<endl,
ans=max(ans,h[j]*(R[j]-L[j]-1)),
++cnt[h[j]][R[j]-L[j]-1];
}
int c=0;
for (int i=1;i<=n;++i)
for (int j=1;j<=m;++j)
if (cnt[i][j]&&i*j==ans)
c+=cnt[i][j];
// cout<<c<<endl;
if (c>1)
printf("%d\n",ans);
else {
int res=0;
for (int i=1;i<=n;++i)
for (int j=1;j<=m;++j) {
if (!cnt[i][j]) continue;
if (i*j==ans)
// cout<<(i-1)*j<<endl,cout<<i*(j-1)<<endl,
res=max(res,(i-1)*j),res=max(res,i*(j-1));
else
// cout<<i*j<<endl,
res=max(res,i*j);
}
printf("%d\n",res);
}
return 0;
}
|
6fc9a2bead2ab6eb96e1354ac8e01873359942c7 | f0b7bcc41298354b471a72a7eeafe349aa8655bf | /codebase/apps/cidd/src/CIDD/data_pu_proc.cc | 047ab028be9107dc149e0852aa99f40bdeb2a8d8 | [
"BSD-3-Clause"
] | permissive | NCAR/lrose-core | 23abeb4e4f1b287725dc659fb566a293aba70069 | be0d059240ca442883ae2993b6aa112011755688 | refs/heads/master | 2023-09-01T04:01:36.030960 | 2023-08-25T00:41:16 | 2023-08-25T00:41:16 | 51,408,988 | 90 | 53 | NOASSERTION | 2023-08-18T21:59:40 | 2016-02-09T23:36:25 | C++ | UTF-8 | C++ | false | false | 5,994 | cc | data_pu_proc.cc | // *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
// ** Copyright UCAR (c) 1990 - 2016
// ** University Corporation for Atmospheric Research (UCAR)
// ** National Center for Atmospheric Research (NCAR)
// ** Boulder, Colorado, USA
// ** BSD licence applies - redistribution and use in source and binary
// ** forms, with or without modification, are permitted provided that
// ** the following conditions are met:
// ** 1) If the software is modified to produce derivative works,
// ** such modified software should be clearly marked, so as not
// ** to confuse it with the version available from UCAR.
// ** 2) Redistributions of source code must retain the above copyright
// ** notice, this list of conditions and the following disclaimer.
// ** 3) 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.
// ** 4) Neither the name of UCAR nor the names of its contributors,
// ** if any, may be used to endorse or promote products derived from
// ** this software without specific prior written permission.
// ** DISCLAIMER: THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS
// ** OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
// ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
// *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
/*************************************************************************
* DATA_PU_PROC.c - Notify and event callback functions
*/
#define DATA_PU_PROC
#include "cidd.h"
/*************************************************************************
* Set proper flags which switching fields
*/
void set_field(int value)
{
int i;
int tmp;
static int last_page = 0;
static int last_value = 0;
static int cur_value = 0;
if(value < 0) {
tmp = last_page;
last_page = gd.h_win.page;
gd.h_win.page = tmp;
tmp = cur_value;
cur_value = last_value;
value = last_value;
last_value = tmp;
} else {
last_page = gd.h_win.page;
last_value = cur_value;
cur_value = value;
gd.h_win.page = gd.field_index[value];
}
for(i=0; i < gd.num_datafields; i++) {
if(gd.mrec[i]->auto_render == 0) gd.h_win.redraw[i] = 1;
}
if(gd.mrec[gd.h_win.page]->auto_render &&
gd.h_win.page_xid[gd.h_win.page] != 0 &&
gd.h_win.redraw[gd.h_win.page] == 0) {
save_h_movie_frame(gd.movie.cur_frame,
gd.h_win.page_xid[gd.h_win.page],
gd.h_win.page);
}
for(i=0; i < MAX_FRAMES; i++) {
gd.movie.frame[i].redraw_horiz = 1;
}
if(gd.movie.movie_on ) reset_data_valid_flags(1,0);
xv_set(gd.data_pu->data_st,PANEL_VALUE,value,NULL);
/* make sure the horiz window's slider has the correct label */
set_height_label();
}
/*************************************************************************
* Notify callback function for `data_st'.
*/
void set_data_proc( Panel_item item, int value, Event *event)
{
// Use Unused parameters
item = 0; event = NULL;
gd.last_event_time = time((time_t *) NULL);
set_field(value);
set_v_field(gd.field_index[value]);
}
/*************************************************************************
* Notify callback function for `group_list'.
*/
int
set_group_proc(Panel_item item, const char *string, Xv_opaque client_data, Panel_list_op op, Event *event, int row)
{
int i,j;
char *ptr;
char *ptr2;
char buf[8192];
char *buf2;
for(i=0; i < gd.num_datafields; i++) {
gd.mrec[i]->currently_displayed = FALSE;
xv_set(gd.fields_pu->display_list,PANEL_LIST_SELECT, i, FALSE,NULL);
}
for(j=0 ; j < gd.gui_P->field_list_n; j++) { // Loop through each group button
if(xv_get(gd.data_pu->group_list,PANEL_LIST_SELECTED,j)) { // If group is selected
// Scan through each data grid/field and see if its in the group list
for(i=0; i < gd.num_datafields; i++) {
ptr = gd.gui_P->_field_list[j].grid_list;
strncpy(buf,gd.gui_P->_field_list[j].grid_list,8192);
ptr = strtok_r(buf," ",&buf2); // prime strtok_r
while (ptr != NULL) {
// Compare labels after Underscores are replaced with Spaces if this feature is enabled .
ptr2 = ptr; // use a copy of the pointer for replacement purposes
while(gd.replace_underscores && (ptr2 = strchr(ptr2,'_'))!= NULL) *ptr2 = ' ';
if(strstr(gd.mrec[i]->legend_name,ptr) != NULL) {
// If so... add it to the menu.
gd.mrec[i]->currently_displayed = TRUE;
xv_set(gd.fields_pu->display_list,PANEL_LIST_SELECT, i, TRUE,NULL);
} // Is a match
ptr = strtok_r(NULL," ",&buf2); // pick up next possible token
} // while there are matching strings
} // foreach data field
} // if group is selected
} // foreach group button
init_field_menus();
// Press the appripriate button.
if(gd.mrec[gd.h_win.page]->currently_displayed == TRUE) { // Current field is still on
int target = 0;
int num_buttons = xv_get(gd.data_pu->data_st,PANEL_NCHOICES);
// Find out which button is occupied by the current field
for(i=0; i < num_buttons; i++) {
if(strncmp((char *) xv_get(gd.data_pu->data_st, PANEL_CHOICE_STRING,i),
gd.mrec[gd.h_win.page]->button_name,NAME_LENGTH) == 0) {
target = i;
}
}
set_field(target);
set_v_field(gd.field_index[target]);
} else { // Current field is not in the menu - Back to the Top.
set_field(0);
set_v_field(gd.field_index[0]);
}
return XV_OK;
}
|
c94e362d29afda122c18b20d316dd4d1fea1aee4 | fac41520f67a8bb4881496fc205f26360ba66096 | /binder-demo-master/include/test/ITest.h | 4ff628e4bc14102eb2ea9510ba197520e607926f | [] | no_license | Liangwb/android | 2b9b6f10a3ee647673f836e078f3032a2dd572d9 | 3e8355ff5614a5dbf92b2e592d5dc3ba9c858230 | refs/heads/master | 2020-06-28T04:27:51.165316 | 2019-08-02T01:49:55 | 2019-08-02T01:49:55 | 200,142,548 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 746 | h | ITest.h |
#ifndef ANDROID_ITest_H
#define ANDROID_ITest_H
#include <utils/RefBase.h>
#include <binder/IInterface.h>
#include <binder/Parcel.h>
namespace android {
class Parcel;
class Surface;
class IStreamSource;
class IGraphicBufferProducer;
class ITest: public IInterface
{
public:
DECLARE_META_INTERFACE(Test);
virtual void disconnect() = 0;
};
// ----------------------------------------------------------------------------
class BnTest: public BnInterface<ITest>
{
public:
virtual status_t onTransact( uint32_t code,
const Parcel& data,
Parcel* reply,
uint32_t flags = 0);
};
}; // namespace android
#endif
|
5a9a2c677d934008f88b1a37a4bf7c11d50e3ff9 | 5071065c885bc3bb3a4d0025654ebdf00ef9e357 | /5/Bit_Vector.cxx | bd755b2b4c1d9da36ad820c8ca9833e53c1ddc21 | [] | no_license | ybai69/Cpp-program | 4c2b072a8b33d6489d1f00b1cf81771e7290d0d4 | 9a29b17ebc00b5fcf269e44c39e0a1376768a9f5 | refs/heads/master | 2021-01-18T16:07:16.010999 | 2019-08-23T01:03:32 | 2019-08-23T01:03:32 | 86,713,843 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,012 | cxx | Bit_Vector.cxx | // Bit_Vector.cxx implements the class declared in Bit_Vector.h.
// Note: You don't have to change this code.
#include <iostream> // for istream, ostream
#include <climits> // for CHAR_BIT, #bits in a char
#include <cassert> // for assert()
#include "Bit_Vector.h"
using namespace std;
void Bit_Vector::write(ostream &os) {
unsigned char c = 0;
os << size() << endl;
for (size_t i = 0; i < size(); i++) {
if ((i > 0) && ((i % 8) == 0)) {
os.put(c);
c = 0;
}
c |= ((*this)[i] << (i % 8)); // Set bit number (i % 8) of c.
}
os.put(c);
}
void Bit_Vector::read(istream &is) {
size_t n;
is >> n;
unsigned char c = is.get();
assert(c == '\n');
while (!is.eof()) {
c = is.get();
for (size_t i = 0; i < CHAR_BIT; i++)
push_back(1 & (c >> i)); // Add bit i of c to back of vector.
}
resize(n);
}
ostream & operator<<(ostream &os, const Bit_Vector &b) {
for (size_t i = 0; i < b.size(); i++)
os << (b[i] ? '1' : '0');
return os;
}
|
3a18ffcc184e6a3d56dfb7ca40b66628b2bd789b | 9254d35b527df03c1791a21d5bc43fbcd4bea0f1 | /AppliIHM/serviceControle2/lot.cpp | 43e59cdcecb78ff0915730c114b86045d8549b5f | [] | no_license | BaptisteAngot/BTSEpreuve | 40273e0a05b45cc50d17a37033f8c33908db8c5b | e51508e0bccff122ef156fae10ec888a36c09994 | refs/heads/master | 2020-11-30T05:49:01.736882 | 2019-12-26T20:59:03 | 2019-12-26T20:59:03 | 230,323,176 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 247 | cpp | lot.cpp | #include "lot.h"
#include <iostream>
using namespace std;
Lot::Lot(ProductionPersonnalise &pp, int quantite, string numCommande, bool statut) : pp(pp)
{
this->quantite=quantite;
this->numCommande=numCommande;
this->statut=statut;
}
|
585483a4b69c3bed01af54766a2f2ad96aef126b | 1345397c014d757daf99e4d782d76b502c3c6e2a | /cxx_271/change/main_1a.cpp | bf38d0ace380d3f785756199b8d95a736a033deb | [] | no_license | eobrie16/courses | 637dc912c949ac00509b590b65a8b213fe6c5298 | f660ca2a2791ef115e84230cceea90dba8f802bd | refs/heads/master | 2023-02-25T11:21:37.465227 | 2022-02-11T04:19:18 | 2022-02-11T04:19:18 | 85,152,794 | 0 | 0 | null | 2023-02-16T02:48:20 | 2017-03-16T04:30:50 | HTML | UTF-8 | C++ | false | false | 1,610 | cpp | main_1a.cpp | #include <iostream>
using namespace std;
struct CHANGE
{
int tens;
int fives;
int ones;
int quarters;
int dimes;
int nickels;
int pennies;
};
void printChange(CHANGE chg)
{
cout << "tens=" << chg.tens << " fives=" << chg.fives << " ones=" << chg.ones<<
" quarters="<< chg.quarters << " dimes=" << chg.dimes <<
" nickels=" << chg.nickels << " pennies=" << chg.pennies << endl;
}
int getMoney( char prompt[])
{
cout << prompt << " [format: dollars.pennies] = ";
double money;
cin >> money;
// Adding 0.005 and casting with (int) effectively does a Rounding operation
// to the nearest penny
return (int)(money*100+0.005);
}
int getRemain(int cents, int & remain)
{
int change;
change = remain/cents;
remain = remain%cents;
return change;
}
CHANGE getChange(int cost, int paid)
{
CHANGE chg;
int remain;
remain = paid - cost;
chg.tens = getRemain(1000, remain);
chg.fives = getRemain(500, remain);
chg.ones = getRemain(100, remain);
chg.quarters = getRemain(25, remain);
chg.dimes = getRemain(10, remain);
chg.nickels = getRemain(5, remain);
chg.pennies = remain;
return chg;
}
int main()
{
int priceInPennies = getMoney( "Enter Price ");
while (priceInPennies > 0)
{
int moneyInPennies = getMoney( "Enter Money Submitted ");
CHANGE returnVal = getChange(priceInPennies, moneyInPennies);
cout << "Change Returned:" << endl;
printChange(returnVal);
cout << "*********************" << endl;
priceInPennies = getMoney( "Enter Price ");
}
return 0;
} |
ee55c200253b448f15589f4c9fd752ccbfad68f5 | 648a23ea59771a8ed11a94440b6ec51f3ba97e4d | /Desktop/CHEGG/c++/priorityqueue.cpp | 4ab761a023e981d60b8e737b3db50c208d3a3321 | [] | no_license | Anil-Bhimwal/chegg | 8f2e6aa0e4bf31ee238ff0563921387773e551ba | 4f7457814d0e803c15414b599c6f3e6ce1a99561 | refs/heads/master | 2022-07-29T03:05:23.394406 | 2020-05-14T18:03:47 | 2020-05-14T18:03:47 | 263,989,126 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 519 | cpp | priorityqueue.cpp | #include <iostream>
using namespace std;
#include <queue>
void kSortedArray(int input[], int n, int k) {
priority_queue<int> pq;
int i = 0;
for(; i < k; i++) {
pq.push(input[i]);
}
for(; i < n; i++) {
input[i-k] = pq.top();//Input[i-k]=pq.top();
pq.pop();
pq.push(input[i]);
}
while(!pq.empty()) {
input[i-k] = pq.top();
pq.pop();
i++;
}
}
int main() {
int input[] = {10, 12, 6, 7, 9};
int k = 3;
kSortedArray(input, 5, k);
for(int i = 0; i < 5; i++) {
cout << input[i] << " ";
}
}
|
b5cca9baa4c26d3bd6376c6d1d429dcaa35ea3ec | 747336d891514ad5f6a9e95220590f9253de590d | /interview_questions/distinct_pairs/distinct_pairs.hpp | 058269d2f415108012def1a7e1f658a60a2bb45f | [] | no_license | alexcthompson/algo_learning | cf89de42d2784806c450187a8d5fbab6af662a3a | 0e6be95b26bbc7285f7b544deed267aae9d85fad | refs/heads/master | 2023-08-06T03:10:38.884767 | 2023-07-29T19:03:40 | 2023-07-29T19:03:40 | 159,570,983 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 870 | hpp | distinct_pairs.hpp | /*
From an interview, was asked to count the number of distinct pairs of nums in a which summed to k.
*/
#include <unordered_map>
#include <vector>
using namespace std;
int numberOfPairs(vector<int> a, long k) {
std::unordered_map<long, int> seen_elems;
int distinct_pairs = 0;
for (auto num : a) {
std::cout << "num = " << num << std::endl;
seen_elems[num]++;
std::cout << "seen_elems[num] = " << seen_elems[num] << std::endl;
std::cout << "seen_elems[k - num] = " << seen_elems[k - num] << std::endl;
if (num == k - num) {
if (seen_elems[num] == 2) { distinct_pairs++; }
}
else if (seen_elems[num] == 1 && seen_elems[k - num] > 0) {
distinct_pairs++;
}
std::cout << "distinct_pairs = " << distinct_pairs << std::endl;
}
return distinct_pairs;
} |
4ad5a82b4b0c816542938d2988d13f23d9a75953 | d030061ef5bbcf1b78bf78469ed6b767b26fa62c | /submission/AlertEngine.cpp | f580f874c3f42e9c48b3c20c777561e96da284c1 | [] | no_license | AdamRaph/262A3 | 84e2cde4e578fbd997afc22caf371b90a9f928e0 | 859907daa9cace70c008d562b8a0fdb2bfb1bf9b | refs/heads/master | 2021-05-30T07:59:33.067736 | 2015-10-26T15:01:27 | 2015-10-26T15:01:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,554 | cpp | AlertEngine.cpp | #include <vector>
#include <stdlib.h>
#include <iostream>
#include <iomanip>
#include "AlertEngine.h"
#include "DataType.h"
/**
* check the anomaly in daily stat log
*/
void AlertEngine::checkAnomaly(vector<Stat> currentStats,vector<vector<EventTotal> > eventsTotals,vector<Event> events){
//create daily counters
vector<double> counters;
for (int i = 0; i < eventsTotals.size(); ++i) {
counters.push_back(0);
}
//calculate daily thresholds
vector<double> thresholds;
for (int i = 0; i < eventsTotals.size(); ++i) {
double threshold = 0;
for (int j = 0; j < eventsTotals[i].size(); ++j) {
threshold += events[j].weight;
}
threshold*=2;
thresholds.push_back(threshold);
}
//calculate daily counters
for (int i = 0; i < eventsTotals.size(); ++i) {
for (int j = 0; j < eventsTotals[i].size(); ++j) {
//formula: weight * abs(total - mean) / stdDev
double diff = eventsTotals[i][j].total-currentStats[j].mean;
if(diff<0) diff = -diff;
counters[i] += (events[j].weight * diff / currentStats[j].stdDev);
}
}
//print the anomaly status
cout<<setw(5)<<"Day"<<setw(10)<<"Counter"<<setw(10)<<"Threshold"<<setw(10)<<"Status"<<endl;
for (int i = 0; i < eventsTotals.size(); ++i) {
string status = counters[i]>thresholds[i]?"Abnormal":"Okay";
cout<<setw(5)<<i+1<<setw(10)<<fixed<<setprecision(2)<<counters[i]<<setw(10)<<thresholds[i]<<setw(10)<<status<<endl;
}
}
|
5e2b7aa3c090db6cefe5a0e010e704219d2dbea1 | 1c803d259e1f459426fdd62b5399f4c3a65a5291 | /4/eg1.cpp | 697925f7cff42a783b44adf685791041a89bb97f | [] | no_license | CIS190/spring2020 | 3c13816718116b333d8ec9744fc19cde3e7661db | 3d58cefae7051e0adfa7159f6a83e439fe96bb14 | refs/heads/master | 2021-08-05T22:10:37.891693 | 2020-12-18T20:46:53 | 2020-12-18T20:46:53 | 230,176,647 | 7 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 476 | cpp | eg1.cpp | #include <iostream>
using namespace std;
class integer
{
private:
int * p = nullptr;
public:
integer(int i) : p {new int {i}}
{
cout << "ctor\n";
}
virtual ~integer()
{
delete p;
cout << "dtor\n";
}
int get() const
{
return *p;
}
void set(int i)
{
*p = i;
}
};
int main()
{
integer i {1};
integer j {2};
integer k {i.get() + j.get()};
cout << k.get() << "\n";
}
|
004cbc72c0cc66fdf40562f286b3d30466b57126 | f26d9c7d6560ffff2fb0479e3ecd52a48432052e | /1155C.cpp | cd0b79c758df353d18836717b7559354c2ffc888 | [] | no_license | HelioStrike/Codeforces | e7fc10af38546638ad1049e3a80a9c0884a3ca92 | 39ae1a0cd8c4ea6b795e74db7b486bef94db84dc | refs/heads/master | 2021-06-24T18:29:57.882308 | 2020-10-29T16:44:44 | 2020-10-29T16:44:44 | 158,788,257 | 1 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 490 | cpp | 1155C.cpp | #include <bits/stdc++.h>
#define FOR(i,a,b) for(int i = (a); i < (b); i++)
#define ll long long
using namespace std;
int n,m;
ll c,k,s,p,t;
ll gcd(ll a, ll b) { return b?gcd(b,a%b):a; }
int main()
{
cin>>n>>m;
cin>>c>>p; s=c; k=p-c;
FOR(i,2,n) cin>>c,k=gcd(k,c-p),p=c;
FOR(i,1,m+1)
{
cin>>c;
if(k%c==0) { t=i; break; }
}
if(t)
{
cout<<"YES"<<'\n';
cout<<s<<' '<<t<<'\n';
}
else cout<<"NO"<<'\n';
return 0;
} |
1bad8a7af4632bb74488c4f11791e7a1dbb1277c | c3ffa07567d3d29a7439e33a6885a5544e896644 | /CodeForce/409-H.cpp | 84524cd549e31382785012c9e5d86d442d82741c | [] | no_license | a00012025/Online_Judge_Code | 398c90c046f402218bd14867a06ae301c0c67687 | 7084865a7050fc09ffb0e734f77996172a93d3ce | refs/heads/master | 2018-01-08T11:33:26.352408 | 2015-10-10T23:20:35 | 2015-10-10T23:20:35 | 44,031,127 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 153 | cpp | 409-H.cpp | #include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
main()
{
int a,b ;
scanf("%d%d",&a,&b) ;
printf("%d",a+b) ;
}
|
3dbd2f5a7b5282a64eb607a695965336c9e469ea | 2f78e134c5b55c816fa8ee939f54bde4918696a5 | /code/3rdparty/hk410/include/physics/hkdynamics/world/commandqueue/hkPhysicsCommandQueue.h | 59f97b367494d7b72bc908ca0ba23582aafee58a | [] | no_license | narayanr7/HeavenlySword | b53afa6a7a6c344e9a139279fbbd74bfbe70350c | a255b26020933e2336f024558fefcdddb48038b2 | refs/heads/master | 2022-08-23T01:32:46.029376 | 2020-05-26T04:45:56 | 2020-05-26T04:45:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,139 | h | hkPhysicsCommandQueue.h | /*
*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent.This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2006 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
#ifndef HK_DYNAMICS2_PHYSICS_COMMAND_QUEUE_H
#define HK_DYNAMICS2_PHYSICS_COMMAND_QUEUE_H
#include <hkdynamics/world/commandqueue/hkPhysicsCommand.h>
class hkPhysicsCommandQueue
{
public:
HK_FORCE_INLINE hkPhysicsCommandQueue( hkPhysicsCommand* bufferStart, hkPhysicsCommand* bufferEnd );
public:
template<typename COMMAND_STRUCT>
HK_FORCE_INLINE void addCommand(COMMAND_STRUCT command);
template<typename COMMAND_STRUCT>
HK_FORCE_INLINE COMMAND_STRUCT& newCommand();
public:
hkPhysicsCommand* m_start;
hkPhysicsCommand* m_current;
hkPhysicsCommand* m_end;
};
template<int NUM_BYTES>
class hkFixedSizePhysicsCommandQueue: public hkPhysicsCommandQueue
{
public:
hkFixedSizePhysicsCommandQueue(): hkPhysicsCommandQueue( (hkPhysicsCommand*)&m_buffer[0], (hkPhysicsCommand*)&m_buffer[NUM_BYTES] ){}
public:
HK_ALIGN16( hkUchar m_buffer[NUM_BYTES] );
};
#include <hkdynamics/world/commandqueue/hkPhysicsCommandQueue.inl>
#endif // HK_DYNAMICS2_PHYSICS_COMMAND_QUEUE_H
/*
* Havok SDK - PUBLIC RELEASE, BUILD(#20060902)
*
* Confidential Information of Havok. (C) Copyright 1999-2006
* Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
* Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership
* rights, and intellectual property rights in the Havok software remain in
* Havok and/or its suppliers.
*
* Use of this software for evaluation purposes is subject to and indicates
* acceptance of the End User licence Agreement for this product. A copy of
* the license is included with this software and is also available from salesteam@havok.com.
*
*/
|
053c57ecfe7ec3d814bf23ceea5d4ef85a9a8028 | 92ecb3bf6c5c7beaff43ab58654d0e2aae0dfc51 | /src/engine/input.h | 594f3de086b3ad000ee187825fe86ba0e38307ac | [] | no_license | dualword/irrlamb | c6fca3b9c0b45fcd2cb6c2469808276f89abaf3e | ee8a9e50f65aaf17b21e9cc445d30982b792cb32 | refs/heads/master | 2023-03-16T05:15:58.324016 | 2013-05-14T21:44:31 | 2013-05-14T21:44:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,583 | h | input.h | /*************************************************************************************
* irrlamb - http://irrlamb.googlecode.com
* Copyright (C) 2013 Alan Witkowski
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
**************************************************************************************/
#include <all.h>
#pragma once
// Classes
class _Input : public irr::IEventReceiver {
public:
enum MouseButtonType {
MOUSE_LEFT,
MOUSE_RIGHT,
MOUSE_MIDDLE,
MOUSE_COUNT,
};
enum InputType {
KEYBOARD,
MOUSE_BUTTON,
MOUSE_AXIS,
JOYSTICK_BUTTON,
JOYSTICK_AXIS,
INPUT_COUNT,
};
_Input();
bool OnEvent(const irr::SEvent &Event);
void ResetInputState();
void InitializeJoysticks(bool ShowLog=false);
bool GetKeyState(int Key) const { return Keys[Key]; }
bool GetMouseState(int Button) const { return MouseButtons[Button]; }
void SetMouseLocked(bool Value);
bool GetMouseLocked() const { return MouseLocked; }
float GetMouseX() const { return MouseX; }
float GetMouseY() const { return MouseY; }
void SetMouseX(float Value) { MouseX = Value; }
void SetMouseY(float Value) { MouseY = Value; }
bool HasJoystick() const { return Joysticks.size() > 0; }
const irr::SEvent::SJoystickEvent &GetJoystickState();
const irr::SJoystickInfo &GetJoystickInfo();
float GetAxis(int Axis);
void DriveMouse(int Action, float Value);
irr::core::stringc GetCleanJoystickName();
const char *GetKeyName(int Key);
private:
void SetKeyState(int Key, bool State) { Keys[Key] = State; }
void SetMouseState(int Button, bool State) { MouseButtons[Button] = State; }
// Input
bool Keys[irr::KEY_KEY_CODES_COUNT], MouseButtons[MOUSE_COUNT];
// Joystick
irr::core::array<irr::SJoystickInfo> Joysticks;
irr::SEvent::SJoystickEvent JoystickState;
irr::u32 LastJoystickButtonState;
float DeadZone;
// States
bool MouseLocked;
float MouseX, MouseY;
bool VirtualMouseMoved;
};
// Singletons
extern _Input Input;
|
30ee8681ec4687d6bace6bd8b6104a973a0bf0f9 | 91f9e8ade87071becbfd1a9620d2b9148082d4eb | /Render.h | 66a865269baef30990a923de8544d50eba8af414 | [] | no_license | kuznetss/gd_project | 93fde6196cf8fc0c384218d586f0db905033527e | 85ffb0077d8c38fdf98342ddf9e9f31475badb37 | refs/heads/master | 2021-09-12T08:13:58.167523 | 2018-04-15T13:43:27 | 2018-04-15T13:43:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 349 | h | Render.h | #ifndef GD_PROJECT_RENDER_H
#define GD_PROJECT_RENDER_H
#include <vector>
#include <clocale>
#include "Consts.h"
#include "Bitmap.h"
#include "Map.h"
void render_map(Map, Bitmap*);
void render_path(std::vector<Coordinates> path, Bitmap * bmp);
void draw_line(Coordinates point_1, Coordinates point_2, Bitmap *bmp);
#endif //GD_PROJECT_RENDER_H
|
018438e18ac1b8915315b733eeff4b08e9ddc430 | 8fb32f1bf227c2ff37e420a5a671047ee132e4c8 | /ㅇ3ㅇ/fightScene.cpp | 8f86f5b9dc43e90bbebd62607eb987e440d445f2 | [] | no_license | JaesunHan/FreeFighter | 0c0251ea81feb136577fc8c2d1564b8489eeed27 | d2ace29868544ab3e78ef5cf4d698590b5a6fed6 | refs/heads/master | 2020-03-22T00:00:50.911623 | 2018-08-04T08:36:07 | 2018-08-04T08:36:07 | 139,219,200 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 4,379 | cpp | fightScene.cpp | #include "stdafx.h"
#include "fightScene.h"
#include "playerManager.h"
#include "enemyManager.h"
#include "camera.h"
#include "player.h"
#include "enemy.h"
#include "grid.h"
#include "cube.h"
fightScene::fightScene()
: _pm(NULL)
, _em(NULL)
, _gameMode(GAME_NONE)
, _playerMode(PMODE_NONE)
, _physXScene(NULL)
, _material(NULL)
, _cm(NULL)
, _camera(NULL)
, _backGround(NULL)
, _grid(NULL)
{
}
fightScene::~fightScene()
{
}
HRESULT fightScene::init()
{
IMAGEMANAGER->addImage(_T("win"), _T(".\\texture\\ui\\win.png"));
IMAGEMANAGER->addImage(_T("lose"), _T(".\\texture\\ui\\lose.png"));
//물리엔진이 적용되는 신 생성
PHYSX->createScene(&_physXScene, &_material);
_cm = PxCreateControllerManager(*_physXScene);
_cm->setOverlapRecoveryModule(false);
D3DDEVICE->GetViewport(&_originViewport);
_pm = new playerManager;
_pm->init(_gameMode, _playerMode, _vPlayerSelect, &_cm, _material);
_em = new enemyManager;
_em->setPhysX(_cm, _material);
_em->Init(1, _pm->getPlayersNum());
_em->SetPlayerAdressLink(_pm);
_pm->setEMMemory(_em);
_camera = new camera;
_camera->init();
_backGround = new cube;
_backGround->init();
_backGround->scaleLocal(50.0f, 50.0f, 50.0f);
_backGround->SetMtlTexName(_T("spaceBackground"), _T("spaceBackground"));
TEXTUREMANAGER->addTexture(_T("spaceBackground"), _T(".\\texture\\sky\\spaceBackground.jpg"));
D3DMATERIAL9 skyMaterial;
ZeroMemory(&skyMaterial, sizeof(skyMaterial));
skyMaterial.Ambient = D3DXCOLOR(255, 255, 255, 255);
MATERIALMANAGER->addMaterial(_T("spaceBackground"), skyMaterial);
_grid = new grid;
_grid->init(WHITE, 20, 0.0f);
if (_playerMode == PMODE_PLAYER2)
_pm->setOpponent();
_gameoverAlpha = 0;
_isGameOver = false;
_gameoverTime = 0.0f;
return S_OK;
}
void fightScene::release()
{
SAFE_OBJRELEASE(_pm);
SAFE_DELETE(_em);
D3DDEVICE->SetViewport(&_originViewport);
if (_physXScene)
{
_physXScene->release();
_physXScene = NULL;
}
if (_material)
{
_material->release();
_material = NULL;
}
if (_cm)
_cm->purgeControllers();
SAFE_OBJRELEASE(_camera);
SAFE_OBJRELEASE(_backGround);
SAFE_OBJRELEASE(_grid);
}
void fightScene::update()
{
if (_backGround)
{
_backGround->rotateWorld(0, 0, 0.01f * DEG2RAD);
_backGround->update();
}
if (KEYMANAGER->isOnceKeyDown(VK_ESCAPE))
{
SCENEMANAGER->changeChild(_T("returnScene"));
SCENEMANAGER->currentSceneInit();
}
if (!_isGameOver)
{
if (_pm)
{
_pm->update();
if (_pm->isOneDead())
_isGameOver = true;
}
if (_em)
{
_em->Update();
if (_em->isFightDeadCheck())
_isGameOver = true;
}
if (_isDebug)
{
if (_camera)
_camera->update(&(_pm->getVPlayers()[0]->p->GetPosition()));
}
}
else
{
if (_pm)
_pm->update();
if (_em)
_em->Update();
_gameoverTime += TIMEMANAGER->getElapsedTime();
if (_gameoverTime > 10.0f)
{
SCENEMANAGER->changeScene(_T("mainScene"));
SCENEMANAGER->sceneInit();
}
_gameoverAlpha++;
if (_gameoverAlpha > 255)
_gameoverAlpha = 255;
}
}
void fightScene::render()
{
if (_pm)
{
for (int i = 0; i < _pm->getPlayersNum(); ++i)
{
if (_backGround)
_backGround->render();
// ======================== 여기에 랜더하렴^^ ========================
_pm->render(i);
if (_em)
_em->Render(_pm->getPlayersNum());
if (_grid)
_grid->render();
// ======================== 여기에 랜더하렴^^ ========================
_pm->renderParticle();
_pm->renderUi(i);
_em->RenderParticle(_pm->getPlayersNum());
if (_isGameOver)
{
D3DVIEWPORT9 vp;
D3DDEVICE->GetViewport(&vp);
float destX, destY;
if (_pm->getVPlayers()[i]->p->GetIsDead())
{
destX = vp.X + vp.Width / 2 - IMAGEMANAGER->findImage(_T("lose"))->getWidth() / 2;
destY = vp.Y + vp.Height / 2 - IMAGEMANAGER->findImage(_T("lose"))->getHeight() / 2;
IMAGEMANAGER->alphaRender(_T("lose"), destX, destY, _gameoverAlpha);
}
else
{
destX = vp.X + vp.Width / 2 - IMAGEMANAGER->findImage(_T("win"))->getWidth() / 2;
destY = vp.Y + vp.Height / 2 - IMAGEMANAGER->findImage(_T("win"))->getHeight() / 2;
IMAGEMANAGER->alphaRender(_T("win"), destX, destY, _gameoverAlpha);
}
}
}
}
D3DDEVICE->SetViewport(&_originViewport);
}
void fightScene::cameraZoom(float zoom)
{
if (_isDebug)
_camera->cameraZoom(zoom);
}
|
0b91f0d319778b5c3322bb3e9376c32dfa359196 | 0b5f5a38bb3f43ded62b9c1e4f710f882b1155c5 | /owGameMap/WDL_Node_Pass.h | 112f14ab3239c4b232c60a4baef41421cf434d30 | [
"Apache-2.0"
] | permissive | xuebai5/OpenWow | a3c41d984cebe4dc34e9e3d0530363da4106bb61 | 97b2738862ce0244fd5b708f4dc3f05db7491f8b | refs/heads/master | 2020-04-26T23:16:26.733576 | 2019-03-03T12:41:04 | 2019-03-03T12:41:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 328 | h | WDL_Node_Pass.h | #pragma once
// A pass that renders the opaque geometry in the scene.
class WDL_Node_Pass : public BasePass
{
public:
typedef BasePass base;
WDL_Node_Pass(std::shared_ptr<Scene3D> scene, std::shared_ptr<PipelineState> pipeline);
virtual ~WDL_Node_Pass();
virtual bool Visit(IMesh& mesh) override;
protected:
private:
}; |
7908452dee34317ad42b69c776b4071e8470b7a1 | 27fbce7c075cd9f4cee7e1250e82cd56a7699c02 | /tao/x11/dynamic_any/dynenum_i.cpp | fda49ebeb5b30acd4712b44fc818509ce13036c6 | [
"MIT"
] | permissive | jwillemsen/taox11 | fe11af6a7185c25d0f236b80c608becbdbf3c8c3 | f16805cfdd5124d93d2426094191f15e10f53123 | refs/heads/master | 2023-09-04T18:23:46.570811 | 2023-08-14T19:50:01 | 2023-08-14T19:50:01 | 221,247,177 | 0 | 0 | MIT | 2023-09-04T14:53:28 | 2019-11-12T15:14:26 | C++ | UTF-8 | C++ | false | false | 7,859 | cpp | dynenum_i.cpp | /**
* @file dynenum_i.cpp
* @author Marijke Henstmengel
*
* @brief CORBA C++11 TAOX11 DynamicAny::DynAny implementation
*
* @copyright Copyright (c) Remedy IT Expertise BV
*/
#include "tao/AnyTypeCode/Marshal.h"
#include "tao/x11/anytypecode/typecode_impl.h"
#include "tao/x11/anytypecode/any_unknown_type.h"
#include "tao/x11/dynamic_any/dynenum_i.h"
#include "tao/x11/dynamic_any/dynanyutils_t.h"
namespace TAOX11_NAMESPACE
{
namespace DynamicAny
{
DynEnum_i::DynEnum_i (bool allow_truncation)
: TAOX11_DynCommon (allow_truncation)
, value_ (0)
{
TAOX11_LOG_TRACE ("DynEnum_i::DynEnum_i");
}
void
DynEnum_i::init_common ()
{
this->ref_to_component_ = false;
this->container_is_destroying_ = false;
this->has_components_ = false;
this->destroyed_ = false;
this->current_position_ = -1;
this->component_count_ = 0;
}
IDL::traits<DynamicAny::DynAny>::ref_type
DynEnum_i::init (const CORBA::Any &any)
{
TAOX11_LOG_TRACE ("DynEnum_i::init with any");
IDL::traits<CORBA::TypeCode>::ref_type tc = any.type ();
CORBA::TCKind kind = DynAnyFactory_i::unalias (tc);
if (kind != CORBA::TCKind::tk_enum)
{
throw DynamicAny::DynAnyFactory::InconsistentTypeCode ();
}
this->type_ = tc;
TAOX11_CORBA::Any::impl_ref_type impl = any.impl ();
if (impl->encoded ())
{
std::shared_ptr<Unknown_IDL_Type> const unk =
std::dynamic_pointer_cast<Unknown_IDL_Type> (impl);
if (!unk)
throw CORBA::INTERNAL ();
// We don't want unk's rd_ptr to move, in case we are shared by
// another Any, so we use this to copy the state, not the buffer.
TAO_InputCDR for_reading (unk->_tao_get_cdr ());
for_reading.read_ulong (this->value_);
}
else
{
TAO_OutputCDR out;
impl->marshal_value (out);
TAO_InputCDR in (out);
in.read_ulong (this->value_);
}
this->init_common ();
return this->_this();
}
IDL::traits<DynamicAny::DynAny>::ref_type
DynEnum_i::init (IDL::traits<CORBA::TypeCode>::ref_type tc)
{
TAOX11_LOG_TRACE ("DynEnum_i::init with typecode");
CORBA::TCKind kind = DynAnyFactory_i::unalias (tc);
if (kind != CORBA::TCKind::tk_enum)
{
throw DynamicAny::DynAnyFactory::InconsistentTypeCode ();
}
this->type_ = tc;
this->value_ = 0;
this->init_common ();
return this->_this();
}
std::string
DynEnum_i::get_as_string ()
{
TAOX11_LOG_TRACE ("DynEnum_i::get_as_string");
IDL::traits<CORBA::TypeCode>::ref_type ct =
DynAnyFactory_i::strip_alias (this->type_);
const std::string retval = ct->member_name (this->value_);
return retval;
}
void
DynEnum_i::set_as_string (const std::string &value_as_string)
{
TAOX11_LOG_TRACE ("DynEnum_i::set_as_string");
IDL::traits<CORBA::TypeCode>::ref_type ct =
DynAnyFactory_i::strip_alias (this->type_);
uint32_t count = ct->member_count ();
uint32_t i;
std::string temp {};
for (i = 0; i < count; ++i)
{
temp = ct->member_name (i);
if (value_as_string == temp)
{
break;
}
}
if (i < count)
{
this->value_ = i;
}
else
{
throw DynamicAny::DynAny::InvalidValue ();
}
}
uint32_t
DynEnum_i::get_as_ulong ()
{
TAOX11_LOG_TRACE ("DynEnum_i::DynEnum_i");
return this->value_;
}
void
DynEnum_i::set_as_ulong (uint32_t value_as_ulong)
{
TAOX11_LOG_TRACE ("DynEnum_i::set_as_ulong");
IDL::traits<CORBA::TypeCode>::ref_type ct =
DynAnyFactory_i::strip_alias (this->type_);
uint32_t const max = ct->member_count ();
if (value_as_ulong < max)
{
this->value_ = value_as_ulong;
}
else
{
throw DynamicAny::DynAny::InvalidValue ();
}
}
void
DynEnum_i::from_any (const CORBA::Any& any)
{
TAOX11_LOG_TRACE ("DynEnum_i::from_any");
IDL::traits<CORBA::TypeCode>::ref_type tc = any.type ();
CORBA::TCKind kind = DynAnyFactory_i::unalias (tc);
if (kind == CORBA::TCKind::tk_enum)
{
// Get the CDR stream of the Any, if there isn't one, make one.
TAOX11_CORBA::Any::impl_ref_type impl = any.impl ();
if (impl->encoded ())
{
std::shared_ptr<Unknown_IDL_Type> const unk =
std::dynamic_pointer_cast<Unknown_IDL_Type> (impl);
if (!unk)
throw CORBA::INTERNAL ();
// We don't want unk's rd_ptr to move, in case we are shared by
// another Any, so we use this to copy the state, not the buffer.
TAO_InputCDR for_reading (unk->_tao_get_cdr ());
for_reading.read_ulong (this->value_);
}
else
{
TAO_OutputCDR out;
impl->marshal_value (out);
TAO_InputCDR in (out);
in.read_ulong (this->value_);
}
}
else
{
throw DynamicAny::DynAny::TypeMismatch ();
}
}
CORBA::Any
DynEnum_i::to_any ()
{
TAOX11_LOG_TRACE ("DynEnum_i::to_any");
TAO_OutputCDR out_cdr;
out_cdr.write_ulong (this->value_);
CORBA::Any retval {};
try
{
TAO_InputCDR in_cdr (out_cdr);
TAOX11_NAMESPACE::Unknown_IDL_Type::ref_type safe_impl =
std::make_shared<TAOX11_NAMESPACE::Unknown_IDL_Type> (this->type_, in_cdr);
retval.replace (safe_impl);
}
catch (const std::bad_alloc&)
{
throw CORBA::NO_MEMORY ();
}
return retval;
}
bool
DynEnum_i::equal (IDL::traits<DynamicAny::DynAny>::ref_type rhs)
{
TAOX11_LOG_TRACE ("DynEnum_i::equal");
IDL::traits<CORBA::TypeCode>::ref_type tc = rhs->type ();
bool equivalent = tc->equivalent (this->type_);
if (!equivalent)
{
return false;
}
CORBA::Any any = rhs->to_any ();
TAOX11_CORBA::Any::impl_ref_type impl = any.impl ();
uint32_t value;
if (impl->encoded ())
{
std::shared_ptr<Unknown_IDL_Type> const unk =
std::dynamic_pointer_cast<Unknown_IDL_Type> (impl);
if (!unk)
throw CORBA::INTERNAL ();
// We don't want unk's rd_ptr to move, in case we are shared by
// another Any, so we use this to copy the state, not the buffer.
TAO_InputCDR for_reading (unk->_tao_get_cdr ());
for_reading.read_ulong (value);
}
else
{
TAO_OutputCDR out;
impl->marshal_value (out);
TAO_InputCDR in (out);
in.read_ulong (value);
}
return value == this->value_;
}
void
DynEnum_i::destroy ()
{
if (this->destroyed_)
{
throw CORBA::OBJECT_NOT_EXIST ();
}
if (!this->ref_to_component_ || this->container_is_destroying_)
{
this->destroyed_ = true;
}
}
IDL::traits<DynamicAny::DynAny>::ref_type
DynEnum_i::current_component ()
{
TAOX11_LOG_TRACE ("DynEnum_i::current_component");
if (this->destroyed_)
{
throw CORBA::OBJECT_NOT_EXIST ();
}
throw DynamicAny::DynAny::TypeMismatch ();
}
}
namespace CORBA
{
template<>
TAOX11_DynamicAny_Export object_traits<DynamicAny::DynEnum>::ref_type
object_traits<DynamicAny::DynEnum>::narrow (
object_reference<CORBA::Object> obj)
{
if (obj)
{
if (obj->_is_local ())
{
return ref_type::_narrow (std::move(obj));
}
}
return nullptr;
}
}
}
|
746be7c3f7256e3ae328751f9726feb7a6e8bf51 | f39ca4d74cd69ac1e275803b3e3ed861e44abf90 | /Model/Animation.h | a7d76f8043725221b66e0685d5e5b7cfefdaed8e | [] | no_license | lyleunderwood/TGL | 856241ec88993218335537c288b5db115a972823 | 25df5fa2942613812a421262c3fa21a86b5c16f1 | refs/heads/master | 2021-01-16T17:42:57.456363 | 2012-11-22T03:49:05 | 2012-11-22T03:49:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 722 | h | Animation.h | #ifndef ANIMATION_H
#define ANIMATION_H
#include <QList>
#include "Frame.h"
#include "savable.h"
class Animation : public Savable
{
bool SaveToFile(QFile &file);
bool LoadFromFile(QFile &file);
private:
QString animationName;
QList<Frame*> frameList;
bool loop;
int nextAnimationID;
public:
Animation();
Frame *GetFrame(int ID);
Frame *GetFrameAtIndex(int i);
void AddFrame(Frame *newFrame);
void DeleteFrame(int ID);
int GetFrameCount();
int GetNumFrames();
QString GetName();
void SetName(QString newName);
bool GetLoop() { return loop; }
void SetLoop(bool newLoop) { loop = newLoop; }
void DestroyAllFrames();
};
#endif // ANIMATION_H
|
f3ea792e59c70d47837082dcb588d1416a1b2b3f | eecf0603c8336a49d35ca87f12ad7b2769115422 | /QOSS-V1.0/VTK/include/Ellipsoid.h | 16f2f27fcb25c7c9a3fd773c1c8fbcb6fe0b03d3 | [] | no_license | Devil-ly/QOSS-V1.0 | e90fab43f9a69fdd16f5cbfc5f95db83fa09e656 | 73e15f398be7567e187cb2814415a2dd23caaf63 | refs/heads/master | 2021-05-06T19:12:02.890104 | 2018-05-26T07:49:56 | 2018-05-26T07:49:56 | 112,161,447 | 2 | 4 | null | 2018-04-12T06:13:32 | 2017-11-27T07:15:17 | C++ | GB18030 | C++ | false | false | 853 | h | Ellipsoid.h | /*
* created by liyun 2017/12/7
* function 二次曲面 的子类
* x^2 / a^2 + y^2 / b^2 + z^2 / c^2 = 1
* R 为x,y的最大值
* version 1.0
*/
#ifndef ELLIPSOID_H
#define ELLIPSOID_H
#include "QuadricSurfaceMirror.h"
class Ellipsoid : public QuadricSurfaceMirror
{
public:
// 构造默认的平面镜 没有传入参数
Ellipsoid(const GraphTrans & _graphTrans);
// 构造平面镜 传入参数
Ellipsoid(const GraphTrans & _graphTrans, const std::vector<double>& parameter);
void setParameter(double a, double b, double c, double theta);
virtual QTreeWidgetItem* getTree();
void setA(double a);
double getA() const { return a; }
void setB(double b);
double getB() const { return b; }
void setC(double c);
double getC() const { return c; }
private:
double a;
double b;
double c;
double theta;
};
#endif // ELLIPSOID_H |
7bbafa13674ecefccab3e6d61146c370718b4251 | d37f2a4582730c1a6c8e2f4a3dbe4001bed82803 | /Cola/modeloCola.cpp | 2bce50c0a77468002016174b59638fb7cd116ddd | [] | no_license | andreina96/I-Tarea-Programada_Estructuras_de_Datos | 48731b9244e75b9aac90f4c8dcbb6cd2f8df30e4 | 7e4768bf980f174ed65d83f4b8a5b7d64f247f5e | refs/heads/master | 2020-07-12T02:38:50.481060 | 2016-11-17T04:45:00 | 2016-11-17T04:45:00 | 73,990,773 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 1,296 | cpp | modeloCola.cpp | #include "modeloCola.h"
modeloCola::modeloCola(){}
void modeloCola::crear(){
primero = 1; //el primero se coloa adelante del último para decir que la cola está vacia
ultimo = 0;
numElem = 0;
}
void modeloCola::destruir(){}
void modeloCola::vaciar(){
primero = 1;
ultimo = 0;
numElem = 0;
}
bool modeloCola::vacia(){
if(numElem == 0)
return true;
return false;
}
void modeloCola::agregar(nodo elemento){ //se agrega el elemento al final y el señalador al último se corre una posicion hacia la derecha.
if(numElem != 100){
if(numElem == 0){
ultimo = 1;
arreglo[1] = elemento;
}else if(ultimo == (99)){
arreglo[0] = elemento;
ultimo = 0;
}
else {
ultimo ++;
arreglo[ultimo] = elemento;
}
numElem ++;
}
}
void modeloCola::sacar(){ //se saca el primer elemento y se corre la posicion del señalador al primero un espacio hacia delante.
if(primero == 99){
primero = 0;
}
else{
primero ++;
}
numElem --;
if(numElem == 0){
vaciar();
}
}
nodo& modeloCola::frente(){ //nos imprime el primer elemento del frente.
return arreglo[primero];
}
|
5fa1e579bea8be445fcdc5dd90036e9b2902d524 | 2e6c001805d872577fb4b05d1e91bc812d1db41c | /answers/JS-0369/string/string.cpp | e941945fc37a76e4db42bdd04c7069fd21df338b | [] | no_license | fsy-juruo/noip2020-JS-Answers | f9e7ec8c7d86274bb8d18ecf7a9b858b11d9a8bb | 476106a54046665e1362bee246fa83b6f0d00857 | refs/heads/main | 2023-01-31T02:37:52.273421 | 2020-12-05T12:27:17 | 2020-12-05T12:27:17 | 318,722,231 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,231 | cpp | string.cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll MOD1 = 1e9 + 7, MOD2 = 9999991;
const int maxn = 5e5 + 10, A = 26, SIZE = maxn * 20;
struct node {
ll a, b;
} sh[maxn];
ll pow261[maxn], pow262[maxn];
node gethash(int l, int r){
node re;
re.a = (sh[r].a - sh[l - 1].a * pow261[r - l + 1] % MOD1 + MOD1) % MOD1;
re.b = (sh[r].b - sh[l - 1].b * pow262[r - l + 1] % MOD2 + MOD2) % MOD2;
return re;
}
bool check(node a, node b){
return a.a == b.a && a.b == b.b;
}
int n;
int s[A];
char ch[maxn];
int as[maxn], cs[maxn];
bool f[maxn];
int sum[SIZE], lc[SIZE], rc[SIZE], root[maxn], tot;
int frm[maxn], nxt[maxn], val[maxn], Head, Tail;
inline void pushin(int c){
if (Tail) nxt[Tail] = ++Tail; else ++Tail;
frm[Tail] = Tail - 1;
nxt[Tail] = 0;
val[Tail] = c;
}
inline void remove(int x){
if (x == Head){
Head = nxt[Head];
frm[Head] = 0;
return;
}
if (x == Tail){
Tail = frm[Tail];
nxt[Tail] = 0;
return;
}
nxt[frm[x]] = nxt[x];
frm[nxt[x]] = frm[x];
}
void build(int &f1, int f2, int l, int r, int x){
if (!f1) f1 = ++tot;
if (l == r){
sum[f1] = sum[f2] + 1;
return;
}
int mid = l + r >> 1;
if (x <= mid){
build(lc[f1], lc[f2], l, mid, x);
rc[f1] = rc[f2];
} else {
build(rc[f1], rc[f2], mid + 1, r, x);
lc[f1] = lc[f2];
}
sum[f1] = sum[lc[f1]] + sum[rc[f1]];
}
int query(int f, int l, int r, int x){
if (r <= x) return sum[f];
int mid = l + r >> 1, re = 0;
if (x > mid) re = query(rc[f], mid + 1, r, x);
return re + query(lc[f], l, mid, x);
}
void Init(){
memset(root, 0, sizeof root);
memset(as, 0, sizeof as);
memset(cs, 0, sizeof cs);
memset(sum, 0, sizeof sum);
}
int main(){
freopen("string.in", "r", stdin);
freopen("string.out", "w", stdout);
pow261[0] = pow262[0] = 1;
for (int i = 1; i < maxn; i++){
pow261[i] = pow261[i - 1] * 26 % MOD1;
pow262[i] = pow262[i - 1] * 26 % MOD2;
}
int T;
scanf("%d", &T);
while (T--){
Init();
scanf("%s", ch + 1);
n = strlen(ch + 1);
for (int i = 1, idx; i <= n; i++){
idx = ch[i] - 'a';
sh[i].a = (sh[i - 1].a * 26 + idx) % MOD1;
sh[i].b = (sh[i - 1].b * 26 + idx) % MOD2;
}
for (int i = 0; i < A; i++) s[i] = 0;
for (int i = n, idx; i >= 1; i--){
idx = ch[i] - 'a';
s[idx]++;
if (s[idx] & 1) cs[i] = cs[i + 1] + 1; else cs[i] = cs[i + 1] - 1;
}
for (int i = 0; i < A; i++) s[i] = 0;
for (int i = 1, idx; i <= n; i++){
idx = ch[i] - 'a';
s[idx]++;
if (s[idx] & 1) as[i] = as[i - 1] + 1; else as[i] = as[i - 1] - 1;
build(root[i], root[i - 1], 0, n, as[i]);
}
int ans = 0;
memset(f, 0, sizeof f);
Head = 1; Tail = 0;
for (int i = 2; i < n; i++){
pushin(i);
for (int j = Head, len; j; j = nxt[j]){
len = val[j];
if (f[val[j]]){
remove(j);
continue;
}
//if (len * len > i) break;
if (i % len) continue;
if (check(gethash(i - len + 1, i), sh[len]))
ans += query(root[len - 1], 0, n, cs[i + 1]);
else remove(j);
/*
if (len * len == i) continue;
len = i / len;
if (check(gethash(i - len + 1, i), sh[len]))
ans += query(root[len - 1], 0, n, cs[i + 1]);
else f[len] = 1;
*/
}
// printf("%d %d\n", i, ans);
}
printf("%d\n", ans);
}
return 0;
}
|
234382609ee9b033061152122264b4d8b5ebcb15 | 614c73ad0afca74558cb4a8a4d7546745c16f8c8 | /Hmwk/Assignment4/Gaddis_8thEd_Chap5_Prob22_SquareDisplay/main.cpp | 8e3380b95840a29f58328b28207c1a47e3cef86e | [] | no_license | jg2436765/GarciaJesse_CIS5_45561 | 71de6e1490f07ec106e5ce8693f58f1658d1d138 | e013581b75128a58928691631095639a7afffa26 | refs/heads/master | 2021-01-21T14:47:59.735374 | 2017-07-25T19:50:12 | 2017-07-25T19:50:12 | 95,333,059 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 913 | cpp | main.cpp | /*
* File: main.cpp
* Author: Jesse Garcia
* Created on July 10, 2017, 11:47 AM
* Purpose: Square Display
*/
//System Libraries
#include <iostream> //Input - Output Library
using namespace std; //Name-space under which system libraries exist
//User Libraries
//Global Constants
//Function Prototypes
//Execution begins here
int main(int argc, char** argv) {
//Declare variables
int number;
//Initialize variables
//Input data
//Map inputs to outputs or process the data
cout<<"Enter a positive integer but no greater than 15: ";
cin>>number;
//Output the transformed data
if (number <1)
number =1;
else if (number >15)
number =15;
for (int c=0; c<number; c++){
for (int y=0; y<number; y++)
{
cout<<'X';
}cout<<endl;
}
//Exit stage right!
return 0;
}
|
6e4d9718386ef7a516bfb9c53744c8e2c343e99f | f77c8f6812905bbc761373c59bf87ed112e60fa2 | /Samples/System/SimpleExceptionHandling/SimpleExceptionHandling.h | 325fc8d4e819bfb91658c4bf3880de59f13be98b | [
"MIT"
] | permissive | kantamRobo/Xbox-GDK-Samples | d323fe14f79b994a6758e37291e8947cf8096af4 | d25a824d0ac395732826faecc803c586b8813104 | refs/heads/main | 2023-08-25T14:21:37.750150 | 2021-09-27T20:18:53 | 2021-09-27T20:18:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,249 | h | SimpleExceptionHandling.h | //--------------------------------------------------------------------------------------
// SimpleExceptionHandling.h
//
// Advanced Technology Group (ATG)
// Copyright (C) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
#pragma once
#include "DeviceResources.h"
#include "StepTimer.h"
void GenerateDump(EXCEPTION_POINTERS* exceptionPointers);
// A basic sample implementation that creates a D3D12 device and
// provides a render loop.
class Sample final : public DX::IDeviceNotify
{
public:
Sample() noexcept(false);
~Sample();
Sample(Sample&&) = default;
Sample& operator= (Sample&&) = default;
Sample(Sample const&) = delete;
Sample& operator= (Sample const&) = delete;
// Initialization and management
void Initialize(HWND window, int width, int height);
// Basic render loop
void Tick();
// IDeviceNotify
void OnDeviceLost() override;
void OnDeviceRestored() override;
// Messages
void OnActivated();
void OnDeactivated();
void OnSuspending();
void OnResuming();
void OnWindowMoved();
void OnWindowSizeChanged(int width, int height);
// Properties
void GetDefaultSize(int& width, int& height) const noexcept;
static std::wstring m_testOutputMessage;
private:
enum ExceptionTest
{
e_handled,
e_ignored,
e_structured,
e_vectored,
e_language,
e_recommended,
e_null,
};
ExceptionTest m_lastTestRun;
void ExecuteHandledException();
void ExecuteIgnoredException();
void ExecuteStructuredException();
void ExecuteVectoredException();
void ExecuteLanguageException();
void ExecuteRecommended();
void CatchLanguageExceptionWithStructured();
void DrawHelpText(DirectX::XMFLOAT2& pos, ExceptionTest whichTest, const std::wstring& button);
void Update(DX::StepTimer const& timer);
void Render();
void Clear();
void CreateDeviceDependentResources();
void CreateWindowSizeDependentResources();
// Device resources.
std::unique_ptr<DX::DeviceResources> m_deviceResources;
// Rendering loop timer.
uint64_t m_frame;
DX::StepTimer m_timer;
// Input device.
std::unique_ptr<DirectX::GamePad> m_gamePad;
std::unique_ptr<DirectX::Keyboard> m_keyboard;
std::unique_ptr<DirectX::Mouse> m_mouse;
DirectX::GamePad::ButtonStateTracker m_gamePadButtons;
DirectX::Keyboard::KeyboardStateTracker m_keyboardButtons;
// DirectXTK objects.
std::unique_ptr<DirectX::GraphicsMemory> m_graphicsMemory;
std::unique_ptr<DirectX::DescriptorHeap> m_resourceDescriptors;
std::unique_ptr<DirectX::SpriteBatch> m_spriteBatch;
Microsoft::WRL::ComPtr<ID3D12Resource> m_background;
std::unique_ptr<DirectX::SpriteFont> m_regularFont;
std::unique_ptr<DirectX::SpriteFont> m_largeFont;
std::unique_ptr<DirectX::SpriteFont> m_ctrlFont;
enum Descriptors
{
Background,
RegularFont,
LargeFont,
CtrlFont,
Count
};
};
|
9c2cd1db8c0b33ace0e567ff66ad27e79c75c3af | 120f701ee4439524534294fac5401c97bbe4d28f | /Esculturas.h | f164dcb7e1eb6c24d1c365b441b019e8c122d211 | [] | no_license | alessadge/Examen120172-AlessandroGrimaldi | 1dae1a7bf60ff443e270c501bcc2fe51af347e7b | 37cc7d5109e972569e97c65d1147e599d6ca81c7 | refs/heads/master | 2021-01-21T15:18:20.491476 | 2017-05-19T23:46:00 | 2017-05-19T23:46:00 | 91,836,332 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 347 | h | Esculturas.h | #ifndef ESCULTURAS_H
#define ESCULTURAS_H
#include "Obras.h"
class Esculturas:public Obras{
protected:
double peso;
string material;
public:
Esculturas();
Esculturas(double, string,string,string,string,string,int);
double getPeso();
void setPeso(double);
string getMaterial();
void setMaterial(string);
};
#endif
|
ec0963c5b090dfcf7e80913227ba67c459811592 | 34f7ee9ffb012c3c1b1c0e0e692752b0fbf8679a | /Funciones/3.cpp | 9bfcdcb024890517dfea70cad24f1acb44840015 | [] | no_license | Sleri/tallerNo5 | 9314fbc4e0a013f0513ded091f828b44835b9482 | eea3dff8235651c8c50fa9f1562eb67189050ddb | refs/heads/master | 2020-03-28T13:19:47.359368 | 2018-09-11T21:53:38 | 2018-09-11T21:53:38 | 148,384,316 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 519 | cpp | 3.cpp | #include <iostream>
#include <conio.h>
#include <string.h>
/*
* Programa: Lista desde 1 hasta x numero
* Fecha: 8 de septiembre de 2018
* Elaborado por: Natalia Agudelo Valdes
*/
using namespace std;
//impresion de lista
int num(int n1){
int i;
for(i = 1; i <= n1; i++){
printf("%d\n", i);
}
}
//funcion principal
int main() {
int num1;
do{
printf("Ingrese el numero al cual se le imprimira una lista: ");
scanf("%d", &num1);
num(num1);
} while(num1 > 0);
printf("Ingreso un numero negativo");
}
|
7cc8350611b81e3065f88f7a5623472057f7f985 | cf1feebbace47827b1e1c7944ef65cd2687ccdee | /08 最近点问题-分治策略.cpp | 1daa2a3e8e1cf8488caa0e51f6e56585efe5900f | [] | no_license | plutoNJU/recursion | 7d2d9911dd54c2137732c7bb5b11c4c79d382cc8 | 544e7c2591b96ddc7d7ed388b5fc91b965517826 | refs/heads/master | 2020-04-03T15:37:30.198836 | 2019-01-17T06:59:59 | 2019-01-17T06:59:59 | 155,369,211 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,990 | cpp | 08 最近点问题-分治策略.cpp | #include <iostream>
using namespace std;
//最近对分治求解
//初始点按照x的从小到大排列点集S
struct point
{
int x,y;
};
double Distance(point a, point b);
void QuicksortByY(point P[], int first, int end);
void quickSort(point r[], int first, int end);
double ClosestPoint(point S[], int low, int high)
{
double d1, d2, d3, d;
int mid, i, j, index;
point P[1000]; //预设小于1000个点
if ((high - low) == 1)
//return Distance(S[low],S[high]);
return Distance(S[low], S[high]);
if ((high - low) == 2)
{
d1 = Distance(S[low], S[low + 1]);
d2 = Distance(S[low + 1], S[high]);
d3 = Distance(S[low], S[high]);
if ((d1 < d2) && (d1 < d3))
return d1;
else if (d2 < d3)
return d2;
else
return d3;
}
mid = (low + high) / 2;
d1 = ClosestPoint(S, low, mid);
d2 = ClosestPoint(S, mid + 1, high);
if (d1 < d2)
d = d1;
else
d = d2;
//情况c的计算
index = 0;
for (i = mid;(i >= low) && ((S[mid].x - S[i].x) < d);i--)//建立点集P1
{
P[index++] = S[i];
}
for (i = mid + 1;(i <= high) && ((S[i].x - S[mid].x) < d);i++)//建立点集P2
{
P[index++] = S[i];
}
QuicksortByY(P, 0, index - 1);//对于集合P1和P2关于y坐标排序
for (i = 0;i < index;i++)
{
for (j = i+1;j < index;j++)
{
if ((P[j].y - P[i].y) >= d)
break;
else
{
d3 = Distance(P[i], P[j]);
if (d3 < d)
d = d3;
}
}
}
return d;
}
double Distance(point a, point b)
{
return sqrt((a.x - b.x)*(a.x - b.x) + (a.y - b.y)*(a.y - b.y));
}
void QuicksortByY(point P[], int first, int end)
{
quickSort(P, first, end);
}
int Partition(point r[], int first, int end)
{
int i = first, j = end;
//右侧扫描
while (i < j)
{
while (i < j && r[i].y <= r[j].y)
j--;
if (i < j)
{
//point temp = r[i];
point temp;
temp.x = r[i].x;
temp.y = r[i].y;
//r[i] = r[j];
r[i].x = r[j].x;
r[i].y = r[j].y;
//r[j] = temp;
r[j].x = temp.x;
r[j].y = temp.y;
i++;
}
}
//左侧扫描
while (i < j && r[i].y <= r[j].y)
i++;
if (i < j)
{
//int temp = r[i];
point temp;
temp.x = r[i].x;
temp.y = r[i].y;
//r[i] = r[j];
r[i].x = r[j].x;
r[i].y = r[j].y;
//r[j] = temp;
r[j].x = temp.x;
r[j].y = temp.y;
j--;
}
return i;
}
void quickSort(point r[], int first, int end)
{
int pivot;
if (first < end)
{
pivot = Partition(r, first, end);
quickSort(r, first, pivot - 1);
quickSort(r, pivot + 1, end);
}
}
int main()
{
point a,b,c,d,e,f,g,h;
a.x = 1;a.y = 21;
b.x = 3;b.y = 91;
c.x = 4;c.y = 100;
d.x = 5;d.y = 8;
e.x = 6;e.y = 12;
f.x = 8;f.y = 10;
g.x = 10;g.y = 14;
h.x = 19;h.y = 7;
point P[] = {a,b,c,d,e,f,g,h};
cout << P[0].x << " " << P[6].y << endl;
//quickSort(P,0,7);
for (int j = 0;j <= 7;j++)
{
cout << P[j].y;
cout << " ";
}
cout << endl;
cout << P[0].y << " " << P[6].y << endl;
double sum = ClosestPoint(P, 0, 7);
cout << "最近距离是:" << sum << endl;
system("pause");
return 0;
}
|
edb9d7aaee32434bae04eb1f4fae72cbc07da3a6 | 014d58ab427fcae07269e7ea24c2ff267682e4c4 | /Lecture 16 Graphs 1/12 3 Cycle.cpp | 8ec79a56cbebd8a1a115915c92575454b56ef997 | [] | no_license | Sumit1608/CodingNinjas_CompetitiveProgramming_Solutions | 3113c8303912f729ac543fb4fe5111418d4fc434 | a36de7f67a3939932aa3ddfcb497479925ad4bed | refs/heads/main | 2023-07-18T15:18:05.204615 | 2021-09-08T07:25:32 | 2021-09-08T07:25:32 | 344,851,223 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 658 | cpp | 12 3 Cycle.cpp | #include<bits/stdc++.h>
using namespace std;
// time comp => O(n^3)
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int v, e;
cin >> v >> e;
int** arr = new int*[v];
for (int i = 0; i < v; i++)
arr[i] = new int[v]();
while (e--){
int a, b;
cin >> a >> b;
arr[a][b] = 1;
arr[b][a] = 1;
}
int cycleCount = 0;
for (int i = 0; i < v-2; ++i)
for (int j = i+1; j < v-1; ++j)
for (int k = j+1; k < v; ++k)
if (arr[i][j] && arr[j][k] && arr[k][i])
++cycleCount;
cout << cycleCount <<endl;
return 0;
}
|
c07e86d3c19dd8f312c039e56e9e017ca2e4171a | ea2786bfb29ab1522074aa865524600f719b5d60 | /MultimodalSpaceShooter/src/core/Managers.cpp | 69ce07f56571c1839d16f8de30e605886ad8cf04 | [] | no_license | jeremysingy/multimodal-space-shooter | 90ffda254246d0e3a1e25558aae5a15fed39137f | ca6e28944cdda97285a2caf90e635a73c9e4e5cd | refs/heads/master | 2021-01-19T08:52:52.393679 | 2011-04-12T08:37:03 | 2011-04-12T08:37:03 | 1,467,691 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 565 | cpp | Managers.cpp | #include "core/Managers.h"
#include "core/Game.h"
AudioEngine& audioEngine()
{
return Game::instance().myAudioEngine;
}
EventManager& eventManager()
{
return Game::instance().myEventManager;
}
MultimodalManager& multimodalManager()
{
return Game::instance().myMultimodalManager;
}
EntityManager& entityManager()
{
return Game::instance().myEntityManager;
}
ImageManager& imageManager()
{
return Game::instance().myImageManager;
}
SoundManager& soundManager()
{
return Game::instance().mySoundManager;
}
|
d8012dbc092b6b6c0ade0946275c068c01259eb2 | cadf9f2b9f281f2adc2732c165b561f30830cc71 | /Libraries/Source/og/Math/Color.cpp | d10844b0e7abcce0eaf0104f169feafe14076923 | [
"Zlib",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | ensiform/open-game-libraries | 0f687adc42beb2d628b19aa0261ed7398245c7e7 | 265c0d13198bd1910fe3c253b4ac04d55016b73f | refs/heads/master | 2020-05-16T23:42:18.476970 | 2014-04-26T17:47:21 | 2014-04-26T17:47:21 | 8,855,538 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,553 | cpp | Color.cpp | /*
===========================================================================
The Open Game Libraries.
Copyright (C) 2007-2010 Lusito Software
Author: Santo Pfingsten (TTK-Bandit)
Purpose: Color class
-----------------------------------------
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
===========================================================================
*/
#include <og/Math.h>
namespace og {
/*
================
SingleHexToFloat
================
*/
static float SingleHexToFloat( char c ) {
if ( c <= '9' && c >= '0' )
return static_cast<float>( c - '0' ) / 15.0f;
else if ( c <= 'f' && c >= 'a' )
return static_cast<float>( c - 'a' + 10 ) / 15.0f;
else if ( c <= 'F' && c >= 'A' )
return static_cast<float>( c - 'A' + 10 ) / 15.0f;
return 1.0f;
}
/*
==============================================================================
Color
==============================================================================
*/
/*
================
Color::GetEscapeColor
================
*/
int Color::GetEscapeColor( const char *str, Color &destColor, const Color &defaultColor ) {
if ( *str == '\0' )
return -1;
if ( *str == 'c' ) {
if ( str[1] == '\0' || str[2] == '\0' || str[3] == '\0' )
return -1;
destColor.r = SingleHexToFloat( str[1] );
destColor.g = SingleHexToFloat( str[2] );
destColor.b = SingleHexToFloat( str[3] );
return 4;
}
switch( *str ) {
default:
case '0':
destColor = defaultColor;
break;
case '1':
destColor = c_color::red;
break;
case '2':
destColor = c_color::green;
break;
case '3':
destColor = c_color::yellow;
break;
case '4':
destColor = c_color::blue;
break;
case '5':
destColor = c_color::cyan;
break;
case '6':
destColor = c_color::magenta;
break;
case '7':
destColor = c_color::white;
break;
case '8':
destColor = c_color::gray;
break;
case '9':
destColor = c_color::black;
break;
}
return 1;
}
namespace c_color {
Color transparent( 0.0f, 0.0f, 0.0f, 0.0f );
Color white( 1.0f, 1.0f, 1.0f, 1.0f );
Color black( 0.0f, 0.0f, 0.0f, 1.0f );
Color gray( 0.5f, 0.5f, 0.5f, 1.0f );
Color gray_dark( 0.25f, 0.25f, 0.25f, 1.0f );
Color gray_light( 0.75f, 0.75f, 0.75f, 1.0f );
Color red( 1.0f, 0.0f, 0.0f, 1.0f );
Color green( 0.0f, 1.0f, 0.0f, 1.0f );
Color blue( 0.0f, 0.0f, 1.0f, 1.0f );
Color cyan( 0.0f, 1.0f, 1.0f, 1.0f );
Color magenta( 1.0f, 0.0f, 1.0f, 1.0f );
Color yellow( 1.0f, 1.0f, 0.0f, 1.0f );
Color orange( 1.0f, 0.5f, 0.0f, 1.0f );
Color purple( 0.75f, 0.0f, 1.0f, 1.0f );
Color pink( 1.0f, 0.0f, 1.0f, 1.0f );
Color brown( 0.5f, 0.25f, 0.0f, 1.0f );
}
}
|
a171c9d01f97b4a23d38448486b50d6dc9f7a21c | 6d088ec295b33db11e378212d42d40d5a190c54c | /core/vpgl/algo/Templates/vpgl_em_compute_5_point+double-.cxx | 8ee291ca7f3be257beacb12bb844a64a39487809 | [] | no_license | vxl/vxl | 29dffd5011f21a67e14c1bcbd5388fdbbc101b29 | 594ebed3d5fb6d0930d5758630113e044fee00bc | refs/heads/master | 2023-08-31T03:56:24.286486 | 2023-08-29T17:53:12 | 2023-08-29T17:53:12 | 9,819,799 | 224 | 126 | null | 2023-09-14T15:52:32 | 2013-05-02T18:32:27 | C++ | UTF-8 | C++ | false | false | 145 | cxx | vpgl_em_compute_5_point+double-.cxx | // Instantiaion of vpgl_em_compute_5_point<double>
#include <vpgl/algo/vpgl_em_compute_5_point.hxx>
VPGL_EM_COMPUTE_5_POINT_INSTANTIATE(double);
|
a998f36cefcef8de2db88209147bceb9d88ce67f | a41718adf8fdef37dff1bb70a9ba57ac776d139b | /src/net.cpp | 990753d455023b55c65649a12e06d222eb74dc3e | [
"BSD-4-Clause-UC"
] | permissive | saulopz/edge_filters | a803829f31c90e98a3320b57a9e7cd8416e65c30 | 85bd32a4e8093a6a8e64de4647cd71dd6b5f1964 | refs/heads/master | 2023-05-25T23:06:07.986256 | 2021-06-10T19:12:23 | 2021-06-10T19:12:23 | 375,805,412 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,947 | cpp | net.cpp | /* Neural network C code created by QwikNet V2.23
* Network file name: untitled
* Structure: 9/10/1
* Date: Thu Aug 30 08:45:32 2001
*/
#include <math.h>
#include <stdlib.h>
#define INPUTS 9
#define HIDDEN1 10
#define OUTPUTS 1
#define HIDDEN1_INDEX (INPUTS)
#define OUTPUT_INDEX (HIDDEN1_INDEX + HIDDEN1)
#define NUMNEURONS (INPUTS + HIDDEN1 + OUTPUTS)
static double NEURON[NUMNEURONS];
/* Weight arrays */
static const double W_In_H1[HIDDEN1][INPUTS + 1] = {
1.46306, -0.48353, 0.556802, 0.696731, -3.54228, 0.580612, -1.29206, 2.21547, -0.218727, 0.30247,
0.12464, -0.363792, -0.00912601, -0.208304, 1.57896, -0.759195, 0.448252, -0.246646, -0.347245, -0.128616,
1.36362, -2.34813, 0.198959, -1.62104, 3.97698, 4.22806e-005, -1.18597, -0.227945, 0.0399828, -0.338878,
0.391645, -0.321871, 0.721798, -0.257518, 1.97014, -0.427979, -0.39448, 0.592101, -0.633118, 0.149267,
0.473705, 0.669365, 0.679692, 0.557485, -2.159, 0.399681, 0.00418039, 0.82986, 0.637189, 0.035582,
0.804048, 1.72548, 1.35932, -0.0380864, -2.99959, 0.576475, 0.904021, 1.08142, 0.991563, 0.25353,
0.33809, -0.319366, 0.451423, -0.977038, -2.31819, -0.223899, -0.826951, 0.0597971, 0.0875238, -0.515679,
-0.20823, 0.640548, 0.349454, 1.45503, -2.91341, 0.269586, 0.793465, 0.326139, 0.357733, 0.13929,
1.64543, -0.776498, 1.18467, 0.695131, -3.7529, 0.287333, -1.59288, 2.46328, -0.76261, 0.421524,
-0.178771, 0.779554, 0.395544, 1.52267, -3.41258, 0.351137, 0.67866, 0.489285, 0.376394, 0.408207};
static const double W_H1_Out[OUTPUTS][HIDDEN1 + 1] = {
4.45606, -2.40843, -5.90517, -3.18314, 2.35856, 4.03491, 3.45828, 3.09768, 5.04998, 3.6273, -2.01805};
/* Scale factors */
static const double R_MIN[INPUTS + OUTPUTS] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
static const double R_MAX[INPUTS + OUTPUTS] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
static const double S_MIN[INPUTS + OUTPUTS] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, 0};
static const double S_MAX[INPUTS + OUTPUTS] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
/* Nonlinearity functions */
static double sigmoid(double x) { return (1.0 / (1.0 + exp(-x))); }
//static double ftanh( double x ) { return tanh( x ); }
//static double gaussian( double x ) { return exp( -x*x/2 ); }
//static double linear( double x ) { return x; }
/* Compute the network response
* Arguments:
* inputs pointer to (double) array containing the input values
* outputs pointer to (double) array which receives the results
* Return:
* NonZero (1) if successful, 0 if not.
*/
int eval_net(const double *inputs, double *outputs)
{
double F;
int i, j;
/* Check for invalid arguments */
if (inputs == NULL || outputs == NULL)
return 0;
/* Zero neuron sums */
for (i = 0; i < NUMNEURONS; i++)
NEURON[i] = 0.0;
/* Apply inputs */
for (i = 0; i < INPUTS; i++)
{
F = (S_MAX[i] - S_MIN[i]) / (R_MAX[i] - R_MIN[i]); /* scale factor */
NEURON[i] = F * inputs[i] + S_MIN[i] - F * R_MIN[i];
}
/* Compute hidden layer #1 */
for (i = 0; i < HIDDEN1; i++)
{
for (j = 0; j < INPUTS; j++)
{
NEURON[HIDDEN1_INDEX + i] += NEURON[j] * W_In_H1[i][j];
}
NEURON[HIDDEN1_INDEX + i] += W_In_H1[i][INPUTS]; /* BIAS */
NEURON[HIDDEN1_INDEX + i] = sigmoid(NEURON[HIDDEN1_INDEX + i]);
}
/* Compute network outputs */
for (i = 0; i < OUTPUTS; i++)
{
for (j = 0; j < HIDDEN1; j++)
{
NEURON[OUTPUT_INDEX + i] += NEURON[HIDDEN1_INDEX + j] * W_H1_Out[i][j];
}
NEURON[OUTPUT_INDEX + i] += W_H1_Out[i][HIDDEN1]; /* BIAS */
NEURON[OUTPUT_INDEX + i] = sigmoid(NEURON[OUTPUT_INDEX + i]);
}
/* Copy outputs to output array */
for (i = 0; i < OUTPUTS; i++)
{
F = (R_MAX[i + INPUTS] - R_MIN[i + INPUTS]) / (S_MAX[i + INPUTS] - S_MIN[i + INPUTS]); /* unscale factor */
outputs[i] = F * NEURON[OUTPUT_INDEX + i] + R_MIN[i + INPUTS] - F * S_MIN[i + INPUTS];
}
return 1;
}
|
70d7e4560012abec45e7f5faaae47e513626127a | 87ff31b06c2c7e02e50c452189dba3d0f965c8f6 | /Kpp/reg_alloc/reg_alloc.cpp | 8777042b4d56a1b85eb2e125cd22c4992cf2218e | [
"MIT"
] | permissive | Tonyx97/Kpp | 9b162e016c5daec3dae91ba75ac895809f4b1b3e | 13f23b371abf60967a89fd5c029195cb91fd88cc | refs/heads/main | 2023-08-20T09:42:07.161163 | 2021-10-19T10:30:07 | 2021-10-19T10:30:07 | 340,162,421 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 3,384 | cpp | reg_alloc.cpp | #include <defs.h>
#include <ir/ir.h>
#include <ssa/ssa.h>
#include "reg_alloc.h"
using namespace kpp;
reg_alloc::~reg_alloc()
{
}
bool reg_alloc::init()
{
x64::for_each_register([&](reg* r) { free_regs.insert(r); });
return true;
}
bool reg_alloc::calculate()
{
for (auto prototype : ir.get_ir_info().prototypes)
{
auto entry = prototype->get_entry_block();
if (!entry)
return false;
if (!calculate_register_usage(prototype->ssa, entry))
return false;
if (!undo_phis(prototype))
return false;
PRINT(C_DARK_RED, "Max usage: %i", max_usage);
/*for (auto b : prototype->blocks)
{
PRINT(C_CYAN, "'%s':", b->name.c_str());
PRINT_TABS_NL(C_CYAN, 1, "Block info:");
for (auto info : b->regs_assigned)
PRINT_TABS(C_GREEN, 2, "'%s'\n", STRINGIFY_REGISTER(info->name).c_str());
PRINT_TABS_NL(C_CYAN, 1, "Values info:");
for (auto i : b->items)
{
i->for_each_left_op([&](ir::Value* v)
{
if (v->r)
PRINT_TABS(C_GREEN, 2, "'%s' -> '%s'\n", v->name.c_str(), STRINGIFY_REGISTER(v->r->name).c_str());
else PRINT_TABS(C_GREEN, 2, "'%s' has no register\n", v->name.c_str());
return nullptr;
});
}
}
for (auto v : ctx->ssa_values)
{
if (v->r)
PRINT(C_CYAN, "'%s' -> '%s'", v->name.c_str(), STRINGIFY_REGISTER(v->r->name).c_str());
else PRINT(C_CYAN, "'%s' has no register (xd)", v->name.c_str());
}*/
}
return true;
}
bool reg_alloc::calculate_register_usage(ssa_ctx* ctx, ir::Block* block)
{
auto prototype = ctx->prototype;
for (auto v_in : ctx->in_out[block].in)
for (auto v_ver : v_in->vers)
if (v_ver->storage.r && v_ver->life.has_block(block))
block->regs_assigned.insert(v_ver->storage.r);
PRINT(C_CYAN, "'%s':", block->name.c_str());
for (auto i : block->items)
{
i->for_each_right_op([&](ir::Value* v)
{
if (v->life.last == i && !v->storage.default_r)
{
free_reg(block, v->storage.r);
PRINT_TABS_NL(C_RED, 1, "'%s' -> '%s' freed", v->name.c_str(), STRINGIFY_REGISTER(v->storage.r->id).c_str());
}
return nullptr;
});
i->for_each_left_op([&](ir::Value* v)
{
if (v->life.first != v->life.last && !v->storage.default_r)
{
prototype->add_register(v->storage.r = alloc_reg(block));
PRINT_TABS_NL(C_GREEN, 1, "'%s' -> '%s' allocated", v->name.c_str(), STRINGIFY_REGISTER(v->storage.r->id).c_str());
}
return nullptr;
});
}
for (auto dom : block->doms)
if (dom != block)
calculate_register_usage(ctx, dom);
return true;
}
bool reg_alloc::undo_phis(ir::Prototype* prototype)
{
for (auto b : prototype->blocks)
for (auto phi : b->phis)
for (auto param : phi->values)
for (auto predecessor : b->refs)
if (param->life.has_block(predecessor))
predecessor->add_phi_alias(phi->op, param);
return true;
}
void reg_alloc::free_reg(ir::Block* b, reg* r)
{
if (!r || !r->general)
return;
if (used_regs.contains(r))
{
b->regs_assigned.erase(r);
used_regs.erase(r);
free_regs.insert(r);
--current_usage;
}
}
reg* reg_alloc::alloc_reg(ir::Block* b)
{
if (!free_regs.empty())
{
for (auto r : free_regs)
if (r->general)
{
b->regs_assigned.insert(r);
free_regs.erase(r);
used_regs.insert(r);
max_usage = std::max(++current_usage, max_usage);
return r;
}
}
PRINT(C_RED, "There are no registers left to assign");
return nullptr;
} |
4ef10dfebdc681ca58cb0cfaaf6bc292e8852147 | b0abfa1599ae74dbefcb3a724ac86ba7db8308e8 | /Truck_coutainer_sercher/Truck_coutainer_sercher.ino | f0c6e659dc32eb6af3d8616b21ce97a243569312 | [] | no_license | sakatanitouga/Track_container_Sercher | ed98d4d936dfde0fb3696e21071171d8b8873a38 | db05815d9784c1b1e44e53f26eb3a83f44cdcff4 | refs/heads/master | 2022-12-19T18:23:46.138896 | 2020-10-05T08:24:52 | 2020-10-05T08:24:52 | 301,331,929 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,101 | ino | Truck_coutainer_sercher.ino | #include <SD.h>
#include "BluetoothSerial.h"
#include <driver/adc.h>
#define PSD 2800
const uint8_t cs_SD = 5;
File fo;
BluetoothSerial SerialBT;
int i = 0;
int d=0;
const char* fname ="/test1.txt";
void setup() {
adc2_config_channel_atten(ADC2_CHANNEL_4,ADC_ATTEN_DB_11);
delay(1000);
SerialBT.begin("ESP_32");
Serial.begin(115200);
if(SD.begin(cs_SD,SPI,24000000,"/sd"))
Serial.println("Open_SD");
else
Serial.println("Error_OPEN");
delay(1000);
fo=SD.open(fname,FILE_WRITE);
if(!fo){
Serial.println("Error_write");
}else{
for(i=0;i<10;i++){
fo.print("This is test.\n");
delay(1000);
Serial.println(i,DEC);
}
}
fo.close();
}
void loop() {
int psd =0;
adc2_get_raw(ADC2_CHANNEL_4,ADC_WIDTH_BIT_12,&psd);
// put your main code here, to run repeatedly:
if(psd>PSD){
Serial.printf("Close psd_sencor%d.\r\n",psd);
SerialBT.printf("Close psd_sencor:%d.\r\n",psd);
}else{
Serial.printf("Open psd_sencor:%d.\r\n",psd);
SerialBT.printf("Open psd_sencor:%d.\r\n",psd);
}
delay(500);
}
|
7d29d160cc5377dd9ab570853cbca8252d6a108f | 8a22dbf51e9b7e6651b29746c25a2402ee91cd48 | /testing.h | 8d67094962f7ab8bac46b5d101df09e31f3976ce | [] | no_license | Bak-JH/QMLLab | cbf8f707a5c03518c538584951a83e8b28346b05 | 72571c8c4c7924f240c68185e8f362040781d7a6 | refs/heads/master | 2020-08-17T16:19:38.763870 | 2019-10-18T07:58:24 | 2019-10-18T07:58:24 | 215,686,640 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 562 | h | testing.h | #ifndef TESTING_H
#define TESTING_H
#include <QtQuick/QQuickPaintedItem>
#include <QtQuick/5.12.3/QtQuick/private/qquickrectangle_p.h>
#include <QtQuick/5.12.3/QtQuick/private/qquickmousearea_p.h>
#include <QtQuick/5.12.3/QtQuick/private/qquickevents_p_p.h>
#include <QColor>
#include <QQmlComponent>
#include <QQmlEngine>
class PopupShell : public QQuickRectangle
{
Q_OBJECT
public:
PopupShell();
public slots:
void onClick();
private:
QQuickMouseArea* mouseArea;
};
class TestPopup : public PopupShell
{
Q_OBJECT
};
#endif // TESTING_H
|
eed0eafcf0d6591d78113aff4f29b2ee55edba4a | ddbbe9e6bead08f1f0089cbf9cdb2ff80bf08a78 | /reference.cpp | bfe88b70a6e377112c1a0c28cb6839265fac1c39 | [
"MIT"
] | permissive | xiaji/noip-csp | ff7405c863944326273fa06c8d906de941cd88e7 | 7551478e848f3c3d2a4cc2d780d0efeedab67e6e | refs/heads/master | 2020-08-08T12:14:40.902950 | 2019-11-15T12:46:37 | 2019-11-15T12:46:37 | 213,830,049 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 849 | cpp | reference.cpp | #include <iostream>
using namespace std;
void times_ref(int& a, int& b) {
a *= 2;
b *= 2;
}
void times(int a, int b) {
a *= 2;
b *= 2;
}
void prevnext(int x, int& prev, int& next) {
prev = x * 2;
next = prev + 1;
}
int main() {
int a = 2, b = 3;
times(a, b);
cout << "call times method without ampersand sign (&): ";
cout << "a: " << a << " b: " << b << endl;
times_ref(a, b);
cout << "call times method with ampersand sign: ";
cout << "a: " << a << " b: "<< b << endl;
prevnext(0, a, b);
cout << "call prevnext(int x, int& prev, int& next): ";
cout << "a: " << a << " b: "<< b << endl;
int& temp = a;
int x = temp;
temp = 10;
cout << "x: " << x << " temp: " << temp << " a: " << a << endl;
cout << "x: " << &x << endl;
cout << "temp: " << &temp << endl;
cout << "a: " << &a << endl;
return 0;
}
|
80dcc842e59ce62fb295bef15aeeda0af6a54f49 | cc848d47940a3d5e5d9906ffef0d553c465978d4 | /ch01/main.cpp | 7017bb2a6704f17c41127e8dd4c7a0945382d6ea | [] | no_license | BeastwareBoom/CppPrimer | 1b141f1a912e76dc9e9145d1965970ad5580dd02 | fbfa9b7fc611ed7f255f54c94d0daa80fc9ae5b5 | refs/heads/master | 2021-07-15T20:54:27.661155 | 2020-06-15T09:12:27 | 2020-06-15T09:12:27 | 175,634,429 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,246 | cpp | main.cpp | #include <iostream>
#include <string.h>
//using namespace std;
struct X
{
virtual void foo()/*=0*/;
};
struct Y : X
{
void foo() {}
};
struct A
{
virtual ~A() = 0;
};
struct B: A
{
virtual ~B(){}
};
//decleration only,see https://www.tutorialspoint.com/What-is-the-difference-between-a-definition-and-a-declaration-in-Cplusplus
extern int x;
void foo();
int main()
{
x = 0;//变量声明,去掉extern可解决
// foo();//只声明,未定义,定义可解决
// Y y;//X中foo声明为纯虚方法可解决
// B b;//A中析构函数,空实现可解决
}
/* auto generated MAIN by live template */
int main_aux_source_directory(int argc, char *argv[]) {
std::cout<<"aux_source_directory command"<<std::endl;
return EXIT_SUCCESS;
}
int main_const() {
double di = 3.14;
// const int &refi = di;
const int a = 1;
const int *aptr = &a;//aptr must be const
// int *aptr2 = &a;//error,a is const
// *aptr=2;// error,read-only a
int b=1,*bptr = &b;
//从右往左读,首先是const类型,然后为int类型指针
const int *const acptr = &a;
// acptr = bptr;//error
return EXIT_SUCCESS;
}
int main_data_type() {
unsigned char c1 = 255;
signed char c2 = -128;
std::cout << "c1=" << c1 << std::endl;
std::cout << "c2=" << c2 << std::endl;
const char *u8str = u8"aaa";//utf-8字符串字面值
std::string str = u8"sss";
return EXIT_SUCCESS;
}
//indeterminate input
int main_in() {
int sum = 0, value = 0;
while (std::cin >> value) {
sum += value;
}
//Ctrl+D for output
std::cout << "sum=" << sum << std::endl;
return EXIT_SUCCESS;
}
int main_stream() {
int v1 = 0, v2 = 0;
//string literal
std::cout << "Please input the numbers:" << std::endl;
std::cin >> v1 >> v2;
// std::cout<<"Please input the second num:"<<std::endl;
// std::cin>>v2;
std::cout << "Numbers are: " << v1 << "," << v2 << std::endl;
return EXIT_SUCCESS;
#if false
std::cout << "Hello, World!" << std::endl;
std::cerr << "Hello, cerr!" << std::endl;
std::clog << "Hello, clog!" << std::endl;
return EXIT_SUCCESS;//0
// return EXIT_FAILURE;//1
// return -1;
#endif
} |
69ded89ee19b4c4bc2bf35b4d66671534e337374 | f95c4d9fcea5606a0229844adc709c5fea1b6421 | /solvers/tisi/src/tisi.cpp | ff45ebc3b93f28e8e61f0e7adc84639e324ca0cf | [
"BSD-3-Clause"
] | permissive | sellamiy/GPiD-Framework | 4c5db6caa24929775f75b3e033aff187b3ba55a4 | f6ed1abb2da6d51639f5ee410b1f9b143a200465 | refs/heads/master | 2021-06-13T21:47:35.654411 | 2021-02-08T04:51:49 | 2021-02-08T04:51:49 | 140,702,115 | 8 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,184 | cpp | tisi.cpp | #define TISI_W_DOC_FOR_GPID__CPP
#include <tisi.hpp>
using namespace abdulot;
static TisiManager dummyManager;
static TisiConstraint dummyConstraint;
static TisiModel dummyModel;
static ObjectMapper<TisiLiteral> dummyMapper;
static std::map<typename TisiGenerator::index_t,
std::vector<typename TisiGenerator::index_t>> dummyLinks;
std::string TisiLiteral::str() { return "^_^"; }
bool TisiModel::implies(TisiLiteral&) const { return false; }
TisiManager& TisiProblemLoader::getContextManager() { return dummyManager; }
TisiManager& TisiInterface::getContextManager() { return dummyManager; }
TisiModel& TisiInterface::getModel() { return dummyModel; }
void TisiProblemLoader::load(std::string filename, std::string language) {
std::cerr << "This should load the file " << filename
<< " with the following input language handler: " << language
<< std::endl;
}
void TisiProblemLoader::prepareReader() {}
bool TisiProblemLoader::hasConstraint() { return false; }
TisiConstraint& TisiProblemLoader::nextConstraint() { return dummyConstraint; }
TisiGenerator::TisiGenerator(TisiProblemLoader&) {}
TisiInterface::TisiInterface(TisiManager&, const SolverInterfaceOptions&) {}
void TisiGenerator::load(std::string filename) {
std::cerr << "This should load abducible literals from " << filename
<< std::endl;
}
void TisiGenerator::generate(std::string generatorid) {
std::cerr << "This should generate abducible using the " << generatorid
<< " method" << std::endl;
}
size_t TisiGenerator::count() { return 0; }
ObjectMapper<TisiLiteral>& TisiGenerator::getMapper() { return dummyMapper; }
std::map<typename TisiGenerator::index_t, std::vector<typename TisiGenerator::index_t>>&
TisiGenerator::getLinks() { return dummyLinks; }
void TisiInterface::addConstraint(TisiConstraint&) {}
void TisiInterface::addLiteral(LiteralT&, bool) {}
void TisiInterface::clearUnsafeClauses() {}
void TisiInterface::push() {}
void TisiInterface::pop() {}
SolverTestStatus TisiInterface::check() { return SolverTestStatus::UNSAT; }
std::string TisiInterface::getPrintableAssertions(bool) { return "O_0"; }
|
261109ec67c2d5f3f44a0dad73dcfe2c0e7b585b | ca4c0b4c3747150cb985377cf00aaaf6062fed9f | /GFG DSA KING/2 SEARCHING/2 without adjustment.cpp | ea82fb522b2a50491d336ec2c6f0899118f2e736 | [] | no_license | darkLuciferDevilOfHisWord/GFG_DSA | 3ed3bde5fbab49d9272a3fc90d497d40d5cc7416 | cdcdf23dbd1f35ef9203ac4ca9749763d216c8c3 | refs/heads/main | 2023-06-06T16:24:10.721411 | 2021-06-30T10:51:23 | 2021-06-30T10:51:23 | 381,668,474 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 740 | cpp | 2 without adjustment.cpp | #include<bits/stdc++.h>
using namespace std;
long long arr[11000001];
long long FindMaxSum(int n)
{
long long incl_prev = arr[0];
long long excl_prev = 0;
long long incl_curr = 0;
long long excl_curr = 0;
int i;
for (i = 1; i < n; i++)
{
excl_curr = max(incl_prev, excl_prev);
incl_curr = excl_prev + arr[i];
incl_prev = incl_curr;
excl_prev = excl_curr;
}
return max(incl_curr, excl_curr);
}
int main()
{
int t;
cin >> t;
while(t--){
int n;
cin >> n;
for(int i = 0;i<n;i++){
cin >> arr[i];
}
if(n == 1)
cout << arr[0] << endl;
else cout << FindMaxSum(n) << endl;
}
return 0;
} |
9f4c5972540db47fb9b94d8d3665922c3febbd3b | 435e3c72f428de58c173c872232042093d7e122b | /A4_STL/4_1_vector/main.cpp | bb583f5f279d16fcdf8f91cc634ffd7215c08e30 | [] | no_license | RioKKH/c_example | 3cb05eb26a13094f5201996a057f7c5be9e4a4d8 | 697d80d9bc91d832dfba1ecc3893a79128963d43 | refs/heads/master | 2023-08-09T17:30:35.523459 | 2023-07-24T16:45:45 | 2023-07-24T16:45:45 | 164,203,389 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 694 | cpp | main.cpp | #include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<int> v1;
vector<string> v2;
v1.push_back(1);
v1.push_back(2);
v1.push_back(3);
v2.push_back("ABC");
v2.push_back("DEF");
unsigned int i;
for (i = 0; i < v1.size(); i++) {
cout << "v1[" << i << "]=" << v1[i] << endl;
}
for (i = 0; i < v2.size(); i++) {
cout << "v2[" << i << "]=" << v2[i] << endl;
}
cout << "Size:" << v1.size() << endl;
cout << "Capacity:" << v1.capacity() << endl;
cout << "Is empty?:" << v1.empty() << endl;
v1.clear();
cout << "Is empty?:" << v1.empty() << endl;
return 0;
}
|
a2b5c4c4c5eaca380bfd5de3ffa35fc4cdd4b7c8 | 48f33ee027073e137ed98f4b0b2fe836756d8a34 | /Source/NetworkProgramming/FGRocket.h | a3231a54b1586cb10e4a7f93fc9a4f0b575d9eb1 | [] | no_license | fredrikhanses/NetworkProgramming | 6e748490646a803b60c22c5bc808b022c659ab61 | d683444f98e5b942013c0c28dc9d8e1c75688bf1 | refs/heads/main | 2023-02-26T07:10:09.578995 | 2021-01-31T22:56:48 | 2021-01-31T22:56:48 | 317,240,818 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,309 | h | FGRocket.h | #pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "FGRocket.generated.h"
class UStaticMeshComponent;
UCLASS()
class NETWORKPROGRAMMING_API AFGRocket : public AActor
{
GENERATED_BODY()
public:
AFGRocket();
protected:
virtual void BeginPlay() override;
public:
virtual void Tick(float DeltaTime) override;
void StartMoving(const FVector& Forward, const FVector& InStartLocation);
void ApplyCorrection(const FVector& Forward);
bool IsFree() const { return bIsFree; }
void Explode();
void MakeFree();
void SetRocketVisibility(bool bVisible);
uint32 Damage = 10;
private:
FCollisionQueryParams CachedCollisionQueryParams;
UPROPERTY(EditAnywhere, Category = VFX)
UParticleSystem* Explosion = nullptr;
UPROPERTY(EditAnywhere, Category = Mesh)
UStaticMeshComponent* MeshComponent = nullptr;
UPROPERTY(EditAnywhere, Category = Debug)
bool bDebugDrawCorrection = false;
FVector OrigianlFacingDirection = FVector::ZeroVector;
FVector FacingRotationStart = FVector::ZeroVector;
FQuat FacingRotationCorrection = FQuat::Identity;
FVector RocketStartLocation = FVector::ZeroVector;
float LifeTime = 2.0f;
float LifeTimeElapsed = 0.0f;
float DistanceMoved = 0.0f;
UPROPERTY(EditAnywhere, Category = VFX)
float MovementVelocity = 1300.0f;
bool bIsFree = true;
};
|
3a99fab4123fc8996cf8102bd196a395b27b6a41 | 1fe10ee5e34cd76067c720ef4b4a054f6107b286 | /mobile/mobile/bundled_jni/chill/mobile/jni/PasswordManagerDialogRequest_jni.h | 4c3f78a207d09797b6824fb4762b63c2ba4ea819 | [
"BSD-2-Clause"
] | permissive | bopopescu/ofa | 9f001c4f36b07fa27347ade37337422fd6719dcc | 84e319101d4a1200657337dcdf9ed3857fc59e03 | refs/heads/master | 2021-06-14T08:53:05.865737 | 2017-04-03T12:50:44 | 2017-04-03T12:50:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,119 | h | PasswordManagerDialogRequest_jni.h | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file is autogenerated by
// base/android/jni_generator/jni_generator.py
// For
// com/opera/android/browser/passwordmanager/PasswordManagerDialogRequest
#ifndef com_opera_android_browser_passwordmanager_PasswordManagerDialogRequest_JNI
#define com_opera_android_browser_passwordmanager_PasswordManagerDialogRequest_JNI
#include <jni.h>
#include "../../../../../../../../../../../../../../../base/android/jni_generator/jni_generator_helper.h"
#include "base/android/jni_int_wrapper.h"
// Step 1: forward declarations.
namespace {
const char kPasswordManagerDialogRequestClassPath[] =
"com/opera/android/browser/passwordmanager/PasswordManagerDialogRequest";
// Leaking this jclass as we cannot use LazyInstance from some threads.
base::subtle::AtomicWord g_PasswordManagerDialogRequest_clazz
__attribute__((unused)) = 0;
#define PasswordManagerDialogRequest_clazz(env) base::android::LazyGetClass(env, kPasswordManagerDialogRequestClassPath, &g_PasswordManagerDialogRequest_clazz)
} // namespace
namespace opera {
// Step 2: method stubs.
JNI_GENERATOR_EXPORT void
Java_com_opera_android_browser_passwordmanager_PasswordManagerDialogRequest_nativeOnResult(JNIEnv*
env, jobject jcaller,
jlong nativePasswordManagerDialogRequest,
jboolean accepted) {
PasswordManagerDialogRequest* native =
reinterpret_cast<PasswordManagerDialogRequest*>(nativePasswordManagerDialogRequest);
CHECK_NATIVE_PTR(env, jcaller, native, "OnResult");
return native->OnResult(env, base::android::JavaParamRef<jobject>(env,
jcaller), accepted);
}
static base::subtle::AtomicWord
g_PasswordManagerDialogRequest_showRememberPasswordDialog = 0;
static void Java_PasswordManagerDialogRequest_showRememberPasswordDialog(JNIEnv*
env, const base::android::JavaRefOrBare<jobject>& obj) {
CHECK_CLAZZ(env, obj.obj(),
PasswordManagerDialogRequest_clazz(env));
jmethodID method_id =
base::android::MethodID::LazyGet<
base::android::MethodID::TYPE_INSTANCE>(
env, PasswordManagerDialogRequest_clazz(env),
"showRememberPasswordDialog",
"("
")"
"V",
&g_PasswordManagerDialogRequest_showRememberPasswordDialog);
env->CallVoidMethod(obj.obj(),
method_id);
jni_generator::CheckException(env);
}
static base::subtle::AtomicWord
g_PasswordManagerDialogRequest_showReplacePasswordDialog = 0;
static void Java_PasswordManagerDialogRequest_showReplacePasswordDialog(JNIEnv*
env, const base::android::JavaRefOrBare<jobject>& obj) {
CHECK_CLAZZ(env, obj.obj(),
PasswordManagerDialogRequest_clazz(env));
jmethodID method_id =
base::android::MethodID::LazyGet<
base::android::MethodID::TYPE_INSTANCE>(
env, PasswordManagerDialogRequest_clazz(env),
"showReplacePasswordDialog",
"("
")"
"V",
&g_PasswordManagerDialogRequest_showReplacePasswordDialog);
env->CallVoidMethod(obj.obj(),
method_id);
jni_generator::CheckException(env);
}
static base::subtle::AtomicWord g_PasswordManagerDialogRequest_create = 0;
static base::android::ScopedJavaLocalRef<jobject>
Java_PasswordManagerDialogRequest_create(JNIEnv* env, jlong
nativeDialogRequest,
const base::android::JavaRefOrBare<jobject>& tab) {
CHECK_CLAZZ(env, PasswordManagerDialogRequest_clazz(env),
PasswordManagerDialogRequest_clazz(env), NULL);
jmethodID method_id =
base::android::MethodID::LazyGet<
base::android::MethodID::TYPE_STATIC>(
env, PasswordManagerDialogRequest_clazz(env),
"create",
"("
"J"
"Lcom/opera/android/browser/chromium/ChromiumTab;"
")"
"Lcom/opera/android/browser/passwordmanager/PasswordManagerDialogRequest;",
&g_PasswordManagerDialogRequest_create);
jobject ret =
env->CallStaticObjectMethod(PasswordManagerDialogRequest_clazz(env),
method_id, nativeDialogRequest, tab.obj());
jni_generator::CheckException(env);
return base::android::ScopedJavaLocalRef<jobject>(env, ret);
}
// Step 3: RegisterNatives.
static const JNINativeMethod kMethodsPasswordManagerDialogRequest[] = {
{ "nativeOnResult",
"("
"J"
"Z"
")"
"V",
reinterpret_cast<void*>(Java_com_opera_android_browser_passwordmanager_PasswordManagerDialogRequest_nativeOnResult)
},
};
static bool RegisterNativesImpl(JNIEnv* env) {
if (base::android::IsManualJniRegistrationDisabled()) return true;
const int kMethodsPasswordManagerDialogRequestSize =
arraysize(kMethodsPasswordManagerDialogRequest);
if (env->RegisterNatives(PasswordManagerDialogRequest_clazz(env),
kMethodsPasswordManagerDialogRequest,
kMethodsPasswordManagerDialogRequestSize) < 0) {
jni_generator::HandleRegistrationError(
env, PasswordManagerDialogRequest_clazz(env), __FILE__);
return false;
}
return true;
}
} // namespace opera
#endif // com_opera_android_browser_passwordmanager_PasswordManagerDialogRequest_JNI
|
9727c12c1c88387e2c2d0819be223e7d4289d80c | b315d27f7abcf63769b99aae07b5425f4fc0c242 | /USS-Game-Project/Bullet.h | 0a955082124d2a2c1f87c1460a37bcf95cce2363 | [] | no_license | sachinjangra/USS-Game-Project | 5599fd33beb7b4956c86eff7dd106270a8bb3b48 | 3bc2de4dc890d404dd44b6a3ac0581f001ce16c6 | refs/heads/master | 2021-08-26T03:52:22.018842 | 2017-11-21T14:10:07 | 2017-11-21T14:10:07 | 110,434,975 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 359 | h | Bullet.h | #pragma once
class Bullet
{
public:
Bullet(bool isFiredTowardsRight);
void update(sf::Time& dt);
void draw(sf::RenderWindow& window);
void setPosition(sf::Vector2f position);
sf::Vector2f getPosition();
sf::Vector2f getSize();
void setTexture(sf::Texture& texture);
private:
sf::RectangleShape mBullet;
bool mIsFiredTowardsRight;
}; |
7f5b1d07f47ef1c4a218c054e2fa40a9b6c7f786 | d0362ca7ab49b02149a53b1cae9a7ce0623d1f7b | /DACView/Source/Objects/CPICTURE.CPP | 3c613183c2f1acde1367e9e93c2b8894b330716e | [] | no_license | realgsg/DACView | 2fffb87b7feacbde2d468d63584e279f0935e2fe | 93ce0a9d479d6701e788159843ca4cf9546629df | refs/heads/master | 2023-06-19T04:09:04.757229 | 2019-05-15T12:56:38 | 2019-05-15T12:56:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,773 | cpp | CPICTURE.CPP | #include "stdafx.h"
#include "CUnitBase.h"
#include "cPicture.h"
//#include "DlgPic.h"
#include "globedef.h"
IMPLEMENT_SERIAL(CObjectPicture, CRectVirtual, 1 | VERSIONABLE_SCHEMA)
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
static CString s_strClassName = "Picture";
ParaName CObjectPicture::sm_ptrParaName[] =
{ {"" , 0, 1},
};
ULONG CObjectPicture::sm_ulArrayIndex[] = { 0 };
const ULONG CObjectPicture::sm_ulDoubleEnd = 0;
const ULONG CObjectPicture::sm_ulWordEnd = 0;
const ULONG CObjectPicture::sm_ulStringEnd = 0;
CObjectPicture::CObjectPicture(const CString& s, CRect r) : CRectVirtual(s, r) {
m_fCreateMemoryDC = FALSE;
if ( m_rectArea.Width() < 60 ) m_rectArea.right = m_rectArea.left + 60;
if ( m_rectArea.Height() < 60 ) m_rectArea.bottom = m_rectArea.top + 60;
}
CObjectPicture::CObjectPicture( void ) : CRectVirtual( ) {
m_fCreateMemoryDC = FALSE;
}
CObjectPicture::~CObjectPicture() {
}
/////////////////////////////////////////////////////////////////////////////
// CObjectPicture diagnostics
#ifdef _DEBUG
void CObjectPicture::AssertValid() const
{
CRectVirtual::AssertValid();
}
void CObjectPicture::Dump(CDumpContext& dc) const
{
CRectVirtual::Dump(dc);
}
#endif //_DEBUG
//////////////////////////////////////////////////////////////////////////////
// COjbectRect member function
void CObjectPicture::Serialize( CArchive& ar ) {
CRectVirtual::Serialize( ar );
if( ar.IsStoring() ) {
ar << m_strBitmapName;
}
else {
switch ( ar.GetObjectSchema() ) {
case 1 :
case -1 :
ar >> m_strBitmapName;
break;
default :
ShowMessage(IDS_WARN_LOAD_OBJECT_VERSION, s_strClassName);
break;
}
}
}
const CString& CObjectPicture::GetClassNameStr( void ) {
return(s_strClassName);
}
BOOL CObjectPicture::ExectiveLink( void ) {
// Dynamic Link Button
return( TRUE );
}
void CObjectPicture::ToShowStatic( CDC * const pdc, CPoint ) {
}
void CObjectPicture::ToShowDynamic( CDC * const pdc, CPoint ) {
}
ParaName* CObjectPicture::GetParaNameAddress( void ) {
return( sm_ptrParaName );
}
char * CObjectPicture::GetParaName( ULONG index ) {
ASSERT( index == 0 );
}
ULONG CObjectPicture::GetDynLinkType(ULONG ulIndex) {
ASSERT(0);
return(0);
}
void CObjectPicture::SelectParameter(ULONG ulType) {
}
ULONG CObjectPicture::GetIndex( ULONG ulIndex ) {
return( 0 );
}
void CObjectPicture::SetProperty( void ) {
CDlgSetMeterProperty CDlg;
CDlg.SetData( m_strName, m_ulScanRate, m_strBitmapName );
CDlg.DoModal();
CDlg.GetData( m_strName, m_ulScanRate, m_strBitmapName );
}
BOOL CObjectPicture::CheckSelf( void ) {
return( TRUE );
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.