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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8bb91c69daea6e7b42b8948513394eabd9027efb
|
a9e416db797908d0533da4062dae4060a07ff7fd
|
/src/graphics/node_sprite_p.h
|
6888678b1b1c8af02ad29c45398b3ceacb31b6dc
|
[
"WTFPL"
] |
permissive
|
dfyx/jumping-cubes-tactics
|
b7a1f73d3742816b2bc3ce07ae751181af0cf7d9
|
30a96816ebe698302f3cc0a8d4971f68689508a0
|
refs/heads/master
| 2021-01-22T04:49:17.013675
| 2015-01-28T19:56:40
| 2015-01-28T19:56:40
| 15,534,874
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 402
|
h
|
node_sprite_p.h
|
#ifndef JCT_SFML_GRAPHICS_NODE_SPRITE_P_H
#define JCT_SFML_GRAPHICS_NODE_SPRITE_P_H
#include <SFML/Graphics.hpp>
namespace JCT_SFML
{
namespace Gamedata
{
class Node;
}
namespace Graphics
{
class NodeSpritePrivate
{
public:
Gamedata::Node *node;
sf::CircleShape circle;
sf::Text text;
sf::Font font;
bool highlighted;
};
}
}
#endif // JCT_SFML_GRAPHICS_NODE_SPRITE_P_H
|
77161429ee0eb603841283e2f51dca8296ccd597
|
096961ee99272213aae979902aad0fed8b86a957
|
/csacademy/66/processing_discounts.cc
|
6109c468bd73dbff2ef0e1c27ed8300ea1632edd
|
[] |
no_license
|
yassin64b/competitive-programming
|
2d92ee9878e33b5f40da4f0440e994beb595a21b
|
180a309da3e12d00c9e4dc384a9aa95ec3e80938
|
refs/heads/master
| 2021-03-27T15:58:27.450505
| 2020-01-11T16:40:17
| 2020-01-11T16:40:17
| 53,347,417
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 574
|
cc
|
processing_discounts.cc
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
int N, X;
cin >> N >> X;
vector<pair<int, int>> ab(N);
for (int i = 0; i < N; ++i) {
cin >> ab[i].first >> ab[i].second;
}
sort(ab.begin(), ab.end());
int best = X, cur = X, cur_disc = 0;
for (int i = 0; i < N; ++i) {
cur = max(cur, ab[i].first);
cur_disc += ab[i].second;
best = min(best, cur - cur_disc);
}
cout << best << endl;
return 0;
}
|
7ae420e5ef54b6671be4cfb4393f2bc70aeb0ad1
|
104d3b210b9c70505a4041f0acc11d5745b9028b
|
/Source/LetsGo/PlayerStates/MatchPlayerState.h
|
ae763534e40df781b780ee1721c553985d7c3c96
|
[] |
no_license
|
lmbrmb/LetsGo
|
12cbf1e736836b362fe4722a1261b1c1bf7f502a
|
4ac0e256354179eb35774b4902d191bb523ded40
|
refs/heads/master
| 2023-06-05T18:22:01.669851
| 2021-06-29T08:59:31
| 2021-06-29T08:59:31
| 326,523,056
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 232
|
h
|
MatchPlayerState.h
|
#pragma once
#include "GameFramework/PlayerState.h"
#include "MatchPlayerState.generated.h"
///<summary>
///Match player state
///</summary>
UCLASS()
class LETSGO_API AMatchPlayerState : public APlayerState
{
GENERATED_BODY()
};
|
93de7ebab942dd1e097668652a93aa5f34dbf311
|
6a890dee5f189532d9d8d8a98974e4f9b5c7f926
|
/src/CommandLineOption.cpp
|
4a8c5021bbf5de5f74b5ab01c76eafe9c1f93691
|
[] |
no_license
|
is3000nx/text2prn
|
9a1c7261d5f5a7dd12c80c9fe18edac237631f66
|
75eb794823cc7c1cbe55dcf16e6886b67e289db2
|
refs/heads/master
| 2020-04-13T07:54:19.609087
| 2015-01-12T01:31:52
| 2015-01-12T01:31:52
| 29,112,523
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 691
|
cpp
|
CommandLineOption.cpp
|
/*! @file
@brief コマンドライン引数
@author 依積晶紀
*/
#include "stdafx.h"
#include "CommandLineOption.h"
/* ==================================================================== */
//! コマンドライン引数の解析
/*
スイッチ("/","-"で始まる)は除外し、
存在するファイルのみを記憶する。 */
/* ==================================================================== */
void CommandLineOption::ParseParam(LPCTSTR lpszParam, BOOL bFlag, BOOL bLast)
{
if (bFlag)
return;
if (!::PathFileExists(lpszParam))
return;
if (::PathIsDirectory(lpszParam))
return;
files_.push_back(lpszParam);
}
|
38c021734cc73a8f9a03548bf3487cf9e668173b
|
ccae26bab9b2ed70a28aacdd33e67649d559cc36
|
/LINKEDLIST/listmain.cpp
|
3bf5eac412b6752484d4116062b887c6fe69449c
|
[] |
no_license
|
KateOlaz/Exercises
|
a4c5c0a063b514781a8da717a92f0704ef6fc6c9
|
39d38788a2f72019f58310075d1b0e8ea15d7ee8
|
refs/heads/master
| 2020-05-07T14:24:17.541037
| 2019-09-10T16:22:07
| 2019-09-10T16:22:07
| 180,592,966
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 879
|
cpp
|
listmain.cpp
|
#include <iostream>
//#include "linkedList.h"
#include "orderedLinkedList.h"
using namespace std;
int main()
{
orderedLinkedList<int> list1, list2;
int num;
cout << "Line 7: Enter numbers ending "<< "with -999." << endl;
cin >> num;
while (num != -999)
{
list1.orderedLinkedList<int>::insert(num);
cin >> num;
}
cout << endl;
cout << "Line 15: list1: ";
list1.linkedListType<int>::print();
cout << endl;
list2 = list1; //test the assignment operator
cout << "Line 19: list2: ";
list2.linkedListType<int>::print();
cout << endl;
cout << "Line 22: Enter the number to be deleted: ";
cin >> num;
cout << endl;
list2.deleteNode(num);
cout << "Line 26: After deleting "<< num << ", list2: " << endl;
list2.linkedListType<int>::print();
cout << endl;
return 0;
}
|
1ef5936c014146bf173e5216a44e30ca447f9eb3
|
010279e2ba272d09e9d2c4e903722e5faba2cf7a
|
/library/cpp/yt/threading/count_down_latch.h
|
14e344365edf2fe8e5a3d4e72f6c6a8220c94c7f
|
[
"Apache-2.0"
] |
permissive
|
catboost/catboost
|
854c1a1f439a96f1ae6b48e16644be20aa04dba2
|
f5042e35b945aded77b23470ead62d7eacefde92
|
refs/heads/master
| 2023-09-01T12:14:14.174108
| 2023-09-01T10:01:01
| 2023-09-01T10:22:12
| 97,556,265
| 8,012
| 1,425
|
Apache-2.0
| 2023-09-11T03:32:32
| 2017-07-18T05:29:04
|
Python
|
UTF-8
|
C++
| false
| false
| 908
|
h
|
count_down_latch.h
|
#pragma once
#include "public.h"
#ifndef _linux_
#include <util/system/condvar.h>
#include <util/system/mutex.h>
#endif
namespace NYT::NThreading {
////////////////////////////////////////////////////////////////////////////////
//! A synchronization aid that allows one or more threads to wait until
//! a set of operations being performed in other threads completes.
/*!
* See https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CountDownLatch.html
*/
class TCountDownLatch final
{
public:
explicit TCountDownLatch(int count);
void CountDown();
void Wait() const;
bool TryWait() const;
int GetCount() const;
private:
std::atomic<int> Count_;
#ifndef _linux_
mutable TCondVar ConditionVariable_;
mutable TMutex Mutex_;
#endif
};
////////////////////////////////////////////////////////////////////////////////
} // namespace NYT::NThreading
|
b4fdb1ca76bf2b5e6920caf65e634a3be419d9ea
|
73ede1a995799326a6ca715c52b3419d9feba624
|
/chp7/ex_7_2.cpp
|
d5c5c9385892cf6bd7fb55a4b60feb2fff8ca827
|
[] |
no_license
|
ljjhome/CPrimerPractice
|
613382ed1d94a6b936dd0a0b8d7fe848bf7d02c1
|
ce193c4cd06e6f4be9a70fc3821cdacb6a27ba50
|
refs/heads/master
| 2021-01-21T10:33:54.508816
| 2017-10-02T06:04:12
| 2017-10-02T06:04:12
| 83,449,075
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 948
|
cpp
|
ex_7_2.cpp
|
#include <iostream>
#include <string>
using namespace std;
struct Sale_data {
string bookNo;
unsigned units_sold = 0;
double revenue = 0.0;
Sale_data & combine(const Sale_data &sa);
string isbn(){return bookNo;}
};
Sale_data & Sale_data::combine(const Sale_data &sa){
units_sold += sa.units_sold;
revenue += sa.revenue;
return *this;
}
int main(){
Sale_data total;
if(cin>>total.bookNo>>total.units_sold>>total.revenue){
Sale_data trans;
while(cin>>trans.bookNo>>trans.units_sold>>trans.revenue){
if(total.isbn() == trans.isbn()){
total.combine(trans);
}else{
cout << total.isbn()<<" "<<total.units_sold<<" "<<total.revenue<<endl;
total = trans;
}
}
cout << total.isbn()<<" "<<total.units_sold<<" "<<total.revenue<<endl;
}else{
cout <<"no data?"<<endl;
}
return 0;
}
|
232ee6960aec6dd73c13d72efd145d86c595ee24
|
55021895dca1f57e884421ab1b9a9e398b89d1ce
|
/videowallcontroller.h
|
1edb5c63d742a683da0a6997db7496e90211c246
|
[] |
no_license
|
sensorlab030/videowall-client
|
07f7f18e516098db288afc5d7ea1260fea409e74
|
64e557422164f4e1a1fa3e18570852905923c36e
|
refs/heads/master
| 2020-03-24T00:15:34.368450
| 2019-09-17T11:26:39
| 2019-09-17T11:26:39
| 142,282,518
| 2
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,988
|
h
|
videowallcontroller.h
|
#ifndef VIDEOWALLCONTROLLER_H
#define VIDEOWALLCONTROLLER_H
#include <QObject>
#include "enums.h"
#include "animationmodel.h"
class WebSocket;
class VideoWallController : public QObject {
Q_OBJECT
Q_PROPERTY(ConnectionState::Enum connectionState READ connectionState NOTIFY connectionStateChanged)
Q_PROPERTY(int activeAnimationId READ activeAnimationId NOTIFY activeAnimationIdChanged)
Q_PROPERTY(int brightness READ brightness WRITE setBrightness NOTIFY brightnessChanged)
Q_PROPERTY(int playMode READ playMode WRITE setPlayMode NOTIFY playModeChanged)
Q_PROPERTY(QString socketError READ socketError NOTIFY socketError)
Q_PROPERTY(QString hostUrl READ hostUrl WRITE setHostUrl NOTIFY hostUrlChanged)
public:
explicit VideoWallController(QObject *parent = nullptr);
AnimationModel* getAnimationModel();
// Property getters
ConnectionState::Enum connectionState() const;
int brightness() const;
int playMode() const;
QString hostUrl() const;
QString socketError() const;
int activeAnimationId() const;
signals:
void activeAnimationIdChanged(int activeAnimationId);
void activeAnimationChanged(int id, const QString& name, const QString& description);
void brightnessChanged(int brightness);
void playModeChanged(int playMode);
void connectionStateChanged(ConnectionState::Enum state);
void socketError(const QString& errorString);
void hostUrlChanged(const QString& hostUrl);
public slots:
void openSocket();
void closeSocket();
void setActiveAnimation(int animationId);
void setBrightness(int brightness);
void setPlayMode(int playMode);
void setHostUrl(const QString& hostUrl);
private slots:
void onActiveAnimationIdChanged(int id);
void onBrightnessChanged(int brightness);
void onPlayModeChanged(int playMode);
private:
QString _hostUrl;
WebSocket* _socket;
AnimationModel* _animationModel;
Animation* _activeAnimation;
int _brightness;
int _playMode;
};
#endif // VIDEOWALLCONTROLLER_H
|
f8f588f64553089ae215eaab563877b7de63e53d
|
96f73138d7d9d1e8e7a0e5e342ccbf40e7f4e151
|
/TextGame/Locations.cpp
|
11aed78109aa734997c59ac91140615ca588e5d3
|
[] |
no_license
|
GameSquatch/TextGame
|
41bf6789668dd5036e1a8a6dcd5febb9846178bf
|
5f221349ce27f1cefb19eb71e46606f0109df0a5
|
refs/heads/master
| 2020-03-12T08:52:02.846468
| 2018-05-16T18:57:55
| 2018-05-16T18:57:55
| 130,538,138
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,960
|
cpp
|
Locations.cpp
|
//
// Locations.cpp
// TextGame
//
// Created by Ezekiel Williams on 5/23/17.
// Copyright © 2017 Ezekiel Williams. All rights reserved.
//
#include "Locations.hpp"
Locations::Locations(std::string title) {
prev = nullptr;
next = nullptr;
this->title = title;
staticOptionsStartKey = 1;
}
void Locations::addNextLocation(Locations* next) {
//if it doesn't have next assigned yet, assign it
if (this->next == nullptr) {
this->next = next;
}
}
void Locations::addPrevLocation(Locations* prev) {
//if it doesn't have previous assigned yet, assign it
if (this->prev == nullptr) {
this->prev = prev;
}
}
void Locations::addDynamicOption(Option* option) {
if (option != nullptr) {
dynamicOptions.push_back(option);
} else {
std::cout << "\nTRIED TO ADD DYNAMIC OPTION NULLPTR" << std::endl;
}
}
void Locations::addStaticOption(Option* option) {
if (option != nullptr) {
staticOptions[staticOptionsStartKey++] = option;
} else {
std::cout << "\nTRIED TO ADD STATIC OPTION NULLPTR" << std::endl;
}
}
void Locations::showOptions() const {
std::cout << "\nOptions\n";
unsigned short int i;
std::map<unsigned short int, Option*>::const_iterator staticIter;
if (staticOptions.size() > 0) {
for (staticIter = staticOptions.cbegin(); staticIter != staticOptions.cend(); staticIter++) {
Option* option = staticIter->second;
std::cout << staticIter->first << ". " << option->getOutputText() << std::endl;
//std::cout << staticIter->first << std::endl;
}
}
for (i = 0; i < dynamicOptions.size(); ++i) {
unsigned short int num = i + staticOptions.size() + 1;
std::cout << num << ". " << dynamicOptions[i]->getOutputText() << std::endl;
}
std::cout << std::endl;
}
std::string Locations::getTitle() {
return this->title;
}
Locations* Locations::getLocation(MovingDirections direction) {
//this gets the linked location of desired direction from current
if (direction == MovingDirections::Next) {
return this->next;
} else {
return this->prev;
}
}
Option* Locations::getOption(unsigned short int index) {
if (index < staticOptions.size()) {
//because we start the map at one, we need to add one back to the index for the
//static options.
return staticOptions[index + 1];
}
else if (index >= staticOptions.size() && index < staticOptions.size() + dynamicOptions.size()) {
Option* option = dynamicOptions[index];
//Since dynamic options is a vector and the elements are shown AFTER the dynamic options,
//the index passed is the static options size, so subtract the size
dynamicOptions.erase(dynamicOptions.cbegin() + (index - staticOptions.size()));
return option;
}
else {
return nullptr;
}
}
|
9a7416a3f9867461362710f781176eebfab3c751
|
5ef7f5ba06b98319a5406dfa3b25c985257713d4
|
/IGC/WrapperLLVM/include/llvmWrapper/IR/Value.h
|
1b3ec8778bc527fa52bd0a38b7a86a9a2a298816
|
[
"MIT"
] |
permissive
|
intel/intel-graphics-compiler
|
6a1ae1a84c541e967e70324492f22c941a02e38f
|
ea522543be6d042ec80e5db8e8878be31af68938
|
refs/heads/master
| 2023-09-03T20:31:55.215461
| 2023-08-29T18:31:52
| 2023-09-02T08:55:05
| 105,299,467
| 546
| 176
|
NOASSERTION
| 2023-08-23T08:57:03
| 2017-09-29T17:27:54
|
C++
|
UTF-8
|
C++
| false
| false
| 2,559
|
h
|
Value.h
|
/*========================== begin_copyright_notice ============================
Copyright (C) 2020-2023 Intel Corporation
SPDX-License-Identifier: MIT
============================= end_copyright_notice ===========================*/
#ifndef IGCLLVM_IR_VALUE_H
#define IGCLLVM_IR_VALUE_H
#include "Probe/Assertion.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Config/llvm-config.h"
#include "llvmWrapper/IR/User.h"
namespace IGCLLVM
{
#if LLVM_VERSION_MAJOR >= 10
#define stripPointerCastsNoFollowAliases() stripPointerCasts()
#endif
inline void
replaceUsesWithIf(llvm::Value *V, llvm::Value *New,
llvm::function_ref<bool(llvm::Use &U)> ShouldReplace) {
// similar to llvm::Value::replaceUsesWithIf implementation
IGC_ASSERT_MESSAGE(V, "Cannot replace uses of nullptr");
IGC_ASSERT_MESSAGE(New, "Value::replaceUsesWithIf(<null>) is invalid!");
IGC_ASSERT_MESSAGE(New->getType() == V->getType(),
"replaceUses of value with new value of different type!");
#if LLVM_VERSION_MAJOR < 10
for (auto UI = V->use_begin(), E = V->use_end(); UI != E;) {
llvm::Use &U = *UI;
++UI;
if (!ShouldReplace(U))
continue;
U.set(New);
}
#else
V->replaceUsesWithIf(New, ShouldReplace);
#endif
}
inline uint64_t getPointerDereferenceableBytes(const llvm::Value* Ptr, const llvm::DataLayout& DL, bool& CanBeNull, bool& CanBeFreed)
{
#if LLVM_VERSION_MAJOR >= 13
// LLVM 13 introduced CanBeFreed argument.
//
// > IF CanBeFreed is true, the pointer is known to be dereferenceable at
// > point of definition only. Caller must prove that allocation is not
// > deallocated between point of definition and use.
//
// Differential Revision: https://reviews.llvm.org/D98908
return Ptr->getPointerDereferenceableBytes(DL, CanBeNull, CanBeFreed);
#else
return Ptr->getPointerDereferenceableBytes(DL, CanBeNull);
#endif
}
inline llvm::User *getUniqueUndroppableUser(llvm::Value* V) {
#if LLVM_VERSION_MAJOR >= 14
return V->getUniqueUndroppableUser();
#else // For earlier versions, simply copy LLVM 14's implementation
llvm::User* Result = nullptr;
for (auto* U : V->users())
{
if (IGCLLVM::isDroppable(U))
{
if (Result && Result != U)
return nullptr;
Result = U;
}
}
return Result;
#endif
}
}
#endif
|
06ae93eb47e5ae1d8bbbe33953e28995a1a50082
|
690af9ab3de69553a531d07d6f0a16c6976b01a4
|
/mainwindow.cpp
|
2afacd973add453edc26bb5f3cb42ff42dffc3cc
|
[] |
no_license
|
aspirantip/GData
|
fd5a6e583257767805da28524186dd4ffe9f57a9
|
0d0b6988023ab36ac9ec37559394e372f362fd1f
|
refs/heads/master
| 2020-12-25T15:17:46.197243
| 2016-11-11T16:10:27
| 2016-11-11T16:10:27
| 67,041,738
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 17,626
|
cpp
|
mainwindow.cpp
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
f_loadModel(false)
{
ui->setupUi(this);
this->setWindowTitle( "Генерация данных" );
ui->sbNoiseLevel->setValue( 10 );
brHit = QBrush(Qt::green);
brNoise = QBrush(Qt::gray);
brClean = QBrush(Qt::white);
scene = new QGraphicsScene();
ui->gv_canvas->setScene( scene );
ui->gv_canvas->update();
//ui->gv_canvas->scale(1.5, 1.5);
track = new QGraphicsLineItem();
nmChambers = 2;
nmLayers = 3;
nmTubes = 10;
diamTube = 30.;
radTube = diamTube/2.;
drawSystem();
// Initialization state machine
// ====================================================
createStates();
createTransitions();
stateMachine.setInitialState(initState);
QTimer::singleShot(0, &stateMachine, SLOT(start()));
// Files and TextStream
// ====================================================
fl_train_data.setFileName("train_data.txt");
fl_test_data.setFileName("test_data.txt");
fl_train_data.open(QIODevice::WriteOnly | QIODevice::Text);
fl_test_data.open(QIODevice::WriteOnly | QIODevice::Text);
out_train_data.setDevice( &fl_train_data );
out_test_data.setDevice( &fl_test_data );
// Neural Network Model
// ====================================================
ClassModel = new NNModel(this);
createConnections();
}
MainWindow::~MainWindow()
{
delete ui;
out_train_data.flush();
out_test_data.flush();
fl_train_data.close();
fl_test_data.close();
}
void MainWindow::createConnections()
{
connect(&runningState, &QState::entered, this, &MainWindow::startGenerationDataSet);
connect(&stateMachine, &QStateMachine::finished, this, &MainWindow::closeApplication);
connect(ui->chbVisualization, &QCheckBox::stateChanged, this, &MainWindow::changeStateVisualization);
connect(ui->pbLoadModel, &QPushButton::clicked, this, &MainWindow::loadNeuralNetworkModel);
connect(ui->pbClassify, &QPushButton::clicked, this, &MainWindow::classifyImage);
connect(ui->sbThreshold, SIGNAL(valueChanged(double)), ClassModel, SLOT(setThreshold(double)));
}
void MainWindow::createStates()
{
qDebug() << "createStates()";
initState = new QState(&stateMachine);
initState->assignProperty(ui->chbVisualization, "checked", true);
initState->assignProperty(ui->pbDataGenStop, "enabled", false);
normalState = new QState(&stateMachine);
runningState.setParent(normalState);
runningState.assignProperty(ui->pbDataGenStart, "enabled", false);
runningState.assignProperty(ui->pbDataGenStop, "enabled", true);
runningState.assignProperty(this, "running", true);
stoppedState = new QState(normalState);
stoppedState->assignProperty(ui->pbDataGenStart, "enabled", true);
stoppedState->assignProperty(ui->pbDataGenStop, "enabled", false);
stoppedState->assignProperty(this, "running", false);
finalState = new QFinalState(&stateMachine);
}
void MainWindow::createTransitions()
{
qDebug() << "createTransitions()";
initState->addTransition(initState, SIGNAL(propertiesAssigned()), stoppedState);
normalState->addTransition(ui->pbExit, SIGNAL(clicked()), finalState);
runningState.addTransition(ui->pbDataGenStop, SIGNAL(clicked()), stoppedState);
runningState.addTransition(this, SIGNAL(stoppedGenerationDataSet()), stoppedState);
stoppedState->addTransition(ui->pbDataGenStart, SIGNAL(clicked()), &runningState);
}
void MainWindow::drawSystem()
{
qDebug() << "MainWindow::drawSystem()";
uint chambersPositionY = 50;
uint chambersPositionX = 50;
// рисуем систему детектора/детекторов
for (uint8_t chamber = 0; chamber < nmChambers; ++chamber)
{
QPointF st_pointSystem(chambersPositionX, chambersPositionY); // точка, относительно которой строится система
QPointF st_point; // точка, относительно которой строится элемент в системе
st_point = st_pointSystem;
//QPen pen(Qt::black, 1, Qt::DotLine);
QVector < QVector <QGraphicsEllipseItem *> > vLayers;
for (uint8_t lr = 0; lr < nmLayers; ++lr)
{
QVector <QGraphicsEllipseItem *> layer;
vLayers.append( layer );
st_point.setX( st_pointSystem.x() );
// для среднего слоя делаем смещение по координате Х на половину диаметра трубки
if ( lr == 1 )
st_point.setX( st_point.x() + radTube);
for (uint tb = 0; tb < nmTubes; ++tb)
{
vLayers[lr].append(scene->addEllipse( st_point.x(), st_point.y(), diamTube, diamTube));
//system_el[lr].append(scene->addEllipse( st_point.x(), st_point.y(), diamTube, diamTube));
st_point.setX( st_point.x() + diamTube );
}
uint y_shift = sqrt( pow(diamTube, 2) - pow(radTube, 2) );
st_point.setY( st_point.y() + y_shift);
}
vTrackSystem.insert( chamber, vLayers );
chambersPositionY += 100; //Меняем позицию для новой камеры по Y на 100
}
ui->gv_canvas->update();
}
void MainWindow::cleanSystem()
{
//qDebug() << "cleanSystem";
for (uint8_t ch = 0; ch < nmChambers; ++ch)
{
for (uint8_t lr = 0; lr < nmLayers; ++lr)
{
for (uint8_t tb = 0; tb < nmTubes; ++tb)
{
vTrackSystem[ch][lr][tb]->setBrush( brClean );
}
}
}
ui->gv_canvas->update();
}
QGraphicsLineItem* MainWindow::createTrack(const QLineF line)
{
deleteTrack();
QPen penLine;
penLine.setColor( Qt::red );
penLine.setWidth( 1 );
return scene->addLine( line, penLine);
}
inline void MainWindow::deleteTrack()
{
//qDebug() << "\tdeleteTrack()";
if (track != nullptr){
//qDebug() << "\ttrack != nullprt";
delete track;
track = nullptr;
}
}
QList<QGraphicsEllipseItem *> MainWindow::getMaskTrack(QGraphicsLineItem* track)
{
QGraphicsItem* crItem;
QGraphicsEllipseItem el;
QList<QGraphicsEllipseItem *> lstHits;
QList<QGraphicsItem *> lstItems = track->collidingItems();
foreach(crItem, lstItems)
{
if (crItem->type() == el.type()) {
QGraphicsEllipseItem *ellipse = qgraphicsitem_cast<QGraphicsEllipseItem *>(crItem);
lstHits << ellipse;
}
}
return lstHits;
}
void MainWindow::drawMaskTack(QList<QGraphicsEllipseItem *> lstHits)
{
foreach (QGraphicsEllipseItem* crEllipseItem, lstHits)
crEllipseItem->setBrush( brHit );
ui->gv_canvas->update();
}
void MainWindow::drawNoiseHits(QList<QGraphicsEllipseItem *> lstHits)
{
foreach (QGraphicsEllipseItem* crEllipseItem, lstHits)
crEllipseItem->setBrush( brNoise );
ui->gv_canvas->update();
}
void MainWindow::getInstance(const bool f_track, const uint8_t levelNoise, std::vector<float> &image)
{
/*
* 1) задать линию
* а) обе точки прямой задаются случайным образом
* б) устанавливается минимально возможный шаг для смещения линии и
* создается N (например 100) образцов с лучайным шумом
* и случайным количеством отсутствующих хитов (тут тоже надо подойти с умом)
* 2) ищем маску
* 3) конвертируем в текстовый формат или формат Mat OpenCV
* 4) сохраняем в БД
*
* добавить образцы просто с шумом и образцы где трек прошел только через часть детекторов
*/
// очищаем контейнеры
// ==============================================================
lstHitsTrack.clear();
lstHitsNoise.clear();
// type of sample
// ==============================================================
if (f_track){
const int field (diamTube*nmTubes + radTube);
float x1 = rand() % field + 50;
float x2 = rand() % field + 50;
const float y1 = 0.0;
const float y2 = 300.0;
l_track = QLineF(x1, y1, x2, y2);
track = createTrack( l_track );
lstHitsTrack = getMaskTrack( track );
deleteTrack();
}
// add noise
// ==============================================================
if (levelNoise > 0){
bool f_dbg_noise = false;
if (f_dbg_noise){
qDebug() << "noise info:";
qDebug() << "=====================================";
}
for (uint8_t ind = 0; ind < levelNoise; ++ind){
uint8_t nmChamber = rand() % nmChambers;
uint8_t nmLayer = rand() % nmLayers;
uint8_t nmTube = rand() % nmTubes;
if (f_dbg_noise){
qDebug() << "|| hit: " << ind;
qDebug() << "|| ================================";
qDebug() << "|| number of chamber: " << nmChamber;
qDebug() << "|| number of layer: " << nmLayer;
qDebug() << "|| number of tube: " << nmTube;
qDebug() << "|| ================================";
qDebug() << "||";
}
// проверяем, что данная трубка не входит в список listHitsTrack
// если все норм то добавляем данную трубку в lstHitsNoise
bool f_hitTrack = false;
foreach(QGraphicsEllipseItem* hit, lstHitsTrack){
if (vTrackSystem[nmChamber][nmLayer][nmTube] == hit){
f_hitTrack = true;
break;
}
}
if ( !f_hitTrack )
lstHitsNoise.append( vTrackSystem[nmChamber][nmLayer][nmTube] );
}
if (f_dbg_noise)
qDebug() << "=====================================\n";
}
// save image to vector
// ==============================================================
for (uint8_t ch = 0; ch < nmChambers; ++ch)
{
for (uint8_t lr = 0; lr < nmLayers; ++lr)
{
for (uint8_t tb = 0; tb < nmTubes; ++tb)
{
bool f_hit = false;
foreach (QGraphicsEllipseItem* hit_track, lstHitsTrack) {
if (vTrackSystem[ch][lr][tb] == hit_track){
f_hit = true;
break;
}
}
foreach (QGraphicsEllipseItem* hit_noise, lstHitsNoise) {
if (vTrackSystem[ch][lr][tb] == hit_noise){
f_hit = true;
break;
}
}
f_hit ? image.push_back(1) : image.push_back(0);
}
}
}
}
void MainWindow::showImage(const bool f_track)
{
cleanSystem();
if (f_track)
track = createTrack( l_track );
else
deleteTrack();
drawNoiseHits( lstHitsNoise );
drawMaskTack ( lstHitsTrack );
}
void MainWindow::saveImage(const bool f_track, const uint32_t indImage, const std::vector<float> image)
{
QString image_txt;
foreach (float value, image) {
value ? image_txt += "1 " : image_txt += "0 ";
}
// сохранение убрать и упаковать в отдельную функцию
// ===========================================================
image_txt.chop(1);
QString sample("|labels " + QString::number(f_track) + " |features " + image_txt + "\n");
qDebug() << sample << "\n";
// здесь разбиваем данные на обучающую и тестовую выборку
// ===========================================================
qDebug() << "indImage = " << indImage;
if (indImage%3 == 0)
out_test_data << sample;
else
out_train_data << sample;
}
void MainWindow::startGenerationDataSet()
{
ui->statusBar->showMessage( tr("Data generation ..."));
uint32_t numInstance = ui->sbNumberInstance->value();
const float_t one_percent = 100.0/numInstance;
bool f_track = true;
float onePercent = (nmChambers * nmLayers * nmTubes)/100.0;
float maxLevel = ui->sbNoiseLevel->value();
uint8_t topLevelNoise = onePercent * maxLevel;
uint8_t levelNoise = 0;
for (uint32_t cnt = 0; cnt < numInstance; ++cnt)
{
f_track = rand()%2;
if (topLevelNoise)
levelNoise = rand() % topLevelNoise + 1;
// debug information
// ==============================================================
qDebug() << "Image #" << cnt << "\t";
qDebug() << "f_track = " << f_track;
qDebug() << "levelNoise = " << levelNoise;
qDebug() << "topLevelNoise = " << topLevelNoise;
std::vector<float> image;
getInstance(f_track, levelNoise, image);
if (ui->chbVisualization->isChecked())
showImage(f_track);
if (ui->chbWriteImage->isChecked())
saveImage(f_track, cnt, image);
ui->prbProgress->setValue( (cnt+1)*one_percent );
}
out_test_data.flush();
out_train_data.flush();
ui->statusBar->showMessage(tr("Data generation is complete."));
emit stoppedGenerationDataSet();
}
void MainWindow::stopGenerationDataSet()
{
}
void MainWindow::changeStateVisualization()
{
qDebug() << "changeStateVisualization()";
if (ui->chbVisualization->isChecked()){
if (lstHitsTrack.size() > 0)
track = createTrack( l_track );
drawMaskTack( lstHitsTrack );
drawNoiseHits( lstHitsNoise );
}
else{
deleteTrack();
cleanSystem();
}
}
void MainWindow::loadNeuralNetworkModel()
{
qDebug() << "MainWindow::loadNeuralNetworkModel()";
// 1# Load model
// =============================================
//const std::string modelFilePath = "/home/plotnikov/cntk/Examples/Image/MNIST/Output/Models/01_OneHidden";
const std::string modelFilePath = "/home/plotnikov/cntk/Projects/Models/LR_ImageTrack.dnn";
f_loadModel = ClassModel->loadModel( modelFilePath );
if (f_loadModel){
ClassModel->setThreshold( ui->sbThreshold->value() );
ui->statusBar->showMessage(tr("Модель загружена: %1").arg(modelFilePath.data()));
}
}
void MainWindow::classifyImage()
{
qDebug() << "MainWindow::ClassifyImage()";
if ( !f_loadModel ){
QMessageBox::critical(this, tr("Critical error"),
tr("Model of neural network have not been loaded."));
return;
}
// 2# create image
// =============================================
/*
std::vector<float> image {0, 1, 1, 1, 0, 0, 0, 0, 0, 0,
1, 0, 0, 1, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 1, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 1, 0, 0, 0, 0,
0, 0, 0, 0, 0, 1, 1, 0, 0, 0,
0, 0, 0, 0, 0, 0, 1, 0, 0, 0};
*/
/*
std::vector<float> image {0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 1, 0, 0, 1, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 1, 0};
*/
std::vector<float> image;
size_t size_ivector = ClassModel->getSizeInputVector();
bool f_track = rand()%2;
float onePercent = (nmChambers * nmLayers * nmTubes)/100.0;
float maxLevel = ui->sbNoiseLevel->value();
uint8_t topLevelNoise = onePercent * maxLevel;
uint8_t levelNoise = 0;
if (topLevelNoise)
levelNoise = rand() % topLevelNoise + 1;
// debug information
// ==============================================================
qDebug() << "\nImage of system:" << "\t";
qDebug() << "f_track = " << f_track;
qDebug() << "levelNoise = " << levelNoise;
qDebug() << "topLevelNoise = " << topLevelNoise;
getInstance(f_track, levelNoise, image);
showImage(f_track);
// проверка размерностей векторов
if (size_ivector != image.size()){
QMessageBox::critical(this, tr("Критическая ошибка"),
tr("Размерность входного вектора модели нейронной сети и вектора образа не совпадает. (%1/%2)").arg(size_ivector).arg(image.size()));
return;
}
// 3# classify image
// =============================================
bool result = ClassModel->ClassificationImage( image );
if (result)
ui->statusBar->showMessage("Образ с треком.");
else
ui->statusBar->showMessage("Образ без трека.");
}
void MainWindow::closeApplication()
{
close();
}
|
c6f773b3d9b739ca7ee9d8355ad415a05f409015
|
c1eacf630af8b23852845f27d6509b4b0d5eea1b
|
/DataStruct/0004.cpp
|
788958c5250c8aa56c6b34c5f3cceaf2b3c405ad
|
[] |
no_license
|
GISjingjie/DataStruct
|
59f2408a44cdcde9b6307847267be9b7d07388f7
|
9bed92b9a19b09dd51479f73460b31a6b8dee464
|
refs/heads/master
| 2021-07-12T16:23:31.641629
| 2020-06-15T08:59:43
| 2020-06-15T08:59:43
| 146,618,934
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 199
|
cpp
|
0004.cpp
|
#include <stdio.h>
int main()
{
int i;
int a[5]={0,1,2,3,4};
int *p=a;
for(i=0;i<5;i++)
{
printf("a[%d]=%d *(a+%d)=%d p[%d]=%d *(p+%d)=%d\n",i,a[i],i,(a+i),i,&p[i],i,(p+i));
return 0;
}
}
|
40f840f28ac1e974c0ea14dd0bac5beb58c08c70
|
c6c5e2dc50aa6b1287cf243046c7e931a30121ce
|
/FLKGameEngine/src/FLKGameEngine/Core/Frameworks/Events/EventsGLFW.cpp
|
150c147fd362d6171bd28be101949e21dded257c
|
[] |
no_license
|
FreshLambdaKebab/OGL-Game-Engine
|
a613f15588ccdb0a077194e77e8a52e52743f0d3
|
15146a0abf93db14c38fdb777cb9293d2a05926b
|
refs/heads/master
| 2020-04-06T03:35:15.915083
| 2016-10-31T04:54:19
| 2016-10-31T04:54:19
| 69,552,912
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 451
|
cpp
|
EventsGLFW.cpp
|
#include "EventsGLFW.hpp"
#ifdef FLK__GLFW
#include <iostream>
namespace FLKGameEngine
{
EventsGLFW::EventsGLFW()
{
// glfwSetKeyCallback( this->window, FrameworkGLFW::KeyCallback );
// glfwSetWindowCloseCallback( this->window, cbfun );
}
void EventsGLFW::KeyCallback(GLFWwindow * window, int key, int scancode, int action, int mods)
{
// if (key == GLFW_KEY_E && action == GLFW_PRESS)
// activate_dickShip();
}
}
#endif
|
c11eba2db54de87c637702979ac8adc04cd6044c
|
2a0679562d901db59d5ac4139eee63924d04cafc
|
/GUI/CFont.cpp
|
6d4e81daa8d9c216360315bca71eda8bf206ef9a
|
[] |
no_license
|
basecq/GUIRenderAPI
|
6a7b17c5406b6c0df0f3ac9a8e00d2f1f5d4493b
|
724b30ad92b542e2c67843fd8dbbbd95eb31da8d
|
refs/heads/master
| 2020-04-09T18:37:12.386909
| 2016-04-07T05:53:19
| 2016-04-07T05:53:19
| 60,545,809
| 1
| 0
| null | 2016-06-06T17:06:16
| 2016-06-06T17:06:14
| null |
UTF-8
|
C++
| false
| false
| 3,116
|
cpp
|
CFont.cpp
|
#include "CGUI.h"
/*
CFont::CFont( CDialog *Gui, IDirect3DDevice9 * pDevice, int iHeight, SIMPLEGUI_CHAR * pszFaceName, bool bold, bool italic )
{
m_pDialog = Gui;
HRESULT hResult = D3DXCreateFont( pDevice, -MulDiv( iHeight, GetDeviceCaps( GetDC( 0 ), LOGPIXELSY ), 72 ), 0, bold?FW_BOLD:FW_NORMAL, 0, italic, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, pszFaceName, &m_pFont );
if( FAILED( hResult ) )
MessageBox( 0, /*DXGetErrorDescription9( hResult )_UI("Error"), _UI("D3DXCreateFontA failed"), 0 );
m_pFont->PreloadCharacters( 0, 255 );
InitializeCriticalSection(&cs);
}
CFont::~CFont()
{
SAFE_RELEASE( m_pFont );
DeleteCriticalSection(&cs);
}
void CFont::OnLostDevice()
{
EnterCriticalSection(&cs);
m_pFont->OnLostDevice();
LeaveCriticalSection(&cs);
}
void CFont::OnResetDevice()
{
EnterCriticalSection(&cs);
m_pFont->OnResetDevice();
LeaveCriticalSection(&cs);
}
void CFont::DrawString( int iX, int iY, DWORD dwFlags, CColor * pColor, SIMPLEGUI_STRING sString, int iWidth )
{
if(!m_pFont) return;
if(!m_pDialog) return;
if(!sString.c_str()) return;
if(!pColor) return;
EnterCriticalSection(&cs);
if( iWidth )CutString( iWidth, sString );
m_pDialog->GetSprite()->Begin( D3DXSPRITE_ALPHABLEND | D3DXSPRITE_SORT_TEXTURE );
D3DXMATRIX mat;
D3DXMatrixTranslation( &mat, static_cast<float>( iX ), static_cast<float>( iY ), 0 );
m_pDialog->GetSprite()->SetTransform( &mat );
RECT drawRect = { 0 };
DWORD dwDrawFlags = DT_NOCLIP | ( ( dwFlags & FT_CENTER ) ? DT_CENTER : 0 ) | ( ( dwFlags & FT_VCENTER ) ? DT_VCENTER : 0 );
m_pFont->DrawText( m_pDialog->GetSprite(), sString.c_str(), -1, &drawRect, dwDrawFlags, pColor->GetD3DCOLOR() );
m_pDialog->GetSprite()->End();
LeaveCriticalSection(&cs);
}
int CFont::GetStringWidth( const SIMPLEGUI_CHAR * pszString )
{
if(!m_pFont) return 0;
if(!pszString) return 0;
//uistring sString( pszString );
RECT rRect = { 0 };
/*for( int i = 0; i <= static_cast<int>( sString.size() ); i++ )
if( sString[i] == _UI(' ') )
sString[i] = _UI('.');
EnterCriticalSection(&cs);
m_pFont->DrawText ( 0, sString.c_str()pszString, -1, &rRect, DT_CALCRECT, 0 );
LeaveCriticalSection(&cs);
return rRect.right - rRect.left;
}
int CFont::GetStringHeight()
{
if(!m_pFont) return 0;
RECT rRect = { 0 };
EnterCriticalSection(&cs);
m_pFont->DrawText ( 0, _UI("Y"), -1, &rRect, DT_CALCRECT, 0 );
LeaveCriticalSection(&cs);
return rRect.bottom - rRect.top;
}
void CFont::SetColor( int iIndex, CColor cColor )
{
if( iIndex < 0 || iIndex > 8 )
return;
m_cColors[ iIndex ] = cColor;
}
CColor & CFont::GetColor( int iIndex )
{
if( iIndex < 0 || iIndex > 8 )
return m_cColors[ 0 ];
return m_cColors[ iIndex ];
}
void CFont::CutString( int iMaxWidth, SIMPLEGUI_STRING & rString )
{
int iIndex = 0, iLength = rString.length();
for( int iWidth = 0; iIndex < iLength && iWidth + 10 < iMaxWidth; )
{
SIMPLEGUI_CHAR szCurrent[ 2 ] = { rString.c_str()[ iIndex ], 0 };
iWidth += GetStringWidth( szCurrent );
iIndex++;
}
if( iIndex < iLength )
rString[ iIndex - 1 ] = _UI('\0');
}*/
|
ffe2e37bfa925d2f1da5425b83cd78b59004994f
|
28c132f1551963d59b1dc899ec9aed39f947af5d
|
/src/737_SentenceSimilarityII/Solution.cpp
|
1ef7ceddcd5f67868cbb32132c45b6219a75e2b1
|
[] |
no_license
|
ericxl/LeetCode
|
eb8f18e42848611f40064e83f49de6256be91a1c
|
ae9deb7e0e07b3e095952389d421389500676539
|
refs/heads/master
| 2021-03-30T17:12:58.243258
| 2018-04-11T18:47:18
| 2018-04-11T18:47:18
| 118,958,356
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 687
|
cpp
|
Solution.cpp
|
//
// Created by Eric Liang on 4/10/18.
//
#include <leetcode.h>
string find(map<string, string>& m, string s) {
return !m.count(s) ? m[s] = s : (m[s] == s ? s : find(m, m[s]));
}
bool areSentencesSimilarTwo(vector<string>& a, vector<string>& b, vector<pair<string, string>> pairs) {
if (a.size() != b.size()) return false;
map<string, string> m;
for (pair<string, string> p : pairs) {
string parent1 = find(m, p.first), parent2 = find(m, p.second);
if (parent1 != parent2) m[parent1] = parent2;
}
for (int i = 0; i < a.size(); i++)
if (a[i] != b[i] && find(m, a[i]) != find(m, b[i])) return false;
return true;
}
int main(){
}
|
3560824c9759c6c0a35a4a4fff84c50b70fc9826
|
3b2fa6ddc534dd793b747f1695bc0483f442ff57
|
/usaco silver practice/practice december 2020/rectangularpasture.cpp
|
035df939c9db9bfdb8a14beee2aa242d6c659eea
|
[] |
no_license
|
hannahjzhang/explorations
|
37616a30b9b4b63bd5bcc0860d55b4ca8b21938e
|
91544bfdb5743703b4aa9bfab7f8062553849e33
|
refs/heads/main
| 2023-03-16T20:28:23.637210
| 2021-03-15T04:22:27
| 2021-03-15T04:22:27
| 316,864,868
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,121
|
cpp
|
rectangularpasture.cpp
|
//
// main.cpp
// RectangularPasture
//
// Created by Hannah Zhang on 2/13/21.
//
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int N;
const int maxN = 2501;
pair<int, int> points[maxN];
int prefix[maxN][maxN];
bool compareY(pair<int, int> a, pair<int, int> b) {
return a.second < b.second;
}
void printpair(pair<int, int> arr[], int size) {
for (int i = 0; i < size; i++) {
cerr << arr[i].first << " " << arr[i].second << endl;
}
}
void printarr(int size) {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
cerr << prefix[i][j] << " ";
}
cerr << endl;
}
}
int main() {
cin >> N;
// read the points into a 2d vector
for (int i = 0; i < N; i++) {
int x; int y;
cin >> x >> y;
points[i] = make_pair(x, y);
}
// compact the array in the x
sort(points, points+N); // automatically sorts the first
for (int i = 0; i < N; i++) {
points[i].first = i;
}
// compact in the y direction
sort(points, points+N, compareY);
for (int i = 0; i < N; i++) {
points[i].second = i;
}
// printpair(points, N);
// set areas with cows to 1 on the prefix array
for (int i = 0; i < N; i++) {
int xCoord = points[i].first;
int yCoord = points[i].second;
prefix[xCoord + 1][yCoord + 1] = 1;
}
// compute prefix sum, remember to add a row & col extra
for (int i = 1; i < N+1; i++) {
for (int j = 1; j < N+1; j++) {
prefix[i][j] += prefix[i-1][j] + prefix[i][j-1] - prefix[i-1][j-1];
}
}
// printarr(N+1);
// use prefix sums and previously determined formula to compute possibilities, add it to the counter
long long possible = 0;
for (int i = 0; i < N; i++) {
for (int j = i+1; j < N; j++) {
// find the next possible rectangle combo
int minX = min(points[i].first, points[j].first);
int maxX = max(points[i].first, points[j].first);
pair<int, int> topCorner = make_pair(minX, points[i].second);
pair<int, int> bottomCorner = make_pair(maxX, points[j].second);
// check point i with every points after
// multiply leftSum and rightSum
int x1 = topCorner.first+1; int y1 = topCorner.second+1;
int x2 = bottomCorner.first+1; int y2 = bottomCorner.second+1;
//
int leftNum = prefix[x1][y2] - prefix[x1][y1-1];
int rightNum = prefix[N][y2] - prefix[N][y1-1] - prefix[x2-1][y2] + prefix[x2-1][y1-1];
int toAdd = leftNum * rightNum;
possible += toAdd;
// cout << topCorner.first << ", " << topCorner.second << endl;
// cout << bottomCorner.first << ", " << bottomCorner.second << endl;
// cout << leftNum << " " << rightNum << " " << possible << endl;
// cout << endl;
}
}
// add all the combos + the total grid + the individual grid fences
cout << possible+N+1 << endl;
}
|
f1500bd10d4f7b0f43f2b34edadf579176ca27e9
|
8911eae8c3b902b8f8128556da6e43345a011f23
|
/src/ast/fake_map.cpp
|
0d93fa6fbfeb2a6cf7c030673e46bde914cf5729
|
[
"Apache-2.0"
] |
permissive
|
delphix/bpftrace
|
85aeff7c2e5c5d2f6cde93a8c97e7ee13e6a457e
|
5c01e35c47e5a3c37e37f6fbeac91c6119c53bd9
|
refs/heads/master
| 2023-08-16T19:49:47.777296
| 2021-04-29T04:19:16
| 2021-04-29T04:19:16
| 157,599,611
| 4
| 12
|
Apache-2.0
| 2023-04-06T23:59:32
| 2018-11-14T19:25:09
|
C++
|
UTF-8
|
C++
| false
| false
| 1,364
|
cpp
|
fake_map.cpp
|
#include "fake_map.h"
namespace bpftrace {
int FakeMap::next_mapfd_ = 1;
FakeMap::FakeMap(const std::string &name,
const SizedType &type __attribute__((unused)),
const MapKey &key __attribute__((unused)),
int min __attribute__((unused)),
int max __attribute__((unused)),
int step __attribute__((unused)),
int max_entries __attribute__((unused)))
{
name_ = name;
mapfd_ = next_mapfd_++;
}
FakeMap::FakeMap(const std::string &name,
const SizedType &type __attribute__((unused)),
const MapKey &key __attribute__((unused)),
int max_entries __attribute__((unused)))
{
name_ = name;
mapfd_ = next_mapfd_++;
}
FakeMap::FakeMap(const std::string &name,
enum bpf_map_type type __attribute__((unused)),
int key_size __attribute__((unused)),
int value_size __attribute__((unused)),
int max_entries __attribute__((unused)),
int flags __attribute__((unused)))
{
name_ = name;
mapfd_ = next_mapfd_++;
}
FakeMap::FakeMap(const SizedType &type __attribute__((unused)))
{
mapfd_ = next_mapfd_++;
}
FakeMap::FakeMap(enum bpf_map_type map_type __attribute__((unused)))
{
mapfd_ = next_mapfd_++;
}
} // namespace bpftrace
|
d15d69ee91ef8515251d7ec7a003615480111d01
|
4d719c1e70f5342581a94af0ed85301f64d66cfc
|
/Deque/client.h
|
e2a5a6eef7850111dbc199d507a30ca16f4b6d7d
|
[] |
no_license
|
afrederick89/DSA
|
752f53b2f742595591c6febdbe13f2198faf2e60
|
9ef15c73b2875bee171ae83c47019dfcc17c5d7d
|
refs/heads/main
| 2023-06-25T23:04:04.293729
| 2021-07-14T04:42:44
| 2021-07-14T04:42:44
| 385,814,582
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,565
|
h
|
client.h
|
//============================================================================
// Name : Alex Frederick
// Assignment : 2 - Stacks/Queues
// Date : 2/7/2018
//============================================================================
#ifndef CLIENT_H_
#define CLIENT_H_
#include <iostream>
#include <iomanip>
#include <stack>
#include <string>
#include <vector>
#include "SingleLinkedList.h"
#include "QueueList.h"
#include "DequeList.h"
using namespace std;
//Parenthesis Algorithm hard coded with given input data
void parenthesis_Algorithm(){
string expressions[] = {"{2x-8)(12x+6)","{{8x+5)-5x[9x+3]})",
"{2x+5}(6x+4)", "(((4x+8)-x[4x+3])))","[(5x-5)-4x[6x+2]]",
"{(8x+5)-6x[9x+3]]","(12x+6)(2x-4)"};
vector<string> vExp;
linkedStackType<char> parenStack;
vExp.insert(vExp.begin(),expressions, expressions+7);
for(int i=0;i<vExp.size();++i){
for(int j=0; j<vExp[i].size();++j){
if(vExp[i][j] == '{')parenStack.push(vExp[i][j]);
if(vExp[i][j] == '[')parenStack.push(vExp[i][j]);
if(vExp[i][j] == '(')parenStack.push(vExp[i][j]);
if(vExp[i][j] == '}' && parenStack.vTop() == '{'){
parenStack.pop();
}
if(vExp[i][j] == ']' && parenStack.vTop() == '['){
parenStack.pop();
}
if(vExp[i][j] == ')' && parenStack.vTop() == '('){
parenStack.pop();
}
}
if(parenStack.isEmptyStack()){
cout << vExp[i] << " is valid!\n";
} else {
cout << vExp[i] << " is NOT valid!\n";
}
parenStack.destroyStack();
}
}
#endif /* CLIENT_H_ */
|
2971016d06a0af403aee1f18719c4aef07699460
|
72f2992a3659ff746ba5ce65362acbe85a918df9
|
/apps-src/apps/librose/gui/widgets/vertical_scrollbar.cpp
|
f2e11f33eb2e23cbafb17f77d5528bb95441fe6d
|
[
"BSD-2-Clause"
] |
permissive
|
chongtianfeiyu/Rose
|
4742f06ee9ecd55f9717ac6378084ccf8bb02a15
|
412175b57265ba2cda1e33dd2047a5a989246747
|
refs/heads/main
| 2023-05-23T14:03:08.095087
| 2021-06-19T13:23:58
| 2021-06-19T14:00:25
| 391,238,554
| 0
| 1
|
BSD-2-Clause
| 2021-07-31T02:39:25
| 2021-07-31T02:39:24
| null |
UTF-8
|
C++
| false
| false
| 3,302
|
cpp
|
vertical_scrollbar.cpp
|
/* $Id: vertical_scrollbar.cpp 52533 2012-01-07 02:35:17Z shadowmaster $ */
/*
Copyright (C) 2008 - 2012 by Mark de Wever <koraq@xs4all.nl>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY.
See the COPYING file for more details.
*/
#define GETTEXT_DOMAIN "rose-lib"
#include "gui/widgets/vertical_scrollbar.hpp"
#include "gui/auxiliary/widget_definition/vertical_scrollbar.hpp"
#include "gui/auxiliary/window_builder/vertical_scrollbar.hpp"
#include "gui/widgets/settings.hpp"
#include "gui/widgets/window.hpp"
#include "font.hpp"
using namespace std::placeholders;
namespace gui2 {
REGISTER_WIDGET(vertical_scrollbar)
tpoint tvertical_scrollbar::mini_get_best_text_size() const
{
const std::string vertical_id = settings::vertical_scrollbar_id;
if (id_ == vertical_id) {
tfloat_widget* item = get_window()->find_float_widget(id_);
return tpoint(item->scrollbar_size, 0);
}
return tpoint(0, 0);
}
int tvertical_scrollbar::minimum_positioner_length() const
{
boost::intrusive_ptr<const tvertical_scrollbar_definition::tresolution> conf =
boost::dynamic_pointer_cast<const tvertical_scrollbar_definition::tresolution>(config());
assert(conf);
return conf->minimum_positioner_length;
}
int tvertical_scrollbar::maximum_positioner_length() const
{
boost::intrusive_ptr<const tvertical_scrollbar_definition::tresolution> conf =
boost::dynamic_pointer_cast<const tvertical_scrollbar_definition::tresolution>(config());
assert(conf);
return conf->maximum_positioner_length;
}
int tvertical_scrollbar::offset_before() const
{
boost::intrusive_ptr<const tvertical_scrollbar_definition::tresolution> conf =
boost::dynamic_pointer_cast<const tvertical_scrollbar_definition::tresolution>(config());
assert(conf);
return conf->top_offset;
}
int tvertical_scrollbar::offset_after() const
{
boost::intrusive_ptr<const tvertical_scrollbar_definition::tresolution> conf =
boost::dynamic_pointer_cast<const tvertical_scrollbar_definition::tresolution>(config());
assert(conf);
return conf->bottom_offset;
}
bool tvertical_scrollbar::on_positioner(const tpoint& coordinate) const
{
// Note we assume the positioner is over the entire width of the widget.
return coordinate.y >= static_cast<int>(get_positioner_offset())
&& coordinate.y < static_cast<int>(get_positioner_offset() + get_positioner_length())
&& coordinate.x > 0
&& coordinate.x < static_cast<int>(get_width());
}
int tvertical_scrollbar::on_bar(const tpoint& coordinate) const
{
// Not on the widget, leave.
if (coordinate.x > get_width() || coordinate.y > get_height()) {
return 0;
}
// we also assume the bar is over the entire width of the widget.
if (coordinate.y < get_positioner_offset()) {
return -1;
} else if (coordinate.y > get_positioner_offset() + get_positioner_length()) {
return 1;
} else {
return 0;
}
}
const std::string& tvertical_scrollbar::get_control_type() const
{
static const std::string type = "vertical_scrollbar";
return type;
}
} // namespace gui2
|
9950a80654b89df6a9bc6fbe00c09ee6460a7dcd
|
b4b4e324cbc6159a02597aa66f52cb8e1bc43bc1
|
/C++ code/Uva Online Judge/Q10559(2).cpp
|
ef50b0f7bf9aabe1f25f9ffdc179695dff7521f3
|
[] |
no_license
|
fsps60312/old-C-code
|
5d0ffa0796dde5ab04c839e1dc786267b67de902
|
b4be562c873afe9eacb45ab14f61c15b7115fc07
|
refs/heads/master
| 2022-11-30T10:55:25.587197
| 2017-06-03T16:23:03
| 2017-06-03T16:23:03
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,907
|
cpp
|
Q10559(2).cpp
|
#include<cstdio>
#include<cstdlib>
#include<map>
using namespace std;
struct pairtype
{
int color;
int sum;
};
pairtype S[200];
int Ssum,T,n;
map<int,int> colorcollect;
int tmp[200][200][200];//from, to, last clicked length(color is S[j].color)
int Max[200][200];
int main()
{
freopen("in.txt","r",stdin);
scanf("%d",&T);
while(T--)
{
colorcollect.clear();
Ssum=0;
scanf("%d",&n);
for(int i=0,j;i<n;i++)
{
scanf("%d",&j);
if(colorcollect.find(j)==colorcollect.end()) colorcollect[j]=colorcollect.size()-1;
j=colorcollect[j];
if(i==0)
{
S[0].color=j;
S[0].sum=1;
}
else
{
if(j!=S[Ssum].color)
{
Ssum++;
S[Ssum].color=j;
S[Ssum].sum=1;
}
else
{
S[Ssum].sum++;
}
}
}
for(int i=0;i<=Ssum;i++)
{
for(int j=0;j<=Ssum;j++)
{
for(int k=0;k<=n;k++)
{
tmp[i][j][k]=0;
}
Max[i][j]=0;
}
}
for(int i=0;i<=Ssum;i++)
{
tmp[i][i][S[i].sum]=Max[i][i]=S[i].sum*S[i].sum;
}
for(int i=1;i<=Ssum;i++)
{
for(int j=0;j+i<=Ssum;j++)
{
for(int k=j+i-1;k>=j;k--)
{
if(S[k].color==S[j+i].color)
{
for(int l=1;l<=n;l++)
{
if(tmp[j][k][l]>0)
{
int m=l+S[j+i].sum;
int o=tmp[j][k][l]-l*l+m*m;
if(k+1<=j+i-1) o+=Max[k+1][j+i-1];
if(o>tmp[j][j+i][m])
{
tmp[j][j+i][m]=o;
if(tmp[j][j+i][m]>Max[j][j+i]) Max[j][j+i]=tmp[j][j+i][m];
}
}
}
}
else
{
for(int l=1;l<=n;l++)
{
if(tmp[j][k][l]>0)
{
if(tmp[j][k][l]+S[j+i].sum*S[j+i].sum>tmp[j][j+i][S[j+i].sum])
{
tmp[j][j+i][S[j+i].sum]=tmp[j][k][l]+S[j+i].sum*S[j+i].sum;
if(tmp[j][j+i][S[j+i].sum]>Max[j][j+i]) Max[j][j+i]=tmp[j][j+i][S[j+i].sum];
}
}
}
}
}
}
}
printf("%d\n",Max[0][Ssum]);
}
return 0;
}
|
bed16064e8105131e46ded7a4e6741ac521bbbb2
|
ce434fc49f92c3b0bfefbf59e18adc7ed5ac59cf
|
/OpenLM35/OpenLM35_Example.ino
|
aa95d3ecfc28988e84d40394f94505e0a2604a5d
|
[] |
no_license
|
tantt2810/OpenSensor
|
19959d8f0892105962d7257f0386d91370f8fc3e
|
9648ec98c03e7e341f62f30434b11fa6b3df5942
|
refs/heads/master
| 2021-01-21T13:14:14.935657
| 2016-05-26T07:40:03
| 2016-05-26T07:40:03
| 52,935,719
| 5
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,202
|
ino
|
OpenLM35_Example.ino
|
/****************************************************************************************************
* The OpenSensor Arduino Library is an open sources for every body who work with sensor and arduino.
*
* @Created by Tran Tri Tan <tantt2810@gmail.com>.
* @Copyright (C) 2016.
*
* Full sources: https://github.com/tantt2810/Opensensor
*
***********************************************
* DESCRIPTION
*
* This is example for temperature sensor LM35. It measures the temperature(in Celsius or Fahrenheit).
*
* See it as the sample and know how to use OpenSensor. Then you can modify it to your code.
******************************************************************************************************/
#include <OpenLM35.h>
#define analogpin A0
OpenLM35 lm35(analogpin); //OpenLM35(analogpin): declare analog pin of sensor.
void setup() {
Serial.begin(9600); //set up UART, baudrate = 9600bps.
lm35.setup(5, 10); //begin(Vcc, resolution): declare Vcc and resolution value of sensor.
//lm35.setup(); //or this function if you want to use default value: default Vcc=5V, default resolution=10bit.
// Getting info about sensor.
Serial.println("*********************< LM35 >************************");
Serial.print("Name: ");
Serial.println(lm35.getSensor().name);
Serial.print("Version: ");
Serial.println(lm35.getSensor().version);
Serial.print("Type: ");
Serial.println(lm35.getSensor().type);
Serial.print("Min value: ");
Serial.println(lm35.getSensor().min_value);
Serial.print("Max value: ");
Serial.println(lm35.getSensor().max_value);
Serial.print("Vcc: ");
Serial.print(lm35.getSensor().Vcc);
Serial.println("V");
Serial.print("Resolution: ");
Serial.print(lm35.getSensor().resolution);
Serial.println("bit");
Serial.println("******************************************************");
}
void loop() {
Serial.print("Temperature: ");
Serial.print("Celsius: ");
Serial.print(lm35.readCelsius()); //call function readCelsius().
Serial.print(" *C ");
Serial.print("Fahrenheit: ");
Serial.print(lm35.readFahrenheit()); //call function readCelsius().
Serial.println(" *F");
delay(1000);
}
|
f272a3999833b41d56ecab3418a73e322050c1fe
|
32809f6f425bf5665fc19de2bc929bacc3eeb469
|
/src/1095-Find-in-Mountain-Array/1095.cpp
|
f623cadd8e487a182f95e0b58ab99ff73a334e78
|
[] |
no_license
|
luliyucoordinate/Leetcode
|
9f6bf01f79aa680e2dff11e73e4d10993467f113
|
bcc04d49969654cb44f79218a7ef2fd5c1e5449a
|
refs/heads/master
| 2023-05-25T04:58:45.046772
| 2023-05-24T11:57:20
| 2023-05-24T11:57:20
| 132,753,892
| 1,575
| 569
| null | 2023-05-24T11:57:22
| 2018-05-09T12:30:59
|
C++
|
UTF-8
|
C++
| false
| false
| 737
|
cpp
|
1095.cpp
|
class Solution
{
public:
int findInMountainArray(int target, MountainArray &m)
{
int p = 0, r = m.length()-1;
while (p < r)
{
int mid = (p + r) >> 1;
if (m.get(mid) > m.get(mid + 1)) r = mid;
else p = mid + 1;
}
int i = bs(m, target, 0, p, true);
return i != -1 ? i : bs(m, target, p+1, m.length()-1, false);
}
int bs(MountainArray &m, int t, int l, int r, bool asc)
{
while (l < r)
{
int mid = (l + r) >> 1;
if ((asc and m.get(mid) >= t) or (!asc and m.get(mid) <= t)) r = mid;
else l = mid + 1;
}
if (m.get(l) == t) return l;
return -1;
}
};
|
298908af71e58e076e46c1909e547b2abeeae280
|
dbcfe515a5adce8a5ae290e03cae6244ce1c592b
|
/src/test.cc
|
2c391bdadb8fe6f34caaedb4e0dd8ea5bd4aee2d
|
[] |
no_license
|
xiaoDongSky/momenta-lane-detect
|
ebe00fc3500a6ccfc8d6857c2565408c4a7a38ba
|
d7e5dacaa7487d12f8ab763605e80ab1563236fc
|
refs/heads/master
| 2021-04-05T23:40:52.294758
| 2017-05-07T01:16:13
| 2017-05-07T01:16:13
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,202
|
cc
|
test.cc
|
#include <cv.h>
#include <cvaux.h>
#include <highgui.h>
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <cmath>
using namespace std;
using namespace cv;
const double PI = 3.14159;
vector< vector< vector<Point> > > lanes;
void read_image_lines() {
string image_dir = "../caltech-lanes/test1/";
string result_file = "list.txt_results.txt";
ifstream in(image_dir + result_file);
if (! in.is_open()) {
cout << "open result file fail!" << endl;
exit(1);
}
vector< vector<Point> > line_vec;
char buffer[256];
string s;
while (! in.eof()) {
in.getline(buffer, 100);
s = string(buffer);
if (s.size() == 0) {
continue;
}
int line_num = s[19] - '0';
// printf("line num: %d\n", line_num);
while (line_num-- && ! in.eof()) {
in.getline(buffer, 100);
s = string(buffer);
int points_num = s[14] - '0';
vector<Point> point_vec;
while (points_num-- && ! in.eof()) {
in.getline(buffer, 100);
s = string(buffer);
stringstream ss;
ss << s;
float x, y;
ss >> x;
char c;
ss >> c;
ss >> y;
Point p(x, y);
point_vec.push_back(p);
}
line_vec.push_back(point_vec);
}
lanes.push_back(line_vec);
// cout << "\n\n" << endl;
line_vec.clear();
}
// cout << lanes.size() << endl;
for (auto image_lines: lanes) {
// cout << "lines: " << image_lines.size() << endl;
for (auto image_line_points: image_lines) {
// cout << "points: " << image_line_points.size() << endl;
for (auto line_point: image_line_points) {
// cout << line_point.x <<"\t" << line_point.y << endl;
}
}
// cout << "\n" << endl;
}
}
int main()
{
read_image_lines();
char buffer[256];
// ifstream in("../caltech-lanes/test1/label.txt");
ifstream in("../caltech-lanes/image_with_lanes/label.txt");
if (!in.is_open()) {
cout << "open file fail!" << endl;
return 1;
}
// string image_dir = "../caltech-lanes/test1/";
string image_dir = "../caltech-lanes/image_with_lanes/";
vector<string> str_vec;
int image_index = 0;
while (! in.eof()) {
str_vec.clear();
while (! in.eof()) {
in.getline(buffer, 100);
string l(buffer);
// cout << l.size() << endl;
if (l.size() == 1 || l.size() == 0) {
break;
}
// cout << l << endl;
str_vec.push_back(l);
}
// cout << str_vec[0].size() << endl;
string image_name = str_vec[0].substr(0, 36);
Mat image = imread(image_dir + image_name);
Mat I;
Canny(image, I, 125, 350);
cvtColor(image, I, CV_BGR2GRAY);
Mat contours;
Canny(I, contours, 640, 350);
vector<Vec4i> lines;
// cout << "\n\n" << endl;
for (int i = 1; i < str_vec.size(); i++) {
stringstream in_s;
// cout << str_vec[i] << endl;
in_s << str_vec[i];
vector<int> ax_vec;
int temp;
while (! in_s.eof()) {
in_s >> temp;
ax_vec.push_back(temp);
}
vector<int> left_up_and_right_down(4, 0);
for (int j = 0; j < 4; j++) {
left_up_and_right_down[j] = ax_vec[j];
}
Vec4i up_edge;
up_edge[0] = left_up_and_right_down[0];
up_edge[1] = left_up_and_right_down[1];
up_edge[2] = left_up_and_right_down[2];
up_edge[3] = left_up_and_right_down[1];
Vec4i down_edge;
down_edge[0] = left_up_and_right_down[0];
down_edge[1] = left_up_and_right_down[3];
down_edge[2] = left_up_and_right_down[2];
down_edge[3] = left_up_and_right_down[3];
Vec4i left_edge;
left_edge[0] = left_up_and_right_down[0];
left_edge[1] = left_up_and_right_down[1];
left_edge[2] = left_up_and_right_down[0];
left_edge[3] = left_up_and_right_down[3];
Vec4i right_edge;
right_edge[0] = left_up_and_right_down[2];
right_edge[1] = left_up_and_right_down[1];
right_edge[2] = left_up_and_right_down[2];
right_edge[3] = left_up_and_right_down[3];
lines.push_back(left_edge);
lines.push_back(right_edge);
lines.push_back(up_edge);
lines.push_back(down_edge);
if (lanes[image_index].size() != 0) {
// Point left_up(left_up_and_right_down[0], left_up_and_right_down[1]);
Point right_down(left_up_and_right_down[2], left_up_and_right_down[3]);
Point left_down(left_up_and_right_down[0], left_up_and_right_down[3]);
// Point right_up(left_up_and_right_down[2], left_up_and_right_down[1]);
// vector<Point> candidate_points = {left_up, left_down, right_up, right_down};
vector<Point> candidate_points = {left_down, right_down};
for (auto candidate_point : candidate_points) {
for (auto line_points : lanes[image_index]) {
double a = line_points[3].y - line_points[0].y;
double b = line_points[0].x - line_points[3].x;
double c = line_points[3].x * line_points[0].y -
line_points[0].x * line_points[3].y;
if (candidate_point == left_down) {
Vec4i add_edge;
add_edge[0] = line_points[3].x;
add_edge[1] = line_points[3].y;
double x_lowest = - (360 * b + c) / a;
if (x_lowest < 0) {
add_edge[2] = 0;
add_edge[3] = -c / b;
} else if (x_lowest > 640) {
add_edge[2] = 640;
add_edge[3] = -(640 * a + c) / b;
} else {
add_edge[2] = x_lowest;
add_edge[3] = 360;
}
cout << add_edge[0] << endl;
lines.push_back(add_edge);
}
if (line_points[0].y > candidate_point.y) {
double d = fabs( (a * candidate_point.x + b *
candidate_point.y + c)
/ sqrt(a * a + b * b) );
double p2p_dis =
sqrt((line_points[0].x - candidate_point.x) *
(line_points[0].x - candidate_point.x) +
(line_points[0].y - candidate_point.y) *
(line_points[0].y - candidate_point.y));
if (asin(d / p2p_dis) < PI / 9) {
cout << "hehe" << endl;
Vec4i add_edge;
add_edge[0] = line_points[0].x;
add_edge[1] = line_points[0].y;
add_edge[2] = candidate_point.x;
add_edge[3] = candidate_point.y;
lines.push_back(add_edge);
cout << add_edge[0] << endl;
}
}
}
}
}
}
threshold(contours, contours, 128, 255, THRESH_BINARY);
cout << lines.size() << endl;
auto it = lines.begin();
while(it != lines.end())
{
Point pt1((*it)[0], (*it)[1]);
Point pt2((*it)[2], (*it)[3]);
line(image, pt1, pt2, Scalar(0,255,0), 2); // 线条宽度设置为2
++it;
}
image_index++;
namedWindow("Lines");
imshow("Lines", image);
cout << "image_index: " << image_index << endl;
waitKey();
}
return 0;
}
|
d4ee535cddc7001e98d652f2cf01d3c760673773
|
b3fb682a5a421b7f89dc678bb02d0f7a8df0c1ef
|
/libgraphics/src/main/cpp/clear_state_info.cpp
|
3a1916850c715986ec236333072a823cebeb5c9c
|
[] |
no_license
|
zmichaels11/asmjs-test
|
b84bf71905e444ebdaccba39e4f9965a0bd9019e
|
c21b4b59f70d13bb23c40f97f77f10c74d693d71
|
refs/heads/master
| 2020-06-14T18:33:03.622291
| 2018-02-15T00:36:21
| 2018-02-15T00:36:21
| 195,088,249
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 332
|
cpp
|
clear_state_info.cpp
|
#include "graphics/hstate/clear_state_info.hpp"
#include "graphics/hbitfield/clear_buffer.hpp"
namespace graphics {
clear_state_info clear_state_info::defaults() noexcept {
return {
static_cast<clear_buffer> (0),
{0.0F, 0.0F, 0.0F, 0.0F},
1.0F,
0
};
}
}
|
8ebd96bc79fff9ea7e6054cf70e512182543bb2c
|
4eac9e5e93d34429104d273450156e78d65b887c
|
/mysql_learning/connmysql-nonpre.cpp
|
c39062030aa712a1d896f965ef66e725e950d526
|
[] |
no_license
|
yushiyaogg/backup
|
6e878793d86b89ed874222b6fd48552d7cded123
|
8eb6bab42027236d0d0934e45b51908abefd8dc8
|
refs/heads/master
| 2021-01-10T21:10:51.194152
| 2014-08-02T01:43:10
| 2014-08-02T01:43:10
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,302
|
cpp
|
connmysql-nonpre.cpp
|
/*
* =====================================================================================
*
* Filename: connmysql-nonpre.cpp
*
* Description: Show use Connector/C to communicate with mysql
*
* Version: 1.0
* Created: 01/10/2013 03:12:15 AM
* Revision: none
* Compiler: gcc
*
* Author: (wuyu),wuyu2012@gmail.com
* Company: NDSL UESTC
*
* =====================================================================================
*/
#include "mysql/mysql.h"
#include <stdio.h>
int main(void)
{
MYSQL mysql;
MYSQL_ROW row;
MYSQL_RES *result;
MYSQL_FIELD *field;
unsigned int num_fields;
unsigned int i;
const char *host_info=0;
mysql_init(&mysql);
host_info=mysql_get_host_info(&mysql);
printf("host info:%s\n",host_info);
if (!mysql_real_connect(&mysql,"localhost","expriment","uestc8020","exp",0,NULL,0))
{
fprintf(stderr, "Failed to connect to database: Error: %s\n",
mysql_error(&mysql));
}
else
{
if(mysql_query(&mysql, "select stu_name from student_list where stu_id='1234'"))
fprintf(stderr,"MYSQL QUERY failed:Error:%s\n",mysql_error(&mysql));
else
{
result = mysql_use_result(&mysql);
if(result)
{
num_fields = mysql_num_fields(result);
while((field=mysql_fetch_field(result)))
printf("field name:%s\n",field->name);
while ((row = mysql_fetch_row(result)))
{
unsigned long *lengths;
lengths = mysql_fetch_lengths(result);
for(i = 0; i < num_fields; i++)
{
printf("[%.*s] \t",(int)lengths[i],row[i] ? row[i] : "NULL");
}
printf("\n");
}
mysql_free_result(result);
}
else
{
if(mysql_errno(&mysql))
fprintf(stderr,"Error happened:%s\n",mysql_error(&mysql));
else if(0==mysql_field_count(&mysql))
printf("Query doesn't return data\n");
}
}
}
mysql_close(&mysql);
return 0;
}
|
62b47af9a5982a44956a8c211368b209ad443c18
|
ccf3d4ddf8355b4a8e20ef9ade6af7e22d6b6159
|
/groups/csa/csabbg/csabbg_allocatorforward.cpp
|
19640dd06eb6d1c4bfde625deed89828800edff2
|
[
"MIT"
] |
permissive
|
hmaldona/bde_verify
|
809442ecf0c36fd57d53f0251368baa5ae17247f
|
6fb86bb21c387e829f77bbc9d25c86530c4d68d9
|
refs/heads/debian
| 2020-05-02T08:49:06.504911
| 2016-04-15T16:08:28
| 2016-04-15T16:08:28
| 38,367,232
| 0
| 3
| null | 2015-09-16T12:36:28
| 2015-07-01T11:22:29
|
C++
|
UTF-8
|
C++
| false
| false
| 44,795
|
cpp
|
csabbg_allocatorforward.cpp
|
// csabbg_allocatorforward.cpp -*-C++-*-
#include <clang/AST/ASTContext.h>
#include <clang/AST/Decl.h>
#include <clang/AST/DeclBase.h>
#include <clang/AST/DeclCXX.h>
#include <clang/AST/DeclTemplate.h>
#include <clang/AST/Expr.h>
#include <clang/AST/ExprCXX.h>
#include <clang/AST/Stmt.h>
#include <clang/AST/TemplateBase.h>
#include <clang/AST/TemplateName.h>
#include <clang/AST/Type.h>
#include <clang/ASTMatchers/ASTMatchFinder.h>
#include <clang/ASTMatchers/ASTMatchers.h>
#include <clang/ASTMatchers/ASTMatchersInternal.h>
#include <clang/ASTMatchers/ASTMatchersMacros.h>
#include <clang/Basic/SourceLocation.h>
#include <clang/Basic/Specifiers.h>
#include <csabase_analyser.h>
#include <csabase_debug.h>
#include <csabase_diagnostic_builder.h>
#include <csabase_registercheck.h>
#include <csabase_report.h>
#include <csabase_util.h>
#include <llvm/ADT/APSInt.h>
#include <llvm/ADT/Optional.h>
#include <llvm/ADT/VariadicFunction.h>
#include <llvm/Support/Casting.h>
#include <utils/event.hpp>
#include <utils/function.hpp>
#include <map>
#include <set>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
namespace csabase { class PPObserver; }
namespace csabase { class Visitor; }
using namespace clang;
using namespace clang::ast_matchers;
using namespace clang::ast_matchers::internal;
using namespace csabase;
// -----------------------------------------------------------------------------
static std::string const check_name("allocator-forward");
// -----------------------------------------------------------------------------
namespace {
bool is_allocator(QualType type, ASTContext& c, bool includeBases = true)
// Return 'true' iff the specified 'type' is pointer or reference to
// an allocator.
{
static const std::string a1 = "BloombergLP::bslma::Allocator";
static const std::string a2 = "bsl::allocator";
type = type.getDesugaredType(c);
if (type->isPointerType()) {
type = type->getPointeeType().getDesugaredType(c);
} else if (type->isReferenceType()) {
type = type->getPointeeType().getDesugaredType(c);
if (type->isPointerType()) {
type = type->getPointeeType().getDesugaredType(c);
}
}
bool is = false;
if (auto r = type->getAsCXXRecordDecl()) {
auto all_true = [](const CXXRecordDecl *decl, void *) { return true; };
auto not_alloc = [](const CXXRecordDecl *decl, void *) {
std::string t = decl->getQualifiedNameAsString();
return t != a1 && t != a2;
};
auto rd = r->getDefinition();
is = !not_alloc(r, 0) ||
(includeBases &&
rd &&
rd->forallBases(all_true, 0) &&
!rd->forallBases(not_alloc, 0));
}
return is;
}
bool is_allocator(const Type& type, ASTContext& c, bool includeBases = true)
{
return is_allocator(QualType(&type, 0), c, includeBases);
}
}
namespace clang {
namespace ast_matchers {
AST_MATCHER_P(TemplateArgument, equalsIntegral, unsigned, N) {
return Node.getKind() == TemplateArgument::Integral &&
Node.getAsIntegral() == N;
}
AST_MATCHER_P(FunctionDecl, hasLastParameter,
internal::Matcher<ParmVarDecl>, InnerMatcher) {
return Node.getNumParams() > 0 &&
InnerMatcher.matches(
*Node.getParamDecl(Node.getNumParams() - 1), Finder, Builder);
}
AST_MATCHER(Type, isAllocator) {
return is_allocator(Node, Finder->getASTContext());
}
}
}
namespace
{
struct data
// Data stored for this set of checks.
{
typedef std::vector<const CXXConstructorDecl*> Ctors;
Ctors ctors_;
// The set of constructor declarations seen.
typedef std::set<const NamedDecl*> DeclsWithAllocatorTrait;
DeclsWithAllocatorTrait decls_with_true_allocator_trait_;
// The set of declarations having a true allocator trait.
DeclsWithAllocatorTrait decls_with_false_allocator_trait_;
// The set of declarations having a false allocator trait.
DeclsWithAllocatorTrait decls_with_dependent_allocator_trait_;
// The set of declarations having a dependent allocator trait.
typedef std::set<const CXXConstructExpr*> Cexprs;
Cexprs cexprs_;
// The set of constructor expressions seen.
typedef std::map<const Type*, bool> TypeTakesAllocator;
TypeTakesAllocator type_takes_allocator_;
// A map of whether a type has a constructor with an allocator
// parameter.
typedef std::map<const CXXConstructorDecl*, bool> CtorTakesAllocator;
CtorTakesAllocator ctor_takes_allocator_;
// A map of whether a constructor has an allocator parameter.
typedef std::set<const ReturnStmt*> Returns;
Returns returns_;
typedef std::set<const VarDecl*> Globals;
Globals globals_;
};
struct report : Report<data>
// This class two static analysis checkers, one to detect object
// constructors with allocator parameters which do not pass an allocator to
// the constructors of their base classes and members with allocator
// parameters, and a second which detects constructor expressions with an
// explicit allocator argument in which that argument does not initialize
// an allocator parameter. It also contains a variety of utility methods
// used in implementing those checks.
{
INHERIT_REPORT_CTOR(report, Report, data);
const CXXRecordDecl *get_record_decl(QualType type);
// Return the record declaration for the specified 'type' and a null
// pointer if it does not have one.
bool is_allocator(QualType type, bool includeBases = true);
// Return 'true' iff the specified 'type' is pointer or reference to
// 'bslma::Allocator'. If the optionally specified 'includeBases' is
// false, do not consider base classes of 'type'.
bool last_arg_is_explicit_allocator(const CXXConstructExpr* call);
// Return 'true' iff the specified 'call' to a constructor has
// arguments and the last argument is an explicitly passed allocator.
bool takes_allocator(QualType type);
// Return 'true' iff the 'specified' type has a constructor which has a
// final allocator paramater.
bool takes_allocator(CXXConstructorDecl const* constructor);
// Return 'true' iff the specified 'constructor' has a final allocator
// pointer paramater.
void match_nested_allocator_trait(const BoundNodes& nodes);
// Callback for classes with nested allocator traits.
void match_class_using_allocator(const BoundNodes& nodes);
// Callback for classes having constructors with allocator parameters.
void match_allocator_trait(data::DeclsWithAllocatorTrait* set,
const BoundNodes& nodes);
// Method to insert discovered classes with allocator traits contained
// within the specifed 'nodes' into the specified 'set'.
void match_negative_allocator_trait(const BoundNodes& nodes);
// Callback for discovered classes with negative allocator traits
// contained within the specifed 'nodes'.
void match_positive_allocator_trait(const BoundNodes& nodes);
// Callback for discovered classes with positive allocator traits
// contained within the specifed 'nodes'.
void match_dependent_allocator_trait(const BoundNodes& nodes);
// Callback for discovered classes with dependent allocator traits
// contained within the specifed 'nodes'.
void match_ctor_expr(const BoundNodes& nodes);
// Callback for constructor expressions.
void match_return_stmt(const BoundNodes& nodes);
// Callback for return statements.
void match_var_decl(const BoundNodes& nodes);
// Callback for variable declarations.
void match_ctor_decl(const BoundNodes& nodes);
// Callback for constructor declarations.
bool hasRVCognate(const FunctionDecl *func);
// Return 'true' iff the specified 'func' (which returns 'void' and
// returns a value through a pointer first parameter) has a cognate
// function that returns by value.
void match_should_return_by_value(const BoundNodes& nodes);
// Callback for functions which could return by value instead of
// through a pointer.
void operator()();
// Invoke the checking procedures.
void check_globals_use_allocator(data::Globals::const_iterator begin,
data::Globals::const_iterator end);
bool has_public_copy_constructor(const CXXRecordDecl *decl);
// Whether the class has a publicly accessible copy constructor.
void check_not_forwarded(data::Ctors::const_iterator begin,
data::Ctors::const_iterator end);
// Invoke the forwarding check on the items in the range from the
// specified 'begin' up to but not including the specified 'end'.
void check_not_forwarded(const CXXConstructorDecl *decl);
// If the specified constructor 'decl' takes an allocator parameter,
// check whether it passes the parameter to its subobjects.
void check_not_forwarded(CXXConstructorDecl::init_const_iterator begin,
CXXConstructorDecl::init_const_iterator end,
const ParmVarDecl* palloc);
// Check if the items in the sequence from the specified 'begin' up to
// but not including the specified 'end' are passed the specified
// 'palloc' allocator parameter.
void check_not_forwarded(const CXXCtorInitializer* init,
const ParmVarDecl* palloc);
// Check if the specified 'init' initializer is passed the specified
// 'palloc' allocator parameter, if the initialized object is capable
// of being so initialized.
std::string parm_name(const ParmVarDecl* parm, int position);
// Construct a descriptive name string for the specified 'parm'
// parameter, incorporating the specified 'position'.
template <typename Iter>
void check_wrong_parm(Iter begin, Iter end);
// Check if the items in the sequence from the specified 'begin' up to
// but not including the specified 'end' initialize a non-allocator
// parameter from an explicit allocator argument.
void check_wrong_parm(const CXXConstructExpr *expr);
// Check whether the specified 'expr' constructor expression contains a
// final explicit allocator pointer argument used to initialize a non-
// allocator parameter. The canonical case is
//..
// struct X {
// bdef_Function<void(*)()> d_f;
// X(const bdef_Function<void(*)()>& f, bslma::Allocator *a = 0);
// };
// X x(bslma::Default::defaultAllocator());
//..
// typically occurring when a bdef_Function member is added to a class
// which did not have one.
template <typename Iter>
void check_alloc_returns(Iter begin, Iter end);
// Check that the return statements in the specified half-open range
// '[ begin .. end )' do not return items that take allocators.
void check_alloc_return(const ReturnStmt* stmt);
// Check that the specified return 'stmt' does not return an item that
// takes allocators.
};
const CXXRecordDecl *report::get_record_decl(QualType type)
{
const TemplateSpecializationType *tst =
llvm::dyn_cast<TemplateSpecializationType>(type.getTypePtr());
if (tst) {
type = tst->desugar();
}
const SubstTemplateTypeParmType *sttpt =
llvm::dyn_cast<SubstTemplateTypeParmType>(type.getTypePtr());
if (sttpt) {
type = sttpt->desugar();
}
const CXXRecordDecl *rdecl = type->getAsCXXRecordDecl();
if (!rdecl) {
rdecl = type->getPointeeCXXRecordDecl();
}
if (rdecl) {
rdecl = rdecl->getCanonicalDecl();
}
return rdecl;
}
bool report::is_allocator(QualType type, bool includeBases)
{
return ::is_allocator(type, *a.context(), includeBases);
}
bool report::last_arg_is_explicit_allocator(const CXXConstructExpr* call)
{
unsigned n = call ? call->getNumArgs() : 0;
const Expr *last = n ? call->getArg(n - 1) : 0;
return last && !last->isDefaultArgument() && is_allocator(last->getType());
}
bool report::takes_allocator(QualType type)
{
while (type->isArrayType()) {
type = QualType(type->getArrayElementTypeNoTypeQual(), 0);
}
return d.type_takes_allocator_
[type.getTypePtr()->getCanonicalTypeInternal().getTypePtr()];
}
bool report::takes_allocator(CXXConstructorDecl const* constructor)
{
data::CtorTakesAllocator::iterator itr =
d.ctor_takes_allocator_.find(constructor);
if (itr != d.ctor_takes_allocator_.end()) {
return itr->second;
}
d.ctor_takes_allocator_[constructor] = false;
unsigned n = constructor->getNumParams();
if (n == 0) {
return false; // RETURN
}
QualType type = constructor->getParamDecl(n - 1)->getType();
#if 1
return d.ctor_takes_allocator_[constructor] = is_allocator(type);
#else
if (is_allocator(type)) {
return d.ctor_takes_allocator_[constructor] = true; // RETURN
}
const ReferenceType *ref =
llvm::dyn_cast<ReferenceType>(type.getTypePtr());
if (!ref) {
return false; // RETURN
}
type = ref->getPointeeType();
if (!type.isConstQualified()) {
return false; // RETURN
}
return d.ctor_takes_allocator_[constructor] = takes_allocator(type);
#endif
}
static internal::DynTypedMatcher nested_allocator_trait_matcher()
// Return an AST matcher which looks for nested traits. Expanded from
// macros, allocator traits look like:
//..
// class MyClass { operator bslalg::TypeTraitUsesBslmaAllocator::
// NestedTraitDeclaration<MyClass>() const ... };
//..
// or
//..
// class MyClass { operator BloombergLP::bslmf::NestedTraitDeclaration<
// MyClass,
// bslma::UsesBslmaAllocator,
// true>() const ... };
//..
// In the second case above, the final boolean parameter may also be false
// or missing. The details of the classes involved are too hairy to tease
// out in the AST matcher; instead the matcher looks for a superset of
// methods and the callback looks for further structure.
{
return decl(forEachDescendant(
methodDecl(
matchesName("::operator NestedTraitDeclaration($|<)"),
returns(qualType().bind("type")),
ofClass(recordDecl().bind("class"))
).bind("trait")
));
}
void report::match_nested_allocator_trait(const BoundNodes& nodes)
{
CXXRecordDecl const* decl = nodes.getNodeAs<CXXRecordDecl>("class");
QualType qt = *nodes.getNodeAs<QualType>("type");
std::string type = qt.getAsString();
if (!contains_word(type, decl->getNameAsString())) {
a.report(nodes.getNodeAs<CXXMethodDecl>("trait"),
check_name, "BT01",
"Trait declaration does not mention its class '%0'")
<< decl->getNameAsString();
}
const NamedDecl *nd = llvm::dyn_cast<NamedDecl>(decl->getCanonicalDecl());
if (type.find("bslalg::struct TypeTraitUsesBslmaAllocator::"
"NestedTraitDeclaration<") == 0 ||
type.find("bslalg_TypeTraitUsesBslmaAllocator::"
"NestedTraitDeclaration<") == 0 ||
type.find("bdealg_TypeTraitUsesBdemaAllocator::"
"NestedTraitDeclaration<") == 0) {
d.decls_with_true_allocator_trait_.insert(nd);
} else if (type.find("BloombergLP::bslmf::NestedTraitDeclaration<") == 0 &&
type.find(", bslma::UsesBslmaAllocator") != type.npos) {
auto ts = qt->getAs<TemplateSpecializationType>();
if (ts && ts->getNumArgs() == 3) {
const TemplateArgument& ta = ts->getArg(2);
if (!ta.isDependent()) {
bool value, found;
if (ta.getKind() == TemplateArgument::Integral) {
value = ta.getAsIntegral() != 0;
found = true;
} else if (ta.getKind() == TemplateArgument::Expression &&
ta.getAsExpr()->EvaluateAsBooleanCondition(
value, *a.context())) {
found = true;
} else {
found = false;
}
if (found) {
if (value) {
d.decls_with_true_allocator_trait_.insert(nd);
} else {
d.decls_with_false_allocator_trait_.insert(nd);
}
return;
}
}
}
if (type.find(", bslma::UsesBslmaAllocator, true>") != type.npos ||
type.find(", bslma::UsesBslmaAllocator>") != type.npos) {
d.decls_with_true_allocator_trait_.insert(nd);
} else if (type.find(", bslma::UsesBslmaAllocator, false>") !=
type.npos) {
d.decls_with_false_allocator_trait_.insert(nd);
} else if (type.find(", bslma::UsesBslmaAllocator,") != type.npos) {
d.decls_with_dependent_allocator_trait_.insert(nd);
}
}
}
static internal::DynTypedMatcher class_using_allocator_matcher()
// Matcher for classes that have constructors with a final parameter that
// is a pointer or reference to an allocator or a reference to a class that
// has such a constructor.
{
return decl(forEachDescendant(recordDecl(
has(constructorDecl(hasLastParameter(parmVarDecl(anyOf(
hasType(pointerType(isAllocator())),
hasType(referenceType(isAllocator()))
)))))
).bind("class")));
}
void report::match_class_using_allocator(const BoundNodes& nodes)
{
QualType type = nodes.getNodeAs<CXXRecordDecl>("class")
->getTypeForDecl()
->getCanonicalTypeInternal();
// Allocators look like they take allocators because of their copy
// constructors. But they shouldn't be considered that way.
if (!is_allocator(type, false)) {
d.type_takes_allocator_[type.getTypePtr()] = true;
}
}
static internal::DynTypedMatcher allocator_trait_matcher(int value)
{
return decl(forEachDescendant(
classTemplateSpecializationDecl(
hasName("::BloombergLP::bslma::UsesBslmaAllocator"),
templateArgumentCountIs(1),
isDerivedFrom(classTemplateSpecializationDecl(
hasName("::bsl::integral_constant"),
templateArgumentCountIs(2),
hasTemplateArgument(0, refersToType(asString("_Bool"))),
hasTemplateArgument(1, equalsIntegral(value)))))
.bind("class")));
}
void report::match_allocator_trait(data::DeclsWithAllocatorTrait* set,
const BoundNodes& nodes)
{
const ClassTemplateSpecializationDecl* td =
nodes.getNodeAs<ClassTemplateSpecializationDecl>("class");
QualType arg = td->getTemplateArgs()[0].getAsType();
const NamedDecl *d = arg->getAsCXXRecordDecl();
if (!d) {
const TemplateSpecializationType* tst =
arg->getAs<TemplateSpecializationType>();
if (tst) {
d = tst->getTemplateName().getAsTemplateDecl();
if (d) {
d = llvm::dyn_cast<TemplateDecl>(d)->getTemplatedDecl();
}
}
}
if (d) {
d = llvm::dyn_cast<NamedDecl>(d->getCanonicalDecl());
set->insert(d);
}
}
void report::match_negative_allocator_trait(const BoundNodes& nodes)
{
match_allocator_trait(&d.decls_with_false_allocator_trait_, nodes);
}
void report::match_positive_allocator_trait(const BoundNodes& nodes)
{
match_allocator_trait(&d.decls_with_true_allocator_trait_, nodes);
}
static internal::DynTypedMatcher dependent_allocator_trait_matcher()
{
return decl(forEachDescendant(
classTemplateSpecializationDecl(
hasName("::BloombergLP::bslma::UsesBslmaAllocator"),
templateArgumentCountIs(1),
unless(isDerivedFrom(classTemplateSpecializationDecl(
hasName("::bsl::integral_constant"),
templateArgumentCountIs(2),
hasTemplateArgument(0, refersToType(asString("_Bool"))),
anyOf(hasTemplateArgument(1, equalsIntegral(0)),
hasTemplateArgument(1, equalsIntegral(1)))))))
.bind("class")));
}
void report::match_dependent_allocator_trait(const BoundNodes& nodes)
{
match_allocator_trait(&d.decls_with_dependent_allocator_trait_, nodes);
}
static internal::DynTypedMatcher should_return_by_value_matcher()
{
return decl(forEachDescendant(
functionDecl(
returns(asString("void")),
hasParameter(
0,
parmVarDecl(
hasType(pointerType(unless(pointee(isConstQualified())),
unless(pointee(asString("void"))),
unless(pointee(functionType())),
unless(pointee(memberPointerType())))
.bind("type")))
.bind("parm")),
anyOf(parameterCountIs(1),
hasParameter(
1,
unless(
anyOf(hasType(isInteger()),
hasType(pointerType(
unless(pointee(asString("void"))),
unless(pointee(functionType())),
unless(pointee(memberPointerType())))))))),
anyOf(hasDescendant(binaryOperator(
hasOperatorName("="),
hasLHS(unaryOperator(
hasOperatorName("*"),
hasUnaryOperand(ignoringImpCasts(declRefExpr(
to(decl(equalsBoundNode("parm")))))))))),
hasDescendant(operatorCallExpr(
hasOverloadedOperatorName("="),
hasArgument(
0,
ignoringImpCasts(unaryOperator(
hasOperatorName("*"),
hasUnaryOperand(ignoringImpCasts(declRefExpr(
to(decl(equalsBoundNode("parm")))))))))))))
.bind("func")));
}
bool report::hasRVCognate(const FunctionDecl *func)
{
const DeclContext *parent = func->getLookupParent();
std::string name = func->getNameAsString();
DeclContext::decl_iterator declsb = parent->decls_begin();
DeclContext::decl_iterator declse = parent->decls_end();
while (declsb != declse) {
const Decl *decl = *declsb++;
const FunctionDecl* cfunc = llvm::dyn_cast<FunctionDecl>(decl);
const FunctionTemplateDecl* ctplt =
llvm::dyn_cast<FunctionTemplateDecl>(decl);
if (ctplt) {
cfunc = ctplt->getTemplatedDecl();
}
if (cfunc &&
cfunc->getNameAsString() == name &&
cfunc->getNumParams() == func->getNumParams() - 1 &&
cfunc->getCallResultType() ==
func->getParamDecl(0)->getOriginalType()->getPointeeType()) {
return true;
}
}
return false;
}
void report::match_should_return_by_value(const BoundNodes& nodes)
{
auto func = nodes.getNodeAs<FunctionDecl>("func");
auto p1 = nodes.getNodeAs<PointerType>("type");
if (func->getCanonicalDecl() == func &&
func->getTemplatedKind() == FunctionDecl::TK_NonTemplate &&
!func->getLocation().isMacroID() &&
!llvm::dyn_cast<CXXConstructorDecl>(func) &&
!p1->getPointeeType()->isDependentType() &&
!p1->getPointeeType()->isInstantiationDependentType() &&
!p1->getPointeeType()->isAnyCharacterType() &&
!p1->getPointeeType()->isFunctionType() &&
!p1->getPointeeType()->isMemberPointerType() &&
!func->getParamDecl(0)->hasDefaultArg() &&
!is_allocator(p1->desugar()) &&
!takes_allocator(p1->getPointeeType().getCanonicalType()) &&
(func->getNumParams() == 1 ||
func->getParamDecl(0)->getOriginalType().getUnqualifiedType() !=
func->getParamDecl(1)->getOriginalType().getUnqualifiedType()) &&
!hasRVCognate(func)) {
a.report(func, check_name, "RV01",
"Consider returning '%0' by value")
<< p1->getPointeeType().getCanonicalType().getAsString();
a.report(func->getParamDecl(0), check_name, "RV01",
"instead of through pointer parameter",
false, DiagnosticIDs::Note);
}
}
static internal::DynTypedMatcher ctor_expr_matcher()
{
return decl(forEachDescendant(constructExpr(anything()).bind("e")));
}
void report::match_ctor_expr(const BoundNodes& nodes)
{
auto expr = nodes.getNodeAs<CXXConstructExpr>("e");
d.cexprs_.insert(expr);
}
static internal::DynTypedMatcher return_stmt_matcher()
{
return decl(forEachDescendant(
functionDecl(forEachDescendant(returnStmt(anything()).bind("r")))
.bind("f")));
}
void report::match_return_stmt(const BoundNodes& nodes)
{
//if (!nodes.getNodeAs<FunctionDecl>("f")->isTemplateInstantiation())
{
auto stmt = nodes.getNodeAs<ReturnStmt>("r");
d.returns_.insert(stmt);
}
}
static internal::DynTypedMatcher var_decl_matcher()
{
return decl(forEachDescendant(varDecl(anything()).bind("v")));
}
void report::match_var_decl(const BoundNodes& nodes)
{
auto decl = nodes.getNodeAs<VarDecl>("v");
if (decl->hasGlobalStorage() &&
decl->hasInit() &&
llvm::dyn_cast<CXXConstructExpr>(decl->getInit())) {
d.globals_.insert(decl);
}
}
static internal::DynTypedMatcher ctor_decl_matcher()
{
return decl(forEachDescendant(constructorDecl(anything()).bind("c")));
}
void report::match_ctor_decl(const BoundNodes& nodes)
{
auto decl = nodes.getNodeAs<CXXConstructorDecl>("c");
d.ctors_.push_back(decl);
}
void report::operator()()
{
MatchFinder mf;
OnMatch<report, &report::match_nested_allocator_trait> m2(this);
mf.addDynamicMatcher(nested_allocator_trait_matcher(), &m2);
OnMatch<report, &report::match_negative_allocator_trait> m4(this);
mf.addDynamicMatcher(allocator_trait_matcher(0), &m4);
OnMatch<report, &report::match_positive_allocator_trait> m6(this);
mf.addDynamicMatcher(allocator_trait_matcher(1), &m6);
OnMatch<report, &report::match_dependent_allocator_trait> m5(this);
mf.addDynamicMatcher(dependent_allocator_trait_matcher(), &m5);
OnMatch<report, &report::match_class_using_allocator> m3(this);
mf.addDynamicMatcher(class_using_allocator_matcher(), &m3);
OnMatch<report, &report::match_should_return_by_value> m7(this);
mf.addDynamicMatcher(should_return_by_value_matcher(), &m7);
OnMatch<report, &report::match_ctor_expr> m1(this);
mf.addDynamicMatcher(ctor_expr_matcher(), &m1);
OnMatch<report, &report::match_return_stmt> m8(this);
mf.addDynamicMatcher(return_stmt_matcher(), &m8);
OnMatch<report, &report::match_var_decl> m9(this);
mf.addDynamicMatcher(var_decl_matcher(), &m9);
OnMatch<report, &report::match_ctor_decl> m10(this);
mf.addDynamicMatcher(ctor_decl_matcher(), &m10);
mf.match(*a.context()->getTranslationUnitDecl(), *a.context());
check_not_forwarded(d.ctors_.begin(), d.ctors_.end());
check_wrong_parm(d.cexprs_.begin(), d.cexprs_.end());
check_alloc_returns(d.returns_.begin(), d.returns_.end());
check_globals_use_allocator(d.globals_.begin(), d.globals_.end());
}
void report::check_globals_use_allocator(data::Globals::const_iterator begin,
data::Globals::const_iterator end)
{
for (data::Globals::const_iterator itr = begin; itr != end; ++itr) {
const VarDecl *decl = *itr;
const CXXConstructExpr *expr =
llvm::dyn_cast<CXXConstructExpr>(decl->getInit());
if (takes_allocator(expr->getType()) &&
!is_allocator(expr->getType())) {
unsigned n = expr->getNumArgs();
bool bad = n == 0;
if (n > 0) {
const Expr *last = expr->getArg(n - 1);
bool result;
if (last->isDefaultArgument() ||
(last->EvaluateAsBooleanCondition(result, *a.context()) &&
result == false)) {
bad = true;
}
}
if (bad) {
a.report(decl, check_name, "GA01",
"Variable with global storage must be "
"initialized with non-default allocator");
}
}
}
}
bool report::has_public_copy_constructor(const CXXRecordDecl *decl)
{
if (!decl->hasDefinition() || !decl->hasUserDeclaredCopyConstructor()) {
return true; // RETURN
}
for (auto c : decl->ctors()) {
if (c->isCopyConstructor() && c->getAccess() == AS_public) {
return true; // RETURN
}
}
return false;
}
void report::check_not_forwarded(data::Ctors::const_iterator begin,
data::Ctors::const_iterator end)
{
std::set<std::pair<bool, const CXXRecordDecl *> > records;
for (auto itr = begin; itr != end; ++itr) {
const CXXConstructorDecl *decl = *itr;
const CXXRecordDecl* record = decl->getParent()->getCanonicalDecl();
bool uses_allocator = takes_allocator(
record->getTypeForDecl()->getCanonicalTypeInternal());
bool has_true_alloc_trait =
d.decls_with_true_allocator_trait_.count(record);
bool has_false_alloc_trait =
d.decls_with_false_allocator_trait_.count(record);
bool has_dependent_alloc_trait =
!has_true_alloc_trait &&
!has_false_alloc_trait &&
d.decls_with_dependent_allocator_trait_.count(record);
const CXXRecordDecl *tr = record;
if (const ClassTemplateSpecializationDecl* ts =
llvm::dyn_cast<ClassTemplateSpecializationDecl>(tr)) {
const CXXRecordDecl* tr = ts->getSpecializedTemplate()
->getTemplatedDecl()
->getCanonicalDecl();
if (uses_allocator &&
!has_true_alloc_trait &&
!has_false_alloc_trait &&
!has_dependent_alloc_trait) {
record = tr;
}
if (d.decls_with_true_allocator_trait_.count(tr)) {
has_true_alloc_trait = true;
}
if (d.decls_with_false_allocator_trait_.count(tr)) {
has_false_alloc_trait = true;
}
if (d.decls_with_dependent_allocator_trait_.count(tr)) {
has_dependent_alloc_trait = true;
}
}
if (has_false_alloc_trait) {
continue;
}
std::pair<bool, const CXXRecordDecl *> rp =
std::make_pair(uses_allocator, record);
check_not_forwarded(decl);
if (records.count(rp) == 0) {
records.insert(rp);
if (has_public_copy_constructor(record)) {
if (!uses_allocator && has_true_alloc_trait) {
a.report(record, check_name, "AT01",
"Class %0 does not use allocators but has a "
"positive allocator trait")
<< record;
} else if (uses_allocator &&
!has_true_alloc_trait &&
!has_dependent_alloc_trait) {
a.report(record, check_name, "AT02",
"Class %0 uses allocators but does not have an "
"allocator trait")
<< record;
}
}
}
if (decl == decl->getCanonicalDecl() &&
!decl->isMoveConstructor() &&
uses_allocator &&
!takes_allocator(decl)) {
// Warn if the class does not have a constructor that matches this
// one, but with a final allocator parameter.
bool found = // Private copy constructor declarations are OK.
decl->getAccess() == AS_private &&
decl->isCopyOrMoveConstructor() &&
decl->isUserProvided() &&
!decl->hasBody();
unsigned num_parms = decl->getNumParams();
for (auto ci = begin; !found && ci != end; ++ci) {
const CXXConstructorDecl *ctor = *ci;
auto r = ctor->getParent()->getCanonicalDecl();
if (auto ts =
llvm::dyn_cast<ClassTemplateSpecializationDecl>(r)) {
r = ts->getSpecializedTemplate()
->getTemplatedDecl()
->getCanonicalDecl();
}
if (ctor == ctor->getCanonicalDecl() &&
ctor != decl &&
r == record &&
ctor->getNumParams() == num_parms + 1 &&
takes_allocator(ctor)) {
found = true;
for (unsigned pi = 0; found && pi < num_parms; ++pi) {
if (decl->getParamDecl(pi)->getOriginalType() !=
ctor->getParamDecl(pi)->getOriginalType()) {
found = false;
}
}
}
}
if (!found) {
std::string type =
decl->isDefaultConstructor() ? "default " :
decl->isCopyConstructor() ? "copy " :
decl->isMoveConstructor() ? "move " :
"";
if (decl->isUserProvided()) {
a.report(decl, check_name, "AC01",
"This " + type + "constructor has no version "
"that can be called with an allocator as the "
"final argument")
<< decl;
}
else {
a.report(decl, check_name, "AC02",
"Implicit " + type + "constructor cannot be "
"called with an allocator as the final argument")
<< decl;
}
}
}
}
}
void report::check_not_forwarded(const CXXConstructorDecl *decl)
{
if (!decl->hasBody()) {
return; // RETURN
}
if (!takes_allocator(decl)) {
return; // RETURN
}
// The allocator parameter is the last one.
const ParmVarDecl* palloc =
decl->getParamDecl(decl->getNumParams() - 1);
// Iterate through the base and member initializers and report those
// which take an allocator parameter that we do not pass.
check_not_forwarded(decl->init_begin(), decl->init_end(), palloc);
}
void report::check_not_forwarded(CXXConstructorDecl::init_const_iterator begin,
CXXConstructorDecl::init_const_iterator end,
const ParmVarDecl* palloc)
{
while (begin != end) {
check_not_forwarded(*begin++, palloc);
}
}
void report::check_not_forwarded(const CXXCtorInitializer* init,
const ParmVarDecl* palloc)
{
auto ctor_expr = llvm::dyn_cast<CXXConstructExpr>(init->getInit());
if (!ctor_expr) {
return; // RETURN
}
if (takes_allocator(ctor_expr->getConstructor()) &&
last_arg_is_explicit_allocator(ctor_expr)) {
// The allocator parameter is passed.
return; // RETURN
}
// Type of object being initialized.
const Type *type = init->isBaseInitializer() ?
init->getBaseClass() :
init->isAnyMemberInitializer() ?
init->getAnyMember()->getType().getTypePtr() :
nullptr;
if (!type || !takes_allocator(type->getCanonicalTypeInternal())) {
return; // RETURN
}
auto rd = get_record_decl(type->getCanonicalTypeInternal());
while (rd) {
rd = rd->getCanonicalDecl();
if (d.decls_with_false_allocator_trait_.count(rd)) {
return; // RETURN
}
rd = rd->getTemplateInstantiationPattern();
}
SourceLocation loc;
SourceRange range;
if (init->isWritten()) {
loc = ctor_expr->getExprLoc();
range = init->getSourceRange();
} else {
loc = palloc->getLocation();
range = palloc->getSourceRange();
}
if (init->isBaseInitializer()) {
a.report(loc, check_name, "MA01",
"Allocator not passed to base %0")
<< init->getBaseClass()->getCanonicalTypeInternal().getAsString()
<< range;
} else {
a.report(loc, check_name, "MA02",
"Allocator not passed to member %0")
<< init->getAnyMember()->getNameAsString() << range;
}
}
std::string report::parm_name(const ParmVarDecl* parm, int position)
{
std::ostringstream s;
s << "parameter " << position;
std::string name = parm->getNameAsString();
if (name.length() > 0) {
s << " ('" << name << "')";
}
return s.str();
}
template <typename Iter>
void report::check_wrong_parm(Iter begin, Iter end)
{
while (begin != end) {
check_wrong_parm(*begin++);
}
}
void report::check_wrong_parm(const CXXConstructExpr *expr)
{
const CXXConstructorDecl *decl = expr->getConstructor();
unsigned n = expr->getNumArgs();
const ParmVarDecl *lastp;
const Expr *lastarg;
// For the problem to possibly occur, we need each of the following:
//: 1 The constructor has at least two parameters.
//:
//: 2 The constructor and the constructor expression have the same
//: number of parameters/arguments. (I believe this will always be
//: true.)
//:
//: 3 The final constructor parameter has a default argument.
//:
//: 4 The final constructor argument expression is the default
//: argument.
//:
//: 5 The type of the final constructor parameter is pointer to
//: allocator.
if ( n >= 2
&& decl->getNumParams() == n
&& (lastp = decl->getParamDecl(n - 1))->hasDefaultArg()
&& (lastarg = expr->getArg(n - 1))->isDefaultArgument()
&& is_allocator(lastp->getType())) {
// The error will be that the second-to-last parameter is
// initialized by the allocator.
const ParmVarDecl* allocp = decl->getParamDecl(n - 1);
const ParmVarDecl* wrongp = decl->getParamDecl(n - 2);
// Descend into the expression, looking for a conversion from an
// allocator. The details of this come from an examination of the
// type structure when a test case exhibiting the problem is
// encountered. We use a loop because elements of the descent can
// repeat.
const Expr* arg = expr->getArg(n - 2);
for (;;) {
arg = arg->IgnoreImpCasts();
if (const MaterializeTemporaryExpr* mte =
llvm::dyn_cast<MaterializeTemporaryExpr>(arg)) {
arg = mte->GetTemporaryExpr();
continue;
}
if (const CXXBindTemporaryExpr* bte =
llvm::dyn_cast<CXXBindTemporaryExpr>(arg)) {
arg = bte->getSubExpr();
continue;
}
if (const CXXConstructExpr* ce =
llvm::dyn_cast<CXXConstructExpr>(arg)) {
unsigned i;
for (i = ce->getNumArgs(); i > 0; --i) {
const Expr* carg = ce->getArg(i - 1);
if (!carg->isDefaultArgument()) {
// Get the rightmost non-defaulted argument
// expression.
arg = carg->IgnoreImpCasts();
break;
}
}
if (i > 0) {
continue;
}
}
// At this point, we should have stripped off all the outer
// layers of the argument expression which are performing the
// conversion to the parameter type, and have the inner
// expression with its actual type. If that type is
// pointer-to-allocator, report the problem if it is new.
if (is_allocator(arg->getType())) {
a.report(arg->getExprLoc(), check_name, "AM01",
"Allocator argument initializes "
"non-allocator %0 of type '%1' rather than "
"allocator %2")
<< parm_name(wrongp, n - 1)
<< wrongp->getType().getAsString()
<< parm_name(allocp, n)
<< arg->getSourceRange();
}
break; // Done.
}
}
}
template <typename Iter>
void report::check_alloc_returns(Iter begin, Iter end)
{
for (Iter itr = begin; itr != end; ++itr) {
check_alloc_return(*itr);
}
}
void report::check_alloc_return(const ReturnStmt *stmt)
{
if ( stmt->getRetValue()
&& !stmt->getRetValue()->getType()->isPointerType()
&& d.decls_with_true_allocator_trait_.count(
get_record_decl(stmt->getRetValue()->getType()))) {
const FunctionDecl* func = a.get_parent<FunctionDecl>(stmt);
if (!func || !func->getReturnType()->isReferenceType()) {
a.report(stmt, check_name, "AR01",
"Type using allocator is returned by value");
}
}
}
void subscribe(Analyser& analyser, Visitor&, PPObserver&)
// Create a callback within the specified 'analyser' which will be invoked
// after a translation unit has been processed.
{
analyser.onTranslationUnitDone += report(analyser);
}
} // close anonymous namespace
static RegisterCheck c1(check_name, &subscribe);
// ----------------------------------------------------------------------------
// Copyright (C) 2014 Bloomberg Finance L.P.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// ----------------------------- END-OF-FILE ----------------------------------
|
510d002bd77616cf6dc329d77b7b9177a9c1af90
|
09fc7cba003d4637a9850aba7ab304154317b115
|
/src/Client/Modules/SR3Lib/sr3_world.h
|
d1dc9c212f6e16ef367b257b785ae83e50efcf6c
|
[] |
no_license
|
RootKiller/sr3mp-Abandoned
|
cc04632d50d6098ffd96adc329afdb0c49d02435
|
3ca7d11f2b85e0246c036c042779b5b38141938f
|
refs/heads/master
| 2020-04-13T22:19:14.344079
| 2018-12-29T04:57:53
| 2018-12-29T04:57:53
| 163,476,212
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 388
|
h
|
sr3_world.h
|
//
// Saints Row The Third Multiplayer
// Copyright (C) 2015 All rights reserved
//
#pragma once
#include "Modules/Game/Memory/Hooks.h"
#include "objects/ctg_object.h"
class sr3_world /*: public ctg_world*/
{
public:
int destroy_object(ctg_object *const object, int, int);
};
inline sr3_world *get_world(void)
{
return Memory::Hooks::Read<sr3_world *>(0x05849CD0);
}
/* EOF */
|
7f5cb9c4c65fe111a9a300ef128dd1b14c273391
|
1e7fc3dff647658bf3a77ac521ac433d4e09afe4
|
/a3k-src/UI/a3kspeedselect.cpp
|
76b26d1045854c1e23d0307f273c083b65659d4d
|
[] |
no_license
|
kueller/a3k
|
1be2928f1cd4d49612f24aace313e28cec1fbe10
|
f24e668ccce324fc2ed03a36e7c1a7b618a39c13
|
refs/heads/master
| 2021-01-21T13:49:29.883361
| 2016-05-18T03:36:03
| 2016-05-18T03:36:03
| 51,227,451
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 572
|
cpp
|
a3kspeedselect.cpp
|
#include "a3kspeedselect.h"
#include "ui_a3kspeedselect.h"
#include "a3k.h"
a3kSpeedSelect::a3kSpeedSelect(QWidget *parent) :
QDialog(parent),
ui(new Ui::a3kSpeedSelect)
{
ui->setupUi(this);
}
a3kSpeedSelect::~a3kSpeedSelect()
{
delete ui;
}
void a3kSpeedSelect::on_pushButton_clicked()
{
bool ok;
int speed = ui->lineEdit->text().toInt(&ok);
if (!ok) {
ui->lineEdit->setText("");
} else {
if (speed >= MIN_SPEED && speed <= MAX_SPEED) {
emit speedSelect(speed);
this->hide();
}
}
}
|
99649daf78fbc7e4acd466834af3a2e88249f2a4
|
39123f68902324b7f1b66790f3dfdb5ab3038d77
|
/TrueDiskOper.h
|
1d85c2e2079524ed87129ae16caf2a31a31cadc0
|
[] |
no_license
|
springtiger/VirtualDisk
|
2a0a2a2f7d7f222b58898d01ffc1bd4204462f2b
|
134c7ba9ebabe5673d0b75eaae9882f36f1261ab
|
refs/heads/main
| 2023-07-01T16:59:07.981001
| 2021-08-03T11:21:24
| 2021-08-03T11:21:24
| null | 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 1,218
|
h
|
TrueDiskOper.h
|
#pragma warning(disable:4244)
#include <windows.h>
#include <io.h>
#include <fstream>
#include "FileDisk.h"
#include "File.h"
//真实磁盘的操作
class TrueDiskOper
{
public:
TrueDiskOper();
virtual ~TrueDiskOper();
public:
static bool IsTrueDiskPath(string &path);//判断是否为真实磁盘路径,是并去除@字符
static vector<unsigned char> ReadFileFromTrueDisk(string &path);//从真实磁盘中读取文件数据
static bool GetFilsName(const string &true_path, vector<string> &files_name);//获取目录下所有文件名
static bool IsFileOrFolder(const string &true_path, string &file_name);//判断为文件或文件夹,true为文件,false为文件夹
public:
static void WriteDataToTrueDisk(const string &path, Component *component);//写虚拟磁盘数据到真实磁盘
static void WriteInt(const string &path, int size);//写整型变量
static void Writestring(const string &path, string &str);//写字符串变量
static Component* ReadDataFromTrueDisk(ifstream &load_file);//从真实磁盘中读磁盘文件
static int ReadInt(ifstream &load_file);//读整型变量
static string Readstring(ifstream &load_file);//读字符串变量
};
|
9dbd807d2a4f35bbe0690e97ccb53c135ffab734
|
6c22d7f75bcbb5ccb694406aa98579dc20aaa3aa
|
/fishparty/fishparty/fishparty/test_walkthrough1.xaml.cpp
|
f74f5a7935086023eaf0a065dc8ed5638f3cd4a2
|
[] |
no_license
|
raltyinferno/fishparty
|
51479cc4e0b94a8bfd2858b7d955bd255869ff0c
|
22b45e693211322e670ee35f740754d871550009
|
refs/heads/master
| 2018-09-20T01:42:38.730912
| 2018-06-06T10:56:06
| 2018-06-06T10:56:06
| 118,066,261
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,591
|
cpp
|
test_walkthrough1.xaml.cpp
|
//
// test_walkthrough1.xaml.cpp
// Implementation of the test_walkthrough1 class
//
#include "pch.h"
#include "test_walkthrough1.xaml.h"
using namespace fishparty;
using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Navigation;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=234238
test_walkthrough1::test_walkthrough1()
{
InitializeComponent();
}
void fishparty::test_walkthrough1::forward_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
this->Frame->Navigate(Windows::UI::Xaml::Interop::TypeName(test_walkthrough2::typeid));
}
fishparty::walkthrough_page::walkthrough_page(walkthrough_page^ forward, walkthrough_page^ back,
walkthrough_page^ left, walkthrough_page^ right):
forward(forward), back(back), left(left), right(right)
{
}
void fishparty::walkthrough_page::open()
{
}
void fishparty::walkthrough_page::walk_forward()
{
forward->open();
}
void fishparty::walkthrough_page::walk_back()
{
back->open();
}
void fishparty::walkthrough_page::walk_left()
{
left->open();
}
void fishparty::walkthrough_page::walk_right()
{
right->open();
}
|
d342e2d302efc14dba6331b5e97f3616dbcd4e15
|
306212bf4b655d2415e42c3394c63d79f8f78c91
|
/hw6_2/hw6_2/hw6_2.cpp
|
cf2c29de8871d52c8d22f3ed85cb0a0c525de60c
|
[] |
no_license
|
skyloon95/CPP_Progrmming
|
caa44cc00d84ef8fb2295dff5670c3cbe5cfade8
|
a64e06d75c0f1a06c4845a780dada8667bef230f
|
refs/heads/master
| 2021-04-06T09:12:15.143944
| 2018-06-05T18:58:42
| 2018-06-05T18:58:42
| 125,147,668
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 539
|
cpp
|
hw6_2.cpp
|
//***************************
// File_Name: hw6_2.cpp
// Name: Seol-Ah Mo / 201432014
// Date: 2018.04.13
// Content: Use Television class
//***************************
#include <iostream>
#include "Television.h"
using namespace std;
int main() {
cout << "hw6_2 : Seol-Ah Mo" << endl << endl;
cout << "current number of TVs : " << Television::getNumberOfTVs() << endl << endl;
Television tv1;
Television tv2("Samsung_Smart_UHD");
Television tv3("LG_UHD", 7200000);
showTvIfo(tv1);
showTvIfo(tv2);
showTvIfo(tv3);
return 0;
}
|
f54736ea2c8be127a7a588bbfe94ad88337273a5
|
dcf3a012610ec242e523812df254e88e82401035
|
/lab5/Rational/Rational/Rational.cpp
|
b8a0755922af56dc49b59e66bca0a1ee382d2122
|
[] |
no_license
|
venera13/oop
|
d398d766819d21ed44d54d3d526d8b424276de02
|
38d55b33015d47cd336b578aa77fe3d9fcf04688
|
refs/heads/master
| 2021-01-08T07:40:09.002914
| 2020-07-08T19:25:12
| 2020-07-08T19:25:12
| 241,957,166
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,267
|
cpp
|
Rational.cpp
|
#include "Rational.h"
CRational::CRational(int numerator, int denominator)
{
if (denominator == 0)
{
m_numerator = 0;
m_denominator = 1;
}
else
{
m_numerator = numerator;
m_denominator = denominator;
NormalizeRational();
}
}
int CRational::GetNumerator() const
{
return m_numerator;
}
int CRational::GetDenominator() const
{
return m_denominator;
}
double CRational::ToDouble() const
{
return (double)m_numerator / (double)m_denominator;
}
std::pair<int, CRational> CRational::ToCompoundFraction() const
{
int integer = m_numerator / m_denominator;
int newNumerator = m_numerator - integer * m_denominator;
return std::make_pair(integer, CRational(newNumerator, m_denominator));
}
CRational const CRational::operator+() const
{
return CRational(m_numerator, m_denominator);
}
CRational const CRational::operator-() const
{
return CRational(-m_numerator, m_denominator);
}
CRational& CRational::operator+=(const CRational& rational)
{
m_numerator = m_numerator * rational.GetDenominator() + rational.GetNumerator() * m_denominator;
m_denominator *= rational.GetDenominator();
NormalizeRational();
return *this;
}
CRational& CRational::operator-=(const CRational& rational)
{
m_numerator = m_numerator * rational.GetDenominator() - rational.GetNumerator() * m_denominator;
m_denominator *= rational.GetDenominator();
NormalizeRational();
return *this;
}
CRational& CRational::operator*=(const CRational& rational)
{
m_numerator *= rational.GetNumerator();
m_denominator *= rational.GetDenominator();
NormalizeRational();
return *this;
}
CRational& CRational::operator/=(const CRational& rational)
{
if (rational.GetNumerator() == 0)
{
throw std::invalid_argument("Denominator is zero");
}
m_numerator *= rational.GetDenominator();
m_denominator *= rational.GetNumerator();
NormalizeRational();
return *this;
}
void CRational::NormalizeRational()
{
int gcd = std::gcd(m_numerator, m_denominator);
m_numerator /= gcd;
m_denominator /= gcd;
if (m_denominator < 0)
{
m_numerator = -m_numerator;
m_denominator = -m_denominator;
}
}
CRational const operator+(const CRational& firstRational, const CRational& secondRational)
{
int newNumerator = firstRational.GetNumerator() * secondRational.GetDenominator() + secondRational.GetNumerator() * firstRational.GetDenominator();
int newDenominator = firstRational.GetDenominator() * secondRational.GetDenominator();
return CRational(newNumerator, newDenominator);
}
CRational const operator-(const CRational& firstRational, const CRational& secondRational)
{
int newNumerator = firstRational.GetNumerator() * secondRational.GetDenominator() - secondRational.GetNumerator() * firstRational.GetDenominator();
int newDenominator = firstRational.GetDenominator() * secondRational.GetDenominator();
return CRational(newNumerator, newDenominator);
}
CRational const operator*(const CRational& firstRational, const CRational& secondRational)
{
int newNumerator = firstRational.GetNumerator() * secondRational.GetNumerator();
int newDenominator = secondRational.GetDenominator() * firstRational.GetDenominator();
return CRational(newNumerator, newDenominator);
}
CRational const operator/(const CRational& firstRational, const CRational& secondRational)
{
if (secondRational.GetNumerator() == 0)
{
throw std::invalid_argument("Denominator is zero");
}
int newNumerator = firstRational.GetNumerator() * secondRational.GetDenominator();
int newDenominator = firstRational.GetDenominator() * secondRational.GetNumerator();
return CRational(newNumerator, newDenominator);
}
bool operator==(const CRational& firstRational, const CRational& secondRational)
{
return firstRational.GetNumerator() == secondRational.GetNumerator() && firstRational.GetDenominator() == secondRational.GetDenominator();
}
bool operator!=(const CRational& firstRational, const CRational& secondRational)
{
return firstRational.GetNumerator() != secondRational.GetNumerator() || firstRational.GetDenominator() != secondRational.GetDenominator();
}
bool operator<(const CRational& firstRational, const CRational& secondRational)
{
return firstRational.GetNumerator() * secondRational.GetDenominator() < firstRational.GetDenominator() * secondRational.GetNumerator();
}
bool operator<=(const CRational& firstRational, const CRational& secondRational)
{
return firstRational.GetNumerator() * secondRational.GetDenominator() <= firstRational.GetDenominator() * secondRational.GetNumerator();
}
bool operator>(const CRational& firstRational, const CRational& secondRational)
{
return firstRational.GetNumerator() * secondRational.GetDenominator() > firstRational.GetDenominator() * secondRational.GetNumerator();
}
bool operator>=(const CRational& firstRational, const CRational& secondRational)
{
return firstRational.GetNumerator() * secondRational.GetDenominator() >= firstRational.GetDenominator() * secondRational.GetNumerator();
}
std::ostream& operator<<(std::ostream& ostream, const CRational& rational)
{
ostream << rational.GetNumerator() << "/" << rational.GetDenominator();
return ostream;
}
|
53674e6be39b640cb6c6440b9a03161db13e8a56
|
a71e9cdceb5e006ad12562908c5240c9c92337f3
|
/examples/ntrip_caster.cc
|
b7414a243563b17e6e0daa128d7f793d5d3204df
|
[
"Apache-2.0"
] |
permissive
|
hail-linda/pi_ublox-ntrip
|
ada78e41dbe4b95e4ffd9f1f9b2684d7eb478e6b
|
647cae59ee687216180a475d38fdf32ba90a1a25
|
refs/heads/master
| 2022-12-25T07:16:46.324604
| 2020-10-06T06:58:41
| 2020-10-06T06:58:41
| 294,602,322
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 992
|
cc
|
ntrip_caster.cc
|
// Copyright 2019 Yuming Meng. 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 "ntrip_caster.h"
using libntrip::NtripCaster;
int main(int argc, char *argv[]) {
NtripCaster my_caster;
my_caster.Init(8090, 30, 2000);
// my_caster.Init("127.0.0.1", 8090, 10, 2000);
my_caster.Run();
while (1) {
// TODO(mengyuming@hotmail.com) : Add your code in here.
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
return 0;
}
|
3188285b5056e1966601751a6e73cdab6abb668f
|
16669e70e8bcb950b785e9cc9964b988eb732121
|
/src/Result.cpp
|
e4313c59652e4f79eb52aac14e372f1cc03dacab
|
[] |
no_license
|
rijan-chapagain/registration
|
9430eabde6bf3a0eb1ef0e6916107e3ea41e321d
|
a0e9bf5ff4a6843d53d8393d99257a85dffb5a34
|
refs/heads/main
| 2023-05-09T18:13:04.069925
| 2021-06-07T05:46:15
| 2021-06-07T05:46:15
| 350,561,617
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,846
|
cpp
|
Result.cpp
|
//
//
// Generated by StarUML(tm) C++ Add-In
//
// @ Project : Registration
// @ File Name : Result.cpp
// @ Date : 18/03/2021
// @ Author : RC
//
//
// Includes
#include <fstream>
#include "Result.h"
Result::Result() = default;
// for testing
void Result::SetCredits(unsigned credits)
{
units[0].SetCredits(credits);
units[1].SetCredits(credits);
}
unsigned Result::GetCredits(int count) const
{
return units[count].GetCredits();
}
unsigned Result::GetMarks() const
{
return marks;
}
/**
* @brief Set the marks object
*
* @param mrks
*/
void Result::SetMarks(unsigned mrks)
{
marks = mrks;
}
void Result::GetResultsInfo(int& count, std::string& name,
std::string& idUnit, unsigned& credits, unsigned& mrks, unsigned& day, std::string& month, unsigned& year)
{
// String refurbishments
units[count].CleanTheString(name, " ", "_");
units[count].CleanTheString(name, " And ", "&");
units[count].ReArrangeStringWithUnitID(name, idUnit);
// Unit Info
units[count].SetName(name);
units[count].SetID_Unit(idUnit);
units[count].SetCredits(credits);
// Marks
SetMarks(mrks);
// Date
dates[count].SetDayNo(day);
dates[count].SetMonth(month);
dates[count].SetYearNo(year);
}
void Result::SetResultsInfo(std::ofstream &fileOutput, int count)
{
fileOutput << '\t' << "Unit ID: " << units[count].GetIDUnit() << '\n'
<< '\t' << "Unit Name: " << units[count].GetName() << '\n'
<< '\t' << "Credits: " << units[count].GetCredits() << '\n'
<< '\t' << "Marks: " << GetMarks() << '\n'
<< '\t' << "Date: " << dates[count].GetDayNo()<<" "
<< dates[count].GetMonth()<<" "
<< dates[count].GetYearNo()<< '\n'<<'\n';
}
|
c113136dc0dd644fbe7052ca182d9f684bf8c6cb
|
44e26d76eed48195bc2432d7209386fb0a6d3c9d
|
/hw3/HTTPclient.cpp
|
8bc3655b545fe5a070eff35d44a9db2775aef23e
|
[] |
no_license
|
Cdower/netprog
|
932d67fa1da50d9f54e94f26b0123b8889ca358f
|
e482a87a271b7da8156ef0fc7493390078b1f2ca
|
refs/heads/master
| 2021-01-01T05:06:15.864976
| 2017-01-13T20:31:36
| 2017-01-13T20:31:36
| 57,340,712
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,274
|
cpp
|
HTTPclient.cpp
|
#include <cstring>
#include <string>
#include <iostream>
#include <stdio.h>
#include <cstdlib>
#include <sstream>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netdb.h>
using namespace std;
struct url_p{
const char * host;
const char * port;
const char * path;
//const char * service;
};
int parseURL(char * URL, url_p& parsed){
int hostSplit;
string host, port, token, path;//, service;
string sURL(URL);
token = sURL.substr(sURL.find("www"));
/*service = sURL.substr(0,sURL.find("://"));
cout << service << endl;/**/
hostSplit = token.find(":");
if(hostSplit != string::npos){
host = token.substr(0,hostSplit);
port = token.substr(hostSplit+1);
port = port.substr(0,port.find('/'));
}else{
port = "80";
host = token.substr(0,token.find('/'));
}
path = token.substr(token.find('/'));
parsed.host = host.c_str();
parsed.path = path.c_str();
parsed.port = port.c_str();
return EXIT_SUCCESS;
}
///Makes TCP Socket Connection
//Returns addrinfo of connection by reference
int connectToHost(url_p parsed, struct addrinfo *first){
int sockfd, ret, lenHost, lenPort;
char *host, *port;
struct addrinfo hints, *i;
lenHost = strlen(parsed.host);
lenPort = strlen(parsed.port);
host = new char[lenHost+1]();
port = new char[lenPort+1]();
strncpy(host, parsed.host, lenHost);
strncpy(port, parsed.port, lenPort);
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
///Initialize & Connect TCP Socket
ret = getaddrinfo(host, port, &hints, &first);
if(ret != 0){
fprintf(stderr, "getaddrinfo() failed: %s\n", gai_strerror(ret));
exit(1);
}
for(i=first; i!= NULL; i=i->ai_next){
if((sockfd = socket(i->ai_family, SOCK_DGRAM, 0)) == -1 ){
perror("socket");
continue;
}
bind(sockfd, (struct sockaddr *) i, sizeof(*i));
if( connect( sockfd, (i->ai_addr), i->ai_addrlen) == -1){
cout << "Connect Failure" << endl;
close(sockfd);
perror("connect");
continue;
}
break;
}
//ret = connect(sockfd, first->ai_addr, first->ai_addrlen);
return sockfd;
}
int sendRequest(char* path, char* host, char* port, int sockfd){
string query = "GET ";
query.append(path);
query.append(" HTTP/1.1\r\nHost: ");
query.append(host); query.append(":"); query.append(port);
query.append("\r\n");
query.append("User-Agent: dowerc-netprog-hw3/1.0\r\n\r\n\0");
if(send(sockfd, query.c_str(), sizeof(query.c_str()), 0) < 0){
cout << "Not written: " << query << endl;
}else{cout << "Sent:\n" << query << endl;}
return 0;
}
int listenResponse(int sockfd){
char buf[1024];
char * headerEnd;
int len, flags = 0;
int total = 2147483647; //INTMAX
cout << "Recieved: " << endl;
while( (len = recv(sockfd, buf, sizeof(buf)-1, 0)) > 0 && total > 0){
buf[len] = '\0';
headerEnd = strstr(buf, "\r\n\r\n");
if(headerEnd != NULL && flags == 0){
//get headers to properrly set stderrr
int headerSize = headerEnd - buf;
char headers[headerSize + 5];
strncpy(headers, buf, headerSize);
snprintf(headers+headerSize, 5, "\r\n\r\n");
headers[headerSize+4] = '\0';
fwrite(headers, 1, sizeof(headers), stderr);
//
char* contentSize = strstr(headers, "Content-Size: ");
if(contentSize == NULL){ exit(1);}
contentSize = contentSize + strlen("Content=Size: ");
char * rnIndex = strstr(contentSize, "\r\n");
char length[rnIndex - contentSize + 1];
strncpy(length, contentSize, sizeof(length));
total = atoi(length);
//
fwrite(headerEnd+4, 1, len-headerSize-4, stdout);
fflush(stdout);
total = total-len;
flags = 1;
}
else{
//
fwrite(buf, 1, len, stdout);
fflush(stdout);
total=total-len;
}
memset(buf, 0, len);
}
/*len = recv(sockfd,buf, sizeof(buf)-1,0);
while(len > 0){
cout << buf << endl;
cout.write(buf, sizeof(len));
cout << endl;
memset(&buf[0], 0, sizeof(buf));
recv(sockfd,buf, 255,0);
}/**/
cout << endl;
return 0;
}
int main(int argc, char * argv[]){
url_p parsed;
char queryPath[512], queryHost[256], queryPort[20];
struct addrinfo *first, hints, *i;
int sockfd, ret;
if(argc < 2){
perror("Requires input url to parse.");
exit(EXIT_FAILURE);
}
//Start parseURL
//parseURL(argv[1], parsed);
size_t hostSplit;
string host, port, token, path, service;
string sURL(argv[1]);
service = sURL.substr(0,sURL.find("://"));
hostSplit = sURL.find("www");
hostSplit!= string::npos ? (token=sURL.substr(hostSplit)) : (token = token);
hostSplit = 0;
hostSplit = token.find(":");
if(hostSplit != string::npos){
host = token.substr(0,hostSplit);
port = token.substr(hostSplit+1);
hostSplit=port.find('/');
hostSplit != string::npos ? (port = port.substr(0,hostSplit) ) : (port = port) ;
}else{
hostSplit = token.find('/');
hostSplit!=string::npos ? host = token.substr(0,hostSplit) : host = token;
service.compare("https")==0 ? port="443" : port="80";
//true ? cout << "True" << endl : cout << "false" << endl;
//cout << host << endl;
//host = token.substr(0,hostSplit);
}
hostSplit=token.find('/');
hostSplit!=string::npos ? path = token.substr(hostSplit) : path="";
//cout << path << endl;
parsed.host = host.c_str();
parsed.path = path.c_str();
parsed.port = port.c_str();
//End parseURL
strcpy(queryPath, parsed.path);
strcpy(queryHost, parsed.host);
strcpy(queryPort, parsed.port);
//sockfd = connectToHost(parsed, first);
//Begin connect to host
int lenHost = strlen(parsed.host), lenPort = strlen(parsed.port);
char *host_c = new char[lenHost+1](), *port_c = new char[lenPort+1]();
strncpy(host_c, parsed.host, lenHost);
strncpy(port_c, parsed.port, lenPort);
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
///Initialize & Connect TCP Socket
if(ret = getaddrinfo(host_c, port_c, &hints, &first) != 0){
fprintf(stderr, "getaddrinfo() failed: %s\n", gai_strerror(ret));
exit(1);
}
//cout << "getaddr success" << cout;
for(i=first; i!= NULL; i=i->ai_next){
if((sockfd = socket(i->ai_family, i->ai_socktype, i->ai_protocol)) == -1 ){
perror("socket");
continue;
}
bind(sockfd, (struct sockaddr *) &i, sizeof(i));
if( connect( sockfd, (i->ai_addr), i->ai_addrlen) == -1){
cout << "Connect Failure" << endl;
close(sockfd);
perror("connect");
continue;
}
break;
}
/* struct sockaddr_in addr;
socklen_t addrlen = sizeof(addr);
getpeername(sockfd, (struct sockaddr *)&addr, &addrlen);
printf("%s\n", inet_ntoa(addr.sin_addr));
//end connect to host
if(sockfd == -1){
close(sockfd);
exit(EXIT_FAILURE);
}/**/
//sendRequest(queryPath, queryHost, queryPort, sockfd);
///Begin sendRequest to build and send GET request
char request[1024];
sprintf(request, "GET %s HTTP/1.1\r\nHost: %s:%s\r\nUser-Agent: dowerc-netprog-hw3/1.0\r\n\r\n", parsed.path, queryHost, parsed.port);
if(send(sockfd, request, sizeof(request), 0) < 0){
cout << "Not written: " << request << endl;
}else{cout << "Sent:\n" << request << endl;}
///End sendRequest
///Begin listenResponse//listenResponse(sockfd);
char buf[1024];
char * headerEnd = NULL;
int len, flags = 0;
int total = 2147483647; //INTMAX
cout << "Recieved: " << endl;
while( (len = recv(sockfd, buf, sizeof(buf)-1, 0)) > 0 && total > 0){
buf[len] = '\0';
cout << buf << endl;
headerEnd = strstr(buf, "\r\n\r\n");/*
if(headerEnd != NULL && flags == 0){
//get headers to properrly set stderrr
int headerSize = headerEnd - buf;
char headers[headerSize + 5];
strncpy(headers, buf, headerSize);
snprintf(headers+headerSize, 5, "\r\n\r\n");
headers[headerSize+4] = '\0';
fwrite(headers, 1, sizeof(headers), stderr);
//
char* contentSize = strstr(headers, "Content-Size: ");
if(contentSize == NULL) { exit(1); }
contentSize = contentSize + strlen("Content-Size: ");
cout << "Content-Length: " << contentSize << endl;
char * rnIndex = strstr(contentSize, "\r\n");
char length[rnIndex - contentSize + 1];
strncpy(length, contentSize, sizeof(length));
total = atoi(length);
//
fwrite(headerEnd+4, 1, len-headerSize-4, stdout);
fflush(stdout);
cout << headerSize << endl;
total = total-len;
flags = 1;
}
else{
fwrite(buf, 1, len, stdout);
fflush(stdout);
total=total-len;
}/**/
memset(buf, 0, len);
}/**/
///End listenResponse
fclose(stdout);
close(sockfd);
return EXIT_SUCCESS;
}
|
40d935e25a4c420e826531b6b5a84e116cc23c70
|
3348039647aee132165e2cf982937ca163341b4b
|
/Homework/MiniGameStarter/TrainingFramework/src/GameObject/Text.h
|
b986cda1ddda0a66dded93473b66b5b6c5666193
|
[] |
no_license
|
HoangNhat629/Game
|
64b12df184ea265dd613f7b070c8d5caae4120fa
|
e32ad7e95384d8c8228a2636105c2653353453e7
|
refs/heads/master
| 2023-08-23T14:29:39.577071
| 2021-10-18T03:19:05
| 2021-10-18T03:19:05
| 418,326,661
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,314
|
h
|
Text.h
|
#pragma once
#include "BaseObject.h"
enum class TextColor
{
WHITE = 0,
RED,
GREEN,
BLUE,
YELLOW,
PURPLE,
CYAN,
BLACK
};
enum class TextAlign
{
LEFT = 0,
RIGHT,
CENTER
};
class Font;
class Text : public BaseObject
{
public:
Text(std::shared_ptr<Shader> shader, std::shared_ptr<Font> font, std::string text, TextColor color, float size, float lineSpacing = 1.0f, TextAlign align = TextAlign::LEFT);
Text(std::shared_ptr<Shader> shader, std::shared_ptr<Font> font, std::string text, Vector4 color, float size, float lineSpacing = 1.0f, TextAlign align = TextAlign::LEFT);
Text(std::shared_ptr<Shader> shader, std::shared_ptr<Font> font, std::string text, std::shared_ptr<Texture> texture, float size, float lineSpacing = 1.0f, TextAlign align = TextAlign::LEFT);
~Text();
void Init() override;
void Draw() final;
void SetFont(std::shared_ptr<Font> font);
void SetText(std::string text);
void Set2DPosition(GLfloat x, GLfloat y);
void Set2DPosition(Vector2 pos);
private:
void CalculateLineWidths();
Vector4 EnumToVector(TextColor color);
private:
std::string m_text;
std::shared_ptr<Font> m_font;
Vector2 m_scale;
float m_lineSpacing;
TextAlign m_align;
std::vector<float> m_lineWidths;
};
|
b9c8927c8f6e15784a7aef10964e5c510e76a5a2
|
71fe190bbeffdea271f74f2c862af7e1760d3f51
|
/TGP_Project/Source/TGP_Project/Private/BodyGuardAI.cpp
|
64a1ee7c890cd0179aac97864fadc3dc24896452
|
[] |
no_license
|
Sweet-Logic/TGP_PairProject
|
537a06adedd348e26ac7bb84b732f77f42a6666a
|
d3804d6e8ddb56b292f707f91f53bd16b8a2d4b3
|
refs/heads/master
| 2021-10-10T00:23:56.860935
| 2019-01-05T00:11:07
| 2019-01-05T00:11:07
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,938
|
cpp
|
BodyGuardAI.cpp
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "BodyGuardAI.h"
#include "BasePlayer.h"
#include "RestrictedEntrance.h"
#include "Engine/TargetPoint.h"
#include "Blueprint/AIBlueprintHelperLibrary.h"
#include "Kismet/GameplayStatics.h"
#include "DrawDebugHelpers.h"
#include "WeaponBase.h"
#include "Runtime/Engine/Classes/GameFramework/CharacterMovementComponent.h"
#include "Runtime/Engine/Classes/Engine/World.h"
#include "Runtime/Engine/Classes/GameFramework/Actor.h"
#include "gm_TGPGAME.h"
ABodyGuardAI::ABodyGuardAI()
{
_allAreasPass = true;
_patrol = false;
_minDistanceToHostile = 200.0f;
_warningTimeLimit = 5.0f;
GetCharacterMovement()->MaxWalkSpeed = 100.0f;
}
// Called when the game starts or when spawned
void ABodyGuardAI::BeginPlay()
{
Super::BeginPlay();
FVector Location = GetActorLocation();
FRotator Rotation = FRotator(-90.0f, 0.0f, 90.0f);
_currentWeapon = GetWorld()->SpawnActor<AWeaponBase>(_defaultGun, Location, Rotation);
_currentWeapon->AttachToComponent(RootComponent, FAttachmentTransformRules::SnapToTargetIncludingScale, FName(TEXT("EquipedWeapon")));
if (_patrol)
{
NextWaypoint();
}
}
void ABodyGuardAI::Tick(float DeltaTime)
{
Super ::Tick(DeltaTime);
if (IsCharacterAlive())
{
//move back to guard post
if (_state == AI_STATE::IDLE)
{
_sawSuspicious = false;
_heardSuspicious = false;
if (_patrol)
{
float distanceToWaypoint = (GetActorLocation() - _currentWaypoint->GetActorLocation()).Size();
if (distanceToWaypoint < _minDistanceToTarget)
{
NextWaypoint();
}
MoveToActor(_currentWaypoint);
}
else
{
if (_post)
{
float distanceToWaypoint = (GetActorLocation() - _post->GetActorLocation()).Size();
if (distanceToWaypoint > _minDistanceToTarget)
{
MoveToActor(_post);
}
else
{
ARestrictedEntrance* post = Cast<ARestrictedEntrance>(_post);
if (post)
{
SetActorRotation(post->GetActorRotation());
}
}
}
}
}
if (_state == AI_STATE::SUSPICIOUS)
{
MoveToLocation(_target);
if (_sawSuspicious)
{
_warningTimeCount += DeltaTime;
if (_warningTimeCount >= _warningTimeLimit)
{
_warningTimeCount = 0;
SetIsWeaponDrawn(true);
_state = AI_STATE::ALERTED;
_sawSuspicious = false;
}
else if (_warningTimeCount <= 0.0f)
{
_warningTimeCount = 0;
_state = AI_STATE::IDLE;
}
}
else if (_heardSuspicious)
{
_warningTimeCount -= DeltaTime;
if (_warningTimeCount <= 0.0f)
{
_warningTimeCount = 0;
_state = AI_STATE::IDLE;
}
}
}
if (_state == AI_STATE::ALERTED)
{
float distanceToWaypoint = (GetActorLocation() - _hostileTarget->GetActorLocation()).Size();
if (distanceToWaypoint > _minDistanceToHostile)
{
MoveToActor(_hostileTarget);
}
else
{
StopMovement();
FVector tempDir = FVector(FVector2D((_hostileTarget->GetActorLocation() - GetActorLocation()).X,
(_hostileTarget->GetActorLocation() - GetActorLocation()).Y), 0.0f);
tempDir.Normalize();
UpdateWeaponPosition(FVector2D(tempDir.X, tempDir.Y));
AWeaponBase* WeaponRef = Cast<AWeaponBase>(_currentWeapon);
WeaponRef->Use(tempDir);
//fire the weapon
}
}
Agm_TGPGAME* gameMode = (Agm_TGPGAME*)GetWorld()->GetAuthGameMode();
if (gameMode && gameMode->IsGameOver())
{
StopMovement();
}
}
}
void ABodyGuardAI::NextWaypoint()
{
if (_currentWaypoint != nullptr)
{
FVector delta = GetActorLocation() - _currentWaypoint->GetActorLocation();
float distanceToWaypoint = delta.Size();
if (_currentWaypointValue == (_waypoints.Num() - 1))
{
_currentWaypoint = _waypoints[0];
_currentWaypointValue = 0;
}
else if (distanceToWaypoint < _minDistanceToTarget)
{
_currentWaypointValue++;
_currentWaypoint = _waypoints[_currentWaypointValue];
}
}
else
{
_currentWaypoint = _waypoints[0];
_currentWaypointValue = 0;
}
}
void ABodyGuardAI::OnPawnSeen(APawn * instigator)
{
Super::OnPawnSeen(instigator);
//AFPSGameMode* GM = Cast<AFPSGameMode>(GetWorld()->GetAuthGameMode());
//if (GM)
{
//GM->CompleteMission(instigator, false);
}
//player check
ABasePlayer* player = Cast<ABasePlayer>(instigator);
if (player)
{
if (!player->IsCharacterAlive())
{
//end game
SetIsWeaponDrawn(false);
}
//if player holding gun or if player in restricted area or entrance
if (player->GetIsWeaponDrawn())
{
SetIsWeaponDrawn(true);
DrawDebugSphere(GetWorld(), instigator->GetActorLocation(), 32.0f, 12, FColor::Red, false, 10.0f);
SetAIState(AI_STATE::ALERTED);
_hostileTarget = player;
}
if (player->GetIsPlayerInRestrictedArea())
{
SetAIState(AI_STATE::SUSPICIOUS);
SetIsWeaponDrawn(false);
_target = player->GetActorLocation();
_hostileTarget = player;
_sawSuspicious = true;
}
}
//bodyguard check
ABodyGuardAI* bodyguard = Cast<ABodyGuardAI>(instigator);
if (bodyguard)
{
if (!bodyguard->IsCharacterAlive())
{
//end game
SetIsWeaponDrawn(true);
//alert other bodyguards nearby
}
}
}
void ABodyGuardAI::OnNoiseHeard(APawn * instigator, const FVector & location, float volume)
{
Super::OnNoiseHeard(instigator, location, volume);
DrawDebugSphere(GetWorld(), location, 32.0f, 12, FColor::Green, false, 10.0f);
RotateTowards(location);
//GetWorldTimerManager().ClearTimer(_timerResetRot);
//GetWorldTimerManager().SetTimer(_timerResetRot, this, &ABodyGuardAI::ResetOrientation, 3.0f);
SetAIState(AI_STATE::SUSPICIOUS);
_target = location;
_heardSuspicious = true;
_warningTimeCount = _warningTimeLimit * 0.7f;
}
void ABodyGuardAI::AlertOthers()
{
UGameplayStatics::PlaySound2D(this, _alertingOthers);
}
void ABodyGuardAI::Shot()
{
Agm_TGPGAME* gameMode = (Agm_TGPGAME*)GetWorld()->GetAuthGameMode();
gameMode->BodyGaurdKilled();
}
|
88f1619b5654fce8a2e1338c29a80050f490a04e
|
8cb1752acec0400400c0b33737e982f980a4eb9e
|
/aosp/android-1.6/frameworks/base/services/surfaceflinger/SurfaceFlinger.h
|
3284fdba999a031efc8e22760f768b2bcab8030d
|
[] |
no_license
|
jollen/android-framework-mokoid
|
80c1698743dac66df0ba6ba9db480731386d92c0
|
1075260ce25d320a73a3519af686e615c044d9fe
|
refs/heads/master
| 2023-04-02T12:58:40.057364
| 2021-04-15T01:24:15
| 2021-04-15T01:24:34
| 6,413,284
| 29
| 16
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 16,965
|
h
|
SurfaceFlinger.h
|
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_SURFACE_FLINGER_H
#define ANDROID_SURFACE_FLINGER_H
#include <stdint.h>
#include <sys/types.h>
#include <utils/Atomic.h>
#include <utils/Errors.h>
#include <utils/KeyedVector.h>
#include <utils/RefBase.h>
#include <utils/SortedVector.h>
#include <utils/threads.h>
#include <binder/BinderService.h>
#include <binder/IMemory.h>
#include <ui/PixelFormat.h>
#include <surfaceflinger/IGraphicBufferAlloc.h>
#include <surfaceflinger/ISurfaceComposer.h>
#include <surfaceflinger/ISurfaceComposerClient.h>
#include "Barrier.h"
#include "Layer.h"
#include "MessageQueue.h"
namespace android {
// ---------------------------------------------------------------------------
class Client;
class DisplayHardware;
class FreezeLock;
class Layer;
class LayerDim;
class LayerScreenshot;
struct surface_flinger_cblk_t;
#define LIKELY( exp ) (__builtin_expect( (exp) != 0, true ))
#define UNLIKELY( exp ) (__builtin_expect( (exp) != 0, false ))
// ---------------------------------------------------------------------------
class Client : public BnSurfaceComposerClient
{
public:
Client(const sp<SurfaceFlinger>& flinger);
~Client();
status_t initCheck() const;
// protected by SurfaceFlinger::mStateLock
size_t attachLayer(const sp<LayerBaseClient>& layer);
void detachLayer(const LayerBaseClient* layer);
sp<LayerBaseClient> getLayerUser(int32_t i) const;
private:
// ISurfaceComposerClient interface
virtual sp<ISurface> createSurface(
surface_data_t* params, const String8& name,
DisplayID display, uint32_t w, uint32_t h,PixelFormat format,
uint32_t flags);
virtual status_t destroySurface(SurfaceID surfaceId);
virtual status_t onTransact(
uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags);
// constant
sp<SurfaceFlinger> mFlinger;
// protected by mLock
DefaultKeyedVector< size_t, wp<LayerBaseClient> > mLayers;
size_t mNameGenerator;
// thread-safe
mutable Mutex mLock;
};
class GraphicBufferAlloc : public BnGraphicBufferAlloc
{
public:
GraphicBufferAlloc();
virtual ~GraphicBufferAlloc();
virtual sp<GraphicBuffer> createGraphicBuffer(uint32_t w, uint32_t h,
PixelFormat format, uint32_t usage, status_t* error);
};
// ---------------------------------------------------------------------------
class GraphicPlane
{
public:
static status_t orientationToTransfrom(int orientation, int w, int h,
Transform* tr);
GraphicPlane();
~GraphicPlane();
bool initialized() const;
void setDisplayHardware(DisplayHardware *);
status_t setOrientation(int orientation);
int getOrientation() const { return mOrientation; }
int getWidth() const;
int getHeight() const;
const DisplayHardware& displayHardware() const;
DisplayHardware& editDisplayHardware();
const Transform& transform() const;
EGLDisplay getEGLDisplay() const;
private:
GraphicPlane(const GraphicPlane&);
GraphicPlane operator = (const GraphicPlane&);
DisplayHardware* mHw;
Transform mGlobalTransform;
Transform mDisplayTransform;
int mOrientation;
float mDisplayWidth;
float mDisplayHeight;
int mWidth;
int mHeight;
};
// ---------------------------------------------------------------------------
enum {
eTransactionNeeded = 0x01,
eTraversalNeeded = 0x02
};
class SurfaceFlinger :
public BinderService<SurfaceFlinger>,
public BnSurfaceComposer,
public IBinder::DeathRecipient,
protected Thread
{
public:
static char const* getServiceName() { return "SurfaceFlinger"; }
SurfaceFlinger();
virtual ~SurfaceFlinger();
void init();
virtual status_t onTransact(
uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags);
virtual status_t dump(int fd, const Vector<String16>& args);
// ISurfaceComposer interface
virtual sp<ISurfaceComposerClient> createConnection();
virtual sp<IGraphicBufferAlloc> createGraphicBufferAlloc();
virtual sp<IMemoryHeap> getCblk() const;
virtual void bootFinished();
virtual void setTransactionState(const Vector<ComposerState>& state,
int orientation);
virtual status_t freezeDisplay(DisplayID dpy, uint32_t flags);
virtual status_t unfreezeDisplay(DisplayID dpy, uint32_t flags);
virtual int setOrientation(DisplayID dpy, int orientation, uint32_t flags);
virtual bool authenticateSurfaceTexture(const sp<ISurfaceTexture>& surface) const;
virtual status_t captureScreen(DisplayID dpy,
sp<IMemoryHeap>* heap,
uint32_t* width, uint32_t* height,
PixelFormat* format, uint32_t reqWidth, uint32_t reqHeight,
uint32_t minLayerZ, uint32_t maxLayerZ);
virtual status_t turnElectronBeamOff(int32_t mode);
virtual status_t turnElectronBeamOn(int32_t mode);
void screenReleased(DisplayID dpy);
void screenAcquired(DisplayID dpy);
status_t renderScreenToTexture(DisplayID dpy,
GLuint* textureName, GLfloat* uOut, GLfloat* vOut);
status_t postMessageAsync(const sp<MessageBase>& msg,
nsecs_t reltime=0, uint32_t flags = 0);
status_t postMessageSync(const sp<MessageBase>& msg,
nsecs_t reltime=0, uint32_t flags = 0);
status_t removeLayer(const sp<LayerBase>& layer);
status_t addLayer(const sp<LayerBase>& layer);
status_t invalidateLayerVisibility(const sp<LayerBase>& layer);
void invalidateHwcGeometry();
sp<Layer> getLayer(const sp<ISurface>& sur) const;
GLuint getProtectedTexName() const { return mProtectedTexName; }
class MessageDestroyGLTexture : public MessageBase {
GLuint texture;
public:
MessageDestroyGLTexture(GLuint texture) : texture(texture) { }
virtual bool handler() {
glDeleteTextures(1, &texture);
return true;
}
};
private:
// DeathRecipient interface
virtual void binderDied(const wp<IBinder>& who);
private:
friend class Client;
friend class LayerBase;
friend class LayerBaseClient;
friend class Layer;
sp<ISurface> createSurface(
ISurfaceComposerClient::surface_data_t* params,
const String8& name,
const sp<Client>& client,
DisplayID display, uint32_t w, uint32_t h, PixelFormat format,
uint32_t flags);
sp<Layer> createNormalSurface(
const sp<Client>& client, DisplayID display,
uint32_t w, uint32_t h, uint32_t flags,
PixelFormat& format);
sp<LayerDim> createDimSurface(
const sp<Client>& client, DisplayID display,
uint32_t w, uint32_t h, uint32_t flags);
sp<LayerScreenshot> createScreenshotSurface(
const sp<Client>& client, DisplayID display,
uint32_t w, uint32_t h, uint32_t flags);
status_t removeSurface(const sp<Client>& client, SurfaceID sid);
status_t destroySurface(const wp<LayerBaseClient>& layer);
uint32_t setClientStateLocked(const sp<Client>& client, const layer_state_t& s);
class LayerVector : public SortedVector< sp<LayerBase> > {
public:
LayerVector() { }
LayerVector(const LayerVector& rhs) : SortedVector< sp<LayerBase> >(rhs) { }
virtual int do_compare(const void* lhs, const void* rhs) const {
const sp<LayerBase>& l(*reinterpret_cast<const sp<LayerBase>*>(lhs));
const sp<LayerBase>& r(*reinterpret_cast<const sp<LayerBase>*>(rhs));
// sort layers by Z order
uint32_t lz = l->currentState().z;
uint32_t rz = r->currentState().z;
// then by sequence, so we get a stable ordering
return (lz != rz) ? (lz - rz) : (l->sequence - r->sequence);
}
};
struct State {
State() {
orientation = ISurfaceComposer::eOrientationDefault;
freezeDisplay = 0;
}
LayerVector layersSortedByZ;
uint8_t orientation;
uint8_t orientationFlags;
uint8_t freezeDisplay;
};
virtual bool threadLoop();
virtual status_t readyToRun();
virtual void onFirstRef();
public: // hack to work around gcc 4.0.3 bug
const GraphicPlane& graphicPlane(int dpy) const;
GraphicPlane& graphicPlane(int dpy);
void signalEvent();
void repaintEverything();
private:
void waitForEvent();
void handleConsoleEvents();
void handleTransaction(uint32_t transactionFlags);
void handleTransactionLocked(uint32_t transactionFlags);
void computeVisibleRegions(
const LayerVector& currentLayers,
Region& dirtyRegion,
Region& wormholeRegion);
void handlePageFlip();
bool lockPageFlip(const LayerVector& currentLayers);
void unlockPageFlip(const LayerVector& currentLayers);
void handleWorkList();
void handleRepaint();
void postFramebuffer();
void setupHardwareComposer(Region& dirtyInOut);
void composeSurfaces(const Region& dirty);
void setInvalidateRegion(const Region& reg);
Region getAndClearInvalidateRegion();
ssize_t addClientLayer(const sp<Client>& client,
const sp<LayerBaseClient>& lbc);
status_t addLayer_l(const sp<LayerBase>& layer);
status_t removeLayer_l(const sp<LayerBase>& layer);
status_t purgatorizeLayer_l(const sp<LayerBase>& layer);
uint32_t getTransactionFlags(uint32_t flags);
uint32_t peekTransactionFlags(uint32_t flags);
uint32_t setTransactionFlags(uint32_t flags);
void commitTransaction();
status_t captureScreenImplLocked(DisplayID dpy,
sp<IMemoryHeap>* heap,
uint32_t* width, uint32_t* height, PixelFormat* format,
uint32_t reqWidth, uint32_t reqHeight,
uint32_t minLayerZ, uint32_t maxLayerZ);
status_t turnElectronBeamOffImplLocked(int32_t mode);
status_t turnElectronBeamOnImplLocked(int32_t mode);
status_t electronBeamOffAnimationImplLocked();
status_t electronBeamOnAnimationImplLocked();
status_t renderScreenToTextureLocked(DisplayID dpy,
GLuint* textureName, GLfloat* uOut, GLfloat* vOut);
friend class FreezeLock;
sp<FreezeLock> getFreezeLock() const;
inline void incFreezeCount() {
if (mFreezeCount == 0)
mFreezeDisplayTime = 0;
mFreezeCount++;
}
inline void decFreezeCount() { if (mFreezeCount > 0) mFreezeCount--; }
inline bool hasFreezeRequest() const { return mFreezeDisplay; }
inline bool isFrozen() const {
return (mFreezeDisplay || mFreezeCount>0) && mBootFinished;
}
void debugFlashRegions();
void debugShowFPS() const;
void drawWormhole() const;
mutable MessageQueue mEventQueue;
// access must be protected by mStateLock
mutable Mutex mStateLock;
State mCurrentState;
volatile int32_t mTransactionFlags;
Condition mTransactionCV;
SortedVector< sp<LayerBase> > mLayerPurgatory;
bool mResizeTransationPending;
// protected by mStateLock (but we could use another lock)
GraphicPlane mGraphicPlanes[1];
bool mLayersRemoved;
DefaultKeyedVector< wp<IBinder>, wp<Layer> > mLayerMap;
// access must be protected by mInvalidateLock
mutable Mutex mInvalidateLock;
Region mInvalidateRegion;
// constant members (no synchronization needed for access)
sp<IMemoryHeap> mServerHeap;
surface_flinger_cblk_t* mServerCblk;
GLuint mWormholeTexName;
GLuint mProtectedTexName;
nsecs_t mBootTime;
// Can only accessed from the main thread, these members
// don't need synchronization
State mDrawingState;
Region mDirtyRegion;
Region mDirtyRegionRemovedLayer;
Region mSwapRegion;
Region mWormholeRegion;
bool mVisibleRegionsDirty;
bool mHwWorkListDirty;
bool mFreezeDisplay;
int32_t mElectronBeamAnimationMode;
int32_t mFreezeCount;
nsecs_t mFreezeDisplayTime;
Vector< sp<LayerBase> > mVisibleLayersSortedByZ;
// don't use a lock for these, we don't care
int mDebugRegion;
int mDebugBackground;
int mDebugDDMS;
int mDebugDisableHWC;
int mDebugDisableTransformHint;
volatile nsecs_t mDebugInSwapBuffers;
nsecs_t mLastSwapBufferTime;
volatile nsecs_t mDebugInTransaction;
nsecs_t mLastTransactionTime;
bool mBootFinished;
// these are thread safe
mutable Barrier mReadyToRunBarrier;
// protected by mDestroyedLayerLock;
mutable Mutex mDestroyedLayerLock;
Vector<LayerBase const *> mDestroyedLayers;
// atomic variables
enum {
eConsoleReleased = 1,
eConsoleAcquired = 2
};
volatile int32_t mConsoleSignals;
// only written in the main thread, only read in other threads
volatile int32_t mSecureFrameBuffer;
};
// ---------------------------------------------------------------------------
class FreezeLock : public LightRefBase<FreezeLock> {
SurfaceFlinger* mFlinger;
public:
FreezeLock(SurfaceFlinger* flinger)
: mFlinger(flinger) {
mFlinger->incFreezeCount();
}
~FreezeLock() {
mFlinger->decFreezeCount();
}
};
// ---------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_SURFACE_FLINGER_H
|
4e329559e267b7e1f12b497c43074ed6f4b892fc
|
70fbadd5f5dd9a0853b66b9424b1a65eeca7f057
|
/SimpleNetworkProtocol/src/PeriodicExecutor.hpp
|
9e1dd609cd32fcf8094c5691a0e481c651e1e996
|
[
"Apache-2.0"
] |
permissive
|
DrLk/MultiThreaded-Socket
|
1a683e4dc12a8e8a2d14a1cc333eba05e68e8fed
|
db46457e0aa0c23bc981c090da4c0308dacb1cf7
|
refs/heads/master
| 2023-08-17T02:06:22.203941
| 2023-08-16T19:53:51
| 2023-08-16T19:53:51
| 206,960,901
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 497
|
hpp
|
PeriodicExecutor.hpp
|
#pragma once
#include <chrono>
#include <functional>
namespace FastTransport::Protocol {
class PeriodicExecutor {
using clock = std::chrono::steady_clock;
public:
PeriodicExecutor(std::function<void()>, const std::chrono::microseconds& interval);
void Run();
private:
std::function<void()> _function;
std::chrono::microseconds _interval;
std::chrono::microseconds _start;
clock::time_point _end;
void RunFunction();
};
} // namespace FastTransport::Protocol
|
099fed7a611086e96b7081e104fb644b94b7fe4c
|
f61044b562fcc07b51ec29d35662148c8b4e763f
|
/contest067/Decrease.cc
|
4e0cc5c06fe424805a4296f73929a6fecabe227b
|
[] |
no_license
|
Sinclair-Dee/myAtcode
|
3557d3f4275922787d79f3799d54f08e0348b36b
|
f1f543b66664703dc15480de9aaac2c4f7733dd3
|
refs/heads/master
| 2020-12-02T10:03:41.085108
| 2017-08-05T14:36:37
| 2017-08-05T14:36:37
| 96,683,652
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 597
|
cc
|
Decrease.cc
|
//占用空间和时间都比较少的一种算法。
//Status:TO DO
//尚不理解题意。
#include <iostream>
#include <cstdio>
#include <algorithm>//??这个头文件中是什么??
using namespace std;
long long num[50];
int main()
{
long long k;
cin >> k;
long long t = k / 50;
for(int i = 0;i < 50;i ++) num[i] = k / 50;
k %= 50;
for(int i = 0;i < 50;i ++)
{
if(i != (50 - k)) num[i] += i;
else num[i] += 50;
}
printf("50\n");
for(int i = 0;i < 49;i ++) printf("%lld ",num[i]);
printf("%lld\n",num[49]);
return 0;
}
|
417b8446434fe2b25619b81dcbf469d04ca591fe
|
f48d5e72bd34dfd599c1687ae53aa4fc86384eaf
|
/hg_style/T2lSfeatLineS.cpp
|
389853958e6f018a675703fa1fb1d0d6f7ac60ff
|
[] |
no_license
|
ta2la/hg
|
f3c08fac5686a51f6529410a976e1bc9ae765508
|
937008bfa3bff78754099bae4c5473951b5ee7ee
|
refs/heads/master
| 2021-06-28T01:44:42.045458
| 2020-12-14T21:15:47
| 2020-12-14T21:15:47
| 190,577,067
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,171
|
cpp
|
T2lSfeatLineS.cpp
|
//
// Copyright (C) 2015 Petr Talla. [petr.talla@gmail.com]
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=============================================================================
#include "T2lSfeatLineS.h"
using namespace T2l;
//=============================================================================
SfeatLineS::SfeatLineS( const Color& color, T2l::Symbol* symbol, double spacing,
double offset, bool along ) :
Sfeat(color),
symbol_(symbol),
spacing_(spacing),
offset_(offset),
along_(along)
{
}
//=============================================================================
|
7419e202952072988cce128c999f1725734ef580
|
7719e2ae617b3bd0a444444707682d75c379c82d
|
/Labirintas/Daiktai.cpp
|
6c37b4629a3384037d10b7327d61c7706ec5cf48
|
[] |
no_license
|
deivunis/Labirintas
|
d599db168eca8b38cc410ef3a9736b08b4402bb7
|
45b6806d30d185dd5afad1cb319ce3620721bcbf
|
refs/heads/master
| 2023-04-20T01:20:44.277461
| 2021-05-14T16:36:23
| 2021-05-14T16:36:23
| 364,684,556
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 378
|
cpp
|
Daiktai.cpp
|
#include "Daiktai.h"
using namespace std;
int Items::Random()
{
srand((unsigned)time(0));
int skaicius = 1 + (rand() % 100);
return skaicius;
}
string Items::Maisas()
{
string auksas = "Aukso Maisas";
return auksas;
}
string Items::Hp()
{
string hp = "Gyvybiu eleksyras";
return hp;
}
string Items::Energy()
{
string energy = "Energijos eleksyras";
return energy;
}
|
28c98e7fadeee86e024f2050ce14903a77a13aad
|
0768e217ef0b48b149e5c9b87f41d772cd9917f1
|
/src/subr_port.cpp
|
b99f10270dc49a065b694db9d5d6528d1f518c0b
|
[
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] |
permissive
|
fujita-y/ypsilon
|
e45c897436e333cf1a1009e13bfef72c3fb3cbe9
|
62e73643a4fe87458ae100e170bf4721d7a6dd16
|
refs/heads/master
| 2023-09-05T00:06:06.525714
| 2023-01-25T03:56:13
| 2023-01-25T04:02:59
| 41,003,666
| 45
| 7
|
BSD-2-Clause
| 2022-06-25T05:44:49
| 2015-08-19T00:05:35
|
Scheme
|
UTF-8
|
C++
| false
| false
| 87,452
|
cpp
|
subr_port.cpp
|
// Copyright (c) 2004-2022 Yoshikatsu Fujita / LittleWing Company Limited.
// See LICENSE file for terms and conditions of use.
#include "core.h"
#include "arith.h"
#include "exception.h"
#include "fasl.h"
#include "heap.h"
#include "ioerror.h"
#include "port.h"
#include "printer.h"
#include "reader.h"
#include "subr.h"
#include "ucs4.h"
#include "utf8.h"
#include "violation.h"
#include "vm.h"
// set-port-current-line!
scm_obj_t subr_set_port_current_line(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 2) {
if (PORTP(argv[0])) {
scm_port_t port = (scm_port_t)argv[0];
scoped_lock lock(port->lock);
if (port_input_pred(port)) {
if (FIXNUMP(argv[1])) {
port->line = FIXNUM(argv[1]);
return scm_unspecified;
}
if (exact_integer_pred(argv[1])) {
invalid_argument_violation(vm, "set-port-current-line!", "line too large,", argv[1], 1, argc, argv);
return scm_undef;
} else {
wrong_type_argument_violation(vm, "set-port-current-line!", 1, "exact integer", argv[1], argc, argv);
return scm_undef;
}
}
/*** FALL THROUGH ***/
}
wrong_type_argument_violation(vm, "set-port-current-line!", 0, "input port", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "set-port-current-line!", 2, 2, argc, argv);
return scm_undef;
}
// set-port-current-column!
scm_obj_t subr_set_port_current_column(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 2) {
if (PORTP(argv[0])) {
scm_port_t port = (scm_port_t)argv[0];
scoped_lock lock(port->lock);
if (port_output_pred(port)) {
if (FIXNUMP(argv[1])) {
port->column = FIXNUM(argv[1]);
return scm_unspecified;
}
if (exact_integer_pred(argv[1])) {
invalid_argument_violation(vm, "set-port-current-column!", "column too large,", argv[1], 1, argc, argv);
return scm_undef;
} else {
wrong_type_argument_violation(vm, "set-port-current-column!", 1, "exact integer", argv[1], argc, argv);
return scm_undef;
}
}
/*** FALL THROUGH ***/
}
wrong_type_argument_violation(vm, "set-port-current-column!", 0, "output port", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "set-port-current-column!", 2, 2, argc, argv);
return scm_undef;
}
// port?
scm_obj_t subr_port_pred(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 1) {
if (PORTP(argv[0])) return scm_true;
return scm_false;
}
wrong_number_of_arguments_violation(vm, "port?", 1, 1, argc, argv);
return scm_undef;
}
// input-port?
scm_obj_t subr_input_port_pred(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 1) {
if (PORTP(argv[0])) {
scm_port_t port = (scm_port_t)argv[0];
scoped_lock lock(port->lock);
return port_input_pred(port) ? scm_true : scm_false;
}
return scm_false;
}
wrong_number_of_arguments_violation(vm, "input-port?", 1, 1, argc, argv);
return scm_undef;
}
// output-port?
scm_obj_t subr_output_port_pred(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 1) {
if (PORTP(argv[0])) {
scm_port_t port = (scm_port_t)argv[0];
scoped_lock lock(port->lock);
return port_output_pred(port) ? scm_true : scm_false;
}
return scm_false;
}
wrong_number_of_arguments_violation(vm, "output-port?", 1, 1, argc, argv);
return scm_undef;
}
// port-closed?
scm_obj_t subr_port_closed_pred(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 1) {
if (PORTP(argv[0])) {
scm_port_t port = (scm_port_t)argv[0];
scoped_lock lock(port->lock);
return port_open_pred(port) ? scm_false : scm_true;
}
wrong_type_argument_violation(vm, "port-closed?", 0, "port", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "port-closed?", 1, 1, argc, argv);
return scm_undef;
}
// output-port-buffer-mode
scm_obj_t subr_output_port_buffer_mode(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 1) {
if (PORTP(argv[0])) {
scm_port_t port = (scm_port_t)argv[0];
scoped_lock lock(port->lock);
CHECK_OUTPUT_PORT(0, "output-port-buffer-mode");
try {
int i = port_output_buffer_mode(port);
switch (i) {
case SCM_PORT_BUFFER_MODE_NONE:
return make_symbol(vm->m_heap, "none");
case SCM_PORT_BUFFER_MODE_LINE:
return make_symbol(vm->m_heap, "line");
case SCM_PORT_BUFFER_MODE_BLOCK:
return make_symbol(vm->m_heap, "block");
default:
fatal("%s:%u wrong port buffer mode", __FILE__, __LINE__);
}
} catch (io_exception_t& e) {
raise_io_error(vm, "output-port-buffer-mode", e.m_operation, e.m_message, e.m_err, port, scm_false);
return scm_undef;
// } catch (reader_exception_t& exception) {
// raise_lexical_violation(vm, make_symbol(vm->m_heap, "output-port-buffer-mode"), exception.m_message);
// return scm_undef;
}
}
}
wrong_number_of_arguments_violation(vm, "output-port-buffer-mode", 1, 1, argc, argv);
return scm_undef;
}
// flush-output-port
scm_obj_t subr_flush_output_port(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 1) {
if (PORTP(argv[0])) {
scm_port_t port = (scm_port_t)argv[0];
scoped_lock lock(port->lock);
CHECK_OUTPUT_PORT(0, "flush-output-port");
try {
port_flush_output(port);
port_sync_port_position(port);
return scm_unspecified;
} catch (io_exception_t& e) {
raise_io_error(vm, "flush-output-port", e.m_operation, e.m_message, e.m_err, port, scm_false);
return scm_undef;
// } catch (reader_exception_t& exception) {
// raise_lexical_violation(vm, make_symbol(vm->m_heap, "flush-output-port"), exception.m_message);
// return scm_undef;
}
}
}
wrong_number_of_arguments_violation(vm, "flush-output-port", 1, 1, argc, argv);
return scm_undef;
}
// close-port
scm_obj_t subr_close_port(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 1) {
if (PORTP(argv[0])) {
scm_port_t port = (scm_port_t)argv[0];
scoped_lock lock(port->lock);
try {
port_close(port);
} catch (io_exception_t& e) {
raise_io_error(vm, "close-port", e.m_operation, e.m_message, e.m_err, port, scm_false);
return scm_undef;
}
return scm_unspecified;
}
wrong_type_argument_violation(vm, "close-port", 0, "port", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "close-port", 1, 1, argc, argv);
return scm_undef;
}
// eof-object
scm_obj_t subr_eof_object(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 0) return scm_eof;
wrong_number_of_arguments_violation(vm, "eof-object", 0, 0, argc, argv);
return scm_undef;
}
// eof-object?
scm_obj_t subr_eof_object_pred(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 1) return (argv[0] == scm_eof) ? scm_true : scm_false;
wrong_number_of_arguments_violation(vm, "eof-object?", 1, 1, argc, argv);
return scm_undef;
}
// current-input-port
scm_obj_t subr_current_input_port(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 0) return vm->m_current_input;
wrong_number_of_arguments_violation(vm, "current-input-port", 0, 0, argc, argv);
return scm_undef;
}
// current-output-port
scm_obj_t subr_current_output_port(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 0) return vm->m_current_output;
wrong_number_of_arguments_violation(vm, "current-output-port", 0, 0, argc, argv);
return scm_undef;
}
// current-error-port
scm_obj_t subr_current_error_port(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 0) return vm->m_current_error;
wrong_number_of_arguments_violation(vm, "current-error-port", 0, 0, argc, argv);
return scm_undef;
}
// standard-input-port
scm_obj_t subr_standard_input_port(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 0) {
try {
scm_port_t port;
int fd = dup(PORT_STDIN_FD);
#if USE_CLOEXEC
if (fd >= 0) fcntl(fd, F_SETFD, FD_CLOEXEC);
#endif
port = make_std_port(vm->m_heap, fd, make_string_literal(vm->m_heap, "/dev/stdin"), SCM_PORT_DIRECTION_IN, 0, SCM_PORT_BUFFER_MODE_BLOCK,
scm_false);
port->mark = std_port_position(PORT_STDIN_FD);
return port;
} catch (io_exception_t& e) {
raise_io_error(vm, "standard-input-port", e.m_operation, e.m_message, e.m_err, scm_false, scm_false);
return scm_undef;
}
}
wrong_number_of_arguments_violation(vm, "standard-input-port", 0, 0, argc, argv);
return scm_undef;
}
// standard-output-port
scm_obj_t subr_standard_output_port(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 0) {
try {
scm_port_t port;
int fd = dup(PORT_STDOUT_FD);
#if USE_CLOEXEC
if (fd >= 0) fcntl(fd, F_SETFD, FD_CLOEXEC);
#endif
port = make_std_port(vm->m_heap, fd, make_string_literal(vm->m_heap, "/dev/stdout"), SCM_PORT_DIRECTION_OUT, 0, SCM_PORT_BUFFER_MODE_BLOCK,
scm_false);
port->mark = std_port_position(PORT_STDOUT_FD);
return port;
} catch (io_exception_t& e) {
raise_io_error(vm, "standard-output-port", e.m_operation, e.m_message, e.m_err, scm_false, scm_false);
return scm_undef;
}
}
wrong_number_of_arguments_violation(vm, "standard-output-port", 0, 0, argc, argv);
return scm_undef;
}
// standard-error-port
scm_obj_t subr_standard_error_port(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 0) {
try {
scm_port_t port;
int fd = dup(PORT_STDERR_FD);
#if USE_CLOEXEC
if (fd >= 0) fcntl(fd, F_SETFD, FD_CLOEXEC);
#endif
port = make_std_port(vm->m_heap, fd, make_string_literal(vm->m_heap, "/dev/stderr"), SCM_PORT_DIRECTION_OUT, 0, SCM_PORT_BUFFER_MODE_NONE,
scm_false);
port->mark = std_port_position(PORT_STDERR_FD);
return port;
} catch (io_exception_t& e) {
raise_io_error(vm, "standard-error-port", e.m_operation, e.m_message, e.m_err, scm_false, scm_false);
return scm_undef;
}
}
wrong_number_of_arguments_violation(vm, "standard-error-port", 0, 0, argc, argv);
return scm_undef;
}
// native-transcoder-descriptor
scm_obj_t subr_native_transcoder_descriptor(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 0) {
return vm->m_heap->m_native_transcoder;
}
wrong_number_of_arguments_violation(vm, "native-transcoder-descriptor", 0, 0, argc, argv);
return scm_undef;
}
// port-transcoder-descriptor
scm_obj_t subr_port_transcoder_descriptor(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 1) {
if (PORTP(argv[0])) {
scm_port_t port = (scm_port_t)argv[0];
scoped_lock lock(port->lock);
return port->transcoder;
}
wrong_type_argument_violation(vm, "port-transcoder-descriptor", 0, "port", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "port-transcoder-descriptor", 0, 0, argc, argv);
return scm_undef;
}
// port-device-subtype
scm_obj_t subr_port_device_subtype(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 1) {
if (PORTP(argv[0])) {
scm_port_t port = (scm_port_t)argv[0];
scoped_lock lock(port->lock);
switch (port->subtype) {
case SCM_PORT_SUBTYPE_NONE:
return make_symbol(vm->m_heap, "none");
case SCM_PORT_SUBTYPE_CHAR_SPECIAL:
return make_symbol(vm->m_heap, "char");
case SCM_PORT_SUBTYPE_FIFO:
return make_symbol(vm->m_heap, "fifo");
default:
fatal("%s:%u unknown port subtype", __FILE__, __LINE__);
}
}
wrong_type_argument_violation(vm, "port-device-subtype", 0, "port", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "port-device-subtype", 0, 0, argc, argv);
return scm_undef;
}
// extract-accumulated-bytevector
scm_obj_t subr_extract_accumulated_bytevector(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 1) {
if (PORTP(argv[0])) {
scm_port_t port = (scm_port_t)argv[0];
scoped_lock lock(port->lock);
CHECK_OPENED_PORT(0, "extract-accumulated-bytevector");
if (port_bytevector_pred(port) && port_output_pred(port)) return port_extract_bytevector(vm->m_heap, port);
wrong_type_argument_violation(vm, "extract-accumulated-bytevector", 0, "bytevector or string output port", argv[0], argc, argv);
return scm_undef;
}
wrong_type_argument_violation(vm, "extract-accumulated-bytevector", 0, "bytevector or string output port", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "extract-accumulated-bytevector", 0, 0, argc, argv);
return scm_undef;
}
// get-accumulated-bytevector
scm_obj_t subr_get_accumulated_bytevector(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 1) {
if (PORTP(argv[0])) {
scm_port_t port = (scm_port_t)argv[0];
scoped_lock lock(port->lock);
CHECK_OPENED_PORT(0, "get-accumulated-bytevector");
if (port_bytevector_pred(port) && port_output_pred(port)) return port_get_bytevector(vm->m_heap, port);
wrong_type_argument_violation(vm, "get-accumulated-bytevector", 0, "bytevector or string output port", argv[0], argc, argv);
return scm_undef;
}
wrong_type_argument_violation(vm, "get-accumulated-bytevector", 0, "bytevector or string output port", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "get-accumulated-bytevector", 0, 0, argc, argv);
return scm_undef;
}
// extract-accumulated-string
scm_obj_t subr_extract_accumulated_string(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 1) {
if (PORTP(argv[0])) {
scm_port_t port = (scm_port_t)argv[0];
scoped_lock lock(port->lock);
CHECK_OPENED_PORT(0, "extract-accumulated-string");
if (port_bytevector_pred(port) && port_output_pred(port)) return port_extract_string(vm->m_heap, port);
wrong_type_argument_violation(vm, "extract-accumulated-string", 0, "bytevector or string output port", argv[0], argc, argv);
return scm_undef;
}
wrong_type_argument_violation(vm, "extract-accumulated-string", 0, "bytevector or string output port", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "extract-accumulated-string", 0, 0, argc, argv);
return scm_undef;
}
// get-accumulated-string
scm_obj_t subr_get_accumulated_string(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 1) {
if (PORTP(argv[0])) {
scm_port_t port = (scm_port_t)argv[0];
scoped_lock lock(port->lock);
CHECK_OPENED_PORT(0, "get-accumulated-string");
if (port_bytevector_pred(port) && port_output_pred(port)) return port_get_string(vm->m_heap, port);
wrong_type_argument_violation(vm, "get-accumulated-string", 0, "bytevector or string output port", argv[0], argc, argv);
return scm_undef;
}
wrong_type_argument_violation(vm, "get-accumulated-string", 0, "bytevector or string output port", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "get-accumulated-string", 0, 0, argc, argv);
return scm_undef;
}
// make-string-output-port
scm_obj_t subr_make_string_output_port(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 0) {
scm_bvector_t transcoder = make_bvector(vm->m_heap, 3);
transcoder->elts[0] = SCM_PORT_CODEC_UTF8;
transcoder->elts[1] = SCM_PORT_EOL_STYLE_NONE;
transcoder->elts[2] = SCM_PORT_ERROR_HANDLING_MODE_IGNORE;
return make_bytevector_port(vm->m_heap, make_symbol(vm->m_heap, "string"), SCM_PORT_DIRECTION_OUT, scm_false, transcoder);
}
wrong_number_of_arguments_violation(vm, "make-string-output-port", 0, 0, argc, argv);
return scm_undef;
}
// make-string-input-port
scm_obj_t subr_make_string_input_port(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 1) {
if (STRINGP(argv[0])) {
scm_bvector_t transcoder = make_bvector(vm->m_heap, 3);
transcoder->elts[0] = SCM_PORT_CODEC_UTF8;
transcoder->elts[1] = SCM_PORT_EOL_STYLE_NONE;
transcoder->elts[2] = SCM_PORT_ERROR_HANDLING_MODE_IGNORE;
scm_string_t string = (scm_string_t)argv[0];
int size = string->size;
scm_bvector_t bvector = make_bvector(vm->m_heap, size);
memcpy(bvector->elts, string->name, size);
return make_bytevector_port(vm->m_heap, make_symbol(vm->m_heap, "string"), SCM_PORT_DIRECTION_IN, bvector, transcoder);
}
wrong_type_argument_violation(vm, "make-string-input-port", 0, "string", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "make-string-input-port", 1, 1, argc, argv);
return scm_undef;
}
// open-port
scm_obj_t subr_open_port(VM* vm, int argc, scm_obj_t argv[]) {
scm_symbol_t proc;
if (SYMBOLP(argv[0])) {
proc = (scm_symbol_t)argv[0];
} else {
wrong_type_argument_violation(vm, "open-port", 0, "symbol", argv[0], argc, argv);
return scm_undef;
}
int type = 0;
if (FIXNUMP(argv[1])) {
type = FIXNUM(argv[1]);
switch (type) {
case SCM_PORT_TYPE_NAMED_FILE:
break;
case SCM_PORT_TYPE_BYTEVECTOR:
break;
case SCM_PORT_TYPE_CUSTOM:
break;
default:
invalid_argument_violation(vm, "open-port", "bad port type,", argv[1], 1, argc, argv);
return scm_undef;
}
} else {
wrong_type_argument_violation(vm, "open-port", 1, "fixnum", argv[1], argc, argv);
return scm_undef;
}
int direction = 0;
if (FIXNUMP(argv[2])) {
direction = FIXNUM(argv[2]);
switch (type) {
case SCM_PORT_DIRECTION_IN:
break;
case SCM_PORT_DIRECTION_OUT:
break;
case SCM_PORT_DIRECTION_BOTH:
break;
default:
invalid_argument_violation(vm, "open-port", "bad port direction,", argv[2], 2, argc, argv);
return scm_undef;
}
} else {
wrong_type_argument_violation(vm, "open-port", 2, "fixnum", argv[2], argc, argv);
return scm_undef;
}
scm_obj_t name = argv[3];
if (!(STRINGP(name) || SYMBOLP(name))) {
wrong_type_argument_violation(vm, "open-port", 3, "string or symbol", argv[3], argc, argv);
return scm_undef;
}
switch (type) {
case SCM_PORT_TYPE_NAMED_FILE: {
if (STRINGP(name)) {
int file_options;
if (FIXNUMP(argv[4])) {
file_options = FIXNUM(argv[4]);
} else if (argv[4] == scm_false) {
file_options = SCM_PORT_FILE_OPTION_NONE;
} else {
wrong_type_argument_violation(vm, "open-port", 4, "#f or fixnum", argv[4], argc, argv);
return scm_undef;
}
if (file_options &
~(SCM_PORT_FILE_OPTION_NONE | SCM_PORT_FILE_OPTION_NO_CREATE | SCM_PORT_FILE_OPTION_NO_FAIL | SCM_PORT_FILE_OPTION_NO_TRUNCATE)) {
invalid_argument_violation(vm, "open-port", "bad file options,", argv[4], 4, argc, argv);
return scm_undef;
}
int buffer_mode;
if (FIXNUMP(argv[5])) {
buffer_mode = FIXNUM(argv[5]);
} else if (argv[5] == scm_false) {
buffer_mode = SCM_PORT_BUFFER_MODE_NONE;
} else {
wrong_type_argument_violation(vm, "open-port", 5, "#f or fixnum", argv[5], argc, argv);
}
switch (buffer_mode) {
case SCM_PORT_BUFFER_MODE_NONE:
break;
case SCM_PORT_BUFFER_MODE_LINE:
break;
case SCM_PORT_BUFFER_MODE_BLOCK:
break;
default:
invalid_argument_violation(vm, "open-port", "bad buffer mode,", argv[5], 5, argc, argv);
return scm_undef;
}
scm_obj_t transcoder;
if (BOOLP(argv[6]) || BVECTORP(argv[6])) {
transcoder = argv[6];
} else {
wrong_type_argument_violation(vm, "open-port", 6, "#f, #t, or bytevector", argv[6], argc, argv);
return scm_undef;
}
try {
return make_file_port(vm->m_heap, name, direction, file_options, buffer_mode, transcoder);
} catch (io_exception_t& e) {
raise_io_error(vm, proc->name, e.m_operation, e.m_message, e.m_err, scm_false, name);
return scm_undef;
}
return scm_unspecified;
}
wrong_type_argument_violation(vm, "open-port", 3, "string", argv[3], argc, argv);
return scm_undef;
} break;
case SCM_PORT_TYPE_BYTEVECTOR: {
if (SYMBOLP(name)) {
scm_obj_t bytes;
if (BVECTORP(argv[4])) {
if (direction == SCM_PORT_DIRECTION_OUT) {
wrong_type_argument_violation(vm, "open-port", 4, "#f for bytevector output port", argv[4], argc, argv);
return scm_undef;
} else {
bytes = argv[4];
}
} else if (argv[4] == scm_false) {
if (direction == SCM_PORT_DIRECTION_IN) {
wrong_type_argument_violation(vm, "open-port", 4, "bytevector for bytevector input port", argv[4], argc, argv);
return scm_undef;
} else {
bytes = scm_false;
}
} else {
wrong_type_argument_violation(vm, "open-port", 4, "#f or bytevector", argv[4], argc, argv);
return scm_undef;
}
if (argv[5] != scm_false) {
wrong_type_argument_violation(vm, "open-port", 5, "#f for bytevector port", argv[5], argc, argv);
return scm_undef;
}
scm_obj_t transcoder;
if (BOOLP(argv[6]) || BVECTORP(argv[6])) {
transcoder = argv[6];
} else {
wrong_type_argument_violation(vm, "open-port", 6, "#f, #t, or bytevector", argv[6], argc, argv);
return scm_undef;
}
try {
return make_bytevector_port(vm->m_heap, name, direction, bytes, transcoder);
} catch (io_exception_t& e) {
raise_io_error(vm, proc->name, e.m_operation, e.m_message, e.m_err, scm_false, scm_false);
return scm_undef;
}
return scm_unspecified;
}
wrong_type_argument_violation(vm, "open-port", 3, "symbol", argv[3], argc, argv);
return scm_undef;
} break;
case SCM_PORT_TYPE_CUSTOM: {
if (STRINGP(name)) {
scm_obj_t handlers;
if (VECTORP(argv[4])) {
handlers = argv[4];
} else {
wrong_type_argument_violation(vm, "open-port", 4, "vector", argv[4], argc, argv);
return scm_undef;
}
if (argv[5] != scm_false) {
wrong_type_argument_violation(vm, "open-port", 5, "#f for custom port", argv[5], argc, argv);
return scm_undef;
}
scm_obj_t transcoder;
if (BOOLP(argv[6])) {
transcoder = argv[6];
} else {
wrong_type_argument_violation(vm, "open-port", 6, "#f or #t for custom port", argv[6], argc, argv);
return scm_undef;
}
try {
return make_custom_port(vm->m_heap, name, direction, handlers, transcoder);
} catch (io_exception_t& e) {
raise_io_error(vm, proc->name, e.m_operation, e.m_message, e.m_err, scm_false, scm_false);
return scm_undef;
}
return scm_unspecified;
}
wrong_type_argument_violation(vm, "open-port", 3, "string", argv[3], argc, argv);
return scm_undef;
} break;
default:
assert(false);
}
return scm_unspecified;
}
/*
// open-port
scm_obj_t
subr_open_port(VM* vm, int argc, scm_obj_t argv[])
{
int type = 0;
if (FIXNUMP(argv[0])) {
type = FIXNUM(argv[0]);
switch (type) {
case SCM_PORT_TYPE_NAMED_FILE: break;
case SCM_PORT_TYPE_BYTEVECTOR: break;
case SCM_PORT_TYPE_CUSTOM: break;
default:
invalid_argument_violation(vm, "open-port", "bad port type,", argv[0], 0, argc, argv);
return scm_undef;
}
} else {
wrong_type_argument_violation(vm, "open-port", 0, "fixnum", argv[0], argc, argv);
return scm_undef;
}
int direction = 0;
if (FIXNUMP(argv[1])) {
direction = FIXNUM(argv[1]);
switch (type) {
case SCM_PORT_DIRECTION_IN: break;
case SCM_PORT_DIRECTION_OUT: break;
case SCM_PORT_DIRECTION_BOTH: break;
default:
invalid_argument_violation(vm, "open-port", "bad port direction,", argv[1], 1, argc, argv);
return scm_undef;
}
} else {
wrong_type_argument_violation(vm, "open-port", 1, "fixnum", argv[1], argc, argv);
return scm_undef;
}
scm_obj_t name = argv[2];
if (!(STRINGP(name) || SYMBOLP(name))) {
wrong_type_argument_violation(vm, "open-port", 2, "string or symbol", argv[2], argc, argv);
return scm_undef;
}
switch (type) {
case SCM_PORT_TYPE_NAMED_FILE: {
if (STRINGP(name)) {
int file_options;
if (FIXNUMP(argv[3])) {
file_options = FIXNUM(argv[3]);
} else if (argv[3] == scm_false) {
file_options = SCM_PORT_FILE_OPTION_NONE;
} else {
wrong_type_argument_violation(vm, "open-port", 3, "#f or fixnum", argv[3], argc, argv);
return scm_undef;
}
if (file_options & ~(SCM_PORT_FILE_OPTION_NONE |
SCM_PORT_FILE_OPTION_NO_CREATE |
SCM_PORT_FILE_OPTION_NO_FAIL |
SCM_PORT_FILE_OPTION_NO_TRUNCATE)) {
invalid_argument_violation(vm, "open-port", "bad file options,", argv[3], 3, argc, argv);
return scm_undef;
}
int buffer_mode;
if (FIXNUMP(argv[4])) {
buffer_mode = FIXNUM(argv[4]);
} else if (argv[4] == scm_false) {
buffer_mode = SCM_PORT_BUFFER_MODE_NONE;
} else {
wrong_type_argument_violation(vm, "open-port", 4, "#f or fixnum", argv[4], argc, argv);
}
switch (buffer_mode) {
case SCM_PORT_BUFFER_MODE_NONE: break;
case SCM_PORT_BUFFER_MODE_LINE: break;
case SCM_PORT_BUFFER_MODE_BLOCK: break;
default:
invalid_argument_violation(vm, "open-port", "bad buffer mode,", argv[4], 4, argc, argv);
return scm_undef;
}
scm_obj_t transcoder;
if (BOOLP(argv[5]) || BVECTORP(argv[5])) {
transcoder = argv[5];
} else {
wrong_type_argument_violation(vm, "open-port", 5, "#f, #t, or bytevector", argv[5], argc, argv);
return scm_undef;
}
try {
return make_file_port(vm->m_heap, name, direction, file_options, buffer_mode, transcoder);
} catch (io_exception_t& e) {
raise_io_error(vm, "open-port", e.m_operation, e.m_message, e.m_err, scm_false, name);
return scm_undef;
}
return scm_unspecified;
}
wrong_type_argument_violation(vm, "open-port", 2, "string", argv[2], argc, argv);
return scm_undef;
} break;
case SCM_PORT_TYPE_BYTEVECTOR: {
if (SYMBOLP(name)) {
scm_obj_t bytes;
if (BVECTORP(argv[3])) {
if (direction == SCM_PORT_DIRECTION_OUT) {
wrong_type_argument_violation(vm, "open-port", 3, "#f for bytevector output port", argv[3], argc, argv);
return scm_undef;
} else {
bytes = argv[3];
}
} else if (argv[3] == scm_false) {
if (direction == SCM_PORT_DIRECTION_IN) {
wrong_type_argument_violation(vm, "open-port", 3, "bytevector for bytevector input port", argv[3], argc, argv);
return scm_undef;
} else {
bytes = scm_false;
}
} else {
wrong_type_argument_violation(vm, "open-port", 3, "#f or bytevector", argv[3], argc, argv);
return scm_undef;
}
if (argv[4] != scm_false) {
wrong_type_argument_violation(vm, "open-port", 4, "#f for bytevector port", argv[3], argc, argv);
return scm_undef;
}
scm_obj_t transcoder;
if (BOOLP(argv[5]) || BVECTORP(argv[5])) {
transcoder = argv[5];
} else {
wrong_type_argument_violation(vm, "open-port", 5, "#f, #t, or bytevector", argv[5], argc, argv);
return scm_undef;
}
try {
return make_bytevector_port(vm->m_heap, name, direction, bytes, transcoder);
} catch (io_exception_t& e) {
raise_io_error(vm, "open-port", e.m_operation, e.m_message, e.m_err, scm_false, scm_false);
return scm_undef;
}
return scm_unspecified;
}
wrong_type_argument_violation(vm, "open-port", 2, "symbol", argv[2], argc, argv);
return scm_undef;
} break;
case SCM_PORT_TYPE_CUSTOM: {
if (STRINGP(name)) {
scm_obj_t handlers;
if (VECTORP(argv[3])) {
handlers = argv[3];
} else {
wrong_type_argument_violation(vm, "open-port", 3, "vector", argv[3], argc, argv);
return scm_undef;
}
if (argv[4] != scm_false) {
wrong_type_argument_violation(vm, "open-port", 4, "#f for custom port", argv[3], argc, argv);
return scm_undef;
}
scm_obj_t transcoder;
if (BOOLP(argv[5])) {
transcoder = argv[5];
} else {
wrong_type_argument_violation(vm, "open-port", 5, "#f or #t for custom port", argv[5], argc, argv);
return scm_undef;
}
try {
return make_custom_port(vm->m_heap, name, direction, handlers, transcoder);
} catch (io_exception_t& e) {
raise_io_error(vm, "open-port", e.m_operation, e.m_message, e.m_err, scm_false, scm_false);
return scm_undef;
}
return scm_unspecified;
}
wrong_type_argument_violation(vm, "open-port", 2, "string", argv[2], argc, argv);
return scm_undef;
} break;
default: assert(false);
}
return scm_unspecified;
}
*/
// open-script-input-port
scm_obj_t subr_open_script_input_port(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 1) {
if (STRINGP(argv[0])) {
scm_port_t port = NULL;
try {
scm_bvector_t transcoder = make_bvector(vm->m_heap, 3);
transcoder->elts[0] = SCM_PORT_CODEC_UTF8;
transcoder->elts[1] = SCM_PORT_EOL_STYLE_LF;
transcoder->elts[2] = SCM_PORT_ERROR_HANDLING_MODE_RAISE;
port = make_file_port(vm->m_heap, (scm_string_t)argv[0], SCM_PORT_DIRECTION_IN, 0, SCM_PORT_BUFFER_MODE_BLOCK, transcoder);
assert(PORTP(port));
scoped_lock lock(port->lock);
scm_obj_t ch = port_lookahead_utf8(port);
if (CHARP(ch)) {
uint32_t ucs4 = CHAR(ch);
if (ucs4 == SCM_PORT_UCS4_BOM) port_get_utf8(port);
}
off64_t pos = port_position(port);
ch = port_lookahead_utf8(port);
if (CHARP(ch) && CHAR(ch) == '#') {
port_get_utf8(port);
scm_obj_t ch1 = port_get_utf8(port);
scm_obj_t ch2 = port_get_utf8(port);
if (CHARP(ch1) && CHAR(ch1) == '!' && CHARP(ch2) && (CHAR(ch2) == '/' || CHAR(ch2) == ' ')) {
do {
ch = port_get_char(port);
if (ch == scm_eof) break;
} while (CHARP(ch) && CHAR(ch) != SCM_PORT_UCS4_LF);
} else {
port_set_port_position(port, pos);
port->track_line_column = true;
port->column = 1;
port->line = 1;
}
}
return port;
} catch (io_exception_t& e) {
raise_io_error(vm, "open-script-input-port", e.m_operation, e.m_message, e.m_err, (port ? port : scm_false), argv[0]);
return scm_undef;
} catch (io_codec_exception_t& e) {
raise_io_codec_error(vm, "open-script-input-port", e.m_operation, e.m_message, (port ? port : scm_false), e.m_ch);
return scm_undef;
}
}
wrong_type_argument_violation(vm, "open-script-input-port", 0, "string", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "open-script-input-port", 1, 1, argc, argv);
return scm_undef;
}
// make-file-input-port
scm_obj_t subr_make_file_input_port(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 1) {
if (STRINGP(argv[0])) {
scm_port_t port = NULL;
try {
port = make_file_port(vm->m_heap, (scm_string_t)argv[0], SCM_PORT_DIRECTION_IN, 0, SCM_PORT_BUFFER_MODE_BLOCK, scm_true);
assert(PORTP(port));
return port;
} catch (io_exception_t& e) {
raise_io_error(vm, "make-file-input-port", e.m_operation, e.m_message, e.m_err, (port ? port : scm_false), argv[0]);
return scm_undef;
} catch (io_codec_exception_t& e) {
raise_io_codec_error(vm, "make-file-input-port", e.m_operation, e.m_message, (port ? port : scm_false), e.m_ch);
return scm_undef;
}
}
wrong_type_argument_violation(vm, "make-file-input-port", 0, "string", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "make-file-input-port", 1, 1, argc, argv);
return scm_undef;
}
// make-file-output-port
scm_obj_t subr_make_file_output_port(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 1) {
if (STRINGP(argv[0])) {
scm_port_t port = NULL;
try {
port = make_file_port(vm->m_heap, (scm_string_t)argv[0], SCM_PORT_DIRECTION_OUT, SCM_PORT_FILE_OPTION_NO_FAIL,
SCM_PORT_BUFFER_MODE_BLOCK, scm_true);
assert(PORTP(port));
return port;
} catch (io_exception_t& e) {
raise_io_error(vm, "make-file-output-port", e.m_operation, e.m_message, e.m_err, (port ? port : scm_false), argv[0]);
return scm_undef;
} catch (io_codec_exception_t& e) {
raise_io_codec_error(vm, "make-file-output-port", e.m_operation, e.m_message, (port ? port : scm_false), e.m_ch);
return scm_undef;
}
}
wrong_type_argument_violation(vm, "make-file-output-port", 0, "string", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "make-output-file-port", 1, 1, argc, argv);
return scm_undef;
}
// make-temporary-file-port
scm_obj_t subr_make_temporary_file_port(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 2) {
if (STRINGP(argv[0])) {
scm_string_t name = (scm_string_t)argv[0];
if (BOOLP(argv[1]) || BVECTORP(argv[1])) {
scm_obj_t transcoder = argv[1];
try {
return make_temp_file_port(vm->m_heap, name, SCM_PORT_BUFFER_MODE_BLOCK, transcoder);
} catch (io_exception_t& e) {
raise_io_error(vm, "make-temporary-file-port", e.m_operation, e.m_message, e.m_err, scm_false, name);
return scm_undef;
}
return scm_unspecified;
}
wrong_type_argument_violation(vm, "make-temporary-file-port", 1, "#f, #t, or bytevector", argv[1], argc, argv);
return scm_undef;
}
wrong_type_argument_violation(vm, "make-temporary-file-port", 0, "string", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "make-temporary-file-port", 2, 2, argc, argv);
return scm_undef;
}
// nonblock-byte-ready?
scm_obj_t subr_nonblock_byte_ready_pred(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 1) {
if (PORTP(argv[0])) {
scm_port_t port = (scm_port_t)argv[0];
scoped_lock lock(port->lock);
CHECK_OPENED_INPUT_PORT(0, "nonblock-byte-ready?");
try {
return port_nonblock_byte_ready(port) ? scm_true : scm_false;
} catch (io_exception_t& e) {
raise_io_error(vm, "nonblock-byte-ready?", e.m_operation, e.m_message, e.m_err, port, scm_false);
return scm_undef;
}
}
wrong_type_argument_violation(vm, "nonblock-byte-ready?", 0, "port", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "nonblock-byte-ready?", 1, 1, argc, argv);
return scm_undef;
}
// get-char
scm_obj_t subr_get_char(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 1) {
if (PORTP(argv[0])) {
scm_port_t port = (scm_port_t)argv[0];
scoped_lock lock(port->lock);
CHECK_OPENED_TEXTUAL_INPUT_PORT(0, "get-char");
try {
return port_get_char(port);
} catch (io_exception_t& e) {
raise_io_error(vm, "get-char", e.m_operation, e.m_message, e.m_err, port, scm_false);
return scm_undef;
} catch (io_codec_exception_t& e) {
raise_io_codec_error(vm, "get-char", e.m_operation, e.m_message, port, e.m_ch);
return scm_undef;
}
}
wrong_type_argument_violation(vm, "get-char", 0, "port", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "get-char", 1, 1, argc, argv);
return scm_undef;
}
// lookahead-char
scm_obj_t subr_lookahead_char(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 1) {
if (PORTP(argv[0])) {
scm_port_t port = (scm_port_t)argv[0];
scoped_lock lock(port->lock);
CHECK_OPENED_TEXTUAL_INPUT_PORT(0, "lookahead-char");
try {
return port_lookahead_char(port);
} catch (io_exception_t& e) {
raise_io_error(vm, "lookahead-char", e.m_operation, e.m_message, e.m_err, port, scm_false);
return scm_undef;
} catch (io_codec_exception_t& e) {
raise_io_codec_error(vm, "lookahead-char", e.m_operation, e.m_message, port, e.m_ch);
return scm_undef;
}
}
wrong_type_argument_violation(vm, "lookahead-char", 0, "port", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "lookahead-char", 1, 1, argc, argv);
return scm_undef;
}
// port-has-port-position?
scm_obj_t subr_port_has_port_position_pred(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 1) {
if (PORTP(argv[0])) {
scm_port_t port = (scm_port_t)argv[0];
scoped_lock lock(port->lock);
try {
return port_has_port_position_pred(port) ? scm_true : scm_false;
} catch (io_exception_t& e) {
raise_io_error(vm, "port-has-port-position?", e.m_operation, e.m_message, e.m_err, port, scm_false);
return scm_undef;
}
}
wrong_type_argument_violation(vm, "port-has-port-position?", 0, "port", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "port-has-port-position?", 1, 1, argc, argv);
return scm_undef;
}
// port-position
scm_obj_t subr_port_position(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 1) {
if (PORTP(argv[0])) {
scm_port_t port = (scm_port_t)argv[0];
scoped_lock lock(port->lock);
CHECK_OPENED_PORT(0, "port-position");
if (port_has_port_position_pred(port)) {
try {
assert(sizeof(off64_t) <= sizeof(int64_t));
int64_t off = port_position(port);
return int64_to_integer(vm->m_heap, off);
} catch (io_exception_t& e) {
raise_io_error(vm, "port-position", e.m_operation, e.m_message, e.m_err, port, scm_false);
return scm_undef;
}
}
wrong_type_argument_violation(vm, "port-position", 0, "positionable port", argv[0], argc, argv);
return scm_undef;
}
wrong_type_argument_violation(vm, "port-position", 0, "port", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "port-position", 1, 1, argc, argv);
return scm_undef;
}
// port-has-set-port-position!?
scm_obj_t subr_port_has_set_port_position_pred(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 1) {
if (PORTP(argv[0])) {
scm_port_t port = (scm_port_t)argv[0];
scoped_lock lock(port->lock);
try {
return port_has_set_port_position_pred(port) ? scm_true : scm_false;
} catch (io_exception_t& e) {
raise_io_error(vm, "port-has-set-port-position!?", e.m_operation, e.m_message, e.m_err, port, scm_false);
return scm_undef;
}
}
wrong_type_argument_violation(vm, "port-has-set-port-position!?", 0, "port", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "port-has-set-port-position!?", 1, 1, argc, argv);
return scm_undef;
}
// set-port-position!
scm_obj_t subr_set_port_position(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 2) {
if (PORTP(argv[0])) {
scm_port_t port = (scm_port_t)argv[0];
scoped_lock lock(port->lock);
CHECK_OPENED_PORT(0, "set-port-position!");
if (port_has_set_port_position_pred(port)) {
if (exact_non_negative_integer_pred(argv[1])) {
try {
assert(sizeof(off64_t) <= sizeof(int64_t));
int64_t off;
if (exact_integer_to_int64(argv[1], &off)) {
port_set_port_position(port, off);
return scm_unspecified;
} else {
invalid_argument_violation(vm, "set-port-position!", "index out of bounds,", argv[1], 1, argc, argv);
return scm_undef;
}
} catch (io_exception_t& e) {
raise_io_error(vm, "set-port-position!", e.m_operation, e.m_message, e.m_err, port, scm_false);
return scm_undef;
}
}
wrong_type_argument_violation(vm, "set-port-position!", 1, "exact non-negative integer", argv[1], argc, argv);
return scm_undef;
}
wrong_type_argument_violation(vm, "set-port-position!", 0, "positionable port", argv[0], argc, argv);
return scm_undef;
}
wrong_type_argument_violation(vm, "set-port-position!", 0, "port", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "set-port-position!", 2, 2, argc, argv);
return scm_undef;
}
// port-eof?
scm_obj_t subr_port_eof_pred(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 1) {
if (PORTP(argv[0])) {
scm_port_t port = (scm_port_t)argv[0];
scoped_lock lock(port->lock);
CHECK_OPENED_INPUT_PORT(0, "port-eof?");
try {
return port_eof(port) ? scm_true : scm_false;
} catch (io_exception_t& e) {
raise_io_error(vm, "port-eof?", e.m_operation, e.m_message, e.m_err, port, scm_false);
return scm_undef;
}
}
wrong_type_argument_violation(vm, "port-eof?", 0, "port", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "port-eof?", 1, 1, argc, argv);
return scm_undef;
}
// get-u8
scm_obj_t subr_get_u8(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 1) {
if (PORTP(argv[0])) {
scm_port_t port = (scm_port_t)argv[0];
scoped_lock lock(port->lock);
CHECK_OPENED_BINARY_INPUT_PORT(0, "get-u8");
try {
return port_get_u8(port);
} catch (io_exception_t& e) {
raise_io_error(vm, "get-u8", e.m_operation, e.m_message, e.m_err, port, scm_false);
return scm_undef;
}
}
wrong_type_argument_violation(vm, "get-u8", 0, "port", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "get-u8", 1, 1, argc, argv);
return scm_undef;
}
// lookahead-u8
scm_obj_t subr_lookahead_u8(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 1) {
if (PORTP(argv[0])) {
scm_port_t port = (scm_port_t)argv[0];
scoped_lock lock(port->lock);
CHECK_OPENED_BINARY_INPUT_PORT(0, "lookahead-u8");
try {
return port_lookahead_u8(port);
} catch (io_exception_t& e) {
raise_io_error(vm, "lookahead-u8", e.m_operation, e.m_message, e.m_err, port, scm_false);
return scm_undef;
}
}
wrong_type_argument_violation(vm, "lookahead-u8", 0, "port", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "lookahead-u8", 1, 1, argc, argv);
return scm_undef;
}
// get-byte
scm_obj_t subr_get_byte(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 1) {
if (PORTP(argv[0])) {
scm_port_t port = (scm_port_t)argv[0];
scoped_lock lock(port->lock);
CHECK_OPENED_INPUT_PORT(0, "get-byte");
try {
return port_get_u8(port);
} catch (io_exception_t& e) {
raise_io_error(vm, "get-byte", e.m_operation, e.m_message, e.m_err, port, scm_false);
return scm_undef;
}
}
wrong_type_argument_violation(vm, "get-byte", 0, "port", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "get-byte", 1, 1, argc, argv);
return scm_undef;
}
// lookahead-byte
scm_obj_t subr_lookahead_byte(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 1) {
if (PORTP(argv[0])) {
scm_port_t port = (scm_port_t)argv[0];
scoped_lock lock(port->lock);
CHECK_OPENED_INPUT_PORT(0, "lookahead-byte");
try {
return port_lookahead_u8(port);
} catch (io_exception_t& e) {
raise_io_error(vm, "lookahead-byte", e.m_operation, e.m_message, e.m_err, port, scm_false);
return scm_undef;
}
}
wrong_type_argument_violation(vm, "lookahead-byte", 0, "port", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "lookahead-byte", 1, 1, argc, argv);
return scm_undef;
}
// get-bytevector-n
scm_obj_t subr_get_bytevector_n(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 2) {
if (PORTP(argv[0])) {
scm_port_t port = (scm_port_t)argv[0];
scoped_lock lock(port->lock);
CHECK_OPENED_BINARY_INPUT_PORT(0, "get-bytevector-n");
CHECK_NON_NEGATIVE_FIXNUM(1, "get-bytevector-n");
int count = FIXNUM(argv[1]);
try {
scm_bvector_t bvector = make_bvector(vm->m_heap, count);
#if USE_MULTIBYTE_READ
if (count == 0) return bvector;
int n = port_get_bytes(port, bvector->elts, count);
if (n == 0) return scm_eof;
if (n == count) return bvector;
scm_bvector_t bvector2 = make_bvector(vm->m_heap, n);
memcpy(bvector2->elts, bvector->elts, n);
return bvector2;
#else
for (int i = 0; i < count; i++) {
int c = port_get_byte(port);
if (c == EOF) {
if (i == 0) return scm_eof;
scm_bvector_t bvector2 = make_bvector(vm->m_heap, i);
memcpy(bvector2->elts, bvector->elts, i);
return bvector2;
}
bvector->elts[i] = c;
}
return bvector;
#endif
} catch (io_exception_t& e) {
raise_io_error(vm, "get-bytevector-n", e.m_operation, e.m_message, e.m_err, port, scm_false);
return scm_undef;
}
}
wrong_type_argument_violation(vm, "get-bytevector-n", 0, "port", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "get-bytevector-n", 2, 2, argc, argv);
return scm_undef;
}
// get-bytevector-n!
scm_obj_t subr_get_bytevector_n_ex(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 4) {
if (PORTP(argv[0])) {
scm_port_t port = (scm_port_t)argv[0];
scoped_lock lock(port->lock);
CHECK_OPENED_BINARY_INPUT_PORT(0, "get-bytevector-n!");
if (BVECTORP(argv[1])) {
scm_bvector_t bvector = (scm_bvector_t)argv[1];
CHECK_NON_NEGATIVE_FIXNUM(2, "get-bytevector-n!");
int start = FIXNUM(argv[2]);
CHECK_NON_NEGATIVE_FIXNUM(3, "get-bytevector-n!");
int count = FIXNUM(argv[3]);
if (start + count <= bvector->count) {
try {
#if USE_MULTIBYTE_READ
if (count == 0) return MAKEFIXNUM(0);
int n = port_get_bytes(port, bvector->elts + start, count);
if (n == 0) return scm_eof;
return MAKEFIXNUM(n);
#else
for (int i = 0; i < count; i++) {
int c = port_get_byte(port);
if (c == EOF) {
if (i == 0) return scm_eof;
return MAKEFIXNUM(i);
}
bvector->elts[start + i] = c;
}
return MAKEFIXNUM(count);
#endif
} catch (io_exception_t& e) {
raise_io_error(vm, "get-bytevector-n!", e.m_operation, e.m_message, e.m_err, port, scm_false);
return scm_undef;
}
}
if (start >= bvector->count) {
invalid_argument_violation(vm, "get-bytevector-n!", "index out of bounds,", argv[2], 2, argc, argv);
return scm_undef;
} else {
invalid_argument_violation(vm, "get-bytevector-n!", "too many elements,", argv[3], 3, argc, argv);
return scm_undef;
}
}
wrong_type_argument_violation(vm, "get-bytevector-n!", 1, "bytevector", argv[1], argc, argv);
return scm_undef;
}
wrong_type_argument_violation(vm, "get-bytevector-n!", 0, "port", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "get-bytevector-n", 4, 4, argc, argv);
return scm_undef;
}
// get-bytevector-some
scm_obj_t subr_get_bytevector_some(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 1) {
if (PORTP(argv[0])) {
scm_port_t port = (scm_port_t)argv[0];
scoped_lock lock1(port->lock);
CHECK_OPENED_BINARY_INPUT_PORT(0, "get-bytevector-some");
try {
int c = port_lookahead_byte(port);
if (c == EOF) return scm_eof;
int n = port_buffered_byte_count(port);
scm_bvector_t bvector = make_bvector(vm->m_heap, n);
for (int i = 0; i < n; i++) bvector->elts[i] = port_get_byte(port);
return bvector;
} catch (io_exception_t& e) {
raise_io_error(vm, "get-bytevector-some", e.m_operation, e.m_message, e.m_err, port, scm_false);
return scm_undef;
}
}
wrong_type_argument_violation(vm, "get-bytevector-some", 0, "port", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "get-bytevector-some", 1, 1, argc, argv);
return scm_undef;
}
// get-bytevector-all
scm_obj_t subr_get_bytevector_all(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 1) {
if (PORTP(argv[0])) {
scm_port_t port = (scm_port_t)argv[0];
scoped_lock lock1(port->lock);
CHECK_OPENED_BINARY_INPUT_PORT(0, "get-bytevector-all");
scm_port_t output = make_bytevector_port(vm->m_heap, make_symbol(vm->m_heap, "bytevector"), SCM_PORT_DIRECTION_OUT, scm_false, scm_false);
scoped_lock lock2(output->lock);
try {
#if USE_MULTIBYTE_READ && USE_MULTIBYTE_WRITE
uint8_t buf[SCM_PORT_BLOCK_BUFFER_SIZE];
while (true) {
int n = port_get_bytes(port, buf, sizeof(buf));
if (n == 0) {
if (port_position(output) == 0) return scm_eof;
return port_extract_bytevector(vm->m_heap, output);
}
port_put_bytes(output, buf, n);
}
#else
while (true) {
int b = port_get_byte(port);
if (b == EOF) {
if (port_position(output) == 0) return scm_eof;
return port_extract_bytevector(vm->m_heap, output);
}
port_put_byte(output, b);
}
#endif
} catch (io_exception_t& e) {
raise_io_error(vm, "get-bytevector-all", e.m_operation, e.m_message, e.m_err, port, scm_false);
return scm_undef;
}
}
wrong_type_argument_violation(vm, "get-bytevector-all", 0, "port", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "get-bytevector-all", 1, 1, argc, argv);
return scm_undef;
}
// get-string-n
scm_obj_t subr_get_string_n(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 2) {
if (PORTP(argv[0])) {
scm_port_t port = (scm_port_t)argv[0];
scoped_lock lock(port->lock);
CHECK_OPENED_TEXTUAL_INPUT_PORT(0, "get-string-n");
CHECK_NON_NEGATIVE_FIXNUM(1, "get-string-n");
int count = FIXNUM(argv[1]);
scm_port_t output = make_bytevector_port(vm->m_heap, make_symbol(vm->m_heap, "bytevector"), SCM_PORT_DIRECTION_OUT, scm_false, scm_false);
scoped_lock lock2(output->lock);
try {
for (int i = 0; i < count; i++) {
scm_obj_t ch = port_get_char(port);
if (ch == scm_eof) {
if (i == 0) return scm_eof;
return port_extract_string(vm->m_heap, output);
}
uint8_t utf8[4];
int n = cnvt_ucs4_to_utf8(CHAR(ch), utf8);
for (int i = 0; i < n; i++) port_put_byte(output, utf8[i]);
}
return port_extract_string(vm->m_heap, output);
} catch (io_exception_t& e) {
raise_io_error(vm, "get-string-n", e.m_operation, e.m_message, e.m_err, port, scm_false);
return scm_undef;
} catch (io_codec_exception_t& e) {
raise_io_codec_error(vm, "get-string-n", e.m_operation, e.m_message, port, e.m_ch);
return scm_undef;
}
}
wrong_type_argument_violation(vm, "get-string-n", 0, "port", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "get-string-n", 2, 2, argc, argv);
return scm_undef;
}
// get-string-n!
scm_obj_t subr_get_string_n_ex(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 4) {
if (PORTP(argv[0])) {
scm_port_t port = (scm_port_t)argv[0];
scoped_lock lock(port->lock);
CHECK_OPENED_TEXTUAL_INPUT_PORT(0, "get-string-n!");
if (STRINGP(argv[1])) {
scm_string_t string = (scm_string_t)argv[1];
int length = utf8_string_length(string);
CHECK_NON_NEGATIVE_FIXNUM(2, "get-string-n!");
int start = FIXNUM(argv[2]);
CHECK_NON_NEGATIVE_FIXNUM(3, "get-string-n!");
int count = FIXNUM(argv[3]);
if (start + count <= length) {
try {
for (int i = 0; i < count; i++) {
scm_obj_t ch = port_get_char(port);
if (ch == scm_eof) {
if (i == 0) return scm_eof;
return MAKEFIXNUM(i);
}
utf8_string_set(vm->m_heap, string, start + i, CHAR(ch));
}
return MAKEFIXNUM(count);
} catch (io_exception_t& e) {
raise_io_error(vm, "get-string-n!", e.m_operation, e.m_message, e.m_err, port, scm_false);
return scm_undef;
} catch (io_codec_exception_t& e) {
raise_io_codec_error(vm, "get-string-n!", e.m_operation, e.m_message, port, e.m_ch);
return scm_undef;
}
}
if (start >= length) {
invalid_argument_violation(vm, "get-string-n!", "index out of bounds,", argv[2], 2, argc, argv);
return scm_undef;
} else {
invalid_argument_violation(vm, "get-string-n!", "too many elements,", argv[3], 3, argc, argv);
return scm_undef;
}
}
wrong_type_argument_violation(vm, "get-string-n!", 1, "string", argv[1], argc, argv);
return scm_undef;
}
wrong_type_argument_violation(vm, "get-string-n!", 0, "port", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "get-string-n!", 4, 4, argc, argv);
return scm_undef;
}
// get-string-all
scm_obj_t subr_get_string_all(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 1) {
if (PORTP(argv[0])) {
scm_port_t port = (scm_port_t)argv[0];
scoped_lock lock1(port->lock);
CHECK_OPENED_TEXTUAL_INPUT_PORT(0, "get-string-all");
scm_port_t output = make_bytevector_port(vm->m_heap, make_symbol(vm->m_heap, "bytevector"), SCM_PORT_DIRECTION_OUT, scm_false, scm_false);
scoped_lock lock2(output->lock);
try {
while (true) {
scm_obj_t ch = port_get_char(port);
if (ch == scm_eof) {
if (port_position(output) == 0) return scm_eof;
return port_extract_string(vm->m_heap, output);
}
uint8_t utf8[4];
int n = cnvt_ucs4_to_utf8(CHAR(ch), utf8);
for (int i = 0; i < n; i++) port_put_byte(output, utf8[i]);
}
} catch (io_exception_t& e) {
raise_io_error(vm, "get-string-all", e.m_operation, e.m_message, e.m_err, port, scm_false);
return scm_undef;
} catch (io_codec_exception_t& e) {
raise_io_codec_error(vm, "get-string-all", e.m_operation, e.m_message, port, e.m_ch);
return scm_undef;
}
}
wrong_type_argument_violation(vm, "get-string-all", 0, "port", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "get-string-all", 1, 1, argc, argv);
return scm_undef;
}
// get-line
scm_obj_t subr_get_line(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 1) {
if (PORTP(argv[0])) {
scm_port_t port = (scm_port_t)argv[0];
scoped_lock lock1(port->lock);
CHECK_OPENED_TEXTUAL_INPUT_PORT(0, "get-line");
scm_port_t output = make_bytevector_port(vm->m_heap, make_symbol(vm->m_heap, "bytevector"), SCM_PORT_DIRECTION_OUT, scm_false, scm_false);
scoped_lock lock2(output->lock);
try {
while (true) {
scm_obj_t ch = port_get_char(port);
if (ch == scm_eof) {
if (port_position(output) == 0) return scm_eof;
return port_extract_string(vm->m_heap, output);
}
if (CHAR(ch) == SCM_PORT_UCS4_LF) return port_extract_string(vm->m_heap, output);
uint8_t utf8[4];
int n = cnvt_ucs4_to_utf8(CHAR(ch), utf8);
for (int i = 0; i < n; i++) port_put_byte(output, utf8[i]);
}
} catch (io_exception_t& e) {
raise_io_error(vm, "get-line", e.m_operation, e.m_message, e.m_err, port, scm_false);
return scm_undef;
} catch (io_codec_exception_t& e) {
raise_io_codec_error(vm, "get-line", e.m_operation, e.m_message, port, e.m_ch);
return scm_undef;
}
}
wrong_type_argument_violation(vm, "get-line", 0, "port", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "get-line", 1, 1, argc, argv);
return scm_undef;
}
// get-datum
scm_obj_t subr_get_datum(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 1) {
if (PORTP(argv[0])) {
scm_port_t port = (scm_port_t)argv[0];
scoped_lock lock(port->lock);
CHECK_OPENED_TEXTUAL_INPUT_PORT(0, "get-datum");
try {
return reader_t(vm, port).read(NULL);
} catch (io_exception_t& e) {
raise_io_error(vm, "get-datum", e.m_operation, e.m_message, e.m_err, port, scm_false);
return scm_undef;
} catch (io_codec_exception_t& e) {
raise_io_codec_error(vm, "get-datum", e.m_operation, e.m_message, port, e.m_ch);
return scm_undef;
} catch (reader_exception_t& exception) {
lexical_violation(vm, make_symbol(vm->m_heap, "get-datum"), exception.m_message);
return scm_undef;
}
}
wrong_type_argument_violation(vm, "get-datum", 0, "port", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "get-datum", 1, 1, argc, argv);
return scm_undef;
}
// put-u8
scm_obj_t subr_put_u8(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 2) {
if (PORTP(argv[0])) {
scm_port_t port = (scm_port_t)argv[0];
scoped_lock lock(port->lock);
CHECK_OPENED_BINARY_OUTPUT_PORT(0, "put-u8");
CHECK_OCTET(1, "put-u8");
try {
port_put_byte(port, FIXNUM(argv[1]));
if (port->force_sync) port_flush_output(port);
return scm_unspecified;
} catch (io_exception_t& e) {
raise_io_error(vm, "put-u8", e.m_operation, e.m_message, e.m_err, port, scm_false);
return scm_undef;
}
}
wrong_type_argument_violation(vm, "put-u8", 0, "port", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "put-u8", 2, 2, argc, argv);
return scm_undef;
}
// put-byte
scm_obj_t subr_put_byte(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 2) {
if (PORTP(argv[0])) {
scm_port_t port = (scm_port_t)argv[0];
scoped_lock lock(port->lock);
CHECK_OPENED_OUTPUT_PORT(0, "put-byte");
CHECK_OCTET(1, "put-byte");
try {
port_put_byte(port, FIXNUM(argv[1]));
if (port->force_sync) port_flush_output(port);
return scm_unspecified;
} catch (io_exception_t& e) {
raise_io_error(vm, "put-byte", e.m_operation, e.m_message, e.m_err, port, scm_false);
return scm_undef;
}
}
wrong_type_argument_violation(vm, "put-byte", 0, "port", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "put-byte", 2, 2, argc, argv);
return scm_undef;
}
// put-bytevector
scm_obj_t subr_put_bytevector(VM* vm, int argc, scm_obj_t argv[]) {
if (argc >= 2 && argc <= 4) {
if (PORTP(argv[0])) {
scm_port_t port = (scm_port_t)argv[0];
scoped_lock lock(port->lock);
CHECK_OPENED_BINARY_OUTPUT_PORT(0, "put-bytevector");
if (BVECTORP(argv[1])) {
scm_bvector_t bvector = (scm_bvector_t)argv[1];
int start = 0;
int count = bvector->count;
if (argc > 2) {
CHECK_NON_NEGATIVE_FIXNUM(2, "put-bytevector");
start = FIXNUM(argv[2]);
count = bvector->count - start;
}
if (argc > 3) {
CHECK_NON_NEGATIVE_FIXNUM(3, "put-bytevector");
count = FIXNUM(argv[3]);
}
if (start + count <= bvector->count) {
try {
#if USE_MULTIBYTE_WRITE
port_put_bytes(port, bvector->elts + start, count);
#else
for (int i = 0; i < count; i++) port_put_byte(port, bvector->elts[start + i]);
#endif
if (port->force_sync) port_flush_output(port);
return scm_unspecified;
} catch (io_exception_t& e) {
raise_io_error(vm, "put-bytevector", e.m_operation, e.m_message, e.m_err, port, scm_false);
return scm_undef;
}
}
if (start >= bvector->count) {
invalid_argument_violation(vm, "put-bytevector", "index out of bounds,", argv[2], 2, argc, argv);
return scm_undef;
} else {
invalid_argument_violation(vm, "put-bytevector", "too many elements,", argv[3], 3, argc, argv);
return scm_undef;
}
}
wrong_type_argument_violation(vm, "put-bytevector", 1, "bytevector", argv[1], argc, argv);
return scm_undef;
}
wrong_type_argument_violation(vm, "put-bytevector", 0, "port", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "put-bytevector", 2, 4, argc, argv);
return scm_undef;
}
// put-char
scm_obj_t subr_put_char(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 2) {
if (PORTP(argv[0])) {
scm_port_t port = (scm_port_t)argv[0];
scoped_lock lock(port->lock);
CHECK_OPENED_TEXTUAL_OUTPUT_PORT(0, "put-char");
if (CHARP(argv[1])) {
try {
port_put_char(port, argv[1]);
if (port->force_sync) port_flush_output(port);
return scm_unspecified;
} catch (io_exception_t& e) {
raise_io_error(vm, "put-char", e.m_operation, e.m_message, e.m_err, port, scm_false);
return scm_undef;
} catch (io_codec_exception_t& e) {
raise_io_codec_error(vm, "put-char", e.m_operation, e.m_message, port, e.m_ch);
return scm_undef;
}
}
wrong_type_argument_violation(vm, "put-char", 1, "char", argv[1], argc, argv);
return scm_undef;
}
wrong_type_argument_violation(vm, "put-char", 0, "port", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "put-char", 2, 2, argc, argv);
return scm_undef;
}
// put-string
scm_obj_t subr_put_string(VM* vm, int argc, scm_obj_t argv[]) {
if (argc >= 2 && argc <= 4) {
if (PORTP(argv[0])) {
scm_port_t port = (scm_port_t)argv[0];
scoped_lock lock(port->lock);
CHECK_OPENED_TEXTUAL_OUTPUT_PORT(0, "put-string");
if (STRINGP(argv[1])) {
scm_string_t string = (scm_string_t)argv[1];
if (argc == 2) {
try {
port_put_string(port, string);
if (port->force_sync) port_flush_output(port);
return scm_unspecified;
} catch (io_exception_t& e) {
raise_io_error(vm, "put-string", e.m_operation, e.m_message, e.m_err, port, scm_false);
return scm_undef;
} catch (io_codec_exception_t& e) {
raise_io_codec_error(vm, "put-string", e.m_operation, e.m_message, port, e.m_ch);
return scm_undef;
}
}
int len = utf8_string_length(string);
int start = 0;
int count = len;
if (argc > 2) {
CHECK_NON_NEGATIVE_FIXNUM(2, "put-string");
start = FIXNUM(argv[2]);
count = len - start;
}
if (argc > 3) {
CHECK_NON_NEGATIVE_FIXNUM(3, "put-string");
count = FIXNUM(argv[3]);
}
if (start + count <= len) {
try {
for (int i = 0; i < count; i++) {
int c = utf8_string_ref(string, start + i);
if (c >= 0) {
port_put_char(port, MAKECHAR(c));
continue;
}
invalid_object_violation(vm, "put-string", "properly encoded string", string, argc, argv);
return scm_undef;
}
if (port->force_sync) port_flush_output(port);
return scm_unspecified;
} catch (io_exception_t& e) {
raise_io_error(vm, "put-string", e.m_operation, e.m_message, e.m_err, port, scm_false);
return scm_undef;
} catch (io_codec_exception_t& e) {
raise_io_codec_error(vm, "put-string", e.m_operation, e.m_message, port, e.m_ch);
return scm_undef;
}
}
if (start >= len) {
invalid_argument_violation(vm, "put-string", "index out of bounds,", argv[2], 2, argc, argv);
return scm_undef;
} else {
invalid_argument_violation(vm, "put-string", "too many elements,", argv[3], 3, argc, argv);
return scm_undef;
}
}
wrong_type_argument_violation(vm, "put-string", 1, "string", argv[1], argc, argv);
return scm_undef;
}
wrong_type_argument_violation(vm, "put-string", 0, "port", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "put-string", 2, 4, argc, argv);
return scm_undef;
}
// put-datum
scm_obj_t subr_put_datum(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 2) {
if (PORTP(argv[0])) {
scm_port_t port = (scm_port_t)argv[0];
scoped_lock lock(port->lock);
CHECK_OPENED_TEXTUAL_OUTPUT_PORT(0, "put-datum");
try {
if (BOOLP(port->transcoder)) {
printer_t prt(vm, port);
prt.format("~s", argv[1]);
} else {
scm_port_t buf = make_bytevector_port(vm->m_heap, make_symbol(vm->m_heap, "string"), SCM_PORT_DIRECTION_OUT, scm_false, scm_true);
scoped_lock lock2(buf->lock);
printer_t prt(vm, buf);
prt.format("~s", argv[1]);
port_put_string(port, port_extract_string(vm->m_heap, buf));
if (port->force_sync) port_flush_output(port);
}
return scm_unspecified;
} catch (io_exception_t& e) {
raise_io_error(vm, "put-datum", e.m_operation, e.m_message, e.m_err, port, scm_false);
return scm_undef;
} catch (io_codec_exception_t& e) {
raise_io_codec_error(vm, "put-datum", e.m_operation, e.m_message, port, e.m_ch);
return scm_undef;
}
}
wrong_type_argument_violation(vm, "put-datum", 0, "port", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "put-datum", 2, 2, argc, argv);
return scm_undef;
}
// put-fasl
scm_obj_t subr_put_fasl(VM* vm, int argc, scm_obj_t argv[]) {
#if DISABLE_FASL
return subr_put_datum(vm, argc, argv);
#endif
if (argc == 2) {
if (PORTP(argv[0])) {
scm_port_t port = (scm_port_t)argv[0];
scoped_lock lock(port->lock);
CHECK_OPENED_OUTPUT_PORT(0, "put-fasl");
try {
port_puts(port, "\n#!fasl0\n");
scm_obj_t bad = fasl_printer_t(vm, port).put(argv[1]);
if (bad) {
non_serializable_object_violation(vm, "put-fasl", bad, argc, argv);
return scm_undef;
}
return scm_unspecified;
} catch (io_codec_exception_t& e) {
raise_io_codec_error(vm, "put-fasl", e.m_operation, e.m_message, port, e.m_ch);
return scm_undef;
} catch (io_exception_t& e) {
raise_io_error(vm, "put-fasl", e.m_operation, e.m_message, e.m_err, port, scm_false);
return scm_undef;
}
}
wrong_type_argument_violation(vm, "put-fasl", 0, "port", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "put-fasl", 2, 2, argc, argv);
return scm_undef;
}
// write
scm_obj_t subr_write(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 1 || argc == 2) {
scm_port_t port;
if (argc == 1) {
port = vm->m_current_output;
} else {
if (PORTP(argv[1])) {
port = (scm_port_t)argv[1];
} else {
wrong_type_argument_violation(vm, "write", 1, "port", argv[1], argc, argv);
return scm_undef;
}
}
scoped_lock lock(port->lock);
if (argc == 2) {
CHECK_OPENED_TEXTUAL_OUTPUT_PORT(1, "write");
} else {
if (!port_open_pred(port) || !port_output_pred(port) || !port_textual_pred(port)) {
invalid_object_violation(vm, "write", "current output port is textual and it opened for output", port, argc, argv);
return scm_undef;
}
}
try {
if (BOOLP(port->transcoder)) {
printer_t prt(vm, port);
prt.format("~s", argv[0]);
} else {
scm_port_t buf = make_bytevector_port(vm->m_heap, make_symbol(vm->m_heap, "string"), SCM_PORT_DIRECTION_OUT, scm_false, scm_true);
scoped_lock lock2(buf->lock);
printer_t prt(vm, buf);
prt.format("~s", argv[0]);
port_put_string(port, port_extract_string(vm->m_heap, buf));
}
if (port->force_sync) port_flush_output(port);
return scm_unspecified;
} catch (io_exception_t& e) {
raise_io_error(vm, "write", e.m_operation, e.m_message, e.m_err, port, scm_false);
return scm_undef;
} catch (io_codec_exception_t& e) {
raise_io_codec_error(vm, "write", e.m_operation, e.m_message, port, e.m_ch);
return scm_undef;
}
}
wrong_number_of_arguments_violation(vm, "write", 1, 2, argc, argv);
return scm_undef;
}
// display
scm_obj_t subr_display(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 1 || argc == 2) {
scm_port_t port;
if (argc == 1) {
port = vm->m_current_output;
} else {
if (PORTP(argv[1])) {
port = (scm_port_t)argv[1];
} else {
wrong_type_argument_violation(vm, "display", 1, "port", argv[1], argc, argv);
return scm_undef;
}
}
scoped_lock lock(port->lock);
if (argc == 2) {
CHECK_OPENED_TEXTUAL_OUTPUT_PORT(1, "display");
} else {
if (!port_open_pred(port) || !port_output_pred(port) || !port_textual_pred(port)) {
invalid_object_violation(vm, "display", "current output port is textual and it opened for output", port, argc, argv);
return scm_undef;
}
}
try {
if (BOOLP(port->transcoder)) {
printer_t(vm, port).format("~a", argv[0]);
} else {
scm_port_t buf = make_bytevector_port(vm->m_heap, make_symbol(vm->m_heap, "string"), SCM_PORT_DIRECTION_OUT, scm_false, scm_true);
scoped_lock lock2(buf->lock);
printer_t(vm, buf).format("~a", argv[0]);
port_put_string(port, port_extract_string(vm->m_heap, buf));
}
if (port->force_sync) port_flush_output(port);
return scm_unspecified;
} catch (io_exception_t& e) {
raise_io_error(vm, "display", e.m_operation, e.m_message, e.m_err, port, scm_false);
return scm_undef;
} catch (io_codec_exception_t& e) {
raise_io_codec_error(vm, "display", e.m_operation, e.m_message, port, e.m_ch);
return scm_undef;
}
}
wrong_number_of_arguments_violation(vm, "display", 1, 2, argc, argv);
return scm_undef;
}
// newline
scm_obj_t subr_newline(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 0 || argc == 1) {
scm_port_t port;
if (argc == 0) {
port = vm->m_current_output;
} else {
if (PORTP(argv[0])) {
port = (scm_port_t)argv[0];
} else {
wrong_type_argument_violation(vm, "newline", 0, "port", argv[0], argc, argv);
return scm_undef;
}
}
scoped_lock lock(port->lock);
if (argc == 1) {
CHECK_OPENED_TEXTUAL_OUTPUT_PORT(0, "newline");
} else {
if (!port_open_pred(port) || !port_output_pred(port) || !port_textual_pred(port)) {
invalid_object_violation(vm, "newline", "current output port is textual and it opened for output", port, argc, argv);
return scm_undef;
}
}
try {
printer_t(vm, port).format("~%", argv[1]);
if (port->force_sync) port_flush_output(port);
return scm_unspecified;
} catch (io_exception_t& e) {
raise_io_error(vm, "newline", e.m_operation, e.m_message, e.m_err, port, scm_false);
return scm_undef;
} catch (io_codec_exception_t& e) {
raise_io_codec_error(vm, "newline", e.m_operation, e.m_message, port, e.m_ch);
return scm_undef;
}
}
wrong_number_of_arguments_violation(vm, "newline", 0, 1, argc, argv);
return scm_undef;
}
// read-char
scm_obj_t subr_read_char(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 0 || argc == 1) {
scm_port_t port;
if (argc == 0) {
port = vm->m_current_input;
} else {
if (PORTP(argv[0])) {
port = (scm_port_t)argv[0];
} else {
wrong_type_argument_violation(vm, "read-char", 0, "port", argv[0], argc, argv);
return scm_undef;
}
}
scoped_lock lock(port->lock);
if (argc == 1) {
CHECK_OPENED_TEXTUAL_INPUT_PORT(0, "read-char");
} else {
if (!port_open_pred(port) || !port_input_pred(port) || !port_textual_pred(port)) {
invalid_object_violation(vm, "read-char", "current input port is textual and it opened for input", port, argc, argv);
return scm_undef;
}
}
try {
return port_get_char(port);
} catch (io_exception_t& e) {
raise_io_error(vm, "read-char", e.m_operation, e.m_message, e.m_err, port, scm_false);
return scm_undef;
} catch (io_codec_exception_t& e) {
raise_io_codec_error(vm, "read-char", e.m_operation, e.m_message, port, e.m_ch);
return scm_undef;
}
}
wrong_number_of_arguments_violation(vm, "read-char", 0, 1, argc, argv);
return scm_undef;
}
// peek-char
scm_obj_t subr_peek_char(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 0 || argc == 1) {
scm_port_t port;
if (argc == 0) {
port = vm->m_current_input;
} else {
if (PORTP(argv[0])) {
port = (scm_port_t)argv[0];
} else {
wrong_type_argument_violation(vm, "peek-char", 0, "port", argv[0], argc, argv);
return scm_undef;
}
}
scoped_lock lock(port->lock);
if (argc == 1) {
CHECK_OPENED_TEXTUAL_INPUT_PORT(0, "peek-char");
} else {
if (!port_open_pred(port) || !port_input_pred(port) || !port_textual_pred(port)) {
invalid_object_violation(vm, "peek-char", "current input port is textual and it opened for input", port, argc, argv);
return scm_undef;
}
}
try {
return port_lookahead_char(port);
} catch (io_exception_t& e) {
raise_io_error(vm, "peek-char", e.m_operation, e.m_message, e.m_err, port, scm_false);
return scm_undef;
} catch (io_codec_exception_t& e) {
raise_io_codec_error(vm, "peek-char", e.m_operation, e.m_message, port, e.m_ch);
return scm_undef;
}
}
wrong_number_of_arguments_violation(vm, "peek-char", 0, 1, argc, argv);
return scm_undef;
}
// write-char
scm_obj_t subr_write_char(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 1 || argc == 2) {
scm_port_t port;
if (argc == 1) {
port = vm->m_current_output;
} else {
if (PORTP(argv[1])) {
port = (scm_port_t)argv[1];
} else {
wrong_type_argument_violation(vm, "write-char", 1, "port", argv[1], argc, argv);
return scm_undef;
}
}
scoped_lock lock(port->lock);
if (argc == 2) {
CHECK_OPENED_TEXTUAL_OUTPUT_PORT(1, "write-char");
} else {
if (!port_open_pred(port) || !port_output_pred(port) || !port_textual_pred(port)) {
invalid_object_violation(vm, "write-char", "current output port is textual and it opened for output", port, argc, argv);
return scm_undef;
}
}
if (CHARP(argv[0])) {
try {
port_put_char(port, argv[0]);
if (port->force_sync) port_flush_output(port);
return scm_unspecified;
} catch (io_exception_t& e) {
raise_io_error(vm, "write-char", e.m_operation, e.m_message, e.m_err, port, scm_false);
return scm_undef;
} catch (io_codec_exception_t& e) {
raise_io_codec_error(vm, "write-char", e.m_operation, e.m_message, port, e.m_ch);
return scm_undef;
}
}
wrong_type_argument_violation(vm, "write-char", 0, "char", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "write-char", 1, 2, argc, argv);
return scm_undef;
}
// read
scm_obj_t subr_read(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 0 || argc == 1) {
scm_port_t port;
if (argc == 0) {
port = vm->m_current_input;
} else {
if (PORTP(argv[0])) {
port = (scm_port_t)argv[0];
} else {
wrong_type_argument_violation(vm, "read", 0, "port", argv[0], argc, argv);
return scm_undef;
}
}
scoped_lock lock(port->lock);
if (argc == 1) {
CHECK_OPENED_TEXTUAL_INPUT_PORT(0, "read");
} else {
if (!port_open_pred(port) || !port_input_pred(port) || !port_textual_pred(port)) {
invalid_object_violation(vm, "read", "current input port is textual and it opened for input", port, argc, argv);
return scm_undef;
}
}
try {
return reader_t(vm, port).read(NULL);
} catch (io_exception_t& e) {
raise_io_error(vm, "read", e.m_operation, e.m_message, e.m_err, port, scm_false);
return scm_undef;
} catch (io_codec_exception_t& e) {
raise_io_codec_error(vm, "read", e.m_operation, e.m_message, port, e.m_ch);
return scm_undef;
} catch (reader_exception_t& exception) {
lexical_violation(vm, make_symbol(vm->m_heap, "read"), exception.m_message);
return scm_undef;
}
}
wrong_number_of_arguments_violation(vm, "read", 0, 1, argc, argv);
return scm_undef;
}
// make-transcoded-port
scm_obj_t subr_make_transcoded_port(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 2) {
if (PORTP(argv[0])) {
scm_port_t port = (scm_port_t)argv[0];
scoped_lock lock(port->lock);
CHECK_OPENED_BINARY_PORT(0, "make-transcoded-port");
if (BVECTORP(argv[1])) {
scm_bvector_t transcoder = (scm_bvector_t)argv[1];
try {
scm_port_t textual =
make_transcoded_port(vm->m_heap, make_list(vm->m_heap, 2, make_symbol(vm->m_heap, "transcoded"), port->name), port, transcoder);
return textual;
} catch (io_exception_t& e) {
raise_io_error(vm, "make-transcoded-port", e.m_operation, e.m_message, e.m_err, port, scm_false);
return scm_undef;
}
}
wrong_type_argument_violation(vm, "make-transcoded-port", 1, "bytevector", argv[1], argc, argv);
return scm_undef;
}
wrong_type_argument_violation(vm, "make-transcoded-port", 0, "port", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "make-transcoded-port", 2, 2, argc, argv);
return scm_undef;
}
// set-current-input-port!
scm_obj_t subr_set_current_input_port(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 1) {
if (PORTP(argv[0])) {
vm->m_current_input = (scm_port_t)argv[0];
return scm_unspecified;
}
wrong_type_argument_violation(vm, "set-current-input-port!", 0, "port", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "set-current-input-port!", 1, 1, argc, argv);
return scm_undef;
}
// set-current-output-port!
scm_obj_t subr_set_current_output_port(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 1) {
if (PORTP(argv[0])) {
vm->m_current_output = (scm_port_t)argv[0];
return scm_unspecified;
}
wrong_type_argument_violation(vm, "set-current-output-port!", 0, "port", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "set-current-output-port!", 1, 1, argc, argv);
return scm_undef;
}
// set-current-error-port!
scm_obj_t subr_set_current_error_port(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 1) {
if (PORTP(argv[0])) {
vm->m_current_error = (scm_port_t)argv[0];
return scm_unspecified;
}
wrong_type_argument_violation(vm, "set-current-error-port!", 0, "port", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "set-current-error-port!", 1, 1, argc, argv);
return scm_undef;
}
// shutdown-output-port
scm_obj_t subr_shutdown_output_port(VM* vm, int argc, scm_obj_t argv[]) {
if (argc == 1) {
if (PORTP(argv[0])) {
scm_port_t port = (scm_port_t)argv[0];
scoped_lock lock(port->lock);
if (port->type == SCM_PORT_TYPE_SOCKET) {
try {
port_shutdown_output(port);
return scm_unspecified;
} catch (io_exception_t& e) {
raise_io_error(vm, "shutdown-output-port", e.m_operation, e.m_message, e.m_err, port, scm_false);
return scm_undef;
}
}
wrong_type_argument_violation(vm, "shutdown-output-port", 0, "socket port", argv[0], argc, argv);
return scm_undef;
}
wrong_type_argument_violation(vm, "shutdown-output-port", 0, "port", argv[0], argc, argv);
return scm_undef;
}
wrong_number_of_arguments_violation(vm, "shutdown-output-port", 1, 1, argc, argv);
return scm_undef;
}
void init_subr_port(object_heap_t* heap) {
#define DEFSUBR(SYM, FUNC) heap->intern_system_subr(SYM, FUNC)
DEFSUBR("port?", subr_port_pred);
DEFSUBR("input-port?", subr_input_port_pred);
DEFSUBR("output-port?", subr_output_port_pred);
DEFSUBR("close-port", subr_close_port);
DEFSUBR("eof-object", subr_eof_object);
DEFSUBR("eof-object?", subr_eof_object_pred);
DEFSUBR("current-input-port", subr_current_input_port);
DEFSUBR("current-output-port", subr_current_output_port);
DEFSUBR("current-error-port", subr_current_error_port);
DEFSUBR("standard-input-port", subr_standard_input_port);
DEFSUBR("standard-output-port", subr_standard_output_port);
DEFSUBR("standard-error-port", subr_standard_error_port);
DEFSUBR("flush-output-port", subr_flush_output_port);
DEFSUBR("output-port-buffer-mode", subr_output_port_buffer_mode);
DEFSUBR("set-port-current-line!", subr_set_port_current_line);
DEFSUBR("set-port-current-column!", subr_set_port_current_column);
DEFSUBR("port-device-subtype", subr_port_device_subtype);
DEFSUBR("native-transcoder-descriptor", subr_native_transcoder_descriptor);
DEFSUBR("port-transcoder-descriptor", subr_port_transcoder_descriptor);
DEFSUBR("extract-accumulated-bytevector", subr_extract_accumulated_bytevector);
DEFSUBR("get-accumulated-bytevector", subr_get_accumulated_bytevector);
DEFSUBR("extract-accumulated-string", subr_extract_accumulated_string);
DEFSUBR("get-accumulated-string", subr_get_accumulated_string);
DEFSUBR("make-string-output-port", subr_make_string_output_port);
DEFSUBR("make-string-input-port", subr_make_string_input_port);
DEFSUBR("open-script-input-port", subr_open_script_input_port);
DEFSUBR("make-file-input-port", subr_make_file_input_port);
DEFSUBR("make-file-output-port", subr_make_file_output_port);
DEFSUBR("make-temporary-file-port", subr_make_temporary_file_port);
DEFSUBR("open-port", subr_open_port);
DEFSUBR("nonblock-byte-ready?", subr_nonblock_byte_ready_pred);
DEFSUBR("get-char", subr_get_char);
DEFSUBR("lookahead-char", subr_lookahead_char);
DEFSUBR("port-has-port-position?", subr_port_has_port_position_pred);
DEFSUBR("port-position", subr_port_position);
DEFSUBR("port-has-set-port-position!?", subr_port_has_set_port_position_pred);
DEFSUBR("set-port-position!", subr_set_port_position);
DEFSUBR("port-eof?", subr_port_eof_pred);
DEFSUBR("get-u8", subr_get_u8);
DEFSUBR("get-byte", subr_get_byte);
DEFSUBR("lookahead-u8", subr_lookahead_u8);
DEFSUBR("lookahead-byte", subr_lookahead_byte);
DEFSUBR("get-bytevector-n", subr_get_bytevector_n);
DEFSUBR("get-bytevector-n!", subr_get_bytevector_n_ex);
DEFSUBR("get-bytevector-some", subr_get_bytevector_some);
DEFSUBR("get-bytevector-all", subr_get_bytevector_all);
DEFSUBR("get-string-n", subr_get_string_n);
DEFSUBR("get-string-n!", subr_get_string_n_ex);
DEFSUBR("get-string-all", subr_get_string_all);
DEFSUBR("get-line", subr_get_line);
DEFSUBR("get-datum", subr_get_datum);
DEFSUBR("put-u8", subr_put_u8);
DEFSUBR("put-byte", subr_put_byte);
DEFSUBR("put-bytevector", subr_put_bytevector);
DEFSUBR("put-char", subr_put_char);
DEFSUBR("put-string", subr_put_string);
DEFSUBR("put-datum", subr_put_datum);
DEFSUBR("put-fasl", subr_put_fasl);
DEFSUBR("display", subr_display);
DEFSUBR("write", subr_write);
DEFSUBR("newline", subr_newline);
DEFSUBR("peek-char", subr_peek_char);
DEFSUBR("read-char", subr_read_char);
DEFSUBR("write-char", subr_write_char);
DEFSUBR("read", subr_read);
DEFSUBR("make-transcoded-port", subr_make_transcoded_port);
DEFSUBR("set-current-input-port!", subr_set_current_input_port);
DEFSUBR("set-current-output-port!", subr_set_current_output_port);
DEFSUBR("set-current-error-port!", subr_set_current_error_port);
DEFSUBR("shutdown-output-port", subr_shutdown_output_port);
DEFSUBR("port-closed?", subr_port_closed_pred);
}
|
37b02574ae43a7fe60bf9a889b6fa8d685478991
|
5a34f38e1d0b6a925bb602383705f0e45b449dff
|
/summerCamp/2018/d1w1/h.cpp
|
e39a98aaaab5389764c518c407420cc4cd0ad04a
|
[] |
no_license
|
samuraiexx/competitiveProgramming
|
15fcbcf75114c80d112473e5ce9d69b9f33d5280
|
1862e381d0d7aecc0082f2416950cd18b26858d4
|
refs/heads/master
| 2021-06-10T20:53:39.039074
| 2019-03-25T01:02:21
| 2019-03-25T01:02:21
| 106,463,296
| 0
| 1
| null | 2019-10-20T21:18:08
| 2017-10-10T19:43:09
|
C++
|
UTF-8
|
C++
| false
| false
| 1,479
|
cpp
|
h.cpp
|
#include<bits/stdc++.h>
using namespace std;
#define st first
#define nd second
#define mp make_pair
#define pb push_back
#define db(x) cerr << #x << "==" << x << endl
#define dbs(x) cerr << x << endl
#define _ << ", " <<
typedef long long ll;
typedef long double ld;
typedef pair<int, int> pii;
typedef pair<int, pii> piii;
typedef pair<ll, ll> pll;
typedef vector<int> vi;
const int INF = 0x3f3f3f3f, MOD = 1e9+7, N = 1e2+5;
int m, n, xi, yi, xf, yf, p, q;
int vis[N][N], parx[N][N], pary[N][N];
int print(int x, int y, int cont) {
if(parx[x][y] != 0 and pary[x][y] != 0) {
print(parx[x][y], pary[x][y], cont+1);
}
else {
printf("%d\n", cont);
}
printf("%d %d\n", x, y);
}
int main() {
scanf("%d%d%d%d%d%d%d%d", &m, &n, &p, &q, &xi, &yi, &xf, &yf);
int dx[] = {p, p, q, q, -p, -p, -q, -q},
dy[] = {q, -q, p, -p, q, -q, p, -p};
queue<pii> q;
q.push(mp(xi, yi));
vis[xi][yi] = 1;
while(!q.empty()) {
int x = q.front().st, y = q.front().nd;
q.pop();
if(x == xf and y == yf) {
print(x, y, 0);
return 0;
}
for(int i=0; i<8; i++) {
int a = x+dx[i], b = y+dy[i];
if(a <= 0 or a > m or b <= 0 or b > n) continue;
if(vis[a][b]) continue;
q.push(mp(a, b));
parx[a][b] = x;
pary[a][b] = y;
vis[a][b] = 1;
}
}
printf("-1\n");
return 0;
}
|
7703af91dfe1390667a38f66f6427834f6d0fc0b
|
18e64b590476fc55e4fbbe9df9f6228c25e720ab
|
/Engine/Game.cpp
|
fbfdfeca2eec245434a0b880e36de99d1687a732
|
[] |
no_license
|
ammar-nasser/arkanoid
|
e9c707dfcfa0004792e2d028fb9753431bc93fe8
|
b4b1d964fe7d76e7a05d636fbcbaf9b5f610e18e
|
refs/heads/Arkanoid-master
| 2023-03-02T14:49:16.374189
| 2021-02-06T20:09:54
| 2021-02-06T20:09:54
| 335,603,382
| 2
| 0
| null | 2021-02-06T20:09:55
| 2021-02-03T11:32:13
|
C++
|
UTF-8
|
C++
| false
| false
| 2,816
|
cpp
|
Game.cpp
|
/******************************************************************************************
* Chili DirectX Framework Version 16.07.20 *
* Game.cpp *
* Copyright 2016 PlanetChili.net <http://www.planetchili.net> *
* *
* This file is part of The Chili DirectX Framework. *
* *
* The Chili DirectX Framework 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. *
* *
* The Chili DirectX Framework 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 The Chili DirectX Framework. If not, see <http://www.gnu.org/licenses/>. *
******************************************************************************************/
#include "MainWindow.h"
#include "Game.h"
Game::Game(MainWindow& wnd)
:
wnd(wnd),
gfx(wnd),
walls(Vec2(0.0f, 0.0f), Vec2(float(Graphics::ScreenWidth), float(Graphics::ScreenHeight))),
ball(Vec2(100.0f, 200.0f), Vec2(350.0f, 350.0f)),
pad(Vec2(500, 500), 50, 15),
hit_pad(L"Sounds\\arkpad.wav"),
hit_brick(L"Sounds\\arkbrick.wav"),
game_over(L"Sounds\\game_over.wav")
{
const Vec2 top_left = { brick_width, brick_height };
for (int y = 0; y < n_rows; y++)
{
const Color c = bricks_color[y%5];//5 is the number of colors in the arry bricks_color
for (int x = 0; x < n_column; x++)
{
bricks[y * n_column + x] = Brick(
am::Rectangle(Vec2(top_left.x + x * brick_width, top_left.y + y * brick_height), brick_width, brick_height), c);
}
}
}
void Game::Go()
{
gfx.BeginFrame();
UpdateModel();
ComposeFrame();
gfx.EndFrame();
}
void Game::UpdateModel()
{
if (!is_game_over)
{
const float dt = ft.Mark();
ball.update(dt);
pad.update(wnd.kbd, dt);
pad.is_collide_with_walls(walls);
if (pad.is_collide_with_ball(ball))
hit_pad.Play();
if (ball.is_collide_with_ground(walls))
{
is_game_over = true;
game_over.Play();
}
if (ball.is_collide_with_walls(walls) && !is_game_over)
hit_pad.Play();
for (Brick& brick : bricks)
{
if (brick.is_collide_with_ball(ball))
{
hit_brick.Play();
break;
}
}
}
}
void Game::ComposeFrame()
{
for (Brick& brick : bricks)
{
brick.draw(gfx);
}
if (!is_game_over)
{
ball.draw(gfx);
}
pad.draw(gfx);
}
|
823116c9c32b7ba812df9ca0e2d01472472e8c97
|
60441fc86dfbefacfa1e7bec9145d3b28a509d34
|
/Checkers_Client/Peers/Peers.cpp
|
16d772eb23650e2925e3d719f6019a5c4660cdf5
|
[] |
no_license
|
x64joxer/Checkers-New
|
30e274eb86fadebe3059145085db42a2907817e9
|
a59df8e712c8a615ccec67a5bd27edff1bfa49eb
|
refs/heads/master
| 2020-04-03T20:56:54.943165
| 2017-06-02T04:13:57
| 2017-06-02T04:13:57
| 52,630,082
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 28
|
cpp
|
Peers.cpp
|
../../Common/Peers/Peers.cpp
|
d4974c62d43750b0ba8158e5f787ac65008ef22b
|
f0a5c4ce1a1f74bd73fe0eb35a08385c8b4070e6
|
/C++/level1/Arviz.cpp
|
61c1335bd6b4fcaa497c828f5aa491495a913db3
|
[] |
no_license
|
pumpuidev/referencia
|
613fe4551f81459db63abed7f9b02c9f8efe1ddc
|
769789e3b3f126750c4bda6daa211f9d023e64f5
|
refs/heads/main
| 2023-03-02T05:21:02.883613
| 2021-02-15T01:49:24
| 2021-02-15T01:49:24
| 305,376,917
| 0
| 0
| null | null | null | null |
ISO-8859-2
|
C++
| false
| false
| 1,327
|
cpp
|
Arviz.cpp
|
//Feladat: Egy folyószakasz vízmagasságot mérnek.
//Adjuk meg az árvizes szakaszokat 800>i. mérés és 800<i+1 mérés
#include <iostream>
using namespace std;
const int maxN=100;
void beolvasas(int &N,int F[]);
void arviziSzakasz(const int N,const int F[],int &Db);
void kiiras(const int N,const int F[],const int Db);
int main()
{ int N;
int F[maxN]; // folyó vízmagasságai
int Db; // árvizi szakaszok darabszáma
cout<<"Arvizi szakaszok darabszama."<<endl<<endl;
beolvasas(N,F);
arviziSzakasz(N,F,Db);
kiiras(N,F,Db);
return 0;
}
void beolvasas(int &N,int F[]){
do{
cout<<"Hany szakaszon mertunk? (0.."<<maxN<<")";
cin>>N;
}while (!((N>=0)&&(N<=maxN))); //meresek szama csak nem negativ lehet
for (int i=0;i<N;++i){
cout<<i<<". szakasz magassaga (cm)";
cin>>F[i];
}
}
void arviziSzakasz(const int N,const int F[],int &Db){
Db=0;
for (int i=0;i<N-1;++i){
if ((F[i]<=800)&&(F[i+1]>800)){
Db=Db+1;
}
}
}
void kiiras(const int N,const int F[],const int Db){
cout<<"A mert magassagok..."<<endl;
for (int i=0;i<N;++i){
cout<<F[i]<<", ";
}
cout<<" Az arvizi szakaszok szama: "<<Db<<endl;
}
|
f196e9ba5ba907101f6b09aeee9abda2a7655ab9
|
7161fbb98007be442bdf905cd39ba09fd859b5cd
|
/Transformation.cpp
|
a53cb4e7d68ad7d9050612d10c2745f797c707f5
|
[] |
no_license
|
ruthra-kumar/usaco
|
521da827dada7257adc0e73cb022d113e3d6a5c0
|
b57f2c5e920f679c45a5cf380110dcb27dc33086
|
refs/heads/master
| 2021-01-19T03:17:07.764483
| 2019-04-08T02:56:22
| 2019-04-08T02:56:22
| 55,295,514
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,579
|
cpp
|
Transformation.cpp
|
#include <iostream>
#include <fstream>
#define MAXSIZE 10
using namespace std;
class matrix{
char **b=NULL;
int n;
public:
matrix(int sz):n{sz}{ //base initializer
b = new char*[n];
for(int i=0;i<n;++i) b[i] = new char[n];
}
matrix(const matrix &m){ //copy constructor
n = m.Size();
b = new char*[n];
for(int i=0;i<n;++i) b[i] = new char[n];
for(int i=0;i<n;++i){
for(int j=0;j<n;++j){
b[i][j] = m.Get(i,j);
}
}
}
void Set(int x,int y,char c){
b[x][y] = c;
}
char Get(int x,int y) const{
return b[x][y];
}
void Print(){
for(int i=0;i<n;++i){
for(int j=0;j<n;++j){
cout<<b[i][j];
}
cout<<endl;
}
}
int Size() const { return n; }
bool operator==(matrix y){
for(int i=0;i<n;++i){
for(int j=0;j<n;++j){
if(b[i][j] != y.Get(i,j)) return false;
}
}
return true;
}
~matrix(){
for(int i=0;i<n;++i) delete[] b[i];
}
};
matrix Rotate(matrix m){
int S = m.Size();
matrix x(S);
int i,j;
for(i=0;i<S;++i){
for(j=0;j<S;++j){
x.Set(j,(S-1-i),m.Get(i,j));
}
}
return x;
}
matrix Reflect(matrix m){
int S = m.Size();
matrix x(S);
int i,j;
for(i=0;i<S;++i){
for(j=0;j<S;++j){
x.Set(i,(S-j-1),m.Get(i,j));
}
}
return x;
}
int main(int argc,char *argv[]){
fstream fin("transform.in",ios::in),fout("transform.out",ios::out);
int N;
char ch;
fin>>N;
matrix before(N),after(N);
for(int i=0;i<N;++i){
for(int j=0;j<N;++j){
fin>>ch;
before.Set(i,j,ch);
}
}
for(int i=0;i<N;++i){
for(int j=0;j<N;++j){
fin>>ch;
after.Set(i,j,ch);
}
}
if(Rotate(before) == after){
cout<<1<<endl;
}
else if(Rotate(Rotate(before)) == after){
cout<<2<<endl;
}
else if(Rotate(Rotate(Rotate(before))) == after){
cout<<3<<endl;
}
else if(after == Reflect(before)){
cout<<4<<endl;
}
else if( (after == Rotate(Reflect(before)))
|| (after == Rotate(Rotate(Reflect(before))))
|| (after == Rotate(Rotate(Rotate(Reflect(before))))) ){
cout<<5<<endl;
}
else if(before == after){
cout<<6<<endl;
}
else{
cout<<7<<endl;
}
return 0;
}
|
6fc2634c8731489b853183683571e4d0cf71b62e
|
6f28c1657ad31c5c615fb4a7539cb909f505fa57
|
/trunk/Source/Components/Collision/CCollideable.h
|
e720a1d32be6d3ccbbd3edd341af9f78fd8299d1
|
[] |
no_license
|
BGCX067/falconfish-scd-svn-to-git
|
e094adcc2e9a922ba986ec367c101d489ab916ce
|
f4f9993dbbf4ac908f036e4bcd23b6710fe6b6bd
|
refs/heads/master
| 2021-01-13T00:56:29.780363
| 2015-12-28T14:36:25
| 2015-12-28T14:36:25
| 48,872,900
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,252
|
h
|
CCollideable.h
|
/************************************************************************
* Filename: CCollideable.h
* Mod. Date: 07/25/2011
* Mod. Initials: RN
* Author: Raymond W. Nieves
* Purpose: Encapsulates all collision code within a Behavior Object
************************************************************************/
#ifndef _CCOLLIDEABLE_H_
#define _CCOLLIDEABLE_H_
#include <D3dx9math.h>
#include "..\..\IComponent.h"
#include "..\..\Enums.h"
class CObject;
class CBVHNode;
//structures for various bounding volumes
//triangle
struct TTriangle
{
D3DXVECTOR3 tVert0;
D3DXVECTOR3 tVert1;
D3DXVECTOR3 tVert2;
D3DXVECTOR3 tNorm;
};
//Axis-aligned Bounding Box
struct TAABB
{
D3DXVECTOR3 cBoxMin;
D3DXVECTOR3 cBoxMax;
};
//Oriented Bounding Box
struct TOBB
{
D3DXVECTOR3 cCenterPoint; //center point of OBB
D3DXVECTOR3 tU[3]; //local x, y, and z axes
D3DXVECTOR3 tE; //positive halfwidth extents along each axes
};
//Sphere BV
struct TSphere
{
D3DXVECTOR3 cPosition;
float fRadius;
};
//Plane (not so much a BV, but it will represent a collideable surface such as a wall)
struct TPlane
{
D3DXVECTOR3 cPlaneNormal;
D3DXVECTOR3 cPlanePoint;
float fOffset;
};
//Line
struct TLine
{
D3DXVECTOR3 cLineStart;
D3DXVECTOR3 cLineEnd;
};
struct TRay
{
D3DXVECTOR3 cRayStart;
D3DXVECTOR3 cRayNormal;
};
class CCollideable : public IComponent
{
private:
//various bounding volumes, objects should only use the ones they need
/////////////////////////////////
// TOBB m_BVOBB;
// TPlane m_BVPlane;
// TLine m_BVLine;
// TFrustum m_BVFrustum;
/////////////////////////////////
int m_nBVType; //type of bounding volume
bool m_bWasChecked; //if the object was checked on the current frame
bool m_bIsStatic; //true if the object's position is static
bool m_bIsReactor; //true if the object causes a collision reaction or if objects pass through it
unsigned int m_nObjType; //object type
CBVHNode *m_cBVHNode; //bvh node where this object is located
CObject *m_cParent; //pointer to the object holding this
public:
//new collision volume, works for all shapes
//SPHERE - centerpoint - derp figure it out, localaxes = local x/y/z axes, m_fextents = radius
//AABB - centerpoint - (min+max)/2, local axes = local x/y/z, extents = halfwidth extents along each localaxes[]
//OBB - this definition is how an obb is best defined, pretty much the same as the aabb definition
//TRIANGLE - centerpoint = can be the center of the tri, local axes would be the tri verts, extents would be the normal
//PLANE - just define the way a triangle would be defined with this
//Line/Ray - centerpoint = start, local axes[0] would be the line direction or end point of segment, extents[0] would be the ray distance
D3DXVECTOR3 m_cCenterPoint;
D3DXVECTOR3 m_tLocalAxes[3];
D3DXVECTOR3 m_fExtents; //used as a radius for the 3 axes
//tunneling members
bool m_bNextFrameTunneling; //true if the next frame may have tunneling
D3DXVECTOR3 m_vPrevPos, m_vPrevNorm; //previous position, and the normal of the previous frame's collision
CObject* m_cTunneledObject; //object we may have tunneled through
//default constructor
CCollideable()
{
m_bWasChecked = false;
}
//constructor
CCollideable(int type) : m_nBVType(type)
{
}
//destructor
~CCollideable()
{
}
//initialize function
void Init(void);
//Accessors
bool GetStatic(void);
unsigned int GetFlags(void);
CObject* GetParent(void);
CBVHNode* GetBVHNode(void);
int GetBVType();
TAABB GetAABB();
TOBB GetOBB();
TSphere GetSphere();
TPlane GetPlane();
TLine GetLine();
bool GetWasChecked();
unsigned int GetObjType();
bool GetReactor();
//Mutators
void SetStatic(bool bstatic);
void SetFlags(unsigned int nflag);
void SetParent(CObject* cParent);
void SetWasChecked(bool bchecked);
void SetBVHNode(CBVHNode* cNode);
void SetBVType(int type);
void SetAABB(TAABB taabb);
void SetOBB(TOBB tobb);
void SetSphere(TSphere tsphere);
void SetPlane(TPlane tplane);
void SetLine(TLine tLine);
void SetObjType(unsigned int ntype);
void SetIsReactor(bool breact);
};
#endif
|
78972082b9a3d56d952e90208b31288715c3358e
|
820c61849a45ed69f3e4636e2d3f0486304b5d46
|
/Contest Participations/Brain Fry/c.cpp
|
616485c785217fd03cc6496998ed757e2dde1429
|
[] |
no_license
|
Tanmoytkd/programming-projects
|
1d842c994b6e2c546ab37a5378a823f9c9443c39
|
42c6f741d6da1e4cf787b1b4971a72ab2c2919e1
|
refs/heads/master
| 2021-08-07T18:00:43.530215
| 2021-06-04T11:18:27
| 2021-06-04T11:18:27
| 42,516,841
| 2
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 191
|
cpp
|
c.cpp
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while(t--) {
long double m;
cin >> m;
m = m*m/2.00;
cout << fixed << setprecision(2) << m << endl;
}
}
|
658d29a81fe29d9bdf466c3bf1d9a7c0580db2cc
|
5d3404096286830fab472bdf9f30842f0f13a6b6
|
/LeetCode/Medium/120.Triangle/main.cpp
|
560abe61e3919d347bd13372b8552b3196a98c2d
|
[] |
no_license
|
YeongjinOh/Algorithm-practice
|
0d4b2ed00e6eebc46667435c3fdc47f8fb1ae886
|
871428eed1158ef85ff31930588aaeb3d69661d2
|
refs/heads/master
| 2021-01-23T13:42:54.361325
| 2018-03-17T12:47:38
| 2018-03-17T12:47:38
| 54,641,868
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,292
|
cpp
|
main.cpp
|
class Solution {
public:
//////////////////////////////////////////////////////
// Solution 1) DP
// Time : O(n^2)
// Extra space : O(n^2) (if we can't change triangle)
//////////////////////////////////////////////////////
int minimumTotal(vector<vector<int>>& triangle) {
int n = triangle.size();
if (n == 0) return 0;
for (int i=n-2; i>=0; i--) {
for (int j=0; j<triangle[i].size(); j++) {
triangle[i][j] += min(triangle[i+1][j], triangle[i+1][j+1]);
}
}
return triangle[0][0];
}
//////////////////////////////////////////////////////
// Solution 2) DP
// Time : O(n^2)
// Extra space : O(n)
//////////////////////////////////////////////////////
int minimumTotal2(vector<vector<int>>& triangle) {
int n = triangle.size();
if (n == 0) return 0;
vector<int> minPath (n, 0);
for (int i=n-1; i>=0; i--) {
for (int j=0; j<triangle[i].size(); j++) {
minPath[j] = triangle[i][j] + min(minPath[j], minPath[j+1]);
}
}
return minPath[0];
}
};
|
72a7b21603c91a73a2890eecc88c006082558a3b
|
82a7a8ff8fcdc569dff4486710defdea1d2c2c75
|
/kernel.cpp
|
9179962fc731111587e99637403fec087950f983
|
[] |
no_license
|
nnductuan/My_OS
|
f8c29d2aa7b18816d387cbafe1498b56dab7a1bc
|
a28fbcd02108b27cba838f2f2db329a0f094fc87
|
refs/heads/master
| 2021-08-28T08:16:22.725879
| 2017-12-11T17:12:41
| 2017-12-11T17:12:41
| 113,762,846
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,059
|
cpp
|
kernel.cpp
|
#include "types.h"
#include "gdt.h"
#include "port.h"
#include "interrupts.h"
void printf(char* str){
static uint16_t* VideoMemory = (unsigned uint16_t*)0xb8000;
static uint8_t x, y;
for(int i = 0; str[i] != '\0'; i++){
switch (str[i]){
case '\n':
x=0;
y++;
break;
default:
VideoMemory[80*y+x] = (VideoMemory[80*y+x] & 0xFF00) | str[i];
x++;
break;
}
if(x >=80){
x = 0;
y++;
}
if(y >= 25){
for(uint8_t i = 0;i <= 80; i++)
for(uint8_t j = 0; j <= 80; j++)
VideoMemory[80*i+j] = (VideoMemory[80*i+j] & 0xFF00) | ' ';
x=0;
y=0;
}
}
}
extern "C" void kernelMain(void* mutiboot_structure, unsigned int magicnumber){
printf("Hello world! ");
GlobalDescriptorTable gdt;
InterruptManager interrupts(&gdt);
interrupts.Activate();
while(1);
}
|
7db5db761cfc938351089af5480324311e1674e6
|
d2f5e0b43885cd080a4c5026ce133e288482f8d0
|
/UVA/UVA_12247/Source.cpp
|
a197f17810683b37fba921d56082c9d68324ffda
|
[] |
no_license
|
tito-kimbo/Online-Judge-Solutions
|
fb0ea2f2b9d8724a4b1f914a8be02294f1664135
|
1207e95365fb6f2691de077beaf2cbe7f0724c11
|
refs/heads/master
| 2020-06-03T04:18:32.970773
| 2019-06-11T19:12:52
| 2019-06-11T19:12:52
| 191,435,206
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,041
|
cpp
|
Source.cpp
|
#include <algorithm>
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
bool solve() {
vector<int> princess(3), prince(2);
unordered_map<int, bool> used;
cin >> princess[0] >> princess[1] >> princess[2];
cin >> prince[0] >> prince[1];
used[princess[0]] = used[princess[1]] = used[princess[2]] =
used[prince[0]] = used[prince[1]] = true;
if (princess[0] == 0 && princess[1] == 0 && princess[2] == 0 &&
prince[0] == 0 && prince[1] == 0) {
return false;
}
sort(princess.begin(), princess.end());
sort(prince.begin(), prince.end());
int aux;
if (prince[1] > princess[2]) {
if (prince[0] > princess[2]) {
aux = 1;
}
else if (prince[0] > princess[1]) {
aux = princess[1] + 1;
} else {
aux = princess[2] + 1;
}
}
else {
if (prince[1] > princess[1] && prince[0] > princess[1]) {
aux = princess[1] + 1;
}
else {
aux = -1;
}
}
while (used[aux]) {
aux++;
}
if (aux > 52) aux = -1;
cout << aux << '\n';
return true;
}
int main() {
while (solve());
}
|
f3278e168cfa58ce68632b06a5ed1b0b63311417
|
98fd36b72994d0cddb993ceadcf9916d08ef2ff7
|
/code/cuckoo_hash_map.h
|
3dca691f4142b9e81ece589057a1469092731551
|
[] |
no_license
|
BensonQiu/ParaCuckooHash
|
7f775508444cdb331fc3823b5bb9a6711a6dedfd
|
819df27775b1c07f7b9655af689945c8e139a89b
|
refs/heads/master
| 2020-12-25T21:34:56.854674
| 2016-05-10T05:35:46
| 2016-05-10T05:35:46
| 55,447,523
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 529
|
h
|
cuckoo_hash_map.h
|
#ifndef CUCKOO_HASHMAP_H
#define CUCKOO_HASHMAP_H
template <typename T>
class CuckooHashMap {
public:
const int SLOTS_PER_BUCKET = 4;
const int MAX_ITERS = 500;
CuckooHashMap(int num_buckets=64);
~CuckooHashMap();
T get(std::string key);
void put(std::string key, T val);
private:
struct HashEntry {
std::string key;
T val;
};
HashEntry **m_table;
int m_num_buckets;
};
#include "cuckoo_hash_map.cpp"
#endif
|
e6c792d5ce179b9a7596a4cb5bb444f65fdbd907
|
614478aefc56e0d0c479c1bb68fdea18e10e963f
|
/Week_01/26.remove-duplicates-from-sorted-array.cpp
|
b8f30446def7c0425b388b196e91fb2f25d16026
|
[] |
no_license
|
lzlssg/algorithm008-class01
|
67742bff88e00c69a6c31af22b133eb5c9238b63
|
569912c5702a3af016b3b1f0326456b46e9195c4
|
refs/heads/master
| 2023-05-02T05:39:34.821327
| 2021-05-31T12:29:20
| 2021-05-31T12:29:20
| 255,243,966
| 0
| 0
| null | 2020-04-13T05:58:46
| 2020-04-13T05:58:46
| null |
UTF-8
|
C++
| false
| false
| 515
|
cpp
|
26.remove-duplicates-from-sorted-array.cpp
|
/*
* @lc app=leetcode id=26 lang=cpp
*
* [26] Remove Duplicates from Sorted Array
*/
// @lc code=start
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int len = nums.size();
if (len == 0)
{
return 0;
}
int i = 0,j = 0;
while (j < len)
{
if (nums[i] != nums[j])
{
nums[++i] = nums[j];
}
++j;
}
return i + 1;
}
};
// @lc code=end
|
80e9e1fc1fa8becaff3f89a629d6ef478efdc8df
|
5b5b8427c68b7304fd220c89c86832fbc51eded2
|
/Array/GetLargest_E.cpp
|
d263f04f229f91212595a053020466c2631dbc24
|
[] |
no_license
|
callmepranavv/DSA
|
95f6c7fad245aabd04baa23d57ea9fc35b1c7259
|
6605dd11e4ab583272030bfe33e7c4f3bdb07d27
|
refs/heads/main
| 2023-08-03T17:24:47.945383
| 2021-09-19T01:01:42
| 2021-09-19T01:01:42
| 376,510,351
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 588
|
cpp
|
GetLargest_E.cpp
|
#include<iostream>
using namespace std;
int GetMinMax(int arr[] , int n)
{
int res = 0,res1=0;
for(int i = 1 ; i < n ; i++){
if (arr[i] > arr[res])
res = i;
if (arr[i] < arr[res1])
res1 = i;
}
cout<<"Largest Number is:->"<<arr[res]<<endl<<"Smallest Number is:->"<<arr[res1]<<endl;
return 0;
}
int main()
{
int n;
cout<<"Enter the size of Array\n";
cin>>n;
int arr[n];
cout<<"Enter the Values in Array\n";
for(int i = 0 ; i < n ; i++)
cin>>arr[i];
GetMinMax(arr,n);
//cout<<"Smallest Number in Array is:-"<< GetSmallest(arr,n);
//cout << endl;
return 0;
}
|
5e5da3432160bb93e45f4082f491bb9634619f88
|
4828e4af2a8d96e708e6127b21abcf9da57945b2
|
/Arduino/testing/components/home/home.ino
|
4311da009cb14e6fe03b73dd088e50f85a83705c
|
[] |
no_license
|
M-Hawkins/M3-LS_Micromanipulator
|
9f8861a6aeb869fdfa1f49ba4b0dd33bc56eec6a
|
eaec87f37625c6aa8c428f19d55ae16a58d10917
|
refs/heads/master
| 2021-01-09T20:21:54.602559
| 2017-04-20T19:57:55
| 2017-04-20T19:57:55
| 81,275,061
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,714
|
ino
|
home.ino
|
#include "M3LS.h"
int xpin = 2;
int ypin = 3;
int zpin = 4;
int xjoystickPin = A5;
int yjoystickPin = A6;
int zjoystickPin = A7;
int homeCounter = 0;
M3LS *myM3LS;
void setup(){
Serial.begin(9600);
Serial.println("Testing M3LS Joystick movement");
myM3LS = new M3LS(xpin, ypin, zpin);
Serial.println("Done instantiating M3LS");
pinMode(xjoystickPin, INPUT);
pinMode(yjoystickPin, INPUT);
pinMode(zjoystickPin, INPUT);
myM3LS->setControlMode(M3LS::open);
myM3LS->setControlMode(M3LS::position);
}
void loop(){
homeCounter++;
if (homeCounter == 200){
myM3LS->getCurrentPosition();
Serial.println("\n\n\nSetting home position to:");
Serial.println(myM3LS->currentPosition[0]);
Serial.println(myM3LS->currentPosition[1]);
Serial.println(myM3LS->currentPosition[2]);
myM3LS->setHome();
Serial.println("\nActual Home");
Serial.println(myM3LS->homePosition[0]);
Serial.println(myM3LS->homePosition[1]);
Serial.println(myM3LS->homePosition[2]);
}
if (homeCounter > 400){
myM3LS->returnHome();
delay(1000);
myM3LS->getCurrentPosition();
Serial.println("\nReturned to:");
Serial.println(myM3LS->currentPosition[0]);
Serial.println(myM3LS->currentPosition[1]);
Serial.println(myM3LS->currentPosition[2]);
homeCounter = 0;
} else {
int nextPosx = map((1023 - analogRead(xjoystickPin))/8, 0, 127, 500, 11500);
int nextPosy = map((1023 - analogRead(yjoystickPin))/8, 0, 127, 500, 11500);
int nextPosz = map(analogRead(zjoystickPin)/8, 0, 127, 500, 11500);
myM3LS->updatePosition(nextPosx, nextPosy, nextPosz);
}
delay(100);
}
|
0648de6e6b4bb54391ee121795d5f41c6c1f7457
|
9d963319678fcd4930c8a0b2f29e2dd7575ca5c3
|
/ArcGISRuntimeSDKQt_CppSamples_Widgets/DisplayInformation/BuildLegend/BuildLegend.h
|
e4e30da5ee25e2259ce8e13bdd394567394cc0a1
|
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
Gela/arcgis-runtime-samples-qt
|
a9ed563fe1b483c3fdb593e423955f45194b1304
|
1fe287ebd2ee887e708c22d620b3f28107d62e85
|
refs/heads/main
| 2023-08-03T06:20:11.722313
| 2021-08-25T21:35:42
| 2021-08-25T21:35:42
| 402,888,991
| 2
| 0
|
Apache-2.0
| 2021-09-03T20:21:22
| 2021-09-03T20:21:22
| null |
UTF-8
|
C++
| false
| false
| 1,176
|
h
|
BuildLegend.h
|
// [WriteFile Name=GORenderers, Category=DisplayInformation]
// [Legal]
// Copyright 2018 Esri.
// 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.
// [Legal]
#ifndef BUILDLEGEND_H
#define BUILDLEGEND_H
namespace Ui
{
class BuildLegend;
}
namespace Esri
{
namespace ArcGISRuntime
{
class Map;
class MapGraphicsView;
}
}
#include <QWidget>
class BuildLegend : public QWidget
{
Q_OBJECT
public:
explicit BuildLegend(QWidget* parent = nullptr);
~BuildLegend() override;
private:
void addLayers();
Esri::ArcGISRuntime::Map* m_map = nullptr;
Esri::ArcGISRuntime::MapGraphicsView* m_mapView = nullptr;
Ui::BuildLegend* m_ui = nullptr;
};
#endif // BUILDLEGEND_H
|
b6ff3b7d53186ab07ea7bd46cd8a156203425a90
|
8e5d3e0cf1bb293e9e85c9c13c87798f80f18e51
|
/kameleon-plus/trunk/kameleon-plus-working/src/ccmc/pyreaders/testVirtual.cpp
|
2aab4fa8855ed169f7777b05d34e72044161459c
|
[] |
no_license
|
ccmc/ccmc-software
|
8fc43f9fa00e44d0b4a212c1841d574a9eaf3304
|
0e2fb90add626f185b0b71cdb9a7b8b3b5c43266
|
refs/heads/master
| 2021-01-17T03:58:07.261337
| 2018-04-04T15:22:37
| 2018-04-04T15:22:37
| 40,681,189
| 10
| 7
| null | 2015-08-13T20:51:18
| 2015-08-13T20:51:18
| null |
UTF-8
|
C++
| false
| false
| 2,278
|
cpp
|
testVirtual.cpp
|
#include <boost/python.hpp>
using std::string;
using namespace boost::python;
namespace ccmc
{
class Base
{
public:
virtual string foo() const = 0; //pure virtual method
virtual string foo(int a) const = 0;
string fooBase() const { return foo(); }
// string fooBase(int a) const { return foo(a); }
};
}
class BaseWrapper: public ccmc::Base, public wrapper<ccmc::Base>
{
public:
string fooBar() const {
std::cout << "fooBar calling overide with no args" << std::endl;
return this->get_override("foo")();
}
string foo() const {
std::cout << "calling overide with no args" << std::endl;
return this->get_override("foo")();
}
string foo(int a) const {
std::cout << "calling override with int" << std::endl;
return this->get_override("foo")(a);
}
};
// // Base member function pointers
string (ccmc::Base::*foo1)() const = &ccmc::Base::foo;
string (ccmc::Base::*foo2)(int) const = &ccmc::Base::foo;
string (BaseWrapper::*foobar1)() const = &BaseWrapper::fooBar;
// string (BaseWrapper::*foo3)() const = &BaseWrapper::foo;
// string (BaseWrapper::*foo4)(int) const = &BaseWrapper::foo;
string (ccmc::Base::*foobase1)() const = &ccmc::Base::fooBase;
// string (ccmc::Base::*foobase2)(int) const = &ccmc::Base::fooBase;
struct X
{
bool f(int a)
{
return true;
}
bool f(int a, double b)
{
return true;
}
bool f(int a, double b, string c)
{
std::cout << "called f with " << a << ' ' << b<< ' ' << c << std::endl;
return true;
}
int f(int a, int b, int c)
{
return a + b + c;
};
};
bool (X::*fx1)(int) = &X::f;
bool (X::*fx2)(int, double) = &X::f;
bool (X::*fx3)(int, double, string)= &X::f;
int (X::*fx4)(int, int, int) = &X::f;
BOOST_PYTHON_MODULE(Baz){
class_<BaseWrapper,boost::noncopyable>("Base")
.def("foo",pure_virtual(foo1))
.def("foo",pure_virtual(foo2))
// .def("foo",foo3)
// .def("foo",foo4)
.def("fooBar", foobar1)
.def("fooBase",foobase1)
// .def("fooBase",foobase2)
;
class_<X,boost::noncopyable>("X")
.def("f", fx1)
.def("f", fx2)
.def("f", fx3)
.def("f", fx4)
;
}
|
990b59ca80b67ca2e31d67cb8a43361d590a450e
|
59b8e01374417f0e4030c710a57cd3e14911390c
|
/FlipGame/gridboard.cpp
|
7e94435a55b7a1e52a62cadc13d73200c25825ea
|
[] |
no_license
|
wfyaibaib/FlipGame
|
501051f8c0fa8e838a59dd5b3dc8aff76e1eb836
|
3cdc01251858e2f9eab8f0d55699f2d8e9385e07
|
refs/heads/master
| 2016-09-05T16:44:51.961629
| 2013-08-14T10:35:30
| 2013-08-14T10:35:30
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,348
|
cpp
|
gridboard.cpp
|
#include "gridboard.h"
#include "ui_gridboard.h"
GridBoard::GridBoard(QWidget *parent) :
QWidget(parent),
ui(new Ui::GridBoard)
{
ui->setupUi(this);
int rowcnt = ui->gridLayout->rowCount();
int colcnt = ui->gridLayout->columnCount();
for (int i = 0; i < rowcnt; ++i)
for (int j = 0; j < colcnt; ++j)
{
connect(itemAt(i,j), SIGNAL(clicked()),
itemAt(i, j), SLOT(flip()));
if (i > 0)// up
{
connect(itemAt(i, j), SIGNAL(clicked()),
itemAt(i - 1, j), SLOT(flip()));
}
if (j > 0)// left
{
connect(itemAt(i, j), SIGNAL(clicked()),
itemAt(i, j - 1), SLOT(flip()));
}
if (j < colcnt - 1)// right
{
connect(itemAt(i, j), SIGNAL(clicked()),
itemAt(i, j + 1), SLOT(flip()));
}
if (i < rowcnt - 1)// down
{
connect(itemAt(i, j), SIGNAL(clicked()),
itemAt(i + 1, j), SLOT(flip()));
}
}
}
GridBoard::~GridBoard()
{
delete ui;
}
FlipButton *GridBoard::itemAt(int row, int col)
{
return static_cast<FlipButton*>(ui->gridLayout->itemAtPosition(row, col)->widget());
}
|
4943152babb0ffec16690d6cb02410b691c67718
|
dff1c58789b80ef1453ee260f0349d29bc1fd0fc
|
/src/detection_3d_visualizer_node.cpp
|
2b51d16e4c1d986f9898686e5371741e552584c3
|
[] |
no_license
|
OUXT-Polaris/vision_msgs_visualization
|
8b40164928c3e876ff51e402d10bfc077f88967b
|
8d2a4a767e00fae48559f12fcc1fdd17c8189ff9
|
refs/heads/master
| 2020-05-22T03:33:35.803659
| 2019-09-19T00:44:56
| 2019-09-19T00:44:56
| 186,214,609
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 382
|
cpp
|
detection_3d_visualizer_node.cpp
|
// headers for ros
#include <ros/ros.h>
// headers in this package
#include <vision_msgs_visualization/detection_3d_visualizer.h>
int main(int argc, char *argv[])
{
ros::init(argc, argv, "detection_3d_visualizer_node");
ros::NodeHandle nh;
ros::NodeHandle pnh("~");
Detection3DVisualizer visualizer = Detection3DVisualizer(nh,pnh);
ros::spin();
return 0;
}
|
b9a33d12e1c12df017b7ae69314d896181338313
|
f5cb39a50f462b7d9a50f520d21094db46db61fd
|
/source/pancake.cc
|
81acc06131aeb49588821402f37462f2f246296b
|
[] |
no_license
|
radekmie/shiny-pancake
|
706034c0182749a984e95483c5f7215cd5a9046b
|
69df8422caacdacfd07694cbb1bc8c6e9c0bbc4f
|
refs/heads/master
| 2021-01-11T08:41:06.922605
| 2016-12-20T16:37:15
| 2016-12-20T16:37:15
| 76,674,145
| 0
| 3
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 450
|
cc
|
pancake.cc
|
#include "GameObject.hpp"
#include "Simulate.hpp"
#include <memory>
#include <node.h>
#include <v8.h>
void getData(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::Isolate* isolate = args.GetIsolate();
auto result = simulate(isolate, args[0]->NumberValue());
args.GetReturnValue().Set(result);
}
void init(v8::Local<v8::Object> exports) {
initWorld();
NODE_SET_METHOD(exports, "getData", getData);
}
NODE_MODULE(pancake, init);
|
1ce03655a498b436a9f563e871a70dd77942f263
|
de5bbebd0b6c83f76bd65fc8984c5bb2154d8446
|
/2020-2021/opencv/01/cv.cpp
|
c0a5396572c89593ab5bbd63ac15ddb56c38231d
|
[
"MIT"
] |
permissive
|
pantadeusz/examples-ai
|
5760f812de6112c2d66924160b35eef89b823300
|
7529242eb47123dd948d13eb44c5a28d225d11b9
|
refs/heads/master
| 2023-01-24T03:02:28.022307
| 2023-01-18T11:36:34
| 2023-01-18T11:36:34
| 90,629,458
| 3
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,214
|
cpp
|
cv.cpp
|
#include <opencv2/opencv.hpp>
#include <opencv2/highgui.hpp>
#include <iostream>
#include <vector>
// g++ `pkg-config --cflags opencv4` cv.cpp `pkg-config --libs opencv4`
using namespace std;
using namespace cv;
int main(int argc, char **argv)
{
VideoCapture cap1(0);
if (!cap1.isOpened())
return -1;
namedWindow("1", WINDOW_AUTOSIZE);
int range = 0;
createTrackbar("range", "1", &range, 255);
while (true)
{
Mat f1, small_img, thr,thr_a, small_hsv;
cap1 >> f1;
resize(f1,small_img,{320,320});
putText(f1, to_string(range), {10, 30}, FONT_HERSHEY_PLAIN, 1.0, {0, 255, 0, 255});
imshow("1", f1);
cvtColor(small_img,small_hsv,COLOR_BGR2HSV);
cvtColor(small_img,small_img,COLOR_BGR2GRAY);
imshow("small", small_img);
imshow("small_hsv", small_hsv);
threshold(small_img,thr,128.0,255.0,0);
adaptiveThreshold(small_img,thr_a,255.0, ADAPTIVE_THRESH_GAUSSIAN_C,0,3,range/255.0);
imshow("thr_a", thr_a);
dilate(thr_a,thr_a, getStructuringElement(MORPH_ELLIPSE, {3,3}));
imshow("thr_a_dil", thr_a);
char k = waitKey(1);
if (k == 27)
break;
if (k == 's')
{
auto r = selectROI("small_hsv", small_hsv);
Mat roi = f1(r);
imshow("ROI", roi);
}
}
return 0;
}
|
1fc8d40b75d73e79da470f41c382fff7fed34bbf
|
67edf71151cf12e6a0ab092741623842f7dbd490
|
/firmware/Magic_8_ball/Magic_8_ball.ino
|
eb8ac899c1e4bbac7ad2946e7a930efc15386f23
|
[
"MIT"
] |
permissive
|
platisd/dialectic-ball
|
c79085b79f701a58552447aee70539726d1d60cf
|
670c791aaca9cd13c13acce2415db578768c6d74
|
refs/heads/master
| 2020-03-18T20:57:24.098235
| 2018-11-12T13:38:55
| 2018-11-12T13:38:55
| 135,249,286
| 5
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 10,517
|
ino
|
Magic_8_ball.ino
|
#include <Nokia_LCD.h>
#include <avr/sleep.h>
#include <avr/power.h>
#include <avr/wdt.h>
#include <avr/interrupt.h>
#include <avr/pgmspace.h>
#include <stdint.h>
#include "bitmaps.hpp"
#include "tips.hpp"
enum WatchDogTimeout {
WDT_16ms = 0,
WDT_32ms,
WDT_64ms,
WDT_128ms,
WDT_250ms,
WDT_500ms,
WDT_1sec,
WDT_2sec,
WDT_4sec,
WDT_8sec
};
enum RunningState {
// Ball facing down for long amount of time
// Screen is off
// Slow check of accelerometer for changes
DEEP_SLEEP,
// Ball facing up
// Screen is on - Waiting display
// Fast check of accelerometer for changes
IDLE_SCREEN,
// Ball facing up
// Screen is on - Game views
// Faster check of accelerometer for changes
PLAYING,
};
const uint8_t V_ACC_PIN = 8; // PB2
const uint8_t CLK_PIN = 9; // PB1
const uint8_t V_DIS_PIN = 10; // PB0
const uint8_t X_OUT_PIN = A7; // PA7
const uint8_t Y_OUT_PIN = A6; // PA6
const uint8_t Z_OUT_PIN = A5; // PA5
const uint8_t RST_PIN = 4; // PA4
const uint8_t DIN_PIN = 3; // PA3
const uint8_t CE_PIN = 2; // PA2
const uint8_t DC_PIN = 1; // PA1
const uint8_t LED_PIN = 0; // PA0
// Input & output pins directly controlled in this scope
const uint8_t OUTPUT_PINS[] = {V_ACC_PIN, V_DIS_PIN, LED_PIN};
const uint8_t INPUT_PINS[] = {X_OUT_PIN, Y_OUT_PIN, Z_OUT_PIN};
const uint8_t LCD_DATA_PINS[] = {CLK_PIN, DIN_PIN, DC_PIN, CE_PIN, RST_PIN};
// The experimentally determined Z-axis value over which we consider
// ourselves to be facing up
const unsigned int MIN_FACING_UP_THRESHOLD = 470;
// The minimum acceleration delta (on X,Y,Z axes) to be considered as a movement
// The smaller the number the easier a "movement" will be registered
const unsigned int MOVEMENT_ACCELERATION_THRESHOLD = 25; // Experimentally determined
// The amount of detected movements needed to start a game
const uint8_t AMOUNT_OF_MOVEMENTS_THRESHOLD = 5;
// How much to wait before using the accelerometer in milliseconds
const unsigned long ACCELEROMETER_BOOTUP_TIME = 15;
// Sleep duration while in DEEP_SLEEP mode
const unsigned long DEEP_SLEEP_INTERVAL = 1000;
// Sleep duration while in IDLE_SCREEN mode
const unsigned long IDLE_SCREEN_INTERVAL = 100;
// Sleep duration while in PLAYING mode
const unsigned long TIP_INTERVAL = 2500;
const uint8_t TIPS_LENGTH = 50; // The tips' max length in characters
const unsigned long EIGHTBALL_SLEEP = 500; // How long to display the 8ball logo in milliseconds
volatile bool watchdogBarked = false;
Nokia_LCD lcd(CLK_PIN /* CLK */, DIN_PIN /* DIN */, DC_PIN /* DC */, CE_PIN /* CE */, RST_PIN /* RST */);
RunningState currentState = DEEP_SLEEP;
unsigned int amountOfMovements = 0;
int previousAcceleration = 0;
bool justWokeUp = true; // A flag to indicate whether the screen is turning on just now
/**
Watchdog interrupt routine to be triggered when watchdog times out.
*/
ISR(WDT_vect) {
watchdogBarked = true;
}
/**
Sets up watchdog to be triggered (once) after the specified time
@param wdt the watchdog timeout duration
*/
void triggerWatchDogIn(WatchDogTimeout wdt) {
// Adopted from InsideGadgets (www.insidegadgets.com)
byte timeoutVal = wdt & 7;
if (wdt > 7) {
timeoutVal |= (1 << 5);
}
timeoutVal |= (1 << WDCE);
MCUSR &= ~(1 << WDRF);
WDTCSR |= (1 << WDCE) | (1 << WDE); // Start timed sequence
WDTCSR = timeoutVal;
WDTCSR |= _BV(WDIE);
wdt_reset(); // Pat the dog
}
/**
A utility method to derive a watchdog timeout's duration
@param wdt the watchdog timeout
@return the amount of milliseconds corresponding to a watchdog timeout
*/
unsigned long getTimeoutDuration(WatchDogTimeout wdt) {
return 1 << (wdt + 4);
}
void goToSleep() {
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
power_all_disable ();
sleep_enable();
sleep_cpu(); // Sleep here and wait for the interrupt
sleep_disable();
power_all_enable(); // power everything back on
}
/**
Blocks and stays in deep sleep until the specified time has elapsed
using the current watchdog timeout.
@param sleepDuration how long to stay in deep sleep in milliseconds
@param timeoutInterval the watchdog timeout interval
*/
void stayInDeepSleepFor(unsigned long sleepDuration, WatchDogTimeout timeoutInterval = WDT_16ms) {
unsigned long sleepTime = 0;
// Start by triggering the watchdog to wake us up every `timeoutInterval`
triggerWatchDogIn(timeoutInterval);
while (sleepTime <= sleepDuration) {
// Sleep until an interrupt occurs (external, change or watchdog)
goToSleep();
// Verify we woke up because of the watchdog and not
// a spurious wake up due to some other unrelated interrupt.
if (watchdogBarked) {
// Note down that we have processed the watchdog bark
watchdogBarked = false;
// Increase the time we have already slept
sleepTime += getTimeoutDuration(timeoutInterval);
}
}
wdt_disable(); // Disable watchdog so it stops barking
}
/*** Helper functions ***/
void turnScreenOn() {
digitalWrite(V_DIS_PIN, HIGH);
}
void turnScreenOff() {
digitalWrite(V_DIS_PIN, LOW);
for (auto pin : LCD_DATA_PINS) {
digitalWrite(pin, LOW);
}
}
void turnBacklightOn() {
digitalWrite(LED_PIN, LOW);
}
void turnBacklightOff() {
digitalWrite(LED_PIN, HIGH);
}
void turnAccelerometerOn() {
// Accelerometer needs some few milliseconds to get ready
// so we need to make sure that we give it this time
digitalWrite(V_ACC_PIN, HIGH);
stayInDeepSleepFor(ACCELEROMETER_BOOTUP_TIME, WDT_16ms); // Give the accelerometer some time to boot
enableADC();
}
void turnAccelerometerOff() {
disableADC();
digitalWrite(V_ACC_PIN, LOW);
}
unsigned int getAccelerationX() {
return analogRead(X_OUT_PIN);
}
unsigned int getAccelerationY() {
return analogRead(Y_OUT_PIN);
}
unsigned int getAccelerationZ() {
return analogRead(Z_OUT_PIN);
}
unsigned int getAccelerationXYZ() {
return getAccelerationX() + getAccelerationY() + getAccelerationZ();
}
void disableADC() {
ADCSRA &= ~(1 << ADEN);
}
void enableADC() {
ADCSRA |= (1 << ADEN);
}
bool isFacingUp() {
return getAccelerationZ() >= MIN_FACING_UP_THRESHOLD;
}
/*** Helper functions ***/
void setup() {
// Set pin directions
for (auto pin : INPUT_PINS) {
pinMode(pin, INPUT);
}
for (auto pin : OUTPUT_PINS) {
pinMode(pin, OUTPUT);
}
// Disable digital pin buffers for analog pins
// to save some power, since we are doing only analog readings
bitSet(DIDR0, ADC5D); // Disable digital buffer on A5
bitSet(DIDR0, ADC6D); // Disable digital buffer on A6
bitSet(DIDR0, ADC7D); // Disable digital buffer on A7
turnBacklightOff();
}
void loop() {
switch (currentState) {
case DEEP_SLEEP:
{
turnAccelerometerOn();
// Store whether it is facing up in a variable
// so we can turn the accelerometer off right away
// before printing to the screen or sleeping more
bool facingUp = isFacingUp();
turnAccelerometerOff();
if (facingUp) {
// Prepare the transition to the IDLE_SCREEN state
currentState = IDLE_SCREEN;
// Prepare the screen
turnScreenOn();
lcd.begin();
lcd.setContrast(60);
// If we just woke up, display the 8-ball logo to the user
if (justWokeUp) {
justWokeUp = false;
lcd.draw(eightball, sizeof(eightball) / sizeof(unsigned char));
stayInDeepSleepFor(EIGHTBALL_SLEEP, WDT_500ms);
lcd.clear();
} else {
lcd.clear(); // Clear the screen for the upcomming prompt
}
lcd.draw(ask_question, sizeof(ask_question) / sizeof(unsigned char));
lcd.setCursor(3, 5); // Set the cursor to the start of the progress bar
lcd.draw(left_side_bar, sizeof(left_side_bar) / sizeof(unsigned char));
// Initialize the movement related variables
amountOfMovements = 0;
turnAccelerometerOn();
previousAcceleration = getAccelerationXYZ(); // Get some initial measurement
turnAccelerometerOff();
} else {
turnScreenOff();
stayInDeepSleepFor(DEEP_SLEEP_INTERVAL, WDT_1sec);
justWokeUp = true;
}
}
break;
case IDLE_SCREEN:
{
stayInDeepSleepFor(IDLE_SCREEN_INTERVAL, WDT_32ms);
// Check for movements
// Calculate the current delta in acceleration
turnAccelerometerOn();
int currentAcceleration = getAccelerationXYZ();
turnAccelerometerOff();
int accelerationDelta = currentAcceleration - previousAcceleration;
previousAcceleration = currentAcceleration;
// Determine whether the current difference in acceleration constitutes a movement
// and whether we need to transist to a different state
if (abs(accelerationDelta) >= MOVEMENT_ACCELERATION_THRESHOLD) {
if (++amountOfMovements >= AMOUNT_OF_MOVEMENTS_THRESHOLD) {
currentState = PLAYING;
}
// Print out visual feedback/affirmation for the user's movement
lcd.draw(progress_bar, sizeof(progress_bar) / sizeof(unsigned char));
} else {
// If there hasn't been any movement, check to see if we are facing down therefore
// should go to sleep
turnAccelerometerOn();
bool facingUp = isFacingUp();
turnAccelerometerOff();
if (!facingUp) {
currentState = DEEP_SLEEP;
}
}
}
break;
case PLAYING:
{
lcd.clear();
// Display a very helpful message to the user
// Randomly select a helpful tip
randomSeed(previousAcceleration + millis());
uint8_t randomTip = random(0, AMOUNT_OF_TIPS);
// Read the tip from flash memory
char tipsBuffer[TIPS_LENGTH];
strcpy_P(tipsBuffer, (char*)pgm_read_word(&(TIPS[randomTip])));
// Place a null terminator in the end just to be safe
tipsBuffer[TIPS_LENGTH - 1] = '\0';
lcd.print(tipsBuffer);
// Draw a text-face under the tip to make it more appealing 乁( ◔ ౪◔)「
uint8_t randomFace = random(0, NUM_OF_FACES);
// Print the face on the last two rows (make sure not to overlay the text)
lcd.setCursor(0, 4);
lcd.draw(pgm_read_ptr_near(&(FACES[randomFace])), FACE_SIZE);
stayInDeepSleepFor(TIP_INTERVAL, WDT_1sec);
currentState = DEEP_SLEEP;
}
break;
default:
break;
}
}
|
5ff2c65a0179f776e8cfe4f3b419d76d17ca77a9
|
8016aff531962cf0cfe742415309b2af9517bd57
|
/PCDanmakuFlameMaster/utilities/StringUtils.hpp
|
911ce3c5077da0307096dc23874ca362a4f12cfa
|
[
"Apache-2.0"
] |
permissive
|
CalvinNeo/PCDanmakuFlameMaster
|
fd5580460c0ca876aeefb52469786278836b8f67
|
d39a81472341cbceb28e1f2f1e9e4adf68061e89
|
refs/heads/master
| 2020-04-06T11:32:37.458205
| 2015-01-05T06:00:27
| 2015-01-05T06:00:27
| 29,225,565
| 1
| 0
| null | 2015-01-14T03:34:41
| 2015-01-14T03:34:41
| null |
UTF-8
|
C++
| false
| false
| 1,823
|
hpp
|
StringUtils.hpp
|
/**
* @file StringUtils.hpp
* @brief ...
* @author zheng qian <xqq@0ginr.com>
* @date 2014-12-06
*/
#ifndef _PCDFM_UTILS_STRING_UTILS_HPP
#define _PCDFM_UTILS_STRING_UTILS_HPP
#include <string>
#include <vector>
#include <algorithm>
namespace PCDanmakuFlameMaster {
namespace util {
namespace StringUtils {
static inline std::vector<std::string> splitString(const char* input, char delimiter) {
std::vector<std::string> fragments;
while (auto next = strchr(input, delimiter)) {
fragments.push_back(std::string(input, next));
input = next + 1;
}
fragments.push_back(std::string(input));
return fragments;
}
static inline std::vector<std::string> splitString(const char* input, const char* delimiterString) {
std::vector<std::string> fragments;
// TODO
return std::vector<std::string>();
}
static inline std::string trim(std::string input) {
input.erase(std::remove_if(input.begin(), input.end(), isspace), input.end());
return input;
}
static inline void trim_in_situ(std::string& input) {
input.erase(std::remove_if(input.begin(), input.end(), isspace), input.end());
}
static inline bool startsWith(std::string& input, const char* what) {
return (input.find(what) == 0);
}
static inline bool startsWith(std::string& input, std::string& what) {
return (input.find(what) == 0);
}
static inline bool endsWith(std::string& input, const char* what) {
return (input.rfind(what) == input.length() - strlen(what));
}
static inline bool endsWith(std::string& input, std::string& what) {
return (input.rfind(what) == input.length() - what.length());
}
}
}
}
#endif // _PCDFM_UTILS_STRING_UTILS_HPP
|
4ccce0c14d3bf730d31b9536f88290fa688d9a1f
|
05980d569d9d099789f94fff165238d0192151e5
|
/libraries/VDG_Mod/LedFlash.cpp
|
8cdb1f4c26deaa47f2d4b56359daf63ef2b4a1bd
|
[] |
no_license
|
Den-W/WebOutlet
|
e543740047f0b681be1f78d8c2c0b66209812254
|
17be9976b8ae8b4976c1b887028da956e35cef72
|
refs/heads/master
| 2021-01-22T22:16:31.499257
| 2018-02-23T12:44:13
| 2018-02-23T12:44:13
| 92,767,024
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 709
|
cpp
|
LedFlash.cpp
|
/* Copyright (C) 2017 Vidyakin Denis Georgievich. All rights reserved.
*
* This software may be distributed and modified freely.
*/
#include <Arduino.h>
#include "VDG_Mod.h"
void VM_LedFlash( byte Pin, byte No, short MsLight, short MsDark )
{ pinMode( Pin, OUTPUT );
for( int i=0; i<No; i++ )
{ digitalWrite( Pin, HIGH );
delay( MsLight );
digitalWrite( Pin, LOW );
delay( MsDark );
}
}
void VM_Led13Flash( byte No, short MsLight, short MsDark )
{ for( int i=0; i<No; i++ )
{ pinMode( LED_BUILTIN, OUTPUT );
digitalWrite( LED_BUILTIN, HIGH );
delay( MsLight );
pinMode( LED_BUILTIN, INPUT );
digitalWrite( LED_BUILTIN, LOW );
delay( MsDark );
}
}
|
6f44253fdffea3c836966405496a39b4ccd39b92
|
0b335ed5c4a5c6686ed874845e3bc87e43b82a44
|
/software/SpMVAcceleratorBufferAllDriver.hpp
|
378417b37e348e8849de7903338f7ba7926ccdb0
|
[] |
no_license
|
hoangt/spmv-vector-cache
|
19a7d691a529603fd065722c843949cf7f106d18
|
a2bbb0f5bde231188af881e662b08673820bf694
|
refs/heads/master
| 2020-06-19T06:42:44.282695
| 2015-09-07T22:22:13
| 2015-09-07T22:22:13
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,684
|
hpp
|
SpMVAcceleratorBufferAllDriver.hpp
|
#ifndef SpMVAcceleratorBufferAllDriver_H
#define SpMVAcceleratorBufferAllDriver_H
#include <assert.h>
class SpMVAcceleratorBufferAllDriver {
public:
static unsigned int expSignature() {return 0x34182cf6;};
SpMVAcceleratorBufferAllDriver(volatile unsigned int * baseAddr) {
m_baseAddr = baseAddr; assert(signature() == expSignature());};
// read+write register: startInit index: 12
void startInit(unsigned int v) {m_baseAddr[12] = v;};
unsigned int startInit() {return m_baseAddr[12];};
// read+write register: startRegular index: 13
void startRegular(unsigned int v) {m_baseAddr[13] = v;};
unsigned int startRegular() {return m_baseAddr[13];};
// read+write register: startWrite index: 14
void startWrite(unsigned int v) {m_baseAddr[14] = v;};
unsigned int startWrite() {return m_baseAddr[14];};
// read+write register: numRows index: 15
void numRows(unsigned int v) {m_baseAddr[15] = v;};
unsigned int numRows() {return m_baseAddr[15];};
// read+write register: numCols index: 16
void numCols(unsigned int v) {m_baseAddr[16] = v;};
unsigned int numCols() {return m_baseAddr[16];};
// read+write register: numNZ index: 17
void numNZ(unsigned int v) {m_baseAddr[17] = v;};
unsigned int numNZ() {return m_baseAddr[17];};
// read+write register: baseColPtr index: 18
void baseColPtr(unsigned int v) {m_baseAddr[18] = v;};
unsigned int baseColPtr() {return m_baseAddr[18];};
// read+write register: baseRowInd index: 19
void baseRowInd(unsigned int v) {m_baseAddr[19] = v;};
unsigned int baseRowInd() {return m_baseAddr[19];};
// read+write register: baseNZData index: 20
void baseNZData(unsigned int v) {m_baseAddr[20] = v;};
unsigned int baseNZData() {return m_baseAddr[20];};
// read+write register: baseInputVec index: 21
void baseInputVec(unsigned int v) {m_baseAddr[21] = v;};
unsigned int baseInputVec() {return m_baseAddr[21];};
// read+write register: baseOutputVec index: 22
void baseOutputVec(unsigned int v) {m_baseAddr[22] = v;};
unsigned int baseOutputVec() {return m_baseAddr[22];};
// read+write register: thresColPtr index: 23
void thresColPtr(unsigned int v) {m_baseAddr[23] = v;};
unsigned int thresColPtr() {return m_baseAddr[23];};
// read+write register: thresRowInd index: 24
void thresRowInd(unsigned int v) {m_baseAddr[24] = v;};
unsigned int thresRowInd() {return m_baseAddr[24];};
// read+write register: thresNZData index: 25
void thresNZData(unsigned int v) {m_baseAddr[25] = v;};
unsigned int thresNZData() {return m_baseAddr[25];};
// read+write register: thresInputVec index: 26
void thresInputVec(unsigned int v) {m_baseAddr[26] = v;};
unsigned int thresInputVec() {return m_baseAddr[26];};
// read+write register: statBackend index: 1
void statBackend(unsigned int v) {m_baseAddr[1] = v;};
unsigned int statBackend() {return m_baseAddr[1];};
// read+write register: statFrontend index: 2
void statFrontend(unsigned int v) {m_baseAddr[2] = v;};
unsigned int statFrontend() {return m_baseAddr[2];};
// read+write register: hazardStalls index: 3
void hazardStalls(unsigned int v) {m_baseAddr[3] = v;};
unsigned int hazardStalls() {return m_baseAddr[3];};
// read+write register: bwMon_totalCycles index: 4
void bwMon_totalCycles(unsigned int v) {m_baseAddr[4] = v;};
unsigned int bwMon_totalCycles() {return m_baseAddr[4];};
// read+write register: bwMon_activeCycles index: 5
void bwMon_activeCycles(unsigned int v) {m_baseAddr[5] = v;};
unsigned int bwMon_activeCycles() {return m_baseAddr[5];};
// read+write register: bwMon_noValidButReady index: 6
void bwMon_noValidButReady(unsigned int v) {m_baseAddr[6] = v;};
unsigned int bwMon_noValidButReady() {return m_baseAddr[6];};
// read+write register: bwMon_noReadyButValid index: 7
void bwMon_noReadyButValid(unsigned int v) {m_baseAddr[7] = v;};
unsigned int bwMon_noReadyButValid() {return m_baseAddr[7];};
// read+write register: ocmWords index: 8
void ocmWords(unsigned int v) {m_baseAddr[8] = v;};
unsigned int ocmWords() {return m_baseAddr[8];};
// read+write register: fifoCountsCPRI index: 9
void fifoCountsCPRI(unsigned int v) {m_baseAddr[9] = v;};
unsigned int fifoCountsCPRI() {return m_baseAddr[9];};
// read+write register: fifoCountsNZIV index: 10
void fifoCountsNZIV(unsigned int v) {m_baseAddr[10] = v;};
unsigned int fifoCountsNZIV() {return m_baseAddr[10];};
// read+write register: debug index: 11
void debug(unsigned int v) {m_baseAddr[11] = v;};
unsigned int debug() {return m_baseAddr[11];};
// read+write register: signature index: 0
void signature(unsigned int v) {m_baseAddr[0] = v;};
unsigned int signature() {return m_baseAddr[0];};
protected:
volatile unsigned int * m_baseAddr;
};
#endif
|
2fe14bd07830ab9de5e4e038e85c59b8304e3590
|
b153b59ce27cdd08a4a0fd120ec738bfcc5eb18b
|
/src/ImageAnalysis/ImageAnalysis/CoinFinder.h
|
259d80faf41b32236a8dcddde3f1573bf2e17fe3
|
[] |
no_license
|
redcurry/BlackPearl
|
6872af00b64db826ab0caac19cb097d9972131c4
|
246954a7430a3adbb8f48ea2df72efff073c10bd
|
refs/heads/master
| 2020-04-23T09:45:08.093229
| 2019-02-26T03:15:02
| 2019-02-26T03:15:02
| 171,079,838
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,082
|
h
|
CoinFinder.h
|
#pragma once
#include <opencv2/opencv.hpp>
#include "Common.h"
class CoinFinder
{
public:
cv::RotatedRect find_coin(const cv::Mat& image) const;
private:
const double MedianKRatio = 0.02;
const int CannyThreshold1 = 300;
const int CannyThreshold2 = 150;
const double MinCircleFitRatio = 0.5;
const double MaxCircleFitError = 0.05;
const double MinCoinRadiusRatio = 0.02;
const double MaxCoinRadiusRatio = 0.05;
cv::Mat median(const cv::Mat& image) const;
cv::Mat canny(const cv::Mat& image) const;
std::vector<Contour> find_contours(const cv::Mat& image) const;
std::vector<cv::RotatedRect> find_circles(const std::vector<Contour>& contours) const;
std::vector<cv::RotatedRect> find_coins(const cv::Mat& image, const std::vector<cv::RotatedRect>& circles) const;
std::vector<cv::RotatedRect> filter_by_radius(std::vector<cv::RotatedRect> circles, double min, double max) const;
double calc_circle_fit_ratio(const Contour& contour, const cv::Point2f& center, double r) const;
int calc_median_k(const cv::Mat& image) const;
int round_odd(double x) const;
};
|
4d87018cb32c89d2bcfe83dac63d55fb74caf5ed
|
1dd791ef8132ed6bebc458d7c3c1ba5a9c8ca985
|
/src/rx/render/canvas.h
|
1fd49812454c7de7ea09c11ac4a7020a5cfb51a5
|
[
"MIT"
] |
permissive
|
BuckeyeSoftware/rex
|
e4ef1a743745b027eb02c629541edf85faf1d026
|
a0380e2e3ce26e610b4c9fcbe0ece19ecc8c3531
|
refs/heads/main
| 2021-12-20T17:41:51.163916
| 2021-12-05T04:07:52
| 2021-12-05T04:07:52
| 171,078,375
| 40
| 7
|
MIT
| 2020-12-15T03:24:33
| 2019-02-17T03:38:52
|
C++
|
UTF-8
|
C++
| false
| false
| 1,446
|
h
|
canvas.h
|
#ifndef RX_RENDER_CANVAS_H
#define RX_RENDER_CANVAS_H
#include "rx/core/vector.h"
#include "rx/math/mat3x4.h"
#include "rx/render/frontend/state.h"
extern "C" typedef struct NVGcontext NVGcontext;
namespace Rx::Render {
namespace Frontend {
struct Context;
struct Buffer;
struct Program;
struct Target;
struct Texture2D;
struct Technique;
} // namespace Frontend
struct Canvas {
RX_MARK_NO_COPY(Canvas);
enum : Uint8 {
ANTIALIAS = 1 << 0,
STENCIL_STROKES = 1 << 1
};
static Optional<Canvas> create(Frontend::Context* _context,
const Math::Vec2z& _dimensions, Uint8 _flags);
Frontend::Texture2D* texture() const;
Canvas() : m_context{nullptr} {}
Canvas(Canvas&& canvas_);
~Canvas();
Canvas& operator=(Canvas&& canvas_);
operator NVGcontext*() const;
private:
constexpr Canvas(NVGcontext* _context);
void release();
NVGcontext* m_context;
};
inline constexpr Canvas::Canvas(NVGcontext* _context)
: m_context{_context}
{
}
inline Canvas::Canvas(Canvas&& canvas_)
: m_context{Utility::exchange(canvas_.m_context, nullptr)}
{
}
inline Canvas::~Canvas() {
release();
}
inline Canvas& Canvas::operator=(Canvas&& canvas_) {
if (&canvas_ != this) {
release();
m_context = Utility::exchange(canvas_.m_context, nullptr);
}
return *this;
}
inline Canvas::operator NVGcontext*() const {
return m_context;
}
} // namespace Rx::Render
#endif // RX_RENDER_CANVAS_H
|
5a07375a4d85c939eca83546137d4e3acda0d78b
|
35c836ed4b443a8f2a5076edf25e8a00b1b93203
|
/WebKit2-7606.2.104.1.1/WebKit2-7606.2.104.1.1/NetworkProcess/curl/NetworkDataTaskCurl.cpp
|
ea2c10014e3c94701f5de4fd70cf4a65684d5017
|
[
"MIT"
] |
permissive
|
mlcldh/appleWebKit2
|
e3260c49e7bf82bf70617841868af81fc32c5d9f
|
39cc42a4710c9319c8da269621844493ab2ccdd6
|
refs/heads/master
| 2021-06-12T05:52:05.942098
| 2021-05-27T07:27:38
| 2021-05-27T07:27:38
| 190,697,531
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 15,910
|
cpp
|
NetworkDataTaskCurl.cpp
|
/*
* Copyright (C) 2018 Sony Interactive Entertainment Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "NetworkDataTaskCurl.h"
#include "AuthenticationManager.h"
#include "NetworkSessionCurl.h"
#include <WebCore/AuthenticationChallenge.h>
#include <WebCore/CookiesStrategy.h>
#include <WebCore/CurlRequest.h>
#include <WebCore/NetworkStorageSession.h>
#include <WebCore/NotImplemented.h>
#include <WebCore/ResourceError.h>
#include <WebCore/SameSiteInfo.h>
using namespace WebCore;
namespace WebKit {
NetworkDataTaskCurl::NetworkDataTaskCurl(NetworkSession& session, NetworkDataTaskClient& client, const ResourceRequest& requestWithCredentials, StoredCredentialsPolicy storedCredentialsPolicy, ContentSniffingPolicy shouldContentSniff, ContentEncodingSniffingPolicy, bool shouldClearReferrerOnHTTPSToHTTPRedirect, bool dataTaskIsForMainFrameNavigation)
: NetworkDataTask(session, client, requestWithCredentials, storedCredentialsPolicy, shouldClearReferrerOnHTTPSToHTTPRedirect, dataTaskIsForMainFrameNavigation)
{
if (m_scheduledFailureType != NoFailure)
return;
auto request = requestWithCredentials;
if (request.url().protocolIsInHTTPFamily()) {
if (m_storedCredentialsPolicy == StoredCredentialsPolicy::Use) {
auto url = request.url();
m_user = url.user();
m_password = url.pass();
request.removeCredentials();
if (m_user.isEmpty() && m_password.isEmpty())
m_initialCredential = m_session->networkStorageSession().credentialStorage().get(m_partition, request.url());
else
m_session->networkStorageSession().credentialStorage().set(m_partition, Credential(m_user, m_password, CredentialPersistenceNone), request.url());
}
}
m_curlRequest = createCurlRequest(request, ShouldPreprocess::Yes);
if (!m_initialCredential.isEmpty())
m_curlRequest->setUserPass(m_initialCredential.user(), m_initialCredential.password());
m_curlRequest->start();
}
NetworkDataTaskCurl::~NetworkDataTaskCurl()
{
if (m_curlRequest)
m_curlRequest->invalidateClient();
}
void NetworkDataTaskCurl::resume()
{
ASSERT(m_state != State::Running);
if (m_state == State::Canceling || m_state == State::Completed)
return;
m_state = State::Running;
if (m_scheduledFailureType != NoFailure) {
ASSERT(m_failureTimer.isActive());
return;
}
if (m_curlRequest)
m_curlRequest->resume();
}
void NetworkDataTaskCurl::suspend()
{
ASSERT(m_state != State::Suspended);
if (m_state == State::Canceling || m_state == State::Completed)
return;
m_state = State::Suspended;
if (m_curlRequest)
m_curlRequest->suspend();
}
void NetworkDataTaskCurl::cancel()
{
if (m_state == State::Canceling || m_state == State::Completed)
return;
m_state = State::Canceling;
if (m_curlRequest)
m_curlRequest->cancel();
}
void NetworkDataTaskCurl::invalidateAndCancel()
{
cancel();
if (m_curlRequest)
m_curlRequest->invalidateClient();
}
NetworkDataTask::State NetworkDataTaskCurl::state() const
{
return m_state;
}
Ref<CurlRequest> NetworkDataTaskCurl::createCurlRequest(const ResourceRequest& request, ShouldPreprocess shouldPreprocess)
{
m_currentRequest = request;
if (shouldPreprocess == ShouldPreprocess::Yes)
appendCookieHeader(m_currentRequest);
// Creates a CurlRequest in suspended state.
// Then, NetworkDataTaskCurl::resume() will be called and communication resumes.
return CurlRequest::create(m_currentRequest, *this, CurlRequest::ShouldSuspend::Yes);
}
void NetworkDataTaskCurl::curlDidSendData(CurlRequest&, unsigned long long totalBytesSent, unsigned long long totalBytesExpectedToSend)
{
auto protectedThis = makeRef(*this);
if (state() == State::Canceling || state() == State::Completed || !m_client)
return;
m_client->didSendData(totalBytesSent, totalBytesExpectedToSend);
}
void NetworkDataTaskCurl::curlDidReceiveResponse(CurlRequest&, const CurlResponse& receivedResponse)
{
auto protectedThis = makeRef(*this);
if (state() == State::Canceling || state() == State::Completed || !m_client)
return;
m_response = ResourceResponse(receivedResponse);
handleCookieHeaders(receivedResponse);
if (m_response.shouldRedirect()) {
willPerformHTTPRedirection();
return;
}
if (m_response.isUnauthorized()) {
tryHttpAuthentication(AuthenticationChallenge(receivedResponse, m_authFailureCount, m_response));
m_authFailureCount++;
return;
}
didReceiveResponse(ResourceResponse(m_response), [this, protectedThis = makeRef(*this)](PolicyAction policyAction) {
if (m_state == State::Canceling || m_state == State::Completed)
return;
switch (policyAction) {
case PolicyAction::Use:
if (m_curlRequest)
m_curlRequest->completeDidReceiveResponse();
break;
case PolicyAction::Ignore:
break;
case PolicyAction::Download:
notImplemented();
break;
}
});
}
void NetworkDataTaskCurl::curlDidReceiveBuffer(CurlRequest&, Ref<SharedBuffer>&& buffer)
{
auto protectedThis = makeRef(*this);
if (state() == State::Canceling || state() == State::Completed || (!m_client && !isDownload()))
return;
m_client->didReceiveData(WTFMove(buffer));
}
void NetworkDataTaskCurl::curlDidComplete(CurlRequest& request)
{
if (state() == State::Canceling || state() == State::Completed || (!m_client && !isDownload()))
return;
m_response.setDeprecatedNetworkLoadMetrics(request.networkLoadMetrics().isolatedCopy());
m_client->didCompleteWithError({ }, m_response.deprecatedNetworkLoadMetrics());
}
void NetworkDataTaskCurl::curlDidFailWithError(CurlRequest&, const ResourceError& resourceError)
{
if (state() == State::Canceling || state() == State::Completed || (!m_client && !isDownload()))
return;
m_client->didCompleteWithError(resourceError);
}
bool NetworkDataTaskCurl::shouldRedirectAsGET(const ResourceRequest& request, bool crossOrigin)
{
if (request.httpMethod() == "GET" || request.httpMethod() == "HEAD")
return false;
if (!request.url().protocolIsInHTTPFamily())
return true;
if (m_response.isSeeOther())
return true;
if ((m_response.isMovedPermanently() || m_response.isFound()) && (request.httpMethod() == "POST"))
return true;
if (crossOrigin && (request.httpMethod() == "DELETE"))
return true;
return false;
}
void NetworkDataTaskCurl::willPerformHTTPRedirection()
{
static const int maxRedirects = 20;
if (m_redirectCount++ > maxRedirects) {
m_client->didCompleteWithError(ResourceError::httpError(CURLE_TOO_MANY_REDIRECTS, m_response.url()));
return;
}
ResourceRequest request = m_currentRequest;
URL redirectedURL = URL(m_response.url(), m_response.httpHeaderField(HTTPHeaderName::Location));
if (!redirectedURL.hasFragmentIdentifier() && request.url().hasFragmentIdentifier())
redirectedURL.setFragmentIdentifier(request.url().fragmentIdentifier());
request.setURL(redirectedURL);
// Should not set Referer after a redirect from a secure resource to non-secure one.
if (m_shouldClearReferrerOnHTTPSToHTTPRedirect && !request.url().protocolIs("https") && protocolIs(request.httpReferrer(), "https"))
request.clearHTTPReferrer();
bool isCrossOrigin = !protocolHostAndPortAreEqual(m_currentRequest.url(), request.url());
if (!equalLettersIgnoringASCIICase(request.httpMethod(), "get")) {
// Change request method to GET if change was made during a previous redirection or if current redirection says so.
if (!request.url().protocolIsInHTTPFamily() || shouldRedirectAsGET(request, isCrossOrigin)) {
request.setHTTPMethod("GET");
request.setHTTPBody(nullptr);
request.clearHTTPContentType();
}
}
bool didChangeCredential = false;
const auto& url = request.url();
m_user = url.user();
m_password = url.pass();
m_lastHTTPMethod = request.httpMethod();
request.removeCredentials();
if (isCrossOrigin) {
// The network layer might carry over some headers from the original request that
// we want to strip here because the redirect is cross-origin.
request.clearHTTPAuthorization();
request.clearHTTPOrigin();
} else if (m_storedCredentialsPolicy == StoredCredentialsPolicy::Use) {
// Only consider applying authentication credentials if this is actually a redirect and the redirect
// URL didn't include credentials of its own.
if (m_user.isEmpty() && m_password.isEmpty()) {
auto credential = m_session->networkStorageSession().credentialStorage().get(m_partition, request.url());
if (!credential.isEmpty()) {
m_initialCredential = credential;
didChangeCredential = true;
}
}
}
auto response = ResourceResponse(m_response);
m_client->willPerformHTTPRedirection(WTFMove(response), WTFMove(request), [this, protectedThis = makeRef(*this), didChangeCredential](const ResourceRequest& newRequest) {
if (newRequest.isNull() || m_state == State::Canceling)
return;
if (m_curlRequest)
m_curlRequest->cancel();
m_curlRequest = createCurlRequest(newRequest, ShouldPreprocess::Yes);
if (didChangeCredential && !m_initialCredential.isEmpty())
m_curlRequest->setUserPass(m_initialCredential.user(), m_initialCredential.password());
m_curlRequest->start();
if (m_state != State::Suspended) {
m_state = State::Suspended;
resume();
}
});
}
void NetworkDataTaskCurl::tryHttpAuthentication(AuthenticationChallenge&& challenge)
{
if (!m_user.isNull() && !m_password.isNull()) {
auto persistence = m_storedCredentialsPolicy == WebCore::StoredCredentialsPolicy::Use ? WebCore::CredentialPersistenceForSession : WebCore::CredentialPersistenceNone;
restartWithCredential(Credential(m_user, m_password, persistence));
m_user = String();
m_password = String();
return;
}
if (m_storedCredentialsPolicy == StoredCredentialsPolicy::Use) {
if (!m_initialCredential.isEmpty() || challenge.previousFailureCount()) {
// The stored credential wasn't accepted, stop using it. There is a race condition
// here, since a different credential might have already been stored by another
// NetworkDataTask, but the observable effect should be very minor, if any.
m_session->networkStorageSession().credentialStorage().remove(m_partition, challenge.protectionSpace());
}
if (!challenge.previousFailureCount()) {
auto credential = m_session->networkStorageSession().credentialStorage().get(m_partition, challenge.protectionSpace());
if (!credential.isEmpty() && credential != m_initialCredential) {
ASSERT(credential.persistence() == CredentialPersistenceNone);
if (challenge.failureResponse().isUnauthorized()) {
// Store the credential back, possibly adding it as a default for this directory.
m_session->networkStorageSession().credentialStorage().set(m_partition, credential, challenge.protectionSpace(), challenge.failureResponse().url());
}
restartWithCredential(credential);
return;
}
}
}
m_client->didReceiveChallenge(AuthenticationChallenge(challenge), [this, protectedThis = makeRef(*this), challenge](AuthenticationChallengeDisposition disposition, const Credential& credential) {
if (m_state == State::Canceling || m_state == State::Completed)
return;
if (disposition == AuthenticationChallengeDisposition::Cancel) {
cancel();
m_client->didCompleteWithError(ResourceError::httpError(CURLE_COULDNT_RESOLVE_HOST, m_response.url()));
return;
}
if (disposition == AuthenticationChallengeDisposition::UseCredential && !credential.isEmpty()) {
if (m_storedCredentialsPolicy == StoredCredentialsPolicy::Use) {
if (credential.persistence() == CredentialPersistenceForSession || credential.persistence() == CredentialPersistencePermanent)
m_session->networkStorageSession().credentialStorage().set(m_partition, credential, challenge.protectionSpace(), challenge.failureResponse().url());
}
}
restartWithCredential(credential);
});
}
void NetworkDataTaskCurl::restartWithCredential(const Credential& credential)
{
if (m_curlRequest)
m_curlRequest->cancel();
m_curlRequest = createCurlRequest(m_currentRequest, ShouldPreprocess::No);
if (!credential.isEmpty())
m_curlRequest->setUserPass(credential.user(), credential.password());
m_curlRequest->start();
if (m_state != State::Suspended) {
m_state = State::Suspended;
resume();
}
}
void NetworkDataTaskCurl::appendCookieHeader(WebCore::ResourceRequest& request)
{
const auto& storageSession = m_session->networkStorageSession();
const auto& cookieJar = storageSession.cookieStorage();
auto includeSecureCookies = request.url().protocolIs("https") ? IncludeSecureCookies::Yes : IncludeSecureCookies::No;
auto cookieHeaderField = cookieJar.cookieRequestHeaderFieldValue(storageSession, request.firstPartyForCookies(), WebCore::SameSiteInfo::create(request), request.url(), std::nullopt, std::nullopt, includeSecureCookies).first;
if (!cookieHeaderField.isEmpty())
request.addHTTPHeaderField(HTTPHeaderName::Cookie, cookieHeaderField);
}
void NetworkDataTaskCurl::handleCookieHeaders(const CurlResponse& response)
{
static const auto setCookieHeader = "set-cookie: ";
const auto& storageSession = m_session->networkStorageSession();
const auto& cookieJar = storageSession.cookieStorage();
for (auto header : response.headers) {
if (header.startsWithIgnoringASCIICase(setCookieHeader)) {
String setCookieString = header.right(header.length() - strlen(setCookieHeader));
cookieJar.setCookiesFromHTTPResponse(storageSession, response.url, setCookieString);
}
}
}
} // namespace WebKit
|
151520a7b2056e952b0890c5362a0827dfa65d51
|
9499ab3d4f135e009c838a0134f4deb03c747d48
|
/training/20-Nov-2019/J.cpp
|
2e5cabbe9c899b268a9d21fcb6e9b90a3671d196
|
[] |
no_license
|
haleyk10198/HPtt
|
3940ed838da32cb752251c34feae4c0d2fb9244e
|
ea9c9b16be3abc0c9ef3d2223cb9128ef5ec0306
|
refs/heads/master
| 2020-04-12T19:06:05.997361
| 2019-12-18T06:14:32
| 2019-12-18T06:14:32
| 162,699,604
| 7
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,642
|
cpp
|
J.cpp
|
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/detail/standard_policies.hpp>
using namespace __gnu_pbds;
using namespace std;
using ll = long long;
#define pii pair<ll, ll>
#define fi first
#define se second
typedef tree<
pair<ll, pii>,
null_type,
greater<>,
rb_tree_tag,
tree_order_statistics_node_update>
OT;
#define MAXN 1000010
int n;
set<pii> edges;
map<pii, int> weights;
void solve(int u, int v, OT &out) {
vector<OT> children;
const int u0 = u;
const int v0 = v;
edges.erase(pair(v, -u));
while(true) {
auto it = edges.upper_bound(pair(v, -u));
if(it == edges.begin()) {
break;
}
--it;
int y = it->first;
int x = -it->second;
if(y <= u) break;
children.push_back(OT());
solve(x, y, children.back());
v = x;
}
if(children.empty()) {
if(weights.count(pair(u0, v0))) {
out.insert(pair(weights[pair(u0, v0)], pair(u0, v0)));
}
return;
}
int idx = 0;
for(int i = 0; i < children.size(); i++) {
if(children[idx].size() < children[i].size()) {
idx = i;
}
}
swap(out, children[idx]);
for(int i = 0; i < children.size(); i++) {
if(i != idx) {
auto it = out.begin();
for(int j = 0; j+1 < children[i].size(); j++) it++;
for(auto pit = it, oit = --children[i].end(); ; --oit, it = pit) {
if(it != out.begin()) --pit;
ll vv = it->first+oit->first;
out.erase(it);
out.insert(pair(vv, oit->second));
if(oit == children[i].begin()) break;
}
}
}
if(weights.count(pair(u0, v0))) {
out.insert(pair(weights[pair(u0, v0)], pair(u0, v0)));
}
return;
}
ll writeBuffer[MAXN];
int main() {
#ifdef LOCAL
freopen("input.txt", "r", stdin);
#endif
ios_base::sync_with_stdio(false);
cin >> n;
for(int i = 0, s, t, v; i < n; i++) {
cin >> s >> t;
cin >> weights[pair(s, t)];
edges.insert(pair(t, -s));
}
OT res;
solve(1, 1e6, res);
{
int idx = 0;
for(auto node: res) {
writeBuffer[idx] += node.first;
writeBuffer[idx+1] += writeBuffer[idx];
idx++;
}
for( idx; idx < n; idx++) writeBuffer[idx] = writeBuffer[idx-1];
}
for(int i = 0; i < n; i++) cout << writeBuffer[i] << (i+1 == n? '\n': ' ');
return 0;
}
|
d0b06a71cef42188673a2aa985c5322beef2a270
|
35a3a794c94fbe9a3d9b0bcb19eaeb60c7ca6a26
|
/cf1106b.cpp
|
9aeca2f23b5d02ea00d3b27f66e578f92eed7213
|
[] |
no_license
|
jshky/CODE
|
be7eae06f8478706495ea1886233165995ba6f69
|
e78b61572953167091796b51a2c152780cf8c661
|
refs/heads/master
| 2021-07-06T23:55:00.038980
| 2020-09-20T05:44:42
| 2020-09-20T05:44:42
| 183,609,334
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,094
|
cpp
|
cf1106b.cpp
|
#include<cstdio>
#include<algorithm>
using namespace std;
const int N=2e5+5;
int n,m,cheap,num=1;
struct dish{
int a,c,id;
}a[N],b[N];
bool cmp(dish x,dish y){
return x.c==y.c?x.id<y.id:x.c<y.c;
}
int main(){
scanf("%d%d",&n,&m);
for (int i=1;i<=n;++i) scanf("%d",&a[i].a);
for (int i=1;i<=n;++i) scanf("%d",&a[i].c),a[i].id=i;
for (int i=1;i<=n;++i) b[i]=a[i];
sort(b+1,b+1+n,cmp);
cheap=b[num].id;
for (int i=1,t,d;i<=m;++i){
scanf("%d%d",&t,&d);
long long ans=0;
if (a[t].a){
int eaten=min(a[t].a,d);
a[t].a-=eaten; d-=eaten;
ans+=1LL*eaten*a[t].c;
}
if (!d){
printf("%lld\n",ans);
continue;
}
bool flag=0;
while (d){
if (!a[cheap].a){
cheap=b[++num].id;
if (num>n){flag=1; break;}
}
int eaten=min(a[cheap].a,d);
a[cheap].a-=eaten; d-=eaten;
ans+=1LL*eaten*a[cheap].c;
}
printf("%lld\n",flag?0:ans);
}
return 0;
}
|
543311c1cb39ed32c8606d2632211ca012c12025
|
6367550fd6c35cb8f5a29093444d65393b8412d3
|
/largest.CPP
|
06889a0ecd0b00f51164198e7d599d0f44f88c27
|
[] |
no_license
|
karthicsankar/CPLUS
|
695f9d1789dbd6ca215a554415474bae2c53f540
|
b099ec0f16dba6f525dac66d5ea4575e78506fe2
|
refs/heads/master
| 2021-04-30T15:09:14.655556
| 2018-03-14T11:19:58
| 2018-03-14T11:19:58
| 121,230,696
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 317
|
cpp
|
largest.CPP
|
#include<iostream>
using namespace std;
int main()
{
int a[9];
cout<<"Enter the numberS:";
for(int i=0;i<=9;i++)
{
cin>>a[i];
}
for(int j=0;j<=9;j++)
{
cout<<"\n"<<a[j];
if(a[j]>>(a[j+1]))
{
cout<<"\n"<<a[j];
}
}
for(int j=0;j<=9;j--)
{
if(a[j+1]<<(a[j]))
{
cout<<"\n"<<a[j+1];
}
}
return 0;
}
|
752f13f8d00af5ebfd4a89084f32fd7d39ab0c40
|
3244f247fca884cc86aa2396a69330672a277d5a
|
/Macros/VerifyPointing/newSBIs/source/SBIreader.cpp
|
23ec59286edf1e2c2787a8e200d4d20a861d4282
|
[] |
no_license
|
ecatanzani/refMapsBuilder
|
0b03e4b1eb50107f14bb340c001568c0c8ca9e10
|
66fab38c8a93363dae0069271b1175fc1cbc4897
|
refs/heads/master
| 2021-09-24T06:46:07.083296
| 2018-10-04T17:40:26
| 2018-10-04T17:40:26
| 151,611,363
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,508
|
cpp
|
SBIreader.cpp
|
#include "MyHead.h"
void read_SBI_data(
Double_t &galactic_lat,
Double_t &galactic_lon,
Double_t &geographic_lat,
Double_t &geographic_lon,
Double_t sat_ra[],
Double_t sat_dec[],
UInt_t &sec,
UShort_t &n_events,
bool &good,
TChain &tree,
Float_t &lvtime,
std::vector<std::string> &SBIpaths,
Int_t &tot_events
)
{
for(UInt_t idx_p = 0; idx_p < SBIpaths.size(); idx_p++)
tree.Add(SBIpaths.at(idx_p).c_str());
tree.SetBranchAddress("second",&sec);
tree.SetBranchAddress("goodsbi",&good);
tree.SetBranchAddress("glon",&galactic_lon);
tree.SetBranchAddress("glat",&galactic_lat);
tree.SetBranchAddress("nev",&n_events);
tree.SetBranchAddress("ra_scx",&sat_ra[0]);
tree.SetBranchAddress("ra_scy",&sat_ra[1]);
tree.SetBranchAddress("ra_scz",&sat_ra[2]);
tree.SetBranchAddress("dec_scx",&sat_dec[0]);
tree.SetBranchAddress("dec_scy",&sat_dec[1]);
tree.SetBranchAddress("dec_scz",&sat_dec[2]);
tree.SetBranchAddress("lat_geo",&geographic_lat);
tree.SetBranchAddress("lon_geo",&geographic_lon);
tree.SetBranchAddress("lvtime",&lvtime);
tot_events = tree.GetEntries();
std::cout << "\nSBI data has been loaded" << std::endl << std::endl;
}
|
514bff749b1da7c728a463bec8184597a3d1105a
|
a91796ab826878e54d91c32249f45bb919e0c149
|
/modules/dnn/src/ocl4dnn/src/ocl4dnn_conv_spatial.cpp
|
90cc2108d6731207b96139a2a8630dfb7ffc58ce
|
[
"Apache-2.0"
] |
permissive
|
opencv/opencv
|
8f1c8b5a16980f78de7c6e73a4340d302d1211cc
|
a308dfca9856574d37abe7628b965e29861fb105
|
refs/heads/4.x
| 2023-09-01T12:37:49.132527
| 2023-08-30T06:53:59
| 2023-08-30T06:53:59
| 5,108,051
| 68,495
| 62,910
|
Apache-2.0
| 2023-09-14T17:37:48
| 2012-07-19T09:40:17
|
C++
|
UTF-8
|
C++
| false
| false
| 71,713
|
cpp
|
ocl4dnn_conv_spatial.cpp
|
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2017, Intel Corporation, all rights reserved.
// Copyright (c) 2016-2017 Fabian David Tschopp, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#include "../../precomp.hpp"
#include <opencv2/core/utils/configuration.private.hpp>
#include <string>
#include <vector>
#include <fstream>
#include <sys/stat.h>
#include "../include/common.hpp"
#include "../include/ocl4dnn.hpp"
#include "opencl_kernels_dnn.hpp"
#include "../include/math_functions.hpp"
#include "../include/default_kernel_config.hpp"
#include "opencv2/dnn/shape_utils.hpp"
#include "opencv2/core/utils/logger.hpp"
#if defined WIN32 || defined _WIN32
#include <windows.h>
#include <direct.h>
#undef min
#undef max
#endif
namespace cv { namespace dnn { namespace ocl4dnn {
static cv::Mutex kernelConfigMutex;
typedef std::map<std::string, std::string> kernel_hash_t;
static kernel_hash_t kernelConfigMap;
static bool defaultConfigLoaded = false;
static bool enableWorkaroundIDLF()
{
static bool param = utils::getConfigurationParameterSizeT("OPENCV_OCL4DNN_WORKAROUND_IDLF", true);
return param;
}
static bool dumpFailedResult()
{
static bool param = utils::getConfigurationParameterSizeT("OPENCV_OCL4DNN_DUMP_FAILED_RESULT", false);
return param;
}
static size_t testAllKernels()
{
static size_t param = utils::getConfigurationParameterSizeT("OPENCV_OCL4DNN_TEST_ALL_KERNELS", 0);
return param;
}
static bool raiseOnCheckError()
{
static bool param = utils::getConfigurationParameterBool("OPENCV_OCL4DNN_TUNING_RAISE_CHECK_ERROR", false);
return param;
}
static std::string sanitize(const std::string& s)
{
std::string s_ = s;
for (size_t i = 0; i < s_.size(); i++)
{
char c = s_[i];
if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_'))
{
s_[i] = '_';
}
}
// TODO add hash?
// s_ = s_ + cv::format("_%08llx", crc64((uchar*)s.c_str(), s.size()));
return s_;
}
static void initializeGlobalBuiltinConfigurations(const std::string& cache_path)
{
CV_Assert(defaultConfigLoaded == false);
CV_Assert(kernelConfigMap.empty());
/* fp32 config */
size_t numConfigs = sizeof(default_kernel_config_intel_fp32) /
sizeof(default_kernel_config_intel_fp32[0]) / 2;
for (size_t i = 0; i < numConfigs; i++)
{
std::string key = std::string("Intel(R) Corporation_") + default_kernel_config_intel_fp32[2 * i];
if (!cache_path.empty())
{
std::string cacheFile = cache_path + sanitize(key);
std::ifstream cachedKernel(cacheFile.c_str());
if (cachedKernel)
continue; // external configuration found, skip builtin
}
std::pair<std::string, std::string> entry(
key,
default_kernel_config_intel_fp32[2 * i + 1]);
kernelConfigMap.insert(entry);
}
/* fp16 config */
numConfigs = sizeof(default_kernel_config_intel_fp16) /
sizeof(default_kernel_config_intel_fp16[0]) / 2;
for (size_t i = 0; i < numConfigs; i++)
{
std::string key = std::string("Intel(R) Corporation_") + default_kernel_config_intel_fp16[2 * i];
if (!cache_path.empty())
{
std::string cacheFile = cache_path + sanitize(key);
std::ifstream cachedKernel(cacheFile.c_str());
if (cachedKernel)
continue; // external configuration found, skip builtin
}
std::pair<std::string, std::string> entry(
key,
default_kernel_config_intel_fp16[2 * i + 1]);
kernelConfigMap.insert(entry);
}
defaultConfigLoaded = true;
}
template<typename Dtype>
OCL4DNNConvSpatial<Dtype>::OCL4DNNConvSpatial(OCL4DNNConvConfig config)
{
bias_term_ = config.bias_term;
int dims = config.in_shape.size();
int spatial_dims = 2;
channels_ = config.in_shape[dims - spatial_dims - 1];
num_output_ = config.out_shape[dims - spatial_dims - 1];
group_ = config.group;
CV_CheckGT(group_, 0, ""); // avoid div by zero below
fused_activ_ = OCL4DNN_CONV_FUSED_ACTIV_NONE;
fused_eltwise_ = false;
power_ = 1.f;
negative_slope_ = 0;
min_value_ = 0;
max_value_ = 0;
prev_kernel_type_ = -1;
tuned_ = false;
use_half_ = config.use_half;
// assumption: spatial dimension is 2.
kernel_h_ = config.kernel.height;
kernel_w_ = config.kernel.width;
// pads: [pad_top, pad_bottom, pad_left, pad_right]
pad_h_ = config.pads[0]; // pad_top
pad_bottom_ = config.pads[1];
pad_w_ = config.pads[2]; // pad_left
pad_right_ = config.pads[3];
stride_h_ = config.stride.height;
stride_w_ = config.stride.width;
dilation_h_ = config.dilation.height;
dilation_w_ = config.dilation.width;
M_ = num_output_ / group_;
height_ = config.in_shape[dims - spatial_dims + 0];
width_ = config.in_shape[dims - spatial_dims + 1];
output_h_ = config.out_shape[dims - spatial_dims + 0];
output_w_ = config.out_shape[dims - spatial_dims + 1];
bottom_dim_ = channels_ * width_ * height_;
top_dim_ = num_output_ * output_w_ * output_h_;
cache_path_ = utils::getConfigurationParameterString("OPENCV_OCL4DNN_CONFIG_PATH", "");
dwconv_ = (num_output_ == channels_ && channels_ == group_);
use_cache_path_ = false;
if (!cache_path_.empty())
{
#if defined _WIN32
struct _stat file_stat;
use_cache_path_ = _stat(cache_path_.c_str(), &file_stat) == 0 &&
((_S_IFDIR & file_stat.st_mode) != 0);
#else
struct stat file_stat;
use_cache_path_ = stat(cache_path_.c_str(), &file_stat) == 0 &&
S_ISDIR(file_stat.st_mode);
#endif
if (!use_cache_path_)
{
CV_LOG_ONCE_ERROR(NULL, "OpenCV(ocl4dnn): Kernel configuration cache directory doesn't exist: " << cache_path_);
}
}
run_auto_tuning_ = use_cache_path_ && !utils::getConfigurationParameterBool("OPENCV_OCL4DNN_DISABLE_AUTO_TUNING", false);
force_auto_tuning_ = utils::getConfigurationParameterBool("OPENCV_OCL4DNN_FORCE_AUTO_TUNING", false);
}
template<typename Dtype>
OCL4DNNConvSpatial<Dtype>::~OCL4DNNConvSpatial()
{
if (!swizzled_weights_umat.empty()) {
swizzled_weights_umat.release();
}
}
template<typename Dtype>
void OCL4DNNConvSpatial<Dtype>::setFusionDefine(ocl4dnnFusedActiv_t fused_activ, bool fused_eltwise)
{
if (fused_eltwise)
addDef("FUSED_CONV_ELTWISE", 1);
switch (fused_activ) {
case OCL4DNN_CONV_FUSED_ACTIV_RELU:
addDef("FUSED_CONV_RELU", 1);
break;
case OCL4DNN_CONV_FUSED_ACTIV_PRELU:
addDef("FUSED_CONV_PRELU", 1);
break;
case OCL4DNN_CONV_FUSED_ACTIV_POWER:
addDef("FUSED_CONV_POWER", 1);
break;
case OCL4DNN_CONV_FUSED_ACTIV_TANH:
addDef("FUSED_CONV_TANH", 1);
break;
case OCL4DNN_CONV_FUSED_ACTIV_RELU6:
addDef("FUSED_CONV_RELU6", 1);
break;
default:
;
}
return;
}
template<typename Dtype>
void OCL4DNNConvSpatial<Dtype>::setFusionArg(ocl4dnnFusedActiv_t fused_activ, bool fused_eltwise, int fused_eltwise_offset, ocl::Kernel &kernel, cl_uint &argIdx)
{
if (fused_eltwise)
{
kernel.set(argIdx++, ocl::KernelArg::PtrReadOnly(bottom_data2_));
if (fused_eltwise_offset >= 0)
kernel.set(argIdx++, fused_eltwise_offset);
}
switch (fused_activ) {
case OCL4DNN_CONV_FUSED_ACTIV_RELU:
kernel.set(argIdx++, (float)negative_slope_);
break;
case OCL4DNN_CONV_FUSED_ACTIV_PRELU:
kernel.set(argIdx++, ocl::KernelArg::PtrReadOnly(negative_slope_umat_));
break;
case OCL4DNN_CONV_FUSED_ACTIV_POWER:
kernel.set(argIdx++, (float)power_);
break;
case OCL4DNN_CONV_FUSED_ACTIV_RELU6:
kernel.set(argIdx++, (float)min_value_);
kernel.set(argIdx++, (float)max_value_);
break;
default:
;
}
return;
}
typedef enum {
TYPE_FLOAT = 1,
TYPE_HALF = 2
} ocl4dnnConvSpatialType_t;
template<typename Dtype>
void OCL4DNNConvSpatial<Dtype>::collectCommonInformation()
{
if (use_half_)
{
addDef("TYPE", TYPE_HALF);
addDef("Dtype", "half");
addDef("Dtype2", "half2");
addDef("Dtype4", "half4");
addDef("Dtype8", "half8");
addDef("Dtype16", "half16");
addDef("as_Dtype", "as_half");
addDef("as_Dtype2", "as_half2");
addDef("as_Dtype4", "as_half4");
addDef("as_Dtype8", "as_half8");
}
else
{
addDef("TYPE", TYPE_FLOAT);
addDef("Dtype", "float");
addDef("Dtype2", "float2");
addDef("Dtype4", "float4");
addDef("Dtype8", "float8");
addDef("Dtype16", "float16");
addDef("as_Dtype", "as_float");
addDef("as_Dtype2", "as_float2");
addDef("as_Dtype4", "as_float4");
addDef("as_Dtype8", "as_float8");
}
}
typedef enum {
KERNEL_TYPE_INTEL_IDLF = 2,
KERNEL_TYPE_BASIC = 4,
KERNEL_TYPE_GEMM_LIKE = 5,
KERNEL_TYPE_DWCONV = 6
} ocl4dnnConvSpatialKernelType_t;
template<typename Dtype>
void OCL4DNNConvSpatial<Dtype>::setupKernelDetails(int32_t kernelType,
int32_t blockM,
int32_t blockK,
int32_t blockN)
{
std::string kernelUKey;
int32_t simd_size;
if (kernelType == KERNEL_TYPE_INTEL_IDLF) {
simd_size = blockN;
kernelUKey = generateSpecificKey(KERNEL_TYPE_INTEL_IDLF, blockM, blockK, 1);
// kernel name
kernel_name_ = "IDLF_";
kernel_name_ += kernelUKey;
if (simd_size == 16)
kernel_name_ += "_SIMD16";
else
kernel_name_ += "_SIMD8";
// options
options_ << " -cl-fast-relaxed-math -D KERNEL_IDLF -D convolve_simd=" << kernel_name_;
options_ << " -cl-mad-enable";
if (clOptionSupport("-cl-no-subgroup-ifp"))
options_ << " -cl-no-subgroup-ifp ";
// defs
int32_t output_block_width = blockM;
int32_t output_block_height = blockK;
int tile_x = (output_block_width - 1) * stride_w_ + kernel_w_ * dilation_w_;
int tile_y = (output_block_height - 1) * stride_h_ + kernel_h_ * dilation_h_;
int invec_size = tile_y;
addDef("SIMD_SIZE", simd_size);
addDef("OUT_BLOCK_WIDTH", output_block_width);
addDef("OUT_BLOCK_HEIGHT", output_block_height);
addDef("INPUT_DEPTH", channels_ / group_);
addDef("TOTAL_INPUT_DEPTH_SIZE", channels_);
addDef("TOTAL_OUTPUT_DEPTH", num_output_);
addDef("NUM_FILTERS", M_);
addDef("TILE_X", tile_x);
addDef("TILE_Y", tile_y);
addDef("INVEC_SIZE", invec_size);
addDef("ALIGNED_NUM_FILTERS", (int)alignSize(M_, simd_size));
addDef("OUT_BLOCK_SIZE", (output_block_width*output_block_height));
addDef("APPLY_BIAS", bias_term_);
addDef("WEIGHT_PREF", ((kernel_w_ * kernel_h_) == 1) ? 1 : 8);
addDef("INPUT_PITCH", (width_ * height_));
addDef("OUTPUT_PITCH", (output_w_ * output_h_));
addDef("LEFT_FILTERS", ((int)alignSize(M_, simd_size) - M_));
addDef("INPUT_WIDTH", width_);
addDef("INPUT_HEIGHT", height_);
addDef("FILTERS_IN_GROUP", ((int)alignSize(M_, simd_size) / simd_size));
setFusionDefine(fused_activ_, fused_eltwise_);
src_ = cv::ocl::dnn::conv_layer_spatial_oclsrc;
}
else if (kernelType == KERNEL_TYPE_BASIC)
{
addDef("KERNEL_BASIC");
kernelUKey = generateSpecificKey(KERNEL_TYPE_BASIC, blockM, blockK, blockN);
kernel_name_ = "BASIC_";
kernel_name_ += kernelUKey;
// opts
options_ << " -cl-fast-relaxed-math -D ConvolveBasic=" << kernel_name_;
if (clOptionSupport("-cl-no-subgroup-ifp"))
options_ << " -cl-no-subgroup-ifp ";
// defs
addDef("CHANNELS", channels_ / group_);
addDef("APPLY_BIAS", bias_term_);
addDef("OUTPUT_Z", M_);
setFusionDefine(fused_activ_, fused_eltwise_);
src_ = cv::ocl::dnn::conv_layer_spatial_oclsrc;
}
else if (kernelType == KERNEL_TYPE_GEMM_LIKE)
{
simd_size = blockK;
kernelUKey = generateSpecificKey(KERNEL_TYPE_GEMM_LIKE, blockM, blockK, blockN);
kernel_name_ = "U_GEMM_LIKE_CONV_";
kernel_name_ += kernelUKey.c_str();
kernel_name_ += (blockK == 8) ? "_SIMD8" : "_SIMD16";
std::stringstream kernelDef;
kernelDef << "GEMM_LIKE_CONV_" << blockN << "_" << blockM;
if (blockK == 16)
kernelDef << "_SIMD16";
// Build list of options and defines
options_ << " -cl-fast-relaxed-math " << " -D " << kernelDef.str()
<< " -D Conv_Interleaved=" << kernel_name_.c_str();
options_ << " -cl-mad-enable";
if (clOptionSupport("-cl-no-subgroup-ifp"))
options_ << " -cl-no-subgroup-ifp ";
addDef("KERNEL_GEMM_LIKE");
addDef("INPUT_DEPTH", channels_);
addDef("WIDTH1", M_);
addDef("OUT_PADDING_LEFT", 0);
addDef("OUT_PADDING_HEIGHT", 0);
addDef("OUT_DEPTH", M_);
addDef("NUM_BATCHES", num_);
addDef("DY", blockM);
addDef("DX", blockN);
addDef("KERNEL_WIDTH_DIV2", kernel_w_ / 2);
addDef("KERNEL_SLICE_DIV2", (kernel_w_ * kernel_h_) / 2);
addDef("TILE_N_LAST", M_ % 32);
addDef("TILE_N_LAST_DIV8", (M_ % 32) / 8);
addDef("APPLY_BIAS", bias_term_);
setFusionDefine(fused_activ_, fused_eltwise_);
src_ = ocl::dnn::conv_layer_spatial_oclsrc;
}
else if (kernelType == KERNEL_TYPE_DWCONV)
{
kernelUKey = generateSpecificKey(KERNEL_TYPE_DWCONV, blockM, blockK, blockN);
kernel_name_ = "DWCONV_";
kernel_name_ += kernelUKey.c_str();
options_ << " -cl-fast-relaxed-math ";
if (clOptionSupport("-cl-no-subgroup-ifp"))
options_ << " -cl-no-subgroup-ifp ";
addDef("KERNEL_DWCONV");
addDef("KERNEL_SIZE", kernel_w_ * kernel_h_);
addDef("KERNEL_W", kernel_w_);
addDef("KERNEL_H", kernel_h_);
addDef("APPLY_BIAS", bias_term_);
addDef("OUTPUT_Z", num_output_ * num_);
addDef("CHANNELS", num_output_);
setFusionDefine(fused_activ_, fused_eltwise_);
options_ << " -D DWCONV=" << kernel_name_;
src_ = cv::ocl::dnn::conv_layer_spatial_oclsrc;
}
}
template<typename Dtype>
void OCL4DNNConvSpatial<Dtype>::setupKernel()
{
collectCommonInformation();
addDef("KERNEL_WIDTH", kernel_w_);
addDef("KERNEL_HEIGHT" , kernel_h_);
addDef("STRIDE_X", stride_w_);
addDef("STRIDE_Y", stride_h_);
addDef("DILATION_X", dilation_w_);
addDef("DILATION_Y", dilation_h_);
if (kernelType_ != KERNEL_TYPE_BASIC)
{
addDef("INPUT_PAD_W", pad_w_);
addDef("INPUT_PAD_H", pad_h_);
addDef("INPUT_PAD_RIGHT", pad_right_);
addDef("INPUT_PAD_BOTTOM", pad_bottom_);
}
setupKernelDetails(kernelType_, blockM_, blockK_, blockN_);
}
template<typename Dtype>
void OCL4DNNConvSpatial<Dtype>::setBias(bool bias_term)
{
bias_term_ = bias_term;
}
template<typename Dtype>
void OCL4DNNConvSpatial<Dtype>::setActivReLU(bool fuse_activ, float slope)
{
if ( fuse_activ )
{
fused_activ_ = OCL4DNN_CONV_FUSED_ACTIV_RELU;
negative_slope_ = slope;
}
else
fused_activ_ = OCL4DNN_CONV_FUSED_ACTIV_NONE;
}
template<typename Dtype>
void OCL4DNNConvSpatial<Dtype>::setActivReLU6(bool fuse_activ, float min, float max)
{
if ( fuse_activ )
{
fused_activ_ = OCL4DNN_CONV_FUSED_ACTIV_RELU6;
min_value_ = min;
max_value_ = max;
}
else
fused_activ_ = OCL4DNN_CONV_FUSED_ACTIV_NONE;
}
template<typename Dtype>
void OCL4DNNConvSpatial<Dtype>::setActivPReLU(bool fuse_activ, std::vector<float> &slope)
{
if ( fuse_activ )
{
fused_activ_ = OCL4DNN_CONV_FUSED_ACTIV_PRELU;
Mat tmpMat = Mat(num_output_, 1, CV_32FC1, (uchar*)&slope[0]);
tmpMat.copyTo(negative_slope_umat_);
}
else
fused_activ_ = OCL4DNN_CONV_FUSED_ACTIV_NONE;
}
template<typename Dtype>
void OCL4DNNConvSpatial<Dtype>::setActivPower(bool fuse_activ, float power)
{
if ( fuse_activ )
{
fused_activ_ = OCL4DNN_CONV_FUSED_ACTIV_POWER;
power_ = power;
}
else
fused_activ_ = OCL4DNN_CONV_FUSED_ACTIV_NONE;
}
template<typename Dtype>
void OCL4DNNConvSpatial<Dtype>::setActivTanh(bool fuse_activ)
{
if ( fuse_activ )
{
fused_activ_ = OCL4DNN_CONV_FUSED_ACTIV_TANH;
}
else
fused_activ_ = OCL4DNN_CONV_FUSED_ACTIV_NONE;
}
template<typename Dtype>
bool OCL4DNNConvSpatial<Dtype>::Forward(const UMat& bottom,
const UMat& bottom2,
const UMat& weight,
const UMat& bias,
UMat& top,
int32_t numImages)
{
num_ = numImages;
if (!bottom2.empty())
{
fused_eltwise_ = true;
bottom_data2_ = bottom2;
}
else
{
fused_eltwise_ = false;
}
if (use_half_ && !bias.empty())
CV_CheckTypeEQ(bias.type(), CV_16SC1, "");
if (use_half_)
CV_CheckTypeEQ(weight.type(), CV_16SC1, "");
prepareKernel(bottom, top, weight, bias, numImages);
if (bestKernelConfig.empty())
return false;
return convolve(bottom, top, weight, bias, numImages, bestKernelConfig);
}
template<typename Dtype>
void OCL4DNNConvSpatial<Dtype>::calculateBenchmark(const UMat &bottom, UMat &verifyTop,
const UMat &weight, const UMat &bias,
int32_t numImages)
{
options_.str(""); options_.clear(); // clear contents and state flags
createBasicKernel(1, 1, 1);
CV_Assert(!kernelQueue.empty()); // basic kernel must be available
kernel_index_ = kernelQueue.size() - 1;
convolve(bottom, verifyTop, weight, bias, numImages, kernelQueue[kernel_index_]);
CV_Assert(phash.find(kernelQueue[kernel_index_]->kernelName) != phash.end());
//unloadProgram(kernelQueue[kernel_index_]->kernelName);
kernelQueue.pop_back();
return;
}
// For large enough input size, we do not need to tune kernels for different
// size. The reason is with large input size, there will be enough work items
// to feed al the EUs.
// FIXME for the gemm like convolution, switch back to exact image size.
#define TUNING_SIZE(x) ((x) > 256 ? 256 : (alignSize(x, 16)))
template<typename Dtype>
void OCL4DNNConvSpatial<Dtype>::generateKey()
{
std::string precision = (use_half_) ? "FP16" : "FP32";
std::stringstream keyBuilder;
// FIXME: to support fuse?
keyBuilder << "k" << kernel_w_ << "x" << kernel_h_ << "_"
<< "cn" << channels_ << "_"
<< "g" << group_ << "_"
<< "s" << stride_w_ << "x" << stride_h_ << "_"
<< "d" << dilation_w_ << "x" << dilation_h_ << "_"
<< "b" << bias_term_ << "_"
<< "in" << TUNING_SIZE(width_) << "x" << TUNING_SIZE(height_) << "_"
<< "p" << pad_w_ << "x" << pad_h_ << "_"
<< "num" << num_ << "_"
<< "M" << M_ << "_"
<< "activ" << (int)fused_activ_ << "_"
<< "eltwise" << fused_eltwise_ << "_"
<< precision;
key_ = ocl::Device::getDefault().vendorName() + "_EU" + cv::format("%d", ocl::Device::getDefault().maxComputeUnits()) + "_" + keyBuilder.str();
key_sanitized_ = sanitize(key_);
short_key_ = keyBuilder.str();
}
template<typename Dtype>
std::string OCL4DNNConvSpatial<Dtype>::generateSpecificKey(int32_t type, int32_t blockWidth,
int32_t blockHeight, int32_t blockDepth)
{
std::stringstream keyBuilder;
keyBuilder << short_key_
<< "_" << type
<< "_" << blockWidth
<< "_" << blockHeight
<< "_" << blockDepth;
return keyBuilder.str();
}
template<typename Dtype>
void interleaveMatrix(Dtype* mem_dst, const Dtype *mem,
int r, int c, int interleavedRows, int nonInterleavedRows,
int blockWidth, int rowAlignment )
{
CV_Check(interleavedRows, interleavedRows % 2 == 0, "interleaveMatrix only supports even values for interleavedRows.");
size_t memSize = r * c * sizeof(float);
size_t dstSize = memSize *
(interleavedRows + nonInterleavedRows * 2) /
(interleavedRows + nonInterleavedRows);
memset(mem_dst, 0, dstSize); // NOLINT
const int xStride = blockWidth;
const int yStride = c * 2;
const Dtype *pSrc = mem;
Dtype* pDst = mem_dst;
for (int y = 0; y < r;)
{
for (int rows = 0; rows < interleavedRows; rows += 2)
{
if (y >= r)
break;
if ((c % xStride) == 0) {
for (int x = 0; x < c / xStride; x++) {
memcpy(pDst + x * xStride * 2, // NOLINT
pSrc + x * xStride, xStride * sizeof(Dtype));
memcpy(pDst + x * xStride * 2 + xStride, // NOLINT
pSrc + x * xStride + c, xStride * sizeof(Dtype));
}
} else {
const int count = c / xStride;
int x = 0;
for (; x < count - 1; x++) {
memcpy(pDst + x * xStride * 2, // NOLINT
pSrc + x * xStride, xStride * sizeof(Dtype));
memcpy(pDst + x * xStride * 2 + xStride, // NOLINT
pSrc + x * xStride + c, xStride * sizeof(Dtype));
}
memcpy(pDst + x * xStride * 2, // NOLINT
pSrc + x * xStride, xStride * sizeof(Dtype));
}
pSrc += yStride;
pDst += yStride;
y += 2;
}
for (int rows = 0; rows < nonInterleavedRows; rows++)
{
if (y >= r)
break;
const int stride = rowAlignment;
int remaining = c;
for (int x = 0; x < c; x += stride)
{
if (remaining >= stride) {
memcpy(pDst + x * 2, pSrc + x, stride * sizeof(Dtype)); // NOLINT
remaining -=stride;
} else {
memcpy(pDst + x * 2, pSrc + x, remaining * sizeof(Dtype)); // NOLINT
}
}
pSrc += yStride / 2;
pDst += yStride;
y++;
}
}
}
template<typename Dtype>
bool OCL4DNNConvSpatial<Dtype>::swizzleWeight(const UMat &weight,
int32_t swizzled_factor,
bool interleave)
{
// Simply skip the weight swizzle if we already got a swizzled_weights_
// in test phase and not in auto tuning
// This requires we always call convolve again with the winner configuration
// during the auto tuning stage.
if (tuned_ && !swizzled_weights_umat.empty())
return true;
if (swizzled_weights_umat.empty())
swizzled_weights_umat.create(1, (int)alignSize(num_output_, 16) * channels_ *
kernel_h_ * (int)alignSize(kernel_w_, 2),
(use_half_) ? CV_16SC1 : CV_32FC1);
if (!interleave) {
int32_t channels = channels_ / group_;
ocl::Kernel oclk_copy_weight(
use_half_ ? "copyWeightsSwizzled_half" : "copyWeightsSwizzled_float",
cv::ocl::dnn::conv_spatial_helper_oclsrc,
use_half_ ? "-DHALF_SUPPORT=1 -DDtype=half" : "-DDtype=float"
);
if (oclk_copy_weight.empty())
return false;
oclk_copy_weight.args(
ocl::KernelArg::PtrReadOnly(weight),
ocl::KernelArg::PtrWriteOnly(swizzled_weights_umat),
kernel_w_,
kernel_h_,
channels,
num_output_,
swizzled_factor
);
size_t global_work_size_copy[1] = { (size_t)(alignSize(num_output_, swizzled_factor) * channels * kernel_w_ * kernel_h_) };
if (!oclk_copy_weight.run_(1, global_work_size_copy, NULL, false))
{
CV_LOG_ERROR(NULL, "DNN/OpenCL: Swizzle kernel run failed");
return false;
}
} else {
// assumption: kernel dimension is 2
Mat weightMat;
Mat swizzledWeightMat;
UMat weight_tmp; // FP32 in half mode, TODO implement FP16 repack
if (use_half_)
{
CV_CheckTypeEQ(weight.type(), CV_16SC1, "");
convertFp16(weight, weight_tmp);
weightMat = weight_tmp.getMat(ACCESS_READ);
swizzledWeightMat.create(shape(swizzled_weights_umat), CV_32F);
}
else
{
weightMat = weight.getMat(ACCESS_READ);
swizzledWeightMat = swizzled_weights_umat.getMat(ACCESS_WRITE);
}
CV_CheckTypeEQ(weightMat.type(), CV_32FC1, "");
Dtype* cpu_weight = (Dtype *)weightMat.ptr<float>();
Dtype* cpu_swizzled_weight = (Dtype *)swizzledWeightMat.ptr<float>();
int interleavedRows = (kernel_w_ / 2) * 2;
int nonInterleavedRows = kernel_w_ % 2;
int blockWidth = swizzled_factor; // should equal to simd size.
int rowAlignment = 32;
size_t interleaved_filter_size = M_ * kernel_w_ * kernel_h_ * channels_ * sizeof(Dtype);
cv::AutoBuffer<Dtype, 0> tmpSwizzledWeight(interleaved_filter_size);
for (int od = 0; od < M_; od++)
for (int id = 0; id < channels_; id++)
for (int r = 0; r < kernel_h_; r++)
for (int c = 0; c < kernel_w_; c++)
tmpSwizzledWeight[((id * kernel_h_ + r)* kernel_w_ + c) * M_ + od] =
cpu_weight[((od * channels_ + id) * kernel_h_ + r)*kernel_w_+c];
interleaveMatrix(cpu_swizzled_weight,
tmpSwizzledWeight.data(),
kernel_w_ * kernel_h_ * channels_, M_,
interleavedRows,
nonInterleavedRows,
blockWidth,
rowAlignment);
// unmap OpenCL buffers
weightMat.release();
if (use_half_)
convertFp16(swizzledWeightMat, swizzled_weights_umat);
}
return true;
}
template<>
bool OCL4DNNConvSpatial<float>::createBasicKernel(int32_t blockWidth,
int32_t blockHeight, int32_t blockDepth)
{
kernelType_ = KERNEL_TYPE_BASIC;
blockM_ = blockWidth;
blockK_ = blockHeight;
blockN_ = blockDepth;
setupKernel();
ocl::Program program = compileKernel();
if (program.ptr())
{
int32_t workItemOutput[3] = { 1, 1, 1 };
size_t globalSize[3] = { (size_t)output_w_, (size_t)output_h_, (size_t)M_ };
kernelQueue.push_back(makePtr<kernelConfig>(kernel_name_, &globalSize[0], (const size_t*)NULL, &workItemOutput[0],
false, KERNEL_TYPE_BASIC));
return true;
}
else
return false;
}
template<>
bool OCL4DNNConvSpatial<float>::convolve(const UMat &bottom, UMat &top,
const UMat &weight, const UMat &bias,
int32_t numImages, kernelConfig* config)
{
ocl::Program program;
phash_t::iterator it = phash.find(config->kernelName);
if (it != phash.end())
program = it->second;
else
return false;
int32_t bias_offset;
int32_t element_size = use_half_ ? sizeof(short) : sizeof(float);
if (config->kernelType == KERNEL_TYPE_INTEL_IDLF) {
if (!swizzleWeight(weight, config->workItem_output[2], false))
return false;
#if 0
size_t total_bottom_size = bottom_dim_ * numImages;
size_t total_kernel_size = kernel_h_ * kernel_w_ * channels_ * M_;
size_t total_bias_size = M_ * group_;
size_t total_top_size = top_dim_ * numImages;
#endif
for (int32_t g = 0; g < group_; ++g) {
bias_offset = M_ * g;
int32_t image_offset = width_ * height_ * (channels_ / group_) * g;
int32_t output_image_offset = output_w_ * output_h_ * M_ * g;
int32_t kernel_offset = kernel_h_ * kernel_w_ * (channels_ / group_) * M_ * g;
ocl::Kernel kernel(config->kernelName.c_str(), program);
if (kernel.empty())
return false;
cl_uint argIdx = 0;
setFusionArg(fused_activ_, fused_eltwise_, output_image_offset, kernel, argIdx);
kernel.set(argIdx++, ocl::KernelArg::PtrReadOnly(bottom));
kernel.set(argIdx++, image_offset);
kernel.set(argIdx++, ocl::KernelArg::PtrReadOnly(swizzled_weights_umat));
kernel.set(argIdx++, kernel_offset);
if (bias_term_)
{
kernel.set(argIdx++, ocl::KernelArg::PtrReadOnly(bias));
kernel.set(argIdx++, bias_offset);
}
kernel.set(argIdx++, ocl::KernelArg::PtrWriteOnly(top));
kernel.set(argIdx++, (int)(top.offset / element_size) + output_image_offset);
kernel.set(argIdx++, (uint16_t)width_);
kernel.set(argIdx++, (uint16_t)height_);
kernel.set(argIdx++, (uint16_t)output_w_);
kernel.set(argIdx++, (uint16_t)output_h_);
if (!kernel.run_(3, config->global_work_size, config->local_work_size, false))
{
CV_LOG_ERROR(NULL, "DNN/OpenCL: IDLF kernel run failed");
return false;
}
}
} else if (config->kernelType == KERNEL_TYPE_GEMM_LIKE) {
if (!swizzleWeight(weight, config->workItem_output[1], true))
return false;
#if 0
size_t total_bottom_size = bottom_dim_ * numImages;
size_t total_kernel_size = kernel_h_ * kernel_w_ * channels_ * M_;
size_t total_bias_size = M_ * group_;
#endif
size_t total_top_size = top_dim_ * numImages;
for (int32_t g = 0; g < group_; ++g) {
bias_offset = M_ * g;
int32_t image_offset = width_ * height_ * (channels_ / group_) * g;
int32_t output_image_offset = output_w_ * output_h_ * M_ * g;
int32_t kernel_offset = kernel_h_ * kernel_w_ * (channels_ / group_) * M_ * g;
ocl::Kernel kernel(config->kernelName.c_str(), program);
if (kernel.empty())
return false;
cl_uint argIdx = 0;
setFusionArg(fused_activ_, fused_eltwise_, output_image_offset, kernel, argIdx);
kernel.set(argIdx++, ocl::KernelArg::PtrReadOnly(bottom));
kernel.set(argIdx++, (int)image_offset);
kernel.set(argIdx++, (int)(bottom.total() - image_offset));
kernel.set(argIdx++, ocl::KernelArg::PtrReadOnly(swizzled_weights_umat));
kernel.set(argIdx++, (int)kernel_offset);
kernel.set(argIdx++, (int)(swizzled_weights_umat.total() - kernel_offset));
if (bias_term_)
{
kernel.set(argIdx++, ocl::KernelArg::PtrReadOnly(bias));
kernel.set(argIdx++, (int)bias_offset);
}
kernel.set(argIdx++, ocl::KernelArg::PtrWriteOnly(top));
kernel.set(argIdx++, (int)(top.offset / element_size) + output_image_offset);
kernel.set(argIdx++, (int)total_top_size - (int)(top.offset / element_size));
kernel.set(argIdx++, (uint16_t)width_);
kernel.set(argIdx++, (uint16_t)height_);
kernel.set(argIdx++, (uint16_t)output_w_);
kernel.set(argIdx++, (uint16_t)output_h_);
int out_pitch_y = output_w_ * output_h_;
int out_pitch_z = out_pitch_y * M_;
int aligned_input_size = height_ * width_ * channels_ / group_;
int slice_pitch = width_ * height_;
kernel.set(argIdx++, (uint32_t)out_pitch_y);
kernel.set(argIdx++, (uint32_t)out_pitch_z);
kernel.set(argIdx++, (uint32_t)aligned_input_size);
kernel.set(argIdx++, (uint32_t)slice_pitch);
int blockM = config->workItem_output[0];
int blockK = config->workItem_output[1];
int blockN = config->workItem_output[2];
int alignedFilterWidth = alignSize(M_, blockN);
int alignedExpandHeight = alignSize(output_w_ * output_h_, blockM);
int globalWorkSizeDX = blockN;
int globalWorkSizeDY = blockM;
size_t sgemm_m = alignedExpandHeight;
size_t sgemm_n = alignedFilterWidth;
size_t gx = divUp(sgemm_n, globalWorkSizeDX);
size_t gy = divUp(sgemm_m, globalWorkSizeDY);
gy = alignSize(gy, blockK);
size_t global_size[3] = { gx, gy, config->global_work_size[2] };
if (!kernel.run_(3, global_size, config->local_work_size, false))
{
CV_LOG_ERROR(NULL, "DNN/OpenCL: GEMM like kernel run failed");
return false;
}
}
} else if (config->kernelType == KERNEL_TYPE_DWCONV) {
ocl::Kernel kernel(config->kernelName.c_str(), program);
if (kernel.empty())
return false;
cl_uint argIdx = 0;
setFusionArg(fused_activ_, fused_eltwise_, -1, kernel, argIdx);
kernel.set(argIdx++, ocl::KernelArg::PtrReadOnly(bottom));
kernel.set(argIdx++, ocl::KernelArg::PtrReadOnly(weight));
if (bias_term_)
kernel.set(argIdx++, ocl::KernelArg::PtrReadOnly(bias));
kernel.set(argIdx++, ocl::KernelArg::PtrWriteOnly(top));
kernel.set(argIdx++, (int)(top.offset / element_size));
kernel.set(argIdx++, (uint16_t)width_);
kernel.set(argIdx++, (uint16_t)height_);
kernel.set(argIdx++, (uint16_t)output_w_);
kernel.set(argIdx++, (uint16_t)output_h_);
size_t wgs = kernel.workGroupSize();
if (!wgs)
{
CV_LOG_ERROR(NULL, "DNN/OpenCL: Can't query workGroupSize of DWCONV kernel");
return false;
}
size_t lws[1] = { wgs };
size_t gws[1] = { roundUp((size_t)output_w_ * output_h_ * num_output_ * num_, (unsigned)lws[0]) };
if (!kernel.run_(1, gws, lws, false))
{
CV_LOG_ERROR(NULL, "DNN/OpenCL: DWCONV kernel run failed");
return false;
}
} else {
for (int32_t n = 0; n < numImages; ++n) {
for (int32_t g = 0; g < group_; ++g) {
bias_offset = M_ * g;
int32_t image_offset = n * bottom_dim_
+ width_ * height_ * (channels_ / group_) * g;
int32_t output_image_offset = n * top_dim_
+ output_w_ * output_h_ * M_ * g;
int32_t kernel_offset = kernel_h_ * kernel_w_ *
(channels_ / group_) * M_
* g;
ocl::Kernel kernel(config->kernelName.c_str(), program);
if (kernel.empty())
return false;
cl_uint argIdx = 0;
setFusionArg(fused_activ_, fused_eltwise_, -1, kernel, argIdx);
kernel.set(argIdx++, ocl::KernelArg::PtrReadOnly(bottom));
kernel.set(argIdx++, image_offset);
kernel.set(argIdx++, ocl::KernelArg::PtrReadOnly(weight));
kernel.set(argIdx++, kernel_offset);
if (bias_term_)
kernel.set(argIdx++, ocl::KernelArg::PtrReadOnly(bias));
else
kernel.set(argIdx++, (void *)NULL);
kernel.set(argIdx++, bias_offset);
kernel.set(argIdx++, ocl::KernelArg::PtrWriteOnly(top));
kernel.set(argIdx++, (int)(top.offset / element_size));
kernel.set(argIdx++, output_image_offset);
kernel.set(argIdx++, (uint16_t)width_);
kernel.set(argIdx++, (uint16_t)height_);
kernel.set(argIdx++, (uint16_t)output_w_);
kernel.set(argIdx++, (uint16_t)output_h_);
kernel.set(argIdx++, (uint16_t)pad_w_);
kernel.set(argIdx++, (uint16_t)pad_h_);
size_t wgs = kernel.workGroupSize();
if (!wgs)
{
CV_LOG_ERROR(NULL, "DNN/OpenCL: Can't query workGroupSize of Basic kernel");
return false;
}
size_t lws[1] = { wgs };
size_t gws[1] = { roundUp((size_t)output_w_ * output_h_ * M_, (unsigned)lws[0]) };
if (!kernel.run_(1, gws, lws, false))
{
CV_LOG_ERROR(NULL, "DNN/OpenCL: Basic kernel run failed");
return false;
}
}
}
}
return true;
}
template<>
float OCL4DNNConvSpatial<float>::timedConvolve(const UMat &bottom, UMat &top,
const UMat &weight, const UMat &bias,
int32_t numImages, kernelConfig* config)
{
cv::ocl::Queue queue;
try
{
queue = cv::ocl::Queue::getDefault();
}
catch (const std::exception& e)
{
CV_LOG_ONCE_ERROR(NULL, "OpenCV(ocl4dnn): Can't get OpenCL default queue for auto-tuning: " << e.what());
return 1e6;
}
// warm up.
bool saved_tuned = tuned_;
tuned_ = false;
convolve(bottom, top, weight, bias, numImages, config);
cv::ocl::Timer timer(queue);
timer.start();
bool res = true;;
CV_LOG_INFO(NULL, "Benchmarking kernel: " << config->kernelName);
tuned_ = true;
int loop_cnt = 4;
for (int i = 0; i < loop_cnt; i++) {
res = convolve(bottom, top, weight, bias, numImages, config);
if (!res)
break;
}
tuned_ = saved_tuned;
timer.stop();
if (!res) {
config->tested = true;
config->verified = false;
return 1e5;
}
float elapsedTime = timer.durationNS() * 1e-6 / loop_cnt;
double out_w = output_w_;
double out_h = output_h_;
double out_z = M_;
double k_w = kernel_w_;
double k_h = kernel_h_;
double k_z = channels_;
double totalFlops = ((k_w*k_h*k_z -1)*2)*(out_w*out_h*out_z)*num_;
CV_LOG_INFO(NULL, "\tEstimated Gflops:" << (totalFlops * 1e-9));
CV_LOG_INFO(NULL, "\tEstimated GFLOPS/S: " << ((totalFlops * 1e-9)*(1000.0/elapsedTime)));
return elapsedTime;
}
template<>
bool OCL4DNNConvSpatial<float>::verifyResult(const UMat &bottom,
UMat &top,
const UMat &weight,
const UMat &bias,
int32_t numImages,
kernelConfig* config,
UMat &verifyTop)
{
if (config->verified)
return true;
else if (config->tested)
return false;
//int32_t sz[4] = {numImages, num_output_, output_h_, output_w_};
CV_CheckEQ(top.total(), (size_t)numImages * num_output_ * output_h_ * output_w_, "");
CV_CheckTypeEQ(top.type(), (use_half_) ? CV_16SC1 : CV_32FC1, "");
top.setTo(Scalar::all(0));
bool saved_tuned = tuned_;
tuned_ = false;
convolve(bottom, top, weight, bias, numImages, config);
tuned_ = saved_tuned;
config->tested = true;
UMat new_top, new_verify_top;
Mat mat_top, mat_verify_top;
if (use_half_)
{
convertFp16(top, new_top);
convertFp16(verifyTop, new_verify_top);
mat_top = new_top.getMat(ACCESS_READ);
mat_verify_top = new_verify_top.getMat(ACCESS_READ);
}
else
{
mat_top = top.getMat(ACCESS_READ);
mat_verify_top = verifyTop.getMat(ACCESS_READ);
}
const float* data = mat_top.ptr<float>();
const float* verify_data = mat_verify_top.ptr<float>();
int error_slice_offset = 0;
int error_slice = 0;
float relative_eps = use_half_ ? 0.1f : 0.01f;
size_t errors = 0;
double rel_err = norm(mat_top.reshape(1, 1), mat_verify_top.reshape(1, 1), NORM_L1 | NORM_RELATIVE);
if (rel_err >= relative_eps)
{
for (int32_t n = 0; n < num_; ++n) {
for (int32_t g = 0; g < group_; ++g) {
int32_t output_image_offset = n * top_dim_ + output_w_ * output_h_ * M_ * g;
for (int out_ch = 0; out_ch < M_; out_ch++)
for (int h = 0; h < output_h_; h++)
for (int w = 0; w < output_w_; w++) {
size_t offset = output_image_offset + out_ch * output_w_ * output_h_ + h * output_w_ + w;
bool has_error = !(data[offset] == data[offset]); // is NaN
if (!has_error)
{
float error_factor = std::fabs(data[offset] - verify_data[offset]);
float base_value_abs = std::max(1e-3f, std::fabs(verify_data[offset]));
has_error = error_factor > relative_eps * base_value_abs;
}
if (has_error)
{
if (errors == 0)
{
error_slice = (int)(offset / (output_w_ * output_h_));
error_slice_offset = (int)(offset % (output_w_ * output_h_));
CV_LOG_ERROR(NULL, "Kernel: " << config->kernelName);
}
if (errors < 10)
CV_LOG_ERROR(NULL, "test verification failed @ image " << n << " group " << g
<< " out_ch " << out_ch << " h " << h << " w " << w
<< " (offset: " << offset << ")"
<< " got " << data[offset] << " expected " << verify_data[offset]);
errors++;
}
}
}
}
}
if (errors)
{
if (dumpFailedResult())
{
try
{
int n_outputs = (int)(mat_top.size[0]*mat_top.size[1]);
int slice_size = (int)(mat_top.total() / n_outputs);
Rect roi(0, 0, slice_size, n_outputs);
roi.width = std::min(roi.width, 32);
roi.height = std::min(roi.height, 16);
roi.x = std::max(0, std::min(slice_size - roi.width, error_slice_offset - roi.width/2));
roi.y = std::max(0, std::min(n_outputs - roi.height, error_slice - roi.height/2));
std::cout << "roi = " << roi << " errors=" << errors << std::endl;
std::cout << "mat_top = " << shape(mat_top) << std::endl
<< mat_top.reshape(1, 1).reshape(1, n_outputs)(roi) << std::endl;
std::cout << "verify_top = " << shape(mat_verify_top) << std::endl
<< mat_verify_top.reshape(1, 1).reshape(1, n_outputs)(roi) << std::endl;
}
catch (const std::exception& e)
{
CV_LOG_ERROR(NULL, "Results dump failed: " << e.what());
}
catch (...)
{
CV_LOG_ERROR(NULL, "Results dump failed")
}
}
if (raiseOnCheckError())
CV_Error_(Error::StsError, ("ocl4dnn tuning verification failed: %s (errors %lld)", config->kernelName.c_str(), (long long int)errors));
return false;
}
else
{
config->verified = true;
return true;
}
}
template<typename Dtype>
void OCL4DNNConvSpatial<Dtype>::unloadProgram(const std::string& kernelName)
{
ocl::Program program;
phash_t::iterator it = phash.find(kernelName);
if (it != phash.end())
{
program = it->second;
it->second = ocl::Program();
}
else
return;
ocl::Context ctx = ocl::Context::getDefault();
ctx.unloadProg(program);
}
template<typename Dtype>
ocl::Program OCL4DNNConvSpatial<Dtype>::compileKernel()
{
phash_t::iterator it = phash.find(kernel_name_);
if (it != phash.end())
{
return it->second;
}
String errmsg;
ocl::Context ctx = ocl::Context::getDefault();
std::string options = options_.str();
CV_Assert(options.size() != 0);
ocl::Program program = ctx.getProg(src_, options, errmsg);
phash.insert(std::pair<std::string, ocl::Program>(kernel_name_, program));
if (!program.ptr())
{
CV_LOG_WARNING(NULL, "DNN/OpenCL: Failed to compile kernel: " << kernel_name_
<< ", buildflags: '" << options << "', errmsg: '" << errmsg << "'"
);
}
return program;
}
template<>
bool OCL4DNNConvSpatial<float>::createGEMMLikeConvKernel(int32_t blockM,
int32_t blockK,
int32_t blockN)
{
int32_t simd_size = blockK;
int workItemOutput[3] = { blockM, blockK, blockN };
size_t gx = (size_t)divUp(M_, blockN);
size_t gy = (size_t)divUp(output_w_ * output_h_, blockM);
gy = alignSize(gy, simd_size);
size_t gz = num_;
size_t global_size[3] = { gx, gy, gz };
size_t local_size[3] = { 1, static_cast<size_t>(simd_size), 1 };
kernelType_ = KERNEL_TYPE_GEMM_LIKE;
blockM_ = blockM;
blockK_ = blockK;
blockN_ = blockN;
setupKernel();
ocl::Program program = compileKernel();
if (program.ptr())
{
ocl::Kernel kernel(kernel_name_.c_str(), program);
if (kernel.empty())
return false;
kernelQueue.push_back(makePtr<kernelConfig>(kernel_name_, &global_size[0], &local_size[0], &workItemOutput[0],
true, KERNEL_TYPE_GEMM_LIKE));
return true;
}
else
return false;
}
template<>
bool OCL4DNNConvSpatial<float>::createIDLFKernel(int32_t blockWidth,
int32_t blockHeight,
int32_t simd_size)
{
int32_t workItemOutput[3] = { blockWidth, blockHeight, simd_size };
const int32_t num_output_maps = M_;
int32_t output_width = output_w_;
int32_t output_height = output_h_;
int32_t output_block_width = blockWidth;
int32_t output_block_height = blockHeight;
int32_t num_batches = num_;
size_t global_size[3] = {
(size_t)divUp(output_width, output_block_width),
(size_t)divUp(output_height, output_block_height),
(size_t)num_batches * alignSize(num_output_maps, simd_size) };
size_t local_size[3] = { 1, 1, static_cast<size_t>(simd_size) };
kernelType_ = KERNEL_TYPE_INTEL_IDLF;
blockM_ = blockWidth;
blockK_ = blockHeight;
blockN_ = simd_size;
setupKernel();
if (enableWorkaroundIDLF() && ocl::Device::getDefault().intelSubgroupsSupport())
{
// Issues are observed with these kernels: 3x1 (covered by tests), 2x1, 4x1, 5x1, 3x2
// kernels 1x3, 3x3, 2x3 are good
if (pad_h_ != 0 && kernel_w_ <= simd_size && kernel_h_ <= 2)
{
CV_LOG_INFO(NULL, "DNN(workaround): skip IDLF kernel: " << kernel_name_);
return false;
}
}
ocl::Program program = compileKernel();
if (program.ptr())
{
ocl::Kernel kernel(kernel_name_.c_str(), program);
if (kernel.empty())
return false;
kernelQueue.push_back(makePtr<kernelConfig>(kernel_name_, &global_size[0], &local_size[0], &workItemOutput[0],
true, KERNEL_TYPE_INTEL_IDLF));
return true;
}
else
return false;
}
template<>
bool OCL4DNNConvSpatial<float>::createDWConvKernel(int32_t blockWidth,
int32_t blockHeight,
int32_t blockDepth)
{
if (!dwconv_)
return false;
int workItemOutput[3] = { 1, 1, 1 };
size_t local_size[3] = { 1, 1, 1 };
size_t global_size[3];
global_size[0] = divUp(output_w_, workItemOutput[0]);
global_size[1] = divUp(output_h_, workItemOutput[1]);
global_size[2] = divUp(M_ * num_, workItemOutput[2]);
kernelType_ = KERNEL_TYPE_DWCONV;
blockM_ = blockWidth;
blockK_ = blockHeight;
blockN_ = blockDepth;
setupKernel();
ocl::Program program = compileKernel();
if (program.ptr())
{
kernelQueue.push_back(makePtr<kernelConfig>(kernel_name_, &global_size[0], &local_size[0],
&workItemOutput[0], false, KERNEL_TYPE_DWCONV));
return true;
}
else
return false;
}
template<>
bool OCL4DNNConvSpatial<float>::createConvolutionKernel(int32_t kernelType,
int32_t blockWidth,
int32_t blockHeight,
int32_t blockDepth)
{
kernelType_ = kernelType;
options_.str(""); options_.clear(); // clear contents and state flags
src_ = ocl::ProgramSource();
if (kernelType == KERNEL_TYPE_INTEL_IDLF)
return createIDLFKernel(blockWidth, blockHeight, blockDepth);
else if (kernelType == KERNEL_TYPE_BASIC)
return createBasicKernel(blockWidth, blockHeight, blockDepth);
else if (kernelType == KERNEL_TYPE_GEMM_LIKE)
return createGEMMLikeConvKernel(blockWidth, blockHeight, blockDepth);
else if (kernelType == KERNEL_TYPE_DWCONV)
return createDWConvKernel(blockWidth, blockHeight, blockDepth);
else
CV_Assert(0 && "Internal error");
return false;
}
template<>
void OCL4DNNConvSpatial<float>::generate_gemmlike_tuneritems(std::vector< cv::Ptr<tunerParam> > &tunerItems,
int blockM, int blockK, int blockN)
{
if (group_ != 1 || ((M_ % 8 != 0) || (M_ % 32 == 24)))
return;
if (blockM != 1 && blockM != 2)
return;
if (blockN != 32)
return;
if (blockK != 8 && blockK != 16)
return;
if (blockK == 16)
{
if ((blockM == 1 && (kernel_w_ > 4)) || M_ % 32 != 0)
return;
if ((blockM == 2) || M_ % 32 != 0)
return;
}
tunerItems.push_back(makePtr<tunerParam>(KERNEL_TYPE_GEMM_LIKE, blockM, blockK, blockN));
}
template<>
void OCL4DNNConvSpatial<float>::generate_idlf_tuneritems(std::vector< cv::Ptr<tunerParam> > &tunerItems,
int blockM, int blockK, int simd_size)
{
int max_compute_units = ocl::Device::getDefault().maxComputeUnits();
if (simd_size != 8 && simd_size != 16)
return;
if (simd_size == 8 && !((group_ == 1 || M_ % 8 == 0)))
return;
if (simd_size == 16 && !(group_ == 1 || M_ % 16 == 0))
return;
int width_max, height_max, block_size_max;
width_max = 14;
height_max = 14;
block_size_max = 32;
if (blockM > width_max)
return;
if (blockK > height_max)
return;
if (blockM > output_w_)
return;
if (blockK > output_h_)
return;
// Only when the work items count is less than the device
// max work items or the M_ is less than 16, we will tune
// for simd 8.
if (simd_size == 8 && M_ >= 16 &&
((num_ * M_ * output_w_ * output_h_ / static_cast<float>(blockM * blockK)) >=
max_compute_units * 7 * 16))
return;
int actual_tile_x = kernel_w_ * dilation_w_ + (blockM - 1) * stride_w_ ;
int tile_x = alignSize(actual_tile_x, simd_size);
if (tile_x > simd_size)
return;
if (blockM * blockK > block_size_max)
return;
tunerItems.push_back(makePtr<tunerParam>(KERNEL_TYPE_INTEL_IDLF, blockM, blockK, simd_size));
}
template<>
void OCL4DNNConvSpatial<float>::generate_dwconv_tuneritems(std::vector< cv::Ptr<tunerParam> > &tunerItems,
int blockM, int blockK, int blockN)
{
if (!dwconv_)
return;
tunerItems.push_back(makePtr<tunerParam>(KERNEL_TYPE_DWCONV, blockM, blockK, blockN));
}
template<>
void OCL4DNNConvSpatial<float>::generateTunerItems(std::vector< cv::Ptr<tunerParam> > &tunerItems)
{
if (ocl::Device::getDefault().intelSubgroupsSupport())
{
// depthwise kernel
generate_dwconv_tuneritems(tunerItems, 1, 1, 1);
if (tunerItems.size() > 0 && group_ > 8)
return;
// gemm like kernel
generate_gemmlike_tuneritems(tunerItems, 1, 8, 32);
generate_gemmlike_tuneritems(tunerItems, 2, 8, 32);
generate_gemmlike_tuneritems(tunerItems, 1, 16, 32);
generate_gemmlike_tuneritems(tunerItems, 2, 16, 32);
// idlf kernel
for (int simd_size = 8; simd_size <= 16; simd_size += 8)
{
int width_max, height_max;
width_max = 14;
height_max = 14;
for (uint32_t width = width_max; width > 0; width--)
{
for (uint32_t height = height_max; height > 0; height--)
{
generate_idlf_tuneritems(tunerItems, width, height, simd_size);
}
}
}
}
}
template<>
void OCL4DNNConvSpatial<float>::useFirstAvailable(const UMat &bottom,
UMat &top,
const UMat &weight,
const UMat &bias,
int32_t numImages,
UMat &verifyTop)
{
std::vector< cv::Ptr<tunerParam> > tunerItems;
generateTunerItems(tunerItems);
tunerItems.push_back(makePtr<tunerParam>(KERNEL_TYPE_BASIC, 1, 1, 1));
for (int i = 0; i < tunerItems.size(); i++)
{
if (createConvolutionKernel(tunerItems[i]->kernelType,
tunerItems[i]->blockWidth,
tunerItems[i]->blockHeight,
tunerItems[i]->blockDepth))
{
CV_Assert(!kernelQueue.empty()); // basic kernel must be available
int kernelIdx = kernelQueue.size() - 1;
kernelConfig* config = kernelQueue[kernelIdx].get();
bool failed = false;
const size_t testCount = testAllKernels();
for(int t = 0; t < testCount; t++)
{
try
{
config->tested = false;
config->verified = false;
if (!verifyResult(bottom, top, weight, bias, numImages, config, verifyTop))
{
CV_LOG_ERROR(NULL, "Failed on test iteration: " << t);
failed = true;
break;
}
}
catch (...)
{
CV_LOG_ERROR(NULL, "Failed on test iteration: " << t);
throw;
}
}
if (!failed && verifyResult(bottom, top, weight, bias, numImages, config, verifyTop))
{
bestKernelConfig = kernelQueue[kernelIdx];
if (bestKernelConfig->kernelType != KERNEL_TYPE_INTEL_IDLF &&
bestKernelConfig->kernelType != KERNEL_TYPE_GEMM_LIKE)
if (!swizzled_weights_umat.empty())
swizzled_weights_umat.release();
for (int32_t j = 0; j < kernelIdx; j++) {
CV_Assert(phash.find(kernelQueue[j]->kernelName) != phash.end());
unloadProgram(kernelQueue[j]->kernelName);
}
kernelQueue.clear();
tuned_ = true;
break;
}
}
}
}
template<>
void OCL4DNNConvSpatial<float>::cacheTunedConfig()
{
if (tuned_)
{
cv::AutoLock lock(kernelConfigMutex);
std::stringstream outputKernel;
outputKernel << bestKernelConfig->workItem_output[0] << " "
<< bestKernelConfig->workItem_output[1] << " "
<< bestKernelConfig->workItem_output[2] << " "
<< bestKernelConfig->kernelType << " "
<< bestKernelConfig->local_work_size[0] << " "
<< bestKernelConfig->local_work_size[1] << " "
<< bestKernelConfig->local_work_size[2] << " "
<< bestKernelConfig->swizzle_weights << " "
<< bestKernelConfig->use_null_local << " ";
kernelConfigMap.insert(std::pair<std::string, std::string>(key_, outputKernel.str()));
}
}
template<>
void OCL4DNNConvSpatial<float>::setupConvolution(const UMat &bottom,
UMat &top,
const UMat &weight,
const UMat &bias,
int32_t numImages,
UMat &verifyTop)
{
std::vector< cv::Ptr<tunerParam> > tunerItems;
generateTunerItems(tunerItems);
for (int i = 0; i < tunerItems.size(); i++)
createConvolutionKernel(tunerItems[i]->kernelType,
tunerItems[i]->blockWidth,
tunerItems[i]->blockHeight,
tunerItems[i]->blockDepth);
const size_t testCount = testAllKernels();
for (int32_t x = 0; x < kernelQueue.size(); x++)
{
kernelConfig* config = kernelQueue[x];
config->executionTime = timedConvolve(bottom, top, weight, bias, numImages, config);
for(int t = 0; t < testCount; t++)
{
try
{
config->tested = false;
config->verified = false;
bool verified = verifyResult(bottom, top, weight, bias, numImages, config, verifyTop);
if (verified == false)
{
CV_LOG_ERROR(NULL, "Kernel " << config->kernelName << " failed verification");
CV_LOG_ERROR(NULL, "workItem="
<< config->workItem_output[0] << ","
<< config->workItem_output[1] << ","
<< config->workItem_output[2] << " "
<< "kernelType: " << config->kernelType << " "
<< "global_work_size="
<< config->global_work_size[0] << ","
<< config->global_work_size[1] << ","
<< config->global_work_size[2] << " "
<< "local_work_size="
<< config->local_work_size[0] << ","
<< config->local_work_size[1] << ","
<< config->local_work_size[2] << " "
<< config->swizzle_weights << " "
<< config->use_null_local);
}
else
{
CV_LOG_VERBOSE(NULL, 0, "Kernel " << config->kernelName << " pass verification");
}
}
catch (...)
{
CV_LOG_ERROR(NULL, "Failed on test iteration: " << t);
throw;
}
}
}
int32_t failures = 0;
bool verification = false;
if (kernelQueue.size()) {
while (failures < kernelQueue.size()) {
int32_t fastestKernel = -1;
float fastestTime = std::numeric_limits<float>::infinity();
for (int32_t x = 0; x < kernelQueue.size(); x++) {
if (kernelQueue[x]->executionTime < fastestTime &&
kernelQueue[x]->tested == false) {
fastestKernel = x;
fastestTime = kernelQueue[x]->executionTime;
}
}
if (fastestKernel < 0)
break;
// Test fastest kernel
bool verified = verifyResult(bottom, top, weight, bias, numImages, kernelQueue[fastestKernel], verifyTop);
if (verified == true) {
kernel_index_ = fastestKernel;
verification = true;
break;
} else {
CV_LOG_ERROR(NULL, "Kernel " << kernelQueue[fastestKernel]->kernelName <<
" failed verification");
failures++;
}
}
}
if (verification) {
CV_LOG_INFO(NULL, "Kernel <" << kernelQueue[kernel_index_]->kernelName <<
"> passed verification");
CV_LOG_INFO(NULL, "Convolution Time:" << kernelQueue[kernel_index_]->executionTime);
double out_w = output_w_;
double out_h = output_h_;
double out_z = M_;
double k_w = kernel_w_;
double k_h = kernel_h_;
double k_z = channels_;
float elapsedTime = kernelQueue[kernel_index_]->executionTime;
double totalFlops = ((k_w*k_h*k_z -1)*2)*(out_w*out_h*out_z)*num_;
CV_LOG_INFO(NULL, "\tEstimated Gflops:" << (totalFlops * 1e-9));
CV_LOG_INFO(NULL, "\tEstimated GFLOPS/S: " << ((totalFlops * 1e-9)*(1000.0/elapsedTime)));
} else {
CV_LOG_INFO(NULL, "fallback to basic kernel");
options_.str(""); options_.clear(); // clear contents and state flags
createBasicKernel(1, 1, 1);
CV_Assert(!kernelQueue.empty()); // basic kernel must be available
kernel_index_ = kernelQueue.size() - 1;
}
this->bestKernelConfig = kernelQueue[kernel_index_];
if (bestKernelConfig->kernelType != KERNEL_TYPE_INTEL_IDLF && bestKernelConfig->kernelType != KERNEL_TYPE_GEMM_LIKE)
if (!swizzled_weights_umat.empty())
swizzled_weights_umat.release();
for (int32_t x = 0; x < kernelQueue.size(); x++) {
if (x != kernel_index_) {
CV_Assert(phash.find(kernelQueue[x]->kernelName) != phash.end());
unloadProgram(kernelQueue[x]->kernelName);
}
}
kernelQueue.clear();
tuned_ = true;
saveTunedConfig();
}
template<typename Dtype>
void OCL4DNNConvSpatial<Dtype>::saveTunedConfig()
{
CV_Assert(tuned_);
if (!use_cache_path_ || cache_path_.empty())
return;
std::string outputFile;
outputFile = cache_path_ + "/" + key_sanitized_;
std::ofstream outputKernel;
outputKernel.open(outputFile.c_str());
outputKernel << bestKernelConfig->workItem_output[0] << " "
<< bestKernelConfig->workItem_output[1] << " "
<< bestKernelConfig->workItem_output[2] << " "
<< bestKernelConfig->kernelType << " "
<< bestKernelConfig->local_work_size[0] << " "
<< bestKernelConfig->local_work_size[1] << " "
<< bestKernelConfig->local_work_size[2] << " "
<< bestKernelConfig->swizzle_weights << " "
<< bestKernelConfig->use_null_local << " ";
outputKernel.close();
}
template<typename Dtype>
void OCL4DNNConvSpatial<Dtype>::prepareKernel(const UMat &bottom, UMat &top,
const UMat &weight, const UMat &bias,
int32_t numImages)
{
std::string previous_key = key_;
generateKey();
if (key_.compare(previous_key) == 0 && bestKernelConfig)
return;
if (bestKernelConfig)
{
prev_kernel_type_ = bestKernelConfig->kernelType;
CV_Assert(phash.find(bestKernelConfig->kernelName) != phash.end());
phash.erase(bestKernelConfig->kernelName);
bestKernelConfig.release();
}
if (loadCachedConfig()) // check in-memory cache
return;
if (loadTunedConfig()) // check external storage
return;
UMat benchData(1, numImages * top_dim_, (use_half_) ? CV_16SC1 : CV_32FC1);
calculateBenchmark(bottom, benchData, weight, bias, numImages);
if (run_auto_tuning_ || force_auto_tuning_)
{
setupConvolution(bottom, top, weight, bias, numImages, benchData);
}
else
{
useFirstAvailable(bottom, top, weight, bias, numImages, benchData);
}
cacheTunedConfig();
}
template<typename Dtype>
bool OCL4DNNConvSpatial<Dtype>::loadCachedConfig()
{
cv::AutoLock lock(kernelConfigMutex);
if (!defaultConfigLoaded && !force_auto_tuning_)
initializeGlobalBuiltinConfigurations((use_cache_path_ && !cache_path_.empty()) ? (cache_path_ + '/') : std::string());
kernel_hash_t::iterator it = kernelConfigMap.find(key_);
if (it != kernelConfigMap.end())
{
int32_t x, y, z, type, lx, ly, lz;
bool swizzle, nullLocal;
std::stringstream cachedKernel(it->second);
if (cachedKernel)
{
cachedKernel >> x;
cachedKernel >> y;
cachedKernel >> z;
cachedKernel >> type;
cachedKernel >> lx;
cachedKernel >> ly;
cachedKernel >> lz;
cachedKernel >> swizzle;
cachedKernel >> nullLocal;
if (setupKernelByConfig(x, y, z, type, lx, ly, lz, swizzle, nullLocal)) {
tuned_ = true;
return true;
}
}
}
return false;
}
template<typename Dtype>
bool OCL4DNNConvSpatial<Dtype>::setupKernelByConfig(int x, int y, int z, int type,
int lx, int ly, int lz,
bool swizzle, bool nullLocal)
{
if (type == KERNEL_TYPE_INTEL_IDLF)
{
if (z == 1)
z = 16;
CV_Check(z, z == 16 || z == 8, "DNN/OpenCL: IDLF - invalid SIMD size");
}
kernelQueue.clear();
createConvolutionKernel(type, x, y, z);
if (kernelQueue.size() != 1)
{
CV_LOG_ERROR(NULL, "DNN/OpenCL: Failed setup kernel by config: "
<< " x = " << x
<< " y = " << y
<< " z = " << z
<< " type = " << type
);
return false;
}
bestKernelConfig = kernelQueue[0];
kernelQueue.clear();
bestKernelConfig->local_work_size[0] = lx;
bestKernelConfig->local_work_size[1] = ly;
bestKernelConfig->local_work_size[2] = lz;
bestKernelConfig->swizzle_weights = swizzle;
bestKernelConfig->use_null_local = nullLocal;
// If kernel type changed to type 2 or 4, we need to reset the swizzled
// weights pointer to invalidate the previous swizzled weights data.
if (prev_kernel_type_ != bestKernelConfig->kernelType &&
(bestKernelConfig->kernelType == KERNEL_TYPE_INTEL_IDLF ||
bestKernelConfig->kernelType == KERNEL_TYPE_GEMM_LIKE))
{
if (!swizzled_weights_umat.empty())
swizzled_weights_umat.release();
}
return true;
}
template<typename Dtype>
bool OCL4DNNConvSpatial<Dtype>::loadTunedConfig()
{
if (force_auto_tuning_)
return false; // don't load results from external storage
if (!use_cache_path_)
{
if (cache_path_.empty())
{
CV_LOG_ONCE_WARNING(NULL, "OpenCV(ocl4dnn): consider to specify kernel configuration cache directory "
"through OPENCV_OCL4DNN_CONFIG_PATH parameter."
);
}
return false;
}
int32_t x, y, z, type, lx, ly, lz;
bool swizzle, nullLocal;
// Find cached kernel configuration from file
std::string cacheFile = cache_path_ + "/" + key_sanitized_;
std::ifstream cachedKernel(cacheFile.c_str());
if (cachedKernel)
{
cachedKernel >> x;
cachedKernel >> y;
cachedKernel >> z;
cachedKernel >> type;
cachedKernel >> lx;
cachedKernel >> ly;
cachedKernel >> lz;
cachedKernel >> swizzle;
cachedKernel >> nullLocal;
if (setupKernelByConfig(x, y, z, type, lx, ly, lz, swizzle, nullLocal)) {
tuned_ = true;
return true;
}
}
return false;
}
template class OCL4DNNConvSpatial<float>;
}}} // namespace cv::dnn::ocl4dnn
|
84b45a498b037a1e0ec5689af215f10e353a67b4
|
29a8394c699636cf02218cdf44c172df7847ffef
|
/routelab-w15_agam_edits/messages.cc
|
c0c984b3ad198edc3df2923794e39f90a998a01a
|
[] |
no_license
|
aiqiliu/EECS340
|
7ecb450b77426e0dcae5cd18111f7326605fcfbb
|
52f70930770688631a3f97688c8375ec9a1e3432
|
refs/heads/master
| 2021-01-10T14:04:37.508291
| 2016-03-14T21:20:40
| 2016-03-14T21:20:40
| 49,908,787
| 0
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 781
|
cc
|
messages.cc
|
#include "messages.h"
#if defined(GENERIC)
ostream &RoutingMessage::Print(ostream &os) const
{
os << "RoutingMessage()";
return os;
}
#endif
#if defined(LINKSTATE)
ostream &RoutingMessage::Print(ostream &os) const
{
return os;
}
RoutingMessage::RoutingMessage()
{}
RoutingMessage::RoutingMessage(const RoutingMessage &rhs)
{}
#endif
#if defined(DISTANCEVECTOR)
ostream &RoutingMessage::Print(ostream &os) const
{
os << "RoutingMessage(src=" << src << ", dest=" << dest << ", cost=" << cost << ")";
return os;
}
RoutingMessage::RoutingMessage()
{}
RoutingMessage::RoutingMessage(const RoutingMessage &rhs) :
src(rhs.src), dest(rhs.dest), cost(rhs.cost)
{}
RoutingMessage::RoutingMessage(Node s, Node d, double c) :
src(s), dest(d), cost(c)
{}
#endif
|
09798f187d1caa042f180c318ade3032c32811cf
|
0fdc8677fe5cd71cb30d16d25c0900c93a5176d4
|
/software/remote_controlled/robocar/src/car/sensors/SteeringServo.cpp
|
ad375235deecc7f2fdb44a28843d47039c2d7c59
|
[
"MIT"
] |
permissive
|
bierschi/robo_car
|
6365503c1cdc7bcd20e6cef946626dd5bf85a3ff
|
f3b308afd9b53a252d07f041c4cae9cbe007ecf3
|
refs/heads/master
| 2022-01-09T05:03:38.883476
| 2021-12-30T14:55:31
| 2021-12-30T14:55:31
| 145,824,540
| 7
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,889
|
cpp
|
SteeringServo.cpp
|
//
// Created by christian on 16.10.18.
//
#include "car/sensors/SteeringServo.h"
/**
* Constructor for a SteeringServo instance
*
* USAGE:
* SteeringServo* ss = new SteeringServo(15);
*
* @param chan: connected channel number of the steering servo
*/
SteeringServo::SteeringServo(uint8_t chan) : PCA9685(1, 0x40, 60),
channel(chan),
xLeft(2100),
xRight(1600)
{
}
/**
* Destructor in SteeringServo
*/
SteeringServo::~SteeringServo() {
}
/**
*moves the steering servo to the left side
*/
void SteeringServo::driveLeft() {
PCA9685::setPWM(channel, 1750, 1895);
}
/**
* moves the steering servo between 0% - 100%, where 0% is straight ahead and 100% is driveLeft()
*
* @param x: int value between 0 and 100
*/
void SteeringServo::driveXLeft(int x) {
if (x >= 100) {
xLeft = 1900;
} else if (x <= 0) {
xLeft = 2100;
} else {
xLeft = xLeft - (2*x);
}
PCA9685::setPWM(channel, 1750, xLeft);
//set default value
xLeft = 2100;
}
/**
* moves the steering servo to the right side
*/
void SteeringServo::driveRight() {
PCA9685::setPWM(channel, 1230, 1720);
}
/**
* moves the steering servo between 0% - 100%, where 0% is straight ahead and 100% is driveRight()
*
* @param x: int value between 0 and 100
*/
void SteeringServo::driveXRight(int x) {
if (x >= 100) {
xRight = 1720;
} else if (x <= 0) {
xRight = 1600;
} else {
xRight = xRight + (1.2*x);
}
xRight = round(xRight);
PCA9685::setPWM(channel, 1230, (int)xRight);
//set default value
xRight = 1600;
}
/**
* moves the steering servo to the middle
*/
void SteeringServo::driveStraight() {
PCA9685::setPWM(channel, 1770, 2130); //1750-1770
}
|
39574931342337ca0ef3193177383259f62a1419
|
c4105848e5400b630f42f2871067a5397c90a6f0
|
/Apoc/Video/Display.h
|
c6c51c47762a8285f3384d1ca43ed98aec9acd43
|
[
"BSD-2-Clause"
] |
permissive
|
madd-games/apocalypse
|
759a5f8ae17ca33a67e783f03964f06fff9ab1f5
|
ea2192079801d7bea9afaeb3246cb975ab0e37d6
|
refs/heads/master
| 2016-09-02T04:43:33.466918
| 2014-12-31T18:42:39
| 2014-12-31T18:42:39
| 24,066,309
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,358
|
h
|
Display.h
|
/*
Copyright (c) 2014-2015, Madd Games.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef APOC_VIDEO_DISPLAY_H
#define APOC_VIDEO_DISPLAY_H
#include <Apoc/Math/Matrix.h>
#include <Apoc/Math/Vector.h>
#include <Apoc/Video/OpenGL.h>
#include <string>
using namespace std;
/**
* \brief Handles the display of 2D overlays.
*
* Never make instances of this class! Only use the reference passed to onOverlay()
* in Game.
*/
class Display
{
private:
int screenWidth;
int screenHeight;
Matrix matProj;
GLuint uIsParticle; // we set uIsParticle to 2 in the fragment shader to draw overlays.
GLuint uDiffuseColor;
GLuint uProjMatrix;
GLuint uViewMatrix;
GLuint uTexMatrix;
GLuint vao, vbo;
public:
/**
* \brief Arrays of glyphs are used as fonts.
*
* Terminate the list of glyphs with a glyph for codepoint 0.
*/
struct Glyph
{
/**
* \brief The Unicode codepoint for this glyph.
*/
unsigned long codepoint;
int x, y, width, height;
int fontWidth, fontHeight;
};
private:
Glyph* findGlyph(Glyph *font, unsigned long codepoint);
public:
/**
* \brief Constructor. Do not use.
*/
Display(int width, int height);
/**
* \brief Do not use.
*/
void beginDisplay();
/**
* \brief Set the color to draw things with.
*/
void color(Vector col);
/**
* \brief Set the texture to draw stuff with.
*/
void texture(string name);
/**
* \brief Set the texture to "plain".
*/
void notex();
/**
* \brief Sets which part of the texture to apply.
*
* The coordinates and size are normalized.
*/
void texcrop(float x, float y, float width, float height);
/**
* \brief Draw a rectangle.
*/
void rect(int x, int y, int width, int height);
/**
* \brief Draw text.
* \param font An array of Glyph structures, terminated with a glyph for codepoint 0.
* \param str UTF-8 formatted string.
*/
void text(int x, int y, Glyph *font, string str);
/**
* \brief Draw the mouse cursor using the current texture.
* \param width Width of the cursor.
* \param height Height of the cursor.
*/
void cursor(int width, int height);
};
#endif
|
033d4e70c457723f6100564ec1bfaca3d2c1eaf6
|
1b855eb71f8e51c9f858c61c6ad02fc3a649698d
|
/qrtmidi.cpp
|
334749ddb38ca8623a7fe108cc40af2d051cbb8a
|
[
"MIT",
"LicenseRef-scancode-synthesis-toolkit"
] |
permissive
|
scryver/rtmidi
|
7fcefaa18d620831b84b2756ced564fb89aca28d
|
9efbf34a71b3860e5d84cb0d3b1186b56697197e
|
refs/heads/master
| 2021-01-15T23:51:15.627923
| 2016-06-03T14:04:12
| 2016-06-03T14:04:12
| 50,730,357
| 0
| 0
| null | 2016-06-03T14:04:13
| 2016-01-30T15:22:53
|
C++
|
UTF-8
|
C++
| false
| false
| 5,550
|
cpp
|
qrtmidi.cpp
|
#include "qrtmidi.h"
#include <QLoggingCategory>
#include <QDebug>
QLoggingCategory midiLogCat("midi");
void midiError(RtMidiError::Type type, const std::string& errorText,
void *userData = nullptr) {
switch (type) {
case RtMidiError::WARNING:
qCWarning(midiLogCat) << errorText.c_str();
break;
case RtMidiError::DEBUG_WARNING:
qCDebug(midiLogCat) << errorText.c_str();
break;
case RtMidiError::UNSPECIFIED:
case RtMidiError::NO_DEVICES_FOUND:
case RtMidiError::INVALID_DEVICE:
case RtMidiError::INVALID_PARAMETER:
case RtMidiError::INVALID_USE:
qCCritical(midiLogCat) << errorText.c_str();
break;
case RtMidiError::MEMORY_ERROR:
case RtMidiError::DRIVER_ERROR:
case RtMidiError::SYSTEM_ERROR:
case RtMidiError::THREAD_ERROR:
qFatal("%s", errorText.c_str());
break;
}
}
void midiCallback(double timeStamp, std::vector<unsigned char> *message,
void *userData) {
QRtMidi* qtMidiObj = reinterpret_cast<QRtMidi*>(userData);
qtMidiObj->emitMidiMessage(timeStamp, *message);
}
QRtMidi::QRtMidi(QObject *parent) : QObject(parent),
m_midiIn(nullptr),
m_midiOut(nullptr)
{
try {
m_midiIn = new RtMidiIn(RtMidi::UNSPECIFIED, "QRtMidiIn", 256);
m_midiIn->setErrorCallback(&midiError);
m_midiIn->setCallback(&midiCallback, this);
} catch (RtMidiError& e) {
midiError(e.getType(), e.getMessage());
m_midiIn = nullptr;
}
try {
m_midiOut = new RtMidiOut(RtMidi::UNSPECIFIED, "QRtMidiOut");
m_midiOut->setErrorCallback(&midiError);
} catch (RtMidiError& e) {
midiError(e.getType(), e.getMessage());
m_midiOut = nullptr;
}
}
QRtMidi::~QRtMidi() {
if (m_midiIn != nullptr) {
delete m_midiIn;
m_midiIn = nullptr;
}
if (m_midiOut != nullptr) {
delete m_midiOut;
m_midiOut = nullptr;
}
}
void QRtMidi::setInputDevice(int id) {
if (id != m_deviceIn.id) {
setDevice(id, m_midiIn, &m_deviceIn,
&QRtMidi::inputClosed, &QRtMidi::inputOpened);
}
}
void QRtMidi::setInputDevice(QString name) {
if (name != m_deviceIn.name) {
setDevice(name, m_midiIn, &m_deviceIn,
&QRtMidi::inputClosed, &QRtMidi::inputOpened);
}
}
void QRtMidi::setOutputDevice(int id) {
if (id != m_deviceOut.id) {
setDevice(id, m_midiOut, &m_deviceOut,
&QRtMidi::outputClosed, &QRtMidi::outputOpened);
}
}
void QRtMidi::setOutputDevice(QString name) {
if (name != m_deviceOut.name) {
setDevice(name, m_midiOut, &m_deviceOut,
&QRtMidi::outputClosed, &QRtMidi::outputOpened);
}
}
void QRtMidi::emitMidiMessage(double timeStamp,
const std::vector<unsigned char>& message) {
// m_lastReceived.clear();
// for (size_t i = 0; i < message->size(); i++) {
// m_lastReceived.push_back(message->at(i));
// }
emit received(timeStamp, message);
}
void QRtMidi::setDevice(int id, RtMidi* rtMidiHandler, MIDI::Device* device,
void (QRtMidi::*closeSignal)(),
void (QRtMidi::*openSignal)()) {
if (rtMidiHandler == nullptr) {
return;
}
rtMidiHandler->closePort();
emit (this->*closeSignal)();
if (id >= 0 && id < static_cast<int>(rtMidiHandler->getPortCount())) {
rtMidiHandler->openPort(id);
device->id = id;
device->name = (rtMidiHandler->getPortName(static_cast<unsigned int>(id))).c_str();
emit (this->*openSignal)();
}
}
void QRtMidi::setDevice(QString name, RtMidi* rtMidiHandler,
MIDI::Device* device,
void (QRtMidi::*closeSignal)(),
void (QRtMidi::*openSignal)()) {
if (rtMidiHandler == nullptr) {
return;
}
unsigned int numPorts = rtMidiHandler->getPortCount();
QString portName;
int deviceID = -1;
for (unsigned int i = 0; i < numPorts; i++) {
portName = (rtMidiHandler->getPortName(i)).c_str();
if (portName == name) {
deviceID = static_cast<int>(i);
break;
}
}
setDevice(deviceID, rtMidiHandler, device, closeSignal, openSignal);
}
QStringList QRtMidi::getDeviceList(RtMidi* rtMidiHandler) const {
QStringList driverNames;
driverNames.clear();
if (rtMidiHandler == nullptr) {
return driverNames;
}
unsigned int numPorts = rtMidiHandler->getPortCount();
driverNames << QString(tr(MIDI_NO_DEVICE_SELECTED));
for (unsigned int i = 0; i < numPorts; i++) {
driverNames << QString::fromStdString(rtMidiHandler->getPortName(i));
}
if (driverNames.size() == 1) {
driverNames.clear();
driverNames << QString(tr(MIDI_NO_DEVICE_FOUND));
}
return driverNames;
}
void QRtMidi::send(const std::vector<unsigned char>& message) {
if (m_midiOut == nullptr) {
return;
}
m_lastSend = message;
m_midiOut->sendMessage(&m_lastSend);
}
void QRtMidi::send(unsigned char status, unsigned char command) {
std::vector<unsigned char> message = { status, command };
send(message);
}
void QRtMidi::send(unsigned char status, unsigned char command, unsigned char value) {
std::vector<unsigned char> message = { status, command, value };
send(message);
}
|
11f50967d3302df2178b82690ad8a823b39b6c9b
|
2f05d3dec54f3d72bd8405b1bf34d7b73cb0bf03
|
/code/exp-3-bgl/self.cpp
|
773dde1e2b9f1ed88749406099144cc16275c106
|
[] |
no_license
|
anirudhakulkarni/Parallel-MCMF-at-IISc-Research
|
3ee6c61c190b95c7effcc7256ba76c87de29563c
|
ac1f794df529f2f1d002f79ae2c0d26f757e2f1a
|
refs/heads/master
| 2023-06-17T12:25:17.610142
| 2021-07-10T11:05:42
| 2021-07-10T11:05:42
| 368,953,615
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,171
|
cpp
|
self.cpp
|
#include <vector>
#include <chrono>
#include <iostream>
using namespace std;
#include <string>
#include <queue>
#include <tuple>
#define ln "\n"
#define out1(x1) cout << x1 << ln
#define out2(x1,x2) cout << x1 << " " << x2 << ln
#define out3(x1,x2,x3) cout << x1 << " " << x2 << " " << x3 << ln
#define out4(x1,x2,x3,x4) cout << x1 << " " << x2 << " " << x3 << " " << x4 << ln
#define out5(x1,x2,x3,x4,x5) cout << x1 << " " << x2 << " " << x3 << " " << x4 << " " << x5 << ln
#define out6(x1,x2,x3,x4,x5,x6) cout << x1 << " " << x2 << " " << x3 << " " << x4 << " " << x5 << " " << x6 << ln
using namespace std::chrono;
const int INF = 1e9;
struct Edge
{
int from, to, capacity, cost;
};
vector<vector<int>> getNodes(int numberOfNodes)
{
vector<vector<int>> nodes;
for (int i = 1; i < numberOfNodes + 1; i++)
{
nodes.push_back({i});
}
return nodes;
}
vector<int> randomList(int size, int sum)
{
vector<int> arr(size);
for (int i = 0; i < size; i++)
{
arr[i] = 1;
}
for (int i = 0; i < sum - size; i++)
{
arr[rand() % size]++;
}
return arr;
}
tuple<vector<vector<int>>, vector<vector<int>>> distributeSourceSink(vector<vector<int>> nodes, int numberOfSources, int totalCapacity, int totalRequirement)
{
vector<vector<int>> sources;
vector<vector<int>> sinks;
for (int i = 1; i < numberOfSources+1; i++)
{
sources.push_back({i});
}
// cout<<"Sources inside:\n";
// for (int i = 0; i < sources.size(); i++)
// {
// cout<<sources[i][0]<<endl;
// }
for (int i = numberOfSources+1; i < nodes.size()+1; i++)
{
sinks.push_back({i});
}
vector<int> sinkRequirement = randomList(sinks.size(), totalRequirement);
vector<int> sourceCapacity = randomList(sources.size(), totalCapacity);
for (int i = 0; i < sources.size(); i++)
{
sources[i].push_back(sourceCapacity[i]);
}
for (int i = 0; i < sinks.size(); i++)
{
sinks[i].push_back(sinkRequirement[i]);
}
return make_tuple(sources, sinks);
}
vector<Edge> getEdges(vector<vector<int>> sources, vector<vector<int>> sinks)
{
vector<Edge> edges;
for (int i = 0; i < sources.size(); i++)
{
for (int j = 0; j < sinks.size(); j++)
{
Edge edge;
edge.from=sources[i][0];
edge.to=sinks[i][0];
edge.capacity=INF;
edge.cost=rand()%10+2;
// edge.push_back(sources[i][0]);
// edge.push_back(sinks[j][0]);
// edge.push_back(); //weight
edges.push_back(edge);
}
}
return edges;
}
vector<vector<int>> adj, cost, capacity;
void shortest_paths(int n, int v0, vector<int>& d, vector<int>& p) {
d.assign(n, INF);
d[v0] = 0;
vector<bool> inq(n, false);
queue<int> q;
q.push(v0);
p.assign(n, -1);
while (!q.empty()) {
int u = q.front();
q.pop();
inq[u] = false;
for (int v : adj[u]) {
if (capacity[u][v] > 0 && d[v] > d[u] + cost[u][v]) {
d[v] = d[u] + cost[u][v];
p[v] = u;
if (!inq[v]) {
inq[v] = true;
q.push(v);
}
}
}
}
}
int min_cost_flow(int N, vector<Edge> edges, int K, int s, int t) {
adj.assign(N, vector<int>());
cost.assign(N, vector<int>(N, 0));
capacity.assign(N, vector<int>(N, 0));
for (Edge e : edges) {
adj[e.from].push_back(e.to);
adj[e.to].push_back(e.from);
cost[e.from][e.to] = e.cost;
cost[e.to][e.from] = -e.cost;
capacity[e.from][e.to] = e.capacity;
}
int flow = 0;
int cost = 0;
vector<int> d, p;
while (flow < K) {
shortest_paths(N, s, d, p);
if (d[t] == INF)
break;
// find max flow on that path
int f = K - flow;
int cur = t;
while (cur != s) {
f = min(f, capacity[p[cur]][cur]);
cur = p[cur];
}
// apply flow
flow += f;
cost += f * d[t];
cur = t;
while (cur != s) {
capacity[p[cur]][cur] -= f;
capacity[cur][p[cur]] += f;
cur = p[cur];
}
}
if (flow < K)
return -1;
else
return cost;
}
int main(){
vector<vector<int>> experiments;
for (int i = 0; i < 1; i++)
{
experiments.push_back({500, 500 * (i + 1)});
}
for (int i = 0; i < experiments.size(); i++)
{
int numberOfSrcs = experiments[i][0];
int numberOfSnks = experiments[i][1];
int numberOfNodes = numberOfSrcs + numberOfSnks;
int totalCapacity = 10;
int totalRequirement = 10;
vector<vector<int>> nodes = getNodes(numberOfNodes);
vector<vector<int>> sources;
vector<vector<int>> sinks;
tie(sources, sinks) = distributeSourceSink(nodes, numberOfSrcs,totalCapacity,totalRequirement);
vector<Edge> edges = getEdges(sources, sinks);
min_cost_flow(numberOfNodes,edges,)
// cout<<"sanity check\n";
// for (int i = 0; i < nodes.size(); i++)
// {
// cout<<nodes[i][0]<<" "<<nodes[i][1]<<endl;
// }
// cout<<"Sources\n";
// for (int i = 0; i < sources.size(); i++)
// {
// cout<<sources[i][0]<<" "<<sources[i][1]<<endl;
// }
// cout<<"Sinks\n";
// for (int i = 0; i < sinks.size(); i++)
// {
// cout<<sinks[i][0]<<" "<<sinks[i][1]<<endl;
// }
// cout<<"Edges\n";
// for (int i = 0; i < edges.size(); i++)
// {
// out4(edges[i][0],edges[i][1],edges[i][2],edges[i][3]);
// }
cout<<"Starting\n";
auto start = high_resolution_clock::now();
auto stop = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(stop - start);
cout << "Time taken by function: "<< duration.count() << " microseconds" << endl;
cout << cost << endl;
}
// assert(cost == 29);
return 0;
}
|
e35fcae948f8e8f09eb5c929c333d92efda60c72
|
9604f51a1260755940a18839f7e5b2728464da9e
|
/src/Plane.hpp
|
3cc8c11b2b105290ddc0b2d1af7ed9e84e0a6fe5
|
[] |
no_license
|
vivichrist/Renderer308
|
a92d13b99c3f4a4ebe25ee2b504cad4dc134ef06
|
8e39e617024c859e40a49f08a23e3bf7ee2cbee8
|
refs/heads/master
| 2021-01-17T14:02:12.413090
| 2017-01-07T04:28:27
| 2017-01-07T04:28:27
| 41,473,174
| 0
| 0
| null | 2015-10-21T10:26:55
| 2015-08-27T07:51:46
|
C
|
UTF-8
|
C++
| false
| false
| 688
|
hpp
|
Plane.hpp
|
/*
* Plane.h
*
* Created on: 4/02/2015
* Author: vivichrist
*/
#pragma once
#define GLM_FORCE_RADIANS
#include <glm/glm.hpp>
using namespace std;
namespace R308
{
class Plane
{
public:
// point in the plane, normal orthogonal to the plane
Plane();
Plane( const glm::vec3& point, const glm::vec3& normal );
static Plane fromPoints( const glm::vec3& p0
, const glm::vec3& p1
, const glm::vec3& p2 );
float distance( const glm::vec3& point );
float distance( const Plane& point );
glm::vec3 normal();
glm::vec4 plane();
virtual ~Plane();
private:
glm::vec4 parameters;
glm::vec3 point;
};
} // end vogl namespace
|
81a2f140ebb66b9020cd541690d0b06a0e929356
|
ed17d8b5ff69ee5485c0778bec5852fdca50f87f
|
/src/score/statistics.h
|
684a95efa90c2e1db5ecd9848c31b0ed8b5f8aa1
|
[] |
no_license
|
IceAndSnow/touchdown
|
6202f41a91d2816a2307232d8d72be412bcf400e
|
63f134b1c12b85a4a590fb57134c6bb11cdf34b4
|
refs/heads/master
| 2021-07-17T10:03:13.384416
| 2020-08-11T20:48:56
| 2020-08-11T20:48:56
| 198,452,981
| 0
| 1
| null | 2020-08-11T20:48:57
| 2019-07-23T14:59:45
|
C++
|
UTF-8
|
C++
| false
| false
| 757
|
h
|
statistics.h
|
#ifndef TOUCHDOWN_STATISTICS_H
#define TOUCHDOWN_STATISTICS_H
#include "player_statistics.h"
#include "statistics_entry.h"
#include <vector>
#include <unordered_map>
namespace score {
struct Statistics {
std::unordered_map<std::string, PlayerStatistics> m_player_statistics;
void clear();
void print();
void eprint();
void addEntry(const StatisticsEntry entry);
private:
std::vector<std::pair<std::string, PlayerStatistics>> getPlayerNames();
unsigned int getNumberOfEntries();
unsigned int getWins(std::string playerName);
unsigned int getLosses(std::string playerName);
unsigned int getTies(std::string playerName);
};
}
#endif //TOUCHDOWN_STATISTICS_H
|
cbbb53e53fd99c0564b8f86040674bfaf951cddb
|
d926904d5081c2ced7346a6a317222b40c876c9e
|
/testpq/testDB.cpp
|
2898bb50cfbfbfc504afd6e574ee4ad84a999f1a
|
[] |
no_license
|
lifunudt/pq
|
28371d74583e1adfd59e93553ebdaf84425f239a
|
ab8a6e146c9ca621f333a124493827ad247c1cb8
|
refs/heads/master
| 2016-09-13T07:20:59.665487
| 2016-05-14T03:25:26
| 2016-05-14T03:25:26
| 58,785,273
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,816
|
cpp
|
testDB.cpp
|
/*************************************************************************
> File Name: testDB.cpp
> Author: lifu
> Mail: lifunudt@163.com
> Created Time: 二 4/19 20:24:18 2016
************************************************************************/
#include <iostream>
#include <string>
#include <cstdio>
#include "rtabmap/core/DBDriver.h"
using namespace std;
using namespace rtabmap;
int main() {
//DBDriver * db = 0;
const string url = "";
cout<<"hello world\n";
//db.connectDatabaseQuery( url, 0 );
//printf( "the connect stats is : %s\n",db->getUrl().c_str());
/*
std::string sql = " create table testnoresultexe ( id int primary key, age int ) ;";
db.executeNoResultQuery( sql );
sql = " insert into testnoresultexe(id, age) values( 1,22 );";
db.executeNoResultQuery( sql );
//test the func:getDatabaseVersionQuery
string dbversion = "";
db.getDatabaseVersionQuery( dbversion );
cout<<"the dbversion is :"<<dbversion<<endl;
//test loadnode
sql = " create table data ( id int primary key, mapid int, stamp float, weight int ) ;";
db.executeNoResultQuery( sql );
sql = " insert into data (id, mapid, stamp, weight) values( 1, 2, 3.4, 5 );";
db.executeNoResultQuery( sql );
sql = " insert into data (id, mapid, stamp, weight) values( 2, 3, 4.5, 6 );";
db.executeNoResultQuery( sql );
std::list<Signature *> sigs;
Signature t_sig1, t_sig2;
t_sig1.id = 1;
sigs.push_back( &t_sig1 );
t_sig2.id = 2;
sigs.push_back( &t_sig2 );
db.loadNodeDataQuery( sigs );
sql = " drop table data ; ";
db.executeNoResultQuery( sql );
db.disconnectDatabaseQuery();
printf( "the connect stats is : %d\n",(int)db.isConnectedQuery());
*/
return 0;
}
|
a3bb010f19d645b3a7e4408b64f920b8d89626ae
|
e94456baaaef5a2847bcf3fbebcbc250fc5ea5ac
|
/Number_Theory/Permutation.cpp
|
ebf5fb4ae7498afa7d40272a489f1016e3f320aa
|
[
"Unlicense"
] |
permissive
|
Kyabc/Algorithms-and-DataStructures
|
bb780298c0fde6f2c4f48bed57dffad5a053ebde
|
23c3d40d086238a942772cead7981a599741f94f
|
refs/heads/master
| 2021-08-03T14:34:16.623388
| 2021-07-19T14:47:22
| 2021-07-19T14:47:22
| 221,580,897
| 7
| 1
| null | 2020-07-15T12:39:23
| 2019-11-14T00:56:47
|
C++
|
UTF-8
|
C++
| false
| false
| 607
|
cpp
|
Permutation.cpp
|
#include <vector>
template<std::int_fast32_t mod>
struct permutation {
private :
std::vector<modint<mod>> fact, ifact;
public :
permutation(int n) : fact(n + 1), ifact(n + 1) {
fact[0] = 1;
for (int i = 1; i < n + 1; i++) fact[i] = (fact[i - 1] * i);
ifact[n] = inverse(fact[n]);
for (int i = n; i > 0; i--) ifact[i - 1] = ifact[i] * i;
}
modint<mod> operator() (int n, int r) {
if (r < 0 or r > n) return 0;
return fact[n] * ifact[n - r];
}
constexpr const modint<mod> &operator[] (int i) const {
return fact[i];
}
};
|
b605ad6a7e43a1e0f65ef87ce0c9f9876d29e5b3
|
19842f800160fdb4f0266e1d13c3e868542d75cb
|
/include/ext/libSun/wx/wxIrrWindow.cpp
|
0514f4ed8ab4f9fbcc65c3e8077d58aa8175ce66
|
[] |
no_license
|
benjaminhampe/DarkGDK
|
3e32b404d9aafb014a08c39324153bc1888771b8
|
32823a6b350caef3c114daf60d954b73994e3517
|
refs/heads/master
| 2020-06-02T04:05:29.866871
| 2014-02-28T21:33:30
| 2014-02-28T21:33:30
| 17,301,390
| 1
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,850
|
cpp
|
wxIrrWindow.cpp
|
#include "wxIrrWindow.h"
#include <gtk/gtk.h>
#include <gdk/gdkx.h>
wxIrrDevice::wxIrrDevice()
{
Device = NULL;
}
wxIrrDevice::wxIrrDevice(HWND hwnd, IrrVideoDriverType type, bool bResizeable)
{
Create(hwnd, type, bResizeable);
}
wxIrrDevice::~wxIrrDevice()
{
if ( Device )
{
Device->closeDevice();
Device->drop();
}
}
IrrDevice *wxIrrDevice::Create( HWND hwnd, IrrVideoDriverType type, bool bResizeable)
{
if (Device)
return Device;
IrrDeviceParams params;
// ExposedData.OpenGLLinux.X11Context = glXGetCurrentContext();
// ExposedData.OpenGLLinux.X11Display = glXGetCurrentDisplay();
// ExposedData.OpenGLLinux.X11Window = (unsigned long)Params.WindowId;
// Drawable = glXGetCurrentDrawable();
// X11Display = (Display*)ExposedData.OpenGLLinux.X11Display;
// extGlSwapInterval(Params.Vsync ? 1 : 0);
GtkWidget *widget = hwnd;
Window xid = gdk_x11_drawable_get_xid( gtk_widget_get_window(widget));
// It is C because Gtk+ is a C API, but it is also C++, so there should be no problem.
//And don't forget to !
params.WindowId = reinterpret_cast<void *>( (unsigned long)xid );
params.DriverType = type;
params.Fullscreen = false;
params.LoggingLevel = irr::ELL_INFORMATION;
params.Doublebuffer = true;
Device = irr::createDeviceEx(params);
if (Device)
{
Device->setResizable( bResizeable );
}
return Device;
}
IrrCamera *wxIrrDevice::AddCamera( IrrNode *parent, const IrrVec3f &position, const IrrVec3f &lookat, s32 id)
{
IrrSceneManager *smgr=GetSceneManager();
if (smgr)
return (IrrCamera*)smgr->addCameraSceneNode( parent, position, lookat );
else
return NULL;
}
////////////////////////////////////////////////////////////////////////////////
BEGIN_EVENT_TABLE(wxIrrWindow, wxWindow)
EVT_PAINT(wxIrrWindow::OnPaint)
EVT_SIZE(wxIrrWindow::OnSize)
EVT_TIMER( wxID_ANY, wxIrrWindow::OnTimer)
EVT_MOTION( wxIrrWindow::OnMouseMove)
EVT_LEFT_DOWN(wxIrrWindow::OnMouseLeftDown)
EVT_LEFT_UP(wxIrrWindow::OnMouseLeftUp)
END_EVENT_TABLE()
wxIrrWindow::wxIrrWindow(wxWindow *parent, wxWindowID id, long style, IrrVideoDriverType type, bool bResizeable)
: wxWindow( parent, id, wxDefaultPosition, wxDefaultSize, style )
{
Camera = NULL;
Device = wxIrrDevice::Create( wxWindow::GetHandle(), type, bResizeable );
m_timer.SetOwner(this, wxID_ANY);
// font = Device->getGUIEnvironment()->getBuiltInFont();
// m_viewportmanager.SetFont(font);
}
wxIrrWindow::~wxIrrWindow()
{
if ( Camera )
Camera->remove();
}
void wxIrrWindow::OnPaint(wxPaintEvent &event)
{
wxPaintDC dc( this );
doUpdate();
event.Skip();
}
void wxIrrWindow::doUpdate()
{
if ( Device )
{
IrrVideoDriver *driver = Device->getVideoDriver();
IrrSceneManager *smgr = Device->getSceneManager();
IrrGUIEnvironment* env = Device->getGUIEnvironment();
IrrCamera* camera = smgr->getActiveCamera();
if ( driver && smgr && camera && env)
{
driver->beginScene(true, true, IrrColor(255,0,0,0) );
smgr->drawAll();
env->drawAll();
// m_viewportmanager.OnPaint(driver, scenemgr, Camera);
driver->endScene();
}
}
}
void wxIrrWindow::OnSize(wxSizeEvent &event)
{
// resize viewports
// m_viewportmanager.OnSize(event);
if ( Device )
{
IrrVideoDriver *driver=GetVideoDriver();
if ( driver )
{
driver->OnResize( IrrDim2u(GetClientSize().GetWidth(), GetClientSize().GetHeight()) );
if ( !m_timer.IsRunning() )
Update();
}
}
event.Skip();
}
void wxIrrWindow::OnTimer(wxTimerEvent &event)
{
OnSceneUpdate();
Refresh( false );
event.Skip();
}
void wxIrrWindow::OnMouseMove(wxMouseEvent &event)
{
// m_viewportmanager.OnMouseMove(event);
// if ( m_viewportmanager.NeedRefresh() && (!m_timer.IsRunning()) )
// Refresh(false);
event.Skip();
}
void wxIrrWindow::OnMouseLeftDown(wxMouseEvent &event)
{
// m_viewportmanager.OnMouseLeftDown(event);
// if ( m_viewportmanager.NeedRefresh() && (!m_timer.IsRunning()) )
// Refresh(false);
event.Skip();
}
void wxIrrWindow::OnMouseLeftUp(wxMouseEvent &event)
{
// m_viewportmanager.OnMouseLeftUp(event);
}
//
// Do the update of your scene here
//
void wxIrrWindow::OnSceneUpdate(void)
{
IrrSceneManager *scene=GetSceneManager();
if ( scene )
{
IrrNode *cube=scene->getSceneNodeFromId( 1 );
if (cube)
{
IrrVec3f yaw=cube->getRotation();
yaw.X += 1.0;
yaw.Y += 0.5;
yaw.Z += 0.25;
cube->setRotation( yaw );
}
}
}
IrrCamera *wxIrrWindow::AddCamera(IrrNode *parent, const IrrVec3f &position, const IrrVec3f &lookat, s32 id, bool bsetcurrent)
{
IrrCamera *newcamera=NULL;
IrrVec3f pos = position;
IrrVec3f look = lookat;
if (Device)
{
// newcamera = wxIrrDevice::AddCamera(parent, position, lookat, id);
newcamera = wxIrrDevice::AddCamera(parent, pos, look, id);
if ( bsetcurrent )
Camera = newcamera;
}
return newcamera;
}
|
d02b8bb85581775116da951e747212574f6f3765
|
264986797dc81119bfda672fda2a4bbdfe674e8f
|
/0533.cpp
|
2108c0c63fd30465a716b1810bb3143f375989f8
|
[] |
no_license
|
imdew1990/algotester
|
6e530c5fd4cfa2a59aade0e5f393fa3f3f08dabe
|
3fc0b188e7eebf28661c5048b127c5616501de84
|
refs/heads/main
| 2023-03-24T06:26:19.509395
| 2021-03-06T06:50:15
| 2021-03-06T06:50:15
| 345,026,440
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 328
|
cpp
|
0533.cpp
|
#include <bits/stdc++.h>
using namespace std;
string olo(string s)
{
string k;
return k;
}
int main()
{
string s, k;
cin >> s;
while (s.size() > 0)
{
k.push_back(s.front());
s.erase(s.begin());
if (s.size() > 1)
{
k.push_back(s.back());
s.erase(s.size() - 1);
}
}
cout << k << endl;
system("pause");
}
|
11894e26fab34bae8b5bc1dd5034abdea626cc35
|
8121ed9d8fed6078b763bdf49d427a58ddc38b12
|
/13023.cpp
|
8f02efee76d405ca39e308a35960f4aaa10facb9
|
[] |
no_license
|
jkjan/Baekjoon
|
e6e2663eb567c470cb3ce78d7e80a17763a8a1ff
|
e5cd2ba8bdd91234cce82e6c1cd9a4ae169478da
|
refs/heads/master
| 2022-12-18T01:00:27.002673
| 2020-09-13T13:01:59
| 2020-09-13T13:01:59
| 293,594,468
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,148
|
cpp
|
13023.cpp
|
#include <iostream>
#include <vector>
#include <algorithm>
#define MAX_SIZE 2000
using namespace std;
vector<int> graph[MAX_SIZE];
bool visited[MAX_SIZE] = {false, };
int level[MAX_SIZE] = {0, };
int input();
bool dfs(int v, int depth);
bool compare(int a, int b) {
return level[a] < level[b];
}
int main() {
int N = input();
bool exists = false;
for (int i = 0; i < N; ++i) {
sort(graph[i].begin(), graph[i].end(), compare);
}
for (int i = 0; i < N; ++i) {
fill(visited, visited + MAX_SIZE, false);
if (dfs(i, 1))
exists = true;
}
printf("%d", exists);
return 0;
}
int input() {
int N, M, a, b;
scanf(" %d %d", &N, &M);
for (int i = 0; i < M; ++i) {
scanf(" %d %d", &a, &b);
graph[a].push_back(b);
graph[b].push_back(a);
level[a]++;
level[b]++;
}
return N;
}
bool dfs(int v, int depth) {
visited[v] = true;
if (depth == 5)
return true;
for (auto adj : graph[v]) {
if (!visited[adj]) {
if (dfs(adj, depth + 1))
return true;
}
}
return false;
}
|
716223501f02c21dc41fb296c5677cc7f296694f
|
817adba1d173e1c822d29b46183398c3cde7f9b8
|
/alea/alea.cpp
|
2c4a81707a91e19c144789cbe3dab41b4ba85366
|
[] |
no_license
|
DrDam/RDN-Core
|
89adcd686830555aa52bdf130da5a3bb469301a7
|
6db01ce4dba14788bf1cac93ca9ebcccea4da53b
|
refs/heads/master
| 2021-01-01T17:09:50.848433
| 2015-03-25T18:17:33
| 2015-03-25T18:17:33
| 22,768,559
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 319
|
cpp
|
alea.cpp
|
#include <stdlib.h>
#include <assert.h>
int alea( int n )
{
assert (0 < n && n <= RAND_MAX);
unsigned int partSize = (RAND_MAX) / (n+1);
unsigned int firstToBeDropped = partSize * (n+1);
unsigned int draw;
do {
draw = rand();
} while (draw >= firstToBeDropped);
return draw % (n + 1);
}
|
13de085bb9c0d7c659012f596759c6832e444202
|
a753a5900180eae398ddd45cd6922d972007440c
|
/data/tplcache/698c2ab4927ead658e002aad18858a04.inc
|
b40d7196d455fc55ef3c75407ca3594b2c75880b
|
[] |
no_license
|
liyee/Instruments
|
6475cb0f22ae651973403c6e9f74ce1008562ccf
|
5e47a47e600c66ceb5af7ce3c1e77ac761c171c9
|
refs/heads/master
| 2020-07-26T15:24:44.443858
| 2019-11-12T08:00:16
| 2019-11-12T08:00:16
| 208,688,586
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 90
|
inc
|
698c2ab4927ead658e002aad18858a04.inc
|
{dede:img text='' width='971' height='368'} /uploads/190719/1-1ZG92131152K.jpg {/dede:img}
|
e0810b0f240cf1642a70011063996dc5d91f3e9f
|
ef8f557bc75f620cb94db76734eaf9b04cfa01bf
|
/abc/abc175/b.cpp
|
23f2c408318f709fffa09bc9862567d9d4ce3c44
|
[] |
no_license
|
Kanazawanaoaki/atcoder_memo
|
3273d52093ab3e4a3c2a312dfc9658c8e1df820c
|
4f4dcb847d3479cb1f5ef01710c0e101a3bd6dfb
|
refs/heads/master
| 2021-08-17T02:37:51.175202
| 2020-09-01T02:55:11
| 2020-09-01T02:55:11
| 217,087,895
| 0
| 0
| null | 2020-03-23T02:36:08
| 2019-10-23T15:12:49
|
C++
|
UTF-8
|
C++
| false
| false
| 643
|
cpp
|
b.cpp
|
#include <bits/stdc++.h>
using namespace std;
int check(int i, int j, int k, vector<int> &l){
int flag = 0;
if( l[i]!=l[j] && l[j]!=l[k] && l[k]!=l[i]) flag =1;
if(flag==1){
int maxl = max(l[i],l[j]);
maxl = max(maxl, l[k]);
if(maxl < l[i]+l[j]+l[k]-maxl) flag =2;
}
if(flag==2){
return 1;
} else {
return 0;
}
}
int main() {
int n;
cin >> n;
vector<int> l(n);
for(int i=0; i<n; i++){
cin >> l[i];
}
int ans = 0;
for(int i=0;i<n-2;i++){
for(int j=i;j<n-1;j++){
for(int k=j; k<n;k++){
if(check(i,j,k,l)==1){
ans++;
}
}
}
}
cout << ans << endl;
return 0;
}
|
8b9308f74b4f73c6a81ea9a999b6e38aaf0715ae
|
2d06c74333e68648337384c39fbfbff20f98d6d1
|
/guziqiu/02.c++/00.cpp预习/06.友元函数.cpp
|
333ed07d917a7814e77ce5054793c65cc2d92e18
|
[] |
no_license
|
guziqiu/qiu
|
b7573698825374145139e4f2b0231e9198d552c8
|
0221f078eb570e6c0998b9798c4767a750548d7b
|
refs/heads/master
| 2023-06-04T13:24:13.330675
| 2021-07-02T06:13:09
| 2021-07-02T06:13:09
| 381,987,030
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,136
|
cpp
|
06.友元函数.cpp
|
#include <iostream>
#include <cmath>
using namespace std;
class PointManager {
public:
double PointDistance(Point &p1, Point &p2);
};
class Point {
public:
Point(int x, int y) {
this->x = x;
this->y = y;
}
int getX() {
return this->x;
}
int getY() {
return this->y;
}
private:
int x;
int y;
// 声明全局函数PointDistance是类Point类的一个友元函数
//friend double PointDistance(Point &p1, Point &p2);
friend double PointManager::PointDistance(Point &p1, Point &p2);
};
#if 0
double PointDistance(Point &p1, Point &p2) {
double dis;
int ddx = p1.x - p2.x;
int ddy = p1.y - p2.y;
dis = sqrt(ddx * ddx + ddy * ddy);
return dis;
}
#endif
double PointManager::PointDistance(Point &p1, Point &p2) {
double dis;
int ddx = p1.x - p2.x;
int ddy = p1.y - p2.y;
dis = sqrt(ddx * ddx + ddy * ddy);
return dis;
}
int main() {
Point p1(1, 2);
Point p2(2, 4);
//cout << PointDistance(p1, p2) << endl;
PointManager pm;
cout << pm.PointDistance(p1, p2) << endl;
return 0;
}
|
b0faa918e1b4c2e17c7f2f8d8ed5f8658d0c4cee
|
0c1abc428cf3d18ef3c6681f8f29bc4e7fb010e4
|
/LW_1/Library.cpp
|
9171bf8b3caa83144658ab35344b78472e03df5b
|
[] |
no_license
|
Black-Viking-63/LW_1_TP
|
593ab664866e13f8d9a168d574423b0ff9d0cf7f
|
53e0948b43d9ff01774e6f51f6bba276ba376f74
|
refs/heads/master
| 2023-03-06T04:53:14.899436
| 2021-02-24T08:55:36
| 2021-02-24T08:55:36
| null | 0
| 0
| null | null | null | null |
WINDOWS-1251
|
C++
| false
| false
| 1,817
|
cpp
|
Library.cpp
|
#include "pch.h"
#include <utility>
#include <limits.h>
#include "Library.h"
#include "iostream"
using namespace std;
double d, d1, x, y, x0, x1;
double discriminant(long long a, long long b, long long c)
{
d = pow(b, 2) - 4 * a * c;
return d;
}
void equation_solution(long long a, long long b, long long c)
{
d = discriminant(a, b, c);
d1 = -discriminant(a, b, c);
x = 0.0;
y = 0.0;
if (d > 0)
{
cout << "Дискриминант = " << sqrt(d) << ". Следовательно имеем два вещественных корня." << "\n";
cout << "Первый вещественный корень:" << "\n";
x = (-b - sqrt(d)) / (2 * a);
cout << x;
cout << "\n" << "Второй вещественный корень:" << "\n";
y = (-b + sqrt(d)) / (2 * a);
cout << y;
cout << "\n" << "Решение урованения найдено.";
}
if (d < 0)
{
cout << "Дискриминант = -" << sqrt(d1) << ". Следовательно уравнение вещественного решения не имеет." << "\n" << "Будем искать комплексное решение уравнения." << "\n";
cout << "Первый комплексный корень:" << "\n";
x0 = -(double)b / (2 * a);
x1 = sqrt(d1) / (2 * a);
cout << "x = " << x0 << " + i * " << x1 << endl;
cout << "\n" << " Второй вещественный корень:" << "\n";
cout << "x = " << x0 << " - i * " << x1 << endl;
cout << "\n" << "Решение урованения найдено.";
}
if (d == 0)
{
cout << "Дискриминант = " << d << ". Следовательно имеем один вещественный корень:" << "\n";
x = (-b) / (2 * a);
cout << x << "\n" << "Решение урованения найдено.";
}
}
|
b5e6edf8188c268251817673aa4ff47c17bfc70f
|
52c96c707172d0d6c7bfb3b672b2eb86a76473fc
|
/src/PartsForm/PartsForm.cpp
|
2317ba6aba835a760ca4dc8c2e341ee55fd2719b
|
[] |
no_license
|
Naify/Transport
|
9bc428549da408dbcbbd9b5c7e85343beca2f9ee
|
b9be3740882fdb7f097f42a04f4546f76574369e
|
refs/heads/main
| 2023-04-24T18:50:06.904708
| 2021-05-12T13:57:43
| 2021-05-12T13:57:43
| 366,734,389
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,134
|
cpp
|
PartsForm.cpp
|
#include "PartsForm/PartsForm.h"
#include "header_view/ProxyModelWithHeaderModels.h"
#include "PartsForm/PartsModel.h"
#include "PartsForm/PartsItemDelegate.h"
#include <OdsInterface>
#include "global_defs.h"
#include "OrderForm/orderform.h"
#include <QDebug>
PartsForm::PartsForm(int id, ODS::OdsInterface* iface, QWidget *parent) :
QWidget(parent),
m_model(0),
m_headerModel(0),
m_proxy_header(0),
m_iface(iface),
m_order_id(id)
{
setupUi(this);
init();
}
//
PartsForm::~PartsForm()
{
delete m_proxy_header;
delete m_headerModel;
delete m_model;
}
//
void PartsForm::init()
{
HierarchicalHeaderView* hv = new HierarchicalHeaderView(Qt::Horizontal, tvParts);
tvParts->setHorizontalHeader(hv);
m_model = new PartsModel(m_order_id, m_iface, tvParts);
m_model->setColumnCount(11);
m_headerModel = new QStandardItemModel(tvParts);
fillHeaderModel(m_headerModel);
m_proxy_header = new ProxyModelWithHeaderModels(tvParts);
#if QT_VERSION >= 0x050000
m_proxy_header->setSourceModel(m_model);
#else
m_proxy_header->setModel(m_model);
#endif
m_proxy_header->setHorizontalHeaderModel(m_headerModel);
tvParts->setItemDelegate(new PartsItemDelegate(tvParts));
tvParts->setModel(m_proxy_header);
tvParts->resizeColumnsToContents();
tvParts->verticalHeader()->setVisible(false);
#if QT_VERSION >= 0x050000
tvParts->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
tvParts->verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
#else
tvParts->horizontalHeader()->setResizeMode(QHeaderView::Stretch);
tvParts->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents);
#endif
//
connect (pbAdd, SIGNAL(clicked()),
this, SLOT(addParts()));
connect (pbDel, SIGNAL(clicked()),
this, SLOT(removeParts()));
connect (pbCancel, SIGNAL(clicked()),
this, SLOT(cancelParts()));
connect (pbSave, SIGNAL(clicked()),
this, SLOT(save()));
connect (pushButton_exit, SIGNAL(clicked()),
this, SLOT(closeForm()));
connect(cbOrder, SIGNAL(currentIndexChanged(int)),
this, SLOT(orderChanged(int)));
initOrders();
}
void PartsForm::closeForm()
{
this->parentWidget()->close();
}
//
void PartsForm::fillHeaderModel(QStandardItemModel* headerModel)
{
QStandardItem* item = new QStandardItem("Наименование");
QFontMetrics fm(item->font());
item->setData(QSize(fm.width(item->text())+10, qMax(27, fm.height()+2+2)), Qt::SizeHintRole);
headerModel->setItem(0, 0, item);
item = new QStandardItem("Номенклат номер");
item->setData(QSize(fm.width(item->text())+20, qMax(27, fm.height()+2+2)), Qt::SizeHintRole);
headerModel->setItem(0, 1, item);
item = new QStandardItem("Обозначение\n(индекс)");
item->setData(QSize(fm.width("Обозначение")+20, qMax(27, fm.height()+2+2)), Qt::SizeHintRole);
headerModel->setItem(0, 2, item);
item = new QStandardItem("Зав. №");
item->setData(QSize(fm.width("Шифр")+20, qMax(27, fm.height()+2+2)), Qt::SizeHintRole);
headerModel->setItem(0, 3, item);
item = new QStandardItem("Гриф\nсекр.");
item->setData(QSize(fm.width("секр.")+20, qMax(27, fm.height()+2+2)), Qt::SizeHintRole);
headerModel->setItem(0, 4, item);
item = new QStandardItem("Шифр тары");
item->setData(QSize(fm.width(item->text())+10, qMax(27, fm.height()+2+2)), Qt::SizeHintRole);
headerModel->setItem(0, 5, item);
item = new QStandardItem("К-во мест");
item->setData(QSize(fm.width(item->text())+10, qMax(27, fm.height()+2+2)), Qt::SizeHintRole);
headerModel->setItem(0, 6, item);
item = new QStandardItem("Оттиски пломб на таре");
item->setData(QSize(fm.width(item->text())+10, qMax(27, fm.height()+2+2)), Qt::SizeHintRole);
headerModel->setItem(0, 7, item);
QList<QStandardItem*> list;
QStandardItem* child = new QStandardItem("Пломба");
child->setData(QSize(fm.width(child->text())+30, qMax(27, fm.height()+2+2)), Qt::SizeHintRole);
item->appendColumn(list<<child);
list.clear();
child = new QStandardItem("Количество");
child->setData(QSize(fm.width(child->text())+30, qMax(27, fm.height()+2+2)), Qt::SizeHintRole);
item->appendColumn(list<<child);
list.clear();
item = new QStandardItem("Номер\nвагона");
item->setData(QSize(fm.width("вагона")+10, qMax(27, fm.height()+2+2)), Qt::SizeHintRole);
headerModel->setItem(0, 8, item);
item = new QStandardItem("Примечание");
item->setData(QSize(fm.width(item->text())+10, qMax(27, fm.height()+2+2)), Qt::SizeHintRole);
headerModel->setItem(0, 9, item);
}
//
void PartsForm::addParts()
{
m_model->addEmptyRow();
}
//
void PartsForm::removeParts()
{
QModelIndex index = tvParts->currentIndex();
if (!index.isValid())
return;
// qDebug()<<Q_FUNC_INFO<<index<<index.row();
m_model->removeParts(index);
}
//
void PartsForm::cancelParts()
{
m_model->load();
}
//
void PartsForm::save()
{
if (!m_model->save())
qDebug()<<"ERROR";
}
void PartsForm::orderChanged(int index)
{
int order_id = cbOrder->itemData(index).toInt();
m_model->changeOrder(order_id);
}
void PartsForm::initOrders()
{
ODS::IObjectManager ioMan = ODS::OdsInterface::self()->iobjectManager();
ODS::IObjectCursor cursor = ioMan.getIObjects(JOURNAL_TYPE);
cbOrder->clear();
for (ODS::IObjectCursor::iterator iobjIt = cursor.begin(); iobjIt != cursor.end(); ++iobjIt ){
ODS::IObject iobj = (*iobjIt);
cbOrder->addItem(iobj.getStringAttr(NUMBER_ATTR), QVariant(iobj.id()));
}
int order_id = OrderForm::get_current_order_id();
if ( order_id == 0) {
cbOrder->setCurrentIndex(0);
orderChanged(0);
} else {
int order_index = cbOrder->findData(order_id);
cbOrder->setCurrentIndex(order_index);
orderChanged(order_index);
}
}
|
ac398946773da55833cbda1e646fe4ef459b9670
|
5521a03064928d63cc199e8034e4ea76264f76da
|
/fboss/cli/fboss2/utils/CmdClientUtils.cpp
|
9c80f8de9eb4cf4fffb8b4aea3c48c295789f1fc
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
facebook/fboss
|
df190fd304e0bf5bfe4b00af29f36b55fa00efad
|
81e02db57903b4369200eec7ef22d882da93c311
|
refs/heads/main
| 2023-09-01T18:21:22.565059
| 2023-09-01T15:53:39
| 2023-09-01T15:53:39
| 31,927,407
| 925
| 353
|
NOASSERTION
| 2023-09-14T05:44:49
| 2015-03-09T23:04:15
|
C++
|
UTF-8
|
C++
| false
| false
| 765
|
cpp
|
CmdClientUtils.cpp
|
/*
* Copyright (c) 2004-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include "fboss/cli/fboss2/utils/CmdClientUtils.h"
namespace facebook::fboss::utils {
template <>
std::unique_ptr<facebook::fboss::FbossCtrlAsyncClient> createClient(
const HostInfo& hostInfo) {
return utils::createAgentClient(hostInfo);
}
template <>
std::unique_ptr<facebook::fboss::QsfpServiceAsyncClient> createClient(
const HostInfo& hostInfo) {
return utils::createQsfpClient(hostInfo);
}
} // namespace facebook::fboss::utils
|
a7e8f3f363f12be1a4119665436c83e55dda7f5e
|
655393d95f6762a94294ec3b0adf08dfeaa3d3b9
|
/src/InformationManager.cpp
|
cdcdb2dfd6712e85d07df4a6f7cd617e36fcca65
|
[
"MIT"
] |
permissive
|
Itja/ByunJR
|
8e8c2873eb8c48c0e9316c1997a1fd0680f97ecc
|
a191c7c4f4ae891478f55289d2e173bc1bebe9f4
|
refs/heads/master
| 2021-08-08T16:23:43.421001
| 2017-11-02T22:49:23
| 2017-11-02T22:49:23
| 110,275,368
| 0
| 0
| null | 2017-11-10T17:41:07
| 2017-11-10T17:41:06
| null |
UTF-8
|
C++
| false
| false
| 10,305
|
cpp
|
InformationManager.cpp
|
#include <sc2api/sc2_api.h>
#include "ByunJRBot.h"
#include "InformationManager.h"
#include "common/BotAssert.h"
#include "common/Common.h"
#include "information/unitInfo.h"
#include "util/Util.h"
InformationManager::InformationManager(ByunJRBot & bot)
: bot_(bot)
, building_placer_(bot)
, unit_info_(bot)
{
}
void InformationManager::OnStart()
{
building_placer_.OnStart();
unit_info_.OnStart();
// get my race
const auto player_id = bot_.Observation()->GetPlayerID();
for (auto & player_info : bot_.Observation()->GetGameInfo().player_info)
{
if (player_info.player_id == player_id)
{
player_race_[static_cast<int>(PlayerArrayIndex::Self)] = player_info.race_actual;
}
else
{
player_race_[static_cast<int>(PlayerArrayIndex::Enemy)] = player_info.race_requested;
}
}
for (int y = 0; y < bot_.Map().TrueMapHeight(); ++y)
{
dps_map_.push_back(std::vector<int>());
for (int x = 0; x < bot_.Map().TrueMapWidth(); ++x)
{
// There is an inherit "danger" for traveling through any square.
// Don't use 0, otherwise we won't find the "shortest and safest path"
dps_map_[y].push_back(1);
}
}
}
void InformationManager::OnUnitCreated(const sc2::Unit* unit)
{
}
void InformationManager::OnUnitDestroyed(const sc2::Unit* unit)
{
unit_info_.OnUnitDestroyed(unit);
}
void InformationManager::OnFrame()
{
unit_info_.OnFrame();
// Reset dps_map_
for (const auto & unit : unit_info_.GetUnits(PlayerArrayIndex::Enemy))
{
for (int y = 0; y < dps_map_.size(); ++y)
{
for (int x = 0; x < dps_map_[y].size(); ++x)
{
dps_map_[y][x] = 1;
}
}
}
// Update dps_map_
for(const auto & unit : unit_info_.GetUnits(PlayerArrayIndex::Enemy))
{
const int damage = Util::GetAttackDamage(unit->unit_type, bot_);
if (damage == 0) continue;
int range = Util::GetAttackRange(unit->unit_type, bot_);
// Melee units are dangerous too.
if (range == 0 && !Util::IsBuilding(unit->unit_type)) range = 2;
for (int y = 0; y < dps_map_.size(); ++y)
{
for (int x = 0; x < dps_map_[y].size(); ++x)
{
if( Util::DistSq(sc2::Point2D(x,y),unit->pos) <= (range*range) )
{
dps_map_[y][x] += damage;
}
}
}
}
for (int y = 0; y < bot_.Map().TrueMapHeight(); ++y)
{
for (int x = 0; x < bot_.Map().TrueMapWidth(); ++x)
{
if (!bot_.Map().IsWalkable(x, y))
dps_map_[y][x] = 999;
}
}
}
BuildingPlacer & InformationManager::BuildingPlacer()
{
return building_placer_;
}
UnitInfoManager & InformationManager::UnitInfo()
{
return unit_info_;
}
sc2::Point2DI InformationManager::GetProxyLocation() const
{
return bot_.GetProxyManager().GetProxyLocation();
}
// TODO: Figure out my race
const sc2::Race & InformationManager::GetPlayerRace(PlayerArrayIndex player) const
{
BOT_ASSERT(player == PlayerArrayIndex::Self || player == PlayerArrayIndex::Enemy, "invalid player for GetPlayerRace");
return player_race_[static_cast<int>(player)];
}
const sc2::Unit* InformationManager::GetBuilder(Building& b, const bool set_job_as_builder)
{
const std::vector<UnitMission> acceptable_missions{ UnitMission::Minerals, UnitMission::Proxy };
const sc2::Unit* builder_worker = GetClosestUnitWithJob(sc2::Point2D(b.finalPosition.x, b.finalPosition.y), acceptable_missions);
// if the worker exists (one may not have been found in rare cases)
if (builder_worker && set_job_as_builder)
{
unit_info_.SetJob(builder_worker, UnitMission::Build);
}
return builder_worker;
}
// Does not look for flying bases. Only landed bases.
const sc2::Unit* InformationManager::GetClosestBase(const sc2::Unit* reference_unit) const
{
const sc2::Unit* closest_unit = nullptr;
double closest_distance = std::numeric_limits<double>::max();
for (auto unit : bot_.InformationManager().UnitInfo().GetUnits(PlayerArrayIndex::Self))
{
if (unit->unit_type == sc2::UNIT_TYPEID::TERRAN_COMMANDCENTER
|| unit->unit_type == sc2::UNIT_TYPEID::TERRAN_ORBITALCOMMAND
|| unit->unit_type == sc2::UNIT_TYPEID::TERRAN_PLANETARYFORTRESS
|| unit->unit_type == sc2::UNIT_TYPEID::PROTOSS_NEXUS
|| unit->unit_type == sc2::UNIT_TYPEID::ZERG_HATCHERY
|| unit->unit_type == sc2::UNIT_TYPEID::ZERG_LAIR
|| unit->unit_type == sc2::UNIT_TYPEID::ZERG_HIVE)
{
const double distance = Util::DistSq(unit->pos, reference_unit->pos);
if (!closest_unit || distance < closest_distance)
{
closest_unit = unit;
closest_distance = distance;
}
}
}
return closest_unit;
}
const ::UnitInfo * InformationManager::GetClosestUnitInfoWithJob(const sc2::Point2D reference_point, const UnitMission unit_mission) const
{
const ::UnitInfo * closest_unit = nullptr;
double closest_distance = std::numeric_limits<double>::max();
for (auto & unit_info_pair : bot_.InformationManager().UnitInfo().GetUnitInfoMap(PlayerArrayIndex::Self))
{
const ::UnitInfo & unit_info = unit_info_pair.second;
if (unit_info.mission == unit_mission)
{
const double distance = Util::DistSq(reference_point, unit_info.unit->pos);
if (!closest_unit || distance < closest_distance)
{
closest_unit = &unit_info;
closest_distance = distance;
}
}
}
return closest_unit;
}
const sc2::Unit * InformationManager::GetClosestUnitWithJob(const sc2::Point2D reference_point, const UnitMission unit_mission) const
{
const sc2::Unit * closest_unit = nullptr;
double closest_distance = std::numeric_limits<double>::max();
for (auto & unit_info_pair : bot_.InformationManager().UnitInfo().GetUnitInfoMap(PlayerArrayIndex::Self))
{
const ::UnitInfo & unit_info = unit_info_pair.second;
if (unit_info.mission == unit_mission)
{
const double distance = Util::DistSq(reference_point, unit_info.unit->pos);
if (distance < closest_distance)
{
closest_unit = unit_info.unit;
closest_distance = distance;
}
}
}
return closest_unit;
}
const UnitInfo* InformationManager::GetClosestUnitInfoWithJob(const sc2::Point2D point,
const std::vector<UnitMission> mission_vector) const
{
const ::UnitInfo * closest_unit = nullptr;
double closest_distance = std::numeric_limits<double>::max();
for (auto & unit_info_pair : bot_.InformationManager().UnitInfo().GetUnitInfoMap(PlayerArrayIndex::Self))
{
if (std::find(mission_vector.begin(), mission_vector.end(), unit_info_pair.second.mission) != mission_vector.end())
{
const double distance = Util::DistSq(unit_info_pair.second.unit->pos, point);
if (distance < closest_distance)
{
closest_unit = &unit_info_pair.second;
closest_distance = distance;
}
}
}
return closest_unit;
}
const sc2::Unit* InformationManager::GetClosestUnitWithJob(const sc2::Point2D point,
const std::vector<UnitMission> mission_vector) const
{
const sc2::Unit * closest_unit = nullptr;
double closest_distance = std::numeric_limits<double>::max();
for (auto & unit_info_pair : bot_.InformationManager().UnitInfo().GetUnitInfoMap(PlayerArrayIndex::Self))
{
const ::UnitInfo & unit_info = unit_info_pair.second;
if (std::find(mission_vector.begin(), mission_vector.end(), unit_info.mission) != mission_vector.end())
{
const double distance = Util::DistSq(unit_info_pair.second.unit->pos, point);
if (distance < closest_distance)
{
closest_unit = unit_info.unit;
closest_distance = distance;
}
}
}
return closest_unit;
}
const sc2::Unit* InformationManager::GetClosestUnitOfType(const sc2::Unit* reference_unit,
const sc2::UnitTypeID reference_type_id) const
{
const sc2::Unit* closest_unit = nullptr;
double closest_distance = std::numeric_limits<double>::max();
for (auto unit : bot_.InformationManager().UnitInfo().GetUnits(PlayerArrayIndex::Self))
{
if (unit->unit_type == reference_type_id)
{
const double distance = Util::DistSq(unit->pos, reference_unit->pos);
if (!closest_unit || distance < closest_distance)
{
closest_unit = unit;
closest_distance = distance;
}
}
}
return closest_unit;
}
const sc2::Unit* InformationManager::GetClosestNotOptimalRefinery(const sc2::Unit* reference_unit) const
{
const sc2::Unit* closest_refinery = nullptr;
double closest_distance = std::numeric_limits<double>::max();
// Find all our refineries. If they not full, fill em up.
for (auto refinery : bot_.InformationManager().UnitInfo().GetUnits(PlayerArrayIndex::Self))
{
if (Util::IsRefinery(refinery) && Util::IsCompleted(refinery))
{
const int num_assigned = bot_.InformationManager().UnitInfo().GetNumAssignedWorkers(refinery);
if (0 < (refinery->ideal_harvesters - num_assigned))
{
const double distance = Util::DistSq(refinery->pos, reference_unit->pos);
if (!closest_refinery || distance < closest_distance)
{
closest_refinery = refinery;
closest_distance = distance;
}
}
}
}
return closest_refinery;
}
size_t UnitInfoManager::UnitsInProductionOfType(sc2::UnitTypeID unit_type) const
{
return bot_.ProductionManager().NumberOfUnitsInProductionOfType(unit_type);
}
vvi InformationManager::GetDPSMap() const
{
return dps_map_;
}
|
02f84cf321d8f2165673cb0f06a1e69a7c660751
|
85d401ada0cb12a02033275d157743412f4870b0
|
/poj/p2155_datamaker.cpp
|
2e5f84e4def41d2a7f9ea20194c8a5c466d660c1
|
[] |
no_license
|
csimstu/OI
|
4535025f0b6a6c63caf5487a6d806f772086ebc5
|
b5f4eadd6ad180a9ee26b7ae336ede7b980314a9
|
refs/heads/master
| 2021-01-22T02:03:33.264345
| 2013-04-05T12:08:41
| 2013-04-05T12:08:41
| 2,553,733
| 1
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 525
|
cpp
|
p2155_datamaker.cpp
|
#include <cstdio>
#include <cstdlib>
#include <algorithm>
using namespace std;
int n,m,seed;
int main()
{
freopen("t.in", "w", stdout);
scanf("%d%d%d",&n,&m,&seed);
srand(seed);
printf("1\n");
printf("%d %d\n", n, m);
while(m --)
{
int t = rand() %2;
int x1 = rand() % n + 1;
int x2 = rand() % n + 1;
int y1 = rand() % n + 1;
int y2 = rand() % n + 1;
if(x1 > x2) swap(x1, x2);
if(y1 > y2) swap(y1, y2);
if(t)
printf("C %d %d %d %d\n", x1, y1, x2, y2);
else
printf("Q %d %d\n", x1, y1);
}
}
|
652a1f00cf0f088af8bbc234e3b1a6f1d78a2ab2
|
d3a2d022ba792ec08331f9536c42c9dfd43fcb36
|
/src/Aligner.cpp
|
a91ce903f7ade6d1940eed3a9c77db4c42f4fe2f
|
[] |
no_license
|
binka/4314_HIA
|
c43f38470e94dc48dcf21e79da1d49c3ee283854
|
877c2da6be9634e81a0f56251c23bbb56429845b
|
refs/heads/master
| 2021-01-10T14:09:32.991011
| 2016-05-01T22:26:48
| 2016-05-01T22:26:48
| 55,652,479
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,515
|
cpp
|
Aligner.cpp
|
#include <iostream>
#include <string>
#include <algorithm>
#include <tuple>
#include <list>
#include <cmath>
#include "Aligner.h"
using namespace std;
struct match_region{
long diagonal;
long read_pos;
long seq_pos;
long length;
};
struct candidate_mr{
list<match_region> mr_list;
unsigned int matched_bases;
};
typedef pair<GappedSequence, GappedSequence> GS_pair;
Aligner::Aligner(unsigned int kmer_length, const string &reference):
kmer_length(kmer_length),
reference(reference),
index(kmer_length, reference){}
pair<GappedSequence, GappedSequence> Aligner::find_alignment(const string &read){
return find_alignment(read, this->kmer_length);
}
pair<GappedSequence, GappedSequence> Aligner::find_alignment(const string &read, unsigned int kmer_length){
if(kmer_length < this->kmer_length){
cerr << "Warning: 0 results will be returned when finding an alignment using kmer sizes less than what was specfied when building the hybrid index.\n";
}
//Contains a list of diagonal, kmer read position pairs
vector<match_region> matching_regions;
for(unsigned int i = 0; i < read.length() - kmer_length + 1; i++){
cout << read.substr(i, kmer_length) << endl;
cout << index.query(read.substr(i, kmer_length)).size() << " results\n";
for(long elm : index.query(read.substr(i, kmer_length))){
matching_regions.push_back({elm-i, i, elm, kmer_length});
}
}
//Sort MR's by diagonal then read position
sort(begin(matching_regions), end(matching_regions),
[](const match_region &a, const match_region &b){
//compare using the ints as indices into the sequence
if(a.diagonal == b.diagonal){
return a.read_pos < b.read_pos;
}else{
return a.diagonal < b.diagonal;
}
});
for(auto elm : matching_regions){
cout << elm.diagonal << " " << elm.read_pos << " " << elm.seq_pos << " " << elm.length << endl;
}
//Merge MR's if they have identical diagonal values and successive offsets
list<match_region> new_mrs;
int cur_diagonal = matching_regions.front().diagonal;
unsigned int cur_pos = matching_regions.front().read_pos;
unsigned int seq_pos = matching_regions.front().seq_pos;
unsigned int start_pos = cur_pos;
unsigned int cur_length = kmer_length;
for(auto elm : matching_regions){
//Add merged MR's
if(elm.diagonal != cur_diagonal || elm.read_pos != cur_pos){
new_mrs.push_back({cur_diagonal, start_pos, seq_pos, cur_length-1});
cur_diagonal = elm.diagonal;
cur_pos = elm.read_pos;
start_pos = cur_pos;
cur_length = elm.length;
seq_pos = elm.seq_pos;
}
cur_pos++;
cur_length++;
}
//Add remaining MR
cout << "last: " << cur_diagonal << endl;
new_mrs.push_back({cur_diagonal, start_pos, seq_pos, cur_length-1});
cout << "New matching regions.\n";
for(auto elm : matching_regions){
cout << elm.diagonal << " " << elm.read_pos << " " << elm.seq_pos << " " << elm.length << endl;
}
//max_adjacency allowed for combining MR's into CAR's
//TODO: better estimate
int max_adjacency = 2;//0.1 * read.size();
//Compute CAR's by merging MR's with diagonals with a different <= max_adjacency
vector<candidate_mr> candidate_regions;
cur_diagonal = new_mrs.front().diagonal;
unsigned int cur_match = 0;
list<match_region> l;
for(auto elm : new_mrs){
//Add merged MR's
if(abs(elm.diagonal - cur_diagonal) <= max_adjacency){
cout << "mr with diag " << elm.diagonal << " is in range of cur diag " << cur_diagonal << endl;
l.push_back(elm);
cur_match += kmer_length - abs(cur_diagonal - elm.diagonal);
}else{
cout << "mr with diag " << elm.diagonal << " is not in range of cur diag " << cur_diagonal << endl;
candidate_regions.push_back({l, cur_match});
l.clear();
l.push_back(elm);
cur_diagonal = elm.diagonal;
cur_match = elm.length;
}
}
candidate_regions.push_back({l, cur_match});
//Sort CAR's
sort(begin(candidate_regions), end(candidate_regions),
[](const candidate_mr &a, const candidate_mr &b){
return a.matched_bases > b.matched_bases;
});
for(auto car : candidate_regions){
cout << car.matched_bases << " matches:\n";
for(auto elm : car.mr_list){
cout << elm.diagonal << " " << elm.read_pos << " " << elm.seq_pos << " " << elm.length << endl;
}
}
//Align each candidate region
for(auto cr : candidate_regions){
int search_limit = kmer_length;
//Align LMUR (Left-Most Unmatched Region)
match_region mr = cr.mr_list.front();
GS_pair gs_pair = global_align(reference, read, pair<int, int>(mr.seq_pos - search_limit - mr.read_pos, mr.seq_pos), pair<int, int>(0, mr.read_pos));
//Align RMUR (Right-Most Unmatched Region)
mr = cr.mr_list.back();
GS_pair gs_pair2 = global_align(reference, read, pair<int, int>(mr.seq_pos, mr.seq_pos + search_limit + mr.read_pos), pair<int, int>(mr.read_pos, string::npos));
//Align all MRUR
GS_pair gs_pair_acc = GS_pair(GappedSequence::merge(gs_pair.first, gs_pair2.first), GappedSequence::merge(gs_pair.second, gs_pair2.second));
auto it1 = begin(cr.mr_list);
auto it2 = begin(cr.mr_list);
it2++;
for(; it2 != end(cr.mr_list); it1++, it2++){
auto seq_range = pair<int, int>(it1->seq_pos + it1->length, it2->seq_pos);
auto read_range = pair<int, int>(it1->read_pos + it1->length, it2->read_pos);
GS_pair gs_temp = global_align(reference, read, seq_range, read_range);
gs_pair_acc = GS_pair(GappedSequence::merge(gs_temp.first, gs_pair_acc.first), GappedSequence::merge(gs_temp.second, gs_pair_acc.second));
}
}
return GS_pair(GappedSequence(read), GappedSequence(read));
}
GS_pair Aligner::global_align(const string &seq1, const string &seq2, pair<int, int> seq1_range, pair<int, int> seq2_range){
//these need to be changed from length of the whole string to the length of the regions
// of seq1_range and seq2_range
int seq1Length = seq1.length();
int seq2Length = seq2.length();
int numCols = seq1Length + 1;
int numRows = seq2Length + 1;
int substitution = 0;
int left, top, diagonal, num = 0;
vector < vector<int> > matrix;
matrix.resize(numRows, vector<int>(numCols, 0));
// ##################################################
// ########## Building DP Matrix ####################
// ##################################################
for (int row = 0; row < numRows; row++){
for (int col = 0; col < numCols; col++){
if (row == 0 && col == 0){
matrix[row][col] = 0;
}else if (row == 0) {
matrix[row][col] = matrix[row][col - 1] + 1;
}else if (col == 0) {
matrix[row][col] = matrix[row - 1][col] + 1;
}else {
if (seq1[col - 1] == seq2[row - 1]){
substitution = 0; //match score = 0
}else{
substitution = 1; //mismatch score = 1
}
left = matrix[row][col - 1] + 1; //gap penalty: +1
top = matrix[row - 1][col] + 1; //gap penalty: +1
diagonal = matrix[row - 1][col - 1] + substitution; //match/mismatch
num = min(min(left, top), diagonal);
matrix[row][col] = num;
}
}
}
// for (int i = 0; i < numRows; i++)
// {
// for (int j = 0; j < numCols; j++)
// {
// cout << matrix[i][j] << " ";
// }
// cout << endl;
// }
// ##################################################
// ########## Aligning Sequences ####################
// ##################################################
GappedSequence s1(seq1, "", "", "");
GappedSequence s2(seq2, "", "", "");
bool match = 0;
int currentCol = seq1Length;
int currentRow = seq2Length;
left = 0;
top = 0;
diagonal = 0;
num = 0;
int string1Index = seq1Length;
int string2Index = seq2Length;
while(true){
if (currentCol == 0 and currentRow == 0) break;
if (currentRow != 0 && currentCol != 0){
left = matrix[currentRow][currentCol - 1];
top = matrix[currentRow - 1][currentCol];
diagonal = matrix[currentRow - 1][currentCol - 1];
}
num = min(diagonal, min(left, top));
match = seq1[currentCol - 1] == seq2[currentRow - 1];
if ((num == left && num != diagonal && !match) || (currentRow == 0)){
// left
s2.add_gaps(string2Index);
currentCol -= 1;
string2Index -= 1;
}else if ((num == top && num != diagonal && !match) || (currentCol == 0)){
// top
s1.add_gaps(string1Index);
currentRow -= 1;
string1Index -= 1;
}else{
// diagonal
currentCol -= 1;
currentRow -= 1;
string1Index -= 1;
string2Index -= 1;
}
}
return GS_pair(s1, s2);
}
|
f3b115ff902bfcf9c92c91ad5fc48a429b940c53
|
69e6c82c848156f8426797767304aa42c6849d35
|
/sumRegion2.cpp
|
eed838e5a16ed21fb9c167e0d5548b45107ecee4
|
[] |
no_license
|
dalanlan/algo
|
cea8d79e914f3e973d4ac256e9bb1eaf2a12925c
|
94e85d1e1a79646c44f09c58096584b2521628b9
|
refs/heads/master
| 2020-04-05T18:57:33.051988
| 2016-10-18T08:06:57
| 2016-10-18T08:06:57
| 38,982,619
| 0
| 3
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 665
|
cpp
|
sumRegion2.cpp
|
/*
LeetCode: Range Sum Query 2D Immutable
https://leetcode.com/problems/range-sum-query-2d-immutable/
*/
class NumMatrix {
public:
int row;
int col;
vector<vector<int>> sum;
NumMatrix(vector<vector<int>> &matrix) {
row = matrix.size();
col = row==0?0:matrix[0].size();
sum = vector<vector<int>> (row+1, vector<int>(col+1, 0));
for(int i=1; i<=row; i++) {
for(int j=1; j<=col; j++) {
sum[i][j] = sum[i-1][j] + sum[i][j-1] - sum[i-1][j-1] + matrix[i-1][j-1];
}
}
}
int sumRegion(int row1, int col1, int row2, int col2) {
return sum[row2+1][col2+1] - sum[row2+1][col1] - sum[row1][col2+1] + sum[row1][col1];
}
};
|
d1f5fa1a2c3af1acd1b37060793fcdff2144b036
|
60d206fbbe439bddecb3e44331823b22de4bf683
|
/kangaroo/cu_convolution.h
|
1078bf72ad2718923d6462a32bfa26fc6d98fa22
|
[] |
no_license
|
jzienkiewicz/Kangaroo
|
bb3d54e96273ae1d80e348b18a65fbf34e2749e1
|
d2d1e18408044ce88e68ee873ae4208c511b1c90
|
refs/heads/master
| 2021-01-16T20:30:41.953501
| 2014-03-26T11:54:10
| 2014-03-26T11:54:10
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 203
|
h
|
cu_convolution.h
|
#pragma once
#include "Image.h"
namespace roo
{
template<typename OT, typename IT, typename KT, typename ACC>
void Convolution(
Image<OT> out, Image<IT> in, Image<KT> kern, int kx, int ky
);
}
|
f6e820defa53e007b7eba30acda6539e81eecfea
|
9b42d80abebd5e8ec344c952c945e98fa34c573d
|
/graphs/test.cpp
|
c4374d59562d276f6e791be7ec28c2c4a1fa9729
|
[] |
no_license
|
yuboq/dumpster
|
e5765f1b15cd2fa66d97f7ab4d5b11670c38594f
|
6f3ad1814f215f1a4352b5bb1757d4440b563928
|
refs/heads/master
| 2022-09-05T04:17:30.263355
| 2020-06-01T04:18:21
| 2020-06-01T04:18:21
| 268,422,456
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 328
|
cpp
|
test.cpp
|
#include <iostream>
#include <vector>
#include <stack>
#include <algorithm>
int main()
{
int a[10]={0};
for (auto i: a)
{
std::cout << i << std::endl;
}
std::vector<int> myVec {10,20,3,4,6,18};
std::cout <<std::distance (myVec.begin(), std::max_element (myVec.begin(), myVec.end())) <<std::endl;
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.