blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8e307367d5ebd3b9674789e03a8ad2da87f8c33f | d0f7a8ed6473959d7119a78c986f509d565bacaf | /bufferCircular/bufferCircular.cpp | 873239f0928e67bbd2a41bfba03980666dfb9001 | [] | no_license | sudhamadhuri/Challenge3 | 807377bf7ae84d6dea9c184fb3761ea98be3fba2 | 24fac9774a7228069e12dbaa23cde1e5e8845150 | refs/heads/master | 2016-09-10T19:46:00.545337 | 2014-12-29T16:19:01 | 2014-12-29T16:19:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,081 | cpp | // bufferCircular.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition.hpp>
#include <boost/circular_buffer.hpp>
#include "Circbuffer.h"
#include "Consumer.h"
template<class Buffer>
void fifo_test(Buffer* buffer) {
boost::progress_timer progress;
// Initialize the buffer with some values before launching producer and consumer threads.
for (unsigned long i = QUEUE_SIZE / 2L; i > 0; --i) {
#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x581))
buffer->push_front(Buffer::value_type());
#else
buffer->push_front(BOOST_DEDUCED_TYPENAME Buffer::value_type());
#endif
}
Consumer<Buffer> consumer(buffer);
Producer<Buffer> producer(buffer);
// Start the threads.
boost::thread consume(consumer);
boost::thread produce(producer);
}
int main(int argc, char** argv)
{
bounded_buffer<int> bb_int(QUEUE_SIZE);
std::cout << "bounded_buffer<int> ";
while(1)
{
fifo_test(&bb_int);
}
return 0;
} | [
"sudhamk91@gmail.com"
] | sudhamk91@gmail.com |
740a307d34fb75338a29b033ca6ac76ba1a3dcb0 | 601ef8f84521f8d99786fa530ab97b4a7a6fbf49 | /algoritmos/estructura_de_datos/trie/trie_metodo_delete/trie_repaso.cpp | 3c4f937c6405fa0ddeef37f068eb1949c5a040c4 | [] | no_license | HugoAlejandro2002/Algoritmica-2 | 4cfe1adb3cdff9758c43ae0c3887cc992548661a | 1252965bb8ce0a4ab7f8740eebab6e81f10b9a2a | refs/heads/main | 2023-07-15T21:43:40.637203 | 2021-09-02T13:34:17 | 2021-09-02T13:34:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,145 | cpp | #include <bits/stdc++.h>
using namespace std;
struct node {
char currentCharacter;
bool isWord = false;
int contadorLetras = 0;
// int priority = 0;
struct node *children[10]; // [null,null,null,......,null]
}*trie;
// Inicializar
void init() {
trie = new node(); // Instanciar el objeto trie
}
int palabrasConPrefijo(string prefijo){
node *currentNode = trie;
for (int i = 0; i< prefijo.length(); i++) { // alba
int character = prefijo[i] - '0'; // i = 0 'a'-'a' = 0
if(currentNode->children[character] == NULL) {
return 0;
}
currentNode = currentNode->children[character];
}
return currentNode->contadorLetras;
}
void insertWord(string word) { // alba
node *currentNode = trie;
for (int i = 0; i< word.length(); i++) { // alba
int character = word[i] - '0'; // i = 0 'a'-'a' = 0
if(currentNode->children[character] == NULL ) {
currentNode->children[character] = new node();
// currentNode->isWord = false;
}
// currentNode = max(currentNode->priority,priority);
currentNode = currentNode->children[character];
currentNode->currentCharacter = word[i];
currentNode->contadorLetras++;
}
currentNode->isWord = true;
}
bool searchWord(string word) { // alto
node *currentNode = trie;
for (int i = 0; i< word.length(); i++) {
int character = word[i] - '0'; // i = 0 'a'-'a' = 0
if(currentNode->children[character] == NULL ) {
return false;
}
currentNode = currentNode->children[character];
}
return currentNode->isWord;
}
void isThereWord(string word) {
if(searchWord(word)) {
cout<<"Si existe "<< "'" << word << "'"<< " en el trie"<<endl;
} else {
cout<<"No Existe "<< "'" << word << "'"<< " en el trie"<<endl;
}
}
void deleteWord(string word){
if(searchWord(word)){
node *currentNode = trie;
int depthNodeDelete = 1;
int tempDepth = 0;
for (int i = 0; i< word.length(); i++) {
int character = word[i] - '0';
if(currentNode->children[character]->isWord && word.length() != i+1) {
depthNodeDelete+= tempDepth;
}
currentNode = currentNode->children[character];
tempDepth++;
}
currentNode->isWord = false;
currentNode = trie;
for (int i = 0; i< depthNodeDelete; i++) {
int character = word[i] - '0';
currentNode = currentNode->children[character];
}
currentNode = NULL;
delete currentNode;
cout << "Se elimino una palabra " << "'" << word << "'" << " del trie" << endl;
}else{
cout << "No se puede borrar " << "'" << word << "'" << " porque no es una palabra en el trie"<< endl;
}
}
int main() {
// Inicializar Trie
init();
insertWord("2350");
insertWord("2150");
insertWord("2210");
insertWord("2211");
cout << palabrasConPrefijo("2210") << endl;
return 0;
} | [
"dylanchambifi@gmail.com"
] | dylanchambifi@gmail.com |
ba85c914cc9913f56d6c849abb114d234051413a | 70950c7e1a6233c42ae80c79f998761c3eb01024 | /CodeForces/461 DIV 2 A.cpp | 4f05c1da738a08fbc094d939f3d66e37dd4264ab | [] | no_license | karimelghazouly/CompetitiveProgramming | be54f9cf0f70d131bb44025077eb852539e5c405 | f1e1beb23b1301e154cdec4f12ddaf08b7cfe514 | refs/heads/master | 2021-09-14T00:33:44.856073 | 2018-05-06T17:52:58 | 2018-05-06T17:52:58 | 100,038,836 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 414 | cpp | #include <bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
//while(1)
//{
int x,y;
cin>>x>>y;
//x=rand()%10; y=rand()%10;
//cout<<"x = "<<x<<" y = "<<y<<endl;
y--;
int diff=x-y;
if(diff<0||diff%2!=0||(x>0&&y==0||y<0))cout<<"No"<<endl;
else cout<<"Yes"<<endl;
//}
return 0;
}
| [
"karimelghazouly@gmail.com"
] | karimelghazouly@gmail.com |
93753c4497fdf700944b65f566b3610ef8668d09 | 6ced41da926682548df646099662e79d7a6022c5 | /aws-cpp-sdk-quicksight/include/aws/quicksight/model/RestoreAnalysisResult.h | 9a560bc48290aae1daa68b7bbe32d01db06379d1 | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | irods/aws-sdk-cpp | 139104843de529f615defa4f6b8e20bc95a6be05 | 2c7fb1a048c96713a28b730e1f48096bd231e932 | refs/heads/main | 2023-07-25T12:12:04.363757 | 2022-08-26T15:33:31 | 2022-08-26T15:33:31 | 141,315,346 | 0 | 1 | Apache-2.0 | 2022-08-26T17:45:09 | 2018-07-17T16:24:06 | C++ | UTF-8 | C++ | false | false | 5,097 | h | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/quicksight/QuickSight_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace QuickSight
{
namespace Model
{
class AWS_QUICKSIGHT_API RestoreAnalysisResult
{
public:
RestoreAnalysisResult();
RestoreAnalysisResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
RestoreAnalysisResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
/**
* <p>The HTTP status of the request.</p>
*/
inline int GetStatus() const{ return m_status; }
/**
* <p>The HTTP status of the request.</p>
*/
inline void SetStatus(int value) { m_status = value; }
/**
* <p>The HTTP status of the request.</p>
*/
inline RestoreAnalysisResult& WithStatus(int value) { SetStatus(value); return *this;}
/**
* <p>The Amazon Resource Name (ARN) of the analysis that you're restoring.</p>
*/
inline const Aws::String& GetArn() const{ return m_arn; }
/**
* <p>The Amazon Resource Name (ARN) of the analysis that you're restoring.</p>
*/
inline void SetArn(const Aws::String& value) { m_arn = value; }
/**
* <p>The Amazon Resource Name (ARN) of the analysis that you're restoring.</p>
*/
inline void SetArn(Aws::String&& value) { m_arn = std::move(value); }
/**
* <p>The Amazon Resource Name (ARN) of the analysis that you're restoring.</p>
*/
inline void SetArn(const char* value) { m_arn.assign(value); }
/**
* <p>The Amazon Resource Name (ARN) of the analysis that you're restoring.</p>
*/
inline RestoreAnalysisResult& WithArn(const Aws::String& value) { SetArn(value); return *this;}
/**
* <p>The Amazon Resource Name (ARN) of the analysis that you're restoring.</p>
*/
inline RestoreAnalysisResult& WithArn(Aws::String&& value) { SetArn(std::move(value)); return *this;}
/**
* <p>The Amazon Resource Name (ARN) of the analysis that you're restoring.</p>
*/
inline RestoreAnalysisResult& WithArn(const char* value) { SetArn(value); return *this;}
/**
* <p>The ID of the analysis that you're restoring. </p>
*/
inline const Aws::String& GetAnalysisId() const{ return m_analysisId; }
/**
* <p>The ID of the analysis that you're restoring. </p>
*/
inline void SetAnalysisId(const Aws::String& value) { m_analysisId = value; }
/**
* <p>The ID of the analysis that you're restoring. </p>
*/
inline void SetAnalysisId(Aws::String&& value) { m_analysisId = std::move(value); }
/**
* <p>The ID of the analysis that you're restoring. </p>
*/
inline void SetAnalysisId(const char* value) { m_analysisId.assign(value); }
/**
* <p>The ID of the analysis that you're restoring. </p>
*/
inline RestoreAnalysisResult& WithAnalysisId(const Aws::String& value) { SetAnalysisId(value); return *this;}
/**
* <p>The ID of the analysis that you're restoring. </p>
*/
inline RestoreAnalysisResult& WithAnalysisId(Aws::String&& value) { SetAnalysisId(std::move(value)); return *this;}
/**
* <p>The ID of the analysis that you're restoring. </p>
*/
inline RestoreAnalysisResult& WithAnalysisId(const char* value) { SetAnalysisId(value); return *this;}
/**
* <p>The Amazon Web Services request ID for this operation.</p>
*/
inline const Aws::String& GetRequestId() const{ return m_requestId; }
/**
* <p>The Amazon Web Services request ID for this operation.</p>
*/
inline void SetRequestId(const Aws::String& value) { m_requestId = value; }
/**
* <p>The Amazon Web Services request ID for this operation.</p>
*/
inline void SetRequestId(Aws::String&& value) { m_requestId = std::move(value); }
/**
* <p>The Amazon Web Services request ID for this operation.</p>
*/
inline void SetRequestId(const char* value) { m_requestId.assign(value); }
/**
* <p>The Amazon Web Services request ID for this operation.</p>
*/
inline RestoreAnalysisResult& WithRequestId(const Aws::String& value) { SetRequestId(value); return *this;}
/**
* <p>The Amazon Web Services request ID for this operation.</p>
*/
inline RestoreAnalysisResult& WithRequestId(Aws::String&& value) { SetRequestId(std::move(value)); return *this;}
/**
* <p>The Amazon Web Services request ID for this operation.</p>
*/
inline RestoreAnalysisResult& WithRequestId(const char* value) { SetRequestId(value); return *this;}
private:
int m_status;
Aws::String m_arn;
Aws::String m_analysisId;
Aws::String m_requestId;
};
} // namespace Model
} // namespace QuickSight
} // namespace Aws
| [
"aws-sdk-cpp-automation@github.com"
] | aws-sdk-cpp-automation@github.com |
f93241648cec5c5bcfec2970eb029bb533ee3e0d | 98448b1558327a0f05c5efdb85308d52891336b5 | /Eigen/src/misc/Solve.h | 7f70d60afbd348be857c772c4f9398fd2051336f | [
"GPL-1.0-or-later",
"Apache-2.0",
"GPL-2.0-only"
] | permissive | gnina/gnina | 6aaf681824800a8e794f499224c05da7ade1d3ef | da19662b9d34b6e2ba640fd115746ba6f6f932e5 | refs/heads/master | 2023-09-04T12:55:35.150558 | 2023-08-31T14:59:27 | 2023-08-31T14:59:27 | 45,548,146 | 467 | 146 | Apache-2.0 | 2023-08-31T14:59:29 | 2015-11-04T15:29:17 | C++ | UTF-8 | C++ | false | false | 2,485 | h | // This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2009 Benoit Jacob <jacob.benoit.1@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_MISC_SOLVE_H
#define EIGEN_MISC_SOLVE_H
namespace Eigen {
namespace internal {
/** \class solve_retval_base
*
*/
template<typename DecompositionType, typename Rhs>
struct traits<solve_retval_base<DecompositionType, Rhs> >
{
typedef typename DecompositionType::MatrixType MatrixType;
typedef Matrix<typename Rhs::Scalar,
MatrixType::ColsAtCompileTime,
Rhs::ColsAtCompileTime,
Rhs::PlainObject::Options,
MatrixType::MaxColsAtCompileTime,
Rhs::MaxColsAtCompileTime> ReturnType;
};
template<typename _DecompositionType, typename Rhs> struct solve_retval_base
: public ReturnByValue<solve_retval_base<_DecompositionType, Rhs> >
{
typedef typename remove_all<typename Rhs::Nested>::type RhsNestedCleaned;
typedef _DecompositionType DecompositionType;
typedef ReturnByValue<solve_retval_base> Base;
typedef typename Base::Index Index;
solve_retval_base(const DecompositionType& dec, const Rhs& rhs)
: m_dec(dec), m_rhs(rhs)
{}
inline Index rows() const { return m_dec.cols(); }
inline Index cols() const { return m_rhs.cols(); }
inline const DecompositionType& dec() const { return m_dec; }
inline const RhsNestedCleaned& rhs() const { return m_rhs; }
template<typename Dest> inline void evalTo(Dest& dst) const
{
static_cast<const solve_retval<DecompositionType,Rhs>*>(this)->evalTo(dst);
}
protected:
const DecompositionType& m_dec;
typename Rhs::Nested m_rhs;
};
} // end namespace internal
#define EIGEN_MAKE_SOLVE_HELPERS(DecompositionType,Rhs) \
typedef typename DecompositionType::MatrixType MatrixType; \
typedef typename MatrixType::Scalar Scalar; \
typedef typename MatrixType::RealScalar RealScalar; \
typedef typename MatrixType::Index Index; \
typedef Eigen::internal::solve_retval_base<DecompositionType,Rhs> Base; \
using Base::dec; \
using Base::rhs; \
using Base::rows; \
using Base::cols; \
solve_retval(const DecompositionType& dec, const Rhs& rhs) \
: Base(dec, rhs) {}
} // end namespace Eigen
#endif // EIGEN_MISC_SOLVE_H
| [
"dkoes@pitt.edu"
] | dkoes@pitt.edu |
ec999d7ea1750ffb35aab1a4ff56d867018b1ddf | bb7a3421c17dc5ddcb2987729af55c694faab1d4 | /Sa/Bll/StudentPointManager.h | cecb4cc0ebd54b6d47839a436860df19e0d9c0f4 | [
"MIT"
] | permissive | saeedmaghdam/StudentClassScoreCPP | f082cecb30786f6510a5a721076db227a6d7d79e | aa5b7d57b9a3c91521622cddeae247833e17a931 | refs/heads/master | 2023-02-21T08:50:38.543007 | 2021-01-24T19:44:57 | 2021-01-24T19:53:56 | 332,539,966 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,611 | h | #ifndef Bll_StudentPointManager
#define Bll_StudentPointManager
#include <string>
#include "../Model/StudentPoint.h"
using namespace std;
namespace Sa{
namespace Bll{
class StudentPointManager{
public:
void Insert(Sa::Model::StudentPoint studentPoint){
Sa::Helper::File db = Sa::Helper::File(dbName);
db.Append(string(studentPoint.CourseId) + "|" + string(studentPoint.StudentId) + "|" + studentPoint.Point);
}
vector<Sa::Model::StudentPoint> Get(){
Sa::Helper::File db = Sa::Helper::File(dbName);
vector<Sa::Model::StudentPoint> result;
vector<string> lines = db.GetLines();
for(int i = 0; i < lines.size(); i++)
{
Sa::Helper::String stringHelper;
Sa::Model::StudentPoint studentPoint;
string line = lines[i];
vector<string> parts = stringHelper.Split(line, '|');
studentPoint.CourseId = parts[0];
studentPoint.StudentId = parts[1];
studentPoint.Point = parts[2];
result.push_back(studentPoint);
}
return result;
}
bool IsDuplicate(Sa::Model::StudentPoint studentPoint){
vector<Sa::Model::StudentPoint> studentPoints = Get();
bool isDuplicate = false;
for(int i = 0; i < studentPoints.size(); i++){
if (studentPoint.CourseId.compare(studentPoints[i].CourseId) == 0 && studentPoint.StudentId.compare(studentPoints[i].StudentId) == 0){
isDuplicate = true;
break;
}
}
return isDuplicate;
}
private:
const string dbName = "student_point";
};
}
}
#endif
| [
"me.register@outlook.com"
] | me.register@outlook.com |
bade818404bd2ed8bc34e1eb2dfb56feeef07e39 | bc377fcafd15b5186163bf937e80c5088d23a112 | /pds2/lab5/05.01/src/peca.cpp | 0e558ab16a1ae0f595df17b4e39ca376d64072a8 | [] | no_license | guilhermealbm/CC-UFMG | 9ec885da17e773a40db6b913dcf51092f95902a7 | 667cc012e3f3788c8babf5c4c9fd9106ee812a2a | refs/heads/master | 2022-08-09T19:31:23.272393 | 2022-07-20T21:23:13 | 2022-07-20T21:23:13 | 195,878,712 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 384 | cpp | #include "../include/peca.h"
#include <iostream>
Peca::Peca(int x, int y, std::string color) {
this->x = x;
this->y = y;
this->color = color;
}
int Peca::getX(){
return this->x;
}
void Peca::setX(int x){
this->x = x;
}
int Peca::getY(){
return this->y;
}
void Peca::setY(int y){
this->y = y;
}
std::string Peca::getColor(){
return this->color;
}
| [
"gui.miranda.13@gmail.com"
] | gui.miranda.13@gmail.com |
39693716d07f58ecfdf0203f6ce3ed7ebf05598d | 2d75e17aeba62a8c14ddfd9702d566778dbeea7f | /UVa 10038.cpp | 16dbc07d73f71fd2f53b8af3c60a42bf2aec1c2f | [] | no_license | f0x-mulder/UVa-solutions | ac47ecfb5ceb20bffaaa3b13ec852e43ca560c26 | 7c6903ea1fa48bcd77926aee97010e11188e042e | refs/heads/master | 2020-04-21T21:40:54.037581 | 2019-11-28T14:45:54 | 2019-11-28T14:45:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 511 | cpp | #include <bits/stdc++.h>
using namespace std;
int main() {
int n;
while (scanf("%d", &n) != EOF) {
vector<bool> v(n, false);
int last = 0;
int curr = 0;
for (int i = 0; i < n; i++) {
cin >> curr;
if (i != 0) {
int diff = abs(curr - last);
if (diff <= n - 1) v[diff] = true;
}
last = curr;
}
bool jolly = true;
for (int i = 1; i < n; i++) {
if (!v[i]) {
jolly = false;
break;
}
}
if (jolly) cout << "Jolly" << endl;
else cout << "Not jolly" << endl;
}
}
| [
"noreply@github.com"
] | noreply@github.com |
8344b268063db2562af43b7a3d8645adabf0d8ce | 44aa76e2dbf8c8dbe83b8c54ea8cdcee7031f5ac | /Multi-threading/Future.cpp | ef209ae98d18467e989fd7c82dbb532aed8feb71 | [
"MIT"
] | permissive | Avelyev/Cplusplus | b66ab98b7e35e0e47ad827645878db2a60e5606f | 3e9f99e8421ea6f747a6b00302deafffe1f930b6 | refs/heads/master | 2021-01-21T21:57:32.165827 | 2017-06-22T19:09:42 | 2017-06-22T19:09:42 | 95,136,290 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,562 | cpp | /*****************************************************************************
* This example demonstrates how to create and work with multiple threads of program and use future
*
* Этот пример демонстрирует создание и работу с несколькими потоками в программе с использованием future
*
* Code&Robots site: http://codrob.ru/
* YouTube Channel: https://www.youtube.com/c/code_robots
* Social networks: https://vk.com/codrob
* https://www.facebook.com/groups/295824740787675/
*
* This example code is in public domain and licensed under MIT license
*****************************************************************************/
#include <iostream>
#include <unistd.h>
#include <thread>
#include <future>
using namespace std;
bool task (int n)
{
sleep(n);
cout << n << ": ";
return true;
}
void task_f (future<int>& f)
{
int n = f.get();
sleep(n);
cout << n << ": " << "DONE" << endl;
}
int main ()
{
//Create thread and wait return value
{
future<bool> ft = async(task, 3);
if (ft.get())
{
cout << "DONE 1" << endl;
}
}
//Create thread and wait return value
{
packaged_task<bool(int)> tsk (task);
future<bool> ret = tsk.get_future();
thread th (move(tsk), 2);
if (ret.get())
{
cout << "DONE 2" << endl;
}
th.join();
}
//Self set return future value
{
promise<int> prom;
future<int> ft = prom.get_future();
thread t1 (task_f, ref(ft));
prom.set_value(1);
t1.join();
}
}
| [
"eugene@codrob.ru"
] | eugene@codrob.ru |
c281dafe07b3fb3a2a3e6856a834b5bc3fd7a44f | d0c44dd3da2ef8c0ff835982a437946cbf4d2940 | /cmake-build-debug/programs_tiling/function13813/function13813_schedule_4/function13813_schedule_4.cpp | 2779982142229f83f6d40d905399388b8432bd77 | [] | no_license | IsraMekki/tiramisu_code_generator | 8b3f1d63cff62ba9f5242c019058d5a3119184a3 | 5a259d8e244af452e5301126683fa4320c2047a3 | refs/heads/master | 2020-04-29T17:27:57.987172 | 2019-04-23T16:50:32 | 2019-04-23T16:50:32 | 176,297,755 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,091 | cpp | #include <tiramisu/tiramisu.h>
using namespace tiramisu;
int main(int argc, char **argv){
tiramisu::init("function13813_schedule_4");
constant c0("c0", 65536), c1("c1", 1024);
var i0("i0", 0, c0), i1("i1", 0, c1), i01("i01"), i02("i02"), i03("i03"), i04("i04");
input input00("input00", {i0}, p_int32);
input input01("input01", {i0}, p_int32);
input input02("input02", {i1}, p_int32);
computation comp0("comp0", {i0, i1}, input00(i0) + input01(i0) * input02(i1));
comp0.tile(i0, i1, 64, 64, i01, i02, i03, i04);
comp0.parallelize(i01);
buffer buf00("buf00", {65536}, p_int32, a_input);
buffer buf01("buf01", {65536}, p_int32, a_input);
buffer buf02("buf02", {1024}, p_int32, a_input);
buffer buf0("buf0", {65536, 1024}, p_int32, a_output);
input00.store_in(&buf00);
input01.store_in(&buf01);
input02.store_in(&buf02);
comp0.store_in(&buf0);
tiramisu::codegen({&buf00, &buf01, &buf02, &buf0}, "../data/programs/function13813/function13813_schedule_4/function13813_schedule_4.o");
return 0;
} | [
"ei_mekki@esi.dz"
] | ei_mekki@esi.dz |
6a13b9840573dabd6a30bd7f193b689693f48197 | 870d759b359de1e393452e4d280a2fd199fb95b5 | /UiLib/Layout/UIVerticalLayout.cpp | 17ec0f47255943fa3a40b7742e338486ab39d4b0 | [] | no_license | yuechuanbingzhi163/UPIM | 8ff40d58f14a6d615725b3432b50489f1e723d05 | b02053b107fd662311620ac34f4b5eb55a37d46f | refs/heads/master | 2023-03-20T19:00:30.040607 | 2016-07-20T00:55:28 | 2016-07-20T00:55:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,096 | cpp | #include "stdafx.h"
#include "UIVerticalLayout.h"
namespace DuiLib
{
CVerticalLayoutUI::CVerticalLayoutUI() : m_iSepHeight(0), m_uButtonState(0), m_bImmMode(false)
{
ptLastMouse.x = ptLastMouse.y = 0;
::ZeroMemory(&m_rcNewPos, sizeof(m_rcNewPos));
}
LPCTSTR CVerticalLayoutUI::GetClass() const
{
return _T("VerticalLayoutUI");
}
LPVOID CVerticalLayoutUI::GetInterface(LPCTSTR pstrName)
{
if( _tcscmp(pstrName, DUI_CTR_VERTICALLAYOUT) == 0 ) return static_cast<CVerticalLayoutUI*>(this);
return CContainerUI::GetInterface(pstrName);
}
UINT CVerticalLayoutUI::GetControlFlags() const
{
if( IsEnabled() && m_iSepHeight != 0 ) return UIFLAG_SETCURSOR;
else return 0;
}
void CVerticalLayoutUI::SetPos(RECT rc)
{
CControlUI::SetPos(rc);
rc = m_rcItem;
// Adjust for inset
rc.left += m_rcInset.left;
rc.top += m_rcInset.top;
rc.right -= m_rcInset.right;
rc.bottom -= m_rcInset.bottom;
if( m_pVerticalScrollBar && m_pVerticalScrollBar->IsVisible() ) rc.right -= m_pVerticalScrollBar->GetFixedWidth();
if( m_pHorizontalScrollBar && m_pHorizontalScrollBar->IsVisible() ) rc.bottom -= m_pHorizontalScrollBar->GetFixedHeight();
if( m_items.GetSize() == 0) {
ProcessScrollBar(rc, 0, 0);
return;
}
// Determine the minimum size
SIZE szAvailable = { rc.right - rc.left, rc.bottom - rc.top };
if( m_pHorizontalScrollBar && m_pHorizontalScrollBar->IsVisible() )
szAvailable.cx += m_pHorizontalScrollBar->GetScrollRange();
int nAdjustables = 0;
int cyFixed = 0;
int nEstimateNum = 0;
for( int it1 = 0; it1 < m_items.GetSize(); it1++ ) {
CControlUI* pControl = static_cast<CControlUI*>(m_items[it1]);
if( !pControl->IsVisible() ) continue;
if( pControl->IsFloat() ) continue;
SIZE sz = pControl->EstimateSize(szAvailable);
if( sz.cy == 0 ) {
nAdjustables++;
}
else {
if( sz.cy < pControl->GetMinHeight() ) sz.cy = pControl->GetMinHeight();
if( sz.cy > pControl->GetMaxHeight() ) sz.cy = pControl->GetMaxHeight();
}
cyFixed += sz.cy + pControl->GetPadding().top + pControl->GetPadding().bottom;
nEstimateNum++;
}
cyFixed += (nEstimateNum - 1) * m_iChildPadding;
// Place elements
int cyNeeded = 0;
int cyExpand = 0;
if( nAdjustables > 0 ) cyExpand = MAX(0, (szAvailable.cy - cyFixed) / nAdjustables);
// Position the elements
SIZE szRemaining = szAvailable;
int iPosY = rc.top;
if( m_pVerticalScrollBar && m_pVerticalScrollBar->IsVisible() ) {
iPosY -= m_pVerticalScrollBar->GetScrollPos();
}
int iPosX = rc.left;
if( m_pHorizontalScrollBar && m_pHorizontalScrollBar->IsVisible() ) {
iPosX -= m_pHorizontalScrollBar->GetScrollPos();
}
int iAdjustable = 0;
int cyFixedRemaining = cyFixed;
for( int it2 = 0; it2 < m_items.GetSize(); it2++ ) {
CControlUI* pControl = static_cast<CControlUI*>(m_items[it2]);
if( !pControl->IsVisible() ) continue;
if( pControl->IsFloat() ) {
SetFloatPos(it2);
continue;
}
RECT rcPadding = pControl->GetPadding();
szRemaining.cy -= rcPadding.top;
SIZE sz = pControl->EstimateSize(szRemaining);
if( sz.cy == 0 ) {
iAdjustable++;
sz.cy = cyExpand;
// Distribute remaining to last element (usually round-off left-overs)
if( iAdjustable == nAdjustables ) {
sz.cy = MAX(0, szRemaining.cy - rcPadding.bottom - cyFixedRemaining);
}
if( sz.cy < pControl->GetMinHeight() ) sz.cy = pControl->GetMinHeight();
if( sz.cy > pControl->GetMaxHeight() ) sz.cy = pControl->GetMaxHeight();
}
else {
if( sz.cy < pControl->GetMinHeight() ) sz.cy = pControl->GetMinHeight();
if( sz.cy > pControl->GetMaxHeight() ) sz.cy = pControl->GetMaxHeight();
cyFixedRemaining -= sz.cy + rcPadding.top + rcPadding.bottom;
}
cyFixedRemaining -= m_iChildPadding;
sz.cx = pControl->GetFixedWidth();
if( sz.cx == 0 ) sz.cx = szAvailable.cx - rcPadding.left - rcPadding.right;
if( sz.cx < 0 ) sz.cx = 0;
if( sz.cx < pControl->GetMinWidth() ) sz.cx = pControl->GetMinWidth();
if( sz.cx > pControl->GetMaxWidth() ) sz.cx = pControl->GetMaxWidth();
RECT rcCtrl = { iPosX + rcPadding.left, iPosY + rcPadding.top, iPosX + rcPadding.left + sz.cx, iPosY + sz.cy + rcPadding.top };
pControl->SetPos(rcCtrl);
iPosY += sz.cy + m_iChildPadding + rcPadding.top + rcPadding.bottom;
cyNeeded += sz.cy + rcPadding.top + rcPadding.bottom;
szRemaining.cy -= sz.cy + m_iChildPadding + rcPadding.bottom;
}
cyNeeded += (nEstimateNum - 1) * m_iChildPadding;
// Process the scrollbar
ProcessScrollBar(rc, 0, cyNeeded);
}
void CVerticalLayoutUI::DoPostPaint(HDC hDC, const RECT& rcPaint)
{
if( (m_uButtonState & UISTATE_CAPTURED) != 0 && !m_bImmMode ) {
RECT rcSeparator = GetThumbRect(true);
CRenderEngine::DrawColor(hDC, rcSeparator, 0xAA000000);
}
}
void CVerticalLayoutUI::SetSepHeight(int iHeight)
{
m_iSepHeight = iHeight;
}
int CVerticalLayoutUI::GetSepHeight() const
{
return m_iSepHeight;
}
void CVerticalLayoutUI::SetSepImmMode(bool bImmediately)
{
if( m_bImmMode == bImmediately ) return;
if( (m_uButtonState & UISTATE_CAPTURED) != 0 && !m_bImmMode && m_pManager != NULL ) {
m_pManager->RemovePostPaint(this);
}
m_bImmMode = bImmediately;
}
bool CVerticalLayoutUI::IsSepImmMode() const
{
return m_bImmMode;
}
void CVerticalLayoutUI::SetAttribute(LPCTSTR pstrName, LPCTSTR pstrValue)
{
if( _tcscmp(pstrName, _T("sepheight")) == 0 ) SetSepHeight(_ttoi(pstrValue));
else if( _tcscmp(pstrName, _T("sepimm")) == 0 ) SetSepImmMode(_tcscmp(pstrValue, _T("true")) == 0);
else CContainerUI::SetAttribute(pstrName, pstrValue);
}
void CVerticalLayoutUI::DoEvent(TEventUI& event)
{
if( m_iSepHeight != 0 ) {
if( event.Type == UIEVENT_BUTTONDOWN && IsEnabled() )
{
RECT rcSeparator = GetThumbRect(false);
if( ::PtInRect(&rcSeparator, event.ptMouse) ) {
m_uButtonState |= UISTATE_CAPTURED;
ptLastMouse = event.ptMouse;
m_rcNewPos = m_rcItem;
if( !m_bImmMode && m_pManager ) m_pManager->AddPostPaint(this);
return;
}
}
if( event.Type == UIEVENT_BUTTONUP )
{
if( (m_uButtonState & UISTATE_CAPTURED) != 0 ) {
m_uButtonState &= ~UISTATE_CAPTURED;
m_rcItem = m_rcNewPos;
if( !m_bImmMode && m_pManager ) m_pManager->RemovePostPaint(this);
NeedParentUpdate();
return;
}
}
if( event.Type == UIEVENT_MOUSEMOVE )
{
if( (m_uButtonState & UISTATE_CAPTURED) != 0 ) {
LONG cy = event.ptMouse.y - ptLastMouse.y;
ptLastMouse = event.ptMouse;
RECT rc = m_rcNewPos;
if( m_iSepHeight >= 0 ) {
if( cy > 0 && event.ptMouse.y < m_rcNewPos.bottom + m_iSepHeight ) return;
if( cy < 0 && event.ptMouse.y > m_rcNewPos.bottom ) return;
rc.bottom += cy;
if( rc.bottom - rc.top <= GetMinHeight() ) {
if( m_rcNewPos.bottom - m_rcNewPos.top <= GetMinHeight() ) return;
rc.bottom = rc.top + GetMinHeight();
}
if( rc.bottom - rc.top >= GetMaxHeight() ) {
if( m_rcNewPos.bottom - m_rcNewPos.top >= GetMaxHeight() ) return;
rc.bottom = rc.top + GetMaxHeight();
}
}
else {
if( cy > 0 && event.ptMouse.y < m_rcNewPos.top ) return;
if( cy < 0 && event.ptMouse.y > m_rcNewPos.top + m_iSepHeight ) return;
rc.top += cy;
if( rc.bottom - rc.top <= GetMinHeight() ) {
if( m_rcNewPos.bottom - m_rcNewPos.top <= GetMinHeight() ) return;
rc.top = rc.bottom - GetMinHeight();
}
if( rc.bottom - rc.top >= GetMaxHeight() ) {
if( m_rcNewPos.bottom - m_rcNewPos.top >= GetMaxHeight() ) return;
rc.top = rc.bottom - GetMaxHeight();
}
}
CDuiRect rcInvalidate = GetThumbRect(true);
m_rcNewPos = rc;
m_cxyFixed.cy = m_rcNewPos.bottom - m_rcNewPos.top;
if( m_bImmMode ) {
m_rcItem = m_rcNewPos;
NeedParentUpdate();
}
else {
rcInvalidate.Join(GetThumbRect(true));
rcInvalidate.Join(GetThumbRect(false));
if( m_pManager ) m_pManager->Invalidate(rcInvalidate);
}
return;
}
}
if( event.Type == UIEVENT_SETCURSOR )
{
RECT rcSeparator = GetThumbRect(false);
if( IsEnabled() && ::PtInRect(&rcSeparator, event.ptMouse) ) {
::SetCursor(::LoadCursor(NULL, MAKEINTRESOURCE(IDC_SIZENS)));
return;
}
}
}
CContainerUI::DoEvent(event);
}
RECT CVerticalLayoutUI::GetThumbRect(bool bUseNew) const
{
if( (m_uButtonState & UISTATE_CAPTURED) != 0 && bUseNew) {
if( m_iSepHeight >= 0 )
return CDuiRect(m_rcNewPos.left, MAX(m_rcNewPos.bottom - m_iSepHeight, m_rcNewPos.top),
m_rcNewPos.right, m_rcNewPos.bottom);
else
return CDuiRect(m_rcNewPos.left, m_rcNewPos.top, m_rcNewPos.right,
MIN(m_rcNewPos.top - m_iSepHeight, m_rcNewPos.bottom));
}
else {
if( m_iSepHeight >= 0 )
return CDuiRect(m_rcItem.left, MAX(m_rcItem.bottom - m_iSepHeight, m_rcItem.top), m_rcItem.right,
m_rcItem.bottom);
else
return CDuiRect(m_rcItem.left, m_rcItem.top, m_rcItem.right,
MIN(m_rcItem.top - m_iSepHeight, m_rcItem.bottom));
}
}
}
| [
"lhbabyblue@163.com"
] | lhbabyblue@163.com |
9869f9b841cee44ea953663eb74f026eb85f575f | 311e0608b4005865b90eb153d961b8758ba6de28 | /LAB 7/ShortestRoute3.cpp | c6b8df3e5b1f45db297ea80102d5366cbab3a137 | [] | no_license | JPL4494/DVC-COMSC200 | e71c9c46b33bd4886932ee87c0be31e581cb8c3e | c76a7f087b353ba16fdac9a1b0ba27e972daa5f0 | refs/heads/master | 2020-03-19T00:25:03.075887 | 2018-05-30T19:23:33 | 2018-05-30T19:23:33 | 135,479,290 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,122 | cpp | /*
Lab 7b, The third version of the shortest route Program
Programmer: Joshua Long
Editor used: Notepad
Compiler used: CodeBlocks
*/
#include<iostream>
using std::cout;
using std::endl;
using std::ostream;
#include<string>
using std::string;
class Route;
class Leg
{
const string city1;
const string city2;
const double distance;
public:
Leg(const string, const string, const double = 0);
friend void printLeg(ostream&, const Leg&);
friend class Route;
friend void printRoute(ostream&, const Route&);
};
Leg::Leg(const string cityA, const string cityB, const double d)
:city1(cityA), city2(cityB), distance(d)
{}
void printLeg(ostream& out, const Leg& temp)
{
out << "From " << temp.city1 << " to " << temp.city2 << " " << temp.distance << " miles" << endl ;
}
class Route
{
const int counter;
const double distance;
const Leg** const leg;
public:
Route(const Leg&);
Route(const Route&, const Leg&);
Route(const Route&);
bool isGreaterThan(const Route&) const;
friend void printRoute(ostream&, const Route&);
~Route() {delete [] leg;};
};
Route::Route(const Leg& l)
:counter(1), distance(l.distance), leg(new const Leg* [counter])
{
int c = counter - 1;
leg[c] = (&l);
}
Route::Route(const Route& r, const Leg& l)
:counter(r.counter+1), distance(l.distance+r.distance), leg(new const Leg* [counter])
{
if(l.city1 != (r.leg[r.counter-1] -> city2))
{
delete [] leg;
throw "CITY1 != CITY2";
}
for(int i = 0; i < r.counter; i++)
{
leg[i] = (r.leg[i]);
}
leg[r.counter] = (&l);
}
Route::Route(const Route& r)
:counter(r.counter), distance(r.distance), leg(new const Leg* [counter])
{
for(int i = 0; i < r.counter; i++)
{
leg[i] = (r.leg[i]);
}
}
bool Route::isGreaterThan(const Route& route) const
{
if(distance > route.distance)
{
return true;
}
else
{
return false;
}
}
void printRoute(ostream& out, const Route& r)
{
out << "From " << (r.leg[0]) -> city1;
for(int i = 0; i < r.counter; i++)
{
out << " to ";
out << (r.leg[i]) -> city2;
}
out << ", Distance: " << r.distance << endl;
}
int main()
{
cout << "Lab 7b, The shortest route Program" << endl;
cout << "Programmer: Joshua Long" << endl;
cout << "Editor used: Notepad" << endl;
cout << "Compiler used: CodeBlocks" << endl;
cout << "File: " << __FILE__ << endl;
cout << "Compiled: " << __DATE__ << " at " << __TIME__ << endl << endl;
Leg a("Concord", "San Francisco", 30.8);
Leg b("San Francisco", "San Jose", 47.8);
Leg c("San Jose", "Santa Cruz", 32.7);
Leg d("Santa Cruz", "Monterey", 42.3);
Leg e("Monterey", "Santa Barbara", 235);
cout << endl;
Route ra(a);
Route rb(ra, b);
Route rc(rb, c);
Route rd(rc, d);
Route re(rd, e);
printRoute(cout, re);
{
cout << endl << "Copying through inline decleration" << endl;
Route rCopy = re;
printRoute(cout,rCopy);
}
{
cout << endl << "Testing copy function" << endl;
Route reCopy(re);
printRoute(cout,reCopy);
}
cout << endl << "Testing isGreaterThan member function between route a and b, expected false" << endl;
if(ra.isGreaterThan((rb)))
{
cout << "True" << endl;
}
else
{
cout << "False" << endl;
}
cout << endl << "Testing isGreaterThan member function between route e and b, expected true" << endl;
if(re.isGreaterThan((rb)))
{
cout << "True" << endl;
}
else
{
cout << "False" << endl;
}
cout << endl << "Testing isGreaterThan member function between route a and d, expected false" << endl;
if(ra.isGreaterThan((rd)))
{
cout << "True" << endl;
}
else
{
cout << "False" << endl;
}
cout << endl << "Running throw and catch error, expected result ERROR: CITY1 != CITY2" << endl;
try
{
Route(Route(Leg("a", "b", 0)), Leg("c", "d", 0));
}
catch (const char* ex)
{
cout << "ERROR DETECTED: " << ex << endl;
}
cout << endl << endl;
}
| [
"noreply@github.com"
] | noreply@github.com |
680932de60418dd29fb9af35b8572356037335bf | 51c1c5e9b8489ef8afa029b162aaf4c8f8bda7fc | /easyshadow/src/libshadow/Sprite.h | c8b400799b0639421bdb9c6617045266870a617e | [
"MIT"
] | permissive | aimoonchen/easyeditor | 3e5c77f0173a40a802fd73d7b741c064095d83e6 | 9dabdbfb8ad7b00c992d997d6662752130d5a02d | refs/heads/master | 2021-04-26T23:06:27.016240 | 2018-02-12T02:28:50 | 2018-02-12T02:28:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 428 | h | #ifndef _EASYSHADOW_SPRITE_H_
#define _EASYSHADOW_SPRITE_H_
#include <ee/Sprite.h>
namespace eshadow
{
class Symbol;
class Sprite : public ee::Sprite
{
public:
Sprite(const Sprite& spr);
Sprite& operator = (const Sprite& spr);
Sprite(const s2::SymPtr& sym, uint32_t id = -1);
static ee::SprPtr Create(const std::shared_ptr<ee::Symbol>& sym);
S2_SPR_CLONE_FUNC(Sprite)
}; // Sprite
}
#endif // _EASYSHADOW_SPRITE_H_ | [
"zhuguang@ejoy.com"
] | zhuguang@ejoy.com |
a87ed24c9e6c84d2e9499f02043927fa4df59a33 | ee5be159d1373382a9389b9b3d0afc9fd9ef9773 | /include/libflatarray/detail/destroy_functor.hpp | 1fd47f1f961e84aee9bcaaac085fd0f70c6e792d | [
"BSL-1.0"
] | permissive | zhulianhua/libflatarray | 78de4aa8b6708b38f3b8f4d91fec64f9e9bba9f8 | 9e7d3e105ada33424130ecc4b5ced781ef65a40d | refs/heads/master | 2021-01-21T18:33:15.263886 | 2017-03-23T06:56:12 | 2017-03-23T06:56:12 | 92,053,234 | 0 | 1 | null | 2017-05-22T12:53:26 | 2017-05-22T12:53:26 | null | UTF-8 | C++ | false | false | 3,007 | hpp | /**
* Copyright 2016-2017 Andreas Schäfer
*
* Distributed under the Boost Software License, Version 1.0. (See accompanying
* file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef FLAT_ARRAY_DETAIL_DESTROY_FUNCTOR_HPP
#define FLAT_ARRAY_DETAIL_DESTROY_FUNCTOR_HPP
#include <libflatarray/config.h>
#include <libflatarray/detail/generate_cuda_launch_config.hpp>
namespace LibFlatArray {
namespace detail {
namespace flat_array {
/**
* Will call the destructor on all grid cells, relies on the SoA
* (Struct of Arrays) accessor to destroy a cell's members
* individually.
*/
template<typename CELL, bool USE_CUDA_FUNCTORS = false>
class destroy_functor
{
public:
destroy_functor(
std::size_t dim_x,
std::size_t dim_y,
std::size_t dim_z) :
dim_x(dim_x),
dim_y(dim_y),
dim_z(dim_z)
{}
template<long DIM_X, long DIM_Y, long DIM_Z, long INDEX>
void operator()(soa_accessor<CELL, DIM_X, DIM_Y, DIM_Z, INDEX>& accessor) const
{
for (std::size_t z = 0; z < dim_z; ++z) {
for (std::size_t y = 0; y < dim_y; ++y) {
accessor.index() = long(soa_accessor<CELL, DIM_X, DIM_Y, DIM_Z, INDEX>::gen_index(0, y, z));
for (std::size_t x = 0; x < dim_x; ++x) {
accessor.destroy_members();
++accessor;
}
}
}
}
private:
std::size_t dim_x;
std::size_t dim_y;
std::size_t dim_z;
};
#ifdef LIBFLATARRAY_WITH_CUDA
#ifdef __CUDACC__
template<typename CELL, long DIM_X, long DIM_Y, long DIM_Z, long INDEX>
__global__
void destroy_kernel(char *data, long dim_x, long dim_y, long dim_z)
{
long x = blockDim.x * blockIdx.x + threadIdx.x;
long y = blockDim.y * blockIdx.y + threadIdx.y;
long z = blockDim.z * blockIdx.z + threadIdx.z;
if (x >= dim_x) {
return;
}
if (y >= dim_y) {
return;
}
if (z >= dim_z) {
return;
}
typedef soa_accessor_light<CELL, DIM_X, DIM_Y, DIM_Z, INDEX> accessor_type;
long index = accessor_type::gen_index(x, y, z);
accessor_type accessor(data, index);
accessor.destroy_members();
}
/**
* Specialization for CUDA
*/
template<typename CELL>
class destroy_functor<CELL, true>
{
public:
destroy_functor(
std::size_t dim_x,
std::size_t dim_y,
std::size_t dim_z) :
dim_x(dim_x),
dim_y(dim_y),
dim_z(dim_z)
{}
template<long DIM_X, long DIM_Y, long DIM_Z, long INDEX>
void operator()(soa_accessor<CELL, DIM_X, DIM_Y, DIM_Z, INDEX>& accessor) const
{
dim3 grid_dim;
dim3 block_dim;
generate_launch_config()(&grid_dim, &block_dim, dim_x, dim_y, dim_z);
destroy_kernel<CELL, DIM_X, DIM_Y, DIM_Z, INDEX><<<grid_dim, block_dim>>>(accessor.data(), dim_x, dim_y, dim_z);
}
private:
std::size_t dim_x;
std::size_t dim_y;
std::size_t dim_z;
};
#endif
#endif
}
}
}
#endif
| [
"gentryx@gmx.de"
] | gentryx@gmx.de |
5b3efe38794a188fd1ddcd33b3ae1643f969d88f | b2097f2c200768ce0b4b9bb397ab766f7752558e | /Attack.cpp | 9aeea364e7ae7f405aeeb9f52f82c52c46f57035 | [] | no_license | dhairyaagrawal/zork-project | a8a45859dfa941b679404932545b88555ed67e67 | c6c77bb7e4783169955ab20c0dbb957d0672c847 | refs/heads/master | 2020-04-04T15:30:07.346364 | 2019-10-01T18:57:07 | 2019-10-01T18:57:07 | 156,040,070 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 141 | cpp | /*
* Attack.cpp
*
* Created on: Nov 4, 2018
* Author: Dhairya
*/
#include "Attack.hpp"
Attack::Attack() {}
Attack::~Attack() {}
| [
"dhairyaagrawal@gmail.com"
] | dhairyaagrawal@gmail.com |
7903bf92dcded9627d7f412251cf8548220190e1 | e51562372a36b4729033bf19a4daf7ca7e462e30 | /hdu-4828-2 Accepted.cpp | df7e40d407b186191f75e0bd54674165a9c0dffb | [] | no_license | sl1296/acm-code | 72cd755e5c63dfdf9d0202cb14a183ccff3d9576 | 50f6b9ea865e33d9af5882acd0f2a05c9252c1f8 | refs/heads/master | 2020-08-22T11:56:17.002467 | 2019-11-09T11:08:25 | 2019-11-09T11:08:25 | 216,388,381 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 597 | cpp |
#include <cstdio>
#define ll __int64
#define mod 1000000007
ll jc[2000010],res[1000010];
void exgcd(__int64 a,__int64 b,__int64 &x,__int64 &y){
if (b==0){
x=1,y=0;
return;
}
exgcd(b,a%b,y,x);
y-=a/b*x;
}
int main(){
int n,t,i,z;
ll a,b;
jc[0]=1;
for(i=1;i<2000005;i++)jc[i]=(jc[i-1]*i)%mod;
for(i=1;i<1000005;i++){
exgcd(jc[i],mod,a,b);
res[i]=(a%mod+mod)%mod;
}
scanf("%d",&t);
for(z=1;z<=t;z++){
scanf("%d",&n);
a=jc[n+n]*res[n+1]%mod*res[n]%mod;
printf("Case #%d:\n%I64d\n",z,a);
}
}
| [
"guocl0729@163.com"
] | guocl0729@163.com |
af928675759a8f639bbf5b7394a8b60f946a2e75 | 791e96a1388d22fb777fe7b5b99d507b967ed9fb | /Desktop/code/C++_codes/C_pro_codes/Alphabets/o.cpp | 1ce45a4fd1c16feb57bbdd62a02136c74b42d4f5 | [] | no_license | baggamrohithraj/Alpha_auto | 23d01b94304f7fec3b205c12199ffa320622b4d0 | c5c013e43978b084852f2fe286d07ff371d67e6a | refs/heads/main | 2022-12-24T06:36:01.403357 | 2020-10-11T09:21:50 | 2020-10-11T09:21:50 | 303,070,434 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 406 | cpp | #include<iostream>
using namespace std;
time() {
for(int k=0;k<89999900;k++) {
k++;
k--;
}
}
int main() {
int n=5;
int i,j,k;
cout<<"\t ";
for(i=0;i<n-3;i++) {
time();
cout<<" * ";
}
cout<<endl;
for(i=0;i<n;i++) {
time();
cout<<"\t*";
for(j=0;j<n+2;j++) {
cout<<" ";
}
time();
cout<<"*";
cout<<endl;
}
cout<<"\t ";
for(i=0;i<n-3;i++) {
time();
cout<<" * ";
}
}
| [
"rohithrajbaggam@gmail.com"
] | rohithrajbaggam@gmail.com |
fed751de07ff0f656e894403f7c7b4421b44e5a3 | 13a1091034461938ca5a3872b93a90a03c08e0b2 | /Engine/Source/Shared/System/Renderer/RsRenderState.cpp | bed956f8c5e3933d1f20ef17081c21a53c187bd8 | [
"LicenseRef-scancode-public-domain",
"Zlib",
"MIT",
"BSD-3-Clause"
] | permissive | Kimau/Psybrus | 48bcd404a65e69a32bb5f8b2d1dce4e495d38b78 | c9cd7ce4f1aa1e3b9a0fc4f32942e05a95291202 | refs/heads/develop | 2020-05-20T22:25:28.289005 | 2015-12-14T02:19:23 | 2015-12-14T02:19:23 | 47,588,608 | 0 | 0 | null | 2015-12-08T00:41:38 | 2015-12-08T00:41:37 | null | UTF-8 | C++ | false | false | 8,560 | cpp | /**************************************************************************
*
* File: RsRenderState.cpp
* Author: Neil Richardson
* Ver/Date:
* Description:
* Render state creation and management.
*
*
*
*
**************************************************************************/
#include "System/Renderer/RsRenderState.h"
#include <type_traits>
//////////////////////////////////////////////////////////////////////////
// Assertions.
#if !PLATFORM_ANDROID
static_assert( std::is_trivially_copyable< RsRenderTargetBlendState >::value, "Unable to trivially copy RsRenderTargetBlendState" );
static_assert( std::is_trivially_copyable< RsBlendState >::value, "Unable to trivially copy RsBlendState" );
static_assert( std::is_trivially_copyable< RsStencilFaceState >::value, "Unable to trivially copy RsStencilFaceState" );
static_assert( std::is_trivially_copyable< RsStencilFaceState >::value, "Unable to trivially copy RsStencilFaceState" );
static_assert( std::is_trivially_copyable< RsDepthStencilState >::value, "Unable to trivially copy RsDepthStencilState" );
static_assert( std::is_trivially_copyable< RsRasteriserState >::value, "Unable to trivially copy RsRasteriserState" );
static_assert( std::is_trivially_copyable< RsRenderStateDesc >::value, "Unable to trivially copy RsRenderStateDesc" );
#endif
//////////////////////////////////////////////////////////////////////////
// RsRenderTargetBlendState
REFLECTION_DEFINE_BASIC( RsRenderTargetBlendState );
void RsRenderTargetBlendState::StaticRegisterClass()
{
ReField* Fields[] =
{
new ReField( "Enable_", &RsRenderTargetBlendState::Enable_ ),
new ReField( "SrcBlend_", &RsRenderTargetBlendState::SrcBlend_ ),
new ReField( "DestBlend_", &RsRenderTargetBlendState::DestBlend_ ),
new ReField( "BlendOp_", &RsRenderTargetBlendState::BlendOp_ ),
new ReField( "SrcBlendAlpha_", &RsRenderTargetBlendState::SrcBlendAlpha_ ),
new ReField( "DestBlendAlpha_", &RsRenderTargetBlendState::DestBlendAlpha_ ),
new ReField( "BlendOpAlpha_", &RsRenderTargetBlendState::BlendOpAlpha_ ),
new ReField( "WriteMask_", &RsRenderTargetBlendState::WriteMask_ ),
};
ReRegisterClass< RsRenderTargetBlendState >( Fields );
}
RsRenderTargetBlendState::RsRenderTargetBlendState( ReNoInit ):
Enable_( BcFalse ),
SrcBlend_( RsBlendType::ONE ),
DestBlend_( RsBlendType::ONE ),
BlendOp_( RsBlendOp::ADD ),
SrcBlendAlpha_( RsBlendType::ONE ),
DestBlendAlpha_( RsBlendType::ONE ),
BlendOpAlpha_( RsBlendOp::ADD ),
WriteMask_( 0xf )
{
}
RsRenderTargetBlendState::RsRenderTargetBlendState():
Enable_( BcFalse ),
SrcBlend_( RsBlendType::ONE ),
DestBlend_( RsBlendType::ONE ),
BlendOp_( RsBlendOp::ADD ),
SrcBlendAlpha_( RsBlendType::ONE ),
DestBlendAlpha_( RsBlendType::ONE ),
BlendOpAlpha_( RsBlendOp::ADD ),
WriteMask_( 0xf )
{
}
//////////////////////////////////////////////////////////////////////////
// RsBlendState
REFLECTION_DEFINE_BASIC( RsBlendState );
void RsBlendState::StaticRegisterClass()
{
ReField* Fields[] =
{
new ReField( "RenderTarget_", &RsBlendState::RenderTarget_ ),
};
ReRegisterClass< RsBlendState >( Fields );
}
RsBlendState::RsBlendState( ReNoInit ):
RenderTarget_()
{
}
RsBlendState::RsBlendState():
RenderTarget_()
{
}
//////////////////////////////////////////////////////////////////////////
// RsStencilFaceState
REFLECTION_DEFINE_BASIC( RsStencilFaceState );
void RsStencilFaceState::StaticRegisterClass()
{
ReField* Fields[] =
{
new ReField( "Fail_", &RsStencilFaceState::Fail_ ),
new ReField( "DepthFail_", &RsStencilFaceState::DepthFail_ ),
new ReField( "Pass_", &RsStencilFaceState::Pass_ ),
new ReField( "Func_", &RsStencilFaceState::Func_ ),
new ReField( "Mask_", &RsStencilFaceState::Mask_ ),
};
ReRegisterClass< RsStencilFaceState >( Fields );
}
RsStencilFaceState::RsStencilFaceState( ReNoInit ):
Fail_( RsStencilOp::KEEP ),
DepthFail_( RsStencilOp::KEEP ),
Pass_( RsStencilOp::KEEP ),
Func_( RsCompareMode::ALWAYS ),
Mask_( 0 )
{
}
RsStencilFaceState::RsStencilFaceState():
Fail_( RsStencilOp::KEEP ),
DepthFail_( RsStencilOp::KEEP ),
Pass_( RsStencilOp::KEEP ),
Func_( RsCompareMode::ALWAYS ),
Mask_( 0 )
{
}
//////////////////////////////////////////////////////////////////////////
// RsDepthStencilState
REFLECTION_DEFINE_BASIC( RsDepthStencilState );
void RsDepthStencilState::StaticRegisterClass()
{
ReField* Fields[] =
{
new ReField( "DepthTestEnable_", &RsDepthStencilState::DepthTestEnable_ ),
new ReField( "DepthWriteEnable_", &RsDepthStencilState::DepthWriteEnable_ ),
new ReField( "DepthFunc_", &RsDepthStencilState::DepthFunc_ ),
new ReField( "StencilEnable_", &RsDepthStencilState::StencilEnable_ ),
new ReField( "StencilRead_", &RsDepthStencilState::StencilRead_ ),
new ReField( "StencilWrite_", &RsDepthStencilState::StencilWrite_ ),
new ReField( "StencilFront_", &RsDepthStencilState::StencilFront_ ),
new ReField( "StencilBack_", &RsDepthStencilState::StencilBack_ ),
new ReField( "StencilRef_", &RsDepthStencilState::StencilRef_ ),
};
ReRegisterClass< RsDepthStencilState >( Fields );
}
RsDepthStencilState::RsDepthStencilState( ReNoInit ):
DepthTestEnable_( BcFalse ),
DepthWriteEnable_( BcFalse ),
DepthFunc_( RsCompareMode::LESS ),
StencilEnable_( BcFalse ),
StencilFront_(),
StencilBack_(),
StencilRef_( 0x0 ),
StencilRead_( 0x0 ),
StencilWrite_( 0x0 ),
Padding_( 0 )
{
}
RsDepthStencilState::RsDepthStencilState():
DepthTestEnable_( BcFalse ),
DepthWriteEnable_( BcFalse ),
DepthFunc_( RsCompareMode::LESS ),
StencilEnable_( BcFalse ),
StencilFront_(),
StencilBack_(),
StencilRef_( 0 ),
StencilRead_( 0x0 ),
StencilWrite_( 0x0 ),
Padding_( 0 )
{
}
//////////////////////////////////////////////////////////////////////////
// RsRasteriserState
REFLECTION_DEFINE_BASIC( RsRasteriserState );
void RsRasteriserState::StaticRegisterClass()
{
ReField* Fields[] =
{
new ReField( "FillMode_", &RsRasteriserState::FillMode_ ),
new ReField( "CullMode_", &RsRasteriserState::CullMode_ ),
new ReField( "DepthBias_", &RsRasteriserState::DepthBias_ ),
new ReField( "SlopeScaledDepthBias_", &RsRasteriserState::SlopeScaledDepthBias_ ),
new ReField( "DepthClipEnable_", &RsRasteriserState::DepthClipEnable_ ),
new ReField( "ScissorEnable_", &RsRasteriserState::ScissorEnable_ ),
new ReField( "AntialiasedLineEnable_", &RsRasteriserState::AntialiasedLineEnable_ ),
};
ReRegisterClass< RsRasteriserState >( Fields );
}
RsRasteriserState::RsRasteriserState( ReNoInit ):
FillMode_( RsFillMode::SOLID ),
CullMode_( RsCullMode::NONE ),
DepthBias_( 0.0f ),
SlopeScaledDepthBias_( 0.0f ),
DepthClipEnable_( BcTrue ),
ScissorEnable_( BcFalse ),
AntialiasedLineEnable_( BcTrue )
{
}
RsRasteriserState::RsRasteriserState():
FillMode_( RsFillMode::SOLID ),
CullMode_( RsCullMode::NONE ),
DepthBias_( 0.0f ),
SlopeScaledDepthBias_( 0.0f ),
DepthClipEnable_( BcTrue ),
ScissorEnable_( BcFalse ),
AntialiasedLineEnable_( BcTrue )
{
}
//////////////////////////////////////////////////////////////////////////
// RsRenderStateDesc
REFLECTION_DEFINE_BASIC( RsRenderStateDesc );
void RsRenderStateDesc::StaticRegisterClass()
{
ReField* Fields[] =
{
new ReField( "BlendState_", &RsRenderStateDesc::BlendState_ ),
new ReField( "DepthStencilState_", &RsRenderStateDesc::DepthStencilState_ ),
new ReField( "RasteriserState_", &RsRenderStateDesc::RasteriserState_ ),
};
ReRegisterClass< RsRenderStateDesc >( Fields );
}
RsRenderStateDesc::RsRenderStateDesc( ReNoInit ):
BlendState_( NOINIT ),
DepthStencilState_( NOINIT ),
RasteriserState_( NOINIT )
{
}
RsRenderStateDesc::RsRenderStateDesc():
BlendState_(),
DepthStencilState_(),
RasteriserState_()
{
}
RsRenderStateDesc::RsRenderStateDesc(
const RsBlendState& BlendState,
const RsDepthStencilState& DepthStencilState,
const RsRasteriserState& RasteriserState ):
BlendState_( BlendState ),
DepthStencilState_( DepthStencilState ),
RasteriserState_( RasteriserState )
{
}
//////////////////////////////////////////////////////////////////////////
// Ctor
RsRenderState::RsRenderState( class RsContext* pContext, const RsRenderStateDesc& Desc ):
RsResource( RsResourceType::RENDER_STATE, pContext ),
Desc_( Desc )
{
}
//////////////////////////////////////////////////////////////////////////
// Dtor
//virtual
RsRenderState::~RsRenderState()
{
}
//////////////////////////////////////////////////////////////////////////
// getDesc
const RsRenderStateDesc& RsRenderState::getDesc() const
{
return Desc_;
}
| [
"neilo@neilo.gd"
] | neilo@neilo.gd |
383e6a3c2657a45b08d7112b8b779a9345a8b32c | 140d78334109e02590f04769ec154180b2eaf78d | /aws-cpp-sdk-clouddirectory/source/model/BatchListIndexResponse.cpp | 88d306ba28a7b9240a5df81b9122712bef72e3ad | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | coderTong/aws-sdk-cpp | da140feb7e5495366a8d2a6a02cf8b28ba820ff6 | 5cd0c0a03b667c5a0bd17394924abe73d4b3754a | refs/heads/master | 2021-07-08T07:04:40.181622 | 2017-08-22T21:50:00 | 2017-08-22T21:50:00 | 101,145,374 | 0 | 1 | Apache-2.0 | 2021-05-04T21:06:36 | 2017-08-23T06:24:37 | C++ | UTF-8 | C++ | false | false | 2,514 | cpp | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/clouddirectory/model/BatchListIndexResponse.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace CloudDirectory
{
namespace Model
{
BatchListIndexResponse::BatchListIndexResponse() :
m_indexAttachmentsHasBeenSet(false),
m_nextTokenHasBeenSet(false)
{
}
BatchListIndexResponse::BatchListIndexResponse(const JsonValue& jsonValue) :
m_indexAttachmentsHasBeenSet(false),
m_nextTokenHasBeenSet(false)
{
*this = jsonValue;
}
BatchListIndexResponse& BatchListIndexResponse::operator =(const JsonValue& jsonValue)
{
if(jsonValue.ValueExists("IndexAttachments"))
{
Array<JsonValue> indexAttachmentsJsonList = jsonValue.GetArray("IndexAttachments");
for(unsigned indexAttachmentsIndex = 0; indexAttachmentsIndex < indexAttachmentsJsonList.GetLength(); ++indexAttachmentsIndex)
{
m_indexAttachments.push_back(indexAttachmentsJsonList[indexAttachmentsIndex].AsObject());
}
m_indexAttachmentsHasBeenSet = true;
}
if(jsonValue.ValueExists("NextToken"))
{
m_nextToken = jsonValue.GetString("NextToken");
m_nextTokenHasBeenSet = true;
}
return *this;
}
JsonValue BatchListIndexResponse::Jsonize() const
{
JsonValue payload;
if(m_indexAttachmentsHasBeenSet)
{
Array<JsonValue> indexAttachmentsJsonList(m_indexAttachments.size());
for(unsigned indexAttachmentsIndex = 0; indexAttachmentsIndex < indexAttachmentsJsonList.GetLength(); ++indexAttachmentsIndex)
{
indexAttachmentsJsonList[indexAttachmentsIndex].AsObject(m_indexAttachments[indexAttachmentsIndex].Jsonize());
}
payload.WithArray("IndexAttachments", std::move(indexAttachmentsJsonList));
}
if(m_nextTokenHasBeenSet)
{
payload.WithString("NextToken", m_nextToken);
}
return payload;
}
} // namespace Model
} // namespace CloudDirectory
} // namespace Aws | [
"henso@amazon.com"
] | henso@amazon.com |
f717ce0f40623c0cb110dfe07f166ea3a06858fb | f2e1ef881c5835fce122f8076f484c0475bff9df | /src/LuminoEngine/src/Font/TextLayoutEngine.cpp | d938521ba6ab8b821a72e00eb403bbd91e9c69ce | [
"MIT"
] | permissive | lp249839965/Lumino | def5d41f32d4a3f3c87966719fd5ded954b348cc | 94b1919f1579610fc6034c371cf96e7e8517c5e9 | refs/heads/master | 2023-02-13T09:33:22.868358 | 2020-12-22T15:30:55 | 2020-12-22T15:30:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,318 | cpp |
#include "Internal.hpp"
#include <LuminoEngine/Graphics/Bitmap.hpp>
#include <LuminoEngine/Font/Font.hpp>
#include "../../LuminoCore/src/Text/UnicodeUtils.hpp"
#include "TextLayoutEngine.hpp"
namespace ln {
namespace detail {
//==============================================================================
// TextLayoutEngine
TextLayoutEngine::TextLayoutEngine()
: m_font(nullptr)
, m_text(nullptr)
, m_length(0)
, m_pos(0)
, m_targetArea()
, m_alignment(TextAlignment::Forward)
, m_globalMetrics()
{
}
void TextLayoutEngine::layout(FontCore* font, const Char* text, size_t length, const Rect& targetArea, float strokeSize, TextAlignment alignment)
{
if (LN_REQUIRE(font)) return;
if (LN_REQUIRE(text)) return;
if (length == 0) return;
m_font = font;
m_text = text;
m_length = length;
m_pos = 0;
m_targetArea = targetArea;
m_strokeSize = strokeSize;
m_alignment = alignment;
m_layoutLines.clear();
m_font->getGlobalMetrics(&m_globalMetrics);
m_renderAreaSize = Size::Zero;
resetStream();
layoutTextHorizontal(LayoutMode::Measure);
placementTextHorizontal();
}
// "\r\n" => '\n'
UTF32 TextLayoutEngine::readChar()
{
if (m_pos >= m_length) {
return 0; // EOF
}
auto str = (const UTF16*)m_text;
const UTF16* begin = str + m_pos;
const UTF16* end = str + m_length;
if (begin[0] == '\r' && (begin < end - 1 && begin[1] == '\n')) {
m_pos += 2;
return '\n';
}
UTF32 ch = 0;
UTFConversionOptions options;
options.ReplacementChar = '?';
const UTF16* ps = begin;
UnicodeUtils::convertCharUTF16toUTF32(&ps, end, &options, &ch);
m_pos += (ps - begin);
return ch;
}
void TextLayoutEngine::resetStream()
{
m_pos = 0;
}
//void TextLayoutEngine::onMeasureGlyph(UTF32 ch, const Vector2& pos, const FontGlyphMetrics& metrix, Size* outSizeOffset)
//{
//}
void TextLayoutEngine::layoutTextHorizontal(LayoutMode mode)
{
float baselineY = m_globalMetrics.ascender;
while (layoutLineHorizontal(baselineY, mode))
{
baselineY += m_globalMetrics.lineSpace;
}
}
bool TextLayoutEngine::layoutLineHorizontal(float baselineY, LayoutMode mode)
{
LayoutLine layoutLine;
UTF32 prev = 0;
Vector2 pos;// (0, baselineY - m_globalMetrics.ascender);
//pos.x = m_renderAreaOffset.x;
while (UTF32 ch = readChar())
{
if (ch == '\r' || ch == '\n') {
return true; // end with newline
}
if (prev)
{
Vector2 delta = m_font->getKerning(prev, ch);
pos.x += delta.x;
}
FontGlyphMetrics metrics;
m_font->getGlyphMetrics(ch, &metrics);
pos.y = /*m_renderAreaOffset.y + */(baselineY - metrics.bearingY);
pos.x += metrics.bearingX;
//if (mode == LayoutMode::Measure) {
m_renderAreaSize.width = std::max(m_renderAreaSize.width, (pos.x + m_strokeSize * 2) + metrics.size.width);
m_renderAreaSize.height = std::max(m_renderAreaSize.height, (pos.y + m_strokeSize * 2) + metrics.size.height);
layoutLine.glyphs.add({ ch, pos, metrics.size });
//}
//else {
// onPlacementGlyph(ch, pos, metrics);
//}
pos.x += metrics.advance.x + (m_strokeSize * 2);
prev = ch;
}
//if (mode == LayoutMode::Measure) {
m_layoutLines.add(std::move(layoutLine));
//}
return false; // end with EOF or Error
}
void TextLayoutEngine::placementTextHorizontal()
{
for (auto& layoutLine : m_layoutLines) {
calculateRenderAreaHorizontalOffset(&layoutLine);
placementLineHorizontal(layoutLine);
}
}
void TextLayoutEngine::placementLineHorizontal(const LayoutLine& layoutLine)
{
for (auto& glyph : layoutLine.glyphs) {
onPlacementGlyph(glyph.ch, glyph.pos + m_renderAreaOffset, glyph.size);
}
}
void TextLayoutEngine::calculateRenderAreaHorizontalOffset(LayoutLine* layoutLine)
{
TextAlignment alignment = m_alignment;
if (alignment == TextAlignment::Justify) {
if (layoutLine->glyphs.size() == 0) {
alignment = TextAlignment::Forward;
}
else if (layoutLine->glyphs.size() == 1) {
alignment = TextAlignment::Center;
}
}
switch (alignment)
{
case TextAlignment::Forward:
m_renderAreaOffset.x = 0;
break;
case TextAlignment::Center:
m_renderAreaOffset.x = (m_targetArea.width - m_renderAreaSize.width) / 2;
break;
case TextAlignment::Backward:
m_renderAreaOffset.x = m_targetArea.width - m_renderAreaSize.width;
break;
case TextAlignment::Justify:
{
// "A B C" などの時の空白数
int blank = layoutLine->glyphs.size() - 1;
// 余りの空白量
float remain = m_targetArea.width - m_renderAreaSize.width;
float sw = remain / blank;
for (int i = 1; i < layoutLine->glyphs.size() - 1; i++) {
layoutLine->glyphs[i].pos.x += sw * i;
}
// 最後の一つは右詰 (加算誤差で微妙に見切れないようにする)
layoutLine->glyphs.back().pos.x = m_targetArea.width - layoutLine->glyphs.back().size.width;
break;
}
}
}
//==============================================================================
// MeasureTextLayoutEngine
void MeasureTextLayoutEngine::onPlacementGlyph(UTF32 ch, const Vector2& pos, const Size& size)
{
areaSize.width = std::max(areaSize.width, pos.x + size.width);
areaSize.height = std::max(areaSize.height, pos.y + size.height);
}
//==============================================================================
// BitmapTextRenderer
void BitmapTextRenderer::render(Bitmap2D* bitmap, const StringRef& text, const Rect& rect, Font* font, const Color& color, TextAlignment alignment)
{
m_bitmap = bitmap;
m_rect = rect;
m_color = color;
m_font = FontHelper::resolveFontCore(font, 1.0f);
layout(m_font, text.data(), text.length(), rect, 0, alignment);
}
void BitmapTextRenderer::onPlacementGlyph(UTF32 ch, const Vector2& pos, const Size& size)
{
BitmapGlyphInfo info;
info.glyphBitmap = nullptr; // 内部ビットマップをもらう
m_font->lookupGlyphBitmap(ch, &info);
m_bitmap->blit(
RectI(m_rect.x + pos.x, m_rect.y + pos.y, info.size),
info.glyphBitmap,
RectI(0, 0, info.size),
ColorI::fromLinearColor(m_color), BitmapBlitOptions::AlphaBlend);
}
} // namespace detail
} // namespace ln
| [
"lriki.net@gmail.com"
] | lriki.net@gmail.com |
c51e96f4335c707e902adde298195b5cfbb7d581 | 6765928eced9da30e7af8f47a254a0925342cfe9 | /交换最大数最小数位置.cpp | 678119e50216a10bd69ab5116e0c9161502ed93d | [] | no_license | Zzzhouxiaochen/Zzzhouxiaochen | f3304c955b89c1c6afb17767be6c2fddc8ae7660 | e2195d3ac869a90df1f815202204c175babfa032 | refs/heads/master | 2020-04-12T18:43:57.259437 | 2019-05-20T01:17:24 | 2019-05-20T01:17:24 | 162,688,924 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 774 | cpp | #define _CRT_SECURE_NO_WARNINGS
#include<stdlib.h>
#include<stdio.h>
int main()
{
int a[20], max, min, i, j=0, k=0, n;
printf("请输入数据个数:\n");
scanf("%d", &n);
printf("请输入数据:\n");
for ( i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
min = a[0]; //求最小数
for (i = 1; i < n; i++)
{
if (a[i] < min)
{
min = a[i];
j = i;
}
}
max = a[0]; //求最大数
for (i = 1; i < n; i++)
{
if (a[i] > max)
{
max = a[i];
k = i;
}
}
a[k] = min; //最大数位置放最小数
a[j] = max; //最小数放最大数
printf("最小数位置是%d。\n", j);
printf("最大数位置是%d。\n", k);
printf("现在数据为:\n");
for ( i = 0; i < n; i++)
{
printf("%5d", a[i]);
}
system("pause");
return 0;
} | [
"zxc2890326540@163.com"
] | zxc2890326540@163.com |
69dc71bf6d8d2609b6b70da6a6d0dc8a5d1c6bd1 | 2d6a8a21cf01d13c552b82d043561c5c5eb09bbc | /students/kondrat'ev_a/lr_3/lr_3.h | 11a80b2fa1232befff4ff5ba47cd8405c17046e6 | [] | no_license | leti-fkti-1381/2013-1381-sem-4 | 1fd42b812ab3e34ff7e49915099111c32715a422 | b40e5985841b73f0661161e71911a590b8801fce | refs/heads/master | 2016-09-11T04:55:28.208734 | 2013-06-11T19:11:53 | 2013-06-11T19:11:53 | 8,007,891 | 0 | 2 | null | 2013-02-04T14:47:36 | 2013-02-04T13:39:58 | null | WINDOWS-1251 | C++ | false | false | 2,208 | h | #ifndef _lr_3_
#define _lr_3_
#include <vector>
#include <limits>
using namespace std;
//---------------------------------------------------------------
const int max_amount = 100; // Максимальное количество элементов
const int max_value = 100; // Максимальное значение элемента
//---------------------------------------------------------------
int Solution (vector <int>, int); // Функция нахождения решения
void MinSolution (vector <int>, int, int, int&); // Рекурсивная Функция нахождения минимального решения
//---------------------------------------------------------------
// Функция нахождения решения
int Solution (vector <int> arr , int amount_arr)
{
// Проверка введенных данных
if (!(amount_arr > 1 && amount_arr <= max_amount))
return -1;
for (int i = 0; i < arr.size(); i++)
if (arr[i] > max_value)
return -1;
int solution = numeric_limits<int>::max(); // Максимальное значение типа int;
MinSolution (arr, amount_arr, 0, solution); // Нахождение решения
return solution;
}
//---------------------------------------------------------------
// Рекурсивная Функция нахождения минимального решения
void MinSolution (vector <int> arr, int amount_arr, int curr, int& solution)
{
int step = 0; // Цена шага
for (int i = 1; i < amount_arr-1; i++)
{
// Вычисление стоимости шага
step = (arr[i-1]+arr[i+1])*arr[i];
// Проверка на продолжение выполнения
if (curr+step <= solution)
{
int erase_elem = arr[i]; // Удаляемый элемент
arr.erase(arr.begin()+i); // Удаление
MinSolution (arr, amount_arr-1, curr+step, solution);
arr.insert(arr.begin()+i, erase_elem); // Востановление удаленного элемента
}
}
// Сравнение полученного результата с текущим решением
if (amount_arr == 2 && curr < solution)
{
solution = curr;
}
}
#endif | [
"alskondr@yandex.ru"
] | alskondr@yandex.ru |
1d4665d14eacdc143533764177fe5ef33cd1463b | e2f184fd6489d0ff2573179919d1cda308b42382 | /Add_by_two.cpp | b6e86391cb75a7bafac2a80c4bc2ef039e51d312 | [] | no_license | Haeun-Oh/Programmers | 35c881cc5b3b3c5e12fa1df9bce90dec4df70794 | e071d10f69d09db54c193391258027fd47abebdd | refs/heads/main | 2023-06-08T08:26:03.605916 | 2021-06-30T15:03:12 | 2021-06-30T15:03:12 | 323,313,624 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 441 | cpp | #include <string>
#include <vector>
#include <algorithm>
#include <set>
using namespace std;
vector<int> solution(vector<int> numbers) {
set<int>s;
set<int>::iterator iter;
vector<int>vec;
for(int i=0;i<numbers.size()-1;i++){
for (int j=i+1;j<numbers.size();j++)
s.insert(numbers[i]+numbers[j]);
}
for (iter = s.begin(); iter!=s.end();iter++){
vec.push_back(*iter);
}
return vec;
}
| [
"noreply@github.com"
] | noreply@github.com |
4e82bfc47c304a5b3104f98045929f30a3083198 | 8f680f6a7f1bf550ad39bcfa37f613dd57062f55 | /src/basics/perfect_forwarding/integer.hpp | 47c4399d8853e83701f0b08d234ec0bf15d2b2bc | [] | no_license | Hdbcoding/cpp_scratchpad | 6cd85a816f7f1251b3ac6cd66479785cc8cf9151 | 230cdcbf544c68c392be51abd8e12112be6bd292 | refs/heads/master | 2023-03-07T03:34:45.012358 | 2021-02-21T17:34:06 | 2021-02-21T17:34:06 | 277,338,529 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 902 | hpp |
class integer
{
int *v;
public:
// rule of 3 -> { destructor, copy constructor, copy assignment operator }
// e.g., if you need custom implementation for one of those three, you need all three
// rule of 5 -> { destructor, copy constructor, copy assignment operator, move constructor, move assignment operator }
// same as rule of 3, just more to implement
// default constructor
integer();
// destructor
~integer();
// parameterized constructor
integer(int value);
// copy constructor - takes a const lvalue reference
integer(const integer &obj);
// move constructor - takes an rvalue reference
integer(integer &&obj);
// copy assignment operator
integer &operator=(const integer &a);
// move assignment operator
integer &operator=(integer &&a);
int getValue() const;
void setValue(int value);
}; | [
"henry.byrd@claricode.com"
] | henry.byrd@claricode.com |
fd7f7542ff1a35983a3c989b00063c50b3adb109 | 299648a8c633728662d0b7651cd98afdc28db902 | /src/thirdparty/sentry-native/external/crashpad/snapshot/linux/process_reader_linux_test.cc | 73e350dbf8d1c2981e65106262cb1e6860950373 | [
"Apache-2.0",
"MIT",
"BSD-3-Clause"
] | permissive | aardvarkxr/aardvark | 2978277b34c2c3894d6aafc4c590f3bda50f4d43 | 300d0d5e9b872ed839fae932c56eff566967d24b | refs/heads/master | 2023-01-12T18:42:10.705028 | 2021-08-18T04:09:02 | 2021-08-18T04:09:02 | 182,431,653 | 183 | 25 | BSD-3-Clause | 2023-01-07T12:42:14 | 2019-04-20T16:55:30 | TypeScript | UTF-8 | C++ | false | false | 27,451 | cc | // Copyright 2017 The Crashpad Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "snapshot/linux/process_reader_linux.h"
#include <dlfcn.h>
#include <elf.h>
#include <errno.h>
#include <link.h>
#include <pthread.h>
#include <sched.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/resource.h>
#include <sys/syscall.h>
#include <unistd.h>
#include <map>
#include <memory>
#include <string>
#include <utility>
#include "base/format_macros.h"
#include "base/memory/free_deleter.h"
#include "base/stl_util.h"
#include "base/strings/stringprintf.h"
#include "build/build_config.h"
#include "gtest/gtest.h"
#include "test/errors.h"
#include "test/linux/fake_ptrace_connection.h"
#include "test/linux/get_tls.h"
#include "test/multiprocess.h"
#include "test/scoped_module_handle.h"
#include "test/test_paths.h"
#include "util/file/file_io.h"
#include "util/file/file_writer.h"
#include "util/file/filesystem.h"
#include "util/linux/direct_ptrace_connection.h"
#include "util/misc/address_sanitizer.h"
#include "util/misc/from_pointer_cast.h"
#include "util/misc/memory_sanitizer.h"
#include "util/synchronization/semaphore.h"
#if defined(OS_ANDROID)
#include <android/api-level.h>
#include <android/set_abort_message.h>
#include "dlfcn_internal.h"
// Normally this comes from set_abort_message.h, but only at API level 21.
extern "C" void android_set_abort_message(const char* msg)
__attribute__((weak));
#endif
namespace crashpad {
namespace test {
namespace {
pid_t gettid() {
return syscall(SYS_gettid);
}
TEST(ProcessReaderLinux, SelfBasic) {
FakePtraceConnection connection;
connection.Initialize(getpid());
ProcessReaderLinux process_reader;
ASSERT_TRUE(process_reader.Initialize(&connection));
#if defined(ARCH_CPU_64_BITS)
EXPECT_TRUE(process_reader.Is64Bit());
#else
EXPECT_FALSE(process_reader.Is64Bit());
#endif
EXPECT_EQ(process_reader.ProcessID(), getpid());
EXPECT_EQ(process_reader.ParentProcessID(), getppid());
static constexpr char kTestMemory[] = "Some test memory";
char buffer[base::size(kTestMemory)];
ASSERT_TRUE(process_reader.Memory()->Read(
reinterpret_cast<LinuxVMAddress>(kTestMemory),
sizeof(kTestMemory),
&buffer));
EXPECT_STREQ(kTestMemory, buffer);
EXPECT_EQ("", process_reader.AbortMessage());
}
constexpr char kTestMemory[] = "Read me from another process";
class BasicChildTest : public Multiprocess {
public:
BasicChildTest() : Multiprocess() {}
~BasicChildTest() {}
private:
void MultiprocessParent() override {
DirectPtraceConnection connection;
ASSERT_TRUE(connection.Initialize(ChildPID()));
ProcessReaderLinux process_reader;
ASSERT_TRUE(process_reader.Initialize(&connection));
#if !defined(ARCH_CPU_64_BITS)
EXPECT_FALSE(process_reader.Is64Bit());
#else
EXPECT_TRUE(process_reader.Is64Bit());
#endif
EXPECT_EQ(process_reader.ParentProcessID(), getpid());
EXPECT_EQ(process_reader.ProcessID(), ChildPID());
std::string read_string;
ASSERT_TRUE(process_reader.Memory()->ReadCString(
reinterpret_cast<LinuxVMAddress>(kTestMemory), &read_string));
EXPECT_EQ(read_string, kTestMemory);
}
void MultiprocessChild() override { CheckedReadFileAtEOF(ReadPipeHandle()); }
DISALLOW_COPY_AND_ASSIGN(BasicChildTest);
};
TEST(ProcessReaderLinux, ChildBasic) {
BasicChildTest test;
test.Run();
}
class TestThreadPool {
public:
struct ThreadExpectation {
LinuxVMAddress tls = 0;
LinuxVMAddress stack_address = 0;
LinuxVMSize max_stack_size = 0;
int sched_policy = 0;
int static_priority = 0;
int nice_value = 0;
};
TestThreadPool() : threads_() {}
~TestThreadPool() {
for (const auto& thread : threads_) {
thread->exit_semaphore.Signal();
}
for (const auto& thread : threads_) {
EXPECT_EQ(pthread_join(thread->pthread, nullptr), 0)
<< ErrnoMessage("pthread_join");
}
}
void StartThreads(size_t thread_count, size_t stack_size = 0) {
for (size_t thread_index = 0; thread_index < thread_count; ++thread_index) {
threads_.push_back(std::make_unique<Thread>());
Thread* thread = threads_.back().get();
pthread_attr_t attr;
ASSERT_EQ(pthread_attr_init(&attr), 0)
<< ErrnoMessage("pthread_attr_init");
if (stack_size > 0) {
void* stack_ptr;
errno = posix_memalign(&stack_ptr, getpagesize(), stack_size);
ASSERT_EQ(errno, 0) << ErrnoMessage("posix_memalign");
thread->stack.reset(reinterpret_cast<char*>(stack_ptr));
ASSERT_EQ(pthread_attr_setstack(&attr, thread->stack.get(), stack_size),
0)
<< ErrnoMessage("pthread_attr_setstack");
thread->expectation.max_stack_size = stack_size;
}
ASSERT_EQ(pthread_attr_setschedpolicy(&attr, SCHED_OTHER), 0)
<< ErrnoMessage("pthread_attr_setschedpolicy");
thread->expectation.sched_policy = SCHED_OTHER;
sched_param param;
param.sched_priority = 0;
ASSERT_EQ(pthread_attr_setschedparam(&attr, ¶m), 0)
<< ErrnoMessage("pthread_attr_setschedparam");
thread->expectation.static_priority = 0;
thread->expectation.nice_value = thread_index % 20;
ASSERT_EQ(pthread_create(&thread->pthread, &attr, ThreadMain, thread), 0)
<< ErrnoMessage("pthread_create");
}
for (const auto& thread : threads_) {
thread->ready_semaphore.Wait();
}
}
pid_t GetThreadExpectation(size_t thread_index,
ThreadExpectation* expectation) {
CHECK_LT(thread_index, threads_.size());
const Thread* thread = threads_[thread_index].get();
*expectation = thread->expectation;
return thread->tid;
}
private:
struct Thread {
Thread()
: pthread(),
expectation(),
ready_semaphore(0),
exit_semaphore(0),
tid(-1) {}
~Thread() {}
pthread_t pthread;
ThreadExpectation expectation;
std::unique_ptr<char[], base::FreeDeleter> stack;
Semaphore ready_semaphore;
Semaphore exit_semaphore;
pid_t tid;
};
static void* ThreadMain(void* argument) {
Thread* thread = static_cast<Thread*>(argument);
CHECK_EQ(setpriority(PRIO_PROCESS, 0, thread->expectation.nice_value), 0)
<< ErrnoMessage("setpriority");
thread->expectation.tls = GetTLS();
thread->expectation.stack_address =
reinterpret_cast<LinuxVMAddress>(&thread);
thread->tid = gettid();
thread->ready_semaphore.Signal();
thread->exit_semaphore.Wait();
CHECK_EQ(pthread_self(), thread->pthread);
return nullptr;
}
std::vector<std::unique_ptr<Thread>> threads_;
DISALLOW_COPY_AND_ASSIGN(TestThreadPool);
};
using ThreadMap = std::map<pid_t, TestThreadPool::ThreadExpectation>;
void ExpectThreads(const ThreadMap& thread_map,
const std::vector<ProcessReaderLinux::Thread>& threads,
PtraceConnection* connection) {
ASSERT_EQ(threads.size(), thread_map.size());
MemoryMap memory_map;
ASSERT_TRUE(memory_map.Initialize(connection));
for (const auto& thread : threads) {
SCOPED_TRACE(
base::StringPrintf("Thread id %d, tls 0x%" PRIx64
", stack addr 0x%" PRIx64 ", stack size 0x%" PRIx64,
thread.tid,
thread.thread_info.thread_specific_data_address,
thread.stack_region_address,
thread.stack_region_size));
const auto& iterator = thread_map.find(thread.tid);
ASSERT_NE(iterator, thread_map.end());
EXPECT_EQ(thread.thread_info.thread_specific_data_address,
iterator->second.tls);
ASSERT_TRUE(memory_map.FindMapping(thread.stack_region_address));
ASSERT_TRUE(memory_map.FindMapping(thread.stack_region_address +
thread.stack_region_size - 1));
#if !defined(ADDRESS_SANITIZER)
// AddressSanitizer causes stack variables to be stored separately from the
// call stack.
EXPECT_LE(thread.stack_region_address, iterator->second.stack_address);
EXPECT_GE(thread.stack_region_address + thread.stack_region_size,
iterator->second.stack_address);
#endif // !defined(ADDRESS_SANITIZER)
if (iterator->second.max_stack_size) {
EXPECT_LT(thread.stack_region_size, iterator->second.max_stack_size);
}
EXPECT_EQ(thread.sched_policy, iterator->second.sched_policy);
EXPECT_EQ(thread.static_priority, iterator->second.static_priority);
EXPECT_EQ(thread.nice_value, iterator->second.nice_value);
}
}
class ChildThreadTest : public Multiprocess {
public:
ChildThreadTest(size_t stack_size = 0)
: Multiprocess(), stack_size_(stack_size) {}
~ChildThreadTest() {}
private:
void MultiprocessParent() override {
ThreadMap thread_map;
for (size_t thread_index = 0; thread_index < kThreadCount + 1;
++thread_index) {
pid_t tid;
TestThreadPool::ThreadExpectation expectation;
CheckedReadFileExactly(ReadPipeHandle(), &tid, sizeof(tid));
CheckedReadFileExactly(
ReadPipeHandle(), &expectation, sizeof(expectation));
thread_map[tid] = expectation;
}
DirectPtraceConnection connection;
ASSERT_TRUE(connection.Initialize(ChildPID()));
ProcessReaderLinux process_reader;
ASSERT_TRUE(process_reader.Initialize(&connection));
const std::vector<ProcessReaderLinux::Thread>& threads =
process_reader.Threads();
ExpectThreads(thread_map, threads, &connection);
}
void MultiprocessChild() override {
TestThreadPool thread_pool;
thread_pool.StartThreads(kThreadCount, stack_size_);
TestThreadPool::ThreadExpectation expectation;
#if defined(MEMORY_SANITIZER)
// memset() + re-initialization is required to zero padding bytes for MSan.
memset(&expectation, 0, sizeof(expectation));
#endif // defined(MEMORY_SANITIZER)
expectation = {};
expectation.tls = GetTLS();
expectation.stack_address = reinterpret_cast<LinuxVMAddress>(&thread_pool);
int res = sched_getscheduler(0);
ASSERT_GE(res, 0) << ErrnoMessage("sched_getscheduler");
expectation.sched_policy = res;
sched_param param;
ASSERT_EQ(sched_getparam(0, ¶m), 0) << ErrnoMessage("sched_getparam");
expectation.static_priority = param.sched_priority;
errno = 0;
res = getpriority(PRIO_PROCESS, 0);
ASSERT_FALSE(res == -1 && errno) << ErrnoMessage("getpriority");
expectation.nice_value = res;
pid_t tid = gettid();
CheckedWriteFile(WritePipeHandle(), &tid, sizeof(tid));
CheckedWriteFile(WritePipeHandle(), &expectation, sizeof(expectation));
for (size_t thread_index = 0; thread_index < kThreadCount; ++thread_index) {
tid = thread_pool.GetThreadExpectation(thread_index, &expectation);
CheckedWriteFile(WritePipeHandle(), &tid, sizeof(tid));
CheckedWriteFile(WritePipeHandle(), &expectation, sizeof(expectation));
}
CheckedReadFileAtEOF(ReadPipeHandle());
}
static constexpr size_t kThreadCount = 3;
const size_t stack_size_;
DISALLOW_COPY_AND_ASSIGN(ChildThreadTest);
};
TEST(ProcessReaderLinux, ChildWithThreads) {
ChildThreadTest test;
test.Run();
}
TEST(ProcessReaderLinux, ChildThreadsWithSmallUserStacks) {
ChildThreadTest test(PTHREAD_STACK_MIN);
test.Run();
}
// Tests a thread with a stack that spans multiple mappings.
class ChildWithSplitStackTest : public Multiprocess {
public:
ChildWithSplitStackTest() : Multiprocess(), page_size_(getpagesize()) {}
~ChildWithSplitStackTest() {}
private:
void MultiprocessParent() override {
LinuxVMAddress stack_addr1;
LinuxVMAddress stack_addr2;
LinuxVMAddress stack_addr3;
CheckedReadFileExactly(ReadPipeHandle(), &stack_addr1, sizeof(stack_addr1));
CheckedReadFileExactly(ReadPipeHandle(), &stack_addr2, sizeof(stack_addr2));
CheckedReadFileExactly(ReadPipeHandle(), &stack_addr3, sizeof(stack_addr3));
DirectPtraceConnection connection;
ASSERT_TRUE(connection.Initialize(ChildPID()));
ProcessReaderLinux process_reader;
ASSERT_TRUE(process_reader.Initialize(&connection));
const std::vector<ProcessReaderLinux::Thread>& threads =
process_reader.Threads();
ASSERT_EQ(threads.size(), 1u);
LinuxVMAddress thread_stack_start = threads[0].stack_region_address;
EXPECT_LE(thread_stack_start, stack_addr1);
EXPECT_LE(thread_stack_start, stack_addr2);
EXPECT_LE(thread_stack_start, stack_addr3);
LinuxVMAddress thread_stack_end =
thread_stack_start + threads[0].stack_region_size;
EXPECT_GE(thread_stack_end, stack_addr1);
EXPECT_GE(thread_stack_end, stack_addr2);
EXPECT_GE(thread_stack_end, stack_addr3);
}
void MultiprocessChild() override {
const LinuxVMSize stack_size = page_size_ * 4;
GrowStack(stack_size, reinterpret_cast<LinuxVMAddress>(&stack_size));
}
void GrowStack(LinuxVMSize stack_size, LinuxVMAddress bottom_of_stack) {
char stack_contents[4096];
auto stack_address = reinterpret_cast<LinuxVMAddress>(&stack_contents);
if (bottom_of_stack - stack_address < stack_size) {
GrowStack(stack_size, bottom_of_stack);
} else {
// Write-protect a page on our stack to split up the mapping
LinuxVMAddress page_addr =
stack_address - (stack_address % page_size_) + 2 * page_size_;
ASSERT_EQ(
mprotect(reinterpret_cast<void*>(page_addr), page_size_, PROT_READ),
0)
<< ErrnoMessage("mprotect");
CheckedWriteFile(
WritePipeHandle(), &bottom_of_stack, sizeof(bottom_of_stack));
CheckedWriteFile(WritePipeHandle(), &page_addr, sizeof(page_addr));
CheckedWriteFile(
WritePipeHandle(), &stack_address, sizeof(stack_address));
// Wait for parent to read us
CheckedReadFileAtEOF(ReadPipeHandle());
ASSERT_EQ(mprotect(reinterpret_cast<void*>(page_addr),
page_size_,
PROT_READ | PROT_WRITE),
0)
<< ErrnoMessage("mprotect");
}
}
const size_t page_size_;
DISALLOW_COPY_AND_ASSIGN(ChildWithSplitStackTest);
};
// AddressSanitizer with use-after-return detection causes stack variables to
// be allocated on the heap.
#if defined(ADDRESS_SANITIZER)
#define MAYBE_ChildWithSplitStack DISABLED_ChildWithSplitStack
#else
#define MAYBE_ChildWithSplitStack ChildWithSplitStack
#endif
TEST(ProcessReaderLinux, MAYBE_ChildWithSplitStack) {
ChildWithSplitStackTest test;
test.Run();
}
// Android doesn't provide dl_iterate_phdr on ARM until API 21.
#if !defined(OS_ANDROID) || !defined(ARCH_CPU_ARMEL) || __ANDROID_API__ >= 21
int ExpectFindModule(dl_phdr_info* info, size_t size, void* data) {
SCOPED_TRACE(
base::StringPrintf("module %s at 0x%" PRIx64 " phdrs 0x%" PRIx64,
info->dlpi_name,
LinuxVMAddress{info->dlpi_addr},
FromPointerCast<LinuxVMAddress>(info->dlpi_phdr)));
auto modules =
reinterpret_cast<const std::vector<ProcessReaderLinux::Module>*>(data);
#if defined(OS_ANDROID)
// Prior to API 27, Bionic includes a null entry for /system/bin/linker.
if (!info->dlpi_name) {
EXPECT_EQ(info->dlpi_addr, 0u);
EXPECT_EQ(info->dlpi_phnum, 0u);
EXPECT_EQ(info->dlpi_phdr, nullptr);
return 0;
}
#endif
// Bionic doesn't always set both of these addresses for the vdso and
// /system/bin/linker, but it does always set one of them.
VMAddress module_addr = info->dlpi_phdr
? FromPointerCast<LinuxVMAddress>(info->dlpi_phdr)
: info->dlpi_addr;
// TODO(jperaza): This can use a range map when one is available.
bool found = false;
for (const auto& module : *modules) {
if (module.elf_reader && module_addr >= module.elf_reader->Address() &&
module_addr <
module.elf_reader->Address() + module.elf_reader->Size()) {
found = true;
break;
}
}
EXPECT_TRUE(found);
return 0;
}
#endif // !OS_ANDROID || !ARCH_CPU_ARMEL || __ANDROID_API__ >= 21
void ExpectModulesFromSelf(
const std::vector<ProcessReaderLinux::Module>& modules) {
for (const auto& module : modules) {
EXPECT_FALSE(module.name.empty());
EXPECT_NE(module.type, ModuleSnapshot::kModuleTypeUnknown);
}
// Android doesn't provide dl_iterate_phdr on ARM until API 21.
#if !defined(OS_ANDROID) || !defined(ARCH_CPU_ARMEL) || __ANDROID_API__ >= 21
EXPECT_EQ(
dl_iterate_phdr(
ExpectFindModule,
reinterpret_cast<void*>(
const_cast<std::vector<ProcessReaderLinux::Module>*>(&modules))),
0);
#endif // !OS_ANDROID || !ARCH_CPU_ARMEL || __ANDROID_API__ >= 21
}
bool WriteTestModule(const base::FilePath& module_path,
const std::string& soname) {
#if defined(ARCH_CPU_64_BITS)
using Ehdr = Elf64_Ehdr;
using Phdr = Elf64_Phdr;
using Shdr = Elf64_Shdr;
using Dyn = Elf64_Dyn;
using Sym = Elf64_Sym;
unsigned char elf_class = ELFCLASS64;
#else
using Ehdr = Elf32_Ehdr;
using Phdr = Elf32_Phdr;
using Shdr = Elf32_Shdr;
using Dyn = Elf32_Dyn;
using Sym = Elf32_Sym;
unsigned char elf_class = ELFCLASS32;
#endif
struct {
Ehdr ehdr;
struct {
Phdr load1;
Phdr load2;
Phdr dynamic;
} phdr_table;
struct {
Dyn hash;
Dyn strtab;
Dyn symtab;
Dyn strsz;
Dyn syment;
Dyn soname;
Dyn null;
} dynamic_array;
struct {
Elf32_Word nbucket;
Elf32_Word nchain;
Elf32_Word bucket;
Elf32_Word chain;
} hash_table;
char string_table[32];
struct {
} section_header_string_table;
struct {
Sym und_symbol;
} symbol_table;
struct {
Shdr null;
Shdr dynamic;
Shdr string_table;
Shdr section_header_string_table;
} shdr_table;
} module = {};
module.ehdr.e_ident[EI_MAG0] = ELFMAG0;
module.ehdr.e_ident[EI_MAG1] = ELFMAG1;
module.ehdr.e_ident[EI_MAG2] = ELFMAG2;
module.ehdr.e_ident[EI_MAG3] = ELFMAG3;
module.ehdr.e_ident[EI_CLASS] = elf_class;
#if defined(ARCH_CPU_LITTLE_ENDIAN)
module.ehdr.e_ident[EI_DATA] = ELFDATA2LSB;
#else
module.ehdr.e_ident[EI_DATA] = ELFDATA2MSB;
#endif // ARCH_CPU_LITTLE_ENDIAN
module.ehdr.e_ident[EI_VERSION] = EV_CURRENT;
module.ehdr.e_type = ET_DYN;
#if defined(ARCH_CPU_X86)
module.ehdr.e_machine = EM_386;
#elif defined(ARCH_CPU_X86_64)
module.ehdr.e_machine = EM_X86_64;
#elif defined(ARCH_CPU_ARMEL)
module.ehdr.e_machine = EM_ARM;
#elif defined(ARCH_CPU_ARM64)
module.ehdr.e_machine = EM_AARCH64;
#elif defined(ARCH_CPU_MIPSEL) || defined(ARCH_CPU_MIPS64EL)
module.ehdr.e_machine = EM_MIPS;
#endif
module.ehdr.e_version = EV_CURRENT;
module.ehdr.e_ehsize = sizeof(module.ehdr);
module.ehdr.e_phoff = offsetof(decltype(module), phdr_table);
module.ehdr.e_phnum = sizeof(module.phdr_table) / sizeof(Phdr);
module.ehdr.e_phentsize = sizeof(Phdr);
module.ehdr.e_shoff = offsetof(decltype(module), shdr_table);
module.ehdr.e_shentsize = sizeof(Shdr);
module.ehdr.e_shnum = sizeof(module.shdr_table) / sizeof(Shdr);
module.ehdr.e_shstrndx =
offsetof(decltype(module.shdr_table), section_header_string_table) /
sizeof(Shdr);
constexpr size_t load2_vaddr = 0x200000;
module.phdr_table.load1.p_type = PT_LOAD;
module.phdr_table.load1.p_offset = 0;
module.phdr_table.load1.p_vaddr = 0;
module.phdr_table.load1.p_filesz = sizeof(module);
module.phdr_table.load1.p_memsz = sizeof(module);
module.phdr_table.load1.p_flags = PF_R;
module.phdr_table.load1.p_align = load2_vaddr;
module.phdr_table.load2.p_type = PT_LOAD;
module.phdr_table.load2.p_offset = 0;
module.phdr_table.load2.p_vaddr = load2_vaddr;
module.phdr_table.load2.p_filesz = sizeof(module);
module.phdr_table.load2.p_memsz = sizeof(module);
module.phdr_table.load2.p_flags = PF_R | PF_W;
module.phdr_table.load2.p_align = load2_vaddr;
module.phdr_table.dynamic.p_type = PT_DYNAMIC;
module.phdr_table.dynamic.p_offset =
offsetof(decltype(module), dynamic_array);
module.phdr_table.dynamic.p_vaddr =
load2_vaddr + module.phdr_table.dynamic.p_offset;
module.phdr_table.dynamic.p_filesz = sizeof(module.dynamic_array);
module.phdr_table.dynamic.p_memsz = sizeof(module.dynamic_array);
module.phdr_table.dynamic.p_flags = PF_R | PF_W;
module.phdr_table.dynamic.p_align = 8;
module.dynamic_array.hash.d_tag = DT_HASH;
module.dynamic_array.hash.d_un.d_ptr = offsetof(decltype(module), hash_table);
module.dynamic_array.strtab.d_tag = DT_STRTAB;
module.dynamic_array.strtab.d_un.d_ptr =
offsetof(decltype(module), string_table);
module.dynamic_array.symtab.d_tag = DT_SYMTAB;
module.dynamic_array.symtab.d_un.d_ptr =
offsetof(decltype(module), symbol_table);
module.dynamic_array.strsz.d_tag = DT_STRSZ;
module.dynamic_array.strsz.d_un.d_val = sizeof(module.string_table);
module.dynamic_array.syment.d_tag = DT_SYMENT;
module.dynamic_array.syment.d_un.d_val = sizeof(Sym);
constexpr size_t kSonameOffset = 1;
module.dynamic_array.soname.d_tag = DT_SONAME;
module.dynamic_array.soname.d_un.d_val = kSonameOffset;
module.dynamic_array.null.d_tag = DT_NULL;
module.hash_table.nbucket = 1;
module.hash_table.nchain = 1;
module.hash_table.bucket = 0;
module.hash_table.chain = 0;
CHECK_GE(sizeof(module.string_table), soname.size() + 2);
module.string_table[0] = '\0';
memcpy(&module.string_table[kSonameOffset], soname.c_str(), soname.size());
module.shdr_table.null.sh_type = SHT_NULL;
module.shdr_table.dynamic.sh_name = 0;
module.shdr_table.dynamic.sh_type = SHT_DYNAMIC;
module.shdr_table.dynamic.sh_flags = SHF_WRITE | SHF_ALLOC;
module.shdr_table.dynamic.sh_addr = module.phdr_table.dynamic.p_vaddr;
module.shdr_table.dynamic.sh_offset = module.phdr_table.dynamic.p_offset;
module.shdr_table.dynamic.sh_size = module.phdr_table.dynamic.p_filesz;
module.shdr_table.dynamic.sh_link =
offsetof(decltype(module.shdr_table), string_table) / sizeof(Shdr);
module.shdr_table.string_table.sh_name = 0;
module.shdr_table.string_table.sh_type = SHT_STRTAB;
module.shdr_table.string_table.sh_offset =
offsetof(decltype(module), string_table);
module.shdr_table.string_table.sh_size = sizeof(module.string_table);
module.shdr_table.section_header_string_table.sh_name = 0;
module.shdr_table.section_header_string_table.sh_type = SHT_STRTAB;
module.shdr_table.section_header_string_table.sh_offset =
offsetof(decltype(module), section_header_string_table);
module.shdr_table.section_header_string_table.sh_size =
sizeof(module.section_header_string_table);
FileWriter writer;
if (!writer.Open(module_path,
FileWriteMode::kCreateOrFail,
FilePermissions::kWorldReadable)) {
ADD_FAILURE();
return false;
}
if (!writer.Write(&module, sizeof(module))) {
ADD_FAILURE();
return false;
}
return true;
}
ScopedModuleHandle LoadTestModule(const std::string& module_name,
const std::string& module_soname) {
base::FilePath module_path(
TestPaths::Executable().DirName().Append(module_name));
if (!WriteTestModule(module_path, module_soname)) {
return ScopedModuleHandle(nullptr);
}
EXPECT_TRUE(IsRegularFile(module_path));
ScopedModuleHandle handle(
dlopen(module_path.value().c_str(), RTLD_LAZY | RTLD_LOCAL));
EXPECT_TRUE(handle.valid())
<< "dlopen: " << module_path.value() << " " << dlerror();
EXPECT_TRUE(LoggingRemoveFile(module_path));
return handle;
}
void ExpectTestModule(ProcessReaderLinux* reader,
const std::string& module_name) {
for (const auto& module : reader->Modules()) {
if (module.name.find(module_name) != std::string::npos) {
ASSERT_TRUE(module.elf_reader);
VMAddress dynamic_addr;
ASSERT_TRUE(module.elf_reader->GetDynamicArrayAddress(&dynamic_addr));
auto dynamic_mapping = reader->GetMemoryMap()->FindMapping(dynamic_addr);
auto mappings =
reader->GetMemoryMap()->FindFilePossibleMmapStarts(*dynamic_mapping);
EXPECT_EQ(mappings->Count(), 2u);
return;
}
}
ADD_FAILURE() << "Test module not found";
}
TEST(ProcessReaderLinux, SelfModules) {
const std::string module_name = "test_module.so";
const std::string module_soname = "test_module_soname";
ScopedModuleHandle empty_test_module(
LoadTestModule(module_name, module_soname));
ASSERT_TRUE(empty_test_module.valid());
FakePtraceConnection connection;
connection.Initialize(getpid());
ProcessReaderLinux process_reader;
ASSERT_TRUE(process_reader.Initialize(&connection));
ExpectModulesFromSelf(process_reader.Modules());
ExpectTestModule(&process_reader, module_soname);
}
class ChildModuleTest : public Multiprocess {
public:
ChildModuleTest() : Multiprocess(), module_soname_("test_module_soname") {}
~ChildModuleTest() = default;
private:
void MultiprocessParent() override {
char c;
ASSERT_TRUE(LoggingReadFileExactly(ReadPipeHandle(), &c, sizeof(c)));
DirectPtraceConnection connection;
ASSERT_TRUE(connection.Initialize(ChildPID()));
ProcessReaderLinux process_reader;
ASSERT_TRUE(process_reader.Initialize(&connection));
ExpectModulesFromSelf(process_reader.Modules());
ExpectTestModule(&process_reader, module_soname_);
}
void MultiprocessChild() override {
ScopedModuleHandle empty_test_module(
LoadTestModule("test_module.so", module_soname_));
ASSERT_TRUE(empty_test_module.valid());
char c = 0;
ASSERT_TRUE(LoggingWriteFile(WritePipeHandle(), &c, sizeof(c)));
CheckedReadFileAtEOF(ReadPipeHandle());
}
const std::string module_soname_;
DISALLOW_COPY_AND_ASSIGN(ChildModuleTest);
};
TEST(ProcessReaderLinux, ChildModules) {
ChildModuleTest test;
test.Run();
}
#if defined(OS_ANDROID)
const char kTestAbortMessage[] = "test abort message";
TEST(ProcessReaderLinux, AbortMessage) {
// This test requires Q. The API level on Q devices will be 28 until the API
// is finalized, so we can't check API level yet. For now, test for the
// presence of a libc symbol which was introduced in Q.
if (!crashpad::internal::Dlsym(RTLD_DEFAULT,
"android_fdsan_close_with_tag")) {
GTEST_SKIP();
}
android_set_abort_message(kTestAbortMessage);
FakePtraceConnection connection;
connection.Initialize(getpid());
ProcessReaderLinux process_reader;
ASSERT_TRUE(process_reader.Initialize(&connection));
EXPECT_EQ(kTestAbortMessage, process_reader.AbortMessage());
}
#endif
} // namespace
} // namespace test
} // namespace crashpad
| [
"joe@valvesoftware.com"
] | joe@valvesoftware.com |
982f7eb427e30a2025ab871ea190da3b9c8c784c | 834408da4e7dfe7b353b9dfdc1a33eb5121ba830 | /engine/include/core/Id.h | fa4c9487ccfacd9bcc2f5bfde96e34920253e4b9 | [
"MIT"
] | permissive | jsandham/PhysicsEngine | c99b2cc6da76d5ec14a1aecfaacf974f6fb9e8e0 | 69b488828763310d9b22603669d11de7211ada42 | refs/heads/master | 2023-08-08T21:11:18.708136 | 2023-07-22T19:41:20 | 2023-07-22T19:41:20 | 132,405,936 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 863 | h | #ifndef ID_H__
#define ID_H__
#include <functional>
namespace PhysicsEngine
{
class Id
{
private:
int mId;
public:
Id();
Id(int id);
~Id();
Id &operator=(const Id &id);
bool operator==(const Id &id) const;
bool operator!=(const Id &id) const;
bool operator<(const Id &id) const;
bool isValid() const;
bool isInvalid() const;
static Id newId();
static const Id INVALID;
};
} // namespace PhysicsEngine
// allow use of Guid in unordered_set and unordered_map
namespace std
{
template <> struct hash<PhysicsEngine::Id>
{
size_t operator()(const PhysicsEngine::Id &id) const noexcept
{
static_assert(sizeof(PhysicsEngine::Id) == sizeof(int));
const int *p = reinterpret_cast<const int *>(&id);
std::hash<int> hash;
return hash(*p);
}
};
} // namespace std
#endif | [
"jsandham@uwaterloo.ca"
] | jsandham@uwaterloo.ca |
deb83f3a4188c51ab36d911d58a5f9c669f942cf | 1d5d650014ac3dd142965906cf2b4fdbe34afb63 | /abc173/abc173_a.cpp | bbf713ee8ec756cf69f027c4cfb9199e9c8d4e91 | [] | no_license | tks3210/Atcoder | c1b88654762273693bd41db417811169780c0161 | 593dda88e13f703bdb3b4c3e6d795bc425e29416 | refs/heads/master | 2021-07-02T17:46:00.099867 | 2020-12-19T07:57:14 | 2020-12-19T07:57:14 | 146,293,715 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 692 | cpp | #include <bits/stdc++.h>
using namespace std;
#define MOD 1000000007
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define rep1(i, n) for(int i = 1; i <= (int)(n); i++)
#define showmap(is, js, x) {rep(i, is){rep(j, js){cout << x[i][j] << " ";}cout << endl;}}
#define show(x) {for(auto i: x){cout << i << " ";} cout<<endl;}
#define showm(m) {for(auto i: m){cout << m.x << " ";} cout<<endl;}
typedef long long ll;
typedef pair<int, int> P;
typedef pair<ll, ll> llP;
ll gcd(int x, int y){ return y?gcd(y, x%y):x;}
ll lcm(ll x, ll y){ return (x*y)/gcd(x,y);}
int main()
{
int n;
cin >> n;
int ans = 1000 - (n%1000);
if (ans == 1000) ans = 0;
cout << ans << endl;
}
| [
"fujinaga.3210.takashi@gmail.com"
] | fujinaga.3210.takashi@gmail.com |
61c1d50f02cef254bf8765c147366ac2f3c3618f | 56e02f5a7fad092f2aef94f182d4b4e58b19bcb6 | /Source/Tools/Toolbox/SystemUI/Widgets.cpp | e6eb7cbd12d56ceeb193dad7ead8e144d3ca0578 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | bin601/rbfx | 4a53c6f8ab6a39b553e1e3997480d94833131c3e | 92c4369964ab35b9180c338b2cf63a56578c990b | refs/heads/master | 2020-07-09T16:26:58.120546 | 2019-08-21T11:25:49 | 2019-08-21T11:25:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,242 | cpp | //
// Copyright (c) 2017-2019 the rbfx project.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#include "Widgets.h"
#include <ImGui/imgui_internal.h>
#include <Urho3D/Core/Context.h>
#include <Urho3D/Input/Input.h>
#include <SDL/SDL_scancode.h>
#include <Urho3D/SystemUI/SystemUI.h>
using namespace Urho3D;
namespace ImGui
{
struct UIStateWrapper
{
void Set(void* state, void(*deleter)(void*)=nullptr)
{
lastUse_ = ui::GetCurrentContext()->FrameCount;
state_ = state;
deleter_ = deleter;
}
void Unset()
{
if (deleter_ && state_)
deleter_(state_);
state_ = nullptr;
deleter_ = nullptr;
}
void* Get()
{
lastUse_ = ui::GetCurrentContext()->FrameCount;
return state_;
}
bool IsExpired()
{
return (ui::GetCurrentContext()->FrameCount - lastUse_) > 1;
}
protected:
/// User state pointer.
void* state_ = nullptr;
/// Function that handles deleting state object when it becomes unused.
void(*deleter_)(void* state) = nullptr;
/// Frame when value was last used.
int lastUse_ = 0;
};
static ea::unordered_map<ImGuiID, UIStateWrapper> uiState_;
static int uiStateLastGcFrame_ = 0;
void SetUIStateP(void* state, void(*deleter)(void*))
{
auto id = ui::GetCurrentWindow()->IDStack.back();
uiState_[id].Set(state, deleter);
}
void* GetUIStateP()
{
void* result = nullptr;
auto id = ui::GetCurrentWindow()->IDStack.back();
auto it = uiState_.find(id);
if (it != uiState_.end())
result = it->second.Get();
int currentFrame = ui::GetCurrentContext()->FrameCount;
if (uiStateLastGcFrame_ != currentFrame)
{
uiStateLastGcFrame_ = currentFrame;
for (auto jt = uiState_.begin(); jt != uiState_.end();)
{
if (jt->second.IsExpired())
{
jt->second.Unset();
jt = uiState_.erase(jt);
}
else
++jt;
}
}
return result;
}
void ExpireUIStateP()
{
auto it = uiState_.find(ui::GetCurrentWindow()->IDStack.back());
if (it != uiState_.end())
{
it->second.Unset();
uiState_.erase(it);
}
}
int DoubleClickSelectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags, const ImVec2& size)
{
if (ui::Selectable(label, p_selected, flags | ImGuiSelectableFlags_AllowDoubleClick, size))
{
if (ui::IsMouseDoubleClicked(MOUSEB_LEFT))
return 2;
else
return 1;
}
if (ui::IsItemHovered() && ui::IsMouseClicked(MOUSEB_RIGHT))
{
*p_selected = true;
return 1;
}
return 0;
}
int DoubleClickSelectable(const char* label, bool selected, ImGuiSelectableFlags flags, const ImVec2& size)
{
return DoubleClickSelectable(label, &selected, flags, size);
}
bool CollapsingHeaderSimple(const char* label, ImGuiTreeNodeFlags flags)
{
ImGuiWindow* window = ui::GetCurrentWindow();
if (window->SkipItems)
return false;
ui::PushStyleColor(ImGuiCol_HeaderActive, 0);
ui::PushStyleColor(ImGuiCol_HeaderHovered, 0);
ui::PushStyleColor(ImGuiCol_Header, 0);
bool open = ui::TreeNodeBehavior(window->GetID(label), flags | ImGuiTreeNodeFlags_NoAutoOpenOnLog | ImGuiTreeNodeFlags_NoTreePushOnOpen, label);
ui::PopStyleColor(3);
return open;
}
bool ToolbarButton(const char* label)
{
auto& g = *ui::GetCurrentContext();
float dimension = g.FontBaseSize + g.Style.FramePadding.y * 2.0f;
return ui::ButtonEx(label, {0, dimension}, ImGuiButtonFlags_PressedOnClick);
}
void SetHelpTooltip(const char* text, Key requireKey)
{
unsigned scancode = requireKey & (~SDLK_SCANCODE_MASK);
if (ui::IsItemHovered() && (requireKey == KEY_UNKNOWN || ui::IsKeyDown(scancode)))
ui::SetTooltip("%s", text);
}
bool IconButton(const char* label)
{
float size = ui::GetItemRectSize().y;
return ui::Button(label, {size, size});
}
bool MaskSelector(unsigned int* mask)
{
bool modified = false;
const ImGuiStyle& style = ui::GetStyle();
ImVec2 pos = ui::GetCursorPos();
for (auto row = 0; row < 2; row++)
{
for (auto col = 0; col < 16; col++)
{
auto bitPosition = row * 16 + col;
int bitMask = 1 << bitPosition;
bool selected = (*mask & bitMask) != 0;
if (selected)
{
ui::PushStyleColor(ImGuiCol_Button, style.Colors[ImGuiCol_ButtonActive]);
ui::PushStyleColor(ImGuiCol_ButtonHovered, style.Colors[ImGuiCol_ButtonActive]);
}
else
{
ui::PushStyleColor(ImGuiCol_Button, style.Colors[ImGuiCol_Button]);
ui::PushStyleColor(ImGuiCol_ButtonHovered, style.Colors[ImGuiCol_Button]);
}
ui::PushID(bitMask);
if (ui::Button("", {8_dp, 9_dp}))
{
modified = true;
*mask ^= bitMask;
}
if (ui::IsItemHovered())
ui::SetTooltip("%d", bitPosition);
ui::PopID();
ui::SameLine(0, 0);
ui::PopStyleColor(2);
}
ui::NewLine();
if (row < 1)
ui::SetCursorPos({pos.x, pos.y + 9_dp});
}
return modified;
}
enum TransformResizeType
{
RESIZE_NONE = 0,
RESIZE_LEFT = 1,
RESIZE_RIGHT = 2,
RESIZE_TOP = 4,
RESIZE_BOTTOM = 8,
RESIZE_MOVE = 15,
};
}
/// Flag manipuation operators.
URHO3D_FLAGSET_EX(ImGui, TransformResizeType, TransformResizeTypeFlags);
namespace ImGui
{
bool TransformRect(IntRect& inOut, TransformSelectorFlags flags)
{
IntRect delta;
return TransformRect(inOut, delta, flags);
}
bool TransformRect(Urho3D::IntRect& inOut, Urho3D::IntRect& delta, TransformSelectorFlags flags)
{
struct State
{
/// A flag indicating type of resize action currently in progress
TransformResizeTypeFlags resizing_ = RESIZE_NONE;
/// A cache of system cursors
ea::unordered_map<TransformResizeTypeFlags, SDL_Cursor*> cursors_;
/// Default cursor shape
SDL_Cursor* cursorArrow_;
/// Flag indicating that this selector set cursor handle
bool ownsCursor_ = false;
State()
{
cursors_[RESIZE_MOVE] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEALL);
cursors_[RESIZE_LEFT] = cursors_[RESIZE_RIGHT] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEWE);
cursors_[RESIZE_BOTTOM] = cursors_[RESIZE_TOP] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENS);
cursors_[RESIZE_TOP | RESIZE_LEFT] = cursors_[RESIZE_BOTTOM | RESIZE_RIGHT] = SDL_CreateSystemCursor(
SDL_SYSTEM_CURSOR_SIZENWSE);
cursors_[RESIZE_TOP | RESIZE_RIGHT] = cursors_[RESIZE_BOTTOM | RESIZE_LEFT] = SDL_CreateSystemCursor(
SDL_SYSTEM_CURSOR_SIZENESW);
cursorArrow_ = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_ARROW);
}
~State()
{
SDL_FreeCursor(cursorArrow_);
for (const auto& it : cursors_)
SDL_FreeCursor(it.second);
}
};
Input* input = ui::GetSystemUI()->GetSubsystem<Input>();
auto renderHandle = [&](IntVector2 screenPos, int wh) -> bool {
IntRect rect(
screenPos.x_ - wh / 2,
screenPos.y_ - wh / 2,
screenPos.x_ + wh / 2,
screenPos.y_ + wh / 2
);
if (!(flags & TSF_HIDEHANDLES))
{
ui::GetWindowDrawList()->AddRectFilled(ToImGui(rect.Min()), ToImGui(rect.Max()),
ui::GetColorU32(ToImGui(Color::RED)));
}
return rect.IsInside(input->GetMousePosition()) == INSIDE;
};
auto size = inOut.Size();
auto handleSize = Max(Min(Min(size.x_ / 4, size.y_ / 4), 8), 2);
bool modified = false;
auto* s = ui::GetUIState<State>();
auto id = ui::GetID(s);
// Extend rect to cover resize handles that are sticking out of ui element boundaries.
auto extendedRect = inOut + IntRect(-handleSize / 2, -handleSize / 2, handleSize / 2, handleSize / 2);
ui::ItemSize(ToImGui(inOut));
if (ui::ItemAdd(ToImGui(extendedRect), id))
{
TransformResizeTypeFlags resizing = RESIZE_NONE;
if (renderHandle(inOut.Min() + size / 2, handleSize))
resizing = RESIZE_MOVE;
bool canResizeHorizontal = !(flags & TSF_NOHORIZONTAL);
bool canResizeVertical = !(flags & TSF_NOVERTICAL);
if (canResizeHorizontal && canResizeVertical)
{
if (renderHandle(inOut.Min(), handleSize))
resizing = RESIZE_LEFT | RESIZE_TOP;
if (renderHandle(inOut.Min() + IntVector2(0, size.y_), handleSize))
resizing = RESIZE_LEFT | RESIZE_BOTTOM;
if (renderHandle(inOut.Min() + IntVector2(size.x_, 0), handleSize))
resizing = RESIZE_TOP | RESIZE_RIGHT;
if (renderHandle(inOut.Max(), handleSize))
resizing = RESIZE_BOTTOM | RESIZE_RIGHT;
}
if (canResizeHorizontal)
{
if (renderHandle(inOut.Min() + IntVector2(0, size.y_ / 2), handleSize))
resizing = RESIZE_LEFT;
if (renderHandle(inOut.Min() + IntVector2(size.x_, size.y_ / 2), handleSize))
resizing = RESIZE_RIGHT;
}
if (canResizeVertical)
{
if (renderHandle(inOut.Min() + IntVector2(size.x_ / 2, 0), handleSize))
resizing = RESIZE_TOP;
if (renderHandle(inOut.Min() + IntVector2(size.x_ / 2, size.y_), handleSize))
resizing = RESIZE_BOTTOM;
}
// Draw rect around selected element
ui::GetWindowDrawList()->AddRect(ToImGui(inOut.Min()), ToImGui(inOut.Max()),
ui::GetColorU32(ToImGui(Color::RED)));
// Reset mouse cursor if we are not hovering any handle and are not resizing
if (resizing == RESIZE_NONE && s->resizing_ == RESIZE_NONE && s->ownsCursor_)
{
SDL_SetCursor(s->cursorArrow_);
s->ownsCursor_ = false;
}
// Prevent interaction when something else blocks inactive transform.
if (s->resizing_ != RESIZE_NONE || (ui::IsItemHovered(ImGuiHoveredFlags_RectOnly) &&
(!ui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow) || ui::IsWindowHovered())))
{
// Set mouse cursor if handle is hovered or if we are resizing
if (resizing != RESIZE_NONE && !s->ownsCursor_)
{
SDL_SetCursor(s->cursors_[resizing]);
s->ownsCursor_ = true;
}
// Begin resizing
if (ui::IsMouseClicked(0))
s->resizing_ = resizing;
IntVector2 d = ToIntVector2(ui::GetIO().MouseDelta);
if (s->resizing_ != RESIZE_NONE)
{
ui::SetActiveID(id, ui::GetCurrentWindow());
if (!ui::IsMouseDown(0))
s->resizing_ = RESIZE_NONE;
else if (d != IntVector2::ZERO)
{
delta = IntRect::ZERO;
if (s->resizing_ == RESIZE_MOVE)
{
delta.left_ += d.x_;
delta.right_ += d.x_;
delta.top_ += d.y_;
delta.bottom_ += d.y_;
modified = true;
}
else
{
if (s->resizing_ & RESIZE_LEFT)
{
delta.left_ += d.x_;
modified = true;
}
else if (s->resizing_ & RESIZE_RIGHT)
{
delta.right_ += d.x_;
modified = true;
}
if (s->resizing_ & RESIZE_TOP)
{
delta.top_ += d.y_;
modified = true;
}
else if (s->resizing_ & RESIZE_BOTTOM)
{
delta.bottom_ += d.y_;
modified = true;
}
}
}
}
else if (ui::IsItemActive())
ui::SetActiveID(0, ui::GetCurrentWindow());
if (modified)
inOut += delta;
}
else if (ui::IsItemActive())
ui::SetActiveID(0, ui::GetCurrentWindow());
}
return modified;
}
SystemUI* GetSystemUI()
{
return static_cast<SystemUI*>(ui::GetIO().UserData);
}
bool EditorToolbarButton(const char* text, const char* tooltip, bool active)
{
const auto& style = ui::GetStyle();
if (active)
ui::PushStyleColor(ImGuiCol_Button, style.Colors[ImGuiCol_ButtonActive]);
else
ui::PushStyleColor(ImGuiCol_Button, style.Colors[ImGuiCol_Button]);
bool result = ui::ToolbarButton(text);
ui::PopStyleColor();
ui::SameLine(0, 0);
if (ui::IsItemHovered() && tooltip)
ui::SetTooltip("%s", tooltip);
return result;
}
void OpenTreeNode(ImGuiID id)
{
auto& storage = ui::GetCurrentWindow()->DC.StateStorage;
if (!storage->GetInt(id))
{
storage->SetInt(id, true);
ui::TreePushOverrideID(id);
}
}
void BeginButtonGroup()
{
auto* storage = ui::GetStateStorage();
auto* lists = ui::GetWindowDrawList();
ImVec2 pos = ui::GetCursorScreenPos();
storage->SetFloat(ui::GetID("button-group-x"), pos.x);
storage->SetFloat(ui::GetID("button-group-y"), pos.y);
lists->ChannelsSplit(2);
lists->ChannelsSetCurrent(1);
}
void EndButtonGroup()
{
auto& style = ui::GetStyle();
auto* lists = ui::GetWindowDrawList();
auto* storage = ui::GetStateStorage();
ImVec2 min(
storage->GetFloat(ui::GetID("button-group-x")),
storage->GetFloat(ui::GetID("button-group-y"))
);
lists->ChannelsSetCurrent(0);
lists->AddRectFilled(min, ui::GetItemRectMax(), ImColor(style.Colors[ImGuiCol_Button]), style.FrameRounding);
lists->ChannelsMerge();
}
void TextElided(const char* text, float width)
{
float x = ui::GetCursorPosX();
if (ui::CalcTextSize(text).x <= width)
{
ui::TextUnformatted(text);
ui::SameLine(0, 0);
ui::SetCursorPosX(x + width);
ui::NewLine();
return;
}
else
{
float w = ui::CalcTextSize("...").x;
for (const char* c = text; *c; c++)
{
w += ui::CalcTextSize(c, c + 1).x;
if (w >= width)
{
ui::TextUnformatted(text, c > text ? c - 1 : c);
ui::SameLine(0, 0);
ui::TextUnformatted("...");
ui::SameLine(0, 0);
ui::SetCursorPosX(x + width);
ui::NewLine();
return;
}
}
}
ui::SetCursorPosX(x + width);
ui::NewLine();
}
}
| [
"rokups@zoho.com"
] | rokups@zoho.com |
cb86049de645a5b1c37b1a3fadc17d36a7e0d919 | f75eefba63cf4e11e268c5c91e10df0af96d98e3 | /Source/NoesisGui/Classes/GeneratedClasses/NoesisGuiBinding.h | 3613ccf1028de9aef087a7311479866ca1065b31 | [] | no_license | bibleuspro/UE4Plugin | 7468b4a175ecd37c00e77953a2b0b97cde61ad2a | 1e09fa2b327f33e21dfd8d8351ce6eea5cdb78f5 | refs/heads/master | 2021-01-11T02:37:42.648194 | 2016-10-20T10:49:06 | 2016-10-20T10:49:06 | 70,951,187 | 0 | 0 | null | 2016-10-14T22:20:26 | 2016-10-14T22:20:26 | null | UTF-8 | C++ | false | false | 2,884 | h | ////////////////////////////////////////////////////////////////////////////////////////////////////
// Noesis Engine - http://www.noesisengine.com
// Copyright (c) 2009-2010 Noesis Technologies S.L. All Rights Reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma once
#include "NoesisGuiTypes.h"
#include "GeneratedClasses/NoesisGuiBaseBinding.h"
#include "NoesisGuiBinding.generated.h"
UCLASS()
class NOESISGUI_API UNoesisGuiBinding : public UNoesisGuiBaseBinding
{
public:
GENERATED_UCLASS_BODY()
virtual void SetNoesisComponent(Noesis::Core::BaseComponent* NoesisComponent) override;
// Property Converter
UFUNCTION(BlueprintCallable, Category = "NoesisGui")
UNoesisGuiIValueConverter* GetConverter();
UFUNCTION(BlueprintCallable, Category = "NoesisGui")
void SetConverter(UNoesisGuiIValueConverter* InConverter);
// Property ConverterParameter
UFUNCTION(BlueprintCallable, Category = "NoesisGui")
class UNoesisGuiBaseComponent* GetConverterParameter();
UFUNCTION(BlueprintCallable, Category = "NoesisGui")
void SetConverterParameter(class UNoesisGuiBaseComponent* InConverterParameter);
// Property ElementName
UFUNCTION(BlueprintCallable, Category = "NoesisGui")
FString GetElementName();
UFUNCTION(BlueprintCallable, Category = "NoesisGui")
void SetElementName(FString InElementName);
// Property Mode
UFUNCTION(BlueprintCallable, Category = "NoesisGui")
ENoesisGuiBindingMode GetMode();
UFUNCTION(BlueprintCallable, Category = "NoesisGui")
void SetMode(ENoesisGuiBindingMode InMode);
// Property Path
UFUNCTION(BlueprintCallable, Category = "NoesisGui")
class UNoesisGuiPropertyPath* GetPath();
UFUNCTION(BlueprintCallable, Category = "NoesisGui")
void SetPath(class UNoesisGuiPropertyPath* InPath);
// Property RelativeSource
UFUNCTION(BlueprintCallable, Category = "NoesisGui")
class UNoesisGuiRelativeSource* GetRelativeSource();
UFUNCTION(BlueprintCallable, Category = "NoesisGui")
void SetRelativeSource(class UNoesisGuiRelativeSource* InRelativeSource);
// Property Source
UFUNCTION(BlueprintCallable, Category = "NoesisGui")
class UNoesisGuiBaseComponent* GetSource();
UFUNCTION(BlueprintCallable, Category = "NoesisGui")
void SetSource(class UNoesisGuiBaseComponent* InSource);
// Property UpdateSourceTrigger
UFUNCTION(BlueprintCallable, Category = "NoesisGui")
ENoesisGuiUpdateSourceTrigger GetUpdateSourceTrigger();
UFUNCTION(BlueprintCallable, Category = "NoesisGui")
void SetUpdateSourceTrigger(ENoesisGuiUpdateSourceTrigger InUpdateSourceTrigger);
UFUNCTION(BlueprintCallable, Category = "NoesisGui")
FNoesisGuiObjectWithNameScope GetSourceObject(class UNoesisGuiBaseComponent* Target, const class UNoesisGuiDependencyProperty* TargetProperty);
// UObject interface
virtual void BeginDestroy() override;
// End of UObject interface
};
| [
"hcpizzi@hotmail.com"
] | hcpizzi@hotmail.com |
1ced7bca860ea2ec40ccbd27ae34f961d87f63a0 | 2e0e6bbeac7ee292c122ee6bfce8891c346f2142 | /LabTest1P2.cpp | 804b44803b4353a5d9834b57154e06989b358f43 | [] | no_license | MichaelKBailey/ComputerSciencePrograms | ecc31fb8dc5c44fc6977a65d5b861d9bb2755803 | f7671fabd6c5b244e76be033acdc4c122f350a9a | refs/heads/master | 2020-04-09T09:03:59.674964 | 2018-12-03T16:41:09 | 2018-12-03T16:41:09 | 160,219,796 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,032 | cpp | /*
Michael Bailey
Assignment: LabTest1
This program will draw a poly-line
*/
#include <iostream>
#include "graph1.h"
using namespace std;
void getData(int* no_points, int* x, int* y, int*r, int* g, int* b);
int* drawPolyLine(int *x, int *y, int no_points);
void colorPolyLine(int* objects, int no_points, int r, int g, int b);
int main()
{
const int max_elements = 10;
int x[max_elements];
int y[max_elements];
char repeat = 'y';
int no_points = 0;
int* objects = NULL;
int r = 0;
int g = 0;
int b = 0;
displayGraphics();
do
{
getData(&no_points, x, y, &r, &g, &b);
objects = drawPolyLine(x, y, no_points);
colorPolyLine(objects, no_points, r, g, b);
cout << "Repeat this program?";
cin >> repeat;
clearGraphics();
system("cls");
} while ((repeat == 'y') || (repeat == 'Y'));
delete[] objects;
return 0;
}
void getData(int* no_points, int* x, int* y, int*r, int* g, int* b)
{
int i = 0;
int j = 0;
do{
cout << "Please enter the number of points: ";
cin >> *no_points;
if (*no_points < 3 || *no_points > 10)
cout << "\nPlease enter a number between 3 and 10. ";
}while (*no_points < 3 || *no_points > 10);
do {
cout << "Please enter the x/y coordinates for the #" << i + 1 << " point: ";
cin >> x[i] >> y[i];
i++;
} while (i < *no_points);
do {
cout << "Please enter the r, g, and b values for each line segment #" << j + 1 << endl;
cin >> r[j] >> g[j] >> b[j];
j++;
}while (j < *no_points);
}
int* drawPolyLine(int *x, int *y, int no_points)
{
x = new int[no_points];
y = new int[no_points];
int* objects = NULL;
objects = new int[no_points];
for (int i = 0; i < no_points; i++)
{
objects[i] = drawLine(x[i], y[i], x[i + 1], y[i + 1], 1);
}
return objects;
}
void colorPolyLine(int* objects, int no_points, int r, int g, int b)
{
for (int i = 0; i < no_points; i++)
{
setColor(objects[i], r, g, b);
}
} | [
"noreply@github.com"
] | noreply@github.com |
83a6587ea7c0ade204059cdb2cd8945609b073d3 | e3c8f2e177eb73ee8a23b32c369ec7b870833eae | /ChatApplication/GeneratedFiles/Debug/moc_MyTextEdit.cpp | f67b13ab478558f143dec18ffcfabe2ef88aec90 | [] | no_license | Codrin18/OOP | d99c763f8a08a21f63886f334ff55d46a338de11 | e13bf7243295a6006b1472961206ab32ac5162c3 | refs/heads/master | 2020-04-26T04:22:55.478861 | 2019-06-12T07:44:22 | 2019-06-12T07:44:22 | 173,300,073 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,966 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'MyTextEdit.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 "../../MyTextEdit.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'MyTextEdit.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_MyTextEdit_t {
QByteArrayData data[3];
char stringdata0[25];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_MyTextEdit_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_MyTextEdit_t qt_meta_stringdata_MyTextEdit = {
{
QT_MOC_LITERAL(0, 0, 10), // "MyTextEdit"
QT_MOC_LITERAL(1, 11, 12), // "enterPressed"
QT_MOC_LITERAL(2, 24, 0) // ""
},
"MyTextEdit\0enterPressed\0"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_MyTextEdit[] = {
// content:
8, // revision
0, // classname
0, 0, // classinfo
1, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
1, // signalCount
// signals: name, argc, parameters, tag, flags
1, 0, 19, 2, 0x06 /* Public */,
// signals: parameters
QMetaType::Void,
0 // eod
};
void MyTextEdit::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
auto *_t = static_cast<MyTextEdit *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->enterPressed(); break;
default: ;
}
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast<int *>(_a[0]);
{
using _t = void (MyTextEdit::*)();
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&MyTextEdit::enterPressed)) {
*result = 0;
return;
}
}
}
Q_UNUSED(_a);
}
QT_INIT_METAOBJECT const QMetaObject MyTextEdit::staticMetaObject = { {
&QTextEdit::staticMetaObject,
qt_meta_stringdata_MyTextEdit.data,
qt_meta_data_MyTextEdit,
qt_static_metacall,
nullptr,
nullptr
} };
const QMetaObject *MyTextEdit::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *MyTextEdit::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_MyTextEdit.stringdata0))
return static_cast<void*>(this);
return QTextEdit::qt_metacast(_clname);
}
int MyTextEdit::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QTextEdit::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 1)
qt_static_metacall(this, _c, _id, _a);
_id -= 1;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 1)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 1;
}
return _id;
}
// SIGNAL 0
void MyTextEdit::enterPressed()
{
QMetaObject::activate(this, &staticMetaObject, 0, nullptr);
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| [
"noreply@github.com"
] | noreply@github.com |
58e11823a4620591c307db3de4efb96d96ab4773 | 5c2a9346540261fe4df7e30585afbfadb3c42811 | /系统--Final 1.0/Book.h | 305d96e217003aa0c053c4894e17fa6975d7eeb8 | [] | no_license | lbtxdy/library-manegerment-system | 7ccba598a910c69a12ffd212980218c63c637673 | 947ffc36e584a07964658050b7a916f75ad7f8db | refs/heads/master | 2020-05-17T00:27:49.666047 | 2015-06-27T04:09:26 | 2015-06-27T04:09:26 | 38,146,076 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 191 | h | #ifndef _Book_H_
#define _Book_H_
#include<string>
using namespace std;
class Book
{
protected:
string name;
string ISBN;
string Area;
bool CanBorrow;
bool Borrowed;
};
#endif
| [
"lbtxdy@qq.com"
] | lbtxdy@qq.com |
f97e92b40cc092df62bbeb5a7bd8847fe46055fa | 94f3e5f98a635ae663634fb663023dfda14fe393 | /leetcode/leetcode/GetNumberOfK.h | 510fc39409cb87c04e497e07fe91230acf5dfc29 | [] | no_license | shaugier/leetcode | 0816789a40c28c7665bf499b563126be005fd343 | 062611485eb9a9c13f372aec0671991a5cecd0b4 | refs/heads/master | 2021-01-10T03:47:43.083837 | 2016-03-07T08:40:37 | 2016-03-07T08:40:37 | 45,114,894 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 457 | h | #include"leethead2.h"
class Solution35 {
public:
int GetNumberOfK(vector<int> data, int k) {
stringstream ss;
string numbers;
for (int i = 0; i < data.size(); i++)
{
ss << data[i];
numbers = numbers + ss.str();
ss.str("");
}
int result = 0;
ss.clear();
ss << k;
char pivot = (ss.str()).front();
cout << pivot;
for (int j = 0; j < numbers.size(); j++)
{
if (numbers[j] == pivot)
result++;
}
return result;
}
}; | [
"shaugier@qq.com"
] | shaugier@qq.com |
d17090518bff8a05e00e67dc57ad898533ad651c | 725104e743ab6c99e6dcfd4e749c069af4c9cdc9 | /LeetCodeTestSolutions/Ex031-LongestValidParentheses.cpp | 9a9c656b20f6e89b3e6070133c9255634bbf841f | [] | no_license | Msudyc/LeetCodePartCpp | 7306af23a1921e0c52fc29d12b32fad337a62174 | 0204709753fdaeee6fa222f70fa11ff9bd1f6e6d | refs/heads/master | 2021-01-15T10:25:49.839340 | 2014-11-09T04:05:49 | 2014-11-09T04:05:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,152 | cpp | /*
Given a string containing just the characters '(' and
')', find the length of the longest valid (well-formed)
parentheses substring.
For "(()", the longest valid parentheses substring is "()",
which has length = 2.
Another example is ")()())", where the longest valid
parentheses substring is "()()", which has length = 4.
class Solution {
public:
int longestValidParentheses(string s) {
}
};
*/
#include <stack>
#include "Ex031-LongestValidParentheses.h"
namespace LeetCodeTestSolutions
{
int Ex31::longestValidParentheses(string s)
{
int res = 0, last = -1;
stack<int> lefts;
for(int i = 0; i < (int)s.size(); i++)
{
if(s[i] == '(') lefts.push(i);
else if(s[i] == ')')
{
if(lefts.empty()) last = i; // no matching left
else
{
// find a matching pair
lefts.pop();
if(lefts.empty()) res = max(res, i - last);
else res = max(res, i - lefts.top());
}
}
}
return res;
}
} | [
"msudyc@gmail.com"
] | msudyc@gmail.com |
aefb8ad87a8f853a4dbdd8511e0849e168f96f34 | 2f9f3ad110563ec3db62d2d74c3c120137c73df1 | /cstudy/datatypetest1/datatypetest1/datatypetest1.cpp | c1503398603038004d52f8b1a90452e237b2b84f | [] | no_license | D-Gun/DoNotAfraid | 293cb94ad6cff1ffc9b28ff7cb488b3f411759c6 | 11860df5394586b312d8f6ee31d6a4edcf5aefd1 | refs/heads/master | 2023-07-26T18:48:18.991958 | 2021-09-05T14:07:21 | 2021-09-05T14:07:21 | 320,894,909 | 0 | 0 | null | 2021-01-08T00:51:11 | 2020-12-12T18:16:00 | C# | UTF-8 | C++ | false | false | 1,138 | cpp | // datatypetest1.cpp : 이 파일에는 'main' 함수가 포함됩니다. 거기서 프로그램 실행이 시작되고 종료됩니다.
//
#include <iostream>
int main()
{
std::cout << "Hello World!\n";
std::cout << 'H\n';
std::cout << 123+456;
}
// 프로그램 실행: <Ctrl+F5> 또는 [디버그] > [디버깅하지 않고 시작] 메뉴
// 프로그램 디버그: <F5> 키 또는 [디버그] > [디버깅 시작] 메뉴
// 시작을 위한 팁:
// 1. [솔루션 탐색기] 창을 사용하여 파일을 추가/관리합니다.
// 2. [팀 탐색기] 창을 사용하여 소스 제어에 연결합니다.
// 3. [출력] 창을 사용하여 빌드 출력 및 기타 메시지를 확인합니다.
// 4. [오류 목록] 창을 사용하여 오류를 봅니다.
// 5. [프로젝트] > [새 항목 추가]로 이동하여 새 코드 파일을 만들거나, [프로젝트] > [기존 항목 추가]로 이동하여 기존 코드 파일을 프로젝트에 추가합니다.
// 6. 나중에 이 프로젝트를 다시 열려면 [파일] > [열기] > [프로젝트]로 이동하고 .sln 파일을 선택합니다.
| [
"daegeungim7301@gmail.com"
] | daegeungim7301@gmail.com |
f9c20d8027ec4641cdc5c45685cbea09c376d76b | 3bd07bb9e3e4f5e33767ba5ff025cfa3fb8c91dd | /4_1/mainwindow.h | dbbe41089fd87838cc00e328ca302f8d81146f00 | [] | no_license | Andrew-Chernyavski/hw_1_2 | a00d1633937bc2d924972bdab83e4fbe3057ecff | 98031f976503e2f780cc00234537196b2e2daa45 | refs/heads/master | 2016-08-03T07:24:45.646391 | 2012-05-24T20:31:40 | 2012-05-24T20:31:40 | 3,538,239 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 368 | h | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void on_horizontalScrollBar_valueChanged(int value);
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
| [
"andrew-chernyavski@yandex.ru"
] | andrew-chernyavski@yandex.ru |
9f15168113f7beb0fd323cdf6ca45b72cd66258b | 83309645c3d7eaf945861020e452e7ad27b12aec | /textured_rect.cpp | 3ce4e49642b472a5a29ab261fe68a0f095e405b1 | [] | no_license | Dm94st/Space-Invaders | b53ff242da4867699bcfcff124aa9ef1e21d5208 | f9af654791b9027cab5e4e543ac1643fc938284f | refs/heads/master | 2020-04-05T12:11:15.985010 | 2017-07-22T13:46:38 | 2017-07-22T20:37:36 | 68,703,882 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,514 | cpp | #include "textured_rect.hpp"
#include <QPainter>
#include <QPaintEngine>
#include <Qtime>
#include <math.h>
TexturedRect::~TexturedRect()
{
delete m_program;
delete m_vertexShader;
delete m_fragmentShader;
m_vbo.destroy();
}
bool TexturedRect::Initialize(QOpenGLFunctions * functions)
{
m_functions = functions;
if (m_functions == nullptr) return false;
// Shaders
m_vertexShader = new QOpenGLShader(QOpenGLShader::Vertex);
char const * vsrc =
"attribute highp vec3 a_position;\n"
"attribute highp vec2 a_texCoord;\n"
"uniform mediump mat4 u_modelViewProjection;\n"
"varying highp vec2 v_texCoord;\n"
"uniform float frame;\n"
"uniform float frameCount;\n"
"void main(void)\n"
"{\n"
" gl_Position = u_modelViewProjection * vec4(a_position, 1.0);\n"
" if (frameCount == 1.0)\n"
" v_texCoord = a_texCoord;\n"
" else\n"
" v_texCoord = vec2((frame + a_texCoord[0])/frameCount, a_texCoord[1]);\n"
"}\n";
// Shader compilation
if (!m_vertexShader->compileSourceCode(vsrc)) return false;
m_fragmentShader = new QOpenGLShader(QOpenGLShader::Fragment);
char const * fsrc =
"varying highp vec2 v_texCoord;\n"
"uniform sampler2D tex;\n"
"uniform float time;\n"
"uniform float posx;\n"
"uniform float posy;\n"
"void main(void)\n"
"{\n"
" highp vec4 color = texture2D(tex, v_texCoord);\n"
" float n = time == -1.0 ? 1.0 : sin((6.14*time + posx)/10.0 + 0.5);\n"
" gl_FragColor = vec4(color.r, color.g, color.b, n) * color.a;\n"
"}\n";
if (!m_fragmentShader->compileSourceCode(fsrc)) return false;
// Adding shaders to program
m_program = new QOpenGLShaderProgram();
m_program->addShader(m_vertexShader);
m_program->addShader(m_fragmentShader);
if (!m_program->link()) return false;
m_positionAttr = m_program->attributeLocation("a_position");
m_texCoordAttr = m_program->attributeLocation("a_texCoord");
m_modelViewProjectionUniform = m_program->uniformLocation("u_modelViewProjection");
m_textureUniform = m_program->uniformLocation("tex"); // Set texture
m_time = m_program->uniformLocation("time");
m_posx = m_program->uniformLocation("posx");
m_frame = m_program->uniformLocation("frame");
m_frameCount = m_program->uniformLocation("frameCount");
// Create vertex (вершинный) buffer
m_vbo.create();
std::vector<float> data
{
-1.0f, -1.0f, 0.0f, 0.0f, 1.0f,
-1.0f, 1.0f, 0.0f, 0.0f, 0.0f,
1.0f, -1.0f, 0.0f, 1.0f, 1.0f,
-1.0f, 1.0f, 0.0f, 0.0f, 0.0f,
1.0f, 1.0f, 0.0f, 1.0f, 0.0f,
1.0f, -1.0f, 0.0f, 1.0f, 1.0f
};
m_vbo.bind(); // Activate vertex buffer
m_vbo.allocate(data.data(), data.size() * sizeof(float)); // Allocate memory
m_vbo.release();
return true;
}
void TexturedRect::Render(QOpenGLTexture * texture, QVector2D const & position,
QSize const & size, QSize const & screenSize, float rate, bool blink, int frame, int frameCount)
{
if (texture == nullptr) return;
QMatrix4x4 mvp;
QTime t;
t.start();
mvp.translate(2.0f * position.x() * rate / screenSize.width() - 1.0f,
2.0f * position.y() * rate / screenSize.height() - 1.0f);
mvp.scale(static_cast<float>(rate * size.width()) / screenSize.width(),
static_cast<float>(rate * size.height()) / screenSize.height());
m_program->bind(); // Program activation
m_program->setUniformValue(m_textureUniform, 0); // Use 0 texture unit
m_program->setUniformValue(m_time, blink ? (float)t.msec()/100 : -1);
m_program->setUniformValue(m_posx, position.x());
m_program->setUniformValue(m_frame, (float)frame);
m_program->setUniformValue(m_frameCount, (float)frameCount);
m_program->setUniformValue(m_modelViewProjectionUniform, mvp);
texture->bind(); // Texture activation
m_program->enableAttributeArray(m_positionAttr);
m_program->enableAttributeArray(m_texCoordAttr);
m_vbo.bind();
m_program->setAttributeBuffer(m_positionAttr, GL_FLOAT, 0, 3, 5 * sizeof(float)); // Source, type, from, size, offset
m_program->setAttributeBuffer(m_texCoordAttr, GL_FLOAT, 3 * sizeof(float), 2, 5 * sizeof(float));
m_vbo.release();
m_functions->glDrawArrays(GL_TRIANGLES, 0, 6);
m_program->disableAttributeArray(m_positionAttr);
m_program->disableAttributeArray(m_texCoordAttr);
m_program->release(); // Program deactivation
}
| [
"stavitsky94@gmail.com"
] | stavitsky94@gmail.com |
088f3c90e68c1657e66ac9a83168f234b99c5650 | 3336be60a936dc52095126932efd4d623bf909ea | /emb.h | 40a827965388f786372fee3212c3605e850296ae | [] | no_license | Amrf000/PIAutotest | f92318c02137b8ca473a52ed6b89db165bd1d6f2 | aeaf75dbcd616cf22438ca8008f8afab47e19b2c | refs/heads/master | 2020-04-26T19:08:06.504664 | 2019-03-25T14:26:24 | 2019-03-25T14:26:24 | 173,764,589 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 882 | h | #ifndef EMB_H
#define EMB_H
#include <functional>
#ifdef _DEBUG
#undef _DEBUG
#pragma push_macro("slots")
#undef slots
#include "Python.h"
#pragma pop_macro("slots")
#define _DEBUG
#else
#pragma push_macro("slots")
#undef slots
#include "Python.h"
#pragma pop_macro("slots")
#endif
namespace emb
{
typedef std::function<void(std::string)> stdout_write_type;
struct Stdout
{
PyObject_HEAD
stdout_write_type write;
};
PyObject* Stdout_write(PyObject* self, PyObject* args);
PyObject* Stdout_flush(PyObject* self, PyObject* args);
extern PyMethodDef Stdout_methods[];
extern PyTypeObject StdoutType;
// Internal state
extern PyObject* g_stdout;
extern PyObject* g_stdout_saved;
extern PyObject* g_stderr_saved;
extern PyModuleDef embmodule;
PyMODINIT_FUNC PyInit_emb(void);
void set_stdout(stdout_write_type write);
void reset_stdout();
} // namespace emb
#endif // EMB_H
| [
"1138824393@qq.com"
] | 1138824393@qq.com |
c0051057ba694f34a7e0b8c058a5e82a135b1e90 | eb43dfffd3a353acbe57b76d3a0e89754773825a | /partition_list.cpp | 3695243c882496a9d0446831a3a702d2cac932f2 | [] | no_license | deekookee/lintcode | d85a2bac0df10fe70ae3b755f8b9dc07d7fb90ad | f3e9ce5f981851872492ad48c86e8179824778c2 | refs/heads/master | 2021-01-15T23:50:11.831424 | 2016-01-05T04:47:54 | 2016-01-05T04:47:54 | 32,809,299 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,052 | cpp | /**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: The first node of linked list.
* @param x: an integer
* @return: a ListNode
*/
ListNode *partition(ListNode *head, int x) {
// write your code here
ListNode dummyLess(0);
ListNode dummyGreater(0);
ListNode *headLess = &dummyLess;
ListNode *headGreater = &dummyGreater;
while (head != NULL) {
if (head->val < x) {
headLess->next = head;
headLess = headLess->next;
} else {
headGreater->next = head;
headGreater = headGreater->next;
}
head = head->next;
}
headGreater->next = NULL;
headLess->next = dummyGreater.next;
return dummyLess.next;
}
};
| [
"deekookee@gmail.com"
] | deekookee@gmail.com |
c626a025b4ae26886fc3872f0f89b5ba8090b0d4 | b9ac3f216183e3fc7f52845598c8b8e4eee2497d | /xls/data_structures/graph_contraction_test.cc | 68d91feb9417c2c958dc598ed273a9a3f19dbe93 | [
"Apache-2.0"
] | permissive | google/xls | ba225b411161836889a41c6d0e3a2fc09edc25ef | c2f3c725a9b54802119173a82412dc7a0bdf5a2e | refs/heads/main | 2023-09-02T06:56:27.410732 | 2023-09-01T22:27:04 | 2023-09-01T22:28:01 | 262,163,993 | 1,003 | 152 | Apache-2.0 | 2023-08-31T14:47:44 | 2020-05-07T21:38:30 | C++ | UTF-8 | C++ | false | false | 12,597 | cc | // Copyright 2021 The XLS Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "xls/data_structures/graph_contraction.h"
#include <cstdint>
#include <optional>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
namespace xls {
namespace {
using ::testing::UnorderedElementsAre;
static absl::monostate MergeMonostate(absl::monostate x, absl::monostate y) {
return absl::monostate();
}
static int32_t Sum(int32_t x, int32_t y) { return x + y; }
TEST(GraphContractionTest, NodeWeightsAreAdded) {
// Test that node weights are added
GraphContraction<char, int32_t, absl::monostate> gc;
gc.AddVertex('a', 5);
gc.AddVertex('b', 10);
EXPECT_EQ(gc.Vertices(), absl::flat_hash_set<char>({'a', 'b'}));
EXPECT_TRUE(gc.IdentifyVertices('a', 'b', Sum, MergeMonostate));
EXPECT_EQ(gc.WeightOf('a'), 15);
EXPECT_EQ(gc.WeightOf('b'), 15);
EXPECT_EQ(gc.Vertices(), absl::flat_hash_set<char>({'a'}));
}
TEST(GraphContractionTest, AToBYieldsSelfLoop) {
// Test that {a -> b} yields a self-loop when a and b are merged.
GraphContraction<char, absl::monostate, int32_t> gc;
gc.AddVertex('a', absl::monostate());
gc.AddVertex('b', absl::monostate());
gc.AddEdge('a', 'b', 20);
EXPECT_TRUE(gc.IdentifyVertices('a', 'b', MergeMonostate, Sum));
EXPECT_THAT(gc.Vertices(), UnorderedElementsAre('a'));
EXPECT_THAT(gc.EdgesOutOf('a'), UnorderedElementsAre(std::pair('a', 20)));
EXPECT_THAT(gc.EdgesInto('a'), UnorderedElementsAre(std::pair('a', 20)));
}
TEST(GraphContractionTest, AToBAndBToAYieldsSelfLoop) {
// Test that {a -> b, b -> a} yields a self-loop with added weights
// when a and b are merged.
GraphContraction<char, absl::monostate, int32_t> gc;
gc.AddVertex('a', absl::monostate());
gc.AddVertex('b', absl::monostate());
gc.AddEdge('a', 'b', 20);
gc.AddEdge('b', 'a', 30);
EXPECT_TRUE(gc.IdentifyVertices('a', 'b', MergeMonostate, Sum));
EXPECT_THAT(gc.Vertices(), UnorderedElementsAre('a'));
EXPECT_THAT(gc.EdgesOutOf('a'), UnorderedElementsAre(std::pair('a', 50)));
EXPECT_THAT(gc.EdgesInto('a'), UnorderedElementsAre(std::pair('a', 50)));
}
TEST(GraphContractionTest, AllABCombinationsYieldSelfLoop) {
// Test that {a -> a, b -> b, a -> b, b -> a} yields a self-loop with
// added weights when a and b are merged.
GraphContraction<char, absl::monostate, int32_t> gc;
gc.AddVertex('a', absl::monostate());
gc.AddVertex('b', absl::monostate());
gc.AddEdge('a', 'a', 10);
gc.AddEdge('b', 'b', 20);
gc.AddEdge('a', 'b', 30);
gc.AddEdge('b', 'a', 40);
EXPECT_TRUE(gc.IdentifyVertices('a', 'b', MergeMonostate, Sum));
EXPECT_THAT(gc.Vertices(), UnorderedElementsAre('a'));
EXPECT_THAT(gc.EdgesOutOf('a'), UnorderedElementsAre(std::pair('a', 100)));
EXPECT_THAT(gc.EdgesInto('a'), UnorderedElementsAre(std::pair('a', 100)));
}
TEST(GraphContractionTest, AToCAndBToCYieldsAToC) {
// Test that {a -> c, b -> c} yields {a -> c} with added weights
// when a and b are merged.
GraphContraction<char, absl::monostate, int32_t> gc;
gc.AddVertex('a', absl::monostate());
gc.AddVertex('b', absl::monostate());
gc.AddVertex('c', absl::monostate());
gc.AddEdge('a', 'c', 30);
gc.AddEdge('b', 'c', 40);
EXPECT_TRUE(gc.IdentifyVertices('a', 'b', MergeMonostate, Sum));
EXPECT_THAT(gc.Vertices(), UnorderedElementsAre('a', 'c'));
EXPECT_THAT(gc.EdgesOutOf('a'), UnorderedElementsAre(std::pair('c', 70)));
EXPECT_THAT(gc.EdgesInto('c'), UnorderedElementsAre(std::pair('a', 70)));
}
TEST(GraphContractionTest, CToAAndCToBYieldsCToA) {
// Test that {c -> a, c -> b} yields {c -> a} with added weights
// when a and b are merged.
GraphContraction<char, absl::monostate, int32_t> gc;
gc.AddVertex('a', absl::monostate());
gc.AddVertex('b', absl::monostate());
gc.AddVertex('c', absl::monostate());
EXPECT_TRUE(gc.AddEdge('c', 'a', 30));
EXPECT_TRUE(gc.AddEdge('c', 'b', 40));
EXPECT_TRUE(gc.IdentifyVertices('a', 'b', MergeMonostate, Sum));
EXPECT_THAT(gc.Vertices(), UnorderedElementsAre('a', 'c'));
EXPECT_THAT(gc.EdgesOutOf('c'), UnorderedElementsAre(std::pair('a', 70)));
EXPECT_THAT(gc.EdgesInto('a'), UnorderedElementsAre(std::pair('c', 70)));
}
TEST(GraphContractionTest, CToBYieldsCToA) {
// Test that {c -> b} yields {c -> a} when a and b are merged.
GraphContraction<char, absl::monostate, int32_t> gc;
gc.AddVertex('a', absl::monostate());
gc.AddVertex('b', absl::monostate());
gc.AddVertex('c', absl::monostate());
EXPECT_TRUE(gc.AddEdge('c', 'b', 40));
EXPECT_TRUE(gc.IdentifyVertices('a', 'b', MergeMonostate, Sum));
EXPECT_THAT(gc.Vertices(), UnorderedElementsAre('a', 'c'));
EXPECT_THAT(gc.EdgesOutOf('c'), UnorderedElementsAre(std::pair('a', 40)));
EXPECT_THAT(gc.EdgesInto('a'), UnorderedElementsAre(std::pair('c', 40)));
}
TEST(GraphContractionTest, Diamond) {
// Test that {c -> a, c -> b, a -> d, b -> d} yields {c -> a -> d} when
// a and b are merged.
GraphContraction<char, absl::monostate, int32_t> gc;
gc.AddVertex('a', absl::monostate());
gc.AddVertex('b', absl::monostate());
gc.AddVertex('c', absl::monostate());
gc.AddVertex('d', absl::monostate());
EXPECT_TRUE(gc.AddEdge('c', 'a', 10));
EXPECT_TRUE(gc.AddEdge('c', 'b', 20));
EXPECT_TRUE(gc.AddEdge('a', 'd', 30));
EXPECT_TRUE(gc.AddEdge('b', 'd', 40));
EXPECT_TRUE(gc.IdentifyVertices('a', 'b', MergeMonostate, Sum));
EXPECT_THAT(gc.Vertices(), UnorderedElementsAre('c', 'a', 'd'));
EXPECT_THAT(gc.EdgesOutOf('c'), UnorderedElementsAre(std::pair('a', 30)));
EXPECT_THAT(gc.EdgesOutOf('a'), UnorderedElementsAre(std::pair('d', 70)));
EXPECT_THAT(gc.EdgesInto('a'), UnorderedElementsAre(std::pair('c', 30)));
EXPECT_THAT(gc.EdgesInto('d'), UnorderedElementsAre(std::pair('a', 70)));
}
TEST(GraphContractionTest, WeightOfWorks) {
// Test that `WeightOf` works properly.
GraphContraction<char, int32_t, int32_t> gc;
gc.AddVertex('a', 5);
gc.AddVertex('b', 7);
gc.AddEdge('a', 'b', 10);
EXPECT_EQ(gc.WeightOf('a'), 5);
EXPECT_EQ(gc.WeightOf('b'), 7);
EXPECT_EQ(gc.WeightOf('a', 'b'), 10);
}
TEST(GraphContractionTest, ContainsWorks) {
// Test that `Contains` works properly.
GraphContraction<char, absl::monostate, absl::monostate> gc;
gc.AddVertex('a', absl::monostate());
gc.AddVertex('b', absl::monostate());
EXPECT_TRUE(gc.Contains('a'));
EXPECT_TRUE(gc.Contains('b'));
EXPECT_FALSE(gc.Contains('c'));
}
TEST(GraphContractionTest, RepresentativeOfWorks) {
// Test that `RepresentativeOf` works properly.
GraphContraction<char, absl::monostate, absl::monostate> gc;
gc.AddVertex('a', absl::monostate());
gc.AddVertex('b', absl::monostate());
EXPECT_TRUE(gc.IdentifyVertices('a', 'b', MergeMonostate, MergeMonostate));
EXPECT_EQ(gc.RepresentativeOf('a'), 'a');
EXPECT_EQ(gc.RepresentativeOf('b'), 'a');
EXPECT_EQ(gc.RepresentativeOf('c'), std::nullopt);
}
TEST(GraphContractionTest, AddEdgeWithNonexistentVertices) {
// Test that adding an edge with source/target that was not previously
// inserted returns `false`.
GraphContraction<char, absl::monostate, absl::monostate> gc;
gc.AddVertex('a', absl::monostate());
EXPECT_FALSE(gc.AddEdge('b', 'c', absl::monostate()));
EXPECT_FALSE(gc.AddEdge('a', 'b', absl::monostate()));
EXPECT_FALSE(gc.AddEdge('b', 'a', absl::monostate()));
}
TEST(GraphContractionTest, IdentifyNonExistentVertices) {
// Test that identifying two vertices where one or more of them was not
// previously inserted returns `false`.
GraphContraction<char, absl::monostate, absl::monostate> gc;
gc.AddVertex('a', absl::monostate());
EXPECT_FALSE(gc.IdentifyVertices('b', 'c', MergeMonostate, MergeMonostate));
EXPECT_FALSE(gc.IdentifyVertices('a', 'b', MergeMonostate, MergeMonostate));
EXPECT_FALSE(gc.IdentifyVertices('b', 'a', MergeMonostate, MergeMonostate));
}
TEST(GraphContractionTest, SelfIdentification) {
// Test that identify a node with itself returns `true`.
GraphContraction<char, absl::monostate, absl::monostate> gc;
gc.AddVertex('a', absl::monostate());
EXPECT_TRUE(gc.IdentifyVertices('a', 'a', MergeMonostate, MergeMonostate));
}
TEST(GraphContractionTest, QueryNonexistentVerticesAndEdges) {
// Test that `EdgesOutOf`, `EdgesInto`, and `WeightOf` returns the right
// thing for nonexistent vertices and edges.
GraphContraction<char, absl::monostate, absl::monostate> gc;
gc.AddVertex('a', absl::monostate());
gc.AddVertex('b', absl::monostate());
gc.AddEdge('a', 'b', absl::monostate());
EXPECT_TRUE(gc.EdgesOutOf('c').empty());
EXPECT_TRUE(gc.EdgesInto('c').empty());
EXPECT_FALSE(gc.WeightOf('c').has_value());
EXPECT_FALSE(gc.WeightOf('a', 'c').has_value());
EXPECT_FALSE(gc.WeightOf('c', 'a').has_value());
EXPECT_FALSE(gc.WeightOf('c', 'd').has_value());
}
TEST(GraphContractionTest, LongestNodePaths) {
// Test that `LongestNodePaths` works properly on this graph:
//
// a 5
// ╱ ╲
// 10 b c 15
// │ ╳ │
// 10 d e 15
// ╲ ╱
// f 5
GraphContraction<char, int32_t, absl::monostate> gc;
gc.AddVertex('a', 5);
gc.AddVertex('b', 10);
gc.AddVertex('c', 15);
gc.AddVertex('d', 10);
gc.AddVertex('e', 15);
gc.AddVertex('f', 5);
gc.AddEdge('a', 'b', absl::monostate());
gc.AddEdge('a', 'c', absl::monostate());
gc.AddEdge('b', 'd', absl::monostate());
gc.AddEdge('b', 'e', absl::monostate());
gc.AddEdge('c', 'd', absl::monostate());
gc.AddEdge('c', 'e', absl::monostate());
gc.AddEdge('d', 'f', absl::monostate());
gc.AddEdge('e', 'f', absl::monostate());
auto longest_paths_maybe = gc.LongestNodePaths();
EXPECT_TRUE(longest_paths_maybe.has_value());
absl::flat_hash_map<char, absl::flat_hash_map<char, int32_t>> longest_paths =
longest_paths_maybe.value();
absl::flat_hash_map<char, absl::flat_hash_map<char, int32_t>> expected;
expected.insert_or_assign('a', {});
expected.insert_or_assign('b', {});
expected.insert_or_assign('c', {});
expected.insert_or_assign('d', {});
expected.insert_or_assign('e', {});
expected['a'].insert_or_assign('a', 5);
expected['a'].insert_or_assign('b', 15);
expected['a'].insert_or_assign('c', 20);
expected['a'].insert_or_assign('d', 30);
expected['a'].insert_or_assign('e', 35);
expected['a'].insert_or_assign('f', 40);
expected['b'].insert_or_assign('b', 10);
expected['b'].insert_or_assign('d', 20);
expected['b'].insert_or_assign('e', 25);
expected['b'].insert_or_assign('f', 30);
expected['c'].insert_or_assign('c', 15);
expected['c'].insert_or_assign('d', 25);
expected['c'].insert_or_assign('e', 30);
expected['c'].insert_or_assign('f', 35);
expected['d'].insert_or_assign('d', 10);
expected['d'].insert_or_assign('f', 15);
expected['e'].insert_or_assign('e', 15);
expected['e'].insert_or_assign('f', 20);
expected['f'].insert_or_assign('f', 5);
EXPECT_EQ(longest_paths, expected);
}
TEST(GraphContractionTest, LongestNodePathsCyclic) {
// Test that `LongestNodePaths` detects a cyclic graph properly.
GraphContraction<char, int32_t, absl::monostate> gc;
gc.AddVertex('a', 1);
gc.AddVertex('b', 1);
gc.AddVertex('c', 1);
gc.AddEdge('a', 'b', absl::monostate());
gc.AddEdge('b', 'c', absl::monostate());
gc.AddEdge('c', 'a', absl::monostate());
EXPECT_FALSE(gc.LongestNodePaths().has_value());
}
TEST(GraphContractionTest, LongestNodePathsSelfEdge) {
// Test that `LongestNodePaths` detects a self-edge properly.
GraphContraction<char, int32_t, absl::monostate> gc;
gc.AddVertex('a', 1);
gc.AddEdge('a', 'a', absl::monostate());
EXPECT_FALSE(gc.LongestNodePaths().has_value());
}
// TODO(taktoa): 2021-04-23 add a test that constructs a random graph and
// identifies all the vertices together in some random order, which should
// always result in a graph with a single vertex and possibly a self-edge
// (and the vertex/edge weights should be the sum of all vertex/edge weights).
} // namespace
} // namespace xls
| [
"copybara-worker@google.com"
] | copybara-worker@google.com |
a3ac86e682ded990260831c68424ec2159142459 | dcaecb02a39e6a9a6cc3d0514006010f00d800ee | /C++/Ordenamiento.cpp | 4cd244b168b940df0f53b57acfc2f77a363ee227 | [] | no_license | jhoel100/PracticaIS | c9a6463c1a4004f8d09337d160c25a524875dbf0 | 1a312f3cc0092da6d3c801a6ca4a21b451f494fe | refs/heads/master | 2022-12-17T19:40:57.794064 | 2020-09-23T03:27:50 | 2020-09-23T03:27:50 | 297,837,399 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,379 | cpp | //g++ orden.cpp -std=c++11 -lpthread -o orden.out
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <algorithm>
#include <iostream>
#include <math.h>
#include <chrono>
#include <time.h>
#include <bits/stdc++.h>
#include <fstream>
#include <thread>
using namespace std;
void imprimir(int arreglo[],int longitud){
for(int i=0;i<longitud;i++){
cout<<arreglo[i]<<" ";
}
cout<<endl;
}
void imprimirf(float arreglo[],int longitud){
for(int i=0;i<longitud;i++){
cout<<arreglo[i]<<" ";
}
cout<<endl;
}
//1-BUBBLE SORT
void BubbleSort(int arreglo[],int longitud)
{
int auxiliar;
for (int i = 0; i < longitud-1; i++){
// Last i elements are already in place
for (int j = 0; j < longitud-i-1; j++){
if (arreglo[j] > arreglo[j+1]){
auxiliar=arreglo[j];
arreglo[j]=arreglo[j+1];
arreglo[j+1]=auxiliar;
}
}
}
}
//2-COUNTING SORT
void countingSort(int arr[],int n,int rango){
int c[rango]={0};
int i;
int out[n];
for(i=0;i<n;i++)
++c[arr[i]];
for(i=1;i<rango;i++)
c[i]+=c[i-1];
for(i=n-1;i>=0;i--){
out[c[arr[i]]-1]=arr[i];
--c[arr[i]];
}
for(i=0;i<n;i++)
arr[i]=out[i];
}
//3-HEAP SORT
void amontonar(int arr[], int n, int i)
{
int masGrande = i;
int izquierda = 2*i + 1;
int derecha = 2*i + 2;
if (izquierda < n && arr[izquierda] > arr[masGrande])
masGrande = izquierda;
if (derecha < n && arr[derecha] > arr[masGrande])
masGrande = derecha;
if (masGrande != i)
{
swap(arr[i], arr[masGrande]);
amontonar(arr, n, masGrande);
}
}
void heapSort(int arr[], int n)
{
for (int i = n / 2 - 1; i >= 0; i--)
amontonar(arr, n, i);
for (int i=n-1; i>0; i--)
{
swap(arr[0], arr[i]);
amontonar(arr, i, 0);
}
}
//4-INSERTION SORT
void InsertionSort(int arreglo[],int longitud){
for(int j=1;j<longitud;j++){
int clave=arreglo[j];
int i=j-1;
while(i>=0 && arreglo[i]>clave){
arreglo[i+1]=arreglo[i];
i=i-1;
}
arreglo[i+1]=clave;
}
}
//5-MERGE SORT
void Intercala(int arreglo[], int inicio,int medio, int fin){
vector<int> auxiliar(fin-inicio+1);
int i;
int j;
int k;
for(i=inicio;i<=medio;i++){
auxiliar[i-inicio]=arreglo[i];
}
for(j=medio+1;j<=fin;j++){
auxiliar[fin+medio+1-j-inicio]=arreglo[j];
}
i=inicio;
j=fin;
for(k=inicio;k<=fin;k++){
if(auxiliar[i-inicio]<=auxiliar[j-inicio]){
arreglo[k]=auxiliar[i-inicio];
i=i+1;
}else{
arreglo[k]=auxiliar[j-inicio];
j=j-1;
}
}
}
void MergeSort(int arreglo[], int inicio, int fin){
if(inicio<fin){
int medio=floor((inicio+fin)/2);
MergeSort(arreglo,inicio,medio);
MergeSort(arreglo,medio+1,fin);
Intercala(arreglo,inicio,medio,fin);
}
}
//6-QUICK SORT
int Particion(int arreglo[], int inicio, int fin)
{
int pivote=arreglo[fin];
int i=inicio-1;
int auxiliar;
for(int j=inicio;j<fin;j++){
if(arreglo[j]<=pivote){
i=i+1;
auxiliar=arreglo[i];
arreglo[i]=arreglo[j];
arreglo[j]=auxiliar;
}
}
auxiliar=arreglo[i+1];
arreglo[i+1]=arreglo[fin];
arreglo[fin]=auxiliar;
return i+1;
}
void QuickSort(int arreglo[], int inicio, int fin)
{
if(inicio<fin){
int medio=Particion(arreglo,inicio,fin);
QuickSort(arreglo,inicio,medio-1);
QuickSort(arreglo,medio+1,fin);
}
}
//7-SELECTION SORT
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void selectionSort(int arr[], int n)
{
int i, j, min_idx;
for (i = 0; i < n-1; i++)
{
min_idx = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
swap(&arr[min_idx], &arr[i]);
}
}
int main(){
int NUM_ELEMENTOS=100000;
int paso=100;
int NUM_PUNTOS=NUM_ELEMENTOS/paso;
// X, Y valores de los puntos a graficar
double * valoresX;
valoresX = new double [NUM_PUNTOS];
double * valoresY;
valoresY = new double [NUM_PUNTOS];
double * valoresY2;
valoresY2 = new double [NUM_PUNTOS];
double * valoresY3;
valoresY3 = new double [NUM_PUNTOS];
double * valoresY4;
valoresY4 = new double [NUM_PUNTOS];
double * valoresY5;
valoresY5 = new double [NUM_PUNTOS];
double * valoresY6;
valoresY6 = new double [NUM_PUNTOS];
double * valoresY7;
valoresY7 = new double [NUM_PUNTOS];
register int i=0;
srand(time(NULL));
for(int n=1;n<=NUM_PUNTOS;n++){
int * arr;
arr = new int [n*paso];
int * arr2;
arr2 = new int [n*paso];
int * arr3;
arr3 = new int [n*paso];
int * arr4;
arr4 = new int [n*paso];
int * arr5;
arr5 = new int [n*paso];
int * arr6;
arr6 = new int [n*paso];
int * arr7;
arr7 = new int [n*paso];
valoresX[n-1]=n*paso;
for(int i=1;i<=n*paso;i++){
arr[i-1]=1 + rand() % (n*n*paso - 1);
arr2[i-1]=arr[i-1];
arr3[i-1]=arr[i-1];
arr4[i-1]=arr[i-1];
arr5[i-1]=arr[i-1];
arr6[i-1]=arr[i-1];
arr7[i-1]=arr[i-1];
}
//cout<<"Quick SOrt "<<n*paso-1<<endl;
//imprimir(arr,n*paso-1);
auto inicioSort = chrono::high_resolution_clock::now();
QuickSort(arr,0,n*paso-1);
auto finSort = chrono::high_resolution_clock::now();
long long tiemposort = chrono::duration_cast<chrono::nanoseconds> (finSort-inicioSort).count();
valoresY[n-1]=tiemposort;
//imprimir(arr,n*paso-1);
//cout<<endl;
//cout<<"Merge SOrt "<<n*paso-1<<endl;
//imprimir(arr2,n*paso-1);
auto inicioSort2 = chrono::high_resolution_clock::now();
MergeSort(arr2,0,n*paso-1);
auto finSort2 = chrono::high_resolution_clock::now();
long long tiemposort2 = chrono::duration_cast<chrono::nanoseconds> (finSort2-inicioSort2).count();
valoresY2[n-1]=tiemposort2;
//imprimir(arr2,n*paso-1);
//cout<<endl;
//cout<<"Insertion SOrt "<<n*paso-1<<endl;
//imprimir(arr3,n*paso-1);
auto inicioSort3 = chrono::high_resolution_clock::now();
InsertionSort(arr3,n*paso-1);
auto finSort3 = chrono::high_resolution_clock::now();
long long tiemposort3 = chrono::duration_cast<chrono::nanoseconds> (finSort3-inicioSort3).count();
valoresY3[n-1]=tiemposort3;
//imprimir(arr3,n*paso-1);
//cout<<endl;
//cout<<"Bubble SOrt "<<n*paso-1<<endl;
//imprimir(arr4,n*paso-1);
auto inicioSort4 = chrono::high_resolution_clock::now();
BubbleSort(arr4,n*paso-1);
auto finSort4 = chrono::high_resolution_clock::now();
long long tiemposort4 = chrono::duration_cast<chrono::nanoseconds> (finSort4-inicioSort4).count();
valoresY4[n-1]=tiemposort4;
//imprimir(arr4,n*paso-1);
//cout<<endl;
//cout<<"Counting SOrt "<<n*paso-1<<endl;
//imprimir(arr5,n*paso-1);
auto inicioSort5 = chrono::high_resolution_clock::now();
countingSort(arr5,n*paso-1,n*n*paso);
auto finSort5 = chrono::high_resolution_clock::now();
long long tiemposort5 = chrono::duration_cast<chrono::nanoseconds> (finSort5-inicioSort5).count();
valoresY5[n-1]=tiemposort5;
//imprimir(arr5,n*paso-1);
//cout<<endl;
//cout<<"Heap SOrt "<<n*paso-1<<endl;
//imprimir(arr6,n*paso-1);
auto inicioSort6 = chrono::high_resolution_clock::now();
heapSort(arr6,n*paso-1);
auto finSort6 = chrono::high_resolution_clock::now();
long long tiemposort6 = chrono::duration_cast<chrono::nanoseconds> (finSort6-inicioSort6).count();
valoresY6[n-1]=tiemposort6;
//imprimir(arr6,n*paso-1);
//cout<<endl;
//cout<<"Selection SOrt "<<n*paso-1<<endl;
//imprimir(arr7,n*paso-1);
auto inicioSort7 = chrono::high_resolution_clock::now();
selectionSort(arr7,n*paso-1);
auto finSort7 = chrono::high_resolution_clock::now();
long long tiemposort7 = chrono::duration_cast<chrono::nanoseconds> (finSort7-inicioSort7).count();
valoresY7[n-1]=tiemposort7;
//imprimir(arr7,n*paso-1);
//cout<<endl;
delete [] arr;
delete [] arr2;
delete [] arr3;
delete [] arr4;
delete [] arr5;
delete [] arr6;
delete [] arr7;
}
//Lee el archivo puntosGraficar par aguardar los valores
FILE * archivoPuntos = fopen("QuickSort.txt", "w");
FILE * archivoPuntos2 = fopen("MergeSort.txt", "w");
FILE * archivoPuntos3 = fopen("InsertionSort.txt", "w");
FILE * archivoPuntos4 = fopen("BubbleSort.txt", "w");
FILE * archivoPuntos5 = fopen("CountingSort.txt", "w");
FILE * archivoPuntos6 = fopen("HeapSort.txt", "w");
FILE * archivoPuntos7 = fopen("SelectionSort.txt", "w");
for (int i=0;i<NUM_PUNTOS;i++){
fprintf(archivoPuntos, "%f %f \n", valoresX[i], valoresY[i]);
fprintf(archivoPuntos2, "%f %f \n", valoresX[i], valoresY2[i]);
fprintf(archivoPuntos3, "%f %f \n", valoresX[i], valoresY3[i]);
fprintf(archivoPuntos4, "%f %f \n", valoresX[i], valoresY4[i]);
fprintf(archivoPuntos5, "%f %f \n", valoresX[i], valoresY5[i]);
fprintf(archivoPuntos6, "%f %f \n", valoresX[i], valoresY6[i]);
fprintf(archivoPuntos7, "%f %f \n", valoresX[i], valoresY7[i]);
}
fclose(archivoPuntos);
fclose(archivoPuntos2);
fclose(archivoPuntos3);
fclose(archivoPuntos4);
fclose(archivoPuntos5);
fclose(archivoPuntos6);
fclose(archivoPuntos7);
delete [] valoresX;
delete [] valoresY;
delete [] valoresY2;
delete [] valoresY3;
delete [] valoresY4;
delete [] valoresY5;
delete [] valoresY6;
delete [] valoresY7;
return 0;
}
| [
"taparajoel@hotmail.com"
] | taparajoel@hotmail.com |
58d842882a1782c0e410fadde55c74e359e717de | 230b7714d61bbbc9a75dd9adc487706dffbf301e | /content/common/mime_sniffing_throttle.h | 539fecb883692655afd17a633e1f85fe64dc696c | [
"BSD-3-Clause"
] | permissive | byte4byte/cloudretro | efe4f8275f267e553ba82068c91ed801d02637a7 | 4d6e047d4726c1d3d1d119dfb55c8b0f29f6b39a | refs/heads/master | 2023-02-22T02:59:29.357795 | 2021-01-25T02:32:24 | 2021-01-25T02:32:24 | 197,294,750 | 1 | 2 | BSD-3-Clause | 2019-09-11T19:35:45 | 2019-07-17T01:48:48 | null | UTF-8 | C++ | false | false | 1,531 | h | // Copyright 2018 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 CONTENT_COMMON_MIME_SNIFFING_THROTTLE_H_
#define CONTENT_COMMON_MIME_SNIFFING_THROTTLE_H_
#include "base/memory/weak_ptr.h"
#include "content/common/content_export.h"
#include "content/public/common/url_loader_throttle.h"
namespace content {
// Throttle for mime type sniffing. This may intercept the request and
// modify the response's mime type in the response head.
class CONTENT_EXPORT MimeSniffingThrottle : public URLLoaderThrottle {
public:
// |task_runner| is used to bind the right task runner for handling incoming
// IPC in MimeSniffingLoader. |task_runner| is supposed to be bound to the
// current sequence.
explicit MimeSniffingThrottle(
scoped_refptr<base::SingleThreadTaskRunner> task_runner);
~MimeSniffingThrottle() override;
// Implements URLLoaderThrottle.
void WillProcessResponse(const GURL& response_url,
network::ResourceResponseHead* response_head,
bool* defer) override;
// Called from MimeSniffingURLLoader once mime type is ready.
void ResumeWithNewResponseHead(
const network::ResourceResponseHead& new_response_head);
private:
scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
base::WeakPtrFactory<MimeSniffingThrottle> weak_factory_{this};
};
} // namespace content
#endif // CONTENT_COMMON_MIME_SNIFFING_THROTTLE_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
22af5315f371560479cfacd7ec9b4c793a2ec2b2 | d9bb656bd11f85e6419ebd786aec6fe3f917cb73 | /modules/io/pass_thru.cpp | 0a851baa7c3b4bd9c02bb06a674d909a1ba968ba | [
"BSD-2-Clause"
] | permissive | spiralgenetics/biograph | 55a91703a70429568107209ce20e71f6b96577df | 5f40198e95b0626ae143e021ec97884de634e61d | refs/heads/main | 2023-08-30T18:04:55.636103 | 2021-10-31T00:50:48 | 2021-10-31T00:51:08 | 386,059,959 | 21 | 10 | NOASSERTION | 2021-07-22T23:28:45 | 2021-07-14T19:52:15 | HTML | UTF-8 | C++ | false | false | 197 | cpp | #include "modules/io/pass_thru.h"
#include <stdarg.h>
void pass_thru_writable::print(const char* format, ...)
{
va_list args;
va_start(args, format);
m_in.print(format, args);
va_end(args);
}
| [
"rob@spiralgenetics.com"
] | rob@spiralgenetics.com |
56cd134e3fff3211a0515aff5dda9c19a02ddd1d | 1164e110181e49c66f1e09fef6a27b5ac8e8621c | /libs/oef-core/include/oef-core/tasks/utils.hpp | 26867857f3145ce8644dfb4df0d48072279c6beb | [
"Apache-2.0"
] | permissive | fetchai/ledger | 3d560d7f75282bc4c4f08c97a9954100bf6e7257 | c49fb154ec148518d72d4a8f3d2e9b020160d5dd | refs/heads/master | 2021-11-25T06:44:22.761854 | 2021-11-18T09:21:19 | 2021-11-18T09:21:19 | 117,567,381 | 82 | 55 | Apache-2.0 | 2021-11-18T09:28:30 | 2018-01-15T16:15:05 | C++ | UTF-8 | C++ | false | false | 4,940 | hpp | #pragma once
//------------------------------------------------------------------------------
//
// Copyright 2018-2020 Fetch.AI Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//------------------------------------------------------------------------------
#include <algorithm>
#include <iostream>
#include <iterator>
#include <memory>
#include <sstream>
#include <string>
#include <vector>
template <class Container>
void split(const std::string &str, Container &cont, char delim = ' ')
{
std::stringstream ss(str);
std::string token;
while (std::getline(ss, token, delim))
{
cont.push_back(token);
}
if (str.back() == '/')
{
cont.push_back("");
}
}
namespace OEFURI {
class URI
{
public:
std::string protocol;
std::string coreURI;
std::string CoreKey;
std::vector<std::string> namespaces;
std::string AgentKey;
std::string AgentAlias;
bool empty;
URI()
: protocol{"tcp"}
, coreURI{""}
, CoreKey{""}
, AgentKey{""}
, AgentAlias{""}
, empty{true}
{}
virtual ~URI() = default;
std::string ToString()
{
std::string nspaces = "";
if (!namespaces.empty())
{
for (const std::string &nspace : namespaces)
{
nspaces += nspace + "/";
}
nspaces = nspaces.substr(0, nspaces.size() - 1);
}
std::string uri{""};
uri += protocol + "://" += coreURI + "/" += CoreKey + "/" += nspaces + "/" += AgentKey + "/" +=
AgentAlias;
return uri;
}
std::string AgentPartAsString()
{
return AgentKey + (AgentAlias.size() > 0 ? ("/" + AgentAlias) : "");
}
void parse(const std::string &uri)
{
std::vector<std::string> vec;
split(uri, vec, '/');
if (vec.size() < 7)
{
return;
}
std::cerr << "GOT: " << uri << std::endl;
std::cerr << "SIZE: " << vec.size() << std::endl;
for (std::size_t i = 0; i < vec.size(); ++i)
{
std::cerr << i << ": " << vec[static_cast<std::size_t>(i)] << std::endl;
}
empty = false;
protocol = vec[0].substr(0, vec[0].size() - 1);
coreURI = vec[2];
CoreKey = vec[3];
AgentAlias = vec[vec.size() - 1];
AgentKey = vec[vec.size() - 2];
for (std::size_t i = 4, limit = vec.size() - 2; i < limit; ++i)
{
namespaces.push_back(vec[i]);
}
}
void ParseAgent(const std::string &src)
{
if (src.find('/') == std::string::npos)
{
AgentKey = src;
return;
}
std::vector<std::string> vec;
split(src, vec, '/');
if (vec.size() != 2)
{
std::cerr << "parseDestination got invalid string: " << src
<< "! Splitted size: " << vec.size() << std::endl;
return;
}
empty = false;
AgentKey = vec[0];
AgentAlias = vec[1];
}
void print()
{
std::cout << "protocol: " << protocol << std::endl
<< "coreURI: " << coreURI << std::endl
<< "CoreKey: " << CoreKey << std::endl
<< "AgentKey: " << AgentKey << std::endl
<< "AgentAlias: " << AgentAlias << std::endl
<< "empty: " << empty << std::endl
<< "namespaces: " << std::endl;
for (const auto &n : namespaces)
{
std::cout << " - " << n << std::endl;
}
}
};
class Builder
{
public:
using BuilderPtr = std::shared_ptr<Builder>;
static BuilderPtr create(URI uri = URI())
{
return std::make_shared<Builder>(std::move(uri));
}
Builder(URI uri)
: uri_(std::move(uri))
{}
virtual ~Builder() = default;
Builder *protocol(std::string protocol)
{
uri_.protocol = std::move(protocol);
return this;
}
Builder *CoreAddress(std::string host, int port)
{
uri_.coreURI = std::move(host);
uri_.coreURI += std::to_string(port);
return this;
}
Builder *CoreKey(std::string key)
{
uri_.CoreKey = std::move(key);
return this;
}
Builder *AgentKey(std::string key)
{
uri_.AgentKey = std::move(key);
return this;
}
Builder *AddNamespace(std::string nspace)
{
uri_.namespaces.push_back(std::move(nspace));
return this;
}
Builder *AgentAlias(std::string alias)
{
uri_.AgentAlias = std::move(alias);
return this;
}
URI build()
{
return std::move(uri_);
}
private:
URI uri_;
};
} // namespace OEFURI
| [
"42541508+fetch-bot@users.noreply.github.com"
] | 42541508+fetch-bot@users.noreply.github.com |
50989a92a711b504eb0e9892095bdbe49725a5e2 | 164ffe077dde59373ad9fadcfd727f279a1cfe93 | /jni_build/jni/include/external/protobuf/src/google/protobuf/compiler/objectivec/objectivec_field.cc | f73a1851aab3a7d85367d4c61e150c02c786f920 | [] | no_license | Basofe/Community_Based_Repository_Traffic_Signs | 524a4cfc77dc6ed3b279556e4201ba63ee8cf6bd | a20da440a21ed5160baae4d283c5880b8ba8e83c | refs/heads/master | 2021-01-22T21:17:37.392145 | 2017-09-28T21:35:58 | 2017-09-28T21:35:58 | 85,407,197 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 17,851 | cc | // Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <iostream>
#include <google/protobuf/compiler/objectivec/objectivec_field.h>
#include <google/protobuf/compiler/objectivec/objectivec_helpers.h>
#include <google/protobuf/compiler/objectivec/objectivec_enum_field.h>
#include <google/protobuf/compiler/objectivec/objectivec_map_field.h>
#include <google/protobuf/compiler/objectivec/objectivec_message_field.h>
#include <google/protobuf/compiler/objectivec/objectivec_primitive_field.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/wire_format.h>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/strutil.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace objectivec {
namespace {
void SetCommonFieldVariables(const FieldDescriptor* descriptor,
map<string, string>* variables) {
string camel_case_name = FieldName(descriptor);
string raw_field_name;
if (descriptor->type() == FieldDescriptor::TYPE_GROUP) {
raw_field_name = descriptor->message_type()->name();
} else {
raw_field_name = descriptor->name();
}
// The logic here has to match -[GGPBFieldDescriptor textFormatName].
const string un_camel_case_name(
UnCamelCaseFieldName(camel_case_name, descriptor));
const bool needs_custom_name = (raw_field_name != un_camel_case_name);
SourceLocation location;
if (descriptor->GetSourceLocation(&location)) {
(*variables)["comments"] = BuildCommentsString(location);
} else {
(*variables)["comments"] = "\n";
}
const string& classname = ClassName(descriptor->containing_type());
(*variables)["classname"] = classname;
(*variables)["name"] = camel_case_name;
const string& capitalized_name = FieldNameCapitalized(descriptor);
(*variables)["capitalized_name"] = capitalized_name;
(*variables)["raw_field_name"] = raw_field_name;
(*variables)["field_number_name"] =
classname + "_FieldNumber_" + capitalized_name;
(*variables)["field_number"] = SimpleItoa(descriptor->number());
(*variables)["field_type"] = GetCapitalizedType(descriptor);
(*variables)["deprecated_attribute"] = GetOptionalDeprecatedAttribute(descriptor);
std::vector<string> field_flags;
if (descriptor->is_repeated()) field_flags.push_back("GPBFieldRepeated");
if (descriptor->is_required()) field_flags.push_back("GPBFieldRequired");
if (descriptor->is_optional()) field_flags.push_back("GPBFieldOptional");
if (descriptor->is_packed()) field_flags.push_back("GPBFieldPacked");
// ObjC custom flags.
if (descriptor->has_default_value())
field_flags.push_back("GPBFieldHasDefaultValue");
if (needs_custom_name) field_flags.push_back("GPBFieldTextFormatNameCustom");
if (descriptor->type() == FieldDescriptor::TYPE_ENUM) {
field_flags.push_back("GPBFieldHasEnumDescriptor");
}
(*variables)["fieldflags"] = BuildFlagsString(field_flags);
(*variables)["default"] = DefaultValue(descriptor);
(*variables)["default_name"] = GPBGenericValueFieldName(descriptor);
(*variables)["dataTypeSpecific_name"] = "className";
(*variables)["dataTypeSpecific_value"] = "NULL";
(*variables)["storage_offset_value"] =
"(uint32_t)offsetof(" + classname + "__storage_, " + camel_case_name + ")";
(*variables)["storage_offset_comment"] = "";
// Clear some common things so they can be set just when needed.
(*variables)["storage_attribute"] = "";
}
} // namespace
FieldGenerator* FieldGenerator::Make(const FieldDescriptor* field,
const Options& options) {
FieldGenerator* result = NULL;
if (field->is_repeated()) {
switch (GetObjectiveCType(field)) {
case OBJECTIVECTYPE_MESSAGE: {
if (field->is_map()) {
result = new MapFieldGenerator(field, options);
} else {
result = new RepeatedMessageFieldGenerator(field, options);
}
break;
}
case OBJECTIVECTYPE_ENUM:
result = new RepeatedEnumFieldGenerator(field, options);
break;
default:
result = new RepeatedPrimitiveFieldGenerator(field, options);
break;
}
} else {
switch (GetObjectiveCType(field)) {
case OBJECTIVECTYPE_MESSAGE: {
result = new MessageFieldGenerator(field, options);
break;
}
case OBJECTIVECTYPE_ENUM:
result = new EnumFieldGenerator(field, options);
break;
default:
if (IsReferenceType(field)) {
result = new PrimitiveObjFieldGenerator(field, options);
} else {
result = new PrimitiveFieldGenerator(field, options);
}
break;
}
}
result->FinishInitialization();
return result;
}
FieldGenerator::FieldGenerator(const FieldDescriptor* descriptor,
const Options& options)
: descriptor_(descriptor) {
SetCommonFieldVariables(descriptor, &variables_);
}
FieldGenerator::~FieldGenerator() {}
void FieldGenerator::GenerateFieldNumberConstant(io::Printer* printer) const {
printer->Print(
variables_,
"$field_number_name$ = $field_number$,\n");
}
void FieldGenerator::GenerateCFunctionDeclarations(
io::Printer* printer) const {
// Nothing
}
void FieldGenerator::GenerateCFunctionImplementations(
io::Printer* printer) const {
// Nothing
}
void FieldGenerator::DetermineForwardDeclarations(
set<string>* fwd_decls) const {
// Nothing
}
void FieldGenerator::GenerateFieldDescription(
io::Printer* printer, bool include_default) const {
// Printed in the same order as the structure decl.
if (include_default) {
printer->Print(
variables_,
"{\n"
" .defaultValue.$default_name$ = $default$,\n"
" .core.name = \"$name$\",\n"
" .core.dataTypeSpecific.$dataTypeSpecific_name$ = $dataTypeSpecific_value$,\n"
" .core.number = $field_number_name$,\n"
" .core.hasIndex = $has_index$,\n"
" .core.offset = $storage_offset_value$,$storage_offset_comment$\n"
" .core.flags = $fieldflags$,\n"
" .core.dataType = GPBDataType$field_type$,\n"
"},\n");
} else {
printer->Print(
variables_,
"{\n"
" .name = \"$name$\",\n"
" .dataTypeSpecific.$dataTypeSpecific_name$ = $dataTypeSpecific_value$,\n"
" .number = $field_number_name$,\n"
" .hasIndex = $has_index$,\n"
" .offset = $storage_offset_value$,$storage_offset_comment$\n"
" .flags = $fieldflags$,\n"
" .dataType = GPBDataType$field_type$,\n"
"},\n");
}
}
void FieldGenerator::SetRuntimeHasBit(int has_index) {
variables_["has_index"] = SimpleItoa(has_index);
}
void FieldGenerator::SetNoHasBit(void) {
variables_["has_index"] = "GPBNoHasBit";
}
int FieldGenerator::ExtraRuntimeHasBitsNeeded(void) const {
return 0;
}
void FieldGenerator::SetExtraRuntimeHasBitsBase(int index_base) {
// NOTE: src/google/protobuf/compiler/plugin.cc makes use of cerr for some
// error cases, so it seems to be ok to use as a back door for errors.
cerr << "Error: should have overriden SetExtraRuntimeHasBitsBase()." << endl;
cerr.flush();
abort();
}
void FieldGenerator::SetOneofIndexBase(int index_base) {
if (descriptor_->containing_oneof() != NULL) {
int index = descriptor_->containing_oneof()->index() + index_base;
// Flip the sign to mark it as a oneof.
variables_["has_index"] = SimpleItoa(-index);
}
}
void FieldGenerator::FinishInitialization(void) {
// If "property_type" wasn't set, make it "storage_type".
if ((variables_.find("property_type") == variables_.end()) &&
(variables_.find("storage_type") != variables_.end())) {
variables_["property_type"] = variable("storage_type");
}
}
SingleFieldGenerator::SingleFieldGenerator(const FieldDescriptor* descriptor,
const Options& options)
: FieldGenerator(descriptor, options) {
// Nothing
}
SingleFieldGenerator::~SingleFieldGenerator() {}
void SingleFieldGenerator::GenerateFieldStorageDeclaration(
io::Printer* printer) const {
printer->Print(variables_, "$storage_type$ $name$;\n");
}
void SingleFieldGenerator::GeneratePropertyDeclaration(
io::Printer* printer) const {
printer->Print(variables_, "$comments$");
printer->Print(
variables_,
"@property(nonatomic, readwrite) $property_type$ $name$$deprecated_attribute$;\n"
"\n");
if (WantsHasProperty()) {
printer->Print(
variables_,
"@property(nonatomic, readwrite) BOOL has$capitalized_name$$deprecated_attribute$;\n");
}
}
void SingleFieldGenerator::GeneratePropertyImplementation(
io::Printer* printer) const {
if (WantsHasProperty()) {
printer->Print(variables_, "@dynamic has$capitalized_name$, $name$;\n");
} else {
printer->Print(variables_, "@dynamic $name$;\n");
}
}
bool SingleFieldGenerator::WantsHasProperty(void) const {
if (descriptor_->containing_oneof() != NULL) {
// If in a oneof, it uses the oneofcase instead of a has bit.
return false;
}
if (HasFieldPresence(descriptor_->file())) {
// In proto1/proto2, every field has a has_$name$() method.
return true;
}
return false;
}
bool SingleFieldGenerator::RuntimeUsesHasBit(void) const {
if (descriptor_->containing_oneof() != NULL) {
// The oneof tracks what is set instead.
return false;
}
return true;
}
ObjCObjFieldGenerator::ObjCObjFieldGenerator(const FieldDescriptor* descriptor,
const Options& options)
: SingleFieldGenerator(descriptor, options) {
variables_["property_storage_attribute"] = "strong";
if (IsRetainedName(variables_["name"])) {
variables_["storage_attribute"] = " NS_RETURNS_NOT_RETAINED";
}
}
ObjCObjFieldGenerator::~ObjCObjFieldGenerator() {}
void ObjCObjFieldGenerator::GenerateFieldStorageDeclaration(
io::Printer* printer) const {
printer->Print(variables_, "$storage_type$ *$name$;\n");
}
void ObjCObjFieldGenerator::GeneratePropertyDeclaration(
io::Printer* printer) const {
// Differs from SingleFieldGenerator::GeneratePropertyDeclaration() in that
// it uses pointers and deals with Objective C's rules around storage name
// conventions (init*, new*, etc.)
printer->Print(variables_, "$comments$");
printer->Print(
variables_,
"@property(nonatomic, readwrite, $property_storage_attribute$, null_resettable) $property_type$ *$name$$storage_attribute$$deprecated_attribute$;\n");
if (WantsHasProperty()) {
printer->Print(
variables_,
"/// Test to see if @c $name$ has been set.\n"
"@property(nonatomic, readwrite) BOOL has$capitalized_name$$deprecated_attribute$;\n");
}
if (IsInitName(variables_.find("name")->second)) {
// If property name starts with init we need to annotate it to get past ARC.
// http://stackoverflow.com/questions/18723226/how-do-i-annotate-an-objective-c-property-with-an-objc-method-family/18723227#18723227
printer->Print(variables_,
"- ($property_type$ *)$name$ GPB_METHOD_FAMILY_NONE$deprecated_attribute$;\n");
}
printer->Print("\n");
}
RepeatedFieldGenerator::RepeatedFieldGenerator(
const FieldDescriptor* descriptor, const Options& options)
: ObjCObjFieldGenerator(descriptor, options) {
// Default to no comment and let the cases needing it fill it in.
variables_["array_comment"] = "";
}
RepeatedFieldGenerator::~RepeatedFieldGenerator() {}
void RepeatedFieldGenerator::FinishInitialization(void) {
FieldGenerator::FinishInitialization();
if (variables_.find("array_property_type") == variables_.end()) {
variables_["array_property_type"] = variable("array_storage_type");
}
}
void RepeatedFieldGenerator::GenerateFieldStorageDeclaration(
io::Printer* printer) const {
printer->Print(variables_, "$array_storage_type$ *$name$;\n");
}
void RepeatedFieldGenerator::GeneratePropertyImplementation(
io::Printer* printer) const {
printer->Print(variables_, "@dynamic $name$, $name$_Count;\n");
}
void RepeatedFieldGenerator::GeneratePropertyDeclaration(
io::Printer* printer) const {
// Repeated fields don't need the has* properties, but they do expose a
// *Count (to check without autocreation). So for the field property we need
// the same logic as ObjCObjFieldGenerator::GeneratePropertyDeclaration() for
// dealing with needing Objective C's rules around storage name conventions
// (init*, new*, etc.)
printer->Print(
variables_,
"$comments$"
"$array_comment$"
"@property(nonatomic, readwrite, strong, null_resettable) $array_property_type$ *$name$$storage_attribute$$deprecated_attribute$;\n"
"/// The number of items in @c $name$ without causing the array to be created.\n"
"@property(nonatomic, readonly) NSUInteger $name$_Count$deprecated_attribute$;\n");
if (IsInitName(variables_.find("name")->second)) {
// If property name starts with init we need to annotate it to get past ARC.
// http://stackoverflow.com/questions/18723226/how-do-i-annotate-an-objective-c-property-with-an-objc-method-family/18723227#18723227
printer->Print(variables_,
"- ($array_property_type$ *)$name$ GPB_METHOD_FAMILY_NONE$deprecated_attribute$;\n");
}
printer->Print("\n");
}
bool RepeatedFieldGenerator::WantsHasProperty(void) const {
// Consumer check the array size/existance rather than a has bit.
return false;
}
bool RepeatedFieldGenerator::RuntimeUsesHasBit(void) const {
return false; // The array having anything is what is used.
}
FieldGeneratorMap::FieldGeneratorMap(const Descriptor* descriptor,
const Options& options)
: descriptor_(descriptor),
field_generators_(
new scoped_ptr<FieldGenerator>[descriptor->field_count()]),
extension_generators_(
new scoped_ptr<FieldGenerator>[descriptor->extension_count()]) {
// Construct all the FieldGenerators.
for (int i = 0; i < descriptor->field_count(); i++) {
field_generators_[i].reset(
FieldGenerator::Make(descriptor->field(i), options));
}
for (int i = 0; i < descriptor->extension_count(); i++) {
extension_generators_[i].reset(
FieldGenerator::Make(descriptor->extension(i), options));
}
}
FieldGeneratorMap::~FieldGeneratorMap() {}
const FieldGenerator& FieldGeneratorMap::get(
const FieldDescriptor* field) const {
GOOGLE_CHECK_EQ(field->containing_type(), descriptor_);
return *field_generators_[field->index()];
}
const FieldGenerator& FieldGeneratorMap::get_extension(int index) const {
return *extension_generators_[index];
}
int FieldGeneratorMap::CalculateHasBits(void) {
int total_bits = 0;
for (int i = 0; i < descriptor_->field_count(); i++) {
if (field_generators_[i]->RuntimeUsesHasBit()) {
field_generators_[i]->SetRuntimeHasBit(total_bits);
++total_bits;
} else {
field_generators_[i]->SetNoHasBit();
}
int extra_bits = field_generators_[i]->ExtraRuntimeHasBitsNeeded();
if (extra_bits) {
field_generators_[i]->SetExtraRuntimeHasBitsBase(total_bits);
total_bits += extra_bits;
}
}
return total_bits;
}
void FieldGeneratorMap::SetOneofIndexBase(int index_base) {
for (int i = 0; i < descriptor_->field_count(); i++) {
field_generators_[i]->SetOneofIndexBase(index_base);
}
}
bool FieldGeneratorMap::DoesAnyFieldHaveNonZeroDefault(void) const {
for (int i = 0; i < descriptor_->field_count(); i++) {
if (HasNonZeroDefaultValue(descriptor_->field(i))) {
return true;
}
}
return false;
}
} // namespace objectivec
} // namespace compiler
} // namespace protobuf
} // namespace google
| [
"helder_m_p_novais@hotmail.com"
] | helder_m_p_novais@hotmail.com |
3434bd9be3e3221be935a4248992a44fa05c0f2a | 03c5a90740816ce6070b95d6ced4691ae2766470 | /lib/LuaPlugin.cpp | 9227281e53462cbf1e39eb8622a3188b17f050de | [
"MIT"
] | permissive | handicraftsman/particlebot | 201c79665b750323f3f7884d433d4850356dd412 | 9ebb404ec98c2721a04a5ffc3e005b551ec0a808 | refs/heads/master | 2021-04-25T18:51:39.121230 | 2018-03-30T20:14:36 | 2018-03-30T20:14:36 | 121,540,864 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 31,556 | cpp | #define PB_PLUGIN
#include "include.hpp"
static std::string find_path_to_plugin(std::string name) {
const std::vector<std::string> paths {
"./pb-" + name + ".lua",
"./pb-" + name + "/main.lua",
"../pb-" + name + ".lua",
"../pb-" + name + "/main.lua",
"/usr/share/pb-" + name + ".lua",
"/usr/share/pb-" + name + "/main.lua",
"/usr/local/share/pb-" + name + ".lua",
"/usr/local/share/pb-" + name + "/main.lua"
};
for (std::string path : paths) {
if (std::ifstream(path).good())
return path;
}
throw std::runtime_error("Unable to find lua plugin " + name);
}
static PB::LuaPlugin* get_self(lua_State* L) {
lua_getglobal(L, "__pb_addr");
void** s = (void**) lua_touserdata(L, -1);
lua_pop(L, 1);
return (PB::LuaPlugin*) *s;
}
static std::map<PB::EventType, std::string> names {
{ PB::EventType::Event, "Event" },
{ PB::EventType::TestEvent, "TestEvent" },
{ PB::EventType::ConnectEvent, "ConnectEvent" },
{ PB::EventType::DisconnectEvent, "DisconnectEvent" },
{ PB::EventType::IRCMessageEvent, "IRCMessageEvent" },
{ PB::EventType::CodeEvent, "CodeEvent" },
{ PB::EventType::PingEvent, "PingEvent" },
{ PB::EventType::WHOREPLYEvent, "WHOREPLYEvent" },
{ PB::EventType::JoinEvent, "JoinEvent" },
{ PB::EventType::PartEvent, "PartEvent" },
{ PB::EventType::NickEvent, "NickEvent" },
{ PB::EventType::PRIVMSGEvent, "PRIVMSGEvent" },
{ PB::EventType::PRIVMSGEvent, "CTCPEvent" },
{ PB::EventType::NOTICEEvent, "NOTICEEvent" },
{ PB::EventType::CommandEvent, "CommandEvent" },
};
static bool get_table_value(lua_State* L, std::string type) {
lua_pushnil(L);
while (lua_next(L, -2)) {
if (lua_isstring(L, -2) && type == std::string(lua_tostring(L, -2)))
return true;
lua_pop(L, 1);
}
lua_pop(L, 1);
return false;
}
void stackdump_g(lua_State* l) {
int i;
int top = lua_gettop(l);
printf("total in stack %d\n",top);
for (i = 1; i <= top; i++) {
int t = lua_type(l, i);
printf(" ");
switch (t) {
case LUA_TSTRING:
printf("string: '%s'\n", lua_tostring(l, i));
break;
case LUA_TBOOLEAN:
printf("boolean %s\n",lua_toboolean(l, i) ? "true" : "false");
break;
case LUA_TNUMBER:
printf("number: %g\n", lua_tonumber(l, i));
break;
default:
printf("%s\n", lua_typename(l, t));
break;
}
}
printf("\n");
}
static void push_event_table(lua_State* L, PB::Event* _e) {
switch (_e->type()) {
case PB::EventType::TestEvent: {
lua_createtable(L, 0, 1);
lua_pushstring(L, ((PB::TestEvent*) _e)->str.c_str());
lua_setfield(L, -2, "str");
break;
}
case PB::EventType::ConnectEvent: {
lua_createtable(L, 0, 1);
lua_pushstring(L, ((PB::ConnectEvent*) _e)->socket->name.c_str());
lua_setfield(L, -2, "socket");
break;
}
case PB::EventType::DisconnectEvent: {
lua_createtable(L, 0, 1);
lua_pushstring(L, ((PB::DisconnectEvent*) _e)->socket->name.c_str());
lua_setfield(L, -2, "socket");
break;
}
case PB::EventType::IRCMessageEvent: {
PB::IRCMessageEvent* e = (PB::IRCMessageEvent*) _e;
lua_createtable(L, 0, 2);
lua_pushstring(L, e->socket->name.c_str());
lua_setfield(L, -2, "socket");
lua_pushstring(L, e->raw_msg.c_str());
lua_setfield(L, -2, "raw_msg");
break;
}
case PB::EventType::CodeEvent: {
PB::CodeEvent* e = (PB::CodeEvent*) _e;
lua_createtable(L, 0, 3);
lua_pushstring(L, e->socket->name.c_str());
lua_setfield(L, -2, "socket");
lua_pushstring(L, e->code.c_str());
lua_setfield(L, -2, "code");
lua_pushstring(L, e->extra.c_str());
lua_setfield(L, -2, "extra");
break;
}
case PB::EventType::PingEvent: {
PB::PingEvent* e = (PB::PingEvent*) _e;
lua_createtable(L, 0, 2);
lua_pushstring(L, e->socket->name.c_str());
lua_setfield(L, -2, "socket");
lua_pushstring(L, e->target.c_str());
lua_setfield(L, -2, "target");
break;
}
case PB::EventType::WHOREPLYEvent: {
PB::WHOREPLYEvent* e = (PB::WHOREPLYEvent*) _e;
lua_createtable(L, 0, 4);
lua_pushstring(L, e->socket->name.c_str());
lua_setfield(L, -2, "socket");
lua_pushstring(L, e->nick.c_str());
lua_setfield(L, -2, "nick");
lua_pushstring(L, e->user.c_str());
lua_setfield(L, -2, "user");
lua_pushstring(L, e->host.c_str());
lua_setfield(L, -2, "host");
break;
}
case PB::EventType::JoinEvent: {
PB::JoinEvent* e = (PB::JoinEvent*) _e;
lua_createtable(L, 0, 4);
lua_pushstring(L, e->socket->name.c_str());
lua_setfield(L, -2, "socket");
lua_pushstring(L, e->nick.c_str());
lua_setfield(L, -2, "nick");
lua_pushstring(L, e->user.c_str());
lua_setfield(L, -2, "user");
lua_pushstring(L, e->host.c_str());
lua_setfield(L, -2, "host");
break;
}
case PB::EventType::PartEvent: {
PB::PartEvent* e = (PB::PartEvent*) _e;
lua_createtable(L, 0, 5);
lua_pushstring(L, e->socket->name.c_str());
lua_setfield(L, -2, "socket");
lua_pushstring(L, e->nick.c_str());
lua_setfield(L, -2, "nick");
lua_pushstring(L, e->user.c_str());
lua_setfield(L, -2, "user");
lua_pushstring(L, e->host.c_str());
lua_setfield(L, -2, "host");
lua_pushstring(L, e->reason.c_str());
lua_setfield(L, -2, "reason");
break;
}
case PB::EventType::NickEvent: {
PB::NickEvent* e = (PB::NickEvent*) _e;
lua_createtable(L, 0, 5);
lua_pushstring(L, e->socket->name.c_str());
lua_setfield(L, -2, "socket");
lua_pushstring(L, e->nick.c_str());
lua_setfield(L, -2, "nick");
lua_pushstring(L, e->user.c_str());
lua_setfield(L, -2, "user");
lua_pushstring(L, e->host.c_str());
lua_setfield(L, -2, "host");
lua_pushstring(L, e->new_nick.c_str());
lua_setfield(L, -2, "new_nick");
break;
}
case PB::EventType::PRIVMSGEvent: {
PB::PRIVMSGEvent* e = (PB::PRIVMSGEvent*) _e;
lua_createtable(L, 0, 7);
lua_pushstring(L, e->socket->name.c_str());
lua_setfield(L, -2, "socket");
lua_pushstring(L, e->nick.c_str());
lua_setfield(L, -2, "nick");
lua_pushstring(L, e->user.c_str());
lua_setfield(L, -2, "user");
lua_pushstring(L, e->host.c_str());
lua_setfield(L, -2, "host");
lua_pushstring(L, e->target.c_str());
lua_setfield(L, -2, "target");
lua_pushstring(L, e->reply_to.c_str());
lua_setfield(L, -2, "reply_to");
lua_pushstring(L, e->message.c_str());
lua_setfield(L, -2, "message");
break;
}
case PB::EventType::CTCPEvent: {
PB::CTCPEvent* e = (PB::CTCPEvent*) _e;
lua_createtable(L, 0, 7);
lua_pushstring(L, e->socket->name.c_str());
lua_setfield(L, -2, "socket");
lua_pushstring(L, e->nick.c_str());
lua_setfield(L, -2, "nick");
lua_pushstring(L, e->user.c_str());
lua_setfield(L, -2, "user");
lua_pushstring(L, e->host.c_str());
lua_setfield(L, -2, "host");
lua_pushstring(L, e->target.c_str());
lua_setfield(L, -2, "target");
lua_pushstring(L, e->reply_to.c_str());
lua_setfield(L, -2, "reply_to");
lua_createtable(L, 0, e->split.size());
int i = 1;
for (std::string s : e->split) {
lua_pushinteger(L, i);
lua_pushstring(L, s.c_str());
lua_settable(L, -3);
++i;
}
lua_setfield(L, -2, "split");
break;
}
case PB::EventType::NOTICEEvent: {
PB::NOTICEEvent* e = (PB::NOTICEEvent*) _e;
lua_createtable(L, 0, 6);
lua_pushstring(L, e->socket->name.c_str());
lua_setfield(L, -2, "socket");
lua_pushstring(L, e->nick.c_str());
lua_setfield(L, -2, "nick");
lua_pushstring(L, e->user.c_str());
lua_setfield(L, -2, "user");
lua_pushstring(L, e->host.c_str());
lua_setfield(L, -2, "host");
lua_pushstring(L, e->target.c_str());
lua_setfield(L, -2, "target");
lua_pushstring(L, e->message.c_str());
lua_setfield(L, -2, "message");
break;
}
case PB::EventType::CommandEvent: {
PB::CommandEvent* e = (PB::CommandEvent*) _e;
lua_createtable(L, 0, 9);
lua_pushstring(L, e->socket->name.c_str());
lua_setfield(L, -2, "socket");
lua_pushstring(L, e->nick.c_str());
lua_setfield(L, -2, "nick");
lua_pushstring(L, e->user.c_str());
lua_setfield(L, -2, "user");
lua_pushstring(L, e->host.c_str());
lua_setfield(L, -2, "host");
lua_pushstring(L, e->target.c_str());
lua_setfield(L, -2, "target");
lua_pushstring(L, e->reply_to.c_str());
lua_setfield(L, -2, "reply_to");
lua_pushstring(L, e->message.c_str());
lua_setfield(L, -2, "message");
lua_pushstring(L, e->command.c_str());
lua_setfield(L, -2, "command");
lua_createtable(L, 0, e->split.size());
int i = 1;
for (std::string s : e->split) {
lua_pushinteger(L, i);
lua_pushstring(L, s.c_str());
lua_settable(L, -3);
++i;
}
lua_setfield(L, -2, "split");
break;
}
default:
throw std::runtime_error("fired base event or there's no event handler for " + names[_e->type()]);
break;
}
}
void PB::LuaPlugin::handle_event(std::shared_ptr<Event> e) {
std::lock_guard<std::mutex> lock(lmtx);
lua_getglobal(L, "__pb_event_handlers");
if (get_table_value(L, names[e->type()]) && lua_isfunction(L, -1)) {
push_event_table(L, e.get());
if (lua_pcall(L, 1, 0, 0))
log.error("Lua error: %s", lua_tostring(L, -1));
}
lua_settop(L, 0);
}
int lfunc_command(lua_State* L) {
PB::LuaPlugin* self = get_self(L);
std::string name;
std::string group;
PB::CommandInfo info;
lua_pushnil(L);
while (lua_next(L, 1)) {
if (lua_isstring(L, 2)) {
std::string key(lua_tostring(L, 2));
if (lua_isnumber(L, 3)) {
int value(lua_tonumber(L, 3));
if (key == "level") {
info.level = value;
} else if (key == "cooldown") {
info.cooldown = value;
}
} else if (lua_isstring(L, 3)) {
std::string value(lua_tostring(L, 3));
if (key == "name") {
name = value;
} else if (key == "group") {
group = value;
} else if (key == "description") {
info.description = value;
} else if (key == "usage") {
info.usage = value;
}
}
}
lua_pop(L, 1);
}
lua_pop(L, 1);
info.handler = [self, name, group] (PB::CommandEvent* e) noexcept {
std::lock_guard<std::mutex> lock(self->lmtx);
lua_getglobal(self->L, "__pb_command_handlers");
lua_getfield(self->L, -1, group.c_str());
if (!lua_istable(self->L, -1)) {
std::cerr << "__pb_command_handlers[group] is not table" << std::endl;
lua_settop(self->L, 0);
return;
}
lua_getfield(self->L, -1, name.c_str());
if (!lua_isfunction(self->L, -1)) {
std::cerr << "__pb_command_handlers[group][name] is not function" << std::endl;
lua_settop(self->L, 0);
return;
}
push_event_table(self->L, e);
if (lua_pcall(self->L, 1, 0, 0))
std::cerr << std::string(lua_tostring(self->L, -1)) << std::endl;
lua_settop(self->L, 0);
};
(*self->commands)[group][name] = info;
return 0;
}
static int lfunc_write(lua_State* L) {
PB::LuaPlugin* self = get_self(L);
if (lua_gettop(L) != 2 || !lua_isstring(L, 1) || !lua_isstring(L, 2)) {
lua_pushstring(L, "lfunc_write: Invalid arguments"); lua_error(L);
return 0;
}
self->plugin_manager->bot->sockets[std::string(lua_tostring(L, 1))]->write(std::string(lua_tostring(L, 2)));
return 0;
}
static int lfunc_join(lua_State* L) {
PB::LuaPlugin* self = get_self(L);
if (lua_gettop(L) != 2 || !lua_isstring(L, 1) || !lua_isstring(L, 2)) {
lua_pushstring(L, "lfunc_join: Invalid arguments"); lua_error(L);
return 0;
}
self->plugin_manager->bot->sockets[std::string(lua_tostring(L, 1))]->join(std::string(lua_tostring(L, 2)));
return 0;
}
static int lfunc_part(lua_State* L) {
PB::LuaPlugin* self = get_self(L);
if (lua_gettop(L) != 3 || !lua_isstring(L, 1) || !lua_isstring(L, 2) || !lua_isstring(L, 3)) {
lua_pushstring(L, "lfunc_part: Invalid arguments"); lua_error(L);
return 0;
}
self->plugin_manager->bot->sockets[std::string(lua_tostring(L, 1))]->part(std::string(lua_tostring(L, 2)), std::string(lua_tostring(L, 3)));
return 0;
}
static int lfunc_nick(lua_State* L) {
PB::LuaPlugin* self = get_self(L);
if (lua_gettop(L) != 2 || !lua_isstring(L, 1) || !lua_isstring(L, 2)) {
lua_pushstring(L, "lfunc_nick: Invalid arguments"); lua_error(L);
return 0;
}
self->plugin_manager->bot->sockets[std::string(lua_tostring(L, 1))]->change_nick(std::string(lua_tostring(L, 2)));
return 0;
}
static int lfunc_who(lua_State* L) {
PB::LuaPlugin* self = get_self(L);
if (lua_gettop(L) != 2 || !lua_isstring(L, 1) || !lua_isstring(L, 2)) {
lua_pushstring(L, "lfunc_who: Invalid arguments"); lua_error(L);
return 0;
}
self->plugin_manager->bot->sockets[std::string(lua_tostring(L, 1))]->who(std::string(lua_tostring(L, 2)));
return 0;
}
static int lfunc_privmsg(lua_State* L) {
PB::LuaPlugin* self = get_self(L);
if (lua_gettop(L) != 3 || !lua_isstring(L, 1) || !lua_isstring(L, 2) || !lua_isstring(L, 3)) {
lua_pushstring(L, "lfunc_privmsg: Invalid arguments"); lua_error(L);
return 0;
}
self->plugin_manager->bot->sockets[std::string(lua_tostring(L, 1))]->privmsg(std::string(lua_tostring(L, 2)), std::string(lua_tostring(L, 3)));
return 0;
}
static int lfunc_ctcp(lua_State* L) {
PB::LuaPlugin* self = get_self(L);
if (lua_gettop(L) != 3 || !lua_isstring(L, 1) || !lua_isstring(L, 2) || !lua_isstring(L, 3)) {
lua_pushstring(L, "lfunc_ctcp: Invalid arguments"); lua_error(L);
return 0;
}
self->plugin_manager->bot->sockets[std::string(lua_tostring(L, 1))]->ctcp(std::string(lua_tostring(L, 2)), std::string(lua_tostring(L, 3)));
return 0;
}
static int lfunc_notice(lua_State* L) {
PB::LuaPlugin* self = get_self(L);
if (lua_gettop(L) != 3 || !lua_isstring(L, 1) || !lua_isstring(L, 2) || !lua_isstring(L, 3)) {
lua_pushstring(L, "lfunc_notice: Invalid arguments"); lua_error(L);
return 0;
}
self->plugin_manager->bot->sockets[std::string(lua_tostring(L, 1))]->notice(std::string(lua_tostring(L, 2)), std::string(lua_tostring(L, 3)));
return 0;
}
static int lfunc_nctcp(lua_State* L) {
PB::LuaPlugin* self = get_self(L);
if (lua_gettop(L) != 3 || !lua_isstring(L, 1) || !lua_isstring(L, 2) || !lua_isstring(L, 3)) {
lua_pushstring(L, "lfunc_nctcp: Invalid arguments"); lua_error(L);
return 0;
}
self->plugin_manager->bot->sockets[std::string(lua_tostring(L, 1))]->nctcp(std::string(lua_tostring(L, 2)), std::string(lua_tostring(L, 3)));
return 0;
}
static int lfunc_mode(lua_State* L) {
PB::LuaPlugin* self = get_self(L);
if (lua_gettop(L) != 3 || !lua_isstring(L, 1) || !lua_isstring(L, 2) || !lua_isstring(L, 3)) {
lua_pushstring(L, "lfunc_mode Invalid arguments"); lua_error(L);
return 0;
}
self->plugin_manager->bot->sockets[std::string(lua_tostring(L, 1))]->mode(std::string(lua_tostring(L, 2)), std::string(lua_tostring(L, 3)));
return 0;
}
static int lfunc_kick(lua_State* L) {
PB::LuaPlugin* self = get_self(L);
if (lua_gettop(L) != 4 || !lua_isstring(L, 1) || !lua_isstring(L, 2) || !lua_isstring(L, 3) || !lua_isstring(L, 4)) {
lua_pushstring(L, "lfunc_kick Invalid arguments"); lua_error(L);
return 0;
}
self->plugin_manager->bot->sockets[std::string(lua_tostring(L, 1))]->kick(
std::string(lua_tostring(L, 2)),
std::string(lua_tostring(L, 3)),
std::string(lua_tostring(L, 4))
);
return 0;
}
static int lfunc_remove(lua_State* L) {
PB::LuaPlugin* self = get_self(L);
if (lua_gettop(L) != 4 || !lua_isstring(L, 1) || !lua_isstring(L, 2) || !lua_isstring(L, 3) || !lua_isstring(L, 4)) {
lua_pushstring(L, "lfunc_remove Invalid arguments"); lua_error(L);
return 0;
}
self->plugin_manager->bot->sockets[std::string(lua_tostring(L, 1))]->remove(
std::string(lua_tostring(L, 2)),
std::string(lua_tostring(L, 3)),
std::string(lua_tostring(L, 4))
);
return 0;
}
static int lfunc_op(lua_State* L) {
PB::LuaPlugin* self = get_self(L);
if (lua_gettop(L) != 3 || !lua_isstring(L, 1) || !lua_isstring(L, 2) || !lua_isstring(L, 3)) {
lua_pushstring(L, "lfunc_op: Invalid arguments"); lua_error(L);
return 0;
}
self->plugin_manager->bot->sockets[std::string(lua_tostring(L, 1))]->op(std::string(lua_tostring(L, 2)), std::string(lua_tostring(L, 3)));
return 0;
}
static int lfunc_deop(lua_State* L) {
PB::LuaPlugin* self = get_self(L);
if (lua_gettop(L) != 3 || !lua_isstring(L, 1) || !lua_isstring(L, 2) || !lua_isstring(L, 3)) {
lua_pushstring(L, "lfunc_deop: Invalid arguments"); lua_error(L);
return 0;
}
self->plugin_manager->bot->sockets[std::string(lua_tostring(L, 1))]->deop(std::string(lua_tostring(L, 2)), std::string(lua_tostring(L, 3)));
return 0;
}
static int lfunc_hop(lua_State* L) {
PB::LuaPlugin* self = get_self(L);
if (lua_gettop(L) != 3 || !lua_isstring(L, 1) || !lua_isstring(L, 2) || !lua_isstring(L, 3)) {
lua_pushstring(L, "lfunc_hop: Invalid arguments"); lua_error(L);
return 0;
}
self->plugin_manager->bot->sockets[std::string(lua_tostring(L, 1))]->hop(std::string(lua_tostring(L, 2)), std::string(lua_tostring(L, 3)));
return 0;
}
static int lfunc_dehop(lua_State* L) {
PB::LuaPlugin* self = get_self(L);
if (lua_gettop(L) != 3 || !lua_isstring(L, 1) || !lua_isstring(L, 2) || !lua_isstring(L, 3)) {
lua_pushstring(L, "lfunc_dehop: Invalid arguments"); lua_error(L);
return 0;
}
self->plugin_manager->bot->sockets[std::string(lua_tostring(L, 1))]->dehop(std::string(lua_tostring(L, 2)), std::string(lua_tostring(L, 3)));
return 0;
}
static int lfunc_voice(lua_State* L) {
PB::LuaPlugin* self = get_self(L);
if (lua_gettop(L) != 3 || !lua_isstring(L, 1) || !lua_isstring(L, 2) || !lua_isstring(L, 3)) {
lua_pushstring(L, "lfunc_voice: Invalid arguments"); lua_error(L);
return 0;
}
self->plugin_manager->bot->sockets[std::string(lua_tostring(L, 1))]->voice(std::string(lua_tostring(L, 2)), std::string(lua_tostring(L, 3)));
return 0;
}
static int lfunc_devoice(lua_State* L) {
PB::LuaPlugin* self = get_self(L);
if (lua_gettop(L) != 3 || !lua_isstring(L, 1) || !lua_isstring(L, 2) || !lua_isstring(L, 3)) {
lua_pushstring(L, "lfunc_devoice: Invalid arguments"); lua_error(L);
return 0;
}
self->plugin_manager->bot->sockets[std::string(lua_tostring(L, 1))]->devoice(std::string(lua_tostring(L, 2)), std::string(lua_tostring(L, 3)));
return 0;
}
static int lfunc_quiet(lua_State* L) {
PB::LuaPlugin* self = get_self(L);
if (lua_gettop(L) != 3 || !lua_isstring(L, 1) || !lua_isstring(L, 2) || !lua_isstring(L, 3)) {
lua_pushstring(L, "lfunc_quiet: Invalid arguments"); lua_error(L);
return 0;
}
self->plugin_manager->bot->sockets[std::string(lua_tostring(L, 1))]->quiet(std::string(lua_tostring(L, 2)), std::string(lua_tostring(L, 3)));
return 0;
}
static int lfunc_unquiet(lua_State* L) {
PB::LuaPlugin* self = get_self(L);
if (lua_gettop(L) != 3 || !lua_isstring(L, 1) || !lua_isstring(L, 2) || !lua_isstring(L, 3)) {
lua_pushstring(L, "lfunc_unquiet: Invalid arguments"); lua_error(L);
return 0;
}
self->plugin_manager->bot->sockets[std::string(lua_tostring(L, 1))]->unquiet(std::string(lua_tostring(L, 2)), std::string(lua_tostring(L, 3)));
return 0;
}
static int lfunc_ban(lua_State* L) {
PB::LuaPlugin* self = get_self(L);
if (lua_gettop(L) != 3 || !lua_isstring(L, 1) || !lua_isstring(L, 2) || !lua_isstring(L, 3)) {
lua_pushstring(L, "lfunc_ban: Invalid arguments"); lua_error(L);
return 0;
}
self->plugin_manager->bot->sockets[std::string(lua_tostring(L, 1))]->ban(std::string(lua_tostring(L, 2)), std::string(lua_tostring(L, 3)));
return 0;
}
static int lfunc_unban(lua_State* L) {
PB::LuaPlugin* self = get_self(L);
if (lua_gettop(L) != 3 || !lua_isstring(L, 1) || !lua_isstring(L, 2) || !lua_isstring(L, 3)) {
lua_pushstring(L, "lfunc_unban: Invalid arguments"); lua_error(L);
return 0;
}
self->plugin_manager->bot->sockets[std::string(lua_tostring(L, 1))]->unban(std::string(lua_tostring(L, 2)), std::string(lua_tostring(L, 3)));
return 0;
}
static int lfunc_exempt(lua_State* L) {
PB::LuaPlugin* self = get_self(L);
if (lua_gettop(L) != 3 || !lua_isstring(L, 1) || !lua_isstring(L, 2) || !lua_isstring(L, 3)) {
lua_pushstring(L, "lfunc_exempt: Invalid arguments"); lua_error(L);
return 0;
}
self->plugin_manager->bot->sockets[std::string(lua_tostring(L, 1))]->exempt(std::string(lua_tostring(L, 2)), std::string(lua_tostring(L, 3)));
return 0;
}
static int lfunc_unexempt(lua_State* L) {
PB::LuaPlugin* self = get_self(L);
if (lua_gettop(L) != 3 || !lua_isstring(L, 1) || !lua_isstring(L, 2) || !lua_isstring(L, 3)) {
lua_pushstring(L, "lfunc_unexempt: Invalid arguments"); lua_error(L);
return 0;
}
self->plugin_manager->bot->sockets[std::string(lua_tostring(L, 1))]->unexempt(std::string(lua_tostring(L, 2)), std::string(lua_tostring(L, 3)));
return 0;
}
static int lfunc_get_host(lua_State* L) {
PB::LuaPlugin* self = get_self(L);
if (lua_gettop(L) != 1 || !lua_isstring(L, 1)) {
lua_pushstring(L, "lfunc_get_host: Invalid arguments"); lua_error(L);
return 0;
}
lua_pushstring(L, self->plugin_manager->bot->sockets[std::string(lua_tostring(L, 1))]->host.c_str());
return 1;
}
static int lfunc_get_port(lua_State* L) {
PB::LuaPlugin* self = get_self(L);
if (lua_gettop(L) != 1 || !lua_isstring(L, 1)) {
lua_pushstring(L, "lfunc_get_port: Invalid arguments"); lua_error(L);
return 0;
}
lua_pushnumber(L, self->plugin_manager->bot->sockets[std::string(lua_tostring(L, 1))]->port);
return 1;
}
static int lfunc_get_nick(lua_State* L) {
PB::LuaPlugin* self = get_self(L);
if (lua_gettop(L) != 1 || !lua_isstring(L, 1)) {
lua_pushstring(L, "lfunc_get_nick: Invalid arguments"); lua_error(L);
return 0;
}
lua_pushstring(L, self->plugin_manager->bot->sockets[std::string(lua_tostring(L, 1))]->nick.c_str());
return 1;
}
static int lfunc_get_user(lua_State* L) {
PB::LuaPlugin* self = get_self(L);
if (lua_gettop(L) != 1 || !lua_isstring(L, 1)) {
lua_pushstring(L, "lfunc_get_user: Invalid arguments"); lua_error(L);
return 0;
}
lua_pushstring(L, self->plugin_manager->bot->sockets[std::string(lua_tostring(L, 1))]->user.c_str());
return 1;
}
static int lfunc_get_pass(lua_State* L) {
PB::LuaPlugin* self = get_self(L);
if (lua_gettop(L) != 1 || !lua_isstring(L, 1)) {
lua_pushstring(L, "lfunc_get_pass: Invalid arguments"); lua_error(L);
return 0;
}
std::shared_ptr<PB::IRCSocket> sock = self->plugin_manager->bot->sockets[std::string(lua_tostring(L, 1))];
if (sock->has_pass) {
lua_pushstring(L, sock->pass.c_str());
} else {
lua_pushnil(L);
}
return 1;
}
static int lfunc_get_autojoin(lua_State* L) {
PB::LuaPlugin* self = get_self(L);
if (lua_gettop(L) != 1 || !lua_isstring(L, 1)) {
lua_pushstring(L, "lfunc_get_pass: Invalid arguments"); lua_error(L);
return 0;
}
std::shared_ptr<PB::IRCSocket> sock = self->plugin_manager->bot->sockets[std::string(lua_tostring(L, 1))];
lua_createtable(L, 0, sock->autojoin.size());
int i = 1;
for (std::string s : sock->autojoin) {
lua_pushinteger(L, i);
lua_pushstring(L, s.c_str());
lua_settable(L, -3);
++i;
}
return 1;
}
static int lfunc_get_autoowner(lua_State* L) {
PB::LuaPlugin* self = get_self(L);
if (lua_gettop(L) != 1 || !lua_isstring(L, 1)) {
lua_pushstring(L, "lfunc_get_autoowner: Invalid arguments"); lua_error(L);
return 0;
}
std::shared_ptr<PB::IRCSocket> sock = self->plugin_manager->bot->sockets[std::string(lua_tostring(L, 1))];
if (sock->autoowner == std::nullopt) {
lua_pushnil(L);
} else {
lua_pushstring(L, sock->autoowner.value_or("<UNKNOWN>").c_str());
}
return 1;
}
static int lfunc_get_prefix(lua_State* L) {
PB::LuaPlugin* self = get_self(L);
if (lua_gettop(L) != 1 || !lua_isstring(L, 1)) {
lua_pushstring(L, "lfunc_get_prefix: Invalid arguments"); lua_error(L);
return 0;
}
lua_pushstring(L, self->plugin_manager->bot->sockets[std::string(lua_tostring(L, 1))]->prefix.c_str());
return 1;
}
static int lfunc_get_user_info(lua_State* L) {
PB::LuaPlugin* self = get_self(L);
if (lua_gettop(L) != 2 || !lua_isstring(L, 1) || !lua_isstring(L, 2)) {
lua_pushstring(L, "lfunc_get_pass: Invalid arguments"); lua_error(L);
return 0;
}
std::shared_ptr<PB::IRCSocket> sock = self->plugin_manager->bot->sockets[std::string(lua_tostring(L, 1))];
PB::User u = sock->user_cache[std::string(lua_tostring(L, 2))];
lua_createtable(L, 0, 3);
lua_pushstring(L, lua_tostring(L, 2));
lua_setfield(L, -2, "nick");
if (u.user == std::nullopt) {
lua_pushnil(L);
} else {
lua_pushstring(L, u.user.value_or("<UNKNOWN>").c_str());
}
lua_setfield(L, -2, "user");
if (u.host == std::nullopt) {
lua_pushnil(L);
} else {
lua_pushstring(L, u.host.value_or("<UNKNOWN>").c_str());
}
lua_setfield(L, -2, "host");
return 1;
}
static int lfunc_log(lua_State* L) {
PB::LuaPlugin* self = get_self(L);
if (lua_gettop(L) != 1 || !lua_isstring(L, 1)) {
lua_pushstring(L, "lfunc_log: Invalid arguments"); lua_error(L);
return 0;
}
self->log.write("%s", lua_tostring(L, 1));
return 1;
}
static int lfunc_log_debug(lua_State* L) {
PB::LuaPlugin* self = get_self(L);
if (lua_gettop(L) != 1 || !lua_isstring(L, 1)) {
lua_pushstring(L, "lfunc_log_debug: Invalid arguments"); lua_error(L);
return 0;
}
self->log.debug("%s", lua_tostring(L, 1));
return 1;
}
static int lfunc_log_io(lua_State* L) {
PB::LuaPlugin* self = get_self(L);
if (lua_gettop(L) != 1 || !lua_isstring(L, 1)) {
lua_pushstring(L, "lfunc_log_io: Invalid arguments"); lua_error(L);
return 0;
}
self->log.io("%s", lua_tostring(L, 1));
return 1;
}
static int lfunc_log_info(lua_State* L) {
PB::LuaPlugin* self = get_self(L);
if (lua_gettop(L) != 1 || !lua_isstring(L, 1)) {
lua_pushstring(L, "lfunc_log_info: Invalid arguments"); lua_error(L);
return 0;
}
self->log.info("%s", lua_tostring(L, 1));
return 1;
}
static int lfunc_log_warning(lua_State* L) {
PB::LuaPlugin* self = get_self(L);
if (lua_gettop(L) != 1 || !lua_isstring(L, 1)) {
lua_pushstring(L, "lfunc_log_warning: Invalid arguments"); lua_error(L);
return 0;
}
self->log.warning("%s", lua_tostring(L, 1));
return 1;
}
static int lfunc_log_error(lua_State* L) {
PB::LuaPlugin* self = get_self(L);
if (lua_gettop(L) != 1 || !lua_isstring(L, 1)) {
lua_pushstring(L, "lfunc_log_error: Invalid arguments"); lua_error(L);
return 0;
}
self->log.error("%s", lua_tostring(L, 1));
return 1;
}
static int lfunc_log_important(lua_State* L) {
PB::LuaPlugin* self = get_self(L);
if (lua_gettop(L) != 1 || !lua_isstring(L, 1)) {
lua_pushstring(L, "lfunc_log_important: Invalid arguments"); lua_error(L);
return 0;
}
self->log.important("%s", lua_tostring(L, 1));
return 1;
}
static int lfunc_log_critical(lua_State* L) {
PB::LuaPlugin* self = get_self(L);
if (lua_gettop(L) != 1 || !lua_isstring(L, 1)) {
lua_pushstring(L, "lfunc_log_critical: Invalid arguments"); lua_error(L);
return 0;
}
self->log.critical("%s", lua_tostring(L, 1));
return 1;
}
PB::LuaPlugin::LuaPlugin(PB::PluginManager* _plugin_manager, std::string _name)
: PB::Plugin(_plugin_manager, _name, PB::Plugin::Type::Lua)
{
commands = std::shared_ptr<PB::Plugin::CMap>(new PB::Plugin::CMap());
load();
}
PB::LuaPlugin::~LuaPlugin() {
unload();
}
void PB::LuaPlugin::load() {
std::lock_guard<std::mutex> lock(lmtx);
L = lua_open();
luaL_openlibs(L);
void** dp = (void**) lua_newuserdata(L, sizeof(this));
*dp = this;
lua_setglobal(L, "__pb_addr");
lua_pushlightuserdata(L, plugin_manager->bot->db);
lua_setglobal(L, "__pb_db");
lua_newtable(L);
lua_setglobal(L, "__pb_event_handlers");
lua_newtable(L);
lua_setglobal(L, "__pb_command_handlers");
lua_register(L, "write", lfunc_write);
lua_register(L, "join", lfunc_join);
lua_register(L, "part", lfunc_part);
lua_register(L, "nick", lfunc_nick);
lua_register(L, "who", lfunc_who);
lua_register(L, "privmsg", lfunc_privmsg);
lua_register(L, "ctcp", lfunc_ctcp);
lua_register(L, "notice", lfunc_notice);
lua_register(L, "nctcp", lfunc_nctcp);
lua_register(L, "mode", lfunc_mode);
lua_register(L, "kick", lfunc_kick);
lua_register(L, "remove", lfunc_remove);
lua_register(L, "op", lfunc_op);
lua_register(L, "deop", lfunc_deop);
lua_register(L, "hop", lfunc_hop);
lua_register(L, "dehop", lfunc_dehop);
lua_register(L, "voice", lfunc_voice);
lua_register(L, "devoice", lfunc_devoice);
lua_register(L, "quiet", lfunc_quiet);
lua_register(L, "unquiet", lfunc_unquiet);
lua_register(L, "ban", lfunc_ban);
lua_register(L, "unban", lfunc_unban);
lua_register(L, "exempt", lfunc_exempt);
lua_register(L, "unexempt", lfunc_unexempt);
lua_register(L, "get_host", lfunc_get_host);
lua_register(L, "get_port", lfunc_get_port);
lua_register(L, "get_nick", lfunc_get_nick);
lua_register(L, "get_user", lfunc_get_user);
lua_register(L, "get_pass", lfunc_get_pass);
lua_register(L, "get_autojoin", lfunc_get_autojoin);
lua_register(L, "get_autoowner", lfunc_get_autoowner);
lua_register(L, "get_prefix", lfunc_get_prefix);
lua_register(L, "get_user_info", lfunc_get_user_info);
lua_register(L, "log", lfunc_log);
lua_register(L, "log_debug", lfunc_log_debug);
lua_register(L, "log_io", lfunc_log_io);
lua_register(L, "log_info", lfunc_log_info);
lua_register(L, "log_warning", lfunc_log_warning);
lua_register(L, "log_error", lfunc_log_error);
lua_register(L, "log_important", lfunc_log_important);
lua_register(L, "log_critical", lfunc_log_critical);
if(luaL_dostring(L,
"sqlite3 = require('lsqlite3')\n" \
"db = sqlite3.open_ptr(__pb_db)\n" \
"function on(name, handler)\n" \
"__pb_event_handlers[name] = handler\n" \
"end\n" \
"function command(params, handler)\n" \
"if params['name'] == nil then\n" \
"error('no command name')\n" \
"end\n" \
"if params['group'] == nil then\n" \
"error('no command group')\n" \
"end\n" \
"if __pb_command_handlers[params['group']] == nil then\n" \
"__pb_command_handlers[params['group']] = {}" \
"end\n" \
"__pb_command_handlers[params['group']][params['name']] = handler\n" \
"__pb_register_command(params)\n" \
"end\n" \
"function reply(e, message)\n" \
"privmsg(e.socket, e.reply_to, message)\n"\
"end\n" \
"function nreply(e, message)\n" \
"notice(e.socket, e.nick, message)\n"
"end\n"
)) throw std::runtime_error(std::string(lua_tostring(L, -1)));
lua_register(L, "__pb_register_command", lfunc_command);
if (luaL_dofile(L, find_path_to_plugin(name).c_str()))
throw std::runtime_error(std::string(lua_tostring(L, -1)));
lua_settop(L, 0);
}
void PB::LuaPlugin::unload() {
std::lock_guard<std::mutex> lock(lmtx);
commands = std::shared_ptr<PB::Plugin::CMap>(new PB::Plugin::CMap());
lua_close(L);
} | [
"nickolay02@inbox.ru"
] | nickolay02@inbox.ru |
ed8a5ef99e478cb97faef13f248274be681931cc | 4677b50a043e6d2c6f734d266baefe41bb851c1f | /system/core/fs_mgr/fs_mgr_overlayfs.cpp | 9a94d79124829444d62bcecb1638403d953102a4 | [] | no_license | Cryolin/aosp_system_core | d7e322682f6aeda0a8eb71f2cef70767102d2645 | ff00ca6dfd3c9dcf6188779debcb14a2d2394b10 | refs/heads/main | 2023-06-19T09:44:05.158533 | 2021-07-18T13:04:16 | 2021-07-18T13:04:16 | 387,176,707 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 59,306 | cpp | /*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/fs.h>
#include <selinux/selinux.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mount.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <sys/statvfs.h>
#include <sys/types.h>
#include <sys/utsname.h>
#include <sys/vfs.h>
#include <unistd.h>
#include <algorithm>
#include <memory>
#include <string>
#include <vector>
#include <android-base/file.h>
#include <android-base/macros.h>
#include <android-base/properties.h>
#include <android-base/strings.h>
#include <android-base/unique_fd.h>
#include <ext4_utils/ext4_utils.h>
#include <fs_mgr.h>
#include <fs_mgr/file_wait.h>
#include <fs_mgr_dm_linear.h>
#include <fs_mgr_overlayfs.h>
#include <fstab/fstab.h>
#include <libdm/dm.h>
#include <libfiemap/image_manager.h>
#include <libgsi/libgsi.h>
#include <liblp/builder.h>
#include <liblp/liblp.h>
#include <storage_literals/storage_literals.h>
#include "fs_mgr_priv.h"
#include "libfiemap/utility.h"
using namespace std::literals;
using namespace android::dm;
using namespace android::fs_mgr;
using namespace android::storage_literals;
using android::fiemap::FilesystemHasReliablePinning;
using android::fiemap::IImageManager;
namespace {
bool fs_mgr_access(const std::string& path) {
auto save_errno = errno;
auto ret = access(path.c_str(), F_OK) == 0;
errno = save_errno;
return ret;
}
// determine if a filesystem is available
bool fs_mgr_overlayfs_filesystem_available(const std::string& filesystem) {
std::string filesystems;
if (!android::base::ReadFileToString("/proc/filesystems", &filesystems)) return false;
return filesystems.find("\t" + filesystem + "\n") != std::string::npos;
}
} // namespace
#if ALLOW_ADBD_DISABLE_VERITY == 0 // If we are a user build, provide stubs
Fstab fs_mgr_overlayfs_candidate_list(const Fstab&) {
return {};
}
bool fs_mgr_overlayfs_mount_all(Fstab*) {
return false;
}
bool fs_mgr_overlayfs_mount_fstab_entry(const std::string&, const std::string&) {
return false;
}
std::vector<std::string> fs_mgr_overlayfs_required_devices(Fstab*) {
return {};
}
bool fs_mgr_overlayfs_setup(const char*, const char*, bool* change, bool) {
if (change) *change = false;
return false;
}
bool fs_mgr_overlayfs_teardown(const char*, bool* change) {
if (change) *change = false;
return false;
}
bool fs_mgr_overlayfs_is_setup() {
return false;
}
namespace android {
namespace fs_mgr {
void MapScratchPartitionIfNeeded(Fstab*, const std::function<bool(const std::set<std::string>&)>&) {
}
void CleanupOldScratchFiles() {}
void TeardownAllOverlayForMountPoint(const std::string&) {}
} // namespace fs_mgr
} // namespace android
#else // ALLOW_ADBD_DISABLE_VERITY == 0
namespace {
bool fs_mgr_in_recovery() {
// Check the existence of recovery binary instead of using the compile time
// macro, because first-stage-init is compiled with __ANDROID_RECOVERY__
// defined, albeit not in recovery. More details: system/core/init/README.md
return fs_mgr_access("/system/bin/recovery");
}
bool fs_mgr_is_dsu_running() {
// Since android::gsi::CanBootIntoGsi() or android::gsi::MarkSystemAsGsi() is
// never called in recovery, the return value of android::gsi::IsGsiRunning()
// is not well-defined. In this case, just return false as being in recovery
// implies not running a DSU system.
if (fs_mgr_in_recovery()) return false;
auto saved_errno = errno;
auto ret = android::gsi::IsGsiRunning();
errno = saved_errno;
return ret;
}
// list of acceptable overlayfs backing storage
const auto kScratchMountPoint = "/mnt/scratch"s;
const auto kCacheMountPoint = "/cache"s;
std::vector<const std::string> OverlayMountPoints() {
// Never fallback to legacy cache mount point if within a DSU system,
// because running a DSU system implies the device supports dynamic
// partitions, which means legacy cache mustn't be used.
if (fs_mgr_is_dsu_running()) {
return {kScratchMountPoint};
}
return {kScratchMountPoint, kCacheMountPoint};
}
// Return true if everything is mounted, but before adb is started. Right
// after 'trigger load_persist_props_action' is done.
bool fs_mgr_boot_completed() {
return android::base::GetBoolProperty("ro.persistent_properties.ready", false);
}
bool fs_mgr_is_dir(const std::string& path) {
struct stat st;
return !stat(path.c_str(), &st) && S_ISDIR(st.st_mode);
}
// Similar test as overlayfs workdir= validation in the kernel for read-write
// validation, except we use fs_mgr_work. Covers space and storage issues.
bool fs_mgr_dir_is_writable(const std::string& path) {
auto test_directory = path + "/fs_mgr_work";
rmdir(test_directory.c_str());
auto ret = !mkdir(test_directory.c_str(), 0700);
return ret | !rmdir(test_directory.c_str());
}
// At less than 1% or 8MB of free space return value of false,
// means we will try to wrap with overlayfs.
bool fs_mgr_filesystem_has_space(const std::string& mount_point) {
// If we have access issues to find out space remaining, return true
// to prevent us trying to override with overlayfs.
struct statvfs vst;
auto save_errno = errno;
if (statvfs(mount_point.c_str(), &vst)) {
errno = save_errno;
return true;
}
static constexpr int kPercentThreshold = 1; // 1%
static constexpr unsigned long kSizeThreshold = 8 * 1024 * 1024; // 8MB
return (vst.f_bfree >= (vst.f_blocks * kPercentThreshold / 100)) &&
(static_cast<uint64_t>(vst.f_bfree) * vst.f_frsize) >= kSizeThreshold;
}
const auto kPhysicalDevice = "/dev/block/by-name/"s;
constexpr char kScratchImageMetadata[] = "/metadata/gsi/remount/lp_metadata";
// Note: this is meant only for recovery/first-stage init.
bool ScratchIsOnData() {
// The scratch partition of DSU is managed by gsid.
if (fs_mgr_is_dsu_running()) {
return false;
}
return fs_mgr_access(kScratchImageMetadata);
}
bool fs_mgr_update_blk_device(FstabEntry* entry) {
if (entry->fs_mgr_flags.logical) {
fs_mgr_update_logical_partition(entry);
}
if (fs_mgr_access(entry->blk_device)) {
return true;
}
if (entry->blk_device != "/dev/root") {
return false;
}
// special case for system-as-root (taimen and others)
auto blk_device = kPhysicalDevice + "system";
if (!fs_mgr_access(blk_device)) {
blk_device += fs_mgr_get_slot_suffix();
if (!fs_mgr_access(blk_device)) {
return false;
}
}
entry->blk_device = blk_device;
return true;
}
bool fs_mgr_overlayfs_enabled(FstabEntry* entry) {
// readonly filesystem, can not be mount -o remount,rw
// for squashfs, erofs or if free space is (near) zero making such a remount
// virtually useless, or if there are shared blocks that prevent remount,rw
if (!fs_mgr_filesystem_has_space(entry->mount_point)) {
return true;
}
// blk_device needs to be setup so we can check superblock.
// If we fail here, because during init first stage and have doubts.
if (!fs_mgr_update_blk_device(entry)) {
return true;
}
// check if ext4 de-dupe
auto save_errno = errno;
auto has_shared_blocks = fs_mgr_has_shared_blocks(entry->mount_point, entry->blk_device);
if (!has_shared_blocks && (entry->mount_point == "/system")) {
has_shared_blocks = fs_mgr_has_shared_blocks("/", entry->blk_device);
}
errno = save_errno;
return has_shared_blocks;
}
bool fs_mgr_rm_all(const std::string& path, bool* change = nullptr, int level = 0) {
auto save_errno = errno;
std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(path.c_str()), closedir);
if (!dir) {
if (errno == ENOENT) {
errno = save_errno;
return true;
}
PERROR << "opendir " << path << " depth=" << level;
if ((errno == EPERM) && (level != 0)) {
errno = save_errno;
return true;
}
return false;
}
dirent* entry;
auto ret = true;
while ((entry = readdir(dir.get()))) {
if (("."s == entry->d_name) || (".."s == entry->d_name)) continue;
auto file = path + "/" + entry->d_name;
if (entry->d_type == DT_UNKNOWN) {
struct stat st;
save_errno = errno;
if (!lstat(file.c_str(), &st) && (st.st_mode & S_IFDIR)) entry->d_type = DT_DIR;
errno = save_errno;
}
if (entry->d_type == DT_DIR) {
ret &= fs_mgr_rm_all(file, change, level + 1);
if (!rmdir(file.c_str())) {
if (change) *change = true;
} else {
if (errno != ENOENT) ret = false;
PERROR << "rmdir " << file << " depth=" << level;
}
continue;
}
if (!unlink(file.c_str())) {
if (change) *change = true;
} else {
if (errno != ENOENT) ret = false;
PERROR << "rm " << file << " depth=" << level;
}
}
return ret;
}
const auto kUpperName = "upper"s;
const auto kWorkName = "work"s;
const auto kOverlayTopDir = "/overlay"s;
std::string fs_mgr_get_overlayfs_candidate(const std::string& mount_point) {
if (!fs_mgr_is_dir(mount_point)) return "";
const auto base = android::base::Basename(mount_point) + "/";
for (const auto& overlay_mount_point : OverlayMountPoints()) {
auto dir = overlay_mount_point + kOverlayTopDir + "/" + base;
auto upper = dir + kUpperName;
if (!fs_mgr_is_dir(upper)) continue;
auto work = dir + kWorkName;
if (!fs_mgr_is_dir(work)) continue;
if (!fs_mgr_dir_is_writable(work)) continue;
return dir;
}
return "";
}
const auto kLowerdirOption = "lowerdir="s;
const auto kUpperdirOption = "upperdir="s;
// default options for mount_point, returns empty string for none available.
std::string fs_mgr_get_overlayfs_options(const std::string& mount_point) {
auto candidate = fs_mgr_get_overlayfs_candidate(mount_point);
if (candidate.empty()) return "";
auto ret = kLowerdirOption + mount_point + "," + kUpperdirOption + candidate + kUpperName +
",workdir=" + candidate + kWorkName;
if (fs_mgr_overlayfs_valid() == OverlayfsValidResult::kOverrideCredsRequired) {
ret += ",override_creds=off";
}
return ret;
}
const std::string fs_mgr_mount_point(const std::string& mount_point) {
if ("/"s != mount_point) return mount_point;
return "/system";
}
bool fs_mgr_rw_access(const std::string& path) {
if (path.empty()) return false;
auto save_errno = errno;
auto ret = access(path.c_str(), R_OK | W_OK) == 0;
errno = save_errno;
return ret;
}
bool fs_mgr_overlayfs_already_mounted(const std::string& mount_point, bool overlay_only = true) {
Fstab fstab;
auto save_errno = errno;
if (!ReadFstabFromFile("/proc/mounts", &fstab)) {
return false;
}
errno = save_errno;
const auto lowerdir = kLowerdirOption + mount_point;
for (const auto& entry : fstab) {
if (overlay_only && "overlay" != entry.fs_type && "overlayfs" != entry.fs_type) continue;
if (mount_point != entry.mount_point) continue;
if (!overlay_only) return true;
const auto options = android::base::Split(entry.fs_options, ",");
for (const auto& opt : options) {
if (opt == lowerdir) {
return true;
}
}
}
return false;
}
bool fs_mgr_wants_overlayfs(FstabEntry* entry) {
// Don't check entries that are managed by vold.
if (entry->fs_mgr_flags.vold_managed || entry->fs_mgr_flags.recovery_only) return false;
// *_other doesn't want overlayfs.
if (entry->fs_mgr_flags.slot_select_other) return false;
// Only concerned with readonly partitions.
if (!(entry->flags & MS_RDONLY)) return false;
// If unbindable, do not allow overlayfs as this could expose us to
// security issues. On Android, this could also be used to turn off
// the ability to overlay an otherwise acceptable filesystem since
// /system and /vendor are never bound(sic) to.
if (entry->flags & MS_UNBINDABLE) return false;
if (!fs_mgr_overlayfs_enabled(entry)) return false;
return true;
}
constexpr char kOverlayfsFileContext[] = "u:object_r:overlayfs_file:s0";
bool fs_mgr_overlayfs_setup_dir(const std::string& dir, std::string* overlay, bool* change) {
auto ret = true;
auto top = dir + kOverlayTopDir;
if (setfscreatecon(kOverlayfsFileContext)) {
ret = false;
PERROR << "setfscreatecon " << kOverlayfsFileContext;
}
auto save_errno = errno;
if (!mkdir(top.c_str(), 0755)) {
if (change) *change = true;
} else if (errno != EEXIST) {
ret = false;
PERROR << "mkdir " << top;
} else {
errno = save_errno;
}
setfscreatecon(nullptr);
if (overlay) *overlay = std::move(top);
return ret;
}
bool fs_mgr_overlayfs_setup_one(const std::string& overlay, const std::string& mount_point,
bool* change) {
auto ret = true;
if (fs_mgr_overlayfs_already_mounted(mount_point)) return ret;
auto fsrec_mount_point = overlay + "/" + android::base::Basename(mount_point) + "/";
if (setfscreatecon(kOverlayfsFileContext)) {
ret = false;
PERROR << "setfscreatecon " << kOverlayfsFileContext;
}
auto save_errno = errno;
if (!mkdir(fsrec_mount_point.c_str(), 0755)) {
if (change) *change = true;
} else if (errno != EEXIST) {
ret = false;
PERROR << "mkdir " << fsrec_mount_point;
} else {
errno = save_errno;
}
save_errno = errno;
if (!mkdir((fsrec_mount_point + kWorkName).c_str(), 0755)) {
if (change) *change = true;
} else if (errno != EEXIST) {
ret = false;
PERROR << "mkdir " << fsrec_mount_point << kWorkName;
} else {
errno = save_errno;
}
setfscreatecon(nullptr);
auto new_context = fs_mgr_get_context(mount_point);
if (!new_context.empty() && setfscreatecon(new_context.c_str())) {
ret = false;
PERROR << "setfscreatecon " << new_context;
}
auto upper = fsrec_mount_point + kUpperName;
save_errno = errno;
if (!mkdir(upper.c_str(), 0755)) {
if (change) *change = true;
} else if (errno != EEXIST) {
ret = false;
PERROR << "mkdir " << upper;
} else {
errno = save_errno;
}
if (!new_context.empty()) setfscreatecon(nullptr);
return ret;
}
uint32_t fs_mgr_overlayfs_slot_number() {
return SlotNumberForSlotSuffix(fs_mgr_get_slot_suffix());
}
std::string fs_mgr_overlayfs_super_device(uint32_t slot_number) {
return kPhysicalDevice + fs_mgr_get_super_partition_name(slot_number);
}
bool fs_mgr_overlayfs_has_logical(const Fstab& fstab) {
for (const auto& entry : fstab) {
if (entry.fs_mgr_flags.logical) {
return true;
}
}
return false;
}
void fs_mgr_overlayfs_umount_scratch() {
// Lazy umount will allow us to move on and possibly later
// establish a new fresh mount without requiring a reboot should
// the developer wish to restart. Old references should melt
// away or have no data. Main goal is to shut the door on the
// current overrides with an expectation of a subsequent reboot,
// thus any errors here are ignored.
umount2(kScratchMountPoint.c_str(), MNT_DETACH);
LINFO << "umount(" << kScratchMountPoint << ")";
rmdir(kScratchMountPoint.c_str());
}
bool fs_mgr_overlayfs_teardown_scratch(const std::string& overlay, bool* change) {
// umount and delete kScratchMountPoint storage if we have logical partitions
if (overlay != kScratchMountPoint) return true;
// Validation check.
if (fs_mgr_is_dsu_running()) {
LERROR << "Destroying DSU scratch is not allowed.";
return false;
}
auto save_errno = errno;
if (fs_mgr_overlayfs_already_mounted(kScratchMountPoint, false)) {
fs_mgr_overlayfs_umount_scratch();
}
const auto partition_name = android::base::Basename(kScratchMountPoint);
auto images = IImageManager::Open("remount", 10s);
if (images && images->BackingImageExists(partition_name)) {
#if defined __ANDROID_RECOVERY__
if (!images->DisableImage(partition_name)) {
return false;
}
#else
if (!images->UnmapImageIfExists(partition_name) ||
!images->DeleteBackingImage(partition_name)) {
return false;
}
#endif
}
auto slot_number = fs_mgr_overlayfs_slot_number();
auto super_device = fs_mgr_overlayfs_super_device(slot_number);
if (!fs_mgr_rw_access(super_device)) return true;
auto builder = MetadataBuilder::New(super_device, slot_number);
if (!builder) {
errno = save_errno;
return true;
}
if (builder->FindPartition(partition_name) == nullptr) {
errno = save_errno;
return true;
}
builder->RemovePartition(partition_name);
auto metadata = builder->Export();
if (metadata && UpdatePartitionTable(super_device, *metadata.get(), slot_number)) {
if (change) *change = true;
if (!DestroyLogicalPartition(partition_name)) return false;
} else {
LERROR << "delete partition " << overlay;
return false;
}
errno = save_errno;
return true;
}
bool fs_mgr_overlayfs_teardown_one(const std::string& overlay, const std::string& mount_point,
bool* change, bool* should_destroy_scratch = nullptr) {
const auto top = overlay + kOverlayTopDir;
if (!fs_mgr_access(top)) {
if (should_destroy_scratch) *should_destroy_scratch = true;
return true;
}
auto cleanup_all = mount_point.empty();
const auto partition_name = android::base::Basename(mount_point);
const auto oldpath = top + (cleanup_all ? "" : ("/" + partition_name));
const auto newpath = cleanup_all ? overlay + "/." + kOverlayTopDir.substr(1) + ".teardown"
: top + "/." + partition_name + ".teardown";
auto ret = fs_mgr_rm_all(newpath);
auto save_errno = errno;
if (!rename(oldpath.c_str(), newpath.c_str())) {
if (change) *change = true;
} else if (errno != ENOENT) {
ret = false;
PERROR << "mv " << oldpath << " " << newpath;
} else {
errno = save_errno;
}
ret &= fs_mgr_rm_all(newpath, change);
save_errno = errno;
if (!rmdir(newpath.c_str())) {
if (change) *change = true;
} else if (errno != ENOENT) {
ret = false;
PERROR << "rmdir " << newpath;
} else {
errno = save_errno;
}
if (!cleanup_all) {
save_errno = errno;
if (!rmdir(top.c_str())) {
if (change) *change = true;
cleanup_all = true;
} else if (errno == ENOTEMPTY) {
cleanup_all = true;
// cleanup all if the content is all hidden (leading .)
std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(top.c_str()), closedir);
if (!dir) {
PERROR << "opendir " << top;
} else {
dirent* entry;
while ((entry = readdir(dir.get()))) {
if (entry->d_name[0] != '.') {
cleanup_all = false;
break;
}
}
}
errno = save_errno;
} else if (errno == ENOENT) {
cleanup_all = true;
errno = save_errno;
} else {
ret = false;
PERROR << "rmdir " << top;
}
}
if (should_destroy_scratch) *should_destroy_scratch = cleanup_all;
return ret;
}
bool fs_mgr_overlayfs_set_shared_mount(const std::string& mount_point, bool shared_flag) {
auto ret = mount(nullptr, mount_point.c_str(), nullptr, shared_flag ? MS_SHARED : MS_PRIVATE,
nullptr);
if (ret) {
PERROR << "__mount(target=" << mount_point
<< ",flag=" << (shared_flag ? "MS_SHARED" : "MS_PRIVATE") << ")=" << ret;
return false;
}
return true;
}
bool fs_mgr_overlayfs_move_mount(const std::string& source, const std::string& target) {
auto ret = mount(source.c_str(), target.c_str(), nullptr, MS_MOVE, nullptr);
if (ret) {
PERROR << "__mount(source=" << source << ",target=" << target << ",flag=MS_MOVE)=" << ret;
return false;
}
return true;
}
struct mount_info {
std::string mount_point;
bool shared_flag;
};
std::vector<mount_info> ReadMountinfoFromFile(const std::string& path) {
std::vector<mount_info> info;
auto file = std::unique_ptr<FILE, decltype(&fclose)>{fopen(path.c_str(), "re"), fclose};
if (!file) {
PERROR << __FUNCTION__ << "(): cannot open file: '" << path << "'";
return info;
}
ssize_t len;
size_t alloc_len = 0;
char* line = nullptr;
while ((len = getline(&line, &alloc_len, file.get())) != -1) {
/* if the last character is a newline, shorten the string by 1 byte */
if (line[len - 1] == '\n') {
line[len - 1] = '\0';
}
static constexpr char delim[] = " \t";
char* save_ptr;
if (!strtok_r(line, delim, &save_ptr)) {
LERROR << "Error parsing mount ID";
break;
}
if (!strtok_r(nullptr, delim, &save_ptr)) {
LERROR << "Error parsing parent ID";
break;
}
if (!strtok_r(nullptr, delim, &save_ptr)) {
LERROR << "Error parsing mount source";
break;
}
if (!strtok_r(nullptr, delim, &save_ptr)) {
LERROR << "Error parsing root";
break;
}
char* p;
if (!(p = strtok_r(nullptr, delim, &save_ptr))) {
LERROR << "Error parsing mount_point";
break;
}
mount_info entry = {p, false};
if (!strtok_r(nullptr, delim, &save_ptr)) {
LERROR << "Error parsing mount_flags";
break;
}
while ((p = strtok_r(nullptr, delim, &save_ptr))) {
if ((p[0] == '-') && (p[1] == '\0')) break;
if (android::base::StartsWith(p, "shared:")) entry.shared_flag = true;
}
if (!p) {
LERROR << "Error parsing fields";
break;
}
info.emplace_back(std::move(entry));
}
free(line);
if (info.empty()) {
LERROR << __FUNCTION__ << "(): failed to load mountinfo from : '" << path << "'";
}
return info;
}
bool fs_mgr_overlayfs_mount(const std::string& mount_point) {
auto options = fs_mgr_get_overlayfs_options(mount_point);
if (options.empty()) return false;
auto retval = true;
auto save_errno = errno;
struct move_entry {
std::string mount_point;
std::string dir;
bool shared_flag;
};
std::vector<move_entry> move;
auto parent_private = false;
auto parent_made_private = false;
auto dev_private = false;
auto dev_made_private = false;
for (auto& entry : ReadMountinfoFromFile("/proc/self/mountinfo")) {
if ((entry.mount_point == mount_point) && !entry.shared_flag) {
parent_private = true;
}
if ((entry.mount_point == "/dev") && !entry.shared_flag) {
dev_private = true;
}
if (!android::base::StartsWith(entry.mount_point, mount_point + "/")) {
continue;
}
if (std::find_if(move.begin(), move.end(), [&entry](const auto& it) {
return android::base::StartsWith(entry.mount_point, it.mount_point + "/");
}) != move.end()) {
continue;
}
// use as the bound directory in /dev.
auto new_context = fs_mgr_get_context(entry.mount_point);
if (!new_context.empty() && setfscreatecon(new_context.c_str())) {
PERROR << "setfscreatecon " << new_context;
}
move_entry new_entry = {std::move(entry.mount_point), "/dev/TemporaryDir-XXXXXX",
entry.shared_flag};
const auto target = mkdtemp(new_entry.dir.data());
if (!target) {
retval = false;
save_errno = errno;
PERROR << "temporary directory for MS_BIND";
setfscreatecon(nullptr);
continue;
}
setfscreatecon(nullptr);
if (!parent_private && !parent_made_private) {
parent_made_private = fs_mgr_overlayfs_set_shared_mount(mount_point, false);
}
if (new_entry.shared_flag) {
new_entry.shared_flag = fs_mgr_overlayfs_set_shared_mount(new_entry.mount_point, false);
}
if (!fs_mgr_overlayfs_move_mount(new_entry.mount_point, new_entry.dir)) {
retval = false;
save_errno = errno;
if (new_entry.shared_flag) {
fs_mgr_overlayfs_set_shared_mount(new_entry.mount_point, true);
}
continue;
}
move.emplace_back(std::move(new_entry));
}
// hijack __mount() report format to help triage
auto report = "__mount(source=overlay,target="s + mount_point + ",type=overlay";
const auto opt_list = android::base::Split(options, ",");
for (const auto& opt : opt_list) {
if (android::base::StartsWith(opt, kUpperdirOption)) {
report = report + "," + opt;
break;
}
}
report = report + ")=";
auto ret = mount("overlay", mount_point.c_str(), "overlay", MS_RDONLY | MS_NOATIME,
options.c_str());
if (ret) {
retval = false;
save_errno = errno;
PERROR << report << ret;
} else {
LINFO << report << ret;
}
// Move submounts back.
for (const auto& entry : move) {
if (!dev_private && !dev_made_private) {
dev_made_private = fs_mgr_overlayfs_set_shared_mount("/dev", false);
}
if (!fs_mgr_overlayfs_move_mount(entry.dir, entry.mount_point)) {
retval = false;
save_errno = errno;
} else if (entry.shared_flag &&
!fs_mgr_overlayfs_set_shared_mount(entry.mount_point, true)) {
retval = false;
save_errno = errno;
}
rmdir(entry.dir.c_str());
}
if (dev_made_private) {
fs_mgr_overlayfs_set_shared_mount("/dev", true);
}
if (parent_made_private) {
fs_mgr_overlayfs_set_shared_mount(mount_point, true);
}
errno = save_errno;
return retval;
}
// Mount kScratchMountPoint
bool fs_mgr_overlayfs_mount_scratch(const std::string& device_path, const std::string mnt_type,
bool readonly = false) {
if (readonly) {
if (!fs_mgr_access(device_path)) return false;
} else {
if (!fs_mgr_rw_access(device_path)) return false;
}
auto f2fs = fs_mgr_is_f2fs(device_path);
auto ext4 = fs_mgr_is_ext4(device_path);
if (!f2fs && !ext4) return false;
if (setfscreatecon(kOverlayfsFileContext)) {
PERROR << "setfscreatecon " << kOverlayfsFileContext;
}
if (mkdir(kScratchMountPoint.c_str(), 0755) && (errno != EEXIST)) {
PERROR << "create " << kScratchMountPoint;
}
FstabEntry entry;
entry.blk_device = device_path;
entry.mount_point = kScratchMountPoint;
entry.fs_type = mnt_type;
if ((mnt_type == "f2fs") && !f2fs) entry.fs_type = "ext4";
if ((mnt_type == "ext4") && !ext4) entry.fs_type = "f2fs";
entry.flags = MS_NOATIME | MS_RDONLY;
auto mounted = true;
if (!readonly) {
if (entry.fs_type == "ext4") {
// check if ext4 de-dupe
entry.flags |= MS_RDONLY;
auto save_errno = errno;
mounted = fs_mgr_do_mount_one(entry) == 0;
if (mounted) {
mounted = !fs_mgr_has_shared_blocks(entry.mount_point, entry.blk_device);
fs_mgr_overlayfs_umount_scratch();
}
errno = save_errno;
}
entry.flags &= ~MS_RDONLY;
fs_mgr_set_blk_ro(device_path, false);
}
entry.fs_mgr_flags.check = true;
auto save_errno = errno;
if (mounted) mounted = fs_mgr_do_mount_one(entry) == 0;
if (!mounted) {
if ((entry.fs_type == "f2fs") && ext4) {
entry.fs_type = "ext4";
mounted = fs_mgr_do_mount_one(entry) == 0;
} else if ((entry.fs_type == "ext4") && f2fs) {
entry.fs_type = "f2fs";
mounted = fs_mgr_do_mount_one(entry) == 0;
}
if (!mounted) save_errno = errno;
}
setfscreatecon(nullptr);
if (!mounted) rmdir(kScratchMountPoint.c_str());
errno = save_errno;
return mounted;
}
const std::string kMkF2fs("/system/bin/make_f2fs");
const std::string kMkExt4("/system/bin/mke2fs");
// Only a suggestion for _first_ try during mounting
std::string fs_mgr_overlayfs_scratch_mount_type() {
if (!access(kMkF2fs.c_str(), X_OK) && fs_mgr_overlayfs_filesystem_available("f2fs")) {
return "f2fs";
}
if (!access(kMkExt4.c_str(), X_OK) && fs_mgr_overlayfs_filesystem_available("ext4")) {
return "ext4";
}
return "auto";
}
// Note: we do not check access() here except for the super partition, since
// in first-stage init we wouldn't have registed by-name symlinks for "other"
// partitions that won't be mounted.
static std::string GetPhysicalScratchDevice() {
auto slot_number = fs_mgr_overlayfs_slot_number();
auto super_device = fs_mgr_overlayfs_super_device(slot_number);
auto path = fs_mgr_overlayfs_super_device(slot_number == 0);
if (super_device != path) {
return path;
}
if (fs_mgr_access(super_device)) {
// Do not try to use system_other on a DAP device.
return "";
}
auto other_slot = fs_mgr_get_other_slot_suffix();
if (!other_slot.empty()) {
return kPhysicalDevice + "system" + other_slot;
}
return "";
}
// Note: The scratch partition of DSU is managed by gsid, and should be initialized during
// first-stage-mount. Just check if the DM device for DSU scratch partition is created or not.
static std::string GetDsuScratchDevice() {
auto& dm = DeviceMapper::Instance();
std::string device;
if (dm.GetState(android::gsi::kDsuScratch) != DmDeviceState::INVALID &&
dm.GetDmDevicePathByName(android::gsi::kDsuScratch, &device)) {
return device;
}
return "";
}
// This returns the scratch device that was detected during early boot (first-
// stage init). If the device was created later, for example during setup for
// the adb remount command, it can return an empty string since it does not
// query ImageManager. (Note that ImageManager in first-stage init will always
// use device-mapper, since /data is not available to use loop devices.)
static std::string GetBootScratchDevice() {
// Note: fs_mgr_is_dsu_running() always returns false in recovery or fastbootd.
if (fs_mgr_is_dsu_running()) {
return GetDsuScratchDevice();
}
auto& dm = DeviceMapper::Instance();
// If there is a scratch partition allocated in /data or on super, we
// automatically prioritize that over super_other or system_other.
// Some devices, for example, have a write-protected eMMC and the
// super partition cannot be used even if it exists.
std::string device;
auto partition_name = android::base::Basename(kScratchMountPoint);
if (dm.GetState(partition_name) != DmDeviceState::INVALID &&
dm.GetDmDevicePathByName(partition_name, &device)) {
return device;
}
// There is no dynamic scratch, so try and find a physical one.
return GetPhysicalScratchDevice();
}
bool fs_mgr_overlayfs_make_scratch(const std::string& scratch_device, const std::string& mnt_type) {
// Force mkfs by design for overlay support of adb remount, simplify and
// thus do not rely on fsck to correct problems that could creep in.
auto command = ""s;
if (mnt_type == "f2fs") {
command = kMkF2fs + " -w 4096 -f -d1 -l" + android::base::Basename(kScratchMountPoint);
} else if (mnt_type == "ext4") {
command = kMkExt4 + " -F -b 4096 -t ext4 -m 0 -O has_journal -M " + kScratchMountPoint;
} else {
errno = ESRCH;
LERROR << mnt_type << " has no mkfs cookbook";
return false;
}
command += " " + scratch_device + " >/dev/null 2>/dev/null </dev/null";
fs_mgr_set_blk_ro(scratch_device, false);
auto ret = system(command.c_str());
if (ret) {
LERROR << "make " << mnt_type << " filesystem on " << scratch_device << " return=" << ret;
return false;
}
return true;
}
static void TruncatePartitionsWithSuffix(MetadataBuilder* builder, const std::string& suffix) {
auto& dm = DeviceMapper::Instance();
// Remove <other> partitions
for (const auto& group : builder->ListGroups()) {
for (const auto& part : builder->ListPartitionsInGroup(group)) {
const auto& name = part->name();
if (!android::base::EndsWith(name, suffix)) {
continue;
}
if (dm.GetState(name) != DmDeviceState::INVALID && !DestroyLogicalPartition(name)) {
continue;
}
builder->ResizePartition(builder->FindPartition(name), 0);
}
}
}
// Create or update a scratch partition within super.
static bool CreateDynamicScratch(std::string* scratch_device, bool* partition_exists,
bool* change) {
const auto partition_name = android::base::Basename(kScratchMountPoint);
auto& dm = DeviceMapper::Instance();
*partition_exists = dm.GetState(partition_name) != DmDeviceState::INVALID;
auto partition_create = !*partition_exists;
auto slot_number = fs_mgr_overlayfs_slot_number();
auto super_device = fs_mgr_overlayfs_super_device(slot_number);
auto builder = MetadataBuilder::New(super_device, slot_number);
if (!builder) {
LERROR << "open " << super_device << " metadata";
return false;
}
auto partition = builder->FindPartition(partition_name);
*partition_exists = partition != nullptr;
auto changed = false;
if (!*partition_exists) {
partition = builder->AddPartition(partition_name, LP_PARTITION_ATTR_NONE);
if (!partition) {
LERROR << "create " << partition_name;
return false;
}
changed = true;
}
// Take half of free space, minimum 512MB or maximum free - margin.
static constexpr auto kMinimumSize = uint64_t(512 * 1024 * 1024);
if (partition->size() < kMinimumSize) {
auto partition_size =
builder->AllocatableSpace() - builder->UsedSpace() + partition->size();
if ((partition_size > kMinimumSize) || !partition->size()) {
// Leave some space for free space jitter of a few erase
// blocks, in case they are needed for any individual updates
// to any other partition that needs to be flashed while
// overlayfs is in force. Of course if margin_size is not
// enough could normally get a flash failure, so
// ResizePartition() will delete the scratch partition in
// order to fulfill. Deleting scratch will destroy all of
// the adb remount overrides :-( .
auto margin_size = uint64_t(3 * 256 * 1024);
BlockDeviceInfo info;
if (builder->GetBlockDeviceInfo(fs_mgr_get_super_partition_name(slot_number), &info)) {
margin_size = 3 * info.logical_block_size;
}
partition_size = std::max(std::min(kMinimumSize, partition_size - margin_size),
partition_size / 2);
if (partition_size > partition->size()) {
if (!builder->ResizePartition(partition, partition_size)) {
// Try to free up space by deallocating partitions in the other slot.
TruncatePartitionsWithSuffix(builder.get(), fs_mgr_get_other_slot_suffix());
partition_size =
builder->AllocatableSpace() - builder->UsedSpace() + partition->size();
partition_size = std::max(std::min(kMinimumSize, partition_size - margin_size),
partition_size / 2);
if (!builder->ResizePartition(partition, partition_size)) {
LERROR << "resize " << partition_name;
return false;
}
}
if (!partition_create) DestroyLogicalPartition(partition_name);
changed = true;
*partition_exists = false;
}
}
}
// land the update back on to the partition
if (changed) {
auto metadata = builder->Export();
if (!metadata || !UpdatePartitionTable(super_device, *metadata.get(), slot_number)) {
LERROR << "add partition " << partition_name;
return false;
}
if (change) *change = true;
}
if (changed || partition_create) {
CreateLogicalPartitionParams params = {
.block_device = super_device,
.metadata_slot = slot_number,
.partition_name = partition_name,
.force_writable = true,
.timeout_ms = 10s,
};
if (!CreateLogicalPartition(params, scratch_device)) {
return false;
}
if (change) *change = true;
} else if (scratch_device->empty()) {
*scratch_device = GetBootScratchDevice();
}
return true;
}
static bool CreateScratchOnData(std::string* scratch_device, bool* partition_exists, bool* change) {
*partition_exists = false;
if (change) *change = false;
auto images = IImageManager::Open("remount", 10s);
if (!images) {
return false;
}
auto partition_name = android::base::Basename(kScratchMountPoint);
if (images->GetMappedImageDevice(partition_name, scratch_device)) {
*partition_exists = true;
return true;
}
BlockDeviceInfo info;
PartitionOpener opener;
if (!opener.GetInfo(fs_mgr_get_super_partition_name(), &info)) {
LERROR << "could not get block device info for super";
return false;
}
if (change) *change = true;
// Note: calling RemoveDisabledImages here ensures that we do not race with
// clean_scratch_files and accidentally try to map an image that will be
// deleted.
if (!images->RemoveDisabledImages()) {
return false;
}
if (!images->BackingImageExists(partition_name)) {
static constexpr uint64_t kMinimumSize = 16_MiB;
static constexpr uint64_t kMaximumSize = 2_GiB;
uint64_t size = std::clamp(info.size / 2, kMinimumSize, kMaximumSize);
auto flags = IImageManager::CREATE_IMAGE_DEFAULT;
if (!images->CreateBackingImage(partition_name, size, flags)) {
LERROR << "could not create scratch image of " << size << " bytes";
return false;
}
}
if (!images->MapImageDevice(partition_name, 10s, scratch_device)) {
LERROR << "could not map scratch image";
return false;
}
return true;
}
static bool CanUseSuperPartition(const Fstab& fstab, bool* is_virtual_ab) {
auto slot_number = fs_mgr_overlayfs_slot_number();
auto super_device = fs_mgr_overlayfs_super_device(slot_number);
if (!fs_mgr_rw_access(super_device) || !fs_mgr_overlayfs_has_logical(fstab)) {
return false;
}
auto metadata = ReadMetadata(super_device, slot_number);
if (!metadata) {
return false;
}
*is_virtual_ab = !!(metadata->header.flags & LP_HEADER_FLAG_VIRTUAL_AB_DEVICE);
return true;
}
bool fs_mgr_overlayfs_create_scratch(const Fstab& fstab, std::string* scratch_device,
bool* partition_exists, bool* change) {
// Use the DSU scratch device managed by gsid if within a DSU system.
if (fs_mgr_is_dsu_running()) {
*scratch_device = GetDsuScratchDevice();
*partition_exists = !scratch_device->empty();
*change = false;
return *partition_exists;
}
// Try a physical partition first.
*scratch_device = GetPhysicalScratchDevice();
if (!scratch_device->empty() && fs_mgr_rw_access(*scratch_device)) {
*partition_exists = true;
return true;
}
// If that fails, see if we can land on super.
bool is_virtual_ab;
if (CanUseSuperPartition(fstab, &is_virtual_ab)) {
bool can_use_data = false;
if (is_virtual_ab && FilesystemHasReliablePinning("/data", &can_use_data) && can_use_data) {
return CreateScratchOnData(scratch_device, partition_exists, change);
}
return CreateDynamicScratch(scratch_device, partition_exists, change);
}
errno = ENXIO;
return false;
}
// Create and mount kScratchMountPoint storage if we have logical partitions
bool fs_mgr_overlayfs_setup_scratch(const Fstab& fstab, bool* change) {
if (fs_mgr_overlayfs_already_mounted(kScratchMountPoint, false)) return true;
std::string scratch_device;
bool partition_exists;
if (!fs_mgr_overlayfs_create_scratch(fstab, &scratch_device, &partition_exists, change)) {
return false;
}
// If the partition exists, assume first that it can be mounted.
auto mnt_type = fs_mgr_overlayfs_scratch_mount_type();
if (partition_exists) {
if (fs_mgr_overlayfs_mount_scratch(scratch_device, mnt_type)) {
if (!fs_mgr_access(kScratchMountPoint + kOverlayTopDir) &&
!fs_mgr_filesystem_has_space(kScratchMountPoint)) {
// declare it useless, no overrides and no free space
fs_mgr_overlayfs_umount_scratch();
} else {
if (change) *change = true;
return true;
}
}
// partition existed, but was not initialized; fall through to make it.
errno = 0;
}
if (!fs_mgr_overlayfs_make_scratch(scratch_device, mnt_type)) return false;
if (change) *change = true;
return fs_mgr_overlayfs_mount_scratch(scratch_device, mnt_type);
}
bool fs_mgr_overlayfs_invalid() {
if (fs_mgr_overlayfs_valid() == OverlayfsValidResult::kNotSupported) return true;
// in recovery or fastbootd, not allowed!
return fs_mgr_in_recovery();
}
} // namespace
Fstab fs_mgr_overlayfs_candidate_list(const Fstab& fstab) {
Fstab candidates;
for (const auto& entry : fstab) {
FstabEntry new_entry = entry;
if (!fs_mgr_overlayfs_already_mounted(entry.mount_point) &&
!fs_mgr_wants_overlayfs(&new_entry)) {
continue;
}
auto new_mount_point = fs_mgr_mount_point(entry.mount_point);
auto duplicate_or_more_specific = false;
for (auto it = candidates.begin(); it != candidates.end();) {
auto it_mount_point = fs_mgr_mount_point(it->mount_point);
if ((it_mount_point == new_mount_point) ||
(android::base::StartsWith(new_mount_point, it_mount_point + "/"))) {
duplicate_or_more_specific = true;
break;
}
if (android::base::StartsWith(it_mount_point, new_mount_point + "/")) {
it = candidates.erase(it);
} else {
++it;
}
}
if (!duplicate_or_more_specific) candidates.emplace_back(std::move(new_entry));
}
return candidates;
}
static void TryMountScratch() {
// Note we get the boot scratch device here, which means if scratch was
// just created through ImageManager, this could fail. In practice this
// should not happen because "remount" detects this scenario (by checking
// if verity is still disabled, i.e. no reboot occurred), and skips calling
// fs_mgr_overlayfs_mount_all().
auto scratch_device = GetBootScratchDevice();
if (!fs_mgr_rw_access(scratch_device)) {
return;
}
if (!WaitForFile(scratch_device, 10s)) {
return;
}
const auto mount_type = fs_mgr_overlayfs_scratch_mount_type();
if (!fs_mgr_overlayfs_mount_scratch(scratch_device, mount_type, true /* readonly */)) {
return;
}
auto has_overlayfs_dir = fs_mgr_access(kScratchMountPoint + kOverlayTopDir);
fs_mgr_overlayfs_umount_scratch();
if (has_overlayfs_dir) {
fs_mgr_overlayfs_mount_scratch(scratch_device, mount_type);
}
}
bool fs_mgr_overlayfs_mount_fstab_entry(const std::string& lowers,
const std::string& mount_point) {
if (fs_mgr_overlayfs_invalid()) return false;
std::string aux = "lowerdir=" + lowers + ",override_creds=off";
auto rc = mount("overlay", mount_point.c_str(), "overlay", MS_RDONLY | MS_NOATIME, aux.c_str());
if (rc == 0) return true;
return false;
}
bool fs_mgr_overlayfs_mount_all(Fstab* fstab) {
auto ret = false;
if (fs_mgr_overlayfs_invalid()) return ret;
auto scratch_can_be_mounted = true;
for (const auto& entry : fs_mgr_overlayfs_candidate_list(*fstab)) {
if (fs_mgr_is_verity_enabled(entry)) continue;
auto mount_point = fs_mgr_mount_point(entry.mount_point);
if (fs_mgr_overlayfs_already_mounted(mount_point)) {
ret = true;
continue;
}
if (scratch_can_be_mounted) {
scratch_can_be_mounted = false;
TryMountScratch();
}
if (fs_mgr_overlayfs_mount(mount_point)) ret = true;
}
return ret;
}
// Returns false if setup not permitted, errno set to last error.
// If something is altered, set *change.
bool fs_mgr_overlayfs_setup(const char* backing, const char* mount_point, bool* change,
bool force) {
if (change) *change = false;
auto ret = false;
if (fs_mgr_overlayfs_valid() == OverlayfsValidResult::kNotSupported) return ret;
if (!fs_mgr_boot_completed()) {
errno = EBUSY;
PERROR << "setup";
return ret;
}
auto save_errno = errno;
Fstab fstab;
if (!ReadDefaultFstab(&fstab)) {
return false;
}
errno = save_errno;
auto candidates = fs_mgr_overlayfs_candidate_list(fstab);
for (auto it = candidates.begin(); it != candidates.end();) {
if (mount_point &&
(fs_mgr_mount_point(it->mount_point) != fs_mgr_mount_point(mount_point))) {
it = candidates.erase(it);
continue;
}
save_errno = errno;
auto verity_enabled = !force && fs_mgr_is_verity_enabled(*it);
if (errno == ENOENT || errno == ENXIO) errno = save_errno;
if (verity_enabled) {
it = candidates.erase(it);
continue;
}
++it;
}
if (candidates.empty()) return ret;
std::string dir;
for (const auto& overlay_mount_point : OverlayMountPoints()) {
if (backing && backing[0] && (overlay_mount_point != backing)) continue;
if (overlay_mount_point == kScratchMountPoint) {
if (!fs_mgr_overlayfs_setup_scratch(fstab, change)) continue;
} else {
if (GetEntryForMountPoint(&fstab, overlay_mount_point) == nullptr) {
continue;
}
}
dir = overlay_mount_point;
break;
}
if (dir.empty()) {
if (change && *change) errno = ESRCH;
if (errno == EPERM) errno = save_errno;
return ret;
}
std::string overlay;
ret |= fs_mgr_overlayfs_setup_dir(dir, &overlay, change);
for (const auto& entry : candidates) {
ret |= fs_mgr_overlayfs_setup_one(overlay, fs_mgr_mount_point(entry.mount_point), change);
}
return ret;
}
// Note: This function never returns the DSU scratch device in recovery or fastbootd,
// because the DSU scratch is created in the first-stage-mount, which is not run in recovery.
static bool EnsureScratchMapped(std::string* device, bool* mapped) {
*mapped = false;
*device = GetBootScratchDevice();
if (!device->empty()) {
return true;
}
if (!fs_mgr_in_recovery()) {
errno = EINVAL;
return false;
}
auto partition_name = android::base::Basename(kScratchMountPoint);
// Check for scratch on /data first, before looking for a modified super
// partition. We should only reach this code in recovery, because scratch
// would otherwise always be mapped.
auto images = IImageManager::Open("remount", 10s);
if (images && images->BackingImageExists(partition_name)) {
if (!images->MapImageDevice(partition_name, 10s, device)) {
return false;
}
*mapped = true;
return true;
}
// Avoid uart spam by first checking for a scratch partition.
auto metadata_slot = fs_mgr_overlayfs_slot_number();
auto super_device = fs_mgr_overlayfs_super_device(metadata_slot);
auto metadata = ReadCurrentMetadata(super_device);
if (!metadata) {
return false;
}
auto partition = FindPartition(*metadata.get(), partition_name);
if (!partition) {
return false;
}
CreateLogicalPartitionParams params = {
.block_device = super_device,
.metadata = metadata.get(),
.partition = partition,
.force_writable = true,
.timeout_ms = 10s,
};
if (!CreateLogicalPartition(params, device)) {
return false;
}
*mapped = true;
return true;
}
// This should only be reachable in recovery, where DSU scratch is not
// automatically mapped.
static bool MapDsuScratchDevice(std::string* device) {
std::string dsu_slot;
if (!android::gsi::IsGsiInstalled() || !android::gsi::GetActiveDsu(&dsu_slot) ||
dsu_slot.empty()) {
// Nothing to do if no DSU installation present.
return false;
}
auto images = IImageManager::Open("dsu/" + dsu_slot, 10s);
if (!images || !images->BackingImageExists(android::gsi::kDsuScratch)) {
// Nothing to do if DSU scratch device doesn't exist.
return false;
}
images->UnmapImageDevice(android::gsi::kDsuScratch);
if (!images->MapImageDevice(android::gsi::kDsuScratch, 10s, device)) {
return false;
}
return true;
}
// Returns false if teardown not permitted, errno set to last error.
// If something is altered, set *change.
bool fs_mgr_overlayfs_teardown(const char* mount_point, bool* change) {
if (change) *change = false;
auto ret = true;
// If scratch exists, but is not mounted, lets gain access to clean
// specific override entries.
auto mount_scratch = false;
if ((mount_point != nullptr) && !fs_mgr_overlayfs_already_mounted(kScratchMountPoint, false)) {
std::string scratch_device = GetBootScratchDevice();
if (!scratch_device.empty()) {
mount_scratch = fs_mgr_overlayfs_mount_scratch(scratch_device,
fs_mgr_overlayfs_scratch_mount_type());
}
}
bool should_destroy_scratch = false;
for (const auto& overlay_mount_point : OverlayMountPoints()) {
ret &= fs_mgr_overlayfs_teardown_one(
overlay_mount_point, mount_point ? fs_mgr_mount_point(mount_point) : "", change,
overlay_mount_point == kScratchMountPoint ? &should_destroy_scratch : nullptr);
}
// Do not attempt to destroy DSU scratch if within a DSU system,
// because DSU scratch partition is managed by gsid.
if (should_destroy_scratch && !fs_mgr_is_dsu_running()) {
ret &= fs_mgr_overlayfs_teardown_scratch(kScratchMountPoint, change);
}
if (fs_mgr_overlayfs_valid() == OverlayfsValidResult::kNotSupported) {
// After obligatory teardown to make sure everything is clean, but if
// we didn't want overlayfs in the first place, we do not want to
// waste time on a reboot (or reboot request message).
if (change) *change = false;
}
// And now that we did what we could, lets inform
// caller that there may still be more to do.
if (!fs_mgr_boot_completed()) {
errno = EBUSY;
PERROR << "teardown";
ret = false;
}
if (mount_scratch) {
fs_mgr_overlayfs_umount_scratch();
}
return ret;
}
bool fs_mgr_overlayfs_is_setup() {
if (fs_mgr_overlayfs_already_mounted(kScratchMountPoint, false)) return true;
Fstab fstab;
if (!ReadDefaultFstab(&fstab)) {
return false;
}
if (fs_mgr_overlayfs_invalid()) return false;
for (const auto& entry : fs_mgr_overlayfs_candidate_list(fstab)) {
if (fs_mgr_is_verity_enabled(entry)) continue;
if (fs_mgr_overlayfs_already_mounted(fs_mgr_mount_point(entry.mount_point))) return true;
}
return false;
}
namespace android {
namespace fs_mgr {
void MapScratchPartitionIfNeeded(Fstab* fstab,
const std::function<bool(const std::set<std::string>&)>& init) {
if (fs_mgr_overlayfs_invalid()) {
return;
}
if (GetEntryForMountPoint(fstab, kScratchMountPoint) != nullptr) {
return;
}
bool want_scratch = false;
for (const auto& entry : fs_mgr_overlayfs_candidate_list(*fstab)) {
if (fs_mgr_is_verity_enabled(entry)) {
continue;
}
if (fs_mgr_overlayfs_already_mounted(fs_mgr_mount_point(entry.mount_point))) {
continue;
}
want_scratch = true;
break;
}
if (!want_scratch) {
return;
}
if (ScratchIsOnData()) {
if (auto images = IImageManager::Open("remount", 0ms)) {
images->MapAllImages(init);
}
}
// Physical or logical partitions will have already been mapped here,
// so just ensure /dev/block symlinks exist.
auto device = GetBootScratchDevice();
if (!device.empty()) {
init({android::base::Basename(device)});
}
}
void CleanupOldScratchFiles() {
if (!ScratchIsOnData()) {
return;
}
if (auto images = IImageManager::Open("remount", 0ms)) {
images->RemoveDisabledImages();
}
}
void TeardownAllOverlayForMountPoint(const std::string& mount_point) {
if (!fs_mgr_in_recovery()) {
LERROR << __FUNCTION__ << "(): must be called within recovery.";
return;
}
// Empty string means teardown everything.
const std::string teardown_dir = mount_point.empty() ? "" : fs_mgr_mount_point(mount_point);
constexpr bool* ignore_change = nullptr;
// Teardown legacy overlay mount points that's not backed by a scratch device.
for (const auto& overlay_mount_point : OverlayMountPoints()) {
if (overlay_mount_point == kScratchMountPoint) {
continue;
}
fs_mgr_overlayfs_teardown_one(overlay_mount_point, teardown_dir, ignore_change);
}
// Map scratch device, mount kScratchMountPoint and teardown kScratchMountPoint.
bool mapped = false;
std::string scratch_device;
if (EnsureScratchMapped(&scratch_device, &mapped)) {
fs_mgr_overlayfs_umount_scratch();
if (fs_mgr_overlayfs_mount_scratch(scratch_device, fs_mgr_overlayfs_scratch_mount_type())) {
bool should_destroy_scratch = false;
fs_mgr_overlayfs_teardown_one(kScratchMountPoint, teardown_dir, ignore_change,
&should_destroy_scratch);
if (should_destroy_scratch) {
fs_mgr_overlayfs_teardown_scratch(kScratchMountPoint, nullptr);
}
fs_mgr_overlayfs_umount_scratch();
}
if (mapped) {
DestroyLogicalPartition(android::base::Basename(kScratchMountPoint));
}
}
// Teardown DSU overlay if present.
if (MapDsuScratchDevice(&scratch_device)) {
fs_mgr_overlayfs_umount_scratch();
if (fs_mgr_overlayfs_mount_scratch(scratch_device, fs_mgr_overlayfs_scratch_mount_type())) {
fs_mgr_overlayfs_teardown_one(kScratchMountPoint, teardown_dir, ignore_change);
fs_mgr_overlayfs_umount_scratch();
}
DestroyLogicalPartition(android::gsi::kDsuScratch);
}
}
} // namespace fs_mgr
} // namespace android
#endif // ALLOW_ADBD_DISABLE_VERITY != 0
bool fs_mgr_has_shared_blocks(const std::string& mount_point, const std::string& dev) {
struct statfs fs;
if ((statfs((mount_point + "/lost+found").c_str(), &fs) == -1) ||
(fs.f_type != EXT4_SUPER_MAGIC)) {
return false;
}
android::base::unique_fd fd(open(dev.c_str(), O_RDONLY | O_CLOEXEC));
if (fd < 0) return false;
struct ext4_super_block sb;
if ((TEMP_FAILURE_RETRY(lseek64(fd, 1024, SEEK_SET)) < 0) ||
(TEMP_FAILURE_RETRY(read(fd, &sb, sizeof(sb))) < 0)) {
return false;
}
struct fs_info info;
if (ext4_parse_sb(&sb, &info) < 0) return false;
return (info.feat_ro_compat & EXT4_FEATURE_RO_COMPAT_SHARED_BLOCKS) != 0;
}
std::string fs_mgr_get_context(const std::string& mount_point) {
char* ctx = nullptr;
if (getfilecon(mount_point.c_str(), &ctx) == -1) {
return "";
}
std::string context(ctx);
free(ctx);
return context;
}
OverlayfsValidResult fs_mgr_overlayfs_valid() {
// Overlayfs available in the kernel, and patched for override_creds?
if (fs_mgr_access("/sys/module/overlay/parameters/override_creds")) {
return OverlayfsValidResult::kOverrideCredsRequired;
}
if (!fs_mgr_overlayfs_filesystem_available("overlay")) {
return OverlayfsValidResult::kNotSupported;
}
struct utsname uts;
if (uname(&uts) == -1) {
return OverlayfsValidResult::kNotSupported;
}
int major, minor;
if (sscanf(uts.release, "%d.%d", &major, &minor) != 2) {
return OverlayfsValidResult::kNotSupported;
}
if (major < 4) {
return OverlayfsValidResult::kOk;
}
if (major > 4) {
return OverlayfsValidResult::kNotSupported;
}
if (minor > 3) {
return OverlayfsValidResult::kNotSupported;
}
return OverlayfsValidResult::kOk;
}
| [
"siyu@mail.ustc.edu.cn"
] | siyu@mail.ustc.edu.cn |
422808e0e5fddb0a97f16e08fb75b8a26296e27d | befaf0dfc5880d18f42e1fa7e39e27f8d2f8dde9 | /SDK/SCUM_CoreUObject_classes.hpp | 69f0c11c74a780c7ad42a39923f497ed62a60c6c | [] | no_license | cpkt9762/SCUM-SDK | 0b59c99748a9e131eb37e5e3d3b95ebc893d7024 | c0dbd67e10a288086120cde4f44d60eb12e12273 | refs/heads/master | 2020-03-28T00:04:48.016948 | 2018-09-04T13:32:38 | 2018-09-04T13:32:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,891 | hpp | #pragma once
// SCUM (0.1.17.8320) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "SCUM_CoreUObject_structs.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// Class CoreUObject.Object
// 0x0028
class UObject
{
public:
static FUObjectArray* GObjects; // 0x0000(0x0000)
void* Vtable; // 0x0000(0x0000) NOT AUTO-GENERATED PROPERTY
int32_t ObjectFlags; // 0x0000(0x0000) NOT AUTO-GENERATED PROPERTY
int32_t InternalIndex; // 0x0000(0x0000) NOT AUTO-GENERATED PROPERTY
class UClass* Class; // 0x0000(0x0000) NOT AUTO-GENERATED PROPERTY
FName Name; // 0x0000(0x0000) NOT AUTO-GENERATED PROPERTY
class UObject* Outer; // 0x0000(0x0000) NOT AUTO-GENERATED PROPERTY
static inline TUObjectArray& GetGlobalObjects()
{
return GObjects->ObjObjects;
}
std::string GetName() const;
std::string GetFullName() const;
template<typename T>
static T* FindObject(const std::string& name)
{
for (int i = 0; i < GetGlobalObjects().Num(); ++i)
{
auto object = GetGlobalObjects().GetByIndex(i);
if (object == nullptr)
{
continue;
}
if (object->GetFullName() == name)
{
return static_cast<T*>(object);
}
}
return nullptr;
}
static UClass* FindClass(const std::string& name)
{
return FindObject<UClass>(name);
}
template<typename T>
static T* GetObjectCasted(std::size_t index)
{
return static_cast<T*>(GetGlobalObjects().GetByIndex(index));
}
bool IsA(UClass* cmp) const;
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.Object");
return ptr;
}
inline void ProcessEvent(class UFunction* function, void* parms)
{
return GetVFunction<void(*)(UObject*, class UFunction*, void*)>(this, 63)(this, function, parms);
}
void ExecuteUbergraph(int EntryPoint);
};
// Class CoreUObject.Interface
// 0x0000 (0x0028 - 0x0028)
class UInterface : public UObject
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.Interface");
return ptr;
}
};
// Class CoreUObject.GCObjectReferencer
// 0x0038 (0x0060 - 0x0028)
class UGCObjectReferencer : public UObject
{
public:
unsigned char UnknownData00[0x38]; // 0x0028(0x0038) MISSED OFFSET
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.GCObjectReferencer");
return ptr;
}
};
// Class CoreUObject.TextBuffer
// 0x0028 (0x0050 - 0x0028)
class UTextBuffer : public UObject
{
public:
unsigned char UnknownData00[0x28]; // 0x0028(0x0028) MISSED OFFSET
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.TextBuffer");
return ptr;
}
};
// Class CoreUObject.Field
// 0x0008 (0x0030 - 0x0028)
class UField : public UObject
{
public:
class UField* Next; // 0x0000(0x0000) NOT AUTO-GENERATED PROPERTY
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.Field");
return ptr;
}
};
// Class CoreUObject.Struct
// 0x0058 (0x0088 - 0x0030)
class UStruct : public UField
{
public:
class UStruct* SuperField; // 0x0000(0x0000) NOT AUTO-GENERATED PROPERTY
class UField* Children; // 0x0000(0x0000) NOT AUTO-GENERATED PROPERTY
int32_t PropertySize; // 0x0000(0x0000) NOT AUTO-GENERATED PROPERTY
int32_t MinAlignment; // 0x0000(0x0000) NOT AUTO-GENERATED PROPERTY
unsigned char UnknownData0x0048[0x40]; // 0x0000(0x0000) NOT AUTO-GENERATED PROPERTY
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.Struct");
return ptr;
}
};
// Class CoreUObject.ScriptStruct
// 0x0010 (0x0098 - 0x0088)
class UScriptStruct : public UStruct
{
public:
unsigned char UnknownData00[0x10]; // 0x0088(0x0010) MISSED OFFSET
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.ScriptStruct");
return ptr;
}
};
// Class CoreUObject.Package
// 0x0070 (0x0098 - 0x0028)
class UPackage : public UObject
{
public:
unsigned char UnknownData00[0x70]; // 0x0028(0x0070) MISSED OFFSET
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.Package");
return ptr;
}
};
// Class CoreUObject.Class
// 0x0170 (0x01F8 - 0x0088)
class UClass : public UStruct
{
public:
unsigned char UnknownData00[0x170]; // 0x0088(0x0170) MISSED OFFSET
template<typename T>
inline T* CreateDefaultObject()
{
return static_cast<T*>(CreateDefaultObject());
}
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.Class");
return ptr;
}
inline UObject* CreateDefaultObject()
{
return GetVFunction<UObject*(*)(UClass*)>(this, 100)(this);
}
};
// Class CoreUObject.Function
// 0x0030 (0x00B8 - 0x0088)
class UFunction : public UStruct
{
public:
int32_t FunctionFlags; // 0x0000(0x0000) NOT AUTO-GENERATED PROPERTY
int16_t RepOffset; // 0x0000(0x0000) NOT AUTO-GENERATED PROPERTY
int8_t NumParms; // 0x0000(0x0000) NOT AUTO-GENERATED PROPERTY
int16_t ParmsSize; // 0x0000(0x0000) NOT AUTO-GENERATED PROPERTY
int16_t ReturnValueOffset; // 0x0000(0x0000) NOT AUTO-GENERATED PROPERTY
int16_t RPCId; // 0x0000(0x0000) NOT AUTO-GENERATED PROPERTY
int16_t RPCResponseId; // 0x0000(0x0000) NOT AUTO-GENERATED PROPERTY
class UProperty* FirstPropertyToInit; // 0x0000(0x0000) NOT AUTO-GENERATED PROPERTY
class UFunction* EventGraphFunction; // 0x0000(0x0000) NOT AUTO-GENERATED PROPERTY
int32_t EventGraphCallOffset; // 0x0000(0x0000) NOT AUTO-GENERATED PROPERTY
void* Func; // 0x0000(0x0000) NOT AUTO-GENERATED PROPERTY
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.Function");
return ptr;
}
};
// Class CoreUObject.DelegateFunction
// 0x0000 (0x00B8 - 0x00B8)
class UDelegateFunction : public UFunction
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.DelegateFunction");
return ptr;
}
};
// Class CoreUObject.DynamicClass
// 0x0068 (0x0260 - 0x01F8)
class UDynamicClass : public UClass
{
public:
unsigned char UnknownData00[0x68]; // 0x01F8(0x0068) MISSED OFFSET
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.DynamicClass");
return ptr;
}
};
// Class CoreUObject.PackageMap
// 0x00B8 (0x00E0 - 0x0028)
class UPackageMap : public UObject
{
public:
unsigned char UnknownData00[0xB8]; // 0x0028(0x00B8) MISSED OFFSET
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.PackageMap");
return ptr;
}
};
// Class CoreUObject.Enum
// 0x0030 (0x0060 - 0x0030)
class UEnum : public UField
{
public:
unsigned char UnknownData00[0x30]; // 0x0030(0x0030) MISSED OFFSET
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.Enum");
return ptr;
}
};
// Class CoreUObject.Property
// 0x0040 (0x0070 - 0x0030)
class UProperty : public UField
{
public:
unsigned char UnknownData00[0x40]; // 0x0030(0x0040) MISSED OFFSET
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.Property");
return ptr;
}
};
// Class CoreUObject.EnumProperty
// 0x0010 (0x0080 - 0x0070)
class UEnumProperty : public UProperty
{
public:
unsigned char UnknownData00[0x10]; // 0x0070(0x0010) MISSED OFFSET
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.EnumProperty");
return ptr;
}
};
// Class CoreUObject.LinkerPlaceholderClass
// 0x01B8 (0x03B0 - 0x01F8)
class ULinkerPlaceholderClass : public UClass
{
public:
unsigned char UnknownData00[0x1B8]; // 0x01F8(0x01B8) MISSED OFFSET
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.LinkerPlaceholderClass");
return ptr;
}
};
// Class CoreUObject.LinkerPlaceholderExportObject
// 0x00C8 (0x00F0 - 0x0028)
class ULinkerPlaceholderExportObject : public UObject
{
public:
unsigned char UnknownData00[0xC8]; // 0x0028(0x00C8) MISSED OFFSET
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.LinkerPlaceholderExportObject");
return ptr;
}
};
// Class CoreUObject.LinkerPlaceholderFunction
// 0x01B8 (0x0270 - 0x00B8)
class ULinkerPlaceholderFunction : public UFunction
{
public:
unsigned char UnknownData00[0x1B8]; // 0x00B8(0x01B8) MISSED OFFSET
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.LinkerPlaceholderFunction");
return ptr;
}
};
// Class CoreUObject.MetaData
// 0x00A0 (0x00C8 - 0x0028)
class UMetaData : public UObject
{
public:
unsigned char UnknownData00[0xA0]; // 0x0028(0x00A0) MISSED OFFSET
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.MetaData");
return ptr;
}
};
// Class CoreUObject.ObjectRedirector
// 0x0008 (0x0030 - 0x0028)
class UObjectRedirector : public UObject
{
public:
unsigned char UnknownData00[0x8]; // 0x0028(0x0008) MISSED OFFSET
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.ObjectRedirector");
return ptr;
}
};
// Class CoreUObject.ArrayProperty
// 0x0008 (0x0078 - 0x0070)
class UArrayProperty : public UProperty
{
public:
unsigned char UnknownData00[0x8]; // 0x0070(0x0008) MISSED OFFSET
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.ArrayProperty");
return ptr;
}
};
// Class CoreUObject.ObjectPropertyBase
// 0x0008 (0x0078 - 0x0070)
class UObjectPropertyBase : public UProperty
{
public:
unsigned char UnknownData00[0x8]; // 0x0070(0x0008) MISSED OFFSET
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.ObjectPropertyBase");
return ptr;
}
};
// Class CoreUObject.BoolProperty
// 0x0008 (0x0078 - 0x0070)
class UBoolProperty : public UProperty
{
public:
unsigned char UnknownData00[0x8]; // 0x0070(0x0008) MISSED OFFSET
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.BoolProperty");
return ptr;
}
};
// Class CoreUObject.NumericProperty
// 0x0000 (0x0070 - 0x0070)
class UNumericProperty : public UProperty
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.NumericProperty");
return ptr;
}
};
// Class CoreUObject.ByteProperty
// 0x0008 (0x0078 - 0x0070)
class UByteProperty : public UNumericProperty
{
public:
unsigned char UnknownData00[0x8]; // 0x0070(0x0008) MISSED OFFSET
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.ByteProperty");
return ptr;
}
};
// Class CoreUObject.ObjectProperty
// 0x0000 (0x0078 - 0x0078)
class UObjectProperty : public UObjectPropertyBase
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.ObjectProperty");
return ptr;
}
};
// Class CoreUObject.ClassProperty
// 0x0008 (0x0080 - 0x0078)
class UClassProperty : public UObjectProperty
{
public:
unsigned char UnknownData00[0x8]; // 0x0078(0x0008) MISSED OFFSET
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.ClassProperty");
return ptr;
}
};
// Class CoreUObject.DelegateProperty
// 0x0008 (0x0078 - 0x0070)
class UDelegateProperty : public UProperty
{
public:
unsigned char UnknownData00[0x8]; // 0x0070(0x0008) MISSED OFFSET
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.DelegateProperty");
return ptr;
}
};
// Class CoreUObject.DoubleProperty
// 0x0000 (0x0070 - 0x0070)
class UDoubleProperty : public UNumericProperty
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.DoubleProperty");
return ptr;
}
};
// Class CoreUObject.FloatProperty
// 0x0000 (0x0070 - 0x0070)
class UFloatProperty : public UNumericProperty
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.FloatProperty");
return ptr;
}
};
// Class CoreUObject.IntProperty
// 0x0000 (0x0070 - 0x0070)
class UIntProperty : public UNumericProperty
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.IntProperty");
return ptr;
}
};
// Class CoreUObject.Int16Property
// 0x0000 (0x0070 - 0x0070)
class UInt16Property : public UNumericProperty
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.Int16Property");
return ptr;
}
};
// Class CoreUObject.Int64Property
// 0x0000 (0x0070 - 0x0070)
class UInt64Property : public UNumericProperty
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.Int64Property");
return ptr;
}
};
// Class CoreUObject.Int8Property
// 0x0000 (0x0070 - 0x0070)
class UInt8Property : public UNumericProperty
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.Int8Property");
return ptr;
}
};
// Class CoreUObject.InterfaceProperty
// 0x0008 (0x0078 - 0x0070)
class UInterfaceProperty : public UProperty
{
public:
unsigned char UnknownData00[0x8]; // 0x0070(0x0008) MISSED OFFSET
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.InterfaceProperty");
return ptr;
}
};
// Class CoreUObject.LazyObjectProperty
// 0x0000 (0x0078 - 0x0078)
class ULazyObjectProperty : public UObjectPropertyBase
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.LazyObjectProperty");
return ptr;
}
};
// Class CoreUObject.MapProperty
// 0x0038 (0x00A8 - 0x0070)
class UMapProperty : public UProperty
{
public:
unsigned char UnknownData00[0x38]; // 0x0070(0x0038) MISSED OFFSET
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.MapProperty");
return ptr;
}
};
// Class CoreUObject.MulticastDelegateProperty
// 0x0008 (0x0078 - 0x0070)
class UMulticastDelegateProperty : public UProperty
{
public:
unsigned char UnknownData00[0x8]; // 0x0070(0x0008) MISSED OFFSET
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.MulticastDelegateProperty");
return ptr;
}
};
// Class CoreUObject.NameProperty
// 0x0000 (0x0070 - 0x0070)
class UNameProperty : public UProperty
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.NameProperty");
return ptr;
}
};
// Class CoreUObject.SetProperty
// 0x0028 (0x0098 - 0x0070)
class USetProperty : public UProperty
{
public:
unsigned char UnknownData00[0x28]; // 0x0070(0x0028) MISSED OFFSET
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.SetProperty");
return ptr;
}
};
// Class CoreUObject.SoftObjectProperty
// 0x0000 (0x0078 - 0x0078)
class USoftObjectProperty : public UObjectPropertyBase
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.SoftObjectProperty");
return ptr;
}
};
// Class CoreUObject.SoftClassProperty
// 0x0008 (0x0080 - 0x0078)
class USoftClassProperty : public USoftObjectProperty
{
public:
unsigned char UnknownData00[0x8]; // 0x0078(0x0008) MISSED OFFSET
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.SoftClassProperty");
return ptr;
}
};
// Class CoreUObject.StrProperty
// 0x0000 (0x0070 - 0x0070)
class UStrProperty : public UProperty
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.StrProperty");
return ptr;
}
};
// Class CoreUObject.StructProperty
// 0x0008 (0x0078 - 0x0070)
class UStructProperty : public UProperty
{
public:
unsigned char UnknownData00[0x8]; // 0x0070(0x0008) MISSED OFFSET
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.StructProperty");
return ptr;
}
};
// Class CoreUObject.UInt16Property
// 0x0000 (0x0070 - 0x0070)
class UUInt16Property : public UNumericProperty
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.UInt16Property");
return ptr;
}
};
// Class CoreUObject.UInt32Property
// 0x0000 (0x0070 - 0x0070)
class UUInt32Property : public UNumericProperty
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.UInt32Property");
return ptr;
}
};
// Class CoreUObject.UInt64Property
// 0x0000 (0x0070 - 0x0070)
class UUInt64Property : public UNumericProperty
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.UInt64Property");
return ptr;
}
};
// Class CoreUObject.WeakObjectProperty
// 0x0000 (0x0078 - 0x0078)
class UWeakObjectProperty : public UObjectPropertyBase
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.WeakObjectProperty");
return ptr;
}
};
// Class CoreUObject.TextProperty
// 0x0000 (0x0070 - 0x0070)
class UTextProperty : public UProperty
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>("Class CoreUObject.TextProperty");
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"igromanru@yahoo.de"
] | igromanru@yahoo.de |
b31fbebc05a9a7bedd685fabbe5ee52d974694fb | c9244ef34e21509984f37dd60b6d1f6e7c92506a | /hw3/src/db/dbCmd.cpp | 7eccc004ba309b241f6cd47a52ea5426e49503f9 | [] | no_license | Kenchu123/DSnP | 2d56bed53ff10817d2efddad93148a97effe106b | 8540dfaaad70ce21ddc1daf33db94575cb4cf6fb | refs/heads/master | 2023-02-16T01:10:38.208961 | 2021-01-03T06:33:59 | 2021-01-03T06:33:59 | 207,793,323 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 10,293 | cpp | /****************************************************************************
FileName [ dbCmd.cpp ]
PackageName [ db ]
Synopsis [ Define database commands ]
Author [ Chung-Yang (Ric) Huang ]
Copyright [ Copyleft(c) 2015-present LaDs(III), GIEE, NTU, Taiwan ]
****************************************************************************/
#include <iostream>
#include <iomanip>
#include <cassert>
#include <cmath>
#include "util.h"
#include "dbCmd.h"
#include "dbJson.h"
// Global variable
DBJson dbjson;
bool
initDbCmd()
{
// TODO...
vector<bool> check;
check.push_back(cmdMgr->regCmd("DBAPpend", 4, new DBAppendCmd));
check.push_back(cmdMgr->regCmd("DBAVerage", 4, new DBAveCmd));
check.push_back(cmdMgr->regCmd("DBCount", 3, new DBCountCmd));
check.push_back(cmdMgr->regCmd("DBMAx", 4, new DBMaxCmd));
check.push_back(cmdMgr->regCmd("DBMIn", 4, new DBMinCmd));
check.push_back(cmdMgr->regCmd("DBPrint", 3, new DBPrintCmd));
check.push_back(cmdMgr->regCmd("DBRead", 3, new DBReadCmd));
check.push_back(cmdMgr->regCmd("DBSOrt", 4, new DBSortCmd));
check.push_back(cmdMgr->regCmd("DBSUm", 4, new DBSumCmd));
for (auto i : check) {
if (!i) {
cerr << "Registering \"init\" commands fails... exiting" << endl;
return false;
}
}
return true;
}
//----------------------------------------------------------------------
// DBAPpend <(string key)><(int value)>
//----------------------------------------------------------------------
CmdExecStatus
DBAppendCmd::exec(const string& option)
{
// TODO...
// check db is created
if (!dbjson) {
cerr << "Error: DB is not created yet!!" << endl;
return CMD_EXEC_ERROR;
}
// check option
vector<string> tokens;
if (!CmdExec::lexOptions(option, tokens, 2))
return CMD_EXEC_ERROR;
// check valid
string key = tokens[0];
int value;
if (!isValidVarName(key))
return CmdExec::errorOption(CMD_OPT_ILLEGAL, key);
if (!myStr2Int(tokens[1], value))
return CmdExec::errorOption(CMD_OPT_ILLEGAL, tokens[1]);
DBJsonElem ele(key, value);
if (!dbjson.add(ele)) {
cerr << "Element with key \"" << key << "\" already exists!!" << endl;
return CMD_EXEC_ERROR;
}
return CMD_EXEC_DONE;
}
void
DBAppendCmd::usage(ostream& os) const
{
os << "Usage: DBAPpend <(string key)><(int value)>" << endl;
}
void
DBAppendCmd::help() const
{
cout << setw(15) << left << "DBAPpend: "
<< "append an JSON element (key-value pair) to the end of DB" << endl;
}
//----------------------------------------------------------------------
// DBAVerage
//----------------------------------------------------------------------
CmdExecStatus
DBAveCmd::exec(const string& option)
{
// check option
if (!CmdExec::lexNoOption(option))
return CMD_EXEC_ERROR;
float a = dbjson.ave();
if (isnan(a)) {
cerr << "Error: The average of the DB is nan." << endl;
return CMD_EXEC_ERROR;
}
ios_base::fmtflags origFlags = cout.flags();
cout << "The average of the DB is " << fixed
<< setprecision(2) << a << ".\n";
cout.flags(origFlags);
return CMD_EXEC_DONE;
}
void
DBAveCmd::usage(ostream& os) const
{
os << "Usage: DBAVerage" << endl;
}
void
DBAveCmd::help() const
{
cout << setw(15) << left << "DBAVerage: "
<< "compute the average of the DB" << endl;
}
//----------------------------------------------------------------------
// DBCount
//----------------------------------------------------------------------
CmdExecStatus
DBCountCmd::exec(const string& option)
{
// check option
if (!CmdExec::lexNoOption(option))
return CMD_EXEC_ERROR;
size_t n = dbjson.size();
if (n > 1)
cout << "There are " << n << " JSON elements in DB." << endl;
else if (n == 1)
cout << "There is 1 JSON element in DB." << endl;
else
cout << "There is no JSON element in DB." << endl;
return CMD_EXEC_DONE;
}
void
DBCountCmd::usage(ostream& os) const
{
os << "Usage: DBCount" << endl;
}
void
DBCountCmd::help() const
{
cout << setw(15) << left << "DBCount: "
<< "report the number of JSON elements in the DB" << endl;
}
//----------------------------------------------------------------------
// DBMAx
//----------------------------------------------------------------------
CmdExecStatus
DBMaxCmd::exec(const string& option)
{
// check option
if (!CmdExec::lexNoOption(option))
return CMD_EXEC_ERROR;
size_t maxI;
int maxN = dbjson.max(maxI);
if (maxN == INT_MIN) {
cerr << "Error: The max JSON element is nan." << endl;
return CMD_EXEC_ERROR;
}
cout << "The max JSON element is { " << dbjson[maxI] << " }." << endl;
return CMD_EXEC_DONE;
}
void
DBMaxCmd::usage(ostream& os) const
{
os << "Usage: DBMAx" << endl;
}
void
DBMaxCmd::help() const
{
cout << setw(15) << left << "DBMAx: "
<< "report the maximum JSON element" << endl;
}
//----------------------------------------------------------------------
// DBMIn
//----------------------------------------------------------------------
CmdExecStatus
DBMinCmd::exec(const string& option)
{
// check option
if (!CmdExec::lexNoOption(option))
return CMD_EXEC_ERROR;
size_t minI;
int minN = dbjson.min(minI);
if (minN == INT_MAX) {
cerr << "Error: The min JSON element is nan." << endl;
return CMD_EXEC_ERROR;
}
cout << "The min JSON element is { " << dbjson[minI] << " }." << endl;
return CMD_EXEC_DONE;
}
void
DBMinCmd::usage(ostream& os) const
{
os << "Usage: DBMIn" << endl;
}
void
DBMinCmd::help() const
{
cout << setw(15) << left << "DBMIn: "
<< "report the minimum JSON element" << endl;
}
//----------------------------------------------------------------------
// DBPrint [(string key)]
//----------------------------------------------------------------------
CmdExecStatus
DBPrintCmd::exec(const string& option)
{
// TODO...
// check single option
string token;
if (!CmdExec::lexSingleOption(option, token))
return CMD_EXEC_ERROR;
if (!dbjson) {
cerr << "Error: DB is not created yet!!" << endl;
return CMD_EXEC_ERROR;
}
// has option
if (token.size()) {
// check key(token) is in _obj
bool isFound = 0;
for (size_t i = 0;i < dbjson.size(); ++i) {
if (dbjson[i].key() == token) {
isFound = 1;
cout << "{ " << dbjson[i] << " }" << endl;
break;
}
}
if (!isFound) {
cerr << "Error: No JSON element with key \"" << token << "\" is found." << endl;
return CMD_EXEC_ERROR;
}
}
// no option
else cout << dbjson;
return CMD_EXEC_DONE;
}
void
DBPrintCmd::usage(ostream& os) const
{
os << "DBPrint [(string key)]" << endl;
}
void
DBPrintCmd::help() const
{
cout << setw(15) << left << "DBPrint: "
<< "print the JSON element(s) in the DB" << endl;
}
//----------------------------------------------------------------------
// DBRead <(string jsonFile)> [-Replace]
//----------------------------------------------------------------------
CmdExecStatus
DBReadCmd::exec(const string& option)
{
// check option
vector<string> options;
if (!CmdExec::lexOptions(option, options))
return CMD_EXEC_ERROR;
if (options.empty())
return CmdExec::errorOption(CMD_OPT_MISSING, "");
bool doReplace = false;
string fileName;
for (size_t i = 0, n = options.size(); i < n; ++i) {
if (myStrNCmp("-Replace", options[i], 2) == 0) {
if (doReplace) return CmdExec::errorOption(CMD_OPT_EXTRA,options[i]);
doReplace = true;
}
else {
if (fileName.size())
return CmdExec::errorOption(CMD_OPT_ILLEGAL, options[i]);
fileName = options[i];
}
}
ifstream ifs(fileName.c_str());
if (!ifs) {
cerr << "Error: \"" << fileName << "\" does not exist!!" << endl;
return CMD_EXEC_ERROR;
}
if (dbjson) {
if (!doReplace) {
cerr << "Error: DB exists. Use \"-Replace\" option for "
<< "replacement.\n";
return CMD_EXEC_ERROR;
}
cout << "DB is replaced..." << endl;
dbjson.reset();
}
// if (!(ifs >> dbtbl)) return CMD_EXEC_ERROR;
ifs >> dbjson;
cout << "\"" << fileName << "\" was read in successfully." << endl;
return CMD_EXEC_DONE;
}
void
DBReadCmd::usage(ostream& os) const
{
os << "Usage: DBRead <(string jsonFile)> [-Replace]" << endl;
}
void
DBReadCmd::help() const
{
cout << setw(15) << left << "DBRead: "
<< "read data from .json file" << endl;
}
//----------------------------------------------------------------------
// DBSOrt <-Key | -Value>
//----------------------------------------------------------------------
CmdExecStatus
DBSortCmd::exec(const string& option)
{
// check option
string token;
if (!CmdExec::lexSingleOption(option, token, false))
return CMD_EXEC_ERROR;
if (myStrNCmp("-Key", token, 2) == 0) dbjson.sort(DBSortKey());
else if (myStrNCmp("-Value", token, 2) == 0) dbjson.sort(DBSortValue());
else return CmdExec::errorOption(CMD_OPT_ILLEGAL, token);
return CMD_EXEC_DONE;
}
void
DBSortCmd::usage(ostream& os) const
{
os << "Usage: DBSOrt <-Key | -Value>" << endl;
}
void
DBSortCmd::help() const
{
cout << setw(15) << left << "DBSOrt: "
<< "sort the JSON object by key or value" << endl;
}
//----------------------------------------------------------------------
// DBSUm
//----------------------------------------------------------------------
CmdExecStatus
DBSumCmd::exec(const string& option)
{
// check option
if (!CmdExec::lexNoOption(option))
return CMD_EXEC_ERROR;
if (dbjson.empty()) {
cerr << "Error: The sum of the DB is nan." << endl;
return CMD_EXEC_ERROR;
}
cout << "The sum of the DB is " << dbjson.sum() << "." << endl;
return CMD_EXEC_DONE;
}
void
DBSumCmd::usage(ostream& os) const
{
os << "Usage: DBSUm" << endl;
}
void
DBSumCmd::help() const
{
cout << setw(15) << left << "DBSUm: "
<< "compute the summation of the DB" << endl;
}
| [
"k88913n@gmail.com"
] | k88913n@gmail.com |
615911ce6dfb978ac3a0b842fb4dabffe6d1915b | abcab8cbc42fe8059c3927f03f86db2995ab5eeb | /out/include/sys/thread/Lock.h | 69eb1cfda76de39524e6a07b9b321c910c3f3d72 | [
"MIT"
] | permissive | sonygod/pb | 8fb6a8d2152637f203c35e1d77629cbdec92931c | a1bdc04c74bd91c71e96feb9f673075e780cbc81 | refs/heads/master | 2020-08-16T19:13:17.999773 | 2020-06-06T03:38:05 | 2020-06-06T03:38:05 | 215,273,448 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | true | 2,132 | h | // Generated by Haxe 4.1.0-rc.1+0545ce110
#ifndef INCLUDED_sys_thread_Lock
#define INCLUDED_sys_thread_Lock
#ifndef HXCPP_H
#include <hxcpp.h>
#endif
HX_DECLARE_STACK_FRAME(_hx_pos_f17acceeafd9582a_30_new)
HX_DECLARE_CLASS2(sys,thread,Lock)
namespace sys{
namespace thread{
class HXCPP_CLASS_ATTRIBUTES Lock_obj : public hx::Object
{
public:
typedef hx::Object super;
typedef Lock_obj OBJ_;
Lock_obj();
public:
enum { _hx_ClassId = 0x0ed2d2f6 };
void __construct();
inline void *operator new(size_t inSize, bool inContainer=true,const char *inName="sys.thread.Lock")
{ return hx::Object::operator new(inSize,inContainer,inName); }
inline void *operator new(size_t inSize, int extra)
{ return hx::Object::operator new(inSize+extra,true,"sys.thread.Lock"); }
inline static hx::ObjectPtr< Lock_obj > __new() {
hx::ObjectPtr< Lock_obj > __this = new Lock_obj();
__this->__construct();
return __this;
}
inline static hx::ObjectPtr< Lock_obj > __alloc(hx::Ctx *_hx_ctx) {
Lock_obj *__this = (Lock_obj*)(hx::Ctx::alloc(_hx_ctx, sizeof(Lock_obj), true, "sys.thread.Lock"));
*(void **)__this = Lock_obj::_hx_vtable;
{
HX_STACKFRAME(&_hx_pos_f17acceeafd9582a_30_new)
HXDLIN( 30) ( ( ::sys::thread::Lock)(__this) )->l = ::__hxcpp_lock_create();
}
return __this;
}
static void * _hx_vtable;
static Dynamic __CreateEmpty();
static Dynamic __Create(hx::DynamicArray inArgs);
//~Lock_obj();
HX_DO_RTTI_ALL;
hx::Val __Field(const ::String &inString, hx::PropertyAccess inCallProp);
hx::Val __SetField(const ::String &inString,const hx::Val &inValue, hx::PropertyAccess inCallProp);
void __GetFields(Array< ::String> &outFields);
static void __register();
void __Mark(HX_MARK_PARAMS);
void __Visit(HX_VISIT_PARAMS);
bool _hx_isInstanceOf(int inClassId);
::String __ToString() const { return HX_("Lock",0b,c8,90,32); }
::Dynamic l;
bool wait( ::Dynamic timeout);
::Dynamic wait_dyn();
void release();
::Dynamic release_dyn();
};
} // end namespace sys
} // end namespace thread
#endif /* INCLUDED_sys_thread_Lock */
| [
"sonygodx@gmail.com"
] | sonygodx@gmail.com |
322ff2aff3d8a7588f253a3aa69dd04ce5c54007 | 6a82b383545f4500df5c26afd17cf03e0e89d292 | /opendnp3/DNP3/ClassCounter.h | 9738df4a203520ff8b2a1ebdb4d8de62946c525c | [] | no_license | nitesh-agsft/internal-projects | 98f8de64c981601219ce07d80905a5d505beb310 | c2bd16857a9701795b4ad1ba932a0fa63577c98c | refs/heads/master | 2021-01-16T17:39:00.655783 | 2017-10-09T13:02:25 | 2017-10-09T13:02:25 | 100,011,951 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,753 | h | //
// Licensed to Green Energy Corp (www.greenenergycorp.com) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. Green Enery Corp licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
#ifndef __CLASS_COUNTER_H_
#define __CLASS_COUNTER_H_
#include <stddef.h>
#include <assert.h>
#include "DNPDatabaseTypes.h"
#include <opendnp3/APL/Types.h>
namespace apl
{
namespace dnp
{
/** Utility class that keeps class event counters accessible by enumeration.
*/
class ClassCounter
{
public:
ClassCounter() : mNumClass1(0), mNumClass2(0), mNumClass3(0) {};
~ClassCounter() {};
inline size_t GetNum(PointClass aClass) {
switch(aClass) {
case(PC_CLASS_1):
return mNumClass1;
case(PC_CLASS_2):
return mNumClass2;
case(PC_CLASS_3):
return mNumClass3;
case(PC_ALL_EVENTS):
return mNumClass1 + mNumClass2 + mNumClass3;
default:
return 0;
}
}
size_t GetNumAllClass() {
return mNumClass1 + mNumClass2 + mNumClass3;
}
void IncrCount(dnp::PointClass aClass);
void DecrCount(dnp::PointClass aClass);
private:
size_t mNumClass1;
size_t mNumClass2;
size_t mNumClass3;
};
}
}
#endif
| [
"nitesh@agsft.com"
] | nitesh@agsft.com |
ef02bd76025f308b4a5bba4ecf6cbdbcf58df40d | 0fee103f9ed82978144d9741e46882c7df9eedb1 | /UOJ/UNR5/Day1/B.cpp | 2719893179197e0fbbba9204880cd2cb17201532 | [] | no_license | Flying2019/testgit | 2776b6bc3a5839a005726ff108fb69d971065871 | 86a42bb1d4bfd65b5471373f03162270013da2af | refs/heads/main | 2023-07-15T00:57:55.321869 | 2021-08-21T01:16:53 | 2021-08-21T01:16:53 | 302,891,112 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,971 | cpp | #include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>
#define N 3010
#define pb push_back
#define S(x) ((int)x.size())
#define MP make_pair
#define fi first
#define se second
#define mod 998244353
using namespace std;
int n;
vector<int>g[N];
namespace Root{
int siz[N],mx,rt;
void dfs(int u,int p)
{
siz[u]=1;
int mr=0;
for(int v:g[u]) if(v!=p) dfs(v,u),siz[u]+=siz[v],mr=max(mr,siz[v]);
mr=max(mr,n-siz[u]);
if(!rt || mx>mr) rt=u,mx=mr;
}
int find(){dfs(1,0);return rt;}
}
int fac[N],inv[N];
int ksm(int a,int b=mod-2)
{
int r=1;
for(;b;b>>=1)
{
if(b&1) r=1ll*r*a%mod;
a=1ll*a*a%mod;
}
return r;
}
int C(int a,int b){return a<b?0:1ll*fac[a]*inv[b]%mod*inv[a-b]%mod;}
void init(int n=N-10)
{
fac[0]=1;
for(int i=1;i<=n;i++) fac[i]=1ll*fac[i-1]*i%mod;
inv[n]=ksm(fac[n]);
for(int i=n-1;i>=0;i--) inv[i]=1ll*inv[i+1]*(i+1)%mod;
}
int f[N][N],sf[N],ss[N],sg[N];
string dfs(int u,int p)
{
vector<pair<string,int> > son;
for(int v:g[u]) if(v!=p) son.push_back(MP(dfs(v,u),v));
sort(son.begin(),son.end());
for(int i=0;i<=n;i++) sf[i]=0;
f[u][0]=1;
for(int l=0,r=0;l<S(son);l=r)
{
for(int p=0;p<=n;p++) sf[p]=0;
sf[0]=1;
for(r=l+1;r<S(son) && son[l].fi==son[r].fi;r++);
int v=son[l].se;
for(int p=0;p<=n;p++) ss[p]=f[u][p];
for(int i=l;i<r;i++)
{
for(int p=0;p<=n;p++) sg[p]=sf[p],sf[p]=0;
for(int p=0;p<=n;p++)
for(int j=1;j<=p;j++)
sf[p]=(sf[p]+1ll*sg[p-j]*f[v][j]%mod*C(p,j))%mod;
for(int p=0;p<=n;p++)
for(int j=0;j<=p;j++)
f[u][p]=(f[u][p]+1ll*sf[j]*ss[p-j]%mod*inv[i-l+1]%mod*C(p,j))%mod;
}
}
for(int p=n-1;p>=0;p--) f[u][p+1]=(f[u][p+1]+1ll*f[u][p]*(p+1)%mod)%mod;
string a;
for(auto v:son) a+="0"+v.fi+"1";
return a;
}
int main()
{
init();
scanf("%d",&n);
for(int i=1,u,v;i<n;i++) scanf("%d%d",&u,&v),g[u].pb(v),g[v].pb(u);
int u=Root::find();Root::dfs(u,0);
for(int v:g[u])
if(Root::siz[v]*2==n)
{
auto a=dfs(u,v),b=dfs(v,u);
if(a==b)
{
for(int p=0;p<=n;p++) sf[p]=0;
f[0][0]=1;
sf[0]=1;
u=0;
for(int p=0;p<=n;p++) ss[p]=f[u][p];
for(int i=1;i<=2;i++)
{
for(int p=0;p<=n;p++) sg[p]=sf[p],sf[p]=0;
for(int p=0;p<=n;p++)
for(int j=1;j<=p;j++)
sf[p]=(sf[p]+1ll*sg[p-j]*f[v][j]%mod*C(p,j))%mod;
for(int p=0;p<=n;p++)
for(int j=0;j<=p;j++)
f[u][p]=(f[u][p]+1ll*sf[j]*ss[p-j]%mod*inv[i]%mod*C(p,j))%mod;
}
}
break;
}
if(u) dfs(u,0);
for(int i=1;i<=n;i++) printf("%d ",f[u][i]);
return 0;
} | [
"815375530@qq.com"
] | 815375530@qq.com |
a90f1a906cb4aed512ab762b8e4a5013a153fbc5 | 5bf8868cbf5c7da6f14fefb8cc0fd4d968fe9e7f | /Tests/Parser/main.cpp | 254e8347484bbbce7f22323d269163d29582a60b | [
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause-LBNL"
] | permissive | mrowan137/amrex | 13ae249c00d775eff87c0392d8b27efaf0cc4812 | 3aa6b21d1f1ed9c51c7aa93692d90c1ee6a17a82 | refs/heads/master | 2022-03-18T15:57:09.287381 | 2022-02-15T01:59:33 | 2022-02-15T01:59:33 | 219,851,095 | 0 | 0 | NOASSERTION | 2019-11-05T21:10:03 | 2019-11-05T21:10:03 | null | UTF-8 | C++ | false | false | 21,027 | cpp | #include <AMReX.H>
#include <AMReX_Parser.H>
#include <AMReX_IParser.H>
#include <map>
using namespace amrex;
static int max_stack_size = 0;
static int test_number = 0;
template <typename F>
int test1 (std::string const& f,
std::map<std::string,Real> const& constants,
Vector<std::string> const& variables,
F && fb, Array<Real,1> const& lo, Array<Real,1> const& hi,
int N, Real reltol, Real abstol)
{
amrex::Print() << test_number++ << ". Testing \"" << f << "\" ";
Parser parser(f);
for (auto const& kv : constants) {
parser.setConstant(kv.first, kv.second);
}
parser.registerVariables(variables);
auto const exe = parser.compile<1>();
max_stack_size = std::max(max_stack_size, parser.maxStackSize());
GpuArray<Real,1> dx{(hi[0]-lo[0]) / (N-1)};
int nfail = 0;
Real max_relerror = 0.;
for (int i = 0; i < N; ++i) {
Real x = lo[0] + i*dx[0];
double result = exe(x);
double benchmark = fb(x);
double abserror = std::abs(result-benchmark);
double relerror = abserror / (1.e-50 + std::max(std::abs(result),std::abs(benchmark)));
if (abserror > abstol && relerror > reltol) {
amrex::Print() << "\n f(" << x << ") = " << result << ", "
<< benchmark;
max_relerror = std::max(max_relerror, relerror);
++nfail;
}
}
if (nfail > 0) {
amrex::Print() << "\n failed " << nfail << " times. Max rel. error: "
<< max_relerror << "\n";
return 1;
} else {
amrex::Print() << " pass\n";
return 0;
}
}
template <typename F>
int test3 (std::string const& f,
std::map<std::string,Real> const& constants,
Vector<std::string> const& variables,
F && fb, Array<Real,3> const& lo, Array<Real,3> const& hi,
int N, Real reltol, Real abstol)
{
amrex::Print() << test_number++ << ". Testing \"" << f << "\" ";
Parser parser(f);
for (auto const& kv : constants) {
parser.setConstant(kv.first, kv.second);
}
parser.registerVariables(variables);
auto const exe = parser.compile<3>();
max_stack_size = std::max(max_stack_size, parser.maxStackSize());
GpuArray<Real,3> dx{(hi[0]-lo[0]) / (N-1),
(hi[1]-lo[1]) / (N-1),
(hi[2]-lo[2]) / (N-1)};
int nfail = 0;
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N; ++j) {
for (int k = 0; k < N; ++k) {
Real x = lo[0] + i*dx[0];
Real y = lo[1] + j*dx[1];
Real z = lo[2] + k*dx[2];
double result = exe(x,y,z);
double benchmark = fb(x,y,z);
double abserror = std::abs(result-benchmark);
double relerror = abserror / (1.e-50 + std::max(std::abs(result),std::abs(benchmark)));
if (abserror > abstol && relerror > reltol) {
amrex::Print() << " f(" << x << "," << y << "," << z << ") = " << result << ", "
<< benchmark << "\n";
++nfail;
}
}}}
if (nfail > 0) {
amrex::Print() << " failed " << nfail << " times\n";
return 1;
} else {
amrex::Print() << " pass\n";
return 0;
}
}
template <typename F>
int test4 (std::string const& f,
std::map<std::string,Real> const& constants,
Vector<std::string> const& variables,
F && fb, Array<Real,4> const& lo, Array<Real,4> const& hi,
int N, Real reltol, Real abstol)
{
amrex::Print() << test_number++ << ". Testing \"" << f << "\" ";
Parser parser(f);
for (auto const& kv : constants) {
parser.setConstant(kv.first, kv.second);
}
parser.registerVariables(variables);
auto const exe = parser.compile<4>();
max_stack_size = std::max(max_stack_size, parser.maxStackSize());
GpuArray<Real,4> dx{(hi[0]-lo[0]) / (N-1),
(hi[1]-lo[1]) / (N-1),
(hi[2]-lo[2]) / (N-1),
(hi[3]-lo[3]) / (N-1)};
int nfail = 0;
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N; ++j) {
for (int k = 0; k < N; ++k) {
for (int m = 0; m < N; ++m) {
Real x = lo[0] + i*dx[0];
Real y = lo[1] + j*dx[1];
Real z = lo[2] + k*dx[2];
Real t = lo[3] + m*dx[3];
double result = exe(x,y,z,t);
double benchmark = fb(x,y,z,t);
double abserror = std::abs(result-benchmark);
double relerror = abserror / (1.e-50 + std::max(std::abs(result),std::abs(benchmark)));
if (abserror > abstol && relerror > reltol) {
amrex::Print() << " f(" << x << "," << y << "," << z << "," << t << ") = " << result << ", "
<< benchmark << "\n";
++nfail;
}
}}}}
if (nfail > 0) {
amrex::Print() << " failed " << nfail << " times\n";
return 1;
} else {
amrex::Print() << " pass\n";
return 0;
}
}
int main (int argc, char* argv[])
{
amrex::Initialize(argc, argv);
{
amrex::Print() << "\n";
int nerror = 0;
nerror += test3("if( ((z-zc)*(z-zc)+(y-yc)*(y-yc)+(x-xc)*(x-xc))^(0.5) < (r_star-dR), 0.0, if(((z-zc)*(z-zc)+(y-yc)*(y-yc)+(x-xc)*(x-xc))^(0.5) <= r_star, dens, 0.0))",
{{"xc", 0.1}, {"yc", -1.0}, {"zc", 0.2}, {"r_star", 0.73}, {"dR", 0.57}, {"dens", 12.}},
{"x","y","z"},
[=] (Real x, Real y, Real z) -> Real {
Real xc=0.1, yc=-1.0, zc=0.2, r_star=0.73, dR=0.57, dens=12.;
Real r = std::sqrt((z-zc)*(z-zc) + (y-yc)*(y-yc) + (x-xc)*(x-xc));
if (r >= r_star-dR && r <= r_star) {
return dens;
} else {
return 0.0;
}
},
{-1., -1., -1.0}, {1.0, 1.0, 1.0}, 100,
1.e-12, 1.e-15);
nerror += test3("r=sqrt((z-zc)*(z-zc)+(y-yc)*(y-yc)+(x-xc)*(x-xc)); if(r < (r_star-dR), 0.0, if(r <= r_star, dens, 0.0))",
{{"xc", 0.1}, {"yc", -1.0}, {"zc", 0.2}, {"r_star", 0.73}, {"dR", 0.57}, {"dens", 12.}},
{"x","y","z"},
[=] (Real x, Real y, Real z) -> Real {
Real xc=0.1, yc=-1.0, zc=0.2, r_star=0.73, dR=0.57, dens=12.;
Real r = std::sqrt((z-zc)*(z-zc) + (y-yc)*(y-yc) + (x-xc)*(x-xc));
if (r >= r_star-dR && r <= r_star) {
return dens;
} else {
return 0.0;
}
},
{-1., -1., -1.0}, {1.0, 1.0, 1.0}, 100,
1.e-12, 1.e-15);
nerror += test3("r2=(z-zc)*(z-zc)+(y-yc)*(y-yc)+(x-xc)*(x-xc); r=sqrt(r2); if(r < (r_star-dR), 0.0, if(r <= r_star, dens, 0.0))",
{{"xc", 0.1}, {"yc", -1.0}, {"zc", 0.2}, {"r_star", 0.73}, {"dR", 0.57}, {"dens", 12.}},
{"x","y","z"},
[=] (Real x, Real y, Real z) -> Real {
Real xc=0.1, yc=-1.0, zc=0.2, r_star=0.73, dR=0.57, dens=12.;
Real r = std::sqrt((z-zc)*(z-zc) + (y-yc)*(y-yc) + (x-xc)*(x-xc));
if (r >= r_star-dR && r <= r_star) {
return dens;
} else {
return 0.0;
}
},
{-1., -1., -1.0}, {1.0, 1.0, 1.0}, 100,
1.e-12, 1.e-15);
nerror += test3("( ((( (z-zc)*(z-zc) + (y-yc)*(y-yc) + (x-xc)*(x-xc) )^(0.5))<=r_star) * ((( (z-zc)*(z-zc) + (y-yc)*(y-yc) + (x-xc)*(x-xc) )^(0.5))>=(r_star-dR)) )*dens",
{{"xc", 0.1}, {"yc", -1.0}, {"zc", 0.2}, {"r_star", 0.73}, {"dR", 0.57}, {"dens", 12.}},
{"x","y","z"},
[=] (Real x, Real y, Real z) -> Real {
Real xc=0.1, yc=-1.0, zc=0.2, r_star=0.73, dR=0.57, dens=12.;
Real r = std::sqrt((z-zc)*(z-zc) + (y-yc)*(y-yc) + (x-xc)*(x-xc));
if (r >= r_star-dR && r <= r_star) {
return dens;
} else {
return 0.0;
}
},
{-1., -1., -1.0}, {1.0, 1.0, 1.0}, 100,
1.e-12, 1.e-15);
nerror += test4("( (( (z-zc)*(z-zc) + (y-yc)*(y-yc) + (x-xc)*(x-xc) )^(0.5))>=r_star)*(-( (t<to)*(t/to)*omega + (t>=to)*omega )*(((x-xc)*(x-xc) + (y-yc)*(y-yc))^(0.5))/((1.0-( ( (t<to)*(t/to)*omega + (t>=to)*omega) *(((x-xc)*(x-xc) + (y-yc)*(y-yc))^(0.5))/c)^2)^(0.5)) * (y-yc)/(((x-xc)*(x-xc) + (y-yc)*(y-yc))^(0.5)))",
{{"xc", 0.1}, {"yc", -1.0}, {"zc", 0.2}, {"to", 3.}, {"omega", 0.33}, {"c", 30.}, {"r_star", 0.75}},
{"x","y","z","t"},
[=] (Real x, Real y, Real z, Real t) -> Real {
Real xc=0.1, yc=-1.0, zc=0.2, to=3., omega=0.33, c=30., r_star=0.75;
Real r = std::sqrt((z-zc)*(z-zc) + (y-yc)*(y-yc) + (x-xc)*(x-xc));
if (r >= r_star) {
Real tomega = (t>=to) ? omega : omega*(t/to);
Real r2d = std::sqrt((x-xc)*(x-xc) + (y-yc)*(y-yc));
return -tomega * r / std::sqrt(1.0-(tomega*r2d/c)*(tomega*r2d/c)) * (y-yc)/r;
} else {
return 0.0;
}
},
{-1., -1., -1.0, 0.0}, {1.0, 1.0, 1.0, 10}, 30,
1.e-12, 1.e-15);
nerror += test4("r=sqrt((z-zc)*(z-zc) + (y-yc)*(y-yc) + (x-xc)*(x-xc)); tomega=if(t>=to, omega, omega*(t/to)); r2d=sqrt((y-yc)*(y-yc) + (x-xc)*(x-xc)); (r>=r_star)*(-tomega*r/(1.0-((tomega*r2d/c)^2))^0.5 * (y-yc)/r)",
{{"xc", 0.1}, {"yc", -1.0}, {"zc", 0.2}, {"to", 3.}, {"omega", 0.33}, {"c", 30.}, {"r_star", 0.75}},
{"x","y","z","t"},
[=] (Real x, Real y, Real z, Real t) -> Real {
Real xc=0.1, yc=-1.0, zc=0.2, to=3., omega=0.33, c=30., r_star=0.75;
Real r = std::sqrt((z-zc)*(z-zc) + (y-yc)*(y-yc) + (x-xc)*(x-xc));
if (r >= r_star) {
Real tomega = (t>=to) ? omega : omega*(t/to);
Real r2d = std::sqrt((x-xc)*(x-xc) + (y-yc)*(y-yc));
return -tomega * r / std::sqrt(1.0-(tomega*r2d/c)*(tomega*r2d/c)) * (y-yc)/r;
} else {
return 0.0;
}
},
{-1., -1., -1.0, 0.0}, {1.0, 1.0, 1.0, 10}, 30,
1.e-12, 1.e-15);
nerror += test3("cos(m * pi / Lx * (x - Lx / 2)) * cos(n * pi / Ly * (y - Ly / 2)) * sin(p * pi / Lz * (z - Lz / 2))*mu_0*(x>-0.5)*(x<0.5)*(y>-0.5)*(y<0.5)*(z>-0.5)*(z<0.5)",
{{"m", 0.0}, {"n", 1.0}, {"pi", 3.14}, {"p", 1.0}, {"Lx", 1.}, {"Ly", 1.}, {"Lz", 1.}, {"mu_0", 1.27e-6}},
{"x","y","z"},
[=] (Real x, Real y, Real z) -> Real {
Real m=0.0,n=1.0,pi=3.14,p=1.0,Lx=1.,Ly=1.,Lz=1.,mu_0=1.27e-6;
if ((x>-0.5) && (x<0.5) && (y>-0.5) && (y<0.5) && (z>-0.5) &&(z<0.5)) {
return std::cos(m * pi / Lx * (x - Lx / 2)) * std::cos(n * pi / Ly * (y - Ly / 2)) * std::sin(p * pi / Lz * (z - Lz / 2))*mu_0;
} else {
return 0.0;
}
},
{-0.8, -0.8, -0.8}, {0.8, 0.8, 0.8}, 100,
1.e-12, 1.e-15);
nerror += test3("if ((x>-0.5) and (x<0.5) and (y>-0.5) and (y<0.5) and (z>-0.5) and (z<0.5), cos(m * pi / Lx * (x - Lx / 2)) * cos(n * pi / Ly * (y - Ly / 2)) * sin(p * pi / Lz * (z - Lz / 2))*mu_0*(x>-0.5)*(x<0.5)*(y>-0.5)*(y<0.5)*(z>-0.5)*(z<0.5), 0)",
{{"m", 0.0}, {"n", 1.0}, {"pi", 3.14}, {"p", 1.0}, {"Lx", 1.}, {"Ly", 1.}, {"Lz", 1.}, {"mu_0", 1.27e-6}},
{"x","y","z"},
[=] (Real x, Real y, Real z) -> Real {
Real m=0.0,n=1.0,pi=3.14,p=1.0,Lx=1.,Ly=1.,Lz=1.,mu_0=1.27e-6;
if ((x>-0.5) && (x<0.5) && (y>-0.5) && (y<0.5) && (z>-0.5) &&(z<0.5)) {
return std::cos(m * pi / Lx * (x - Lx / 2)) * std::cos(n * pi / Ly * (y - Ly / 2)) * std::sin(p * pi / Lz * (z - Lz / 2))*mu_0;
} else {
return 0.0;
}
},
{-0.8, -0.8, -0.8}, {0.8, 0.8, 0.8}, 100,
1.e-12, 1.e-15);
nerror += test3("2.*sqrt(2.)+sqrt(-log(x))*cos(2*pi*z)",
{{"pi", 3.14}},
{"x","y","z"},
[=] (Real x, Real, Real z) -> Real {
Real pi = 3.14;
return 2.*std::sqrt(2.)+std::sqrt(-std::log(x))*std::cos(2*pi*z);
},
{0.5, 0.8, 0.3}, {16, 16, 16}, 100,
1.e-12, 1.e-15);
nerror += test1("nc*n0*(if(abs(z)<=r0, 1.0, if(abs(z)<r0+Lcut, exp((-abs(z)+r0)/L), 0.0)))",
{{"nc",1.742e27},{"n0",30.},{"r0",2.5e-6},{"Lcut",2.e-6},{"L",0.05e-6}},
{"z"},
[=] (Real z) -> Real {
Real nc=1.742e27, n0=30., r0=2.5e-6, Lcut=2.e-6, L=0.05e-6;
if (std::abs(z) <= r0) {
return nc*n0;
} else if (std::abs(z) < r0+Lcut) {
return nc*n0*std::exp((-std::abs(z)+r0)/L);
} else {
return 0.0;
}
},
{-5.e-6}, {25.e-6}, 10000,
1.e-12, 1.e-15);
nerror += test1("(z<lramp)*0.5*(1-cos(pi*z/lramp))*dens+(z>lramp)*dens",
{{"lramp",8.e-3},{"pi",3.14},{"dens",1.e23}},
{"z"},
[=] (Real z) -> Real {
Real lramp=8.e-3, pi=3.14, dens=1.e23;
if (z < lramp) {
return 0.5*(1-std::cos(pi*z/lramp))*dens;
} else {
return dens;
}
},
{-149.e-6}, {1.e-6}, 1000,
1.e-12, 1.e-15);
nerror += test1("if(z<lramp, 0.5*(1-cos(pi*z/lramp))*dens, dens)",
{{"lramp",8.e-3},{"pi",3.14},{"dens",1.e23}},
{"z"},
[=] (Real z) -> Real {
Real lramp=8.e-3, pi=3.14, dens=1.e23;
if (z < lramp) {
return 0.5*(1-std::cos(pi*z/lramp))*dens;
} else {
return dens;
}
},
{-149.e-6}, {1.e-6}, 1000,
1.e-12, 1.e-15);
nerror += test1("if(z<zp, nc*exp((z-zc)/lgrad), if(z<=zp2, 2.*nc, nc*exp(-(z-zc2)/lgrad)))",
{{"zc",20.e-6},{"zp",20.05545177444479562e-6},{"nc",1.74e27},{"lgrad",0.08e-6},{"zp2",24.e-6},{"zc2",24.05545177444479562e6}},
{"z"},
[=] (Real z) -> Real {
Real zc=20.e-6, zp=20.05545177444479562e-6, nc=1.74e27, lgrad=0.08e-6, zp2=24.e-6, zc2=24.05545177444479562e6;
if (z < zp) {
return nc*std::exp((z-zc)/lgrad);
} else if (z <= zp2) {
return 2.*nc;
} else {
return nc*exp(-(z-zc2)/lgrad);
}
},
{0.}, {100.e-6}, 1000,
1.e-12, 1.e-15);
nerror += test3("epsilon/kp*2*x/w0**2*exp(-(x**2+y**2)/w0**2)*sin(k0*z)",
{{"epsilon",0.01},{"kp",3.5},{"w0",5.e-6},{"k0",3.e5}},
{"x","y","z"},
[=] (Real x, Real y, Real z) -> Real {
Real epsilon=0.01, kp=3.5, w0=5.e-6, k0=3.e5;
return epsilon/kp*2*x/(w0*w0)*std::exp(-(x*x+y*y)/(w0*w0))*sin(k0*z);
},
{0.e-6, 0.0, -20.e-6}, {20.e-6, 1.e-10, 20.e-6}, 100,
1.e-12, 1.e-15);
amrex::Print() << "\nMax stack size is " << max_stack_size << "\n";
if (nerror > 0) {
amrex::Print() << nerror << " tests failed\n";
amrex::Abort();
} else {
amrex::Print() << "All tests passed\n";
}
amrex::Print() << "\n";
}
{
int count = 0;
int x = 11;
{
auto f = [&] (std::string s) -> int
{
amrex::Print() << count++ << ". Testing \"" << s << "\"\n";
IParser iparser(s);
iparser.registerVariables({"x"});
auto exe = iparser.compileHost<1>();
return exe(x);
};
AMREX_ALWAYS_ASSERT(f("2*(x/3)") == (2*(x/3)));
AMREX_ALWAYS_ASSERT(f("2*(3/x)") == (2*(3/x)));
AMREX_ALWAYS_ASSERT(f("2/(x/3)") == (2/(x/3)));
AMREX_ALWAYS_ASSERT(f("2/(22/x)") == (2/(22/x)));
AMREX_ALWAYS_ASSERT(f("x/13*5") == ((x/13)*5));
AMREX_ALWAYS_ASSERT(f("13/x*5") == ((13/x)*5));
AMREX_ALWAYS_ASSERT(f("x/13/5") == ((x/13)/5));
AMREX_ALWAYS_ASSERT(f("13/x/5") == ((13/x)/5));
auto g = [&] (std::string s, std::string c, int cv) -> int
{
amrex::Print() << count++ << ". Testing \"" << s << "\"\n";
IParser iparser(s);
iparser.registerVariables({"x"});
iparser.setConstant(c, cv);
auto exe = iparser.compileHost<1>();
return exe(x);
};
AMREX_ALWAYS_ASSERT(g("a*(x/3)", "a", 2) == (2*(x/3)));
AMREX_ALWAYS_ASSERT(g("a*(3/x)", "a", 2) == (2*(3/x)));
AMREX_ALWAYS_ASSERT(g("a/(x/3)", "a", 2) == (2/(x/3)));
AMREX_ALWAYS_ASSERT(g("a/(22/x)", "a", 2) == (2/(22/x)));
AMREX_ALWAYS_ASSERT(g("x/b*5", "b", 13) == ((x/13)*5));
AMREX_ALWAYS_ASSERT(g("b/x*5", "b", 13) == ((13/x)*5));
AMREX_ALWAYS_ASSERT(g("x/b/5", "b", 13) == ((x/13)/5));
AMREX_ALWAYS_ASSERT(g("b/x/5", "b", 13) == ((13/x)/5));
auto h = [&] (std::string s) -> int
{
amrex::Print() << count++ << ". Testing \"" << s << "\"\n";
IParser iparser(s);
auto exe = iparser.compileHost<0>();
return exe();
};
AMREX_ALWAYS_ASSERT(h("2**10") == 1024);
AMREX_ALWAYS_ASSERT(h("3^-1") == 1/3);
AMREX_ALWAYS_ASSERT(h("5^0") == 1);
AMREX_ALWAYS_ASSERT(h("(-2)**3") == -8);
AMREX_ALWAYS_ASSERT(h("(-3)**-1") == 1/(-3));
AMREX_ALWAYS_ASSERT(h("(-5)^0") == 1);
amrex::Print() << count++ << ". Testing \"a // b\"\n";
for (int a = -15; a <= 15; ++a) {
for (int b = -5; b <= 5; ++b) {
if (b != 0) {
IParser iparser("a//b");
iparser.setConstant("a",a);
iparser.registerVariables({"b"});
auto exe = iparser.compile<1>();
AMREX_ALWAYS_ASSERT(exe(b) ==
static_cast<int>(std::floor(double(a)/double(b))));
}
}
}
}
amrex::Print() << "\nAll IParser tests passed\n\n";
}
amrex::Finalize();
}
| [
"noreply@github.com"
] | noreply@github.com |
04bd594d804fa57793cf884eb2ee61bea9620f1f | 886d4b1d6f8e919c6491a0030a3e65c6b17a793c | /viewer/MsnhViewerNodeCfg.h | 850e9afb1d5bfbbf26a1f467eba4e013cd1fe6ef | [
"MIT"
] | permissive | wishgale/Msnhnet | 0ef7c29f3dad592f2ea2dca93dc5034f4ac23597 | 95522102b57e3cee679875ddf7766c032fde5655 | refs/heads/master | 2022-11-28T15:58:13.415871 | 2020-08-06T07:36:00 | 2020-08-06T07:36:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,123 | h | #ifndef MSNHVIEWERNODECFG_H
#define MSNHVIEWERNODECFG_H
#include <MsnhViewerView.h>
#include <MsnhViewerColorTabel.h>
#include <MsnhViewerNodeCreator.h>
namespace MsnhViewer
{
class NodeCfg
{
public:
static void configNodes()
{
NodeCreator::instance().addItem("Inputs",
{
{"output", "string", AttributeInfo::Type::output},
});
ColorTabel::instance().addColor("Inputs",QColor(0xce4a50));
NodeCreator::instance().addItem("AddOutputs",
{
{"input", "string", AttributeInfo::Type::input},
});
ColorTabel::instance().addColor("AddOutputs",QColor(0xB5B83E));
NodeCreator::instance().addItem("ConcatOutputs",
{
{"input", "string", AttributeInfo::Type::input},
});
ColorTabel::instance().addColor("ConcatOutputs",QColor(0xCF7531));
NodeCreator::instance().addItem("Empty",
{
{"input", "string", AttributeInfo::Type::input},
{"output", "string", AttributeInfo::Type::output},
});
ColorTabel::instance().addColor("Empty",QColor(0xB85646));
NodeCreator::instance().addItem("Activate",
{
{"input", "string", AttributeInfo::Type::input},
{"act", "string", AttributeInfo::Type::member},
{"output", "string", AttributeInfo::Type::output},
});
ColorTabel::instance().addColor("Activate",QColor(0xcc2121));
NodeCreator::instance().addItem("AddBlock",
{
{"input", "string", AttributeInfo::Type::input},
{"act", "string", AttributeInfo::Type::member},
{"output", "string", AttributeInfo::Type::output},
});
ColorTabel::instance().addColor("AddBlock",QColor(0x377375));
NodeCreator::instance().addItem("BatchNorm",
{
{"input", "string", AttributeInfo::Type::input},
{"act", "string", AttributeInfo::Type::member},
{"output", "string", AttributeInfo::Type::output},
});
ColorTabel::instance().addColor("BatchNorm",QColor(0x5B9FFF));
NodeCreator::instance().addItem("ConcatBlock",
{
{"input", "string", AttributeInfo::Type::input},
{"act", "string", AttributeInfo::Type::member},
{"output", "string", AttributeInfo::Type::output},
});
ColorTabel::instance().addColor("ConcatBlock",QColor(0x954f75));
NodeCreator::instance().addItem("Connected",
{
{"input", "string", AttributeInfo::Type::input},
{"act", "string", AttributeInfo::Type::member},
{"output", "string", AttributeInfo::Type::output},
});
ColorTabel::instance().addColor("Connected",QColor(0x009394));
NodeCreator::instance().addItem("Conv",
{
{"input", "string", AttributeInfo::Type::input},
{"filters", "string", AttributeInfo::Type::member},
{"kernel", "string", AttributeInfo::Type::member},
{"stride", "string", AttributeInfo::Type::member},
{"pad", "string", AttributeInfo::Type::member},
{"dilate", "string", AttributeInfo::Type::member},
{"group", "string", AttributeInfo::Type::member},
{"act", "string", AttributeInfo::Type::member},
{"output", "string", AttributeInfo::Type::output},
});
ColorTabel::instance().addColor("Conv",QColor(0x49D3D6));
NodeCreator::instance().addItem("DeConv",
{
{"input", "string", AttributeInfo::Type::input},
{"filters", "string", AttributeInfo::Type::member},
{"kernel", "string", AttributeInfo::Type::member},
{"stride", "string", AttributeInfo::Type::member},
{"pad", "string", AttributeInfo::Type::member},
{"act", "string", AttributeInfo::Type::member},
{"output", "string", AttributeInfo::Type::output},
});
ColorTabel::instance().addColor("DeConv",QColor(0x27F2BD));
NodeCreator::instance().addItem("ConvBN",
{
{"input", "string", AttributeInfo::Type::input},
{"filters", "string", AttributeInfo::Type::member},
{"kernel", "string", AttributeInfo::Type::member},
{"stride", "string", AttributeInfo::Type::member},
{"pad", "string", AttributeInfo::Type::member},
{"dilate", "string", AttributeInfo::Type::member},
{"group", "string", AttributeInfo::Type::member},
{"act", "string", AttributeInfo::Type::member},
{"output", "string", AttributeInfo::Type::output},
});
ColorTabel::instance().addColor("ConvBN",QColor(0xF14BBB));
NodeCreator::instance().addItem("ConvDW",
{
{"input", "string", AttributeInfo::Type::input},
{"filters", "string", AttributeInfo::Type::member},
{"kernel", "string", AttributeInfo::Type::member},
{"stride", "string", AttributeInfo::Type::member},
{"pad", "string", AttributeInfo::Type::member},
{"dilate", "string", AttributeInfo::Type::member},
{"group", "string", AttributeInfo::Type::member},
{"act", "string", AttributeInfo::Type::member},
{"output", "string", AttributeInfo::Type::output},
});
ColorTabel::instance().addColor("ConvDW",QColor(0xFF5186));
NodeCreator::instance().addItem("Crop",
{
{"input", "string", AttributeInfo::Type::input},
{"output", "string", AttributeInfo::Type::output},
});
ColorTabel::instance().addColor("Crop",QColor(0xA83A90));
NodeCreator::instance().addItem("LocalAvgPool",
{
{"input", "string", AttributeInfo::Type::input},
{"filters", "string", AttributeInfo::Type::member},
{"kernel", "string", AttributeInfo::Type::member},
{"stride", "string", AttributeInfo::Type::member},
{"pad", "string", AttributeInfo::Type::member},
{"output", "string", AttributeInfo::Type::output},
});
ColorTabel::instance().addColor("LocalAvgPool",QColor(0xFFDB97));
NodeCreator::instance().addItem("GlobalAvgPool",
{
{"input", "string", AttributeInfo::Type::input},
{"output", "string", AttributeInfo::Type::output},
});
ColorTabel::instance().addColor("GlobalAvgPool",QColor(0xFFDB97));
NodeCreator::instance().addItem("MaxPool",
{
{"input", "string", AttributeInfo::Type::input},
{"filters", "string", AttributeInfo::Type::member},
{"kernel", "string", AttributeInfo::Type::member},
{"stride", "string", AttributeInfo::Type::member},
{"pad", "string", AttributeInfo::Type::member},
{"output", "string", AttributeInfo::Type::output},
});
ColorTabel::instance().addColor("MaxPool",QColor(0x3353CA));
NodeCreator::instance().addItem("Padding",
{
{"input", "string", AttributeInfo::Type::input},
{"pad", "string", AttributeInfo::Type::member},
{"output", "string", AttributeInfo::Type::output},
});
ColorTabel::instance().addColor("Padding",QColor(0xFFAA5A));
NodeCreator::instance().addItem("Res2Block",
{
{"input", "string", AttributeInfo::Type::input},
{"act", "string", AttributeInfo::Type::member},
{"output", "string", AttributeInfo::Type::output},
});
ColorTabel::instance().addColor("Res2Block",QColor(0x6DACFF));
NodeCreator::instance().addItem("ResBlock",
{
{"input", "string", AttributeInfo::Type::input},
{"act", "string", AttributeInfo::Type::member},
{"output", "string", AttributeInfo::Type::output},
});
ColorTabel::instance().addColor("ResBlock",QColor(0xFF5B74));
NodeCreator::instance().addItem("Route",
{
{"input", "string", AttributeInfo::Type::input},
{"group", "string", AttributeInfo::Type::member},
{"type", "string", AttributeInfo::Type::member},
{"output", "string", AttributeInfo::Type::output},
});
ColorTabel::instance().addColor("Route",QColor(0xBB87FF));
NodeCreator::instance().addItem("SoftMax",
{
{"input", "string", AttributeInfo::Type::input},
{"groups", "string", AttributeInfo::Type::member},
{"temperature", "string", AttributeInfo::Type::member},
{"output", "string", AttributeInfo::Type::output},
});
ColorTabel::instance().addColor("SoftMax",QColor(0x60FFDF));
NodeCreator::instance().addItem("UpSample",
{
{"input", "string", AttributeInfo::Type::input},
{"scale", "string", AttributeInfo::Type::member},
{"stride", "string", AttributeInfo::Type::member},
{"output", "string", AttributeInfo::Type::output},
});
ColorTabel::instance().addColor("UpSample",QColor(0x886BFF));
NodeCreator::instance().addItem("Yolov3",
{
{"input", "string", AttributeInfo::Type::input},
{"classes", "string", AttributeInfo::Type::member},
{"output", "string", AttributeInfo::Type::output},
});
ColorTabel::instance().addColor("Yolov3",QColor(0xFF5000));
NodeCreator::instance().addItem("Yolov3Out",
{
{"input", "string", AttributeInfo::Type::input},
{"conf", "string", AttributeInfo::Type::member},
{"nms", "string", AttributeInfo::Type::member}
});
ColorTabel::instance().addColor("Yolov3Out",QColor(0x7A85FF));
}
};
}
#endif
| [
"noreply@github.com"
] | noreply@github.com |
699d54ff5b28760c90e1ab7ec8ce7ea5cdd9f50e | be54dd706789c6911e3c33de52ac1677258c9fba | /sketchbook/libraries/IrDistCom/IrDistCom.cpp | 9a7c0f63e1b7b3a70ca4aca4b66296d12def3153 | [] | no_license | hdlam91/master | 851ad2346a863b6df631618d693d789f586ac6fd | 5f2b58944c2f2a7556bbb3f63eb2b382fa24e5f3 | refs/heads/master | 2021-05-28T19:16:17.978726 | 2015-06-14T20:30:07 | 2015-06-14T20:30:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,820 | cpp | /*
Chirp Ir communication and distance library v0.1
by Christian Skjetne
*/
#include <Wire.h>
#include "Arduino.h"
#include "IrDistCom.h"
#define front_com_pin 4
#define back_com_pin 5
uint8_t IrDistCom::irdistcom_addr_front = 0xF;
uint8_t IrDistCom::irdistcom_addr_back = 0xB;
IrDistCom::IrDistCom()
{
}
void IrDistCom::begin(uint8_t addrF, uint8_t addrB)
{
irdistcom_addr_front = addrF;
irdistcom_addr_back = addrB;
}
void IrDistCom::getDistSensors(unsigned short distSensors[8])
{
Wire.beginTransmission(irdistcom_addr_front);
Wire.write('D');
Wire.write(0);
Wire.endTransmission();
Wire.requestFrom(irdistcom_addr_front, (uint8_t)5); // request uint8_ts from slave device, BLOCKING!
// Serial.print("\nwaiting for robot...\n");
int i = 0;
uint8_t* data1 = (uint8_t*)&sensor_data1;
while(Wire.available()) // slave may send less than requested
{
data1[i++] = Wire.read();
if(i == 5) break;
}
Wire.beginTransmission(irdistcom_addr_back);
Wire.write('D');
Wire.write(0);
Wire.endTransmission();
Wire.requestFrom(irdistcom_addr_back, (uint8_t)5); // request uint8_ts from slave device, BLOCKING!
int j = 0;
uint8_t* data2 = (uint8_t*)&sensor_data2;
while(Wire.available()) // slave may send less than requested
{
data2[j++] = Wire.read();
if(j == 5) break;
}
distSensors[0] = sensor_data1.sensor0;
distSensors[1] = sensor_data1.sensor1;
distSensors[2] = sensor_data1.sensor2;
distSensors[3] = sensor_data1.sensor3;
distSensors[4] = sensor_data2.sensor0;
distSensors[5] = sensor_data2.sensor1;
distSensors[6] = sensor_data2.sensor2;
distSensors[7] = sensor_data2.sensor3;
}
uint8_t IrDistCom::sendIrDataBlocking(uint8_t data[], int sizeOfData) //max data size is 32 uint8_ts
{
//send data to the front ATtiny:
Wire.beginTransmission(irdistcom_addr_front);
Wire.write('S');
Wire.write(sizeOfData);
for(int i = 0; i < sizeOfData; i++)
Wire.write(data[i]);
Wire.endTransmission();
//data sent to the front ATtiny, lets do the back:
Wire.beginTransmission(irdistcom_addr_back);
Wire.write('S');
Wire.write(sizeOfData);
for(int i = 0; i < sizeOfData; i++)
Wire.write(data[i]);
Wire.endTransmission();
//this is the locking method, do a spinlock to wait for the transmissions to either succeed, or time out.
delay(1); // give the ATtiny time to react. TODO: replace with interrupt.
while(true)
{
if(digitalRead(front_com_pin) == LOW && digitalRead(back_com_pin) == LOW) //both ATtinies have ended the transmission.
{
//time to get the results.
Wire.requestFrom(irdistcom_addr_front, (uint8_t)1);
int success1 = -2;
while(Wire.available()) // slave may send less than requested
{
success1 = Wire.read();
break;
}
Wire.requestFrom(irdistcom_addr_back, (uint8_t)1);
int success2 = -2;
while(Wire.available()) // slave may send less than requested
{
success2 = Wire.read();
break;
}
if(success1 == 0 && success2 == 0)//both timed out
{
return 0;
}
else if(success1 == 1 && success2 == 0)//front succeeded, back timed out
{
return 1;
}
else if(success1 == 0 && success2 == 1)//front timed out, back succeeded
{
return 2;
}
else if(success1 == 1 && success2 == 1)//both succeeded
{
return 3;
}
else //illegal state, something went wrong
return 4;
}
delay(10);//wait for the ATtinies to end transmission.
}
}
/*
void IrDistCom::sendIrDataNonLocking(uint8_t data[32], int sizeOfData) //max data size is 32 uint8_ts
{
//send data to the front ATtiny:
Wire.beginTransmission(irdistcom_addr_front);
Wire.write('S');
Wire.write(sizeOfData);
for(int i = 0; i < sizeOfData; i++)
Wire.write(data[i]);
Wire.endTransmission();
//data sent to the front ATtiny, lets do the back:
Wire.beginTransmission(irdistcom_addr_back);
Wire.write('S');
Wire.write(sizeOfData);
for(int i = 0; i < sizeOfData; i++)
Wire.write(data[i]);
Wire.endTransmission();
}
uint8_t IrDistCom::getDataSuccess()//TODO: replace with interrupt.
{
//this is the non locking method, check the transmissions to see if they either succeed, or timed out.
if(digitalRead(front_com_pin) == LOW && digitalRead(back_com_pin) == LOW) //both ATtinies have ended the transmission.
{
//time to get the results.
Wire.requestFrom(irdistcom_addr_front, (uint8_t)1);
int success1 = -2;
while(Wire.available()) // slave may send less than requested
{
success1 = Wire.read();
break;
}
Wire.requestFrom(irdistcom_addr_back, (uint8_t)1);
int success2 = -2;
while(Wire.available()) // slave may send less than requested
{
success2 = Wire.read();
break;
}
if(success1 == 0 && success2 == 0)//both timed out
{
return 0;
}
else if(success1 == 1 && success2 == 0)//front succeeded, back timed out
{
return 1;
}
else if(success1 == 0 && success2 == 1)//front timed out, back succeeded
{
return 2;
}
else if(success1 == 1 && success2 == 1)//both succeeded
{
return 3;
}
}
else //The attinies still have their status pins high. wait for time out or success.
return 5;
}*/
uint8_t IrDistCom::isIrDataAvailable()
{
bool frontStatus = digitalRead(front_com_pin);
bool backStatus = digitalRead(back_com_pin);
if(frontStatus == 0 && backStatus == 0)
{
return 0;//no data
}
else if(frontStatus == 1 && backStatus == 0)
{
return 1;//front has data
}
else if(frontStatus == 0 && backStatus == 1)
{
return 2;//back has data
}
else if(frontStatus == 1 && backStatus == 1)
{
return 3;//both have data
}
}
uint8_t IrDistCom::getIrData(bool frontATtinyHasData, uint8_t dataBuffer[32])
{
uint8_t addrToData = irdistcom_addr_front;
if( !frontATtinyHasData)
addrToData = irdistcom_addr_back;
//send the get data command
Wire.beginTransmission(addrToData);
Wire.write('R');
Wire.write(0);
Wire.endTransmission();
//get the number of uint8_ts available
Wire.requestFrom(addrToData, (uint8_t)1);
uint8_t sizeToRead = 0;
while(Wire.available()) // slave may send less than requested
{
sizeToRead = Wire.read();
}
if (sizeToRead != 0)//no data? ok.
{
Wire.requestFrom(addrToData, (uint8_t)sizeToRead);
int i = 0;
while(Wire.available()) // slave may send less than requested
{
dataBuffer[i++] = Wire.read();
if(i == sizeToRead) break;
}
}
return sizeToRead;
}
| [
"hongdang@stud.ntnu.no"
] | hongdang@stud.ntnu.no |
074cb6c6f2dfa1a326bd9392e9ba6970bfeb39e1 | 9da899bf6541c6a0514219377fea97df9907f0ae | /Runtime/Engine/Private/Animation/AnimNode_SequencePlayer.cpp | b086ea6ef5241bc212984874e019a5d3575a88e0 | [] | no_license | peichangliang123/UE4 | 1aa4df3418c077dd8f82439ecc808cd2e6de4551 | 20e38f42edc251ee96905ed8e96e1be667bc14a5 | refs/heads/master | 2023-08-17T11:31:53.304431 | 2021-09-15T00:31:03 | 2021-09-15T00:31:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,944 | cpp | // Copyright Epic Games, Inc. All Rights Reserved.
#include "Animation/AnimNode_SequencePlayer.h"
#include "AnimEncoding.h"
#include "Animation/AnimInstanceProxy.h"
#include "Animation/AnimTrace.h"
#include "Animation/AnimPoseSearchProvider.h"
#define LOCTEXT_NAMESPACE "AnimNode_SequencePlayer"
/////////////////////////////////////////////////////
// FAnimSequencePlayerNode
float FAnimNode_SequencePlayer::GetCurrentAssetTime()
{
return InternalTimeAccumulator;
}
float FAnimNode_SequencePlayer::GetCurrentAssetTimePlayRateAdjusted()
{
const float SequencePlayRate = (Sequence ? Sequence->RateScale : 1.f);
const float AdjustedPlayRate = PlayRateScaleBiasClamp.ApplyTo(FMath::IsNearlyZero(PlayRateBasis) ? 0.f : (PlayRate / PlayRateBasis), 0.f);
const float EffectivePlayrate = SequencePlayRate * AdjustedPlayRate;
return (EffectivePlayrate < 0.0f) ? GetCurrentAssetLength() - InternalTimeAccumulator : InternalTimeAccumulator;
}
float FAnimNode_SequencePlayer::GetCurrentAssetLength()
{
return Sequence ? Sequence->GetPlayLength() : 0.0f;
}
void FAnimNode_SequencePlayer::Initialize_AnyThread(const FAnimationInitializeContext& Context)
{
DECLARE_SCOPE_HIERARCHICAL_COUNTER_ANIMNODE(Initialize_AnyThread);
FAnimNode_AssetPlayerBase::Initialize_AnyThread(Context);
GetEvaluateGraphExposedInputs().Execute(Context);
if (Sequence && !ensureMsgf(!Sequence->IsA<UAnimMontage>(), TEXT("Sequence players do not support anim montages.")))
{
Sequence = nullptr;
}
InternalTimeAccumulator = StartPosition;
PlayRateScaleBiasClamp.Reinitialize();
if (Sequence != nullptr)
{
const float EffectiveStartPosition = GetEffectiveStartPosition(Context);
InternalTimeAccumulator = FMath::Clamp(EffectiveStartPosition, 0.f, Sequence->GetPlayLength());
const float AdjustedPlayRate = PlayRateScaleBiasClamp.ApplyTo(FMath::IsNearlyZero(PlayRateBasis) ? 0.f : (PlayRate / PlayRateBasis), 0.f);
const float EffectivePlayrate = Sequence->RateScale * AdjustedPlayRate;
if ((EffectiveStartPosition == 0.f) && (EffectivePlayrate < 0.f))
{
InternalTimeAccumulator = Sequence->GetPlayLength();
}
}
}
void FAnimNode_SequencePlayer::CacheBones_AnyThread(const FAnimationCacheBonesContext& Context)
{
DECLARE_SCOPE_HIERARCHICAL_COUNTER_ANIMNODE(CacheBones_AnyThread);
}
void FAnimNode_SequencePlayer::UpdateAssetPlayer(const FAnimationUpdateContext& Context)
{
DECLARE_SCOPE_HIERARCHICAL_COUNTER_ANIMNODE(UpdateAssetPlayer);
GetEvaluateGraphExposedInputs().Execute(Context);
if (Sequence && !ensureMsgf(!Sequence->IsA<UAnimMontage>(), TEXT("Sequence players do not support anim montages.")))
{
Sequence = nullptr;
}
if ((Sequence != nullptr) && (Context.AnimInstanceProxy->IsSkeletonCompatible(Sequence->GetSkeleton())))
{
InternalTimeAccumulator = FMath::Clamp(InternalTimeAccumulator, 0.f, Sequence->GetPlayLength());
const float AdjustedPlayRate = PlayRateScaleBiasClamp.ApplyTo(FMath::IsNearlyZero(PlayRateBasis) ? 0.f : (PlayRate / PlayRateBasis), Context.GetDeltaTime());
CreateTickRecordForNode(Context, Sequence, bLoopAnimation, AdjustedPlayRate);
}
#if WITH_EDITORONLY_DATA
if (FAnimBlueprintDebugData* DebugData = Context.AnimInstanceProxy->GetAnimBlueprintDebugData())
{
DebugData->RecordSequencePlayer(Context.GetCurrentNodeId(), GetAccumulatedTime(), Sequence != nullptr ? Sequence->GetPlayLength() : 0.0f, Sequence != nullptr ? Sequence->GetNumberOfSampledKeys() : 0);
}
#endif
TRACE_ANIM_SEQUENCE_PLAYER(Context, *this);
TRACE_ANIM_NODE_VALUE(Context, TEXT("Name"), Sequence != nullptr ? Sequence->GetFName() : NAME_None);
TRACE_ANIM_NODE_VALUE(Context, TEXT("Sequence"), Sequence);
TRACE_ANIM_NODE_VALUE(Context, TEXT("Playback Time"), InternalTimeAccumulator);
}
void FAnimNode_SequencePlayer::Evaluate_AnyThread(FPoseContext& Output)
{
DECLARE_SCOPE_HIERARCHICAL_COUNTER_ANIMNODE(Evaluate_AnyThread);
if ((Sequence != nullptr) && (Output.AnimInstanceProxy->IsSkeletonCompatible(Sequence->GetSkeleton())))
{
const bool bExpectedAdditive = Output.ExpectsAdditivePose();
const bool bIsAdditive = Sequence->IsValidAdditive();
if (bExpectedAdditive && !bIsAdditive)
{
FText Message = FText::Format(LOCTEXT("AdditiveMismatchWarning", "Trying to play a non-additive animation '{0}' into a pose that is expected to be additive in anim instance '{1}'"), FText::FromString(Sequence->GetName()), FText::FromString(Output.AnimInstanceProxy->GetAnimInstanceName()));
Output.LogMessage(EMessageSeverity::Warning, Message);
}
FAnimationPoseData AnimationPoseData(Output);
Sequence->GetAnimationPose(AnimationPoseData, FAnimExtractContext(InternalTimeAccumulator, Output.AnimInstanceProxy->ShouldExtractRootMotion()));
}
else
{
Output.ResetToRefPose();
}
}
void FAnimNode_SequencePlayer::OverrideAsset(UAnimationAsset* NewAsset)
{
if (UAnimSequenceBase* AnimSequence = Cast<UAnimSequenceBase>(NewAsset))
{
Sequence = AnimSequence;
}
}
void FAnimNode_SequencePlayer::GatherDebugData(FNodeDebugData& DebugData)
{
FString DebugLine = DebugData.GetNodeName(this);
DebugLine += FString::Printf(TEXT("('%s' Play Time: %.3f)"), Sequence ? *Sequence->GetName() : TEXT("NULL"), InternalTimeAccumulator);
DebugData.AddDebugItem(DebugLine, true);
}
float FAnimNode_SequencePlayer::GetTimeFromEnd(float CurrentNodeTime)
{
return Sequence->GetPlayLength() - CurrentNodeTime;
}
float FAnimNode_SequencePlayer::GetEffectiveStartPosition(const FAnimationBaseContext& Context) const
{
// Override the start position if pose matching is enabled
if (Sequence != nullptr && bStartFromMatchingPose)
{
UE::Anim::IPoseSearchProvider* PoseSearchProvider = UE::Anim::IPoseSearchProvider::Get();
if (PoseSearchProvider)
{
UE::Anim::IPoseSearchProvider::FSearchResult Result = PoseSearchProvider->Search(Context, Sequence);
if (Result.PoseIdx >= 0)
{
return Result.TimeOffsetSeconds;
}
}
}
return StartPosition;
}
#undef LOCTEXT_NAMESPACE | [
"ouczbs@qq.com"
] | ouczbs@qq.com |
5e4853177cc25d22bdcc693b96390fa7efabec0c | 47a1e9e7b5c595936b0d654c532a60c6a9896730 | /4_CH_AP.ino | b1895c537fcfdfe399017433f3481644fc82c511 | [] | no_license | dhavalkalariya09/Smart-Home-Automation | 5fe8edbf3a70f2253f87ae051bfb44400f77b6a4 | fbae7e327bc1eb68e584ac9086cf3f5a98492df1 | refs/heads/master | 2020-12-29T19:18:22.269972 | 2020-02-06T14:12:25 | 2020-02-06T14:12:25 | 238,702,212 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,825 | ino |
// Load Wi-Fi library
#include <WiFi.h>
// Replace with your network credentials
// to create its own wifi network
const char* ssid = "ESP32-Access-Point";
const char* password = "123456789";
// Set web server port number to 80
WiFiServer server(80);
// Variable to store the HTTP request
String header;
// Auxiliar variables to store the current output state
//this pins for esp32
//change the pins for esp8266
String output12State = "off";
String output13State = "off";
String output14State = "off";
String output27State = "off";
// Assign output variables to GPIO pins
const int output12 = 12;
const int output13 = 13;
const int output14 = 14;
const int output27 = 27;
void setup() {
Serial.begin(115200);
// Initialize the output variables as outputs
pinMode(output12, OUTPUT);
pinMode(output13, OUTPUT);
pinMode(output14, OUTPUT);
pinMode(output27, OUTPUT);
// Set outputs to high because we are using active low type relay module
digitalWrite(output12, HIGH);
digitalWrite(output13, HIGH);
digitalWrite(output14, HIGH);
digitalWrite(output27, HIGH);
// Connect to Wi-Fi network with SSID and password
Serial.print("Setting AP (Access Point)…");
// Remove the password parameter, if you want the AP (Access Point) to be open
WiFi.softAP(ssid, password);
IPAddress IP = WiFi.softAPIP();
Serial.print("AP IP address: ");
Serial.println(IP);
server.begin();
}
void loop(){
WiFiClient client = server.available(); // Listen for incoming clients
if (client) { // If a new client connects,
Serial.println("New Client."); // print a message out in the serial port
String currentLine = ""; // make a String to hold incoming data from the client
while (client.connected()) { // loop while the client's connected
if (client.available()) { // if there's bytes to read from the client,
char c = client.read(); // read a byte, then
Serial.write(c); // print it out the serial monitor
header += c;
if (c == '\n') { // if the byte is a newline character
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0) {
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println("Connection: close");
client.println();
// turns the GPIOs on and off
//foe GPIO12
if (header.indexOf("GET /12/on") >= 0)
{
Serial.println("GPIO 12 on");
output12State = "on";
digitalWrite(output12, LOW);
}
else if (header.indexOf("GET /12/off") >= 0)
{
Serial.println("GPIO 12 off");
output12State = "off";
digitalWrite(output12, HIGH);
}
//for GPIO13
else if (header.indexOf("GET /13/on") >= 0)
{
Serial.println("GPIO 13 on");
output13State = "on";
digitalWrite(output13, LOW);
}
else if (header.indexOf("GET /13/off") >= 0)
{
Serial.println("GPIO 13 off");
output13State = "off";
digitalWrite(output13, HIGH);
}
//for GPIO14
else if (header.indexOf("GET /14/on") >= 0)
{
Serial.println("GPIO 14 on");
output14State = "on";
digitalWrite(output14, LOW);
}
else if (header.indexOf("GET /14/off") >= 0)
{
Serial.println("GPIO 14 off");
output14State = "off";
digitalWrite(output14, HIGH);
}
//for GPIO27
else if (header.indexOf("GET /27/on") >= 0)
{
Serial.println("GPIO 27 on");
output27State = "on";
digitalWrite(output27, LOW);
}
else if (header.indexOf("GET /27/off") >= 0)
{
Serial.println("GPIO 27 off");
output27State = "off";
digitalWrite(output27, HIGH);
}
// Display the HTML web page
client.println("<!DOCTYPE html><html>");
client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
client.println("<link rel=\"icon\" href=\"data:,\">");
// CSS to style the on/off buttons
// Feel free to change the background-color and font-size attributes to fit your preferences
client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}");
client.println(".button { background-color: #4CAF50; border: none; color: white; padding: 16px 40px;");
client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");
client.println(".button2 {background-color: #555555;}</style></head>");
// Web Page Heading
client.println("<body><h1>ESP32 Web Server</h1>");
// Display current state, and ON/OFF buttons for GPIO 12
client.println("<p>GPIO 12 - State " + output12State + "</p>");
// If the output12State is off, it displays the ON button
if (output12State=="off") {
client.println("<p><a href=\"/12/on\"><button class=\"button\">ON</button></a></p>");
} else {
client.println("<p><a href=\"/12/off\"><button class=\"button button2\">OFF</button></a></p>");
}
// Display current state, and ON/OFF buttons for GPIO 27
client.println("<p>GPIO 27 - State " + output27State + "</p>");
// If the output27State is off, it displays the ON button
if (output27State=="off") {
client.println("<p><a href=\"/27/on\"><button class=\"button\">ON</button></a></p>");
} else {
client.println("<p><a href=\"/27/off\"><button class=\"button button2\">OFF</button></a></p>");
}
// Display current state, and ON/OFF buttons for GPIO 13
client.println("<p>GPIO 13 - State " + output13State + "</p>");
// If the output13State is off, it displays the ON button
if (output13State=="off") {
client.println("<p><a href=\"/13/on\"><button class=\"button\">ON</button></a></p>");
} else {
client.println("<p><a href=\"/13/off\"><button class=\"button button2\">OFF</button></a></p>");
}
// Display current state, and ON/OFF buttons for GPIO 14
client.println("<p>GPIO 14 - State " + output14State + "</p>");
// If the output14State is off, it displays the ON button
if (output14State=="off") {
client.println("<p><a href=\"/14/on\"><button class=\"button\">ON</button></a></p>");
} else {
client.println("<p><a href=\"/14/off\"><button class=\"button button2\">OFF</button></a></p>");
}
client.println("</body></html>");
// The HTTP response ends with another blank line
client.println();
// Break out of the while loop
break;
} else { // if you got a newline, then clear currentLine
currentLine = "";
}
} else if (c != '\r') { // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
}
}
// Clear the header variable
header = "";
// Close the connection
client.stop();
Serial.println("Client disconnected.");
Serial.println("");
}
}
| [
"noreply@github.com"
] | noreply@github.com |
0f12f4720ab91bd53098d7dddf2aa2b734532392 | 95be4d40a5ca1f2e56d3827c402cf2dc6ff424c5 | /CArrayDec.cpp | 088088dd48f11f7850e86c298c14cbef8fef0691 | [
"MIT"
] | permissive | damifi/LZW-Algorithm | 12e2287860a07382191079701a29f82fd7e476a6 | 37813db8e7522e847db8af0119e1bade533c1aa0 | refs/heads/main | 2023-07-18T14:54:08.731343 | 2021-09-09T08:59:57 | 2021-09-09T08:59:57 | 404,653,185 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 1,615 | cpp | ///*
// * CArrayDec.cpp
// *
// * Created on: 14.06.2014
// * Author: Daniel Fischer
// */
#include "CArrayDec.hpp"
#include <vector>
#include <exception>
#include <iostream>
CArrayDec::CArrayDec()
{
for(int i=0;i<256;i++)
{
m_symbolTable[i].setSymbol(intToString(i));
}
}
int CArrayDec::searchInTable(const string &zei)
{
int i =0;
for(i=0; i<LZW_DICT_SIZE; i++)
{
if(m_symbolTable[i].getSymbol().compare(zei) == 0) {return i;}
}
return -1;
}
string CArrayDec::decode(const vector<unsigned int>& vec)
{
std::string out, Sv, S;
std::vector<unsigned int>::const_iterator pos;
unsigned int freeDictPos = 256;
if(vec.empty()) return ""; //wenn Eingabevektor leer ist, leeren string ausgeben
pos = vec.begin();
Sv = m_symbolTable[*pos].getSymbol(); //ersten index einlesen, zugehörigen string speichern
out = Sv;
for(pos = vec.begin()+1; pos !=vec.end(); ++pos) // Durchläuft den rest vom vektor
{
if(*pos > freeDictPos-1 ) //falls Index aus dem Vektor noch nicht im Dictionary ist...
{
S = Sv + Sv[0]; //zuvor decodierten string um sein erstes zeichen verlängern
}
else // ansonsten...
{
S = m_symbolTable[*pos].getSymbol(); //string mit dem indexwert aus dictionary auslesen
}
out = out + S; //Resultat an den ausgabestring anhängen
m_symbolTable[freeDictPos].setSymbol((Sv+S[0]));
freeDictPos++;
Sv = S;
if(freeDictPos >= LZW_DICT_SIZE) // Error
{
std::cerr << "ERROR: Kein Platz im Dictionary mehr vorhanden!";
std::terminate();
}
}
return out;
}
| [
"noreply@github.com"
] | noreply@github.com |
fc542c1a3475e5507e79abe575297ccd61cf6381 | 7e1ad1571278b1e886045313255cdd697ff04dd8 | /C++/二叉树 —— 树的子结构.cpp | 2aee8232ffbbb6530ad62296bcb906d5faf0bd10 | [] | no_license | shanyuqin/SuanFa | 262a62a015945c1e9c7643b5bc4f163e6d3f7ef8 | a943d0cda51a457a8d8f62e87348d8490357db44 | refs/heads/master | 2021-03-07T07:48:51.107403 | 2020-03-12T10:46:28 | 2020-03-12T10:46:28 | 246,252,885 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 899 | cpp | //两个二叉树A和B,判断B是不是A的子结构
#include<stack>
#include<exception>
struct BinaryTreeNode
{
int m_value;
BinaryTreeNode *m_left;
BinaryTreeNode *m_right;
};
bool DoesTree1HaveTree2(BinaryTreeNode *p1 ,BinaryTreeNode *p2){
if (p2 == NULL)
return true;
if (p1 == NULL)
return false;
if (p1->m_value != p2->m_value)
return false;
return DoesTree1HaveTree2(p1->m_left,p2->m_left) && DoesTree1HaveTree2(p1->m_right,p2->m_right);
}
bool HasSubTree(BinaryTreeNode *p1 ,BinaryTreeNode *p2) {
bool result = false;
if (p1 != NULL && p2 != NULL)
{
if (p1->m_value == p2->m_value)
result = DoesTree1HaveTree2(p1,p2);
if (!result)
result = HasSubTree(p1->m_left,p2);
if (!result)
result = HasSubTree(p1->m_right,p2);
}
return result;
}
| [
""
] | |
e40853d1af6bbc7c81b60a887a7b6da2940552c7 | 9f0d25223ba97bb3930c342e7709aab9d9007844 | /include/nocopy/archive.hpp | 68f019e8ebd43d43937742e609ad00ddadccd9a8 | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | mikezackles/nocopy | 9a5118038385da67d121178c80ff58305af7e337 | 7ddae640e88b2bc2ab3b1130d16616da2f673c2a | refs/heads/master | 2021-03-24T13:15:08.241089 | 2016-11-12T18:31:54 | 2016-11-12T18:31:54 | 62,241,637 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,153 | hpp | #ifndef UUID_06CEC703_2131_48E7_BC79_F84A9F0F44BB
#define UUID_06CEC703_2131_48E7_BC79_F84A9F0F44BB
#include <nocopy/fwd/archive.hpp>
#include <nocopy/detail/align_to.hpp>
#include <nocopy/detail/lambda_overload.hpp>
#include <nocopy/detail/narrow_cast.hpp>
#include <nocopy/detail/reference.hpp>
#include <nocopy/detail/traits.hpp>
#include <nocopy/errors.hpp>
#include <nocopy/field.hpp>
#include <nocopy/detail/ignore_warnings_from_dependencies.hpp>
BEGIN_IGNORE_WARNINGS_FROM_DEPENDENCIES
#include <span.h>
END_IGNORE_WARNINGS_FROM_DEPENDENCIES
#include <algorithm>
#include <cassert>
namespace nocopy {
namespace detail {
template <typename Offset, Offset Capacity>
class archive {
NOCOPY_FIELD(buffer, NOCOPY_ARRAY(unsigned char, Capacity));
NOCOPY_FIELD(cursor, Offset);
using reference = detail::reference<Offset>;
template <typename T, bool is_single>
using generic_reference = typename reference::template generic<T, is_single>;
public:
using delegate_type = structpack<buffer_t, cursor_t>;
archive(archive const&) = delete;
template <typename T>
using single_reference = typename reference::template single<T>;
template <typename T>
using range_reference = typename reference::template range<T>;
template <typename T, typename ...Callbacks>
auto alloc(Callbacks... callbacks) const {
auto callback = detail::make_overload(std::move(callbacks)...);
return alloc_helper<T>(
1
, [&](Offset offset, Offset) {
return callback(reference::template create_single<T>(offset));
}
, callback
);
}
template <typename T, typename ...Callbacks>
auto alloc_range(Offset count, Callbacks... callbacks) const {
auto callback = detail::make_overload(std::move(callbacks)...);
return alloc_helper<T>(
count
, [&](Offset offset, Offset count) {
return callback(reference::template create_range<T>(offset, count));
}
, callback
);
}
template <typename T, typename ...Callbacks>
auto add(T const& t, Callbacks... callbacks) const {
auto callback = detail::make_overload(std::move(callbacks)...);
return alloc<T>(
[=](auto& ref) {
this->deref(ref) = t;
return callback(ref);
}
, callback
);
}
template <typename T, typename ...Callbacks>
auto add(gsl::span<T> data, Callbacks... callbacks) const {
auto callback = detail::make_overload(std::move(callbacks)...);
return alloc_range<T>(
data.length()
, [=](auto& ref) {
std::copy(data.cbegin(), data.cend(), this->deref(ref).begin());
return callback(ref);
}
, callback
);
}
template <typename ...Callbacks>
auto add(char const* str, std::size_t len, Callbacks... callbacks) const {
using span = gsl::span<char const>;
static_assert(sizeof(Offset) <= sizeof(typename span::index_type)
, "offset type is too large");
assert(str != nullptr);
auto callback = detail::make_overload(std::move(callbacks)...);
// narrow_cast is necessary because gsl::span uses a signed index type
auto in = span{str, detail::narrow_cast<typename span::index_type>(len)};
return alloc_range<char const>(
len + 1
, [=](auto& ref) {
auto& data = this->deref(ref);
std::copy(in.cbegin(), in.cend(), data.begin());
data[len] = '\0';
return callback(ref);
}
, callback
);
}
template <typename ...Callbacks>
auto add(std::string const& str, Callbacks... callbacks) const {
return this->add(str.c_str(), str.length(), callbacks...);
}
template <typename T, bool Unused>
decltype(auto) deref(generic_reference<T, Unused> const& ref) const noexcept {
auto offset = static_cast<Offset>(ref);
return ref.deref(data[buffer][offset]);
}
char const* get_string(range_reference<char const> const& ref) const noexcept {
return this->deref(ref).data();
}
delegate_type data;
private:
template <typename T, typename Success, typename Error>
auto alloc_helper(std::size_t count, Success&& success_callback, Error&& error_callback) noexcept {
detail::assert_valid_type<T>();
Offset addr = detail::align_to(data[cursor], detail::alignment_for<T>());
auto size = sizeof(T) * count;
if (Capacity - addr < size) {
return error_callback(make_error_code(error::out_of_space));
} else {
data[cursor] = addr + size;
return success_callback(addr, count);
}
}
};
}
//#ifdef UINT32_MAX
// template <uint32_t Capacity>
// using archive32 = detail::archive_impl<uint32_t, Capacity>;
//#endif
//#ifdef UINT64_MAX
// template <uint64_t Capacity>
// using archive64 = detail::archive_impl<uint64_t, Capacity>;
//#endif
}
#endif
| [
"mikezackles@gmail.com"
] | mikezackles@gmail.com |
11c6016cd5ed6864341063d5284d17438916eb4a | 44ca6eaf7ae36a87973ccbe56896ce9312e8bdc1 | /Include/gsmGPRS.h | 461d4de2467656bf6633de90f086981b7ac1842e | [] | no_license | kenzanin/GSM---AVR | 433b5703cb927008061f273d481c0516330f2c6e | 5bf0fcf762311bc022b870292e681d0fd78a5f4c | refs/heads/master | 2020-12-14T01:12:00.774613 | 2013-11-27T18:28:23 | 2013-11-27T18:28:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,459 | h | /*AVR SOURCE FILES FOR GSM,SERIAL FUNCTIONALITY *
* Copyright (C) 2010 Justin Downs of GRounND LAB *
* www.GroundLab.cc 1% *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* with this program. If not, see <http://www.gnu.org/licenses/>. *
************************************************************************/
#ifndef GSMGPRS
#define GSMGPRS
#include "gsmbase.h"
class gsmGPRS : virtual public GSMbase
{
//**FULL FUNC DESCRIPTION IN SOURCE**\\
private:
//you can set up diffrent contexts with diffrent IPs
#define IPsize 16
char ipAddress1[IPsize]; //IP 000.000.000.000 + "/0" for first context
char ipAddress2[IPsize]; //IP 000.000.000.000 + "/0" for second context
char * getData; //Use this to store persistent GET data
public:
gsmGPRS(Serial&, uint32_t(*)(), Serial* = NULL);
inline const char* const getIpAddress(){return ipAddress1;}
////////////////////////////INIT FUNC
virtual bool init(uint16_t); //INITS, CALLS BASE INIT
////////////////////////////////////////////////////////////////////////////////SET SOCKET
//AT+CGREG checks GPRS registration
bool checkCGREG();
//AT+CGDCONT sets up ISP settings
bool setApnCGDCONT(const char * const,const char* const,
const char* const,const char* const requestedStaticIP ="0.0.0.0",
const char* const dataCompression = "0",const char* const headerCompression = "0");
//AT+SCFG sets up TCP/IP socket behavior
bool setTcpIpStackSCFG(const char * const,
const char* const,const char* const minPacketSize = "300",
const char* const globalTimeout = "90", const char* const connectionTimeout = "600",
const char* const txTimeout = "50"); //(conTime and TXTime are in .1 seconds)
//AT+SGACT activates context gets IP from gateway
const char* const setContextSGACT(const char * const,
const char* const,const char* const username =NULL,
const char* const password= NULL);
/////OPTIONAL SOCKET SETTINGS
//AT+CGQMIN defines a min quality of service for the telit to send
bool setQualityCGQMIN(const char * const,
const char* const precedence = "0",const char* const delay = "0",
const char* const reliability = "0", const char* const peak = "0",
const char* const mean = "0");
//AT+CGQREQ asks for a specific quality of service from network
bool requestQualityCGQREQ(const char * const,
const char* const precedence = "0",const char* const delay = "0",
const char* const reliability = "3", const char* const peak = "0",
const char* const mean = "0");
//AT+SGACTAUTH sets security protocal used with network
bool setSecuritySGACTAUTH(const char* const);
////////////////////////////////////////////////////////////////////////////////SOCKET CONTROL
//AT#SD opens a socket connection to a host at Port/IP address
bool socketDialSD(const char * const,const char* const ,const char* const,
const char* const);
bool suspendSocket(); //suspends with +++ sequence
bool resumeSocketSO(const char* const); // resumes a suspended socket
bool closeSocketSH(const char* const); // closes a socket
const char* const socketStatusSS(); // returns status of a socket.
const char* const socketInfoSI(const char* const); //socket info
bool socketListenSL(const char* const, const char* const, //sets a socket to listen for data
const char* const);
bool socketAcceptSA(const char* const); //accepts socket connection after AT#SL
const char* const getHTTP(uint16_t, const char* const, //forms and writes a HTTP GET request
const char* const, const char* const httpVersion="1.1",
bool keepAlive=false);
const char* const postHTTP(uint16_t, const char* const, //forms and wtites post command
const char* const, const char* const, const char* const httpVersion="1.1",
bool keepAlive=false,const char* const reqStr=NULL);
/////////////////////////////////////////////////////////////////////////////FTP CONNECTION
bool ftpTimeOutFTPO(const char* const);
bool FTPOPEN(const char* const serverPort, const char* const username,
const char* password,const char* const mode);
bool ftpDataTypeFTPTYPE(const char* const binaryAscii);
bool FTPCLOSE();
bool FTPPUT(const char* const fileWriteName, const char* const data);
const char* const FTPGET(const char* const fileName, uint16_t dataSize);
bool changeDirFTPCWD(const char* const directory);
};
//Gets registration status (true REGISTERED, false NOT)
inline bool gsmGPRS::checkCGREG(){
//RETURNS: +CREG: 0,1 OK
if ( (sendRecATCommandSplit("AT+CGREG?",":,",2)[0]) == '1') return true;
return false;
}
#endif
| [
"Justin@grndlab.com"
] | Justin@grndlab.com |
b9a0ee91fd545dbbfbacc974240f55a320ca490d | 93740492b18828c5a3fdffd8855b4401fa86e868 | /u_phi_1_transform.hpp | 55f46d293c8cd3e6b2f8f5c595fc6d5a4e59942b | [] | no_license | idosavion/fast-matrix-multiplication | 908265897018e6dd684fa1666a6702d15c8565ab | 25e7e1d39ddfb4bbbb7042cc368762e7b415aaf3 | refs/heads/master | 2022-01-04T14:35:26.490775 | 2020-01-18T16:37:23 | 2020-01-18T16:37:23 | 189,715,142 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 202 | hpp |
#pragma once
#include <iostream>
#include <cmath>
#include "mkl.h"
void u_phi_1_transform(double* original_a, double* transformed_a, int size, int steps_left, double* work);
| [
"elayeek@gmail.com"
] | elayeek@gmail.com |
7557dff758354fadfc5f04e5c5e57b60dcc0b473 | bd1fea86d862456a2ec9f56d57f8948456d55ee6 | /000/106/928/CWE590_Free_Memory_Not_on_Heap__delete_array_wchar_t_declare_66b.cpp | b5b614c2b1987dd2e2191c10894fafbea3cccb25 | [] | no_license | CU-0xff/juliet-cpp | d62b8485104d8a9160f29213368324c946f38274 | d8586a217bc94cbcfeeec5d39b12d02e9c6045a2 | refs/heads/master | 2021-03-07T15:44:19.446957 | 2020-03-10T12:45:40 | 2020-03-10T12:45:40 | 246,275,244 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,273 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE590_Free_Memory_Not_on_Heap__delete_array_wchar_t_declare_66b.cpp
Label Definition File: CWE590_Free_Memory_Not_on_Heap__delete_array.label.xml
Template File: sources-sink-66b.tmpl.cpp
*/
/*
* @description
* CWE: 590 Free Memory Not on Heap
* BadSource: declare Data buffer is declared on the stack
* GoodSource: Allocate memory on the heap
* Sinks:
* BadSink : Print then free data
* Flow Variant: 66 Data flow: data passed in an array from one function to another in different source files
*
* */
#include "std_testcase.h"
#include <wchar.h>
namespace CWE590_Free_Memory_Not_on_Heap__delete_array_wchar_t_declare_66
{
#ifndef OMITBAD
void badSink(wchar_t * dataArray[])
{
/* copy data out of dataArray */
wchar_t * data = dataArray[2];
printWLine(data);
/* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */
delete [] data;
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(wchar_t * dataArray[])
{
wchar_t * data = dataArray[2];
printWLine(data);
/* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */
delete [] data;
}
#endif /* OMITGOOD */
} /* close namespace */
| [
"frank@fischer.com.mt"
] | frank@fischer.com.mt |
ee4783a1716c0a1cdae042c7feffb6c0d5ed806c | 13a06ef97a2e820302bb7061abc6d2137758fee1 | /AshEngine/include/OpenGL/OpenGLRenderer.h | 3e468cb91d17f95a38b7a91b729dceae635a595a | [
"MIT"
] | permissive | haoxiaoshuai01/3dshow | 65c5f94116a610f9613ad068b73288a962dc09d6 | 1f060dca01e2ec1edc93ddf6601743dea7f22707 | refs/heads/main | 2023-08-30T03:13:56.450437 | 2021-07-26T10:06:36 | 2021-07-26T10:06:36 | 388,115,006 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 742 | h | #pragma once
#include <OpenGLScene.h>
class OpenGLRenderer: public QObject {
Q_OBJECT
public:
OpenGLRenderer(QObject* parent = 0);
OpenGLRenderer(const OpenGLRenderer& renderer);
bool hasErrorLog();
QString errorLog();
bool reloadShaders();
void reloadFrameBuffers();
uint32_t pickingPass(OpenGLScene* openGLScene, QPoint cursorPos);
void render(OpenGLScene* openGLScene);
private:
QString m_log;
QOpenGLShaderProgram *m_basicShader, *m_pickingShader, *m_phongShader;
QOpenGLFramebufferObject *m_pickingPassFBO;
QOpenGLShaderProgram * loadShaderFromFile(
QString vertexShaderFilePath,
QString fragmentShaderFilePath,
QString geometryShaderFilePath = "");
};
| [
"15227916361@163.com"
] | 15227916361@163.com |
986956c4864e8394e7956f416c158082d0b1d430 | c95abab9b3b0a836d2d5ed882d166dc99e913954 | /Ejercicios Timus/2012_Andres.cpp | a1f1c4b36f2e13e8a3fcd98f451da0ae761b2e06 | [] | no_license | valehp/OCI_2020 | 54e361311173f28da5911480c013247a19ff1732 | 62914eaafae4553d59f59220410b227fa95115f9 | refs/heads/main | 2023-01-29T06:26:08.668598 | 2020-12-04T21:41:55 | 2020-12-04T21:41:55 | 300,446,721 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 139 | cpp | #include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
if(n>=7)cout <<"YES\n";
else cout << "NO\n";
return 0;
} | [
"noreply@github.com"
] | noreply@github.com |
a7f9d7d5e25fa79682784cca870a3bd72f8f9ee4 | c6e285a6203b03d21755dd55bd13e8d3a8bd42fc | /src/LaplacianScorer.cpp | 68fe3e64244792396d6472f0a3c88aed93f75ade | [
"MIT"
] | permissive | CamaraLab/RayleighSelection | fd7b5263360ce3ef611507ca7373dadc778a44af | f25e83a81cb4e9d8027c3b8e75dbf85c0c7f163e | refs/heads/master | 2021-12-12T09:23:57.310041 | 2021-08-12T17:50:54 | 2021-08-12T17:50:54 | 114,267,839 | 10 | 5 | MIT | 2021-08-11T18:13:31 | 2017-12-14T15:40:36 | R | UTF-8 | C++ | false | false | 10,239 | cpp | //' Computes and samples 0 and 1-dimensional laplacian scores.
//'
//' Builds an object to compute and sample values for the combinatorial laplacian score of functions
//' defined on the set of points underlying a given simplicial complex. Takes in data about the complex and
//' its 0- (and possibly 1-) dimensional laplacian to build a scorer. The scorer pushes functions defined on
//' the points underlying the complex to the 0- (or 1-) dimensional skeleton by averaging over the points associated
//' to each complex and evaluates the Rayleigh quotient of the normalized graph laplacean on the pushed function.
//' The scorer can also sample values from the null distribution obtained by shuffling the labels of the underlying points.
//'
//' @name LaplacianScorer
//' @field new Constructs a scorer using data on the complex and its associated laplacian.\cr\cr
//' \strong{Use} \code{scorer <- new(LaplacianScorer, comb_laplacian, pts_in_vertex, adjacency, one_forms)}\cr\cr
//' \strong{Parameters}\itemize{
//' \item \code{comb_laplacian}: output of \code{\link{combinatorial_laplacian}}
//' \item \code{pts_in_vertex}: list of vectors where the i-th vector contains the index of the points associated to the i-th vertex
//' \item \code{adjacency}: adjacency matrix for 1-skeleton as a sparse matrix
//' \item \code{one_forms}: boolean indicating if laplacian of one-forms will be computed}
//'
//' @field score Pushes functions defined by rows of funcs to the dim-skeleton by
//' averaging and computes its laplacian score.\cr\cr
//' \strong{Use} \code{scorer$score(funcs, dim)}\cr\cr
//' \strong{Parameters}\itemize{
//' \item \code{funcs}: functions to be scored as a rows of a dense matrix
//' \item \code{dim}: dimension of the laplacian (0 or 1)}
//' \strong{Value} Scores of functions as a vector
//'
//' @field sample_scores Takes samples of scores by permuting point labels\cr\cr
//' \strong{Use} \code{scorer$sample_scores(funcs, n_perm, dim, n_cores)}\cr\cr
//' \strong{Parameters}\itemize{
//' \item \code{funcs}: base functions as rows of a dense matrix
//' \item \code{n_perm}: number of permutations
//' \item \code{dim}: dimension of the laplacian
//' \item \code{n_cores}: number of cores to be used, parallelization requires code to be compiled with \code{openmp} }
//' \strong{Value} Dense matrix with sampled scores where the i-th row has samples for the i-th function
//'
//' @field sample_with_covariate Takes samples of scores of function in tandem with scores of covariates
//' by applying the same permutations of labels to both.
//' \strong{Use} \code{scorer$sample_with_covariate(funcs, cov, n_perm, dim, n_cores)}
//' \strong{Parameters}\itemize{
//' \item \code{funcs}: base functions as rows of a dense matrix
//' \item \code{cov}: covariates as rows of a dense matrix
//' \item \code{n_perm}: number of permutations
//' \item \code{dim}: dimension of the laplacian
//' \item \code{n_cores}: number of cores to be used, parallelization requires code to be compiled with \code{openmp} }
//' \strong{Value} A list \code{out} with two elements \itemize{
//' \item \code{out$func_scores}: a dense matrix with sampled scores where the
//' i-th row has samples for the i-th function.
//' \item \code{out$cov_scores}: a dense 3-dimensional array where the position (i, j, k) has the sampled score
//' of the j-th covariate associated to the k-th sample of the i-th function.}
//'
//' @examples
//' library(RayleighSelection)
//'
//' # Create a simplicial complex and compute the associated 0- and 1-laplacians
//' gy <- nerve_complex(list(c(1,4,6,10), c(1,2,7), c(2,3,8), c(3,4,9,10), c(4,5)))
//' lout <- combinatorial_laplacian(gy, one_forms = TRUE)
//'
//' # Create an associated instance of LaplacianScorer
//' scorer <- new(LaplacianScorer, lout, gy$points_in_vertex, gy$adjacency, TRUE)
//'
//' # Compute the 0-laplacian score of a a function
//' scorer$score(t(as.matrix(c(0,1,1,0,0,0,0,0,0,1))), 0)
//'
//' # Sample scores by shuffling the function
//' scorer$sample_scores(t(as.matrix(c(0,1,1,0,0,0,0,0,0,1))), 10, 0, 1)
//'
//' # Sample scores in tandem with a covariate
//' scorer$sample_with_covariate(t(as.matrix(c(0,1,1,0,0,0,0,0,0,1))),
//' t(as.matrix(c(0,1,0,1,0,0,0,0,0,1))), 10, 0, 1)
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::plugins(openmp)]]
#include <RcppArmadillo.h>
#include <Rcpp.h>
#include <math.h>
#include "LaplacianScorer.h"
#ifdef _OPENMP
#include <omp.h>
#endif
using namespace Rcpp;
LaplacianScorer::LaplacianScorer(const List& comb_laplacian,
const List& pts_in_vertex,
const arma::sp_mat& adjacency,
const bool one_forms){
//building points in vertex
points_in_simplex.push_back(std::vector<arma::uvec> ());
for(const IntegerVector& v: pts_in_vertex){
points_in_simplex[0].push_back(as<arma::uvec>(v) - 1);
}
//building other 0-d attributes
weights.push_back(as<arma::vec>(comb_laplacian["zero_weights"]));
length_const.push_back(arma::accu(weights[0]));
l.push_back(as<arma::sp_mat>(comb_laplacian["l0"]));
n_simplex.push_back(pts_in_vertex.length());
if(one_forms){
//getting 1-dim laplacian data
arma::sp_mat _l1 (as<arma::mat>(comb_laplacian["l1up"]) +
as<arma::mat>(comb_laplacian["l1down"]));
l.push_back(_l1);
weights.push_back(as<arma::vec>(comb_laplacian["one_weights"]));
length_const.push_back(arma::accu(weights[1]));
arma::uvec edge_order = as<arma::uvec>(comb_laplacian["adjacency_ordered"]);
n_simplex.push_back(edge_order.n_elem);
//building points in each edge
int i = 0;
points_in_simplex.push_back( std::vector<arma::uvec>(n_simplex[1]) );
for (arma::uword j = 0; j < n_simplex[0]; j++) {
arma::uvec o1 = points_in_simplex[0][j];
arma::uvec idxs = arma::find(adjacency.row(j));
if (idxs.size() == 0) continue;
for(arma::uvec::iterator it = idxs.begin(); it != idxs.end(); ++it) {
arma::uvec o2 = points_in_simplex[0][*it];
arma::uvec edge_cover = arma::intersect(o1, o2);
//if they do not intersect the edge represents the union
if (edge_cover.size() == 0) edge_cover = arma::join_cols(o1, o2);
points_in_simplex[1][edge_order(i)-1] = edge_cover;
i++;
}
}
}
}
arma::vec LaplacianScorer::score(const arma::mat& funcs, int dim){
//pushing function
arma::uword n_funcs = funcs.n_rows;
arma::mat pushed_func(n_funcs, n_simplex[dim], arma::fill::zeros);
for(arma::uword j = 0; j < n_simplex[dim]; ++j){
double num_points = points_in_simplex[dim][j].size();
for(const auto p: points_in_simplex[dim][j]){
for(arma::uword i = 0; i < n_funcs; ++i){
pushed_func.at(i,j) += funcs.at(i, p)/num_points; //unsafe access
}
}
}
//computing component orthogonal to constant (\tilde f)
pushed_func.each_col() -= pushed_func*weights[dim]/length_const[dim];
//computing scores
arma::vec score;
score = arma::diagvec(pushed_func*l[dim]*pushed_func.t()) /
(arma::square(pushed_func)*weights[dim]);
score.replace(arma::datum::nan, arma::datum::inf);
return score;
}
arma::mat LaplacianScorer::sample_scores(const arma::mat& funcs, arma::uword n_perm,
int dim, int n_cores){
arma::uword n_funcs = funcs.n_rows;
arma::mat scores(n_funcs, n_perm);
#if defined(_OPENMP)
#pragma omp parallel for num_threads(n_cores)
#endif
for(arma::uword i = 0; i < n_funcs; i++){
arma::rowvec f = funcs.row(i);
arma::mat shuffled (n_perm, funcs.n_cols);
for(arma::uword k = 0; k < n_perm; k++) shuffled.row(k) = arma::shuffle(f);
scores.row(i) = score(shuffled, dim).t();
}
return scores;
}
List LaplacianScorer::sample_with_covariate(const arma::mat& funcs, const arma::mat& cov,
arma::uword n_perm, int dim, int n_cores){
arma::uword n_funcs = funcs.n_rows;
arma::uword n_cov = cov.n_rows;
arma::mat func_scores (n_funcs, n_perm);//the i-th row has sampled scores
//sampled associated to i-th function
arma::cube cov_scores (n_funcs, n_cov, n_perm);//cov_scores[i, j, k] has the sampled score
//of the j-th covariate associated to
//the k-th sample of the i-th function
#if defined(_OPENMP)
#pragma omp parallel for num_threads(n_cores)
#endif
for(arma::uword i = 0; i < n_funcs; i++){
arma::rowvec f = funcs.row(i);
arma::mat f_shuffled (n_perm, funcs.n_cols); //each row is a shuffled f
arma::cube cov_shuffled (n_perm, funcs.n_cols, n_cov); //each row in the k-th slice is a
//shuffled k-th covariate
arma::uvec seq (funcs.n_cols);//sequence 0, ... , funcs.n_cols - 1
for(arma::uword u = 0; u < funcs.n_cols; u++) seq(u) = u;
//shuffling functions and covariates
for(arma::uword j = 0; j < n_perm; j++){
arma::uvec seq_shuffled = arma::shuffle(seq); //shuffling indices
f_shuffled.row(j) = f(seq_shuffled).t();
for(arma::uword l = 0; l < funcs.n_cols; l++){
for(arma::uword k = 0; k < n_cov; k++){
cov_shuffled(j, l, k) = cov(k, seq_shuffled(l));
}
}
}
//scoring shuffled functions and covariates
func_scores.row(i) = score(f_shuffled, dim).t();
arma::mat cov_scores_temp (n_cov, n_perm);
for(arma::uword k = 0; k < n_cov; k++){
//scores for the k-th covariate
cov_scores_temp.row(k) = score(cov_shuffled.slice(k), dim).t();
}
cov_scores.row(i) = cov_scores_temp;
}
List out = List::create(Named("func_scores") = func_scores,
Named("cov_scores") = cov_scores);
return out;
}
RCPP_MODULE(mod_laplacian){
class_<LaplacianScorer>("LaplacianScorer")
.constructor<List, List, arma::sp_mat, bool>()
.method("score", &LaplacianScorer::score)
.method("sample_scores", &LaplacianScorer::sample_scores)
.method("sample_with_covariate", &LaplacianScorer::sample_with_covariate)
;
}
| [
"artur.bicalho.s@gmail.com"
] | artur.bicalho.s@gmail.com |
59b2f3de6efce482e4ee9d572fbcc3910dd79505 | b18adf09556fa66a9db188684c69ea48849bb01b | /Elsov/SkyFrame/HardwareTest/TranceiverForm.cpp | fcd6a5a273b60168a4481fcfa6efc1bdcb5dafe8 | [] | no_license | zzfd97/projects | d78e3fa6418db1a5a2580edcaef1f2e197d5bf8c | f8e7ceae143317d9e8461f3de8cfccdd7627c3ee | refs/heads/master | 2022-01-12T19:56:48.014510 | 2019-04-05T05:30:31 | 2019-04-05T05:30:31 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 3,853 | cpp | // TranceiverForm.cpp : implementation file
//
#include "stdafx.h"
#include "TranceiverForm.h"
#include "Attached.h"
#include "Tranceiver.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CTranceiverForm
IMPLEMENT_DYNCREATE(CTranceiverForm, CAbstractForm)
CTranceiverForm::CTranceiverForm()
: CAbstractForm(CTranceiverForm::IDD)
{
//{{AFX_DATA_INIT(CTranceiverForm)
m_bOutputEnabled = FALSE;
m_Frequency = 0;
m_Gain = 0.0;
//}}AFX_DATA_INIT
}
CTranceiverForm::~CTranceiverForm()
{
}
void CTranceiverForm::DoDataExchange(CDataExchange* pDX)
{
CAbstractForm::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CTranceiverForm)
DDX_Control(pDX, IDC_GAIN_EDIT, m_GainEdit);
DDX_Control(pDX, IDC_TEMPERATURE_ALARM_STATIC, m_AlarmWnd);
DDX_Control(pDX, IDC_FREQUENCY_EDIT, m_FrequencyEdit);
DDX_Control(pDX, IDC_ONOFF_CHECK, m_bOutputControl);
DDX_Check(pDX, IDC_ONOFF_CHECK, m_bOutputEnabled);
DDX_Text(pDX, IDC_FREQUENCY_EDIT, m_Frequency);
DDX_Text(pDX, IDC_GAIN_EDIT, m_Gain);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CTranceiverForm, CAbstractForm)
//{{AFX_MSG_MAP(CTranceiverForm)
ON_BN_CLICKED(IDC_ONOFF_CHECK, OnOutputOnOffCheck)
ON_BN_CLICKED(IDC_SET_BUTTON, OnSetButton)
ON_BN_CLICKED(IDC_SET_GAIN_BUTTON, OnSetGainButton)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CTranceiverForm diagnostics
#ifdef _DEBUG
void CTranceiverForm::AssertValid() const
{
CAbstractForm::AssertValid();
}
void CTranceiverForm::Dump(CDumpContext& dc) const
{
CAbstractForm::Dump(dc);
}
#endif //_DEBUG
BOOL CTranceiverForm::SetupControls()
{
CDevice *pDevice=m_pAttached->m_pDevice;
m_pTranceiver = (CTranceiver *)pDevice;
m_pTranceiver->IsOutputOn(m_bOutputEnabled);
m_bOutputControl.EnableWindow(m_pTranceiver->CanOutputOnOff());
// Frequency
m_pTranceiver->GetFrequency(m_Frequency);
m_FrequencyEdit.EnableWindow(m_pTranceiver->CanSetFrequency());
GetDescendantWindow(IDC_SET_BUTTON)->EnableWindow(m_pTranceiver->CanSetFrequency());
// Gain
m_pTranceiver->GetGain(m_Gain);
m_GainEdit.EnableWindow(m_pTranceiver->CanSetGain());
GetDescendantWindow(IDC_SET_GAIN_BUTTON)->EnableWindow(m_pTranceiver->CanSetGain());
UpdateAllFields();
UpdateData(FALSE);
return TRUE;
}
BOOL CTranceiverForm::DoTimer()
{
UpdateAllFields();
return TRUE;
}
void CTranceiverForm::UpdateAllFields()
{
CString str;
// Temperature
if (m_pTranceiver->CanGetTemperature())
{
double T = -273.;
m_pTranceiver->GetTemperature(T);
str.Format("Temperature = %4.1f °C", T);
GetDescendantWindow(IDC_TEMPERATURE_STATIC)->SetWindowText(str);
}
// Temperature alarm
BOOL bAlarm = FALSE;
m_pTranceiver->IsTemperatureAlarm(bAlarm);
if (bAlarm)
m_AlarmWnd.ShowWindow(SW_SHOW);
else
m_AlarmWnd.ShowWindow(SW_HIDE);
// Power
if (m_pTranceiver->CanGetPower())
{
double P = 0.;
m_pTranceiver->GetPower(P);
str.Format("Power = %6.2f dBm", P);
GetDescendantWindow(IDC_POWER_STATIC)->SetWindowText(str);
}
else
GetDescendantWindow(IDC_POWER_STATIC)->ShowWindow(SW_HIDE);
}
/////////////////////////////////////////////////////////////////////////////
// CTranceiverForm message handlers
void CTranceiverForm::OnOutputOnOffCheck()
{
CWaitCursor cursor;
UpdateData();
m_pTranceiver->TurnOutputOn(m_bOutputEnabled);
UpdateData(FALSE);
}
void CTranceiverForm::OnSetButton()
{
UpdateData();
m_pTranceiver->SetFrequency(m_Frequency);
UpdateData(FALSE);
}
void CTranceiverForm::OnSetGainButton()
{
UpdateData();
m_pTranceiver->SetGain(m_Gain);
UpdateData(FALSE);
}
| [
"hp@kozhevnikov.org"
] | hp@kozhevnikov.org |
b852c8818b9fd6c189aa101a8b7a0ed4cd4cce3d | bb6ebff7a7f6140903d37905c350954ff6599091 | /net/cert/cert_verify_proc_nss.h | d9971cf34c8bf9620200bc2dce3ea89cac3c3f35 | [
"BSD-3-Clause"
] | permissive | PDi-Communication-Systems-Inc/lollipop_external_chromium_org | faa6602bd6bfd9b9b6277ce3cd16df0bd26e7f2f | ccadf4e63dd34be157281f53fe213d09a8c66d2c | refs/heads/master | 2022-12-23T18:07:04.568931 | 2016-04-11T16:03:36 | 2016-04-11T16:03:36 | 53,677,925 | 0 | 1 | BSD-3-Clause | 2022-12-09T23:46:46 | 2016-03-11T15:49:07 | C++ | UTF-8 | C++ | false | false | 1,676 | h | // Copyright (c) 2012 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 NET_CERT_CERT_VERIFY_PROC_NSS_H_
#define NET_CERT_CERT_VERIFY_PROC_NSS_H_
#include <certt.h>
#include "net/base/net_export.h"
#include "net/cert/cert_verify_proc.h"
namespace net {
// Performs certificate path construction and validation using NSS's libpkix.
class NET_EXPORT_PRIVATE CertVerifyProcNSS : public CertVerifyProc {
public:
CertVerifyProcNSS();
virtual bool SupportsAdditionalTrustAnchors() const OVERRIDE;
protected:
virtual ~CertVerifyProcNSS();
// Like VerifyInternal, but adds a |chain_verify_callback| to override trust
// decisions. See the documentation for CERTChainVerifyCallback and
// CERTChainVerifyCallbackFunc in NSS's lib/certdb/certt.h.
int VerifyInternalImpl(X509Certificate* cert,
const std::string& hostname,
int flags,
CRLSet* crl_set,
const CertificateList& additional_trust_anchors,
CERTChainVerifyCallback* chain_verify_callback,
CertVerifyResult* verify_result);
private:
virtual int VerifyInternal(X509Certificate* cert,
const std::string& hostname,
int flags,
CRLSet* crl_set,
const CertificateList& additional_trust_anchors,
CertVerifyResult* verify_result) OVERRIDE;
};
} // namespace net
#endif // NET_CERT_CERT_VERIFY_PROC_NSS_H_
| [
"mrobbeloth@pdiarm.com"
] | mrobbeloth@pdiarm.com |
06bb1fae6fc629eb05b74f791b00c941d984e338 | 5a60d60fca2c2b8b44d602aca7016afb625bc628 | /aws-cpp-sdk-iotevents/include/aws/iotevents/model/ListInputRoutingsResult.h | 06e913b7b6a3a58bd606d34e8ee17d8ebc09fda6 | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | yuatpocketgems/aws-sdk-cpp | afaa0bb91b75082b63236cfc0126225c12771ed0 | a0dcbc69c6000577ff0e8171de998ccdc2159c88 | refs/heads/master | 2023-01-23T10:03:50.077672 | 2023-01-04T22:42:53 | 2023-01-04T22:42:53 | 134,497,260 | 0 | 1 | null | 2018-05-23T01:47:14 | 2018-05-23T01:47:14 | null | UTF-8 | C++ | false | false | 4,264 | h | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/iotevents/IoTEvents_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/iotevents/model/RoutedResource.h>
#include <utility>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace IoTEvents
{
namespace Model
{
class ListInputRoutingsResult
{
public:
AWS_IOTEVENTS_API ListInputRoutingsResult();
AWS_IOTEVENTS_API ListInputRoutingsResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
AWS_IOTEVENTS_API ListInputRoutingsResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
/**
* <p> Summary information about the routed resources. </p>
*/
inline const Aws::Vector<RoutedResource>& GetRoutedResources() const{ return m_routedResources; }
/**
* <p> Summary information about the routed resources. </p>
*/
inline void SetRoutedResources(const Aws::Vector<RoutedResource>& value) { m_routedResources = value; }
/**
* <p> Summary information about the routed resources. </p>
*/
inline void SetRoutedResources(Aws::Vector<RoutedResource>&& value) { m_routedResources = std::move(value); }
/**
* <p> Summary information about the routed resources. </p>
*/
inline ListInputRoutingsResult& WithRoutedResources(const Aws::Vector<RoutedResource>& value) { SetRoutedResources(value); return *this;}
/**
* <p> Summary information about the routed resources. </p>
*/
inline ListInputRoutingsResult& WithRoutedResources(Aws::Vector<RoutedResource>&& value) { SetRoutedResources(std::move(value)); return *this;}
/**
* <p> Summary information about the routed resources. </p>
*/
inline ListInputRoutingsResult& AddRoutedResources(const RoutedResource& value) { m_routedResources.push_back(value); return *this; }
/**
* <p> Summary information about the routed resources. </p>
*/
inline ListInputRoutingsResult& AddRoutedResources(RoutedResource&& value) { m_routedResources.push_back(std::move(value)); return *this; }
/**
* <p> The token that you can use to return the next set of results, or
* <code>null</code> if there are no more results. </p>
*/
inline const Aws::String& GetNextToken() const{ return m_nextToken; }
/**
* <p> The token that you can use to return the next set of results, or
* <code>null</code> if there are no more results. </p>
*/
inline void SetNextToken(const Aws::String& value) { m_nextToken = value; }
/**
* <p> The token that you can use to return the next set of results, or
* <code>null</code> if there are no more results. </p>
*/
inline void SetNextToken(Aws::String&& value) { m_nextToken = std::move(value); }
/**
* <p> The token that you can use to return the next set of results, or
* <code>null</code> if there are no more results. </p>
*/
inline void SetNextToken(const char* value) { m_nextToken.assign(value); }
/**
* <p> The token that you can use to return the next set of results, or
* <code>null</code> if there are no more results. </p>
*/
inline ListInputRoutingsResult& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;}
/**
* <p> The token that you can use to return the next set of results, or
* <code>null</code> if there are no more results. </p>
*/
inline ListInputRoutingsResult& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;}
/**
* <p> The token that you can use to return the next set of results, or
* <code>null</code> if there are no more results. </p>
*/
inline ListInputRoutingsResult& WithNextToken(const char* value) { SetNextToken(value); return *this;}
private:
Aws::Vector<RoutedResource> m_routedResources;
Aws::String m_nextToken;
};
} // namespace Model
} // namespace IoTEvents
} // namespace Aws
| [
"aws-sdk-cpp-automation@github.com"
] | aws-sdk-cpp-automation@github.com |
2b721eaa43bb8186d6d16c95ddc4d610946577ad | 029462827b95625e0b72f1dada384c49106ac409 | /dellve_cudnn_benchmark/include/CuDNN/ConvolutionBwdDataAlgoPerf.hpp | 53366aaab3584ea072bb32aff3a685b3422c9ae3 | [
"MIT"
] | permissive | dellve/dellve_cudnn | c05c993bacfe721f6a34e3ec83aaa9d7e09ec11c | 61491953f3f3953539e6060ccf18c303e7a3c1fd | refs/heads/master | 2021-01-22T23:15:58.258731 | 2017-05-02T16:45:49 | 2017-05-02T16:45:49 | 89,177,551 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 282 | hpp | #ifndef PYCUDNN_CONVOLUTION_BWD_DATA_ALGO_PERF_HPP
#define PYCUDNN_CONVOLUTION_BWD_DATA_ALGO_PERF_HPP
#include <cudnn.h>
namespace CuDNN {
typedef cudnnConvolutionBwdDataAlgoPerf_t ConvolutionBwdDataAlgoPerf;
} // PyCuDNN
#endif // PYCUDNN_CONVOLUTION_BWD_DATA_ALGO_PERF_HPP
| [
"jayeshjo1@utexas.edu"
] | jayeshjo1@utexas.edu |
6ed2a2dbd3fd1f1745861abeced55eedf2da1936 | 5621fa1ad956aba95995c474f35c09c78a4f008b | /volume11_1193.cpp | 6ff9ba4faee33ee9f17fc63db260f89a91e2660c | [] | no_license | tasogare66/atcoder | ea3e6cdcdd28f2c6be816d85e0b521d0cb94d6a3 | 16bc66ab3f72788f1a940be921edc681763f86f1 | refs/heads/master | 2020-05-09T14:33:30.659718 | 2020-04-14T14:09:37 | 2020-04-14T14:09:37 | 181,196,939 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,817 | cpp | //http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=1193&lang=jp
//連鎖消滅パズル
#include <bits/stdc++.h>
#if LOCAL
#include "dump.hpp"
#else
#define dump(...)
#endif
using namespace std;
using ll=long long;
const ll LINF = 0x1fffffffffffffff;
#define FOR(i,a,b) for(ll i=(a);i<(b);++i)
#define REP(i,n) FOR(i,0,n)
template<class T>bool chmax(T &a, const T &b) {if (a<b) { a=b; return 1; } return 0;}
template<class T>bool chmin(T &a, const T &b) {if (b<a) { a=b; return 1; } return 0;}
bool solve(){
ll h; cin>>h;
if(h<=0) return false;
vector<vector<ll>> tbl(h,vector<ll>(5));
for(auto&& l:tbl){
for(auto&& v:l) cin>>v;
}
auto calc = [](vector<ll>& tbl){
ll result=0;
REP(i,tbl.size()){
ll num=0;
if(tbl.at(i)==0)continue;
FOR(j,i+1,tbl.size()){
if(tbl.at(i)!=tbl.at(j)) break;
++num;
}
++num;
if(num>=3){//先頭も含む
FOR(j,i,i+num){
result += tbl.at(j);
tbl.at(j)=0; //消す
}
break;
}
}
return result;
};
auto otosu =[&](){
FOR(x,0,5){
for(ll y=h-1;y>=0;--y){
if(tbl[y][x]==0){
for(ll y2=y-1;y2>=0;--y2){
if(tbl[y2][x]!=0){
swap(tbl[y][x],tbl[y2][x]);
break;
}
}
}
}
}
};
ll ans=0;
do{
dump(tbl); dump(ans);
ll tmp=0;
FOR(i,0,tbl.size()){
tmp += calc(tbl.at(i));//消す
}
if(tmp==0)break;
ans += tmp;
//落す
otosu();
}while(true);
cout<<ans<<endl;
return true;
}
int main() {
#if LOCAL&01
//std::ifstream in("./test/sample-1.in");
std::ifstream in("./input.txt");
std::cin.rdbuf(in.rdbuf());
#else
cin.tie(0);
ios::sync_with_stdio(false);
#endif
while(solve()){
}
return 0;
} | [
"tasogare66@gmai.com"
] | tasogare66@gmai.com |
20a6fcafc0523e5f59b36be149a334f9ef3fe6f3 | 0c861bd330a647984077430a1af63f549f06085a | /configuration.h | 3b8760fa38db94e8f4484506cd1fc566ede3da11 | [] | no_license | derjust/sqlspruch | 7fba5bd7fa6e5c54f291a1c8704addd94167dd5d | 3dfed8cb4ebef7bbb8bda8c2597cc5de4be94f66 | refs/heads/master | 2021-01-12T12:13:36.729394 | 2006-10-16T15:30:42 | 2006-10-16T15:30:42 | 72,374,048 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 404 | h | #include "unistd.h"
#include <cstdlib>
#include <qstring.h>
#include <iostream>
using namespace std;
class TConfig
{
private:
QString myHost;
QString myUsername;
QString myPassword;
QString myError;
unsigned int myZeilenumbruch;
public:
TConfig(int argc, char **argv);
QString GetUsername();
QString GetPassword();
QString GetHost();
QString GetError();
unsigned int GetZeilenumbruch();
};
| [
"derjust@users.noreply.github.com"
] | derjust@users.noreply.github.com |
696237b87ed6efae1a01f0f640ad56b94e3c9523 | 06cc6e99ee1d0a6ad120763ad004c38d757b77cd | /Timus/1654.cpp | 1f10524b7e10e8ffa8251aa8a65374d091990e2b | [] | no_license | MaicolGomez/ACM | 0eddec0ba8325c6bdc07721acc57a361c03c4588 | ff23b2c24daa5df1cc864b134886ff81a6d488c7 | refs/heads/master | 2020-03-06T20:57:14.628666 | 2018-03-28T01:46:27 | 2018-03-28T01:51:08 | 127,066,787 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,159 | cpp | #include<cstdio>
#include<iostream>
#include<cstring>
#include<vector>
#include<cmath>
#include<algorithm>
#include<climits>
#include<set>
#include<deque>
#include<queue>
#include<map>
#include<climits>
#include<string>
#include<stack>
#include<sstream>
using namespace std;
#define pi (2.0*acos(0.0))
#define eps 1e-6
#define ll long long
#define inf (1<<29)
#define vi vector<int>
#define vll vector<ll>
#define sc(x) scanf("%d",&x)
#define scl(x) scanf("%lld",&x)
#define all(v) v.begin() , v.end()
#define me(a,val) memset( a , val ,sizeof(a) )
#define pb(x) push_back(x)
#define pii pair<int,int>
#define mp(a,b) make_pair(a,b)
#define Q(x) (x) * (x)
#define L(x) ((x<<1) + 1)
#define R(x) ((x<<1) + 2)
#define M(x,y) ((x+y)>>1)
#define fi first
#define se second
#define MOD 1000000007
#define ios ios::sync_with_stdio(0);
#define N 200005
char s[N] , ans[N] = {0};
int main(){
scanf("%s",s);
int len = strlen(s) , sz = 0;
for(int i = 0 ; i < len ; i++){
if( sz == 0 or ans[sz-1] != s[i] ) ans[sz++] = s[i];
else sz--;
}
for(int i = 0 ; i < sz ; i++)
printf("%c",ans[i]);
printf("\n");
return 0;
}
| [
"maycolgo@gmail.com"
] | maycolgo@gmail.com |
0ada146cd126d3055baa5414c8b8e115cdfc2419 | f7cbe3ca5cdbbf18cbff04ea8f9f06fa9ac5be59 | /suwhoanlim/6.DFS/11403_findRoute.cpp | 4a4e4ce6b1c7192f76117bcde4eaea9c016b40bc | [] | no_license | I-ll-Go-Rythm/2021_winter_study | 4fd822c96469e68ced6d01f31169bf39b48ef0cd | 9040022f9d1d13feef433b22f7ee1352e064d1e9 | refs/heads/master | 2023-04-21T13:46:57.066861 | 2021-04-30T12:34:02 | 2021-04-30T12:34:02 | 332,349,909 | 1 | 0 | null | 2021-01-24T02:19:27 | 2021-01-24T02:18:33 | C++ | UTF-8 | C++ | false | false | 947 | cpp | // you need vis array to check whether the node was previously visited or not
// this code can be shortened but i am too lazy to do so
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int N;
vector<int> vec;
int arr[101][101];
int sol[101];
int vis[101];
void dfs(int from, int to) {
if(arr[from][to] != 1 || vis[to] == 1) {return;}
sol[to] = 1; vis[to] = 1;
for(int z = 0; z < N; ++z)
if(arr[to][z] == 1 && vis[z] != 1) dfs(to, z);
return;
}
int main(void) {
cin >> N;
for(int i = 0; i < N; ++i) {
for(int k = 0; k < N; ++k)
cin >> arr[i][k];
}
for(int i = 0; i < N; ++i){
for(int j = 0; j < N; ++j) {
if(arr[i][j] == 1) dfs(i, j);
}
for(int k = 0; k < N; ++k) {
cout << sol[k] << ' ';
sol[k] = 0;
vis[k] = 0;
}
cout << '\n';
}
return 0;
}
| [
"ludence1029@gmail.com"
] | ludence1029@gmail.com |
32cd3325eff6b8c710ab791f04fe03e00b922e7d | c2aba0372ecdeff34f79471f69c4eec320be1b28 | /pset09/asst/a9.h | e7c2181ecd07f47eb3b8dc946e1b641dce1ed036 | [] | no_license | nicholaslocascio/6865 | 471b917d0135641ab09ad42d797f4277a9a253ca | c7f98b38ee08942ef989dcbcc2c65f45bd62af7c | refs/heads/master | 2020-05-20T05:59:12.826908 | 2015-04-23T00:40:04 | 2015-04-23T00:40:04 | 30,370,882 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 787 | h | #ifndef _A9_H_
#define _A9_H_
#include <iostream>
#include <cmath>
#include <Halide.h>
#include <image_io.h>
using std::string;
using std::map;
using std::cout;
using std::cerr;
using std::endl;
void apply_auto_schedule(Func F);
Image<uint8_t> SmoothGradNormalized(void);
Image<uint8_t> WavyRGB(void);
Image<uint8_t> Luminance(Image<uint8_t> input);
Image<uint8_t> Sobel(Image<uint8_t> input);
void cppCovoidorBoxSchedule5(Image<uint8_t> input);
void cppCovoidorBoxSchedule6(Image<uint8_t> input);
void cppCovoidorBoxSchedule7(Image<uint8_t> input);
Func LocalMax(Image<uint8_t> lumi, int window=5);
Func Gaussian(Image<uint8_t> input, float sigma, float truncate=3.0f);
Func UnsharpMask(Image<uint8_t> input, float sigma, float truncate=3.0f, float strength=1.0f);
#endif // _A9_H_
| [
"nicholasjlocascio@gmail.com"
] | nicholasjlocascio@gmail.com |
efe0ce6cb2bf621a9606ca5bfc7d0710ad728151 | e5d80ba4a33aa6a2c6069fdf661e258be4552887 | /src/samples/game/android/app/src/main/cpp/bindings.cpp | 13d0ff4e4eb21c61c75824c538259fce924c646a | [
"Zlib"
] | permissive | sjmerel/ck | 56fc91b805ee3a1b1db8bb7e0f01918570db9388 | 5d4cb073ec95968bc1b461dfddf5a4a89e5d4c31 | refs/heads/master | 2023-03-16T05:33:18.183543 | 2020-02-23T19:05:22 | 2020-02-23T19:05:22 | 242,427,476 | 24 | 12 | Zlib | 2021-06-21T06:35:05 | 2020-02-22T23:36:49 | C++ | UTF-8 | C++ | false | false | 1,268 | cpp | #include <jni.h>
#include "../../../../../game.h"
extern "C"
{
void
Java_com_crickettechnology_game_GameActivity_nativeCreate(JNIEnv* env, jclass, jobject activity)
{
gamePrintf("game create\n");
gameInit(env, activity);
}
void
Java_com_crickettechnology_game_GameRenderer_nativeGlInit(JNIEnv* env, jclass)
{
gamePrintf("game GL init\n");
gameGlInit();
}
void
Java_com_crickettechnology_game_GameRenderer_nativeResize(JNIEnv* env, jclass, jint w, jint h)
{
gamePrintf("game resize\n");
gameResize(w, h);
}
void
Java_com_crickettechnology_game_GameActivity_nativePause(JNIEnv* env, jclass, jint w, jint h)
{
gamePrintf("game suspend\n");
gameSuspend();
}
void
Java_com_crickettechnology_game_GameActivity_nativeResume(JNIEnv* env, jclass, jint w, jint h)
{
gamePrintf("game resume\n");
gameResume();
}
void
Java_com_crickettechnology_game_GameActivity_nativeDestroy(JNIEnv* env, jclass)
{
gamePrintf("game destroy\n");
gameShutdown();
}
void
Java_com_crickettechnology_game_GameRenderer_nativeRender(JNIEnv* env, jclass)
{
gameRender();
}
void
Java_com_crickettechnology_game_GameGLSurfaceView_nativeTouch(JNIEnv* env, jclass, jint code, jfloat x, jfloat y)
{
gameTouch((GameTouchType) code, x, y);
}
}
| [
"steve@focusmotion.io"
] | steve@focusmotion.io |
bbd3bd8997523e1caaf036e574b2c2f9fb2ef1a0 | d6f4fe10f2b06486f166e8610a59f668c7a41186 | /Base/cxx/vtkImageZoom2D.cxx | 14cf3bf58c3e231bf2c19f1bcff526aa14522882 | [] | no_license | nagyistge/slicer2-nohistory | 8a765097be776cbaa4ed1a4dbc297b12b0f8490e | 2e3a0018010bf5ce9416aed5b5554868b24e9295 | refs/heads/master | 2021-01-18T10:55:51.892791 | 2011-02-23T16:49:01 | 2011-02-23T16:49:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,167 | cxx | /*=auto=========================================================================
Portions (c) Copyright 2005 Brigham and Women's Hospital (BWH) All Rights Reserved.
See Doc/copyright/copyright.txt
or http://www.slicer.org/copyright/copyright.txt for details.
Program: 3D Slicer
Module: $RCSfile: vtkImageZoom2D.cxx,v $
Date: $Date: 2006/02/23 01:43:34 $
Version: $Revision: 1.12 $
=========================================================================auto=*/
#include "vtkImageZoom2D.h"
#include "vtkObjectFactory.h"
#include "vtkImageData.h"
//------------------------------------------------------------------------------
vtkImageZoom2D* vtkImageZoom2D::New()
{
// First try to create the object from the vtkObjectFactory
vtkObject* ret = vtkObjectFactory::CreateInstance("vtkImageZoom2D");
if(ret)
{
return (vtkImageZoom2D*)ret;
}
// If the factory was unable to create the object, then create it here.
return new vtkImageZoom2D;
}
//----------------------------------------------------------------------------
// Description:
// Constructor sets default values
vtkImageZoom2D::vtkImageZoom2D()
{
this->Magnification = 1.0;
this->AutoCenterOn();
for (int i=0; i<2; i++)
{
this->Step[i] = 0;
this->Origin[i] = 0;
this->Center[i] = 0;
this->OrigPoint[i] = 0;
this->ZoomPoint[i] = 0;
}
}
//----------------------------------------------------------------------------
void vtkImageZoom2D::ExecuteInformation(vtkImageData *inData,
vtkImageData *outData)
{
int i;
vtkFloatingPointType *spacing, outSpacing[3];
// Change output spacing
if (this->Magnification == 0.0)
{
this->Magnification = 1.0;
}
spacing = inData->GetSpacing();
for (i = 0; i < 3; i++)
{
outSpacing[i] = spacing[i] / this->Magnification;
}
outData->SetSpacing(outSpacing);
}
//----------------------------------------------------------------------------
// x,y is a Zoom point
void vtkImageZoom2D::SetZoomPoint(int x, int y)
{
this->ZoomPoint[0] = x;
this->ZoomPoint[1] = y;
this->OrigPoint[0] = (int)(this->Origin[0] + this->Step[0]*(vtkFloatingPointType)x + 0.49);
this->OrigPoint[1] = (int)(this->Origin[1] + this->Step[1]*(vtkFloatingPointType)y + 0.49);
}
#define NBITS1 16
#define MULTIPLIER1 65536.0f
#define FLOAT_TO_FAST1(x) (int)((x) * MULTIPLIER1)
#define FAST1_TO_FLOAT(x) ((x) / MULTIPLIER1)
#define FAST1_TO_INT(x) ((x) >> NBITS1)
#define INT_TO_FAST1(x) ((x) << NBITS1)
#define FAST1_MULT(x, y) (((x) * (y)) >> NBITS1)
//----------------------------------------------------------------------------
// Description:
// This templated function executes the filter for any type of data.
template <class T>
static void vtkImageZoom2DExecute(vtkImageZoom2D *self,
vtkImageData *inData, T *inPtr, int inExt[6],
vtkImageData *outData, T* outPtr,
int outExt[6], int wExt[6], int id, int integerMath)
{
int i, idxX, idxY, maxX, maxY, inRowLength, inMaxX, inMaxY;
int outIncX, outIncY, outIncZ, numComps;
vtkFloatingPointType scale, step[2], origin[2], center[2], xRewind, invMag;
vtkFloatingPointType x, y;
long idx, nx, ny, nx2, ny2, xi, yi;
// find whole size of output for boundary checking
nx = wExt[1] - wExt[0] + 1;
ny = wExt[3] - wExt[2] + 1;
nx2 = nx - 2;
ny2 = ny - 2;
// find the region to loop over
numComps = inData->GetNumberOfScalarComponents();
maxX = outExt[1];
maxY = outExt[3];
inMaxX = inExt[1] - inExt[0];
inMaxY = inExt[3] - inExt[2];
inRowLength = (inMaxX+1)*numComps;
int scalarSize = numComps*sizeof(T);
// We will walk through zoom space and calculate xy space
// coordinates to obtain source pixels.
invMag = self->GetMagnification();
if (invMag == 0.0)
{
invMag = 1.0;
}
invMag = 1.0 / invMag;
// step vector
step[0] = invMag;
step[1] = invMag;
// If AutoCenter is on, then use the center of the input
if (self->GetAutoCenter())
{
self->SetCenter(nx/2, ny/2);
}
self->GetCenter(center);
// Find origin (upper left) of zoom space in terms of xy space coordinates
origin[0] = center[0] - nx*step[0] / 2.0;
origin[1] = center[1] - ny*step[1] / 2.0;
// Return points to the user
for (i=0; i<2; i++)
{
self->SetOrigin(origin);
self->SetStep(step);
}
// Advance to the origin of this output extent (used for threading)
// x
scale = (vtkFloatingPointType)(outExt[0]-wExt[0])/(vtkFloatingPointType)(wExt[1]-wExt[0]+1);
origin[0] = origin[0] + scale*nx*step[0];
scale = (vtkFloatingPointType)(outExt[2]-wExt[2])/(vtkFloatingPointType)(wExt[3]-wExt[2]+1);
origin[1] = origin[1] + scale*ny*step[1];
// Initialize zoom coords x, y to origin
x = origin[0];
y = origin[1];
// Get increments to march through data
outData->GetContinuousIncrements(outExt, outIncX, outIncY, outIncZ);
if (integerMath)
{
int fround, fx, fy, fxStep, fyStep, fxRewind;
// Convert vtkFloatingPointType to fast
fx = FLOAT_TO_FAST1(x);
fy = FLOAT_TO_FAST1(y);
fxStep = FLOAT_TO_FAST1(step[0]);
fyStep = FLOAT_TO_FAST1(step[1]);
fround = FLOAT_TO_FAST1(0.49);
// Loop through output pixels
for (idxY = outExt[2]; idxY <= maxY; idxY++)
{
fxRewind = fx;
for (idxX = outExt[0]; idxX <= maxX; idxX++)
{
// Compute integer parts of volume coordinates
xi = FAST1_TO_INT(fx + fround);
yi = FAST1_TO_INT(fy + fround);
// Test if coordinates are outside volume
if ((xi < 0) || (yi < 0) || (xi > nx2) || (yi > ny2))
{
memset(outPtr, 0, scalarSize);
}
else
{
idx = yi*inRowLength + xi*numComps;
memcpy(outPtr, &inPtr[idx], scalarSize);
}
outPtr += numComps;
fx += fxStep;
}
outPtr += outIncY;
fx = fxRewind;
fy += fyStep;
}
}
else
{
// Loop through output pixels
for (idxY = outExt[2]; idxY <= maxY; idxY++)
{
xRewind = x;
for (idxX = outExt[0]; idxX <= maxX; idxX++)
{
// Compute integer parts of volume coordinates
xi = (int)(x + 0.49);
yi = (int)(y + 0.49);
// Test if coordinates are outside volume
if ((xi < 0) || (yi < 0) || (xi > nx2) || (yi > ny2))
{
memset(outPtr, 0, scalarSize);
}
else
{
idx = yi*inRowLength + xi*numComps;
memcpy(outPtr, &inPtr[idx], scalarSize);
}
outPtr += numComps;
x += step[0];
}
outPtr += outIncY;
x = xRewind;
y += step[1];
}
}
}
//----------------------------------------------------------------------------
// Description:
// This method is passed a input and output data, and executes the filter
// algorithm to fill the output from the input.
// It just executes a switch statement to call the correct function for
// the datas data types.
void vtkImageZoom2D::ThreadedExecute(vtkImageData *inData,
vtkImageData *outData,
int outExt[6], int id)
{
int *inExt = inData->GetExtent();
void *inPtr = inData->GetScalarPointerForExtent(inExt);
void *outPtr = outData->GetScalarPointerForExtent(outExt);
int wExt[6];
outData->GetWholeExtent(wExt);
// Ensure intput is 2D
if (inExt[5] != inExt[4])
{
vtkErrorMacro("ThreadedExecute: Input must be 2D.");
return;
}
switch (inData->GetScalarType())
{
case VTK_FLOAT:
vtkImageZoom2DExecute(this, inData, (float *)(inPtr), inExt,
outData, (float *) outPtr, outExt, wExt, id, 0);
break;
case VTK_INT:
vtkImageZoom2DExecute(this, inData, (int *)(inPtr), inExt,
outData, (int *) outPtr, outExt, wExt, id, 0);
break;
case VTK_SHORT:
vtkImageZoom2DExecute(this, inData, (short *)(inPtr), inExt,
outData, (short *) outPtr, outExt, wExt, id, 1);
break;
case VTK_UNSIGNED_SHORT:
vtkImageZoom2DExecute(this, inData, (unsigned short *)(inPtr), inExt,
outData, (unsigned short *) outPtr, outExt, wExt, id, 0);
break;
case VTK_UNSIGNED_CHAR:
vtkImageZoom2DExecute(this, inData, (unsigned char *)(inPtr), inExt,
outData, (unsigned char *) outPtr, outExt, wExt, id, 1);
break;
case VTK_CHAR:
vtkImageZoom2DExecute(this, inData, (char *)(inPtr), inExt,
outData, (char *) outPtr, outExt, wExt, id, 1);
break;
case VTK_UNSIGNED_LONG:
vtkImageZoom2DExecute(this, inData, (unsigned long *)(inPtr), inExt,
outData, (unsigned long *) outPtr, outExt, wExt, id, 0);
break;
case VTK_LONG:
vtkImageZoom2DExecute(this, inData, (long *)(inPtr), inExt,
outData, (long *) outPtr, outExt, wExt, id, 0);
break;
case VTK_DOUBLE:
vtkImageZoom2DExecute(this, inData, (double *)(inPtr), inExt,
outData, (double *) outPtr, outExt, wExt, id, 0);
break;
case VTK_UNSIGNED_INT:
vtkImageZoom2DExecute(this, inData, (unsigned int *)(inPtr), inExt,
outData, (unsigned int *) outPtr, outExt, wExt, id, 0);
break;
default:
vtkErrorMacro(<< "Execute: Unknown input ScalarType");
return;
}
}
//----------------------------------------------------------------------------
void vtkImageZoom2D::PrintSelf(ostream& os, vtkIndent indent)
{
Superclass::PrintSelf(os,indent);
os << indent << "Zoom Point X: " << this->ZoomPoint[0] << "\n";
os << indent << "Zoom Point Y: " << this->ZoomPoint[1] << "\n";
os << indent << "Orig Point X: " << this->OrigPoint[0] << "\n";
os << indent << "Orig Point Y: " << this->OrigPoint[1] << "\n";
os << indent << "Center X: " << this->Center[0] << "\n";
os << indent << "Center Y: " << this->Center[1] << "\n";
os << indent << "AutoCenter: " << this->AutoCenter << "\n";
os << indent << "Magnification: " << this->Magnification << "\n";
os << indent << "Step: " << this->Step[0] << "," << \
this -> Step[1] << "\n";
os << indent << "Origin: " << this->Origin[0] << "," << \
this -> Origin[1] << "\n";
}
| [
"pieper@bwh.harvard.edu"
] | pieper@bwh.harvard.edu |
f4d178b026ac3c1cb5136a0040f4c56bfba8c966 | 1431976f2643e5bd94a33d774314a733b0e3c96f | /fnc1.cpp | 03c764df5acfcb9af7ab4a8ff1c2352d8886e760 | [] | no_license | mohsinenur/UVaOnlineJudge | d9a4297893e16d54d320b2010d6661acb7b1aae0 | 21b12b1d00be0f31a9c6f9f941ccaa8543f48ea5 | refs/heads/master | 2021-08-08T23:26:20.197703 | 2017-11-11T15:58:07 | 2017-11-11T15:58:07 | 110,358,606 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 202 | cpp | #include<bits/stdc++.h>
using namespace std;
void nameP(char w[100]){
cout << "My name is " << w << endl;
}
€
int main()
{
char w[100];
cin.getline(w,100);
nameP(w);
return 0;
}
| [
"follow.mohsin@gmail.com"
] | follow.mohsin@gmail.com |
963230b70556ba635430d1afb9395a5a7a944a39 | 8da0a2eb756ec80cc3d706360bd7d87d6715bd19 | /Programs/Arrays/MatrixMultiply.cpp | 49626c9110946f55a7d82fde8ff1b83e8ea9739b | [] | no_license | Lordhacker756/CompetativeCoding | 34c4a44c9668960fcf5f81b01d5792cd8254d185 | 925dc39e00427d25f3f6d6d82556f55c8d1b5604 | refs/heads/main | 2023-08-15T00:40:35.166713 | 2021-10-07T06:33:57 | 2021-10-07T06:33:57 | 410,946,350 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,285 | cpp | // Code for multiplying two matrices!😎
#include <iostream>
using namespace std;
int main()
{
int n1, n2, n3;
cin >> n1 >> n2 >> n3;
int m1[n1][n2];
int m2[n2][n3];
// Taking Inputs for both matrices
for (int i = 0; i < n1; i++)
{
for (int j = 0; j < n2; j++)
{
cin >> m1[i][j];
}
}
for (int i = 0; i < n2; i++)
{
for (int j = 0; j < n3; j++)
{
cin >> m2[i][j];
}
}
// Important step, if you dont intialize the default matrix it will contain vague values and give wrong answer!
int ans[n1][n3];
for (int i = 0; i < n1; i++)
{
for (int j = 0; j < n3; j++)
{
ans[i][j]=0;
}
}
for (int i = 0; i < n1; i++)
{
for (int j = 0; j< n3; j++)
{
for (int k = 0; k < n2; k++)
{
//Compare i j and k with limiting values and relate it with sizes of matrices for easier understanding!
ans[i][j]=m1[i][k]*m2[k][j];
}
}
}
for (int i = 0; i < n1; i++)
{
for (int j = 0; j < n3; j++)
{
cout<<ans[i][j]<<" ";
}
cout<<endl;
}
return 0;
} | [
"utkarshmishra2001@gmail.com"
] | utkarshmishra2001@gmail.com |
b4bc05d810166c63e94e9455f31dc448f8758d3c | d7ace509f6ce64003e3b63e13f581cc8bc86dc1b | /include/GafferUIBindings/NodeGadgetBinding.inl | 26341a4025282b09905013540d2248f0a881c28b | [
"BSD-3-Clause"
] | permissive | ldmoser/gaffer | b9cfd842c0dfde14b0dc2c9fd41fe116a85638f8 | 2987bc772765f47ce7414bd129c92a1c9b16b18a | refs/heads/master | 2021-01-18T20:35:41.445317 | 2014-07-04T15:43:41 | 2014-07-04T15:43:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,593 | inl | //////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2014, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above
// copyright notice, this list of conditions and the following
// disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided with
// the distribution.
//
// * Neither the name of John Haddon nor the names of
// any other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#ifndef GAFFERUIBINDINGS_NODEGADGETBINDING_INL
#define GAFFERUIBINDINGS_NODEGADGETBINDING_INL
namespace GafferUIBindings
{
namespace Detail
{
template<typename T>
GafferUI::NodulePtr nodule( T &p, Gaffer::ConstPlugPtr plug )
{
return p.T::nodule( plug );
}
template<typename T>
Imath::V3f noduleTangent( T &p, const GafferUI::Nodule *nodule )
{
return p.T::noduleTangent( nodule );
}
} // namespace Detail
template<typename T, typename TWrapper>
NodeGadgetClass<T, TWrapper>::NodeGadgetClass( const char *docString )
: GadgetClass<T, TWrapper>( docString )
{
def( "nodule", &Detail::nodule<T> );
def( "noduleTangent", &Detail::noduleTangent<T> );
}
} // namespace GafferUIBindings
#endif // GAFFERUIBINDINGS_NODEGADGETBINDING_INL
| [
"thehaddonyoof@gmail.com"
] | thehaddonyoof@gmail.com |
e139b688fa2d0d48201345215e9d55bed72d0a48 | 3e5f3f010ccaa347ae32cb31a791e924c2ee73ae | /src/trac_ik_lib/src/trac_ik.cpp | 1e7659226fbf719e080cd01e33af0d8ee7c3757e | [] | no_license | brianzhan/trac_ik1 | c6ce9126a77a90ef47d2e3ba8a760e08f50d8cae | 5add2d3ea135d6d496c0bdb0ecbe11549bac4083 | refs/heads/master | 2021-04-30T22:47:06.257812 | 2016-02-10T01:49:40 | 2016-02-10T01:49:40 | 51,415,030 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,899 | cpp | /********************************************************************************
Copyright (c) 2015, TRACLabs, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
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.
********************************************************************************/
// given joints, find position; given 4x4 of desired location and angles, find 6 radians
#include <trac_ik/trac_ik.hpp>
#include <boost/date_time.hpp>
#include <boost/make_shared.hpp>
#include <Eigen/Geometry>
#include <ros/ros.h>
#include <limits>
#include <kdl_parser/kdl_parser.hpp>
#include <urdf/model.h>
namespace TRAC_IK {
TRAC_IK::TRAC_IK(const std::string& base_link, const std::string& tip_link, const std::string& URDF_param, double _maxtime, double _eps, SolveType _type ) : // <param name="urdf_param" value="/robot_description"/>
initialized(false),
eps(_eps),
maxtime(_maxtime),
solvetype(_type),
work(io_service)
{
ros::NodeHandle node_handle("~");
urdf::Model robot_model; // has things like getParentJoint, getChildJoint, initXML
std::string xml_string; // declaring string claled xml_string
std::string urdf_xml,full_urdf_xml;
node_handle.param("urdf_xml",urdf_xml,URDF_param); // tree of urdf_xml loaded into urdf_xml
node_handle.searchParam(urdf_xml,full_urdf_xml);
ROS_DEBUG_NAMED("trac_ik","Reading xml file from parameter server");
if (!node_handle.getParam(full_urdf_xml, xml_string)) //node_handle is class for enstantiating nodes
{
ROS_FATAL_NAMED("trac_ik","Could not load the xml from parameter server: %s", urdf_xml.c_str());
return;
}
node_handle.param(full_urdf_xml,xml_string,std::string()); // (key to be searched for on parameter server, storage for retrieved value, value to use if server doesn't contain this parameter)
robot_model.initString(xml_string); // load model from xml_string
ROS_DEBUG_STREAM_NAMED("trac_ik","Reading joints and links from URDF");
boost::shared_ptr<urdf::Link> link = boost::const_pointer_cast<urdf::Link>(robot_model.getLink(tip_link)); //deleted when the last ptr to it is reset/destroyed
std::vector<double> l_bounds, u_bounds;
while(link->name != base_link)
{
ROS_DEBUG_NAMED("trac_ik","Link %s",link->name.c_str());
boost::shared_ptr<urdf::Joint> joint = link->parent_joint; // creating a tree
if(joint) {
if (joint->type != urdf::Joint::UNKNOWN && joint->type != urdf::Joint::FIXED) {
ROS_DEBUG_STREAM_NAMED("trac_ik","Adding joint " << joint->name );
float lower, upper;
int hasLimits;
if ( joint->type != urdf::Joint::CONTINUOUS ) { // no limits in rotation
if(joint->safety) {
lower = std::max(joint->limits->lower, joint->safety->soft_lower_limit);
upper = std::min(joint->limits->upper, joint->safety->soft_upper_limit);
} else {
lower = joint->limits->lower;
upper = joint->limits->upper;
}
hasLimits = 1;
}
else {
hasLimits = 0;
}
if(hasLimits) {
l_bounds.push_back(lower);
u_bounds.push_back(upper);
}
else {
l_bounds.push_back(std::numeric_limits<float>::lowest());
u_bounds.push_back(std::numeric_limits<float>::max());
}
}
} else {
ROS_WARN_NAMED("trac_ik","no joint corresponding to %s",link->name.c_str());
}
link = link->getParent();
}
uint num_joints_ = l_bounds.size();
std::reverse(l_bounds.begin(),l_bounds.end());
std::reverse(u_bounds.begin(),u_bounds.end());
lb.resize(num_joints_);
ub.resize(num_joints_);
for(uint i=0; i <num_joints_; ++i) {
lb(i)=l_bounds[i];
ub(i)=u_bounds[i];
}
KDL::Tree tree;
if (!kdl_parser::treeFromUrdfModel(robot_model, tree))
ROS_FATAL("Failed to extract kdl tree from xml robot description");
if(!tree.getChain(base_link, tip_link, chain))
ROS_FATAL("Couldn't find chain %s to %s",base_link.c_str(),tip_link.c_str());
initialize();
}
TRAC_IK::TRAC_IK(const KDL::Chain& _chain, const KDL::JntArray& _q_min, const KDL::JntArray& _q_max, double _maxtime, double _eps, SolveType _type):
initialized(false),
chain(_chain),
lb(_q_min),
ub(_q_max),
eps(_eps),
maxtime(_maxtime),
solvetype(_type),
work(io_service)
{
initialize();
}
void TRAC_IK::initialize() {
std::cout << "checking lb data size equals nr of joints" << std::endl;
assert(chain.getNrOfJoints()==lb.data.size());
std::cout << "checking ub data size equals nr of joints" << std::endl;
assert(chain.getNrOfJoints()==ub.data.size());
jacsolver.reset(new KDL::ChainJntToJacSolver(chain));
nl_solver.reset(new NLOPT_IK::NLOPT_IK(chain,lb,ub,maxtime,eps,NLOPT_IK::SumSq));
iksolver.reset(new KDL::ChainIkSolverPos_TL(chain,lb,ub,maxtime,eps,true,true));
for (uint i=0; i<chain.segments.size(); i++) {
std::string type = chain.segments[i].getJoint().getTypeName();
if (type.find("Rot")!=std::string::npos) {
if (ub(types.size())>=std::numeric_limits<float>::max() &&
lb(types.size())<=std::numeric_limits<float>::lowest())
types.push_back(KDL::BasicJointType::Continuous);
else
types.push_back(KDL::BasicJointType::RotJoint);
}
else if (type.find("Trans")!=std::string::npos)
types.push_back(KDL::BasicJointType::TransJoint);
}
std::cout << "checking types size equals lb data size" << std::endl;
assert(types.size()==lb.data.size());
threads.create_thread(boost::bind(&boost::asio::io_service::run,
&io_service));
threads.create_thread(boost::bind(&boost::asio::io_service::run,
&io_service));
initialized = true;
std::cout << "initialized set to true" << std::endl;
}
bool TRAC_IK::unique_solution(const KDL::JntArray& sol) {
for (uint i=0; i< solutions.size(); i++)
if (myEqual(sol,solutions[i]))
return false;
return true;
}
bool TRAC_IK::runKDL(const KDL::JntArray &q_init, const KDL::Frame &p_in)
{
KDL::JntArray q_out;
double fulltime = maxtime;
KDL::JntArray seed = q_init;
boost::posix_time::time_duration timediff;
double time_left;
while (true) {
timediff=boost::posix_time::microsec_clock::local_time()-start_time;
time_left = fulltime - timediff.total_nanoseconds()/1000000000.0;
if (time_left <= 0)
break;
iksolver->setMaxtime(time_left);
int kdlRC = iksolver->CartToJnt(seed,p_in,q_out,bounds);
if (kdlRC >=0) {
switch (solvetype) {
case Manip1:
case Manip2:
normalize_limits(q_init, q_out);
break;
default:
normalize_seed(q_init, q_out);
break;
}
mtx_.lock();
if (unique_solution(q_out)) {
solutions.push_back(q_out);
uint curr_size=solutions.size();
errors.resize(curr_size);
mtx_.unlock();
double err, penalty;
switch (solvetype) {
case Manip1:
penalty = manipPenalty(q_out);
err = penalty*TRAC_IK::ManipValue1(q_out);
break;
case Manip2:
penalty = manipPenalty(q_out);
err = penalty*TRAC_IK::ManipValue2(q_out);
break;
default:
err = TRAC_IK::JointErr(q_init,q_out);
break;
}
mtx_.lock();
errors[curr_size-1] = std::make_pair(err,curr_size-1);
}
mtx_.unlock();
}
if (!solutions.empty() && solvetype == Speed)
break;
for (unsigned int j=0; j<seed.data.size(); j++)
if (types[j]==KDL::BasicJointType::Continuous)
seed(j)=fRand(q_init(j)-2*M_PI, q_init(j)+2*M_PI);
else
seed(j)=fRand(lb(j), ub(j));
}
nl_solver->abort();
iksolver->setMaxtime(fulltime);
return true;
}
bool TRAC_IK::runNLOPT(const KDL::JntArray &q_init, const KDL::Frame &p_in)
{
KDL::JntArray q_out;
double fulltime = maxtime;
KDL::JntArray seed = q_init;
boost::posix_time::time_duration timediff;
double time_left;
while (true) {
timediff=boost::posix_time::microsec_clock::local_time()-start_time;
time_left = fulltime - timediff.total_nanoseconds()/1000000000.0;
if (time_left <= 0)
break;
nl_solver->setMaxtime(time_left);
int nloptRC = nl_solver->CartToJnt(seed,p_in,q_out,bounds);
if (nloptRC >=0) {
switch (solvetype) {
case Manip1:
case Manip2:
normalize_limits(q_init, q_out);
break;
default:
normalize_seed(q_init, q_out);
break;
}
mtx_.lock();
if (unique_solution(q_out)) {
solutions.push_back(q_out);
uint curr_size=solutions.size();
errors.resize(curr_size);
mtx_.unlock();
double err, penalty;
switch (solvetype) {
case Manip1:
penalty = manipPenalty(q_out);
err = penalty*TRAC_IK::ManipValue1(q_out); /// important calculation again
break;
case Manip2:
penalty = manipPenalty(q_out);
err = penalty*TRAC_IK::ManipValue2(q_out);
break;
default:
err = TRAC_IK::JointErr(q_init,q_out);
break;
}
mtx_.lock();
errors[curr_size-1] = std::make_pair(err,curr_size-1);
}
mtx_.unlock();
}
if (!solutions.empty() && solvetype == Speed)
break;
for (unsigned int j=0; j<seed.data.size(); j++)
if (types[j]==KDL::BasicJointType::Continuous)
seed(j)=fRand(q_init(j)-2*M_PI, q_init(j)+2*M_PI);
else
seed(j)=fRand(lb(j), ub(j));
}
iksolver->abort();
nl_solver->setMaxtime(fulltime);
return true;
}
void TRAC_IK::normalize_seed(const KDL::JntArray& seed, KDL::JntArray& solution) {
// Make sure rotational joint values are within 1 revolution of seed; then
// ensure joint limits are met.
bool improved = false;
for (uint i=0; i<lb.data.size(); i++) {
if (types[i]==KDL::BasicJointType::TransJoint)
continue;
double target = seed(i);
double val = solution(i);
if (val > target+M_PI) {
//Find actual angle offset
double diffangle = fmod(val-target,2*M_PI); // fmod returns remainder
// Add that to upper bound and go back a full rotation
val = target + diffangle - 2*M_PI;
}
if (val < target-M_PI) {
//Find actual angle offset
double diffangle = fmod(target-val,2*M_PI);
// Add that to upper bound and go back a full rotation
val = target - diffangle + 2*M_PI;
}
if (types[i]==KDL::BasicJointType::Continuous) {
solution(i) = val;
continue;
}
if (val > ub(i)) {
//Find actual angle offset
double diffangle = fmod(val-ub(i),2*M_PI);
// Add that to upper bound and go back a full rotation
val = ub(i) + diffangle - 2*M_PI;
}
if (val < lb(i)) {
//Find actual angle offset
double diffangle = fmod(lb(i)-val,2*M_PI);
// Add that to upper bound and go back a full rotation
val = lb(i) - diffangle + 2*M_PI;
}
solution(i) = val;
}
}
void TRAC_IK::normalize_limits(const KDL::JntArray& seed, KDL::JntArray& solution) {
// Make sure rotational joint values are within 1 revolution of middle of
// limits; then ensure joint limits are met. WHAT DOES THIS MEAN???
bool improved = false;
for (uint i=0; i<lb.data.size(); i++) {
if (types[i] == KDL::BasicJointType::TransJoint)
continue;
double target = seed(i);
if (types[i] == KDL::BasicJointType::RotJoint)
target = (ub(i)+lb(i))/2.0;
double val = solution(i);
if (val > target+M_PI) {
//Find actual angle offset
double diffangle = fmod(val-target,2*M_PI);
// Add that to upper bound and go back a full rotation
val = target + diffangle - 2*M_PI;
}
if (val < target-M_PI) {
//Find actual angle offset
double diffangle = fmod(target-val,2*M_PI);
// Add that to upper bound and go back a full rotation
val = target - diffangle + 2*M_PI;
}
if (types[i]==KDL::BasicJointType::Continuous) {
solution(i) = val;
continue;
}
if (val > ub(i)) {
//Find actual angle offset
double diffangle = fmod(val-ub(i),2*M_PI);
// Add that to upper bound and go back a full rotation
val = ub(i) + diffangle - 2*M_PI;
}
if (val < lb(i)) {
//Find actual angle offset
double diffangle = fmod(lb(i)-val,2*M_PI);
// Add that to upper bound and go back a full rotation
val = lb(i) - diffangle + 2*M_PI;
}
solution(i) = val;
}
}
double TRAC_IK::manipPenalty(const KDL::JntArray& arr) {
double penalty = 1.0;
for (uint i=0; i< arr.data.size(); i++) {
if (types[i] == KDL::BasicJointType::Continuous)
continue;
double range = ub(i)-lb(i);
penalty *= ((arr(i)-lb(i))*(ub(i)-arr(i))/(range*range));
}
return (1.0 - exp(-1*penalty));
}
double TRAC_IK::ManipValue1(const KDL::JntArray& arr) {
KDL::Jacobian jac(arr.data.size());
jacsolver->JntToJac(arr,jac);
Eigen::JacobiSVD<Eigen::MatrixXd> svdsolver(jac.data);
Eigen::MatrixXd singular_values = svdsolver.singularValues();
double error = 1.0;
for(unsigned int i=0; i < singular_values.rows(); ++i)
error *= singular_values(i,0);
return error;
}
double TRAC_IK::ManipValue2(const KDL::JntArray& arr) {
KDL::Jacobian jac(arr.data.size());
jacsolver->JntToJac(arr,jac);
Eigen::JacobiSVD<Eigen::MatrixXd> svdsolver(jac.data);
Eigen::MatrixXd singular_values = svdsolver.singularValues();
return singular_values.minCoeff()/singular_values.maxCoeff();
}
int TRAC_IK::CartToJnt(const KDL::JntArray &q_init, const KDL::Frame &p_in, KDL::JntArray &q_out, const KDL::Twist& _bounds) {
if (!initialized) {
ROS_ERROR("TRAC-IK was not properly initialized with a valid chain or limits. IK cannot proceed");
return -1;
}
start_time = boost::posix_time::microsec_clock::local_time();
nl_solver->reset();
iksolver->reset();
solutions.clear();
errors.clear();
bounds=_bounds;
std::vector<boost::shared_future<bool> > pending_data;
typedef boost::packaged_task<bool> task_t;
boost::shared_ptr<task_t> task1 = boost::make_shared<task_t>(boost::bind(&TRAC_IK::runKDL, this, boost::cref(q_init), boost::cref(p_in)));
boost::shared_ptr<task_t> task2 = boost::make_shared<task_t>(boost::bind(&TRAC_IK::runNLOPT, this, boost::cref(q_init), boost::cref(p_in)));
boost::shared_future<bool> fut1(task1->get_future());
boost::shared_future<bool> fut2(task2->get_future());
/*
// this was for pre-c++11
pending_data.push_back(boost::move(fut1));
pending_data.push_back(boost::move(fut2));
*/
pending_data.push_back(fut1);
pending_data.push_back(fut2);
io_service.post(boost::bind(&task_t::operator(), task1));
io_service.post(boost::bind(&task_t::operator(), task2));
boost::wait_for_all(pending_data.begin(), pending_data.end());
if (solutions.empty()) {
q_out=q_init;
return -3;
}
switch (solvetype) {
case Manip1:
case Manip2:
std::sort(errors.rbegin(),errors.rend()); // rbegin/rend to sort by max
break;
default:
std::sort(errors.begin(),errors.end());
break;
}
q_out = solutions[errors[0].second];
return solutions.size();
}
TRAC_IK::~TRAC_IK(){
// Force all threads to return from io_service::run().
io_service.stop();
// Suppress all exceptions.
try
{
threads.join_all();
}
catch ( ... ) {}
}
}
| [
"brian.zhan@u.northwestern.edu"
] | brian.zhan@u.northwestern.edu |
e5c2c78d2cc2b6d9085638e1a58829f0c5494122 | 9d497b51303f46268866a303a93b24a0e764cdbf | /src/xzero/StringUtil.cc | 32ad13a50739cf50e1b4488a6835359114e61491 | [
"MIT"
] | permissive | klevler/x0 | 8abf236905f0ee046cdb509b7f196fecd69d3691 | 62896da39d4808853a8702c9ae7186e5a5ac2a27 | refs/heads/master | 2021-01-24T09:01:48.455199 | 2016-09-19T22:13:52 | 2016-09-19T22:13:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,543 | cc | // This file is part of the "x0" project, http://github.com/christianparpart/x0>
// (c) 2009-2016 Christian Parpart <trapni@gmail.com>
//
// Licensed under the MIT License (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of
// the License at: http://opensource.org/licenses/MIT
#include <string>
#include <xzero/RuntimeError.h>
#include <xzero/BufferUtil.h>
#include <xzero/StringUtil.h>
#include <xzero/UTF8.h>
namespace xzero {
void StringUtil::toStringVImpl(std::vector<std::string>* target) {}
template <>
std::string StringUtil::toString(std::string value) {
return value;
}
template <>
std::string StringUtil::toString(const char* value) {
return value;
}
template <>
std::string StringUtil::toString(char value) {
std::string result;
result.push_back(value);
return result;
}
template <>
std::string StringUtil::toString(char* value) {
return value;
}
template <>
std::string StringUtil::toString(int value) {
return std::to_string(value);
}
template <>
std::string StringUtil::toString(unsigned value) {
return std::to_string(value);
}
template <>
std::string StringUtil::toString(unsigned short value) {
return std::to_string(value);
}
template <>
std::string StringUtil::toString(long value) {
return std::to_string(value);
}
template <>
std::string StringUtil::toString(unsigned long value) {
return std::to_string(value);
}
template <>
std::string StringUtil::toString(long long value) {
return std::to_string(value);
}
template <>
std::string StringUtil::toString(unsigned long long value) {
return std::to_string(value);
}
template <>
std::string StringUtil::toString(unsigned char value) {
return std::to_string(value);
}
template <>
std::string StringUtil::toString(void* value) {
return "<ptr>";
}
template <>
std::string StringUtil::toString(const void* value) {
return "<ptr>";
}
template <>
std::string StringUtil::toString(float value) {
char buf[128];
*buf = 0;
auto len = snprintf(buf, sizeof(buf), "%f", value);
if (len < 0) {
RAISE(RuntimeError, "snprintf() failed");
}
while (len > 2 && buf[len - 1] == '0' && buf[len - 2] != '.') {
buf[len--] = 0;
}
return std::string(buf, len);
}
template <>
std::string StringUtil::toString(double value) {
char buf[128]; // FIXPAUL
*buf = 0;
auto len = snprintf(buf, sizeof(buf), "%f", value);
if (len < 0) {
RAISE(RuntimeError, "snprintf() failed");
}
while (len > 2 && buf[len - 1] == '0' && buf[len - 2] != '.') {
buf[len--] = 0;
}
return std::string(buf, len);
}
template <>
std::string StringUtil::toString(bool value) {
return value ? "true" : "false";
}
std::string StringUtil::trim(const std::string& value) {
std::size_t left = 0;
while (std::isspace(value[left])) ++left;
std::size_t right = value.size() - 1;
while (std::isspace(value[right])) --right;
return value.substr(left, 1 + right - left);
}
void StringUtil::stripTrailingSlashes(std::string* str) {
while (str->back() == '/') {
str->pop_back();
}
}
void StringUtil::replaceAll(
std::string* str,
const std::string& pattern,
const std::string& replacement) {
if (str->size() == 0) {
return;
}
size_t cur = 0;
while((cur = str->find(pattern, cur)) != std::string::npos) {
str->replace(cur, pattern.size(), replacement);
cur += replacement.size();
}
}
std::vector<std::string> StringUtil::splitByAny(
const std::string& str,
const std::string& pattern) {
std::vector<std::string> parts;
auto i = str.begin();
auto e = str.end();
do {
// consume delimiters
while (i != e && StringUtil::find(pattern, *i) != std::string::npos) {
i++;
}
// consume token
if (i != e) {
auto begin = i;
while (i != e && StringUtil::find(pattern, *i) == std::string::npos) {
i++;
}
parts.emplace_back(begin, i);
}
} while (i != e);
return parts;
}
std::vector<std::string> StringUtil::split(
const std::string& str,
const std::string& pattern) {
std::vector<std::string> parts;
size_t begin = 0;
for (;;) {
auto end = str.find(pattern, begin);
if (end == std::string::npos) {
parts.emplace_back(str.substr(begin, end));
break;
} else {
parts.emplace_back(str.substr(begin, end - begin));
begin = end + pattern.length();
}
}
return parts;
}
std::string StringUtil::join(const std::vector<std::string>& list, const std::string& join) {
std::string out;
for (size_t i = 0; i < list.size(); ++i) {
if (i > 0) {
out += join;
}
out += list[i];
}
return out;
}
std::string StringUtil::join(const std::set<std::string>& list, const std::string& join) {
std::string out;
size_t i = 0;
for (const auto& item : list) {
if (++i > 1) {
out += join;
}
out += item;
}
return out;
}
bool StringUtil::beginsWith(const std::string& str, const std::string& prefix) {
if (str.length() < prefix.length()) {
return false;
}
return str.compare(
0,
prefix.length(),
prefix) == 0;
}
bool StringUtil::beginsWithIgnoreCase(const std::string& str, const std::string& prefix) {
if (str.length() < prefix.length()) {
return false;
}
return strncasecmp(str.data(),
prefix.data(),
prefix.size()) == 0;
}
bool StringUtil::endsWith(const std::string& str, const std::string& suffix) {
if (str.length() < suffix.length()) {
return false;
}
return str.compare(
str.length() - suffix.length(),
suffix.length(),
suffix) == 0;
}
bool StringUtil::endsWithIgnoreCase(const std::string& str, const std::string& suffix) {
if (str.length() < suffix.length()) {
return false;
}
return strncasecmp(str.data() + str.length() - suffix.length(),
suffix.data(),
suffix.length()) == 0;
}
int StringUtil::compare(
const char* s1,
size_t s1_len,
const char* s2,
size_t s2_len) {
for (; s1_len > 0 && s2_len > 0; s1++, s2++, --s1_len, --s2_len) {
if (*s1 != *s2) {
return (*(uint8_t *) s1 < *(uint8_t *) s2) ? -1 : 1;
}
}
if (s1_len > 0) {
return 1;
}
if (s2_len > 0) {
return -1;
}
return 0;
}
bool StringUtil::isHexString(const std::string& str) {
for (const auto& c : str) {
if ((c >= '0' && c <= '9') ||
(c >= 'a' && c <= 'f') ||
(c >= 'A' && c <= 'F')) {
continue;
}
return false;
}
return true;
}
bool StringUtil::isAlphanumeric(const std::string& str) {
for (const auto& c : str) {
if (!isAlphanumeric(c)) {
return false;
}
}
return true;
}
bool StringUtil::isAlphanumeric(char chr) {
bool is_alphanum =
(chr >= '0' && chr <= '9') ||
(chr >= 'a' && chr <= 'z') ||
(chr >= 'A' && chr <= 'Z');
return is_alphanum;
}
bool StringUtil::isShellSafe(const std::string& str) {
for (const auto& c : str) {
if (!isShellSafe(c)) {
return false;
}
}
return true;
}
bool StringUtil::isShellSafe(char chr) {
bool is_safe =
(chr >= '0' && chr <= '9') ||
(chr >= 'a' && chr <= 'z') ||
(chr >= 'A' && chr <= 'Z') ||
(chr == '_') ||
(chr == '-') ||
(chr == '.');
return is_safe;
}
bool StringUtil::isDigitString(const std::string& str) {
return isDigitString(str.data(), str.data() + str.size());
}
bool StringUtil::isDigitString(const char* begin, const char* end) {
for (auto cur = begin; cur < end; ++cur) {
if (!isdigit(*cur)) {
return false;
}
}
return true;
}
bool StringUtil::isNumber(const std::string& str) {
return isNumber(str.data(), str.data() + str.size());
}
bool StringUtil::isNumber(const char* begin, const char* end) {
auto cur = begin;
if (cur < end && *cur == '-') {
++cur;
}
for (; cur < end; ++cur) {
if (!isdigit(*cur)) {
return false;
}
}
if (cur < end && (*cur == '.' || *cur == ',')) {
++cur;
}
for (; cur < end; ++cur) {
if (!isdigit(*cur)) {
return false;
}
}
return true;
}
void StringUtil::toLower(std::string* str) {
auto& str_ref = *str;
for (size_t i = 0; i < str_ref.length(); ++i) {
str_ref[i] = std::tolower(str_ref[i]);
}
}
std::string StringUtil::toLower(const std::string& str) {
std::string copy = str;
toLower(©);
return copy;
}
void StringUtil::toUpper(std::string* str) {
auto& str_ref = *str;
for (size_t i = 0; i < str_ref.length(); ++i) {
str_ref[i] = std::toupper(str_ref[i]);
}
}
std::string StringUtil::toUpper(const std::string& str) {
std::string copy = str;
toUpper(©);
return copy;
}
size_t StringUtil::find(const std::string& str, char chr) {
for (size_t i = 0; i < str.length(); ++i) {
if (str[i] == chr) {
return i;
}
}
return -1;
}
size_t StringUtil::findLast(const std::string& str, char chr) {
for (int i = str.length() - 1; i >= 0; --i) {
if (str[i] == chr) {
return i;
}
}
return -1;
}
bool StringUtil::includes(const std::string& str, const std::string& subject) {
return str.find(subject) != std::string::npos;
}
std::string StringUtil::hexPrint(
const void* data,
size_t size,
bool sep /* = true */,
bool reverse /* = fase */) {
// FIXME: that's bad, as it's recreating the already existing buffer - just to hexprint it?
Buffer buf((char*) data, size);
return BufferUtil::hexPrint(&buf, sep, reverse);
}
std::string StringUtil::formatv(
const char* fmt,
std::vector<std::string> values) {
std::string str = fmt;
for (size_t i = 0; i < values.size(); ++i) {
StringUtil::replaceAll(
&str,
"$" + std::to_string(i),
StringUtil::toString(values[i]));
}
return str;
}
std::wstring StringUtil::convertUTF8To16(const std::string& str) {
std::wstring out;
const char* cur = str.data();
const char* end = cur + str.length();
char32_t chr;
while ((chr = UTF8::nextCodepoint(&cur, end)) > 0) {
out += (wchar_t) chr;
}
return out;
}
std::string StringUtil::convertUTF16To8(const std::wstring& str) {
std::string out;
for (const auto& c : str) {
UTF8::encodeCodepoint(c, &out);
}
return out;
}
std::string StringUtil::stripShell(const std::string& str) {
std::string out;
for (const auto& c : str) {
if (isAlphanumeric(c) || c == '_' || c == '-' || c == '.') {
out += c;
}
}
return out;
}
} // namespace xzero
| [
"trapni@gmail.com"
] | trapni@gmail.com |
dc66ebb05796800bb17beeb9975d3def028c8d4c | 8502fc2c0fafea5faa0c12ae60b139401a31528d | /KeDeiTFT/3.5inch/int_number_add_reduce/int_number_add_reduce.ino | 7fea840be1e1449061d0a906653f367afd2a2777 | [] | no_license | osoyoo/driver | b5e8b32d2dd271729f1d2859b94ca184486edf26 | 37f1f9f4e48a37bcaa664bfa8389a768d160c0db | refs/heads/master | 2023-04-03T01:53:25.406631 | 2023-03-22T09:15:15 | 2023-03-22T09:15:15 | 89,325,918 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 2,229 | ino | #include <KeDei_TFT.h>
#include <KeDei_TP.h>
#include "KeDei_font.h"
#include "KeDei_button.h"
#define backcolor 0xf800
//LCD class object is TFT
TFTLCD TFT;
//Font class object is font
Font font;
//Touchuscreem TP class object is tp
TP tp;
//Two Button class object is Button1,Button2
Button Button1,Button2;
int value =1688;
void setup() {
//TFT initialization
TFT.begin();
//LCD Clear the screen, backcolor
TFT.clear(backcolor);
font.begin();
//Set the text area for the upper left corner (30, 10), the lower right corner (320,200), the color red, if the color is NULL or R0 G0 B0(black), is also not set text color
font.set_txt(5,5,320,200,TFT.RGB_TO_565(255,0,0));
//Set the text font color
font.set_fontcolor(TFT.RGB_TO_565(0,0,255));
//Displays a string
font.lcd_string("KeDeiTFT");
font.lcd_string("show int number add and reduce");
//Draw the first round button1
Button1.drawButton(100,100,1,"-");
//Draw the second round button
Button2.drawButton(100,250,0,"+");
font.set_txt(100,180,140,197,TFT.RGB_TO_565(255,0,0));
font.lcd_int(value);
}
void loop() {
//check Touch current state detection
tp.pen_down();
//The touch screen is touch
if(tp.flag&&tp.y_val&&tp.x_val)
//Check whether pressing the first button
if(Button1.istouch(tp.x,tp.y))
{
//Touch screen alway be pressed
for(;tp.flag;)
{
//value add by 9
value -= 9;
//clear the text area
font.set_txt(100,180,140,197,TFT.RGB_TO_565(255,0,0));
//Displays new value
font.lcd_int(value);
// delay(500);
tp.pen_down();
}
//Button to restore the original appearance
Button1.penup();
}
else
if(Button2.istouch(tp.x,tp.y))
{
for(;tp.flag;)
{
//value reduce by 9
value += 9;
font.set_txt(100,180,140,197,TFT.RGB_TO_565(255,0,0));
font.lcd_int(value);
// delay(500);
tp.pen_down();
}
Button2.penup();
}
}
| [
"yujian_ca@hotmail.com"
] | yujian_ca@hotmail.com |
518c0766b6d87591a3d95d32a19c494ee85065ce | 94aa2f1a183f4800777e99f7b03e67a5e732e4d0 | /src/lib/tls/tls_callbacks.cpp | f25f392b330d15eb58c5f0be0ce233a354b13e3c | [
"BSD-2-Clause"
] | permissive | Bulat-Ziganshin/botan | e7e71bf4b2cbff9560cc2eaed39edd46a5e1f0b2 | d90c21b69cf0457782e5862c7b87d6e72dea1c40 | refs/heads/master | 2021-01-12T03:44:45.926033 | 2017-01-07T02:28:39 | 2017-01-07T02:28:39 | 78,261,867 | 1 | 0 | null | 2017-01-07T06:00:17 | 2017-01-07T06:00:17 | null | UTF-8 | C++ | false | false | 1,672 | cpp | /*
* TLS Callbacks
* (C) 2016 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/tls_callbacks.h>
#include <botan/tls_policy.h>
#include <botan/x509path.h>
#include <botan/ocsp.h>
#include <botan/certstor.h>
namespace Botan {
TLS::Callbacks::~Callbacks() {}
void TLS::Callbacks::tls_inspect_handshake_msg(const Handshake_Message&)
{
// default is no op
}
std::string TLS::Callbacks::tls_server_choose_app_protocol(const std::vector<std::string>&)
{
return "";
}
void TLS::Callbacks::tls_verify_cert_chain(
const std::vector<X509_Certificate>& cert_chain,
const std::vector<std::shared_ptr<const OCSP::Response>>& ocsp_responses,
const std::vector<Certificate_Store*>& trusted_roots,
Usage_Type usage,
const std::string& hostname,
const TLS::Policy& policy)
{
if(cert_chain.empty())
throw Invalid_Argument("Certificate chain was empty");
Path_Validation_Restrictions restrictions(policy.require_cert_revocation_info(),
policy.minimum_signature_strength());
Path_Validation_Result result =
x509_path_validate(cert_chain,
restrictions,
trusted_roots,
(usage == Usage_Type::TLS_SERVER_AUTH ? hostname : ""),
usage,
std::chrono::system_clock::now(),
tls_verify_cert_chain_ocsp_timeout(),
ocsp_responses);
if(!result.successful_validation())
throw Exception("Certificate validation failure: " + result.result_string());
}
}
| [
"jack@randombit.net"
] | jack@randombit.net |
008dd714ddf450daab84e9b42dbe0374cf36bd6b | 10d41367e7ec3f5d4074ceabae024b3ded3b4a13 | /c++/src/connect/services/timeline.hpp | 8c5420a329f1919e715b8ea2d7ebe97af9f0f994 | [] | no_license | avtomaton/blast-ncbi | fb88c01df0a0f721dc942b7e00bb2cab22d3cac6 | a76cdd948affcc2c5c1c1ae6fc1481098e650d2d | refs/heads/master | 2021-01-01T06:27:01.871908 | 2015-03-06T09:39:43 | 2015-03-06T09:39:43 | 31,762,500 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,299 | hpp | #ifndef CONNECT_SERVICES__TIMELINE_HPP
#define CONNECT_SERVICES__TIMELINE_HPP
/* $Id: timeline.hpp 447459 2014-09-25 20:43:06Z kazimird $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Authors: Dmitry Kazimirov
*
* File Description:
* Grid Worker Node Timeline - declarations.
*
*/
#include <corelib/ncbitime.hpp>
BEGIN_NCBI_SCOPE
class CWorkerNodeTimeline_Base;
class NCBI_XCONNECT_EXPORT CWorkerNodeTimelineEntry : public CObject
{
public:
friend class CWorkerNodeTimeline_Base;
CWorkerNodeTimelineEntry() : m_Timeline(NULL), m_Deadline(0, 0) {}
bool IsInTimeline() const {return m_Timeline != NULL;}
bool IsInTimeline(CWorkerNodeTimeline_Base* timeline) const
{
return m_Timeline == timeline;
}
void MoveTo(CWorkerNodeTimeline_Base* timeline);
const CDeadline& GetTimeout() const {return m_Deadline;}
void ResetTimeout(unsigned seconds)
{
m_Deadline = CDeadline(seconds, 0);
}
bool TimeHasCome() const
{
return m_Deadline.GetRemainingTime().IsZero();
}
private:
CWorkerNodeTimeline_Base* m_Timeline;
CWorkerNodeTimelineEntry* m_Prev;
CWorkerNodeTimelineEntry* m_Next;
CDeadline m_Deadline;
};
class NCBI_XCONNECT_EXPORT CWorkerNodeTimeline_Base
{
protected:
friend class CWorkerNodeTimelineEntry;
CWorkerNodeTimeline_Base() : m_Head(NULL), m_Tail(NULL)
{
}
public:
bool IsEmpty() const {return m_Head == NULL;}
void Push(CWorkerNodeTimelineEntry* new_entry)
{
_ASSERT(new_entry->m_Timeline == NULL);
AttachTail(new_entry);
new_entry->AddReference();
}
protected:
void AttachTail(CWorkerNodeTimelineEntry* new_tail)
{
new_tail->m_Timeline = this;
new_tail->m_Next = NULL;
if ((new_tail->m_Prev = m_Tail) != NULL)
m_Tail->m_Next = new_tail;
else
m_Head = new_tail;
m_Tail = new_tail;
}
CWorkerNodeTimelineEntry* DetachHead()
{
_ASSERT(m_Head != NULL);
CWorkerNodeTimelineEntry* detached_head = m_Head;
if ((m_Head = detached_head->m_Next) != NULL)
m_Head->m_Prev = NULL;
else
m_Tail = NULL;
detached_head->m_Timeline = NULL;
return detached_head;
}
public:
void MoveHeadTo(CWorkerNodeTimeline_Base* timeline)
{
timeline->AttachTail(DetachHead());
}
void Clear()
{
CWorkerNodeTimelineEntry* entry = m_Head;
if (entry != NULL) {
m_Tail = m_Head = NULL;
do {
entry->m_Timeline = NULL;
CWorkerNodeTimelineEntry* next_entry = entry->m_Next;
entry->RemoveReference();
entry = next_entry;
} while (entry != NULL);
}
}
protected:
~CWorkerNodeTimeline_Base()
{
Clear();
}
CWorkerNodeTimelineEntry* m_Head;
CWorkerNodeTimelineEntry* m_Tail;
};
inline void CWorkerNodeTimelineEntry::MoveTo(CWorkerNodeTimeline_Base* timeline)
{
if (m_Timeline != timeline) {
if (m_Timeline == NULL)
AddReference();
else {
if (m_Prev == NULL)
if ((m_Timeline->m_Head = m_Next) != NULL)
m_Next->m_Prev = NULL;
else
m_Timeline->m_Tail = NULL;
else if (m_Next == NULL)
(m_Timeline->m_Tail = m_Prev)->m_Next = NULL;
else
(m_Prev->m_Next = m_Next)->m_Prev = m_Prev;
}
timeline->AttachTail(this);
}
}
template <typename TTimelineEntry, typename TRefType>
class CWorkerNodeTimeline : public CWorkerNodeTimeline_Base
{
public:
TRefType GetHead() const
{
return TRefType(static_cast<TTimelineEntry*>(m_Head));
}
void Shift(TRefType& ref)
{
CWorkerNodeTimelineEntry* head = DetachHead();
ref = static_cast<TTimelineEntry*>(head);
head->RemoveReference();
}
};
END_NCBI_SCOPE
#endif // !defined(CONNECT_SERVICES__TIMELINE_HPP)
| [
"avtomaton@gmail.com"
] | avtomaton@gmail.com |
4326b3afa681bd5b3576ae98d580dd29ea35d0e4 | 24893618660f768d9c411c0723ccbe822a628913 | /Mammoth/TSE/MissionProperties.cpp | 258efd3cdca871cd778da997d6667717764603dc | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | kronosaur/TranscendenceDev | da4940b77dd1e2846f8d1bfa83e349b1277e506d | a53798ed0f23cbbafa69b85dc1b9ec26b1d5bdda | refs/heads/master | 2023-07-09T11:17:37.539313 | 2023-07-01T05:05:49 | 2023-07-01T05:05:49 | 164,558,909 | 31 | 14 | NOASSERTION | 2022-05-12T21:06:30 | 2019-01-08T04:15:34 | C++ | UTF-8 | C++ | false | false | 6,342 | cpp | // MissionProperties.cpp
//
// CMission class
// Copyright (c) 2019 Kronosaur Productions, LLC. All Rights Reserved.
#include "PreComp.h"
#define PROPERTY_ACCEPTED_ON CONSTLIT("acceptedOn")
#define PROPERTY_COMPLETED_ON CONSTLIT("completedOn")
#define PROPERTY_DEBRIEFER_ID CONSTLIT("debrieferID")
#define PROPERTY_IN_PROGRESS CONSTLIT("inProgress")
#define PROPERTY_IS_ACTIVE CONSTLIT("isActive")
#define PROPERTY_IS_COMPLETED CONSTLIT("isCompleted")
#define PROPERTY_IS_DEBRIEFED CONSTLIT("isDebriefed")
#define PROPERTY_IS_DECLINED CONSTLIT("isDeclined")
#define PROPERTY_IS_FAILURE CONSTLIT("isFailure")
#define PROPERTY_IS_INTRO_SHOWN CONSTLIT("isIntroShown")
#define PROPERTY_IS_OPEN CONSTLIT("isOpen")
#define PROPERTY_IS_RECORDED CONSTLIT("isRecorded")
#define PROPERTY_IS_SUCCESS CONSTLIT("isSuccess")
#define PROPERTY_IS_UNAVAILABLE CONSTLIT("isUnavailable")
#define PROPERTY_NAME CONSTLIT("name")
#define PROPERTY_NODE_ID CONSTLIT("nodeID")
#define PROPERTY_OWNER_ID CONSTLIT("ownerID")
#define PROPERTY_SUMMARY CONSTLIT("summary")
#define PROPERTY_UNID CONSTLIT("unid")
#define REASON_DEBRIEFED CONSTLIT("debriefed")
TPropertyHandler<CMission> CMission::m_PropertyTable = std::array<TPropertyHandler<CMission>::SPropertyDef, 20> {{
{
"acceptedOn", "ticks",
[](const CMission &Obj, const CString &sProperty)
{
return (Obj.m_fAcceptedByPlayer ? ICCItemPtr(Obj.m_dwAcceptedOn) : ICCItemPtr(ICCItem::Nil));
},
NULL,
},
{
"arcName", "Name of arc",
[](const CMission &Obj, const CString &sProperty) { return ICCItemPtr(Obj.m_sArcTitle); },
NULL,
},
{
"completedOn", "ticks",
[](const CMission &Obj, const CString &sProperty)
{
return (Obj.IsCompleted() ? ICCItemPtr(Obj.m_dwCompletedOn) : ICCItemPtr(ICCItem::Nil));
},
NULL,
},
{
"debrieferID", "objID",
[](const CMission &Obj, const CString &sProperty)
{
if (Obj.m_pDebriefer.GetID() != OBJID_NULL)
return ICCItemPtr(Obj.m_pDebriefer.GetID());
else if (Obj.m_pOwner.GetID() != OBJID_NULL)
return ICCItemPtr(Obj.m_pOwner.GetID());
else
return ICCItemPtr(ICCItem::Nil);
},
NULL,
},
{
"inProgress", "True|Nil",
[](const CMission &Obj, const CString &sProperty) { return ICCItemPtr(Obj.IsActive() && !Obj.IsCompleted()); },
NULL,
},
{
"isActive", "True|Nil",
[](const CMission &Obj, const CString &sProperty) { return ICCItemPtr(Obj.IsActive()); },
NULL,
},
{
"isCompleted", "True|Nil",
[](const CMission &Obj, const CString &sProperty) { return ICCItemPtr(Obj.IsCompleted()); },
NULL,
},
{
"isDebriefed", "True|Nil",
[](const CMission &Obj, const CString &sProperty) { return ICCItemPtr(Obj.m_fDebriefed ? true : false); },
NULL,
},
{
"isDeclined", "True|Nil",
[](const CMission &Obj, const CString &sProperty) { return ICCItemPtr(Obj.m_fDeclined ? true : false); },
NULL,
},
{
"isFailure", "True|Nil",
[](const CMission &Obj, const CString &sProperty) { return ICCItemPtr(Obj.IsFailure()); },
NULL,
},
{
"isIntroShown", "True|Nil",
[](const CMission &Obj, const CString &sProperty) { return ICCItemPtr(Obj.m_fIntroShown ? true : false); },
NULL,
},
{
"isOpen", "True|Nil",
[](const CMission &Obj, const CString &sProperty) { return ICCItemPtr(Obj.m_iStatus == Status::open); },
NULL,
},
{
"isRecorded", "True|Nil",
[](const CMission &Obj, const CString &sProperty) { return ICCItemPtr(Obj.IsRecorded()); },
NULL,
},
{
"isSuccess", "True|Nil",
[](const CMission &Obj, const CString &sProperty) { return ICCItemPtr(Obj.IsSuccess()); },
NULL,
},
{
"isUnavailable", "True|Nil",
[](const CMission &Obj, const CString &sProperty) { return ICCItemPtr(Obj.IsUnavailable()); },
NULL,
},
{
"missionNumber", "Ordinal of mission of type",
[](const CMission &Obj, const CString &sProperty) { return ICCItemPtr(Obj.m_iMissionNumber); },
NULL,
},
{
"name", "Name of mission",
[](const CMission &Obj, const CString &sProperty) { return ICCItemPtr(Obj.m_sTitle); },
NULL,
},
{
"nodeID", "nodeID",
[](const CMission &Obj, const CString &sProperty)
{
return (Obj.m_sNodeID.IsBlank() ? ICCItemPtr(ICCItem::Nil) : ICCItemPtr(Obj.m_sNodeID));
},
NULL,
},
{
"ownerID", "objID",
[](const CMission &Obj, const CString &sProperty)
{
if (Obj.m_pOwner.GetID() == OBJID_NULL)
return ICCItemPtr(ICCItem::Nil);
else
return ICCItemPtr(Obj.m_pOwner.GetID());
},
NULL,
},
{
"summary", "Summary of mission",
[](const CMission &Obj, const CString &sProperty) { return ICCItemPtr(Obj.m_sInstructions); },
NULL,
}
}};
ICCItemPtr CMission::OnFindProperty (CCodeChainCtx &CCX, const CString &sProperty) const
// OnFindProperty
//
// Returns a property, if found.
{
// First look for a property in our table.
ICCItemPtr pValue;
if (m_PropertyTable.FindProperty(*this, sProperty, pValue))
return pValue;
// Otherwise, not found
else
return ICCItemPtr();
}
bool CMission::SetProperty (const CString &sName, ICCItem *pValue, CString *retsError)
// SetProperty
//
// Sets an object property
{
if (strEquals(sName, PROPERTY_IS_DEBRIEFED))
{
if (m_iStatus == Status::playerSuccess || m_iStatus == Status::playerFailure)
{
if (!pValue->IsNil())
{
if (!m_fDebriefed)
{
m_fDebriefed = true;
FireOnSetPlayerTarget(REASON_DEBRIEFED);
CloseMission();
}
}
else
m_fDebriefed = false;
}
}
else if (strEquals(sName, PROPERTY_DEBRIEFER_ID))
{
if (pValue->IsNil())
m_pDebriefer.SetID(OBJID_NULL);
else
m_pDebriefer.SetID(pValue->GetIntegerValue());
}
else if (strEquals(sName, PROPERTY_IS_DECLINED))
{
if (m_iStatus == Status::open)
m_fDeclined = !pValue->IsNil();
}
else if (strEquals(sName, PROPERTY_IS_INTRO_SHOWN))
{
if (m_iStatus == Status::open)
m_fIntroShown = !pValue->IsNil();
}
else if (strEquals(sName, PROPERTY_NAME))
{
if (IsActive())
m_sTitle = pValue->GetStringValue();
}
else if (strEquals(sName, PROPERTY_SUMMARY))
{
if (IsActive())
m_sInstructions = pValue->GetStringValue();
}
else
return CSpaceObject::SetProperty(sName, pValue, retsError);
return true;
}
| [
"public@neurohack.com"
] | public@neurohack.com |
6a5d21ad4d7c058ce18f8d911ecd20a75b2851e7 | 2419faef76f0364e2b2248d14350ca4ed2e1f99e | /d03/ex04/ScavTrap.cpp | 9894dae5e86f6dd3241172692ee00830f4f6908b | [] | no_license | bgoncharov/42_CPP_Piscine | e2cd1f45f2d698fc2ff7d22e03c56030c5272a31 | f41afd948c921d80f9993c154f9d0ee9806fe695 | refs/heads/master | 2020-08-20T19:35:52.877690 | 2019-11-24T01:55:01 | 2019-11-24T01:55:01 | 216,058,896 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,617 | cpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ScavTrap.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bogoncha <bogoncha@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/10/24 13:06:51 by bogoncha #+# #+# */
/* Updated: 2019/10/25 15:16:06 by bogoncha ### ########.fr */
/* */
/* ************************************************************************** */
#include "ScavTrap.hpp"
/* Constructors & Destructors */
ScavTrap::ScavTrap(void) {
return ;
}
ScavTrap::ScavTrap(std::string name) : ClapTrap(100, 100, 50, 50, 1,
name, 20, 15, 3, 45, 14, 6, 23, 3, "SCRAV") {
std::cout << "ScavTrap constructor called" << std::endl;
return ;
};
ScavTrap::ScavTrap(ScavTrap const &src) {
std::cout << "ScavTrap copy constructor called" << std::endl;
*this = src;
return ;
}
ScavTrap::~ScavTrap(void) {
std::cout << "ScavTrap destructor called" << std::endl;
return ;
}
/* Operators overload */
ScavTrap &ScavTrap::operator=(ScavTrap const &rhs) {
this->_hitPoints = rhs.getHitPoints();
this->_maxHitPoints = rhs.getMaxHitPoints();
this->_energyPoints = rhs.getEnergyPoints();
this->_maxEnergyPoints = rhs.getMaxEnergyPoints();
this->_level = rhs.getLevel();
this->_name = rhs.getName();
this->_meleeAttackDamage = rhs.getMeleeAttackDamage();
this->_rangedAttackDamage = rhs.getArmorDamageReduction();
this->_coltAttackDamage = rhs.getColtAttackDamage();
this->_rockAttackDamage = rhs.getRockAttackDamage();
this->_gunAttackDamage = rhs.getGunAttackDamage();
this->_boboAttackDamage = rhs.getBoboAttackDamage();
this->_ticklesAttackDamage = rhs.getTicklesAttackDamage();
this->_armorDamageReduction = rhs.getArmorDamageReduction();
this->_type = rhs.getType();
return *this;
}
//Challenges
void ScavTrap::challengeNewComer(void) const {
srand(clock());
std::cout << this->_challenges[rand() % this->_nChallenges] << std::endl;
}
std::string const ScavTrap::_challenges[] = {
"Die or die!", "What's up bro?", "Yo man!",
"I'm you father!", "Come with me!", "Today!",
"Never do it again!", "Asta la vista!"
};
int const ScavTrap::_nChallenges = 8;
| [
"bora4bora@gmail.com"
] | bora4bora@gmail.com |
e5f39c5a69758955536be82b436a16008a7ecddb | 960f1f5141539d528401a27f430300cfb8519a03 | /src/modules/planning/state_lattice/include/state_lattice/primitive_generator.hpp | 0602787bb3946cbb0d53de9c7f89a77f12383071 | [
"MIT"
] | permissive | LiYang412/robotnav | 493da43575a4063bd4848560db665570f91b2d9e | ec66655ab90164a3261f291bf91ae844364d35af | refs/heads/master | 2023-03-03T22:52:08.497195 | 2020-10-18T15:27:16 | 2020-10-18T15:27:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,570 | hpp | /*
* primitive_generator.hpp
*
* Created on: Oct 21, 2018 23:46
* Description:
*
* Copyright (c) 2018 Ruixiang Du (rdu)
*/
#ifndef PRIMITIVE_GENERATOR_HPP
#define PRIMITIVE_GENERATOR_HPP
#include <cstdint>
#include "state_lattice/motion_primitive.hpp"
#include "state_lattice/details/point_kinematics.hpp"
#include "state_lattice/details/lookup_table.hpp"
namespace ivnav
{
class PrimitiveGenerator
{
public:
PrimitiveGenerator();
explicit PrimitiveGenerator(std::string lookup_file);
// Optimize trajectory
void LoadLookupTable(std::string lookup_file);
bool Calculate(MotionState state_s, MotionState state_f, MotionPrimitive &mp);
// Warning: optimize trajectory WITHOUT using lookup table
MotionPrimitive Calculate(MotionState state_s, MotionState state_f, PointKinematics::Param init_p);
bool Calculate(MotionState state_s, MotionState state_f, PointKinematics::Param init_p, MotionPrimitive &mp);
private:
const int32_t max_iter_ = 100;
const double cost_th_ = 0.05;
std::vector<double> scalers_ = {1.0, 2.0, 0.5};
StatePMatrix Je_;
PointKinematics model_;
bool lookup_available_ = false;
LookupTable lookup_table_;
StatePMatrix CalcDeltaX(StatePMatrix target, StatePMatrix xi);
JacobianMatrix CalcJacobian(MotionState init, MotionState target, PointKinematics::Param p);
double SelectParamScaler(StatePMatrix start, StatePMatrix target, PointKinematics::Param p, ParamPMatrix p_i, ParamPMatrix delta_pi);
};
} // namespace ivnav
#endif /* PRIMITIVE_GENERATOR_HPP */
| [
"ruixiang.du@gmail.com"
] | ruixiang.du@gmail.com |
013121c05215bf39788ce3e86d91325f9771e22c | d266eb7b6ba92c7658b563975c14b64d4e5d50cc | /libs/guibase/arrowsettingcontainer.h | 3c63ac617e56346b1741340f3f346d31698ff0e8 | [] | no_license | scharlton2/prepost-gui | 5c0a7d45c1f7156513d63e915d19f71233f15f88 | 007fdfcaf4d3e42b606e8edad8285b6de2bfd440 | refs/heads/master | 2023-08-31T01:54:11.798622 | 2022-12-26T01:51:06 | 2022-12-26T01:51:06 | 68,759,445 | 0 | 0 | null | 2020-05-14T22:28:47 | 2016-09-20T22:47:28 | C++ | UTF-8 | C++ | false | false | 1,905 | h | #ifndef ARROWSETTINGCONTAINER_H
#define ARROWSETTINGCONTAINER_H
#include "guibase_global.h"
#include "scalarbarsetting.h"
#include <misc/colorcontainer.h>
#include <misc/compositecontainer.h>
#include <misc/doublecontainer.h>
#include <misc/enumcontainert.h>
#include <misc/intcontainer.h>
#include <misc/stringcontainer.h>
#include <QColor>
class vtkPointSet;
class vtkPolyData;
/// Container for arrow settings
class GUIBASEDLL_EXPORT ArrowSettingContainer : public CompositeContainer
{
public:
const static int DEFAULT_SAMPLING_RATE;
const static int DEFAULT_SAMPLING_NUMBER;
const static double DEFAULT_LEGEND_STANDARD;
const static int DEFAULT_LEGEND_LENGTH;
const static double DEFAULT_LEGEND_MINIMUM;
static const int DEFAULT_ARROWSIZE;
static const int DEFAULT_LINEWIDTH;
enum class SamplingMode {
All = 1,
Rate = 2,
Number = 3,
};
enum class ColorMode {
Custom,
ByScalar
};
enum class LengthMode {
Auto,
Custom
};
ArrowSettingContainer();
ArrowSettingContainer(const ArrowSettingContainer& c);
virtual ~ArrowSettingContainer();
ArrowSettingContainer& operator=(const ArrowSettingContainer& c);
XmlAttributeContainer& operator=(const XmlAttributeContainer& c) override;
double scaleFactor(double stdDistance) const;
vtkPolyData* buildFilteredData(vtkPointSet* data) const;
void updateStandardValueIfNeeded(vtkPointSet* data);
StringContainer target;
EnumContainerT<SamplingMode> samplingMode;
IntContainer samplingRate;
IntContainer samplingNumber;
EnumContainerT<ColorMode> colorMode;
ColorContainer customColor;
StringContainer colorTarget;
EnumContainerT<LengthMode> lengthMode;
DoubleContainer standardValue;
DoubleContainer legendLength;
DoubleContainer minimumValue;
IntContainer arrowSize;
IntContainer lineWidth;
ScalarBarSetting scalarBarSetting;
DoubleContainer oldCameraScale;
};
#endif // ARROWSETTINGCONTAINER_H
| [
"kskinoue@gmail.com"
] | kskinoue@gmail.com |
0d0b9b24035022aef3568432b8ec13603cec82bf | 124e7b896952812492265cae6a9ffabd58b5e315 | /Lib/Arduino/libraries/MiiGenericModem/MiiGenericModem.cpp | b771f0a5ff8e7f366c498556187389e1dfab6a38 | [] | no_license | sjhoeksma/Mii | f42b3cab329a7226eb2126fc55e0fdeae8f20419 | 7014e9417c16afb0f8f0ca415cedd844b3fd8ebf | refs/heads/master | 2021-01-17T15:58:53.510719 | 2017-02-24T18:56:51 | 2017-02-24T18:56:51 | 82,954,770 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,053 | cpp | #include <MiiGenericModem.h>
#if defined MPIDE
#include <peripheral/int.h>
#define memcpy_P memcpy
#define ATOMIC_BLOCK_START unsigned int __status = INTDisableInterrupts(); {
#define ATOMIC_BLOCK_END } INTRestoreInterrupts(__status);
#elif defined ARDUINO
#include <util/atomic.h>
#define ATOMIC_BLOCK_START ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
#define ATOMIC_BLOCK_END }
#endif
MiiGenericModem::MiiGenericModem(uint8_t selectPin, uint8_t intPin, uint8_t sdnPin)
:
_mode(MII_RF_MODE_IDLE),
_selectPin(selectPin),
_intPin(intPin),
_sdnPin(sdnPin),
_timeSync(true),
_thisAddress(MII_BROADCAST_ADDRESS),
_txHeaderTo(MII_BROADCAST_ADDRESS),
_txHeaderFrom(MII_BROADCAST_ADDRESS),
_txHeaderId(0),
_txHeaderFlags(0),
_rxBufValid(0),
_drift(MII_RF_DEFAULT_DRIFT),
_airTime(MII_RF_MIN_MSG_INTERVAL),
_timeout(MII_RF_DEF_TIMEOUT),
_retryCount(MII_RF_DEFAULT_RETRY){
}
//Power own the device
void MiiGenericModem::power(bool state){
if (_sdnPin!=MII_NO_PIN) {
//First turn off the modem
pinMode(_sdnPin, OUTPUT);
digitalWrite(_sdnPin, HIGH);
delay(25);
//Now Enable it again
if (state) digitalWrite(_sdnPin, LOW);
}
delay(50);
}
bool MiiGenericModem::init(){
//Default init procedure
_ready=false;
power(true);
SPI.setDataMode(SPI_MODE0);
SPI.setBitOrder(MSBFIRST);
#if F_CPU <= 8000000
SPI.setClockDivider(SPI_CLOCK_DIV8);
#else
SPI.setClockDivider(SPI_CLOCK_DIV16);
#endif
SPI.begin();
#if SPI_ISOLATE
_SPCR = SPCR;
_SPSR = SPSR;
#endif
// Initialise the slave select pin
pinMode(_selectPin, OUTPUT);
digitalWrite(_selectPin, HIGH);
delay(100); //Give some time
// Add by Adrien van den Bossche <vandenbo@univ-tlse2.fr> for Teensy
// ARM M4 requires the below. else pin interrupt doesn't work properly.
// On all other platforms, its innocuous, belt and braces
pinMode(_intPin, INPUT);
return true;
}
bool MiiGenericModem::recv(bool allowCollision,uint8_t* buf, uint8_t* len){
bool ret = false;
#if MII_MAX_COLLISIONS
if (allowCollision && _collisionCount) ret=popCollision(buf,len);
#endif
if (!ret) { //We had no collision to process, see if there is other data
ret = internalRecv(buf,len);
}
if (ret) {
if (_rxHeaderFrom!=MII_BROADCAST_ADDRESS && _rxHeaderTo==_thisAddress &&
(_rxHeaderFlags & MII_RF_FLAGS_ACK) && _rxTime!=_ackTime) {
_ackTime=_rxTime;
cbi(_rxHeaderFlags,MII_RF_FLAGS_ACK); //Clear Ack Flag
setHeaderId(MII_C_ACK);
setHeaderFlags(0);
setHeaderTo(_rxHeaderFrom);
send((uint8_t*)&_rxHeaderId, sizeof(_rxHeaderId));
waitPacketSent();
}
}
return ret;
}
// Blocks until a valid message is received or timeout expires
// Return true if there is a message available
// Works correctly even on millis() rollover
bool MiiGenericModem::waitAvailable(uint16_t timeout){
unsigned long starttime = millis();
while (timeout==0 || (millis() - starttime) < timeout) {
if (available(false))
return true;
YIELD;
}
return false;
}
bool MiiGenericModem::waitPacketSent(uint16_t timeout){
unsigned long starttime = millis();
while (timeout==0 || (millis() - starttime) < timeout) {
if (_mode != MII_RF_MODE_TX) // Any previous transmit finished?
return true;
YIELD; // Wait for any previous transmit to finish
}
return false;
}
void MiiGenericModem::setPromiscuous(bool promiscuous){
_promiscuous = promiscuous;
}
void MiiGenericModem::setAddress(uint8_t address){
_thisAddress=address;
setHeaderFrom(address);
#if MII_MAX_ADDRESS
setPromiscuous(true); //We will filter the address ourself in available
#endif
if (!_timeInterval)
_timeInterval=_timeSync ? MII_TIME_INTERVAL_CLIENT : MII_TIME_INTERVAL_NOTIMESYNC;
}
void MiiGenericModem::setMaster(uint8_t address){
_masterAddress=address;
if (address==_thisAddress) {
_timeSync=true;
_timeInterval= MII_TIME_INTERVAL_MASTER;
}
}
void MiiGenericModem::setHeaderTo(uint8_t to){
_txHeaderTo = to;
}
void MiiGenericModem::setHeaderFrom(uint8_t from){
_txHeaderFrom = from;
}
void MiiGenericModem::setHeaderId(uint8_t id){
_txHeaderId = id;
}
void MiiGenericModem::setHeaderFlags(uint8_t set, uint8_t clear){
_txHeaderFlags &= ~clear;
_txHeaderFlags |= set;
}
uint8_t MiiGenericModem::headerTo(){
return _rxHeaderTo;
}
uint8_t MiiGenericModem::headerFrom(){
return _rxHeaderFrom;
}
uint8_t MiiGenericModem::headerId(){
return _rxHeaderId;
}
uint8_t MiiGenericModem::headerFlags(){
return _rxHeaderFlags;
}
int8_t MiiGenericModem::lastRssi(){
return _lastRssi;
}
uint8_t MiiGenericModem::mode(){
return _mode;
}
uint32_t MiiGenericModem::rxTime(){
return _rxTime;
}
uint32_t MiiGenericModem::txTime(){
return _txTime;
}
void MiiGenericModem::setTimeSync(bool state){
_timeSync=state;
}
void MiiGenericModem::setRetries(uint8_t retries){_retryCount=retries;} //Set default retry sendAckCmd
void MiiGenericModem::setTimeout(uint16_t timeout){_timeout=timeout;} //Set default timeout for WaitForCmd
void MiiGenericModem::setDrift(uint16_t drift){_drift=drift;} //Set the time allowed to run appart in ms, before a full time sync will be done again
void MiiGenericModem::setTimeInterval(uint32_t interval){ _timeInterval = interval;} //Set the time update interval
//Just wait idle
void MiiGenericModem::idle(uint16_t timeout) {
uint32_t t=timeout+millis();
do {
YIELD;
} while (t>millis());
}
uint8_t MiiGenericModem::spiRead(uint8_t reg){
uint8_t val;
ATOMIC_BLOCK_START;
chipSelectLow();
SPI.transfer(reg & ~MII_RF_SPI_WRITE_MASK); // Send the address with the write mask off
val = SPI.transfer(0); // The written value is ignored, reg value is read
chipSelectHigh();
ATOMIC_BLOCK_END;
return val;
}
void MiiGenericModem::spiWrite(uint8_t reg, uint8_t val){
ATOMIC_BLOCK_START;
chipSelectLow();
SPI.transfer(reg | MII_RF_SPI_WRITE_MASK); // Send the address with the write mask on
SPI.transfer(val); // New value follows
chipSelectHigh();
ATOMIC_BLOCK_END;
}
void MiiGenericModem::spiBurstRead(uint8_t reg, uint8_t* dest, uint8_t len){
ATOMIC_BLOCK_START;
chipSelectLow();
SPI.transfer(reg & ~MII_RF_SPI_WRITE_MASK); // Send the start address with the write mask off
while (len--)
*dest++ = SPI.transfer(0);
chipSelectHigh();
ATOMIC_BLOCK_END;
}
void MiiGenericModem::spiBurstWrite(uint8_t reg, const uint8_t* src, uint8_t len){
ATOMIC_BLOCK_START;
chipSelectLow();
SPI.transfer(reg | MII_RF_SPI_WRITE_MASK); // Send the start address with the write mask on
while (len--)
SPI.transfer(*src++);
chipSelectHigh();
ATOMIC_BLOCK_END;
}
void MiiGenericModem::chipSelectHigh(void){
digitalWrite(_selectPin, HIGH);
#if SPI_ISOLATE
SPDR = 0xFF;
while (!(SPSR & (1 << SPIF)));
SPCR=_SPCRO;
SPSR=_SPSRO;
#endif
}
void MiiGenericModem::chipSelectLow(void){
#if SPI_ISOLATE
_SPCRO=SPCR;
_SPSRO=SPSR;
SPCR = _SPCR;
SPSR = _SPSR;
#endif
digitalWrite(_selectPin, LOW);
}
bool MiiGenericModem::isReady(void){
return _ready;
}
//Discard ad message by receving the message without ack
bool MiiGenericModem::discard(bool allowCollision){
bool ret = false;
#if MII_MAX_COLLISIONS
if (allowCollision && _collisionCount) ret=popCollision();
#endif
if (!ret) { //We had no collision to process, see if there was normal data
if (!hasAvailable()) return false; //We don't want any processing
clearRxBuf();
_rxHeaderTo=0;
ret = true;
}
return ret;
}
//Send a command and wait for Ack when trys is set
bool MiiGenericModem::sendAckCmd(uint8_t cmd,uint8_t* buf, uint8_t len, uint8_t address,uint8_t trys,uint8_t flags){
bool ret=false;
if (trys==0xFF) trys = _retryCount; //trys will be on more than number of retries
if (trys) trys++; //We always loop so 1 try is always needed
if (!address) address=_masterAddress; //When no address is specified we user master
if (!address) return false; //We will not send data to a undefined address
do {
setHeaderFlags(trys && (address!=MII_BROADCAST_ADDRESS) ? (MII_RF_FLAGS_ACK | flags) : flags);
setHeaderId(cmd);
setHeaderTo(address);
//When len is 0 we only send cmd as data
ret = len> 0 ? send(buf, len) : send(&cmd,sizeof(cmd));
waitPacketSent();
if (ret && trys && address!=MII_BROADCAST_ADDRESS) {
//Wait for ACK
ret = waitForCmd(MII_C_ACK,0,0,address);
//reduce the retry counts
trys--;
}
} while (!ret && trys>0);
//Check for master and if we should send update of time, not during sync
if (_timeInterval && isMaster() && millis()>_lastTime+_timeInterval && cmd!=MII_C_TIMESYNC){
// Serial.println("Sending master time");
sendTime();
}
//Return to listening
setModeRx();
return ret;
}
//Send a command to a specific address
bool MiiGenericModem::sendCmd(uint8_t cmd,uint8_t* buf, uint8_t len, uint8_t address,uint8_t flags){
return sendAckCmd(cmd,buf,len,address,0,flags);
}
bool MiiGenericModem::waitForCmd(uint8_t cmd,uint8_t* buf, uint8_t len, uint8_t address,uint16_t timeout){
if (!timeout) timeout=_timeout;
if (!address) address=_masterAddress; //We use master address for ok when not set
uint32_t failtime=timeout+millis();
//We wil not acknowledge messages
while (failtime>millis()){
if (available(false)) {
if (_rxHeaderId==cmd && (address==MII_BROADCAST_ADDRESS || address==_rxHeaderFrom)) {
return recv(false,buf,&len); //We are allowed to send ack we have received it
}
//We have a collision, received message we did not expect
//Store it in collision stack if it is not full
#if MII_MAX_COLLISIONS
if (!pushCollision()) //No more room in collision stack, Clear message directly
#endif
recv(true);
}
YIELD;
}
return false;
}
#if MII_MAX_COLLISIONS
bool MiiGenericModem::pushCollision(){
if (available(false) && _collisionCount<MII_MAX_COLLISIONS-1) {
collisions[_collisionCount].headerId=_rxHeaderId;
collisions[_collisionCount].headerFrom=_rxHeaderFrom;
collisions[_collisionCount].headerTo=_rxHeaderTo;
collisions[_collisionCount].headerFlags=(_rxHeaderFlags & ~_BV(MII_RF_FLAGS_ACK)); //We will ack below
collisions[_collisionCount].length=MII_RF_MAX_MESSAGE_LEN;
recv(false,collisions[_collisionCount].data,&collisions[_collisionCount].length); //We will allow ack to be send
_collisionCount++; //We have read a new collision
return true;
}
return false;
}
bool MiiGenericModem::popCollision(uint8_t* buf, uint8_t* len){
if (_collisionCount) {
if (buf && len){
*len=min(*len,collisions[0].length);
memmove(buf,collisions[0].data,*len);
};
//Check if we are in receiving mode and have already data in.
//If so we have to move it in and out
uint8_t rxHeaderId=collisions[0].headerId;
uint8_t rxHeaderFrom=collisions[0].headerFrom;
uint8_t rxHeaderTo=collisions[0].headerTo;
uint8_t rxHeaderFlags=collisions[0].headerFlags;
_collisionCount--;
memmove(&collisions[0],&collisions[1],sizeof(collisionRec_t)*_collisionCount);
if (available(false)) {
//We have temporary save the collision header before swap record
pushCollision(); //Add the available record to the stack
} else { //Free up the collision
}
//We save record in collision so now we can swap headers
_rxHeaderId=rxHeaderId;
_rxHeaderFrom=rxHeaderFrom;
_rxHeaderTo=rxHeaderTo;
_rxHeaderFlags=rxHeaderFlags;
return true;
}
return false;
}
#endif
bool MiiGenericModem::syncTime(uint8_t address){
if (isMaster()) return false;
_timeDiff=0; //Block sending data
//Send a request for timesync to the MASTER, on receving the request Master will only accept messages from this device
//Master will send his Time T[0] to this device will receive at T[1] and we will response with new request, skipped because of start master
//Master will send his Time T[2] to this device will receive at T[3] and we will response with new request
//Master will send his Time T[4] to this device will receive at T[5] and start calculation
uint8_t _try=0;
uint32_t T[6];
_lastTime=millis();
uint8_t toAddress=MII_BROADCAST_ADDRESS;
for (uint8_t i=0;i<6;){
if (!(sendCmd(MII_C_TIMESYNC,(uint8_t*)&address,sizeof(uint8_t)) &&
waitForCmd(MII_C_TIMESYNC,(uint8_t*)&T[i],sizeof(uint32_t),address)))
{ // Allow search for other time sync
_try++;
if (_try<4 && i==0) continue;
return false;
}
i++; //The send time
if (address==MII_BROADCAST_ADDRESS) address=_rxHeaderFrom; //toAddress can be broadcast for next rounds we take the real address
T[i++]=_rxTime; //The receive time
} //For
_masterAddress=address; //Valid time so set the masterAddress
//Calculate transmit time by dividing round trip using the two times (T[2] and T[4]) of master by 2
//Add this round trip to the T[4]send time of master and substract the receive time T[5]
_airTime=(T[4]-T[2])/2;
_timeDiff=T[4]+_airTime-T[5];
_timeout=_airTime*2+MII_RF_MIN_MSG_INTERVAL*2;
_lastTime=millis();
return true;
}
#if MII_C_CHANNEL
void MiiGenericModem::changeChannel(uint8_t channel){ //Change the channel only master by sending command to all clients
if (isMaster()) {
//Master will broadcast SET_CHANNEL for 10 times, 1 second intervall to all listening
for (int i=0;i<10;i++) {
sendCmd(MII_C_CHANNEL,&channel,sizeof(uint8_t));
delay(1000);
}
}
setChannel(channel);
}
#endif
bool MiiGenericModem::internalProcess(bool allowCollision){
bool ret = false;
if (available(allowCollision)) {
#if MII_MAX_ADDRESS
//We have data build up the addressTable
uint8_t a=0;
for (a=0;a<_addressCount && _address[a].id!=_rxHeaderFrom;a++){}
if (a<_addressCount) { //We found the record, shift first records to freeup record
memmove(&_address[1],&_address[0],sizeof(addressRec_t)*a);
} else { //New Record, insert at first place
memmove(&_address[1],&_address[0],sizeof(addressRec_t)*_addressCount);
if (_addressCount<MII_MAX_ADDRESS-1) _addressCount++;
}
//Fill the first record with data for recieved address
_address[0].id=_rxHeaderFrom;
_address[0].seen=millis(); //Create seconds
_address[0].rssi=_lastRssi;
//Filter the messages, to see if they are for us
if (_rxHeaderFrom == _thisAddress ||
!(_rxHeaderTo == _thisAddress || _rxHeaderTo == MII_BROADCAST_ADDRESS)
) { //Discard the message, it is not for us, no ack
discard(allowCollision);
return false;
}
#endif
switch (_rxHeaderId){
case MII_C_TIMESYNC :
recv(allowCollision); //Clear TimeSync CMD
if ( isMaster() || _rxHeaderTo==_thisAddress) { //Only master or direct requests will reply on Time Sync commands
//Master will send 3 times data, no retry and will not wait for last reqst
uint32_t t;
for (uint8_t i=0;i<3;i++) {
t=time();
if (!sendCmd(MII_C_TIMESYNC,(uint8_t*)&t,sizeof(uint32_t),_rxHeaderFrom)) break;
if (i==2 || !waitForCmd(MII_C_TIMESYNC,0,0,_rxHeaderFrom)) break; //Exit if did not send or got correct response
}
} else {
//When somebody is doing time sync make sure we don't send a message
_txTime=millis()+_airTime*2;
_lastTime=max(_lastTime,_txTime);
}
break;
case MII_C_REQ_TIME:
recv(allowCollision); //Clear Request Time CMD
if (isMaster()) sendTime();
break;
#if MII_C_CHANNEL
case MII_C_CHANNEL: {
uint8_t channel;
if (recv(allowCollision,&channel,sizeof(uint8_t)) changeChannel(channel);
} break;
#endif
case MII_C_TIME:
if (!isMaster()) { //We are just a client and should process this time from master
uint32_t _time;
uint8_t _len=sizeof(_time);
if (recv(allowCollision,(uint8_t *)&_time,&_len) && _time) { //Only accept time if it is set
long diff = time(_rxTime)-_airTime-_time;
_lastTime=_rxTime;
#if MIIRF_SERIAL >= 2
Serial.print("Time:");Serial.print(time(_rxTime));Serial.print("-");Serial.print(time(_airTime));Serial.print("-");Serial.print(_time);Serial.print("=");Serial.print(diff);Serial.print('<');Serial.print(_drift);Serial.print(" [");Serial.print(millis());Serial.print('-');Serial.print(_rxTime);Serial.println("]");Serial.flush();
#endif
if (!_timeSync) {
_masterAddress=_rxHeaderFrom; //Valid time so set the masterAddress
_timeDiff-=diff;
_lastTime=millis();
//We balance the time drift by adding half of the drift if difference is within 10ms
} else if (abs(diff)<=_drift && _timeDiff) { //We need to valid timediff before we calculate diff
_timeDiff-=((diff*3)/4); //For bigger drifts gap is closed better (.75)
_lastTime=millis();
} else { //When difference to large request timing
syncTime();
}
}
} else {
discard(allowCollision); //Clear Time CMD, without ack
}
break;
default : ret=true; break; //We have not internal processed so it is available
}
} else { //Now data was available to process
// check if we should do time sync, when never registered do it fast
if (_timeInterval && !isMaster() && (_lastTime+(_timeDiff==0 ? _timeInterval/3 : _timeInterval))<millis()){
if (!_timeSync) {
if (_timeDiff==0) sendCmd(MII_C_REQ_TIME);
_lastTime=millis();
} else
syncTime();
}
}
return ret;
}
bool MiiGenericModem::hasAvailable(){
if (!_rxBufValid) {
if (_mode==MII_RF_MODE_TX) return false;
setModeRx(); // Make sure we are receiving
}
return _rxBufValid;
}
bool MiiGenericModem::available(bool allowCollision){
//If we allow collision the be retrieved, check if we have them available
#if MII_MAX_COLLISIONS
if (allowCollision && _collisionCount) {
pushCollision(); //If there is real data just pusch it on the stack
//Fill the headers with the data available
_rxHeaderId=collisions[0].headerId;
_rxHeaderFrom=collisions[0].headerFrom;
_rxHeaderTo=collisions[0].headerTo;
_rxHeaderFlags=collisions[0].headerFlags;
return true;
}
#endif
//If where are in the internal processing loops return the original availability
if (_inAvailable) return hasAvailable();
_inAvailable=true;
bool ret = internalProcess(allowCollision);
//Unlock the available loop
_inAvailable=false;
if (!ret) {
YIELD;
}
return ret;
}
void MiiGenericModem::sendTime() {
if (isMaster()) {
setHeaderFlags(0);
setHeaderId(MII_C_TIME);
setHeaderTo(MII_BROADCAST_ADDRESS);
uint32_t _time = time();
if (send((uint8_t*)&_time,sizeof(_time))) {
_lastTime=millis();
waitPacketSent();
}
}
}
uint32_t MiiGenericModem::time(uint32_t _time){
return isMaster() ? (_time ? _time : millis()) : (_timeDiff ? (_time ? _time : millis())+ _timeDiff : _time );
}
bool MiiGenericModem::isMaster(){
return _masterAddress==_thisAddress;
}
#if MII_MAX_ADDRESS
uint8_t MiiGenericModem::nextAddress(uint8_t address,uint32_t liveSpan){
if (!address) address==_thisAddress; //Set address to internal address if no address set
//Go through the list and our own address
uint8_t ret=_thisAddress>address ? _thisAddress :0;
uint32_t allowed=millis()>liveSpan ? millis()-liveSpan : 0;
for (uint8_t i=0;i<_addressCount;i++){
if (_address[i].id>address && _address[i].seen>=allowed)
ret=(ret==0 ? _address[i].id : min(ret,_address[i].id));
}
return ret;
}
uint8_t MiiGenericModem::prevAddress(uint8_t address,uint32_t liveSpan){
if (!address) address==_thisAddress; //Set address to internal address if no address set
//Go through the list
uint8_t ret=_thisAddress<address ? _thisAddress : 0;
uint32_t allowed=millis()>liveSpan ? millis()-liveSpan : 0;
for (uint8_t i=0;i<_addressCount;i++){
if (_address[i].id<address && _address[i].seen>=allowed)
ret=(ret==0 ? _address[i].id : max(ret,_address[i].id));
}
return ret;
}
uint8_t MiiGenericModem::firstAddress(uint8_t address,uint32_t liveSpan){
if (!address) address==_thisAddress; //Set address to internal address if no address set
//Go through the list
uint8_t ret=_thisAddress<address ? _thisAddress : 0;
uint32_t allowed=millis()>liveSpan ? millis()-liveSpan : 0;
for (uint8_t i=0;i<_addressCount;i++){
if (_address[i].id<address && _address[i].seen>=allowed)
ret=(ret==0 ? _address[i].id : min(ret,_address[i].id));
}
return ret;
}
#endif
| [
"sierk@hoeksma.org"
] | sierk@hoeksma.org |
894ce2ecb1809a45ddd6a9d01089973f13208348 | d49f9912788a9e3bba936731955e53b69596a3fd | /models/break.h | abaa29b58395dda63899215e93ff297fddd52a0a | [] | no_license | ChechenItza/Daily-Planner | 9f6af0dcb3512a059c9783b36f0cd12b69a7f532 | 61b2978bc2057f1010a60a6ca391aebaf84f8daf | refs/heads/master | 2022-11-09T16:27:47.272176 | 2020-06-28T13:30:59 | 2020-06-28T13:30:59 | 99,214,353 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 138 | h | #ifndef BREAK_H
#define BREAK_H
class QTime;
struct Break
{
QTime start_time;
QTime end_time;
int id;
};
#endif // BREAK_H
| [
"artka.kazaktar@gmail.com"
] | artka.kazaktar@gmail.com |
88718161c9b47e954d3020e3b6cdeadf3c5bb74b | 88fe84c79e5740b4aaa068df6a70e35841a68d25 | /awkward-cpp/src/cpu-kernels/awkward_IndexedArray_flatten_none2empty.cpp | 92365f80803f21b660fa05909c8f584dbb0302b8 | [
"BSD-3-Clause"
] | permissive | scikit-hep/awkward | 176f56182a936270e163eab92ea18368c2bdc1be | 519bba6ed2eec4e227994d2fd1a62b2a51f15e20 | refs/heads/main | 2023-09-02T20:19:10.175088 | 2023-09-01T20:13:25 | 2023-09-01T20:13:25 | 202,413,762 | 208 | 22 | BSD-3-Clause | 2023-09-14T17:19:29 | 2019-08-14T19:32:12 | Python | UTF-8 | C++ | false | false | 1,934 | cpp | // BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE
#define FILENAME(line) FILENAME_FOR_EXCEPTIONS_C("src/cpu-kernels/awkward_IndexedArray_flatten_none2empty.cpp", line)
#include "awkward/kernels.h"
template <typename T, typename C>
ERROR awkward_IndexedArray_flatten_none2empty(
T* outoffsets,
const C* outindex,
int64_t outindexlength,
const T* offsets,
int64_t offsetslength) {
outoffsets[0] = offsets[0];
int64_t k = 1;
for (int64_t i = 0; i < outindexlength; i++) {
C idx = outindex[i];
if (idx < 0) {
outoffsets[k] = outoffsets[k - 1];
k++;
}
else if (idx + 1 >= offsetslength) {
return failure("flattening offset out of range", i, kSliceNone, FILENAME(__LINE__));
}
else {
T count =
offsets[idx + 1] - offsets[idx];
outoffsets[k] = outoffsets[k - 1] + count;
k++;
}
}
return success();
}
ERROR awkward_IndexedArray32_flatten_none2empty_64(
int64_t* outoffsets,
const int32_t* outindex,
int64_t outindexlength,
const int64_t* offsets,
int64_t offsetslength) {
return awkward_IndexedArray_flatten_none2empty<int64_t, int32_t>(
outoffsets,
outindex,
outindexlength,
offsets,
offsetslength);
}
ERROR awkward_IndexedArrayU32_flatten_none2empty_64(
int64_t* outoffsets,
const uint32_t* outindex,
int64_t outindexlength,
const int64_t* offsets,
int64_t offsetslength) {
return awkward_IndexedArray_flatten_none2empty<int64_t, uint32_t>(
outoffsets,
outindex,
outindexlength,
offsets,
offsetslength);
}
ERROR awkward_IndexedArray64_flatten_none2empty_64(
int64_t* outoffsets,
const int64_t* outindex,
int64_t outindexlength,
const int64_t* offsets,
int64_t offsetslength) {
return awkward_IndexedArray_flatten_none2empty<int64_t, int64_t>(
outoffsets,
outindex,
outindexlength,
offsets,
offsetslength);
}
| [
"noreply@github.com"
] | noreply@github.com |
9d5e7f5ed72a3106fe68346398a097e58463d190 | a8efa18d98e651f7186e898507f78e3ca46c6583 | /threadpool/threadpool.h | 169587421f8e9d75ceae511739c357f73e6e6bcf | [] | no_license | yyt12345/summerbiubiu | 8f2b8f09bc823464c2f70dc7742165e07e114b48 | b16262b6beff2c638a59dc6cf5078d29c4b61d57 | refs/heads/master | 2021-03-06T22:35:32.984869 | 2020-05-18T02:51:33 | 2020-05-18T02:51:33 | 246,229,574 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 774 | h | #include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
#include <functional>
typedef struct task {
void* (*run)();
//void* (*run)(void* args);
//void* arg;
struct task* next;
}task_t;
class threadpool
{
int counter;//已有线程数
int idle;//空闲线程数
int Max_threads;//最大可容纳线程数
task_t* first;
task_t* last;
std::vector<std::thread> workers;//线程
std::mutex queue_mutex;
std::condition_variable condition;
bool quit;
//void thread_rountine(void* arg);
void* thread_rountine();
public:
void helloworld();
threadpool(int threads);
void threadpool_add_task(void* (*run)());
//void threadpool_add_task(void *(*run)(void *args),void *args);
~threadpool();
};
| [
"noreply@github.com"
] | noreply@github.com |
6658f57a6b74585759cc109994a8984578dfb1a1 | c2427408a4c5265595f1365d44454bdb38a0bf4e | /src/htmlstruct/ref.h | 6d0926497fe6bd89ac75f67291f940f23ee6325e | [] | no_license | Patrickxzm/P_Arthur | 07265bea5c30fa70275f564720bd020b2f865d94 | 5c0ee965a0116638befb3f92cb38d38f7cf28ffa | refs/heads/master | 2021-05-16T02:42:16.103559 | 2016-11-25T02:37:46 | 2016-11-25T02:37:46 | 20,324,464 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 734 | h | #ifndef _PAT_REF_H_102402
#define _PAT_REF_H_102402
#include <string>
#include <ostream>
using std::ostream;
using std::string;
class CRef {
public:
CRef(const string &url, int pos, const string &tag);
virtual ~CRef();
void addref(const char* ref);
const string& url() const
{
return _url;
}
const string &urlstr() const;
const string &anchor_text() const
{
return _ref;
}
const string &ref() const
{
return _ref;
}
int pos() const
{
return _pos;
}
const string &tagName() const
{
return _tagName;
}
friend ostream &operator<<(ostream &os, const CRef &);
private:
string _url;
string _ref;
int _pos;
string _tagName;
};
ostream &operator<<(ostream &os, const CRef &);
#endif /* _PAT_REF_H_102402 */
| [
"ZhengmaoXIE@gmail.com"
] | ZhengmaoXIE@gmail.com |
61ccc4df083d468a275d6101a80e337aadc6245f | 8c1009ebbfc34777c677d410aada9e80364fa20d | /src/UI/Node.cpp | d0a78419e2cd1774b3259787cf7a14092facd365 | [
"MIT"
] | permissive | makzyt4/dungeon-saga | 3403daafafb6d2dbee34833b1c8d8132059014db | a367d35fe2c4404a380e61f5b363e4a812cfa2c5 | refs/heads/master | 2021-04-15T07:21:05.438581 | 2018-04-27T08:22:25 | 2018-04-27T08:22:25 | 126,694,751 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 650 | cpp | #include "../../include/UI/Node.hpp"
ds::Node::Node() {
state = MenuState::Normal;
mouseHoverAction = [](){};
mousePressedAction = [](){};
mouseReleasedAction = [](){};
}
void ds::Node::listen(sf::Event* event) {
onMouseHoverAction(event);
onMouseReleasedAction(event);
onMousePressedAction(event);
}
void ds::Node::setOnMouseHoverAction(std::function<void()> action) {
mouseHoverAction = action;
}
void ds::Node::setOnMousePressedAction(std::function<void()> action) {
mousePressedAction = action;
}
void ds::Node::setOnMouseReleasedAction(std::function<void()> action) {
mouseReleasedAction = action;
}
| [
"maksymilian.zytkiewicz@gmail.com"
] | maksymilian.zytkiewicz@gmail.com |
db9d29495bd91fb6ece71ea8e6a52bb5f8ad8a28 | 711e5c8b643dd2a93fbcbada982d7ad489fb0169 | /XPSP1/NT/base/fs/utils/dfrg/dataiocl.cpp | 62ce458400d19b84ea94215de3476eb3f3305dcb | [] | no_license | aurantst/windows-XP-SP1 | 629a7763c082fd04d3b881e0d32a1cfbd523b5ce | d521b6360fcff4294ae6c5651c539f1b9a6cbb49 | refs/heads/master | 2023-03-21T01:08:39.870106 | 2020-09-28T08:10:11 | 2020-09-28T08:10:11 | null | 0 | 0 | null | null | null | null | IBM852 | C++ | false | false | 7,523 | cpp | /**************************************************************************************************
FILENAME: DataIoClient.cpp
COPYRIGHTę 2001 Microsoft Corporation and Executive Software International, Inc.
*/
#define INC_OLE2
#include "stdafx.h"
#ifndef SNAPIN
#include <windows.h>
#endif
#include <stdio.h>
#include "DataIo.h"
#include "DataIoCl.h"
#include "Message.h"
#include "ErrMacro.h"
MULTI_QI mq;
/**************************************************************************************************
COPYRIGHTę 2001 Microsoft Corporation and Executive Software International, Inc.
ROUTINE DESCRIPTION:
This module inititalizes the DCOM DataIo Client communications.
INPUT:
None.
RETURN:
TRUE - Success.
FALSE - Failure to initilize.
*/
BOOL
InitializeDataIoClient(
IN REFCLSID rclsid,
IN PTCHAR pMachine,
IN OUT LPDATAOBJECT* ppstm
)
{
// Check if we already have a pointer to this DCOM server.
if(*ppstm != NULL) {
Message(TEXT("InitializeDataIoClient - called with non-NULL pointer"), -1, NULL);
return FALSE;
}
HRESULT hr;
// TCHAR wsz [200];
COSERVERINFO sServerInfo;
ZeroMemory(&sServerInfo, sizeof(sServerInfo));
/*
if(pMachine != NULL) {
MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, pMachine, -1, wsz, 200);
sServerInfo.pwszName = wsz;
}
*/
// Initialize the Multi QueryInterface structure.
mq.pIID = &IID_IDataObject;
mq.pItf = NULL;
mq.hr = S_OK;
// Create a remote instance of the object on the argv[1] machine
hr = CoCreateInstanceEx(rclsid,
NULL,
CLSCTX_SERVER,
&sServerInfo,
1,
&mq);
// Message(TEXT("InitializeDataIoClient - CoCreateInstanceEx"), hr, NULL);
// Check for failure.
if (FAILED(hr)) {
return FALSE;
}
// Return the pointer to the server.
*ppstm = (IDataObject*)mq.pItf;
return TRUE;
}
/**************************************************************************************************
COPYRIGHTę 2001 Microsoft Corporation and Executive Software International, Inc.
ROUTINE DESCRIPTION:
INPUT:
RETURN:
TRUE - Success.
FALSE - Failure.
typedef struct {
WORD dwID; // ESI data structre ID always = 0x4553 'ES'
WORD dwType; // Type of data structure
WORD dwVersion; // Version number
WORD dwCompatibilty;// Compatibilty number
ULONG ulDataSize; // Data size
WPARAM wparam; // LOWORD(wparam) = Command
TCHAR cData; // Void pointer to the data - NULL = no data
} DATA_IO, *PDATA_IO;
*/
BOOL
DataIoClientSetData(
IN WPARAM wparam,
IN PTCHAR pData,
IN DWORD dwDataSize,
IN LPDATAOBJECT pstm
)
{
// Check for DCOM pointer to the server.
if(pstm == NULL) {
return FALSE;
}
HRESULT hr;
HANDLE hData;
DATA_IO* pDataIo;
// Allocate and lock enough memory for the ESI data structure and the data being sent.
hData = GlobalAlloc(GHND,dwDataSize + sizeof(DATA_IO));
EF_ASSERT(hData);
pDataIo = (DATA_IO*)GlobalLock(hData);
EF_ASSERT(pDataIo);
// Fill in the ESI data structure.
pDataIo->dwID = ESI_DATA_STRUCTURE; // ESI data structre ID always = 0x4553 'ES'
pDataIo->dwType = FR_COMMAND_BUFFER; // Type of data structure
pDataIo->dwVersion = FR_COMMAND_BUFFER_ONE; // Version number
pDataIo->dwCompatibilty = FR_COMMAND_BUFFER_ONE; // Compatibilty number
pDataIo->ulDataSize = dwDataSize; // Data size
pDataIo->wparam = wparam; // LOWORD(wparam) = Command
// Copy the memory into the buffer, unlock it and
// put the handle into the STGMEDIUM data structure.
CopyMemory((PTCHAR)&pDataIo->cData, pData, dwDataSize);
GlobalUnlock(hData);
FORMATETC formatetc;
STGMEDIUM medium;
// Set up FORMATETC with CF_TEXT and global memory.
formatetc.cfFormat = CF_TEXT;
formatetc.ptd = NULL;
formatetc.dwAspect = DVASPECT_CONTENT;
formatetc.lindex = -1;
formatetc.tymed = TYMED_HGLOBAL;
// Set up STGMEDIUM with global memory and NULL for pUnkForRelease.
// SetData msut then be responsible for freeing the memory.
medium.tymed = TYMED_HGLOBAL;
medium.pUnkForRelease = NULL;
medium.hGlobal = hData;
// Send it all to SetData, telling it that it is responsible for freeing the memory.
hr = pstm->SetData(&formatetc, &medium, TRUE);
// Message(TEXT("DataIoClientSetData - IDataObject::SetData"), hr, NULL);
// Check for failure.
if (FAILED(hr)) {
return FALSE;
}
return TRUE;
}
/*****************************************************************************************************************
COPYRIGHTę 2001 Microsoft Corporation and Executive Software International, Inc.
ROUTINE DESCRIPTION:
GLOBALS:
FORMATETC - has been initialized in InitializeDataIoClient.
INPUT:
None.
RETURN:
HGLOBAL - handle to the memory containing the data.
HGLOBAL - NULL = failure.
*/
HGLOBAL
DataIoClientGetData(
IN LPDATAOBJECT pstm
)
{
// Check for DCOM pointer to the server.
if(pstm == NULL) {
return NULL;
}
FORMATETC formatetc;
STGMEDIUM medium;
HRESULT hr;
// Zero the STGMEDIUM structure.
ZeroMemory((void*)&medium, sizeof(STGMEDIUM));
// Set up FORMATETC with CF_TEXT and global memory.
formatetc.cfFormat = CF_TEXT;
formatetc.ptd = NULL;
formatetc.dwAspect = DVASPECT_CONTENT;
formatetc.lindex = -1;
formatetc.tymed = TYMED_HGLOBAL;
// Get the data from the object.
hr = pstm->GetData(&formatetc, &medium);
// Message(TEXT("DataIoClientGetData - IDataObject::GetData"), hr, NULL);
// Check for failure.
if (FAILED(hr)) {
return NULL;
}
DWORD dwSize;
HGLOBAL hDataIn;
PTCHAR pDataSource;
PTCHAR pDataIn;
// Allocate and lock enough memory for the data we received.
dwSize = (DWORD)GlobalSize(medium.hGlobal);
hDataIn = GlobalAlloc(GHND, dwSize);
EF_ASSERT(hDataIn);
pDataIn = (PTCHAR)GlobalLock(hDataIn);
EF_ASSERT(hDataIn);
// Get a pointer and lock the source data.
pDataSource = (PTCHAR)GlobalLock(medium.hGlobal);
// Copy the memory into the local buffer.
CopyMemory(pDataIn, pDataSource, dwSize);
// Unlock the memory.
GlobalUnlock(hDataIn);
GlobalUnlock(medium.hGlobal);
// Free the source memory.
ReleaseStgMedium(&medium);
// Return the handle to the memory.
return hDataIn;
}
/*****************************************************************************************************************
COPYRIGHTę 2001 Microsoft Corporation and Executive Software International, Inc.
ROUTINE DESCRIPTION:
Exit routine for DataIo
GLOBAL VARIABLES:
INPUT:
None;
RETURN:
*/
BOOL
ExitDataIoClient(
IN LPDATAOBJECT* ppstm
)
{
// Release the object.
if(*ppstm != NULL) {
LPDATAOBJECT pstm = *ppstm;
pstm->Release();
*ppstm = NULL;
}
return TRUE;
}
| [
"112426112@qq.com"
] | 112426112@qq.com |
aa0cae78dc45c3feab862f2bc7d148f4d3c1591d | 5ec3126fa503c5ed2c0bcd6dbf487d3df1a4c95c | /src/rpcrawtransaction.cpp | 548e0443c26cc5c656b1dba2d0b2d0dd6e34e71a | [
"MIT"
] | permissive | voxpopulidev/voxpopulicoin | f964cee9964a476668ffc382bd48de44ac395b30 | 6f49fa21f7bef0284a22a77c2679d10f99213b08 | refs/heads/master | 2021-01-13T02:27:05.749931 | 2014-10-12T00:26:22 | 2014-10-12T00:26:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,288 | cpp | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp>
#include "base58.h"
#include "bitcoinrpc.h"
#include "txdb.h"
#include "init.h"
#include "main.h"
#include "net.h"
#include "wallet.h"
using namespace std;
using namespace boost;
using namespace boost::assign;
using namespace json_spirit;
void ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out, bool fIncludeHex)
{
txnouttype type;
vector<CTxDestination> addresses;
int nRequired;
out.push_back(Pair("asm", scriptPubKey.ToString()));
if (fIncludeHex)
out.push_back(Pair("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end())));
if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired))
{
out.push_back(Pair("type", GetTxnOutputType(TX_NONSTANDARD)));
return;
}
out.push_back(Pair("reqSigs", nRequired));
out.push_back(Pair("type", GetTxnOutputType(type)));
Array a;
BOOST_FOREACH(const CTxDestination& addr, addresses)
a.push_back(CBitcoinAddress(addr).ToString());
out.push_back(Pair("addresses", a));
}
void TxToJSON(const CTransaction& tx, const uint256 hashBlock, Object& entry)
{
entry.push_back(Pair("txid", tx.GetHash().GetHex()));
entry.push_back(Pair("version", tx.nVersion));
entry.push_back(Pair("time", (boost::int64_t)tx.nTime));
entry.push_back(Pair("locktime", (boost::int64_t)tx.nLockTime));
Array vin;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
Object in;
if (tx.IsCoinBase())
in.push_back(Pair("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
else
{
in.push_back(Pair("txid", txin.prevout.hash.GetHex()));
in.push_back(Pair("vout", (boost::int64_t)txin.prevout.n));
Object o;
o.push_back(Pair("asm", txin.scriptSig.ToString()));
o.push_back(Pair("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
in.push_back(Pair("scriptSig", o));
}
in.push_back(Pair("sequence", (boost::int64_t)txin.nSequence));
vin.push_back(in);
}
entry.push_back(Pair("vin", vin));
Array vout;
for (unsigned int i = 0; i < tx.vout.size(); i++)
{
const CTxOut& txout = tx.vout[i];
Object out;
out.push_back(Pair("value", ValueFromAmount(txout.nValue)));
out.push_back(Pair("n", (boost::int64_t)i));
Object o;
ScriptPubKeyToJSON(txout.scriptPubKey, o, false);
out.push_back(Pair("scriptPubKey", o));
vout.push_back(out);
}
entry.push_back(Pair("vout", vout));
if (hashBlock != 0)
{
entry.push_back(Pair("blockhash", hashBlock.GetHex()));
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end() && (*mi).second)
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
{
entry.push_back(Pair("confirmations", 1 + nBestHeight - pindex->nHeight));
entry.push_back(Pair("time", (boost::int64_t)pindex->nTime));
entry.push_back(Pair("blocktime", (boost::int64_t)pindex->nTime));
}
else
entry.push_back(Pair("confirmations", 0));
}
}
}
Value getrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getrawtransaction <txid> [verbose=0]\n"
"If verbose=0, returns a string that is\n"
"serialized, hex-encoded data for <txid>.\n"
"If verbose is non-zero, returns an Object\n"
"with information about <txid>.");
uint256 hash;
hash.SetHex(params[0].get_str());
bool fVerbose = false;
if (params.size() > 1)
fVerbose = (params[1].get_int() != 0);
CTransaction tx;
uint256 hashBlock = 0;
if (!GetTransaction(hash, tx, hashBlock))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction");
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << tx;
string strHex = HexStr(ssTx.begin(), ssTx.end());
if (!fVerbose)
return strHex;
Object result;
result.push_back(Pair("hex", strHex));
TxToJSON(tx, hashBlock, result);
return result;
}
Value listunspent(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 3)
throw runtime_error(
"listunspent [minconf=1] [maxconf=9999999] [\"address\",...]\n"
"Returns array of unspent transaction outputs\n"
"with between minconf and maxconf (inclusive) confirmations.\n"
"Optionally filtered to only include txouts paid to specified addresses.\n"
"Results are an array of Objects, each of which has:\n"
"{txid, vout, scriptPubKey, amount, confirmations}");
RPCTypeCheck(params, list_of(int_type)(int_type)(array_type));
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
int nMaxDepth = 9999999;
if (params.size() > 1)
nMaxDepth = params[1].get_int();
set<CBitcoinAddress> setAddress;
if (params.size() > 2)
{
Array inputs = params[2].get_array();
BOOST_FOREACH(Value& input, inputs)
{
CBitcoinAddress address(input.get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid voxpopuli address: ")+input.get_str());
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+input.get_str());
setAddress.insert(address);
}
}
Array results;
vector<COutput> vecOutputs;
pwalletMain->AvailableCoins(vecOutputs, false);
BOOST_FOREACH(const COutput& out, vecOutputs)
{
if (out.nDepth < nMinDepth || out.nDepth > nMaxDepth)
continue;
if(setAddress.size())
{
CTxDestination address;
if(!ExtractDestination(out.tx->vout[out.i].scriptPubKey, address))
continue;
if (!setAddress.count(address))
continue;
}
int64_t nValue = out.tx->vout[out.i].nValue;
const CScript& pk = out.tx->vout[out.i].scriptPubKey;
Object entry;
entry.push_back(Pair("txid", out.tx->GetHash().GetHex()));
entry.push_back(Pair("vout", out.i));
CTxDestination address;
if (ExtractDestination(out.tx->vout[out.i].scriptPubKey, address))
{
entry.push_back(Pair("address", CBitcoinAddress(address).ToString()));
if (pwalletMain->mapAddressBook.count(address))
entry.push_back(Pair("account", pwalletMain->mapAddressBook[address]));
}
entry.push_back(Pair("scriptPubKey", HexStr(pk.begin(), pk.end())));
entry.push_back(Pair("amount",ValueFromAmount(nValue)));
entry.push_back(Pair("confirmations",out.nDepth));
results.push_back(entry);
}
return results;
}
Value createrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 2)
throw runtime_error(
"createrawtransaction [{\"txid\":txid,\"vout\":n},...] {address:amount,...}\n"
"Create a transaction spending given inputs\n"
"(array of objects containing transaction id and output number),\n"
"sending to given address(es).\n"
"Returns hex-encoded raw transaction.\n"
"Note that the transaction's inputs are not signed, and\n"
"it is not stored in the wallet or transmitted to the network.");
RPCTypeCheck(params, list_of(array_type)(obj_type));
Array inputs = params[0].get_array();
Object sendTo = params[1].get_obj();
CTransaction rawTx;
BOOST_FOREACH(Value& input, inputs)
{
const Object& o = input.get_obj();
const Value& txid_v = find_value(o, "txid");
if (txid_v.type() != str_type)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing txid key");
string txid = txid_v.get_str();
if (!IsHex(txid))
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid");
const Value& vout_v = find_value(o, "vout");
if (vout_v.type() != int_type)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
int nOutput = vout_v.get_int();
if (nOutput < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");
CTxIn in(COutPoint(uint256(txid), nOutput));
rawTx.vin.push_back(in);
}
set<CBitcoinAddress> setAddress;
BOOST_FOREACH(const Pair& s, sendTo)
{
CBitcoinAddress address(s.name_);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid voxpopuli address: ")+s.name_);
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_);
setAddress.insert(address);
CScript scriptPubKey;
scriptPubKey.SetDestination(address.Get());
int64_t nAmount = AmountFromValue(s.value_);
CTxOut out(nAmount, scriptPubKey);
rawTx.vout.push_back(out);
}
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << rawTx;
return HexStr(ss.begin(), ss.end());
}
Value decoderawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"decoderawtransaction <hex string>\n"
"Return a JSON object representing the serialized, hex-encoded transaction.");
RPCTypeCheck(params, list_of(str_type));
vector<unsigned char> txData(ParseHex(params[0].get_str()));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
CTransaction tx;
try {
ssData >> tx;
}
catch (std::exception &e) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
}
Object result;
TxToJSON(tx, 0, result);
return result;
}
Value decodescript(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"decodescript <hex string>\n"
"Decode a hex-encoded script.");
RPCTypeCheck(params, list_of(str_type));
Object r;
CScript script;
if (params[0].get_str().size() > 0){
vector<unsigned char> scriptData(ParseHexV(params[0], "argument"));
script = CScript(scriptData.begin(), scriptData.end());
} else {
// Empty scripts are valid
}
ScriptPubKeyToJSON(script, r, false);
r.push_back(Pair("p2sh", CBitcoinAddress(script.GetID()).ToString()));
return r;
}
Value signrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 4)
throw runtime_error(
"signrawtransaction <hex string> [{\"txid\":txid,\"vout\":n,\"scriptPubKey\":hex},...] [<privatekey1>,...] [sighashtype=\"ALL\"]\n"
"Sign inputs for raw transaction (serialized, hex-encoded).\n"
"Second optional argument (may be null) is an array of previous transaction outputs that\n"
"this transaction depends on but may not yet be in the blockchain.\n"
"Third optional argument (may be null) is an array of base58-encoded private\n"
"keys that, if given, will be the only keys used to sign the transaction.\n"
"Fourth optional argument is a string that is one of six values; ALL, NONE, SINGLE or\n"
"ALL|ANYONECANPAY, NONE|ANYONECANPAY, SINGLE|ANYONECANPAY.\n"
"Returns json object with keys:\n"
" hex : raw transaction with signature(s) (hex-encoded string)\n"
" complete : 1 if transaction has a complete set of signature (0 if not)"
+ HelpRequiringPassphrase());
RPCTypeCheck(params, list_of(str_type)(array_type)(array_type)(str_type), true);
vector<unsigned char> txData(ParseHex(params[0].get_str()));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
vector<CTransaction> txVariants;
while (!ssData.empty())
{
try {
CTransaction tx;
ssData >> tx;
txVariants.push_back(tx);
}
catch (std::exception &e) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
}
}
if (txVariants.empty())
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transaction");
// mergedTx will end up with all the signatures; it
// starts as a clone of the rawtx:
CTransaction mergedTx(txVariants[0]);
bool fComplete = true;
// Fetch previous transactions (inputs):
map<COutPoint, CScript> mapPrevOut;
for (unsigned int i = 0; i < mergedTx.vin.size(); i++)
{
CTransaction tempTx;
MapPrevTx mapPrevTx;
CTxDB txdb("r");
map<uint256, CTxIndex> unused;
bool fInvalid;
// FetchInputs aborts on failure, so we go one at a time.
tempTx.vin.push_back(mergedTx.vin[i]);
tempTx.FetchInputs(txdb, unused, false, false, mapPrevTx, fInvalid);
// Copy results into mapPrevOut:
BOOST_FOREACH(const CTxIn& txin, tempTx.vin)
{
const uint256& prevHash = txin.prevout.hash;
if (mapPrevTx.count(prevHash) && mapPrevTx[prevHash].second.vout.size()>txin.prevout.n)
mapPrevOut[txin.prevout] = mapPrevTx[prevHash].second.vout[txin.prevout.n].scriptPubKey;
}
}
// Add previous txouts given in the RPC call:
if (params.size() > 1 && params[1].type() != null_type)
{
Array prevTxs = params[1].get_array();
BOOST_FOREACH(Value& p, prevTxs)
{
if (p.type() != obj_type)
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}");
Object prevOut = p.get_obj();
RPCTypeCheck(prevOut, map_list_of("txid", str_type)("vout", int_type)("scriptPubKey", str_type));
string txidHex = find_value(prevOut, "txid").get_str();
if (!IsHex(txidHex))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "txid must be hexadecimal");
uint256 txid;
txid.SetHex(txidHex);
int nOut = find_value(prevOut, "vout").get_int();
if (nOut < 0)
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive");
string pkHex = find_value(prevOut, "scriptPubKey").get_str();
if (!IsHex(pkHex))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "scriptPubKey must be hexadecimal");
vector<unsigned char> pkData(ParseHex(pkHex));
CScript scriptPubKey(pkData.begin(), pkData.end());
COutPoint outpoint(txid, nOut);
if (mapPrevOut.count(outpoint))
{
// Complain if scriptPubKey doesn't match
if (mapPrevOut[outpoint] != scriptPubKey)
{
string err("Previous output scriptPubKey mismatch:\n");
err = err + mapPrevOut[outpoint].ToString() + "\nvs:\n"+
scriptPubKey.ToString();
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);
}
}
else
mapPrevOut[outpoint] = scriptPubKey;
}
}
bool fGivenKeys = false;
CBasicKeyStore tempKeystore;
if (params.size() > 2 && params[2].type() != null_type)
{
fGivenKeys = true;
Array keys = params[2].get_array();
BOOST_FOREACH(Value k, keys)
{
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(k.get_str());
if (!fGood)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY,"Invalid private key");
CKey key;
bool fCompressed;
CSecret secret = vchSecret.GetSecret(fCompressed);
key.SetSecret(secret, fCompressed);
tempKeystore.AddKey(key);
}
}
else
EnsureWalletIsUnlocked();
const CKeyStore& keystore = (fGivenKeys ? tempKeystore : *pwalletMain);
int nHashType = SIGHASH_ALL;
if (params.size() > 3 && params[3].type() != null_type)
{
static map<string, int> mapSigHashValues =
boost::assign::map_list_of
(string("ALL"), int(SIGHASH_ALL))
(string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY))
(string("NONE"), int(SIGHASH_NONE))
(string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY))
(string("SINGLE"), int(SIGHASH_SINGLE))
(string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY))
;
string strHashType = params[3].get_str();
if (mapSigHashValues.count(strHashType))
nHashType = mapSigHashValues[strHashType];
else
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid sighash param");
}
bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
// Sign what we can:
for (unsigned int i = 0; i < mergedTx.vin.size(); i++)
{
CTxIn& txin = mergedTx.vin[i];
if (mapPrevOut.count(txin.prevout) == 0)
{
fComplete = false;
continue;
}
const CScript& prevPubKey = mapPrevOut[txin.prevout];
txin.scriptSig.clear();
// Only sign SIGHASH_SINGLE if there's a corresponding output:
if (!fHashSingle || (i < mergedTx.vout.size()))
SignSignature(keystore, prevPubKey, mergedTx, i, nHashType);
// ... and merge in other signatures:
BOOST_FOREACH(const CTransaction& txv, txVariants)
{
txin.scriptSig = CombineSignatures(prevPubKey, mergedTx, i, txin.scriptSig, txv.vin[i].scriptSig);
}
if (!VerifyScript(txin.scriptSig, prevPubKey, mergedTx, i, 0))
fComplete = false;
}
Object result;
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << mergedTx;
result.push_back(Pair("hex", HexStr(ssTx.begin(), ssTx.end())));
result.push_back(Pair("complete", fComplete));
return result;
}
Value sendrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 1)
throw runtime_error(
"sendrawtransaction <hex string>\n"
"Submits raw transaction (serialized, hex-encoded) to local node and network.");
RPCTypeCheck(params, list_of(str_type));
// parse hex string from parameter
vector<unsigned char> txData(ParseHex(params[0].get_str()));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
CTransaction tx;
// deserialize binary data stream
try {
ssData >> tx;
}
catch (std::exception &e) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
}
uint256 hashTx = tx.GetHash();
// See if the transaction is already in a block
// or in the memory pool:
CTransaction existingTx;
uint256 hashBlock = 0;
if (GetTransaction(hashTx, existingTx, hashBlock))
{
if (hashBlock != 0)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("transaction already in block ")+hashBlock.GetHex());
// Not in block, but already in the memory pool; will drop
// through to re-relay it.
}
else
{
// push to local node
CTxDB txdb("r");
if (!tx.AcceptToMemoryPool(txdb))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX rejected");
SyncWithWallets(tx, NULL, true);
}
RelayTransaction(tx, hashTx);
return hashTx.GetHex();
}
| [
"voxpopulidev@yahoo.fr"
] | voxpopulidev@yahoo.fr |
b10c6a21e047ff1ca1249e3e34147fbd7be9eece | 093ac11d988780897665ba042eb357bbd0cb1b8e | /init/init_sec.cpp | 72befaba7566e687d78e55bb807e087daccc2807 | [] | no_license | SmatMan/android_device_samsung_universal7880-common | 30bcfd6b5352ac342b9d83c8236113587b5ddf7f | 86c9e0bc7b50eba0927f8cffb8774d53ecbe1951 | refs/heads/master | 2021-02-24T21:33:23.006007 | 2020-03-06T14:38:11 | 2020-03-06T14:38:11 | 245,442,109 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,918 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <android-base/logging.h>
#include <android-base/properties.h>
#define _REALLY_INCLUDE_SYS__SYSTEM_PROPERTIES_H_
#include <sys/_system_properties.h>
#include "property_service.h"
#include "vendor_init.h"
#include "init_sec.h"
#define MODEL_NAME_LEN 5 // e.g. "A520F"
#define BUILD_NAME_LEN 8 // e.g. "XXU2BQH4"
#define CODENAME_LEN 11 // e.g. "a5y17ltecan"
static void property_override(char const prop[], char const value[]) {
prop_info *pi;
pi = (prop_info*) __system_property_find(prop);
if (pi)
__system_property_update(pi, value, strlen(value));
else
__system_property_add(prop, strlen(prop), value, strlen(value));
}
void property_override_dual(char const system_prop[], char const vendor_prop[], char const value[])
{
property_override(system_prop, value);
property_override(vendor_prop, value);
}
void vendor_load_properties()
{
const std::string bootloader = android::base::GetProperty("ro.bootloader", "");
const std::string bl_model = bootloader.substr(0, MODEL_NAME_LEN);
const std::string bl_build = bootloader.substr(MODEL_NAME_LEN);
std::string model; // A520F
std::string device; // a5y17lte
std::string name; // a5y17ltexx
std::string description;
std::string fingerprint;
model = "SM-" + bl_model;
for (size_t i = 0; i < VARIANT_MAX; i++) {
std::string model_ = all_variants[i]->model;
if (model.compare(model_) == 0) {
device = all_variants[i]->codename;
break;
}
}
if (device.size() == 0) {
LOG(ERROR) << "Could not detect device, forcing a5y17lte";
device = "a5y17lte";
}
name = device + "xx";
description = name + "-user 7.0 NRD90M " + bl_model + bl_build + " release-keys";
fingerprint = "samsung/" + name + "/" + device + ":8.0.0/R16NW/" + bl_model + bl_build + ":user/release-keys";
LOG(INFO) << "Found bootloader: %s", bootloader.c_str();
LOG(INFO) << "Setting ro.product.model: %s", model.c_str();
LOG(INFO) << "Setting ro.product.device: %s", device.c_str();
LOG(INFO) << "Setting ro.product.name: %s", name.c_str();
LOG(INFO) << "Setting ro.build.product: %s", device.c_str();
LOG(INFO) << "Setting ro.build.description: %s", description.c_str();
LOG(INFO) << "Setting ro.build.fingerprint: %s", fingerprint.c_str();
property_override_dual("ro.product.model", "ro.vendor.product.model", model.c_str());
property_override_dual("ro.product.device", "ro.vendor.product.device", device.c_str());
property_override_dual("ro.product.name", "ro.vendor.product.name", name.c_str());
property_override("ro.build.product", device.c_str());
property_override("ro.build.description", description.c_str());
property_override_dual("ro.build.fingerprint", "ro.vendor.build.fingerprint", fingerprint.c_str());
}
| [
"gamingajun10@gmail.com"
] | gamingajun10@gmail.com |
fc99a1e7da041c378f1bb703c4cb6bbd5b84f163 | 14bab044fc7c0b7c97a6198ce9173de2264141f7 | /source/fir/Types/ArrayType.cpp | e0f574592292ce93650f9a67303cb57dc7be41dc | [
"Apache-2.0"
] | permissive | firecrackerz/flax | 462d458302600eba9805bf98b9256e99272d5173 | dc31d76ae6ac4b6702c1b0ca0232294a124bc386 | refs/heads/master | 2020-06-06T12:33:44.481296 | 2019-04-28T16:05:07 | 2019-04-28T16:05:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,319 | cpp | // Type.cpp
// Copyright (c) 2014 - 2016, zhiayang@gmail.com
// Licensed under the Apache License Version 2.0.
#include "ir/type.h"
namespace fir
{
ArrayType::ArrayType(Type* elm, size_t num) : Type(TypeKind::Array)
{
this->arrayElementType = elm;
this->arraySize = num;
}
ArrayType* ArrayType::get(Type* elementType, size_t num)
{
return TypeCache::get().getOrAddCachedType(new ArrayType(elementType, num));
}
std::string ArrayType::str()
{
return strprintf("[%s: %ld]", this->arrayElementType->str(), this->getArraySize());
}
std::string ArrayType::encodedStr()
{
return strprintf("[%s: %ld]", this->arrayElementType->encodedStr(), this->getArraySize());
}
bool ArrayType::isTypeEqual(Type* other)
{
if(other->kind != TypeKind::Array)
return false;
auto af = other->toArrayType();
return this->arrayElementType->isTypeEqual(af->arrayElementType) && (this->arraySize == af->arraySize);
}
// array stuff
Type* ArrayType::getElementType()
{
return this->arrayElementType;
}
size_t ArrayType::getArraySize()
{
return this->arraySize;
}
fir::Type* ArrayType::substitutePlaceholders(const util::hash_map<fir::Type*, fir::Type*>& subst)
{
return ArrayType::get(this->arrayElementType->substitutePlaceholders(subst), this->arraySize);
}
}
| [
"zhiayang@gmail.com"
] | zhiayang@gmail.com |
946c7f79040210323d3f2d37f45417eb8ec52697 | b01b8d2fd68d8af15758f3fc1bec1cefe61825e3 | /src/Face.h | d4e73270a52815fa1b26474e6965e5f0b2b5d3ea | [
"BSD-2-Clause"
] | permissive | danheeks/HeeksCAM | 5989cafc832880154033617354578c40306cacde | eb54f5c402effd74aa97fee4041ab303bafd1a7e | refs/heads/master | 2020-12-29T02:24:59.490386 | 2018-10-11T12:40:18 | 2018-10-11T12:40:18 | 32,216,858 | 6 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 2,928 | h | // Face.h
// Copyright (c) 2009, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.
#pragma once
class CEdge;
class CLoop;
class CShape;
class CNurbSurfaceParams;
class CFace:public HeeksObj{
private:
TopoDS_Face m_topods_face;
#if _DEBUG
double m_pos_x;
double m_pos_y;
double m_pos_z;
double m_normal_x;
double m_normal_y;
double m_normal_z;
bool m_orientation;
#endif
int m_marking_gl_list; // simply has material commands, inserted in the parent body's display list
public:
CBox m_box;
int m_temp_attr; // not saved with the model
std::list<CEdge*>::iterator m_edgeIt;
std::list<CEdge*> m_edges;
std::list<CLoop*>::iterator m_loopIt;
std::list<CLoop*> m_loops;
CFace();
CFace(const TopoDS_Face &face);
~CFace();
int GetType()const{return FaceType;}
long GetMarkingMask()const{return MARKING_FILTER_FACE;}
void glCommands(bool select, bool marked, bool no_color);
void GetBox(CBox &box);
const wxBitmap &GetIcon();
HeeksObj *MakeACopy(void)const{ return new CFace(*this);}
const wxChar* GetTypeString(void)const{return _("Face");}
void GetTriangles(void(*callbackfunc)(const double* x, const double* n), double cusp, bool just_one_average_normal = false);
double Area()const;
void ModifyByMatrix(const double* m);
void WriteXML(TiXmlNode *root);
void GetProperties(std::list<Property *> *list);
bool UsesID(){return true;}
void GetTools(std::list<Tool*>* t_list, const wxPoint* p);
void GetGripperPositionsTransformed(std::list<GripData> *list, bool just_for_endof);
const TopoDS_Face &Face(){return m_topods_face;}
gp_Dir GetMiddleNormal(gp_Pnt *pos = NULL)const;
gp_Dir GetNormalAtUV(double u, double v, gp_Pnt *pos = NULL)const;
bool GetUVAtPoint(const gp_Pnt &pos, double *u, double *v)const;
bool GetClosestPoint(const gp_Pnt &pos, gp_Pnt &closest_pnt)const;
bool GetClosestSurfacePoint(const gp_Pnt &pos, gp_Pnt &closest_pnt)const;
void GetPlaneParams(gp_Pln &p);
void GetCylinderParams(gp_Cylinder &c);
void GetSphereParams(gp_Sphere &s);
void GetConeParams(gp_Cone &c);
void GetTorusParams(gp_Torus &t);
bool GetNurbSurfaceParams(CNurbSurfaceParams* params);
int GetSurfaceType();
bool IsAPlane(gp_Pln *returned_plane);
wxString GetSurfaceTypeStr();
CEdge* GetFirstEdge();
CEdge* GetNextEdge();
CLoop* GetFirstLoop();
CLoop* GetNextLoop();
bool Orientation();
void GetUVBox(double *uv_box);
void GetSurfaceUVPeriod(double *uv, bool *isUPeriodic, bool *isVPeriodic);
CShape* GetParentBody();
void MakeSureMarkingGLListExists();
void KillMarkingGLList();
void UpdateMarkingGLList(bool marked, bool no_color);
};
class FaceToSketchTool:public Tool
{
public:
const wxChar* GetTitle(){return _("Make a sketch from face");}
wxString BitmapPath(){return _T("face2sketch");}
void Run();
static double deviation;
};
| [
"danheeks@gmail.com"
] | danheeks@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.