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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a8b2cb08a6b076353025e5a7cfb6d354710e96a5
|
3657bb42387d76fd041d37bf2d69bad7f916f16a
|
/Boost/Boost/dataStructures/any.cpp
|
1426af6540f89e59cbde11ae095164beba15ff3e
|
[
"MIT"
] |
permissive
|
goodspeed24e/Programming
|
61d8652482b3246f1c65f2051f812b2c6d2d40ce
|
ae73fad022396ea03105aad83293facaeea561ae
|
refs/heads/master
| 2016-08-04T02:58:01.477832
| 2015-03-16T15:12:27
| 2015-03-16T15:13:33
| 32,333,164
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,124
|
cpp
|
any.cpp
|
/*
Strongly typed languages such as C++ require that each variable has a
specific data type determining the nature of information it can store. To
store arbitrary information in a variable, a language such as JavaScript
can be used which allows storing a character string, a number and a boolean
value using the same variable. Variables in JavaScript allow storing any
kind of information.
The library Boost.Any offers the boost::any class which, similar to
JavaScript, offers the ability to store arbitrary information in C++.
*/
//#include <boost/any.hpp>
//
//int main()
//{
// boost::any a = 1;
// a = 3.14;
// a = true;
//}
/*
In order to use boost::any, the header file boost/any.hpp must be included.
Objects of type boost::any can then be created to store arbitrary
information.
Please note that variables of type boost::any cannot really store any kind
of information; Boost.Any requires certain preconditions, albeit minimal
ones. Any information, stored in a variable of type boost::any, must be
copy constructible. Hence, to store a character string in a variable of
type boost::any, std::string needs to be explicitly accessed as shown in
the following example.
*/
//#include <boost/any.hpp>
//#include <string>
//
//int main()
//{
// boost::any a = 1;
// a = 3.14;
// a = true;
// a = std::string("Hello, world!");
//}
/*
If the application would try to assign "Hello, world!" to a directly, the
compiler would abort with an error since character strings are arrays
comprised of elements of type char which are not copy constructible in C++.
To access the content of variables of type boost::any, the cast operator
boost::any_cast must be used.
*/
//#include <boost/any.hpp>
//#include <iostream>
//
//int main()
//{
// boost::any a = 1;
// std::cout << boost::any_cast<int>(a) << std::endl;
// a = 3.14;
// std::cout << boost::any_cast<double>(a) << std::endl;
// a = true;
// std::cout << boost::any_cast<bool>(a) << std::endl;
//}
/*
By passing the corresponding data type as the template argument to
boost::any_cast, the content of the variable is converted accordingly. In
case an invalid data type is specified, an exception of type
boost::bad_any_cast is thrown.
*/
//#include <boost/any.hpp>
//#include <iostream>
//
//int main()
//{
// try
// {
// boost::any a = 1;
// std::cout << boost::any_cast<float>(a) << std::endl;
// }
// catch (boost::bad_any_cast &e)
// {
// std::cerr << e.what() << std::endl;
// }
//}
/*
The above example throws an exception since the template argument of type
float does not match the type int stored in a. It is important to always
specify the same data type as used for the variable of type boost::any. The
application would also throw an exception if either short or long would be
specified as the template argument.
Since boost::bad_any_cast is derived from std::bad_cast, catch handlers can
catch exceptions of this type accordingly.
To check whether or not a variable of type boost::any contains information,
the empty() method is used. To check the data type of the stored information
instead, type() can be used.
*/
#include <boost/any.hpp>
#include <typeinfo>
#include <iostream>
int main()
{
boost::any a = 1;
if (!a.empty())
{
const std::type_info &ti = a.type();
std::cout << ti.name() << std::endl;
int *i = boost::any_cast<int>(&a);
std::cout << *i << std::endl;
}
}
/*
The example uses both empty() and type(). While empty() returns a boolean
value, the return value of type() is of type std::type_info which is
defined in typeinfo.
*/
/*
To conclude this section, the final example shows how to obtain a pointer
to the value stored in a variable of type boost::any using boost::any_cast.
*/
//#include <boost/any.hpp>
//#include <iostream>
//
//int main()
//{
// boost::any a = 1;
// int *i = boost::any_cast<int>(&a);
// std::cout << *i << std::endl;
//}
/*
All it takes is passing a pointer to the variable of type boost::any as the
argument to boost::any_cast; the template arguments remain unchanged.
*/
|
7726a7cfa66587d0a7e34752e323c095cb49b7b8
|
c5b5805ed4dd2bf46fd31826670017abec8e872e
|
/Arrays/moveZeroes.cpp
|
eb2a78de236552fd492456220cbec3ba7501e7f5
|
[] |
no_license
|
maverick439/DataStructures
|
3079224f0dcdf1a779e870209e6425fb11661da7
|
bf5d632d8558ff4f051c4ac7939028774b39af56
|
refs/heads/master
| 2022-07-23T16:03:15.218699
| 2022-07-09T03:41:19
| 2022-07-09T03:41:19
| 131,743,165
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 567
|
cpp
|
moveZeroes.cpp
|
/**
* Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.
* Note that you must do this in-place without making a copy of the array.
*
* Input: nums = [0,1,0,3,12]
* Output: [1,3,12,0,0]
* */
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int j = 0; int n = nums.size();
for(int i = 0; i<n; i++){
if(nums[i] != 0){
nums[j++] = nums[i];
}
}
while(j < n){
nums[j++] = 0;
}
}
};
|
e4936063affd9cbe017bb7127c87405447ec5222
|
feaffd12105b46d72460ee2e528ed62c4e944035
|
/src/_Shared/SensorConfig.cpp
|
b96e7a20be2e14986b6c935a3df2bf779aabeff5
|
[] |
no_license
|
Taz7842K/7842K_COMPETITION_CODE
|
4f34ee80280ee50148605c6e20d11b2f0e856b06
|
fe5a8cac9255fba1fc6e5e71a4d6ad97b5d8949a
|
refs/heads/master
| 2020-04-21T06:29:45.750201
| 2019-03-30T08:45:27
| 2019-03-30T08:45:27
| 169,366,875
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 284
|
cpp
|
SensorConfig.cpp
|
#include "main.h"
#include "_Shared/SensorConfig.h"
okapi::Potentiometer pot_catapult('C');
okapi::ADIEncoder enc_catapult('G','H');
pros::ADIAnalogIn light_catapult('E');
pros::ADIDigitalIn sw_catapult('A');
pros::Controller HIDMain(CONTROLLER_MASTER);
double initPotCatapult;
|
8457786091669b92a9ce3738bbc26b0408c35de3
|
f5b936c57a82a479983a2adc71c2abe7d6b3ec9b
|
/Codeforces/round391/b.cpp
|
70668d72ea5f4240b54ba2b3eb90168a824374ea
|
[] |
no_license
|
FranciscoThiesen/OldProblems
|
002e2099fcb7f0c874f3d8927a60d1644521bbdf
|
809747fceb5a75127aae832697d6f91b63d234f5
|
refs/heads/master
| 2021-08-31T16:20:28.969377
| 2017-12-22T02:07:05
| 2017-12-22T02:07:05
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 905
|
cpp
|
b.cpp
|
/*input
3
15 30 45
*/
#include <bits/stdc++.h>
#include <cstring>
using namespace std;
#define gcd __gcd
#define ll long long
#define pb push_back
#define fi first
#define se second
#define mp make_pair
set<int> factor(int x)
{
set<int> fac;
if(x != 1)
fac.insert(x);
for(int i = 2; i <= ceil(sqrt(x)); ++i)
{
if(x%i == 0)
{
fac.insert(i);
if(x/i != i && x/i != i)
fac.insert(x/i);
}
}
return fac;
}
int main()
{
ios::sync_with_stdio(0);
int ans = 1;
unordered_map<int, int> primeSize;
unordered_multiset<int> lst;
int n;
cin >> n;
for(int i = 0; i < n; ++i)
{
int k;
cin >> k;
lst.insert(k);
if(k != 1)
primeSize.insert(mp(k, 0));
}
for(auto& q : lst)
{
int longestSize = 0;
set<int> primeFact = factor(q);
for(auto& p : primeFact)
primeSize[p]++;
for(auto& p : primeSize)
{
ans = max(ans, p.se);
}
}
cout << ans << endl;
return 0;
}
|
2c992df4e52ab85101a2bcc283c9792414bb0f8c
|
387549ab27d89668e656771a19c09637612d57ed
|
/DRGLib UE project/Source/FSD/Public/PostDataModel.h
|
2a23f96c77f1eb0dab20b35ad0791d8089a97269
|
[
"MIT"
] |
permissive
|
SamsDRGMods/DRGLib
|
3b7285488ef98b7b22ab4e00fec64a4c3fb6a30a
|
76f17bc76dd376f0d0aa09400ac8cb4daad34ade
|
refs/heads/main
| 2023-07-03T10:37:47.196444
| 2023-04-07T23:18:54
| 2023-04-07T23:18:54
| 383,509,787
| 16
| 5
|
MIT
| 2023-04-07T23:18:55
| 2021-07-06T15:08:14
|
C++
|
UTF-8
|
C++
| false
| false
| 186
|
h
|
PostDataModel.h
|
#pragma once
#include "CoreMinimal.h"
#include "PostDataModel.generated.h"
USTRUCT(BlueprintType)
struct FPostDataModel {
GENERATED_BODY()
public:
FSD_API FPostDataModel();
};
|
d10627da55a856ea899f8050704d6e0a4888a6dc
|
01c453f302f304d986c8e9049ba781b93fe412e2
|
/utils.cpp
|
928b67670f1dbee9035a2487ee947d54b4f6a874
|
[] |
no_license
|
mrwhyzzz/TcpCmdTransfer
|
d7ccfd8fb4555c8d3889bea6d4a87d4256e4a92d
|
8d6103bdbb6595cb211f622f5fb86bef2a1e36c1
|
refs/heads/master
| 2020-06-04T04:00:04.492996
| 2017-05-22T02:40:24
| 2017-05-22T02:40:24
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,960
|
cpp
|
utils.cpp
|
#include "utils.h"
#include "platformtranslator.h"
#include <QtCore>
#include <QtNetwork>
#include <log4cplus/logger.h>
#include <log4cplus/configurator.h>
#include <log4cplus/helpers/loglog.h>
#include <log4cplus/helpers/stringhelper.h>
#include <log4cplus/helpers/sleep.h>
#include <log4cplus/loggingmacros.h>
#include <log4cplus/thread/threads.h>
using namespace log4cplus;
static log4cplus::thread::Mutex mutex;
bool Utils::isAllBufangCmd(const QByteArray &cmd )
{
quint16 cmdId = getCmdIdFromCmd(cmd);
return isAllBufangCmdId(cmdId);
}
bool Utils::isAllBufangRetCmd(const QByteArray &cmd )
{
quint16 cmdId = getCmdIdFromCmd(cmd);
return isAllBufangRetCmdId(cmdId);
}
quint16 Utils::getCmdIdFromCmd(const QByteArray &cmd )
{
QDataStream is(cmd);
is.skipRawData(5);
quint16 cmdId = 0;
is >> cmdId;
return cmdId;
}
quint32 Utils::getDevIdFromCmd( const QByteArray &cmd )
{
QDataStream is(cmd);
is.skipRawData(1);
quint32 devId = 0;
is >> devId;
return devId;
}
quint16 Utils::getMidFromCmd( const QByteArray &cmd )
{
QDataStream is(cmd);
is.skipRawData(7);
quint16 mid = 0;
is >> mid;
return mid;
}
quint32 Utils::getDevIdFromJsonCmd( const QByteArray &cmd )
{
QJsonDocument jsonDoc = QJsonDocument::fromJson(cmd);
QJsonObject jsonCmdObj = jsonDoc.object();
double dDevId = jsonCmdObj[KEY_DEV_ID].toDouble();
return quint32(dDevId);
}
QByteArray Utils::toReadableCmd(const QByteArray &aCmd )
{
QByteArray cmd;
int size = 0, i = 0, j = 0;
size = aCmd.size();
if('f' == aCmd[i])
j = 8;
else
j = 0;
for(i = j; i < size; ++i)
{
cmd.append(aCmd.at(i));
if(j + 1 == i)
{
cmd.append(' ');
}
else if(j + 9 == i)
{
cmd.append(' ');
}
else if(j + 13 == i)
{
cmd.append(' ');
}
else if(j + 17 == i)
{
cmd.append(' ');
}
else if(j + 21 == i)
{
cmd.append(' ');
}
else if(j + size - 5 == i)
{
cmd.append(' ');
}
}
return cmd;
}
void Utils::logCmd( const char *direction, const QByteArray &cmd, CMD_FORMAT cmdFormat /*= BYTEARRAY_CMD*/ )
{
LOG4CPLUS_DEBUG_FMT(
Logger::getRoot(),
LOG4CPLUS_TEXT("%s : %s"),
direction,
CMD_FORMAT::BYTEARRAY_CMD == cmdFormat ?
toReadableCmd(cmd.toHex()).data()
:
cmd.data()
);
}
void Utils::remoteWinAlarm( quint32 devId )
{
QScopedPointer<QUdpSocket> pUdpSocket(new QUdpSocket());
pUdpSocket->writeDatagram(QString("tcp %1").arg(devId).toUtf8(), QHostAddress::LocalHost, 4444);
}
void Utils::logByteArray( const QByteArray &byteArray, bool isRecv )
{
LOG4CPLUS_WARN_FMT(
Logger::getRoot(),
LOG4CPLUS_TEXT("%s : %s"),
isRecv ? "Recv" : "Send",
toReadableByteArray(byteArray).constData()
);
}
QByteArray Utils::toReadableByteArray( const QByteArray &byteArray )
{
QByteArray readableArray;
QByteArray hexArray = byteArray.toHex();
for(int i = 0; i < hexArray.size(); ++i)
{
readableArray.append(hexArray.at(i));
if(i % 2 != 0)
readableArray.append(' ');
}
return readableArray;
}
|
08881ec2ee99fb159a1bc4d0b6166a0dc2a2aac3
|
ed486dd66a663249f2ec6e61faa2c2a8f30e35a1
|
/maximum_depth_of_tree.cpp
|
ef574925343f41d0fe3dafccd062c2c366e80f5e
|
[] |
no_license
|
CollComm/prep
|
b49034579de21c510213b385edbdda6679c929c7
|
e0cb9edf2da9804c1f5a6d908def64258912cd51
|
refs/heads/master
| 2016-09-09T19:20:37.374226
| 2014-04-01T02:41:18
| 2014-04-01T02:41:18
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,315
|
cpp
|
maximum_depth_of_tree.cpp
|
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
struct StateNode {
TreeNode treeNode;
int height;
public:
StateNode():height(0), treeNode(0) {}
};
#include<stack>
class Solution {
stack<StateNode> treeStack;
public:
int maxDepth(TreeNode *root) {
// Note: The Solution object is instantiated only once and is reused by each test case.
stack<StateNode> tmp;
treeStack.swap(tmp);
int maxHeight = 0;
if (root != NULL)
{
StateNode initState;
initState.height = 1;
initState.treeNode = *root;
treeStack.push(initState);
while(!treeStack.empty())
{
StateNode sNode = treeStack.top();
if (sNode.height > maxHeight)
{
maxHeight = sNode.height;
}
treeStack.pop();
if (sNode.treeNode.left != NULL)
{
StateNode newNode;
newNode.height = sNode.height + 1;
newNode.treeNode = *sNode.treeNode.left;
treeStack.push(newNode);
}
if (sNode.treeNode.right != NULL)
{
StateNode newNode;
newNode.height = sNode.height + 1;
newNode.treeNode = *sNode.treeNode.right;
treeStack.push(newNode);
}
}
}
return maxHeight;
}
};
|
ec14ddca8a30b4c0ae176b861ceec49f32d83e27
|
17d63dc497e6f1b2a366bf1751cb8ef5bee067ae
|
/src/config_client/xconfig_and_register.cpp
|
e7ace03044ed87f1ba736db5c653a3d6803d1d64
|
[] |
no_license
|
hanxinle/xms
|
cdfccc4543d258bb5c9dc0b32101322bff262afd
|
3b3c482300b245caaf32cedab36dd23ec63e99f4
|
refs/heads/master
| 2022-08-29T15:35:18.941631
| 2020-05-28T11:59:33
| 2020-05-28T11:59:33
| null | 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 1,599
|
cpp
|
xconfig_and_register.cpp
|
#include "xconfig_and_register.h"
#include "xregister_client.h"
#include "xconfig_client.h"
#include <string>
using namespace std;
using namespace xmsg;
#define REG XRegisterClient::Get()
#define CONF XConfigClient::Get()
static void ConfTimer()
{
static string conf_ip = "";
static int conf_port = 0;
/////////////////////////////////////////////////////////////////
//读取配置项
//cout << "config root = " << CONF->GetString("root") << endl;
if (conf_port <= 0)
{
//从注册中心获取配置中心的IP
auto confs = REG->GetServcies(CONFIG_NAME, 1);
cout << confs.DebugString();
if (confs.service_size() <= 0)
return;
auto conf = confs.service()[0];
if (conf.ip().empty() || conf.port() <= 0)
return;
conf_ip = conf.ip();
conf_port = conf.port();
CONF->set_server_ip(conf_ip.c_str());
CONF->set_server_port(conf_port);
CONF->Connect();
}
}
bool XConfigAndRegister::Init(const char *service_name,
const char *service_ip,int service_port,
const char *register_ip, int register_port, google::protobuf::Message *conf_message)
{
//设置注册中心的IP和端口
XRegisterClient::Get()->set_server_ip(register_ip);
XRegisterClient::Get()->set_server_port(register_port);
//注册到注册中心
XRegisterClient::Get()->RegisterServer(AUTH_NAME, service_port, service_ip);
//初始化配置中心
//XDirConfig tmp_conf;
CONF->StartGetConf(0, service_port, conf_message, ConfTimer);
return true;
}
|
6c06e9a1276c90b2c1faa627fbd31a9200bc2235
|
3722a067c0477ba213d3ead7c6e75e4c90eab510
|
/src/ultrasonic.h
|
d6f4ce23d5eee66abd495d5caebbb693e2656f9c
|
[] |
no_license
|
shuliga/poweroid-sdk-1.0
|
76a53e88c7224e1ff9b1bbd9eae16cf365957a2b
|
15cd91756a2236f557e587a789f48a880c99a5a0
|
refs/heads/master
| 2023-01-21T10:36:34.446616
| 2023-01-08T22:51:01
| 2023-01-08T22:51:01
| 229,571,460
| 1
| 0
| null | 2023-01-08T22:51:02
| 2019-12-22T13:24:29
|
C
|
UTF-8
|
C++
| false
| false
| 320
|
h
|
ultrasonic.h
|
//
// Created by SHL on 15.02.2019.
//
#ifndef ULTRASONIC_H
#define ULTRASONIC_H
#include "commons.h"
#include "sensors.h"
class Ultrasonic{
public:
void begin(uint8_t n);
uint16_t getDistance();
private:
uint8_t trigger_pin;
uint8_t echo_pin;
};
extern Ultrasonic ULTRASONIC;
#endif //ULTRASONIC_H
|
12f3c120a1d5186166b35c8c98234f6aa9ae26d4
|
4f072b0732be98385ab2dd8a4c4bba395fc5ab27
|
/include/simex/sasm/PreprocessorLexer.h
|
24743c07b0293b06bc2d5d3600b181e6a0da95f2
|
[
"MIT"
] |
permissive
|
nanolith/SIMEX
|
847db15f42c9958e4b3b641bda6dacec24cabe66
|
f67a3498303db5eed45472d63b623d438a7b1cb1
|
refs/heads/master
| 2021-01-13T13:11:58.777004
| 2020-12-03T03:39:44
| 2020-12-03T03:39:44
| 72,690,099
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 8,674
|
h
|
PreprocessorLexer.h
|
/**
* \file PreprocessorLexer.h
*
* Lexer for the Preprocessor.
*
* Copyright (C) 2016 Justin Handville - All Rights Reserved.
*
* This file is part of the SIMEX Virtual Machine which is released under the
* MIT License. See LICENSE.txt in the root of this distribution for further
* information.
*/
#ifndef SIMEX_SASM_PREPROCESSOR_LEXER_HEADER_GUARD
# define SIMEX_SASM_PREPROCESSOR_LEXER_HEADER_GUARD
#include <cstdint>
#include <iosfwd>
#include <memory>
#include <type_traits>
//this header is C++ specific
#ifdef __cplusplus
namespace simex { namespace sasm {
/**
* Preprocessor Input Category.
*
* The preprocessor lexer categorizes input bytes as belonging to one of the
* following categories. These categories are then used by the lexer automaton
* to create tokens for the preprocessor's parser.
*/
enum class PCat
{
//all whitespace characters
Whitespace = 0,
//line end character
LineEnd,
//forward slash
FSlash,
//backslash
BSlash,
//*
Star,
//!
Bang,
//"
DoubleQuote,
//e, E
Exp,
//alphabetical characters, other than e, E, A-F, and a-f
Alpha,
//_
Underscore,
//x
HexX,
//b
BinB,
//0, 1
BNum,
//2, 3, 4, 5, 6, 7
ONum,
//8, 9
DNum,
//A-F, a-f
HNum,
//.
Dot,
//+
Plus,
//-
Minus,
//(
OParen,
//)
CParen,
//<
Lt,
//=
Eq,
//>
Gt,
//,
Comma,
//#
Hash,
//&
Ampersand,
//|
Pipe,
//a byte with the high bit set
HighBit,
//EOF
EndOfFile,
//all other bytes
Unknown
};
/**
* Convert a character to a preprocesser input category.
* This is a lossy conversion.
*
* \param ch The character to convert.
*
* \returns the preprocessor input category for this character.
*/
PCat character2PCat(int by);
/**
* Convert a preprocessor input category to an index.
*
* \param cat The input category to convert.
*
* \returns a 0-based index representing the input category.
*/
inline int pcat2index(PCat cat)
{
//explicit conversion to int
return static_cast<std::underlying_type<PCat>::type>(cat);
}
/**
* Preprocessor Token.
*
* The preprocessor lexer creates tokens with the given enumerated values.
* These tokens are then parsed by the preprocessor parser.
*/
enum class PTok
{
//Newline
Newline = 0,
//String with all valid escapes
String,
//System string (used for system includes)
SystemString,
//#include preprocessing directive
Include,
//#ifdef preprocessing directive
IfDef,
//#ifndef
IfNDef,
//#if preprocessing directive
If,
//#elif preprocessing directive
ElIf,
//#else preprocessing directive
Else,
//#pragma preprocessing directive
Pragma,
//#warning preprocessing directive
Warning,
//#error preprocessing directive
Error,
//&&
And,
//||
Or,
//!
Not,
//(
OParen,
//)
CParen,
//,
Comma,
//a valid identifier
Identifier,
//a valid integer
Integer,
//a valid number
Number,
//##
Concat,
//#identifier -- also acts as intermediate for reducing directives above.
Stringify,
//All other input. Typically passed to the downstream lexer as-is.
Unknown,
//indicates when the end of an input stream has been reached.
EndOfFile,
//Error token. Indicate that the lexer encountered an invalid sequence.
InputError
};
/**
* Convert a preprocessor token into an index.
*
* \param tok The preprocessor token to convert.
*
* \returns a 0-based index representing the preprocessor token.
*/
inline int ptok2index(PTok tok)
{
//explicit conversion to int
return static_cast<std::underlying_type<PTok>::type>(tok);
}
/**
* The Filter interface is a source of filtered input.
*/
class Filter
{
public:
/**
* Filter destructor.
*/
virtual ~Filter();
/**
* The get method works like istream::get(), except that the input is
* filtered.
*
* \returns a filtered input byte, or EOF on EOF.
*/
virtual int get() = 0;
};
/**
* The LineFilter interface tracks the current line number.
*/
class LineFilter : public Filter
{
public:
/**
* Virtual destructor.
*/
virtual ~LineFilter();
/**
* Get the current line number.
*/
virtual int lineNumber() = 0;
/**
* Get the current column number.
*/
virtual int columnNumber() = 0;
};
/**
* The LineFilterImpl class tracks the current line number.
*/
class LineFilterImpl : public LineFilter
{
public:
/**
* Constructor. Create a LineFilterImpl from an input stream.
*/
LineFilterImpl(std::istream& in);
/**
* Virtual destructor.
*/
virtual ~LineFilterImpl();
/**
* The get method works like istream::get(), except that the input is
* filtered.
*
* \returns a filtered input byte, or EOF on EOF.
*/
virtual int get();
/**
* Get the current line number.
*/
virtual int lineNumber();
/**
* Get the current column number.
*/
virtual int columnNumber();
private:
std::istream& in_;
int lineNumber_;
int columnNumber_;
};
/**
* Forward declaration to the private WhitespaceFilterImplementation.
*/
struct WhitespaceFilterImplementation;
/**
* The WhitespaceFilter class reduces whitespace and comments down to a single
* whitespace character, and keeps a physical line count.
*/
class WhitespaceFilter : virtual public LineFilter
{
public:
/**
* A WhitespaceFilter is created from an input stream.
*
* \param istream The input stream used for this filter.
*/
WhitespaceFilter(std::istream& in);
/**
* Destructor. Clean up this instance.
*/
virtual ~WhitespaceFilter();
/**
* The get method works like istream::get(), except that white space
* characters and comments are condensed to a single space.
*
* \returns a filtered input byte, or EOF on EOF.
*/
virtual int get();
/**
* Returns the current physical line number for this input stream.
*/
virtual int lineNumber();
/**
* Get the current column number.
*/
virtual int columnNumber();
private:
std::unique_ptr<WhitespaceFilterImplementation> impl_;
};
/**
* Forward declaration to the private PreprocessorLexerImplementation.
*/
struct PreprocessorLexerImplementation;
/**
* The PreprocessorLexer class transforms an input stream to a series of tokens
* that can be fed into the PreprocessorParser. Methods to return the string,
* integer, and double representations of tokens, where applicable, are
* provided.
*/
class PreprocessorLexer
{
public:
/**
* A PreprocessorLexer is created from an input stream.
*
* \param istream The input stream used for this filter.
*/
PreprocessorLexer(std::istream& in);
/**
* Destructor. Clean up this instance.
*/
virtual ~PreprocessorLexer();
/**
* The get method returns a token from the input stream.
*
* \returns a token from the input stream, or PTok::EndOfFile if the end of
* the input stream has been reached.
*/
PTok get();
/**
* Returns the current physical line number for this input stream.
*/
int lineNumber();
/**
* Get the current column number.
*/
int columnNumber();
/**
* Returns the string representation of the current token.
*/
std::string stringTok();
/**
* Returns the integer representation of the current token.
*/
std::int64_t intTok();
/**
* Returns the unsigned integer representation of the current token.
*/
std::uint64_t uintTok();
/**
* Returns the double representation of the current token.
*/
double doubleTok();
/**
* Returns the line number where the token started.
*/
int tokenStartLineNumber();
/**
* Returns the column number where the token started.
*/
int tokenStartColumnNumber();
/**
* Returns the line number where the token ended.
*/
int tokenEndLineNumber();
/**
* Returns the column number where the token ended.
*/
int tokenEndColumnNumber();
private:
std::unique_ptr<PreprocessorLexerImplementation> impl_;
};
/* namespace sasm */ } /* namespace simex */ }
//end of C++ code
#endif //__cplusplus
#endif //SIMEX_SASM_PREPROCESSOR_LEXER_HEADER_GUARD
|
ca89d81bb17a664b7bf0437d1bef24bd02fd2390
|
864dc68b63491e6286b43ad7e9ef6c615cb6d672
|
/350-str C++/350-str C++/Source1.cpp
|
3652ecbcb85b11dfb3c9a784c9f0686cb5386c4d
|
[] |
no_license
|
HristoHristov95/C--
|
849b65859b17f81f5f7c19218c38474b44ba7616
|
a3cb964cf931f3b2c11eb2ed0fe8841fd0d0c5ac
|
refs/heads/master
| 2021-01-01T03:51:38.704768
| 2016-04-15T18:03:18
| 2016-04-15T18:03:18
| 56,339,634
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 511
|
cpp
|
Source1.cpp
|
#include<iostream>
using namespace std;
class base{
public:
virtual void func()
{
cout << "Using base version of func()\n";
}
};
class derived1 :public base{
public:
/*void func()
{
cout << "Using derived1's version of func()\n";
}*/
};
class derived2 :public derived1{
public:
void func()
{
cout << "Using derived2's version of func()\n";
}
};
int main()
{
base *p;
base ob;
derived1 d_ob1;
derived2 d_ob2;
p = &ob;
p->func();
p = &d_ob1;
p->func();
p = &d_ob2;
p->func();
return 0;
}
|
46c0b0ae066def5df943ec074830a406c482cacb
|
08a25eadde07c7489136c61f80bf326651c293f6
|
/ros_ws/src/crazyswarm/src/crazyswarm_server.cpp
|
6172ec58c6ba661a380f4c5fed7b5ed6f477a713
|
[
"MIT"
] |
permissive
|
USC-ACTLab/crazyswarm
|
36c03d308882518d998c4ab6b26e7e8f5c05745f
|
beb05492eaf226462631545bf5972199099267c2
|
refs/heads/master
| 2023-06-03T04:31:43.944450
| 2022-12-17T19:15:17
| 2022-12-17T19:15:17
| 68,335,694
| 296
| 296
|
MIT
| 2023-05-12T18:08:28
| 2016-09-15T22:18:11
|
Python
|
UTF-8
|
C++
| false
| false
| 64,140
|
cpp
|
crazyswarm_server.cpp
|
#include "ros/ros.h"
#include <tf/transform_broadcaster.h>
#include <tf_conversions/tf_eigen.h>
#include <ros/callback_queue.h>
#include "crazyswarm/LogBlock.h"
#include "crazyswarm/GenericLogData.h"
#include "crazyswarm/UpdateParams.h"
#include "crazyswarm/UploadTrajectory.h"
#include "crazyswarm/NotifySetpointsStop.h"
#undef major
#undef minor
#include "crazyswarm/Hover.h"
#include "crazyswarm/Takeoff.h"
#include "crazyswarm/Land.h"
#include "crazyswarm/GoTo.h"
#include "crazyswarm/StartTrajectory.h"
#include "crazyswarm/SetGroupMask.h"
#include "crazyswarm/FullState.h"
#include "crazyswarm/Position.h"
#include "crazyswarm/VelocityWorld.h"
#include "std_srvs/Empty.h"
#include <std_msgs/Empty.h>
#include "geometry_msgs/Twist.h"
#include "sensor_msgs/Imu.h"
#include "sensor_msgs/Temperature.h"
#include "sensor_msgs/MagneticField.h"
#include "std_msgs/Float32.h"
#include <sensor_msgs/Joy.h>
#include <sensor_msgs/PointCloud.h>
//#include <regex>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <crazyflie_cpp/Crazyflie.h>
// debug test
#include <signal.h>
#include <csignal> // or C++ style alternative
// Motion Capture
#include <libmotioncapture/motioncapture.h>
// Object tracker
#include <libobjecttracker/object_tracker.h>
#include <libobjecttracker/cloudlog.hpp>
#include <fstream>
#include <future>
#include <mutex>
#include <wordexp.h> // tilde expansion
/*
Threading
* There are 2N+1 threads, where N is the number of groups (== number of unique channels)
* The main thread uses the libmotioncapture to receive external state updates; Once a new frame comes in, the
workers (CrazyflieGroup) are notified using a condition variable. Each CrazyflieGroup
does the objectTracking for its own group and broadcasts the resulting mocap data.
* One helper thread is used in the server to take care of incoming global service requests.
Those are forwarded to the groups (using a function call, i.e. the broadcasts run in this thread).
* Each group has two threads:
* Mocap worker. Waits for new mocap data (using a condition variable) and does the object tracking
and broadcasts the result.
* Service worker: Listens to CF-based service calls (such as upload trajectory) and executes
them. Those can be potentially long, without interfering with the mocap update.
*/
constexpr double pi() { return std::atan(1)*4; }
double degToRad(double deg) {
return deg / 180.0 * pi();
}
double radToDeg(double rad) {
return rad * 180.0 / pi();
}
void logWarn(const std::string& msg)
{
ROS_WARN("%s", msg.c_str());
}
class ROSLogger : public Logger
{
public:
ROSLogger()
: Logger()
{
}
virtual ~ROSLogger() {}
virtual void info(const std::string& msg)
{
ROS_INFO("%s", msg.c_str());
}
virtual void warning(const std::string& msg)
{
ROS_WARN("%s", msg.c_str());
}
virtual void error(const std::string& msg)
{
ROS_ERROR("%s", msg.c_str());
}
};
static ROSLogger rosLogger;
class CrazyflieROS
{
public:
CrazyflieROS(
const std::string& link_uri,
const std::string& tf_prefix,
const std::string& frame,
const std::string& worldFrame,
int id,
const std::string& type,
const std::vector<crazyswarm::LogBlock>& log_blocks,
ros::CallbackQueue& queue)
: m_tf_prefix(tf_prefix)
, m_cf(
link_uri,
rosLogger,
std::bind(&CrazyflieROS::onConsole, this, std::placeholders::_1))
, m_frame(frame)
, m_worldFrame(worldFrame)
, m_id(id)
, m_type(type)
, m_serviceUpdateParams()
, m_serviceUploadTrajectory()
, m_serviceStartTrajectory()
, m_serviceTakeoff()
, m_serviceLand()
, m_serviceGoTo()
, m_serviceSetGroupMask()
, m_serviceNotifySetpointsStop()
, m_logBlocks(log_blocks)
, m_initializedPosition(false)
{
ros::NodeHandle nl("~");
nl.param("enable_logging", m_enableLogging, false);
nl.param("enable_logging_pose", m_enableLoggingPose, false);
nl.param("enable_parameters", m_enableParameters, true);
nl.param("force_no_cache", m_forceNoCache, false);
ros::NodeHandle n;
n.setCallbackQueue(&queue);
m_serviceUploadTrajectory = n.advertiseService(tf_prefix + "/upload_trajectory", &CrazyflieROS::uploadTrajectory, this);
m_serviceStartTrajectory = n.advertiseService(tf_prefix + "/start_trajectory", &CrazyflieROS::startTrajectory, this);
m_serviceTakeoff = n.advertiseService(tf_prefix + "/takeoff", &CrazyflieROS::takeoff, this);
m_serviceLand = n.advertiseService(tf_prefix + "/land", &CrazyflieROS::land, this);
m_serviceGoTo = n.advertiseService(tf_prefix + "/go_to", &CrazyflieROS::goTo, this);
m_serviceSetGroupMask = n.advertiseService(tf_prefix + "/set_group_mask", &CrazyflieROS::setGroupMask, this);
m_serviceNotifySetpointsStop = n.advertiseService(tf_prefix + "/notify_setpoints_stop", &CrazyflieROS::notifySetpointsStop, this);
m_subscribeCmdVel = n.subscribe(tf_prefix + "/cmd_vel", 1, &CrazyflieROS::cmdVelChanged, this);
m_subscribeCmdPosition = n.subscribe(tf_prefix + "/cmd_position", 1, &CrazyflieROS::cmdPositionSetpoint, this);
m_subscribeCmdFullState = n.subscribe(tf_prefix + "/cmd_full_state", 1, &CrazyflieROS::cmdFullStateSetpoint, this);
m_subscribeCmdVelocityWorld = n.subscribe(tf_prefix + "/cmd_velocity_world", 1, &CrazyflieROS::cmdVelocityWorldSetpoint, this);
m_subscribeCmdStop = n.subscribe(m_tf_prefix + "/cmd_stop", 1, &CrazyflieROS::cmdStop, this);
// New Velocity command type (Hover)
m_subscribeCmdHover=n.subscribe(m_tf_prefix+"/cmd_hover",1,&CrazyflieROS::cmdHoverSetpoint, this);
if (m_enableLogging) {
m_logFile.open("logcf" + std::to_string(id) + ".csv");
m_logFile << "time,";
for (auto& logBlock : m_logBlocks) {
m_pubLogDataGeneric.push_back(n.advertise<crazyswarm::GenericLogData>(tf_prefix + "/" + logBlock.topic_name, 10));
for (const auto& variableName : logBlock.variables) {
m_logFile << variableName << ",";
}
}
m_logFile << std::endl;
if (m_enableLoggingPose) {
m_pubPose = n.advertise<geometry_msgs::PoseStamped>(m_tf_prefix + "/pose", 10);
}
}
// m_subscribeJoy = n.subscribe("/joy", 1, &CrazyflieROS::joyChanged, this);
}
~CrazyflieROS()
{
m_logBlocks.clear();
m_logBlocksGeneric.clear();
// m_cf.trySysOff();
m_logFile.close();
}
const std::string& frame() const {
return m_frame;
}
const int id() const {
return m_id;
}
const std::string& type() const {
return m_type;
}
void sendPing() {
m_cf.sendPing();
}
// void joyChanged(
// const sensor_msgs::Joy::ConstPtr& msg)
// {
// static bool lastState = false;
// // static float x = 0.0;
// // static float y = 0.0;
// // static float z = 1.0;
// // static float yaw = 0;
// // bool changed = false;
// // float dx = msg->axes[4];
// // if (fabs(dx) > 0.1) {
// // x += dx * 0.01;
// // changed = true;
// // }
// // float dy = msg->axes[3];
// // if (fabs(dy) > 0.1) {
// // y += dy * 0.01;
// // changed = true;
// // }
// // float dz = msg->axes[1];
// // if (fabs(dz) > 0.1) {
// // z += dz * 0.01;
// // changed = true;
// // }
// // float dyaw = msg->axes[0];
// // if (fabs(dyaw) > 0.1) {
// // yaw += dyaw * 1.0;
// // changed = true;
// // }
// // if (changed) {
// // ROS_INFO("[%f, %f, %f, %f]", x, y, z, yaw);
// // m_cf.trajectoryHover(x, y, z, yaw);
// // }
// if (msg->buttons[4] && !lastState) {
// ROS_INFO("hover!");
// m_cf.trajectoryHover(0, 0, 1.0, 0, 2.0);
// }
// lastState = msg->buttons[4];
// }
public:
template<class T, class U>
void updateParam(uint16_t id, const std::string& ros_param) {
U value;
ros::param::get(ros_param, value);
m_cf.addSetParam<T>(id, (T)value);
}
bool updateParams(
crazyswarm::UpdateParams::Request& req,
crazyswarm::UpdateParams::Response& res)
{
ROS_INFO("[%s] Update parameters", m_frame.c_str());
m_cf.startSetParamRequest();
for (auto&& p : req.params) {
std::string ros_param = "/" + m_tf_prefix + "/" + p;
size_t pos = p.find("/");
std::string group(p.begin(), p.begin() + pos);
std::string name(p.begin() + pos + 1, p.end());
auto entry = m_cf.getParamTocEntry(group, name);
if (entry)
{
switch (entry->type) {
case Crazyflie::ParamTypeUint8:
updateParam<uint8_t, int>(entry->id, ros_param);
break;
case Crazyflie::ParamTypeInt8:
updateParam<int8_t, int>(entry->id, ros_param);
break;
case Crazyflie::ParamTypeUint16:
updateParam<uint16_t, int>(entry->id, ros_param);
break;
case Crazyflie::ParamTypeInt16:
updateParam<int16_t, int>(entry->id, ros_param);
break;
case Crazyflie::ParamTypeUint32:
updateParam<uint32_t, int>(entry->id, ros_param);
break;
case Crazyflie::ParamTypeInt32:
updateParam<int32_t, int>(entry->id, ros_param);
break;
case Crazyflie::ParamTypeFloat:
updateParam<float, float>(entry->id, ros_param);
break;
}
}
else {
ROS_ERROR("Could not find param %s/%s", group.c_str(), name.c_str());
}
}
m_cf.setRequestedParams();
return true;
}
bool uploadTrajectory(
crazyswarm::UploadTrajectory::Request& req,
crazyswarm::UploadTrajectory::Response& res)
{
ROS_INFO("[%s] Upload trajectory", m_frame.c_str());
std::vector<Crazyflie::poly4d> pieces(req.pieces.size());
for (size_t i = 0; i < pieces.size(); ++i) {
if ( req.pieces[i].poly_x.size() != 8
|| req.pieces[i].poly_y.size() != 8
|| req.pieces[i].poly_z.size() != 8
|| req.pieces[i].poly_yaw.size() != 8) {
ROS_FATAL("Wrong number of pieces!");
return false;
}
pieces[i].duration = req.pieces[i].duration.toSec();
for (size_t j = 0; j < 8; ++j) {
pieces[i].p[0][j] = req.pieces[i].poly_x[j];
pieces[i].p[1][j] = req.pieces[i].poly_y[j];
pieces[i].p[2][j] = req.pieces[i].poly_z[j];
pieces[i].p[3][j] = req.pieces[i].poly_yaw[j];
}
}
m_cf.uploadTrajectory(req.trajectoryId, req.pieceOffset, pieces);
ROS_INFO("[%s] Uploaded trajectory", m_frame.c_str());
return true;
}
bool startTrajectory(
crazyswarm::StartTrajectory::Request& req,
crazyswarm::StartTrajectory::Response& res)
{
ROS_INFO("[%s] Start trajectory", m_frame.c_str());
m_cf.startTrajectory(req.trajectoryId, req.timescale, req.reversed, req.relative, req.groupMask);
return true;
}
bool notifySetpointsStop(
crazyswarm::NotifySetpointsStop::Request& req,
crazyswarm::NotifySetpointsStop::Response& res)
{
ROS_INFO_NAMED(m_tf_prefix, "NotifySetpointsStop requested");
m_cf.notifySetpointsStop(req.remainValidMillisecs);
return true;
}
bool takeoff(
crazyswarm::Takeoff::Request& req,
crazyswarm::Takeoff::Response& res)
{
ROS_INFO("[%s] Takeoff", m_frame.c_str());
m_cf.takeoff(req.height, req.duration.toSec(), req.groupMask);
return true;
}
bool land(
crazyswarm::Land::Request& req,
crazyswarm::Land::Response& res)
{
ROS_INFO("[%s] Land", m_frame.c_str());
m_cf.land(req.height, req.duration.toSec(), req.groupMask);
return true;
}
bool goTo(
crazyswarm::GoTo::Request& req,
crazyswarm::GoTo::Response& res)
{
ROS_INFO("[%s] GoTo", m_frame.c_str());
m_cf.goTo(req.goal.x, req.goal.y, req.goal.z, req.yaw, req.duration.toSec(), req.relative, req.groupMask);
return true;
}
bool setGroupMask(
crazyswarm::SetGroupMask::Request& req,
crazyswarm::SetGroupMask::Response& res)
{
ROS_INFO("[%s] Set Group Mask", m_frame.c_str());
m_cf.setGroupMask(req.groupMask);
return true;
}
void cmdVelChanged(
const geometry_msgs::Twist::ConstPtr& msg)
{
// if (!m_isEmergency) {
float roll = msg->linear.y;
float pitch = -msg->linear.x;
float yawrate = msg->angular.z;
uint16_t thrust = (uint16_t)msg->linear.z;
m_cf.sendSetpoint(roll, pitch, yawrate, thrust);
// ROS_INFO("cmdVel %f %f %f %d (%f)", roll, pitch, yawrate, thrust, msg->linear.z);
// m_sentSetpoint = true;
// }
}
void cmdPositionSetpoint(
const crazyswarm::Position::ConstPtr& msg)
{
// if(!m_isEmergency) {
float x = msg->x;
float y = msg->y;
float z = msg->z;
float yaw = msg->yaw;
m_cf.sendPositionSetpoint(x, y, z, yaw);
// m_sentSetpoint = true;
// }
}
void cmdFullStateSetpoint(
const crazyswarm::FullState::ConstPtr& msg)
{
//ROS_INFO("got a full state setpoint");
// if (!m_isEmergency) {
float x = msg->pose.position.x;
float y = msg->pose.position.y;
float z = msg->pose.position.z;
float vx = msg->twist.linear.x;
float vy = msg->twist.linear.y;
float vz = msg->twist.linear.z;
float ax = msg->acc.x;
float ay = msg->acc.y;
float az = msg->acc.z;
float qx = msg->pose.orientation.x;
float qy = msg->pose.orientation.y;
float qz = msg->pose.orientation.z;
float qw = msg->pose.orientation.w;
float rollRate = msg->twist.angular.x;
float pitchRate = msg->twist.angular.y;
float yawRate = msg->twist.angular.z;
m_cf.sendFullStateSetpoint(
x, y, z,
vx, vy, vz,
ax, ay, az,
qx, qy, qz, qw,
rollRate, pitchRate, yawRate);
// m_sentSetpoint = true;
//ROS_INFO("set a full state setpoint");
// }
}
void cmdHoverSetpoint(const crazyswarm::Hover::ConstPtr& msg){
//ROS_INFO("got a hover setpoint");
float vx = msg->vx;
float vy = msg->vy;
float yawRate = msg->yawrate;
float zDistance = msg->zDistance;
m_cf.sendHoverSetpoint(vx, vy, yawRate, zDistance);
//ROS_INFO("set a hover setpoint");
}
void cmdVelocityWorldSetpoint(
const crazyswarm::VelocityWorld::ConstPtr& msg)
{
// ROS_INFO("got a velocity world setpoint");
// if (!m_isEmergency) {
float x = msg->vel.x;
float y = msg->vel.y;
float z = msg->vel.z;
float yawRate = msg->yawRate;
m_cf.sendVelocityWorldSetpoint(
x, y, z, yawRate);
// m_sentSetpoint = true;
// ROS_INFO("set a velocity world setpoint");
// }
}
void cmdStop(
const std_msgs::Empty::ConstPtr& msg)
{
//ROS_INFO("got a stop setpoint");
// if (!m_isEmergency) {
m_cf.sendStop();
// m_sentSetpoint = true;
//ROS_INFO("set a stop setpoint");
// }
}
void run(
ros::CallbackQueue& queue)
{
// m_cf.reboot();
// m_cf.syson();
// std::this_thread::sleep_for(std::chrono::milliseconds(1000));
auto start = std::chrono::system_clock::now();
std::function<void(float)> cb_lq = std::bind(&CrazyflieROS::onLinkQuality, this, std::placeholders::_1);
m_cf.setLinkQualityCallback(cb_lq);
m_cf.logReset();
int numParams = 0;
if (m_enableParameters)
{
ROS_INFO("[%s] Requesting parameters...", m_frame.c_str());
m_cf.requestParamToc(m_forceNoCache);
for (auto iter = m_cf.paramsBegin(); iter != m_cf.paramsEnd(); ++iter) {
auto entry = *iter;
std::string paramName = "/" + m_tf_prefix + "/" + entry.group + "/" + entry.name;
switch (entry.type) {
case Crazyflie::ParamTypeUint8:
ros::param::set(paramName, m_cf.getParam<uint8_t>(entry.id));
break;
case Crazyflie::ParamTypeInt8:
ros::param::set(paramName, m_cf.getParam<int8_t>(entry.id));
break;
case Crazyflie::ParamTypeUint16:
ros::param::set(paramName, m_cf.getParam<uint16_t>(entry.id));
break;
case Crazyflie::ParamTypeInt16:
ros::param::set(paramName, m_cf.getParam<int16_t>(entry.id));
break;
case Crazyflie::ParamTypeUint32:
ros::param::set(paramName, (int)m_cf.getParam<uint32_t>(entry.id));
break;
case Crazyflie::ParamTypeInt32:
ros::param::set(paramName, m_cf.getParam<int32_t>(entry.id));
break;
case Crazyflie::ParamTypeFloat:
ros::param::set(paramName, m_cf.getParam<float>(entry.id));
break;
}
++numParams;
}
ros::NodeHandle n;
n.setCallbackQueue(&queue);
m_serviceUpdateParams = n.advertiseService(m_tf_prefix + "/update_params", &CrazyflieROS::updateParams, this);
}
auto end1 = std::chrono::system_clock::now();
std::chrono::duration<double> elapsedSeconds1 = end1-start;
ROS_INFO("[%s] reqParamTOC: %f s (%d params)", m_frame.c_str(), elapsedSeconds1.count(), numParams);
// Logging
if (m_enableLogging) {
ROS_INFO("[%s] Requesting logging variables...", m_frame.c_str());
m_cf.requestLogToc(m_forceNoCache);
auto end2 = std::chrono::system_clock::now();
std::chrono::duration<double> elapsedSeconds2 = end2-end1;
ROS_INFO("[%s] reqLogTOC: %f s", m_frame.c_str(), elapsedSeconds2.count());
m_logBlocksGeneric.resize(m_logBlocks.size());
// custom log blocks
size_t i = 0;
for (auto& logBlock : m_logBlocks)
{
std::function<void(uint32_t, std::vector<double>*, void* userData)> cb =
std::bind(
&CrazyflieROS::onLogCustom,
this,
std::placeholders::_1,
std::placeholders::_2,
std::placeholders::_3);
m_logBlocksGeneric[i].reset(new LogBlockGeneric(
&m_cf,
logBlock.variables,
(void*)&m_pubLogDataGeneric[i],
cb));
m_logBlocksGeneric[i]->start(logBlock.frequency / 10);
++i;
}
auto end3 = std::chrono::system_clock::now();
std::chrono::duration<double> elapsedSeconds3 = end3-end2;
ROS_INFO("[%s] logBlocks: %f s", m_frame.c_str(), elapsedSeconds1.count());
if (m_enableLoggingPose) {
std::function<void(uint32_t, logPose*)> cb = std::bind(&CrazyflieROS::onPoseData, this, std::placeholders::_1, std::placeholders::_2);
m_logBlockPose.reset(new LogBlock<logPose>(
&m_cf,{
{"stateEstimate", "x"},
{"stateEstimate", "y"},
{"stateEstimate", "z"},
{"stateEstimateZ", "quat"}
}, cb));
m_logBlockPose->start(10); // 100ms
}
}
ROS_INFO("Requesting memories...");
m_cf.requestMemoryToc();
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsedSeconds = end-start;
ROS_INFO("[%s] Ready. Elapsed: %f s", m_frame.c_str(), elapsedSeconds.count());
}
const Crazyflie::ParamTocEntry* getParamTocEntry(
const std::string& group,
const std::string& name) const
{
return m_cf.getParamTocEntry(group, name);
}
void initializePositionIfNeeded(float x, float y, float z)
{
if (m_initializedPosition) {
return;
}
m_cf.startSetParamRequest();
auto entry = m_cf.getParamTocEntry("kalman", "initialX");
m_cf.addSetParam(entry->id, x);
entry = m_cf.getParamTocEntry("kalman", "initialY");
m_cf.addSetParam(entry->id, y);
entry = m_cf.getParamTocEntry("kalman", "initialZ");
m_cf.addSetParam(entry->id, z);
m_cf.setRequestedParams();
entry = m_cf.getParamTocEntry("kalman", "resetEstimation");
m_cf.setParam<uint8_t>(entry->id, 1);
// kalmanUSC might not be part of the firmware
entry = m_cf.getParamTocEntry("kalmanUSC", "resetEstimation");
if (entry) {
m_cf.startSetParamRequest();
entry = m_cf.getParamTocEntry("kalmanUSC", "initialX");
m_cf.addSetParam(entry->id, x);
entry = m_cf.getParamTocEntry("kalmanUSC", "initialY");
m_cf.addSetParam(entry->id, y);
entry = m_cf.getParamTocEntry("kalmanUSC", "initialZ");
m_cf.addSetParam(entry->id, z);
m_cf.setRequestedParams();
entry = m_cf.getParamTocEntry("kalmanUSC", "resetEstimation");
m_cf.setParam<uint8_t>(entry->id, 1);
}
m_initializedPosition = true;
}
private:
struct logPose {
float x;
float y;
float z;
int32_t quatCompressed;
} __attribute__((packed));
private:
void onLinkQuality(float linkQuality) {
if (linkQuality < 0.7) {
ROS_WARN("[%s] Link Quality low (%f)", m_frame.c_str(), linkQuality);
}
}
void onConsole(const char* msg) {
m_messageBuffer += msg;
size_t pos = m_messageBuffer.find('\n');
if (pos != std::string::npos) {
m_messageBuffer[pos] = 0;
ROS_INFO("[%s] %s", m_frame.c_str(), m_messageBuffer.c_str());
m_messageBuffer.erase(0, pos+1);
}
}
void onPoseData(uint32_t time_in_ms, logPose* data) {
if (m_enableLoggingPose) {
geometry_msgs::PoseStamped msg;
msg.header.stamp = ros::Time::now();
msg.header.frame_id = "world";
msg.pose.position.x = data->x;
msg.pose.position.y = data->y;
msg.pose.position.z = data->z;
float q[4];
quatdecompress(data->quatCompressed, q);
msg.pose.orientation.x = q[0];
msg.pose.orientation.y = q[1];
msg.pose.orientation.z = q[2];
msg.pose.orientation.w = q[3];
m_pubPose.publish(msg);
tf::Transform tftransform;
tftransform.setOrigin(tf::Vector3(data->x, data->y, data->z));
tftransform.setRotation(tf::Quaternion(q[0], q[1], q[2], q[3]));
m_br.sendTransform(tf::StampedTransform(tftransform, ros::Time::now(), "world", frame()));
}
}
void onLogCustom(uint32_t time_in_ms, std::vector<double>* values, void* userData) {
ros::Publisher* pub = reinterpret_cast<ros::Publisher*>(userData);
crazyswarm::GenericLogData msg;
msg.header.stamp = ros::Time(time_in_ms/1000.0);
msg.values = *values;
m_logFile << time_in_ms / 1000.0 << ",";
for (const auto& value : *values) {
m_logFile << value << ",";
}
m_logFile << std::endl;
pub->publish(msg);
}
private:
std::string m_tf_prefix;
Crazyflie m_cf;
std::string m_frame;
std::string m_worldFrame;
bool m_enableParameters;
bool m_enableLogging;
bool m_enableLoggingPose;
int m_id;
std::string m_type;
ros::ServiceServer m_serviceUpdateParams;
ros::ServiceServer m_serviceUploadTrajectory;
ros::ServiceServer m_serviceStartTrajectory;
ros::ServiceServer m_serviceTakeoff;
ros::ServiceServer m_serviceLand;
ros::ServiceServer m_serviceGoTo;
ros::ServiceServer m_serviceSetGroupMask;
ros::ServiceServer m_serviceNotifySetpointsStop;
ros::Subscriber m_subscribeCmdVel;
ros::Subscriber m_subscribeCmdPosition;
ros::Subscriber m_subscribeCmdFullState;
ros::Subscriber m_subscribeCmdVelocityWorld;
ros::Subscriber m_subscribeCmdStop;
ros::Subscriber m_subscribeCmdHover; // Hover vel subscriber
tf::TransformBroadcaster m_br;
std::vector<crazyswarm::LogBlock> m_logBlocks;
std::vector<ros::Publisher> m_pubLogDataGeneric;
std::vector<std::unique_ptr<LogBlockGeneric> > m_logBlocksGeneric;
ros::Subscriber m_subscribeJoy;
ros::Publisher m_pubPose;
std::unique_ptr<LogBlock<logPose>> m_logBlockPose;
std::ofstream m_logFile;
bool m_forceNoCache;
bool m_initializedPosition;
std::string m_messageBuffer;
};
// handles a group of Crazyflies, which share a radio
class CrazyflieGroup
{
public:
struct latency
{
double objectTracking;
double broadcasting;
};
CrazyflieGroup(
const std::vector<libobjecttracker::DynamicsConfiguration>& dynamicsConfigurations,
const std::vector<libobjecttracker::MarkerConfiguration>& markerConfigurations,
pcl::PointCloud<pcl::PointXYZ>::Ptr pMarkers,
std::map<std::string, libmotioncapture::RigidBody>* pMocapRigidBodies,
int radio,
int channel,
bool useMotionCaptureObjectTracking,
const std::vector<crazyswarm::LogBlock>& logBlocks,
std::string interactiveObject,
bool writeCSVs,
bool sendPositionOnly
)
: m_cfs()
, m_tracker(nullptr)
, m_radio(radio)
, m_pMarkers(pMarkers)
, m_pMocapRigidBodies(pMocapRigidBodies)
, m_slowQueue()
, m_cfbc("radio://" + std::to_string(radio) + "/" + std::to_string(channel) + "/2M/FFE7E7E7E7")
, m_isEmergency(false)
, m_useMotionCaptureObjectTracking(useMotionCaptureObjectTracking)
, m_br()
, m_interactiveObject(interactiveObject)
, m_sendPositionOnly(sendPositionOnly)
, m_outputCSVs()
, m_phase(0)
, m_phaseStart()
{
std::vector<libobjecttracker::Object> objects;
readObjects(objects, channel, logBlocks);
m_tracker = new libobjecttracker::ObjectTracker(
dynamicsConfigurations,
markerConfigurations,
objects);
m_tracker->setLogWarningCallback(logWarn);
if (writeCSVs) {
m_outputCSVs.resize(m_cfs.size());
for (auto& output : m_outputCSVs) {
output.reset(new std::ofstream);
}
}
}
~CrazyflieGroup()
{
for(auto cf : m_cfs) {
delete cf;
}
delete m_tracker;
}
const latency& lastLatency() const {
return m_latency;
}
int radio() const {
return m_radio;
}
void runInteractiveObject(std::vector<CrazyflieBroadcaster::externalPose> &states)
{
publishRigidBody(m_interactiveObject, 0xFF, states);
}
void runFast()
{
auto stamp = std::chrono::high_resolution_clock::now();
std::vector<CrazyflieBroadcaster::externalPose> states;
if (!m_interactiveObject.empty()) {
runInteractiveObject(states);
}
if (m_useMotionCaptureObjectTracking) {
for (auto cf : m_cfs) {
bool found = publishRigidBody(cf->frame(), cf->id(), states);
if (found) {
cf->initializePositionIfNeeded(states.back().x, states.back().y, states.back().z);
}
}
} else {
// run object tracker
{
auto start = std::chrono::high_resolution_clock::now();
m_tracker->update(m_pMarkers);
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsedSeconds = end-start;
m_latency.objectTracking = elapsedSeconds.count();
// totalLatency += elapsedSeconds.count();
// ROS_INFO("Tracking: %f s", elapsedSeconds.count());
}
for (size_t i = 0; i < m_cfs.size(); ++i) {
if (m_tracker->objects()[i].lastTransformationValid()) {
const Eigen::Affine3f& transform = m_tracker->objects()[i].transformation();
Eigen::Quaternionf q(transform.rotation());
const auto& translation = transform.translation();
states.resize(states.size() + 1);
states.back().id = m_cfs[i]->id();
states.back().x = translation.x();
states.back().y = translation.y();
states.back().z = translation.z();
states.back().qx = q.x();
states.back().qy = q.y();
states.back().qz = q.z();
states.back().qw = q.w();
m_cfs[i]->initializePositionIfNeeded(states.back().x, states.back().y, states.back().z);
tf::Transform tftransform;
tftransform.setOrigin(tf::Vector3(translation.x(), translation.y(), translation.z()));
tftransform.setRotation(tf::Quaternion(q.x(), q.y(), q.z(), q.w()));
// Eigen::Affine3d transformd = transform.cast<double>();
// tf::transformEigenToTF(transformd, tftransform);
// tftransform.setOrigin(tf::Vector3(translation.x(), translation.y(), translation.z()));
// tf::Quaternion tfq(q.x(), q.y(), q.z(), q.w());
m_br.sendTransform(tf::StampedTransform(tftransform, ros::Time::now(), "world", m_cfs[i]->frame()));
if (m_outputCSVs.size() > 0) {
std::chrono::duration<double> tDuration = stamp - m_phaseStart;
double t = tDuration.count();
auto rpy = q.toRotationMatrix().eulerAngles(0, 1, 2);
*m_outputCSVs[i] << t << "," << states.back().x << "," << states.back().y << "," << states.back().z
<< "," << rpy(0) << "," << rpy(1) << "," << rpy(2) << "\n";
}
} else {
std::chrono::duration<double> elapsedSeconds = stamp - m_tracker->objects()[i].lastValidTime();
ROS_WARN("No updated pose for CF %s for %f s.",
m_cfs[i]->frame().c_str(),
elapsedSeconds.count());
}
}
}
{
auto start = std::chrono::high_resolution_clock::now();
if (!m_sendPositionOnly) {
m_cfbc.sendExternalPoses(states);
} else {
std::vector<CrazyflieBroadcaster::externalPosition> positions(states.size());
for (size_t i = 0; i < positions.size(); ++i) {
positions[i].id = states[i].id;
positions[i].x = states[i].x;
positions[i].y = states[i].y;
positions[i].z = states[i].z;
}
m_cfbc.sendExternalPositions(positions);
}
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsedSeconds = end-start;
m_latency.broadcasting = elapsedSeconds.count();
// totalLatency += elapsedSeconds.count();
// ROS_INFO("Broadcasting: %f s", elapsedSeconds.count());
}
// auto time = std::chrono::duration_cast<std::chrono::microseconds>(
// std::chrono::high_resolution_clock::now().time_since_epoch()).count();
// for (const auto& state : states) {
// std::cout << time << "," << state.x << "," << state.y << "," << state.z << std::endl;
// }
}
void runSlow()
{
ros::NodeHandle nl("~");
bool enableLogging;
nl.getParam("enable_logging", enableLogging);
while(ros::ok() && !m_isEmergency) {
if (enableLogging) {
for (const auto& cf : m_cfs) {
cf->sendPing();
}
}
m_slowQueue.callAvailable(ros::WallDuration(0));
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
void emergency()
{
m_cfbc.emergencyStop();
m_isEmergency = true;
}
void takeoff(float height, float duration, uint8_t groupMask)
{
// for (size_t i = 0; i < 10; ++i) {
m_cfbc.takeoff(height, duration, groupMask);
// std::this_thread::sleep_for(std::chrono::milliseconds(1));
// }
}
void land(float height, float duration, uint8_t groupMask)
{
// for (size_t i = 0; i < 10; ++i) {
m_cfbc.land(height, duration, groupMask);
// std::this_thread::sleep_for(std::chrono::milliseconds(1));
// }
}
void goTo(float x, float y, float z, float yaw, float duration, uint8_t groupMask)
{
// for (size_t i = 0; i < 10; ++i) {
m_cfbc.goTo(x, y, z, yaw, duration, groupMask);
// std::this_thread::sleep_for(std::chrono::milliseconds(1));
// }
}
void startTrajectory(
uint8_t trajectoryId,
float timescale,
bool reversed,
uint8_t groupMask)
{
// for (size_t i = 0; i < 10; ++i) {
m_cfbc.startTrajectory(trajectoryId, timescale, reversed, groupMask);
// std::this_thread::sleep_for(std::chrono::milliseconds(1));
// }
}
template<class T, class U>
void updateParam(const char* group, const char* name, const std::string& ros_param) {
U value;
ros::param::get(ros_param, value);
m_cfbc.setParam<T>(group, name, (T)value);
}
void updateParams(
const std::vector<std::string>& params)
{
for (const auto& p : params) {
std::string ros_param = "/allcfs/" + p;
size_t pos = p.find("/");
std::string g(p.begin(), p.begin() + pos);
std::string n(p.begin() + pos + 1, p.end());
// This assumes that we can find the variable in the TOC of the first
// CF to find the type (the actual update is done by name)
auto entry = m_cfs.front()->getParamTocEntry(g, n);
if (entry)
{
switch (entry->type) {
case Crazyflie::ParamTypeUint8:
updateParam<uint8_t, int>(g.c_str(), n.c_str(), ros_param);
break;
case Crazyflie::ParamTypeInt8:
updateParam<int8_t, int>(g.c_str(), n.c_str(), ros_param);
break;
case Crazyflie::ParamTypeUint16:
updateParam<uint16_t, int>(g.c_str(), n.c_str(), ros_param);
break;
case Crazyflie::ParamTypeInt16:
updateParam<int16_t, int>(g.c_str(), n.c_str(), ros_param);
break;
case Crazyflie::ParamTypeUint32:
updateParam<uint32_t, int>(g.c_str(), n.c_str(), ros_param);
break;
case Crazyflie::ParamTypeInt32:
updateParam<int32_t, int>(g.c_str(), n.c_str(), ros_param);
break;
case Crazyflie::ParamTypeFloat:
updateParam<float, float>(g.c_str(), n.c_str(), ros_param);
break;
}
}
else {
ROS_ERROR("Could not find param %s/%s", g.c_str(), n.c_str());
}
}
}
private:
bool publishRigidBody(const std::string& name, uint8_t id, std::vector<CrazyflieBroadcaster::externalPose> &states)
{
assert(m_pMocapRigidBodies);
const auto& iter = m_pMocapRigidBodies->find(name);
if (iter != m_pMocapRigidBodies->end()) {
const auto& rigidBody = iter->second;
states.resize(states.size() + 1);
states.back().id = id;
states.back().x = rigidBody.position().x();
states.back().y = rigidBody.position().y();
states.back().z = rigidBody.position().z();
states.back().qx = rigidBody.rotation().x();
states.back().qy = rigidBody.rotation().y();
states.back().qz = rigidBody.rotation().z();
states.back().qw = rigidBody.rotation().w();
tf::Transform transform;
transform.setOrigin(tf::Vector3(
states.back().x,
states.back().y,
states.back().z));
tf::Quaternion q(
states.back().qx,
states.back().qy,
states.back().qz,
states.back().qw);
transform.setRotation(q);
m_br.sendTransform(tf::StampedTransform(transform, ros::Time::now(), "world", name));
return true;
} else {
ROS_WARN("No updated pose for motion capture object %s", name.c_str());
}
return false;
}
void readObjects(
std::vector<libobjecttracker::Object>& objects,
int channel,
const std::vector<crazyswarm::LogBlock>& logBlocks)
{
// read CF config
struct CFConfig
{
std::string uri;
std::string tf_prefix;
std::string frame;
int idNumber;
std::string type;
};
ros::NodeHandle nGlobal;
XmlRpc::XmlRpcValue crazyflies;
nGlobal.getParam("crazyflies", crazyflies);
ROS_ASSERT(crazyflies.getType() == XmlRpc::XmlRpcValue::TypeArray);
objects.clear();
m_cfs.clear();
std::vector<CFConfig> cfConfigs;
for (int32_t i = 0; i < crazyflies.size(); ++i) {
ROS_ASSERT(crazyflies[i].getType() == XmlRpc::XmlRpcValue::TypeStruct);
XmlRpc::XmlRpcValue crazyflie = crazyflies[i];
int id = crazyflie["id"];
int ch = crazyflie["channel"];
std::string type = crazyflie["type"];
if (ch == channel) {
XmlRpc::XmlRpcValue pos = crazyflie["initialPosition"];
ROS_ASSERT(pos.getType() == XmlRpc::XmlRpcValue::TypeArray);
std::vector<double> posVec(3);
for (int32_t j = 0; j < pos.size(); ++j) {
switch (pos[j].getType()) {
case XmlRpc::XmlRpcValue::TypeDouble:
posVec[j] = static_cast<double>(pos[j]);
break;
case XmlRpc::XmlRpcValue::TypeInt:
posVec[j] = static_cast<int>(pos[j]);
break;
default:
std::stringstream message;
message << "crazyflies.yaml error:"
" entry " << j << " of initialPosition for cf" << id <<
" should be type int or double.";
throw std::runtime_error(message.str().c_str());
}
}
Eigen::Affine3f m;
m = Eigen::Translation3f(posVec[0], posVec[1], posVec[2]);
int markerConfigurationIdx;
nGlobal.getParam("crazyflieTypes/" + type + "/markerConfiguration", markerConfigurationIdx);
int dynamicsConfigurationIdx;
nGlobal.getParam("crazyflieTypes/" + type + "/dynamicsConfiguration", dynamicsConfigurationIdx);
std::string name = "cf" + std::to_string(id);
objects.push_back(libobjecttracker::Object(markerConfigurationIdx, dynamicsConfigurationIdx, m, name));
std::stringstream sstr;
sstr << std::setfill ('0') << std::setw(2) << std::hex << id;
std::string idHex = sstr.str();
std::string uri = "radio://" + std::to_string(m_radio) + "/" + std::to_string(channel) + "/2M/E7E7E7E7" + idHex;
std::string tf_prefix = "cf" + std::to_string(id);
std::string frame = "cf" + std::to_string(id);
cfConfigs.push_back({uri, tf_prefix, frame, id, type});
}
}
ROS_INFO("Parsed crazyflies.yaml successfully.");
// add Crazyflies
for (const auto& config : cfConfigs) {
addCrazyflie(config.uri, config.tf_prefix, config.frame, "/world", config.idNumber, config.type, logBlocks);
auto start = std::chrono::high_resolution_clock::now();
updateParams(m_cfs.back());
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed = end - start;
ROS_INFO("Update params: %f s", elapsed.count());
}
}
void addCrazyflie(
const std::string& uri,
const std::string& tf_prefix,
const std::string& frame,
const std::string& worldFrame,
int id,
const std::string& type,
const std::vector<crazyswarm::LogBlock>& logBlocks)
{
ROS_INFO("Adding CF: %s (%s, %s)...", tf_prefix.c_str(), uri.c_str(), frame.c_str());
auto start = std::chrono::high_resolution_clock::now();
CrazyflieROS* cf = new CrazyflieROS(
uri,
tf_prefix,
frame,
worldFrame,
id,
type,
logBlocks,
m_slowQueue);
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed = end - start;
ROS_INFO("CF ctor: %f s", elapsed.count());
cf->run(m_slowQueue);
auto end2 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed2 = end2 - end;
ROS_INFO("CF run: %f s", elapsed2.count());
m_cfs.push_back(cf);
}
void updateParams(
CrazyflieROS* cf)
{
ros::NodeHandle n("~");
ros::NodeHandle nGlobal;
// update parameters
// std::cout << "attempt: " << "firmwareParams/" + cf->type() << std::endl;
// char dummy;
// std::cin >> dummy;
// update global, type-specific, and CF-specific parameters
std::vector<XmlRpc::XmlRpcValue> firmwareParamsVec(2);
n.getParam("firmwareParams", firmwareParamsVec[0]);
nGlobal.getParam("crazyflieTypes/" + cf->type() + "/firmwareParams", firmwareParamsVec[1]);
XmlRpc::XmlRpcValue crazyflies;
nGlobal.getParam("crazyflies", crazyflies);
ROS_ASSERT(crazyflies.getType() == XmlRpc::XmlRpcValue::TypeArray);
for (int32_t i = 0; i < crazyflies.size(); ++i) {
ROS_ASSERT(crazyflies[i].getType() == XmlRpc::XmlRpcValue::TypeStruct);
XmlRpc::XmlRpcValue crazyflie = crazyflies[i];
int id = crazyflie["id"];
if (id == cf->id()) {
if (crazyflie.hasMember("firmwareParams")) {
firmwareParamsVec.push_back(crazyflie["firmwareParams"]);
}
break;
}
}
crazyswarm::UpdateParams::Request request;
crazyswarm::UpdateParams::Response response;
for (auto& firmwareParams : firmwareParamsVec) {
// ROS_ASSERT(firmwareParams.getType() == XmlRpc::XmlRpcValue::TypeArray);
auto iter = firmwareParams.begin();
for (; iter != firmwareParams.end(); ++iter) {
std::string group = iter->first;
XmlRpc::XmlRpcValue v = iter->second;
auto iter2 = v.begin();
for (; iter2 != v.end(); ++iter2) {
std::string param = iter2->first;
XmlRpc::XmlRpcValue value = iter2->second;
if (value.getType() == XmlRpc::XmlRpcValue::TypeBoolean) {
bool b = value;
nGlobal.setParam(cf->frame() + "/" + group + "/" + param, b);
std::cout << "update " << group + "/" + param << " to " << b << std::endl;
} else if (value.getType() == XmlRpc::XmlRpcValue::TypeInt) {
int b = value;
nGlobal.setParam(cf->frame() + "/" + group + "/" + param, b);
std::cout << "update " << group + "/" + param << " to " << b << std::endl;
} else if (value.getType() == XmlRpc::XmlRpcValue::TypeDouble) {
double b = value;
nGlobal.setParam(cf->frame() + "/" + group + "/" + param, b);
std::cout << "update " << group + "/" + param << " to " << b << std::endl;
} else if (value.getType() == XmlRpc::XmlRpcValue::TypeString) {
// "1e-5" is not recognize as double; convert manually here
std::string value_str = value;
double value = std::stod(value_str);
nGlobal.setParam(cf->frame() + "/" + group + "/" + param, value);
std::cout << "update " << group + "/" + param << " to " << value << std::endl;
} else {
ROS_ERROR("No known type for %s.%s! (type: %d)", group.c_str(), param.c_str(), value.getType());
}
request.params.push_back(group + "/" + param);
}
}
}
cf->updateParams(request, response);
}
private:
std::vector<CrazyflieROS*> m_cfs;
std::string m_interactiveObject;
libobjecttracker::ObjectTracker* m_tracker; // non-owning pointer
int m_radio;
pcl::PointCloud<pcl::PointXYZ>::Ptr m_pMarkers;
std::map<std::string, libmotioncapture::RigidBody>* m_pMocapRigidBodies; // non-owning pointer
ros::CallbackQueue m_slowQueue;
CrazyflieBroadcaster m_cfbc;
bool m_isEmergency;
bool m_useMotionCaptureObjectTracking;
tf::TransformBroadcaster m_br;
latency m_latency;
bool m_sendPositionOnly;
std::vector<std::unique_ptr<std::ofstream>> m_outputCSVs;
int m_phase;
std::chrono::high_resolution_clock::time_point m_phaseStart;
};
// handles all Crazyflies
class CrazyflieServer
{
public:
CrazyflieServer()
: m_isEmergency(false)
, m_serviceEmergency()
, m_serviceStartTrajectory()
, m_serviceTakeoff()
, m_serviceLand()
, m_serviceGoTo()
, m_lastInteractiveObjectPosition(-10, -10, 1)
, m_broadcastingNumRepeats(15)
, m_broadcastingDelayBetweenRepeatsMs(1)
{
ros::NodeHandle nh;
nh.setCallbackQueue(&m_queue);
m_serviceEmergency = nh.advertiseService("emergency", &CrazyflieServer::emergency, this);
m_serviceStartTrajectory = nh.advertiseService("start_trajectory", &CrazyflieServer::startTrajectory, this);
m_serviceTakeoff = nh.advertiseService("takeoff", &CrazyflieServer::takeoff, this);
m_serviceLand = nh.advertiseService("land", &CrazyflieServer::land, this);
m_serviceGoTo = nh.advertiseService("go_to", &CrazyflieServer::goTo, this);
m_serviceUpdateParams = nh.advertiseService("update_params", &CrazyflieServer::updateParams, this);
m_pubPointCloud = nh.advertise<sensor_msgs::PointCloud>("pointCloud", 1);
m_subscribeVirtualInteractiveObject = nh.subscribe("virtual_interactive_object", 1, &CrazyflieServer::virtualInteractiveObjectCallback, this);
}
~CrazyflieServer()
{
for (CrazyflieGroup* group : m_groups) {
delete group;
}
}
void virtualInteractiveObjectCallback(const geometry_msgs::PoseStamped::ConstPtr& msg)
{
m_lastInteractiveObjectPosition = Eigen::Vector3f(
msg->pose.position.x,
msg->pose.position.y,
msg->pose.position.z);
}
void run()
{
std::thread tSlow(&CrazyflieServer::runSlow, this);
runFast();
tSlow.join();
}
void runFast()
{
// std::vector<CrazyflieBroadcaster::externalPose> states(1);
// states.back().id = 07;
// states.back().q0 = 0;
// states.back().q1 = 0;
// states.back().q2 = 0;
// states.back().q3 = 1;
// while(ros::ok()) {
// m_cfbc.sendPositionExternalBringup(states);
// // m_cfs[0]->sendPositionExternalBringup(states[0]);
// m_fastQueue.callAvailable(ros::WallDuration(0));
// std::this_thread::sleep_for(std::chrono::milliseconds(10));
// }
// return;
std::vector<libobjecttracker::DynamicsConfiguration> dynamicsConfigurations;
std::vector<libobjecttracker::MarkerConfiguration> markerConfigurations;
std::set<int> channels;
readMarkerConfigurations(markerConfigurations);
readDynamicsConfigurations(dynamicsConfigurations);
readChannels(channels);
bool useMotionCaptureObjectTracking;
std::string logFilePath;
std::string interactiveObject;
bool printLatency;
bool writeCSVs;
bool sendPositionOnly;
std::string motionCaptureType;
ros::NodeHandle nl("~");
std::string objectTrackingType;
nl.getParam("object_tracking_type", objectTrackingType);
useMotionCaptureObjectTracking = (objectTrackingType == "motionCapture");
nl.param<std::string>("save_point_clouds", logFilePath, "");
nl.param<std::string>("interactive_object", interactiveObject, "");
nl.getParam("print_latency", printLatency);
nl.getParam("write_csvs", writeCSVs);
nl.param<std::string>("motion_capture_type", motionCaptureType, "vicon");
nl.param<int>("broadcasting_num_repeats", m_broadcastingNumRepeats, 15);
nl.param<int>("broadcasting_delay_between_repeats_ms", m_broadcastingDelayBetweenRepeatsMs, 1);
nl.param<bool>("send_position_only", sendPositionOnly, false);
// tilde-expansion
wordexp_t wordexp_result;
if (wordexp(logFilePath.c_str(), &wordexp_result, 0) == 0) {
// success - only read first result, could be more if globs were used
logFilePath = wordexp_result.we_wordv[0];
}
wordfree(&wordexp_result);
libobjecttracker::PointCloudLogger pointCloudLogger(logFilePath);
const bool logClouds = !logFilePath.empty();
// custom log blocks
std::vector<std::string> genericLogTopics;
nl.param("genericLogTopics", genericLogTopics, std::vector<std::string>());
std::vector<int> genericLogTopicFrequencies;
nl.param("genericLogTopicFrequencies", genericLogTopicFrequencies, std::vector<int>());
std::vector<crazyswarm::LogBlock> logBlocks;
if (genericLogTopics.size() == genericLogTopicFrequencies.size())
{
size_t i = 0;
for (auto& topic : genericLogTopics)
{
crazyswarm::LogBlock logBlock;
logBlock.topic_name = topic;
logBlock.frequency = genericLogTopicFrequencies[i];
nl.getParam("genericLogTopic_" + topic + "_Variables", logBlock.variables);
logBlocks.push_back(logBlock);
++i;
}
}
else
{
ROS_ERROR("Cardinality of genericLogTopics and genericLogTopicFrequencies does not match!");
}
// Make a new client
std::map<std::string, std::string> cfg;
std::string hostname;
nl.getParam("motion_capture_host_name", hostname);
cfg["hostname"] = hostname;
if (nl.hasParam("motion_capture_interface_ip")) {
std::string interface_ip;
nl.param<std::string>("motion_capture_interface_ip", interface_ip);
cfg["interface_ip"] = interface_ip;
}
std::unique_ptr<libmotioncapture::MotionCapture> mocap;
if (motionCaptureType != "none") {
ROS_INFO(
"libmotioncapture connecting to %s at hostname '%s' - "
"might block indefinitely if unreachable!",
motionCaptureType.c_str(),
hostname.c_str()
);
mocap.reset(libmotioncapture::MotionCapture::connect(motionCaptureType, cfg));
if (!mocap) {
throw std::runtime_error("Unknown motion capture type!");
}
}
pcl::PointCloud<pcl::PointXYZ>::Ptr markers(new pcl::PointCloud<pcl::PointXYZ>);
std::map<std::string, libmotioncapture::RigidBody> mocapRigidBodies;
// Create all groups in parallel and launch threads
{
std::vector<std::future<CrazyflieGroup*> > handles;
int r = 0;
std::cout << "ch: " << channels.size() << std::endl;
for (int channel : channels) {
auto handle = std::async(std::launch::async,
[&](int channel, int radio)
{
// std::cout << "radio: " << radio << std::endl;
return new CrazyflieGroup(
dynamicsConfigurations,
markerConfigurations,
// &client,
markers,
&mocapRigidBodies,
radio,
channel,
useMotionCaptureObjectTracking,
logBlocks,
interactiveObject,
writeCSVs,
sendPositionOnly);
},
channel,
r
);
handles.push_back(std::move(handle));
++r;
}
for (auto& handle : handles) {
m_groups.push_back(handle.get());
}
}
// start the groups threads
std::vector<std::thread> threads;
for (auto& group : m_groups) {
threads.push_back(std::thread(&CrazyflieGroup::runSlow, group));
}
ROS_INFO("Started %lu threads", threads.size());
// Connect to a server
// ROS_INFO("Connecting to %s ...", hostName.c_str());
// while (ros::ok() && !client.IsConnected().Connected) {
// // Direct connection
// bool ok = (client.Connect(hostName).Result == Result::Success);
// if(!ok) {
// ROS_WARN("Connect failed...");
// }
// ros::spinOnce();
// }
if (mocap) {
// setup messages
sensor_msgs::PointCloud msgPointCloud;
msgPointCloud.header.seq = 0;
msgPointCloud.header.frame_id = "world";
auto startTime = std::chrono::high_resolution_clock::now();
struct latencyEntry {
std::string name;
double secs;
};
std::vector<latencyEntry> latencies;
std::vector<double> latencyTotal(6 + 3 * 2, 0.0);
uint32_t latencyCount = 0;
while (ros::ok() && !m_isEmergency) {
// Get a frame
mocap->waitForNextFrame();
latencies.clear();
auto startIteration = std::chrono::high_resolution_clock::now();
double totalLatency = 0;
// Get the latency
const auto& mocapLatency = mocap->latency();
float totalMocapLatency = 0;
for (const auto& item : mocapLatency) {
totalMocapLatency += item.value();
}
if (totalMocapLatency > 0.035) {
std::stringstream sstr;
sstr << "MoCap Latency high: " << totalMocapLatency << " s." << std::endl;
for (const auto& item : mocapLatency) {
sstr << " Latency: " << item.name() << ": " << item.value() << " s." << std::endl;
}
ROS_WARN("%s", sstr.str().c_str());
}
if (printLatency) {
size_t i = 0;
for (const auto& item : mocapLatency) {
latencies.push_back({item.name(), item.value()});
latencyTotal[i] += item.value();
totalLatency += item.value();
latencyTotal.back() += item.value();
}
++i;
}
// size_t latencyCount = client.GetLatencySampleCount().Count;
// for(size_t i = 0; i < latencyCount; ++i) {
// std::string sampleName = client.GetLatencySampleName(i).Name;
// double sampleValue = client.GetLatencySampleValue(sampleName).Value;
// ROS_INFO("Latency: %s: %f", sampleName.c_str(), sampleValue);
// }
// Get the unlabeled markers and create point cloud
if (!useMotionCaptureObjectTracking) {
// ToDO: If we switch our datastructure to pointcloud2 (here, for the ROS publisher, and libobjecttracker)
// we can avoid a copy here.
const auto& pointcloud = mocap->pointCloud();
markers->clear();
for (size_t i = 0; i < pointcloud.rows(); ++i) {
const auto &point = pointcloud.row(i);
markers->push_back(pcl::PointXYZ(point(0), point(1), point(2)));
}
msgPointCloud.header.seq += 1;
msgPointCloud.header.stamp = ros::Time::now();
msgPointCloud.points.resize(markers->size());
for (size_t i = 0; i < markers->size(); ++i) {
const pcl::PointXYZ& point = markers->at(i);
msgPointCloud.points[i].x = point.x;
msgPointCloud.points[i].y = point.y;
msgPointCloud.points[i].z = point.z;
}
m_pubPointCloud.publish(msgPointCloud);
if (logClouds) {
pointCloudLogger.log(markers);
}
}
if (useMotionCaptureObjectTracking || !interactiveObject.empty()) {
// get mocap rigid bodies
mocapRigidBodies = mocap->rigidBodies();
if (interactiveObject == "virtual") {
Eigen::Quaternionf quat(0, 0, 0, 1);
mocapRigidBodies.emplace(interactiveObject,
libmotioncapture::RigidBody(
interactiveObject,
m_lastInteractiveObjectPosition,
quat));
}
}
auto startRunGroups = std::chrono::high_resolution_clock::now();
std::vector<std::future<void> > handles;
for (auto group : m_groups) {
auto handle = std::async(std::launch::async, &CrazyflieGroup::runFast, group);
handles.push_back(std::move(handle));
}
for (auto& handle : handles) {
handle.wait();
}
auto endRunGroups = std::chrono::high_resolution_clock::now();
if (printLatency) {
std::chrono::duration<double> elapsedRunGroups = endRunGroups - startRunGroups;
latencies.push_back({"Run All Groups", elapsedRunGroups.count()});
latencyTotal[4] += elapsedRunGroups.count();
totalLatency += elapsedRunGroups.count();
latencyTotal.back() += elapsedRunGroups.count();
int groupId = 0;
for (auto group : m_groups) {
auto latency = group->lastLatency();
int radio = group->radio();
latencies.push_back({"Group " + std::to_string(radio) + " objectTracking", latency.objectTracking});
latencies.push_back({"Group " + std::to_string(radio) + " broadcasting", latency.broadcasting});
latencyTotal[5 + 2*groupId] += latency.objectTracking;
latencyTotal[6 + 2*groupId] += latency.broadcasting;
++groupId;
}
}
auto endIteration = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed = endIteration - startIteration;
double elapsedSeconds = elapsed.count();
if (elapsedSeconds > 0.009) {
ROS_WARN("Latency too high! Is %f s.", elapsedSeconds);
}
if (printLatency) {
++latencyCount;
std::cout << "Latencies" << std::endl;
for (auto& latency : latencies) {
std::cout << latency.name << ": " << latency.secs * 1000 << " ms" << std::endl;
}
std::cout << "Total " << totalLatency * 1000 << " ms" << std::endl;
// // if (latencyCount % 100 == 0) {
std::cout << "Avg " << latencyCount << std::endl;
for (size_t i = 0; i < latencyTotal.size(); ++i) {
std::cout << latencyTotal[i] / latencyCount * 1000.0 << ",";
}
std::cout << std::endl;
// // }
}
// ROS_INFO("Latency: %f s", elapsedSeconds.count());
// m_fastQueue.callAvailable(ros::WallDuration(0));
}
if (logClouds) {
pointCloudLogger.flush();
}
}
// wait for other threads
for (auto& thread : threads) {
thread.join();
}
}
void runSlow()
{
while(ros::ok() && !m_isEmergency) {
m_queue.callAvailable(ros::WallDuration(0));
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
private:
bool emergency(
std_srvs::Empty::Request& req,
std_srvs::Empty::Response& res)
{
ROS_FATAL("Emergency requested!");
for (size_t i = 0; i < m_broadcastingNumRepeats; ++i) {
for (auto& group : m_groups) {
group->emergency();
}
std::this_thread::sleep_for(std::chrono::milliseconds(m_broadcastingDelayBetweenRepeatsMs));
}
m_isEmergency = true;
return true;
}
bool takeoff(
crazyswarm::Takeoff::Request& req,
crazyswarm::Takeoff::Response& res)
{
ROS_INFO("Takeoff!");
for (size_t i = 0; i < m_broadcastingNumRepeats; ++i) {
for (auto& group : m_groups) {
group->takeoff(req.height, req.duration.toSec(), req.groupMask);
}
std::this_thread::sleep_for(std::chrono::milliseconds(m_broadcastingDelayBetweenRepeatsMs));
}
return true;
}
bool land(
crazyswarm::Land::Request& req,
crazyswarm::Land::Response& res)
{
ROS_INFO("Land!");
for (size_t i = 0; i < m_broadcastingNumRepeats; ++i) {
for (auto& group : m_groups) {
group->land(req.height, req.duration.toSec(), req.groupMask);
}
std::this_thread::sleep_for(std::chrono::milliseconds(m_broadcastingDelayBetweenRepeatsMs));
}
return true;
}
bool goTo(
crazyswarm::GoTo::Request& req,
crazyswarm::GoTo::Response& res)
{
ROS_INFO("GoTo!");
for (size_t i = 0; i < m_broadcastingNumRepeats; ++i) {
for (auto& group : m_groups) {
group->goTo(req.goal.x, req.goal.y, req.goal.z, req.yaw, req.duration.toSec(), req.groupMask);
}
std::this_thread::sleep_for(std::chrono::milliseconds(m_broadcastingDelayBetweenRepeatsMs));
}
return true;
}
bool startTrajectory(
crazyswarm::StartTrajectory::Request& req,
crazyswarm::StartTrajectory::Response& res)
{
ROS_INFO("Start trajectory!");
for (size_t i = 0; i < m_broadcastingNumRepeats; ++i) {
for (auto& group : m_groups) {
group->startTrajectory(req.trajectoryId, req.timescale, req.reversed, req.groupMask);
}
std::this_thread::sleep_for(std::chrono::milliseconds(m_broadcastingDelayBetweenRepeatsMs));
}
return true;
}
bool updateParams(
crazyswarm::UpdateParams::Request& req,
crazyswarm::UpdateParams::Response& res)
{
ROS_INFO("UpdateParams!");
for (size_t i = 0; i < m_broadcastingNumRepeats; ++i) {
for (auto& group : m_groups) {
group->updateParams(req.params);
}
std::this_thread::sleep_for(std::chrono::milliseconds(m_broadcastingDelayBetweenRepeatsMs));
}
return true;
}
//
void readMarkerConfigurations(
std::vector<libobjecttracker::MarkerConfiguration>& markerConfigurations)
{
markerConfigurations.clear();
ros::NodeHandle nGlobal;
int numConfigurations;
nGlobal.getParam("numMarkerConfigurations", numConfigurations);
for (int i = 0; i < numConfigurations; ++i) {
markerConfigurations.push_back(pcl::PointCloud<pcl::PointXYZ>::Ptr(new pcl::PointCloud<pcl::PointXYZ>));
std::stringstream sstr;
sstr << "markerConfigurations/" << i << "/numPoints";
int numPoints;
nGlobal.getParam(sstr.str(), numPoints);
std::vector<double> offset;
std::stringstream sstr2;
sstr2 << "markerConfigurations/" << i << "/offset";
nGlobal.getParam(sstr2.str(), offset);
for (int j = 0; j < numPoints; ++j) {
std::stringstream sstr3;
sstr3 << "markerConfigurations/" << i << "/points/" << j;
std::vector<double> points;
nGlobal.getParam(sstr3.str(), points);
markerConfigurations.back()->push_back(pcl::PointXYZ(points[0] + offset[0], points[1] + offset[1], points[2] + offset[2]));
}
}
}
void readDynamicsConfigurations(
std::vector<libobjecttracker::DynamicsConfiguration>& dynamicsConfigurations)
{
ros::NodeHandle nGlobal;
int numConfigurations;
nGlobal.getParam("numDynamicsConfigurations", numConfigurations);
dynamicsConfigurations.resize(numConfigurations);
for (int i = 0; i < numConfigurations; ++i) {
std::stringstream sstr;
sstr << "dynamicsConfigurations/" << i;
nGlobal.getParam(sstr.str() + "/maxXVelocity", dynamicsConfigurations[i].maxXVelocity);
nGlobal.getParam(sstr.str() + "/maxYVelocity", dynamicsConfigurations[i].maxYVelocity);
nGlobal.getParam(sstr.str() + "/maxZVelocity", dynamicsConfigurations[i].maxZVelocity);
nGlobal.getParam(sstr.str() + "/maxPitchRate", dynamicsConfigurations[i].maxPitchRate);
nGlobal.getParam(sstr.str() + "/maxRollRate", dynamicsConfigurations[i].maxRollRate);
nGlobal.getParam(sstr.str() + "/maxYawRate", dynamicsConfigurations[i].maxYawRate);
nGlobal.getParam(sstr.str() + "/maxRoll", dynamicsConfigurations[i].maxRoll);
nGlobal.getParam(sstr.str() + "/maxPitch", dynamicsConfigurations[i].maxPitch);
nGlobal.getParam(sstr.str() + "/maxFitnessScore", dynamicsConfigurations[i].maxFitnessScore);
}
}
void readChannels(
std::set<int>& channels)
{
// read CF config
ros::NodeHandle nGlobal;
XmlRpc::XmlRpcValue crazyflies;
nGlobal.getParam("crazyflies", crazyflies);
ROS_ASSERT(crazyflies.getType() == XmlRpc::XmlRpcValue::TypeArray);
channels.clear();
for (int32_t i = 0; i < crazyflies.size(); ++i) {
ROS_ASSERT(crazyflies[i].getType() == XmlRpc::XmlRpcValue::TypeStruct);
XmlRpc::XmlRpcValue crazyflie = crazyflies[i];
int channel = crazyflie["channel"];
channels.insert(channel);
}
}
private:
std::string m_worldFrame;
bool m_isEmergency;
ros::ServiceServer m_serviceEmergency;
ros::ServiceServer m_serviceStartTrajectory;
ros::ServiceServer m_serviceTakeoff;
ros::ServiceServer m_serviceLand;
ros::ServiceServer m_serviceGoTo;
ros::ServiceServer m_serviceUpdateParams;
ros::Publisher m_pubPointCloud;
// tf::TransformBroadcaster m_br;
std::vector<CrazyflieGroup*> m_groups;
ros::Subscriber m_subscribeVirtualInteractiveObject;
Eigen::Vector3f m_lastInteractiveObjectPosition;
int m_broadcastingNumRepeats;
int m_broadcastingDelayBetweenRepeatsMs;
private:
// We have two callback queues
// 1. Fast queue handles pose and emergency callbacks. Those are high-priority and can be served quickly
// 2. Slow queue handles all other requests.
// Each queue is handled in its own thread. We don't want a thread per CF to make sure that the fast queue
// gets called frequently enough.
ros::CallbackQueue m_queue;
// ros::CallbackQueue m_slowQueue;
};
int main(int argc, char **argv)
{
// raise(SIGSTOP);
ros::init(argc, argv, "crazyflie_server");
// ros::NodeHandle n("~");
// std::string worldFrame;
// n.param<std::string>("world_frame", worldFrame, "/world");
// std::string broadcastUri;
// n.getParam("broadcast_uri", broadcastUri);
CrazyflieServer server;//(broadcastUri, worldFrame);
// read CF config
ros::NodeHandle nGlobal;
XmlRpc::XmlRpcValue crazyflies;
nGlobal.getParam("crazyflies", crazyflies);
ROS_ASSERT(crazyflies.getType() == XmlRpc::XmlRpcValue::TypeArray);
std::set<int> cfIds;
for (int32_t i = 0; i < crazyflies.size(); ++i)
{
ROS_ASSERT(crazyflies[i].getType() == XmlRpc::XmlRpcValue::TypeStruct);
XmlRpc::XmlRpcValue crazyflie = crazyflies[i];
int id = crazyflie["id"];
int channel = crazyflie["channel"];
if (cfIds.find(id) != cfIds.end()) {
ROS_FATAL("CF with the same id twice in configuration!");
return 1;
}
cfIds.insert(id);
}
// ROS_INFO("All CFs are ready!");
server.run();
return 0;
}
|
bb8938847932527e1704952d6237dcf10c8503ba
|
f205fba722320ab8eb334c758fef5008ba92c4c9
|
/LCD_display/LCD_display.ino
|
6a89da2637c3413054dbacbdac75f3f34a575ac7
|
[] |
no_license
|
rumanmunir/Smart-Home-Safety-and-Security-Coding
|
5854f5b4ba703085e83f89825affa8dea5482cdf
|
cde90875aa330d2daecf5e46d47ecb2cddc7a8f1
|
refs/heads/master
| 2021-01-05T20:14:18.704840
| 2020-04-28T05:11:34
| 2020-04-28T05:11:34
| 241,125,954
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,263
|
ino
|
LCD_display.ino
|
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27,20,4); // set the LCD address to 0x27 for a 16 chars and 2 line display
void setup()
{
lcd.init(); // initialize the lcd
lcd.init();
// Print a message to the LCD.
lcd.backlight();
lcd.setCursor(0,0);
lcd.print("Capstone1");
lcd.setCursor(0,1);
lcd.print("SMART HOME");
lcd.setCursor(0,2);
lcd.print("Security & Safet ");
lcd.setCursor(0,3);
lcd.print("y System ");
}
void loop()
{
void welcomeScreen()
{
lcd.begin(20,4);
lcd.print(F("Welcome to GSM"));
lcd.setCursor(5,1);
delay(1000);
lcd.print(F("Security System"));
delay(2000);
}
void registerScreen()
{
lcd.clear();
lcd.print(F("Register Yourself!!"));
lcd.setCursor(0,1);
lcd.print(F("Please Enter Working"));
lcd.setCursor(0,2);
lcd.print(F("Cell Phone Number."));
respondOk();
}
void numberScreen(){
lcd.clear();
lcd.setCursor(0,0);
lcd.print("Enter Mobile NO:");
// Serial.print("Mobile:");
lcd.setCursor(0,2);
lcd.print("*-Clear Screen");
lcd.setCursor(0,3);
lcd.print("#-Continue");
lcd.setCursor(0,1);
}
void verificationCodeScreen()
{
lcd.clear();
lcd.print(F("A Verification Code"));
lcd.setCursor(0,1);
lcd.print(F("Has been sent to the"));
lcd.setCursor(0,2);
lcd.print(F("given phone Number."));
respondOk();
lcd.clear();
lcd.print(F("Please Input Correct"));
lcd.setCursor(0,1);
lcd.print(F("Verification code to"));
lcd.setCursor(0,2);
lcd.print(F("Save Given Phone NUM"));
respondOk();
}
void mainMenuScreen()
{
lcd.clear();
lcd.print(F("A-Change Mobile"));
lcd.setCursor(0,1);
lcd.print(F("B-Change Pin"));
lcd.setCursor(0,2);
lcd.print(F("C-Neighbours"));
lcd.setCursor(14,3);
lcd.print(F("#-Back"));
}
void deleteSlotEmpty()
{
lcd.clear();
lcd.print(F("This slot is already"));
lcd.setCursor(0,1);
lcd.print(F("Empty.Please Select"));
lcd.setCursor(0,2);
lcd.print(F("Another Slot"));
respondOk();
}
void slotdeleteMsg()
{
lcd.clear();
lcd.print(F("Are you sure?"));
lcd.setCursor(0,1);
lcd.print(F("You want to delete"));
lcd.setCursor(0,2);
lcd.print(F("Slot"));
}
void slotDeleted()
{
lcd.clear();
lcd.print(F("Selected Slot is"));
lcd.setCursor(0,1);
lcd.print(F("successfully deleted"));
respondOk();
}
}
|
b76f70bc0b14a76fbc0b86d82ec1196e320ba0ee
|
3b2211fd79750064689fe09413cbe28be8d7adcd
|
/src/hybrid.cpp
|
22ccae18509a2bf82d7bb54b3235b87d49b46ec3
|
[] |
no_license
|
star2sea/hybrid-python-c
|
a5320c7c25033601dfe6d0607a3778d32c30c7ed
|
8b4eb50af6eeb63dbb30d85e4feb773f3e192508
|
refs/heads/master
| 2020-07-01T11:47:42.864137
| 2019-08-14T01:47:44
| 2019-08-14T01:47:44
| 201,166,112
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,018
|
cpp
|
hybrid.cpp
|
#include "boost/python.hpp"
#include <string>
#include <set>
extern void init_utils();
#define BOOST_PYTHON_STATIC_LIB
using namespace std;
set<string> key_names = { "key_a", "key_b", "key_c" };
namespace bp = boost::python;
/////////////////////////// boost python /////////////////////////////////
void say_hello()
{
printf("hello world\n");
}
enum NumberType
{
First = 1,
Second,
Third,
};
class HybridTest
{
public:
HybridTest(int t1, int t2) : t1_(t1), t2_(t2) {}
void test() { printf("HybridTest: %d + %d = %d\n", t1_, t2_, t1_ + t2_); }
private:
int t1_;
int t2_;
};
BOOST_PYTHON_MODULE(hybrid)
{
init_utils();
for (const string &name : key_names)
{
bp::scope().attr(name.c_str()) = name;
}
bp::def("say_hello", say_hello);
bp::enum_<NumberType>("number_type")
.value("first", NumberType::First)
.value("second", NumberType::Second)
.value("third", NumberType::Third)
;
bp::class_<HybridTest>("HybridTest", bp::init<int, int>())
.def("test", &HybridTest::test)
;
}
|
94c94c1cb29614dd3c631f187d3c27770eff0e48
|
59f1be4e21a738a2f83a3231c0772718250cd22b
|
/GraphicEngine/Game.h
|
703ad1ce375bb06eb2932819c3c702ba7356aa74
|
[] |
no_license
|
Sharundaar/OpenGLSDL
|
c65407e6ad1c42dd28e0583ea53e2d18f2069b20
|
45b3de9788f348d012911bc16eeba3e443ed04c9
|
refs/heads/master
| 2016-09-06T21:53:15.737279
| 2015-05-22T09:28:52
| 2015-05-22T09:28:52
| 32,596,262
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,379
|
h
|
Game.h
|
#pragma once
#include "GameEngine.h"
#include "Scene.h"
#include "Shader.h"
#include "InputManager.h"
#include "GraphicEngine.h"
#include "Camera.h"
#include "Cube.h"
#include "Plane.h"
#include "ParticleSystem.h"
#include "AtmosphericParticleSystem.h"
#include "FireParticle.h"
#include "SDLEventManager.h"
#include "SDLInputManager.h"
#include "OBJImporter.h"
class QuitEventHandler : public SDLEventHandler
{
public:
QuitEventHandler() { m_quit = false; mask.push_back(SDL_QUIT); }
~QuitEventHandler() { }
void externQuit() { m_quit = true; }
void handleEvent(SDL_Event& _event) {
m_quit = true;
}
std::vector<SDL_EventType>& getMasks()
{
return mask;
}
public:
std::vector<SDL_EventType> mask;
bool m_quit;
};
class Game : public GameEngine
{
public:
Game();
virtual ~Game();
protected:
virtual void initialize();
virtual void loadContent();
virtual void update(float _dt);
virtual void draw(float _dt);
virtual void unloadContent();
private:
Scene m_scene;
Shader m_shader;
GraphicEngine m_graphics;
Camera* m_mainCamera;
SceneNode* m_importedObjectNode;
Object3D* m_importedObject;
SceneNode* m_cubeNode;
Cube* m_cube;
QuitEventHandler* m_quitEventHandler = new QuitEventHandler();
SDL_Window* m_window;
ParticleSystem m_particleSystem;
AtmosphericParticleSystem m_atmosphericParticle;
FireParticle m_fireParticle;
};
|
150dbf21c086f3adbe46befd6e8e284c78b81c7f
|
f0eeb6724147908e6903a07cd524472938d5cdba
|
/Baekjoon/1013_Contact.cpp
|
d6d7ebd64412549e31523ad9965ffe1fe5eacfe5
|
[] |
no_license
|
paperfrog1228/Algorithm
|
bb338e51169d2b9257116f8e9c23afc147e65e27
|
14b0da325f317d36537a1254bc178bed32337829
|
refs/heads/master
| 2022-09-22T23:58:28.824408
| 2022-09-09T07:01:41
| 2022-09-09T07:01:41
| 152,889,184
| 3
| 0
| null | 2019-03-24T14:49:13
| 2018-10-13T16:04:45
|
C++
|
UTF-8
|
C++
| false
| false
| 289
|
cpp
|
1013_Contact.cpp
|
#include<iostream>
#include<string>
#include<regex>
using namespace std;
int n;
string s;
int main() {
cin>>n;
regex r("(100+1+|01)+");
while(n--){
cin>>s;
if(regex_match(s,r))
cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
return 0;
}
|
2395f8b78c25eb72a84250c3f13b8761782c2601
|
dae3ee55252774b75041d841f962bbad5595253b
|
/code/core/src/parser2/detail/parser.cpp
|
c9fac349999f47fc2620bf941c3469edfff04841
|
[] |
no_license
|
alcides/insieme
|
a6268728f896d5433b0e9420d8f621fcf227b276
|
500d58a0ba9649da18ad0e4b36b6e94b7e98d9ae
|
refs/heads/master
| 2021-01-17T08:37:16.117572
| 2014-09-06T11:30:30
| 2014-09-06T11:30:44
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 39,268
|
cpp
|
parser.cpp
|
/**
* Copyright (c) 2002-2013 Distributed and Parallel Systems Group,
* Institute of Computer Science,
* University of Innsbruck, Austria
*
* This file is part of the INSIEME Compiler and Runtime System.
*
* We provide the software of this file (below described as "INSIEME")
* under GPL Version 3.0 on an AS IS basis, and do not warrant its
* validity or performance. We reserve the right to update, modify,
* or discontinue this software at any time. We shall have no
* obligation to supply such updates or modifications or any other
* form of support to you.
*
* If you require different license terms for your intended use of the
* software, e.g. for proprietary commercial or industrial use, please
* contact us at:
* insieme@dps.uibk.ac.at
*
* We kindly ask you to acknowledge the use of this software in any
* publication or other disclosure of results by referring to the
* following citation:
*
* H. Jordan, P. Thoman, J. Durillo, S. Pellegrini, P. Gschwandtner,
* T. Fahringer, H. Moritsch. A Multi-Objective Auto-Tuning Framework
* for Parallel Codes, in Proc. of the Intl. Conference for High
* Performance Computing, Networking, Storage and Analysis (SC 2012),
* IEEE Computer Society Press, Nov. 2012, Salt Lake City, USA.
*
* All copyright notices must be kept intact.
*
* INSIEME depends on several third party software packages. Please
* refer to http://www.dps.uibk.ac.at/insieme/license.html for details
* regarding third party software licenses.
*/
#include "insieme/core/parser2/detail/parser.h"
#include <sstream>
#include <iterator>
#include <boost/tokenizer.hpp>
namespace insieme {
namespace core {
namespace parser {
namespace detail {
namespace {
Result fail(Context& context, const TokenIter& begin, const TokenIter& end) throw(ParseException) {
if (!context.isSpeculative())
throw ParseException(begin, end);
return false;
}
string buildErrorMessage(const TokenIter& begin, const TokenIter& end) {
std::stringstream out;
out << "Unable to parse token sequence \""
<< join(" ", begin, end, [](std::ostream& out, const Token& cur) { out << cur.getLexeme(); }) << "\"";
return out.str();
}
}
ParseException::ParseException(const TokenIter& begin, const TokenIter& end)
: msg(buildErrorMessage(begin, end)){}
// -- Term Implementations -------------
Result Term::match(Context& context, const TokenIter& begin, const TokenIter& end) const {
// setting this flag will print a lot of debug messages
// TODO: find a better way to use this flag
const bool DEBUG = false;
if (!DEBUG) {
// -- non-debug version --
if (!range_limit.covers(begin,end)) {
return fail(context, begin, end);
}
return matchInternal(context, begin, end);
} else {
// -- debug version --
// print debug infos
auto offset = times(" ", context.getLevel());
std::cout << offset << "Try matching " << *this << " against " << join(" ", begin, end) << " - speculation: " << ((context.isSpeculative())?"On":"Off") << "\n";
try {
// check constraints on number of tokens
if (!range_limit.covers(begin,end)) {
std::cout << offset << "Match skipped => range limit\n";
return fail(context, begin, end);
}
assert(begin <= end);
context.incLevel();
auto res = matchInternal(context, begin, end);
context.decLevel();
// debug infos ...
std::cout << offset << "Match result: " << ((res)?"OK":"Failed") << " - context: " << context.getTerms() << "\n";
return res;
} catch (const ParseException& pe) {
std::cout << offset << "Failed with error: " << pe.what() << "\n";
throw pe;
}
return false; // just to get rid of warnings
}
}
Result NonTerminal::matchInternal(Context& context, const TokenIter& begin, const TokenIter& end) const {
NodePtr res = context.grammar.match(context, begin, end, nonTerminal);
if (!res) return fail(context,begin,end);
context.push(res);
return res;
}
namespace {
template<typename C>
utils::range<typename C::const_iterator> range(const C& c) {
return utils::range<typename C::const_iterator>(c.begin(), c.end());
}
template<typename Iter>
utils::range<Iter> range(const Iter& begin, const Iter& end) {
return utils::range<Iter>(begin, end);
}
typedef typename vector<TermPtr>::const_iterator TermIter;
typedef typename vector<Sequence::SubSequence>::const_iterator SubSeqIter;
struct SubRange {
utils::range<TermIter> pattern;
utils::range<TokenIter> tokens;
SubRange(const utils::range<TermIter>& pattern, const utils::range<TokenIter>& tokens)
: pattern(pattern), tokens(tokens) {}
};
vector<TokenIter> findSplitCandidates(const Grammar::TermInfo& info,
const TokenIter& begin, const TokenIter& end, const TokenIter& lowerLimit,
const TokenSet& endSet, const TokenSet& followSet,
const TokenSet& terminator = TokenSet()
) {
// initialize candidate list
vector<TokenIter> candidates;
// handle begin differently
if (begin != end && begin >= lowerLimit && followSet.contains(*begin)) {
candidates.push_back(begin);
}
// compute list of candidate-split-points
vector<Token> parentheseStack;
for(auto it = begin; it != end; ++it) {
const Token& cur = *it;
// if current token is an opener => put closer on the stack
if (info.isLeftParenthese(cur)) {
// check whether this is a right-parentheses as well (e.g. $ .. $ )
if (!info.isRightParenthese(cur) || parentheseStack.empty() || parentheseStack.back() != cur) {
// it is not a right-parentheses or it is not the expected one
parentheseStack.push_back(info.getClosingParenthese(cur));
continue;
}
}
// check whether it is a closer
if (info.isRightParenthese(cur)) {
if (!parentheseStack.empty() && parentheseStack.back() == cur) {
parentheseStack.pop_back(); // all fine
} else {
// nothing more will be matched - parentheses not balanced
break; // no need to continue search for candidates
}
}
// check whether iterator is inside a nested expression
if (!parentheseStack.empty()) {
continue; // jup, still inside => no candidate
}
// so, there is nothing on the stack ..
assert(parentheseStack.empty());
// we are getting closer - check whether we are within the search range
if (it+1 < lowerLimit) {
continue;
}
// now check whether current token is a terminator for the body
if (!endSet.contains(cur)) {
continue;
}
// check whether following element is within the follow set
if (it+1 != end && !followSet.contains(*(it+1))) {
continue;
}
// nice - we have a candidate (the end is the next token)
candidates.push_back(it+1);
// check whether this entry is a terminating one
if (terminator.contains(cur)) {
return candidates; // we are done her!
}
}
// that's it - we have a list of candidates
return candidates;
}
Result matchVarOnly(Context& context, const utils::range<TermIter>& pattern, const utils::range<TokenIter>& tokens) {
// check terminal state
if (pattern.empty()) {
return tokens.empty(); // full string consumed?
}
// check that head is a non-terminal entry and not an epsilon
assert(!pattern.front()->isTerminal());
assert(!dynamic_pointer_cast<Empty>(pattern.front()));
auto curVar = *pattern.begin();
// if the pattern is only a single variable (or the last within the recursive processing) ...
if (pattern.single()) {
return curVar->match(context, tokens.begin(), tokens.end());
}
// special treatment for empty token list
if (tokens.empty()) {
if (!curVar->match(context, tokens.begin(), tokens.end())) {
return fail(context, tokens.begin(), tokens.end());
}
return matchVarOnly(context, pattern+1, tokens);
}
// --- search candidates for split-points ---
// search largest portion starting from head being accepted by the body
unsigned size = tokens.size();
TokenIter lowerLimit = tokens.begin() + std::min(curVar->getMinRange(), size);
TokenIter upperLimit = tokens.begin() + std::min(curVar->getMaxRange(), size);
// the set of tokens ending the body
const auto& endSet = context.grammar.getEndSet(pattern[0]);
const auto& followSet = context.grammar.getFollowSet(pattern[0]);
// search set of candidate-split-points
vector<TokenIter> candidates = findSplitCandidates(
context.grammar.getTermInfo(), tokens.begin(), upperLimit, lowerLimit,
endSet, followSet
);
// if there are no candidates this will not match
if (candidates.empty()) {
return fail(context, tokens.begin(), tokens.end());
}
// update speculation flag
context.setSpeculative(context.isSpeculative() || candidates.size() > 1);
// guess end of current variable and process recursively
auto backup = context.backup();
for(const TokenIter& cur : candidates) {
backup.restore(context);
utils::range<TokenIter> partA(tokens.begin(), cur);
utils::range<TokenIter> partB(cur, tokens.end());
// start by trying to match first variable (head)
Result a = curVar->match(context, partA.begin(), partA.end());
if (!a) { continue; } // try next split point
// continue recursively with the rest of the variables
Result b = matchVarOnly(context, pattern+1, partB);
if (b) { return b; }
}
// this term can not be matched
return fail(context, tokens.begin(), tokens.end());
}
Result matchSubRanges(Context& context, const vector<SubRange>& ranges) {
// process sub-ranges
Result res;
auto backup = context.backup();
bool speculationBackup = context.isSpeculative();
for(const SubRange& cur : ranges) {
res = matchVarOnly(context, cur.pattern, cur.tokens);
if (!res) {
backup.restore(context);
return fail(context, cur.tokens.begin(), cur.tokens.end());
}
context.setSpeculative(speculationBackup);
}
// return last result
return res;
}
Result matchInfixSequence(Context& context, const utils::range<SubSeqIter>& sequence, const utils::range<TokenIter>& tokens, bool leftAssociative, vector<SubRange>& ranges) {
// some pre-condition (checking that sequence is an infix sequence)
assert(!sequence.empty());
assert(sequence.size() % 2 == 1); // uneven number of entries for infix
assert(!(sequence.begin()->terminal));
assert(!((sequence.end()-1)->terminal));
// -- recursively build up sub-range list --
// terminal case (last non-terminal sequence)
if (sequence.single()) {
// add final sub-range (has to match all the rest)
ranges.push_back(SubRange(range(sequence.begin()->terms), tokens));
// try solving individual sub-ranges
auto res = matchSubRanges(context, ranges);
// remove final su-range entry
ranges.pop_back();
return res;
}
// find match for next terminal
auto& terminal = sequence[1];
assert(terminal.terminal);
// derive filters for before/after
const TokenSet& before = context.grammar.getSequenceEndSet(sequence[0]);
const TokenSet& after = context.grammar.getSequenceStartSet(sequence[2]);
bool beforeMayBeEmpty = sequence[0].limit.getMin() == 0;
bool afterMayBeEmpty = sequence[2].limit.getMin() == 0;
unsigned terminalSize = terminal.limit.getMin();
assert(terminalSize == terminal.limit.getMax());
// check for sufficient token stream size
if (tokens.size() < terminalSize) {
return fail(context, tokens.begin(), tokens.end());
}
// limit range of search space
unsigned min = sequence[0].limit.getMin();
unsigned max = std::min(sequence[0].limit.getMax(), (unsigned)(tokens.size()-terminalSize));
// get the first terminal to be looking for
TermPtr headTerminal = terminal.terms[0];
// while searching candidates we are speculating ...
bool speculationBackup = context.isSpeculative();
context.setSpeculative(true);
// search all candidates first
const Grammar::TermInfo& info = context.grammar.getTermInfo();
vector<Token> parentheseStack;
vector<unsigned> candidates;
for(unsigned i = 0; i<=max; ++i) {
const Token& cur = tokens[i];
// if current token is an opener => put closer on the stack
if (info.isLeftParenthese(cur)) {
parentheseStack.push_back(info.getClosingParenthese(cur));
}
// check whether it is a closer
if (info.isRightParenthese(cur)) {
if (!parentheseStack.empty() && parentheseStack.back() == cur) {
parentheseStack.pop_back(); // all fine
} else {
if (headTerminal->match(context, tokens.begin() + i, tokens.begin() + i +1)) {
// will be the last to be matched (it is the closing parentheses pair)
max = i;
} else {
// nothing more will be matched - parentheses not balanced
break; // no need to continue search for candidates
}
}
}
// check whether iterator is inside a nested expression
// - if searched head node is start of parentheses pair we still have to continue
bool isOpenToken = info.isLeftParenthese(cur) && headTerminal->match(context, tokens.begin() + i, tokens.begin() + i +1);
if (!(parentheseStack.empty() || (isOpenToken && parentheseStack.size() == 1u))) {
continue; // jup, still inside => no candidate
}
// skip elements outside search range
if (i < min) continue;
// check token before and after token sequence
if (i > 0 && !beforeMayBeEmpty && !before.contains(tokens[i-1])) {
continue;
}
if (i+terminalSize < tokens.size() && !afterMayBeEmpty && !after.contains(tokens[i+terminalSize])) {
continue;
}
// check terminals at corresponding position
TokenIter pos = tokens.begin() + i;
bool fit = true;
for(const TermPtr& cur : terminal.terms) {
fit = fit && cur->match(context, pos, pos+1);
pos++;
}
if (!fit) continue;
// found a candidate
candidates.push_back(i);
}
// check whether candidates are empty
if (candidates.empty()) {
return fail(context, tokens.begin(), tokens.end());
}
// update speculation flag
context.setSpeculative(speculationBackup || candidates.size() > 1u);
// reverse search order in left-associative case
if (leftAssociative) {
std::reverse(candidates.begin(), candidates.end());
}
// search within potential scope
for(unsigned i : candidates) {
// recursively match remaining terminals
ranges.push_back(SubRange(range(sequence.front().terms), tokens.subrange(0,i)));
Result res = matchInfixSequence(context, sequence+2, tokens.subrange(i+terminalSize), leftAssociative, ranges);
// check result => if OK, done
if (res) { return res; }
// continue search
ranges.pop_back();
}
// no matching assignment found
return fail(context, tokens.begin(), tokens.end());
}
}
Result Sequence::matchInternal(Context& context, const TokenIter& begin, const TokenIter& end) const {
auto pattern = range(sequence);
auto token = range(begin, end);
// -- special cases --
// check empty sequences
if (pattern.empty()) {
return token.empty();
}
// check whether token stream is empty (min range will be > 0 if there are any terminals)
if (getMinRange() > 0 && token.empty()) {
return fail(context, begin, end);
}
// Initial terminals:
if (pattern.begin()->terminal) {
const SubSequence& cur = pattern[0];
// match initial terminals
for(const TermPtr& rule : cur.terms) {
if(token.empty() || !rule->match(context, token.begin(), token.begin()+1)) {
return fail(context, token.begin(), token.begin()+1);
}
token+=1;
}
// prune pattern
pattern+=1;
}
// if it is only a sequence of terminals => done!
if (pattern.empty()) {
return token.empty();
}
// Tailing terminals:
if ((pattern.end()-1)->terminal) {
const SubSequence& cur = *(pattern.end()-1);
// match tailing terminals
for(auto it = cur.terms.rbegin(); it != cur.terms.rend(); ++it) {
const TermPtr& rule = *it;
if(token.empty() || !rule->match(context, token.end()-1, token.end())) {
return fail(context, token.end()-1, token.end());
}
token-=1;
}
// prune pattern
pattern-=1;
}
// Now there should only be an infix pattern (head and tail is non-terminal)
assert(!pattern.empty());
assert(pattern.size() % 2 == 1);
assert(!pattern.begin()->terminal);
assert(!(pattern.end()-1)->terminal);
// use recursive matching algorithm
vector<SubRange> ranges;
return matchInfixSequence(context, pattern, token, leftAssociative, ranges);
}
vector<Sequence::SubSequence> Sequence::prepare(const vector<TermPtr>& terms) {
// merge all elements into a single list (inline nested sequences and skip epsilons)
vector<TermPtr> flat;
for(const TermPtr& cur : terms) {
if (auto seq = dynamic_pointer_cast<Sequence>(cur)) {
// add all sub-sequences
for(const SubSequence& subList : seq->sequence) {
flat.insert(flat.end(), subList.terms.begin(), subList.terms.end());
}
} else if (!dynamic_pointer_cast<Empty>(cur)){
flat.push_back(cur);
}
}
// create list of sub-sequences of pure terminal / non-terminal elements
vector<SubSequence> res;
if (flat.empty()) {
return res;
}
// partition into sub-sequences
SubSequence* curSeq = 0;
for(const TermPtr& cur : flat) {
bool terminal = cur->isTerminal();
// check whether new sub-sequence needs to be started
if (!curSeq || curSeq->terminal != terminal) {
// start new sub-sequence
res.push_back(SubSequence(terminal));
curSeq = &res.back();
}
// add term to sub-sequence
curSeq->limit += cur->getLimit();
curSeq->terms.push_back(cur);
}
return res;
}
void Sequence::updateLimit() {
Limit limit(0,0);
for(const SubSequence& sub : sequence) {
for(const TermPtr& rule : sub.terms) {
limit += rule->getLimit();
}
}
setLimit(limit);
}
Result Alternative::matchInternal(Context& context, const TokenIter& begin, const TokenIter& end) const {
// get list of candidates
vector<TermPtr> candidates;
if (begin == end) {
// take all rules with potential length 0
for(const TermPtr& cur : alternatives) {
if (cur->getMinRange() == 0u) {
candidates.push_back(cur);
}
}
} else {
// take all rules with matching start and end tokens
for(const TermPtr& cur : alternatives) {
const auto& sets = context.grammar.getSets(cur);
if (sets.startSet.contains(*begin) && sets.endSet.contains(*(end-1))) {
candidates.push_back(cur);
}
}
}
// check number of candidates
if (candidates.empty()) {
return fail(context, begin, end); // will not match
}
// stupid implementation => improve with priorities and index!
auto backup = context.backup();
context.setSpeculative(context.isSpeculative() || candidates.size() > 1u);
for(const TermPtr& cur : candidates) {
Result res = cur->match(context, begin, end);
if (res) { return res; }
backup.restore(context);
}
return fail(context, begin, end);
}
Result Loop::matchInternal(Context& context, const TokenIter& begin, const TokenIter& end) const {
/**
* Idea:
* 1) search smallest block (from start) matching the loop body => first match
* 2) repeat recursively until range has been consumed
* 3) if recursive resolution worked => done, otherwise search next match in 1)
*/
// terminal case - empty case => will be accepted
if (begin == end) return true;
// the set of tokens ending the body
const auto& sets = context.grammar.getSets(body);
const auto& startSet = sets.startSet;
const auto& endSet = sets.endSet;
// check head and tail element
if (!startSet.contains(*begin) || !endSet.contains(*(end-1))) {
return fail(context, begin, end); // will never match
}
// search largest portion starting from head being accepted by the body
unsigned size = std::distance(begin, end);
TokenIter lowerLimit = begin + std::min(body->getMinRange(), size);
TokenIter upperLimit = begin + std::min(body->getMaxRange(), size);
// find candidates of potential splitting points
vector<TokenIter> candidates = findSplitCandidates(
context.grammar.getTermInfo(), begin, upperLimit, lowerLimit,
endSet, startSet, terminator
);
// check whether there are candidates
if (candidates.empty()) {
return fail(context, begin, end);
}
// update speculation flag
auto backup = context.backup();
context.setSpeculative(context.isSpeculative() || candidates.size() > 1u);
// gradually reduce the range to be matched
for(const auto& curEnd : candidates) {
// try current sub-range
Result res = body->match(context, begin, curEnd);
if (res) {
// try matching the rest!
auto res = match(context, curEnd, end);
// if matching => done
if (res) { return res; }
// otherwise try next ..
backup.restore(context);
}
}
// no first match found => no match at all
return fail(context, begin, end);
}
bool Terminal::updateTokenSets(const Grammar& g, TokenSet& begin, TokenSet& end) const {
return begin.add(terminal) || end.add(terminal);
}
bool Any::updateTokenSets(const Grammar& g, TokenSet& begin, TokenSet& end) const {
TokenSet set = (!type)?(TokenSet(TokenSet::all())):(TokenSet(type));
return begin.add(set) || end.add(set);
}
bool NonTerminal::updateTokenSets(const Grammar& g, TokenSet& begin, TokenSet& end) const {
return begin.add(g.getStartSet(nonTerminal)) || end.add(g.getEndSet(nonTerminal));
}
bool Alternative::updateTokenSets(const Grammar& g, TokenSet& begin, TokenSet& end) const {
bool res = false;
for(const TermPtr& opt : alternatives) {
res = begin.add(g.getStartSet(opt)) || res;
res = end.add(g.getEndSet(opt)) || res;
}
return res;
}
bool Loop::updateTokenSets(const Grammar& g, TokenSet& begin, TokenSet& end) const {
bool res = false;
res = begin.add(g.getStartSet(body)) || res;
res = end.add(g.getEndSet(body)) || res;
return res;
}
bool Sequence::SubSequence::updateStartSet(const Grammar& g, TokenSet& start) const {
if (terms.empty()) return false;
bool res = false;
auto it = terms.begin();
do {
res = start.add(g.getStartSet(*it)) || res;
} while ((*it)->getMinRange() == 0u && (++it) != terms.end());
return res;
}
bool Sequence::SubSequence::updateEndSet(const Grammar& g, TokenSet& end) const {
bool res = false;
auto it = terms.rbegin();
do {
res = end.add(g.getEndSet(*it)) || res;
} while ((*it)->getMinRange() == 0u && (++it) != terms.rend());
return res;
}
vector<TermPtr> Sequence::getTerms() const {
vector<TermPtr> res;
for (auto& cur : sequence) {
res.insert(res.end(), cur.terms.begin(), cur.terms.end());
}
return res;
}
bool Sequence::updateTokenSets(const Grammar& g, TokenSet& begin, TokenSet& end) const {
bool res = false;
// deal with potentially empty sub-sequences in the front
{
auto it = sequence.begin();
do {
res = it->updateStartSet(g, begin) || res;
} while(it->limit.getMin() == 0 && (++it) != sequence.end());
}
// deal with potentially empty sub-sequences in the back
{
auto it = sequence.rbegin();
do {
res = it->updateEndSet(g, end) || res;
} while(it->limit.getMin() == 0 && (++it) != sequence.rend());
}
return res;
}
void Sequence::addSubTerms(std::set<TermPtr>& terms) const {
// collect all sub-terms
for(const SubSequence& cur : sequence) {
for(const TermPtr& term : cur.terms) {
terms.insert(term);
term->addSubTerms(terms);
}
}
}
void Sequence::addTokenPairs(std::map<Token,Token>& map) const {
// not the best but a fool-proof implementation (hopefully)
vector<TermPtr> terms;
for(const SubSequence& cur : sequence) {
for(const TermPtr& term : cur.terms) {
terms.push_back(term);
}
}
// now search token pairs
for(auto a = terms.begin(); a != terms.end(); ++a) {
auto terminal = dynamic_pointer_cast<Terminal>(*a);
if (!terminal) continue;
// found a start symbol
const Token& start = terminal->getTerminal();
if (start.getType() != Token::Symbol) { continue; }
// search end symbol
bool spansNonTerminal = false;
for(auto b=a+1; b != terms.end(); ++b) {
auto terminal = dynamic_pointer_cast<Terminal>(*b);
if (!terminal) {
spansNonTerminal = true;
continue;
}
// if there was no variable part in between ..
if (!spansNonTerminal) {
break; // .. it can be skipped
}
const Token& end = terminal->getTerminal();
if (end.getType() != Token::Symbol) {
spansNonTerminal = true;
continue;
}
// an end has been found!
map[start] = end;
break; // no further search necessary
}
}
}
namespace {
template<typename TokenIter>
bool checkParenthese(const Token& start, const Token& end, const TokenIter& tbegin, const TokenIter& tend) {
// search through range for start token
for(auto a = tbegin; a != tend; ++a) {
if (*a != start) continue;
// if start is present, end has to be as well!
bool found = false;
for(auto b=a+1; !found && b != tend; ++b) {
if (*b == end) {
found = true;
a = b; // continue search from here
} else if (*b == start) {
return false; // another start before the end => pair not supported
}
}
// if there is no corresponding end-symbol the pair is not supported!
if (!found) return false;
}
// no violation found => everything is fine
return true;
}
}
bool Sequence::supportsPair(const pair<Token,Token>& pair) const {
// create list of tokens included within this sequence
vector<Token> tokenSeq;
for(const SubSequence& cur : sequence) {
for(const TermPtr& term : cur.terms) {
if (auto cur = dynamic_pointer_cast<Terminal>(term)) {
const Token& token = cur->getTerminal();
if (token.getType() == Token::Symbol) {
tokenSeq.push_back(token);
}
}
}
}
// extract start and end tokens
const Token& start = pair.first;
const Token& end = pair.second;
// search forward and backward direction
return checkParenthese(start, end, tokenSeq.begin(), tokenSeq.end()) &&
checkParenthese(end, start, tokenSeq.rbegin(), tokenSeq.rend());
}
// -- begin token set
bool TokenSet::add(const Token& token) {
if (contains(token)) return false;
*this += token;
return true;
}
bool TokenSet::add(const Token::Type& type) {
if (coversType(type)) return false;
*this += type;
return true;
}
bool TokenSet::add(const TokenSet& other) {
if (isSubSet(other)) return false;
*this += other;
return true;
}
bool TokenSet::isSubSet(const TokenSet& other) const {
return ((tokenTypeMask | other.tokenTypeMask) == tokenTypeMask) &&
(::all(other.tokens, [&](const Token& cur) { return contains(cur); }));
}
TokenSet& TokenSet::operator+=(const Token& token) {
if (!coversType(token) && !coversToken(token)) {
tokens.push_back(token);
}
return *this;
}
TokenSet& TokenSet::operator+=(const Token::Type& type) {
if (tokenTypeMask & (1<<type)) {
return *this; // nothing to add
}
// add to mask
tokenTypeMask = tokenTypeMask | (1<<type);
// kick out all tokens matched by type mask
auto newEnd = std::remove_if(tokens.begin(), tokens.end(),
[&](const Token& cur) { return coversType(cur); });
tokens.erase(newEnd, tokens.end());
// return updated
return *this;
}
TokenSet& TokenSet::operator+=(const TokenSet& other) {
// merge type mask
tokenTypeMask = tokenTypeMask | other.tokenTypeMask;
// filter out local set
auto newEnd = std::remove_if(tokens.begin(), tokens.end(),
[&](const Token& cur) { return coversType(cur); });
tokens.erase(newEnd, tokens.end());
// merge in other set
for(const Token& cur : other.tokens) {
if (!coversType(cur) && !coversToken(cur)) {
tokens.push_back(cur);
}
}
return *this;
}
std::ostream& TokenSet::printTo(std::ostream& out) const {
assert(Token::Symbol == 1 && Token::String_Literal == 9 && "If this changes, check this code!");
out << "{";
for(unsigned i = Token::Symbol; i != Token::String_Literal; i++) {
Token::Type cur = (Token::Type)i;
if (coversType(cur)) {
out << "(" << cur << ":*),";
}
}
return out << join(",", tokens) << "}";
}
// -- end token set
std::ostream& Grammar::TermInfo::printTo(std::ostream& out) const {
return out << "TermInfo: {\n\t" <<
join("\n\t", termInfos,
[](std::ostream& out, const pair<TermPtr,Sets>& cur) {
out << *cur.first << ": \t" << cur.second.startSet << " ... " << cur.second.endSet << " : " << cur.second.followSet;
}) << "\n\t" <<
join("\n\t", nonTerminalInfos,
[](std::ostream& out, const pair<string,Sets>& cur) {
out << cur.first << ": \t" << cur.second.startSet << " ... " << cur.second.endSet << " : " << cur.second.followSet;
}) << "\n TerminalPairs: \n\t" <<
join("\n\t", parenthesePairs,
[](std::ostream& out, const pair<Token,Token>& cur) {
out << cur.first.getLexeme() << " " << cur.second.getLexeme();
}) << "\n}";
}
NodePtr Grammar::match(NodeManager& manager, const string& code, bool throwOnFail, const std::map<string, NodePtr>& symbols) const {
// step 1) start by obtaining list of tokens
auto tokens = lex(code);
// step 2) check parenthesis - if not properly nested, it is wrong!
if (!checkParenthese(tokens.begin(), tokens.end())) {
if (throwOnFail) throw ParseException("Unbalanced parentheses encountered!");
return NodePtr(); // parenthesis not properly nested!
}
// step 2) parse recursively
NodePtr res;
try {
// create a context for the translation
Context context(*this, manager, tokens.begin(), tokens.end(), false);
// register pre-defined symbols
auto& symManager = context.getSymbolManager();
vector<vector<Token>> symbolTokens;
for(const pair<string, NodePtr>& cur : symbols) {
symbolTokens.push_back(toVector(Token::createIdentifier(cur.first)));
symManager.add(range(symbolTokens.back()), cur.second);
}
// run recursive match
res = match(context, tokens.begin(), tokens.end(), start);
if (!res && throwOnFail) throw ParseException("Unknown parser error!");
} catch (const ParseException& pe) {
// handle exception depending on flag
if (throwOnFail) throw pe;
}
return res;
}
NodePtr Grammar::match(Context& context, const TokenIter& begin, const TokenIter& end, const string& nonTerminal) const {
return matchInternal(context, begin, end, nonTerminal);
// static int hitCounter = 0;
// static int missCounter = 0;
//
// // check the cache
// TokenRange range(begin,end);
//
// // check cache
// NodePtr res = context.lookup(nonTerminal, range);
// if (res) {
// std::cout << "Hit " << ++hitCounter << " vs " << missCounter << "\n";
// return res; // use cached value
// }
// ++missCounter;
//// std::cout << "Miss " << ++missCounter << "\n";
// // parse element +
// res = matchInternal(context, begin, end, nonTerminal);
// context.store(nonTerminal, range, res);
// return res;
}
NodePtr Grammar::matchInternal(Context& context, const TokenIter& begin, const TokenIter& end, const string& nonTerminal) const {
// search for rule set for given non-terminal
auto pos = productions.find(nonTerminal);
if(pos == productions.end()) {
return NodePtr(); // a non-terminal without productions will not be matched
}
// compute set of potential rules
vector<RulePtr> candidates;
if (begin == end) {
// take all rules with potential length 0
for(const RulePtr& rule : pos->second) {
if (rule->getPattern()->getMinRange() == 0u) {
candidates.push_back(rule);
}
}
} else {
// take all rules with matching start and end tokens
for(const RulePtr& rule : pos->second) {
const auto& sets = getSets(rule->getPattern());
if (sets.startSet.contains(*begin) && sets.endSet.contains(*(end-1))) {
candidates.push_back(rule);
}
}
}
// see whether there are candidates
if (candidates.empty()) {
return NodePtr();
}
// create new temporary context
Context localContext(context, begin, end);
localContext.setSpeculative(context.isSpeculative() || candidates.size() > 1u);
auto backup = localContext.backup();
for(const RulePtr& rule : candidates) {
NodePtr res = rule->match(localContext, begin, end);
if (res) return res;
backup.restore(localContext);
}
return NodePtr();
}
Grammar::Productions Grammar::toProductions(const string& symbol, const vector<RulePtr>& rules) {
Grammar::Productions res;
res[symbol].insert(rules.begin(), rules.end());
return res;
}
std::ostream& Grammar::printTo(std::ostream& out) const {
return out << "(" << start << ",{\n\t" << join("\n\t", productions, [](std::ostream& out, const pair<string, RuleSet>& cur) {
out << cur.first << " =\t" << join(" |\n\t\t", cur.second, [](std::ostream& out, const RulePtr& rule) {
out << *rule->getPattern();
}) << "\n";
}) << "})";
}
void Grammar::updateTermInfo() const {
if (infoValid) return;
// mark as up-to-date (already during processing to avoid infinite recursion)
infoValid = true;
// collect set of terms
std::set<TermPtr> terms;
for(const auto& product : productions) {
for(const RulePtr& rule : product.second) {
terms.insert(rule->getPattern());
rule->getPattern()->addSubTerms(terms);
}
}
// re-initialize term info
info = TermInfo();
// ---- compute start / end sets -----
// initialize information
for(const TermPtr& cur : terms) {
info.termInfos[cur]; // uses default initialization
}
for(const auto& production : productions) {
info.nonTerminalInfos[production.first];
}
// iteratively solve equation system for start/end sets
bool changed = true;
while (changed) {
changed = false;
// update sub-sequences
for(const TermPtr& cur : terms) {
if (auto seq = dynamic_pointer_cast<const Sequence>(cur)) {
for(const Sequence::SubSequence& cur : seq->getSubSequences()) {
auto& sets = info.subSequenceInfo[&cur];
changed = cur.updateStartSet(*this,sets.startSet) || changed;
changed = cur.updateEndSet(*this, sets.endSet) || changed;
}
}
}
// update terms
for(const TermPtr& cur : terms) {
auto& sets = info.termInfos[cur];
changed = cur->updateTokenSets(*this, sets.startSet, sets.endSet) || changed;
}
// updated non-terminals
for(const auto& production : productions) {
// update productions for current non-terminal
auto& sets = info.nonTerminalInfos[production.first];
for(const auto& rule : production.second) {
changed = sets.startSet.add(getStartSet(rule->getPattern())) || changed;
changed = sets.endSet.add(getEndSet(rule->getPattern())) || changed;
}
}
}
// update follow sets
for(const TermPtr& cur : terms) {
if (auto seq = dynamic_pointer_cast<const Sequence>(cur)) {
// get sequence of terms
vector<TermPtr> terms = seq->getTerms();
// set up follow sets
for(auto a = terms.begin(); a != terms.end(); ++a) {
TokenSet& followSet = info.termInfos[*a].followSet;
for(auto b= a+1; b != terms.end(); ++b) {
followSet.add(info.termInfos[*b].startSet);
if ((*b)->getLimit().getMin() > 0) break;
}
}
}
}
// ---- compute pairs -----
// start by collecting top-level production rule sequences
typedef std::shared_ptr<Sequence> SequencePtr;
std::vector<SequencePtr> sequences;
for(const auto& production : productions) {
for(const auto& rule : production.second) {
const TermPtr& cur = rule->getPattern();
if (auto sequence = dynamic_pointer_cast<Sequence>(cur)) {
sequences.push_back(sequence);
} else {
// turn into a sequence and add it to the list
sequences.push_back(seq(cur));
}
}
}
// create list of token-pair candidates
std::map<Token,Token> tokenPairCandidates;
for(const SequencePtr& cur : sequences) {
cur->addTokenPairs(tokenPairCandidates);
}
// check candidates (whenever the left-hand-side is present, the right has to be as well)
for(const pair<Token,Token>& cur : tokenPairCandidates) {
// if all sequences support the current pair ...
auto support = [&](const SequencePtr& seq) { return seq->supportsPair(cur); };
if (all(sequences, support)) {
info.addParenthese(cur.first, cur.second); // .. we can add it to the result
}
}
}
bool Grammar::checkParenthese(const TokenIter& begin, const TokenIter& end) const {
const TermInfo& info = getTermInfo();
if (!info.hasParenthesePairs()) {
return true; // nothing to check
}
// check proper nesting
vector<Token> parentheseStack;
for(const Token& cur : range(begin, end)) {
if (info.isLeftParenthese(cur)) {
parentheseStack.push_back(info.getClosingParenthese(cur));
}
if (info.isRightParenthese(cur)) {
if (parentheseStack.empty() || parentheseStack.back() != cur) {
return false; // not matching parentheses
}
parentheseStack.pop_back();
}
}
// now all parentheses should be closed
return parentheseStack.empty();
}
TermPtr cap(const TermPtr& term) {
// define action event handler
struct capture : public detail::actions {
void accept(Context& context, const TokenIter& begin, const TokenIter& end) const {
context.push(TokenRange(begin, end));
}
};
return std::make_shared<Action<capture>>(term);
}
TermPtr varScop(const TermPtr& term) {
// define action event handler
struct var_scope_handler : public detail::actions {
void enter(Context& context, const TokenIter& begin, const TokenIter& end) const {
context.getVarScopeManager().pushScope(true);
}
void leave(Context& context, const TokenIter& begin, const TokenIter& end) const {
context.getVarScopeManager().popScope();
}
};
return std::make_shared<Action<var_scope_handler>>(term);
}
TermPtr newScop(const TermPtr& term) {
// define action event handler
struct new_scope_handler : public detail::actions {
void enter(Context& context, const TokenIter& begin, const TokenIter& end) const {
context.getVarScopeManager().pushScope(false);
}
void leave(Context& context, const TokenIter& begin, const TokenIter& end) const {
context.getVarScopeManager().popScope();
}
};
return std::make_shared<Action<new_scope_handler>>(term);
}
TermPtr symScop(const TermPtr& term) {
// define action event handler
struct new_scope_handler : public detail::actions {
void enter(Context& context, const TokenIter& begin, const TokenIter& end) const {
context.getSymbolManager().pushScope(true);
}
void leave(Context& context, const TokenIter& begin, const TokenIter& end) const {
context.getSymbolManager().popScope();
}
};
return std::make_shared<Action<new_scope_handler>>(term);
}
} // end namespace detail
} // end namespace parser
} // end namespace core
} // end namespace insieme
|
562a9f1ea717e4e5cfb1ceeba6d04dd57a0d9477
|
30bdd8ab897e056f0fb2f9937dcf2f608c1fd06a
|
/Graphs/2472.cpp
|
1d9c198297d2ca596baafc2d452f88da8cb7f444
|
[] |
no_license
|
thegamer1907/Code_Analysis
|
0a2bb97a9fb5faf01d983c223d9715eb419b7519
|
48079e399321b585efc8a2c6a84c25e2e7a22a61
|
refs/heads/master
| 2020-05-27T01:20:55.921937
| 2019-11-20T11:15:11
| 2019-11-20T11:15:11
| 188,403,594
| 2
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,418
|
cpp
|
2472.cpp
|
#include<bits/stdc++.h>
using namespace std;
#define boost() ios_base::sync_with_stdio(false),cin.tie(0)
#define all(c) c.begin(),c.end()
#define rep(i,c,n) for(i=c;i<n;i++)
#define dw(t) while (t--)
#define PB push_back
#define MP make_pair
#define F first
#define S second
typedef pair<int,int> pii;
typedef pair<long,long> pll;
typedef unsigned long long ull;
typedef long long ll;
#define MOD 1000000007
bool sieve[1000001];
void init(){
long long i,j;
sieve[0]=true;
sieve[1]=true;
rep(i,2,1000001)
{
if(!sieve[i])
{
for(j=2*i;j<1000001;j+=i)
sieve[j]=true;
}
}
}
long long power(long x,long n){
if(n==0)
return 1;
if(n==1)
return x;
long n2 = n/2;
long long po = power(x,n2);
if(n%2)
return po*po*x;
return po*po;
}
long long gcd(long long a , long long b)
{
if(b==0) return a;
a%=b;
return gcd(b,a);
}
long long lcm(long long a,long long b)
{
return a*b/gcd(a,b);
}
int nodes;
int color[100005];
vector<int> G[100005];
int dfs(int src, int par, int curr){
// cout<<src<<" "<<par<<" "<<curr<<endl;
int ans = (curr!=color[src]);
for(auto it:G[src]){
if(it==par)
continue;
ans+=dfs(it, src, color[src]);
}
return ans;
}
int main(){
boost();
int i,x,y;
cin>>nodes;
rep(i,1,nodes){
cin>>x;
G[i+1].PB(x);
G[x].PB(i+1);
}
rep(i,0,nodes)
cin>>color[i+1];
cout<<dfs(1,-1,0)<<'\n';
return 0;
}
|
2276a6d0ad4896b3c3ca0f766a1435c01afd701c
|
00061a574c9f76c248c7b71cc3e4e1042a11f17d
|
/ImageBase.hpp
|
b069e5eba93354fefa96f15c49130d1f0fa6f31a
|
[] |
no_license
|
ThenTech/ImageEncoder
|
fb5548bc7a7d3045f63edc0845bfc33ebb7e5c48
|
e321177d73707cda5a65a1b42805e700679d377f
|
refs/heads/master
| 2022-01-11T15:46:30.844535
| 2019-05-06T07:54:33
| 2019-05-06T07:54:33
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,245
|
hpp
|
ImageBase.hpp
|
#ifndef IMAGEBASE_HPP
#define IMAGEBASE_HPP
#include <string>
#include <vector>
#include "BitStream.hpp"
#include "Block.hpp"
#include "MatrixReader.hpp"
namespace dc {
/**
* @brief The ImageBase class
* Provides a base with the image dimensions and the raw byte buffer
* read into an std::vector and accessible through a BitStreamReader instance.
*/
class ImageBase {
protected:
uint16_t width; ///< The width of the image.
uint16_t height; ///< The height of the image.
std::vector<uint8_t> *raw; ///< The raw input stream.
util::BitStreamReader *reader; ///< A BitStreamReader linked to the raw input stream.
public:
ImageBase(const std::string &source_file, const uint16_t &width, const uint16_t &height);
ImageBase(uint8_t * const raw, const uint16_t &width, const uint16_t &height);
~ImageBase(void);
};
////////////////////////////////////////////////////////////////////////////////////
/**
* @brief The ImageProcessor class
*/
class ImageProcessor : protected ImageBase {
protected:
bool use_rle; ///< Whether to use Run Length Encoding.
MatrixReader<> quant_m; ///< A quantization matrix instance.
const std::string &dest_file; ///< The path to the destination file.
std::vector<dc::MicroBlock*> *blocks; ///< A list of every Block for the image.
std::vector<dc::MacroBlock*> *macroblocks; ///< A list of every MacroBlock for the image.
util::BitStreamWriter *writer; ///< The output stream.
void saveResult(bool) const;
bool process(uint8_t * const);
bool processMacroBlocks(uint8_t * const);
void copyMacroblockToMatchingMicroblocks(MacroBlock&);
public:
ImageProcessor(const std::string &source_file, const std::string &dest_file,
const uint16_t &width, const uint16_t &height,
const bool &use_rle, MatrixReader<> &quant_m);
ImageProcessor(const std::string &source_file, const std::string &dest_file);
ImageProcessor(uint8_t * const raw,
const uint16_t &width, const uint16_t &height,
const bool &use_rle, MatrixReader<> &quant_m);
virtual ~ImageProcessor(void);
/**
* @brief Process the image, needs to be implemented in a child class.
* A child class can call ImageProcessor::process(buffer) to create
* block from the buffer.
*/
virtual bool process(void)=0;
virtual void saveResult(void) const {}
dc::MacroBlock* getBlockAtCoord(int16_t, int16_t) const;
static constexpr size_t RLE_BITS = 1u; ///< The amount of bits to use to represent zhether to use RLE or not.
static constexpr size_t DIM_BITS = 15u; ///< The amount of bits to use to represent the image dimensions (width or height).
};
}
#endif // IMAGEBASE_HPP
|
edcde0297a92397e12cbe4e1b8434d35d5508dbe
|
58de89555c46b1a6ac3c0528cc1e546ee8cfb273
|
/Sample/TDXLin/Code/MyLib/File/File.cpp
|
4b9c14af89b9b0c22d7a83caca28796288b29b7b
|
[] |
no_license
|
syaraKamura/SmpleProject
|
8cbd62e2a7d39765c9adc55512d36739af690016
|
9d36bf562b8209d62988c811f85f2a47f1cb0af2
|
refs/heads/master
| 2021-01-16T17:58:00.569626
| 2017-10-10T20:13:55
| 2017-10-10T20:13:55
| 100,028,049
| 0
| 0
| null | 2017-10-08T02:01:02
| 2017-08-11T12:13:15
|
C++
|
SHIFT_JIS
|
C++
| false
| false
| 2,997
|
cpp
|
File.cpp
|
/*!/////////////////////////////////////////////////////////////////////////////////////////
☆メモ
ファイルシステムについて
ファイルの読み込み
Hedder FILE:ファイルの種類 バージョン1.0
TBLリスト
LabelName:
LabelName:
データ1
LabelName1:
データ2
LabelName2:
データサイズで記述
拡張子はmyfile
ファイルの書き出し
ファイルの種類 ファイルのバージョン
ファイルのデータテーブル一覧
ファイルデータの中身
ここは可変
*////////////////////////////////////////////////////////////////////////////////////////////
#include "DxLib.h"
#include "File.h"
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
//画像の基本情報
typedef struct{
int id;
char fileName[256];
int handle; //グラフィックハンドル
}GRAPHICS_INFO;
typedef struct{
int graphicID; //画像番号
int posX;
int posY;
int u1; //画像内座標 左上
int v1;
int u2; //画像内座標 右下
int v2;
}GRAPHICS_UV_DATA;
typedef struct{
GRAPHICS_INFO info; //基本情報
GRAPHICS_UV_DATA graphicsUvData;
}GRAPHICS_SHEET_DATA;
typedef struct{
char fileName[256];
int line; //最大行数
char str[][64]; //文字列データ
}FILE_LOADER_DATA;
static void _GraphicsLoadData(FILE_LOADER_DATA FileData){
int line = 0;
GRAPHICS_SHEET_DATA graphicsSheetData = {};
while(line < FileData.line){
char* str = FileData.str[line];
if(strcmp(str,"FILE") == 0){
}else if(strcmp(str,"VERSION") == 0){
}else if(strcmp(str,"PASH") == 0){
strcpy_s(graphicsSheetData.info.fileName, FileData.str[1]);
}else if(strcmp(str,"VERSION") == 0){
}else if(strcmp(str,"VERSION") == 0){
}
}
}
void File_Wirte(void* data,size_t size){
FILE* fp;
fopen_s(&fp,"testFile.txt","wb");
if(fp == NULL){
return ;
}
fwrite("FILE: VERSION:1.0\n",1,sizeof("FILE: VERSION:1.0\n"),fp);
fwrite("TABLE{",1,sizeof("TABLE{"),fp);
fwrite("Pram",1,sizeof("Pram"),fp);
fwrite("}",1,sizeof("}"),fp);
fwrite("Pram{",1,sizeof("Pram{"),fp);
fwrite("}",1,sizeof("}"),fp);
fclose(fp);
}
void File_Read(){
FILE* fp;
bool isFlag = true;
fopen_s(&fp,"testFile.txt","rb");
if(fp == NULL){
return ;
}
//ファイルから文字列を取得する
char ch = '\0';
char str[1024][64] = {""};
int pos = 0;
int line = 0;
while(feof(fp) == 0){
ch = fgetc(fp);
if(ch == '\t'){
continue;
}else if(ch == ' ' || ch == '\n'){
str[line][pos] = '\0'; //ヌル文字を設定
pos = 0;
line ++;
continue;
}
str[line][pos] = ch;
pos++;
}
//空白行、タブ、半角スペースを読み飛ばす
//ファイルの種類の読み取り
//ファイルのバージョン読み取り
//スクリプト関数の読み取り
fclose(fp);
//文字の分割読み込み開始
}
|
103a282247727a73861c4817a96f4f5cabef1092
|
736df3ae125da593ab85e80201338da9e06a04be
|
/UVA10420.cpp
|
625965035ce40eb6b4932c5e95afe29ff864739c
|
[] |
no_license
|
leoloveacm/Week-02-Coding-Training
|
c7420f4858e49e1b10191073ff81ca7bac889e66
|
9f5b5709964ec9b54a21947022a1dbf87a857aff
|
refs/heads/master
| 2021-01-17T20:41:55.657204
| 2016-04-28T08:10:53
| 2016-04-28T08:10:53
| 56,969,799
| 0
| 0
| null | 2016-04-24T12:15:32
| 2016-04-24T12:15:32
| null |
UTF-8
|
C++
| false
| false
| 520
|
cpp
|
UVA10420.cpp
|
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <map>
#include <string>
using namespace std;
map<string,int>mp;
int main(){
int T;
string str;
scanf("%d",&T);
getchar();
while(T--){
cin>>str;
//cout<<str<<endl;
getchar();
mp[str]++;
getline(cin,str);
}
map<string ,int>::iterator it;
for(it=mp.begin();it!=mp.end();it++)
cout<<it->first<<" "<<it->second<<endl;
return 0;
}
|
aa1cd445d6525b3f9fbf62c14c7bec82a172cd86
|
6d9c67637ffc0876311953250e2de397beaddccf
|
/Licence_agreement/I_accept/PCModel1350/PCModel/3.00/Models/PCDitch/2.13.16/cpp/pl6131600ss.cpp
|
07b1197414174d04f4e9f2881fafc3a453ab89c1
|
[] |
no_license
|
RedTent/PCModel
|
7ed7aa95503bdd2b531929d05c44ec082d8b2562
|
f98f62e15f1975f80c835fb616b36223b33c5d00
|
refs/heads/master
| 2023-04-18T10:14:26.302989
| 2020-08-28T09:52:50
| 2021-05-06T08:20:57
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,240
|
cpp
|
pl6131600ss.cpp
|
_sDepthW_=_sDepthW0_;
_sNH4W_=_sNH4W0_;
_sNO3W_=_sNO3W0_;
_sPO4W_=_sPO4W0_;
_sPAIMW_=_sPAIMW0_;
_sSiO2W_=_sSiO2W0_;
_sO2W_=_sO2W0_;
_sDDetW_=_sDDetW0_;
_sNDetW_=_sNDetW0_;
_sPDetW_=_sPDetW0_;
_sSiDetW_=_sSiDetW0_;
_sDIMW_=_sDIMW0_;
_sDDiatW_=_sDDiatW0_;
_sNDiatW_=_sNDiatW0_;
_sPDiatW_=_sPDiatW0_;
_sDGrenW_=_sDGrenW0_;
_sNGrenW_=_sNGrenW0_;
_sPGrenW_=_sPGrenW0_;
_sDBlueW_=_sDBlueW0_;
_sNBlueW_=_sNBlueW0_;
_sPBlueW_=_sPBlueW0_;
_sDZoo_=_sDZoo0_;
_sNZoo_=_sNZoo0_;
_sPZoo_=_sPZoo0_;
_sDFiAd_=_sDFiAd0_;
_sDFiJv_=_sDFiJv0_;
_sNFiAd_=_sNFiAd0_;
_sNFiJv_=_sNFiJv0_;
_sPFiAd_=_sPFiAd0_;
_sPFiJv_=_sPFiJv0_;
_sDPisc_=_sDPisc0_;
_sNH4S_=_sNH4S0_;
_sNO3S_=_sNO3S0_;
_sPO4S_=_sPO4S0_;
_sPAIMS_=_sPAIMS0_;
_sDDetS_=_sDDetS0_;
_sNDetS_=_sNDetS0_;
_sPDetS_=_sPDetS0_;
_sSiDetS_=_sSiDetS0_;
_sDHumS_=_sDHumS0_;
_sNHumS_=_sNHumS0_;
_sPHumS_=_sPHumS0_;
_sDIMS_=_sDIMS0_;
_sDDiatS_=_sDDiatS0_;
_sNDiatS_=_sNDiatS0_;
_sPDiatS_=_sPDiatS0_;
_sDGrenS_=_sDGrenS0_;
_sNGrenS_=_sNGrenS0_;
_sPGrenS_=_sPGrenS0_;
_sDBlueS_=_sDBlueS0_;
_sNBlueS_=_sNBlueS0_;
_sPBlueS_=_sPBlueS0_;
_sDVeg_=_sDVeg0_;
_sNVeg_=_sNVeg0_;
_sPVeg_=_sPVeg0_;
_sDBent_=_sDBent0_;
_sNBent_=_sNBent0_;
_sPBent_=_sPBent0_;
_sDepthWM_=_sDepthWM0_;
_sNH4WM_=_sNH4WM0_;
_sNO3WM_=_sNO3WM0_;
_sPO4WM_=_sPO4WM0_;
_sPAIMWM_=_sPAIMWM0_;
_sSiO2WM_=_sSiO2WM0_;
_sO2WM_=_sO2WM0_;
_sDDetWM_=_sDDetWM0_;
_sNDetWM_=_sNDetWM0_;
_sPDetWM_=_sPDetWM0_;
_sSiDetWM_=_sSiDetWM0_;
_sDIMWM_=_sDIMWM0_;
_sDDiatWM_=_sDDiatWM0_;
_sNDiatWM_=_sNDiatWM0_;
_sPDiatWM_=_sPDiatWM0_;
_sDGrenWM_=_sDGrenWM0_;
_sNGrenWM_=_sNGrenWM0_;
_sPGrenWM_=_sPGrenWM0_;
_sDBlueWM_=_sDBlueWM0_;
_sNBlueWM_=_sNBlueWM0_;
_sPBlueWM_=_sPBlueWM0_;
_sDZooM_=_sDZooM0_;
_sNZooM_=_sNZooM0_;
_sPZooM_=_sPZooM0_;
_sNH4SM_=_sNH4SM0_;
_sNO3SM_=_sNO3SM0_;
_sPO4SM_=_sPO4SM0_;
_sPAIMSM_=_sPAIMSM0_;
_sDDetSM_=_sDDetSM0_;
_sNDetSM_=_sNDetSM0_;
_sPDetSM_=_sPDetSM0_;
_sSiDetSM_=_sSiDetSM0_;
_sDHumSM_=_sDHumSM0_;
_sNHumSM_=_sNHumSM0_;
_sPHumSM_=_sPHumSM0_;
_sDIMSM_=_sDIMSM0_;
_sDRootPhra_=_sDRootPhra0_;
_sDShootPhra_=_sDShootPhra0_;
_sNRootPhra_=_sNRootPhra0_;
_sNShootPhra_=_sNShootPhra0_;
_sPRootPhra_=_sPRootPhra0_;
_sPShootPhra_=_sPShootPhra0_;
_sDExtTotT_=_sDExtTotT0_;
_sNExtTotT_=_sNExtTotT0_;
_sPExtTotT_=_sPExtTotT0_;
_sSiExtTotT_=_sSiExtTotT0_;
|
6f1416938c4bf511c62a8986f9129cea62f1aed2
|
5424018aa2443f3ad7688fb27afc67ffb6172f81
|
/wajima/pss/src/pss/std/Logger.hpp
|
7f9674843aafd17614842d7566c838b555c7b48c
|
[] |
no_license
|
Amakata/wajima
|
f9ed0b980df70ca9738bac6d381948e0fa2b318f
|
6c58b04efa0c45eb0a2f21d67b79d5058c13f586
|
refs/heads/master
| 2021-01-17T06:24:37.237575
| 2005-01-09T08:24:04
| 2005-01-09T08:24:04
| null | 0
| 0
| null | null | null | null |
SHIFT_JIS
|
C++
| false
| false
| 1,792
|
hpp
|
Logger.hpp
|
#pragma once
// デバッグビルド用
// デバッグビルドで外部で配布されるプログラムはlog4cxxを使うことで、Apacheへの謝辞を記述する必要がある。
#ifdef _DEBUG
#include <log4cxx/logger.h>
#include <log4cxx/basicconfigurator.h>
#include <log4cxx/propertyconfigurator.h>
#include <log4cxx/helpers/exception.h>
#define LOG4CXX_CONFIGUER(propertyFileName) ::log4cxx::PropertyConfigurator::configure(propertyFileName)
#define LOG4CXX_LOGGER(packageName) ::log4cxx::Logger::getLogger(packageName)
#define LOG4CXX_LOGGER_PTR ::log4cxx::LoggerPtr
#define LOG4CXX_IS_DEBUG_ENABLED(log) (log.isDebugEnabled())
#define LOG4CXX_IS_INFO_ENABLED(log) (log.isInfoEnabled())
#define LOG4CXX_IS_WARN_ENABLED(log) (log.isWarnEnabled())
#define LOG4CXX_IS_ERROR_ENABLED(log) (log.isErrorEnabled())
#define LOG4CXX_IS_FATAL_ENABLED(log) (log.isFatalEnabled())
#endif
// リリースビルド用
// log4cxxを使わないので、Apacheへの謝辞を記述する必要がない
#ifdef NDEBUG
namespace pss {
namespace std {
class NullLogger {
public:
NullLogger() {
}
};
}
}
#define LOG4CXX_CONFIGUER(propertyFileName)
#define LOG4CXX_LOGGER(packageName) ::pss::std::NullLogger()
#define LOG4CXX_LOGGER_PTR ::pss::std::NullLogger
#define LOG4CXX_DEBUG(logger, message)
#define LOG4CXX_INFO(logger, message)
#define LOG4CXX_WARN(logger, message)
#define LOG4CXX_ERROR(logger, message)
#define LOG4CXX_FATAL(logger, message)
#define LOG4CXX_IS_DEBUG_ENABLED(log) (false)
#define LOG4CXX_IS_INFO_ENABLED(log) (false)
#define LOG4CXX_IS_WARN_ENABLED(log) (false)
#define LOG4CXX_IS_ERROR_ENABLED(log) (false)
#define LOG4CXX_IS_FATAL_ENABLED(log) (false)
#endif
|
d29604e9fc07a08427ed2894b2e1a40b8d0e60a7
|
5a97be73f3c6e2987480194a791675259f8d7edf
|
/BZOJ/4423/code.cpp
|
f3988c90aaf840a4e69c5b0cef63135f013b7038
|
[
"MIT"
] |
permissive
|
sjj118/OI-Code
|
1d33d2a7a6eeba2ed16692d663e1b81cdc1341fd
|
964ea6e799d14010f305c7e4aee269d860a781f7
|
refs/heads/master
| 2022-02-21T17:54:14.764880
| 2019-09-05T07:16:27
| 2019-09-05T07:16:27
| 65,370,460
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 927
|
cpp
|
code.cpp
|
#include<iostream>
#include<cstdio>
#define rep(i,x,y) for(register int i=(x);i<=(y);++i)
const int maxn=1550;
using namespace std;
int n,k,ans;
inline int sqr(int x){return x*x;}
inline int get(int x,int y){if(x==0||y==0||x==n||y==n)return 0;return (x-1)*(n-1)+y;}
struct UFS{
int pa[maxn*maxn],rank[maxn*maxn];
void init(){rep(i,0,sqr(n-1))pa[i]=i,rank[i]=0;}
int find(int k){return ((pa[k]==k)?k:(pa[k]=find(pa[k])));}
bool unio(int a,int b){
a=find(a);b=find(b);
if(a==b)return 1;
if(rank[a]>rank[b])swap(a,b);
pa[a]=b;
if(rank[a]==rank[b])++rank[b];
return 0;
}
}set;
int main(){
scanf("%d%d\n",&n,&k);set.init();
rep(i,1,k){
int a,b,e,f;char c,g;
if(ans)scanf("\n%d%d %c %d%d %c",&e,&f,&g,&a,&b,&c);
else scanf("\n%d%d %c %d%d %c",&a,&b,&c,&e,&f,&g);
if(c=='N')e=a,f=b,a=a-1;else e=a,f=b,b=b-1;
ans=set.unio(get(a,b),get(e,f));
if(ans)printf("NIE\n");else printf("TAK\n");
}
return 0;
}
|
670ad4d7ed9054e95c41a68fe9360386f48a913f
|
ef2a7453ca56a420c2da788cace7037192024eba
|
/DirectX/Component/Engine/Text/TextFloat.cpp
|
7f3c6ef1742e3fe7c3b5792aa09cd6e75353eff3
|
[] |
no_license
|
5433D-R32433/FbxSelfParser
|
7055fd9303647cd6e8a445959b1b70e54a0821f0
|
6b6d21670ddaf1c57011164014a6645e4a614a22
|
refs/heads/master
| 2023-08-06T18:36:02.870479
| 2021-09-18T10:14:57
| 2021-09-18T10:14:57
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,249
|
cpp
|
TextFloat.cpp
|
#include "TextFloat.h"
#include "../../../Device/DrawString.h"
#include "../../../Engine/DebugManager/Inspector/ImGuiWrapper.h"
#include "../../../Utility/JsonHelper.h"
TextFloat::TextFloat()
: TextBase()
, mNumber(0.f)
, mDecimalDigits(1)
{
}
TextFloat::~TextFloat() = default;
void TextFloat::lateUpdate() {
if (!mIsActive) {
return;
}
mDrawString->drawNumber(mNumber, mPosition, mScale, mDecimalDigits, mColor, mAlpha, mPivot);
}
void TextFloat::saveAndLoad(rapidjson::Value& inObj, rapidjson::Document::AllocatorType& alloc, FileMode mode) {
TextBase::saveAndLoad(inObj, alloc, mode);
JsonHelper::getSet(mNumber, "number", inObj, alloc, mode);
JsonHelper::getSet(mDecimalDigits, "decimalDigits", inObj, alloc, mode);
}
void TextFloat::drawInspector() {
TextBase::drawInspector();
ImGuiWrapper::dragFloat("number", mNumber);
ImGuiWrapper::sliderInt("decimalDigits", mDecimalDigits, 0, 8);
}
void TextFloat::setNumber(float number) {
mNumber = number;
}
float TextFloat::number() const {
return mNumber;
}
void TextFloat::setDecimalDigits(int decimalDigits) {
mDecimalDigits = decimalDigits;
}
int TextFloat::getDecimalDigits() const {
return mDecimalDigits;
}
|
8715ce0a28b7ce94d67d1f32a91ee88da78c2b12
|
fd6ba461ff7746a5d152576930add08ebfcbb975
|
/tests/CompositeRigidBodyTests.cc
|
2bd5505d1bbcbdc79ac042837981a27116254cf9
|
[
"Zlib"
] |
permissive
|
rbdl/rbdl
|
658d3b07e420642dd9c9b1106daff24fd43e526f
|
cbd9371ce822eeea1f0a880d57f71a4c60bc9b8a
|
refs/heads/master
| 2023-07-06T02:54:35.529726
| 2023-06-25T11:11:42
| 2023-06-25T11:11:42
| 208,891,294
| 449
| 141
|
NOASSERTION
| 2023-09-13T16:09:26
| 2019-09-16T20:24:46
|
C++
|
UTF-8
|
C++
| false
| false
| 7,715
|
cc
|
CompositeRigidBodyTests.cc
|
#include <iostream>
#include "rbdl/Logging.h"
#include "rbdl/Model.h"
#include "rbdl/Dynamics.h"
#include "rbdl_tests.h"
#include "Fixtures.h"
using namespace std;
using namespace RigidBodyDynamics;
using namespace RigidBodyDynamics::Math;
const double TEST_PREC = 1.0e-12;
struct CompositeRigidBodyFixture {
CompositeRigidBodyFixture () {
ClearLogOutput();
model = new Model;
model->gravity = Vector3d (0., -9.81, 0.);
}
~CompositeRigidBodyFixture () {
delete model;
}
Model *model;
};
TEST_CASE_METHOD(CompositeRigidBodyFixture,
__FILE__"_TestCompositeRigidBodyForwardDynamicsFloatingBase","")
{
Body base_body(1., Vector3d (1., 0., 0.), Vector3d (1., 1., 1.));
model->AddBody (0, SpatialTransform(),
Joint (
SpatialVector (0., 0., 0., 1., 0., 0.),
SpatialVector (0., 0., 0., 0., 1., 0.),
SpatialVector (0., 0., 0., 0., 0., 1.),
SpatialVector (0., 0., 1., 0., 0., 0.),
SpatialVector (0., 1., 0., 0., 0., 0.),
SpatialVector (1., 0., 0., 0., 0., 0.)
),
base_body);
// Initialization of the input vectors
VectorNd Q = VectorNd::Constant ((size_t) model->dof_count, 0.);
VectorNd QDot = VectorNd::Constant ((size_t) model->dof_count, 0.);
VectorNd QDDot = VectorNd::Constant ((size_t) model->dof_count, 0.);
VectorNd Tau = VectorNd::Constant ((size_t) model->dof_count, 0.);
VectorNd TauInv = VectorNd::Constant ((size_t) model->dof_count, 0.);
MatrixNd H = MatrixNd::Constant ((size_t) model->dof_count,
(size_t) model->dof_count, 0.);
VectorNd C = VectorNd::Constant ((size_t) model->dof_count, 0.);
VectorNd QDDot_zero = VectorNd::Constant ((size_t) model->dof_count, 0.);
VectorNd QDDot_crba = VectorNd::Constant ((size_t) model->dof_count, 0.);
Q[0] = 1.1;
Q[1] = 1.2;
Q[2] = 1.3;
Q[3] = 0.1;
Q[4] = 0.2;
Q[5] = 0.3;
QDot[0] = 1.1;
QDot[1] = -1.2;
QDot[2] = 1.3;
QDot[3] = -0.1;
QDot[4] = 0.2;
QDot[5] = -0.3;
Tau[0] = 2.1;
Tau[1] = 2.2;
Tau[2] = 2.3;
Tau[3] = 1.1;
Tau[4] = 1.2;
Tau[5] = 1.3;
ForwardDynamics(*model, Q, QDot, Tau, QDDot);
ClearLogOutput();
CompositeRigidBodyAlgorithm (*model, Q, H);
// cout << LogOutput.str() << endl;
InverseDynamics (*model, Q, QDot, QDDot_zero, C);
CHECK (LinSolveGaussElimPivot (H, C * -1. + Tau, QDDot_crba));
CHECK_THAT (QDDot,
AllCloseVector(QDDot_crba, TEST_PREC, TEST_PREC)
);
}
TEST_CASE_METHOD(FloatingBase12DoF,
__FILE__"_TestCRBAFloatingBase12DoF", "") {
MatrixNd H = MatrixNd::Zero ((size_t) model->dof_count,
(size_t) model->dof_count);
VectorNd C = VectorNd::Constant ((size_t) model->dof_count, 0.);
VectorNd QDDot_zero = VectorNd::Constant ((size_t) model->dof_count, 0.);
VectorNd QDDot_crba = VectorNd::Constant ((size_t) model->dof_count, 0.);
Q[ 0] = 1.1;
Q[ 1] = 1.2;
Q[ 2] = 1.3;
Q[ 3] = 0.1;
Q[ 4] = 0.2;
Q[ 5] = 0.3;
Q[ 6] = -1.3;
Q[ 7] = -1.4;
Q[ 8] = -1.5;
Q[ 9] = -0.3;
Q[10] = -0.4;
Q[11] = -0.5;
QDot[ 0] = 1.1;
QDot[ 1] = -1.2;
QDot[ 2] = 1.3;
QDot[ 3] = -0.1;
QDot[ 4] = 0.2;
QDot[ 5] = -0.3;
QDot[ 6] = -1.1;
QDot[ 7] = 1.2;
QDot[ 8] = -1.3;
QDot[ 9] = 0.1;
QDot[10] = -0.2;
QDot[11] = 0.3;
Tau[ 0] = -1.1;
Tau[ 1] = 1.2;
Tau[ 2] = -1.3;
Tau[ 3] = 1.1;
Tau[ 4] = -1.2;
Tau[ 5] = 1.3;
Tau[ 6] = 0.1;
Tau[ 7] = -0.2;
Tau[ 8] = 0.3;
Tau[ 9] = -0.1;
Tau[10] = 0.2;
Tau[11] = -0.3;
ForwardDynamics(*model, Q, QDot, Tau, QDDot);
ClearLogOutput();
CompositeRigidBodyAlgorithm (*model, Q, H);
// cout << LogOutput.str() << endl;
InverseDynamics (*model, Q, QDot, QDDot_zero, C);
CHECK (LinSolveGaussElimPivot (H, C * -1. + Tau, QDDot_crba));
CHECK_THAT (QDDot,
AllCloseVector(QDDot_crba, TEST_PREC, TEST_PREC)
);
}
TEST_CASE_METHOD(FloatingBase12DoF,
__FILE__"_TestCRBAFloatingBase12DoFInverseDynamics", "") {
MatrixNd H_crba = MatrixNd::Zero ((size_t) model->dof_count,
(size_t) model->dof_count);
MatrixNd H_id = MatrixNd::Zero ((size_t) model->dof_count,
(size_t) model->dof_count);
Q[ 0] = 1.1;
Q[ 1] = 1.2;
Q[ 2] = 1.3;
Q[ 3] = 0.1;
Q[ 4] = 0.2;
Q[ 5] = 0.3;
Q[ 6] = -1.3;
Q[ 7] = -1.4;
Q[ 8] = -1.5;
Q[ 9] = -0.3;
Q[10] = -0.4;
Q[11] = -0.5;
QDot.setZero();
REQUIRE (model->dof_count == 12);
UpdateKinematicsCustom (*model, &Q, NULL, NULL);
CompositeRigidBodyAlgorithm (*model, Q, H_crba, false);
VectorNd H_col = VectorNd::Zero (model->dof_count);
VectorNd QDDot_zero = VectorNd::Zero (model->dof_count);
unsigned int i;
for (i = 0; i < model->dof_count; i++) {
// compute each column
VectorNd delta_a = VectorNd::Zero (model->dof_count);
delta_a[i] = 1.;
// cout << delta_a << endl;
// compute ID (model, q, qdot, delta_a)
VectorNd id_delta = VectorNd::Zero (model->dof_count);
InverseDynamics (*model, Q, QDot, delta_a, id_delta);
// compute ID (model, q, qdot, zero)
VectorNd id_zero = VectorNd::Zero (model->dof_count);
InverseDynamics (*model, Q, QDot, QDDot_zero, id_zero);
H_col = id_delta - id_zero;
// cout << "H_col = " << H_col << endl;
H_id.block<12, 1>(0, i) = H_col;
}
// cout << "H (crba) = " << endl << H_crba << endl;
// cout << "H (id) = " << endl << H_id << endl;
CHECK_THAT (H_crba,
AllCloseMatrix(H_id, TEST_PREC, TEST_PREC)
);
}
TEST_CASE_METHOD(FixedBase6DoF,
__FILE__"_TestCRBAFloatingBase12DoFInverseDynamics2", "") {
MatrixNd H_crba = MatrixNd::Zero ((size_t) model->dof_count,
(size_t) model->dof_count);
MatrixNd H_id = MatrixNd::Zero ((size_t) model->dof_count,
(size_t) model->dof_count);
Q[ 0] = 1.1;
Q[ 1] = 1.2;
Q[ 2] = 1.3;
Q[ 3] = 0.1;
Q[ 4] = 0.2;
Q[ 5] = 0.3;
QDot.setZero();
REQUIRE (model->dof_count == 6);
UpdateKinematicsCustom (*model, &Q, NULL, NULL);
CompositeRigidBodyAlgorithm (*model, Q, H_crba, false);
VectorNd H_col = VectorNd::Zero (model->dof_count);
VectorNd QDDot_zero = VectorNd::Zero (model->dof_count);
unsigned int i;
for (i = 0; i < 6; i++) {
// compute each column
VectorNd delta_a = VectorNd::Zero (model->dof_count);
delta_a[i] = 1.;
ClearLogOutput();
// compute ID (model, q, qdot, delta_a)
VectorNd id_delta = VectorNd::Zero (model->dof_count);
InverseDynamics (*model, Q, QDot, delta_a, id_delta);
// compute ID (model, q, qdot, zero)
VectorNd id_zero = VectorNd::Zero (model->dof_count);
InverseDynamics (*model, Q, QDot, QDDot_zero, id_zero);
H_col.setZero();
H_col = id_delta - id_zero;
H_id.block<6, 1>(0, i) = H_col;
}
CHECK_THAT (H_crba,
AllCloseMatrix(H_id, TEST_PREC, TEST_PREC)
);
}
TEST_CASE_METHOD(CompositeRigidBodyFixture,
__FILE__"_TestCompositeRigidBodyForwardDynamicsSpherical", "") {
Body base_body(1., Vector3d (0., 0., 0.), Vector3d (1., 2., 3.));
model->AddBody(0, SpatialTransform(), Joint(JointTypeSpherical), base_body);
VectorNd Q = VectorNd::Constant ((size_t) model->q_size, 0.);
model->SetQuaternion (1, Quaternion(), Q);
MatrixNd H = MatrixNd::Constant ((size_t) model->qdot_size,
(size_t) model->qdot_size, 0.);
CompositeRigidBodyAlgorithm (*model, Q, H, true);
Matrix3d H_ref (
1., 0., 0.,
0., 2., 0.,
0., 0., 3.
);
CHECK_THAT (H_ref,
AllCloseMatrix(H, TEST_PREC, TEST_PREC)
);
}
|
c0a56c0dc08ec96798517d0396346684bffc4f05
|
b527dac4a33ef63662a86837e6deb60fd6f820c8
|
/Robot.hpp
|
784d4729343b73797cb22dfc5ae20afc97ec80ff
|
[] |
no_license
|
jgillespie7/robot-dynamics
|
8bb55e1c00c21813d625ccbd860f6dc2a8a8c329
|
84b3061e8bb4dc1ab060908fd0acb936198bce89
|
refs/heads/master
| 2016-09-06T13:05:38.362566
| 2015-02-01T04:44:42
| 2015-02-01T04:44:42
| 30,125,019
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 349
|
hpp
|
Robot.hpp
|
#ifndef ROBOT_HPP_INCLUDED
#define ROBOT_HPP_INCLUDED
#include <vector>
#include "Motor.hpp"
class Robot{
public:
Robot(double);
void addMotor(Motor);
void acceleration(double, double, double, double, double, double, double&, double&, double&);
private:
double mass;
std::vector<Motor> motors;
};
#endif // ROBOT_HPP_INCLUDED
|
bc0b59cf51081a2dd5506e43c1a02a42fe0dfa20
|
c03ab9cee4862e304a0f0cf3d0285e41ee66cc59
|
/problem1.cpp
|
92797a91754440abc355b752c5c0ba69c36b76ce
|
[] |
no_license
|
TashaSekularac/CodeU
|
2b57d332af17e099fea7ead4989f881731047944
|
a069d71750700c984495eb3e4e30dfc3cb7d235c
|
refs/heads/master
| 2021-01-21T15:13:23.043343
| 2017-05-19T18:15:25
| 2017-05-19T18:15:25
| 91,833,213
| 0
| 0
| null | 2017-05-28T16:08:09
| 2017-05-19T18:12:51
|
C++
|
UTF-8
|
C++
| false
| false
| 1,093
|
cpp
|
problem1.cpp
|
#include <stdio.h>
#include <string>
#include <iostream>
using namespace std;
bool permutation ( string a, string b)
{
if(a.length()!=b.length())
return false;
int number[26];
for(int i=0; i<26; i++)
number[i]=0;
for(int i=0; i<a.length(); i++)
if(a[i]<='Z' && a[i]>='A')
number[a[i]-'A']++;
else
if(a[i]<='z' && a[i]>='a')
number[a[i]-'a']++;
else
return false;
for(int i=0; i<b.length(); i++)
{
if(b[i]<='Z' && b[i]>='A')
{
number[b[i]-'A']--;
if(number[b[i]-'A']<0)
return false;
}
else
if(b[i]<='z' && b[i]>='a')
{
number[b[i]-'a']--;
if(number[b[i]-'a']<0)
return false;
}
else
return false;
}
return true;
}
int main()
{
string a,b;
cin>>a>>b;
if(permutation(a, b))
cout<<"True"<<endl;
else
cout<<"False"<<endl;
return 0;
}
|
8f46beb82dd9593cd30a2e5036f9d194ac2033e2
|
5ae1c58c00542138200dd4b26b42af076ad0321e
|
/17. Robot Bounded In Circle.cpp
|
3dba04446a59180f4dd69d7ae2a720e5fb6452dd
|
[] |
no_license
|
psoni207/September-LeetCoding-Challenge
|
18e49583af86ab0c145accbda488799d858e7f33
|
b8648ccc2d241756f973c642dfd3bbf25fe6ac69
|
refs/heads/master
| 2022-12-25T19:29:56.174348
| 2020-10-02T17:29:15
| 2020-10-02T17:29:15
| 300,682,948
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 680
|
cpp
|
17. Robot Bounded In Circle.cpp
|
class Solution {
public:
bool isRobotBounded(string instructions) {
int pos[2] = {0, 0};
int dir[2] = {0, 1};
for(char inst: instructions){
if(inst == 'G'){
pos[0] += dir[0];
pos[1] += dir[1];
}else if(inst == 'L'){
swap(dir[0], dir[1]);
dir[0] = -dir[0];
}else if(inst == 'R'){
swap(dir[0], dir[1]);
dir[1] = -dir[1];
}
}
if( (pos[0] == 0 && pos[1] == 0) || (dir[0] != 0 || dir[1] != 1) ){
return true;
}
return false;
}
};
|
1940d60c39de9d87926fc21d82545229bcb83815
|
6d0626153ea3c0b75b0b1d314d4f69d8e77917b2
|
/boj_lec/sw_basic/part4_graph_bfs/1261.cpp
|
bfc9da361a97c78e386ce2310792e1b5c764617f
|
[] |
no_license
|
JeongP/algorithm
|
020c53be5a0401ce9c8270963474cea9f7b91e1c
|
18fdaeb8cda6739f6f0b285107d3433418a61fb4
|
refs/heads/master
| 2021-07-14T08:35:54.158475
| 2020-09-02T16:59:10
| 2020-09-02T16:59:10
| 201,872,150
| 0
| 0
| null | 2019-08-12T06:57:44
| 2019-08-12T06:37:32
| null |
UTF-8
|
C++
| false
| false
| 1,075
|
cpp
|
1261.cpp
|
#include <iostream>
#include <vector>
using namespace std;
#define MAX 100
#define INF 987654321
int n,m;
int map[MAX][MAX];
int map_crush_cnt[MAX][MAX];
int isVisited[MAX][MAX] = {0,};
int side[4][2] = {{-1,0},{0,1},{1,0},{0,-1}};
void dfs(int depth, int row, int col, int crashed_num) {
if(map_crush_cnt[row][col] <= crashed_num) return;
else map_crush_cnt[row][col] = crashed_num;
if(row == n-1 && col == m-1) return;
for(int i=0;i<4;i++) {
int nrow = row + side[i][0];
int ncol = col + side[i][1];
if(0<=nrow && nrow < n && 0<= ncol && ncol < m && !isVisited[nrow][ncol]) {
isVisited[nrow][ncol] = 1;
dfs(depth+1, nrow, ncol, crashed_num + (map[nrow][ncol] ? 1:0));
isVisited[nrow][ncol] = 0;
}
}
}
int main () {
cin >> n >> m;
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
cin >> map[i][j];
map_crush_cnt[i][j] = INF;
}
}
isVisited[0][0] = 1;
dfs(0,0,0,0);
cout << map_crush_cnt[n-1][m-1];
return 0;
}
|
35b60abe645cd98ea33b412bd2dcffb52ba98721
|
37d2d7feb7d6fe592450dd5e36326e1ac397ef19
|
/_MODEL_FOLDERS_/jetPack/jetPackBindings/jetPackBindings_NORM.cpp
|
f1c53597b323e343ee69b4d3ca3cc1c183498912
|
[] |
no_license
|
marcclintdion/a7_MARC_ANIMATION_B
|
51424721f07059ee02f63bba1542e4069af5cd41
|
22eff173fea023439cb0644be2b1d25fc38c2f5b
|
refs/heads/master
| 2021-01-10T07:11:59.521520
| 2015-09-26T12:42:49
| 2015-09-26T12:42:49
| 43,204,989
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 12,204
|
cpp
|
jetPackBindings_NORM.cpp
|
GLfloat jetPackBindings_NORM[] =
{
//number of vertices = 384
-0.126327, -1.82145e-009, -0.983778,
0.084218, 0, -0.989186,
-0.126327, -9.10725e-010, -0.983778,
-0.126327, -9.10725e-010, -0.983778,
0.084218, 0, -0.989186,
0.168436, 1.17251e-008, -0.978371,
0.126327, -8.79379e-009, 0.983778,
-0.168436, 1.2143e-009, 0.978371,
-0.084218, 0, 0.989186,
0.126327, -8.79379e-009, 0.983778,
-0.084218, 0, 0.989186,
0.126327, -1.75876e-008, 0.983778,
-0.252654, -1.82145e-009, -0.967557,
-0.126327, -9.10725e-010, -0.983778,
-0.252654, 0, -0.967557,
-0.252654, -1.82145e-009, -0.967557,
-0.126327, -1.82145e-009, -0.983778,
-0.126327, -9.10725e-010, -0.983778,
-0.168436, 1.2143e-009, 0.978371,
-0.252654, 1.82145e-009, 0.967557,
-0.084218, 0, 0.989186,
-0.168436, 1.2143e-009, 0.978371,
-0.252654, 3.6429e-009, 0.967557,
-0.252654, 1.82145e-009, 0.967557,
0.168436, 1.17251e-008, -0.978371,
0.252654, 1.75876e-008, -0.967557,
0.252654, 3.51752e-008, -0.967557,
0.084218, 0, -0.989186,
0.252654, 1.75876e-008, -0.967557,
0.168436, 1.17251e-008, -0.978371,
0.252654, -1.75876e-008, 0.967557,
0.126327, -8.79379e-009, 0.983778,
0.126327, -1.75876e-008, 0.983778,
0.252654, 0, 0.967557,
0.126327, -8.79379e-009, 0.983778,
0.252654, -1.75876e-008, 0.967557,
0, 0, 1,
0, 0, 1,
0, 0, 1,
0, 0, 1,
0, 0, 1,
0, 0, 1,
0, 0, -1,
0, 0, -1,
0, 0, -1,
0, 0, -1,
0, 0, -1,
0, 0, -1,
0, 0.801047, -0.598602,
0, 0.801047, -0.598602,
0, 0.801047, -0.598602,
0, 0.801047, -0.598602,
0, 0.801047, -0.598602,
0, 0.801047, -0.598602,
0, -0.790485, -0.612481,
0, -0.790485, -0.612481,
0, -0.790485, -0.612481,
0, -0.790485, -0.612481,
0, -0.790485, -0.612481,
0, -0.790485, -0.612481,
0, -0.790485, 0.612481,
0, -0.790485, 0.612481,
0, -0.790485, 0.612481,
7.77748e-010, -0.790485, 0.612481,
7.77748e-010, -0.790485, 0.612481,
7.77748e-010, -0.790485, 0.612481,
6.59346e-009, 0.801047, 0.598602,
6.59346e-009, 0.801047, 0.598602,
6.59346e-009, 0.801047, 0.598602,
0, 0.801047, 0.598602,
0, 0.801047, 0.598602,
0, 0.801047, 0.598602,
-0.498609, 0.836729, 5.96046e-008,
-0.526349, 0.820895, -0.221557,
-0.526349, 0.820895, 5.21541e-008,
-0.498609, 0.836729, 5.96046e-008,
-0.248643, 0.828088, -0.449838,
-0.470868, 0.852563, -0.226758,
-0.539188, -0.811027, 5.21541e-008,
-0.539188, -0.811027, -0.226961,
-0.511241, -0.827491, 5.21541e-008,
-0.483293, -0.843954, -0.232742,
-0.254989, -0.818522, -0.460843,
-0.511241, -0.827491, 5.21541e-008,
-0.248643, 0.828088, -0.449838,
-0.149297, 0.806733, -0.571745,
-0.149297, 0.806733, -0.571745,
-0.248643, 0.828088, -0.449838,
-0.125765, 0.824968, -0.55101,
-0.125765, 0.824968, -0.55101,
-0.15281, -0.796362, -0.585197,
-0.15281, -0.796362, -0.585197,
-0.254989, -0.818522, -0.460843,
-0.128864, -0.815251, -0.564589,
-0.128864, -0.815251, -0.564589,
-0.254989, -0.818522, -0.460843,
-0.248643, 0.828088, 0.449838,
-0.149298, 0.806733, 0.571745,
-0.149298, 0.806733, 0.571745,
-0.125764, 0.824968, 0.55101,
-0.248643, 0.828088, 0.449838,
-0.125764, 0.824968, 0.55101,
-0.128864, -0.815251, 0.564589,
-0.254989, -0.818522, 0.460843,
-0.128864, -0.815251, 0.564589,
-0.15281, -0.796362, 0.585198,
-0.15281, -0.796362, 0.585198,
-0.254989, -0.818522, 0.460843,
-0.498609, 0.836729, 5.96046e-008,
-0.526349, 0.820895, 5.21541e-008,
-0.526349, 0.820895, 0.221557,
-0.248643, 0.828088, 0.449838,
-0.498609, 0.836729, 5.96046e-008,
-0.470868, 0.852563, 0.226758,
-0.483293, -0.843955, 0.232742,
-0.511241, -0.827491, 5.21541e-008,
-0.254989, -0.818522, 0.460843,
-0.539188, -0.811027, 0.226962,
-0.539188, -0.811027, 5.21541e-008,
-0.511241, -0.827491, 5.21541e-008,
0.532928, -0.815883, -0.224326,
0.532928, -0.815884, 5.21541e-008,
0.505494, -0.831751, 4.84288e-008,
0.252958, -0.820625, -0.45884,
0.478059, -0.847619, -0.230221,
0.505494, -0.831751, 4.84288e-008,
0.246623, 0.830109, -0.447839,
0.492878, 0.840827, 4.84288e-008,
0.465666, 0.856076, -0.224253,
0.520091, 0.825578, -0.218923,
0.492878, 0.840827, 4.84288e-008,
0.520091, 0.825578, 4.47035e-008,
0.152313, -0.797852, -0.583295,
0.152313, -0.797852, -0.583295,
0.252958, -0.820625, -0.45884,
0.128502, -0.816403, -0.563004,
0.128502, -0.816403, -0.563004,
0.252958, -0.820625, -0.45884,
0.148799, 0.808173, -0.569838,
0.246623, 0.830109, -0.447839,
0.148799, 0.808173, -0.569838,
0.125403, 0.826078, -0.549426,
0.246623, 0.830109, -0.447839,
0.125403, 0.826078, -0.549426,
0.152313, -0.797852, 0.583295,
0.152313, -0.797852, 0.583295,
0.252958, -0.820625, 0.45884,
0.252958, -0.820625, 0.45884,
0.128502, -0.816403, 0.563004,
0.128502, -0.816403, 0.563004,
0.246623, 0.830109, 0.447839,
0.125403, 0.826078, 0.549426,
0.125403, 0.826078, 0.549426,
0.148799, 0.808173, 0.569838,
0.246623, 0.830109, 0.447839,
0.148799, 0.808173, 0.569838,
0.505494, -0.831751, 4.84288e-008,
0.478059, -0.847619, 0.230221,
0.252958, -0.820625, 0.45884,
0.532928, -0.815884, 5.21541e-008,
0.532928, -0.815884, 0.224326,
0.505494, -0.831751, 4.84288e-008,
0.520091, 0.825578, 4.47035e-008,
0.492878, 0.840827, 4.84288e-008,
0.520091, 0.825578, 0.218923,
0.492878, 0.840827, 4.84288e-008,
0.246623, 0.830109, 0.447839,
0.465666, 0.856076, 0.224253,
-0.921675, 0, -0.387962,
-0.921675, 0, -0.387962,
-0.921675, 0, -0.387962,
-0.921675, -9.53186e-009, -0.387962,
-0.921675, -9.53186e-009, -0.387962,
-0.921675, -9.53186e-009, -0.387962,
-0.921675, 0, 0.387962,
-0.921675, 0, 0.387962,
-0.921675, 0, 0.387962,
-0.921675, 3.75666e-008, 0.387962,
-0.921675, 3.75666e-008, 0.387962,
-0.921675, 3.75666e-008, 0.387962,
0.921675, 1.6995e-008, -0.387962,
0.921675, 1.6995e-008, -0.387962,
0.921675, 1.6995e-008, -0.387962,
0.921675, 0, -0.387962,
0.921675, 0, -0.387962,
0.921675, 0, -0.387962,
0.921675, -1.01207e-009, 0.387963,
0.921675, -1.01207e-009, 0.387963,
0.921675, -1.01207e-009, 0.387963,
0.921675, 0, 0.387963,
0.921675, 0, 0.387963,
0.921675, 0, 0.387963,
-0.126327, -9.57678e-010, -0.983778,
0.084218, 0, -0.989186,
-0.126327, -4.78839e-010, -0.983778,
-0.126327, -4.78839e-010, -0.983778,
0.084218, 0, -0.989186,
0.168436, 1.23009e-008, -0.978371,
0.126327, -9.22567e-009, 0.983778,
-0.168436, 6.38452e-010, 0.978371,
-0.084218, 0, 0.989186,
0.126327, -9.22567e-009, 0.983778,
-0.084218, 0, 0.989186,
0.126327, -1.84513e-008, 0.983778,
-0.252654, -9.57678e-010, -0.967557,
-0.126327, -4.78839e-010, -0.983778,
-0.252654, 0, -0.967557,
-0.252654, -9.57678e-010, -0.967557,
-0.126327, -9.57678e-010, -0.983778,
-0.126327, -4.78839e-010, -0.983778,
-0.168436, 6.38452e-010, 0.978371,
-0.252654, 9.57678e-010, 0.967557,
-0.084218, 0, 0.989186,
-0.168436, 6.38452e-010, 0.978371,
-0.252654, 1.91536e-009, 0.967557,
-0.252654, 9.57678e-010, 0.967557,
0.168436, 1.23009e-008, -0.978371,
0.252654, 1.84513e-008, -0.967557,
0.252654, 3.69027e-008, -0.967557,
0.084218, 0, -0.989186,
0.252654, 1.84513e-008, -0.967557,
0.168436, 1.23009e-008, -0.978371,
0.252654, -1.84513e-008, 0.967557,
0.126327, -9.22567e-009, 0.983778,
0.126327, -1.84513e-008, 0.983778,
0.252654, 0, 0.967557,
0.126327, -9.22567e-009, 0.983778,
0.252654, -1.84513e-008, 0.967557,
0, 0, 1,
0, 0, 1,
0, 0, 1,
0, 0, 1,
0, 0, 1,
0, 0, 1,
0, 0, -1,
0, 0, -1,
0, 0, -1,
0, 0, -1,
0, 0, -1,
0, 0, -1,
0, 0.801046, -0.598602,
0, 0.801046, -0.598602,
0, 0.801046, -0.598602,
0, 0.801046, -0.598602,
0, 0.801046, -0.598602,
0, 0.801046, -0.598602,
0, -0.790485, -0.612481,
0, -0.790485, -0.612481,
0, -0.790485, -0.612481,
0, -0.790485, -0.612481,
0, -0.790485, -0.612481,
0, -0.790485, -0.612481,
0, -0.790486, 0.612481,
0, -0.790486, 0.612481,
0, -0.790486, 0.612481,
8.02121e-009, -0.790486, 0.612481,
8.02121e-009, -0.790486, 0.612481,
8.02121e-009, -0.790486, 0.612481,
4.63477e-009, 0.801047, 0.598602,
4.63477e-009, 0.801047, 0.598602,
4.63477e-009, 0.801047, 0.598602,
0, 0.801047, 0.598602,
0, 0.801047, 0.598602,
0, 0.801047, 0.598602,
-0.498609, 0.836729, 4.47035e-008,
-0.52635, 0.820895, -0.221557,
-0.52635, 0.820895, 4.47035e-008,
-0.498609, 0.836729, 4.47035e-008,
-0.248644, 0.828088, -0.449838,
-0.470868, 0.852563, -0.226758,
-0.539188, -0.811027, 5.21541e-008,
-0.539188, -0.811027, -0.226961,
-0.51124, -0.827491, 4.47035e-008,
-0.483293, -0.843955, -0.232741,
-0.254989, -0.818523, -0.460842,
-0.51124, -0.827491, 4.47035e-008,
-0.248644, 0.828088, -0.449838,
-0.149298, 0.806733, -0.571745,
-0.149298, 0.806733, -0.571745,
-0.248644, 0.828088, -0.449838,
-0.125765, 0.824967, -0.55101,
-0.125765, 0.824967, -0.55101,
-0.15281, -0.796363, -0.585197,
-0.15281, -0.796363, -0.585197,
-0.254989, -0.818523, -0.460842,
-0.128864, -0.815251, -0.564589,
-0.128864, -0.815251, -0.564589,
-0.254989, -0.818523, -0.460842,
-0.248643, 0.828088, 0.449838,
-0.149298, 0.806732, 0.571746,
-0.149298, 0.806732, 0.571746,
-0.125764, 0.824967, 0.55101,
-0.248643, 0.828088, 0.449838,
-0.125764, 0.824967, 0.55101,
-0.128864, -0.815251, 0.564588,
-0.254989, -0.818523, 0.460842,
-0.128864, -0.815251, 0.564588,
-0.15281, -0.796363, 0.585197,
-0.15281, -0.796363, 0.585197,
-0.254989, -0.818523, 0.460842,
-0.498609, 0.836729, 4.47035e-008,
-0.52635, 0.820895, 4.47035e-008,
-0.52635, 0.820895, 0.221557,
-0.248643, 0.828088, 0.449838,
-0.498609, 0.836729, 4.47035e-008,
-0.470868, 0.852563, 0.226758,
-0.483293, -0.843955, 0.232742,
-0.51124, -0.827491, 4.47035e-008,
-0.254989, -0.818523, 0.460842,
-0.539188, -0.811027, 0.226961,
-0.539188, -0.811027, 5.21541e-008,
-0.51124, -0.827491, 4.47035e-008,
0.532927, -0.815884, -0.224326,
0.532927, -0.815884, 5.21541e-008,
0.505493, -0.831751, 4.84288e-008,
0.252958, -0.820625, -0.458839,
0.478059, -0.847619, -0.230221,
0.505493, -0.831751, 4.84288e-008,
0.246623, 0.830109, -0.447839,
0.492879, 0.840827, 4.84288e-008,
0.465666, 0.856076, -0.224253,
0.520091, 0.825577, -0.218923,
0.492879, 0.840827, 4.84288e-008,
0.520091, 0.825577, 5.21541e-008,
0.152313, -0.797853, -0.583294,
0.152313, -0.797853, -0.583294,
0.252958, -0.820625, -0.458839,
0.128502, -0.816403, -0.563003,
0.128502, -0.816403, -0.563003,
0.252958, -0.820625, -0.458839,
0.148799, 0.808173, -0.569838,
0.246623, 0.830109, -0.447839,
0.148799, 0.808173, -0.569838,
0.125403, 0.826078, -0.549426,
0.246623, 0.830109, -0.447839,
0.125403, 0.826078, -0.549426,
0.152313, -0.797852, 0.583294,
0.152313, -0.797852, 0.583294,
0.252958, -0.820625, 0.45884,
0.252958, -0.820625, 0.45884,
0.128502, -0.816403, 0.563003,
0.128502, -0.816403, 0.563003,
0.246623, 0.830109, 0.447839,
0.125403, 0.826078, 0.549426,
0.125403, 0.826078, 0.549426,
0.148799, 0.808173, 0.569838,
0.246623, 0.830109, 0.447839,
0.148799, 0.808173, 0.569838,
0.505493, -0.831751, 4.84288e-008,
0.478059, -0.847619, 0.230221,
0.252958, -0.820625, 0.45884,
0.532927, -0.815884, 5.21541e-008,
0.532927, -0.815884, 0.224326,
0.505493, -0.831751, 4.84288e-008,
0.520091, 0.825577, 5.21541e-008,
0.492879, 0.840827, 4.84288e-008,
0.520091, 0.825577, 0.218923,
0.492879, 0.840827, 4.84288e-008,
0.246623, 0.830109, 0.447839,
0.465666, 0.856076, 0.224253,
-0.921675, 0, -0.387962,
-0.921675, 0, -0.387962,
-0.921675, 0, -0.387962,
-0.921675, -9.53185e-009, -0.387962,
-0.921675, -9.53185e-009, -0.387962,
-0.921675, -9.53185e-009, -0.387962,
-0.921675, 0, 0.387962,
-0.921675, 0, 0.387962,
-0.921675, 0, 0.387962,
-0.921675, 3.75666e-008, 0.387962,
-0.921675, 3.75666e-008, 0.387962,
-0.921675, 3.75666e-008, 0.387962,
0.921675, 1.6995e-008, -0.387962,
0.921675, 1.6995e-008, -0.387962,
0.921675, 1.6995e-008, -0.387962,
0.921675, 0, -0.387962,
0.921675, 0, -0.387962,
0.921675, 0, -0.387962,
0.921675, -1.38227e-008, 0.387963,
0.921675, -1.38227e-008, 0.387963,
0.921675, -1.38227e-008, 0.387963,
0.921675, 0, 0.387963,
0.921675, 0, 0.387963,
0.921675, 0, 0.387963,
};
|
8e89e8453228922659d11f54b8dc27134aed1ff7
|
63c7c7e07cf23aa82b6a61a516174da63504f095
|
/西北大学新生寒假训练(1)/test.cpp
|
974183d6e93aa15ad9da0ad339eed5c19c178c7b
|
[] |
no_license
|
Linfanty/Code-in-Freshman
|
3b174b6fab510dc1aa214d760f050ca1618afc8d
|
b60b99f520c4740c6b8306880680a610f054f403
|
refs/heads/master
| 2021-01-24T12:37:29.255747
| 2018-02-27T15:10:29
| 2018-02-27T15:10:29
| 123,144,148
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 74
|
cpp
|
test.cpp
|
#include<stdio.h>
int main()
{
for(int i=0;i<5;++i)
printf("%d",i);
}
|
7d8d12c6952d60c804b2f3c7a16fa4496a03ac27
|
3e70f9a3fc23925e4db47f0d2627c6d2e7b26bfa
|
/ch15_Object-Oriented_Programming/exercise_15_03.cc
|
96012e450981fe90733ebc951026e098981721f7
|
[] |
no_license
|
PYChih/CppPrimer
|
77e7445ae75026c624a6469674b62043eb54db74
|
3aa479b993970883252cacddc9d65a274aee1992
|
refs/heads/main
| 2023-03-04T03:44:42.817956
| 2021-02-18T02:23:39
| 2021-02-18T02:23:39
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 442
|
cc
|
exercise_15_03.cc
|
// Exercise 15_03
// Define your own versions of the Quote class
// and the print_total function.
// Quote_15_03.cc Quote_15_03.h
// g++ -c exercise_15_03.cc Quote_15_03.cc
// g++ exercise_15_03.o Quote_15_03.cc && ./a.out
#include "Quote_15_03.h"
using std::cout;
using std::endl;
int main() {
Quote base("999-999", 10);
Bulk_quote derived("999-999", 10, 100, 0.1);
print_total(cout, base, 100);
print_total(cout, derived, 100);
}
|
55496c558af614cca5a18b8bceaec5d63513f146
|
9bfe274dbdf7283328baf524682746fb2ef3a57c
|
/srcs/GlfwWindow.hpp
|
bc4d3f3c2225c60029d96da681583992a21bf96d
|
[] |
no_license
|
Chr0nos/opencl
|
4fce189c1646c95a788949c70dd73c7d46f50164
|
365b94c0a39d06732390e6f2412353b10a620df8
|
refs/heads/master
| 2020-03-14T03:34:14.164740
| 2018-05-22T21:59:34
| 2018-05-22T21:59:34
| 131,422,908
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,519
|
hpp
|
GlfwWindow.hpp
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* GlfwWindow.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: snicolet <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/04/28 17:57:54 by snicolet #+# #+# */
/* Updated: 2018/04/28 18:14:31 by snicolet ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef GLFW_WINDOW_HPP
# define GLFW_WINDOW_HPP
# include <GL/glew.h>
# include <GLFW/glfw3.h>
# include "Vbo.hpp"
# include <string>
# define FLAG_NONE 0
# define FLAG_GLFW_INIT_OK (1u << 0)
# define FLAG_GLEW_INIT_OK (1u << 1)
class GlfwWindow
{
public:
GlfwWindow(std::string title, unsigned int w, unsigned int h);
~GlfwWindow(void);
bool Init(void);
bool Show(void);
void Render(void);
protected:
void RenderFrame(void);
private:
bool InitGlew(void);
unsigned int _flags;
unsigned int _w;
unsigned int _h;
std::string _title;
GLFWwindow *_window;
Vbo *_vbo;
};
#endif
|
41a697674048a181487986d74197d10b177f9126
|
f8c2108705d77ca24213d73240f64fe93564c111
|
/util/QXmlRpcServer.cpp
|
0e48eb25400bd7a19bdbc497f22cc55c2664529e
|
[] |
no_license
|
MikePanMP/QDMVC
|
23e2adfeacf6657c44776dc210b150136387f3a2
|
960a61f91489e7b102dfb2db8b08b556c258d7ea
|
refs/heads/master
| 2020-06-04T21:43:54.809223
| 2014-04-29T19:00:13
| 2014-04-29T19:00:13
| 19,265,541
| 2
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,662
|
cpp
|
QXmlRpcServer.cpp
|
#include "QXmlRpcServer.h"
#include "QXmlRpcServerConnection.h"
void QXmlRpcServer::addMethod(QString method,
QObject* responseObject, const char* responseSlot) {
objectMap[method] = responseObject;
slotMap[method] = responseSlot;
}
void QXmlRpcServer::removeMethod(QString method) {
objectMap.remove(method);
slotMap.remove(method);
}
void QXmlRpcServer::getMethod(QString method, QObject **responseObject, const char **responseSlot) {
if(!objectMap.contains(method)) {
*responseObject = NULL;
*responseSlot = NULL;
return;
}
*responseObject = objectMap[method];
*responseSlot = slotMap[method];
}
void QXmlRpcServer::listen(quint16 port) {
//bool ret = server.listen(QHostAddress::Any, port);
bool ret = server.listen(QHostAddress::Any, port);
qDebug() << "listen on" << port << ", result" << ret;
}
QXmlRpcServer::QXmlRpcServer(QObject* parent)
: QObject(parent), allowedAddresses(NULL) {
connect(&server, SIGNAL(newConnection()), this, SLOT(newConnection()));
}
QXmlRpcServer::~QXmlRpcServer() {
}
void QXmlRpcServer::newConnection() {
qDebug() << "newConnection called";
QTcpSocket *connection = server.nextPendingConnection();
if (!this->allowedAddresses ||
this->allowedAddresses->isEmpty() ||
this->allowedAddresses->contains(connection->peerAddress())) {
QXmlRpcServerConnection *client = new QXmlRpcServerConnection(connection, this);
connect(client, SIGNAL(getMethod(QString, QObject **, const char**)),
this, SLOT(getMethod(QString, QObject **, const char**)));
} else {
qWarning() << "Rejected connection attempt from" << connection->peerAddress().toString();
connection->disconnectFromHost();
}
}
|
f1d7fa7157a8eae4cd0a007de34286d0a74ab259
|
39b003b15d9cdf42483f43ee59293a935cd26ef1
|
/F238_PlatFormSignedNew/F238_PlatFormSigned/multicommu/scpiport_internet.h
|
9260f167014df97c097adc47a48ca25b6f003d2c
|
[] |
no_license
|
hanqianjin/kang
|
f16fb3835ecd850a3a86bb93f0679c878c82acab
|
cc40e6be18287a7a3269e50371f2850cd03bfb5d
|
refs/heads/master
| 2021-06-25T23:47:54.108574
| 2020-11-20T02:46:25
| 2020-11-20T02:46:25
| 142,751,390
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,056
|
h
|
scpiport_internet.h
|
#ifndef SCPIPORT_INTERNET_H
#define SCPIPORT_INTERNET_H
#include "scpiport.h"
#include <QTcpServer>
#include <QTcpSocket>
#include <QSettings>
#include <QByteArray>
#include <QDateTime>
#ifdef Q_OS_LINUX
#include <netinet/tcp.h>
#endif
#define SETTING_TCPSERVER_PORT "SYS/NETWORK/TCPSERVERPORT"
class ScpiPort_internet : public ScpiPort_common
{
Q_OBJECT
public:
ScpiPort_internet(qint32 *port = NULL,QObject *parent = 0);
explicit ScpiPort_internet(QObject *parent = 0);
void * getUserContext(){
return (void *)m_tcpSocketConnected;
}
void closeConn();
void lostConn();
void closeBitConn();
void buildBitConn();
private:
int set_tcp_keepAlive(int fd, int start, int interval, int count);
public slots:
void slotAcceptConnection();
void slotReadTCPConnected();
void slotCloseTCPConnection();
private:
QTcpSocket *m_tcpSocketConnected;
QSettings m_setting;
qint32 *m_port;
QTcpServer m_tcpServer;
QByteArray m_cmdBuffer;
};
#endif // SCPIPORT_INTERNET_H
|
354b74244955b9bed46cfd6b97c97f5f76e9a15e
|
d26a306d0dc07a6a239e0f1e87e83e8d96712681
|
/CANDY_12345/main.cpp
|
63c8210d9195b25d1716cf5fb81cc5a3c51ec268
|
[] |
no_license
|
umar-07/Competitive-Programming-questions-with-solutions
|
e08f8dbbebed7ab48c658c3f0ead19baf966f140
|
39353b923638dff2021923a8ea2f426cd94d2204
|
refs/heads/main
| 2023-05-19T03:05:48.669470
| 2021-06-16T18:36:22
| 2021-06-16T18:36:22
| 377,588,251
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 612
|
cpp
|
main.cpp
|
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
int f=0;
while(n--)
{
string s;
cin >> s;
int l = s.size();
for(int i=0; i<l-1; i++)
{
if((s[i]=='c')&&(s[i+1]=='h'))
{
f++;
break;
}
else if((s[i]=='h')&&(s[i+1]=='e'))
{
f++;
break;
}
else if((s[i]=='e')&&(s[i+1]=='f'))
{
f++;
break;
}
}
}
return 0;
}
|
7fe7567fc401854055cd2743cda5fe1fc56436b8
|
150bb3e9b3f35639322e303f22a9771947169504
|
/LEETCODE/EASY/DYNAMIC_PROGRAMMING/best_time_to_buy_and_sell_stock.cpp
|
c614fbf20a5413e6dc0b68b72c4c4ff6645514f5
|
[] |
no_license
|
aman212yadav/COMPETETIVE_PROGRAMMING
|
d3bb29933e506f42cdd499884c7f3be774aeaefa
|
f17119090705774069a3a9d2ae20d86d14b970e6
|
refs/heads/master
| 2020-11-27T21:33:32.194204
| 2020-02-06T15:38:14
| 2020-02-06T15:38:14
| 229,609,056
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 466
|
cpp
|
best_time_to_buy_and_sell_stock.cpp
|
// problem link - https://leetcode.com/problems/best-time-to-buy-and-sell-stock
// time complexity - O(N)
// space complexity - O(1)
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n=prices.size();
if(!n)
return 0;
int mi=INT_MAX,max_profit=0;
for(int i=0;i<n;i++){
mi=min(mi,prices[i]);
max_profit=max(max_profit,prices[i]-mi);
}
return max_profit;
}
};
|
fc03ca726d9fd0abd9227eaf93f6f3a0ec8afb2d
|
93deffee902a42052d9f5fb01e516becafe45b34
|
/spoj/classical/ADASEQEN.cpp
|
ea7456756887af7e95d825e3e0e7cb1b41fc498c
|
[] |
no_license
|
kobortor/Competitive-Programming
|
1aca670bc37ea6254eeabbe33e1ee016174551cc
|
69197e664a71a492cb5b0311a9f7b00cf0b1ccba
|
refs/heads/master
| 2023-06-25T05:04:42.492243
| 2023-06-16T18:28:42
| 2023-06-16T18:28:42
| 95,998,328
| 10
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 696
|
cpp
|
ADASEQEN.cpp
|
#include<bits/stdc++.h>
using namespace std;
#define allof(x) (x).begin(), (x).end()
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
const int MAXN = 2005;
int N, M;
int val[26];
int dp[MAXN][MAXN];
int main(){
cin.tie(0);
cin.sync_with_stdio(0);
cin >> N >> M;
for(int a = 0; a < 26; a++){
cin >> val[a];
}
string A, B;
cin >> A >> B;
for(int a = 1; a <= N; a++){
for(int b = 1; b <= M; b++){
dp[a][b] = max(dp[a-1][b], dp[a][b-1]);
if(A[a-1] == B[b-1]){
dp[a][b] = max(dp[a][b], dp[a-1][b-1] + val[A[a-1] - 'a']);
}
}
}
cout << dp[N][M];
}
|
3beb8b500708d8b3b27690d3c33a2c2b43fdeb91
|
fc4eeda20f26ae4112bfd12f6837fdb7339be183
|
/os/windows/XConManager/InputDialog.h
|
5e8b22cd81eca0646927182faee8b3c2a63cc198
|
[] |
no_license
|
swhors/simpson_sip_library
|
8b7a64220a46e10059b020ba5c51f54208d9659e
|
87d69dc0cdea49e6662e2c768697a6f58bc80f57
|
refs/heads/main
| 2023-03-14T00:05:12.604722
| 2021-03-01T07:47:17
| 2021-03-01T07:47:17
| 343,330,488
| 0
| 0
| null | null | null | null |
UHC
|
C++
| false
| false
| 635
|
h
|
InputDialog.h
|
#pragma once
#include "afxwin.h"
// CInputDialog 대화 상자입니다.
class CInputDialog : public CDialog
{
DECLARE_DYNAMIC(CInputDialog)
public:
CInputDialog(CWnd* pParent = NULL); // 표준 생성자입니다.
virtual ~CInputDialog();
// 대화 상자 데이터입니다.
enum { IDD = IDD_DLG_INPUT };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 지원입니다.
DECLARE_MESSAGE_MAP()
public:
CEdit m_strUInput;
afx_msg void OnBnClickedOk();
// 사용자가 입력한 값을 갖는 버퍼
CString m_strUInputVar;
virtual BOOL OnInitDialog();
afx_msg void OnBnClickedCancel();
};
|
f2590a7b18f0b13db89f6f993212fc2eff7f264d
|
d974dfccd9b408b4263252ff4fc066668c7b9721
|
/ViscoelasticFluid/moc/moc_MainWindow.cpp
|
2c7d00bf0413b45fe355501bc59d7c16048acb88
|
[] |
no_license
|
Han-S-Dance/ase-2019-20-Han-S-Dance
|
b895ea28072535aeb7023f4e215a9a475350f803
|
805b0b35bff9457e00a35b78821c4c0575f76644
|
refs/heads/master
| 2022-03-31T13:42:12.989687
| 2020-01-31T04:41:52
| 2020-01-31T04:41:52
| 218,768,787
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,146
|
cpp
|
moc_MainWindow.cpp
|
/****************************************************************************
** Meta object code from reading C++ file 'MainWindow.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.3)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../include/MainWindow.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'MainWindow.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.12.3. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_MainWindow_t {
QByteArrayData data[26];
char stringdata0[247];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_MainWindow_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_MainWindow_t qt_meta_stringdata_MainWindow = {
{
QT_MOC_LITERAL(0, 0, 10), // "MainWindow"
QT_MOC_LITERAL(1, 11, 11), // "setFluidity"
QT_MOC_LITERAL(2, 23, 0), // ""
QT_MOC_LITERAL(3, 24, 2), // "_f"
QT_MOC_LITERAL(4, 27, 13), // "setPlasticity"
QT_MOC_LITERAL(5, 41, 2), // "_p"
QT_MOC_LITERAL(6, 44, 13), // "setElasticity"
QT_MOC_LITERAL(7, 58, 2), // "_e"
QT_MOC_LITERAL(8, 61, 10), // "setDensity"
QT_MOC_LITERAL(9, 72, 2), // "_d"
QT_MOC_LITERAL(10, 75, 11), // "setPressure"
QT_MOC_LITERAL(11, 87, 12), // "scaleGravity"
QT_MOC_LITERAL(12, 100, 2), // "_g"
QT_MOC_LITERAL(13, 103, 20), // "setInteractionRadius"
QT_MOC_LITERAL(14, 124, 2), // "_i"
QT_MOC_LITERAL(15, 127, 15), // "toggleViscosity"
QT_MOC_LITERAL(16, 143, 2), // "_v"
QT_MOC_LITERAL(17, 146, 13), // "toggleSprings"
QT_MOC_LITERAL(18, 160, 2), // "_s"
QT_MOC_LITERAL(19, 163, 16), // "toggleRelaxation"
QT_MOC_LITERAL(20, 180, 2), // "_r"
QT_MOC_LITERAL(21, 183, 14), // "stopSimulation"
QT_MOC_LITERAL(22, 198, 17), // "setParticleNumber"
QT_MOC_LITERAL(23, 216, 9), // "setSpread"
QT_MOC_LITERAL(24, 226, 11), // "setVelocity"
QT_MOC_LITERAL(25, 238, 8) // "generate"
},
"MainWindow\0setFluidity\0\0_f\0setPlasticity\0"
"_p\0setElasticity\0_e\0setDensity\0_d\0"
"setPressure\0scaleGravity\0_g\0"
"setInteractionRadius\0_i\0toggleViscosity\0"
"_v\0toggleSprings\0_s\0toggleRelaxation\0"
"_r\0stopSimulation\0setParticleNumber\0"
"setSpread\0setVelocity\0generate"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_MainWindow[] = {
// content:
8, // revision
0, // classname
0, 0, // classinfo
15, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags
1, 1, 89, 2, 0x08 /* Private */,
4, 1, 92, 2, 0x08 /* Private */,
6, 1, 95, 2, 0x08 /* Private */,
8, 1, 98, 2, 0x08 /* Private */,
10, 1, 101, 2, 0x08 /* Private */,
11, 1, 104, 2, 0x08 /* Private */,
13, 1, 107, 2, 0x08 /* Private */,
15, 1, 110, 2, 0x08 /* Private */,
17, 1, 113, 2, 0x08 /* Private */,
19, 1, 116, 2, 0x08 /* Private */,
21, 1, 119, 2, 0x08 /* Private */,
22, 1, 122, 2, 0x08 /* Private */,
23, 1, 125, 2, 0x08 /* Private */,
24, 1, 128, 2, 0x08 /* Private */,
25, 1, 131, 2, 0x08 /* Private */,
// slots: parameters
QMetaType::Void, QMetaType::Double, 3,
QMetaType::Void, QMetaType::Double, 5,
QMetaType::Void, QMetaType::Double, 7,
QMetaType::Void, QMetaType::Double, 9,
QMetaType::Void, QMetaType::Double, 5,
QMetaType::Void, QMetaType::Double, 12,
QMetaType::Void, QMetaType::Double, 14,
QMetaType::Void, QMetaType::Bool, 16,
QMetaType::Void, QMetaType::Bool, 18,
QMetaType::Void, QMetaType::Bool, 20,
QMetaType::Void, QMetaType::Bool, 20,
QMetaType::Void, QMetaType::Int, 5,
QMetaType::Void, QMetaType::Double, 18,
QMetaType::Void, QMetaType::Bool, 16,
QMetaType::Void, QMetaType::Bool, 12,
0 // eod
};
void MainWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
auto *_t = static_cast<MainWindow *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->setFluidity((*reinterpret_cast< double(*)>(_a[1]))); break;
case 1: _t->setPlasticity((*reinterpret_cast< double(*)>(_a[1]))); break;
case 2: _t->setElasticity((*reinterpret_cast< double(*)>(_a[1]))); break;
case 3: _t->setDensity((*reinterpret_cast< double(*)>(_a[1]))); break;
case 4: _t->setPressure((*reinterpret_cast< double(*)>(_a[1]))); break;
case 5: _t->scaleGravity((*reinterpret_cast< double(*)>(_a[1]))); break;
case 6: _t->setInteractionRadius((*reinterpret_cast< double(*)>(_a[1]))); break;
case 7: _t->toggleViscosity((*reinterpret_cast< bool(*)>(_a[1]))); break;
case 8: _t->toggleSprings((*reinterpret_cast< bool(*)>(_a[1]))); break;
case 9: _t->toggleRelaxation((*reinterpret_cast< bool(*)>(_a[1]))); break;
case 10: _t->stopSimulation((*reinterpret_cast< bool(*)>(_a[1]))); break;
case 11: _t->setParticleNumber((*reinterpret_cast< int(*)>(_a[1]))); break;
case 12: _t->setSpread((*reinterpret_cast< double(*)>(_a[1]))); break;
case 13: _t->setVelocity((*reinterpret_cast< bool(*)>(_a[1]))); break;
case 14: _t->generate((*reinterpret_cast< bool(*)>(_a[1]))); break;
default: ;
}
}
}
QT_INIT_METAOBJECT const QMetaObject MainWindow::staticMetaObject = { {
&QMainWindow::staticMetaObject,
qt_meta_stringdata_MainWindow.data,
qt_meta_data_MainWindow,
qt_static_metacall,
nullptr,
nullptr
} };
const QMetaObject *MainWindow::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *MainWindow::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_MainWindow.stringdata0))
return static_cast<void*>(this);
return QMainWindow::qt_metacast(_clname);
}
int MainWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QMainWindow::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 15)
qt_static_metacall(this, _c, _id, _a);
_id -= 15;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 15)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 15;
}
return _id;
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
|
d09952346aef3cc564d4e83c1615b7fda0e910bc
|
8841125320ae48c3ca992eda300c77bedfd33ffb
|
/leetcode/025. Reverse Nodes In K Group.cpp
|
ff0e61179a8cf907a52d979a998aedb4614a290e
|
[] |
no_license
|
zjkang/algorithm
|
ed75e46c6cf97afb0603219be8408d31f7e87feb
|
c913af73144907cc272ced5dd90aedbfc96d3cd0
|
refs/heads/master
| 2021-01-18T23:08:46.194755
| 2017-09-12T01:13:49
| 2017-09-12T01:13:49
| 35,187,672
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,668
|
cpp
|
025. Reverse Nodes In K Group.cpp
|
/*
Author: Zhengjian Kang
Email: zhengjian.kang@nyu.edu
Problem: Reverse Nodes in K-Group
Source: https://leetcode.com/problems/reverse-nodes-in-k-group/
Tags: {Linked List}
Company: Microsoft, Facebook
Notes:
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For example,
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
int getLength(ListNode *head) {
int length = 0;
while (head) {
head = head->next;
length++;
}
return length;
}
ListNode *reverseKGroup(ListNode *head, int k) {
if (k <= 1) return head;
int reverseTimes = getLength(head) / k;
ListNode dummy(0);
dummy.next = head;
head = &dummy;
ListNode *cur = head->next;
while (reverseTimes--) {
for (int i = 0; i < k - 1; ++i) {
ListNode *move = cur->next;
cur->next = move->next;
move->next = head->next;
head->next = move;
}
head = cur;
cur = head->next;
}
return dummy.next;
}
};
|
c93bb82b097eb6f80b9394e854bee907a9ae6b87
|
8e426af05c7402cb474acbec9785e4604cbf8bd6
|
/SDL2_GAME/src/TextureManager.h
|
2c601f3dc02521e43957815cdcb774d19ae1578c
|
[] |
no_license
|
WinRobotics/udacity-CppND-Capstone-BrickBreaker
|
d1c2a1806b5d3a3a924561185836db1d51e5a710
|
ccabbc6377b72e7ca0caabb3b053dd31c8d5aed9
|
refs/heads/main
| 2023-08-04T14:22:07.443045
| 2021-09-11T14:46:04
| 2021-09-11T14:46:04
| 404,017,951
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 375
|
h
|
TextureManager.h
|
#ifndef TextureManager_H
#define TextureManager_H
#include "SDL.h"
#include "SDL_image.h"
#include "game.h"
#include <iostream>
#include <unistd.h>
class TextureManager
{
private:
public:
static SDL_Texture* LoadTexture(std::string fileName);
static void Draw(SDL_Texture* Tex,SDL_Rect Src,SDL_Rect Dest);
TextureManager();
~TextureManager();
};
#endif
|
37260c3602f5ace22d9fcf9c5d740f19831fc861
|
cdd55f2ef133bf0519988d325255af61672bb008
|
/Board.hpp
|
9460961c0db506378568741e22fdf3d21709e19d
|
[
"MIT"
] |
permissive
|
atharjamel/massage-board
|
e7ba7f9bb17c02f0a782154a0c7da41a239de1ff
|
fa8a3fefe8599ee678c072f8978cb503efb40ace
|
refs/heads/main
| 2023-05-29T16:12:39.787659
| 2021-06-16T00:30:06
| 2021-06-16T00:30:06
| 377,326,574
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 694
|
hpp
|
Board.hpp
|
#include <string>
#include "Direction.hpp"
#include <map>
#include <iostream>
#include <climits>
using namespace std;
namespace ariel
{
class Board
{
private:
map<unsigned int, map<unsigned int, char>> board;
unsigned int Max_Row,Min_Row,Max_Column,Min_Column;
public:
Board()
{
Max_Column = 0;
Max_Row = 0;
Min_Row = 0;
Min_Row = 0;
}
~Board(){};
void post(unsigned int row, unsigned int col, Direction direction, string const &str);
string read(unsigned int row, unsigned int col, Direction direction, unsigned int number);
void show();
};
}
|
6a5177348e27f530d470c6b78796b038af282a10
|
865ca7b071c88c41a9c8fe2cccf286fd7540f959
|
/cpp/PermMissingElem1.cpp
|
cfea675b32c027d644421e5ee6cbc5fd6cfe3f34
|
[] |
no_license
|
beetai/codility
|
d760a4515522a9db242f383dd5b66b515fd7053d
|
68afec9d1e551d31ae84f14fc32f1bdb0b22f6db
|
refs/heads/master
| 2020-09-03T10:02:01.036756
| 2019-11-06T05:14:34
| 2019-11-06T05:14:34
| 219,441,111
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,372
|
cpp
|
PermMissingElem1.cpp
|
/* FIRST DRAFT FOR SOLUTION TO PermMissingElem: DOES NOT WORK */
#include <iostream>
#include <algorithm>
#include <vector>
int findMissingNum(std::vector<int> &A) {
if (A) {
return 0;
}
int halfInd = A.size() / 2;
std::vector<int> split_lo(A.begin(), A.begin() + halfInd);
std::vector<int> split_hi(A.begin() + halfInd, A.end());
std::cout << *split_hi.begin() << std::endl;
std::cout << *(split_hi.end() - 1) << std::endl;
std::cout << *split_lo.begin() << std::endl;
std::cout << *(split_lo.end() - 1) << std::endl;
int hi_first = *split_hi.begin();
int hi_last = *(split_hi.end()-1);
int lo_first = *split_lo.begin();
int lo_last = *(split_lo.end()-1);
std::cout << split_hi.size() << std::endl;
std::cout << split_lo.size() << std::endl;
if ((hi_last - hi_first) == split_hi.size()) {
return findMissingNum(split_hi);
} else if ((lo_last - lo_first) == split_lo.size()) {
return findMissingNum(split_lo);
} else {
return hi_last + 1;
}
}
int solution(std::vector<int> &A) {
sort(A.begin(), A.end());
auto A_it = A.begin();
while (A_it != A.end()) {
// std::cout << *A_it << std::endl;
A_it++;
}
findMissingNum(A);
return 0;
}
int main() {
std::vector<int> A{2,3,1,5};
std::cout << solution(A) << std::endl;
}
|
bb010f847ee26248403e96bb557210cb65d99eef
|
388f9257dbac02262585dab814d4369e5ca30b29
|
/include/notifier_pool.h
|
7354572ffdcfb1439e752d27725e63ee0c740aea
|
[
"MIT"
] |
permissive
|
Phantomape/paxos
|
5356c6316f81db63f82b2d0d3f1fc08177ea2e14
|
d88ab88fa5b6c7d74b508580729c4dea4de6f180
|
refs/heads/master
| 2020-03-12T03:43:21.281708
| 2018-07-13T23:40:47
| 2018-07-13T23:40:47
| 130,429,909
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 472
|
h
|
notifier_pool.h
|
#pragma once
#include <map>
#include <mutex>
namespace paxos {
class Notifier {
public:
Notifier();
~Notifier();
int Init();
void SendNotify(const int ret);
void WaitNotify(int & ret);
private:
int m_iPipeFD[2];
};
class NotifierPool
{
public:
NotifierPool();
~NotifierPool();
int GetNotifier(const uint64_t iID, Notifier *& poNotifier);
private:
std::map<uint64_t, Notifier *> m_mapPool;
std::mutex m_oMutex;
};
}
|
86f978fc2c6ae29edf0ffa32bdf0e4e510c30815
|
e6a054dd17ea83265b678711b50ecb7083501e8d
|
/Project-CardMatch/Challenger.h
|
e0a41925ef7531c5a7a7f5e134e80c5ae5e9b602
|
[] |
no_license
|
DoryeongPark/cpp_tutorials
|
69258f544b6d2377c5856d22e2856048907229e3
|
7a22c24069b5a0afd7870dec1b0fde6d1d1ec28f
|
refs/heads/master
| 2021-01-22T18:24:13.297868
| 2016-09-22T11:34:42
| 2016-09-22T11:34:42
| 68,352,390
| 1
| 0
| null | null | null | null |
UHC
|
C++
| false
| false
| 1,288
|
h
|
Challenger.h
|
#ifndef Challenger_H
#define Challenger_H
#include "Common.h"
#include "Player.h"
#include "Game.h"
/*노드*/
typedef struct tagNode Node;
typedef struct tagNode {
int value;
int x, y;//좌표
Node* next;
}Node;
typedef Node* Np;
/*해시테이블*/
typedef struct HashTable {
Np* table;
int tableSize;
}HashTable;
class Challenger : public Player
{
HashTable *ht;
int check;//첫번쨰값넣기에서 하나만있는거 찾을때
int HashArray[LAST_CARD_NUMBER + 1];//값이 얼마나있는지
int xyArray[BOARD_SIZE][BOARD_SIZE];//좌표배열
int CardArr[LAST_CARD_NUMBER];//찾은 매치카드
Point p1;//첫번째꺼 저장할변수
int same;//같은값확인변수
int gru;//처음꺼값확인변수
public :
HashTable* CreateHash(int size);//해시테이블생성
Np CreateNode(int value,int x,int y);//노드만들기
void Data_set(HashTable* ht, int x,int y, int value);//데이터 넣기
bool FindData(HashTable *ht,int x, int y, int value);//데이터 찾기(있으면트루)
void Pop(HashTable *ht,Point p,int value);
Challenger();
int SameValue();//같은값이있나
Point inputFirst();
Point inputSecond();
bool checkboardRange(int x, int y);
void checkCardInfo(Point point, int card);
void matchedCard(Point p1, Point p2, int card);
};
#endif
|
b874ac3fc3bba2783c94ef54f1f238b861f78674
|
d1f8551b344cb9cacb0af765dea52a51872741f6
|
/src/euclideanMst/memoGfk/wspdFilter.h
|
9166a7bd500c6da917cbf9a6a721199bb87f4502
|
[
"MIT"
] |
permissive
|
Oliver-desu/pargeo
|
f5988b679d52078edb45679dba938ab49261840d
|
166f3c4766968ddbebc0f8d90e2c780ed96f0e89
|
refs/heads/main
| 2023-07-23T13:30:38.345645
| 2021-09-04T15:46:09
| 2021-09-04T15:46:09
| 403,062,667
| 0
| 0
|
MIT
| 2021-09-04T13:24:57
| 2021-09-04T13:24:56
| null |
UTF-8
|
C++
| false
| false
| 8,071
|
h
|
wspdFilter.h
|
// This code is part of the project "Fast Parallel Algorithms for Euclidean
// Minimum Spanning Tree and Hierarchical Spatial Clustering"
// Copyright (c) 2021 Yiqiu Wang, Shangdi Yu, Yan Gu, Julian Shun
//
// 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.
#pragma once
#include <atomic>
#include <tuple>
#include <limits>
#include "pargeo/wspd.h"
#include "pargeo/bccp.h"
#include "pargeo/parBuf.h"
#include "pargeo/getTime.h"
#include "parlay/utilities.h"
namespace pargeo {
namespace emstInternal {
template<class nodeT, class UF>
struct rhoUpdateSerial {
using floatT = double;
floatT rho;
floatT beta;
UF *uf;
rhoUpdateSerial(floatT betaa, UF *uff) :
beta(betaa), uf(uff) {
rho = std::numeric_limits<floatT>::max();}
void run(nodeT *u, nodeT *v) {
floatT myDist = nodeDistance(u, v);
if (myDist < rho) rho = myDist;
}
bool moveon(nodeT *u, nodeT *v) {
if (u->hasId() && u->getId() == v->getId()) return false; // filtering todo
if (u->size() + v->size() <= beta) return false; // not in E_u, not considered for rho
if (nodeDistance(u, v) >= rho) return false; // no subsequent finds can update rho
return true;
}
bool start(nodeT *u) {
if (u->size() > beta) {
return true;
} else {
return false;// if node size < beta, so would children
}
}
floatT getRho() { return rho;}
bool wellSeparated(nodeT* u, nodeT* v, floatT s) {return geomWellSeparated(u, v, s);}
};
template<class nodeT, class UF>
struct wspGetSerial {
using floatT = double;
using bcpT = std::tuple<typename nodeT::objT*,
typename nodeT::objT*,
typename nodeT::objT::floatT>;
floatT rhoLo;
floatT rhoHi;
floatT beta;
sequence<bcpT> out;
nodeT *tree;
UF *uf;
wspGetSerial(floatT betaa, floatT rhoLoo, floatT rhoHii, nodeT *treee, UF *uff) :
beta(betaa), rhoLo(rhoLoo), rhoHi(rhoHii), tree(treee), uf(uff) {
out = sequence<bcpT>();
}
void run(nodeT *u, nodeT *v) {
auto bcp = bccp(u, v);
if (u->size() + v->size() <= beta &&
std::get<2>(bcp) >= rhoLo &&
std::get<2>(bcp) < rhoHi) {
out.push_back(bcp);
}
}
bool moveon(nodeT *u, nodeT *v) {
if (u->hasId() && u->getId() == v->getId()) {return false;} // todo need to add id to tree nodes
if (nodeDistance(u, v) >= rhoHi) return false; // too separated to be considered
if (nodeFarDistance(u, v) < rhoLo) return false; // too close to be considered
return true;
}
bool start(nodeT *u) {
if (u->diag() >= rhoLo) {
return true;
} else {
return false;
}
}
bool wellSeparated(nodeT* u, nodeT* v, floatT s) {return geomWellSeparated(u, v, s);}
sequence<bcpT> collect() { return out; };
};
template <class nodeT, class UF>
sequence<std::tuple<typename nodeT::objT*,
typename nodeT::objT*,
typename nodeT::objT::floatT>>
filterWspdSerial(double t_beta,
double t_rho_lo,
double& t_rho_hi,
nodeT *t_kdTree,
UF *t_mst) {
using floatT = double;
using objT = typename nodeT::objT;
using bcpT = std::tuple<objT*, objT*, floatT>;
auto myRho = rhoUpdateSerial<nodeT, UF>(t_beta, t_mst);
pargeo::computeWspdSerial<nodeT, rhoUpdateSerial<nodeT, UF>>(t_kdTree, &myRho);
auto mySplitter = wspGetSerial<nodeT, UF>(t_beta, t_rho_lo, myRho.getRho(), t_kdTree, t_mst);
pargeo::computeWspdSerial<nodeT, wspGetSerial<nodeT, UF>>(t_kdTree, &mySplitter);
t_rho_hi = myRho.getRho();
return mySplitter.collect();
}
template<class nodeT, class UF>
struct rhoUpdateParallel {
using floatT = double;
std::atomic<floatT> rho;
floatT beta;
UF *uf;
rhoUpdateParallel(floatT betaa, UF *uff) :
beta(betaa), uf(uff) {
rho = std::numeric_limits<floatT>::max();}
void run(nodeT *u, nodeT *v) {
floatT myDist = nodeDistance(u, v);
parlay::write_min(&rho, myDist, std::less<floatT>()); //check
}
bool moveon(nodeT *u, nodeT *v) {
if (u->hasId() && u->getId() == v->getId()) return false; // filtering
if (u->size()+v->size() <= beta) return false; // not in E_u, not considered for rho
if (nodeDistance(u, v) >= rho) return false; // no subsequent finds can update rho
return true;
}
bool start(nodeT *u) {
if (u->size() > beta) {
return true;
} else {
return false;// if node size < beta, so would children
}
}
floatT getRho() { return rho;}
bool wellSeparated(nodeT* u, nodeT* v, floatT s) {return geomWellSeparated(u, v, s);}
};
template<class nodeT, class UF>
struct wspGetParallel {
using floatT = double;
using bcpT = std::tuple<typename nodeT::objT*,
typename nodeT::objT*,
typename nodeT::objT::floatT>;
using bufT = parBuf<bcpT>;
floatT rhoLo;
floatT rhoHi;
floatT beta;
nodeT *tree;
UF *uf;
bufT **out;
wspGetParallel(floatT betaa, floatT rhoLoo, floatT rhoHii, nodeT *treee, UF *uff) :
beta(betaa), rhoLo(rhoLoo), rhoHi(rhoHii), tree(treee), uf(uff) {
size_t procs = num_workers();
out = (bufT**) malloc(sizeof(bufT*)*procs);
parallel_for(0, procs, [&](size_t p) {
out[p] = new bufT(tree->size()/procs);
});
}
~wspGetParallel() {
size_t procs = num_workers();
parallel_for(0, procs, [&](size_t p) {
delete out[p];});
free(out);
}
sequence<bcpT> collect() {
int procs = num_workers();
return parBufCollect<bcpT>(out, procs);
}
void run(nodeT *u, nodeT *v) {
auto bcp = bccp(u, v);
if (u->size() + v->size() <= beta &&
std::get<2>(bcp) >= rhoLo &&
std::get<2>(bcp) < rhoHi) {
auto tmp = out[worker_id()]->increment();
get<0>(*tmp) = get<0>(bcp);
get<1>(*tmp) = get<1>(bcp);
get<2>(*tmp) = get<2>(bcp);
}
}
bool moveon(nodeT *u, nodeT *v) {
if (u->hasId() && u->getId() == v->getId()) {return false;}
if (nodeDistance(u, v) >= rhoHi) return false; // too separated to be considered
if (nodeFarDistance(u, v) < rhoLo) return false; // too close to be considered, bug!!
return true;
}
bool start(nodeT *u) {
if (u->diag() >= rhoLo) {
return true;
} else {
return false;
}
}
bool wellSeparated(nodeT* u, nodeT* v, floatT s) {return geomWellSeparated(u, v, s);}
};
template <class nodeT, class UF>
sequence<std::tuple<typename nodeT::objT*,
typename nodeT::objT*,
typename nodeT::objT::floatT>>
filterWspdParallel(double t_beta,
double t_rho_lo,
double& t_rho_hi,
nodeT *t_kdTree,
UF *t_mst) {
using floatT = double;
using objT = typename nodeT::objT;
using bcpT = std::tuple<objT*, objT*, floatT>;
auto myRho = rhoUpdateParallel<nodeT, UF>(t_beta, t_mst);
pargeo::computeWspdParallel<nodeT, rhoUpdateParallel<nodeT, UF>>(t_kdTree, &myRho);
auto mySplitter = wspGetParallel<nodeT, UF>(t_beta, t_rho_lo, myRho.getRho(), t_kdTree, t_mst);
pargeo::computeWspdParallel<nodeT, wspGetParallel<nodeT, UF>>(t_kdTree, &mySplitter);
t_rho_hi = myRho.getRho();
return mySplitter.collect();
}
} // End namespace emstInternal
} // End namespace pargeo
|
e95bf675c1f74130828e51561c949d98f6a27542
|
d59e36022692822e5bef9f28d5322a32976bbbd3
|
/RPG-控制台版/EnemyMgr.cpp
|
6e2f1f3d723cfcd775b60b0c9a9a2f0e5d89ced4
|
[] |
no_license
|
TingXuanR/RPG-Game-In-Cmd
|
e4781dfb6ec8bbc60b642d07b97ada714e7bdf18
|
b6a4e7491d8790b022fd4e36073a474b846f0706
|
refs/heads/main
| 2023-03-20T10:18:07.125358
| 2021-03-14T15:23:12
| 2021-03-14T15:23:12
| 347,670,442
| 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 4,861
|
cpp
|
EnemyMgr.cpp
|
#include "stdafx.h"
#include "EnemyMgr.h"
#include "ConfigMgr.h"
#include "GameMgr.h"
CEnemyMgr::CEnemyMgr() :m_nTimer(0)
{
}
CEnemyMgr::~CEnemyMgr()
{
SAFE_DEL_VEC(m_pVecData);
}
void CEnemyMgr::createEnemies(int mapId)
{
vector<SEnemyDt*> pData = CConfigMgr::getInstance()->getEnemyDtMgr()->getAllData();
int* BirthPoint = new int[6];
BirthPoint = CGameMgr::getInstance()->getGameMap()->getLevelDt()->arrEnemyBirth;
int* StepLength = new int[3];
StepLength = CGameMgr::getInstance()->getGameMap()->getLevelDt()->arrEnemyStep;
int* Dirs = CGameMgr::getInstance()->getGameMap()->getLevelDt()->arrEnemyDir;
for (SEnemyDt* enemyDt : pData)
{
if (enemyDt->MapID == mapId)
{
for (int i = 0; i < 3; i++) // 创建三个敌人
{
CEnemy* enemy = new CEnemy(enemyDt);
enemy->setNum(i);
if (i == 0)
{
enemy->setRow(BirthPoint[0]);
enemy->setCol(BirthPoint[1]);
}
else
{
enemy->setRow(BirthPoint[i * 2]);
enemy->setCol(BirthPoint[i * 2 + 1]);
}
enemy->setDir(Dirs[i]);
enemy->setRowBk(enemy->getRow());
enemy->setColBk(enemy->getCol());
enemy->setBirthRow(enemy->getRow());
enemy->setBirthCol(enemy->getCol());
enemy->setStep(StepLength[i]);
enemy->setStepBk(StepLength[i]);
m_pVecData.push_back(enemy);
}
}
}
}
CEnemy* CEnemyMgr::getEnemy(int row, int col)
{
for (CEnemy* enemy : m_pVecData)
{
if (enemy->getRow() == row && enemy->getCol() == col)
{
return enemy;
}
}
return nullptr;
}
void CEnemyMgr::deleteEnemy(int row, int col)
{
for (int i = 0; i < m_pVecData.size(); i++)
{
if (m_pVecData[i]->getRow() == row && m_pVecData[i]->getCol() == col)
{
m_pVecData.erase(m_pVecData.begin() + i);
}
}
}
int CEnemyMgr::getDataSize()
{
return m_pVecData.size();
}
void CEnemyMgr::release()
{
for (int i = m_pVecData.size() - 1; i >= 0; i--)
{
m_pVecData.erase(m_pVecData.begin() + i);
}
}
void reverseDir(CEnemy* pEnemy)
{
if (pEnemy->getDir() == 0) // 0-Up, 1-Down, 2-Left, 3-Right
{
pEnemy->setDir(1);
}
else if (pEnemy->getDir() == 1)
{
pEnemy->setDir(0);
}
else if (pEnemy->getDir() == 2)
{
pEnemy->setDir(3);
}
else if (pEnemy->getDir() == 3)
{
pEnemy->setDir(2);
}
//pEnemy->setRow(pEnemy->getRowBk());
//pEnemy->setCol(pEnemy->getColBk());
}
void check(CEnemy* pEnemy)
{
/*int nMapRowSize = CGameMgr::getInstance()->getGameMap()->getLevelDt()->nRowSize;
int nMapColSize = CGameMgr::getInstance()->getGameMap()->getLevelDt()->nColSize;*/
//if (pEnemy->getRow() == 0 || pEnemy->getRow() == nMapRowSize - 1) //撞墙
//{
// reverseDir(pEnemy);
//}
//else if (pEnemy->getCol() == 0 || pEnemy->getCol() == nMapColSize - 1)
//{
// reverseDir(pEnemy);
//}
if (pEnemy->getStep() == 0)
{
pEnemy->setStep(pEnemy->getStepBk());
reverseDir(pEnemy);
}
else if (pEnemy->getRow() == pEnemy->getBirthRow() && pEnemy->getCol() == pEnemy->getBirthCol()) //回出生点
{
pEnemy->setStep(pEnemy->getStepBk());
reverseDir(pEnemy);
}
}
void CEnemyMgr::update()
{
m_nTimer++;
if (m_pVecData.size() && m_nTimer >= m_pVecData[0]->getSpeed())
{
for (int i = 0; i < m_pVecData.size(); i++)
{
/*m_pVecData[i]->setRowBk(m_pVecData[i]->getRow());
m_pVecData[i]->setColBk(m_pVecData[i]->getCol());*/
if (m_pVecData[i]->getDir() == 0)
{
m_pVecData[i]->moveUp();
}
else if (m_pVecData[i]->getDir() == 1)
{
m_pVecData[i]->moveDown();
}
else if (m_pVecData[i]->getDir() == 2)
{
m_pVecData[i]->moveLeft();
}
else if (m_pVecData[i]->getDir() == 3)
{
m_pVecData[i]->moveRight();
}
//if (m_pVecData[i]->getNum() == 0) // 第一个向右走,碰障碍物后反方向
//{
// if (m_pVecData[i]->getDir() == 1)
// {
// m_pVecData[i]->moveRight();
// }
// else
// {
// m_pVecData[i]->moveLeft();
// }
//
//}
//else if (m_pVecData[i]->getNum() == 1) //第二个向下走
//{
// if (m_pVecData[i]->getDir() == 1)
// {
// m_pVecData[i]->moveDown();
// }
// else
// {
// m_pVecData[i]->moveUp();
// }
//}
//else if (m_pVecData[i]->getNum() == 2) //第三个向上走
//{
// if (m_pVecData[i]->getDir() == 1)
// {
// m_pVecData[i]->moveUp();
// }
// else
// {
// m_pVecData[i]->moveDown();
// }
//}
m_pVecData[i]->setStep(m_pVecData[i]->getStep() - 1); // 每走一步,可走的步数便减1
check(m_pVecData[i]);
}
m_nTimer = 0;
}
}
//template <class T>
//void CEnemyMgr::checkEnemyCollision(T* t)
//{
// for (int i = 0; i < m_pVecData.size(); i++)
// {
// if (m_pVecData[i]->getRow == t->getRow() && m_pVecData[i] == t->getCol())
// {
// if (m_pVecData[i]->getDir == 0)
// {
// m_pVecData[i]->setDir(1);
// }
// else if (m_pVecData[i]->getDir == 1)
// {
// m_pVecData[i]->setDir(0);
// }
// }
// }
//}
|
d306285b00abb6c2e72059efee88a659c2c24562
|
8cd51b4885680c073566f16236cd68d3f4296399
|
/src/controls/QskComboBoxSkinlet.h
|
a2579e4bdb17e493b514731b50bc14d04fd53d54
|
[
"BSD-3-Clause"
] |
permissive
|
uwerat/qskinny
|
0e0c6552afa020382bfa08453a5636b19ae8ff49
|
bf2c2b981e3a6ea1187826645da4fab75723222c
|
refs/heads/master
| 2023-08-21T16:27:56.371179
| 2023-08-10T17:54:06
| 2023-08-10T17:54:06
| 97,966,439
| 1,074
| 226
|
BSD-3-Clause
| 2023-08-10T17:12:01
| 2017-07-21T16:16:18
|
C++
|
UTF-8
|
C++
| false
| false
| 1,127
|
h
|
QskComboBoxSkinlet.h
|
/******************************************************************************
* QSkinny - Copyright (C) 2016 Uwe Rathmann
* SPDX-License-Identifier: BSD-3-Clause
*****************************************************************************/
#ifndef QSK_COMBO_BOX_SKINLET_H
#define QSK_COMBO_BOX_SKINLET_H
#include "QskSkinlet.h"
class QskComboBox;
class QSK_EXPORT QskComboBoxSkinlet : public QskSkinlet
{
Q_GADGET
using Inherited = QskSkinlet;
public:
enum NodeRole
{
PanelRole,
IconRole,
TextRole,
StatusIndicatorRole,
RoleCount
};
Q_INVOKABLE QskComboBoxSkinlet( QskSkin* = nullptr );
~QskComboBoxSkinlet() override;
QRectF subControlRect( const QskSkinnable*,
const QRectF&, QskAspect::Subcontrol ) const override;
QSizeF sizeHint( const QskSkinnable*,
Qt::SizeHint, const QSizeF& ) const override;
protected:
QSGNode* updateSubNode( const QskSkinnable*,
quint8 nodeRole, QSGNode* ) const override;
private:
QSGNode* updateTextNode( const QskComboBox*, QSGNode* ) const;
};
#endif
|
74811f82de35895020a2d419b4c46b9ee27c2bf0
|
ea02017f2a5bd6ac68791993083b249da60b2602
|
/src/LevelModel.cpp
|
1d187268b388640eecbf972ff004b39d3c3ab662
|
[] |
no_license
|
aarribas/WizardsAndOrcs
|
fc7fbdb888f17f1f677ea0ddbd650eeff9ba0aff
|
c8e7e1c9ae0f6f1f852ac5f7f80fe8ccc902fdba
|
refs/heads/master
| 2020-05-19T07:38:34.978921
| 2013-09-20T18:41:33
| 2013-09-20T18:41:33
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,215
|
cpp
|
LevelModel.cpp
|
#include "LevelModel.h"
#include <iostream>
LevelModel::LevelModel()
{
}
LevelModel::~LevelModel()
{
//clean up of static objects
std::map<int, StaticObjectModel* >::iterator staticObjectModelIt = m_staticObjectModels.begin();
while(staticObjectModelIt != m_staticObjectModels.end())
{
delete staticObjectModelIt->second;
m_staticObjectModels.erase(staticObjectModelIt++);
}
//clean up of dynamacic objects
std::map<int, DynamicObjectModel* >::iterator dynamicObjectModelIt = m_dynamicObjectModels.begin();
while(dynamicObjectModelIt != m_dynamicObjectModels.end())
{
delete dynamicObjectModelIt->second;
m_dynamicObjectModels.erase(dynamicObjectModelIt++);
}
//clean up of enemies
std::map<int, AvatarModel*>::iterator enemyModelIt = m_enemyModels.begin();
while(enemyModelIt != m_enemyModels.end())
{
delete enemyModelIt->second;
m_enemyModels.erase(enemyModelIt++);
}
//clean up of player
delete m_playerModel;
//clean of of the scene info
std::vector<LevelModel::LayerInfo>::iterator layerIt = sceneLayers.begin();
while(layerIt != sceneLayers.end())
{
delete[] layerIt->solidityMap;
std::vector<LevelModel::TileInfo>::iterator tileInfoIt = layerIt->layerTiles.begin();
while(tileInfoIt != layerIt->layerTiles.end())
{
tileInfoIt = layerIt->layerTiles.erase(tileInfoIt);
}
layerIt = sceneLayers.erase(layerIt);
}
//clean up of tile info
std::vector<int>::iterator tileSetInfoIt = m_sourceTileSetInfo.solidity.begin();
while(tileSetInfoIt != m_sourceTileSetInfo.solidity.end())
{
tileSetInfoIt = m_sourceTileSetInfo.solidity.erase(tileSetInfoIt);
}
}
void LevelModel::setPlayerModel(PlayerModel* playerModel)
{
m_playerModel = playerModel;
}
void LevelModel::addEnemyModel(AvatarModel* enemyModel, int key)
{
m_enemyModels.insert(std::make_pair(key,enemyModel));
}
void LevelModel::removeEnemyModel(int key)
{
//erase the enemy and erase by key
delete m_enemyModels[key];
m_enemyModels.erase(key);
}
void LevelModel::addStaticObjectModel(StaticObjectModel* staticObjectModel, int key)
{
m_staticObjectModels.insert(std::make_pair(key,staticObjectModel));
}
void LevelModel::removeStaticObjectModel(int key)
{
//erase the enemy and erase by key
delete m_staticObjectModels[key];
m_staticObjectModels.erase(key);
}
void LevelModel::addDynamicObjectModel(DynamicObjectModel* dynamicObjectModel, int key)
{
m_dynamicObjectModels.insert(std::make_pair(key,dynamicObjectModel));
}
void LevelModel::removeDynamicObjectModel(int key)
{
//erase the enemy and erase by key
delete m_staticObjectModels[key];
m_staticObjectModels.erase(key);
}
int LevelModel::getTileSolidity(int tileX, int tileY)
{
int tileSolidity = 0;
std::vector<LayerInfo>::const_iterator layerIt = sceneLayers.begin();
while(layerIt!=sceneLayers.end())
{
//return maximum solidity if we are out of boundaries of the map
if(tileX < 0 || tileX > (int)layerIt->width) {return 9;}
if(tileY < 0 || tileY > (int)layerIt->height) {return 9;}
if(layerIt->solidityMap[tileY* (int)layerIt->width + tileX] > tileSolidity)
{
tileSolidity = layerIt->solidityMap[tileY* (int)layerIt->width + tileX];
}
layerIt++;
}
return tileSolidity;
}
|
bf88c586e334d200fab9a8c1fc6d282ac5aa6f07
|
db1375699e6d41928bcd08191932cc7a4495ab15
|
/SP1Framework/Mobs.cpp
|
ec15f633d39f32c9ee0a18d97b72a5b59abeed90
|
[] |
no_license
|
HideinCoffee/Studio-Project-1-Team-17
|
c18a8a2a2070650f712e453057c41c368f712ee4
|
0604ca8fac5f72b8138b31386648a1c17f5e8470
|
refs/heads/master
| 2022-12-15T23:11:11.245723
| 2020-08-30T18:30:45
| 2020-08-30T18:30:45
| 285,766,976
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,721
|
cpp
|
Mobs.cpp
|
#include "mobs.h"
Mobs::Mobs(int xpos,int ypos,int index,int damage,int health,bool canshoot, bool trackplayermode,MOVEMENTDIRECTION &mobdirection):Entity(health, true, 0, 0)
{
COORD mob;
mob.X = xpos;
mob.Y = ypos;
setpos(mob);
this->trackplayermode = trackplayermode;
this->mobdirection = mobdirection;
this->canshoot = canshoot;
this->index = index;
this->damage = damage;
//Constructor for mobs
}
Mobs::~Mobs() {
//destructor for mobs// * * *
}// * P *
// * * * <-- like this
bool Mobs::checkmove(COORD playerpos) { // check if the mob is around the position around the player //
bool needtomove = true;
int i = 0;
while (i < 3) {
if ((playerpos.X - 1 == returnPos().X) && ((playerpos.Y-1) + i == returnPos().Y)) {
needtomove = false;
}
else if ((playerpos.X + 1 == returnPos().X) && ((playerpos.Y-1) + i) == returnPos().Y) {
needtomove = false;
}
if ((playerpos.X == returnPos().X) && (playerpos.Y + 1 == returnPos().Y)) {
needtomove = false;
}
else if ((playerpos.X == returnPos().X) && (playerpos.Y - 1 == returnPos().Y)) {
needtomove = false;
}
i++;
}
return needtomove;
}
void Mobs::move(MOVEMENTDIRECTION &movementdir, COORD playerpos, Map& map) {
if (trackplayermode == true) {
trackplayer(playerpos,map);
}
else {
controlledmovement(map);
}
}
void Mobs::trackplayer(COORD playerpos, Map& map) { // make it so that if the player contact // make it so that the mob will explode yes.
int playerx = playerpos.X;
int playery = playerpos.Y;
bool moved = false;
COORD mob;
mob.X = returnPos().X;
mob.Y = returnPos().Y;
if (checkmove(playerpos) == true) {
if ((playerx > mob.X) && (movementcollide(map, mob.X + 1, mob.Y) == false)) { // right
mob.X += 1;
moved = true;
}
else if ((playerx != mob.X) && (movementcollide(map, mob.X - 1, mob.Y) == false)) { // left
mob.X -= 1;
moved = true;
}
if ((playery > mob.Y) && (movementcollide(map, mob.X, mob.Y + 1) == false)) { // down
mob.Y += 1;
moved = true;
}
else if ((playery != mob.Y) && (movementcollide(map, mob.X, mob.Y - 1) == false)) { //up
mob.Y -= 1;
moved = true;
}
if (moved == true) {
map.editmap(returnPos().X, returnPos().Y, ' ');
setpos(mob);
map.editmap(mob.X,mob.Y, 'm');
}
}
}
void Mobs::controlledmovement(Map& map) {
bool moved = false;
COORD mp = { 0,0 };
if (getalive() == true) {
mp = returnPos();
switch (mobdirection.UP) {
case true:
if ((movementcollide(map, mp.X, mp.Y - 1) == false) && (getalive() == true)) { // move up
mp.Y--;
moved = true;
}
else {
mobdirection.UP = false;
mobdirection.DOWN = true;
}
break;
}
switch (mobdirection.DOWN) {
case true:
if ((movementcollide(map, mp.X, mp.Y + 1) == false) && (getalive() == true)) {
mp.Y++;
moved = true;
}
break;
}
switch (mobdirection.LEFT) {
case true:
if ((movementcollide(map, mp.X - 1, mp.Y) == false) && (getalive() == true)) {
mp.X -= 1;
moved = true;
}
else {
mobdirection.LEFT = false;
mobdirection.RIGHT = true;
}
break;
}
switch (mobdirection.RIGHT) {
case true:
if ((movementcollide(map, mp.X + 1, mp.Y) == false) && (getalive() == true)) {
mp.X++;
moved = true;
}
else {
mobdirection.RIGHT = false;
mobdirection.LEFT = true;
}
break;
}
if (moved == true) {
map.editmap(returnPos().X, returnPos().Y, ' ');
setpos(mp);
map.editmap(mp.X, mp.Y, 'm');
}
}
}
void Mobs::shoot(BULLETDIRECTION bulletdir,int index) {
//left blank cuz mobs are unable to shoot for now (if there is time implement shooting for mobs) probably not
}
bool Mobs::movementcollide(Map& map, int x, int y) {
bool returnvalue = false;
switch (map.getchar(x, y)) {
case '#':
returnvalue = true;
break;
case ' ':
returnvalue = false;
break;
case '!':
returnvalue = true;
break;
case '$':
returnvalue = false;
break;
case 'm':
returnvalue = true;
break;
case 'x':
returnvalue = false;
break;
case 'L':
returnvalue = false;
break;
case 'D':
returnvalue = false;
break;
case 'B':
for (int i = 0; i < 20; i++) {
if (enemyarray[i] != nullptr) {
if ((enemyarray[i]->returnPos().X == x) && (enemyarray[i]->returnPos().Y == y))
// enemyarray[i]->takedamage(4);
continue;
if (enemyarray[i]->getalive() == false) {
delete enemyarray[i];
enemyarray[i] = nullptr;
}
}
}
returnvalue = false;
break;
}
return returnvalue;
if (playerarray[0] != nullptr)
if (checkmove(playerarray[0]->returnPos()) == false) {
trackplayermode = true;
}
}
void Mobs::AOEdamage(COORD playerpos){
}
int Mobs::getdamage() {
return damage;
}
|
ea6dcc581c98faaa5d95c266f0b6c20522088fc6
|
598516678259b783f73f4a0b76b9b716ae178d28
|
/stringCal.h
|
88c1c12d5cd3c15a82197761e3ab26f67afbefaa
|
[] |
no_license
|
jmherning/stringCalculatorKata
|
c5770c737b2f2bfd4dbf22f1fc2e351b401390cb
|
7466ef7c026173df36dab13f1a2cca1e26bbf5de
|
refs/heads/master
| 2020-04-25T07:09:23.516214
| 2019-02-26T00:03:08
| 2019-02-26T00:03:08
| 172,605,029
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 196
|
h
|
stringCal.h
|
//
// Created by Jason on 2/15/2019.
//
#ifndef KATASTRINGCAL_STRINGCAL_H
#define KATASTRINGCAL_STRINGCAL_H
#include "string"
int stringCal(std::string s);
#endif //KATASTRINGCAL_STRINGCAL_H
|
ee4888cd16c0089aad934da597314d17772ee620
|
f8df8a579540d618fb4706ece46ea5d89cbd573f
|
/BullCowGame/main.cpp
|
9d3d17e9af3d92c404333084b3128d7887518d26
|
[] |
no_license
|
Trimble-Brandon/BullCowGame
|
e0bb37c7205318c5f646321da23622b2f4e083a6
|
098c421e732fdcbdc1aed1084ea51914e2a83117
|
refs/heads/master
| 2021-01-20T04:51:02.425349
| 2017-04-28T21:08:24
| 2017-04-28T21:08:24
| 89,744,813
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,181
|
cpp
|
main.cpp
|
/**********************************************************
* TITLE: UNREAL/C++ PRACTICE COURSE, BULL COW GAME
* AUTHOR: Brandon Trimble
* SUMMARY: Console executable that makes use of the
* BullCow Class. This acts as the view in a MVC pattern
* and is responsible for all user interaction. For game
* logic see the FBullCowGame Class.
**********************************************************/
#pragma once
#include <iostream>
#include <string>
#include "FBullCowGame.h"
// Syntax adjustments to Unreal standards
using FText = std::string;
using int32 = int;
// Prototypes
void GameIntro();
void PlayGame();
FText GetValidGuess();
bool AskToPlayAgain();
void PrintGameSummary();
FBullCowGame BCGame; // Instantiate a new game.
/**********************************************************
* [MAIN]
* Controller.
**********************************************************/
int main()
{
bool bPlayAgain = false;
do
{
// Introduce the game
GameIntro();
// Play the game
PlayGame();
// Ask user if they want to play again
bPlayAgain = AskToPlayAgain();
}
while (bPlayAgain);
return 0;
}
/**********************************************************
* [GAME INTRO]
* Prints the introduction of the game to the screen.
**********************************************************/
void GameIntro()
{
std::cout << "\n\nWelcome to Bulls and Cows, a fun word game.\n";
std::cout << std::endl;
std::cout << "******************************************************************\n"; // Fun ascii art to enrich the intro and the game as a whole.
std::cout << "* *\n";
std::cout << "* --^^-- ------ *\n";
std::cout << "* / , ,| |, , \\ *\n";
std::cout << "* _____________, @@ @@ ,___________ *\n";
std::cout << "* /| / \\ |\\ *\n";
std::cout << "* / | | | | \\ *\n";
std::cout << "* & |_________________| |_________________| & *\n";
std::cout << "* || || || || || || VVVV || || *\n";
std::cout << "* mm mm mm mm mm mm mm mm *\n";
std::cout << "* *\n";
std::cout << "* *\n";
std::cout << "* **** * * \\ **** *\n";
std::cout << "* * * * * \\ * *\n";
std::cout << "* **** * * * * *** \\ * **** * * **** *\n";
std::cout << "* * * * * * * * \\ * * * * * * * *\n";
std::cout << "* **** ***** * * *** \\ **** **** *** *** *** *\n";
std::cout << "* *\n";
std::cout << "******************************************************************\n";
std::cout << "Bulls and Cows is a game where you guess the word that the program\n"; // Some explanation of how the game works.
std::cout << "is thinking of. The word will always be an isogram, a word with no\n"; // May replace this with a Game menu that includes an option for 'about'.
std::cout << "more than one of each letter in it.\n";
std::cout << "\nYou are provided with the length of the word in numbers. Your\n";
std::cout << "current try is displayed along with the amount of tries that you\n";
std::cout << "have to guess correctly. The amount of tries changes depending on\n";
std::cout << "the length of the word.\n";
std::cout << "\nEach time you enter a guess the game will show you a number of\n";
std::cout << "Bulls and number of Cows. A 'Bull' is the correct letter in the\n";
std::cout << "correct position of the word. A 'Cow' is the correct letter, but is\n";
std::cout << "in the wrong position in the word. Have fun!!\n";
std::cout << "\n-----------------------------------------------------------------";
std::cout << std::endl;
std::cout << "Can you guess the " << BCGame.GetHiddenWordLength();
std::cout << " letter isogram I'm thinking of?\n";
std::cout << std::endl;
return;
}
/**********************************************************
* [PLAY GAME]
* Play the game. Loops through GetGuess and ConfirmGuess.
**********************************************************/
void PlayGame()
{
BCGame.Reset();
int32 MaxTries = BCGame.GetMaxTries();
// Loop asking for guesses while the game
// is NOT won and there are still tries remaining
while(!BCGame.IsGameWon() && BCGame.GetCurrentTry() <= MaxTries)
{
FText Guess = GetValidGuess(); // TODO make loop for validation
// Submit valid guess to the game
FBullCowCount BullCowCount = BCGame.SubmitValidGuess(Guess);
// Print number of bulls and cows
std::cout << "Bulls = " << BullCowCount.Bulls;
std::cout << ". Cows = " << BullCowCount.Cows << "\n\n";
}
// Summarize game
PrintGameSummary();
return;
}
/**********************************************************
* [GET VALID GUESS]
* Prompt user for guess. Loop until the guess is valid.
**********************************************************/
FText GetValidGuess()
{
FText Guess = "";
EGuessStatus Status = EGuessStatus::Invalid_Status;
do
{
int32 CurrentTry = BCGame.GetCurrentTry();
std::cout << "Try " << CurrentTry << " of " << BCGame.GetMaxTries();
std::cout << ". Enter Guess: ";
std::getline(std::cin, Guess);
Status = BCGame.CheckGuessValidity(Guess);
switch (Status)
{
case EGuessStatus::Not_Isogram:
std::cout << "Please enter a word without repeating letters!\n\n";
break;
case EGuessStatus::Not_Lowercase:
std::cout << "Please enter all lowercase letters!\n\n";
break;
case EGuessStatus::Wrong_Length:
std::cout << "Please enter a " << BCGame.GetHiddenWordLength() << " letter word!\n\n";
break;
default:
// assume the guess is valid
break;
}
} while (Status != EGuessStatus::OK); // Keep looping until there are no errors
return Guess;
}
/**********************************************************
* [ASK TO PLAY AGAIN]
* Prompt user and ask if they want to play again.
**********************************************************/
bool AskToPlayAgain()
{
std::cout << "Do you want to play again?(y/n): ";
FText Response = "";
std::getline(std::cin, Response);
return (Response[0] == 'y' || Response[0] == 'Y');
}
/**********************************************************
* [PRINT GAME SUMMARY]
* Determine if the player won or lost and then print the
* message appropriate.
**********************************************************/
void PrintGameSummary()
{
if (BCGame.IsGameWon())
{
std::cout << "CONGRATULATIONS! --- YOU WON!\n";
}
else
{
std::cout << "Better luck next time!\n";
}
}
|
68894d9f7e8c187d938a3b80aac290012d5d539b
|
6d3f8483039d63c3a0ff24a4dac6397360d3f575
|
/Source/WebKit2/UIProcess/API/qt/qdesktopwebview.h
|
b25ddef4747de5a97d28bd79640f94fa2cfac2ba
|
[] |
no_license
|
xiaolu31/webkit-node
|
d45d93643fecad4ff73aec1fea67a60205a84639
|
ef3df7a14a1a014e7e7f8f5c7c1f3e048deefd88
|
refs/heads/node
| 2021-09-29T21:57:22.869737
| 2011-12-12T08:02:27
| 2011-12-12T08:02:27
| 42,396,541
| 1
| 1
| null | 2015-09-13T13:20:36
| 2015-09-13T13:20:36
| null |
UTF-8
|
C++
| false
| false
| 3,979
|
h
|
qdesktopwebview.h
|
/*
* Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this program; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#ifndef qdesktopwebview_h
#define qdesktopwebview_h
#include "qwebkitglobal.h"
#include "qwebkittypes.h"
#include <QUrl>
#include <QtDeclarative/qsgpainteditem.h>
#include <WebKit2/WKBase.h>
class QDesktopWebViewPrivate;
class QWebNavigationController;
QT_BEGIN_NAMESPACE
class QFocusEvent;
class QMouseEvent;
class QHoverEvent;
class QInputMethodEvent;
class QKeyEvent;
class QPainter;
class QRectF;
class QSGDragEvent;
class QTouchEvent;
class QWheelEvent;
QT_END_NAMESPACE
namespace WTR {
class PlatformWebView;
}
class QWEBKIT_EXPORT QDesktopWebView : public QSGPaintedItem {
Q_OBJECT
Q_PROPERTY(QString title READ title NOTIFY titleChanged)
Q_PROPERTY(QUrl url READ url NOTIFY urlChanged)
Q_PROPERTY(int loadProgress READ loadProgress NOTIFY loadProgressChanged)
Q_PROPERTY(QWebNavigationController* navigation READ navigationController CONSTANT FINAL)
Q_ENUMS(NavigationPolicy)
Q_ENUMS(ErrorType)
public:
enum NavigationPolicy {
UsePolicy,
DownloadPolicy,
IgnorePolicy
};
enum ErrorType {
EngineError,
NetworkError,
HttpError
};
QDesktopWebView(QSGItem* parent = 0);
virtual ~QDesktopWebView();
QUrl url() const;
QString title() const;
int loadProgress() const;
QWebNavigationController* navigationController() const;
public Q_SLOTS:
void load(const QUrl&);
Q_SIGNALS:
void titleChanged(const QString& title);
void statusBarMessageChanged(const QString& message);
void loadStarted();
void loadSucceeded();
void loadFailed(QDesktopWebView::ErrorType errorType, int errorCode, const QUrl& url);
void loadProgressChanged(int progress);
void urlChanged(const QUrl& url);
void linkHovered(const QUrl& url, const QString& title);
protected:
virtual void keyPressEvent(QKeyEvent*);
virtual void keyReleaseEvent(QKeyEvent*);
virtual void inputMethodEvent(QInputMethodEvent*);
virtual void focusInEvent(QFocusEvent*);
virtual void focusOutEvent(QFocusEvent*);
virtual void mousePressEvent(QMouseEvent *);
virtual void mouseMoveEvent(QMouseEvent *);
virtual void mouseReleaseEvent(QMouseEvent *);
virtual void mouseDoubleClickEvent(QMouseEvent *);
virtual void wheelEvent(QWheelEvent*);
virtual void touchEvent(QTouchEvent*);
virtual void hoverEnterEvent(QHoverEvent*);
virtual void hoverMoveEvent(QHoverEvent*);
virtual void hoverLeaveEvent(QHoverEvent*);
virtual void dragMoveEvent(QSGDragEvent*);
virtual void dragEnterEvent(QSGDragEvent*);
virtual void dragExitEvent(QSGDragEvent*);
virtual void dragDropEvent(QSGDragEvent*);
virtual void geometryChanged(const QRectF&, const QRectF&);
void paint(QPainter*);
virtual bool event(QEvent*);
private:
QDesktopWebView(WKContextRef, WKPageGroupRef, QSGItem* parent = 0);
WKPageRef pageRef() const;
void init();
friend class WTR::PlatformWebView;
friend class QDesktopWebViewPrivate;
QDesktopWebViewPrivate *d;
};
Q_DECLARE_METATYPE(QDesktopWebView::NavigationPolicy)
#endif /* qdesktopwebview_h */
|
5f7f67e704a6d2dd614146773d1868920120461c
|
045b27be9963ea34d3806b6106d17c5341eb62c0
|
/train4_4.cpp
|
f3cda08eb247757e7c0f44d6f2465c894ed6704b
|
[] |
no_license
|
miyamur/cpp
|
1f316244a88e7a99edf51904c0626b1d9fe73d6d
|
bbc5f914cfa7b7f4ef5e4139f1f2ad00d47141ca
|
refs/heads/master
| 2020-05-21T05:57:05.883517
| 2019-07-28T15:30:50
| 2019-07-28T15:30:50
| 185,931,212
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,067
|
cpp
|
train4_4.cpp
|
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main(){
vector<string> v1;
string x;
while(1){
cout<<"文字列を入力 :";
getline(cin,x);
if(x==""){
break;
}
v1.push_back(x);
}
vector<string> max;
vector<string> min;
max.push_back(v1[0]);
min.push_back(v1[0]);
for (int i=1;i<v1.size();i++){
if(v1[i].length()==max[0].length()){
max.push_back(v1[i]);
}
else if(v1[i].length()>max[0].length()){
max.clear();
max.push_back(v1[i]);
}
}
cout<<"最長の単語";
for (int i=0;i<max.size();i++){
cout<<max[i]<<" ";
}
cout<<endl;
for (int i=1;i<v1.size();i++){
if(v1[i].length()==min[0].length()){
min.push_back(v1[i]);
}
else if(v1[i].length()<min[0].length()){
min.clear();
min.push_back(v1[i]);
}
}
cout<<"最短の単語";
for (int i=0;i<min.size();i++){
cout<<min[i]<<" ";
}
cout<<endl;
return 0;
}
|
874109a2d6dc04c6d1afc978ecc2a5b38469e2e2
|
4dc0a6936789ce0094e5ed83ddc77f4bcecb5890
|
/week 3 - analog in:out/photocell_calibrated/photocell_calibrated.ino
|
adcd5421e4f377fa365ba89cd96cc517f936a102
|
[] |
no_license
|
IDMNYU/Interfaces-and-Net-Devices
|
8171379a0146d75aa7f5119e4dc390a06c882901
|
66d51cccb2c9b49c1e87d0de058a62a155f81dad
|
refs/heads/master
| 2020-04-20T06:39:05.617422
| 2019-03-14T10:43:18
| 2019-03-14T10:43:18
| 168,689,938
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,096
|
ino
|
photocell_calibrated.ino
|
/*
HUZZAH Feather analog Input to serial and analog out with calibration
*/
// These constants won't change. They're used to give names to the pins used:
const int sensorPin = A0; // Analog input pin that the sensor is attached to
const int ledPin = 4; // Analog output pin that the LED is attached to
// variables
int sensorValue = 0; // the sensor value
int sensorMin = 1023; // minimum sensor value
int sensorMax = 0; // maximum sensor value
void setup() {
// initialize serial communications at 9600 bps:
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
pinMode(LED_BUILTIN, OUTPUT);
calibrateSensor();
}
void loop() {
// optional switch to recalibrate
if (digitalRead(5) == HIGH) {
calibrateSensor();
}
// read the sensor:
sensorValue = analogRead(sensorPin);
// apply the calibration to the sensor reading
int outputValue = map(sensorValue, sensorMin, sensorMax, 0, 1023);
// in case the sensor value is outside the range seen during calibration
outputValue = constrain(outputValue, 0, 1023);
// fade the LED using the calibrated value:
analogWrite(ledPin, outputValue);
// print the results to the Serial Monitor:
Serial.print("sensor = ");
Serial.print(sensorValue);
Serial.print("\t output = ");
Serial.println(outputValue);
// wait 5 milliseconds before the next loop for the analog-to-digital
// converter to settle after the last reading:
delay(5);
}
void calibrateSensor() {
digitalWrite(LED_BUILTIN, LOW);
// calibrate during the first five seconds
long currentTime = millis();
Serial.println("calibration");
while (millis() < (currentTime + 5000)) {
sensorValue = analogRead(sensorPin);
// record the maximum sensor value
if (sensorValue > sensorMax) {
sensorMax = sensorValue;
}
// record the minimum sensor value
if (sensorValue < sensorMin) {
sensorMin = sensorValue;
}
Serial.print(".");
yield(); // THIS IS IMPORTANT
}
Serial.println();
// signal the end of the calibration period
digitalWrite(LED_BUILTIN, HIGH);
}
|
bd5dc1f092739381c32b757602cae0b41a69f58f
|
f4ea512b8a156abfaef83f25e044b94c37b6dedb
|
/SampleCodes/Blue100/35.cpp
|
56fde726f4e5093e0cd691b9f0880743147a3950
|
[] |
no_license
|
HubHikari/CompetitiveProgramming
|
9d1483e0a964508e84ae233aba9cb4ade7ff88e3
|
b7c471a80378183b2ed5fe86fa829ee89d26709f
|
refs/heads/main
| 2023-04-13T07:00:13.812800
| 2021-04-24T13:51:27
| 2021-04-24T13:51:27
| 308,897,533
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,758
|
cpp
|
35.cpp
|
#include <algorithm>
#include <array>
#include <bitset>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstring>
#include <deque>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
using namespace std;
typedef long long ll;
typedef vector<int> VI;
typedef vector<ll> VL;
typedef vector<long double> VD;
typedef vector<VI> VVI;
typedef vector<VL> VVL;
typedef vector<VD> VVD;
typedef pair<int, int> P;
typedef pair<ll, ll> PL;
template <typename T>
void chmin(T &a, T b) {
if (a > b) a = b;
}
template <typename T>
void chmax(T &a, T b) {
if (a < b) a = b;
}
int in() {
int x;
cin >> x;
return x;
}
ll lin() {
ll x;
cin >> x;
return x;
}
#define REP(i, n) for (int i = 0; i < n; ++i)
#define FOR(i, a, b) for (int i = a; i <= b; ++i)
#define FORR(i, a, b) for (int i = a; i >= b; --i)
#define ALL(c) (c).begin(), (c).end()
#define I(n) cin >> n
#define O(n) cout << n << endl
#define endl() cout << endl
#define pb(n) push_back((n))
#define mp(i, j) make_pair((i), (j))
#define VI_INI(v, n) v.resize(n)
#define VVI_INI(v, a, b, n) v.resize(a, vector<int>(b, n))
#define DEBUG 1 //デバッグモード 0:OFF 1:ON
#if DEBUG
#define DBG(s) cout << "DEBUG " << s << endl
//#define DBG(s, i) cout << "DEBUG " << s << i << endl;
#define DBGV(s, v) \
cout << "DEBUG " << s; \
for (int nv : v) { \
cout << nv << " "; \
} \
cout << endl;
#define DBGVV(s, v) \
cout << "DEBUG " << s << endl; \
{ \
int loopcount = 0; \
for (VI nv : v) { \
cout << loopcount++ << ": "; \
for (int nnv : nv) { \
cout << setw(4) << nnv; \
} \
cout << endl; \
} \
}
#else
#define DBG(i) /* ... */
#define DBGV(s, i) /* ... */
#define DBGVV(s, i) /* ... */
#endif
// 入力
int N, W;
VI weight,value;
VVI dp;
int main() {
I(N); //個数
I(W); //重さ上限
VI_INI(weight,N);
VI_INI(value, N);
FOR(i, 0, N - 1) {
I(value[i]);
I(weight[i]);
}
DBGV("value:",value);
DBGV("weight:",weight);
VVI_INI(dp, N+1, W+1, 0);
DBGVV("dp:",dp);
FOR(i,0,N-1){
FOR(w,0,W){
if (w >= weight[i])
dp[i + 1][w] =
max(dp[i][w - weight[i]] + value[i], dp[i][w]);
else
dp[i + 1][w] = dp[i][w];
}
}
DBGVV("dp:", dp);
O(dp[N][W]);
}
|
a5a438a38cd6fbfa09ef7603e41f091660044519
|
5f8b0cb48cb35513c7aaed449056f17cdaa9f720
|
/1859. 백만 장자 프로젝트.cpp
|
71234af87d80527188f605d2941ac7cd1a668607
|
[] |
no_license
|
KeunhyoungLee/swexpert
|
65ecdaecb74aa0a8306956bbe99ccc5aeb7de18e
|
0a1f4577dee8c6d1f653563b21819cd42e1a5fa2
|
refs/heads/master
| 2020-04-14T09:02:13.585824
| 2019-03-04T08:37:41
| 2019-03-04T08:37:41
| 163,750,267
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 856
|
cpp
|
1859. 백만 장자 프로젝트.cpp
|
#include <iostream>
using namespace std;
int price[1000000] = { 0 };
int N;
int Max_index(int start);
int main()
{
int T;
scanf("%d", &T);
for (int i =1; i <= T; i++){
//int N;
long long sum =0 ;
//unsigned long long sum = 0;
scanf("%d", &N);
for (int j = 0; j < N; j++) {
scanf("%d", &price[j]);
}
printf("#%d ", i);
for (int j = 0; j < N; j++) {
int max_index = Max_index(j);
//printf("%d", max_index);
for (int k = j; k <= max_index; k++){
sum = sum + price[max_index] - price[k];
}
j = max_index;
}
printf("%lld\n", sum);
//cout << sum << endl;
}
return 0;
}
int Max_index(int start) //start =j
{
int max_value = 0;
int max_index = 0;
for (int i = start; i < N; i++) {
if ( max_value < price[i] ) {
max_value = price[i];
max_index = i;
}
}
return max_index;
}
|
655331c160023482b8d8d4326c70b64942ad5b2d
|
e641bd95bff4a447e25235c265a58df8e7e57c84
|
/chrome/browser/chromeos/policy/dlp/data_transfer_dlp_controller.h
|
4acd17e787d3eec42294ecdadd67db413961399d
|
[
"BSD-3-Clause"
] |
permissive
|
zaourzag/chromium
|
e50cb6553b4f30e42f452e666885d511f53604da
|
2370de33e232b282bd45faa084e5a8660cb396ed
|
refs/heads/master
| 2023-01-02T08:48:14.707555
| 2020-11-13T13:47:30
| 2020-11-13T13:47:30
| 312,600,463
| 0
| 0
|
BSD-3-Clause
| 2022-12-23T17:01:30
| 2020-11-13T14:39:10
| null |
UTF-8
|
C++
| false
| false
| 2,029
|
h
|
data_transfer_dlp_controller.h
|
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_CHROMEOS_POLICY_DLP_DATA_TRANSFER_DLP_CONTROLLER_H_
#define CHROME_BROWSER_CHROMEOS_POLICY_DLP_DATA_TRANSFER_DLP_CONTROLLER_H_
#include "base/strings/string16.h"
#include "ui/base/data_transfer_policy/data_transfer_policy_controller.h"
namespace ui {
class DataTransferEndpoint;
}
namespace policy {
// DataTransferDlpController is responsible for preventing leaks of confidential
// data through clipboard data read or drag-and-drop by controlling read
// operations according to the rules of the Data leak prevention policy set by
// the admin.
class DataTransferDlpController : public ui::DataTransferPolicyController {
public:
// Creates an instance of the class.
// Indicates that restricting clipboard content and drag-n-drop is required.
static void Init();
DataTransferDlpController(const DataTransferDlpController&) = delete;
void operator=(const DataTransferDlpController&) = delete;
// nullptr can be passed instead of `data_src` or `data_dst`. If data read is
// not allowed, this function will show a toast to the user.
bool IsDataReadAllowed(
const ui::DataTransferEndpoint* const data_src,
const ui::DataTransferEndpoint* const data_dst) const override;
private:
DataTransferDlpController();
~DataTransferDlpController() override;
// Shows toast in case the data read is blocked.
// TODO(crbug.com/1131670): Move `ShowBlockToast` to a separate util/helper.
void ShowBlockToast(const base::string16& text) const;
// The text will be different if the data transferred is being shared with
// Crostini or Parallels or ARC.
base::string16 GetToastText(
const ui::DataTransferEndpoint* const data_src,
const ui::DataTransferEndpoint* const data_dst) const;
};
} // namespace policy
#endif // CHROME_BROWSER_CHROMEOS_POLICY_DLP_DATA_TRANSFER_DLP_CONTROLLER_H_
|
f867cde52c6216e281c376cb5f932a38100dca3d
|
62628dc5245c4612d001c7f0e7149e4e9a59429c
|
/Programas/c/FIBONACI.CPP
|
86cce62530629e703cf97465ffa7be5ce8d81319
|
[
"CC0-1.0"
] |
permissive
|
felipeescallon/lenguajes_programacion
|
b3ae3477765b3100b8b454b1868e19f3a0cfc64c
|
5b88bf2a95492e799c94e414997365a14db05c05
|
refs/heads/main
| 2023-07-13T01:37:29.360547
| 2021-08-26T14:42:20
| 2021-08-26T14:42:20
| 386,758,230
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 714
|
cpp
|
FIBONACI.CPP
|
/*CALCULA EL N-ESIMO TERMINO DE LA SERIE DE FIBONACCI*/
//Serie Fibonacci=1,1,2,3,5,8,13,21,34...
//FORMULA:el termino sgte se calcula a traves de la suma de los dos anteriores
#include<stdio.h>
#include<conio.h>
void main()
{
int n,na=0,naa=0,v=0;
clrscr();
printf("Escriba el termino de la serie de Fibonacci que desea averiguar: ");
scanf("%d",&n);
if (n==1 || n==2)
{
printf("El valor es 1");
}
else
{
na=1;
naa=1;
for(int cont=2;cont<n;cont++)
{
v=na+naa;//formula de la serie
/*asignaciones a los proximos valores*/
naa=na;
na=v;
}
n=v;
printf("El valor es: %d",n);
}
getch();
}
|
65bfab33c968e73112deecea44231438c1c648f1
|
86fc0b275da698912b00b410b94cc7d30573f48a
|
/arduino/arduino/src/main.ino
|
c77bc1b3b8331df180dd767f8f2eac388e70583b
|
[] |
no_license
|
kuthian/TrustfallDevice
|
db32801078bdc7b57cb2553cef348c2e859073c8
|
ea181ebcd56e8a369f220b1417d5922e5fe88752
|
refs/heads/master
| 2020-03-28T08:19:19.290566
| 2018-09-08T18:05:44
| 2018-09-08T18:05:44
| 147,957,927
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,539
|
ino
|
main.ino
|
#include <MPU9250.h>
#include <quaternionFilters.h>
#include "MPU9250.h" // Sparkfun Library
#include <SoftwareSerial.h> // Bluetooth Serial Connection
#include<AltSoftSerial.h>
MPU9250 myIMU; // Define the I2C address for the MPU
float run_vx = 0;
float run_vy = 0;
float run_vz = 0;
float run_vxy = 0;
float run_vxz = 0;
float run_vyz = 0;
float run_vxyz = 0;
float dx = 0;
float dy = 0;
float dz = 0;
float dxy = 0;
float dxz = 0;
float dyz = 0;
float dxyz = 0;
float vx;
float vy;
float vz;
float vxy;
float vxz;
float vyz;
float vxyz;
int i = 1;
int N = 100;
int low_batt_flag = 0;
int event_trigger_flag = 0;
int LedPin = 13; // Pin 13 is the arduino pro mini LED pin
unsigned long int now = 0; // Set up variable for the timer
unsigned long int last_fall_time = 0; // var that holds time of last fall
unsigned long int last_batt_check_time = 0; // var that holds time of last fall
float threshold = 3.8; // threshold in G
float threshold2 = 5.5; // threshold in G
AltSoftSerial BT;
void setup()
{
int IntPin = 2; //These can be changed, 2 and 3 are the Arduinos ext int pins
int SoftSerialPin = 9;
pinMode(A0, INPUT);
pinMode(IntPin, INPUT); // Set up the interrupt pin
pinMode(LedPin, OUTPUT); // LED pin
pinMode(SoftSerialPin, OUTPUT); // Needed for SoftSerial not sure why
BT.begin(9600); // set up bluetooth connection, start advertising
Serial.begin(38400); // set up Serial connection
Wire.begin(); // init I2C connection
digitalWrite(IntPin, LOW); // on digital write this pin is held low preventing interupt
// This is checking the MPU addess default is 71
if (myIMU.readByte(MPU9250_ADDRESS, WHO_AM_I_MPU9250) == 0x71)
{
uint8_t SmpRtDiv = 0x09; // This is the number the fundamental freq of MPU sampler is divided by +1 the default fund freq is 1kHz IE for a 100Hz refresh SmpRtDiv = 9
Serial.println("MPU9250 is online...");
myIMU.MPU9250SelfTest(myIMU.SelfTest); //Check Biases
//myIMU.calibrateMPU9250(myIMU.gyroBias, myIMU.accelBias); //Load Biases into registers
myIMU.initMPU9250();
myIMU.writeByte(MPU9250_ADDRESS, SMPLRT_DIV, SmpRtDiv); // Sets the MPU sample rate to 100Hz
Serial.println("MPU9250 initialized...");
}
else
{
Serial.print("Could not connect to MPU9250: 0x");
Serial.println(myIMU.readByte(MPU9250_ADDRESS, WHO_AM_I_MPU9250), HEX); // Print address of MPU
while(1) ; // Loop forever if communication doesn't happen
}
}
void loop()
{
// This loops until the the MPU Int data register goes high, This will go high only when every data register contains new data
if (myIMU.readByte(MPU9250_ADDRESS, INT_STATUS) & 0x01)
{
//Reading from MPU9250
now = millis();
// records how long the MPU has been running in milliseconds
myIMU.readAccelData(myIMU.accelCount); // Read the x/y/z adc values
myIMU.getAres(); // Sets the DAC resolution
myIMU.ax = (float)myIMU.accelCount[0]*myIMU.aRes; // records MPU x axis
myIMU.ay = (float)myIMU.accelCount[1]*myIMU.aRes; // records MPU y axis
myIMU.az = (float)myIMU.accelCount[2]*myIMU.aRes; // records MPU z axis
//These are single datapoints for computing moving average
vx = magfunction1(myIMU.ax);
vy = magfunction1(myIMU.ay);
vz = magfunction1(myIMU.az);
vxy = magfunction2(myIMU.ax,myIMU.ay);
vxz = magfunction2(myIMU.ax,myIMU.az);
vyz = magfunction2(myIMU.ay,myIMU.az);
vxyz = magfunction3(myIMU.ax,myIMU.ay,myIMU.az);
if(i>100)
{
//first time over 100 samples are reached, obtain baseline average
if(i == 101)
{
run_vx = run_vx/100;
run_vy = run_vy/100;
run_vz = run_vz/100;
run_vxy = run_vxy/100;
run_vxz = run_vxz/100;
run_vyz = run_vxz/100;
run_vxyz = run_vxyz/100;
i++;
}
run_vx = (run_vx) + (vx/N) - (run_vx/N);
run_vy = run_vy + vy/N - run_vy/N;
run_vz = run_vz + vz/N - run_vz/N;
run_vxy = run_vxy + vxy/N - run_vxy/N;
run_vxz = run_vxz + vxz/N - run_vxz/N;
run_vyz = run_vyz + vyz/N - run_vyz/N;
run_vxyz = run_vxyz + vxyz/N - run_vxyz/N;
dx = delta(vx, run_vx);
dy = delta(vy, run_vy);
dz = delta(vz, run_vz);
dxy = delta(vxy, run_vxy);
dxz = delta(vxz, run_vxz);
dyz = delta(vyz, run_vyz);
dxyz = delta(vxyz, run_vxyz);
if((low_batt_flag = 0) && ((now - last_batt_check_time) >= 10000))
{
int batt = analogRead(A0);
float voltage = batt * (4.2/1023);
if(voltage < 3.6)
{
low_batt_flag = 1;
BT.print("BATTERY LOW");
}
last_batt_check_time = millis();
}
if ((now - last_fall_time) >= 10000)
{
if ((abs(dx) > threshold) || (abs(dy) > threshold) || (abs(dz) > threshold) || (abs(dxy) > threshold) || (abs(dxz) > threshold) || (abs(dyz) > threshold) || (abs(dxyz) > threshold2))
{
event_trigger_flag = 1;
digitalWrite(LedPin, HIGH);
BT.print("EventTrigger");
last_fall_time = millis();
}
else if (event_trigger_flag == 1)
{
event_trigger_flag = 0;
digitalWrite(LedPin, 0);
}
else
{
event_trigger_flag = 0;
}
}
//myIMU.updateTime(); MIGHT NOT BE NEEDED LOL
}
else
{
//first 100 samples will not have a moving average
run_vx = run_vx + vx;
run_vy = run_vy + vy;
run_vz = run_vz + vz;
run_vxy = run_vxy + vxy;
run_vxz = run_vxz + vxz;
run_vyz = run_vyz + vyz;
run_vxyz = run_vxyz + vxyz;
i++;
}
}
}
float magfunction1(float one){
float mags = sqrt(sq(one));
return mags;
}
float magfunction2(float one, float two){
float mags = sqrt(sq(one)+sq(two));
return mags;
}
float magfunction3(float one, float two, float three){
float mags = sqrt(sq(one)+sq(two)+sq(three));
return mags;
}
//Calculates delta value
float delta(float vx, float run_vx)
{
float delta = vx-run_vx;
return delta;
}
|
f2572d714c1d4324093e1ebee846a2a508f11772
|
c5f67ad3724d62c712d58144b5abea10c06a2314
|
/Lab4/test_inclass.in
|
df644bd6310fe2d5c5a98f892cdd86f2a50a89d6
|
[] |
no_license
|
hyc20908/ECE250
|
fdd74688998475a292978574836b57488d3514d9
|
8d6d5e91b244eea8c8a684c9d8bb48a6337cbc64
|
refs/heads/master
| 2021-01-13T12:07:44.763902
| 2018-09-10T15:05:40
| 2018-09-10T15:05:40
| 78,052,948
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 550
|
in
|
test_inclass.in
|
new: 9
edge_count 0
degree 2 0
degree! -1
degree! 10
insert 0 0 50 0
insert! -1 2 3
insert! 2 -1 4
insert! 2 1 -3
insert! 23 2 4
insert! 2 23 5
erase 2 2 1
erase 2 3 0
erase! -1 2
erase! 2 -1
erase! 0 100
erase! 10 3
insert 4 5 12.3 1
insert 5 4 11 1
erase 5 4 1
erase 4 5 0
insert 0 1 4 1
insert 0 7 8 1
insert 1 2 8 1
insert 1 7 11 1
insert 7 8 7 1
insert 6 8 6 1
insert 8 2 2 1
insert 2 3 7 1
insert 2 5 4 1
insert 3 4 9 1
insert 3 5 14 1
insert 4 5 10 1
insert 5 6 2 1
insert 6 7 1 1
edge_count 14
mst 37 11
clear
edge_count 0
delete
summary
exit
|
c5525ba457b5b6aced0a1487f7b8ebda7916d0c1
|
14d9b87045db993172f693e60cc5eae7efc80643
|
/list/linked list/有序表的并归.cpp
|
740535c8bfeaf057d1aa32c00d1c3cc75479a0f8
|
[] |
no_license
|
zhangkuan-workEveryday/data-structure
|
ad46e0fe6bafc98c45a998c75f21fd2c87152d17
|
8987385308de829b7649c61cf00799c04237efaa
|
refs/heads/master
| 2022-05-09T01:18:44.646764
| 2019-12-10T14:08:33
| 2019-12-10T14:08:33
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,865
|
cpp
|
有序表的并归.cpp
|
//顺序表的并归
//单链表的并归
//有序表并归的应用
//集合的交、并、差运算
#include <iostream>
#include <stdlib.h>
using namespace std;
//--------------------------------定义顺序、链表节点----------------------------
#define MaxSize 50
typedef int ElemType;
typedef struct SqList {
ElemType data[MaxSize];
int length;
} SqList;
typedef struct LinkNode {
ElemType data;
LinkNode * next;
} LinkNode;
//————————————顺序表的二路并归(不破坏原表)————————————
void UnionList (SqList *LA, SqList *LB, SqList *&LC) {
int i = 0;
int j = 0;
int k = 0;
LC = (SqList *)malloc(sizeof(SqList));
while (i < LA->length || j < LB->length) {
if (i < LA->length && j < LB->length && LA->data[i] < LB->data[j] ) {
LC->data[k] = LA->data[i];
i++;
}
else if (i < LA->length && j < LB->length && LB->data[i] < LA->data[j] ) {
LC->data[k] = LB->data[j];
j++;
}
else if (i >= LA->length) {
LC->data[k] = LB->data[j];
j++;
}
else {
LC->data[k] = LA->data[i];
i++;
}
}
}
//————————————链表的二路并归(不破坏原来的表格)——————————
void Un (LinkNode *LA, LinkNode *LB, LinkNode *&LC) {
LC = (LinkNode *)malloc (sizeof(LinkNode));
LinkNode *r = LC;
LinkNode *s;
LinkNode *p = LA->next;
LinkNode *q = LB->next;
while (p != NULL || q != NULL){
if (p != NULL && q != NULL && p->data < q->data) {
s = (LinkNode *)malloc (sizeof(LinkNode));
s->data = p->data;
r->next = s;
r = s;
p = p->next;
}
else if (p != NULL && q != NULL && q->data < p->data) {
s = (LinkNode *)malloc (sizeof(LinkNode));
s->data = q->data;
r->next = s;
r = s;
q = q->next;
}
else if (p == NULL) {
s = (LinkNode *)malloc (sizeof(LinkNode));
s->data = q->data;
r->next = s;
r = s;
q = q->next;
}
else {
s = (LinkNode *)malloc (sizeof(LinkNode));
s->data = p->data;
r->next = s;
r = s;
p = p->next;
}
}
r->next = NULL;
}
//————————————两个集合求并集,含有相同的元素——————————
void Union (LinkNode *LA, LinkNode *LB, LinkNode *&LC) {
LC = (LinkNode *) malloc (sizeof(LinkNode));
LinkNode *p = LA->next;
LinkNode *q = LB->next;
LinkNode *r = LC;
LinkNode *s;
while (p != NULL && q!= NULL) {
if (p->data < q->data) {
s = (LinkNode *) malloc (sizeof(LinkNode));
s->data = p->data;
r->next = s;
r = s;
p = p->next;
}
else if (q->data < p->data) {
s = (LinkNode *) malloc (sizeof(LinkNode));
s->data = q->data;
r->next = s;
r = s;
q = q->next;
}
else {
s = (LinkNode *) malloc (sizeof(LinkNode));
s->data = p->data;
r->next = s;
r = s;
p = p->next;
q= q->next;
}
}
if (q != NULL)
p = q;
while (p != NULL) {
s = (LinkNode *) malloc (sizeof(LinkNode));
s->data = p->data;
r->next = s;
r = s;
p = p->next;
}
r->next = NULL;
}
//————————————三个集合求交集(充分利用空间)——————
void UN(LinkNode *&LA, LinkNode *LB, LinkNode *LC) {
LinkNode *pa = LA->next;
LinkNode *pb = LB->next;
LinkNode *pc = LC->next;
LinkNode *r = LC;
LinkNode *q;
while (pa != NULL) {
while (pb->data < pa->data && pb != NULL) {
pb = pb->next;
}
while (pc->data < pa->data && pc != NULL) {
pc = pc->next;
}
if (pb != NULL && pc != NULL && pb->data == pa->data && pc->data == pa->data) {
r->next = pa;
r = pa;
pa = pa->next;
}
else {
q = pa->next;
free (pa);
pa = q;
}
}
r->next = NULL;
}
//————————————删除有序单链表中相同的元素———————————
void deleteNode (LinkNode *&LA) {
LinkNode *p = LA->next;
LinkNode *q;
while (p != NULL) {
if (p->data == p->next->data) {
q = p->next;
p->next = q->next;
free (q);
}
else
p = p->next;
}
}
//————————————两个集合求差(充分利用)——————————
void sub(LinkNode *&LA, LinkNode *&LB, LinkNode *&LC) {
LinkNode *pa = LA->next;
LinkNode *pb = LB->next;
LC = LA;
LinkNode *r;
r = LC;
while (pa != NULL && pb != NULL) {
if (pa->data < pb->data) {
r->next = pa;
pa = pa->next;
}
else if (pa->data > pb->data) {
pb = pb->next;
}
else {
pa = pa->next;
pb = pb->next;
}
}
if (pb == NULL) {
while (pa != NULL) {
r->next = pa;
pa = pa->next;
}
}
r->next = NULL;
}
|
7e2e0b1b08b85f06e2177d547cf801be5ffba737
|
70aac9459a3d15c7da1db90f69b64b01053b6038
|
/src/UI/UIItemWindow.h
|
35b30f00f501ddce1dc0a00889815f1f807e96b4
|
[] |
no_license
|
kschmidtdev/project404
|
868dbea42d6954988801064d19341091f4907748
|
e0fa7ae768de88aa6a956f7731614786b5ae48d8
|
refs/heads/master
| 2020-04-24T04:31:41.782726
| 2015-03-16T18:29:42
| 2015-03-16T18:29:42
| 32,344,228
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,420
|
h
|
UIItemWindow.h
|
/**
* A description window for items.
*
* #include "UIItemWindow.h"
*
* A description window for items.
*
* Project 404 2007
*
* Authors:
* Andrew Osborne, March 29 2007, Initial Creation
*/
#ifndef UIItemWindow_h
#define UIItemWindow_h
// SYSTEM INCLUDES
//
// PROJECT INCLUDES
//
#include <UI/UIElement.h>
//#include <UI/UIImage.h>
#include <UI/UIText.h>
// LOCAL INCLUDES
//
// FORWARD REFERENCES
//
class Item;
class UIItemWindow : public UIElement
{
public:
// LIFECYCLE
/**
* Default constructor.
*/
UIItemWindow(void);
/**
* Copy constructor.
*
* @param from The value to copy to this object.
*/
//UIItemWindow(const UIItemWindow& from);
/**
* Destructor.
*/
~UIItemWindow(void);
// OPERATORS
/**
* Assignment operator.
*
* @param from The value to assign to this object.
*
* @return A reference to this object.
*/
//UIItemWindow& operator=(UIItemWindow& from);
// OPERATIONS
/**
* Override RenderSelf operation
*/
virtual void RenderSelf(SDL_Surface* destination);
// ACCESS (writing)
/**
* Override Set Position
*/
virtual void SetPos( const Point & nPos );
/**
* Set Item
*/
void SetItem(Item* newItem);
/**
* Clears Item Display
*/
void ClearItem(void);
/**
* Specify to display cost or not
*/
void SetDisplayCost(bool displayCost) { mDisplayCost = displayCost; }
// INQUIRY (reading)
protected:
// PROTECTED VARIABLES
UIText mType;
UIText mNameStatic;
UIText mName;
UIText mAttrStatic; // contains static text "Attr: "
UIText mAttr;
UIText mCostStatic; // Cost:
UIText mCost;
// Display format
bool mDisplayCost;
bool mDisplayItem;
// Font format
int mFontSize;
int mFontRed;
int mFontGreen;
int mFontBlue;
// Positional stuff
Point mStart;
Point mLineOffset;
Point mNumOffset;
//Point mNameStaticStart;
//Point mName;
//Point mAttrStatic; // contains static text "Attr: "
//Point mAttr;
//Point mCostStatic; // Cost:
//Point mCost;
private:
// PRIVATE VARIABLES
};
// INLINE METHODS
//
// EXTERNAL REFERENCES
//
#endif // _UIItemWindow_h_
|
d934ee3236cff54d0ccd9b6b9675e6db7d6fe92b
|
5cb80704598e920de7603211f0190fbb0090e0e2
|
/code/librairies/aidevig_WAVrecorder/aidevig_WAVrecorder.cpp
|
fce5998749c670b6dcd7634e47f5efec04c27261
|
[] |
no_license
|
Aidevig/braceletquentin
|
4847453fabb64338592067daa43783c62d3e25ef
|
1ae5d25e4b0593e43a14f9cd4578df3c6114a511
|
refs/heads/master
| 2021-01-21T10:19:57.563076
| 2017-11-02T16:33:44
| 2017-11-02T16:33:44
| 101,978,279
| 0
| 2
| null | 2017-10-17T14:31:45
| 2017-08-31T08:30:39
|
Arduino
|
ISO-8859-1
|
C++
| false
| false
| 4,817
|
cpp
|
aidevig_WAVrecorder.cpp
|
#include <aidevig_WAVrecorder.h>
File toSend;
File rec;
String pref="REC";
String suf=".WAV";
unsigned long fileSize;
unsigned long waveChunk;
unsigned int waveType;
unsigned int numChannels;
unsigned long sampleRate;
unsigned long bytesPerSec;
unsigned int blockAlign;
unsigned int bitsPerSample;
unsigned long dataSize;
unsigned long oldTime;
unsigned long newTime;
byte byte1, byte2, byte3, byte4;
void initHeader(){
fileSize = 0L;
waveChunk = 16;
waveType = 1;
numChannels = 1;
sampleRate = 8000;
bytesPerSec = 8000;
blockAlign = 1;
bitsPerSample = 8;
dataSize = 0L;
}
String checkName(){
int i;
String nom = pref + i + suf;
while(SD.exists(nom)){
i++;
nom = pref + i + suf;
}
return nom;
}
int countRec(){
int i=0;
String nom = pref + i + suf;
while(SD.exists(nom)){
i++;
nom = pref + i + suf;
}
return i;
}
void sendLast(){
int count = countRec()-1;
char data;
Serial.print(1);
String nom = pref + count + suf;
toSend = SD.open(nom);
if(waitCommand()=='N'){
Serial.print(toSend.name());
}
if(waitCommand()=='O'){
while (toSend.available()) {
data = toSend.read(); // on stocke le caractère dans c
Serial.write(data);
}
}
toSend.close();
}
void sendAudio(){
int count = countRec() + 1; ///ADD 1 FOR DATALOG FILE
int i;
char data;
String nom;
Serial.print(count);
for(i=0;i<count;i++){
nom = pref + i + suf;
toSend = SD.open(nom);
if(waitCommand()=='N'){
Serial.print(toSend.name());
}
if(waitCommand()=='O'){
while (toSend.available()) {
data = toSend.read(); // on stocke le caractère dans c
Serial.write(data);
}
}
toSend.close();
}
}
void sendLog(){
char data;
toSend = SD.open("datalog.txt");
if(waitCommand()=='N'){
Serial.print(toSend.name());
}
if(waitCommand()=='O'){
while (toSend.available()) {
data = toSend.read(); // on stocke le caractère dans c
Serial.write(data);
}
}
toSend.close();
}
char waitCommand(){
while(Serial.available()==0);
return (char)Serial.read();
}
void writeWavHeader() { // write out original WAV header to file
String Name = checkName();
recByteSaved = 0;
bufByteCount = 0;
if(DEBUG) Serial.println(Name);
rec = SD.open(Name, FILE_WRITE);
delay(300);
if(rec){
rec.write("RIFF");
byte1 = fileSize & 0xff;
byte2 = (fileSize >> 8) & 0xff;
byte3 = (fileSize >> 16) & 0xff;
byte4 = (fileSize >> 24) & 0xff;
rec.write(byte1); rec.write(byte2); rec.write(byte3); rec.write(byte4);
rec.write("WAVE");
rec.write("fmt ");
byte1 = waveChunk & 0xff;
byte2 = (waveChunk >> 8) & 0xff;
byte3 = (waveChunk >> 16) & 0xff;
byte4 = (waveChunk >> 24) & 0xff;
rec.write(byte1); rec.write(byte2); rec.write(byte3); rec.write(byte4);
byte1 = waveType & 0xff;
byte2 = (waveType >> 8) & 0xff;
rec.write(byte1); rec.write(byte2);
byte1 = numChannels & 0xff;
byte2 = (numChannels >> 8) & 0xff;
rec.write(byte1); rec.write(byte2);
byte1 = sampleRate & 0xff;
byte2 = (sampleRate >> 8) & 0xff;
byte3 = (sampleRate >> 16) & 0xff;
byte4 = (sampleRate >> 24) & 0xff;
rec.write(byte1); rec.write(byte2); rec.write(byte3); rec.write(byte4);
byte1 = bytesPerSec & 0xff;
byte2 = (bytesPerSec >> 8) & 0xff;
byte3 = (bytesPerSec >> 16) & 0xff;
byte4 = (bytesPerSec >> 24) & 0xff;
rec.write(byte1); rec.write(byte2); rec.write(byte3); rec.write(byte4);
byte1 = blockAlign & 0xff;
byte2 = (blockAlign >> 8) & 0xff;
rec.write(byte1); rec.write(byte2);
byte1 = bitsPerSample & 0xff;
byte2 = (bitsPerSample >> 8) & 0xff;
rec.write(byte1); rec.write(byte2);
rec.write("data");
byte1 = dataSize & 0xff;
byte2 = (dataSize >> 8) & 0xff;
byte3 = (dataSize >> 16) & 0xff;
byte4 = (dataSize >> 24) & 0xff;
rec.write(byte1); rec.write(byte2); rec.write(byte3); rec.write(byte4);
}
else{
if(DEBUG) Serial.println("BUG ECRITURE HEADER");
}
}
void writeOutHeader() { // update WAV header with final filesize/datasize
rec.seek(4);
byte1 = recByteSaved & 0xff;
byte2 = (recByteSaved >> 8) & 0xff;
byte3 = (recByteSaved >> 16) & 0xff;
byte4 = (recByteSaved >> 24) & 0xff;
rec.write(byte1); rec.write(byte2); rec.write(byte3); rec.write(byte4);
rec.seek(40);
rec.write(byte1); rec.write(byte2); rec.write(byte3); rec.write(byte4);
rec.close();
}
void startRec(){
writeWavHeader();
tcStartCounter();
}
void stopRec(){
tcDisable();
writeOutHeader();
}
void writeWav(){
if (recByteCount % 1024 == 512 && record == true) {rec.write(buf00,512); recByteSaved+= 512; } // save buf01 to card
if (recByteCount % 1024 == 0 && record == true) { rec.write(buf01,512); recByteSaved+= 512; } // save buf02 to card
}
|
3c27fb914bf4afb264f0e5fc73bc3240316c9237
|
e4d765e5d919c1221888232cf177201ca330df5a
|
/src/inspector/v8-deep-serializer.cc
|
84bd48f8cc268cfc55019a0295305684712ce6b6
|
[
"SunPro",
"BSD-3-Clause",
"Apache-2.0"
] |
permissive
|
v8/v8
|
76d02c4a3ed542ab98118ccdc043b1d9bd1dc3f2
|
25933a97b1c4a4beeabc16da9694e66f37522457
|
refs/heads/main
| 2023-08-18T19:59:36.949512
| 2023-08-17T11:04:21
| 2023-08-18T19:13:45
| 24,420,506
| 23,260
| 4,890
|
NOASSERTION
| 2023-08-09T21:57:14
| 2014-09-24T15:24:30
|
C++
|
UTF-8
|
C++
| false
| false
| 14,803
|
cc
|
v8-deep-serializer.cc
|
// Copyright 2022 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/inspector/v8-deep-serializer.h"
#include <memory>
#include "include/v8-container.h"
#include "include/v8-context.h"
#include "include/v8-date.h"
#include "include/v8-exception.h"
#include "include/v8-regexp.h"
#include "src/inspector/protocol/Runtime.h"
#include "src/inspector/v8-serialization-duplicate-tracker.h"
#include "src/inspector/value-mirror.h"
namespace v8_inspector {
namespace {
using protocol::Response;
std::unique_ptr<protocol::Value> DescriptionForDate(
v8::Local<v8::Context> context, v8::Local<v8::Date> date) {
v8::Isolate* isolate = context->GetIsolate();
v8::TryCatch tryCatch(isolate);
v8::Local<v8::String> dateISOString = date->ToISOString();
return protocol::StringValue::create(
toProtocolString(isolate, dateISOString));
}
String16 DescriptionForRegExpFlags(v8::Local<v8::RegExp> value) {
String16Builder resultStringBuilder;
v8::RegExp::Flags flags = value->GetFlags();
if (flags & v8::RegExp::Flags::kHasIndices) resultStringBuilder.append('d');
if (flags & v8::RegExp::Flags::kGlobal) resultStringBuilder.append('g');
if (flags & v8::RegExp::Flags::kIgnoreCase) resultStringBuilder.append('i');
if (flags & v8::RegExp::Flags::kLinear) resultStringBuilder.append('l');
if (flags & v8::RegExp::Flags::kMultiline) resultStringBuilder.append('m');
if (flags & v8::RegExp::Flags::kDotAll) resultStringBuilder.append('s');
if (flags & v8::RegExp::Flags::kUnicode) resultStringBuilder.append('u');
if (flags & v8::RegExp::Flags::kUnicodeSets) {
resultStringBuilder.append('v');
}
if (flags & v8::RegExp::Flags::kSticky) resultStringBuilder.append('y');
return resultStringBuilder.toString();
}
Response SerializeRegexp(v8::Local<v8::RegExp> value,
v8::Local<v8::Context> context,
V8SerializationDuplicateTracker& duplicateTracker,
protocol::DictionaryValue& result) {
result.setString("type",
protocol::Runtime::DeepSerializedValue::TypeEnum::Regexp);
std::unique_ptr<protocol::DictionaryValue> resultValue =
protocol::DictionaryValue::create();
resultValue->setValue(protocol::String("pattern"),
protocol::StringValue::create(toProtocolString(
context->GetIsolate(), value->GetSource())));
String16 flags = DescriptionForRegExpFlags(value);
if (!flags.isEmpty()) {
resultValue->setValue(protocol::String("flags"),
protocol::StringValue::create(flags));
}
result.setValue("value", std::move(resultValue));
return Response::Success();
}
Response SerializeDate(v8::Local<v8::Date> value,
v8::Local<v8::Context> context,
V8SerializationDuplicateTracker& duplicateTracker,
protocol::DictionaryValue& result) {
result.setString("type",
protocol::Runtime::DeepSerializedValue::TypeEnum::Date);
std::unique_ptr<protocol::Value> dateDescription =
DescriptionForDate(context, value.As<v8::Date>());
result.setValue("value", std::move(dateDescription));
return Response::Success();
}
Response SerializeArrayValue(v8::Local<v8::Array> value,
v8::Local<v8::Context> context, int maxDepth,
v8::Local<v8::Object> additionalParameters,
V8SerializationDuplicateTracker& duplicateTracker,
std::unique_ptr<protocol::ListValue>* result) {
std::unique_ptr<protocol::ListValue> serializedValue =
protocol::ListValue::create();
uint32_t length = value->Length();
serializedValue->reserve(length);
for (uint32_t i = 0; i < length; i++) {
v8::Local<v8::Value> elementValue;
bool success = value->Get(context, i).ToLocal(&elementValue);
CHECK(success);
USE(success);
std::unique_ptr<protocol::DictionaryValue> elementProtocolValue;
Response response = ValueMirror::create(context, elementValue)
->buildDeepSerializedValue(
context, maxDepth - 1, additionalParameters,
duplicateTracker, &elementProtocolValue);
if (!response.IsSuccess()) return response;
serializedValue->pushValue(std::move(elementProtocolValue));
}
*result = std::move(serializedValue);
return Response::Success();
}
Response SerializeArray(v8::Local<v8::Array> value,
v8::Local<v8::Context> context, int maxDepth,
v8::Local<v8::Object> additionalParameters,
V8SerializationDuplicateTracker& duplicateTracker,
protocol::DictionaryValue& result) {
result.setString("type",
protocol::Runtime::DeepSerializedValue::TypeEnum::Array);
if (maxDepth > 0) {
std::unique_ptr<protocol::ListValue> serializedValue;
Response response =
SerializeArrayValue(value, context, maxDepth, additionalParameters,
duplicateTracker, &serializedValue);
if (!response.IsSuccess()) return response;
result.setValue("value", std::move(serializedValue));
}
return Response::Success();
}
Response SerializeMap(v8::Local<v8::Map> value, v8::Local<v8::Context> context,
int maxDepth, v8::Local<v8::Object> additionalParameters,
V8SerializationDuplicateTracker& duplicateTracker,
protocol::DictionaryValue& result) {
result.setString("type",
protocol::Runtime::DeepSerializedValue::TypeEnum::Map);
if (maxDepth > 0) {
std::unique_ptr<protocol::ListValue> serializedValue =
protocol::ListValue::create();
v8::Local<v8::Array> propertiesAndValues = value->AsArray();
uint32_t length = propertiesAndValues->Length();
serializedValue->reserve(length);
for (uint32_t i = 0; i < length; i += 2) {
v8::Local<v8::Value> keyV8Value, propertyV8Value;
std::unique_ptr<protocol::Value> keyProtocolValue;
std::unique_ptr<protocol::DictionaryValue> propertyProtocolValue;
bool success = propertiesAndValues->Get(context, i).ToLocal(&keyV8Value);
CHECK(success);
success =
propertiesAndValues->Get(context, i + 1).ToLocal(&propertyV8Value);
CHECK(success);
USE(success);
if (keyV8Value->IsString()) {
keyProtocolValue = protocol::StringValue::create(toProtocolString(
context->GetIsolate(), keyV8Value.As<v8::String>()));
} else {
std::unique_ptr<protocol::DictionaryValue> keyDictionaryProtocolValue;
Response response =
ValueMirror::create(context, keyV8Value)
->buildDeepSerializedValue(
context, maxDepth - 1, additionalParameters,
duplicateTracker, &keyDictionaryProtocolValue);
if (!response.IsSuccess()) return response;
keyProtocolValue = std::move(keyDictionaryProtocolValue);
}
Response response = ValueMirror::create(context, propertyV8Value)
->buildDeepSerializedValue(
context, maxDepth - 1, additionalParameters,
duplicateTracker, &propertyProtocolValue);
if (!response.IsSuccess()) return response;
std::unique_ptr<protocol::ListValue> keyValueList =
protocol::ListValue::create();
keyValueList->pushValue(std::move(keyProtocolValue));
keyValueList->pushValue(std::move(propertyProtocolValue));
serializedValue->pushValue(std::move(keyValueList));
}
result.setValue("value", std::move(serializedValue));
}
return Response::Success();
}
Response SerializeSet(v8::Local<v8::Set> value, v8::Local<v8::Context> context,
int maxDepth, v8::Local<v8::Object> additionalParameters,
V8SerializationDuplicateTracker& duplicateTracker,
protocol::DictionaryValue& result) {
result.setString("type",
protocol::Runtime::DeepSerializedValue::TypeEnum::Set);
if (maxDepth > 0) {
std::unique_ptr<protocol::ListValue> serializedValue;
Response response = SerializeArrayValue(value->AsArray(), context, maxDepth,
additionalParameters,
duplicateTracker, &serializedValue);
result.setValue("value", std::move(serializedValue));
}
return Response::Success();
}
Response SerializeObjectValue(v8::Local<v8::Object> value,
v8::Local<v8::Context> context, int maxDepth,
v8::Local<v8::Object> additionalParameters,
V8SerializationDuplicateTracker& duplicateTracker,
std::unique_ptr<protocol::ListValue>* result) {
std::unique_ptr<protocol::ListValue> serializedValue =
protocol::ListValue::create();
// Iterate through object's enumerable properties ignoring symbols.
v8::Local<v8::Array> propertyNames;
bool success =
value
->GetOwnPropertyNames(context,
static_cast<v8::PropertyFilter>(
v8::PropertyFilter::ONLY_ENUMERABLE |
v8::PropertyFilter::SKIP_SYMBOLS),
v8::KeyConversionMode::kConvertToString)
.ToLocal(&propertyNames);
CHECK(success);
uint32_t length = propertyNames->Length();
serializedValue->reserve(length);
for (uint32_t i = 0; i < length; i++) {
v8::Local<v8::Value> keyV8Value, propertyV8Value;
std::unique_ptr<protocol::Value> keyProtocolValue;
std::unique_ptr<protocol::DictionaryValue> propertyProtocolValue;
success = propertyNames->Get(context, i).ToLocal(&keyV8Value);
CHECK(success);
CHECK(keyV8Value->IsString());
v8::Maybe<bool> hasRealNamedProperty =
value->HasRealNamedProperty(context, keyV8Value.As<v8::String>());
// Don't access properties with interceptors.
if (hasRealNamedProperty.IsNothing() || !hasRealNamedProperty.FromJust()) {
continue;
}
keyProtocolValue = protocol::StringValue::create(
toProtocolString(context->GetIsolate(), keyV8Value.As<v8::String>()));
success = value->Get(context, keyV8Value).ToLocal(&propertyV8Value);
CHECK(success);
USE(success);
Response response = ValueMirror::create(context, propertyV8Value)
->buildDeepSerializedValue(
context, maxDepth - 1, additionalParameters,
duplicateTracker, &propertyProtocolValue);
if (!response.IsSuccess()) return response;
std::unique_ptr<protocol::ListValue> keyValueList =
protocol::ListValue::create();
keyValueList->pushValue(std::move(keyProtocolValue));
keyValueList->pushValue(std::move(propertyProtocolValue));
serializedValue->pushValue(std::move(keyValueList));
}
*result = std::move(serializedValue);
return Response::Success();
}
Response SerializeObject(v8::Local<v8::Object> value,
v8::Local<v8::Context> context, int maxDepth,
v8::Local<v8::Object> additionalParameters,
V8SerializationDuplicateTracker& duplicateTracker,
protocol::DictionaryValue& result) {
result.setString("type",
protocol::Runtime::DeepSerializedValue::TypeEnum::Object);
if (maxDepth > 0) {
std::unique_ptr<protocol::ListValue> serializedValue;
Response response = SerializeObjectValue(
value.As<v8::Object>(), context, maxDepth, additionalParameters,
duplicateTracker, &serializedValue);
if (!response.IsSuccess()) return response;
result.setValue("value", std::move(serializedValue));
}
return Response::Success();
}
} // namespace
Response V8DeepSerializer::serializeV8Value(
v8::Local<v8::Object> value, v8::Local<v8::Context> context, int maxDepth,
v8::Local<v8::Object> additionalParameters,
V8SerializationDuplicateTracker& duplicateTracker,
protocol::DictionaryValue& result) {
if (value->IsArray()) {
return SerializeArray(value.As<v8::Array>(), context, maxDepth,
additionalParameters, duplicateTracker, result);
}
if (value->IsRegExp()) {
return SerializeRegexp(value.As<v8::RegExp>(), context, duplicateTracker,
result);
}
if (value->IsDate()) {
return SerializeDate(value.As<v8::Date>(), context, duplicateTracker,
result);
}
if (value->IsMap()) {
return SerializeMap(value.As<v8::Map>(), context, maxDepth,
additionalParameters, duplicateTracker, result);
}
if (value->IsSet()) {
return SerializeSet(value.As<v8::Set>(), context, maxDepth,
additionalParameters, duplicateTracker, result);
}
if (value->IsWeakMap()) {
result.setString("type",
protocol::Runtime::DeepSerializedValue::TypeEnum::Weakmap);
return Response::Success();
}
if (value->IsWeakSet()) {
result.setString("type",
protocol::Runtime::DeepSerializedValue::TypeEnum::Weakset);
return Response::Success();
}
if (value->IsNativeError()) {
result.setString("type",
protocol::Runtime::DeepSerializedValue::TypeEnum::Error);
return Response::Success();
}
if (value->IsProxy()) {
result.setString("type",
protocol::Runtime::DeepSerializedValue::TypeEnum::Proxy);
return Response::Success();
}
if (value->IsPromise()) {
result.setString("type",
protocol::Runtime::DeepSerializedValue::TypeEnum::Promise);
return Response::Success();
}
if (value->IsTypedArray()) {
result.setString(
"type", protocol::Runtime::DeepSerializedValue::TypeEnum::Typedarray);
return Response::Success();
}
if (value->IsArrayBuffer()) {
result.setString(
"type", protocol::Runtime::DeepSerializedValue::TypeEnum::Arraybuffer);
return Response::Success();
}
if (value->IsFunction()) {
result.setString(
"type", protocol::Runtime::DeepSerializedValue::TypeEnum::Function);
return Response::Success();
}
// Serialize as an Object.
return SerializeObject(value.As<v8::Object>(), context, maxDepth,
additionalParameters, duplicateTracker, result);
}
} // namespace v8_inspector
|
c65ec8b09f4e8675437260375647bf638131bd20
|
0e111b47e28d580ac83394d829c820f6b4cee037
|
/src/architecture/arch/operands.hpp
|
63ef28b0d85a4992afeea2d5e7fed843e2b45371
|
[
"BSD-3-Clause"
] |
permissive
|
mrexodia/VTIL-Python
|
a9da9a38bde00b7ed8d71a65140868c61732c8b2
|
c847d8d8f5d2b42f6262d69e35d5378ffb202ef6
|
refs/heads/master
| 2022-11-15T04:40:56.018241
| 2020-07-03T18:18:17
| 2020-07-03T18:18:17
| 277,112,830
| 1
| 0
|
BSD-3-Clause
| 2020-07-04T13:14:45
| 2020-07-04T13:14:44
| null |
UTF-8
|
C++
| false
| false
| 4,841
|
hpp
|
operands.hpp
|
// BSD 3-Clause License
//
// Copyright (c) 2020, Daniel (@L33T), VTIL Project
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
// Furthermore, the following pieces of software have additional copyrights
// licenses, and/or restrictions:
//
// |--------------------------------------------------------------------------|
// | File name | Link for further information |
// |-------------------------|------------------------------------------------|
// | operands.hpp | https://github.com/vtil-project/VTIL-Core |
// | | https://github.com/pybind/pybind11 |
// |--------------------------------------------------------------------------|
//
#pragma once
#include <vtil/vtil>
#include <pybind11/pybind11.h>
using namespace vtil;
namespace py = pybind11;
namespace vtil::python
{
class operand_py : public py::class_<operand>
{
public:
operand_py( const handle& scope, const char* name )
: class_( scope, name )
{
py::class_<operand::immediate_t>( scope, "operand::immediate_t" )
// Constructor
//
.def( py::init<>() )
.def( py::init<uint64_t, bitcnt_t>() )
// Properties
//
.def_readwrite( "i64", &operand::immediate_t::i64 )
.def_readwrite( "u64", &operand::immediate_t::u64 )
.def_readwrite( "bit_count", &operand::immediate_t::bit_count )
// Functions
//
.def( "reduce", py::overload_cast< >( &operand::immediate_t::reduce ) )
;
( *this )
// Properties
//
.def_readwrite( "descriptor", &operand::descriptor )
// Functions
//
.def( "imm", py::overload_cast< >( &operand::imm ) )
.def( "reg", py::overload_cast< >( &operand::reg ) )
.def( "size", &operand::size )
.def( "bit_count", &operand::bit_count )
.def( "is_register", &operand::is_register )
.def( "is_immediate", &operand::is_immediate )
.def( "is_valid", &operand::is_valid )
.def( "reduce", py::overload_cast< >( &operand::reduce ) )
.def( "__str__", &operand::to_string )
.def( "__repr__", &operand::to_string )
// End
//
;
}
};
}
namespace pybind11::detail
{
template<> struct type_caster<operand> : public type_caster_base<operand>
{
using base = type_caster_base<operand>;
template<typename T>
bool explicit_cast( handle src )
{
return py::isinstance<T>( src ) && ( this->value = new operand( py::cast<T>( src ) ) );
}
public:
bool load( handle src, bool convert )
{
if ( py::isinstance<py::int_>( src ) )
{
auto value = py::cast<uint64_t>( src );
this->value = new operand( value, sizeof( value ) * 8 );
return true;
}
return explicit_cast< arm64_reg >( src ) || explicit_cast< x86_reg >( src ) || explicit_cast< register_desc >( src );
}
static handle cast( operand* src, return_value_policy policy, handle parent )
{
return base::cast( src, policy, parent );
}
static handle cast( const operand* src, return_value_policy policy, handle parent )
{
return base::cast( src, policy, parent );
}
static handle cast( operand& src, return_value_policy policy, handle parent )
{
return base::cast( src, policy, parent );
}
static handle cast( const operand& src, return_value_policy policy, handle parent )
{
return base::cast( src, policy, parent );
}
};
}
|
de35e51e7c30068c0df2bacd91834c027a7e88f4
|
275be98dd8acd6d6ec6d7181245fc44705b41ecc
|
/eikonal/test/linear_test.cpp
|
ff736785cccf000921e016a621ee7da287f8efe5
|
[] |
no_license
|
MiroK/eikonal
|
0f360f2a03405e556d9b482a759d40dee017dfa2
|
2b402dc005849ca8d5db4126e05e84fcba30e6e9
|
refs/heads/master
| 2021-01-10T22:10:18.370354
| 2013-11-10T17:06:35
| 2013-11-10T17:06:35
| 13,095,895
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,953
|
cpp
|
linear_test.cpp
|
#include "linear_test.h"
#include "Seeder.h"
#include "Problem.h"
#include "GmshMeshGenerator.h"
#include "RectangleMeshGenerator.h"
#include "gs/Solver.h"
#include "gs/LinMinSolver.h"
#include "gs/LinNewtonSolver.h"
#include "gs/FMMSolver.h"
namespace eikonal
{
int all_linear_tests(int solver, std::size_t precision)
{
enum SOLVERS {LIN_GEOMETRIC, LIN_BRENT, LIN_NEWTON, FMM_GEOMETRIC};
if(solver == LIN_GEOMETRIC)
{
std::cout << "Solving with linear geometric solver:" << std::endl;
run_linear_test<Solver>("point");
run_linear_test<Solver>("twocircle");
run_linear_test<Solver>("triangle");
run_linear_test<Solver>("zalesak");
}
if(solver == LIN_BRENT)
{
std::cout << "Solving with linear Brent solver" << std::endl;
std::cout << precision << std::endl;
run_linear_test<LinMinSolver>("point", precision);
run_linear_test<LinMinSolver>("twocircle", precision);
run_linear_test<LinMinSolver>("triangle", precision);
run_linear_test<LinMinSolver>("zalesak", precision);
}
if(solver == LIN_NEWTON)
{
std::cout << "Solving with linear Newton solver:" << std::endl;
std::cout << precision << std::endl;
run_linear_test<LinNewtonSolver>("point", precision);
run_linear_test<LinNewtonSolver>("twocircle", precision);
run_linear_test<LinNewtonSolver>("triangle", precision);
run_linear_test<LinNewtonSolver>("zalesak", precision);
}
if(solver == FMM_GEOMETRIC)
{
std::cout << "Solving with FMM geometric:" << std::endl;
std::cout << precision << std::endl;
run_linear_test<FMMSolver>("point", precision);
run_linear_test<FMMSolver>("twocircle", precision);
run_linear_test<FMMSolver>("triangle", precision);
run_linear_test<FMMSolver>("zalesak", precision);
}
return 1;
}
//---------------------------------------------------------------------------
}
|
c5f8cc130f8fc5d333ec7910b5e1c1dbc294e7c1
|
b54dfbf8573327c34a385fe968853b41d31aeecc
|
/db_other/AcctUnownerInfoHis.cc
|
99214f5ad90e34bbb748689b71bf7790933ede82
|
[] |
no_license
|
gaokewoo/boss
|
feb2b238d071af1a6055435a1626b06764c1f3c4
|
6f376a97e98d765c8e972b65aed765bd4a2f9113
|
refs/heads/master
| 2020-08-05T02:04:29.437573
| 2014-10-10T14:07:33
| 2014-10-10T14:07:33
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 788
|
cc
|
AcctUnownerInfoHis.cc
|
#include "AcctUnownerInfoHis.hh"
string AcctUnownerInfoHis::insSQL="INSERT INTO ACCT_UNOWNER_INFO_HIS(ACC_NBR,ITEM_SOURCE_ID,ACCT_ITEM_TYPE_ID,REGION_CODE,UNOWNER_FEE,INSERT_TIME,STATE,STATE_DATE)VALUES (:ACC_NBR,:ITEM_SOURCE_ID,:ACCT_ITEM_TYPE_ID,:REGION_CODE,:UNOWNER_FEE,SYSDATE,:STATE,SYSDATE)";
void AcctUnownerInfoHis::insertData()
{
setSQL(insSQL);
executeUpdate();
}
void AcctUnownerInfoHis::prepareSQL()
{
stmt->setString(1,acct_unowner_info_his.m_acc_nbr);
stmt->setNumber(2,acct_unowner_info_his.m_item_source_id);
stmt->setNumber(3,acct_unowner_info_his.m_acct_item_type_id);
stmt->setString(4,acct_unowner_info_his.m_region_code);
stmt->setNumber(5,acct_unowner_info_his.m_unowner_fee);
stmt->setString(6,acct_unowner_info_his.m_state);
}
|
a12a894577673543c8bbc5669458ffb2810bf7d1
|
32b8db47c9335f65aeb39848c928c3b64fc8a52e
|
/tgame-client-classes-20160829/CfgDescCpp/WeaponBuffCfg.pb.cc
|
204e5c248b5886c7b0f41b2989d4964b6ca73ea1
|
[] |
no_license
|
mengtest/backup-1
|
763dedbb09d662b0940a2cedffb4b9fd1f7fb35d
|
d9f34e5bc08fe88485ac82f8e9aa09b994bb0e54
|
refs/heads/master
| 2020-05-04T14:29:30.181303
| 2016-12-13T02:28:23
| 2016-12-13T02:28:23
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| true
| 14,686
|
cc
|
WeaponBuffCfg.pb.cc
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: WeaponBuffCfg.proto
#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION
#include "WeaponBuffCfg.pb.h"
#include <algorithm>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/once.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
// @@protoc_insertion_point(includes)
namespace com {
namespace cfg {
namespace vo {
void protobuf_ShutdownFile_WeaponBuffCfg_2eproto() {
delete WeaponBuffCfg::default_instance_;
delete WeaponBuffCfgSet::default_instance_;
}
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
void protobuf_AddDesc_WeaponBuffCfg_2eproto_impl() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
#else
void protobuf_AddDesc_WeaponBuffCfg_2eproto() {
static bool already_here = false;
if (already_here) return;
already_here = true;
GOOGLE_PROTOBUF_VERIFY_VERSION;
#endif
WeaponBuffCfg::default_instance_ = new WeaponBuffCfg();
WeaponBuffCfgSet::default_instance_ = new WeaponBuffCfgSet();
WeaponBuffCfg::default_instance_->InitAsDefaultInstance();
WeaponBuffCfgSet::default_instance_->InitAsDefaultInstance();
::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_WeaponBuffCfg_2eproto);
}
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AddDesc_WeaponBuffCfg_2eproto_once_);
void protobuf_AddDesc_WeaponBuffCfg_2eproto() {
::google::protobuf::::google::protobuf::GoogleOnceInit(&protobuf_AddDesc_WeaponBuffCfg_2eproto_once_,
&protobuf_AddDesc_WeaponBuffCfg_2eproto_impl);
}
#else
// Force AddDescriptors() to be called at static initialization time.
struct StaticDescriptorInitializer_WeaponBuffCfg_2eproto {
StaticDescriptorInitializer_WeaponBuffCfg_2eproto() {
protobuf_AddDesc_WeaponBuffCfg_2eproto();
}
} static_descriptor_initializer_WeaponBuffCfg_2eproto_;
#endif
// ===================================================================
#ifndef _MSC_VER
const int WeaponBuffCfg::kIDFieldNumber;
const int WeaponBuffCfg::kWeaponCfgIdFieldNumber;
const int WeaponBuffCfg::kWeaponLvFieldNumber;
const int WeaponBuffCfg::kWeaponColorFieldNumber;
#endif // !_MSC_VER
WeaponBuffCfg::WeaponBuffCfg()
: ::google::protobuf::MessageLite() {
SharedCtor();
}
void WeaponBuffCfg::InitAsDefaultInstance() {
}
WeaponBuffCfg::WeaponBuffCfg(const WeaponBuffCfg& from)
: ::google::protobuf::MessageLite() {
SharedCtor();
MergeFrom(from);
}
void WeaponBuffCfg::SharedCtor() {
_cached_size_ = 0;
id_ = 0u;
weaponcfgid_ = 0u;
weaponlv_ = 0u;
weaponcolor_ = 0u;
::memset(_has_bits_, 0, sizeof(_has_bits_));
}
WeaponBuffCfg::~WeaponBuffCfg() {
SharedDtor();
}
void WeaponBuffCfg::SharedDtor() {
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
if (this != &default_instance()) {
#else
if (this != default_instance_) {
#endif
}
}
void WeaponBuffCfg::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const WeaponBuffCfg& WeaponBuffCfg::default_instance() {
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
protobuf_AddDesc_WeaponBuffCfg_2eproto();
#else
if (default_instance_ == NULL) protobuf_AddDesc_WeaponBuffCfg_2eproto();
#endif
return *default_instance_;
}
WeaponBuffCfg* WeaponBuffCfg::default_instance_ = NULL;
WeaponBuffCfg* WeaponBuffCfg::New() const {
return new WeaponBuffCfg;
}
void WeaponBuffCfg::Clear() {
if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) {
id_ = 0u;
weaponcfgid_ = 0u;
weaponlv_ = 0u;
weaponcolor_ = 0u;
}
::memset(_has_bits_, 0, sizeof(_has_bits_));
}
bool WeaponBuffCfg::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!(EXPRESSION)) return false
::google::protobuf::uint32 tag;
while ((tag = input->ReadTag()) != 0) {
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// required uint32 ID = 1;
case 1: {
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
input, &id_)));
set_has_id();
} else {
goto handle_uninterpreted;
}
if (input->ExpectTag(16)) goto parse_WeaponCfgId;
break;
}
// required uint32 WeaponCfgId = 2;
case 2: {
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) {
parse_WeaponCfgId:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
input, &weaponcfgid_)));
set_has_weaponcfgid();
} else {
goto handle_uninterpreted;
}
if (input->ExpectTag(24)) goto parse_WeaponLv;
break;
}
// required uint32 WeaponLv = 3;
case 3: {
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) {
parse_WeaponLv:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
input, &weaponlv_)));
set_has_weaponlv();
} else {
goto handle_uninterpreted;
}
if (input->ExpectTag(32)) goto parse_WeaponColor;
break;
}
// required uint32 WeaponColor = 4;
case 4: {
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) {
parse_WeaponColor:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
input, &weaponcolor_)));
set_has_weaponcolor();
} else {
goto handle_uninterpreted;
}
if (input->ExpectAtEnd()) return true;
break;
}
default: {
handle_uninterpreted:
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
return true;
}
DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
break;
}
}
}
return true;
#undef DO_
}
void WeaponBuffCfg::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// required uint32 ID = 1;
if (has_id()) {
::google::protobuf::internal::WireFormatLite::WriteUInt32(1, this->id(), output);
}
// required uint32 WeaponCfgId = 2;
if (has_weaponcfgid()) {
::google::protobuf::internal::WireFormatLite::WriteUInt32(2, this->weaponcfgid(), output);
}
// required uint32 WeaponLv = 3;
if (has_weaponlv()) {
::google::protobuf::internal::WireFormatLite::WriteUInt32(3, this->weaponlv(), output);
}
// required uint32 WeaponColor = 4;
if (has_weaponcolor()) {
::google::protobuf::internal::WireFormatLite::WriteUInt32(4, this->weaponcolor(), output);
}
}
int WeaponBuffCfg::ByteSize() const {
int total_size = 0;
if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) {
// required uint32 ID = 1;
if (has_id()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt32Size(
this->id());
}
// required uint32 WeaponCfgId = 2;
if (has_weaponcfgid()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt32Size(
this->weaponcfgid());
}
// required uint32 WeaponLv = 3;
if (has_weaponlv()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt32Size(
this->weaponlv());
}
// required uint32 WeaponColor = 4;
if (has_weaponcolor()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt32Size(
this->weaponcolor());
}
}
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = total_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void WeaponBuffCfg::CheckTypeAndMergeFrom(
const ::google::protobuf::MessageLite& from) {
MergeFrom(*::google::protobuf::down_cast<const WeaponBuffCfg*>(&from));
}
void WeaponBuffCfg::MergeFrom(const WeaponBuffCfg& from) {
GOOGLE_CHECK_NE(&from, this);
if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
if (from.has_id()) {
set_id(from.id());
}
if (from.has_weaponcfgid()) {
set_weaponcfgid(from.weaponcfgid());
}
if (from.has_weaponlv()) {
set_weaponlv(from.weaponlv());
}
if (from.has_weaponcolor()) {
set_weaponcolor(from.weaponcolor());
}
}
}
void WeaponBuffCfg::CopyFrom(const WeaponBuffCfg& from) {
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool WeaponBuffCfg::IsInitialized() const {
if ((_has_bits_[0] & 0x0000000f) != 0x0000000f) return false;
return true;
}
void WeaponBuffCfg::Swap(WeaponBuffCfg* other) {
if (other != this) {
std::swap(id_, other->id_);
std::swap(weaponcfgid_, other->weaponcfgid_);
std::swap(weaponlv_, other->weaponlv_);
std::swap(weaponcolor_, other->weaponcolor_);
std::swap(_has_bits_[0], other->_has_bits_[0]);
std::swap(_cached_size_, other->_cached_size_);
}
}
::std::string WeaponBuffCfg::GetTypeName() const {
return "com.cfg.vo.WeaponBuffCfg";
}
// ===================================================================
#ifndef _MSC_VER
const int WeaponBuffCfgSet::kWeaponBuffCfgFieldNumber;
#endif // !_MSC_VER
WeaponBuffCfgSet::WeaponBuffCfgSet()
: ::google::protobuf::MessageLite() {
SharedCtor();
}
void WeaponBuffCfgSet::InitAsDefaultInstance() {
}
WeaponBuffCfgSet::WeaponBuffCfgSet(const WeaponBuffCfgSet& from)
: ::google::protobuf::MessageLite() {
SharedCtor();
MergeFrom(from);
}
void WeaponBuffCfgSet::SharedCtor() {
_cached_size_ = 0;
::memset(_has_bits_, 0, sizeof(_has_bits_));
}
WeaponBuffCfgSet::~WeaponBuffCfgSet() {
SharedDtor();
}
void WeaponBuffCfgSet::SharedDtor() {
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
if (this != &default_instance()) {
#else
if (this != default_instance_) {
#endif
}
}
void WeaponBuffCfgSet::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const WeaponBuffCfgSet& WeaponBuffCfgSet::default_instance() {
#ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER
protobuf_AddDesc_WeaponBuffCfg_2eproto();
#else
if (default_instance_ == NULL) protobuf_AddDesc_WeaponBuffCfg_2eproto();
#endif
return *default_instance_;
}
WeaponBuffCfgSet* WeaponBuffCfgSet::default_instance_ = NULL;
WeaponBuffCfgSet* WeaponBuffCfgSet::New() const {
return new WeaponBuffCfgSet;
}
void WeaponBuffCfgSet::Clear() {
weaponbuffcfg_.Clear();
::memset(_has_bits_, 0, sizeof(_has_bits_));
}
bool WeaponBuffCfgSet::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!(EXPRESSION)) return false
::google::protobuf::uint32 tag;
while ((tag = input->ReadTag()) != 0) {
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// repeated .com.cfg.vo.WeaponBuffCfg weaponBuffCfg = 1;
case 1: {
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) {
parse_weaponBuffCfg:
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, add_weaponbuffcfg()));
} else {
goto handle_uninterpreted;
}
if (input->ExpectTag(10)) goto parse_weaponBuffCfg;
if (input->ExpectAtEnd()) return true;
break;
}
default: {
handle_uninterpreted:
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
return true;
}
DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
break;
}
}
}
return true;
#undef DO_
}
void WeaponBuffCfgSet::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// repeated .com.cfg.vo.WeaponBuffCfg weaponBuffCfg = 1;
for (int i = 0; i < this->weaponbuffcfg_size(); i++) {
::google::protobuf::internal::WireFormatLite::WriteMessage(
1, this->weaponbuffcfg(i), output);
}
}
int WeaponBuffCfgSet::ByteSize() const {
int total_size = 0;
// repeated .com.cfg.vo.WeaponBuffCfg weaponBuffCfg = 1;
total_size += 1 * this->weaponbuffcfg_size();
for (int i = 0; i < this->weaponbuffcfg_size(); i++) {
total_size +=
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
this->weaponbuffcfg(i));
}
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = total_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void WeaponBuffCfgSet::CheckTypeAndMergeFrom(
const ::google::protobuf::MessageLite& from) {
MergeFrom(*::google::protobuf::down_cast<const WeaponBuffCfgSet*>(&from));
}
void WeaponBuffCfgSet::MergeFrom(const WeaponBuffCfgSet& from) {
GOOGLE_CHECK_NE(&from, this);
weaponbuffcfg_.MergeFrom(from.weaponbuffcfg_);
}
void WeaponBuffCfgSet::CopyFrom(const WeaponBuffCfgSet& from) {
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool WeaponBuffCfgSet::IsInitialized() const {
for (int i = 0; i < weaponbuffcfg_size(); i++) {
if (!this->weaponbuffcfg(i).IsInitialized()) return false;
}
return true;
}
void WeaponBuffCfgSet::Swap(WeaponBuffCfgSet* other) {
if (other != this) {
weaponbuffcfg_.Swap(&other->weaponbuffcfg_);
std::swap(_has_bits_[0], other->_has_bits_[0]);
std::swap(_cached_size_, other->_cached_size_);
}
}
::std::string WeaponBuffCfgSet::GetTypeName() const {
return "com.cfg.vo.WeaponBuffCfgSet";
}
// @@protoc_insertion_point(namespace_scope)
} // namespace vo
} // namespace cfg
} // namespace com
// @@protoc_insertion_point(global_scope)
|
f7d4f5e8bc31d6fc69a27d2e32f1625c7d100624
|
f74fd64254c149ae18ab5f471de04173eebc4d7b
|
/sheet1/decimal_to_binary.cpp
|
f10a8ac4ac861dbd63587a417f6b22957293af5e
|
[] |
no_license
|
prithvisbisht/CEC
|
05c66dc0d62a2f710a8429ec85cf8d7135312eaa
|
27f207571852732263f3975907559282e2df3ae8
|
refs/heads/master
| 2018-07-23T02:36:58.037678
| 2018-06-02T11:24:08
| 2018-06-02T11:24:08
| 118,794,708
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 537
|
cpp
|
decimal_to_binary.cpp
|
#include<iostream>
#include<sstream>
using namespace std;
namespace patch
{
template < typename T > std::string to_string( const T& n )
{
std::ostringstream stm ;
stm << n ;
return stm.str() ;
}
}
void tobinary(int num)
{
string s="";
while(num!=0)
{
int rem=num%2;
string temp=patch::to_string(rem);
s=temp+s;
num=num/2;
}
cout<<s;
}
int main(int argc, char const *argv[])
{
int num;
cout<<"enter number you want to convert in binary"<<endl;
cin>>num;
tobinary(num);
return 0;
}
|
6b08b226417932a3c6289551c46bf1d5c00a16eb
|
c51b9b0994649487903f43fc095726e4c15d0d9a
|
/Sources/SBEditor/Vec2.h
|
a231b114bd570871261c4aba24776733f283653b
|
[] |
no_license
|
danskcarvalho/ColorNShapes
|
e2374282b56e81afa5fe809cf27b5700a4b8fe79
|
b9e3a9600068a4c805adc975781e7255116699ce
|
refs/heads/master
| 2021-01-10T12:47:50.638990
| 2016-01-03T03:34:50
| 2016-01-03T03:34:50
| 44,114,244
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,116
|
h
|
Vec2.h
|
/**
Copyright (C) 2014 Danilo Carvalho - All Rights Reserved
You can't use, distribute or modify this code without my permission.
*/
#pragma once
#include "Utils.h"
namespace sb {
enum class RotationDirection {
shortest,
ccw,
cw
};
struct Vec2 {
public:
//Members
float x, y;
//Static Members
static const Vec2 up;
static const Vec2 down;
static const Vec2 left;
static const Vec2 right;
static const Vec2 zero;
static const Vec2 one;
//Constructors
inline Vec2() {
x = 0;
y = 0;
}
inline Vec2(float x, float y) {
this->x = x;
this->y = y;
}
//Basic Functions
//Length
inline float length() const {
return sqrt(x * x + y * y);
}
inline float squaredLength() const {
return x * x + y * y;
}
inline Vec2 normalized() const {
auto len = length();
return Vec2(x / len, y / len);
}
inline void normalize() {
auto len = length();
x /= len;
y /= len;
}
//Size Functions
inline float area() const {
return x * y;
}
inline float width() const {
return x;
}
inline float height() const {
return y;
}
inline void setWidth(float value) {
x = value;
}
inline void setHeight(float value) {
y = value;
}
//Tests
inline bool isZero(bool almost = false) const {
return almost ? (aeq(x, 0) && aeq(y, 0)) : (x == 0 && y == 0);
}
inline bool isUnit(bool almost = false) const {
auto len = squaredLength();
return almost ? aeq(len, 1) : len == 1;
}
inline bool isPerpendicularTo(const Vec2& another, bool almost = false) const {
auto dt = x * another.x + y * another.y;
return almost ? aeq(dt, 0) : dt == 0;
}
inline bool isParallelTo(const Vec2& another, bool almost = false) const {
auto dt = x * another.x + y * another.y;
auto shouldBeZero = dt * dt - this->squaredLength() * another.squaredLength();
return almost ? aeq(shouldBeZero, 0) : shouldBeZero == 0;
}
inline bool pointsAtSameDirection(const Vec2& another) const {
auto dt = x * another.x + y * another.y;
return dt >= 0;
}
//Angle
inline float angleBetween(Vec2 another, RotationDirection rd = RotationDirection::shortest) const {
if (this->isZero() || another.isZero())
return 0;
auto dt = x * another.x + y * another.y;
dt /= length() * another.length();
if (rd == RotationDirection::shortest)
return acosf(dt);
else {
auto c = x * another.y - another.x * y;
if (c == 0) //it may be 0 or +PI
{
if (this->pointsAtSameDirection(another)) {
return 0;
}
else {
return (float)SbPI;
}
}
if (rd == RotationDirection::ccw) {
if (c > 0) {
return acosf(dt);
}
else {
return 2 * (float)SbPI - acosf(dt);
}
}
else {
if (c > 0) {
return 2 * (float)SbPI - acosf(dt);
}
else {
return acosf(dt);
}
}
}
}
inline bool isBetween(const Vec2& v1, const Vec2& v2) const {
auto c1 = sign(v1.x * v2.y - v2.x * v1.y);
auto c2 = sign(v1.x * y - x * v1.y);
auto c3 = sign(x * v2.y - v2.x * y);
return c1 == c2 && c2 == c3;
}
//Projection
inline void projectOver(const Vec2& v) {
auto nv = v.normalized();
auto dt = x * nv.x + y * nv.y;
x = nv.x * dt;
y = nv.y * dt;
}
inline Vec2 projectionOver(const Vec2& v) const {
auto nv = v.normalized();
auto dt = x * nv.x + y * nv.y;
return Vec2(nv.x * dt, nv.y * dt);
}
//Rotation
inline void rotate90() {
auto sx = x;
x = -y;
y = sx;
}
inline Vec2 rotated90() const {
auto v = *this;
v.rotate90();
return v;
}
inline void rotateBy(float angle) {
auto v = *this;
auto cos0 = cosf(angle);
auto sin0 = sinf(angle);
v.x = x * cos0 - y * sin0;
v.y = x * sin0 + y * cos0;
*this = v;
}
inline Vec2 rotatedBy(float angle) const {
auto v = *this;
auto cos0 = cosf(angle);
auto sin0 = sinf(angle);
v.x = x * cos0 - y * sin0;
v.y = x * sin0 + y * cos0;
return v;
}
//Description
inline std::string toString() const {
return "{" + std::to_string(x) + " , " + std::to_string(y) + "}";
}
//Operators
inline Vec2& operator+=(const Vec2& v2) {
this->x += v2.x;
this->y += v2.y;
return *this;
}
inline Vec2& operator*=(const Vec2& v2) {
this->x *= v2.x;
this->y *= v2.y;
return *this;
}
inline Vec2& operator-=(const Vec2& v2) {
this->x -= v2.x;
this->y -= v2.y;
return *this;
}
inline Vec2& operator*=(float s) {
this->x *= s;
this->y *= s;
return *this;
}
inline Vec2& operator/=(const Vec2& v2) {
this->x /= v2.x;
this->y /= v2.y;
return *this;
}
inline Vec2& operator/=(float s) {
this->x /= s;
this->y /= s;
return *this;
}
};
inline Vec2 operator +(const Vec2& v1) {
return v1;
}
inline Vec2 operator -(const Vec2& v1) {
return Vec2(-v1.x, -v1.y);
}
inline Vec2 operator+(const Vec2& v1, const Vec2& v2) {
return Vec2(v1.x + v2.x, v1.y + v2.y);
}
inline Vec2 operator-(const Vec2& v1, const Vec2& v2) {
return Vec2(v1.x - v2.x, v1.y - v2.y);
}
inline Vec2 operator*(const Vec2& v1, const Vec2& v2) {
return Vec2(v1.x * v2.x, v1.y * v2.y);
}
inline Vec2 operator*(const Vec2& v1, float s) {
return Vec2(v1.x * s, v1.y * s);
}
inline Vec2 operator*(float s, const Vec2& v1) {
return Vec2(v1.x * s, v1.y * s);
}
inline Vec2 operator/(const Vec2& v1, const Vec2& v2) {
return Vec2(v1.x / v2.x, v1.y / v2.y);
}
inline Vec2 operator/(const Vec2& v1, float s) {
return Vec2(v1.x / s, v1.y / s);
}
inline bool operator==(const Vec2& v1, const Vec2& v2) {
return v1.x == v2.x && v1.y == v2.y;
}
inline bool operator!=(const Vec2& v1, const Vec2& v2) {
return v1.x != v2.x || v1.y != v2.y;
}
inline bool operator>(const Vec2& v1, const Vec2& v2) {
if (v1.x == v2.x) {
return v1.y > v2.y;
}
else {
return v1.x > v2.x;
}
}
inline bool operator<(const Vec2& v1, const Vec2& v2) {
if (v1.x == v2.x) {
return v1.y < v2.y;
}
else {
return v1.x < v2.x;
}
}
inline bool operator>=(const Vec2& v1, const Vec2& v2) {
if (v1.x == v2.x && v1.y == v2.y)
return true;
if (v1.x == v2.x)
return v1.y > v2.y;
else
return v1.x > v2.x;
}
inline bool operator<=(const Vec2& v1, const Vec2& v2) {
if (v1.x == v2.x && v1.y == v2.y)
return true;
if (v1.x == v2.x)
return v1.y < v2.y;
else
return v1.x < v2.x;
}
inline bool aeq(const Vec2& v1, const Vec2& v2) {
return aeq(v1.x, v2.x) && aeq(v1.y, v2.y);
}
inline float dot(const Vec2& v1, const Vec2& v2) {
return v1.x * v2.x + v1.y * v2.y;
}
inline float distance(const Vec2& v1, const Vec2& v2) {
auto dx = v1.x - v2.x;
auto dy = v1.y - v2.y;
return sqrt(dx * dx + dy * dy);
}
inline float cross(const Vec2& v1, const Vec2& v2) {
return v1.x * v2.y - v2.x * v1.y;
}
inline Vec2 lerp(float t, const Vec2& v1, const Vec2& v2) {
return (1 - t) * v1 + t * v2;
}
}
namespace std {
template<>
class hash < sb::Vec2 > {
public:
size_t operator()(const sb::Vec2& v) const {
return sb::bitwiseHash((const unsigned char*)&v, sizeof(sb::Vec2));
}
};
}
|
c6f69e08424c7d280fad0e7a86de331fb52f0d7e
|
fe479340153355e43d3ce3f3c3d058b7764d2a98
|
/Projects/Base/Util/Formatter.h
|
37b63444d6cb8e419b8f0fa010a024a220709391
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
LudoSapiens/Dev
|
8496490eda1c4ca4288a841c8cbabb8449135125
|
8ad0be9088d2001ecb13a86d4e47e6c8c38f0f2d
|
refs/heads/master
| 2016-09-16T11:11:56.224090
| 2013-04-17T01:55:59
| 2013-04-17T01:55:59
| 9,486,806
| 4
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,697
|
h
|
Formatter.h
|
/*=============================================================================
Copyright (c) 2012, Ludo Sapiens Inc. and contributors.
See accompanying file LICENSE.txt for details.
=============================================================================*/
#ifndef BASE_FORMATTER_H
#define BASE_FORMATTER_H
#include <Base/StdDefs.h>
#include <Base/IO/TextStream.h>
NAMESPACE_BEGIN
/*==============================================================================
CLASS ValueSuffix
==============================================================================*/
//!< A pair of double+suffix which is used as a transient value for formatting.
class ValueSuffix
{
public:
inline ValueSuffix( double value, const char* suffix ):
_value( value ), _suffix( suffix ) {}
inline String toStr() const
{
return String().format( "%g %s", _value, _suffix );
}
inline operator double() const { return _value; }
inline double value() const { return _value; }
inline const char* suffix() const { return _suffix; }
protected:
double _value;
const char* _suffix;
};
//------------------------------------------------------------------------------
//!
inline TextStream& operator<<( TextStream& os, const ValueSuffix& v )
{
return os << v.toStr();
}
//------------------------------------------------------------------------------
//! Converts a size into a human-readable version.
//! The @si parameter specifies that we want base-10 units (1000 increments)
//! as opposed to the base-2 units (1024 increments).
BASE_DLL_API ValueSuffix humanReadableSize( size_t s, bool si = false );
NAMESPACE_END
#endif //BASE_FORMATTER_H
|
eaa673195beb79e28ce9620ebe2926696847decd
|
4a70a3a8a929b80f6adc093557a5f0daead6d1f9
|
/UR5_demo/receiveMessagesUR5.h
|
bb78e028cc24968dc1909becd3bc4f65b1b6d684
|
[
"MIT"
] |
permissive
|
wwkkww1983/UR5_demo
|
1af2f27dc91c929b929830099495f1721a6ec754
|
4a09a7fa551d6f3abba07c66e9eda24f10d19505
|
refs/heads/master
| 2023-06-23T14:25:27.785913
| 2021-07-26T04:01:57
| 2021-07-26T04:01:57
| null | 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 1,351
|
h
|
receiveMessagesUR5.h
|
#pragma once
#include <WinSock2.h>
#include <sstream>
#include <iostream>
using namespace std;
#define MSGSIZE 1220
#define SAFETY_MODE_UNDEFINED_SAFETY_MODE 11
#define SAFETY_MODE_VALIDATE_JOINT_ID 10
#define SAFETY_MODE_FAULT 9
#define SAFETY_MODE_VIOLATION 8
#define SAFETY_MODE_ROBOT_EMERGENCY_STOP 7
#define SAFETY_MODE_SYSTEM_EMERGENCY_STOP 6
#define SAFETY_MODE_SAFEGUARD_STOP 5
#define SAFETY_MODE_RECOVERY 4
#define SAFETY_MODE_PROTECTIVE_STOP 3
#define SAFETY_MODE_REDUCED 2
#define SAFETY_MODE_NORMAL 1
//由于UR返回数据为Big-Endian,而计算机中的数据为Little-Endian,必须进行数据字节转换,所以编了以下两个函数完成
double GetDouble(PBYTE pData);
//实际上GetDword函数和htonl()函数功能一样
DWORD GetDword(PBYTE pData);
//按照UR机器人的30003端口返回数据格式进行解析
double OnRecvData(char* pData, int &nLen, double jointAngles[], double tcpPos[]);
int checkRecvData_len(SOCKET sock); //检查数据包长度是不是MSGSIZE
void RecvData_jointAngles(char* pData, double jointAngles[]); //关节角
void RecvData_tcpPos(char* pData, double tcpPos[]); //tcp位姿
int RecvData_safetyMode(char* pData); //安全模式,检查是否有报错
bool checkRecvData_speed(SOCKET sock); //关节是否还在运动, 返回值false表示出现异常
|
d3678cf054076daa888f83f2642c1eb1fe6227a1
|
50be99b8ad59f9c6a158dfe3007c54b8c88ac82a
|
/SLS_4DOF/BMP.cpp
|
bbac7e8f3b61b13ec307262081ebc4af2d16f213
|
[] |
no_license
|
mikihiroikura/SLS-Simulator
|
c84b6c3d160836120f8b736c7a1a3bce9963dfe7
|
42f83bacba7056b02697073d1514c12fe7d672a4
|
refs/heads/master
| 2020-04-01T18:22:04.581967
| 2018-10-17T16:18:20
| 2018-10-17T16:18:20
| 153,487,800
| 0
| 0
| null | null | null | null |
SHIFT_JIS
|
C++
| false
| false
| 2,861
|
cpp
|
BMP.cpp
|
#include "BMP.h"
/////////////////////////////////////////////////////////////////////////
// BMPヘッダの初期値
/////////////////////////////////////////////////////////////////////////
void initHeaders(BitmapHeaders *file){
file->filetype1 ='B';
file->filetype2 ='M';
file->filesize = 0;
file->reserve1 = 0;
file->reserve2 = 0;
file->offset = 54;
file->header =40;
file->width = 0;
file->height = 0;
file->planes = 1;
file->bit_count =24;
file->compression = 0;
file->size_image = 0;
file->x_resolution = 0;
file->y_resolution = 0;
file->clr_used = 0;
file->clr_important = 0;
};
/////////////////////////////////////////////////////////////////////////
// BMPヘッダの書込
/////////////////////////////////////////////////////////////////////////
void writeHeaders(BitmapHeaders *file,FILE *fp){
fwrite(&(file->filetype1), sizeof(char),1,fp);
fwrite(&(file->filetype2), sizeof(char),1,fp);
fwrite(&(file->filesize), sizeof(int),1,fp);
fwrite(&(file->reserve1), sizeof(short),1,fp);
fwrite(&(file->reserve2), sizeof(short),1,fp);
fwrite(&(file->offset), sizeof(int),1,fp);
fwrite(&(file->header), sizeof(int),1,fp);
fwrite(&(file->width), sizeof(int),1,fp);
fwrite(&(file->height), sizeof(int),1,fp);
fwrite(&(file->planes), sizeof(short),1,fp);
fwrite(&(file->bit_count), sizeof(short),1,fp);
fwrite(&(file->compression), sizeof(int),1,fp);
fwrite(&(file->size_image), sizeof(int),1,fp);
fwrite(&(file->x_resolution), sizeof(int),1,fp);
fwrite(&(file->y_resolution), sizeof(int),1,fp);
fwrite(&(file->clr_used), sizeof(int),1,fp);
fwrite(&(file->clr_important), sizeof(int),1,fp);
}
/////////////////////////////////////////////////////////////////////////
// 描画データのBMPファイルへの書込
// widthとheightは4の倍数である必要あり
/////////////////////////////////////////////////////////////////////////
int writeBMP(const char* filename,int width, int height){
int x, y;
BitmapHeaders file;
FILE *fp;
GLubyte *pixel_data;
// メモリ領域確保
pixel_data = (GLubyte*)malloc((width*3)*(height)*(sizeof(GLubyte)));
glReadPixels(0,0,width,height,GL_RGB,GL_UNSIGNED_BYTE,pixel_data);
// ファイルオープン
fp = fopen(filename, "wb");
if(fp==NULL){
printf("failure\n");
return -1;
}
// BMPヘッダの初期化
initHeaders(&file);
// BMPヘッダの書込
file.width = width;
file.height = height;
file.filesize =(width*3)*height+54;
writeHeaders(&file,fp);
// BMPピクセルデータの書込
for(y=0;y<height;y++){
for(x=0;x<width;x++){
fwrite((pixel_data+x*3+(width*3)*y+2),sizeof(GLubyte),1,fp);
fwrite((pixel_data+x*3+(width*3)*y+1),sizeof(GLubyte),1,fp);
fwrite((pixel_data+x*3+(width*3)*y+0),sizeof(GLubyte),1,fp);
}
}
// メモリ開放
free(pixel_data);
// ファイルクローズ
fclose(fp);
return 0;
}
|
6754e9cec620580c72a22d2a86e5656b6090cfc3
|
3082fc11f32c945e6129b5c4ee54ffbfae97fbca
|
/JoshLewis_Proj9.cpp
|
cf83fd8bdee232ffe1216045be3d334fdd147344
|
[] |
no_license
|
l3e0wu1f/cpp
|
a3e046d3bb8dd515601f76b86edeecb972bf5cda
|
a788d008a75df6c1c7e4e76909f07ca451d6cf06
|
refs/heads/main
| 2022-04-10T03:15:31.436021
| 2020-03-26T16:20:52
| 2020-03-26T16:20:52
| 250,307,239
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,537
|
cpp
|
JoshLewis_Proj9.cpp
|
//
// JoshLewisProj9.cpp
//
//
// Created by Josh Lewis on 12/6//17.
//
//
#include <iostream>
using namespace std;
int str_length(char s[], int start);
// Recursive version of strlen.
// It returns the length of the substring from s[start] to
// the char before '\0',
// inclusive. When str_length(s,0) is called,
// the length of s is returned.
int sum(int n);
// Recursive version to calculate the sum of
// 1 + 2 + .... + n
int main() {
char choice;
do{
// test str_length function
char sentence[80];
cout << "Enter a sentence: ";
cin.getline(sentence, 80);
cout << "There are " << str_length(sentence,0) << " characters in the sentence, including white spaces." << endl;
//test sum function
int n;
cout << "Enter a number: ";
cin >> n;
cout << "The sum of 1 + 2 + ... + " << n << " is: " << sum(n) << "." << endl;
cout << "Do you want to have another run? Y/N: ";
cin >> choice;
while(choice != Y && choice != y && choice != N && choice != n){
cout << "Not a valid entry. Please type Y to continue or N to quit: ";
cin >> choice;
}
} while(choice == 'Y' || choice == 'y');
cout << "Goodbye!";
return 0;
}
int str_length(char s[], int start){
if(s[start] == '\0') // start is the index of '\0'
return 0;
return 1 + str_length(s, start+1);
}
int sum(int n){
if(n != 0)
return n + sum(n - 1);
return 0;
}
|
ba8f06d49d8856e9713b42a97750845c781f5efb
|
8edc9fcde2e6a16a5e268a4c7acfbddf50319775
|
/src/aloha_node.cpp
|
3c7e4d418269aa787152fa76b6ed8f93de8f33e5
|
[
"MIT"
] |
permissive
|
ashariati/pulson_ros
|
676a678fa97c766aa65b83406a9679070319f74d
|
92ac115e3d8e24dc1cc9a5a0ceec268b61acae0b
|
refs/heads/master
| 2020-12-24T07:53:09.547145
| 2017-08-17T16:35:17
| 2017-08-17T16:35:17
| 59,228,435
| 2
| 6
|
MIT
| 2019-07-31T23:04:04
| 2016-05-19T17:38:03
|
C
|
UTF-8
|
C++
| false
| false
| 10,733
|
cpp
|
aloha_node.cpp
|
#include <ros/ros.h>
#include <pulson_ros/P4xx/RangeNet/rcmIf.h>
#include <pulson_ros/P4xx/RangeNet/rcm.h>
#include <pulson_ros/P4xx/RangeNet/ALOHA/rn.h>
#include <pulson_ros/RangeNetNDBEntry.h>
#include <pulson_ros/RangeNetNDB.h>
void init(int node_id,
rcmConfiguration *rcmConfig,
rnConfiguration *rnConfig,
rnALOHAConfiguration *rnAlohaConfig);
void cleanup();
void configure_radio(
int rate,
rcmConfiguration *rcmConfig,
rnConfiguration *rnConfig,
rnALOHAConfiguration *rnAlohaConfig);
void print_status(rcrmMsg_GetStatusInfoConfirm *statusInfo);
void print_rcm_configuration(rcmConfiguration *config);
void print_rn_configuration(rnConfiguration *rnConfig);
void print_rn_aloha_configuration(rnALOHAConfiguration *rnAlohaConfig);
void error_check(int r, const char *msg);
int main(int argc, char **argv)
{
ros::init(argc, argv, "aloha_node");
ros::NodeHandle nh("~");
// parameters
int rate;
int node_id;
nh.param("rate", rate, 10);
nh.param("node_id", node_id, 100);
// publisher
ros::Publisher database_pub = nh.advertise<pulson_ros::RangeNetNDB>("/range_net_db", 100);
// configurations
rcmConfiguration rcmConfig;
rnConfiguration rnConfig;
rnALOHAConfiguration rnAlohaConfig;
// initialize
init(node_id, &rcmConfig, &rnConfig, &rnAlohaConfig);
// configure radio
configure_radio(rate, &rcmConfig, &rnConfig, &rnAlohaConfig);
// P4xx messages datastructures
rcmMsg_FullRangeInfo rangeInfo;
rnMsg_GetFullNeighborDatabaseConfirm ndbInfo;
int r;
ros::Rate loop_rate(rate);
while (ros::ok())
{
// get data
r = rcmInfoGet(&rangeInfo, &ndbInfo);
// ROS message
pulson_ros::RangeNetNDB ndb;
// build message
ndb.host_node = node_id;
ndb.message_id = ndbInfo.msgId;
ndb.number_of_neighbor_entries = ndbInfo.numNeighborEntries;
for (int i = 0; i < ndbInfo.numNeighborEntries; i++)
{
// ROS NDB entry
pulson_ros::RangeNetNDBEntry entry;
// build
entry.node_id = ndbInfo.neighbors[i].nodeId;
entry.range_status = ndbInfo.neighbors[i].rangeStatus;
entry.antenna_mode = ndbInfo.neighbors[i].antennaMode;
entry.stopwatch_time = ndbInfo.neighbors[i].stopwatchTime;
entry.range = ndbInfo.neighbors[i].rangeMm;
entry.range_error = ndbInfo.neighbors[i].rangeErrorEstimate;
entry.range_velocity = ndbInfo.neighbors[i].rangeVelocity;
entry.range_measurement_type = ndbInfo.neighbors[i].rangeMeasurementType;
entry.flags = ndbInfo.neighbors[i].flags;
entry.stats_age_ms = ndbInfo.neighbors[i].statsAgeMs;
entry.range_update_timestamp_ms = ndbInfo.neighbors[i].rangeUpdateTimestampMs;
entry.last_heard_timestamp_ms = ndbInfo.neighbors[i].lastHeardTimestampMs;
entry.added_to_ndb_timestamp_ms = ndbInfo.neighbors[i].addedToNDBTimestampMs;
// save
ndb.database.push_back(entry);
}
// publish
database_pub.publish(ndb);
}
cleanup();
}
void init(int node_id,
rcmConfiguration *rcmConfig,
rnConfiguration *rnConfig,
rnALOHAConfiguration *rnAlohaConfig)
{
int r;
ROS_INFO("Initialization...");
// convert node_id to char*
char n[4];
sprintf(n, "%d", node_id);
// initialize interface
r = rcmIfInit(rcmIfUsb, n);
error_check(r, "Initialization failed");
// put in idle mode during configuration
r = rcmSleepModeSet(RCRM_SLEEP_MODE_IDLE);
error_check(r, "Time out waiting for sleep mode set");
// set to RCM mode
r = rcmOpModeSet(RCRM_OPMODE_RCM);
error_check(r, "Time out waiting for opmode set");
// execute Built-In Test
int status;
r = rcmBit(&status);
error_check(r, "Timeout waiting for BIT");
error_check(status, "Built-in test failed");
// get status information from RCM
rcrmMsg_GetStatusInfoConfirm statusInfo;
r = rcmStatusInfoGet(&statusInfo);
error_check(r, "Timeout waiting for status information");
print_status(&statusInfo);
// Check RCM configuration
r = rcmConfigGet(rcmConfig);
error_check(r, "Timeout waiting for rcmConfig confirm");
print_rcm_configuration(rcmConfig);
// Check RN configuration
r = rnConfigGet(rnConfig);
error_check(r, "Time out waiting for rnConfig confirm");
print_rn_configuration(rnConfig);
// Check ALOHA configuration
r = rnAlohaConfigGet(rnAlohaConfig);
error_check(r, "Time out waiting for rnAlohaConfig confirm");
print_rn_aloha_configuration(rnAlohaConfig);
}
void cleanup()
{
int r;
// return to idle
r = rcmSleepModeSet(RCRM_SLEEP_MODE_IDLE);
error_check(r, "Time out waiting for sleep mode set");
// return to RCM mode
r = rcmOpModeSet(RCRM_OPMODE_RCM);
error_check(r, "Time out waiting for opmode set");
// Flush any pending messages
rcmIfFlush();
// cleanup
rcmIfClose();
}
void configure_radio(
int rate,
rcmConfiguration *rcmConfig,
rnConfiguration *rnConfig,
rnALOHAConfiguration *rnAlohaConfig)
{
ROS_INFO("Configuring...");
int r;
// Set RCM configuration
rcmConfig->flags &= ~RCM_FLAG_ENABLE_ECHO_LAST_RANGE; // Set ELR
rcmConfig->flags &= ~RCM_SEND_SCANINFO_PKTS; // Clear Scans
rcmConfig->flags &= ~RCM_SEND_FULL_SCANINFO_PKTS; // Clear Full Scans
rcmConfig->flags |= RCM_DISABLE_CRE_RANGES; // Disable CRE Ranges (note: setting the bit disables the sending of CREs)
r = rcmConfigSet(rcmConfig);
error_check(r, "Time out waiting for rcmConfig confirm");
print_rcm_configuration(rcmConfig);
// Moving on to RangeNet configuration
rnConfig->autosendType &= ~RN_AUTOSEND_RANGEINFO_FLAGS_MASK; // clear
rnConfig->autosendType &= ~RN_AUTOSEND_NEIGHBOR_DATABASE_FLAGS_MASK; // clear
rnConfig->autosendType |= RN_AUTOSEND_NEIGHBOR_DATABASE_FULL;
rnConfig->rnFlags &= ~RN_CONFIG_FLAG_DO_NOT_RANGE_TO_ME; // Ensure Do Not Range To Me flag is not set
rnConfig->autosendNeighborDbUpdateIntervalMs = (int) ((1 / rate) * 1000);
r = rnConfigSet(rnConfig);
error_check(r, "Time out waiting for rnConfig confirm");
print_rn_configuration(rnConfig);
// Finally set up ALOHA configuration
rnAlohaConfig->flags &= 0;
rnAlohaConfig->flags |= RN_ALOHA_CONFIG_FLAG_USE_ACC;
rnAlohaConfig->maxRequestDataSize = 0; // Let's not have any data this time around
rnAlohaConfig->maxResponseDataSize = 0;
r = rnAlohaConfigSet(rnAlohaConfig);
error_check(r, "Time out waiting for rnAlohaConfig confirm");
print_rn_aloha_configuration(rnAlohaConfig);
// Put into RangeNet Mode
r = rcmOpModeSet(RCRM_OPMODE_RN);
error_check(r, "Time out waiting for opmode set");
// Put into active mode
r = rcmSleepModeSet(RCRM_SLEEP_MODE_ACTIVE);
error_check(r, "Time out waiting for sleep mode set");
// Flush any pending messages
rcmIfFlush();
}
void print_status(rcrmMsg_GetStatusInfoConfirm *statusInfo)
{
char buf[1024];
sprintf(buf, "\n\tStatus Information:\n");
sprintf(buf, "%s\t\tPackage Version: %s\n", buf, statusInfo->packageVersionStr);
sprintf(buf, "%s\t\tRCM Version: %d.%d Build %d\n", buf,
statusInfo->appVersionMajor,
statusInfo->appVersionMinor,
statusInfo->appVersionBuild);
sprintf(buf, "%s\t\tUWB Kernel Version: %d.%d Build %d\n", buf,
statusInfo->uwbKernelVersionMajor,
statusInfo->uwbKernelVersionMinor,
statusInfo->uwbKernelVersionBuild);
sprintf(buf, "%s\t\tFirmware Version: %x/%x/%x Ver. %X\n", buf,
statusInfo->firmwareMonth,
statusInfo->firmwareDay,
statusInfo->firmwareYear,
statusInfo->firmwareVersion);
sprintf(buf, "%s\t\tSerial Number: %08X\n", buf, statusInfo->serialNum);
sprintf(buf, "%s\t\tBoard Revision: %c\n", buf, statusInfo->boardRev);
sprintf(buf, "%s\t\tTemperature: %.2f degC\n", buf, statusInfo->temperature/4.0);
ROS_INFO("[aloha_node] %s", buf);
}
void print_rcm_configuration(rcmConfiguration *rcmConfig)
{
char buf[1024];
sprintf(buf, "\n\tRCM Configuration:\n");
sprintf(buf, "%s\t\tNode ID: %d\n", buf, rcmConfig->nodeId);
sprintf(buf, "%s\t\tIntegration Index: %d\n", buf, rcmConfig->integrationIndex);
sprintf(buf, "%s\t\tAntenna Mode: %d\n", buf, rcmConfig->antennaMode);
sprintf(buf, "%s\t\tCode Channel: %d\n", buf, rcmConfig->codeChannel);
sprintf(buf, "%s\t\tElectrical Delay PsA: %d\n", buf, rcmConfig->electricalDelayPsA);
sprintf(buf, "%s\t\tElectrical Delay PsB: %d\n", buf, rcmConfig->electricalDelayPsB);
sprintf(buf, "%s\t\tFlags: 0x%X\n", buf, rcmConfig->flags);
sprintf(buf, "%s\t\ttxGain: %d\n", buf, rcmConfig->txGain);
ROS_INFO("[aloha_node] %s", buf);
}
void print_rn_configuration(rnConfiguration *rnConfig)
{
char buf[1024];
sprintf(buf, "\n\tRN Configuration: \n");
sprintf(buf, "%s\t\tMax Neighbor Age Ms: %d\n", buf,
rnConfig->maxNeighborAgeMs);
sprintf(buf, "%s\t\tAuto Send NDB Update Interval Ms: %d\n", buf,
rnConfig->autosendNeighborDbUpdateIntervalMs);
sprintf(buf, "%s\t\tRN Flags: 0x%X\n", buf, rnConfig->rnFlags);
sprintf(buf, "%s\t\tNetwork Sync Mode: %d\n", buf, rnConfig->networkSyncMode);
sprintf(buf, "%s\t\tAuto Send Type: 0x%X\n", buf, rnConfig->autosendType);
sprintf(buf, "%s\t\tDefault If: %d\n", buf, rnConfig->defaultIf);
sprintf(buf, "%s\t\tDefault If Addr1: %d\n", buf, rnConfig->defaultIfAddr1);
sprintf(buf, "%s\t\tDefault If Addr2: %d\n", buf, rnConfig->defaultIfAddr2);
ROS_INFO("[aloha_node] %s", buf);
}
void print_rn_aloha_configuration(rnALOHAConfiguration *rnAlohaConfig)
{
char buf[1024];
sprintf(buf, "\n\tRN ALOHA Configuration: \n");
sprintf(buf, "%s\t\tminTimeBetweenTxMs: %d\n", buf, rnAlohaConfig->minTimeBetweenTxMs);
sprintf(buf, "%s\t\tmaxTimeBetweenTxMs: %d\n", buf, rnAlohaConfig->maxTimeBetweenTxMs);
sprintf(buf, "%s\t\tmaxRequestDataSize: %d\n", buf, rnAlohaConfig->maxRequestDataSize);
sprintf(buf, "%s\t\tmaxResponseDataSize: %d\n", buf, rnAlohaConfig->maxResponseDataSize);
sprintf(buf, "%s\t\tFlags: 0x%X\n", buf, rnAlohaConfig->flags);
sprintf(buf, "%s\t\taccKfactor: %d\n", buf, rnAlohaConfig->accKfactor);
ROS_INFO("[aloha_node] %s", buf);
}
void error_check(int r, char const *msg)
{
if (r != 0)
{
ROS_ERROR("[aloha_node] %s\n", msg);
ros::requestShutdown();
}
}
|
acef0d93cdf424c2c57a56eb48119a9660232474
|
eb32bca809264605597a1c112ddb8d2dcde5efb7
|
/p307.cc
|
14db7e45a3386fde92a4bf14bbff0415218e9091
|
[] |
no_license
|
superweaver/leetcode
|
fe423beebafe2b92935ac2376af5cee6da7d55ed
|
7e90a53dbbb28511053a34812bd18209d4adfb26
|
refs/heads/master
| 2023-06-21T20:25:08.284150
| 2023-06-19T17:48:11
| 2023-06-19T17:48:11
| 109,064,436
| 0
| 0
| null | 2020-01-23T05:44:26
| 2017-10-31T23:49:55
|
C++
|
UTF-8
|
C++
| false
| false
| 2,429
|
cc
|
p307.cc
|
#include "common.h"
class NumArray_segment {
public:
NumArray_segment(vector<int> &nums) {
// root is in i = 1
// leftchild = 2*i, rightchild = 2*i + 1
d_size = nums.size();
sgtree.assign(2 * d_size, 0);
for (int i = 0; i < d_size; ++i) {
update(i, nums[i]);
}
}
void update(int i, int val) {
i += d_size;
int delta = val - sgtree[i];
sgtree[i] = val;
while (i > 1) {
i >>= 1; // parent;
sgtree[i] = sgtree[i << 1] + sgtree[(i << 1) + 1];
}
}
int sumRange(int i, int j) {
// inclusive
if (i > j) {
swap(i, j);
}
i += d_size;
j += d_size;
int sum = 0;
while(i <= j) {
if (i & 1) { // i points to right child
sum += sgtree[i++];
}
if (!(j & 1)) { // j points to left child
sum += sgtree[j--];
}
i /= 2;
j /= 2;
}
return sum;
}
private:
vector<int> sgtree;
int d_size;
};
class NumArray {
public:
NumArray(vector<int> &nums) {
original = nums;
n = nums.size() + 1;
BIT.assign(n, 0);
for (int i = 0; i < n - 1; ++i) {
// not update
add(i, nums[i]);
}
}
void update(int i, int val) {
add(i, val - original[i]);
original[i] = val;
}
int sumRange(int i, int j) {
if (i > j) {
swap(i, j);
}
return getsum(j) - getsum(i - 1);
}
private:
// root index is 1
int n; // 1 + original n
vector<int> original;
vector<int> BIT;
void add(int i, int delta) {
if (delta == 0) {
return;
}
for (i++; i < n; i += (i & -i)) {
BIT[i] += delta;
}
}
int getsum(int i) {
// 0 to i
int sum = 0;
for (i++; i > 0; i -= (i & -i)) {
sum += BIT[i];
}
return sum;
}
};
int main() {
vector<int> nums = {1, 3, 5};
NumArray s(nums);
cout << s.sumRange(1, 2) << endl;
s.update(1, -3);
cout << s.sumRange(1, 2) << endl;
NumArray_segment sg(nums);
cout << sg.sumRange(1, 2) << endl;
sg.update(1, -3);
cout << sg.sumRange(1, 2) << endl;
cout << sg.sumRange(1, 1) << endl;
return 0;
}
|
db919ba1ecbd9c212fbc716202d8572f26925261
|
bcb9344032d941729b49952bbb2e17468002e6cb
|
/Homework 5/Homework 5/BearHelper.h
|
9466e4108504c8e01caf0e5c8197d3e3be5f5d3c
|
[] |
no_license
|
FalseShepherd/System-Programming
|
738a53d2bbf9f02b5e9b5957c62a7e1c7877ed65
|
0d0baf38ffeddc68bf2f478bf3f65eb197393ee3
|
refs/heads/master
| 2021-01-20T19:14:01.018675
| 2016-06-16T23:30:39
| 2016-06-16T23:30:39
| 61,326,461
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 525
|
h
|
BearHelper.h
|
#ifndef __FunctionTemplates__bearHelper__
#define __FunctionTemplates__bearHelper__
#include <stdio.h>
class BearHelper
{
public:
BearHelper(const char *);
~BearHelper();
void GetAllWords(const char* required, const char* available);
private:
//A string that will store the entire dictionary
char* theDictionary;
//The size of the dictionary (number of characters)
int size;
bool AllLettersInSet(const char *letters, char *set);
};
#endif /* defined(__FunctionTemplates__bearHelper__) */
|
ae72d87959f9af6b4e6faa67c08c5a6554a8435e
|
6b2a8dd202fdce77c971c412717e305e1caaac51
|
/solutions_5690574640250880_0/C++/Zwergesel/solution.cpp
|
73baf895a6a8bd18f0f5ad0d06b51a4977132a1b
|
[] |
no_license
|
alexandraback/datacollection
|
0bc67a9ace00abbc843f4912562f3a064992e0e9
|
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
|
refs/heads/master
| 2021-01-24T18:27:24.417992
| 2017-05-23T09:23:38
| 2017-05-23T09:23:38
| 84,313,442
| 2
| 4
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,442
|
cpp
|
solution.cpp
|
#include <iostream>
#include <cstring>
using namespace std;
char g[50][50];
void printg(int r, int c) {
for (int i=0; i<r; i++) {
for (int j=0; j<c; j++) {
cout << g[i][j];
}
cout << '\n';
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int t;
cin >> t;
for (int casenum=1; casenum<=t; casenum++) {
cout << "Case #" << casenum << ":\n";
int r, c, m;
cin >> r >> c >> m;
int s = r * c - m;
// Trivial cases
if (m == 0) { // No bomb
cout << 'c' << string(c-1, '.') << '\n';
for (int y=1; y<r; y++) cout << string(c, '.') << '\n';
} else if (r == 1) { // Single row
cout << 'c' << string(c-m-1, '.') << string(m, '*') << '\n';
} else if (c == 1) { // Single column
cout << "c\n";
for (int i=0; i<r-m-1; i++) cout << ".\n";
for (int i=0; i<m; i++) cout << "*\n";
} else if (s == 1) { //Only one space
cout << 'c' << string(c-1, '*') << '\n';
for (int i=1; i<r; i++) cout << string(c, '*') << '\n';
}
// Hard cases
// Odd number of spaces in grid of width or height 2 is impossible
else if (min(r, c) == 2 && s % 2 == 1) {
cout << "Impossible\n";
}
// Even number of spaces
else if (s % 2 == 0 && s >= 4) {
memset(g, '*', sizeof(g));
g[0][1] = g[1][0] = g[1][1] = '.';
g[0][0] = 'c';
s -= 4;
int x = 2;
while (s > 0 && x < c) {
g[0][x] = g[1][x] = '.';
x += 1;
s -= 2;
}
x = 0;
int y = 2;
while (s > 0 && y < r) {
while (s > 0 && x + 1 < c) {
g[y][x] = g[y][x+1] = '.';
x += 2;
s -= 2;
}
y++;
x = 0;
}
y = 2;
x = c - 1;
while (s > 0) {
g[y][x] = g[y+1][x] = '.';
y += 2;
s -= 2;
}
printg(r, c);
}
// Odd number of spaces with at least 9 spaces
else if (s % 2 == 1 && s >= 9) {
memset(g, '*', sizeof(g));
for (int i=0; i<3; i++) for (int j=0; j<3; j++) g[i][j] = '.';
g[0][0] = 'c';
s -= 9;
int x = 3;
while (s > 0 && x < c) {
g[0][x] = g[1][x] = '.';
x += 1;
s -= 2;
}
x = 3;
int y = 2;
while (s > 0 && y < r) {
while (s > 0 && x + 1 < c) {
g[y][x] = g[y][x+1] = '.';
x += 2;
s -= 2;
}
if (x == c) {
if (g[y-1][x-1] == '*') swap(g[y-1][x-1], g[y][x-1]);
}
y++;
x = 0;
}
y = 3;
x = c - 1;
while (s > 0) {
g[y][x] = g[y+1][x] = '.';
y += 2;
s -= 2;
}
printg(r, c);
}
else {
cout << "Impossible\n";
}
}
return 0;
}
|
0a03e2681103a3b4278afbff1bf3bb7137f1ec9c
|
975d45994f670a7f284b0dc88d3a0ebe44458a82
|
/servidor/WarBugsServer/WarBugsServer/Includes/CBonusSecundario.h
|
a0a557b4e56a84dc5e95500ef101d475dbbf5663
|
[] |
no_license
|
phabh/warbugs
|
2b616be17a54fbf46c78b576f17e702f6ddda1e6
|
bf1def2f8b7d4267fb7af42df104e9cdbe0378f8
|
refs/heads/master
| 2020-12-25T08:51:02.308060
| 2010-11-15T00:37:38
| 2010-11-15T00:37:38
| 60,636,297
| 0
| 0
| null | null | null | null |
WINDOWS-1250
|
C++
| false
| false
| 542
|
h
|
CBonusSecundario.h
|
#pragma once
/*
* Classe CBonusPrimario
*
* Autor: Eder Figueiredo
*
* Objetivo: Descrever os bonus primários de um personagem
*
*/
#ifndef _CBONUSSECUNDARIO_H_
#define _CBONUSSECUNDARIO_H_
#include "CHabilidadesSecundarias.h"
#include "CBonus.h"
class CBonusSecundario : public CBonus
{
private:
CHabilidadesSecundarias *_valor;
public:
CBonusSecundario();
int getValue(Atrib tipo);
void createBonus(int FOR_ATC, int AGI_ATD, int DES_DMC, int INS_DMD, int RES_DEF);
int getTotalBonusOf(Atrib tipo);
};
#endif
|
7b864e356074c0ce37e6ecea85fd66a7bdbf524e
|
434072465045438a89095e50abfa4b8c10ba5581
|
/include/delfem2/mat3.h
|
1d33728d2f63c87a7331420e182a9c31bf26e1a3
|
[
"MIT"
] |
permissive
|
mmer547/delfem2
|
8dd616e9b9eb90705a7a3fd9f489f6e48cd0de1b
|
4f4b28931c96467ac30948e6b3f83150ea530c92
|
refs/heads/master
| 2022-01-20T09:02:45.532451
| 2022-01-09T02:36:28
| 2022-01-09T02:36:28
| 229,833,058
| 1
| 0
|
MIT
| 2019-12-23T22:44:02
| 2019-12-23T22:44:01
| null |
UTF-8
|
C++
| false
| false
| 12,803
|
h
|
mat3.h
|
/*
* Copyright (c) 2019 Nobuyuki Umetani
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* @file 3x3 matrix class (CMat3) and functions
* @detail The order of dependency in delfem2 is "vec2 -> mat2 -> vec3 -> quaternion -> mat3 -> mat4",
*/
#ifndef DFM2_MAT3_H
#define DFM2_MAT3_H
#include <vector>
#include <cassert>
#include <cmath>
#include <iostream>
#include <array>
#include <limits> // using NaN Check
#include "delfem2/dfm2_inline.h"
#define NEARLY_ZERO 1.e-16
// -----------------------------
namespace delfem2 {
/**
* @func Set spin 3x3 matrix (skew asymetric matrix)
* @tparam REAL float and double
* @param mat pointer of 3x3 matrix
* @param v ponter of 3 vector
*/
template<typename REAL>
void Mat3_Spin(
REAL *mat,
const REAL *v);
template<typename REAL>
void Mat3_Spin_ScaleAdd(
REAL *mat,
const REAL *v,
REAL alpha,
REAL beta);
template<typename REAL>
void Mat3_Identity(
REAL *mat,
REAL alpha);
template<typename REAL>
DFM2_INLINE void Mat3_Identity_ScaleAdd(
REAL *mat,
REAL alpha = 1,
REAL beta = 0);
template<typename T>
DFM2_INLINE void Mat3_AffineRotation(
T *mat,
T theta);
template<typename T>
void Mat3_AffineTranslation(
T *mat,
const T transl[2]);
template<typename T0, typename T1>
void Copy_Mat3(
T0 m0[9],
const T1 m1[9]) {
for (int i = 0; i < 9; ++i) { m0[i] = m1[i]; }
}
// ------------
template<typename T>
void Transpose_Mat3(
T At[],
const T A[]);
template<typename T0, typename T1>
void Inverse_Mat3(
T0 Ainv[],
const T1 A[]);
template<typename REAL>
void Inverse_Mat3(
REAL Ainv[9]);
/**
* compute C = A*B
* @tparam T0
* @tparam T1
* @tparam T2
* @param C
* @param A
* @param B
*/
template<typename T0, typename T1, typename T2>
void MatMat3(
T0 *AB,
const T1 *A,
const T2 *B);
template<typename T0, typename T1, typename T2>
void MatMatT3(
T0 *ABt,
const T1 *A,
const T2 *B);
/**
* @func product of a transposed 3x3 matrix and another 3x3 matrix.
* [C] = [A]^T[B}
* @details row major data structure
*/
template<typename T0, typename T1, typename T2>
void MatTMat3(
T0 *AtB,
const T1 *A,
const T2 *B);
/**
* @func adding scaled product of a transposed 3x3 matrix and another 3x3 matrix.
* [C] = alpha * [A]^T[B} + beta* [C]
* @details row major data structure
*/
template<typename T>
void MatTMat3_ScaleAdd(
T *C,
const T *A,
const T *B,
T alpha,
T beta);
template<typename T>
T Det_Mat3(
const T U[9]);
template<typename T>
T SquareNormFrobenius_SymMat3(
const T sm[6]);
/**
* @func compute eigen value & vector for symmmetric matrix
* @details
* sm[6] = (M_00,M_11,M_22,M_12,M_20,M_01)
* M = ULU^T
* u[9] = (U_00,U_01,U_02, U_10,U_11,U_12, U_20,U_21,U_22)
*/
DFM2_INLINE bool eigenSym3(
double u[9],
double l[3],
const double sm[6],
int nitr);
DFM2_INLINE void svd3(
double U[9],
double G[3],
double V[9],
const double m[9],
int nitr);
DFM2_INLINE void GetRotPolarDecomp(
double R[9],
const double am[9],
int nitr);
// -----------------
// below: axis angle vector
template<typename T>
DFM2_INLINE void AxisAngleVectorCartesian_Mat3(
T v[3],
const T m[9]);
template<typename REAL>
void Mat3_Rotation_Cartesian(
REAL mat[9],
const REAL vec[3]);
template<typename T>
DFM2_INLINE void AxisAngleVectorCRV_Mat3(
T crv[3],
const T mat[9]);
template<typename T>
DFM2_INLINE void EulerAngle_Mat3(
T ea[3],
const T m[9],
const std::array<int, 3> &axis_idxs);
// ------------------------------------------------
// below: mat3 and vec3
template<typename T0, typename T1, typename T2>
DFM2_INLINE void MatTVec3(
T0 y[3],
const T1 m[9],
const T2 x[3]);
/**
* @func {y} = beta*{y} + alpha*[M]^T{x}
*/
template<typename T0, typename T1, typename T2, typename T3, typename T4>
void MatTVec3_ScaleAdd(
T0 y[3],
const T1 m[9],
const T2 x[3],
T3 alpha,
T4 beta);
/**
* @func matrix vector product for 3x3 matrix {y} := [m]{x}
*/
template<typename T0, typename T1, typename T2>
void MatVec3(
T0 y[3],
const T1 m[9],
const T2 x[3]);
template<typename T>
void MatVec3_ScaleAdd(
T y[3],
const T m[9],
const T x[3],
T alpha,
T beta);
DFM2_INLINE void VecMat3(
double y[3],
const double x[3],
const double m[9]);
template<typename T>
DFM2_INLINE void Vec2_Mat3Vec2_AffineProjection(
T y[2],
const T Z[9],
const T x[2]);
template<typename T>
DFM2_INLINE void Vec2_Mat3Vec2_AffineDirection(
T y[2],
const T A[9],
const T x[2]);
// --------------------------------
// below: mat3 and quat
template<typename REAL>
DFM2_INLINE void Mat3_Quat(
REAL r[],
const REAL q[]);
template <typename T>
DFM2_INLINE void Quat_Mat3(
T quat[4],
const T p_[9]);
template<typename T>
class CMat3; // this pre-definition is needed for following functions
template<typename T>
CMat3<T> operator+(const CMat3<T> &lhs, const CMat3<T> &rhs);
template<typename T>
CMat3<T> operator-(const CMat3<T> &lhs, const CMat3<T> &rhs);
template<typename T>
CMat3<T> operator*(double d, const CMat3<T> &rhs);
template<typename T>
CMat3<T> operator*(const CMat3<T> &m, T d);
template<typename T>
CMat3<T> operator*(const CMat3<T> &lhs, const CMat3<T> &rhs);
template<typename T>
CMat3<T> operator/(const CMat3<T> &m, T d);
template<typename T>
std::ostream &operator<<(std::ostream &output, const CMat3<T> &m);
template<typename T>
std::istream &operator>>(std::istream &output, CMat3<T> &m);
static inline bool myIsNAN_Matrix3(double d) { return !(d > d - 1); }
/**
* @class class of 3x3 matrix
*/
template<typename REAL>
class CMat3 {
public:
CMat3();
explicit CMat3(REAL s);
explicit CMat3(const REAL m[9]);
CMat3(REAL v00, REAL v01, REAL v02,
REAL v10, REAL v11, REAL v12,
REAL v20, REAL v21, REAL v22);
CMat3(REAL x, REAL y, REAL z);
CMat3(const std::array<REAL,9>& m) :
p_{m[0],m[1],m[2],m[3],m[4],m[5],m[6],m[7],m[8]} {}
// ---------------
REAL *data() { return p_; }
[[nodiscard]] const REAL *data() const { return p_; }
// ---------------
void GetElements(REAL m[9]) const { for (unsigned int i = 0; i < 9; i++) { m[i] = p_[i]; }}
[[nodiscard]] double Get(int i, int j) const { return p_[i * 3 + j]; }
// ---------
void AffineMatrixTrans(REAL m[16]) const {
m[0 * 4 + 0] = p_[0];
m[1 * 4 + 0] = p_[1];
m[2 * 4 + 0] = p_[2];
m[3 * 4 + 0] = 0;
m[0 * 4 + 1] = p_[3];
m[1 * 4 + 1] = p_[4];
m[2 * 4 + 1] = p_[5];
m[3 * 4 + 1] = 0;
m[0 * 4 + 2] = p_[6];
m[1 * 4 + 2] = p_[7];
m[2 * 4 + 2] = p_[8];
m[3 * 4 + 2] = 0;
m[0 * 4 + 3] = 0;
m[1 * 4 + 3] = 0;
m[2 * 4 + 3] = 0;
m[3 * 4 + 3] = 1;
}
void CopyToMat4(REAL m[16]) const {
m[0 * 4 + 0] = p_[0];
m[0 * 4 + 1] = p_[1];
m[0 * 4 + 2] = p_[2];
m[1 * 4 + 0] = p_[3];
m[1 * 4 + 1] = p_[4];
m[1 * 4 + 2] = p_[5];
m[2 * 4 + 0] = p_[6];
m[2 * 4 + 1] = p_[7];
m[2 * 4 + 2] = p_[8];
}
void CopyTo(REAL *ptr) const {
for (int i = 0; i < 9; ++i) { ptr[i] = p_[i]; }
}
void CopyToScale(REAL *ptr, REAL s) const {
for (int i = 0; i < 9; ++i) { ptr[i] = p_[i] * s; }
}
void AddToScale(REAL *ptr, REAL s) const {
for (int i = 0; i < 9; ++i) { ptr[i] += p_[i] * s; }
}
// ---------------
[[nodiscard]] std::array<REAL,3> MatVec(const REAL vec0[3]) const;
void MatVecTrans(const REAL vec0[], REAL vec1[]) const;
[[nodiscard]] CMat3 MatMat(const CMat3 &mat0) const;
[[nodiscard]] CMat3 MatMatTrans(const CMat3 &mat0) const;
// ----------------
[[nodiscard]] CMat3 Sym() const {
CMat3 m;
for (unsigned int i = 0; i < 3; i++) {
for (unsigned int j = 0; j < 3; j++) {
m.p_[i * 3 + j] = (p_[i * 3 + j] + p_[j * 3 + i]) * 0.5;
}
}
return m;
}
inline CMat3 operator-() const { return (*this) * static_cast<REAL>(-1); }
inline CMat3 operator+() const { return (*this); }
inline CMat3 &operator+=(const CMat3 &rhs) {
for (unsigned int i = 0; i < 9; i++) { p_[i] += rhs.p_[i]; }
return *this;
}
inline CMat3 &operator-=(const CMat3 &rhs) {
for (unsigned int i = 0; i < 9; i++) { p_[i] -= rhs.p_[i]; }
return *this;
}
inline CMat3 &operator*=(REAL d) {
for (auto &m : p_) { m *= d; }
return *this;
}
inline CMat3 &operator/=(REAL d) {
REAL invd = (REAL) 1.0 / d;
for (auto &m : p_) { m *= invd; }
return *this;
}
inline REAL operator[](int i) const {
return this->p_[i];
}
inline REAL &operator()(int i, int j) {
return this->p_[i * 3 + j];
}
inline const REAL &operator()(int i, int j) const {
return this->p_[i * 3 + j];
}
// -------------------------
[[nodiscard]] CMat3 Inverse() const;
// -------------------------
// function whose name starts with "Set" changes itself
void SetInverse();
void SetSymetric(const REAL sm[6]);
void setZero();
void SetRandom();
void SetRotMatrix_Cartesian(const REAL vec[]);
void SetRotMatrix_Cartesian(REAL x, REAL y, REAL z);
void SetRotMatrix_Rodrigues(const REAL vec[]);
void SetRotMatrix_CRV(const REAL crv[]);
void SetRotMatrix_Quaternion(const REAL quat[]);
void SetRotMatrix_BryantAngle(REAL rx, REAL ry, REAL rz);
void SetIdentity(REAL scale = 1);
void SetMat4(const REAL m[16]) {
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
this->p_[i * 3 + j] = m[i * 4 + j];
}
}
}
// ------------------------
// quaterion (x,y,z,w)
[[nodiscard]] std::array<REAL,4> GetQuaternion() const;
// ------------------------
[[nodiscard]] CMat3 transpose() const {
CMat3 m;
m.p_[0] = p_[0];
m.p_[1] = p_[3];
m.p_[2] = p_[6];
m.p_[3] = p_[1];
m.p_[4] = p_[4];
m.p_[5] = p_[7];
m.p_[6] = p_[2];
m.p_[7] = p_[5];
m.p_[8] = p_[8];
return m;
}
[[nodiscard]] bool isNaN() const {
double s = p_[0] + p_[1] + p_[2] + p_[3] + p_[4] + p_[5] + p_[6] + p_[7] + p_[8];
return myIsNAN_Matrix3(s) != 0;
}
[[nodiscard]] double determinant() const {
return
p_[0] * p_[4] * p_[8] +
p_[3] * p_[7] * p_[2] +
p_[6] * p_[1] * p_[5] -
p_[0] * p_[7] * p_[5] -
p_[6] * p_[4] * p_[2] -
p_[3] * p_[1] * p_[8];
}
[[nodiscard]] double SqNorm_Frobenius() const {
double s = 0.0;
for (auto &i : p_) {
s += i * i;
}
return s;
}
[[nodiscard]] double Trace() const {
return p_[0] + p_[4] + p_[8];
}
[[nodiscard]] double SecondInvarint() const {
const CMat3 &m2 = (*this) * (*this);
const double tr = this->Trace();
return 0.5 * (tr * tr - m2.Trace());
}
void Print() const {
std::cout << p_[0] << " " << p_[1] << " " << p_[2] << std::endl;
std::cout << p_[3] << " " << p_[4] << " " << p_[5] << std::endl;
std::cout << p_[6] << " " << p_[7] << " " << p_[8] << std::endl;
}
void PolerDecomp(CMat3 &R, int nitr) const {
GetRotPolarDecomp(R.p_,
p_, nitr);
}
// --------------------
// static functions
static CMat3 Identity(REAL scale = 1) {
CMat3 m;
m.SetIdentity(scale);
return m;
}
static CMat3 Zero() {
CMat3 m;
m.setZero();
return m;
}
static CMat3 Spin(const REAL *v) {
CMat3 m;
Mat3_Spin(m.p_, v);
return m;
}
static CMat3 OuterProduct(const REAL *v0, const REAL *v1) {
return CMat3<REAL>(
v0[0] * v1[0], v0[0] * v1[1], v0[0] * v1[2],
v0[1] * v1[0], v0[1] * v1[1], v0[1] * v1[2],
v0[2] * v1[0], v0[2] * v1[1], v0[2] * v1[2]);
}
// quaternion order of (x,y,z,w)
static CMat3 Quat(const REAL *q) {
const REAL x2 = q[0] * q[0] * 2;
const REAL y2 = q[1] * q[1] * 2;
const REAL z2 = q[2] * q[2] * 2;
const REAL xy = q[0] * q[1] * 2;
const REAL yz = q[1] * q[2] * 2;
const REAL zx = q[2] * q[0] * 2;
const REAL xw = q[0] * q[3] * 2;
const REAL yw = q[1] * q[3] * 2;
const REAL zw = q[2] * q[3] * 2;
CMat3<REAL> m;
m.p_[0 * 3 + 0] = 1 - y2 - z2;
m.p_[0 * 3 + 1] = xy - zw;
m.p_[0 * 3 + 2] = zx + yw;
m.p_[1 * 3 + 0] = xy + zw;
m.p_[1 * 3 + 1] = 1 - z2 - x2;
m.p_[1 * 3 + 2] = yz - xw;
m.p_[2 * 3 + 0] = zx - yw;
m.p_[2 * 3 + 1] = yz + xw;
m.p_[2 * 3 + 2] = 1 - x2 - y2;
return m;
}
public:
REAL p_[9]; // value with row-major order
};
using CMat3d = CMat3<double>;
using CMat3f = CMat3<float>;
template<typename T>
CMat3<T> Mat3_Identity(T alpha) {
CMat3<T> m;
Mat3_Identity(m.p_, alpha);
return m;
}
}
#ifndef DFM2_STATIC_LIBRARY
# include "delfem2/mat3.cpp"
#endif
#endif /* DFM2_MAT3_H */
|
b9276f2fa2840b958e266015c84c6a826aa0c955
|
60ec79331c650219e77085f9324a2529adb8eb0c
|
/src/AtlantScanner.cpp
|
f2dd9ecde06714de2b608ebf8f9e6fcaeb9b47ef
|
[
"BSL-1.0"
] |
permissive
|
jkerkela/atlant-scanner
|
425663e1bbd1d3cd7d6d014711deeb24b8482572
|
b94788c394499c64bae50b70ceab6b757354b1cc
|
refs/heads/master
| 2023-05-14T16:21:17.128201
| 2021-06-06T13:48:37
| 2021-06-06T13:48:37
| 356,198,057
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,257
|
cpp
|
AtlantScanner.cpp
|
#include <iostream>
#include <string>
#include <set>
#include <exception>
#include <stdlib.h>
#include "Authenticator.hpp"
#include "ScanMetadata.hpp"
#include "FileScanner.hpp"
#include "ScanPoller.hpp"
#include "ResultPrinter.hpp"
int main(int argc, char* argv[])
{
if (argc != 5) {
std::cerr << "Invalid command line parameters - "
"Usage of application: AUTH-URL SCAN-URL CLIENT-ID CLIENT-SECRET INPUT-FILE" << std::endl;
return 1;
}
std::string auth_address = argv[0];
std::string scan_address = argv[1];
std::string client_id = argv[2];
std::string client_secret = argv[3];
std::string input_file = argv[4];
std::set<std::string> auth_scope{ "scan" };
Authenticator authenticator{
std::make_unique<AuthTokenFetcher>(auth_address, std::make_unique<HTTPClientSessionImpl>(auth_address)),
client_id,
client_secret,
auth_scope};
ScanMetadata metadata{};
try {
FileScanner fileScanner{ std::make_unique<HTTPClientSessionImpl>(scan_address), scan_address, authenticator};
ScanPoller scanPoller{fileScanner};
auto result = scanPoller.scan(metadata, input_file);
ResultPrinter::print(result);
}
catch (std::exception e) {
std::cerr << "Error: " << e.what() << std::endl;
std::exit(EXIT_FAILURE);
}
return 0;
}
|
7e5819116fd9b0eb5b637ac690614d33f8c0f3c1
|
9f2b07eb0e9467e17448de413162a14f8207e5d0
|
/libsrc/pylith/feassemble/obsolete/GeometryTri2D.cc
|
82e733eac98559ec2e236850bf9f0492e02663b2
|
[
"MIT"
] |
permissive
|
fjiaqi/pylith
|
2aa3f7fdbd18f1205a5023f8c6c4182ff533c195
|
67bfe2e75e0a20bb55c93eb98bef7a9b3694523a
|
refs/heads/main
| 2023-09-04T19:24:51.783273
| 2021-10-19T17:01:41
| 2021-10-19T17:01:41
| 373,739,198
| 0
| 0
|
MIT
| 2021-06-04T06:12:08
| 2021-06-04T06:12:07
| null |
UTF-8
|
C++
| false
| false
| 7,461
|
cc
|
GeometryTri2D.cc
|
// -*- C++ -*-
//
// ======================================================================
//
// Brad T. Aagaard, U.S. Geological Survey
// Charles A. Williams, GNS Science
// Matthew G. Knepley, University of Chicago
//
// This code was developed as part of the Computational Infrastructure
// for Geodynamics (http://geodynamics.org).
//
// Copyright (c) 2010-2017 University of California, Davis
//
// See COPYING for license information.
//
// ======================================================================
//
#include <portinfo>
#include "GeometryTri2D.hh" // implementation of class methods
#include "GeometryLine2D.hh" // USES GeometryLine2D
#include "petsc.h" // USES PetscLogFlops
#include "pylith/utils/array.hh" // USES scalar_array
#include "pylith/utils/constdefs.h" // USES scalar_array
#include <cassert> // USES assert()
// ----------------------------------------------------------------------
// Default constructor.
pylith::feassemble::GeometryTri2D::GeometryTri2D(void) :
CellGeometry(TRIANGLE, 2)
{ // constructor
const PylithScalar vertices[] = {
-1.0, -1.0,
+1.0, -1.0,
-1.0, +1.0,
};
_setVertices(vertices, 3, 2);
} // constructor
// ----------------------------------------------------------------------
// Default destructor.
pylith::feassemble::GeometryTri2D::~GeometryTri2D(void)
{ // destructor
} // destructor
// ----------------------------------------------------------------------
// Create a copy of geometry.
pylith::feassemble::CellGeometry*
pylith::feassemble::GeometryTri2D::clone(void) const
{ // clone
return new GeometryTri2D();
} // clone
// ----------------------------------------------------------------------
// Get cell geometry for lower dimension cell.
pylith::feassemble::CellGeometry*
pylith::feassemble::GeometryTri2D::geometryLowerDim(void) const
{ // geometryLowerDim
return new GeometryLine2D();
} // geometryLowerDim
// ----------------------------------------------------------------------
// Transform coordinates in reference cell to global coordinates.
void
pylith::feassemble::GeometryTri2D::ptsRefToGlobal(PylithScalar* ptsGlobal,
const PylithScalar* ptsRef,
const PylithScalar* vertices,
const int dim,
const int npts) const
{ // ptsRefToGlobal
assert(ptsGlobal);
assert(ptsRef);
assert(vertices);
assert(2 == dim);
assert(spaceDim() == dim);
const PylithScalar x0 = vertices[0];
const PylithScalar y0 = vertices[1];
const PylithScalar x1 = vertices[2];
const PylithScalar y1 = vertices[3];
const PylithScalar x2 = vertices[4];
const PylithScalar y2 = vertices[5];
const PylithScalar f_1 = x1 - x0;
const PylithScalar g_1 = y1 - y0;
const PylithScalar f_2 = x2 - x0;
const PylithScalar g_2 = y2 - y0;
for (int i=0, iR=0, iG=0; i < npts; ++i) {
const PylithScalar p0 = 0.5 * (1.0 + ptsRef[iR++]);
const PylithScalar p1 = 0.5 * (1.0 + ptsRef[iR++]);
ptsGlobal[iG++] = x0 + f_1 * p0 + f_2 * p1;
ptsGlobal[iG++] = y0 + g_1 * p0 + g_2 * p1;
} // for
PetscLogFlops(4 + npts*12);
} // ptsRefToGlobal
// ----------------------------------------------------------------------
// Compute Jacobian at location in cell.
void
pylith::feassemble::GeometryTri2D::jacobian(scalar_array* jacobian,
PylithScalar* det,
const PylithScalar* vertices,
const int numVertices,
const int spaceDim,
const PylithScalar* location,
const int cellDim) const
{ // jacobian
assert(jacobian);
assert(det);
assert(vertices);
assert(location);
assert(this->numCorners() == numVertices || // linear
this->numCorners()+1 == numVertices); // quadratic
assert(this->spaceDim() == spaceDim);
assert(this->cellDim() == cellDim);
assert(size_t(spaceDim*cellDim) == jacobian->size());
const PylithScalar x0 = vertices[0];
const PylithScalar y0 = vertices[1];
const PylithScalar x1 = vertices[2];
const PylithScalar y1 = vertices[3];
const PylithScalar x2 = vertices[4];
const PylithScalar y2 = vertices[5];
(*jacobian)[0] = (x1 - x0) / 2.0;
(*jacobian)[1] = (x2 - x0) / 2.0;
(*jacobian)[2] = (y1 - y0) / 2.0;
(*jacobian)[3] = (y2 - y0) / 2.0;
*det =
(*jacobian)[0]*(*jacobian)[3] -
(*jacobian)[1]*(*jacobian)[2];
PetscLogFlops(11);
} // jacobian
// ----------------------------------------------------------------------
// Compute Jacobian at location in cell.
void
pylith::feassemble::GeometryTri2D::jacobian(PylithScalar* jacobian,
PylithScalar* det,
const PylithScalar* vertices,
const PylithScalar* location,
const int dim,
const int npts) const
{ // jacobian
assert(jacobian);
assert(det);
assert(vertices);
assert(location);
assert(2 == dim);
assert(spaceDim() == dim);
const PylithScalar x0 = vertices[0];
const PylithScalar y0 = vertices[1];
const PylithScalar x1 = vertices[2];
const PylithScalar y1 = vertices[3];
const PylithScalar x2 = vertices[4];
const PylithScalar y2 = vertices[5];
const PylithScalar j00 = (x1 - x0) / 2.0;
const PylithScalar j01 = (x2 - x0) / 2.0;
const PylithScalar j10 = (y1 - y0) / 2.0;
const PylithScalar j11 = (y2 - y0) / 2.0;
const PylithScalar jdet = j00*j11 - j10*j01;
for (int i=0, iJ=0; i < npts; ++i) {
jacobian[iJ++] = j00;
jacobian[iJ++] = j01;
jacobian[iJ++] = j10;
jacobian[iJ++] = j11;
det[i] = jdet;
} // for
PetscLogFlops(11);
} // jacobian
// ----------------------------------------------------------------------
// Compute minimum width across cell.
PylithScalar
pylith::feassemble::GeometryTri2D::minCellWidth(const PylithScalar* coordinatesCell,
const int numVertices,
const int spaceDim) const
{ // minCellWidth
const int numCorners = 3;
const int dim = 2;
assert(numCorners == numVertices || // linear
numCorners+3 == numVertices); // quadratic
assert(dim == spaceDim);
const int numEdges = 3;
const int edges[numEdges][2] = {
{0, 1}, {1, 2}, {2, 0},
};
PylithScalar minWidth = PYLITH_MAXSCALAR;
for (int iedge=0; iedge < numEdges; ++iedge) {
const int iA = edges[iedge][0];
const int iB = edges[iedge][1];
const PylithScalar xA = coordinatesCell[dim*iA ];
const PylithScalar yA = coordinatesCell[dim*iA+1];
const PylithScalar xB = coordinatesCell[dim*iB ];
const PylithScalar yB = coordinatesCell[dim*iB+1];
const PylithScalar edgeLen = sqrt(pow(xB-xA,2) + pow(yB-yA,2));
if (edgeLen < minWidth) {
minWidth = edgeLen;
} // if
} // for
PetscLogFlops(numEdges*6);
// Ad-hoc to account for distorted cells.
// Radius of inscribed circle.
const PylithScalar xA = coordinatesCell[0];
const PylithScalar yA = coordinatesCell[1];
const PylithScalar xB = coordinatesCell[2];
const PylithScalar yB = coordinatesCell[3];
const PylithScalar xC = coordinatesCell[4];
const PylithScalar yC = coordinatesCell[5];
const PylithScalar c = sqrt(pow(xB-xA,2) + pow(yB-yA, 2));
const PylithScalar a = sqrt(pow(xC-xB,2) + pow(yC-yB, 2));
const PylithScalar b = sqrt(pow(xA-xC,2) + pow(yA-yC, 2));
const PylithScalar k = 0.5 * (a + b + c);
const PylithScalar r = sqrt(k*(k-a)*(k-b)*(k-c)) / k;
const PylithScalar rwidth = 3.0*r; // based on empirical tests
if (rwidth < minWidth) {
minWidth = rwidth;
} // if
PetscLogFlops(3*6 + 3 + 8);
return minWidth;
} // minCellWidth
// End of file
|
97aa0f8d81c1e56314d3dec9d83c81c8a812716a
|
c05742304c66fe704ada0b7a3c5a2ddf151c586d
|
/EasyBMP_1.06/sample/EasyBMPsample.cpp
|
2b25ca22f0f888a15826bc1efe5052d27f6a3dd7
|
[
"BSD-3-Clause"
] |
permissive
|
badass-techie/Handwritten-Text-Reader
|
c5052997ac70e1da70a4c160060afaa9a6cc53ae
|
45f96c4c9ef751f5dad603ed36e56bda0d6458b0
|
refs/heads/master
| 2022-04-18T02:56:23.299016
| 2020-04-20T17:42:42
| 2020-04-20T17:42:42
| 257,348,438
| 5
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,835
|
cpp
|
EasyBMPsample.cpp
|
/*************************************************
* *
* EasyBMP Cross-Platform Windows Bitmap Library *
* *
* Author: Paul Macklin *
* email: macklin01@users.sourceforge.net *
* support: http://easybmp.sourceforge.net *
* *
* file: EasyBMPsample.cpp *
* date added: 03-31-2006 *
* date modified: 12-01-2006 *
* version: 1.06 *
* *
* License: BSD (revised/modified) *
* Copyright: 2005-6 by the EasyBMP Project *
* *
* description: Sample application to demonstrate *
* some functions and capabilities *
* *
*************************************************/
#include "EasyBMP.h"
using namespace std;
int main( int argc, char* argv[] )
{
cout << endl
<< "Using EasyBMP Version " << _EasyBMP_Version_ << endl << endl
<< "Copyright (c) by the EasyBMP Project 2005-6" << endl
<< "WWW: http://easybmp.sourceforge.net" << endl << endl;
BMP Text;
Text.ReadFromFile("EasyBMPtext.bmp");
BMP Background;
Background.ReadFromFile("EasyBMPbackground.bmp");
BMP Output;
Output.SetSize( Background.TellWidth() , Background.TellHeight() );
Output.SetBitDepth( 24 );
RangedPixelToPixelCopy( Background, 0, Output.TellWidth()-1,
Output.TellHeight()-1 , 0,
Output, 0,0 );
RangedPixelToPixelCopyTransparent( Text, 0, 380,
43, 0,
Output, 110,5,
*Text(0,0) );
RangedPixelToPixelCopyTransparent( Text, 0, Text.TellWidth()-1,
Text.TellWidth()-1, 50,
Output, 100,442,
*Text(0,49) );
Output.SetBitDepth( 32 );
cout << "writing 32bpp ... " << endl;
Output.WriteToFile( "EasyBMPoutput32bpp.bmp" );
Output.SetBitDepth( 24 );
cout << "writing 24bpp ... " << endl;
Output.WriteToFile( "EasyBMPoutput24bpp.bmp" );
Output.SetBitDepth( 8 );
cout << "writing 8bpp ... " << endl;
Output.WriteToFile( "EasyBMPoutput8bpp.bmp" );
Output.SetBitDepth( 4 );
cout << "writing 4bpp ... " << endl;
Output.WriteToFile( "EasyBMPoutput4bpp.bmp" );
Output.SetBitDepth( 1 );
cout << "writing 1bpp ... " << endl;
Output.WriteToFile( "EasyBMPoutput1bpp.bmp" );
Output.SetBitDepth( 24 );
Rescale( Output, 'p' , 50 );
cout << "writing 24bpp scaled image ..." << endl;
Output.WriteToFile( "EasyBMPoutput24bpp_rescaled.bmp" );
return 0;
}
|
2bf3fd33459fbb4355e9a5b0ba518041143376f8
|
72b829af6b90821c89fa7078ba0443410051f2a4
|
/Algorithms/C++/traverse_array.cpp
|
09e7f286b1a29768cf5b5869ca2d6553232655d9
|
[] |
no_license
|
reevs2204/HacktoberFest21-1
|
bec731ed7454de96e550058a2069d3edff48f1af
|
ffb4a7fee1fe4ee3ea0d024e2991608f1ccd3729
|
refs/heads/main
| 2023-09-01T08:39:27.748569
| 2021-10-16T19:14:50
| 2021-10-16T19:14:50
| 417,912,712
| 0
| 0
| null | 2021-10-16T18:23:39
| 2021-10-16T18:23:38
| null |
UTF-8
|
C++
| false
| false
| 380
|
cpp
|
traverse_array.cpp
|
#include<iostream>
using namespace std;
int main()
{
int A[100],K=0,UB;
cout<<"Enter the Array size less than 100:";
cin>>UB; /* To enter the size of Array */
cout<<"Enter the elements in array: \n";
for(K=0;K<UB;K++)
{
cin>>A[K];
/* Entering elments of 1-D Array*/
}
cout<<"The Traverse of array is:\n";
for(K=0;K<UB;K++)
{
cout<<A[K];
/*Traversing the Array*/
}
return 0;
}
|
758596fbad541d1b8e5c13b75336b74ffd981285
|
3765be4ab5d4d7829a22208118b255e2c5cc8251
|
/task 113.cpp
|
09215cce7d73c86fa814a9dbabe924c980209271
|
[] |
no_license
|
omirzakye/practice-new-
|
b84449a1020f63d9123d92781c3a6e1039531460
|
a40239aca410784e595b5f416a9f952329dc5900
|
refs/heads/master
| 2020-09-13T02:06:57.501921
| 2019-11-22T07:25:01
| 2019-11-22T07:25:01
| 222,629,232
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 227
|
cpp
|
task 113.cpp
|
#include<iostream>
using namespace std;
int main()
{
for(int i=0; i<20; i++)
{
if(i%2==0){for(int k=0; k<10; k++){cout<<i;}cout<<endl;}
else{for(int k=0; k<10; k++){cout<<1;}cout<<endl;}
}
}
|
7c6f01fd4c7c00556b004354d8f20e983d4d43c0
|
99443caca00e7da2e8a93143acbc42cc8c453df9
|
/Source/OCCore/Task/ITask.h
|
1c0e96b01eeed8cfef9a188429276f67803522e1
|
[] |
no_license
|
RexOrCine/opencine
|
9f26aff5a61973bdfc8e3e1266539e9481a107d1
|
c8e279dfe003f147362f8c135b01f90566c30071
|
refs/heads/master
| 2021-01-01T06:03:22.434701
| 2019-01-06T06:11:34
| 2019-01-06T06:11:34
| 97,345,332
| 0
| 0
| null | 2017-07-15T22:19:56
| 2017-07-15T22:19:56
| null |
UTF-8
|
C++
| false
| false
| 795
|
h
|
ITask.h
|
#ifndef ITASK_H
#define ITASK_H
#include "OCCore_export.h"
#include "ITaskProgress.h"
class OCCORE_EXPORT ITask : public ITaskProgress
{
Q_OBJECT
protected:
unsigned int _id;
public:
ITask()
{
GenerateTaskID();
}
~ITask()
{
}
unsigned int GetID()
{
return _id;
}
private:
void GenerateTaskID()
{
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_int_distribution<unsigned int> dist(100001, 999999);
_id = dist(mt);
}
signals:
// TODO: Needs evaluation, switched to pointer as there are some problems with passing by reference and Qt type registration for abstract classes
void TaskUpdated(ITask*);
};
#endif //ITASK_H
|
ec15ae8943d7a6479992ad01c87e8efc4f523727
|
cfc0ff7895dcfab02db5bbb4577865838a7fb240
|
/experimental/poopi/firmware/arm/ramFile.cpp
|
9fef73f6f572ec0381d926a3a43f7980c1c78ca2
|
[] |
no_license
|
hamer13/speccy2010
|
8ae66662388a02b467dac7c3371b883b8e126ef4
|
b7d9e2673890739bda416a36c5b335fe165496d0
|
refs/heads/master
| 2020-06-08T11:28:55.134271
| 2015-03-24T23:18:46
| 2015-03-24T23:18:46
| 32,830,036
| 2
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,063
|
cpp
|
ramFile.cpp
|
#include "system.h"
#include "ramFile.h"
#include "types.h"
#include "specShell.h"
#define RF_MAX_SIZE 0x00100000
#define RF_MAX_FILES 8
#define RF_START_ADDRESS 0x00800000
static int bankState[ RF_MAX_FILES ];
int rf_open ( RFIL *rfile, const char *name, byte flags )
{
int bank = 0;
while( bankState[ bank ] != 0 && bank < RF_MAX_FILES ) bank++;
if( bank >= RF_MAX_FILES ) return 0xff;
FIL file;
int result = f_open( &file, name, FA_READ );
if( result != 0 ) return result;
if( file.fsize > RF_MAX_SIZE ) return 0xff;
dword address = RF_START_ADDRESS + bank * RF_MAX_SIZE;
word page = address >> 23;
SystemBus_Write( 0xc00020, page );
dword size = file.fsize;
//CPU_Stop();
while( size > 0 )
{
byte buff[2];
dword rsize;
f_read( &file, buff, 2, &rsize );
if( page != ( address >> 23 ) )
{
word page = address >> 23;
SystemBus_Write( 0xc00020, page );
}
SystemBus_Write( 0x800000 | ( ( address & 0x007fffff ) >> 1 ), buff[0] | ( buff[1] << 8 ) );
address += 2;
size -= rsize;
if( ( address & 0xff ) == 0 ) WDT_Kick();
}
//CPU_Start();
rfile->flag = flags;
rfile->fptr = 0;
rfile->fsize = file.fsize;
rfile->ramBank = bank;
bankState[ bank ] = 1;
f_close( &file );
return 0;
}
int rf_close ( RFIL *rfile )
{
bankState[ rfile->ramBank ] = 0;
return 0;
}
int rf_read ( RFIL *rfile, void *buff, dword size, dword *psize )
{
dword address = RF_START_ADDRESS + rfile->ramBank * RF_MAX_SIZE + rfile->fptr;
word page = address >> 23;
SystemBus_Write( 0xc00020, page );
//CPU_Stop();
*psize = 0;
while( *psize < size && rfile->fptr < rfile->fsize && rfile->fptr < RF_MAX_SIZE )
{
if( page != ( address >> 23 ) )
{
word page = address >> 23;
SystemBus_Write( 0xc00020, page );
}
*(byte*)buff = SystemBus_Read( address & 0x7fffff );
buff = (byte*) buff + 1;
address++;
rfile->fptr++;
(*psize)++;
}
//CPU_Start();
return 0;
}
int rf_write ( RFIL *rfile, const void *buff, dword size, dword *psize )
{
dword address = RF_START_ADDRESS + rfile->ramBank * RF_MAX_SIZE + rfile->fptr;
word page = address >> 23;
SystemBus_Write( 0xc00020, page );
//CPU_Stop();
*psize = 0;
while( *psize < size && rfile->fptr < rfile->fsize && rfile->fptr < RF_MAX_SIZE )
{
if( page != ( address >> 23 ) )
{
word page = address >> 23;
SystemBus_Write( 0xc00020, page );
}
SystemBus_Write( address & 0x7fffff, *(byte*)buff );
buff = (byte*) buff + 1;
address++;
rfile->fptr++;
(*psize)++;
}
//CPU_Start();
return 0;
}
int rf_lseek ( RFIL *rfile, dword pos )
{
if( pos < RF_MAX_SIZE && pos < rfile->fsize )
{
rfile->fptr = pos;
return 0;
}
return 0xff;
}
|
2584b7d97641df86b21891cdcc39289d6b72ff0b
|
14714e59c0232aec9e9369a769b96003c23d9e01
|
/Vehicle.cpp
|
acadf7bd2da65ce34d3d642c2f591cce4eba9933
|
[] |
no_license
|
uddeshkatyayan/Traffic_Simulation
|
4fab309cb57c3075afc7536f1d81cb882b9abc82
|
c516b9986172a0a43918cc3ae72224fa2eea559d
|
refs/heads/master
| 2021-10-25T04:11:21.230296
| 2019-03-31T14:37:02
| 2019-03-31T14:37:02
| 173,877,293
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,209
|
cpp
|
Vehicle.cpp
|
#include <iostream>
#include <string>
#include <vector>
#include "Road.h"
#include "Vehicle.h"
#define DEFAULT_VEHICLE_TYPE "Car";
#define DEFAULT_VEHICLE_LENGTH 2;
#define DEFAULT_VEHICLE_WIDTH 2;
#define DEFAULT_VEHICLE_MAXSPEED 1;
#define DEFAULT_VEHICLE_ACCELERATION 1;
#define DEFAULT_VEHICLE_ID 4544;
#define DEFAULT_VEHICLE_X -DEFAULT_VEHICLE_LENGTH;
#define DEFAULT_VEHICLE_Y 1;
#define DEFAULT_VEHICLE_VX 0;
using namespace std;
Vehicle::Vehicle(){
this->Type = DEFAULT_VEHICLE_TYPE;
this->Length = DEFAULT_VEHICLE_LENGTH;
this->Width = DEFAULT_VEHICLE_WIDTH;
this->MaxSpeed = DEFAULT_VEHICLE_MAXSPEED;
this->Acceleration = DEFAULT_VEHICLE_ACCELERATION;
this->Id = DEFAULT_VEHICLE_ID;
this->X = DEFAULT_VEHICLE_X;
this->Y = DEFAULT_VEHICLE_Y;
this->VX = DEFAULT_VEHICLE_VX;
}
Vehicle::Vehicle(const Vehicle &V1){
this->Type = V1.Type;
this->Length = V1.Length;
this->Width = V1.Width;
this->MaxSpeed = V1.MaxSpeed;
this->Acceleration = V1.Acceleration;
this->Id = V1.Id;
this->X = V1.X;
this->Y = V1.Y;
this->VX = V1.VX;
}
Vehicle & Vehicle::operator=(const Vehicle & V1){
this->Type = V1.Type;
this->Length = V1.Length;
this->Width = V1.Width;
this->MaxSpeed = V1.MaxSpeed;
this->Acceleration = V1.Acceleration;
this->Id = V1.Id;
this->X = V1.X;
this->Y = V1.Y;
this->VX = V1.VX;
return *this;
}
Vehicle::Vehicle(string Vehicle_Type, int Vehicle_Length, int Vehicle_Width, int Vehicle_MaxSpeed, int Vehicle_Acceleration){
this->Type = Vehicle_Type;
this->Length = Vehicle_Length;
this->Width = Vehicle_Width;
this->MaxSpeed = Vehicle_MaxSpeed;
this->Acceleration = Vehicle_Acceleration;
this->Id = DEFAULT_VEHICLE_ID;
this->X = DEFAULT_VEHICLE_X;
this->Y = DEFAULT_VEHICLE_Y;
this->VX = DEFAULT_VEHICLE_VX
}
Vehicle::~Vehicle(){
}
int Vehicle::nextSpeedState(){
return 0;
}
int Vehicle::stoppingDistance(){
int distance = 0;
int speed = VX;
int distance = 0;
while(speed!=0){
distance += speed;
speed = max(0, speed - Acceleration);
}
return distance;
}
void Vehicle::update(vector<vector<char>> road, int RoadSignal, string RoadSignalState){
switch (nextSpeedState()){
case 1:
VX = max(0, min(MaxSpeed, VX + Acceleration)); //clamp values to 0 and MaxSpeed
break;
case -1:
VX = max(0, min(MaxSpeed, VX - Acceleration)); //clamp values to 0 and MaxSpeed
break;
case 0:
break;
default:
}
X = X + VX;
}
void Vehicle::printParameters(){
cout/*<<"Vehicle_Type: "*/<<this->Type<<endl;
cout<<" "<<"Vehicle_Length: "<<this->Length<<endl;
cout<<" "<<"Vehicle_Width: "<<this->Width<<endl;
cout<<" "<<"Vehicle_MaxSpeed: "<<this->MaxSpeed<<endl;
cout<<" "<<"Vehicle_Acceleration: "<<this->Acceleration<<endl;
}
bool Vehicle::isCrashed(){
return false;
}
// int main(){
// Vehicle car1("Car", 5, 2, 5, 3);
// Vehicle car2;
// car1.printParameters();
// car2.printParameters();
// cout<< car2.X<<endl;
// return 0;
// }
|
ed633462b00a5037116f143d8007a7a4bc47a54d
|
df9e934f7d19288c50e9553faa6a3200ac9bd8de
|
/array_manipulation.cpp
|
dcaf6591858eae8b2323a2cfb971d9378731bb19
|
[] |
no_license
|
sixthkrum/2048
|
3df1fffd42c840de8eaeca6e270761149dc08348
|
53ea39b3509f26bbd22d54e327072a9a3e7689ce
|
refs/heads/master
| 2021-02-04T02:25:50.271361
| 2020-03-27T13:40:31
| 2020-03-27T13:40:31
| 243,603,450
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,174
|
cpp
|
array_manipulation.cpp
|
#include "array_manipulation.h"
int components_move_up(int numarr[4][4])//moves components up until they reach the boundary or they touch another component uppermost components are moved first and empty spaces have zeros in them if two similar components touch then the bottom most one dissapears and the uppermost one is doubled
{
int i0;
int i1;
unsigned int lastnum;
unsigned int shiftcounter;
bool did_we_move = 0;
for(i0 = 0; i0 < 4; i0 ++)
{
lastnum = 0;
shiftcounter = 1;
for(i1 = 0; i1 < 4; i1 ++)
{
if(numarr[i1][i0] == 0)
{
shiftcounter ++;
}
else
{
if(numarr[i1][i0] == lastnum)
{
did_we_move = 1;
numarr[i1][i0] = 0;
numarr[i1 - shiftcounter][i0] = 2 * numarr[i1 - shiftcounter][i0];
lastnum = 0;
shiftcounter ++;
}
else if(shiftcounter == 1)
{
lastnum = numarr[i1][i0];
}
else if(shiftcounter != 1)
{
did_we_move = 1;
lastnum = numarr[i1][i0];
numarr[i1 - shiftcounter + 1][i0] = numarr[i1][i0];
numarr[i1][i0] = 0;
}
}
}
}
return did_we_move;
}
int components_move_down(int numarr[4][4])
{
int i0;
int i1;
unsigned int lastnum;
unsigned int shiftcounter;
bool did_we_move = 0;
for(i0 = 0; i0 < 4; i0 ++)
{
lastnum = 0;
shiftcounter = 1;
for(i1 = 3; i1 >= 0; i1 --)
{
if(numarr[i1][i0] == 0)
{
shiftcounter ++;
}
else
{
if(numarr[i1][i0] == lastnum)
{
did_we_move = 1;
numarr[i1][i0] = 0;
numarr[i1 + shiftcounter][i0] = 2 * numarr[i1 + shiftcounter][i0];
lastnum = 0;
shiftcounter ++;
}
else if(shiftcounter == 1)
{
lastnum = numarr[i1][i0];
}
else if(shiftcounter != 1)
{
did_we_move = 1;
lastnum = numarr[i1][i0];
numarr[i1 + shiftcounter - 1][i0] = numarr[i1][i0];
numarr[i1][i0] = 0;
}
}
}
}
return did_we_move;
}
int components_move_left(int numarr[4][4])
{
int i0;
int i1;
unsigned int lastnum;
unsigned int shiftcounter;
bool did_we_move = 0;
for(i0 = 0; i0 < 4; i0 ++)
{
lastnum = 0;
shiftcounter = 1;
for(i1 = 0; i1 < 4; i1 ++)
{
if(numarr[i0][i1] == 0)
{
shiftcounter ++;
}
else
{
if(numarr[i0][i1] == lastnum)
{
did_we_move = 1;
numarr[i0][i1] = 0;
numarr[i0][i1 - shiftcounter] = 2 * numarr[i0][i1 - shiftcounter];
lastnum = 0;
shiftcounter ++;
}
else if(shiftcounter == 1)
{
lastnum = numarr[i0][i1];
}
else if(shiftcounter != 1)
{
did_we_move = 1;
lastnum = numarr[i0][i1];
numarr[i0][i1 - shiftcounter + 1] = numarr[i0][i1];
numarr[i0][i1] = 0;
}
}
}
}
return did_we_move;
}
int components_move_right(int numarr[4][4])
{
int i0;
int i1;
unsigned int lastnum;
unsigned int shiftcounter;
bool did_we_move = 0;
for(i0 = 0; i0 < 4; i0 ++)
{
lastnum = 0;
shiftcounter = 1;
for(i1 = 3; i1 >= 0; i1 --)
{
if(numarr[i0][i1] == 0)
{
shiftcounter ++;
}
else
{
if(numarr[i0][i1] == lastnum)
{
did_we_move = 1;
numarr[i0][i1] = 0;
numarr[i0][i1 + shiftcounter] = 2 * numarr[i0][i1 + shiftcounter];
lastnum = 0;
shiftcounter ++;
}
else if(shiftcounter == 1)
{
lastnum = numarr[i0][i1];
}
else if(shiftcounter != 1)
{
did_we_move = 1;
lastnum = numarr[i0][i1];
numarr[i0][i1 + shiftcounter - 1] = numarr[i0][i1];
numarr[i0][i1] = 0;
}
}
}
}
return did_we_move;
}
int check_if_possible_to_move(int numarr[4][4])//only runs if empty_spaces is equal to zero otherwise does not run
{
int i0;
int i1;
unsigned int lastnum = 0;
bool possible_to_move = 0;
for(i0 = 0; i0 < 4; i0 ++)//from up to down check
{
lastnum = 0;
for(i1 = 0; i1 < 4; i1 ++)
{
if(numarr[i1][i0] == lastnum)
{
possible_to_move = 1;
return possible_to_move;
}
lastnum = numarr[i1][i0];
}
}
for(i0 = 0; i0 < 4; i0 ++)//from down to up check
{
lastnum = 0;
for(i1 = 3; i1 >= 0; i1 --)
{
if(numarr[i1][i0] == lastnum)
{
possible_to_move = 1;
return possible_to_move;
}
lastnum = numarr[i1][i0];
}
}
for(i0 = 0; i0 < 4; i0 ++)//left to right
{
lastnum = 0;
for(i1 = 0; i1 < 4; i1 ++)
{
if(numarr[i0][i1] == lastnum)
{
possible_to_move = 1;
return possible_to_move;
}
lastnum = numarr[i0][i1];
}
}
for(i0 = 0; i0 < 4; i0 ++)//right to left
{
lastnum = 0;
for(i1 = 3; i1 >= 0; i1 --)
{
if(numarr[i0][i1] == lastnum)
{
possible_to_move = 1;
return possible_to_move;
}
lastnum = numarr[i0][i1];
}
}
return possible_to_move;
}
|
ff2708f0a1a8616dc0393a90075468f4ef9b7366
|
060370ad797c542ea812d61f755370a9d802d49c
|
/Practica Schaken/Practica Schaken/Bishop.h
|
0768e9798a434082efc62eb345469ac3033c9008
|
[] |
no_license
|
JamyDev/OO1-SchaakSpel
|
d5bad88b4073a40e3952427cbd12753dbd573f46
|
0793f146f47dd2959020e9374b0a272d06448c6f
|
refs/heads/master
| 2020-12-03T05:27:04.339105
| 2015-05-07T20:51:49
| 2015-05-07T20:51:49
| 33,771,950
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 209
|
h
|
Bishop.h
|
#ifndef BISHOP_H
#define BISHOP_H 1
#include "Piece.h"
class Bishop : public Piece
{
public:
bool isValidMove(const Move& move, Game& game);
Bishop();
Bishop(enum Color colornum);
private:
};
#endif
|
1e43b11b20e5b740869bd2a74ec926e9385772a6
|
bc2308447d3b2f9899073e0372e99180a2211642
|
/PuzzleGame/PuzzleGame/Source/BoardHandler.h
|
88cdced641d0b9564cdda55053bd4ceabcf0c267
|
[] |
no_license
|
iris-rod/PuzzleGame
|
1abc7f0c42a1f0b6464a776223b9d274c550e08e
|
39e00562f8e40db2c51fdab3df75b261363b2d73
|
refs/heads/master
| 2023-03-09T08:09:46.691588
| 2021-02-21T22:43:00
| 2021-02-21T22:43:00
| 270,353,788
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 952
|
h
|
BoardHandler.h
|
#pragma once
#include "Board.h"
using namespace PieceStuff;
class BoardHandler {
public:
BoardHandler();
void Init(shared_ptr<SDLEventHandler>& sdl_handler, shared_ptr<EventListener>& other_handler);
void AddColumn();
void Restart();
void HandleAddedNewColumn(shared_ptr<EventListener>& handler);
const vector<shared_ptr<Piece>>& GetObjs() const;
private:
unique_ptr<Board> board;
int currentColumns = INITIAL_COLUMNS;
void RegisterEvents(shared_ptr<SDLEventHandler>& sdl_handler, shared_ptr<EventListener>& otherHandler);
bool IsColumnEmpty(int column);
void OrganiseColumn(int c);
void MoveColumnsBackFrom(int startColumn);
void MoveColumnsForward();
void HandleMoveForward(int startColum, int endColumn);
void HandleMoveBack(int startColum, int endColumn);
void SwapColumn(int startIndex, int endIndex);
void RemoveAllEmptyColumns();
void ReCalculateCurrentColumns();
Piece* FindPiece(const int& x, const int& y) const;
};
|
39ff99711ca06273fb9c84a02da235ac34d69a25
|
5947865dc56dc2906951f21b780db5dc901848c5
|
/GeeksforGeeks/Sum of all substrings of a number.cpp
|
9f9512b9ebe219dbf56ffbb3b5f69d7cc96829ce
|
[] |
no_license
|
nishu112/Geek-Codes
|
6d9cad76291d7c56900bd988c0c123db6d900c36
|
f7eece428655c1f656e402b321260f234de62153
|
refs/heads/master
| 2021-10-07T09:31:13.379816
| 2018-12-04T16:36:54
| 2018-12-04T16:36:54
| 121,122,751
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 388
|
cpp
|
Sum of all substrings of a number.cpp
|
#include<iostream>
#include<string>
using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
{
string str;
cin>>str;
int l=str.length();
int i=0,num=0;
while(str[i]!='\0')
{
int j=i;
int mynum=0;
while(str[j]!='\0')
{
mynum=mynum*10+(str[j]-48);
num+=mynum;
j++;
}
i++;
}
cout<<num<<'\n';
}
return 0;
}
|
1ad72afbac5dd6658bc5b3b41c736106edf091d8
|
4497624912a7af7dbdb800e9c0b152af1cca2655
|
/1063A.cpp
|
c8db3903b835200b79bef008f1807052df65bbca
|
[] |
no_license
|
singhaditya8499/Codeforces
|
0a978ea628660e18188856671e742a4cfec7cb28
|
b73e9654b319580648c016659a915174615a6ed5
|
refs/heads/master
| 2021-05-18T12:22:21.857546
| 2020-04-22T19:14:30
| 2020-04-22T19:14:30
| 251,241,430
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 379
|
cpp
|
1063A.cpp
|
//white_whale
#include<bits/stdc++.h>
#include<unordered_map>
#define mod 1000000007
using namespace std;
typedef long long ll;
int find(int x,int father[])
{
if(father[x]==x)
return x;
return father[x]=find(father[x],father);
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;
cin>>n;
string s;
cin>>s;
sort(s.begin(),s.end());
cout<<s<<"\n";
}
|
210d3169c7d28a8dadef906e2ba821883b46f80f
|
861aca8eeed02b5080eb59b3d5957e633fcb7fa9
|
/include/engine/render_system.h
|
373a25697c204e382e989317061ccc3de1201265
|
[
"MIT"
] |
permissive
|
hxhieu/32blit-hello
|
685a428d06b4cd2839b335ac37cf3ede83ba64e6
|
a44aa10291b54d9b0211f41e9a314b2f11235ac2
|
refs/heads/main
| 2023-07-31T15:27:49.158845
| 2021-09-21T12:39:20
| 2021-09-21T12:39:20
| 369,423,467
| 0
| 0
|
MIT
| 2021-09-21T12:39:21
| 2021-05-21T05:30:07
|
C++
|
UTF-8
|
C++
| false
| false
| 290
|
h
|
render_system.h
|
#pragma once
#include "32blit.hpp"
#include "entt.hpp"
#include "components.h"
namespace mitmeo
{
namespace engine
{
class RenderSystem
{
public:
RenderSystem();
void run(entt::registry &world, uint32_t time_ms);
};
}
}
|
efde3b87e5512265b1e7fa26d7ff956c9d8cb8d7
|
e926bede54cbddf08870036ae478124e0a6cec77
|
/src/tests/unit_tests/matrix_csr_tests.cpp
|
ea10b02b50110ea04e4da5f5d9e57aaed49e7ff6
|
[
"MIT"
] |
permissive
|
doyubkim/fluid-engine-dev
|
2d1228c78690191fba8ff2c107af1dd06212ca44
|
94c300ff5ad8a2f588e5e27e8e9746a424b29863
|
refs/heads/main
| 2023-08-14T08:04:43.513360
| 2022-07-09T06:24:41
| 2022-07-09T06:24:41
| 58,299,041
| 1,725
| 275
|
MIT
| 2022-07-09T06:24:41
| 2016-05-08T06:05:38
|
C++
|
UTF-8
|
C++
| false
| false
| 17,788
|
cpp
|
matrix_csr_tests.cpp
|
// Copyright (c) 2018 Doyub Kim
//
// I am making my contributions/submissions to this project solely in my
// personal capacity and am not conveying any rights to any intellectual
// property of any third parties.
#include <jet/matrix_csr.h>
#include <jet/matrix_mxn.h>
#include <jet/vector_n.h>
#include <gtest/gtest.h>
using namespace jet;
TEST(MatrixCsr, Constructors) {
const MatrixCsrD emptyMat;
EXPECT_EQ(0u, emptyMat.rows());
EXPECT_EQ(0u, emptyMat.cols());
EXPECT_EQ(0u, emptyMat.numberOfNonZeros());
EXPECT_EQ(emptyMat.nonZeroBegin(), emptyMat.nonZeroEnd());
EXPECT_EQ(1, emptyMat.rowPointersEnd() - emptyMat.rowPointersBegin());
EXPECT_EQ(emptyMat.columnIndicesBegin(), emptyMat.columnIndicesEnd());
const MatrixCsrD matInitLst = {
{1.0, 0.0, 0.0, -3.0}, {0.0, 3.0, -5.0, 1.0}, {-4.0, 0.0, 1.0, 5.0}};
EXPECT_EQ(3u, matInitLst.rows());
EXPECT_EQ(4u, matInitLst.cols());
EXPECT_EQ(8u, matInitLst.numberOfNonZeros());
auto iterInitLst = matInitLst.nonZeroBegin();
EXPECT_EQ(1.0, iterInitLst[0]);
EXPECT_EQ(-3.0, iterInitLst[1]);
EXPECT_EQ(3.0, iterInitLst[2]);
EXPECT_EQ(-5.0, iterInitLst[3]);
EXPECT_EQ(1.0, iterInitLst[4]);
EXPECT_EQ(-4.0, iterInitLst[5]);
EXPECT_EQ(1.0, iterInitLst[6]);
EXPECT_EQ(5.0, iterInitLst[7]);
const MatrixMxND matDense = {
{1.0, 0.01, 0.0, -3.0}, {0.01, 3.0, -5.0, 1.0}, {-4.0, 0.01, 1.0, 5.0}};
const MatrixCsrD matSparse(matDense, 0.02);
EXPECT_EQ(3u, matSparse.rows());
EXPECT_EQ(4u, matSparse.cols());
EXPECT_EQ(8u, matSparse.numberOfNonZeros());
auto iterSparse = matSparse.nonZeroBegin();
EXPECT_EQ(1.0, iterSparse[0]);
EXPECT_EQ(-3.0, iterSparse[1]);
EXPECT_EQ(3.0, iterSparse[2]);
EXPECT_EQ(-5.0, iterSparse[3]);
EXPECT_EQ(1.0, iterSparse[4]);
EXPECT_EQ(-4.0, iterSparse[5]);
EXPECT_EQ(1.0, iterSparse[6]);
EXPECT_EQ(5.0, iterSparse[7]);
MatrixCsrD matCopied = matSparse;
EXPECT_EQ(3u, matCopied.rows());
EXPECT_EQ(4u, matCopied.cols());
EXPECT_EQ(8u, matCopied.numberOfNonZeros());
auto iterCopied = matCopied.nonZeroBegin();
EXPECT_EQ(1.0, iterCopied[0]);
EXPECT_EQ(-3.0, iterCopied[1]);
EXPECT_EQ(3.0, iterCopied[2]);
EXPECT_EQ(-5.0, iterCopied[3]);
EXPECT_EQ(1.0, iterCopied[4]);
EXPECT_EQ(-4.0, iterCopied[5]);
EXPECT_EQ(1.0, iterCopied[6]);
EXPECT_EQ(5.0, iterCopied[7]);
const MatrixCsrD matMoved = std::move(matCopied);
EXPECT_EQ(3u, matMoved.rows());
EXPECT_EQ(4u, matMoved.cols());
EXPECT_EQ(8u, matMoved.numberOfNonZeros());
auto iterMovied = matMoved.nonZeroBegin();
EXPECT_EQ(1.0, iterMovied[0]);
EXPECT_EQ(-3.0, iterMovied[1]);
EXPECT_EQ(3.0, iterMovied[2]);
EXPECT_EQ(-5.0, iterMovied[3]);
EXPECT_EQ(1.0, iterMovied[4]);
EXPECT_EQ(-4.0, iterMovied[5]);
EXPECT_EQ(1.0, iterMovied[6]);
EXPECT_EQ(5.0, iterMovied[7]);
EXPECT_EQ(0u, matCopied.rows());
EXPECT_EQ(0u, matCopied.cols());
EXPECT_EQ(0u, matCopied.numberOfNonZeros());
EXPECT_EQ(matCopied.nonZeroBegin(), matCopied.nonZeroEnd());
EXPECT_EQ(matCopied.rowPointersBegin(), matCopied.rowPointersEnd());
EXPECT_EQ(matCopied.columnIndicesBegin(), matCopied.columnIndicesEnd());
}
TEST(MatrixCsr, BasicSetters) {
// Compress initializer list
const std::initializer_list<std::initializer_list<double>> initLst = {
{1.0, 0.01, 0.0, -3.0}, {0.01, 3.0, -5.0, 1.0}, {-4.0, 0.01, 1.0, 5.0}};
MatrixCsrD matInitLst;
matInitLst.compress(initLst, 0.02);
EXPECT_EQ(3u, matInitLst.rows());
EXPECT_EQ(4u, matInitLst.cols());
EXPECT_EQ(8u, matInitLst.numberOfNonZeros());
auto iterInitLst = matInitLst.nonZeroBegin();
EXPECT_EQ(1.0, iterInitLst[0]);
EXPECT_EQ(-3.0, iterInitLst[1]);
EXPECT_EQ(3.0, iterInitLst[2]);
EXPECT_EQ(-5.0, iterInitLst[3]);
EXPECT_EQ(1.0, iterInitLst[4]);
EXPECT_EQ(-4.0, iterInitLst[5]);
EXPECT_EQ(1.0, iterInitLst[6]);
EXPECT_EQ(5.0, iterInitLst[7]);
// Set scalar
matInitLst.set(42.0);
for (size_t i = 0; i < 8; ++i) {
EXPECT_EQ(42.0, iterInitLst[i]);
}
// Compress dense matrix
const MatrixMxND matDense = {
{1.0, 0.01, 0.0, -3.0}, {0.01, 3.0, -5.0, 1.0}, {-4.0, 0.01, 1.0, 5.0}};
MatrixCsrD matSparse;
matSparse.compress(matDense, 0.02);
EXPECT_EQ(3u, matSparse.rows());
EXPECT_EQ(4u, matSparse.cols());
EXPECT_EQ(8u, matSparse.numberOfNonZeros());
auto iterSparse = matSparse.nonZeroBegin();
EXPECT_EQ(1.0, iterSparse[0]);
EXPECT_EQ(-3.0, iterSparse[1]);
EXPECT_EQ(3.0, iterSparse[2]);
EXPECT_EQ(-5.0, iterSparse[3]);
EXPECT_EQ(1.0, iterSparse[4]);
EXPECT_EQ(-4.0, iterSparse[5]);
EXPECT_EQ(1.0, iterSparse[6]);
EXPECT_EQ(5.0, iterSparse[7]);
// Set other CSR mat
matInitLst.set(matSparse);
iterInitLst = matInitLst.nonZeroBegin();
EXPECT_EQ(1.0, iterInitLst[0]);
for (size_t i = 0; i < 8; ++i) {
EXPECT_EQ(iterSparse[i], iterInitLst[i]);
}
// Add/set element
MatrixCsrD matAddElem;
matAddElem.addElement(0, 0, 1.0);
matAddElem.setElement(0, 3, -3.0);
matAddElem.addElement(1, 1, 3.0);
matAddElem.setElement(1, 2, -5.0);
matAddElem.addElement(1, 3, 1.0);
matAddElem.setElement(2, 0, -4.0);
matAddElem.addElement(2, 2, 1.0);
matAddElem.setElement(2, 3, 5.0);
EXPECT_EQ(3u, matAddElem.rows());
EXPECT_EQ(4u, matAddElem.cols());
EXPECT_EQ(8u, matAddElem.numberOfNonZeros());
auto iterAddElem = matAddElem.nonZeroBegin();
EXPECT_EQ(1.0, iterAddElem[0]);
EXPECT_EQ(-3.0, iterAddElem[1]);
EXPECT_EQ(3.0, iterAddElem[2]);
EXPECT_EQ(-5.0, iterAddElem[3]);
EXPECT_EQ(1.0, iterAddElem[4]);
EXPECT_EQ(-4.0, iterAddElem[5]);
EXPECT_EQ(1.0, iterAddElem[6]);
EXPECT_EQ(5.0, iterAddElem[7]);
matAddElem.setElement(1, 3, 7.0);
EXPECT_EQ(7.0, iterAddElem[4]);
// Add element in random order
MatrixCsrD matAddElemRandom;
matAddElemRandom.addElement(2, 2, 1.0);
matAddElemRandom.addElement(0, 3, -3.0);
matAddElemRandom.addElement(2, 0, -4.0);
matAddElemRandom.addElement(1, 1, 3.0);
matAddElemRandom.addElement(2, 3, 5.0);
matAddElemRandom.addElement(1, 3, 1.0);
matAddElemRandom.addElement(1, 2, -5.0);
matAddElemRandom.addElement(0, 0, 1.0);
EXPECT_EQ(3u, matAddElemRandom.rows());
EXPECT_EQ(4u, matAddElemRandom.cols());
EXPECT_EQ(8u, matAddElemRandom.numberOfNonZeros());
auto iterAddElemRandom = matAddElemRandom.nonZeroBegin();
EXPECT_EQ(1.0, iterAddElemRandom[0]);
EXPECT_EQ(-3.0, iterAddElemRandom[1]);
EXPECT_EQ(3.0, iterAddElemRandom[2]);
EXPECT_EQ(-5.0, iterAddElemRandom[3]);
EXPECT_EQ(1.0, iterAddElemRandom[4]);
EXPECT_EQ(-4.0, iterAddElemRandom[5]);
EXPECT_EQ(1.0, iterAddElemRandom[6]);
EXPECT_EQ(5.0, iterAddElemRandom[7]);
// Add row
MatrixCsrD matAddRow;
matAddRow.addRow({1.0, -3.0}, {0, 3});
matAddRow.addRow({3.0, -5.0, 1.0}, {1, 2, 3});
matAddRow.addRow({-4.0, 1.0, 5.0}, {0, 2, 3});
EXPECT_EQ(3u, matAddRow.rows());
EXPECT_EQ(4u, matAddRow.cols());
EXPECT_EQ(8u, matAddRow.numberOfNonZeros());
auto iterAddRow = matAddRow.nonZeroBegin();
EXPECT_EQ(1.0, iterAddRow[0]);
EXPECT_EQ(-3.0, iterAddRow[1]);
EXPECT_EQ(3.0, iterAddRow[2]);
EXPECT_EQ(-5.0, iterAddRow[3]);
EXPECT_EQ(1.0, iterAddRow[4]);
EXPECT_EQ(-4.0, iterAddRow[5]);
EXPECT_EQ(1.0, iterAddRow[6]);
EXPECT_EQ(5.0, iterAddRow[7]);
// Clear
matAddRow.clear();
EXPECT_EQ(0u, matAddRow.rows());
EXPECT_EQ(0u, matAddRow.cols());
EXPECT_EQ(0u, matAddRow.numberOfNonZeros());
EXPECT_EQ(1u, matAddRow.rowPointersEnd() - matAddRow.rowPointersBegin());
EXPECT_EQ(0u, matAddRow.rowPointersBegin()[0]);
}
TEST(MatrixCsr, BinaryOperatorMethods) {
const MatrixCsrD matA = {{1.0, 2.0, 3.0}, {4.0, 5.0, 6.0}};
const MatrixCsrD addResult1 = matA.add(3.5);
for (size_t i = 0; i < 6; ++i) {
EXPECT_EQ(i + 4.5, addResult1.nonZero(i));
}
const MatrixCsrD matC = {{3.0, -1.0, 2.0}, {9.0, 2.0, 8.0}};
const MatrixCsrD addResult2 = matA.add(matC);
const MatrixCsrD addAns1 = {{4.0, 1.0, 5.0}, {13.0, 7.0, 14.0}};
EXPECT_TRUE(addAns1.isEqual(addResult2));
const MatrixCsrD matD = {{3.0, 0.0, 2.0}, {0.0, 2.0, 0.0}};
const MatrixCsrD addResult3 = matA.add(matD);
const MatrixCsrD addAns2 = {{4.0, 2.0, 5.0}, {4.0, 7.0, 6.0}};
EXPECT_TRUE(addAns2.isEqual(addResult3));
const MatrixCsrD matE = {{3.0, 0.0, 2.0}, {0.0, 0.0, 0.0}};
const MatrixCsrD addResult4 = matA.add(matE);
const MatrixCsrD addAns3 = {{4.0, 2.0, 5.0}, {4.0, 5.0, 6.0}};
EXPECT_TRUE(addAns3.isEqual(addResult4));
const MatrixCsrD subResult1 = matA.sub(1.5);
for (size_t i = 0; i < 6; ++i) {
EXPECT_EQ(i - 0.5, subResult1.nonZero(i));
}
const MatrixCsrD subResult2 = matA.sub(matC);
const MatrixCsrD ans2 = {{-2.0, 3.0, 1.0}, {-5.0, 3.0, -2.0}};
EXPECT_TRUE(ans2.isSimilar(subResult2));
const MatrixCsrD matB = matA.mul(2.0);
for (size_t i = 0; i < 6; ++i) {
EXPECT_EQ(2.0 * (i + 1.0), matB.nonZero(i));
}
const VectorND vecA = {-1.0, 9.0, 8.0};
const VectorND vecB = matA.mul(vecA);
const VectorND ansV = {41.0, 89.0};
EXPECT_TRUE(ansV.isEqual(vecB));
const MatrixCsrD matF = {{3.0, -1.0}, {2.0, 9.0}, {2.0, 8.0}};
const MatrixCsrD matG = matA.mul(matF);
const MatrixCsrD ans3 = {{13.0, 41.0}, {34.0, 89.0}};
EXPECT_TRUE(ans3.isEqual(matG));
const MatrixCsrD matH = matA.div(2.0);
for (size_t i = 0; i < 6; ++i) {
EXPECT_EQ((i + 1.0) / 2.0, matH.nonZero(i));
}
const MatrixCsrD matI = matA.radd(3.5);
for (size_t i = 0; i < 6; ++i) {
EXPECT_EQ(i + 4.5, matI.nonZero(i));
}
const MatrixCsrD matJ = matA.rsub(1.5);
for (size_t i = 0; i < 6; ++i) {
EXPECT_EQ(0.5 - i, matJ.nonZero(i));
}
const MatrixCsrD matK = {{3.0, -1.0, 2.0}, {9.0, 2.0, 8.0}};
const MatrixCsrD matL = matA.rsub(matK);
const MatrixCsrD ans4 = {{2.0, -3.0, -1.0}, {5.0, -3.0, 2.0}};
EXPECT_EQ(ans4, matL);
const MatrixCsrD matM = matA.rmul(2.0);
for (size_t i = 0; i < 6; ++i) {
EXPECT_EQ(2.0 * (i + 1.0), matM.nonZero(i));
}
const MatrixCsrD matP = matA.rdiv(2.0);
for (size_t i = 0; i < 6; ++i) {
EXPECT_EQ(2.0 / (i + 1.0), matP.nonZero(i));
}
}
TEST(MatrixCsr, AugmentedMethods) {
const MatrixCsrD matA = {{1.0, 2.0, 3.0}, {4.0, 5.0, 6.0}};
const MatrixCsrD matB = {{3.0, -1.0, 2.0}, {9.0, 2.0, 8.0}};
MatrixCsrD mat = matA;
mat.iadd(3.5);
for (size_t i = 0; i < 6; ++i) {
EXPECT_EQ(i + 4.5, mat.nonZero(i));
}
mat = matA;
mat.iadd(matB);
MatrixCsrD ans = {{4.0, 1.0, 5.0}, {13.0, 7.0, 14.0}};
EXPECT_EQ(ans, mat);
mat = matA;
mat.isub(1.5);
for (size_t i = 0; i < 6; ++i) {
EXPECT_EQ(i - 0.5, mat.nonZero(i));
}
mat = matA;
mat.isub(matB);
ans = {{-2.0, 3.0, 1.0}, {-5.0, 3.0, -2.0}};
EXPECT_EQ(ans, mat);
mat = matA;
mat.imul(2.0);
for (size_t i = 0; i < 6; ++i) {
EXPECT_EQ(2.0 * (i + 1.0), mat.nonZero(i));
}
MatrixCsrD matA2;
MatrixCsrD matC2;
int cnt = 0;
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 5; ++j) {
matA2.setElement(i, j, cnt + 1.0);
matC2.setElement(i, j, 25.0 - cnt);
++cnt;
}
}
matA2.imul(matC2);
MatrixCsrD ans2 = {{175.0, 160.0, 145.0, 130.0, 115.0},
{550.0, 510.0, 470.0, 430.0, 390.0},
{925.0, 860.0, 795.0, 730.0, 665.0},
{1300.0, 1210.0, 1120.0, 1030.0, 940.0},
{1675.0, 1560.0, 1445.0, 1330.0, 1215.0}};
EXPECT_EQ(ans2, matA2);
mat = matA;
mat.idiv(2.0);
for (size_t i = 0; i < 6; ++i) {
EXPECT_EQ((i + 1.0) / 2.0, mat.nonZero(i));
}
}
TEST(MatrixCsr, ComplexGetters) {
const MatrixCsrD matA = {{1.0, 2.0, 3.0}, {4.0, 5.0, 6.0}};
EXPECT_EQ(21.0, matA.sum());
EXPECT_DOUBLE_EQ(21.0 / 6.0, matA.avg());
const MatrixCsrD matB = {{3.0, -1.0, 2.0}, {-9.0, 2.0, 8.0}};
EXPECT_EQ(-9.0, matB.min());
EXPECT_EQ(8.0, matB.max());
EXPECT_EQ(-1.0, matB.absmin());
EXPECT_EQ(-9.0, matB.absmax());
const MatrixCsrD matC = {{3.0, -1.0, 2.0, 4.0, 5.0},
{-9.0, 2.0, 8.0, -1.0, 2.0},
{4.0, 3.0, 6.0, 7.0, -5.0},
{-2.0, 6.0, 7.0, 1.0, 0.0},
{4.0, 2.0, 3.0, 3.0, -9.0}};
EXPECT_EQ(3.0, matC.trace());
const MatrixCsrF matF = matC.castTo<float>();
const MatrixCsrF ansF = {{3.f, -1.f, 2.f, 4.f, 5.f},
{-9.f, 2.f, 8.f, -1.f, 2.f},
{4.f, 3.f, 6.f, 7.f, -5.f},
{-2.f, 6.f, 7.f, 1.f, 0.f},
{4.f, 2.f, 3.f, 3.f, -9.f}};
EXPECT_EQ(ansF, matF);
}
TEST(MatrixCsr, SetterOperators) {
const MatrixCsrD matA = {{1.0, 2.0, 3.0}, {4.0, 5.0, 6.0}};
const MatrixCsrD matB = {{3.0, -1.0, 2.0}, {9.0, 2.0, 8.0}};
MatrixCsrD mat = matA;
mat += 3.5;
for (size_t i = 0; i < 6; ++i) {
EXPECT_EQ(i + 4.5, mat.nonZero(i));
}
mat = matA;
mat += matB;
MatrixCsrD ans = {{4.0, 1.0, 5.0}, {13.0, 7.0, 14.0}};
EXPECT_EQ(ans, mat);
mat = matA;
mat -= 1.5;
for (size_t i = 0; i < 6; ++i) {
EXPECT_EQ(i - 0.5, mat.nonZero(i)) << i;
}
mat = matA;
mat -= matB;
ans = {{-2.0, 3.0, 1.0}, {-5.0, 3.0, -2.0}};
EXPECT_EQ(ans, mat);
mat = matA;
mat *= 2.0;
for (size_t i = 0; i < 6; ++i) {
EXPECT_EQ(2.0 * (i + 1.0), mat.nonZero(i));
}
MatrixCsrD matA2;
MatrixCsrD matC2;
int cnt = 0;
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 5; ++j) {
matA2.setElement(i, j, cnt + 1.0);
matC2.setElement(i, j, 25.0 - cnt);
++cnt;
}
}
matA2 *= matC2;
const MatrixCsrD ans2 = {{175.0, 160.0, 145.0, 130.0, 115.0},
{550.0, 510.0, 470.0, 430.0, 390.0},
{925.0, 860.0, 795.0, 730.0, 665.0},
{1300.0, 1210.0, 1120.0, 1030.0, 940.0},
{1675.0, 1560.0, 1445.0, 1330.0, 1215.0}};
EXPECT_EQ(ans2, matA2);
mat = matA;
mat /= 2.0;
for (size_t i = 0; i < 6; ++i) {
EXPECT_EQ((i + 1.0) / 2.0, mat.nonZero(i));
}
}
TEST(MatrixCsr, GetterOperators) {
const MatrixMxND matDense = {
{1.0, 0.0, 0.0, -3.0}, {0.0, 3.0, -5.0, 1.0}, {-4.0, 0.0, 1.0, 5.0}};
const MatrixCsrD matSparse(matDense, 0.02);
for (size_t i = 0; i < 3; ++i) {
for (size_t j = 0; j < 4; ++j) {
EXPECT_EQ(matDense(i, j), matSparse(i, j));
}
}
}
TEST(MatrixCsr, Builders) {
const MatrixCsrD matIden = MatrixCsrD::makeIdentity(5);
for (size_t i = 0; i < 5; ++i) {
for (size_t j = 0; j < 5; ++j) {
if (i == j) {
EXPECT_EQ(1.0, matIden(i, j));
} else {
EXPECT_EQ(0.0, matIden(i, j));
}
}
}
}
TEST(MatrixCsr, OperatorOverloadings) {
const MatrixCsrD matA = {{1.0, 2.0, 3.0}, {4.0, 5.0, 6.0}};
const MatrixCsrD addResult1 = matA + 3.5;
for (size_t i = 0; i < 6; ++i) {
EXPECT_EQ(i + 4.5, addResult1.nonZero(i));
}
const MatrixCsrD matC = {{3.0, -1.0, 2.0}, {9.0, 2.0, 8.0}};
const MatrixCsrD addResult2 = matA + matC;
const MatrixCsrD addAns1 = {{4.0, 1.0, 5.0}, {13.0, 7.0, 14.0}};
EXPECT_TRUE(addAns1.isEqual(addResult2));
const MatrixCsrD matD = {{3.0, 0.0, 2.0}, {0.0, 2.0, 0.0}};
const MatrixCsrD addResult3 = matA + matD;
const MatrixCsrD addAns2 = {{4.0, 2.0, 5.0}, {4.0, 7.0, 6.0}};
EXPECT_TRUE(addAns2.isEqual(addResult3));
const MatrixCsrD matE = {{3.0, 0.0, 2.0}, {0.0, 0.0, 0.0}};
const MatrixCsrD addResult4 = matA + matE;
const MatrixCsrD addAns3 = {{4.0, 2.0, 5.0}, {4.0, 5.0, 6.0}};
EXPECT_TRUE(addAns3.isEqual(addResult4));
const MatrixCsrD subResult1 = matA - 1.5;
for (size_t i = 0; i < 6; ++i) {
EXPECT_EQ(i - 0.5, subResult1.nonZero(i));
}
const MatrixCsrD subResult2 = matA - matC;
const MatrixCsrD ans2 = {{-2.0, 3.0, 1.0}, {-5.0, 3.0, -2.0}};
EXPECT_TRUE(ans2.isSimilar(subResult2));
const MatrixCsrD matB = matA * 2.0;
for (size_t i = 0; i < 6; ++i) {
EXPECT_EQ(2.0 * (i + 1.0), matB.nonZero(i));
}
const VectorND vecA = {-1.0, 9.0, 8.0};
const VectorND vecB = matA * vecA;
const VectorND ansV = {41.0, 89.0};
EXPECT_TRUE(ansV.isEqual(vecB));
const MatrixCsrD matF = {{3.0, -1.0}, {2.0, 9.0}, {2.0, 8.0}};
const MatrixCsrD matG = matA * matF;
const MatrixCsrD ans3 = {{13.0, 41.0}, {34.0, 89.0}};
EXPECT_TRUE(ans3.isEqual(matG));
const MatrixCsrD matH = matA / 2.0;
for (size_t i = 0; i < 6; ++i) {
EXPECT_EQ((i + 1.0) / 2.0, matH.nonZero(i));
}
const MatrixCsrD matI = 3.5 + matA;
for (size_t i = 0; i < 6; ++i) {
EXPECT_EQ(i + 4.5, matI.nonZero(i));
}
const MatrixCsrD matJ = 1.5 - matA;
for (size_t i = 0; i < 6; ++i) {
EXPECT_EQ(0.5 - i, matJ.nonZero(i));
}
const MatrixCsrD matM = 2.0 * matA;
for (size_t i = 0; i < 6; ++i) {
EXPECT_EQ(2.0 * (i + 1.0), matM.nonZero(i));
}
const MatrixCsrD matP = 2.0 / matA;
for (size_t i = 0; i < 6; ++i) {
EXPECT_EQ(2.0 / (i + 1.0), matP.nonZero(i));
}
}
|
65cca0b8431a54d8ee613ceab79d8c4320a6a4b1
|
776f5892f1395bb8d30731a60466e4c756a44c8c
|
/contests/abc091/abc091_b/main.cc
|
808c8a5de5defaa1396d98c1e90b976f2197efdf
|
[] |
no_license
|
kkishi/atcoder
|
fae494af4b47a9f39f05e7536e93d5c4dd21555b
|
f21d22095699dbf064c0d084a5ce5a09a252dc6b
|
refs/heads/master
| 2023-08-31T18:37:13.293499
| 2023-08-27T21:33:43
| 2023-08-27T21:33:43
| 264,760,383
| 0
| 0
| null | 2023-03-10T05:24:07
| 2020-05-17T21:30:14
|
C++
|
UTF-8
|
C++
| false
| false
| 239
|
cc
|
main.cc
|
#include <bits/stdc++.h>
#include "atcoder.h"
void Main() {
ints(n);
V<string> s(n);
cin >> s;
ints(m);
V<string> t(m);
cin >> t;
int ans = 0;
rep(i, n) chmax(ans, count(all(s), s[i]) - count(all(t), s[i]));
wt(ans);
}
|
f4d634c05ed36fd5d7c03857b0eaf887c6e51a7d
|
9c88338b13f01933b3185cd4a237708e34a12d9b
|
/ComputerVision/object_detection_test/object_detection_test/object_detection_test.cpp
|
0c98101dd8a646a4eb5068e0f4da366a2789d4bf
|
[
"MIT"
] |
permissive
|
taoihsu/light-painting
|
88d0517bbbd54be734315866916b0449a5c0ef73
|
6cd2447f5e9a61ed8be6889f865bceb604c595f7
|
refs/heads/master
| 2020-04-02T05:12:56.247347
| 2018-04-02T01:34:15
| 2018-04-02T01:34:15
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 22,170
|
cpp
|
object_detection_test.cpp
|
// object_detection_test.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string.h>
#include <time.h>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
using namespace cv;
using namespace std;
int VideoStreamColourDetection();
int StaticPhotoColourDetection();
int StaticPhotoEdgeDetection();
int VideoStreamEdgeDetection();
int StaticPhotoCircleDetection();
int VideoStreamColourTracking();
int VideoStreamColourTrackingNewControl();
int SampleCircleDetection();
int StaticPhotoContourDetection();
void wait(double seconds);
int main(int argc, char** argv)
{
return StaticPhotoContourDetection();
return 0;
}
int VideoStreamColourTracking()
{
VideoCapture cap(1); //capture the video from webcam
if (!cap.isOpened()) // if not success, exit program
{
cout << "Cannot open the web cam" << endl;
return -1;
}
namedWindow("Control", CV_WINDOW_AUTOSIZE); //create a window called "Control"
int iLowH = 147;
int iHighH = 179;
int iLowS = 130;
int iHighS = 255;
int iLowV = 0;
int iHighV = 255;
//Create trackbars in "Control" window
createTrackbar("LowH", "Control", &iLowH, 179); //Hue (0 - 179)
createTrackbar("HighH", "Control", &iHighH, 179);
createTrackbar("LowS", "Control", &iLowS, 255); //Saturation (0 - 255)
createTrackbar("HighS", "Control", &iHighS, 255);
createTrackbar("LowV", "Control", &iLowV, 255);//Value (0 - 255)
createTrackbar("HighV", "Control", &iHighV, 255);
int iLastX = -1;
int iLastY = -1;
//Capture a temporary image from the camera
Mat imgTmp;
cap.read(imgTmp);
//Create a black image with the size as the camera output
Mat imgLines = Mat::zeros(imgTmp.size(), CV_8UC3);;
bool draw = false;
while (true)
{
Mat imgOriginal;
bool bSuccess = cap.read(imgOriginal); // read a new frame from video
if (!bSuccess) //if not success, break loop
{
cout << "Cannot read a frame from video stream" << endl;
break;
}
Mat imgHSV;
cvtColor(imgOriginal, imgHSV, COLOR_BGR2HSV); //Convert the captured frame from BGR to HSV
Mat imgThresholded;
inRange(imgHSV, Scalar(iLowH, iLowS, iLowV), Scalar(iHighH, iHighS, iHighV), imgThresholded); //Threshold the image
//morphological opening (removes small objects from the foreground)
erode(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
dilate(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
//morphological closing (removes small holes from the foreground)
dilate(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
erode(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
//Calculate the moments of the thresholded image
Moments oMoments = moments(imgThresholded);
double dM01 = oMoments.m01;
double dM10 = oMoments.m10;
double dArea = oMoments.m00;
// if the area <= 10000, I consider that the there are no object in the image and it's because of the noise, the area is not zero
if (dArea > 1000000)
{
//calculate the position of the ball
int posX = dM10 / dArea;
int posY = dM01 / dArea;
if (iLastX >= 0 && iLastY >= 0 && posX >= 0 && posY >= 0)
{
if (draw)
{
//Draw a red line from the previous point to the current point
line(imgLines, Point(posX, posY), Point(iLastX, iLastY), Scalar(255, 255, 255), 5);
}
}
iLastX = posX;
iLastY = posY;
}
//imgThresholded = imgThresholded + imgLines;
imshow("Thresholded Image", imgThresholded); //show the thresholded image
imgOriginal = imgOriginal - imgLines;
imshow("Original", imgOriginal); //show the original image
if (waitKey(30) == 27) //wait for 'esc' key press for 30ms. If 'esc' key is pressed, break loop
{
cout << "esc key is pressed by user" << endl;
break;
}
if (waitKey(10) == 32) //wait for 'space' key press for 30ms. If 'space' toggle drawing action
{
draw = !draw;
cout << "drawing toggled" << endl;
cout << draw << endl;
}
if (waitKey(10) == 99) //wait for 'C' key press for 30ms. If 'C' is pressed, clear the drawn line
{
imgLines = Mat::zeros(imgTmp.size(), CV_8UC3);;
cout << "cleared" << endl;
}
}
return 0;
}
int VideoStreamColourTrackingNewControl()
{
VideoCapture cap(1); //capture the video from webcam
if (!cap.isOpened()) // if not success, exit program
{
cout << "Cannot open the web cam" << endl;
return -1;
}
cvNamedWindow("Control", CV_WINDOW_AUTOSIZE); //create a window called "Control"
cvNamedWindow("Drawing Control", CV_WINDOW_AUTOSIZE);
int iLowH = 147;
int iHighH = 179;
int iLowS = 130;
int iHighS = 255;
int iLowV = 0;
int iHighV = 255;
int draw = 0;
int clearScreen = 0;
//Create trackbars in "Control" window
createTrackbar("LowH", "Control", &iLowH, 179); //Hue (0 - 179)
createTrackbar("HighH", "Control", &iHighH, 179);
createTrackbar("LowS", "Control", &iLowS, 255); //Saturation (0 - 255)
createTrackbar("HighS", "Control", &iHighS, 255);
createTrackbar("LowV", "Control", &iLowV, 255);//Value (0 - 255)
createTrackbar("HighV", "Control", &iHighV, 255);
createTrackbar("HighV", "Control", &iHighV, 255);
createTrackbar("HighV", "Control", &iHighV, 255);
createTrackbar("Draw", "Drawing Control", &draw, 1);
createTrackbar("Clear", "Drawing Control", &clearScreen, 1);
int iLastX = -1;
int iLastY = -1;
//Capture a temporary image from the camera
Mat imgTmp;
cap.read(imgTmp);
//Create a black image with the size as the camera output
Mat imgLines = Mat::zeros(imgTmp.size(), CV_8UC3);;
bool drawLines = false;
int numPoints = 0;
int numFrames = 0;
vector<pair<double, double>> waypoints;
while (true)
{
Mat imgOriginal;
bool bSuccess = cap.read(imgOriginal); // read a new frame from video
if (!bSuccess) //if not success, break loop
{
cout << "Cannot read a frame from video stream" << endl;
break;
}
Mat imgHSV;
cvtColor(imgOriginal, imgHSV, COLOR_BGR2HSV); //Convert the captured frame from BGR to HSV
Mat imgThresholded;
inRange(imgHSV, Scalar(iLowH, iLowS, iLowV), Scalar(iHighH, iHighS, iHighV), imgThresholded); //Threshold the image
//morphological opening (removes small objects from the foreground)
erode(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
dilate(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
//morphological closing (removes small holes from the foreground)
dilate(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
erode(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
//Calculate the moments of the thresholded image
Moments oMoments = moments(imgThresholded);
double dM01 = oMoments.m01;
double dM10 = oMoments.m10;
double dArea = oMoments.m00;
// if the area <= 100000, I consider that the there are no object in the image and it's because of the noise, the area is not zero
if (dArea > 1000000)
{
//calculate the position of the ball
int posX = dM10 / dArea;
int posY = dM01 / dArea;
//waypoints.push_back(pair<double, double>((double)posX/imgOriginal.size().width, (double)posY / imgOriginal.size().height));
if (iLastX >= 0 && iLastY >= 0 && posX >= 0 && posY >= 0)
{
if (draw != 0)
{
numPoints++;
//Draw a line from the previous point to the current point
line(imgLines, Point(posX, posY), Point(iLastX, iLastY), Scalar(255, 255, 255), 5);
waypoints.push_back(pair<double, double>((double)posX / imgOriginal.size().width, (double)posY / imgOriginal.size().height));
}
}
iLastX = posX;
iLastY = posY;
}
imshow("Thresholded Image", imgThresholded); //show the thresholded image
imgOriginal = imgOriginal - imgLines;
imshow("Original", imgOriginal); //show the original image
if (waitKey(30) == 27) //wait for 'esc' key press for 30ms. If 'esc' key is pressed, break loop
{
cout << "esc key is pressed by user" << endl;
break;
}
if (clearScreen != 0)
{
imgLines = Mat::zeros(imgTmp.size(), CV_8UC3);;
cout << "Number of Path Points: " << numPoints << endl;
clearScreen = 0;
waypoints.clear();
numPoints = 0;
}
cout << numFrames << endl;
numFrames++;
wait(0.5);
}
ofstream waypointsFile("waypoints.txt");
if (waypointsFile.is_open())
{
for (int i = 0; i < waypoints.size(); i++)
{
waypointsFile << waypoints[i].first << "," << waypoints[i].second << endl;
}
waypointsFile.close();
}
return 0;
}
int VideoStreamColourDetection()
{
VideoCapture cap(1); //capture the video from web cam
//VideoCapture cap2(0);
if (!cap.isOpened())// || !cap2.isOpened()) // if not success, exit program
{
cout << "Cannot open the web cam" << endl;
return -1;
}
namedWindow("Control", CV_WINDOW_AUTOSIZE); //create a window called "Control"
int iLowH = 0;
int iHighH = 179;
int iLowS = 0;
int iHighS = 255;
int iLowV = 0;
int iHighV = 255;
//Create trackbars in "Control" window
cvCreateTrackbar("LowH", "Control", &iLowH, 179); //Hue (0 - 179)
cvCreateTrackbar("HighH", "Control", &iHighH, 179);
cvCreateTrackbar("LowS", "Control", &iLowS, 255); //Saturation (0 - 255)
cvCreateTrackbar("HighS", "Control", &iHighS, 255);
cvCreateTrackbar("LowV", "Control", &iLowV, 255); //Value (0 - 255)
cvCreateTrackbar("HighV", "Control", &iHighV, 255);
while (true)
{
Mat imgOriginal;
bool bSuccess = cap.read(imgOriginal); // read a new frame from video
if (!bSuccess) //if not success, break loop
{
cout << "Cannot read a frame from video stream" << endl;
break;
}
Mat imgHSV;
cvtColor(imgOriginal, imgHSV, COLOR_BGR2HSV); //Convert the captured frame from BGR to HSV
Mat imgThresholded;
inRange(imgHSV, Scalar(iLowH, iLowS, iLowV), Scalar(iHighH, iHighS, iHighV), imgThresholded); //Threshold the image
Mat imgMasked;
//morphological opening (remove small objects from the foreground)
erode(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
dilate(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
//morphological closing (fill small holes in the foreground)
dilate(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
erode(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
bitwise_and(imgOriginal, imgOriginal, imgMasked, imgThresholded);
imshow("Thresholded Image", imgThresholded); //show the thresholded image
imshow("Original", imgOriginal); //show the original image
imshow("Masked Image", imgMasked);// show the masked image
if (waitKey(30) == 27) //wait for 'esc' key press for 30ms. If 'esc' key is pressed, break loop
{
cout << "esc key is pressed by user" << endl;
break;
}
}
return 0;
}
int StaticPhotoColourDetection()
{
clock_t starttime = clock();
cout << starttime << endl;
Mat img = imread("C:/Users/Ahmed/Documents/University of Waterloo/FYDP/Test Photos/resized.jpg", CV_LOAD_IMAGE_UNCHANGED);
Mat imgOriginal = img;
namedWindow("Control", CV_WINDOW_AUTOSIZE); //create a window called "Control"
int iLowH = 0;
int iHighH = 179;
int iLowS = 0;
int iHighS = 255;
int iLowV = 0;
int iHighV = 65;
//Create trackbars in "Control" window
cvCreateTrackbar("LowH", "Control", &iLowH, 179); //Hue (0 - 179)
cvCreateTrackbar("HighH", "Control", &iHighH, 179);
cvCreateTrackbar("LowS", "Control", &iLowS, 255); //Saturation (0 - 255)
cvCreateTrackbar("HighS", "Control", &iHighS, 255);
cvCreateTrackbar("LowV", "Control", &iLowV, 255); //Value (0 - 255)
cvCreateTrackbar("HighV", "Control", &iHighV, 255);
Mat imgHSV;
Mat imgThresholded;
while (true)
{
cvtColor(imgOriginal, imgHSV, COLOR_BGR2HSV); //Convert the captured frame from BGR to HSV
inRange(imgHSV, Scalar(iLowH, iLowS, iLowV), Scalar(iHighH, iHighS, iHighV), imgThresholded); //Threshold the image
//morphological opening (remove small objects from the foreground)
erode(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
dilate(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
//morphological closing (fill small holes in the foreground)
dilate(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
erode(imgThresholded, imgThresholded, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
Mat imgFlooded = imgThresholded.clone();
floodFill(imgFlooded, cv::Point(0, 0), Scalar(255));
// Invert floodfilled image
Mat imgFloodedInv = imgFlooded.clone();
bitwise_not(imgFlooded, imgFloodedInv);
//Find center
Moments oMoments = moments(imgThresholded);
double dM01 = oMoments.m01;
double dM10 = oMoments.m10;
double dArea = oMoments.m00;
int posX = 0;
int posY = 0;
if (dArea > 10000)
{
//calculate the center of the deteceted object
posX = dM10 / dArea;
posY = dM01 / dArea;
}
Mat imgOrigianlWithcenter = imgOriginal.clone();
circle(imgOrigianlWithcenter, Point(posX, posY), 5, Scalar(0, 0, 255), 5);
imshow("Thresholded Image", imgThresholded); //show the thresholded image
imshow("Flooded", imgFlooded);
imshow("Inverted", imgFloodedInv);
imshow("Detected Center", imgOrigianlWithcenter);
//imshow("Original", imgOriginal); //show the original image
if (waitKey(30) == 27) //wait for 'esc' key press for 30ms. If 'esc' key is pressed, break loop
{
cout << "esc key is pressed by user" << endl;
imwrite("C:/Users/Ahmed/Documents/University of Waterloo/FYDP/Test Photos/temp/flooded_and_inverted.bmp", imgFloodedInv);
break;
}
}
return 0;
}
Mat src, src_gray;
Mat dst, detected_edges;
int edgeThresh = 1;
int lowThreshold;
int const max_lowThreshold = 100;
int ratio = 3;
int kernel_size = 3;
char* window_name = "Edge Map";
/**
* @function CannyThreshold
* @brief Trackbar callback - Canny thresholds input with a ratio 1:3
*/
void CannyThreshold(int, void*)
{
/// Reduce noise with a kernel 3x3
blur(src_gray, detected_edges, Size(3, 3));
/// Canny detector
Canny(detected_edges, detected_edges, lowThreshold, lowThreshold*ratio, kernel_size);
/// Using Canny's output as a mask, we display our result
dst = Scalar::all(0);
src.copyTo(dst, detected_edges);
imshow(window_name, dst);
}
int StaticPhotoEdgeDetection() {
while (true)
{
/// Load an image
src = imread("C:/Users/Ahmed/Documents/University of Waterloo/FYDP/Test Photos/resized.jpg", CV_LOAD_IMAGE_UNCHANGED);//resized.jpg//dejan-1.jpg
Mat imgOriginal = src;
if (!src.data)
{
return -1;
}
/// Create a matrix of the same type and size as src (for dst)
dst.create(src.size(), src.type());
/// Convert the image to grayscale
cvtColor(src, src_gray, CV_BGR2GRAY);
/// Create a window
namedWindow(window_name, CV_WINDOW_AUTOSIZE);
/// Create a Trackbar for user to enter threshold
createTrackbar("Min Threshold:", window_name, &lowThreshold, max_lowThreshold, CannyThreshold);
/// Show the image
//CannyThreshold(0, 0);
/// Reduce noise with a kernel 3x3
blur(src_gray, detected_edges, Size(3, 3));
/// Canny detector
Canny(detected_edges, detected_edges, lowThreshold, lowThreshold*ratio, kernel_size);
/// Using Canny's output as a mask, we display our result
dst = Scalar::all(0);
src.copyTo(dst, detected_edges);
imshow(window_name, dst);
/// Wait until user exit program by pressing a key
waitKey(0);
}
return 0;
}
int VideoStreamEdgeDetection() {
/// Load an image
VideoCapture cap(0); //capture the video from web cam
if (!cap.isOpened()) // if not success, exit program
{
cout << "Cannot open the web cam" << endl;
return -1;
}
while (true)
{
bool bSuccess = cap.read(src); // read a new frame from video
//= imread("C:/Users/Ahmed/Documents/University of Waterloo/FYDP/Test Photos/resized.jpg", CV_LOAD_IMAGE_UNCHANGED);
Mat imgOriginal = src;
if (!bSuccess) //if not success, break loop
{
cout << "Cannot read a frame from video stream" << endl;
break;
}
if (!src.data)
{
return -1;
}
/// Create a matrix of the same type and size as src (for dst)
dst.create(src.size(), src.type());
/// Convert the image to grayscale
cvtColor(src, src_gray, CV_BGR2GRAY);
/// Create a window
namedWindow(window_name, CV_WINDOW_AUTOSIZE);
/// Create a Trackbar for user to enter threshold
createTrackbar("Min Threshold:", window_name, &lowThreshold, max_lowThreshold, CannyThreshold);
/// Show the image
//CannyThreshold(0, 0);
/// Reduce noise with a kernel 3x3
blur(src_gray, detected_edges, Size(3, 3));
/// Canny detector
Canny(detected_edges, detected_edges, lowThreshold, lowThreshold*ratio, kernel_size);
/// Using Canny's output as a mask, we display our result
dst = Scalar::all(0);
src.copyTo(dst, detected_edges);
imshow(window_name, dst);
if (waitKey(30) == 27) //wait for 'esc' key press for 30ms. If 'esc' key is pressed, break loop
{
cout << "esc key is pressed by user" << endl;
break;
}
/// Wait until user exit program by pressing a key
//waitKey(0);
}
return 0;
}
int StaticPhotoCircleDetection()
{
Mat img = imread("C:/Users/Ahmed/Documents/University of Waterloo/FYDP/Test Photos/board.jpg", CV_LOAD_IMAGE_UNCHANGED);
Mat imgOriginal = img;
Mat imgThresholded;
namedWindow("Control", CV_WINDOW_AUTOSIZE); //create a window called "Control"
int iLowH = 0;
int iHighH = 179;
int iLowS = 0;
int iHighS = 255;
int iLowV = 0;
int iHighV = 255;
//Create trackbars in "Control" window
cvCreateTrackbar("LowH", "Control", &iLowH, 179); //Hue (0 - 179)
cvCreateTrackbar("HighH", "Control", &iHighH, 179);
cvCreateTrackbar("LowS", "Control", &iLowS, 255); //Saturation (0 - 255)
cvCreateTrackbar("HighS", "Control", &iHighS, 255);
cvCreateTrackbar("LowV", "Control", &iLowV, 255); //Value (0 - 255)
cvCreateTrackbar("HighV", "Control", &iHighV, 255);
Mat src, src_gray;
src = imgOriginal;
resize(src, src, Size(640, 480));
//src_gray = src;
if (!src.data)
{
return -1;
}
/// Convert it to gray
cvtColor(src, src_gray, CV_BGR2GRAY);
/// Reduce the noise so we avoid false circle detection
GaussianBlur(src_gray, src_gray, Size(9, 9), 2, 2);
vector<Vec3f> circles;
/// Apply the Hough Transform to find the circles
HoughCircles(src_gray, circles, CV_HOUGH_GRADIENT, 1, 30, 200, 50, 0, 0); //(src_gray, circles, CV_HOUGH_GRADIENT, 1, src_gray.rows / 2, 200, 100, 50, 0);
/// Draw the circles detected
for (size_t i = 0; i < circles.size(); i++)
{
Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));
int radius = cvRound(circles[i][2]);
// circle center
circle(src, center, 3, Scalar(0, 255, 0), -1, 8, 0);
// circle outline
circle(src, center, radius, Scalar(0, 0, 255), 3, 8, 0);
}
/// Show your results
namedWindow("Hough Circle Transform Demo", CV_WINDOW_AUTOSIZE);
imshow("Hough Circle Transform Demo", src);
imshow("Original", imgOriginal); //show the original image
waitKey(0);
return 0;
}
int SampleCircleDetection()
{
Mat src, gray;
src = imread("C:/Users/Ahmed/Documents/University of Waterloo/FYDP/Test Photos/board.jpg", CV_LOAD_IMAGE_COLOR);
resize(src, src, Size(640, 480));
cvtColor(src, gray, CV_BGR2GRAY);
// Reduce the noise so we avoid false circle detection
GaussianBlur(gray, gray, Size(9, 9), 2, 2);
vector<Vec3f> circles;
//circles.capacity.max_size = 10;
// Apply the Hough Transform to find the circles
HoughCircles(gray, circles, CV_HOUGH_GRADIENT, 1, 30, 200, 50, 0, 0);
// Draw the circles detected
for (size_t i = 0; i < circles.size(); i++)
{
Point center(cvRound(circles[i][0]), cvRound(circles[i][1]));
int radius = cvRound(circles[i][2]);
circle(src, center, 3, Scalar(0, 255, 0), -1, 8, 0);// circle center
circle(src, center, radius, Scalar(0, 0, 255), 3, 8, 0);// circle outline
cout << "center : " << center << "\nradius : " << radius << endl;
}
// Show your results
namedWindow("Hough Circle Transform Demo", CV_WINDOW_AUTOSIZE);
imshow("Hough Circle Transform Demo", src);
waitKey(0);
return 0;
}
int StaticPhotoContourDetection()
{
Mat image;
image = imread("../temp/flooded_and_inverted.bmp", CV_LOAD_IMAGE_UNCHANGED);
namedWindow("Display window", CV_WINDOW_AUTOSIZE);
imshow("Display window", image);
Mat gray;
threshold(image, gray, 127, 255, 0);
//cvtColor(image, gray, CV_BGR2GRAY);
//Canny(gray, gray, 100, 200, 3);
/// Find contours
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
RNG rng(12345);
waitKey(0);
findContours(gray, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
/// Draw contours
Mat drawing = Mat::zeros(gray.size(), CV_8UC3);
for (int i = 0; i< contours.size(); i++)
{
Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
drawContours(drawing, contours, i, color, 2, 8, hierarchy, 0, Point());
}
//imshow("Result window", drawing);
waitKey(0);
return 0;
}
void wait(double seconds)
{
clock_t endwait;
endwait = clock() + seconds * CLOCKS_PER_SEC;
while (clock() < endwait) {}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.