blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 247 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2 values | repo_name stringlengths 4 111 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 58 | visit_date timestamp[ns]date 2015-07-25 18:16:41 2023-09-06 10:45:08 | revision_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | committer_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | github_id int64 3.89k 689M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 25 values | gha_event_created_at timestamp[ns]date 2012-06-07 00:51:45 2023-09-14 21:58:52 ⌀ | gha_created_at timestamp[ns]date 2008-03-27 23:40:48 2023-08-24 19:49:39 ⌀ | gha_language stringclasses 159 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 7 10.5M | extension stringclasses 111 values | filename stringlengths 1 195 | text stringlengths 7 10.5M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c51453f8db01038fd8d53ef93e9dea32122949ea | 9426475939c7c7a02c6be8bb0845a655b7528735 | /CommandFactory.cpp | f82c9d16e889f8e6027292353d0590f97d8c3b19 | [] | no_license | ernezto/arduino-ci-monitor | 43729548af1a28f35d2ef21442703a321cf7bacb | 4c4ef6c28986f5c072af03a5d0808a30e03abd92 | refs/heads/master | 2016-09-03T01:12:06.837359 | 2014-03-14T15:35:31 | 2014-03-14T15:35:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,476 | cpp | CommandFactory.cpp | #include "CommandFactory.h"
#include "BrokenBuildCommand.h"
#include "PassedBuildCommand.h"
#include "StartingBuildCommand.h"
CommandFactory::CommandFactory(int red_light, int green_light, int blue_light, int buzzerPin, LiquidCrystal *lcd) {
_lcd = lcd;
_player = new Player(buzzerPin);
brokenBuild = new BrokenBuildCommand(_player, _lcd, red_light);
passedBuild = new PassedBuildCommand(_player, _lcd, green_light);
startingBuild = new StartingBuildCommand(_player, _lcd, blue_light);
}
Command *CommandFactory::getCommandFromString(String input) {
parseInput(input);
if (isPassedCommand()) return passedBuild;
if (isStartingCommand()) return startingBuild;
if (isBrokenCommand()) return brokenBuild;
return 0;
}
String CommandFactory::getPrintVersion() {
return (String)_command + "--/////--" + _text;
}
bool CommandFactory::isPassedCommand() {
passedBuild->setText(_text);
return _command == 1;
}
bool CommandFactory::isStartingCommand() {
startingBuild->setText(_text);
return _command == 2;
}
bool CommandFactory::isBrokenCommand() {
brokenBuild->setText(_text);
return _command == 3;
}
void CommandFactory::parseInput(String input) {
int colon = input.indexOf(":");
int comma = input.indexOf(",");
String commandText = input.substring(colon + 1, comma);
commandText.trim();
_command = commandText.toInt();
colon = input.lastIndexOf(":");
_text = input.substring(colon + 1, input.length());
_text.trim();
}
|
7f2ccd633c920307fa6c30df85fc8df7077893b2 | 967bcba49595cef66241d0ec6652be74dc6e86e5 | /Geometry/ccw.cpp | edfbf848ddc1de4e9409bdeff562b019c9fb2da7 | [] | no_license | mgood2/Algorithm | 668bb8d67d628b146c1a694586f7aa63d2316291 | cd1ddf0c422c6f2aac4e0c1e9605b83dee021c13 | refs/heads/master | 2021-01-19T17:00:25.880775 | 2017-07-30T08:11:35 | 2017-07-30T08:11:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 650 | cpp | ccw.cpp | // =====================================================================================
//
// Filename: ccw.cpp
// Created: 2017년 01월 15일 02시 56분 38초
// Compiler: g++ -O2 -std=c++14
// Author: baactree , bsj0206@naver.com
// Company: Chonnam National University
//
// =====================================================================================
//원점 기준 b가 a의 반시계 > 0, 시계 < 0, 평행 = 0
double ccw(point a, point b){
return a.cross(b);
}
//p 기준 b가 a의 반시계 > 0, 시계 < 0, 평행 = 0
double ccw(point p, point a, point b){
return ccw(a-p, b-p);
}
|
1f0b13ee5cac1fa2c848adc7dc0a9e95594cac10 | cf96c3961e5e0bb883945c41fb4227e2fa1ded0f | /shallow/details/BoundingBox.hpp | 50cf202b89c8acb620221b9b13747948f564a531 | [] | no_license | sabjohnso/shallow | 39afbed486ad2ac81ebea697a61008cfe804aebe | 54eeee508e03b603e40db3492ade69bdce232632 | refs/heads/master | 2022-11-28T09:37:37.465616 | 2020-08-07T01:00:18 | 2020-08-07T01:00:18 | 282,773,982 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 514 | hpp | BoundingBox.hpp | #pragma once
//
// ... Shalow header files
//
#include <shallow/details/Point.hpp>
namespace Shallow::Details
{
template<typename T>
class BoundingBox
{
public:
BoundingBox() = delete;
BoundingBox(Point<T> lower, Point<T> upper)
: lower{lower}
, upper{upper}
{}
const Point<T> lower;
const Point<T> upper;
}; // end of class BoundingBox
template<typename T>
BoundingBox(Point<T> lower, Point<T> upper) -> BoundingBox<T>;
} // end of namespace Shallow::Details
|
2e6bbb3cc0e02945d60d9c0c9cb8337ce4a3d3c0 | dcced388ee83ff57a270f115757f46bdf5bd3868 | /ezEnrollment/tools/atflib/include/atf/ExceptionLogger.h | 800d39865d7c17de2b73da82f74828bef5b5bb0d | [] | no_license | VB6Hobbyst7/vault_repo | a6aebc1dfd9f9f111b21829d92c5f8bdde80d068 | e6f074bfcf04c6a7598edd43f0cbef3ed4c50d01 | refs/heads/master | 2021-12-03T21:58:16.422079 | 2014-11-19T13:23:08 | 2014-11-19T13:23:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,085 | h | ExceptionLogger.h | /*
* $RCSfile: ExceptionLogger.h,v $
*
* $Revision: 1.2 $
*
* last change: $Date: 2003/09/05 07:18:17 $
*/
// TagExceptionLogger.h: interface for the CTagExceptionLogger class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_TAGEXCEPTIONLOGGER_H__EE2DCA14_1802_49E2_980E_5CE93ABACD5C__INCLUDED_)
#define AFX_TAGEXCEPTIONLOGGER_H__EE2DCA14_1802_49E2_980E_5CE93ABACD5C__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class ILogger;
class CAtfException;
class CSystemException;
class CAssertException;
class CCfgException;
class CXmlLoadException;
class CExceptionLogger{
public:
static void Log(ILogger &logger, const CAtfException &ex);
static void Log(ILogger &logger, const CSystemException &ex);
static void Log(ILogger &logger, const CAssertException &ex);
static void Log(ILogger &logger, const CCfgException &ex);
static void Log(ILogger &logger, const CXmlLoadException &ex);
};
#endif // !defined(AFX_TAGEXCEPTIONLOGGER_H__EE2DCA14_1802_49E2_980E_5CE93ABACD5C__INCLUDED_)
|
d02dc1529ca2877ebd859b392154fcfc9b94fcae | 0019f0af5518efe2144b6c0e63a89e3bd2bdb597 | /antares/src/apps/networkstatus/NetworkStatusWindow.h | 26e2cd2115b450f8cb9dc01a70cb288251e43398 | [] | no_license | mmanley/Antares | 5ededcbdf09ef725e6800c45bafd982b269137b1 | d35f39c12a0a62336040efad7540c8c5bce9678a | refs/heads/master | 2020-06-02T22:28:26.722064 | 2010-03-08T21:51:31 | 2010-03-08T21:51:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 446 | h | NetworkStatusWindow.h | /*
* Copyright 2006-2007, Antares, Inc. All Rights Reserved.
* Distributed under the terms of the MIT License.
*
* Authors:
* Axel Dörfler, axeld@pinc-software.de
*/
#ifndef NETWORK_STATUS_WINDOW_H
#define NETWORK_STATUS_WINDOW_H
#include <Window.h>
class NetworkStatusWindow : public BWindow {
public:
NetworkStatusWindow();
virtual ~NetworkStatusWindow();
virtual bool QuitRequested();
};
#endif // NETWORK_STATUS_WINDOW_H
|
91667a5f2b9f5b04077de5bad09e61c34694d76b | 6063111e01bde568104c2113f2fa59884f600ae6 | /cluster_extractor/src/cluster.cpp | 8f0845ec1182e3f3b194ae8c433386d87d1e4a66 | [] | no_license | ajanani85/laser_analysis | 7de061ff1a860fc29f37d2d7bd5275761a52f6c5 | df40cfba596ec83e5d8226629335019662a8c5e8 | refs/heads/master | 2021-08-08T11:30:11.292140 | 2017-11-10T07:30:02 | 2017-11-10T07:30:02 | 108,410,583 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,660 | cpp | cluster.cpp | #include<ros/ros.h>
#include<cluster_extractor/cluster.h>
#include<sensor_msgs/PointCloud.h>
#include<utility>
#include<math.h>
#include<vector>
using namespace std;
Cluster::Cluster()
{
}
Cluster::~Cluster()
{
}
void Cluster::addMember(geometry_msgs::Point32 p)
{
members.points.push_back(p);
sum_x += p.x;
sum_y += p.y;
sum_x2 += p.x * p.x;
sum_y2 += p.y * p.y;
sum_xy += p.x * p.y;
}
void Cluster::getMembers(sensor_msgs::PointCloud &p)
{
p = members;
}
size_t Cluster::size()
{
return members.points.size();
}
pair<double, double> Cluster::getTrend()
{
x_bar = sum_x / members.points.size();
y_bar = sum_y / members.points.size();
slope = (sum_xy - y_bar * sum_x - x_bar * sum_y + members.points.size() * x_bar * y_bar) / (sum_x2 - 2 * x_bar * sum_x + members.points.size() * x_bar * x_bar);
y_intercept = y_bar - slope * x_bar;
// slope = (sum_xy - x_bar * sum_y - y_bar * sum_x + members.size() * y_bar * x_bar) / (sum_y2 - 2 * y_bar * sum_y + members.size() * y_bar * y_bar);
// y_intercept = x_bar - slope * y_bar;
angle_with_x_axis = (atan(slope) * 180.0 / M_PI) + 90.0;
return std::make_pair(slope, y_intercept);
}
void Cluster::clear()
{
members.points.clear();
slope = 0.0;
y_intercept = 0.0;
x_bar = 0.0;
y_bar = 0.0;
sum_x = 0.0;
sum_y = 0.0;
sum_x2 = 0.0;
sum_xy = 0.0;
leftBound = 0;
rightBound = 0;
distanceToLeftCluster = 0.0;
distanceToRightCluster = 0.0;
}
double Cluster::getSlope()
{
return slope;
}
double Cluster::getYIntercept()
{
return y_intercept;
}
double Cluster::getAngleWithXAxis()
{
return angle_with_x_axis;
}
|
51b0e475debc9d0dbce904a5027e146ab97c4c11 | 95a43c10c75b16595c30bdf6db4a1c2af2e4765d | /codecrawler/_code/hdu1861/16209388.cpp | 13d029f2e60f78ccb44d40ecbf2a1cd480c3e099 | [] | no_license | kunhuicho/crawl-tools | 945e8c40261dfa51fb13088163f0a7bece85fc9d | 8eb8c4192d39919c64b84e0a817c65da0effad2d | refs/heads/master | 2021-01-21T01:05:54.638395 | 2016-08-28T17:01:37 | 2016-08-28T17:01:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,315 | cpp | 16209388.cpp | //hdu_1861
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
typedef struct _rent
{
int cnt;
int stim;
int etim;
int ttim;
bool flag;
}rent;
rent rt[101];
int main()
{
// freopen("input.in", "r", stdin);
int bnum, i, ttime, cnt;
char op;
int timh, timm;
memset(rt, 0, sizeof(rt));
while(scanf("%d", &bnum)!=EOF){
if(bnum == -1)break;
if(bnum == 0){
scanf(" %c %d:%d", &op, &timh, &timm);
ttime = cnt = 0;
for(i = 1; i < 101; i ++){
cnt += rt[i].cnt;
ttime += rt[i].ttim;
}
printf(ttime == 0 ? "0 0\n" : "%d %d\n", cnt,
(int)(1.0*ttime / cnt + 0.5));
memset(rt, 0, sizeof(rt));
}
else{
scanf(" %c %d:%d", &op, &timh, &timm);
if(op == 'S'){
rt[bnum].stim = timh*60 + timm;
rt[bnum].flag = 1;
}
if(op == 'E'){
rt[bnum].etim = timh * 60 + timm;
if(rt[bnum].flag != 0){
rt[bnum].cnt ++;
rt[bnum].ttim += rt[bnum].etim - rt[bnum].stim;
rt[bnum].flag = 1;
}
}
}
}
return 0;
}
|
b15ff63b2e094e5db711a57ba80a586f399cfac5 | 84161e06a39ed7357647ebfbed0cf2ef8f2f841a | /contest/1397/d/d.cpp | cb395b74c0c80af1964eb49db414f8fbc2ad48ed | [] | no_license | chachabai/cf | 7dee0a989c19a7abe96b439032c1ba898790fb80 | 069fad31f2e2a5bad250fe44bb982220d651b74a | refs/heads/master | 2022-12-30T09:16:30.876496 | 2020-10-20T06:39:15 | 2020-10-20T06:39:15 | 293,874,493 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 584 | cpp | d.cpp | #include <bits/stdc++.h>
#define watch(x) std::cout << (#x) << " is " << (x) << std::endl
#define print(x) std::cout << (x) << std::endl
using LL = long long;
int main() {
//freopen("in","r",stdin);
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
int cas;
std::cin >> cas;
while (cas--) {
int n;
std::cin >> n;
std::vector<int> a(n);
int s = 0;
for (auto &x : a) {
std::cin >> x;
s += x;
}
int mx = *std::max_element(a.begin(), a.end());
if (n == 1 || (s & 1 ) || s < 2 * mx) {
std::cout << "T\n";
} else std::cout << "HL\n";
}
return 0;
} |
c7a2c2829fc43592f4c61e4b64eb91c0626dc20e | 1edca9aee917e444eb7317a930bcb6d1f1ea4c09 | /Filter/factory.h | 5d342b4d3269ff2374af0e70c2134c083e497d37 | [] | no_license | VitalyGrachev/Nsu-computer-graphics | cd17041cb53389d0125edb5f2d6bc15c212ae39f | 13c33506e7ec4069d61aed1098eaca4668bb976e | refs/heads/master | 2021-01-25T04:16:08.978422 | 2018-10-11T15:51:52 | 2018-10-11T15:51:52 | 93,420,905 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,539 | h | factory.h | #ifndef FACTORY_H
#define FACTORY_H
#include <map>
template<class ID, class PRODUCT>
class Factory {
public:
PRODUCT * create(const ID & id) const;
template<class T>
bool register_type(const ID & id);
static Factory & instance()
{
static Factory f;
return f;
}
private:
Factory() {}
Factory(const Factory &) = delete;
Factory(const Factory &&) = delete;
~Factory();
Factory & operator=(const Factory &) = delete;
Factory & operator=(const Factory &&) = delete;
class BaseCreator {
public:
virtual ~BaseCreator() {}
virtual PRODUCT * operator()() = 0;
};
template<class T>
class DefaultCreator : public BaseCreator {
public:
~DefaultCreator() {}
PRODUCT * operator()() override {
return new T();
}
};
std::map<ID, BaseCreator *> creators;
};
template<class ID, class PRODUCT>
Factory<ID, PRODUCT>::~Factory() {
for (auto & value : creators) {
delete value.second;
}
}
template<class ID, class PRODUCT>
PRODUCT * Factory<ID, PRODUCT>::create(const ID & id) const {
auto creator = creators.find(id);
if (creator != creators.end()) {
return creator->second->operator()();
}
return nullptr;
}
template<class ID, class PRODUCT>
template<class T>
bool Factory<ID, PRODUCT>::register_type(const ID & id) {
BaseCreator * creator = new DefaultCreator<T>();
creators.insert(std::make_pair(id, creator));
return true;
};
#endif //FACTORY_H
|
2614fd7d6d72b61314987c0931b7d078cbeb3684 | 973d723394437d646d0f27f6edd5c4860ee1fd63 | /dsaac/1_C++_Review.hpp | 532e17b5c5b7dab03f38c09f213058fefebc57e6 | [] | no_license | 333mhz/learncpp | a4ffcb4f8baf140974776713b319e76e70075f06 | d2e875ff97b10d3a0c9da7f9aa0b6c389989cb9e | refs/heads/master | 2020-06-25T00:36:04.656244 | 2020-01-19T00:21:12 | 2020-01-19T00:21:12 | 199,141,405 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,140 | hpp | 1_C++_Review.hpp | #ifndef CXX_REVIEW
#define CXX_REVIEW
#include "stdafx.hpp"
//1-1
//1-2
template<class T>
int countvalue(T* a,int length, T value)
{
if(length < 1)
throw "Array length should be > 0";
int count=0;
for(int i = 0;i<length;++i)
{
if(a[i] == value)
++count;
}
return count;
}
//1-3
template<class T>
bool fillarray(T* a,int start,int end,const T& value)
{
bool bValue = true;
for(int i = start;i<end;++i)
{
a[i] = value;
if(a[i] != value)
bValue = false;
}
return bValue;
}
//1-4
template<class T>
T inner_product(T *a,T *b,int length)
{
T sum = 0;
for(int i = 0;i < length;++i)
sum += (a[i]+b[i]);
return sum;
}
//1-5
template<class T>
void iota(T* a,int length,const T& value)
{
for(int i = 0; i<length; ++i)
{
a[i] = value + i;
}
}
//1-6
template<class T>
bool is_sorted(T* a,int length)
{
bool bValue = false;
for(int i = 0;i < length-1; ++i)
if(a[i] < a [i+1] || a[i] == a [i+1])
{
bValue = true;
}
else
{
bValue = false;
break;
}
if(bValue)
return bValue;
for(int i = 0;i < length-1; ++i)
if(a[i] > a [i+1] || a[i] == a [i+1])
{
bValue = true;
}
else
{
bValue = false;
break;
}
return bValue;
}
//1-7
template<class T>
int mismatch(T* a, T* b, int n)
{// Return smallest i such that a[i] != b[i].
// Return n if no such i.
for (int i = 0; i < n; i++)
if (a[i] != b[i])
return i;
// no mismatch
return n;
}
//1-8
//1-9
//1-10
int abcthrow(int a,int b,int c)
{
if(a <= 0 || b <= 0 || c <= 0)
{
throw (a < 0 || b < 0 || c < 0)? 1 : 2;
}
return 0;
}
//1-11
//1-12
template<class T>
bool make2dArray(T ** &x, int d1, int d2)
{
try
{
//Create dimension 1st
x = new T* [d1];
//Create dimension 2nd
for(int i = 0;i < d1;++i)
x[i] = new T[d2];
return true;
}
catch(bad_alloc)
{
std::cerr << "Out of memory,fail to alloc 2D array" << '\n';
return false;
}
}
template<class T>
bool make2dArray(T ** &x, int d1, int* &d2)
{
try
{
//Create dimension 1st
x = new T* [d1];
//Create dimension 2nd
for(int i = 0;i < d1;++i)
x[i] = new T[d2[i]];
return true;
}
catch(bad_alloc)
{
std::cerr << "Out of memory,fail to alloc 2D array" << '\n';
return false;
}
}
//1-13
template<class T>
bool change1dLength(T * &x, int d1,int nd1)
{
if(nd1 < 0)
throw "illegalParameterValue: new length must be >= 0";
try
{
T* tmp = new T[nd1];
int n = min(d1,nd1);
//Create dimension 2nd
//for(int i = 0;i < n;++i)
// tmp[i] = x[i];
//delte[] x;
//x = tmp;
copy(x,x+n,tmp);
delete[] x;
x = tmp;
return true;
}
catch(bad_alloc)
{
std::cerr << "Out of memory,fail to change array 1d length" << '\n';
return false;
}
}
//1-14
template<class T>
bool change2dLength(T ** &x, int d1, int d2, int nd1 , int nd2)
{
if(nd1 < 0 || nd2 < 0)
throw "illegalParameterValue: new length must be >= 0";
try
{
T** tmp = new T* [nd1];
for(int i = 0;i < nd1; ++i)
tmp[i] = new T[nd2];
int n1 = min(d1,nd1);
int n2 = min(d2,nd2);
for(int i = 0;i < n1; ++i)
copy(x[i],x[i]+n2, tmp[i]);
for(int i = 0;i < d1;++i)
delete[] x[i];
delete[] x;
x = tmp;
return true;
}
catch(bad_alloc)
{
std::cerr << "Out of memory,fail to change array 1d length" << '\n';
return false;
}
}
//1-15
//(1)4bytes = 32 bits.2^32-1
//maxium = 2^32-1 dollars + 99 cents
//minium = -2^32-1 dollars + 99 cents
//(2)
//maxium = 2^31-1 dollars + 99 cents
//minium = -2^31-1 dollars + 99 cents
//(3)
//maxium = (2^31-1)/100
//1-16
enum signType{plus, minus};
/*
struct USD
{
USD()
{
m_sign = plus;
m_dollar = 0;
m_cent = 0;
}
signType m_sign;
unsigned long m_dollar;
unsigned int m_cent;
};
*/
class currency
{
friend istream& operator>>(ostream&,const currency&);
friend ostream& operator<<(ostream&,const currency&);
private:
signType m_sign;
unsigned long m_dollar;
unsigned int m_cent;
long amount;
public:
currency():m_sign(signType::plus), m_dollar(0), m_cent(0)
{ }
currency(signType s, unsigned long d, unsigned int c):m_sign(s), m_dollar(d), m_cent(c)
{ if(m_cent >100)
throw illegalParameterValue("Cents should be < 100");
if(m_sign == signType::plus)
amount = m_dollar*100+m_cent;
else
amount = -(m_dollar*100+m_cent);
}
~currency(){ }
void setValue(signType s, unsigned long d, unsigned int c)
{
if(c >=100)
throw illegalParameterValue("Cents should be < 100");
if(s == signType::plus)
amount = d*100+c;
else
amount = -(d*100+c);
}
void setValue(double);
signType getSign() const{
if(amount < 0) return signType::minus;
else return signType::plus;
}
unsigned long getDollars() const{
if(amount < 0 ) return (-amount)/100;
else return amount/100;
}
unsigned int getCents() const{
if(amount < 0) return (-amount)-getDollars()*100;
else return amount-getDollars()*100;
}
currency operator+(const currency& x) const{
currency result;
result.amount = this->amount + x.amount;
return result;
}
currency& operator+=(const currency& x){
this->amount += x.amount;return *this;
}
void output(ostream& out)const{
long theAmount = this->amount;
if(theAmount < 0){
out << '-';
theAmount = - this->amount;
}
long dollars = theAmount/100;
int cents = theAmount - dollars*100;
if(cents <10)
out <<'$'<<dollars<<".0"<<cents<<std::endl;
else
out <<'$'<<dollars<<'.'<<cents<<std::endl;
}
};
ostream& operator<<(ostream& out,const currency& x){
x.output(out); return out;
}
//recursive
int rFactorial(int n){
std::cout<<"In:"<<n<<std::endl;
if(n<=1){
std::cout<<"1.Fin"<<std::endl;
return 1;
}
else{
int r = n*rFactorial(n-1);
std::cout<<"Re:"<<r<<std::endl;
return r;
}
}
template<class T>
T rSum(T a[],int n){
if(n >0)
return rSum(a,n-1)+a[n-1];
return 0;
}
//1-32
template<class T>
void permutations(T list[],int k,int m)
{
if(k == m){
copy(list ,list + m+1,ostream_iterator<T>(cout,","));
std::cout << endl;
}
else{
for(int i = k; i<= m;i++)
{
swap(list[k],list[i]);
permutations(list,k+1,m);
swap(list[k],list[i]);
}
}
}
//1e19
//1 1 2 3 5 8 13 21 34 55
//f n =
int fib(int n)
{
if(n<=2)
{
return 1;
}
else {
return fib(n-1)+fib(n-2);
}
}
int isOddEven(int n)
{
if(n<=0)
return 0;
if(n%2 == 0)
{
return 2;
}
else if(isOddEven(3*n+1) == 2)
{
return 1;
}
return 0;
}
template<class T>
bool isFound(T* a, T x,int n)
{
if(n == 0)
return false;
else if(a[n-1] == x)
return true;
else
return isFound(a, x,n - 1);
}
//https://blog.csdn.net/a7055117a/article/details/48391923
//recursve????
template<class T>
int prtSubset(T *A, bool *B, int cur,int n)
{
if(B == NULL)
{
cout << "/0"<<endl;
B = new bool[n];
}
if(cur==n)//当设置完布尔数组内的全部元素后输出
{
for(int i = 0; i<n;i++)
{
if(B[i] == true)
cout << A[i];
}
cout << endl;
}
else
{
B[cur] = true;//选第cur个元素
prtSubset(A,B,cur + 1,n);
B[cur] = false;//不选第cur个元素
prtSubset(A,B,cur + 1,n);
}
return 0;
}
void prtSubsetB(bool *B,int n,int s)
{
if(B == NULL)
{
B = new bool[n];
}
if(s == n)//当设置完布尔数组内的全部元素后输出
{
for(int i = 0; i<n;i++)
{
if(B[i] == true)
cout << 1;
else
cout<<0;
}
cout << endl;
}
else
{
B[s] = true;//选第cur个元素
prtSubsetB(B,n,s + 1);
B[s] = false;//不选第cur个元素
prtSubsetB(B,n,s + 1);
}
return;
}
void prtSubsetB2(int n)//输出子集s包含的元素
{
for(int s=0;s<(1<<n);s++)
{
for(int i=0;i<n;i++)
{
//<<把一个整型数的所有位向左移动指定的位数,移动到左边界之外的多余二进制位会被丢弃,并从右边界移入0
if(s&(1<<i))//从最右侧开始遍历s中是否含有相应的元素
cout << 1;
else
cout << 0;
}
cout << endl;
}
}
void greyflip(int n)
{
if(n == 1)
cout << 1;
else
{
greyflip(n-1);
cout << n;
greyflip(n-1);
}
}
void greycode(int n)
{
}
//STL
template<typename T>
T sum(T a[], int n)
{
T tsum = 0;
return accumulate(a,a+n,tsum);
}
template<typename T>
T product(T a[],int n)
{
T theProduct = 1;
return accumulate(a,a+n,theProduct,multiplies<T>());
}
template<typename T>
void npermutations(T list[],int k,int m)
{
do{
copy(list ,list+m+1,ostream_iterator<T>(cout,""));
cout << endl;
}while (next_permutation(list,list+m+1));
}
#endif |
e65d08f4f15228b905330b01e8d6f4fe33c94168 | eb70adcfcc30ac8301341ccf72ec146de41a1665 | /src/tagsmanager.cpp | 6880433a73dce234fc8532e085a66cc254daf140 | [] | no_license | Beliaf/leechcraft | ff2166070913f2d7ee480f40542ccdf148e49cad | 0823a7d8f85d11bed0b81e61ddb3bf329f9d5d39 | refs/heads/master | 2021-01-18T11:00:38.531356 | 2009-06-14T22:44:13 | 2009-06-14T22:44:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,717 | cpp | tagsmanager.cpp | #include "tagsmanager.h"
#include <boost/bind.hpp>
#include <QStringList>
#include <QSettings>
#include <QtDebug>
#include <plugininterface/proxy.h>
#include <plugininterface/tagscompleter.h>
using namespace LeechCraft;
TagsManager::TagsManager ()
{
ReadSettings ();
GetID (tr ("untagged"));
LeechCraft::Util::TagsCompleter::SetModel (GetModel ());
}
TagsManager& TagsManager::Instance ()
{
static TagsManager tm;
return tm;
}
TagsManager::~TagsManager ()
{
}
int TagsManager::columnCount (const QModelIndex&) const
{
return 1;
}
QVariant TagsManager::data (const QModelIndex& index, int role) const
{
if (!index.isValid () ||
role != Qt::DisplayRole)
return QVariant ();
TagsDictionary_t::const_iterator pos = Tags_.begin ();
std::advance (pos, index.row ());
return *pos;
}
QModelIndex TagsManager::index (int row, int column, const QModelIndex& parent) const
{
if (!hasIndex (row, column, parent))
return QModelIndex ();
return createIndex (row, column);
}
QModelIndex TagsManager::parent (const QModelIndex&) const
{
return QModelIndex ();
}
int TagsManager::rowCount (const QModelIndex& index) const
{
return index.isValid () ? 0 : Tags_.size ();
}
ITagsManager::tag_id TagsManager::GetID (const QString& tag)
{
QList<QUuid> keys = Tags_.keys (tag);
if (keys.isEmpty ())
return InsertTag (tag);
else if (keys.size () > 1)
throw std::runtime_error (qPrintable (QString ("More than one key for %1").arg (tag)));
else
return keys.at (0).toString ();
}
QString TagsManager::GetTag (ITagsManager::tag_id id) const
{
return Tags_ [id];
}
QStringList TagsManager::Split (const QString& string) const
{
QStringList splitted = string.split (";", QString::SkipEmptyParts);
QStringList result;
Q_FOREACH (QString s, splitted)
result << s.trimmed ();
return result;
}
QString TagsManager::Join (const QStringList& tags) const
{
return tags.join ("; ");
}
ITagsManager::tag_id TagsManager::InsertTag (const QString& tag)
{
beginInsertRows (QModelIndex (), Tags_.size (), Tags_.size ());
QUuid uuid = QUuid::createUuid ();
Tags_ [uuid] = tag;
endInsertRows ();
WriteSettings ();
emit tagsUpdated (GetAllTags ());
return uuid.toString ();
}
void TagsManager::RemoveTag (const QModelIndex& index)
{
if (!index.isValid ())
return;
TagsDictionary_t::iterator pos = Tags_.begin ();
std::advance (pos, index.row ());
beginRemoveRows (QModelIndex (), index.row (), index.row ());
Tags_.erase (pos);
endRemoveRows ();
WriteSettings ();
emit tagsUpdated (GetAllTags ());
}
void TagsManager::SetTag (const QModelIndex& index, const QString& newTag)
{
if (!index.isValid ())
return;
TagsDictionary_t::iterator pos = Tags_.begin ();
std::advance (pos, index.row ());
*pos = newTag;
emit dataChanged (index, index);
WriteSettings ();
emit tagsUpdated (GetAllTags ());
}
QAbstractItemModel* TagsManager::GetModel ()
{
return this;
}
QStringList TagsManager::GetAllTags () const
{
QStringList result;
std::copy (Tags_.begin (), Tags_.end (),
std::back_inserter (result));
return result;
}
void TagsManager::ReadSettings ()
{
QSettings settings (Util::Proxy::Instance ()->GetOrganizationName (),
Util::Proxy::Instance ()->GetApplicationName ());
settings.beginGroup ("Tags");
Tags_ = settings.value ("Dict").value<TagsDictionary_t> ();
beginInsertRows (QModelIndex (), 0, Tags_.size () - 1);
endInsertRows ();
settings.endGroup ();
}
void TagsManager::WriteSettings () const
{
QSettings settings (Util::Proxy::Instance ()->GetOrganizationName (),
Util::Proxy::Instance ()->GetApplicationName ());
settings.beginGroup ("Tags");
settings.setValue ("Dict", QVariant::fromValue<TagsDictionary_t> (Tags_));
settings.endGroup ();
}
|
bf36b22bb2a04d8b326100250f552f34026619e6 | a4af8baee721e7c3610688a6e68586d839095c70 | /rtrim_ws.cpp | be897c7f14083d36b9da13e5684c6cdfc8231f1e | [] | no_license | timothyshull/cpp_scratchpad_old | 0b086916a6b93189d842f89806428976925ecc2b | f670085fa92b8cf4b911a522f88d75d7cc6a759b | refs/heads/master | 2021-01-22T20:34:31.008988 | 2017-03-17T15:52:41 | 2017-03-17T15:52:41 | 85,329,261 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 242 | cpp | rtrim_ws.cpp | #include<string>
#include<iostream>
#include"utility.h"
int main() {
std::string s = "zing ";
std::wstring ws = L"zong ";
rtrimws(s);
rtrimws(ws);
std::cout << s << "|\n";
std::wcout << ws << L"|\n";
return 0;
}
|
bbb7236b476eb7e4cc8a416e23ccd5e6f0944c5b | ebe7b84877fe669a097fec357fc54bf665be0b5a | /accelerated-cpp/ch0/chapter0Exercises.hpp | f2eff689e54c5b0f6934a283801fd7f9ed7ce7be | [] | no_license | treknuts/accelerated-cpp | 71d08c6c0dbdff9516c5ad08bf1a1a91f8fa9d23 | 9e4ddbc7b20675f3d76d3c5f55be62f884683003 | refs/heads/master | 2022-12-11T05:49:22.036039 | 2020-08-27T15:21:06 | 2020-08-27T15:21:06 | 283,932,175 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 356 | hpp | chapter0Exercises.hpp | //
// chapter0Exercises.hpp
// accelerated-cpp
//
// Created by Trevor Knutson on 7/30/20.
// Copyright © 2020 Trevor Knutson. All rights reserved.
//
#ifndef chapter0Exercises_hpp
#define chapter0Exercises_hpp
#include <stdio.h>
#endif /* chapter0Exercises_hpp */
namespace ch0 {
void helloWorld();
void escapeChars();
void tabs();
}
|
aac2e448beb4a5f169ddb6a6b44147f3c30aac03 | fe4eaed1d457379d262c8cc6537bf5fa428f430b | /1 - Introdução à linguagem C e C++/Questionário 1 sobre a linguagem C e C++/Lourdes Oshiro Igarashi/3.cpp | 484e226a95f09042fb768025c7047e915ae522ae | [
"MIT"
] | permissive | GOOOL-UFMS/Algoritmos-e-Programacao-II | 22b0b553960da1d9fa4a392e29b61e9bbd4ba7d9 | 153aab24c37f0a3895630e1ee6ec582e4fd6b96c | refs/heads/main | 2023-08-05T13:29:17.904649 | 2021-09-30T22:15:10 | 2021-09-30T22:15:10 | 395,465,727 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,137 | cpp | 3.cpp | /*
Projete e implemente um programa para calcular
o saldo da sua conta corrente.
Seu programa deve ler o saldo disponível,
a operação a ser realizada, (D) depósito ou (S) saque
e o valor da operação.O programa deve calcular
e imprimir o saldo após a operação.
O valor máximo a ser impresso é R$ +99999.99 ou R$ -99999.99.
O formato inclui uma posição para o sinal (+/-),
são 5 caracteres para a parte inteira,
uma posição para o ponto (.) e duas posições para a parte decimal.
No caso do usuário fornecer um código inválido, a operação não deve ser considerada.
A entrada é dada por um número real, um caractere e um número real,
representando o saldo, o código da operação e o valor da operação, respectivamente.
A saída consiste em imprimir para a operação de cálculo do saldo, o valor do saldo (com mensagens apropriadas).
Os valores do saldo devem ser impressos utilizando 10 espaços, sinal e com duas casas decimais (%+10.2f).
Considerando que o usuário pode entrar com uma letra minúscula para a operação,
transforme todos os caracteres lidos para maiúsculos
usando a função toupper da biblioteca ctype (toupper(a) == A).
Exemplo 1
10000.00 D 1000.99
Saldo atual: R$ +11000.99
Exemplo 2
10000.00 S 250.49
Saldo atual: R$ +9749.51
Exemplo 3
1000.00 C 500.00
Saldo atual: R$ +1000.00
Exemplo 4
5000.00 S 5000.01
Saldo atual: R$ -0.01
Exemplo 5
1000.00 D 9000.00
Saldo atual: R$ +10000.00
*/
#include <stdio.h>
#include <ctype.h>
int main()
{
double saldo, valor, saldoatual;
char operacao;
scanf("%lf", &saldo);
scanf(" %c", &operacao);
scanf("%lf", &valor);
operacao = toupper(operacao);
saldoatual = saldo;
if (operacao == 'D')
{
saldoatual = saldo + valor;
}
else{
if (operacao == 'S')
{
saldoatual = saldo - valor;
}
}
if (saldoatual >= 0){
printf("Saldo atual: R$ +%10.2f", saldoatual);
}
else{
printf("Saldo atual: R$ -%10.2f", saldoatual);
}
return 0;
}
|
7d0a0bd2062ff61b550b6bcb359eab9beefa6674 | 8d2ce459b5f03e2982ba764c5cc383b63f6b19c0 | /1281蹦蹦跳跳/1281.cpp | b10a0a56c9e0e3a398c6b80f9b71cfa16fac3fc4 | [] | no_license | elicassion/SJTU_OnlineJudge | 37a2eebdd4f1d41c23090be79e1771fb8a96bad4 | 532289168c782aca8444ff45764432c9863be2b3 | refs/heads/master | 2021-01-10T12:33:39.186794 | 2016-04-12T12:44:52 | 2016-04-12T12:44:52 | 36,080,058 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,844 | cpp | 1281.cpp | #include<iostream>
#include<fstream>
#include<iomanip>
#include<cstdlib>
#include<ctime>
#include<cstring>
#include<string>
#include<cmath>
#include<algorithm>
#include<cstdio>
#include<queue>
#include<stack>
#include<list>
#include<vector>
#include<set>
#include<map>
#define FOR(i,bg,ed) for(int i=bg;i<=ed;++i)
#define RFOR(i,bg,ed) for(int i=bg;i>=ed;--i)
#define FOR_S(i,bg,ed,step) for(int i=bg;i<=ed;i+=step)
#define RFOR_S(i,bg,ed,step) for(int i=bg;i>=ed;i-=step)
#define MSET(a,i) memset(a,i,sizeof(a))
#define CIa1(a,i) cin>>a[i]
#define CIa2(a,i,j) cin>>a[i][j]
#define COa1(a,i) cout<<a[i]<<' '
#define COa2(a,i,j) cout<<a[i][j]<<' '
#define SCIa1(a,i) scanf("%d",&a[i])
#define SCIa2(a,i,j) scanf("%d",&a[i][j])
#define SCOa1(a,i) printf("%d ",a[i])
#define SCOa2(a,i,j) printf("%d ",a[i][j])
#define RFF(s) freopen(s,"r",stdin)
#define WFF(s) freopen(s,"w",stdout)
#define LL long long int
#define SPACE printf(" ")
#define ENTER printf("\n")
using namespace std;
int M,N,M1,M2;
int bgx,bgy,edx,edy;
int dx[8];
int dy[8];
int a[60][60];
bool v[60][60]={0};
struct node{
int x;
int y;
int t;
};
queue<node> q;
void init_d()
{
dx[0]=-M1;
dx[1]=-M2;
dx[2]=-M2;
dx[3]=-M1;
dx[4]=M1;
dx[5]=M2;
dx[6]=M2;
dx[7]=M1;
dy[0]=-M2;
dy[1]=-M1;
dy[2]=M1;
dy[3]=M2;
dy[4]=M2;
dy[5]=M1;
dy[6]=-M1;
dy[7]=-M2;
/*FOR(i,0,7)
{
cout<<dx[i]<<' ';
}
cout<<endl;*/
}
void init_map()
{
FOR(i,1,M)
{
FOR(j,1,N)
{
CIa2(a,i,j);
if (a[i][j]==3)
{
bgx=i;bgy=j;
}
if (a[i][j]==4)
{
edx=i;edy=j;
}
}
}
}
void bfs()
{
node bg;
bg.x=bgx;bg.y=bgy;bg.t=0;
q.push(bg);
//cout<<bgx<<' '<<bgy<<endl;
//cout<<edx<<' '<<edy<<endl;
while(!q.empty())
{
int cx=q.front().x;
int cy=q.front().y;
int ct=q.front().t;
//cout<<cx<<' '<<cy<<' '<<ct<<endl;
//system("pause");
if (cx==edx && cy==edy)
{
cout<<ct<<endl;
return;
}
FOR(i,0,7)
{
int tx=cx+dx[i];
int ty=cy+dy[i];
if (tx<1 || tx>M || ty<1 || ty>N)
continue;
if (a[tx][ty]==1 && !v[tx][ty])
{
node nxt;
nxt.x=tx;
nxt.y=ty;
nxt.t=ct+1;
q.push(nxt);
v[tx][ty]=1;
}
else if (a[tx][ty]==4)
{
cout<<ct+1<<endl;
return;
}
}
if (!q.empty())
q.pop();
}
}
int main()
{
//RFF("1281.in");
cin>>M>>N>>M1>>M2;
init_d();
init_map();
bfs();
}
|
6b3e4acf370ab399c8934d2d9dfda5e492c6f1d9 | acc35c8382eff69dbfa109f857eae7ad715be121 | /task1/57.HshTable/Source.cpp | 321bcbdbb081f8b82d22c5d4eebdf8b83eb83e1a | [] | no_license | varya1441/Algorithms | bf74767cfa2297bfe90f6c1ac742250f8a656722 | 5725fa153b8106509dc0c5546bbb6a8ed932db98 | refs/heads/master | 2020-04-22T20:57:59.055308 | 2019-08-06T10:46:59 | 2019-08-06T10:46:59 | 170,657,962 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 657 | cpp | Source.cpp | #pragma warning(disable : 4996)
#include <stdio.h>
#include<iostream>
#include<numeric>
#include<algorithm>
#include<vector>
#include<map>
using namespace std;
long m, n, c, x;
//map<int,int>h;
vector <long>ht;
void f(long x) {
int j = 0;
int num;
while (true) {
num= ((x%m) + c * (j++)) % m;
if (ht[num] == -1) {
ht[num] = x;
return;
}
if (ht[num] == x) {
return;
}
}
}
int main()
{
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
cin >> m >> c >> n;
ht.resize(m, -1);
for (long i = 0; i < n; i++)
{
cin >> x;
f(x);
}
for (long i = 0; i < m; i++)
{
cout << ht[i]<<" ";
}
return 0;
} |
7d923349280e54d187aa8057b2c9c5156718deac | be635b55527f1a439d9b6d34dac281cb20f49f3d | /GLEngine/src/Base/Material.cpp | 8b771c475170844a6f5bc695c0ca194e1bbccceb | [] | no_license | xcxcmath/DVRstudy | a468f86815ed353a62a59325a985cb9bc2e43c25 | bd804543f65f0889ff9b7e3a25176a808f9d099a | refs/heads/master | 2020-07-30T05:50:31.848630 | 2019-10-08T07:59:01 | 2019-10-08T07:59:01 | 210,108,327 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 326 | cpp | Material.cpp | //
// Created by bjk on 19. 8. 3..
//
#include <GLEngine/Base/Material.hpp>
GLEngine::Material::Material()
: m_program(std::make_shared<GLEngine::Program>())
{
}
const std::shared_ptr<GLEngine::Program> &GLEngine::Material::getProgram() const noexcept {
return m_program;
}
GLEngine::Material::~Material() = default;
|
0f10d1d41f9bcc96c7824622d66ced4938a2d7ce | 447808a8134b89f6f199198da13dd110cf02c47b | /Ficha.h | 821d2c27b9ab3a13e9ea856ca016b67fe18e3d66 | [] | no_license | AlbertoCasasOrtiz/UCM-Informatica_grafica-Practica_1 | fb4b3bcbc4958f1a71a5c473b63bb62f10e6d7d9 | 3863cdb4de6921f8bbd88dc9d62d5c0395b9fdd3 | refs/heads/master | 2020-12-30T16:41:26.259392 | 2017-05-11T18:52:23 | 2017-05-11T18:52:23 | 91,013,244 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 3,708 | h | Ficha.h | #ifndef FICHA_H
#define FICHA_H
#include "Quesito.h"
#include "Malla.h"
class Ficha : public Malla{
private:
/*Número de vértces en el perfil.*/
const GLint numVerticesPerfil = 3;
/*Perfil que generará el tubo.*/
PV3D** perfil;
/*Crea el perfil.*/
void creaPerfil(GLfloat radio, GLfloat altura) {
this->perfil[0] = new PV3D(radio, 0.0, 0.0, 1);
this->perfil[1] = new PV3D(radio, altura, 0.0, 1);
this->perfil[2] = new PV3D(0.0, altura, 0.0, 1);
}
/*Número de fichas que forman el quesito.*/
const GLint NUM_FICHAS = 6;
public:
/*
Constructora de la clase Ficha.
nQ = número de lados de la parte curva de la ficha.
radio = radio de la ficha.
altura = altura de la ficha.
*/
Ficha(GLint nQ, GLint radio, GLint altura) {
GLfloat incr = 0;
/*Inicializamos malla y perfil.*/
Malla();
this->perfil = new PV3D*[this->numVerticesPerfil];
/*Creamos el perfil.*/
this->creaPerfil(radio, altura);
for (GLint i = 0; i < NUM_FICHAS; i++) {
/*Obtiene el color de la ficha*/
Color *color = this->getColorFicha(i);
/*Llamamos al método revolución, que generará los vértices y las caras.*/
this->revolución(this->perfil, this->numVerticesPerfil, nQ, radio, altura, incr, PI / 3 - 0.03, color);
/*Guardamos los últimos vértices generados.*/
GLint verticeUltimaArriba = this->getNumVertices() - 3;
GLint verticeUltimaAbajo = this->getNumVertices() - 2;
/*Ahora creamos las caras laterales.*/
/*Generamos los vértices centraes.*/
this->insertaVertice(0.0, altura, 0.0);
this->insertaVertice(0.0, 0.0, 0.0);
/*Cara lateral izquierda.*/
this->creaCara(4);
/*Se multiplica el número de vértices por nQ para no sobreescribir caras anteriores, y se resta 2 por las 2 que hemos añadido de vértices centrales.*/
this->insertaVerticeEnCara(this->getNumCaras() - 1, this->getNumVertices() - (nQ+1)*this->numVerticesPerfil - 2 + 1, this->getNumNormales());
this->insertaVerticeEnCara(this->getNumCaras() - 1, this->getNumVertices() - 2, this->getNumNormales());
this->insertaVerticeEnCara(this->getNumCaras() - 1, this->getNumVertices() - 1, this->getNumNormales());
this->insertaVerticeEnCara(this->getNumCaras() - 1, this->getNumVertices() - (nQ + 1)*this->numVerticesPerfil - 2, this->getNumNormales());
PV3D* v = this->CalculoVectorNormalPorNewell(this->getCara(this->getNumCaras() - 1));
this->insertaNormal(v->getX(), v->getY(), v->getZ());
this->insertaColor(color->getR(), color->getG(), color->getB());
/*Cara lateral derecha.*/
this->creaCara(4);
this->insertaVerticeEnCara(this->getNumCaras() - 1, verticeUltimaAbajo, this->getNumNormales());
this->insertaVerticeEnCara(this->getNumCaras() - 1, verticeUltimaArriba, this->getNumNormales());
this->insertaVerticeEnCara(this->getNumCaras() - 1, this->getNumVertices() - 1, this->getNumNormales());
this->insertaVerticeEnCara(this->getNumCaras() - 1, this->getNumVertices() - 2, this->getNumNormales());
v = this->CalculoVectorNormalPorNewell(this->getCara(this->getNumCaras() - 1));
this->insertaNormal(v->getX(), v->getY(), v->getZ());
this->insertaColor(color->getR(), color->getG(), color->getB());
/*El incremento para la posición del siguiente quesito.*/
incr += 2 * PI / 6;
}
}
/*Devuelve el color de cada una de las fichas.*/
Color* getColorFicha(GLint i) {
switch (i) {
case 0:
return new Color("cyan");
break;
case 1:
return new Color("brown");
break;
case 2:
return new Color("green");
break;
case 3:
return new Color("magenta");
break;
case 4:
return new Color("yellow");
break;
case 5:
return new Color("orange");
break;
}
}
};
#endif |
d48831b41778e94c017cd68272a63766bd326e14 | 8a7a6282c6a2fe94240b1ad896e879211f02b33b | /qutilities/trace-whois/traceroute.cpp | d39c1a3c20038b502976ccf140171efee1b93b03 | [] | no_license | mboyar/fundamentals | d580a3cca602c1610ef8e21d67189c0b74e972f1 | 6f424987c87772a9efa4334f00b223ea896caf01 | refs/heads/master | 2021-10-01T00:09:43.973368 | 2018-11-26T06:57:20 | 2018-11-26T06:57:20 | 115,797,216 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 314 | cpp | traceroute.cpp | #include "traceroute.h"
Traceroute::Traceroute(QObject *parent) : QObject(parent)
{
proc.setProgram("traceroute");
proc.setArguments(QStringList() << QCoreApplication::arguments().at(1));
proc.start();
proc.waitForFinished();
qDebug() << proc.readAll();
}
void Traceroute::readOutline()
{
}
|
bef342d537fdb26577eec6582ba85ff690495ce8 | 406b6f3e8355bcab9add96f3cff044823186fe37 | /src/poisson/cpu_parallel/parallel_data_octree.h | 7dd57e23c8f3967f78419a9a10a1e85e50ee3188 | [] | no_license | Micalson/puppet | 96fd02893f871c6bbe0abff235bf2b09f14fe5d9 | d51ed9ec2f2e4bf65dc5081a9d89d271cece28b5 | refs/heads/master | 2022-03-28T22:43:13.863185 | 2019-12-26T13:52:00 | 2019-12-26T13:52:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 707 | h | parallel_data_octree.h | #pragma once
#include "parallel_octree_nodes.h"
#include "parallel_octree_vertex.h"
#include "paralled_octree_edges.h"
#include "parallel_octree_faces.h"
class ParallelDataOctree
{
public:
ParallelDataOctree();
~ParallelDataOctree();
void SetParameters(int depth, float box_extend);
void BuildFromPoints(const std::vector<trimesh::vec3>& positions,
const std::vector<trimesh::vec3>& normals);
protected:
void BuildBoundingBox(const std::vector<trimesh::vec3>& positions);
private:
int m_depth;
float m_box_extend;
trimesh::box m_build_box;
trimesh::box m_real_box;
ParallelOctreeNodes m_nodes;
ParalledOctreeVertex m_vertexes;
ParalledOctreeEdges m_edges;
ParalledOctreeFaces m_faces;
};
|
23ba4bfb86df01d52678eb12619ec559e3b83d98 | 2b5fbd62812f10cfd41c37bb223bbaca8ce1dfe2 | /draft/random_split.hpp | bdbe030cb35ede263d7a8920f9851952a43d07c5 | [
"Apache-2.0"
] | permissive | Better-Idea/Mix-C | 5e6adaa2399cc94437a18d2962ebbca016bc6e71 | 71f34a5fc8c17a516cf99bc397289d046364a82e | refs/heads/master | 2021-12-10T04:59:17.280741 | 2021-09-30T13:36:05 | 2021-09-30T13:36:05 | 208,288,799 | 45 | 9 | Apache-2.0 | 2021-01-05T07:08:29 | 2019-09-13T15:06:16 | C++ | UTF-8 | C++ | false | false | 989 | hpp | random_split.hpp | #define xuser mixc::powerful_cat::inc
#include"math/random.hpp"
#include"interface/ranger.hpp"
namespace mixc::powerful_cat{
inline bstate_t random_split(inc::ranger<uxx> list, uxx total){
uxx length = list.length();
if (total < length or length == 0){
return bstate_t::fail;
}
uxx average = total / length;
uxx first = total - length * average;
for(uxx i = 1; i < length; i++){
list[i] = average;
}
list[0] = first;
for(uxx i = 0; i < length; i++){
uxx left = inc::random<uxx>() % length;
uxx right = inc::random<uxx>() % length;
uxx rest = list[left];
if (rest == 1){
continue;
}
uxx value = inc::random<uxx>() % (rest - 1) + 1;
list[left] -= value;
list[right]+= value;
}
return bstate_t::success;
}
} |
5156d62321b2f69c789977032e696de8156dcc93 | cd2687ef4ea9bd09c35fc437c14eae59ee85c360 | /HW4/GameShow/GameShow/Source.cpp | e267c524ab3041c206362d58ba7c6b4b4d5ca05e | [] | no_license | zacharyjung/CS-171 | 461ebe8fff23d92ef9910ad0a02d3043ba49d5aa | 5b6e62ef5e9028ccf86b43a03839c21ee8c2031e | refs/heads/master | 2020-04-02T03:41:05.113762 | 2016-07-08T03:47:50 | 2016-07-08T03:47:50 | 62,855,515 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,409 | cpp | Source.cpp | #include <iostream>
#include <string>
#include <cmath>
#include <ctime>
using namespace std;
void setupDoors(char &door1, char &door2, char &door3);
void result(char door1, char door2, char door3, int &doorPlayer);
void pickDoorChoices(char door1, char door2, char door3, int &doorPlayer, int &doorMonty);
void chart(double correct, double incorrect);
double correct=0, incorrect=0;//Global Variable so I don't need to return anything
/*This function is used to seed the rand() command and to call the setupDoors function 10,000 times. Then calls the chart function to display the percentages*/
void main()
{
int seed = static_cast<int>(time(0));
srand(seed);
int count = 0;
char door1='a', door2='a', door3='a';
do {
setupDoors(door1, door2, door3);
count++;
} while (count < 10000);
chart(correct, incorrect);
}
/* This function randomly generates where the location of where the car is behind and where the goats are*/
void setupDoors(char &door1, char &door2, char &door3)
{
int n,doorPlayer=0,doorMonty=0;
n = rand() % 3 + 1;
if (n == 1)
{
door1 = 'C';
door2 = 'G';
door3 = 'G';
}
else if (n == 2)
{
door1 = 'G';
door2 = 'C';
door3 = 'G';
}
else if (n == 3)
{
door1 = 'G';
door2 = 'G';
door3 = 'C';
}
pickDoorChoices(door1, door2, door3, doorPlayer, doorMonty);
}
/*This function randomly assigns the player a door. Then based on the door the player chooses Monty is randomly given a number which can't be the door the player
chooses or the door that has the car behind it*/
void pickDoorChoices(char door1, char door2, char door3, int &doorPlayer, int &doorMonty)
{
doorPlayer = rand() % 3 + 1;
if (door1 == 'C')
{
if (doorPlayer == 1)
{
doorMonty = rand() % 2 + 2;
}
if (doorPlayer == 2)
{
doorMonty = 3;
}
if (doorPlayer == 3)
{
doorMonty = 2;
}
}
else if (door2 == 'C')
{
if (doorPlayer == 1)
{
doorMonty = 3;
}
if (doorPlayer == 2)
{
do
{
doorMonty = rand() % 3 + 1;
} while (doorMonty == 2);
}
if (doorPlayer == 3)
{
doorMonty = 1;
}
}
else if (door3 == 'C')
{
if (doorPlayer == 1)
{
doorMonty = 2;
}
if (doorPlayer == 2)
{
doorMonty = 1;
}
if (doorPlayer == 3)
{
doorMonty = rand() % 2 + 1;
}
}
result(door1, door2, door3, doorPlayer);
}
/*This function counts the amount of correct and incorrect doors the user picked for all 10,000 times the game was played*/
void result(char door1, char door2, char door3, int &doorPlayer)
{
if (door1 == 'C'&&doorPlayer == 1)
{
correct++;
}
else if (door2 == 'C' && doorPlayer == 2)
{
correct++;
}
else if (door3 == 'C'&& doorPlayer == 3)
{
correct++;
}
else
{
incorrect++;
}
}
/*This function finds the percentages of the incorrect and correct doors selected when swapped and not swapped. Then it displays a chart of the percentages.*/
void chart(double correct, double incorrect)
{
double correctpercent, incorrectpercent;
correctpercent = (correct / 10000.0)*100.0;
incorrectpercent = (incorrect / 10000.0)*100.0;
cout << "Correct Percentage: " << correctpercent << "%"<<endl;
cout << "Incorrect Percentage: " << incorrectpercent<<"%" << endl;
cout << "Switched Correct Percentage: " << 100.0 - (correctpercent)<<"%" << endl;
cout << "Switched Incorrect Percentage: " << 100.0 - (incorrectpercent)<<"%" << endl;
char dummy;
cout << "Type in a character" << endl;
cin >> dummy;
} |
2901b9ca1e0b3a266fcdf1d14eedec261387f611 | 9cceb49420b9b53923e4c04c50bbb7c146a14064 | /NicoJK/TVTComment/IPC/IPCMessage/TimeIPCMessage.cpp | 3555d2d8ac3ab22e3faf407ce89a0a4cde4ee6d3 | [
"MIT"
] | permissive | flatomoya/TVTComment | fbe3810cb3d7b701c6e5407c5aadaa25f54219db | 12d4029da74be1b3054d10fa6b573e392042b222 | refs/heads/master | 2023-07-10T03:31:11.995992 | 2021-08-14T15:52:07 | 2021-08-14T15:52:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 396 | cpp | TimeIPCMessage.cpp | #include "stdafx.h"
#include "TimeIPCMessage.h"
namespace TVTComment
{
std::string TimeIPCMessage::GetMessageName() const
{
return u8"Time";
}
std::vector<std::string> TimeIPCMessage::Encode() const
{
return { std::to_string(this->Time) };
}
void TimeIPCMessage::Decode(const std::vector<std::string> &)
{
throw std::logic_error("TimeIPCMessage::Decode is not implemented");
}
} |
1a0c7e5a6f8df9f5abcc6b3dbeb12eeb9891cc6e | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/collectd/gumtree/collectd_repos_function_1726_last_repos.cpp | 94ca0f3238f427e498fd10bd7b7b782cabf517cd | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 177 | cpp | collectd_repos_function_1726_last_repos.cpp | static uint64_t ovs_uid_generate() {
uint64_t new_uid;
pthread_mutex_lock(&ovs_uid_mutex);
new_uid = ++ovs_uid;
pthread_mutex_unlock(&ovs_uid_mutex);
return new_uid;
} |
0980730fdb2facc777b5a0f3006b5eda0a4a899b | be9d60bc856095989a7eabb0b629f432cd062a67 | /4 сем/TA/67.2_3568/main.cpp | e221cb37192f91188d0d6edadf759c9090cd87b5 | [] | no_license | Viiktorias/2_course | 01682c9d172c61008ef8b3c49e97e378aa5eb192 | 26fd5fab667e37569436221765edfe49e1d6bd34 | refs/heads/master | 2022-01-29T12:12:40.682971 | 2019-08-07T13:36:56 | 2019-08-07T13:36:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,264 | cpp | main.cpp | #include <fstream>
#include <vector>
#include <stack>
using namespace std;
int isAll(vector<int> &metka, int n)
{
int i;
for (i = 0; ((i < n) && (metka[i] != 0)); i++)
{
}
return i;
}
int main()
{
ifstream fin("input.txt");
int n;
fin >> n;
int curmetka = 1;
vector<vector<int>> matrix(n, vector<int>(n));
vector<int> metka(n, 0);
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < n; ++j)
{
fin >> matrix[i][j];
}
}
fin.close();
stack<int> stack;
int i = 0;
while (i != n)
{
stack.push(i);
while (!stack.empty())
{
int cur = stack.top();
stack.pop();
if (metka[cur] == 0)
{
metka[cur] = curmetka;
curmetka++;
for (int j = n - 1; j > -1; --j)
{
if ((matrix[cur][j] == 1) && (metka[j] == 0))
{
stack.push(j);
}
}
}
}
i = isAll(metka, n);
}
ofstream fout("output.txt");
for (int j = 0; j < n; ++j)
{
fout << metka[j] << " ";
}
fout.close();
return 0;
} |
8c4f7db38ca78de78c3b670249dbfb21296e9877 | b3cdbc27a122f122b62ce8f7430a21108b2a5c0e | /tracetable.h | 93a6e7e654fa4375b262de8a7c95796b12580586 | [] | no_license | lyro41/Calculator | 1a82252cea4a756aeccec347361e09c1058e446c | 0535d8a1a7361dac8c1855fee8a8f02ee3196919 | refs/heads/master | 2021-10-26T09:56:34.005067 | 2019-04-11T20:01:18 | 2019-04-11T20:01:18 | 180,868,480 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 891 | h | tracetable.h | #ifndef TRACETABLE_H
#define TRACETABLE_H
#include <QDialog>
#include <QStandardItemModel>
#include <vector>
#include <string>
#include <algorithm>
typedef unsigned long long ull;
extern void stoull_list(std::string field, std::vector<ull> &list);
extern void command_separate(std::string field, std::vector<ull> &add, std::vector<ull> &mult, std::vector<ull> &pow);
extern ull calculate(ull start, ull final, std::vector<ull> &exceptions, std::vector<ull> &checkpoints, std::vector<ull> &add, std::vector<ull> &mult);
extern int getColumnQuantity(ull &start, ull &final);
namespace Ui {
class TraceTable;
}
class TraceTable : public QDialog
{
Q_OBJECT
public:
explicit TraceTable(QWidget *parent = nullptr, int columns = 1, ull start = 1, ull final = 1);
~TraceTable();
private:
Ui::TraceTable *ui;
QStandardItemModel *model;
};
#endif // TRACETABLE_H
|
178bd57c570c99c7097f10b89c5efe3fbc1f53b5 | d274817dac1dcff8cbe4e1651ab31efcfd658a83 | /include/boo2/inputdev/DeviceSignature.hpp | 0198347b2e741d838c97ef623c7fedb4d5e1e1ce | [
"MIT"
] | permissive | AxioDL/boo2 | 9574999af8fafb9ba884b6f789b8ca52e4cfd371 | c49c028a38b12746ca60c0db6dd7a25d85851856 | refs/heads/master | 2021-04-12T17:15:44.915086 | 2020-10-21T04:53:57 | 2020-10-21T04:53:57 | 249,095,732 | 0 | 2 | NOASSERTION | 2022-11-16T04:51:33 | 2020-03-22T02:02:33 | C++ | UTF-8 | C++ | false | false | 1,653 | hpp | DeviceSignature.hpp | #pragma once
#include <cstdint>
#include <functional>
#include <memory>
#include <string>
#include <typeindex>
#include <vector>
namespace boo2 {
enum class DeviceType { None = 0, USB = 1, Bluetooth = 2, HID = 3, XInput = 4 };
class DeviceToken;
class DeviceBase;
#define dev_typeid(type) std::hash<std::string>()(#type)
struct DeviceSignature {
using TDeviceSignatureSet = std::vector<const DeviceSignature*>;
using TFactoryLambda = std::function<std::shared_ptr<DeviceBase>(DeviceToken*)>;
const char* m_name = nullptr;
uint64_t m_typeHash = 0;
unsigned m_vid = 0;
unsigned m_pid = 0;
TFactoryLambda m_factory;
DeviceType m_type{};
DeviceSignature() : m_typeHash(dev_typeid(DeviceSignature)) {} /* Sentinel constructor */
DeviceSignature(const char* name, uint64_t typeHash, unsigned vid, unsigned pid, TFactoryLambda&& factory,
DeviceType type = DeviceType::None)
: m_name(name), m_typeHash(typeHash), m_vid(vid), m_pid(pid), m_factory(factory), m_type(type) {}
static bool DeviceMatchToken(const DeviceToken& token, const TDeviceSignatureSet& sigSet);
static std::shared_ptr<DeviceBase> DeviceNew(DeviceToken& token);
};
#define DEVICE_SIG(name, vid, pid, type) \
DeviceSignature(#name, dev_typeid(name), vid, pid, \
[](DeviceToken* tok) -> std::shared_ptr<DeviceBase> { return std::make_shared<name>(tok); }, type)
#define DEVICE_SIG_SENTINEL() DeviceSignature()
extern const DeviceSignature BOO_DEVICE_SIGS[];
} // namespace boo2 |
99b80167d26e8244f770c715a88a7f5c082bb5a8 | 8eb8b4b4fb59ba95ce6362a4adc55f44dee27b2c | /HolaOGRE/sinbad.h | 692d0ae45086b1f035a0170c4093e7f4b1f3b603 | [] | no_license | RockekScripts/IG-2-Ogre | 80cf6d61f81956dfd8c0cb669383218c21d43083 | cab18624912f83d7cfbb38bd3a48542451e49c08 | refs/heads/master | 2021-05-07T05:55:32.428890 | 2018-01-28T18:05:46 | 2018-01-28T18:05:46 | 111,676,460 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,001 | h | sinbad.h | #pragma once
#include <OgreInput.h>
#include <Ogre.h>
#include <vector>
#include "ObjectMan.h"
class sinbad : public OgreBites::InputListener,public ObjectMan
{
public:
sinbad(Ogre::SceneNode* scnMgr_);
~sinbad();
virtual bool keyPressed(const OgreBites::KeyboardEvent& evt);
//virtual bool mousePressed(const OgreBites::MouseButtonEvent & evt);
virtual void frameRendered(const Ogre::FrameEvent & evt);
virtual void interactua(const Ogre::String name);
enum estados {
quieto,corriendo, atacando, muerto
};
private:
estados estadoAct = corriendo;
Ogre::SceneNode* scnMgr = nullptr;
Ogre::Entity* ent;
Ogre::AnimationState* top;
Ogre::AnimationState* base;
Ogre::AnimationState* handle;
Ogre::AnimationState* dance;
Ogre::AnimationState* ataca;
Ogre::AnimationState* espadas;
Ogre::MovableObject* espadaL;
Ogre::MovableObject* espadaR;
Ogre::NodeAnimationTrack * track;
Ogre::TransformKeyFrame * kf;
Ogre::AnimationState * animationState;
Ogre::Vector3 keyframePos;
};
|
c8bc14e91b7545f8a96ae78d4dccbcfaf7d40793 | a7764174fb0351ea666faa9f3b5dfe304390a011 | /inc/StepBasic_ApprovalAssignment.hxx | 049f818d7d8e4d0623a9f1a930d04b2787a1ed79 | [] | no_license | uel-dataexchange/Opencascade_uel | f7123943e9d8124f4fa67579e3cd3f85cfe52d91 | 06ec93d238d3e3ea2881ff44ba8c21cf870435cd | refs/heads/master | 2022-11-16T07:40:30.837854 | 2020-07-08T01:56:37 | 2020-07-08T01:56:37 | 276,290,778 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,455 | hxx | StepBasic_ApprovalAssignment.hxx | // This file is generated by WOK (CPPExt).
// Please do not edit this file; modify original file instead.
// The copyright and license terms as defined for the original file apply to
// this header file considered to be the "object code" form of the original source.
#ifndef _StepBasic_ApprovalAssignment_HeaderFile
#define _StepBasic_ApprovalAssignment_HeaderFile
#ifndef _Standard_HeaderFile
#include <Standard.hxx>
#endif
#ifndef _Standard_DefineHandle_HeaderFile
#include <Standard_DefineHandle.hxx>
#endif
#ifndef _Handle_StepBasic_ApprovalAssignment_HeaderFile
#include <Handle_StepBasic_ApprovalAssignment.hxx>
#endif
#ifndef _Handle_StepBasic_Approval_HeaderFile
#include <Handle_StepBasic_Approval.hxx>
#endif
#ifndef _MMgt_TShared_HeaderFile
#include <MMgt_TShared.hxx>
#endif
class StepBasic_Approval;
class StepBasic_ApprovalAssignment : public MMgt_TShared {
public:
Standard_EXPORT virtual void Init(const Handle(StepBasic_Approval)& aAssignedApproval) ;
Standard_EXPORT void SetAssignedApproval(const Handle(StepBasic_Approval)& aAssignedApproval) ;
Standard_EXPORT Handle_StepBasic_Approval AssignedApproval() const;
DEFINE_STANDARD_RTTI(StepBasic_ApprovalAssignment)
protected:
private:
Handle_StepBasic_Approval assignedApproval;
};
// other Inline functions and methods (like "C++: function call" methods)
#endif
|
fe3996175e34ea3f3d1167582f34db4ef2e8b2cf | 6bba188d1bac735374fda6db8d6abe7798c2c17a | /project 2020/Smart irrigation/Water_level_relay_code/Water_level_relay_code.ino | 5fedc3cd4a162ae2e0f14df02a7cdc69ac6d316a | [
"MIT"
] | permissive | pankajdahilkar/FishPondMonetor | 7231b1890cad13bc1194f06668ae880a6dd1c3cf | 5ef1d10001606a9f6ea55415484b15bff663da79 | refs/heads/master | 2023-03-31T20:24:23.225896 | 2021-04-06T14:26:42 | 2021-04-06T14:26:42 | 277,061,107 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,341 | ino | Water_level_relay_code.ino | #include "DHT.h"
#include <LiquidCrystal.h>
#define ON 1
#define OFF 0
#define DHTPIN 2
#define DHTTYPE DHT11
const int rs = 3, en = 4, d4 = 5, d5 = 6, d6 = 7, d7 = 8;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
int incomingByte; // a variable to read incoming serial data into
unsigned long previousMillis = 0, previousMillis_D1 = 0, previousMillis_D2 = 0; // will store last time LED was updated
int water_level = 0;
// constants won't change:
const long interval = 1000; // interval at which to blink (milliseconds)
const long interval_Display = 2500; // interval at which to blink (milliseconds)
int trigPin = A4; // Trigger
int echoPin = A5; // Echo
long duration, cm, inches;
const int Valve_1 = 9;
const int Valve_2 = 10;
const int Valve_3 = 11;
const int Pump = 12;
char V1_FLAG = OFF;
char V2_FLAG = OFF;
char V3_FLAG = OFF;
char PUMP_FLAG = OFF;
DHT dht(DHTPIN, DHTTYPE);
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(Valve_1, OUTPUT);
pinMode(Valve_2, OUTPUT);
pinMode(Valve_3, OUTPUT);
pinMode(Pump, OUTPUT);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// set up the LCD's number of columns and rows:
dht.begin();
lcd.begin(16, 2);
lcd.clear();
lcd.setCursor(0, 0);
// Print a message to the LCD.
lcd.print("Irrigation");
lcd.setCursor(0, 1);
// Print a message to the LCD.
lcd.print("SCADA VIEW");
delay(200);
}
void loop() {
// put your main code here, to run repeatedly:
water_level_check();
check_valves();
Display_valve();
Update_sensors();
}
void Update_sensors()
{
unsigned long currentMillis = millis();
if (currentMillis - previousMillis_D2 >= 2000) {
previousMillis_D2 = currentMillis;
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
lcd.clear();
lcd.setCursor(0, 0);
// Print a message to the LCD.
lcd.print("Temp = ");
lcd.print(t);
lcd.print("*C");
lcd.setCursor(0, 1);
// Print a message to the LCD.
lcd.print("Humidity:");
lcd.print(h);
lcd.print("%");
Serial.print('T');
Serial.println(t);
Serial.print('H');
Serial.println(h);
}
}
void Display_valve()
{
unsigned long currentMillis = millis();
if (currentMillis - previousMillis_D1 >= interval_Display) {
// save the last time you blinked the LED
previousMillis_D1 = currentMillis;
lcd.clear();
lcd.setCursor(0, 0);
// Print a message to the LCD.
lcd.print("V1:");
if ( V1_FLAG == ON ) lcd.print("ON ");
else lcd.print("OFF");
lcd.print(" V2:");
if ( V2_FLAG == ON ) lcd.print("ON ");
else lcd.print("OFF");
lcd.setCursor(0, 1);
// Print a message to the LCD.
lcd.print("V3:");
if ( V3_FLAG == ON ) lcd.print("ON ");
else lcd.print("OFF");
lcd.print(" PUMP");
if ( PUMP_FLAG == ON ) lcd.print("ON ");
else lcd.print("OFF");
lcd.print("SCADA VIEW");
}
}
void water_level_check()
{
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
long dist = Get_Distance_ultrasonic();
int Most = analogRead(A3);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Water L = ");
lcd.print(dist);
lcd.print("*cm");
lcd.setCursor(0, 1);
lcd.print("Soil Moisture :");
lcd.print(Most / 10);
lcd.print("%");
water_level = water_level + 10;
Serial.print('W');
Serial.println(water_level);
Serial.print('M');
Serial.println(Most/10);
if (water_level > 99) {
water_level = 0;
delay(2000);
}
}
}
void check_valves()
{
if (Serial.available() > 0) {
// read the oldest byte in the serial buffer:
incomingByte = Serial.read();
switch (incomingByte)
{
case '1': {
digitalWrite(Valve_1, HIGH);
V1_FLAG = ON;
} break;
case'2': {
digitalWrite(Valve_1, LOW);
V1_FLAG = OFF;
} break;
case '3': {
digitalWrite(Valve_2, HIGH);
V2_FLAG = ON;
} break;
case'4': {
digitalWrite(Valve_2, LOW);
V2_FLAG = OFF;
} break;
case '5': {
digitalWrite(Valve_3, HIGH);
V3_FLAG = ON;
} break;
case'6': {
digitalWrite(Valve_3, LOW);
V3_FLAG = OFF;
} break;
case '7': {
digitalWrite(Pump, HIGH);
PUMP_FLAG = ON;
} break;
case'8': {
digitalWrite(Pump, LOW);
PUMP_FLAG = OFF;
} break;
default : 0;
}
}
}
long Get_Distance_ultrasonic()
{
// The sensor is triggered by a HIGH pulse of 10 or more microseconds.
// Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
digitalWrite(trigPin, LOW);
delayMicroseconds(5);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the signal from the sensor: a HIGH pulse whose
// duration is the time (in microseconds) from the sending
// of the ping to the reception of its echo off of an object.
pinMode(echoPin, INPUT);
duration = pulseIn(echoPin, HIGH);
// Convert the time into a distance
cm = (duration / 2) / 29.1; // Divide by 29.1 or multiply by 0.0343
return cm;
}
|
76052dfa6a1388b77ac851e1355607da3080eda9 | 293c244b17524210780b4fcb644c03d5cd6f1729 | /src/plugin/scripting/pythonlib/include/py_enum.hh | 0284e9668e66a7442fb5d97c1a20136eb6b424ac | [
"BSD-3-Clause"
] | permissive | bugengine/BugEngine | 380c0aee8ba48a07e5b820877352f922cbba0a21 | 1b3831d494ee06b0bd74a8227c939dd774b91226 | refs/heads/master | 2021-08-08T00:20:11.200535 | 2021-07-31T13:53:24 | 2021-07-31T13:53:24 | 20,094,089 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,106 | hh | py_enum.hh | /* BugEngine <bugengine.devel@gmail.com>
see LICENSE for detail */
#ifndef BE_PYTHONLIB_PY_ENUM_HH_
#define BE_PYTHONLIB_PY_ENUM_HH_
/**************************************************************************************************/
#include <bugengine/plugin.scripting.pythonlib/stdafx.h>
#include <py_object.hh>
namespace BugEngine { namespace Python {
struct PyBugEnum : public PyBugObject
{
static void registerType(PyObject* module);
static PyObject* stealValue(PyObject* owner, Meta::Value& value);
static PyObject* repr(PyObject* self);
static PyObject* str(PyObject* self);
static PyObject* toint(PyObject* self);
static PyObject* tolong(PyObject* self);
static PyObject* tofloat(PyObject* self);
static int nonZero(PyObject* self);
static PyTypeObject s_pyType;
static PyTypeObject::Py2NumberMethods s_py2EnumNumber;
static PyTypeObject::Py3NumberMethods s_py3EnumNumber;
};
}} // namespace BugEngine::Python
/**************************************************************************************************/
#endif
|
fad4c5462fda744c08c0e885d4b164a931d9ea4b | 100cd26be1c2196462814902190f3842c09e288f | /source/pkb/relationshipTables/NextTable.cpp | fe0938ed8a37f19cb53bdf66ad08a1e2f9bd924f | [] | no_license | brandonyeoxg/cs3201-simple-spa | bcb9f951d101311e4f92af66b780a083d11d3d96 | deb47a51bbeaaa22c20979cb1669bf4c61dd9361 | refs/heads/master | 2021-03-27T20:31:10.144994 | 2017-11-13T05:57:06 | 2017-11-13T05:57:06 | 101,005,221 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,980 | cpp | NextTable.cpp | #pragma once
#include "NextTable.h"
NextTable::NextTable() {
MAX_LINE_NUM = 0;
m_afterGraph = std::map<PROG_LINE, LIST_OF_PROG_LINES>();
m_beforeGraph = std::map<PROG_LINE, LIST_OF_PROG_LINES>();
}
void NextTable::insertNextRelationship(PROG_LINE t_line1, PROG_LINE t_line2) {
if (MAX_LINE_NUM < t_line1 + 1) {
MAX_LINE_NUM = t_line1 + 1; // offset needed as program lines are 1-based indices
}
if (MAX_LINE_NUM < t_line2 + 1) {
MAX_LINE_NUM = t_line2 + 1;
}
// insert key if not present
if (!isKeyInMap(t_line1, m_afterGraph)) {
m_afterGraph.insert({ t_line1 , LIST_OF_PROG_LINES() });
}
if (!isKeyInMap(t_line2, m_beforeGraph)) {
m_beforeGraph.insert({ t_line2 , LIST_OF_PROG_LINES() });
}
m_afterGraph.at(t_line1).push_back(t_line2);
m_beforeGraph.at(t_line2).push_back(t_line1);
}
void NextTable::executeAfterAllNextInserts() {
// initialize with max number of lines to easily set booleans at specified indices
m_isNextTable = std::vector<std::vector<bool>>(MAX_LINE_NUM, std::vector<bool>(MAX_LINE_NUM, false));
for (auto linePair : m_afterGraph) {
for (auto lineAfter : linePair.second) {
m_isNextTable.at(linePair.first).at(lineAfter) = true;
}
}
// sort each vector mapped to each program line
for (auto linePair : m_afterGraph) {
std::sort(linePair.second.begin(), linePair.second.end());
}
for (auto linePair : m_beforeGraph) {
std::sort(linePair.second.begin(), linePair.second.end());
}
}
bool NextTable::isNext(PROG_LINE t_line1, PROG_LINE t_line2) {
if (t_line1 >= MAX_LINE_NUM || t_line2 >= MAX_LINE_NUM) {
return false;
}
return m_isNextTable.at(t_line1).at(t_line2);
}
bool NextTable::isNextStar(PROG_LINE t_line1, PROG_LINE t_line2) {
// no path from line1 or no path to line2, immediately false
if (!isKeyInMap(t_line1, m_afterGraph) || !isKeyInMap(t_line2, m_beforeGraph)) {
return false;
}
// check Next() relationship first, faster termination if true
if (isNext(t_line1, t_line2)) {
return true;
}
return isTherePath(t_line1, t_line2);
}
LIST_OF_PROG_LINES NextTable::getLinesAfter(PROG_LINE t_line) {
if (isKeyInMap(t_line, m_afterGraph)) {
return m_afterGraph.at(t_line);
} else {
return {};
}
}
LIST_OF_PROG_LINES NextTable::getLinesBefore(PROG_LINE t_line) {
if (isKeyInMap(t_line, m_beforeGraph)) {
return m_beforeGraph.at(t_line);
} else {
return {};
}
}
LIST_OF_PROG_LINES NextTable::getAllLinesAfter(PROG_LINE t_line) {
return getListOfLinesReachable(t_line, m_afterGraph);
}
LIST_OF_PROG_LINES NextTable::getAllLinesBefore(PROG_LINE t_line) {
return getListOfLinesReachable(t_line, m_beforeGraph);
}
MAP_OF_PROG_LINE_TO_LIST_OF_PROG_LINES NextTable::getAllNext() {
MAP_OF_PROG_LINE_TO_LIST_OF_PROG_LINES map = MAP_OF_PROG_LINE_TO_LIST_OF_PROG_LINES();
map.insert(m_afterGraph.begin(), m_afterGraph.end());
return map;
}
MAP_OF_PROG_LINE_TO_LIST_OF_PROG_LINES NextTable::getAllNextStar() {
MAP_OF_PROG_LINE_TO_LIST_OF_PROG_LINES map = MAP_OF_PROG_LINE_TO_LIST_OF_PROG_LINES();
isCaching = true;
m_cacheVisited = MAP_OF_PROG_LINE_TO_LIST_OF_PROG_LINES();
for (auto reverseIter = m_afterGraph.rbegin(); reverseIter != m_afterGraph.rend(); reverseIter++) {
PROG_LINE progLine = reverseIter->first;
LIST_OF_PROG_LINES list;
//std::cout << "Checking: " << progLine << "\n";
list = getListOfLinesReachable(progLine, m_afterGraph);
if (!isKeyInMap(progLine, m_cacheVisited)) {
//std::cout << "Caching\n";
m_cacheVisited.insert({ progLine, list });
}
map.insert({ progLine , list });
}
isCaching = false;
m_cacheVisited.clear();
return map;
}
LIST_OF_PROG_LINES NextTable::getAllLinesAfterAnyLine() {
LIST_OF_PROG_LINES list = LIST_OF_PROG_LINES();
for (auto iter: m_beforeGraph) {
list.push_back(iter.first);
}
return list;
}
LIST_OF_PROG_LINES NextTable::getAllLinesBeforeAnyLine() {
LIST_OF_PROG_LINES list = LIST_OF_PROG_LINES();
for (auto iter : m_afterGraph) {
list.push_back(iter.first);
}
return list;
}
bool NextTable::hasNextRelationship() {
return m_afterGraph.size() > 0;
}
bool NextTable::hasNextLine(PROG_LINE t_line) {
return isKeyInMap(t_line, m_afterGraph) && m_afterGraph.at(t_line).size() != 0;
}
bool NextTable::hasLineBefore(PROG_LINE t_line) {
return isKeyInMap(t_line, m_beforeGraph) && m_beforeGraph.at(t_line).size() != 0;
}
const std::map<PROG_LINE, LIST_OF_PROG_LINES>* NextTable::getAfterGraph() {
return &m_afterGraph;
}
// depth first search
bool NextTable::isTherePath(PROG_LINE t_line1, PROG_LINE t_line2) {
std::vector<bool> visited = std::vector<bool>(MAX_LINE_NUM);
LIST_OF_PROG_LINES toVisit = LIST_OF_PROG_LINES();
for (auto nextLine : m_afterGraph.at(t_line1)) {
toVisit.push_back(nextLine);
}
while (!toVisit.empty()) {
PROG_LINE lineToVisit = toVisit.back(); // remove from stack
toVisit.pop_back();
visited.at(lineToVisit) = true;
if (lineToVisit == t_line2) { // return true once path is found
return true;
}
// has Next() lines to visit
if (isKeyInMap(lineToVisit, m_afterGraph)) {
for (auto nextLine : m_afterGraph.at(lineToVisit)) {
if (!visited.at(nextLine)) { // line not visited yet
toVisit.push_back(nextLine);
}
}
}
}
return false;
}
LIST_OF_PROG_LINES NextTable::getListOfLinesReachable(PROG_LINE t_line,
std::map<PROG_LINE, LIST_OF_PROG_LINES> t_graph) {
LIST_OF_PROG_LINES linesVisited = LIST_OF_PROG_LINES();
std::vector<bool> visited = std::vector<bool>(MAX_LINE_NUM);
if (isKeyInMap(t_line, t_graph)) {
for (auto lineToVisit : t_graph.at(t_line)) {
LIST_OF_PROG_LINES result = traverseGraphDfs(lineToVisit, t_graph, visited);
linesVisited.insert(linesVisited.end(), result.begin(), result.end());
}
}
return linesVisited;
}
LIST_OF_PROG_LINES NextTable::traverseGraphDfs(PROG_LINE t_line, std::map<PROG_LINE,
LIST_OF_PROG_LINES> t_graph, std::vector<bool>& visited) {
if (visited.at(t_line)) {
return{};
}
visited.at(t_line) = true;
LIST_OF_PROG_LINES linesVisited = LIST_OF_PROG_LINES();
linesVisited.push_back(t_line);
if (isKeyInMap(t_line, t_graph)) {
for (auto lineToVisit : t_graph.at(t_line)) {
if (!visited.at(lineToVisit)) {
LIST_OF_PROG_LINES result;
if (isCaching && isKeyInMap(t_line, m_cacheVisited)) {
//std::cout << "Taking from cache\n";
LIST_OF_PROG_LINES cached = m_cacheVisited.at(t_line);
for (auto line : cached) {
if (!visited.at(line)) {
result.push_back(line);
visited.at(line) = true;
}
}
} else {
result = traverseGraphDfs(lineToVisit, t_graph, visited);
}
linesVisited.insert(linesVisited.end(), result.begin(), result.end());
}
}
}
return linesVisited;
} |
7f96b1fa8def09b2aed870ff009cec0337340e2e | 25e90a9e57dfd488e531b049eca36d2f0f47a0ba | /cores/gba/src/platform/qt/utils.cpp | 1c16df9327fc9d489dc43299bc7d69efa74658ce | [
"MIT",
"LicenseRef-scancode-proprietary-license",
"LGPL-2.1-only",
"MPL-1.1",
"LicenseRef-scancode-mame",
"GPL-1.0-or-later",
"Zlib",
"GPL-2.0-only",
"LGPL-2.1-or-later",
"MPL-2.0",
"CC-PDDC",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-brian-gladman-3-clause",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"MPL-1.0"
] | permissive | Pandinosaurus/retro | b9a0df960083f0f0d6563f05e8d102e45afc1e98 | 094531b16221d9199c2e9b7913259ba448c57e37 | refs/heads/master | 2023-04-29T17:59:25.810054 | 2023-04-12T20:48:22 | 2023-04-12T20:48:22 | 221,809,513 | 0 | 0 | MIT | 2023-04-13T01:24:38 | 2019-11-15T00:11:40 | C | UTF-8 | C++ | false | false | 833 | cpp | utils.cpp | /* Copyright (c) 2013-2017 Jeffrey Pfau
*
* 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/. */
#include "utils.h"
#include <QObject>
namespace QGBA {
QString niceSizeFormat(size_t filesize) {
double size = filesize;
QString unit = "B";
if (size >= 1024.0) {
size /= 1024.0;
unit = "kiB";
}
if (size >= 1024.0) {
size /= 1024.0;
unit = "MiB";
}
return QString("%0 %1").arg(size, 0, 'f', 1).arg(unit);
}
QString nicePlatformFormat(mPlatform platform) {
switch (platform) {
#ifdef M_CORE_GBA
case PLATFORM_GBA:
return QObject::tr("GBA");
#endif
#ifdef M_CORE_GB
case PLATFORM_GB:
return QObject::tr("GB");
#endif
default:
return QObject::tr("?");
}
}
}
|
560b129f4afe842f0f9ba0b307a555159456c0ce | c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64 | /Engine/Source/Editor/IntroTutorials/Private/EditorTutorialImportFactory.cpp | 9b196e1c5e4dc11f2497accd3bd14b3f6c4d0df5 | [
"MIT",
"LicenseRef-scancode-proprietary-license"
] | permissive | windystrife/UnrealEngine_NVIDIAGameWorks | c3c7863083653caf1bc67d3ef104fb4b9f302e2a | b50e6338a7c5b26374d66306ebc7807541ff815e | refs/heads/4.18-GameWorks | 2023-03-11T02:50:08.471040 | 2022-01-13T20:50:29 | 2022-01-13T20:50:29 | 124,100,479 | 262 | 179 | MIT | 2022-12-16T05:36:38 | 2018-03-06T15:44:09 | C++ | UTF-8 | C++ | false | false | 5,609 | cpp | EditorTutorialImportFactory.cpp | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "EditorTutorialImportFactory.h"
#include "Misc/Paths.h"
#include "Engine/Blueprint.h"
#include "Engine/BlueprintGeneratedClass.h"
#include "EditorTutorial.h"
#include "Kismet2/KismetEditorUtilities.h"
#include "IDocumentationPage.h"
#include "IDocumentation.h"
#define LOCTEXT_NAMESPACE "UEditorTutorialImportFactory"
UEditorTutorialImportFactory::UEditorTutorialImportFactory(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
bEditorImport = true;
bEditAfterNew = true;
bText = false;
SupportedClass = UBlueprint::StaticClass();
Formats.Add(TEXT("udn;UDN documentation files"));
}
bool UEditorTutorialImportFactory::FactoryCanImport(const FString& Filename)
{
const FString DocDir = FPaths::ConvertRelativePathToFull(FPaths::EngineDir() / TEXT("Documentation/Source"));
FString NewPath = FPaths::ConvertRelativePathToFull(FPaths::GetPath(Filename));
FPaths::NormalizeFilename(NewPath);
return (NewPath.StartsWith(DocDir));
}
static bool GetDocumentationPath(FString& InOutFilePath)
{
const FString DocDir = FPaths::ConvertRelativePathToFull(FPaths::EngineDir() / TEXT("Documentation/Source"));
FString NewPath = FPaths::ConvertRelativePathToFull(FPaths::GetPath(InOutFilePath));
FPaths::NormalizeFilename(NewPath);
if(NewPath.StartsWith(DocDir))
{
InOutFilePath = NewPath.RightChop(DocDir.Len());
return true;
}
return false;
}
UObject* UEditorTutorialImportFactory::FactoryCreateBinary(UClass* InClass, UObject* InParent, FName InName, EObjectFlags Flags, UObject* Context, const TCHAR* Type, const uint8*& Buffer, const uint8* BufferEnd, FFeedbackContext* Warn)
{
UBlueprint* NewBlueprint = FKismetEditorUtilities::CreateBlueprint(UEditorTutorial::StaticClass(), InParent, InName, BPTYPE_Normal, UBlueprint::StaticClass(), UBlueprintGeneratedClass::StaticClass(), NAME_None);
FString PathToImport = GetCurrentFilename();
if(GetDocumentationPath(PathToImport))
{
UEditorTutorial* EditorTutorial = CastChecked<UEditorTutorial>(NewBlueprint->GeneratedClass->GetDefaultObject());
if(Import(EditorTutorial, PathToImport))
{
EditorTutorial->ImportPath = GetCurrentFilename();
}
}
return NewBlueprint;
}
bool UEditorTutorialImportFactory::CanReimport(UObject* Obj, TArray<FString>& OutFilenames)
{
UBlueprint* Blueprint = Cast<UBlueprint>(Obj);
if(Blueprint != nullptr && Blueprint->GeneratedClass)
{
UEditorTutorial* EditorTutorial = Cast<UEditorTutorial>(Blueprint->GeneratedClass->GetDefaultObject());
if(EditorTutorial != nullptr)
{
OutFilenames.Add(EditorTutorial->ImportPath);
return true;
}
}
return false;
}
void UEditorTutorialImportFactory::SetReimportPaths(UObject* Obj, const TArray<FString>& NewReimportPaths)
{
if(NewReimportPaths.Num() > 0)
{
UBlueprint* Blueprint = Cast<UBlueprint>(Obj);
if(Blueprint != nullptr)
{
UEditorTutorial* EditorTutorial = Cast<UEditorTutorial>(Blueprint->GeneratedClass->GetDefaultObject());
if(EditorTutorial != nullptr)
{
if(FactoryCanImport(NewReimportPaths[0]))
{
EditorTutorial->ImportPath = NewReimportPaths[0];
}
}
}
}
}
EReimportResult::Type UEditorTutorialImportFactory::Reimport(UObject* Obj)
{
UBlueprint* Blueprint = Cast<UBlueprint>(Obj);
if(Blueprint != nullptr)
{
UEditorTutorial* EditorTutorial = Cast<UEditorTutorial>(Blueprint->GeneratedClass->GetDefaultObject());
if(EditorTutorial != nullptr)
{
FString PathToImport = EditorTutorial->ImportPath;
if(GetDocumentationPath(PathToImport))
{
return Import(EditorTutorial, PathToImport) ? EReimportResult::Succeeded : EReimportResult::Failed;
}
}
}
return EReimportResult::Failed;
}
int32 UEditorTutorialImportFactory::GetPriority() const
{
return ImportPriority;
}
bool UEditorTutorialImportFactory::Import(UEditorTutorial* InTutorialToImportTo, const FString& InImportPath)
{
if(!InImportPath.IsEmpty() && InTutorialToImportTo != nullptr && IDocumentation::Get()->PageExists(InImportPath))
{
FDocumentationStyle DocumentationStyle;
DocumentationStyle
.ContentStyle(TEXT("Tutorials.Content.Text"))
.BoldContentStyle(TEXT("Tutorials.Content.TextBold"))
.NumberedContentStyle(TEXT("Tutorials.Content.Text"))
.Header1Style(TEXT("Tutorials.Content.HeaderText1"))
.Header2Style(TEXT("Tutorials.Content.HeaderText2"))
.HyperlinkStyle(TEXT("Tutorials.Content.Hyperlink"))
.HyperlinkTextStyle(TEXT("Tutorials.Content.HyperlinkText"))
.SeparatorStyle(TEXT("Tutorials.Separator"));
TSharedRef<IDocumentationPage> Page = IDocumentation::Get()->GetPage(InImportPath, TSharedPtr<FParserConfiguration>(), DocumentationStyle);
InTutorialToImportTo->Modify();
InTutorialToImportTo->Title = Page->GetTitle();
InTutorialToImportTo->Stages.Empty();
TArray<FExcerpt> Excerpts;
Page->GetExcerpts(Excerpts);
for(auto& Excerpt : Excerpts)
{
Page->GetExcerptContent(Excerpt);
if(Excerpt.RichText.Len() > 0)
{
FTutorialStage& Stage = InTutorialToImportTo->Stages[InTutorialToImportTo->Stages.Add(FTutorialStage())];
Stage.Name = *Excerpt.Name;
Stage.Content.Type = ETutorialContent::RichText;
FString RichText;
FString* TitleStringPtr = Excerpt.Variables.Find(TEXT("StageTitle"));
if(TitleStringPtr != nullptr)
{
RichText += FString::Printf(TEXT("<TextStyle Style=\"Tutorials.Content.HeaderText2\">%s</>\n\n"), **TitleStringPtr);
}
RichText += Excerpt.RichText;
Stage.Content.Text = FText::FromString(RichText);
}
}
return true;
}
return false;
}
#undef LOCTEXT_NAMESPACE
|
f0600b69c18fa31edfb673a087c520cafed91761 | 050c8a810d34fe125aecae582f9adfd0625356c6 | /E. Santa Claus and Tangerines/main.cpp | 1fbb2d397a42ef6b06f3b613c1a761db1cb50fa5 | [] | no_license | georgerapeanu/c-sources | adff7a268121ae8c314e846726267109ba1c62e6 | af95d3ce726325dcd18b3d94fe99969006b8e138 | refs/heads/master | 2022-12-24T22:57:39.526205 | 2022-12-21T16:05:01 | 2022-12-21T16:05:01 | 144,864,608 | 11 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,045 | cpp | main.cpp | #include <iostream>
#include <bits/stdc++.h>
#include <cstdio>
#include <algorithm>
#define LL int
using namespace std;
LL N,K,ma;
LL A[1000005];
int dp[10000005];///cate parti de mandarina de i felii pot obtina care sa aiba cel putin val felii
bool ok(LL val)
{
LL nr=0;
for(LL i=1;i<=ma;i++)
{
dp[i]=0;
if(val<=i)
dp[i]=1;
if(i%2)
dp[i]=max(dp[i],dp[i>>1]+dp[(i+1)>>1]);
else
dp[i]=max(dp[i],2*dp[i>>1]);
}
for(LL i=1;i<=N;i++)
{
nr+=dp[A[i]];
if(nr>=K)
return 1;
}
return 0;
}
int main()
{
bool notthesamecode=1;
cin.sync_with_stdio(false);
cout.sync_with_stdio(false);
cin>>N>>K;
for(LL i=1;i<=N;i++)
{cin>>A[i];ma=max(ma,A[i]);}
LL st=0,dr=(1e7+10),mid;
while(st<dr)
{
mid=(st+dr+1)/2;
if(ok(mid))
st=mid;
else
dr=mid-1;
}
if(!st)
cout<<-1;
else
cout<<st;
return 0;
}
///31 - __builtin_clz(3
|
7584f51478827443aca334b8f342e497d23ae62a | 87006e5c8da39e87482fe2ab0c675c1c2a1cea12 | /win/win32/cmd_args.cpp | 37c40d7a01bee6ab04392c5838154440b0fdaf90 | [] | no_license | jelly-lemon/C_Cpp_Study | 85f02dd28b1adc2cdf8bed84fecb88aa64d438c3 | de496675940c5041fc50e5926d9945ff6f55b72a | refs/heads/master | 2023-09-04T18:56:20.530885 | 2021-11-14T03:17:39 | 2021-11-14T03:17:39 | 331,022,316 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,163 | cpp | cmd_args.cpp |
#include <windows.h>
#include <cstdio>
using namespace std;
/**
* 解析命令行参数
*
* lpCmdLine 包含了参数,不过是一个字符串(不包含程序名)
*
* WinMain: LPSTR
* wWinMain:LPWSTR lpCmdLine
*/
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
int argc = 0;
//
// 获取 Unicode 命令行参数
//
LPWSTR* argv = CommandLineToArgvW(GetCommandLineW(), &argc);
//
// 挨个转换
//
char **newArgv = (char**)malloc(argc*sizeof(char*));
for (int i = 0; i < argc; ++i) {
LPWSTR cmd = argv[i];
//
// Unicode 转 utf-8
//
int len = WideCharToMultiByte(CP_UTF8, NULL, cmd, wcslen(cmd), NULL, 0, NULL, NULL);
char *strUTF8 = (char*)malloc((len+1)*sizeof(char));
ZeroMemory(strUTF8, len + 1);
WideCharToMultiByte(CP_UTF8, NULL, cmd, wcslen(cmd), strUTF8, len, NULL, NULL);
newArgv[i] = strUTF8;
printf("argv[%d]:%s\n", i, newArgv[i]);
}
return 0;
}
/**
* 如果同时存在 WinMain 和 main,则会执行 main
*/
//int main() {
//
// return 0;
//}
|
51c2ae6d357b6a6c5491072a548aba7700bbfe57 | 2321e819ad6da204371a2f27333ae39e3feccb25 | /src/crypt/QDataEnDe.h | 0abb01e50bc99f10d33dd1d77d7f865dc13d4818 | [] | no_license | fzzn-2020/qui | 09e7b61aecfe652a95447cb377462c479e812d3b | a77170bfb7e1e3e57647c42558fe35eb79988f5b | refs/heads/master | 2022-10-25T00:54:47.742791 | 2020-06-03T15:59:41 | 2020-06-03T16:01:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 272 | h | QDataEnDe.h | #pragma once
// // #include "QUI.h"
#include "QBuffer.h"
class QDataEnDe
{
public:
BOOL SetCodeData(LPCBYTE p,int len);
BOOL SetCodeData( QBuffer& d );
BOOL DecryptData(__inout QBuffer &buf);
BOOL EncryptData(__inout QBuffer &buf);
private:
BYTE m_code[16];
};
|
775884e1f4b0f077e88eb3a005b4cc857e6c4f43 | db20275e9ef80a3f6c47c954092cbfab1e42e2d6 | /Raven.CppClient/GetResponse.h | b58c2b8746b60810104f5efe288af8772fdf8685 | [
"MIT"
] | permissive | maximburyak/ravendb-cpp-client | 2ccb4d95678a1d0640aff2133892f7c8c9830106 | ab284d00bc659e8438c829f1b4a39aa78c31fa88 | refs/heads/master | 2020-04-26T18:10:12.216454 | 2019-02-28T07:44:40 | 2019-02-28T07:44:40 | 173,736,480 | 0 | 0 | MIT | 2019-03-04T11:58:54 | 2019-03-04T11:58:53 | null | UTF-8 | C++ | false | false | 1,255 | h | GetResponse.h | #pragma once
#include "HttpStatus.h"
namespace ravendb::client::impl::utils
{
struct CompareStringsIgnoreCase;
}
namespace ravendb::client::documents::commands::multi_get
{
struct GetResponse
{
std::optional<std::string> result{};
std::map<std::string, std::string, impl::utils::CompareStringsIgnoreCase> headers{};
int32_t status_code{};
bool force_retry = false;
bool request_has_errors() const
{
bool are_errors = false;
switch (status_code)
{
case 0:
case (int32_t)http::HttpStatus::SC_OK:
case (int32_t)http::HttpStatus::SC_CREATED:
case (int32_t)http::HttpStatus::SC_NON_AUTHORITATIVE_INFORMATION:
case (int32_t)http::HttpStatus::SC_NO_CONTENT:
case (int32_t)http::HttpStatus::SC_NOT_MODIFIED:
case (int32_t)http::HttpStatus::SC_NOT_FOUND:
break;
default:
are_errors = true;
break;
}
return are_errors;
}
};
inline void from_json(const nlohmann::json& j, GetResponse& gr)
{
using impl::utils::json_utils::get_val_from_json;
get_val_from_json(j, "Headers", gr.headers);
if(auto it = j.find("Result");
it != j.end())
{
gr.result = it->dump();
}
get_val_from_json(j, "StatusCode", gr.status_code);
get_val_from_json(j, "ForceRetry", gr.force_retry);
}
}
|
ecbdd02a4a9b3b187fd4f39569ffa62013056a4d | af0ecafb5428bd556d49575da2a72f6f80d3d14b | /CodeJamCrawler/dataset/12_24318_60.cpp | fbdb014b8d02268d07e2b2dce2d94be4aa8ad3f8 | [] | no_license | gbrlas/AVSP | 0a2a08be5661c1b4a2238e875b6cdc88b4ee0997 | e259090bf282694676b2568023745f9ffb6d73fd | refs/heads/master | 2021-06-16T22:25:41.585830 | 2017-06-09T06:32:01 | 2017-06-09T06:32:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 994 | cpp | 12_24318_60.cpp | /*By Zine.Chant*/
#include<algorithm>
#include<iterator>
#include<iostream>
#include<vector>
#include<sstream>
#include<string>
#include<vector>
#include<map>
#include<cstring>
#include<cstdio>
#include<cstdlib>
#include<ctime>
#include<cmath>
using namespace std;
const int maxn=3000001;
int v,a,b,x,y,z,t;
int d[maxn];
bool o[maxn];
long long ans;
int c[9];
int w(int x)
{
int s=0;
while (x>0)
{
x/=10;
s++;
}
return s;
}
int main()
{
// freopen("c.in","r",stdin);
// freopen("c.out","w",stdout);
scanf("%d\n",&v);
c[1]=1;
for (int i=2;i<=8;i++)
c[i]=c[i-1]*10;
memset(o,false,sizeof(o));
for (int u=1;u<=v;u++)
{
ans=0;
scanf("%d %d\n",&a,&b);
for (int i=a;i<=b;i++)
{
y=w(i);
x=i;
t=0;
for (int j=1;j<y;j++)
{
z=x%10;
x/=10;
x+=z*c[y];
if (x>b||x<a||o[x]||x<=i||z==0) continue;
ans++;
t++;
d[t]=x;
o[x]=true;
}
for (int j=1;j<=t;j++)
o[d[j]]=false;
}
cout<<"Case #"<<u<<": "<<ans<<endl;
}
return 0;
}
|
cd317946c854b457714613f15b7a0238ed5ea798 | 47d1033dff5dafe8df5e8c7e31429c467bca3644 | /src/GlobalData.h | c4e5d8a81c108cc5dbe62650bd3013fbae247c1a | [] | no_license | mmavipc/NoName | a370bc64f1b0b2f567ea2da366c91c5ac54d6b47 | b7f8c5f49be0535425a2d46dcb20853b31e78371 | refs/heads/master | 2016-09-05T20:27:46.723565 | 2011-06-13T02:22:20 | 2011-06-13T02:22:20 | 1,878,619 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 445 | h | GlobalData.h | #ifndef GlobalData_H
#define GlobalData_H
#include "Networking\TCPSocket.h"
#include "Bot\GenericBot.h"
#include <vector>
class GlobalData
{
public:
GlobalData(const std::string &configFile, TCPSocket *tcpsock); //Dummy for now
static GlobalData* GetGlobalData();
const std::string& GetServerName();
TCPSocket& GetSocket();
std::vector<GenericBot*> m_botList;
private:
std::string m_serverName;
TCPSocket *m_sock;
};
#endif |
25a9cd9cf61296058a52a8d47694a861615a12b1 | f03d0e9305dbd45a6fbe4d13ee43cb34bfaf89f7 | /src/shared/renderer/render_context.cpp | 83352a1c8ed8595dab10974728db624b0a0bfece | [] | no_license | TomHaygarth/GOAT-Engine | a6013cafc3112db747452b2a0b844facb7b8555f | 8bdf519bd57f6a82df4c8e5119236a47bdfad60f | refs/heads/master | 2023-04-26T00:20:09.961381 | 2021-05-20T16:58:49 | 2021-05-20T16:58:49 | 198,925,137 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 123 | cpp | render_context.cpp | #include "render_context.hpp"
Renderer::IRenderContext::~IRenderContext()
{
// This page is intentionally left blank
} |
367596c0e79e22dca39fb563d655b17151f0fc01 | c071863a05d23461493a5e5ca021489c8275fd84 | /erts/emulator/asmjit/core/osutils.h | a4691295b204f8e46d78ccd71ebc519a1f65e10e | [
"Apache-2.0",
"Zlib"
] | permissive | spawnfest/eep49ers | 06a8b55a55256d0404e72e62bd2d498e8bccc938 | 2fa5789fe176661ae86283663d3e86b0c991b0ce | refs/heads/eep-49 | 2023-08-01T11:27:26.809499 | 2021-09-19T23:18:39 | 2021-09-19T23:18:39 | 406,154,995 | 14 | 1 | Apache-2.0 | 2021-09-19T22:34:18 | 2021-09-13T23:06:36 | Erlang | UTF-8 | C++ | false | false | 2,597 | h | osutils.h | // AsmJit - Machine code generation for C++
//
// * Official AsmJit Home Page: https://asmjit.com
// * Official Github Repository: https://github.com/asmjit/asmjit
//
// Copyright (c) 2008-2020 The AsmJit Authors
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
#ifndef ASMJIT_CORE_OSUTILS_H_INCLUDED
#define ASMJIT_CORE_OSUTILS_H_INCLUDED
#include "../core/globals.h"
ASMJIT_BEGIN_NAMESPACE
//! \addtogroup asmjit_utilities
//! \{
// ============================================================================
// [asmjit::OSUtils]
// ============================================================================
//! Operating system utilities.
namespace OSUtils {
//! Gets the current CPU tick count, used for benchmarking (1ms resolution).
ASMJIT_API uint32_t getTickCount() noexcept;
};
// ============================================================================
// [asmjit::Lock]
// ============================================================================
//! \cond INTERNAL
//! Lock.
//!
//! Lock is internal, it cannot be used outside of AsmJit, however, its internal
//! layout is exposed as it's used by some other classes, which are public.
class Lock {
public:
ASMJIT_NONCOPYABLE(Lock)
#if defined(_WIN32)
#pragma pack(push, 8)
struct ASMJIT_MAY_ALIAS Handle {
void* DebugInfo;
long LockCount;
long RecursionCount;
void* OwningThread;
void* LockSemaphore;
unsigned long* SpinCount;
};
Handle _handle;
#pragma pack(pop)
#elif !defined(__EMSCRIPTEN__)
typedef pthread_mutex_t Handle;
Handle _handle;
#endif
inline Lock() noexcept;
inline ~Lock() noexcept;
inline void lock() noexcept;
inline void unlock() noexcept;
};
//! \endcond
//! \}
ASMJIT_END_NAMESPACE
#endif // ASMJIT_CORE_OSUTILS_H_INCLUDED
|
f8a220e71bf82de231f4d9c3513299745e37735b | 691c8f2849b72b2a3207631abc482086c833f435 | /tests/adc_test.cpp | 1858b0cce74c1fd0822d27fd01aa1f6aa0f41d93 | [] | no_license | nckswt/FARSHAPE | 205ceaad25df174851be0a56911ce28363eafcca | 3bbb96559cada2af857ffd449b633f530fb75889 | refs/heads/master | 2021-01-10T20:13:17.818687 | 2013-04-04T03:52:23 | 2013-04-04T03:52:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 350 | cpp | adc_test.cpp | #include "../system/ADC_SPI.h"
#include <iostream>
int main() {
ADC_SPI adc(0, 0);
while (1) {
std::cout << "Single value grab: ";
std::cout << adc.getSingle() << std::endl;
sleep(1);
std::cout << "Averaging of " << AVERAGING << ": ";
std::cout << adc.getAverage() << std::endl;
sleep(1);
}
return 0;
}
|
f79ca1a4630d9b791038592c08a8687972f31098 | 5b741fb3f38acf58bde184508739c4697690a199 | /CarND-Unscented-Kalman-Filter-Project/src/ukf.cpp | 6ea680d2cba1f7b3a1226c8820ebc420c20a8207 | [] | no_license | nav13n/carnd | 296e0820b41edf68c08a2c31905d28431b862197 | 431d6ffc56965874487a10732583e11e4a3d05db | refs/heads/master | 2021-01-13T05:57:55.488591 | 2018-08-02T23:39:57 | 2018-08-02T23:39:57 | 94,936,148 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,053 | cpp | ukf.cpp | #include "ukf.h"
#include "Eigen/Dense"
#include <iostream>
#define EPS 0.0001
using namespace std;
using Eigen::MatrixXd;
using Eigen::VectorXd;
using std::vector;
/**
* Initializes Unscented Kalman filter
* This is scaffolding, do not modify
*/
UKF::UKF() {
// if this is false, laser measurements will be ignored (except during init)
use_laser_ = true;
// if this is false, radar measurements will be ignored (except during init)
use_radar_ = true;
// initial state vector
x_ = VectorXd(5);
// initial covariance matrix
P_ = MatrixXd(5, 5);
// Process noise standard deviation longitudinal acceleration in m/s^2
std_a_ = 1.6;
// Process noise standard deviation yaw acceleration in rad/s^2
std_yawdd_ = 0.5;
//DO NOT MODIFY measurement noise values below these are provided by the sensor manufacturer.
// Laser measurement noise standard deviation position1 in m
std_laspx_ = 0.15;
// Laser measurement noise standard deviation eposition2 in m
std_laspy_ = 0.15;
// Radar measurement noise standard deviation radius in m
std_radr_ = 0.3;
// Radar measurement noise standard deviation angle in rad
std_radphi_ = 0.03;
// Radar measurement noise standard deviation radius change in m/s
std_radrd_ = 0.3;
//DO NOT MODIFY measurement noise values above these are provided by the sensor manufacturer.
// initially set to false, set to true in first call of ProcessMeasurement
is_initialized_ = false;
// time when the state is true, in us
time_us_ = 0.0;
// state dimension
n_x_ = x_.size();
// Augmented state dimension
n_aug_ = n_x_+2;
// Sigma point spreading parameter
lambda_ = 3 - n_aug_;
// predicted sigma points matrix
Xsig_pred_ = MatrixXd(n_x_, 2 * n_aug_ + 1);
//create vector for weights
weights_ = VectorXd(2 * n_aug_ + 1);
// the current NIS for radar
NIS_radar_ = 0.0;
// the current NIS for laser
NIS_laser_ = 0.0;
//Initialise lidar measurement noise covariance matrix
R_laser_ = MatrixXd(2, 2);
R_laser_ << std_laspx_*std_laspx_, 0,
0, std_laspy_*std_laspy_;
//Initialise radar measurement noise covariance matrix
R_radar_ = MatrixXd(3, 3);
R_radar_ << std_radr_*std_radr_, 0, 0,
0, std_radphi_*std_radphi_, 0,
0, 0, std_radrd_*std_radrd_;
}
UKF::~UKF() {}
void NormalizeAngle(double& phi)
{
phi = atan2(sin(phi), cos(phi));
}
/**
* @param {MeasurementPackage} meas_package The latest measurement data of
* either radar or laser.
*/
void UKF::ProcessMeasurement(MeasurementPackage meas_package) {
// CTRV Model, x_ is [px, py, vel, ang, ang_rate]
/*****************************************************************************
* Initialization
****************************************************************************/
if (!is_initialized_) {
// first measurement
cout << "Initializing UKF" << endl;
VectorXd xi(5); //Initial state
// initialise timestamp
time_us_ = meas_package.timestamp_;
// Initialise state covariance matrix.
P_ << MatrixXd::Identity(n_x_,n_x_);
if (meas_package.sensor_type_ == MeasurementPackage::LASER) {
//set the state with the initial location and zero velocity
float p_x = meas_package.raw_measurements_[0];
float p_y = meas_package.raw_measurements_[1];
float v = 0;
float si = 0;
float si_dot = 0;
xi << p_x, p_y, v, si, si_dot;
x_ = xi;
}
else if (meas_package.sensor_type_ == MeasurementPackage::RADAR) {
/**
Convert radar from polar to cartesian coordinates and initialize state.
*/
/**
Convert radar from polar to cartesian coordinates and initialize state.
*/
const float rho = meas_package.raw_measurements_[0];
const float phi = meas_package.raw_measurements_[1];
const float rho_dot = meas_package.raw_measurements_[2];
const float p_x = rho * cos(phi);
const float p_y = rho * sin(phi);
const float v = sqrt(rho_dot * cos(phi) * rho_dot * cos(phi) + rho_dot * sin(phi) * rho_dot * sin(phi));
const float si = 0;
const float si_dot = 0;
xi << p_x, p_y, v, si, si_dot;
x_ = xi;
}
// Edge case initial state
if (fabs(x_(0)) < 0.0001 and fabs(x_(1)) < 0.0001){
x_(0) = 0.0001;
x_(1) = 0.0001;
}
// Initialize weights
weights_(0) = lambda_ / (lambda_ + n_aug_);
for (int i = 1; i < weights_.size(); i++) {
weights_(i) = 0.5 / (n_aug_ + lambda_);
}
// done initializing, no need to predict or update
is_initialized_ = true;
return;
}
// Ignore RADAR and LASER measurements as per configuration
if ((meas_package.sensor_type_ == MeasurementPackage::RADAR && use_radar_) ||
(meas_package.sensor_type_ == MeasurementPackage::LASER && use_laser_)) {
/*****************************************************************************
* Prediction
****************************************************************************/
//Time elapsed between the current and previous measurements
float dt = (meas_package.timestamp_ - time_us_) / 1000000.0; //dt - expressed in seconds
time_us_ = meas_package.timestamp_;
Prediction(dt);
/*****************************************************************************
* Update
****************************************************************************/
if (meas_package.sensor_type_ == MeasurementPackage::LASER) {
UpdateLidar(meas_package);
}
else if (meas_package.sensor_type_ == MeasurementPackage::RADAR) {
UpdateRadar(meas_package);
}
}
}
/**
* Predicts sigma points, the state, and the state covariance matrix.
* @param {double} delta_t the change in time (in seconds) between the last
* measurement and this one.
*/
void UKF::Prediction(double delta_t) {
/**
Estimate the object's location. Modify the state
vector, x_. Predict sigma points, the state, and the state covariance matrix.
*/
/*****************************************************************************
* Generate Augmented Sigma Points
****************************************************************************/
MatrixXd Xsig_aug = MatrixXd(n_aug_, 2*n_aug_+1);
AugmentedSigmaPoints(&Xsig_aug);
/*****************************************************************************
* Predict Sigma Points
****************************************************************************/
//predict sigma points
for (int i = 0; i < 2 * n_aug_ + 1; i++)
{
//extract values for better readability
const double p_x = Xsig_aug(0, i);
const double p_y = Xsig_aug(1, i);
const double v = Xsig_aug(2, i);
const double yaw = Xsig_aug(3, i);
const double yawd = Xsig_aug(4, i);
const double nu_a = Xsig_aug(5, i);
const double nu_yawdd = Xsig_aug(6, i);
//predicted state values
double px_p, py_p;
//avoid division by zero
if (fabs(yawd) > 0.001) {
px_p = p_x + v / yawd * (sin(yaw + yawd * delta_t) - sin(yaw));
py_p = p_y + v / yawd * (cos(yaw) - cos(yaw + yawd * delta_t));
}
else {
px_p = p_x + v * delta_t * cos(yaw);
py_p = p_y + v * delta_t * sin(yaw);
}
double v_p = v;
double yaw_p = yaw + yawd * delta_t;
double yawd_p = yawd;
//add noise
px_p = px_p + 0.5 * nu_a * delta_t * delta_t * cos(yaw);
py_p = py_p + 0.5 * nu_a * delta_t * delta_t * sin(yaw);
v_p = v_p + nu_a*delta_t;
yaw_p = yaw_p + 0.5*nu_yawdd*delta_t*delta_t;
yawd_p = yawd_p + nu_yawdd*delta_t;
//write predicted sigma point into right column
Xsig_pred_(0, i) = px_p;
Xsig_pred_(1, i) = py_p;
Xsig_pred_(2, i) = v_p;
Xsig_pred_(3, i) = yaw_p;
Xsig_pred_(4, i) = yawd_p;
}
/*****************************************************************************
* Convert Predicted Sigma Points to Mean/Covariance
****************************************************************************/
//predicted state mean
x_.fill(0.0); //******* necessary? *********
for (int i = 0; i < 2 * n_aug_ + 1; i++) { //iterate over sigma points
x_ = x_ + weights_(i) * Xsig_pred_.col(i);
}
//predicted state covariance matrix
P_.fill(0.0); //******* necessary? *********
for (int i = 0; i < 2 * n_aug_ + 1; i++) { //iterate over sigma points
// state difference
VectorXd x_diff = Xsig_pred_.col(i) - x_;
//angle normalization
NormalizeAngle(x_diff(3));
P_ = P_ + weights_(i) * x_diff * x_diff.transpose();
}
}
/**
* Updates the state and the state covariance matrix using a laser measurement.
* @param {MeasurementPackage} meas_package
*/
void UKF::UpdateLidar(MeasurementPackage meas_package) {
/**
Use lidar data to update the belief about the object's
position. Modify the state vector, x_, and covariance, P_. Calculate the lidar NIS.
*/
//extract measurements
VectorXd z = meas_package.raw_measurements_;
//set measurement dimension
// lidar mesaures p_x and p_y
int n_z = 2;
//create matrix for sigma points in measurement space
MatrixXd Zsig = MatrixXd(n_z, 2 * n_aug_ + 1);
//transform sigma points into measurement space
for (int i = 0; i < 2 * n_aug_ + 1; i++) { //2n+1 sigma points
// extract values for better readability
const double p_x = Xsig_pred_(0, i);
const double p_y = Xsig_pred_(1, i);
// measurement model
Zsig(0, i) = p_x;
Zsig(1, i) = p_y;
}
//mean predicted measurement
VectorXd z_pred = VectorXd(n_z);
z_pred.fill(0.0);
for (int i = 0; i < 2 * n_aug_ + 1; i++) {
z_pred = z_pred + weights_(i) * Zsig.col(i);
}
//measurement covariance matrix S
MatrixXd S = MatrixXd(n_z, n_z);
S.fill(0.0);
for (int i = 0; i < 2 * n_aug_ + 1; i++) { //2n+1 simga points
//residuals
VectorXd z_diff = Zsig.col(i) - z_pred;
S = S + weights_(i) * z_diff * z_diff.transpose();
}
S = S + R_laser_;
//create matrix for cross correlation Tc
MatrixXd Tc = MatrixXd(n_x_, n_z);
//calculate cross correlation matrix
Tc.fill(0.0);
for (int i = 0; i < 2 * n_aug_ + 1; i++) { //2n+1 sigma points
//residual
VectorXd z_diff = Zsig.col(i) - z_pred;
// state difference
VectorXd x_diff = Xsig_pred_.col(i) - x_;
Tc = Tc + weights_(i) * x_diff * z_diff.transpose();
}
//Kalman gain K;
MatrixXd K = Tc * S.inverse();
//residual
VectorXd z_diff = z - z_pred;
//calculate NIS
NIS_laser_ = z_diff.transpose() * S.inverse() * z_diff;
//update state mean and covariance matrix
x_ = x_ + K * z_diff;
P_ = P_ - K*S*K.transpose();
}
/**
* Updates the state and the state covariance matrix using a radar measurement.
* @param {MeasurementPackage} meas_package
*/
void UKF::UpdateRadar(MeasurementPackage meas_package) {
/**
Use radar data to update the belief about the object's
position. Modify the state vector, x_, and covariance, P_. Calculate the radar NIS.
*/
//extract measurements
VectorXd z = meas_package.raw_measurements_;
//set measurement dimension
//radar can measure r, phi, and r_dot
int n_z = 3;
//create matrix for sigma points in measurement space
MatrixXd Zsig = MatrixXd(n_z, 2 * n_aug_ + 1);
//transform sigma points into measurement space
for (int i = 0; i < 2 * n_aug_ + 1; i++) { //2n+1 simga points
// extract values for better readability
const double p_x = Xsig_pred_(0, i);
const double p_y = Xsig_pred_(1, i);
const double v = Xsig_pred_(2, i);
const double yaw = Xsig_pred_(3, i);
const double v1 = cos(yaw)*v;
const double v2 = sin(yaw)*v;
// measurement model
const double rho = sqrt(p_x*p_x + p_y*p_y); //rho
const double phi = atan2(p_y, max(EPS,p_x)); //phi
const double rho_dot = (p_x*v1 + p_y*v2) / max(EPS,rho); //rho_dot
Zsig(0, i) = rho;
Zsig(1, i) = phi;
Zsig(2, i) = rho_dot;
}
//mean predicted measurement
VectorXd z_pred = VectorXd(n_z);
z_pred.fill(0.0);
for (int i = 0; i < 2 * n_aug_ + 1; i++) {
z_pred = z_pred + weights_(i) * Zsig.col(i);
}
//measurement covariance matrix S
MatrixXd S = MatrixXd(n_z, n_z);
S.fill(0.0);
for (int i = 0; i < 2 * n_aug_ + 1; i++) { //2n+1 simga points
//residual
VectorXd z_diff = Zsig.col(i) - z_pred;
//angle normalization
while (z_diff(1)> M_PI) z_diff(1) -= 2.*M_PI;
while (z_diff(1)<-M_PI) z_diff(1) += 2.*M_PI;
S = S + weights_(i) * z_diff * z_diff.transpose();
}
S = S + R_radar_;
//create matrix for cross correlation Tc
MatrixXd Tc = MatrixXd(n_x_, n_z);
//calculate cross correlation matrix
Tc.fill(0.0);
for (int i = 0; i < 2 * n_aug_ + 1; i++) { //2n+1 simga points
//residual
VectorXd z_diff = Zsig.col(i) - z_pred;
//angle normalization
while (z_diff(1)> M_PI) z_diff(1) -= 2.*M_PI;
while (z_diff(1)<-M_PI) z_diff(1) += 2.*M_PI;
// state difference
VectorXd x_diff = Xsig_pred_.col(i) - x_;
//angle normalization
while (x_diff(3)> M_PI) x_diff(3) -= 2.*M_PI;
while (x_diff(3)<-M_PI) x_diff(3) += 2.*M_PI;
Tc = Tc + weights_(i) * x_diff * z_diff.transpose();
}
//Kalman gain K
MatrixXd K = Tc * S.inverse();
//residual
VectorXd z_diff = z - z_pred;
//angle normalization
while (z_diff(1)> M_PI) z_diff(1) -= 2.*M_PI;
while (z_diff(1)<-M_PI) z_diff(1) += 2.*M_PI;
//calculate NIS
NIS_radar_ = z_diff.transpose() * S.inverse() * z_diff;
//update state mean and covariance matrix
x_ = x_ + K * z_diff;
P_ = P_ - K*S*K.transpose();
}
/**
* Generates Augmented Sigma Points.
* @param {MatrixXd*} Xsig_aug_out
*/
void UKF::AugmentedSigmaPoints(MatrixXd* Xsig_aug_out) {
//create augmented mean vector
VectorXd x_aug = VectorXd(n_aug_);
//create augmented state covariance matrix
MatrixXd P_aug = MatrixXd(n_aug_, n_aug_);
//create sigma point matrix
MatrixXd Xsig_aug = MatrixXd(n_aug_, 2 * n_aug_ + 1);
//create augmented mean state
x_aug.head(n_x_) = x_;
x_aug(n_x_) = 0;
x_aug(n_x_+1) = 0;
//create augmented covariance matrix
P_aug.fill(0.0);
P_aug.topLeftCorner(n_x_,n_x_) = P_;
P_aug(n_x_, n_x_) = std_a_*std_a_;
P_aug(n_x_+1, n_x_+1) = std_yawdd_*std_yawdd_;
//create square root matrix
MatrixXd L = P_aug.llt().matrixL();
//create augmented sigma points
Xsig_aug.col(0) = x_aug;
double sqrt_lambda_n_aug = sqrt(lambda_+n_aug_);
VectorXd sqrt_lambda_n_aug_L;
for (int i = 0; i< n_aug_; i++)
{
sqrt_lambda_n_aug_L = sqrt_lambda_n_aug * L.col(i);
Xsig_aug.col(i+1) = x_aug + sqrt_lambda_n_aug_L;
Xsig_aug.col(i+1+n_aug_) = x_aug - sqrt_lambda_n_aug_L;
}
*Xsig_aug_out = Xsig_aug;
}
|
9320cda2f62d250206dacbde72c22eaf676a4337 | b367fe5f0c2c50846b002b59472c50453e1629bc | /xbox_leak_may_2020/xbox trunk/xbox/private/vc6addon/ide/pkgs/dbg/stsfile.cpp | 096d8d42502ed3684adad6f88c1a06ff1b2acce7 | [] | no_license | sgzwiz/xbox_leak_may_2020 | 11b441502a659c8da8a1aa199f89f6236dd59325 | fd00b4b3b2abb1ea6ef9ac64b755419741a3af00 | refs/heads/master | 2022-12-23T16:14:54.706755 | 2020-09-27T18:24:48 | 2020-09-27T18:24:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,194 | cpp | stsfile.cpp | // STSFILE.C
// Status file handling
//
//
#include "stdafx.h"
#pragma hdrstop
#ifdef _DEBUG
#undef THIS_FILE
static char BASED_CODE THIS_FILE[] = __FILE__;
#define new DEBUG_NEW
#endif
// [CAVIAR #5459 11/27/92 v-natjm]
// RebuildBreakpoint
//
static BOOL NEAR PASCAL RebuildBreakpoint (
PBREAKPOINTNODE pBPDest,
BREAKPOINTTYPES wType,
LPSTR lpszLocation,
LPSTR lpszExpression,
int iLength,
LPSTR lpszWndProc,
UINT uMessageClass,
UINT uMessageNum,
BOOL bEnabled,
BOOL bAmbig,
int TMindex,
BOOL bWarnedUnsupported,
long cPass,
BOOL fSqlBp )
{
// Clear all fields in the BREAKPOINTNODE destination
_fmemset ( pBPDest, 0, sizeof ( BREAKPOINTNODE ) );
// Action - breakpointtype
pbpnType ( pBPDest ) = wType;
pbpnPassCount( pBPDest ) = (USHORT)cPass;
pbpnSqlBp( pBPDest ) = fSqlBp;
// Location
if ( ( wType == BPLOC ) ||
( wType == BPLOCEXPRTRUE ) ||
( wType == BPLOCEXPRCHGD ) ) {
if ( ! ParseCV400Location ( lpszLocation, pBPDest ) &&
! ParseQC25Location ( lpszLocation, pBPDest ) ) {
return FALSE;
}
}
// Wnd Proc
if ( wType == BPWNDPROCMSGRCVD ) {
// Must have a wndproc and a message class/message
if ( ! ParseWndProc ( lpszWndProc, pBPDest ) ||
uMessageClass == msgNone
) {
return FALSE;
}
// Messages
pbpnMessageClass ( pBPDest ) = uMessageClass;
pbpnMessageNum ( pBPDest ) = uMessageNum;
}
// Expression
if ( ( wType == BPLOCEXPRTRUE ) ||
( wType == BPLOCEXPRCHGD ) ||
( wType == BPEXPRTRUE) ||
( wType == BPEXPRCHGD ) ) {
if ( ! ParseExpression ( lpszExpression, pBPDest ) ) {
return FALSE;
}
}
// Length
if ( ( wType == BPLOCEXPRCHGD ) ||
( wType == BPEXPRCHGD ) ) {
pbpnExprLen(pBPDest) = iLength;
}
// Set the enabled/disabled flag
pbpnEnabled ( pBPDest ) = bEnabled;
pbpnAmbigBP ( pBPDest ) = bAmbig ;
pbpnBPTMindex ( pBPDest ) = TMindex ;
pbpnWarnedUnsupported ( pBPDest ) = bWarnedUnsupported;
// if "line type" bp, set the line numbers to indicate that breakpoint
// is "restorable"
// (i.e. set non- -1 initial line number
if (pbpnFileLineNode(pBPDest))
pbpnInitLine(pBPDest) = pbpnCurLine(pBPDest);
// If get to here the Breakpoint action has necessary data
return TRUE;
}
UINT nVersionNumber = 0x0003000A;
#define ENDOFRECORD ((DWORD)0x47414D00)
static const char BASED_CODE szOPTInfo[] = "Debugger";
BOOL LoadFromOPTFile(CStateSaver &stateSave)
{
BOOL bRetval = TRUE;
CInitFile fileInit;
ASSERT(stateSave.IsLoading());
if (!stateSave.OpenStream(fileInit, szOPTInfo))
return FALSE;
CArchive ar(&fileInit, CArchive::bNoFlushOnDelete | CArchive::load);
CString str;
try
{
long nFormatVersion;
ar >> nFormatVersion;
// For the OPT files, the formats must match exactly.
if ((UINT&)nFormatVersion != nVersionNumber )
AfxThrowArchiveException(CArchiveException::badSchema);
//
// Serialize breakpoint list
//
char szGeneralBuffer[cbBpCmdMax];
WORD wLoop;
WORD wBPCount;
UINT uMsgNum, uMsgClass;
long iTmp;
long lBrkptType;
BREAKPOINTTYPES wBrkptType;
int iRet;
LPSTR pc1, pc2;
long bEnable;
long bAmbig;
long TMindex;
long bWarnedUnsupported;
BREAKPOINTNODE BpNode;
long cPass;
long fSqlBp;
// read the number of breakpoints
ar >> wBPCount;
if (wBPCount)
{
// we have breakpoints to set. read them one by one
// if an info is missing for a breakpoint, just skip it.
// load the generic entry names
// [CAVIAR # 11/26/92 v-natjm]
// Save all necessary flags to restore Ambiguous BP
for (wLoop = 0; wLoop < wBPCount; wLoop++)
{
ar >> lBrkptType;
wBrkptType = (BREAKPOINTTYPES)lBrkptType;
ar >> bEnable;
ar >> bAmbig;
ar >> TMindex;
ar >> bWarnedUnsupported;
ar >> cPass;
ar >> fSqlBp;
switch ( wBrkptType )
{
case BPLOC:
// breakpoint at location
ar >> str;
_tcscpy(szGeneralBuffer, str);
pc1 = szGeneralBuffer + _fstrlen(szGeneralBuffer); // use strlen, not _tcslen, to get bytes not chars
if (RebuildBreakpoint(&BpNode, wBrkptType,
szGeneralBuffer, pc1, 0, pc1, 0, 0, bEnable,
bAmbig, TMindex, bWarnedUnsupported, cPass, fSqlBp))
AddBreakpointNode(&BpNode, FALSE, TRUE, TRUE, &iRet); // iRet unused here
break;
case BPLOCEXPRTRUE:
// breakpoint at location when expression is true
ar >> str;
_tcscpy(szGeneralBuffer, str);
pc1 = szGeneralBuffer + _fstrlen(szGeneralBuffer) + 1; // use strlen, not _tcslen, to get bytes not chars
ar >> str;
_tcscpy(pc1, str);
pc2 = pc1 + _fstrlen(pc1);
if (RebuildBreakpoint(&BpNode, wBrkptType,
szGeneralBuffer, pc1, 0, pc2, 0, 0, bEnable,
bAmbig, TMindex, bWarnedUnsupported, cPass, fSqlBp))
AddBreakpointNode(&BpNode, FALSE, TRUE, TRUE, &iRet);
break;
case BPLOCEXPRCHGD:
// breakpoint at location when expression has changed
ar >> str;
_tcscpy(szGeneralBuffer, str);
pc1 = szGeneralBuffer + _fstrlen(szGeneralBuffer) + 1; // use strlen, not _tcslen, to get bytes not chars
ar >> str;
_tcscpy(pc1, str);
pc2 = pc1 + _fstrlen(pc1);
ar >> iTmp;
if (RebuildBreakpoint(&BpNode, wBrkptType,
szGeneralBuffer, pc1, iTmp, pc2, 0, 0,
bEnable, bAmbig, TMindex, bWarnedUnsupported,
cPass, fSqlBp))
AddBreakpointNode(&BpNode, FALSE, TRUE, TRUE, &iRet);
break;
case BPEXPRTRUE:
// breakpoint when expression is true
ar >> str;
_tcscpy(szGeneralBuffer, str);
pc1 = szGeneralBuffer + _fstrlen(szGeneralBuffer); // use strlen, not _tcslen, to get bytes not chars
if (RebuildBreakpoint(&BpNode, wBrkptType, pc1,
szGeneralBuffer, 0, pc1, 0, 0, bEnable,
bAmbig, TMindex, bWarnedUnsupported, cPass, fSqlBp))
AddBreakpointNode(&BpNode, FALSE, TRUE, TRUE, &iRet);
break;
case BPEXPRCHGD:
// breakpoint when expression has changed
ar >> str;
_tcscpy(szGeneralBuffer, str);
pc1 = szGeneralBuffer + _fstrlen(szGeneralBuffer); // use strlen, not _tcslen, to get bytes not chars
ar >> iTmp;
if (RebuildBreakpoint(&BpNode, wBrkptType, pc1,
szGeneralBuffer, iTmp, pc1, 0, 0, bEnable,
bAmbig, TMindex, bWarnedUnsupported, cPass, fSqlBp))
AddBreakpointNode(&BpNode, FALSE, TRUE, TRUE, &iRet);
break;
case BPWNDPROCMSGRCVD:
// breakpoint at window procedure
ar >> str;
_tcscpy(szGeneralBuffer, str);
pc1 = szGeneralBuffer + _fstrlen(szGeneralBuffer); // use strlen, not _tcslen, to get bytes not chars
ar >> iTmp;
uMsgNum = (UINT)iTmp;
ar >> iTmp;
uMsgClass = (UINT)iTmp;
if (RebuildBreakpoint(&BpNode, wBrkptType, pc1, pc1,
0, szGeneralBuffer, uMsgClass, uMsgNum,
bEnable, bAmbig, TMindex, bWarnedUnsupported,
cPass, fSqlBp))
AddBreakpointNode(&BpNode, FALSE, TRUE, TRUE, &iRet);
break;
}
}
}
// free mem from old list
ClearDLLInfo();
// Restore the additional DLL grid information
long cTargets;
ar >> cTargets;
for (int iTarg=0; iTarg < cTargets; iTarg++)
{
long cDLLRecs;
CString strTargetName;
HBLDTARGET hTarget;
ar >> strTargetName;
gpIBldSys->GetTarget(strTargetName, ACTIVE_BUILDER, &hTarget);
ar >> cDLLRecs;
for (int iRecs=0; iRecs < cDLLRecs; iRecs++)
{
long fPreload;
CString strLocalName;
CString strRemoteName;
ar >> fPreload;
ar >> strLocalName;
ar >> strRemoteName;
// if target doesn't exist, don't add to dll info
if (hTarget != NO_TARGET)
{
AddRecToDLLInfo(strLocalName, strRemoteName, (BOOL) fPreload, (HTARGET)hTarget);
}
}
}
//
// Serialize the exception list
//
long Count,i;
EXCEPTION_OBJECT Object;
DWORD dwExceptionCode;
LONG iAction;
LONG iPlatformId;
// Get # of exception in the file
ar >> Count;
// Reset current list
InitList(DLG_EXCEP_LIST);
EmptyList(DLG_EXCEP_LIST);
// Check if list isn't empty
if (Count == -1)
fExcepListInitialized = FALSE;
else
{
fExcepListInitialized = TRUE;
// Get each exception, and build a string
for (i = 0; i < Count; i++)
{
ar >> dwExceptionCode;
ar >> str;
ar >> iAction;
ar >> iPlatformId;
MakeExceptionObject(&Object, dwExceptionCode, str,
(int) iAction, (UINT) iPlatformId);
ListAddObject(DLG_EXCEP_LIST, (LPSTR)&Object,
sizeof(EXCEPTION_OBJECT));
}
}
//
// Serialize the debugger file alias list
//
int cRestore;
ar >> (long &)cRestore;
while( cRestore-- )
{
CString strFrom;
CString strTo;
ar >> strFrom;
ar >> strTo;
// No hocus pocus, just call the internal routine.
AddMapping(
(LPSTR)(const char FAR *)strFrom,
(LPSTR)(const char FAR *)strTo
);
}
//
// Serialize the watch window state.
//
g_persistWatch.Serialize(ar);
g_persistVars.Serialize(ar);
ar >> ((DWORD&) g_fPromptNoSymbolInfo);
ar.Close();
fileInit.Close();
}
catch (CArchiveException *e)
{
e->Delete();
ar.Close();
fileInit.Abort(); // will not throw an exception
g_persistWatch.InitDefault();
g_persistVars.InitDefault();
g_fPromptNoSymbolInfo = TRUE;
bRetval = FALSE;
}
// Note: At this point, if bRetval is false, then the OPT file is only
// partially loaded and we may be in some sort of weird state
if (bRetval)
{
}
return bRetval;
}
BOOL SaveIntoOPTFile(CStateSaver &stateSave)
{
BOOL bRetval = TRUE;
CInitFile fileInit;
ASSERT(stateSave.IsStoring());
if (!stateSave.OpenStream(fileInit, szOPTInfo))
{
SetFileError(CFileException::generic);
return FALSE;
}
CArchive ar(&fileInit, CArchive::bNoFlushOnDelete | CArchive::store);
CString str;
TRY
{
// Save format version:
ar << ((long)nVersionNumber);
//
// Serialize breakpoint list
//
char szGeneralBuffer[cbBpCmdMax];
WORD wBPCount = 0;
BREAKPOINTTYPES wBrkptType;
PBREAKPOINTNODE pBpNode;
long wLoop;
// do a pass on the eventually existing breakpoints,
// eliminating the breakpoints on assembly
pBpNode = BHFirstBPNode();
while (pBpNode != NULL)
{
// [CAVIAR #5878 11/27/92 v-natjm]
++wBPCount;
pBpNode = pbpnNext(pBpNode);
}
// write out the number of breakpoints to be saved
ar << wBPCount;
// write out the breakpoints
pBpNode = BHFirstBPNode();
for (wLoop = 0; wLoop < wBPCount; wLoop++)
{
// [CAVIAR #5878 11/27/92 v-natjm]
// [CAVIAR #5459 11/27/92 v-natjm]
wBrkptType = pbpnType(pBpNode);
ar << (long)wBrkptType;
ar << (long)pbpnEnabled(pBpNode);
ar << (long)pbpnAmbigBP(pBpNode);
ar << (long)pbpnBPTMindex(pBpNode);
ar << (long)pbpnWarnedUnsupported(pBpNode);
ar << (long)pbpnPassCount(pBpNode);
ar << (long)pbpnSqlBp(pBpNode);
// build the expression depending on each breakpoint type
switch (wBrkptType)
{
case BPLOC:
// breakpoint at location
BuildCV400Location(pBpNode, szGeneralBuffer,
sizeof(szGeneralBuffer), TRUE, TRUE, FALSE, FALSE);
ar << (CString) szGeneralBuffer;
break;
case BPLOCEXPRTRUE:
// breakpoint at location when expression is true
BuildCV400Location(pBpNode, szGeneralBuffer,
sizeof(szGeneralBuffer), TRUE, TRUE, FALSE, FALSE);
ar << (CString) szGeneralBuffer;
BuildCV400Expression(pBpNode, szGeneralBuffer,
sizeof(szGeneralBuffer), TRUE, TRUE, FALSE);
ar << (CString) szGeneralBuffer;
break;
case BPLOCEXPRCHGD:
// breakpoint at location when expression has changed
BuildCV400Location(pBpNode, szGeneralBuffer,
sizeof(szGeneralBuffer), TRUE, TRUE, FALSE, FALSE);
ar << (CString) szGeneralBuffer;
BuildCV400Expression(pBpNode, szGeneralBuffer,
sizeof(szGeneralBuffer), TRUE, TRUE, FALSE);
ar << (CString) szGeneralBuffer;
ar << (long)pbpnExprLen(pBpNode);
break;
case BPEXPRTRUE:
// breakpoint when expression is true
BuildCV400Expression(pBpNode, szGeneralBuffer,
sizeof(szGeneralBuffer), TRUE, TRUE, FALSE);
ar << (CString) szGeneralBuffer;
break;
case BPEXPRCHGD:
// breakpoint when expression has changed
BuildCV400Expression(pBpNode, szGeneralBuffer,
sizeof(szGeneralBuffer), TRUE, TRUE, FALSE);
ar << (CString) szGeneralBuffer;
ar << (long)pbpnExprLen(pBpNode);
break;
case BPWNDPROCMSGRCVD:
// breakpoint at window procedure
BuildCV400Location(pBpNode, szGeneralBuffer,
sizeof(szGeneralBuffer), TRUE, TRUE, FALSE, FALSE);
ar << (CString) szGeneralBuffer;
ar << (long)pbpnMessageNum(pBpNode);
ar << (long)pbpnMessageClass(pBpNode);
break;
}
pBpNode = pbpnNext(pBpNode);
}
//
// Serialize DLL grid information
//
POSITION posGridList;
POSITION posDLLRecList;
GRIDINFO *pGridInfo;
CPtrList *pDLLRecList;
DLLREC *pDLLRec;
CString strTargetName;
long count = (long)DLLGridInfoList.GetCount();
if (!DLLGridInfoList.IsEmpty()) {
posGridList = DLLGridInfoList.GetHeadPosition();
} else {
posGridList = NULL;
}
while (posGridList != NULL)
{
pGridInfo = (GRIDINFO *)DLLGridInfoList.GetNext(posGridList);
if( !(gpIBldSys->GetTargetName((HBLDTARGET)pGridInfo->hTarget, strTargetName, ACTIVE_BUILDER) == S_OK) ){
count--;
}
}
ar << count;
if (!DLLGridInfoList.IsEmpty()) {
posGridList = DLLGridInfoList.GetHeadPosition();
} else {
posGridList = NULL;
}
while (posGridList != NULL)
{
pGridInfo = (GRIDINFO *)DLLGridInfoList.GetNext(posGridList);
pDLLRecList = &pGridInfo->DLLRecList;
BOOL bTest;
bTest = gpIBldSys->GetTargetName((HBLDTARGET)pGridInfo->hTarget, strTargetName, ACTIVE_BUILDER) == S_OK;
if( bTest ){
ar << strTargetName;
ar << (long)pDLLRecList->GetCount();
posDLLRecList = pDLLRecList->GetHeadPosition();
while (posDLLRecList != NULL) {
pDLLRec = (DLLREC *)pDLLRecList->GetNext(posDLLRecList);
ar << (long)pDLLRec->fPreload;
ar << pDLLRec->strLocalName;
ar << pDLLRec->strRemoteName;
}
}
}
//
// Serialize exception list
//
int Count,i;
EXCEPTION_OBJECT Object;
// Get # of exception in our list
// and write it in the sts file
if (fExcepListInitialized)
{
Count = (int)ListGetCount(DLG_EXCEP_LIST);
ar << (long)Count;
}
else
{
Count = 0;
ar << (long)-1;
}
// Get each exception, and build a string
for (i = 0; i < Count; i++)
{
if (!ListGetObject(i, DLG_EXCEP_LIST, (LPSTR)&Object))
{
ASSERT(FALSE);
}
else
{
ar << (DWORD) Object.dwExceptionCode;
ar << (CString) Object.Name;
ar << (LONG) Object.iAction;
ar << (LONG) Object.iPlatformId;
}
}
//
// Serialize the debugger file alias list
//
ar << (long)cmappath;
for(i = 0; i < cmappath; i++)
{
ASSERT( rgmappath[i].lszFrom );
ASSERT( rgmappath[i].lszTo );
ar << (CString) rgmappath[i].lszFrom;
ar << (CString) rgmappath[i].lszTo;
}
//
// Serialize the watch window state.
//
g_persistWatch.Serialize(ar);
g_persistVars.Serialize(ar);
ar << (DWORD) g_fPromptNoSymbolInfo ;
ar.Close();
fileInit.Close();
}
CATCH_ALL (e)
{
#ifdef _DEBUG
AfxDump(e);
TRACE("\n");
#endif // _DEBUG
if (e->IsKindOf(RUNTIME_CLASS(CFileException)))
SetFileError(((CFileException*) e)->m_cause);
else
SetFileError(CFileException::generic);
ar.Close();
fileInit.Abort();
g_fPromptNoSymbolInfo = TRUE;
bRetval = FALSE;
}
END_CATCH_ALL
return bRetval;
}
|
987ec928662bb791221f1a4fe4b34bd659985e10 | 1af43c4ba32d78c60f007a4d068136ce575d917f | /system/apps_experiments/95_sht20/DFRobot_SHT20.h | 52ebb672d0ee935f89f31c4a1043dfb826909898 | [
"MIT"
] | permissive | gabonator/LA104 | a4f1cdf2b3e513300d61c50fff091c5717abda9e | 27d0eece7302c479da2cf86e881b6a51a535f93d | refs/heads/master | 2023-08-31T22:09:36.272616 | 2023-08-27T20:08:08 | 2023-08-27T20:08:08 | 155,659,451 | 500 | 69 | MIT | 2023-08-17T08:44:32 | 2018-11-01T03:54:21 | C | UTF-8 | C++ | false | false | 1,735 | h | DFRobot_SHT20.h | #ifndef DFRobot_SHT20_h
#define DFRobot_SHT20_h
#include "platform.h"
#define ERROR_I2C_TIMEOUT 998
#define ERROR_BAD_CRC 999
#define SLAVE_ADDRESS 0x40
#define TRIGGER_TEMP_MEASURE_HOLD 0xE3
#define TRIGGER_HUMD_MEASURE_HOLD 0xE5
#define TRIGGER_TEMP_MEASURE_NOHOLD 0xF3
#define TRIGGER_HUMD_MEASURE_NOHOLD 0xF5
#define WRITE_USER_REG 0xE6
#define READ_USER_REG 0xE7
#define SOFT_RESET 0xFE
#define USER_REGISTER_RESOLUTION_MASK 0x81
#define USER_REGISTER_RESOLUTION_RH12_TEMP14 0x00
#define USER_REGISTER_RESOLUTION_RH8_TEMP12 0x01
#define USER_REGISTER_RESOLUTION_RH10_TEMP13 0x80
#define USER_REGISTER_RESOLUTION_RH11_TEMP11 0x81
#define USER_REGISTER_END_OF_BATTERY 0x40
#define USER_REGISTER_HEATER_ENABLED 0x04
#define USER_REGISTER_DISABLE_OTP_RELOAD 0x02
#define MAX_WAIT 1000
#define DELAY_INTERVAL 10
#define SHIFTED_DIVISOR 0x988000
#define MAX_COUNTER (MAX_WAIT/DELAY_INTERVAL)
class DFRobot_SHT20
{
public:
void checkSHT20(void);
void setResolution(byte resBits);
void writeUserRegister(byte val);
void initSHT20(TwoWire &wirePort = Wire);
void showReslut(const char *prefix, int val);
float readHumidity(void);
float readTemperature(void);
byte readUserRegister(void);
private:
TwoWire *i2cPort;
byte checkCRC(uint16_t message_from_sensor, uint8_t check_value_from_sensor);
uint16_t readValue(byte cmd);
};
#endif |
59cb930aecbde9c98c5815de0f5995c35d163670 | d55755141c0e12552562cca50837020e73737ac7 | /source/spring-recruitment/119. Pascal's Triangle II.cpp | 252b5c76a49689d3fc2f332d19622b555deaef7a | [] | no_license | xulzee/LeetCodeProjectCPP | 5452e218b57b5bf28117cab98b163f07bcce7329 | 129bea6296560676eca4fa9b20fe83dc935a3b92 | refs/heads/master | 2020-06-26T00:09:27.612312 | 2020-03-22T09:06:54 | 2020-03-22T09:06:54 | 199,463,509 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 914 | cpp | 119. Pascal's Triangle II.cpp | // @Time : 2019/3/30 21:26
// @Author : xulzee
// @Email : xulzee@163.com
// @Software: CLion
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> res(rowIndex + 1, 1);
for (int i = 1; i <= rowIndex; ++i) {
for (int j = i - 1; j > 0; --j) {
res[j] = res[j] + res[j-1];
}
}
return res;
}
vector<int> getRow1(int rowIndex) {
vector<vector<int>> res;
for (int i = 0; i <= rowIndex; ++i) {
vector<int> temp(i+1, 1);
for (int j = 1; j < i; ++j) {
temp[j] = res[i - 1][j] + res[i - 1][j - 1];
}
res.push_back(temp);
}
return res[rowIndex];
}
};
int main(){
int test = 3;
vector<int> temp = Solution().getRow(test);
int temp1 = test;
}
|
26ca704ff1e2042c96e115b2b3f0db1e0184aa88 | a4ff0ed0b66ab58d5bc1bfd2bdd17a4cd8cadbe3 | /Langranges4squareMethod.c++ | 8b8d1c13be0f1d507b07db1835c80917512c5f47 | [] | no_license | rajatsvits/AlgorithmsImplementation | 2783139fe2138549cc6ba4a7f76882ad6deac829 | b90c7a078d5aba4be7a601f067e0ea3b2e365566 | refs/heads/master | 2021-09-06T21:25:34.990014 | 2018-02-11T18:16:28 | 2018-02-11T18:16:28 | 112,160,971 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,856 | Langranges4squareMethod.c++ | /*package whatever //do not write package name here
Adrien-Marie Legendre completed the theorem in 1797–8 with his three-square theorem, by proving that a positive integer can
be expressed as the sum of three squares if and only if it is not of the form {\displaystyle 4^{k}(8m+7)} 4^{k}(8m+7)
for integers {\displaystyle k} k and {\displaystyle m} m. Later, in 1834*
/
import java.io.*;
class GFG {
public static boolean isSquare(int n) {
double sqrt = Math.sqrt(n);
int x = (int) sqrt;
return (Math.pow(sqrt, 2) == Math.pow(x, 2));
}
// Lagrange's Four Square theorem , answer can be 1,2,3 or 4
public static int getMinNumberOfSquares(int sum) {
// case:1
// If answer is 1 => sum is perfect square
if (isSquare(sum))
return 1;
//case:2
//If answer is 2 => one factor has to be (int)square_root and remaining other number has to be a perfect square
int sqrt = (int) (Math.sqrt(sum));
for (int i = 1; i <= sqrt; i++) {
if (isSquare(sum - i * i))
return 2;
}
//case:3
//Let's come back to this in a min
//case:4
//from wiki
//a positive integer can be expressed as the sum of three squares if and only if it is not of the form 4^k(8m+7) for some int k and m
//see "not of" in above line
while (sum % 4 == 0) //handling 4^k
sum = sum / 4;
if (sum % 8 == 7) //handling 8m+7
return 4;
// if none of above, case 3
return 3;
}
public static void main (String[] args) {
System.out.println(getMinNumberOfSquares(6)); //ans 3
System.out.println(getMinNumberOfSquares(8)); //ans 2
System.out.println(getMinNumberOfSquares(9)); //ans 1
System.out.println(getMinNumberOfSquares(7)); //ans 4
}
}
| |
dd6e8b02686688ade5851157fc4ba67092a2a0a1 | 4110496fb8b6cf7fbdabf9682f07255b6dab53f3 | /String/1576. Replace All to Avoid Consecutive Repeating Characters.cpp | 926c4bcbf5f1c78608c0b1806a93695d009b314f | [] | no_license | louisfghbvc/Leetcode | 4cbfd0c8ad5513f60242759d04a067f198351805 | 1772036510638ae85b2d5a1a9e0a8c25725f03bd | refs/heads/master | 2023-08-22T19:20:30.466651 | 2023-08-13T14:34:58 | 2023-08-13T14:34:58 | 227,853,839 | 4 | 0 | null | 2020-11-20T14:02:18 | 2019-12-13T14:09:25 | C++ | UTF-8 | C++ | false | false | 477 | cpp | 1576. Replace All to Avoid Consecutive Repeating Characters.cpp | // O(N). Simulate. just make no repeat char.
class Solution {
public:
string modifyString(string s) {
for(int i = 0; i < s.size(); ++i){
if(s[i] != '?') continue;
char l = '?', r = '?';
if(i) l = s[i-1];
if(i+1 < s.size()) r = s[i+1];
for(int k = 0; k < 26; ++k) if((k+'a') != l && (k+'a') != r){
s[i] = (k+'a');
break;
}
}
return s;
}
};
|
1c7955ef243218937426bf1e76fc5728ffdd2d87 | 091afb7001e86146209397ea362da70ffd63a916 | /inst/include/nt2/arithmetic/include/functions/simd/fast_hypot.hpp | 0cf60f13cfb68477fa34edc733323b14a229e1b9 | [] | no_license | RcppCore/RcppNT2 | f156b58c08863243f259d1e609c9a7a8cf669990 | cd7e548daa2d679b6ccebe19744b9a36f1e9139c | refs/heads/master | 2021-01-10T16:15:16.861239 | 2016-02-02T22:18:25 | 2016-02-02T22:18:25 | 50,460,545 | 15 | 1 | null | 2019-11-15T22:08:50 | 2016-01-26T21:29:34 | C++ | UTF-8 | C++ | false | false | 266 | hpp | fast_hypot.hpp | #ifndef NT2_ARITHMETIC_INCLUDE_FUNCTIONS_SIMD_FAST_HYPOT_HPP_INCLUDED
#define NT2_ARITHMETIC_INCLUDE_FUNCTIONS_SIMD_FAST_HYPOT_HPP_INCLUDED
#include <nt2/arithmetic/functions/fast_hypot.hpp>
#include <boost/simd/arithmetic/functions/generic/fast_hypot.hpp>
#endif
|
d4b6d53a7d5b16330134f4012a906d0ee32a6c0d | 9019188667d35cca4b7a48be48eb2d9e83a31b0d | /Code/Cryptography/XORCipher.cpp | 2a7476adf076a2043fe4cd29e56782b6786cf20c | [
"MIT"
] | permissive | BambooFlower/Math-Scripts | d7ba7daab429eedb7fab833fee2c93e7c2841f61 | fbe0a672c69f5b120125d72c558bf18b5e973a1b | refs/heads/master | 2022-04-30T17:44:10.488485 | 2022-04-23T10:19:52 | 2022-04-23T10:19:52 | 246,305,495 | 4 | 3 | MIT | 2020-10-21T17:35:32 | 2020-03-10T13:16:27 | MATLAB | UTF-8 | C++ | false | false | 810 | cpp | XORCipher.cpp | // Simple cipher that XORs the plaintext with a key
/* Usage: crypto key input_file output_file */
void main (int argc, char *argv[])
{
FILE *fi, *fo;
char *cp;
int c;
if ((cp = argv[1]) && *cp!='\0') {
if ((fi = fopen(argv[2], “rb”)) != NULL) {
if ((fo = fopen(argv[3], “wb”)) != NULL) {
while ((c = getc(fi)) != EOF) {
if (!*cp) cp = argv[1];
c ^= *(cp++);
putc(c,fo);
}
fclose(fo);
}
fclose(fi);
}
}
} |
054c0b72d0a67da392a064408dbf0182f92bcf14 | 88a39e7a97abd90faa04ebf11de2d7eb53e06a10 | /uva/10783.cpp | 9a4ed555f688e617c0a11ea16a7d65ce53899feb | [] | no_license | leonnardo/icpc | a835661410b93a0d472fd4389517fe5c560dca4c | a0d718e31be458c0923fec5472c86b01bdbf032e | refs/heads/master | 2021-01-15T12:26:32.058008 | 2013-06-28T20:23:28 | 2013-06-28T20:23:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 298 | cpp | 10783.cpp | #include <cstdio>
int main() {
int a,b,t,soma,i,caso,n;
scanf("%d", &t);
caso = 1;
while (t--) {
scanf("%d", &a);
scanf("%d", &b);
if (a%2 == 0)
a++;
if (b%2 == 0)
b--;
n = ((b-a)/2)+1;
soma = (a+b)*n/2;
printf("Case %d: %d\n", caso, soma);
caso++;
}
return 0;
}
|
bab9fd52b50413b861d75b3e368f46c02bb6f642 | 0328d5d07344c7269699ea12ec0aa402798015e1 | /Cluster20150816/Cluster/NELbfgs.cpp | 07641b392742e3512364344776395d8c89667712 | [] | no_license | NelabCluster/Cluster-DE | 4821233cc341e11249453409c118ba3e6b2fe3d3 | 8295fa6a11350c19d20e28b18e94703d1ab7fb1c | refs/heads/master | 2021-01-18T22:02:03.447158 | 2016-06-12T11:31:57 | 2016-06-12T11:31:57 | 47,805,550 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,477 | cpp | NELbfgs.cpp | #include "NELbfgs.h"
#include "PE_Tool.h"
#include "Tool.h"
static lbfgsfloatval_t evaluate(
void *instance,
const lbfgsfloatval_t *x,
lbfgsfloatval_t *g,
const int n,
const lbfgsfloatval_t step
)
{
int i;
lbfgsfloatval_t fx = 0.0;
int N = n /3;
double *cood = (double *)malloc(n * sizeof(double));
for (i = 0; i < n; i++)
cood[i] = x[i];
double *R = (double *)calloc(N * N,sizeof(double));
Tool::Distance(cood,R,n/3);
fx = PE_Tool::FS_E(R,n / 3);
// fx = PE_Tool::Johnson_E(R,n / 3);
PE_Tool::FS_F(cood,R,g,n/3);
// PE_Tool::Johnson_F(cood,R,g,n/3);
for (i = 0 ;i < n; i++)
g[i] = -g[i];
free(cood);
free(R);
return fx;
}
static int progress(
void *instance,
const lbfgsfloatval_t *x,
const lbfgsfloatval_t *g,
const lbfgsfloatval_t fx,
const lbfgsfloatval_t xnorm,
const lbfgsfloatval_t gnorm,
const lbfgsfloatval_t step,
int n,
int k,
int ls
)
{
/*printf("Iteration %d:\n", k);
printf(" fx = %f\n", fx);
printf(" xnorm = %f, gnorm = %f, step = %f\n", xnorm, gnorm, step);
printf("\n");*/
return 0;
}
double NELbfgs::local(double *cood, double *force, int N)
{
int ret;
lbfgsfloatval_t fx;
lbfgs_parameter_t param;
lbfgs_parameter_init(¶m);
ret = lbfgs(N*3, cood, &fx,evaluate, progress, NULL, ¶m);
printf("L-BFGS optimization terminated with status code = %d\n", ret);
printf(" fx = %f, x[0] = %f, x[1] = %f\n", fx, cood[0], cood[1]);
return fx;
}
NELbfgs::NELbfgs(void)
{
}
NELbfgs::~NELbfgs(void)
{
}
|
0c7882e12066db7bd5657f6ec722fee7a7adccbe | 1b2eae8cae0c85c0657aa00d2e13f6fb0e93d0e0 | /LinkStack/test.cpp | beb1b8c31f7ff63761ea6d464ba1a402cf1a46ba | [] | no_license | Beautyzizi/myc- | d76942af92b7cb29799dab98a643615917f16993 | 58e620091e4b2885218148b07478b4e66ea60873 | refs/heads/master | 2021-09-14T07:57:40.966913 | 2018-05-10T08:56:10 | 2018-05-10T08:56:10 | 107,508,643 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 361 | cpp | test.cpp | #include<iostream>
#include<string>
#include"LinkStack.h"
using namespcae std;
int main()
{
LinkStack<string> lin;
lin.push("i'am");
lin.push(" ");
lin.push("cool");
cout << "栈顶元素" << lin.top()<<endl;
cout << "栈的大小" << lin.size()<<endl;
while(!lin.isEmpty())
{
lin.pop();
}
cout << "栈的大小" << lin.size() << endl;
return 0;
}
|
05fa42c7c19a43c8982b0ada954eef1fdb5e340d | 2b60d3054c6c1ee01f5628b7745ef51f5cd3f07a | /Gemotry/AdaptDynamicMeshes/ADM/surfaces/parametric.h | efd266e6b029ee6b0408e675a4844bf9c94c6dfe | [] | no_license | LUOFQ5/NumericalProjectsCollections | 01aa40e61747d0a38e9b3a3e05d8e6857f0e9b89 | 6e177a07d9f76b11beb0974c7b720cd9c521b47e | refs/heads/master | 2023-08-17T09:28:45.415221 | 2021-10-04T15:32:48 | 2021-10-04T15:32:48 | 414,977,957 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,913 | h | parametric.h | #ifndef _PARAMETRIC_SURF_
#define _PARAMETRIC_SURF_ 1
#include <adm.h>
class ParametricSurf : public ADM::Oracle
{
protected:
ADM::Matrix Jac, Wein, EigVec;
ADM::Array EigVal;
public:
ParametricSurf()
: Jac(3,2), Wein(2,2), EigVec(2,2), EigVal(2)
{ }
virtual ~ParametricSurf() { }
/*------------------------------------------------------------*/
inline void update(ADM::A48Vertex* v) { project(v); }
inline void project(ADM::A48Vertex* v, ADM::R3 n=ADM::R3())
{ v->set_pos( position(v->pos()) ); }
inline double error(const ADM::R3& p)
{ return (position(p) - p).length(); }
/*------------------------------------------------------------*/
virtual void normal(ADM::A48Vertex* v)
{ v->set_normal( parametric_normal(v->pos()) ); }
virtual void curvature(ADM::A48Vertex* v)
{
ADM::R3 d1, d2;
double k1, k2, km, kg;
parametric_curvature( v->pos(), k1, k2, d1, d2, km, kg);
v->set_max_curv(k1); v->set_min_curv(k2);
v->set_max_direc(d1); v->set_min_direc(d2);
v->set_gaus_curv(kg); v->set_mean_curv(km);
}
/*------------------------------------------------------------*/
ADM::R3 position(const ADM::R3& p)
{
double u, v;
parameterization( p, u, v );
return coordinates( u, v );
}
ADM::R3 parametric_normal(const ADM::R3& p)
{
double u, v;
parameterization( p, u, v );
ADM::R3 d_u = deriv_u(u,v);
ADM::R3 d_v = deriv_v(u,v);
ADM::R3 n = cross( d_u, d_v );
n.normalize();
return n;
}
void parametric_curvature(const ADM::R3& p,
double& k1, double& k2,
ADM::R3& d1, ADM::R3& d2,
double& km, double& kg)
{
double u, v;
parameterization( p, u, v );
// Jacobian matrix
ADM::R3 d_u = deriv_u(u,v), d_v = deriv_v(u,v);
Jac[0][0] = d_u.x; Jac[0][1] = d_v.x;
Jac[1][0] = d_u.y; Jac[1][1] = d_v.y;
Jac[2][0] = d_u.z; Jac[2][1] = d_v.z;
// First fundamental form
double E = dot( d_u, d_u );
double F = dot( d_u, d_v );
double G = dot( d_v, d_v );
// Second fundamental form
ADM::R3 d_uu=deriv_uu(u,v), d_uv=deriv_uv(u,v), d_vv=deriv_vv(u,v);
ADM::R3 n = cross( d_u,d_v ); n.normalize();
double e = dot( n, d_uu );
double f = dot( n, d_uv );
double g = dot( n, d_vv );
double den = E*G - F*F;
kg = (e*g - f*f) / den; // gaussian curv
km = -0.5*(e*G - 2*f*F + g*E) / den; // mean curv
// dN matrix
Wein[0][0] = (f*F - e*G)/den; Wein[0][1] = (g*F - f*G)/den;
Wein[1][0] = (e*F - f*E)/den; Wein[1][1] = (f*F - g*E)/den;
ADM::Eigen eig(Wein);
eig.getRealEigenvalues(EigVal);
eig.getV(EigVec);
int vmax, vmin;
if (EigVal[0]>=EigVal[1]) { vmax = 0; vmin = 1; }
else { vmax = 1; vmin = 0; }
k1 = EigVal[vmax]; // max curv
k2 = EigVal[vmin]; // min curv
ADM::Matrix P(3,2);
P = TNT::matmult( Jac, EigVec );
// max direc
d1 = ADM::R3( P[0][vmax], P[1][vmax], P[2][vmax] );
d1.normalize();
// min direc
d2 = ADM::R3( P[0][vmin], P[1][vmin], P[2][vmin] );
d2.normalize();
}
/*------------------------------------------------------------*/
virtual void parameterization( const ADM::R3& p, double& u, double& v ) = 0;
virtual ADM::R3 coordinates(const double& u, const double& v) = 0;
virtual ADM::R3 deriv_u (const double& u, const double& v) = 0;
virtual ADM::R3 deriv_v (const double& u, const double& v) = 0;
virtual ADM::R3 deriv_uu(const double& u, const double& v) = 0;
virtual ADM::R3 deriv_uv(const double& u, const double& v) = 0;
virtual ADM::R3 deriv_vv(const double& u, const double& v) = 0;
};
#endif
|
b16aad8c931e391d90bdb19a525b2ceeb330eb7c | 7d023c350e2b05c96428d7f5e018a74acecfe1d2 | /my_auv2000_ros/devel/include/utils/altimeter_stamped.h | a92d438cfb52b9f645841d81f17a970500ad1e01 | [] | no_license | thanhhaibk96/VIAM_AUV2000_ROS | 8cbf867e170212e1f1559aa38c36f22d6f5237ad | fe797304fe9283eaf95fe4fa4aaabb1fe1097c92 | refs/heads/main | 2023-06-06T14:15:39.519361 | 2021-06-19T06:01:19 | 2021-06-19T06:01:19 | 376,807,938 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,465 | h | altimeter_stamped.h | // Generated by gencpp from file utils/altimeter_stamped.msg
// DO NOT EDIT!
#ifndef UTILS_MESSAGE_ALTIMETER_STAMPED_H
#define UTILS_MESSAGE_ALTIMETER_STAMPED_H
#include <string>
#include <vector>
#include <map>
#include <ros/types.h>
#include <ros/serialization.h>
#include <ros/builtin_message_traits.h>
#include <ros/message_operations.h>
namespace utils
{
template <class ContainerAllocator>
struct altimeter_stamped_
{
typedef altimeter_stamped_<ContainerAllocator> Type;
altimeter_stamped_()
: alt_in_metres(0.0)
, alt_in_fathoms(0.0)
, alt_in_feet(0.0) {
}
altimeter_stamped_(const ContainerAllocator& _alloc)
: alt_in_metres(0.0)
, alt_in_fathoms(0.0)
, alt_in_feet(0.0) {
(void)_alloc;
}
typedef float _alt_in_metres_type;
_alt_in_metres_type alt_in_metres;
typedef float _alt_in_fathoms_type;
_alt_in_fathoms_type alt_in_fathoms;
typedef float _alt_in_feet_type;
_alt_in_feet_type alt_in_feet;
typedef boost::shared_ptr< ::utils::altimeter_stamped_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::utils::altimeter_stamped_<ContainerAllocator> const> ConstPtr;
}; // struct altimeter_stamped_
typedef ::utils::altimeter_stamped_<std::allocator<void> > altimeter_stamped;
typedef boost::shared_ptr< ::utils::altimeter_stamped > altimeter_stampedPtr;
typedef boost::shared_ptr< ::utils::altimeter_stamped const> altimeter_stampedConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::utils::altimeter_stamped_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::utils::altimeter_stamped_<ContainerAllocator> >::stream(s, "", v);
return s;
}
template<typename ContainerAllocator1, typename ContainerAllocator2>
bool operator==(const ::utils::altimeter_stamped_<ContainerAllocator1> & lhs, const ::utils::altimeter_stamped_<ContainerAllocator2> & rhs)
{
return lhs.alt_in_metres == rhs.alt_in_metres &&
lhs.alt_in_fathoms == rhs.alt_in_fathoms &&
lhs.alt_in_feet == rhs.alt_in_feet;
}
template<typename ContainerAllocator1, typename ContainerAllocator2>
bool operator!=(const ::utils::altimeter_stamped_<ContainerAllocator1> & lhs, const ::utils::altimeter_stamped_<ContainerAllocator2> & rhs)
{
return !(lhs == rhs);
}
} // namespace utils
namespace ros
{
namespace message_traits
{
template <class ContainerAllocator>
struct IsFixedSize< ::utils::altimeter_stamped_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::utils::altimeter_stamped_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::utils::altimeter_stamped_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::utils::altimeter_stamped_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::utils::altimeter_stamped_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::utils::altimeter_stamped_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::utils::altimeter_stamped_<ContainerAllocator> >
{
static const char* value()
{
return "f58ef2ca5af8aa8fd2854fb20c9956ae";
}
static const char* value(const ::utils::altimeter_stamped_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0xf58ef2ca5af8aa8fULL;
static const uint64_t static_value2 = 0xd2854fb20c9956aeULL;
};
template<class ContainerAllocator>
struct DataType< ::utils::altimeter_stamped_<ContainerAllocator> >
{
static const char* value()
{
return "utils/altimeter_stamped";
}
static const char* value(const ::utils::altimeter_stamped_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::utils::altimeter_stamped_<ContainerAllocator> >
{
static const char* value()
{
return "float32 alt_in_metres\n"
"float32 alt_in_fathoms\n"
"float32 alt_in_feet\n"
;
}
static const char* value(const ::utils::altimeter_stamped_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::utils::altimeter_stamped_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.alt_in_metres);
stream.next(m.alt_in_fathoms);
stream.next(m.alt_in_feet);
}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct altimeter_stamped_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::utils::altimeter_stamped_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::utils::altimeter_stamped_<ContainerAllocator>& v)
{
s << indent << "alt_in_metres: ";
Printer<float>::stream(s, indent + " ", v.alt_in_metres);
s << indent << "alt_in_fathoms: ";
Printer<float>::stream(s, indent + " ", v.alt_in_fathoms);
s << indent << "alt_in_feet: ";
Printer<float>::stream(s, indent + " ", v.alt_in_feet);
}
};
} // namespace message_operations
} // namespace ros
#endif // UTILS_MESSAGE_ALTIMETER_STAMPED_H
|
35d2245b33996aae53db5066d4ce1478a6e4c0fe | 2cf73a50d11af8104e979bb9a2180f482ac5af8b | /bai8task4.cpp | eea25e169dd9e2751fa7a0dbc6f3645a54532e43 | [] | no_license | phamvannam191199/task4 | 2efa696b85b7bcf08ea1503aba404a3b326bcead | 13daece2b914b907dcd7869c49382b3cad1908c0 | refs/heads/main | 2023-04-14T17:09:11.004818 | 2021-04-22T11:56:20 | 2021-04-22T11:56:20 | 360,501,889 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 630 | cpp | bai8task4.cpp | #include<stdio.h>
int main(){
printf("/*=========kich thuoc cua cac kieu du lieu=======*\n");
printf("kieu int : 4 byet\n");
printf("so nguyen :15\n");
printf("kieu float : 4 byet \n");
printf("so thuc kieu float : 3.456000\n");
printf("kieu double : 8 byet \n");
printf("so thuc kieu double : 3.45678912345\n");
printf("kieu char : 1 byet \n");
printf("ki tu :E\n");
printf("kieu long int : 4 byet \n");
printf("kieu double int : 12 byet\n");
printf("/*==============================================*/\n");
printf("Bam mot phim bat ki de ket thuc chuong trinh");
}
|
464e571684c7f25107bdd8efd28102875b139c66 | cd9e6b3d7de4080f03fef3a543bcbb251b6f1c99 | /tp2/ast/astArrayElementValue.cpp | 2ca598ae332bfadf7d6873ee88f3b4ca6f331d7c | [] | no_license | DanielaSimoes/Compilers-LFA | c072d3dd6e8df4f93d43b43653e21211f96ab813 | ba8303278fc6dee3351095419bf999e52ed991ca | refs/heads/master | 2021-01-17T16:04:02.931342 | 2016-06-28T22:57:30 | 2016-06-28T22:57:30 | 62,659,742 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 958 | cpp | astArrayElementValue.cpp | #include "astArrayElementValue.h"
#include <stdint.h>
#include <stdio.h>
////////////////////////////////////////////////////
void ASTArrayElementValue::show(uint32_t indent)
{
fprintf(stdout, ";%*s ASTArrayElementValue\n", 4*indent, "");
}
void ASTArrayElementValue::generateLSM(FILE* fout)
{
fprintf(fout, "%15s; accessing element value on array %s\n", " ", label.c_str());
if (ASTNode::text == 0) {
fprintf(fout, "%15s.text", " ");
ASTNode::text = 1;
}
if (type == INT || type == STRING) {
fprintf(fout, "%15sla %s\n", " ", label.c_str());
value->generateLSM(fout);
fprintf(fout, "%15siaload\n", " ");
fprintf(fout, "\n");
} else if (type == FLOAT) {
fprintf(fout, "%15sla %s\n", " ", label.c_str());
value->generateLSM(fout);
fprintf(fout, "%15sfaload\n", " ");
fprintf(fout, "\n");
}
}
////////////////////////////////////////////////////
|
75843b3e322ecf2f3d725735f7d3e97dfbd4df8b | ca18adcd3a4b75f34316a4f0b417158ea5ce91be | /round1review/309. Best Time to Buy and Sell Stock with Cooldown.cpp | 81630d7d5fc05a41f271979589e57aa45c99debd | [] | no_license | lzhpku/leetcode | 0abcd655dfd0bbd17300f8efe76167bdf76cee5e | 6b3b0a429f6d0661fb65cc9f78ec34407a2e2037 | refs/heads/master | 2021-01-19T03:31:36.473193 | 2016-10-28T15:42:28 | 2016-10-28T15:42:28 | 65,123,502 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 389 | cpp | 309. Best Time to Buy and Sell Stock with Cooldown.cpp | class Solution {
public:
int maxProfit(vector<int>& prices) {
int sold = 0, cool = 0, hold = -0x7fffffff;
for(int i = 0; i < prices.size(); i ++) {
int presold = sold;
sold = hold + prices[i];
hold = max(hold, cool - prices[i]);
cool = max(presold, cool);
}
return max(cool, sold);
}
}; |
5b0ec4e17e7de356eafc277fb771cbd9ff791269 | fbbab7857b52b54e6df14ddae84e8a1d4229c19f | /rotate_array.cpp | 5f7a9b5ffc0f0854f0b33569a1109e0fa98f573f | [] | no_license | mansigarg-nith/Array-DataStructures | b6e5f32b089e5ef733db81e0bb1342e177009686 | f719f8b04379cf59f154b4610977180a8aedacae | refs/heads/main | 2023-02-15T09:59:43.492175 | 2021-01-12T13:25:08 | 2021-01-12T13:25:08 | 328,993,427 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,272 | cpp | rotate_array.cpp | #include <iostream>
using namespace std;
void left(int arr[], int n){
int x;
cout<<"Enter the no. of elements by which array is to be rotated: ";
cin>>x;
int temp[x];
for(int i=0; i<x; i++){
temp[i] = arr[i];
}
for(int j=0; j<x; j++){
for(int i=0; i<n; i++){
arr[i] = arr[i+1];
}
}
for(int i=0; i<x; i++){
arr[n-1-i] = temp[x-i-1];
}
cout<<"Left-rotated array is: ";
for(int i=0; i<n; i++){
cout<<arr[i]<<" ";
}
}
void right(int arr[], int n){
int x;
cout<<"Enter the no. of elements by which array is to be rotated: ";
cin>>x;
int temp[x];
for(int i=0; i<x; i++){
temp[x-i-1] = arr[n-1-i];
}
for(int i=0; i<x; i++){
for(int i=0; i<n; i++){
arr[n-1-i] = arr[n-2-i];
}
}
for(int i=0; i<x; i++){
arr[i] = temp[i];
}
cout<<"Right-rotated array is: ";
for(int i=0; i<n; i++){
cout<<arr[i]<<" ";
}
}
int main(){
int n;
cout<<"Enter the size of the array: ";
cin>>n;
int arr[n];
cout<<"Enter the elements of the array: ";
for(int i=0; i<n; i++){
cin>>arr[i];
}
char ch;
cout<<"Left/Right rotation. Enter l/r: ";
cin>>ch;
switch(ch){
case 'l':
left(arr,n);
break;
case 'r':
right(arr,n);
break;
default:
cout<<"Invalid!";
}
}
|
ac1b614ae0b92dc248839933c5072b6dcfde3e3e | 536ba9f25d2b6b87dae8d05b3bcdf614b848232c | /UI/Widgets/Attachments/attachment.cpp | 9ec1d54203ae300d691c59f65297fc0ce7912071 | [] | no_license | Shilza/QTsatTCPClient | fcfdef0117ac5a0e979303029f00370793cd600a | df8462a27e4940469e687a033b18488ce5b69376 | refs/heads/master | 2021-09-07T06:03:36.144907 | 2018-02-18T11:40:32 | 2018-02-18T11:40:32 | 115,352,832 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 836 | cpp | attachment.cpp | #include "attachment.h"
Attachment::Attachment(QWidget *parent) : QWidget(parent){
mainFrame = new QPushButton;
mainFrame->setCursor(Qt::PointingHandCursor);
connect(mainFrame, SIGNAL(released()), SLOT(open()));
connect(&(FTPClient::getInstance()), SIGNAL(getting(QByteArray)), SLOT(fill(QByteArray)));
connect(&(FTPClient::getInstance()), SIGNAL(sizeWasGotten(int)), SLOT(setAttachmentSize(int)));
}
QPushButton *Attachment::getMainFrame() const{
return mainFrame;
}
Attachment::~Attachment(){
delete mainFrame;
delete mainLayout;
}
void Attachment::setAttachmentSize(int sizeOfAttachment){
qDebug() << "sizeOfAaaa" << sizeOfAttachment;
this->sizeOfAttachment = sizeOfAttachment;
disconnect(&(FTPClient::getInstance()), SIGNAL(sizeWasGotten(int)), this, SLOT(setAttachmentSize(int)));
}
|
a116508bd618140fff6dff40b919e7ea6d670e69 | abd55b2805cd3930cf00e96beae28e69c2bf2f86 | /source/adios2/toolkit/format/dataman/DataManSerializer.h | e2092d2d76bfd6a2a5e69bb0bf3683ad918e934f | [
"Apache-2.0"
] | permissive | fbudin69500/ADIOS2 | 2789226d9ab798860778fb5a590955b20b985d59 | 2c6dfa753b7ab59615a9bd1e2ab1b6bad19f909c | refs/heads/master | 2020-03-18T04:40:40.005617 | 2019-01-15T04:02:42 | 2019-01-15T04:02:42 | 134,300,059 | 0 | 0 | null | 2018-05-21T17:08:38 | 2018-05-21T17:08:37 | null | UTF-8 | C++ | false | false | 2,909 | h | DataManSerializer.h | /*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* accompanying file Copyright.txt for details.
*
* DataManSerializer.h Serializer class for DataMan streaming format
*
* Created on: May 11, 2018
* Author: Jason Wang
*/
#ifndef ADIOS2_TOOLKIT_FORMAT_DATAMAN_DATAMANSERIALIZER_H_
#define ADIOS2_TOOLKIT_FORMAT_DATAMAN_DATAMANSERIALIZER_H_
#include <nlohmann/json.hpp>
#include "adios2/ADIOSTypes.h"
#include "adios2/core/IO.h"
#include "adios2/core/Variable.h"
#include <mutex>
#include <unordered_map>
// A - Address
// C - Count
// D - Data Object ID or File Name
// E - Endian
// G - Global Value
// H - Meatadata Hash
// I - Data Size
// M - Major
// N - Variable Name
// O - Start
// P - Position of Memory Block
// S - Shape
// V - Is Single Value
// X - Index (Used only in deserializer)
// Y - Data Type
// Z - Compression Method
// ZP - Compression Parameters
namespace adios2
{
namespace format
{
class DataManSerializer
{
public:
DataManSerializer(bool isRowMajor, const bool contiguousMajor,
bool isLittleEndian);
void New(size_t size);
template <class T>
void Put(const T *inputData, const std::string &varName,
const Dims &varShape, const Dims &varStart, const Dims &varCount,
const Dims &varMemStart, const Dims &varMemCount,
const std::string &doid, const size_t step, const int rank,
const std::string &address, const Params ¶ms);
template <class T>
void Put(const core::Variable<T> &variable, const std::string &doid,
const size_t step, const int rank, const std::string &address,
const Params ¶ms);
void PutAttributes(core::IO &io, const int rank);
const std::shared_ptr<std::vector<char>> Get();
float GetMetaRatio();
static std::shared_ptr<std::vector<char>> EndSignal(size_t step);
private:
template <class T>
bool Zfp(nlohmann::json &metaj, size_t &datasize, const T *inputData,
const Dims &varCount, const Params ¶ms);
template <class T>
bool Sz(nlohmann::json &metaj, size_t &datasize, const T *inputData,
const Dims &varCount, const Params ¶ms);
template <class T>
bool BZip2(nlohmann::json &metaj, size_t &datasize, const T *inputData,
const Dims &varCount, const Params ¶ms);
template <class T>
void PutAttribute(const core::Attribute<T> &attribute, const int rank);
bool IsCompressionAvailable(const std::string &method,
const std::string &type, const Dims &count);
std::shared_ptr<std::vector<char>> m_Buffer;
nlohmann::json m_Metadata;
std::vector<char> m_CompressBuffer;
size_t m_Position = 0;
bool m_IsRowMajor;
bool m_IsLittleEndian;
bool m_ContiguousMajor;
};
} // end namespace format
} // end namespace adios2
#endif
|
2b837e620d17afa229841ff419a2bfe925326013 | 00c3d76394707da69cb24c1aaea0fe6f726a9b8b | /NUTS/ROMDiskDirectory.h | e923b7fd4a60e9e772de8e390ed49c563b009d0c | [] | no_license | RebeccaPhu/NUTS | 73de317e35a43775aa0ab3cbff3e09f4379e84b8 | b571d1ac8225cae7faa9d036a33838886cee7f90 | refs/heads/master | 2023-03-08T02:08:45.290139 | 2023-02-10T22:53:19 | 2023-02-10T22:53:19 | 256,739,354 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 904 | h | ROMDiskDirectory.h | #pragma once
#include "Directory.h"
#include "NUTSConstants.h"
#include "TempFile.h"
#include "FOP.h"
#define ROMDiskFSType L"ROMDisk_Extraneous"
class ROMDiskDirectory :
public Directory
{
public:
ROMDiskDirectory( DataSource *pDataSource ) : Directory( pDataSource )
{
DirectoryID = 0;
}
~ROMDiskDirectory(void)
{
CleanFiles();
}
int ReadDirectory(void);
int WriteDirectory(void);
public:
std::wstring( ProgramDataPath );
QWORD DirectoryID;
void *pSrcFS;
FOPTranslateFunction ProcessFOP;
std::map<DWORD, FOPReturn> FileFOPData;
void Empty()
{
DirectoryID = 0;
FileFOPData.clear();
ResolvedIcons.clear();
}
private:
void ReadNativeFile( QWORD FileIndex, NativeFile *pFile );
BYTEString ReadString( CTempFile &file );
void WriteNativeFile( QWORD FileIndex, NativeFile *pFile );
void WriteString( CTempFile &file, BYTEString &strng );
void CleanFiles();
};
|
1086404cf194cc60f4e83aa443dfdf7737cd0d16 | 910d634de833e81bdbd6269be1950f36b75b765d | /Tile2D/Physics/TileSet.cpp | c6743f9f825d484eb2dcc620a849ab1202435140 | [
"MIT"
] | permissive | mipelius/tile2d | ccc2c3adb4fd3375797babfd3e3ba9090967e805 | 7cbc62d6b47afdea11a7775d25f9e91c900cc627 | refs/heads/master | 2021-09-20T18:34:50.480325 | 2018-07-26T22:16:07 | 2018-07-26T22:16:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,576 | cpp | TileSet.cpp | // MIT License
//
// This file is part of SpaceGame.
// Copyright (c) 2014-2018 Miika Pelkonen
//
// 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 <iostream>
#include "TileSet.h"
#include "MapTexture.h"
#include "JsonFileManager.h"
#include "Tile.h"
TileSet::TileSet(std::string jsonFilename) :
blocks_(std::vector<Tile*>(256))
{
emptyBlock_ = new Tile("empty block", 0.0, 1.0, 1.0, {-1, 0, 0, nullptr});
for (int i = 0; i < 256; i++) {
blocks_[i] = nullptr;
}
json::Object obj = JsonFileManager::load(std::move(jsonFilename));
json::Object commonProperties = obj["commonProperties"].ToObject();
tileW_ = commonProperties["width"].ToInt();
tileH_ = commonProperties["height"].ToInt();
mapTexture_ = new MapTexture(
commonProperties["width"].ToInt(),
commonProperties["height"].ToInt()
);
json::Array blocksJson = obj["blocks"].ToArray();
for (const auto &jsonObj : blocksJson) {
auto blockJson = jsonObj.ToObject();
blocks_[blockJson["id"].ToInt()] = new Tile(blockJson, mapTexture_);
}
}
Tile* TileSet::getTile(unsigned char id) {
return blocks_[id];
}
MapTexture * TileSet::getMapTexture() {
return mapTexture_;
}
TileSet::~TileSet() {
delete emptyBlock_;
delete mapTexture_;
for (auto block : blocks_) {
if (block != nullptr) delete block;
}
}
Tile* TileSet::getEmptyBlock() {
return emptyBlock_;
}
int TileSet::getTileW() {
return tileW_;
}
int TileSet::getTileH() {
return tileH_;
}
|
ac0cd233c8fc73b5b34bc3671442e542a579f3d2 | 0bad107153966793c10523f9ea0c4e6536ed86dc | /chapter05/519.cpp | 28ea536cf37c45aca94770cadeee7d68a0e025a4 | [] | no_license | HersonaREAL/my_cpp_primer_code | 489b50a20be929ef702afa1a19f9401f31530b9d | 87265a26ece711ae42c45ef92868597c561b7331 | refs/heads/master | 2023-03-16T13:26:52.418336 | 2021-03-11T07:46:54 | 2021-03-11T07:46:54 | 318,469,858 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 436 | cpp | 519.cpp | #include<iostream>
#include<vector>
#include<cctype>
using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::vector;
int main(){
string rsp;
do{
string str1,str2;
cout<<"input first string:";
cin>>str1;
cout<<"input second string:";
cin>>str2;
cout<<"The shorter string is : "<<(str1.size()>str2.size()?str2:str1)<<endl;
cout<<"continue?(y/n):";
}while(cin>>rsp&&rsp[0]!='n');
return 0;
}
|
1522f415b2a1c6f582449ec029af7d226bf340b7 | 7b025df774510c8da329f2c9a32af01d4534b36d | /src/logger_dummy.cpp | e11949c9ca9fe999f5efebf264d4f4fef4751e98 | [] | no_license | zhou0/torchat | 93c751ed51333ccb73f598a744c6ab0fdffa1c9d | 2531eccd7d1fc28b88b33d4e386b9bcc3a463783 | refs/heads/master | 2021-06-25T00:40:26.504710 | 2017-05-02T23:27:45 | 2017-05-02T23:27:45 | 105,850,559 | 1 | 1 | null | 2017-10-05T04:50:11 | 2017-10-05T04:50:11 | null | UTF-8 | C++ | false | false | 837 | cpp | logger_dummy.cpp | #define LOGURU_IMPLEMENTATION 1
#include "include/loguru.hpp"
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <pthread.h>
#include <string.h>
#include <stdlib.h>
static pthread_mutex_t *sem = NULL; // mutex to initialize when the log files are used outside of loguru
// eg: when parsing the logs
static char *infoLog = NULL; // store name of the infoLog
static char *errLog = NULL; // same, err
static char *debLog = NULL; // same, debug
/*
* loguru is already thread safe,
* so no need to use mutex for luguru actions
*/
extern "C" void
log_info (const char *json)
{
return;
}
extern "C" void
log_err (const char *err)
{
return;
}
extern "C" void
log_init (const char *name, const char *verbosity)
{
// initialize a log
return ;
}
extern "C" void
log_clear_datastructs ()
{
return;
}
|
15eb3d4c818a0b26cb393aec70742184ccbe102c | 9939aab9b0bd1dcf8f37d4ec315ded474076b322 | /components/containers/partitioned_vector/include/hpx/components/containers/partitioned_vector/partitioned_vector_decl.hpp | 0e9afacaa09f7ff968080d852dca46f61e8c817f | [
"BSL-1.0",
"LicenseRef-scancode-free-unknown"
] | permissive | STEllAR-GROUP/hpx | 1068d7c3c4a941c74d9c548d217fb82702053379 | c435525b4631c5028a9cb085fc0d27012adaab8c | refs/heads/master | 2023-08-30T00:46:26.910504 | 2023-08-29T14:59:39 | 2023-08-29T14:59:39 | 4,455,628 | 2,244 | 500 | BSL-1.0 | 2023-09-14T13:54:12 | 2012-05-26T15:02:39 | C++ | UTF-8 | C++ | false | false | 50,154 | hpp | partitioned_vector_decl.hpp | // Copyright (c) 2014 Anuj R. Sharma
// Copyright (c) 2014-2022 Hartmut Kaiser
//
// SPDX-License-Identifier: BSL-1.0
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
/// \file hpx/components/partitioned_vector/partitioned_vector.hpp
#pragma once
#include <hpx/config.hpp>
#include <hpx/actions_base/traits/is_distribution_policy.hpp>
#include <hpx/assert.hpp>
#include <hpx/async_base/launch_policy.hpp>
#include <hpx/async_combinators/wait_all.hpp>
#include <hpx/async_combinators/when_all.hpp>
#include <hpx/components/client_base.hpp>
#include <hpx/components/get_ptr.hpp>
#include <hpx/distribution_policies/container_distribution_policy.hpp>
#include <hpx/functional/bind.hpp>
#include <hpx/modules/errors.hpp>
#include <hpx/runtime_components/distributed_metadata_base.hpp>
#include <hpx/runtime_components/new.hpp>
#include <hpx/runtime_distributed/copy_component.hpp>
#include <hpx/components/containers/partitioned_vector/export_definitions.hpp>
#include <hpx/components/containers/partitioned_vector/partitioned_vector_component_decl.hpp>
#include <hpx/components/containers/partitioned_vector/partitioned_vector_fwd.hpp>
#include <hpx/components/containers/partitioned_vector/partitioned_vector_segmented_iterator.hpp>
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <iterator>
#include <memory>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
///////////////////////////////////////////////////////////////////////////////
/// \cond NOINTERNAL
namespace hpx::server {
///////////////////////////////////////////////////////////////////////////
struct partitioned_vector_config_data
{
// Each partition is described by it's corresponding client object, its
// size, and locality id.
struct partition_data
{
partition_data()
: size_(0)
, locality_id_(naming::invalid_locality_id)
{
}
partition_data(id_type const& part, std::size_t size,
std::uint32_t locality_id)
: partition_(part)
, size_(size)
, locality_id_(locality_id)
{
}
id_type const& get_id() const
{
return partition_;
}
hpx::id_type partition_;
std::size_t size_;
std::uint32_t locality_id_;
private:
friend class hpx::serialization::access;
template <typename Archive>
void serialize(Archive& ar, unsigned)
{
ar& partition_& size_& locality_id_;
}
};
partitioned_vector_config_data()
: size_(0)
{
}
partitioned_vector_config_data(
std::size_t size, std::vector<partition_data>&& partitions)
: size_(size)
, partitions_(HPX_MOVE(partitions))
{
}
std::size_t size_;
std::vector<partition_data> partitions_;
private:
friend class hpx::serialization::access;
template <typename Archive>
void serialize(Archive& ar, unsigned)
{
ar& size_& partitions_;
}
};
} // namespace hpx::server
HPX_DISTRIBUTED_METADATA_DECLARATION(
hpx::server::partitioned_vector_config_data,
hpx_server_partitioned_vector_config_data)
/// \endcond
namespace hpx {
/// hpx::partitioned_vector is a sequence container that encapsulates
/// dynamic size arrays.
///
/// \note A hpx::partitioned_vector does not stores all elements in a
/// contiguous block of memory. Memory is contiguous inside each of
/// the segmented partitions only.
///
/// The hpx::partitioned_vector is a segmented data structure which is a
/// collection of one
/// or more hpx::server::partitioned_vector_partitions. The hpx::partitioned_vector
/// stores the global
/// ids of each hpx::server::partitioned_vector_partition and the size of each
/// hpx::server::partitioned_vector_partition.
///
/// The storage of the vector is handled automatically, being expanded and
/// contracted as needed. Vectors usually occupy more space than static arrays,
/// because more memory is allocated to handle future growth. This way a vector
/// does not need to reallocate each time an element is inserted, but only when
/// the additional memory is exhausted.
///
/// This contains the client side implementation of the
/// hpx::partitioned_vector. This
/// class defines the synchronous and asynchronous API's for each of the
/// exposed functionalities.
///
/// \tparam T The type of the elements. The requirements that are imposed
/// on the elements depend on the actual operations performed
/// on the container. Generally, it is required that element type
/// is a complete type and meets the requirements of Erasable,
/// but many member functions impose stricter requirements.
///
template <typename T, typename Data>
class partitioned_vector
: public hpx::components::client_base<partitioned_vector<T, Data>,
hpx::components::server::distributed_metadata_base<
server::partitioned_vector_config_data>>
{
public:
typedef typename Data::allocator_type allocator_type;
typedef typename Data::size_type size_type;
typedef typename Data::difference_type difference_type;
typedef T value_type;
typedef T reference;
typedef T const const_reference;
#if defined(HPX_NATIVE_MIC)
typedef T* pointer;
typedef T const* const_pointer;
#else
typedef typename std::allocator_traits<allocator_type>::pointer pointer;
typedef typename std::allocator_traits<allocator_type>::const_pointer
const_pointer;
#endif
private:
typedef hpx::components::client_base<partitioned_vector,
hpx::components::server::distributed_metadata_base<
server::partitioned_vector_config_data>>
base_type;
typedef hpx::server::partitioned_vector<T, Data>
partitioned_vector_partition_server;
typedef hpx::partitioned_vector_partition<T, Data>
partitioned_vector_partition_client;
struct partition_data
: server::partitioned_vector_config_data::partition_data
{
typedef server::partitioned_vector_config_data::partition_data
base_type;
partition_data()
: base_type()
{
}
partition_data(id_type const& part, std::size_t size,
std::uint32_t locality_id)
: base_type(part, size, locality_id)
{
}
partition_data(base_type&& base)
: base_type(HPX_MOVE(base))
{
}
std::shared_ptr<partitioned_vector_partition_server> local_data_;
};
// The list of partitions belonging to this vector.
// Each partition is described by it's corresponding client object, its
// size, and locality id.
typedef std::vector<partition_data> partitions_vector_type;
size_type size_; // overall size of the vector
size_type partition_size_; // cached partition size
// This is the vector representing the base_index and corresponding
// global ID's of the underlying partitioned_vector_partitions.
partitions_vector_type partitions_;
public:
typedef segmented::vector_iterator<T, Data> iterator;
typedef segmented::const_vector_iterator<T, Data> const_iterator;
typedef std::reverse_iterator<iterator> reverse_iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
typedef segmented::local_vector_iterator<T, Data> local_iterator;
typedef segmented::const_local_vector_iterator<T, Data>
const_local_iterator;
typedef segmented::segment_vector_iterator<T, Data,
typename partitions_vector_type::iterator>
segment_iterator;
typedef segmented::const_segment_vector_iterator<T, Data,
typename partitions_vector_type::const_iterator>
const_segment_iterator;
typedef segmented::local_segment_vector_iterator<T, Data,
typename partitions_vector_type::iterator>
local_segment_iterator;
typedef segmented::local_segment_vector_iterator<T, Data,
typename partitions_vector_type::const_iterator>
const_local_segment_iterator;
private:
friend class segmented::vector_iterator<T, Data>;
friend class segmented::const_vector_iterator<T, Data>;
friend class segmented::segment_vector_iterator<T, Data,
typename partitions_vector_type::iterator>;
friend class segmented::const_segment_vector_iterator<T, Data,
typename partitions_vector_type::const_iterator>;
std::size_t get_partition_size() const;
std::size_t get_global_index(std::size_t segment, std::size_t part_size,
size_type local_index) const;
///////////////////////////////////////////////////////////////////////
// Connect this vector to the existing vector using the given symbolic
// name.
void get_data_helper(
id_type id, server::partitioned_vector_config_data data);
// this will be called by the base class once the registered id becomes
// available
future<void> connect_to_helper(id_type id);
public:
future<void> connect_to(std::string const& symbolic_name);
void connect_to(launch::sync_policy, std::string const& symbolic_name);
// Register this vector with AGAS using the given symbolic name
future<void> register_as(std::string const& symbolic_name);
void register_as(launch::sync_policy, std::string const& symbolic_name);
// construct from id
partitioned_vector(future<id_type>&& f);
public:
// Return the sequence number of the segment corresponding to the
// given global index
std::size_t get_partition(size_type global_index) const;
// Return the local index inside the segment corresponding to the
// given global index
std::size_t get_local_index(size_type global_index) const;
// Return the local indices inside the segment corresponding to the
// given global indices
std::vector<size_type> get_local_indices(
std::vector<size_type> indices) const;
// Return the global index corresponding to the local index inside the
// given segment.
template <typename SegmentIter>
std::size_t get_global_index(
SegmentIter const& it, size_type local_index) const
{
std::size_t part_size = partition_size_;
if (part_size == std::size_t(-1) || part_size == 0)
return size_;
std::size_t segment = it.base() - partitions_.cbegin();
if (segment == partitions_.size())
return size_;
return get_global_index(segment, part_size, local_index);
}
template <typename SegmentIter>
std::size_t get_partition(SegmentIter const& it) const
{
return std::distance(partitions_.begin(), it.base());
}
// Return the local iterator referencing an element inside a segment
// based on the given global index.
local_iterator get_local_iterator(size_type global_index) const;
const_local_iterator get_const_local_iterator(
size_type global_index) const;
// Return the segment iterator referencing a segment based on the
// given global index.
segment_iterator get_segment_iterator(size_type global_index);
const_segment_iterator get_const_segment_iterator(
size_type global_index) const;
protected:
/// \cond NOINTERNAL
typedef std::pair<hpx::id_type, std::vector<hpx::id_type>>
bulk_locality_result;
/// \endcond
template <typename DistPolicy>
static hpx::future<std::vector<bulk_locality_result>> create_helper1(
DistPolicy const& policy, std::size_t count, std::size_t size);
template <typename DistPolicy>
static hpx::future<std::vector<bulk_locality_result>> create_helper2(
DistPolicy const& policy, std::size_t count, std::size_t size,
T const& val);
struct get_ptr_helper;
// This function is called when we are creating the vector. It
// initializes the partitions based on the give parameters.
template <typename DistPolicy, typename Create>
void create(DistPolicy const& policy, Create&& creator);
template <typename DistPolicy>
void create(DistPolicy const& policy);
template <typename DistPolicy>
void create(T const& val, DistPolicy const& policy);
// Perform a deep copy from the given vector
void copy_from(partitioned_vector const& rhs);
public:
/// Default Constructor which create hpx::partitioned_vector with
/// \a num_partitions = 0 and \a partition_size = 0. Hence overall size
/// of the vector is 0.
///
partitioned_vector();
/// Constructor which create hpx::partitioned_vector with the given
/// overall \a size
///
/// \param size The overall size of the vector
///
partitioned_vector(size_type size);
/// Constructor which create and initialize vector with the
/// given \a where all elements are initialized with \a val.
///
/// \param size The overall size of the vector
/// \param val Default value for the elements in vector
/// \param symbolic_name The (optional) name to register the newly
/// created vector
///
partitioned_vector(size_type size, T const& val);
/// Constructor which create and initialize vector of size
/// \a size using the given distribution policy.
///
/// \param size The overall size of the vector
/// \param policy The distribution policy to use
/// \param symbolic_name The (optional) name to register the newly
/// created vector
///
template <typename DistPolicy>
partitioned_vector(size_type size, DistPolicy const& policy,
typename std::enable_if<
traits::is_distribution_policy<DistPolicy>::value>::type* =
nullptr);
/// Constructor which create and initialize vector with the
/// given \a where all elements are initialized with \a val and
/// using the given distribution policy.
///
/// \param size The overall size of the vector
/// \param val Default value for the elements in vector
/// \param policy The distribution policy to use
/// \param symbolic_name The (optional) name to register the newly
/// created vector
///
template <typename DistPolicy>
partitioned_vector(size_type size, T const& val,
DistPolicy const& policy,
typename std::enable_if<
traits::is_distribution_policy<DistPolicy>::value>::type* =
nullptr);
/// Copy construction performs a deep copy of the right hand side
/// vector.
partitioned_vector(partitioned_vector const& rhs)
: base_type()
, size_(0)
{
if (rhs.size_ != 0)
copy_from(rhs);
}
partitioned_vector(partitioned_vector&& rhs)
: base_type(HPX_MOVE(rhs))
, size_(rhs.size_)
, partition_size_(rhs.partition_size_)
, partitions_(HPX_MOVE(rhs.partitions_))
{
rhs.size_ = 0;
rhs.partition_size_ = std::size_t(-1);
}
public:
/// \brief Array subscript operator. This does not throw any exception.
///
/// \param pos Position of the element in the vector [Note the first
/// position in the partition is 0]
///
/// \return Returns a proxy object which represents the indexed element.
/// A (possibly remote) access operation is performed only once
/// this proxy instance is used.
///
segmented::detail::vector_value_proxy<T, Data> operator[](size_type pos)
{
return segmented::detail::vector_value_proxy<T, Data>(*this, pos);
}
/// \brief Array subscript operator. This does not throw any exception.
///
/// \param pos Position of the element in the vector [Note the first
/// position in the partition is 0]
///
/// \return Returns the value of the element at position represented by
/// \a pos.
///
/// \note This function does not return a reference to the actual
/// element but a copy of its value.
///
T operator[](size_type pos) const
{
return get_value(launch::sync, pos);
}
/// Copy assignment operator, performs deep copy of the right hand side
/// vector.
///
/// \param rhs This the hpx::partitioned_vector object which is to
/// be copied
///
partitioned_vector& operator=(partitioned_vector const& rhs)
{
if (this != &rhs && rhs.size_ != 0)
copy_from(rhs);
return *this;
}
partitioned_vector& operator=(partitioned_vector&& rhs)
{
if (this != &rhs)
{
this->base_type::operator=(static_cast<base_type&&>(rhs));
size_ = rhs.size_;
partition_size_ = rhs.partition_size_;
partitions_ = HPX_MOVE(rhs.partitions_);
rhs.size_ = 0;
rhs.partition_size_ = std::size_t(-1);
}
return *this;
}
///////////////////////////////////////////////////////////////////////
// Capacity related API's in vector class
/// \brief Compute the size as the number of elements it contains.
///
/// \return Return the number of elements in the vector
///
size_type size() const
{
return size_;
}
//
// Element access API's in vector class
//
/// Returns the element at position \a pos in the vector container.
///
/// \param pos Position of the element in the vector
///
/// \return Returns the value of the element at position represented by
/// \a pos.
///
T get_value(launch::sync_policy, size_type pos) const
{
return get_value(
launch::sync, get_partition(pos), get_local_index(pos));
}
/// Returns the element at position \a pos in the vector container.
///
/// \param part Sequence number of the partition
/// \param pos Position of the element in the partition
///
/// \return Returns the value of the element at position represented by
/// \a pos.
///
T get_value(launch::sync_policy, size_type part, size_type pos) const
{
partition_data const& part_data = partitions_[part];
if (part_data.local_data_)
return part_data.local_data_->get_value(pos);
return partitioned_vector_partition_client(part_data.partition_)
.get_value(launch::sync, pos);
}
/// Returns the element at position \a pos in the vector container
/// asynchronously.
///
/// \param pos Position of the element in the vector
///
/// \return Returns the hpx::future to value of the element at position
/// represented by \a pos.
///
future<T> get_value(size_type pos) const
{
return get_value(get_partition(pos), get_local_index(pos));
}
/// Returns the element at position \a pos in the given partition in
/// the vector container asynchronously.
///
/// \param part Sequence number of the partition
/// \param pos Position of the element in the partition
///
/// \return Returns the hpx::future to value of the element at position
/// represented by \a pos.
///
future<T> get_value(size_type part, size_type pos) const
{
if (partitions_[part].local_data_)
{
return make_ready_future(
partitions_[part].local_data_->get_value(pos));
}
return partitioned_vector_partition_client(
partitions_[part].partition_)
.get_value(pos);
}
/// Returns the elements at the positions \a pos from the given
/// partition in the vector container.
///
/// \param part Sequence number of the partition
/// \param pos Position of the element in the partition
///
/// \return Returns the value of the element at position represented by
/// \a pos.
///
std::vector<T> get_values(launch::sync_policy, size_type part,
std::vector<size_type> const& pos) const
{
partition_data const& part_data = partitions_[part];
if (part_data.local_data_)
return part_data.local_data_->get_values(pos);
return partitioned_vector_partition_client(part_data.partition_)
.get_values(launch::sync, pos);
}
/// Asynchronously returns the elements at the positions \a pos from
/// the given partition in the vector container.
///
/// \param part Sequence number of the partition
/// \param pos Positions of the elements in the vector
///
/// \return Returns the hpx::future to values of the elements at the
/// given positions represented by \a pos.
///
future<std::vector<T>> get_values(
size_type part, std::vector<size_type> const& pos) const
{
partition_data const& part_data = partitions_[part];
if (part_data.local_data_)
return make_ready_future(
part_data.local_data_->get_values(pos));
return partitioned_vector_partition_client(part_data.partition_)
.get_values(pos);
}
/// Returns the elements at the positions \a pos
/// in the vector container.
///
/// \param pos Global position of the element in the vector
///
/// \return Returns the value of the element at position represented by
/// \a pos.
///
future<std::vector<T>> get_values(
std::vector<size_type> const& pos_vec) const
{
// check if position vector is empty
// the following code needs at least one element.
if (pos_vec.empty())
return make_ready_future(std::vector<T>());
// current partition index of the block
size_type part_cur = get_partition(pos_vec[0]);
// iterator to the begin of current block
typename std::vector<size_type>::const_iterator part_begin =
pos_vec.begin();
// vector holding futures of the values for all blocks
std::vector<future<std::vector<T>>> part_values_future;
for (typename std::vector<size_type>::const_iterator it =
pos_vec.begin();
it != pos_vec.end(); ++it)
{
// get the partition of the current position
size_type part = get_partition(*it);
// if the partition of the current position is the same
// as the rest of the current block go to next position
if (part == part_cur)
continue;
// if the partition of the current position is NOT the same
// as the positions before the block ends here
else
{
// this is the end of a block containing indexes ('pos')
// of the same partition ('part').
// get async values for this block
part_values_future.push_back(get_values(part_cur,
get_local_indices(
std::vector<size_type>(part_begin, it))));
// reset block variables to start a new one from here
part_cur = part;
part_begin = it;
}
}
// the end of the vector is also an end of a block
// get async values for this block
part_values_future.push_back(get_values(part_cur,
get_local_indices(
std::vector<size_type>(part_begin, pos_vec.end()))));
// This helper function unwraps the vectors from each partition
// and merge them to one vector
auto merge_func =
[&pos_vec](std::vector<future<std::vector<T>>>&& part_values_f)
-> std::vector<T> {
std::vector<T> values;
values.reserve(pos_vec.size());
for (future<std::vector<T>>& part_f : part_values_f)
{
std::vector<T> part_values = part_f.get();
std::move(part_values.begin(), part_values.end(),
std::back_inserter(values));
}
return values;
};
// when all values are here merge them to one vector
// and return a future to this vector
return dataflow(
launch::async, merge_func, HPX_MOVE(part_values_future));
}
/// Returns the elements at the positions \a pos
/// in the vector container.
///
/// \param pos Global position of the element in the vector
///
/// \return Returns the value of the element at position represented by
/// \a pos.
///
std::vector<T> get_values(
launch::sync_policy, std::vector<size_type> const& pos_vec) const
{
return get_values(pos_vec).get();
}
// //FRONT (never throws exception)
// /** @brief Access the value of first element in the vector.
// *
// * Calling the function on empty container cause undefined behavior.
// *
// * @return Return the value of the first element in the vector
// */
// VALUE_TYPE front() const
// {
// return partitioned_vector_partition_stub::front_async(
// (partitions_.front().first).get()
// ).get();
// }//end of front_value
//
// /** @brief Asynchronous API for front().
// *
// * Calling the function on empty container cause undefined behavior.
// *
// * @return Return the hpx::future to return value of front()
// */
// hpx::future< VALUE_TYPE > front_async() const
// {
// return partitioned_vector_partition_stub::front_async(
// (partitions_.front().first).get()
// );
// }//end of front_async
//
// //BACK (never throws exception)
// /** @brief Access the value of last element in the vector.
// *
// * Calling the function on empty container cause undefined behavior.
// *
// * @return Return the value of the last element in the vector
// */
// VALUE_TYPE back() const
// {
// // As the LAST pair is there and then decrement operator to that
// // LAST is undefined hence used the end() function rather than back()
// return partitioned_vector_partition_stub::back_async(
// ((partitions_.end() - 2)->first).get()
// ).get();
// }//end of back_value
//
// /** @brief Asynchronous API for back().
// *
// * Calling the function on empty container cause undefined behavior.
// *
// * @return Return hpx::future to the return value of back()
// */
// hpx::future< VALUE_TYPE > back_async() const
// {
// //As the LAST pair is there
// return partitioned_vector_partition_stub::back_async(
// ((partitions_.end() - 2)->first).get()
// );
// }//end of back_async
//
// //
// // Modifier component action
// //
//
// //ASSIGN
// /** @brief Assigns new contents to each partition, replacing its
// * current contents and modifying each partition size
// * accordingly.
// *
// * @param n New size of each partition
// * @param val Value to fill the partition with
// *
// * @exception hpx::invalid_vector_error If the \a n is equal to zero
// * then it throw \a hpx::invalid_vector_error exception.
// */
// void assign(size_type n, VALUE_TYPE const& val)
// {
// if(n == 0)
// HPX_THROW_EXCEPTION(
// hpx::invalid_vector_error,
// "assign",
// "Invalid Vector: new_partition_size should be greater than zero"
// );
//
// std::vector<future<void>> assign_lazy_sync;
// for (partition_description_type const& p,
// util::make_iterator_range(partitions_.begin(),
// partitions_.end() - 1)
// )
// {
// assign_lazy_sync.push_back(
// partitioned_vector_partition_stub::assign_async(
// (p.first).get(), n, val)
// );
// }
// hpx::wait_all(assign_lazy_sync);
// adjust_base_index(partitions_.begin(),
// partitions_.end() - 1,
// n);
// }//End of assign
//
// /** @brief Asynchronous API for assign().
// *
// * @param n New size of each partition
// * @param val Value to fill the partition with
// *
// * @exception hpx::invalid_vector_error If the \a n is equal to zero
// * then it throw \a hpx::invalid_vector_error exception.
// *
// * @return This return the hpx::future of type void [The void return
// * type can help to check whether the action is completed or
// * not]
// */
// future<void> assign_async(size_type n, VALUE_TYPE const& val)
// {
// return hpx::async(launch::async,
// &vector::assign,
// this,
// n,
// val
// );
// }
//
// //PUSH_BACK
// /** @brief Add new element at the end of vector. The added element
// * contain the \a val as value.
// *
// * The value is added to the back to the last partition.
// *
// * @param val Value to be copied to new element
// */
// void push_back(VALUE_TYPE const& val)
// {
// partitioned_vector_partition_stub::push_back_async(
// ((partitions_.end() - 2 )->first).get(),
// val
// ).get();
// }
/// Copy the value of \a val in the element at position \a pos in
/// the vector container.
///
/// \param pos Position of the element in the vector
/// \param val The value to be copied
///
template <typename T_>
void set_value(launch::sync_policy, size_type pos, T_&& val)
{
return set_value(launch::sync, get_partition(pos),
get_local_index(pos), HPX_FORWARD(T_, val));
}
/// Copy the value of \a val in the element at position \a pos in
/// the vector container.
///
/// \param part Sequence number of the partition
/// \param pos Position of the element in the partition
/// \param val The value to be copied
///
template <typename T_>
void set_value(
launch::sync_policy, size_type part, size_type pos, T_&& val)
{
partition_data const& part_data = partitions_[part];
if (part_data.local_data_)
{
part_data.local_data_->set_value(pos, HPX_FORWARD(T_, val));
}
else
{
partitioned_vector_partition_client(part_data.partition_)
.set_value(launch::sync, pos, HPX_FORWARD(T_, val));
}
}
/// Asynchronous set the element at position \a pos of the partition
/// \a part to the given value \a val.
///
/// \param pos Position of the element in the vector
/// \param val The value to be copied
///
/// \return This returns the hpx::future of type void which gets ready
/// once the operation is finished.
///
template <typename T_>
future<void> set_value(size_type pos, T_&& val)
{
return set_value(
get_partition(pos), get_local_index(pos), HPX_FORWARD(T_, val));
}
/// Asynchronously set the element at position \a pos in
/// the partition \part to the given value \a val.
///
/// \param part Sequence number of the partition
/// \param pos Position of the element in the partition
/// \param val The value to be copied
///
/// \return This returns the hpx::future of type void which gets ready
/// once the operation is finished.
///
template <typename T_>
future<void> set_value(size_type part, size_type pos, T_&& val)
{
partition_data const& part_data = partitions_[part];
if (part_data.local_data_)
{
part_data.local_data_->set_value(pos, HPX_FORWARD(T_, val));
return make_ready_future();
}
return partitioned_vector_partition_client(part_data.partition_)
.set_value(pos, HPX_FORWARD(T_, val));
}
/// Copy the values of \a val to the elements at positions \a pos in
/// the partition \part of the vector container.
///
/// \param part Sequence number of the partition
/// \param pos Position of the element in the vector
/// \param val The value to be copied
///
void set_values(launch::sync_policy, size_type /* part */,
std::vector<size_type> const& pos, std::vector<T> const& val)
{
set_values(pos, val).get();
}
/// Asynchronously set the element at position \a pos in
/// the partition \part to the given value \a val.
///
/// \param part Sequence number of the partition
/// \param pos Position of the element in the partition
/// \param val The value to be copied
///
/// \return This returns the hpx::future of type void which gets ready
/// once the operation is finished.
///
future<void> set_values(size_type part,
std::vector<size_type> const& pos, std::vector<T> const& val)
{
HPX_ASSERT(pos.size() == val.size());
if (partitions_[part].local_data_)
{
partitions_[part].local_data_->set_values(pos, val);
return make_ready_future();
}
return partitioned_vector_partition_client(
partitions_[part].partition_)
.set_values(pos, val);
}
/// Asynchronously set the element at position \a pos
/// to the given value \a val.
///
/// \param pos Global position of the element in the vector
/// \param val The value to be copied
///
/// \return This returns the hpx::future of type void which gets ready
/// once the operation is finished.
///
future<void> set_values(
std::vector<size_type> const& pos, std::vector<T> const& val)
{
HPX_ASSERT(pos.size() == val.size());
// check if position vector is empty
// the following code needs at least one element.
if (pos.empty())
return make_ready_future();
// partition index of the current block
size_type part_cur = get_partition(pos[0]);
// iterator to the begin of current block
typename std::vector<size_type>::const_iterator pos_block_begin =
pos.begin();
typename std::vector<T>::const_iterator val_block_begin =
val.begin();
// vector holding futures of the state for all blocks
std::vector<future<void>> part_futures;
// going through the position vector
typename std::vector<size_type>::const_iterator pos_it =
pos.begin();
typename std::vector<T>::const_iterator val_it = val.begin();
for (/**/; pos_it != pos.end(); ++pos_it, ++val_it)
{
// get the partition of the current position
size_type part = get_partition(*pos_it);
// if the partition of the current position is the same
// as the rest of the current block go to next position
if (part == part_cur)
continue;
// if the partition of the current position is NOT the same
// as the positions before the block ends here
else
{
// this is the end of a block containing indexes ('pos')
// of the same partition ('part').
// set asynchronous values for this block
part_futures.push_back(set_values(part_cur,
get_local_indices(
std::vector<size_type>(pos_block_begin, pos_it)),
std::vector<T>(val_block_begin, val_it)));
// reset block variables to start a new one from here
part_cur = part;
pos_block_begin = pos_it;
val_block_begin = val_it;
}
}
// the end of the vector is also an end of a block
// get asynchronous values for this block
part_futures.push_back(set_values(part_cur,
get_local_indices(
std::vector<size_type>(pos_block_begin, pos.end())),
std::vector<T>(val_block_begin, val.end())));
return hpx::when_all(part_futures);
}
void set_values(launch::sync_policy, std::vector<size_type> const& pos,
std::vector<T> const& val)
{
return set_values(pos, val).get();
}
// //CLEAR
// //TODO if number of partitions is kept constant every time then
// // clear should modified (clear each partitioned_vector_partition
// // one by one).
// void clear()
// {
// //It is keeping one gid hence iterator does not go
// //in an invalid state
// partitions_.erase(partitions_.begin() + 1,
// partitions_.end()-1);
// partitioned_vector_partition_stub::clear_async(
// (partitions_[0].second).get())
// .get();
// HPX_ASSERT(partitions_.size() > 1);
// //As this function changes the size we should have LAST always.
// }
///////////////////////////////////////////////////////////////////////
/// Return the iterator at the beginning of the first segment located
/// on the given locality.
iterator begin()
{
return iterator(this, get_global_index(segment_cbegin(), 0));
}
/// \brief Return the const_iterator at the beginning of the vector.
const_iterator begin() const
{
return const_iterator(this, get_global_index(segment_cbegin(), 0));
}
/// \brief Return the const_iterator at the beginning of the vector.
const_iterator cbegin() const
{
return const_iterator(this, get_global_index(segment_cbegin(), 0));
}
/// \brief Return the iterator at the end of the vector.
iterator end()
{
return iterator(this, get_global_index(segment_cend(), 0));
}
/// \brief Return the const_iterator at the end of the vector.
const_iterator end() const
{
return const_iterator(this, get_global_index(segment_cend(), 0));
}
/// \brief Return the const_iterator at the end of the vector.
const_iterator cend() const
{
return const_iterator(this, get_global_index(segment_cend(), 0));
}
///////////////////////////////////////////////////////////////////////
/// Return the iterator at the beginning of the first partition of the
/// vector on the given locality.
iterator begin(std::uint32_t id)
{
return iterator(this, get_global_index(segment_begin(id), 0));
}
/// Return the iterator at the beginning of the first partition of the
/// vector on the given locality.
const_iterator begin(std::uint32_t id) const
{
return const_iterator(
this, get_global_index(segment_cbegin(id), 0));
}
/// Return the iterator at the beginning of the first partition of the
/// vector on the given locality.
const_iterator cbegin(std::uint32_t id) const
{
return const_iterator(
this, get_global_index(segment_cbegin(id), 0));
}
/// Return the iterator at the end of the last partition of the
/// vector on the given locality.
iterator end(std::uint32_t id)
{
return iterator(this, get_global_index(segment_end(id), 0));
}
/// Return the iterator at the end of the last partition of the
/// vector on the given locality.
const_iterator end(std::uint32_t id) const
{
return const_iterator(this, get_global_index(segment_cend(id), 0));
}
/// Return the iterator at the end of the last partition of the
/// vector on the given locality.
const_iterator cend(std::uint32_t id) const
{
return const_iterator(this, get_global_index(segment_cend(id), 0));
}
///////////////////////////////////////////////////////////////////////
/// Return the iterator at the beginning of the first segment located
/// on the given locality.
iterator begin(id_type const& id)
{
HPX_ASSERT(naming::is_locality(id));
return begin(naming::get_locality_id_from_id(id));
}
/// Return the iterator at the beginning of the first segment located
/// on the given locality.
const_iterator begin(id_type const& id) const
{
HPX_ASSERT(naming::is_locality(id));
return begin(naming::get_locality_id_from_id(id));
}
/// Return the iterator at the beginning of the first segment located
/// on the given locality.
const_iterator cbegin(id_type const& id) const
{
HPX_ASSERT(naming::is_locality(id));
return cbegin(naming::get_locality_id_from_id(id));
}
/// Return the iterator at the end of the last segment located
/// on the given locality.
iterator end(id_type const& id)
{
HPX_ASSERT(naming::is_locality(id));
return end(naming::get_locality_id_from_id(id));
}
/// Return the iterator at the end of the last segment located
/// on the given locality.
const_iterator end(id_type const& id) const
{
HPX_ASSERT(naming::is_locality(id));
return end(naming::get_locality_id_from_id(id));
}
/// Return the iterator at the end of the last segment located
/// on the given locality.
const_iterator cend(id_type const& id) const
{
HPX_ASSERT(naming::is_locality(id));
return cend(naming::get_locality_id_from_id(id));
}
///////////////////////////////////////////////////////////////////////
// Return global segment iterator
segment_iterator segment_begin()
{
return segment_iterator(partitions_.begin(), this);
}
const_segment_iterator segment_begin() const
{
return const_segment_iterator(partitions_.cbegin(), this);
}
const_segment_iterator segment_cbegin() const //-V524
{
return const_segment_iterator(partitions_.cbegin(), this);
}
segment_iterator segment_end()
{
return segment_iterator(partitions_.end(), this);
}
const_segment_iterator segment_end() const
{
return segment_cend();
}
const_segment_iterator segment_cend() const
{
return const_segment_iterator(partitions_.cend(), this);
}
///////////////////////////////////////////////////////////////////////
// Return local segment iterator
local_segment_iterator segment_begin(std::uint32_t id)
{
return local_segment_iterator(
partitions_.begin(), partitions_.end(), id);
}
const_local_segment_iterator segment_begin(std::uint32_t id) const
{
return segment_cbegin(id);
}
const_local_segment_iterator segment_cbegin(std::uint32_t id) const
{
return const_local_segment_iterator(
partitions_.cbegin(), partitions_.cend(), id);
}
local_segment_iterator segment_end(std::uint32_t id)
{
local_segment_iterator it = segment_begin(id);
it.unsatisfy_predicate();
return it;
}
const_local_segment_iterator segment_end(std::uint32_t id) const
{
const_local_segment_iterator it = segment_begin(id);
it.unsatisfy_predicate();
return it;
}
const_local_segment_iterator segment_cend(std::uint32_t id) const
{
const_local_segment_iterator it = segment_cbegin(id);
it.unsatisfy_predicate();
return it;
}
///////////////////////////////////////////////////////////////////////
local_segment_iterator segment_begin(id_type const& id)
{
HPX_ASSERT(naming::is_locality(id));
return segment_begin(naming::get_locality_id_from_id(id));
}
const_local_segment_iterator segment_begin(id_type const& id) const
{
HPX_ASSERT(naming::is_locality(id));
return segment_begin(naming::get_locality_id_from_id(id));
}
const_local_segment_iterator segment_cbegin(id_type const& id) const
{
HPX_ASSERT(naming::is_locality(id));
return segment_cbegin(naming::get_locality_id_from_id(id));
}
local_segment_iterator segment_end(id_type const& id)
{
HPX_ASSERT(naming::is_locality(id));
return segment_end(naming::get_locality_id_from_id(id));
}
const_local_segment_iterator segment_end(id_type const& id) const
{
HPX_ASSERT(naming::is_locality(id));
return segment_end(naming::get_locality_id_from_id(id));
}
const_local_segment_iterator segment_cend(id_type const& id) const
{
HPX_ASSERT(naming::is_locality(id));
return segment_cend(naming::get_locality_id_from_id(id));
}
};
} // namespace hpx
|
13fa3b7e834bab35b72b7e48df8314fb320d3de5 | beede1d5be2e49f4656251d8020c1ff7452b9c92 | /store/store.cc | 022996f43a941592ca955150cda053d8e5f26e0d | [] | no_license | kryzthov/gooz | 62e47026346e690086076a148bce1eec86ebb663 | 318cf7a8c3b878233a58777c16115627d2956b63 | refs/heads/master | 2020-05-17T17:51:23.069850 | 2017-12-06T07:23:39 | 2017-12-06T07:23:39 | 37,021,627 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,251 | cc | store.cc | #include "store/store.h"
#include <glog/logging.h>
#include "store/values.h"
namespace store {
HeapStore::HeapStore()
: nallocs_(0),
size_(0) {
}
HeapStore::~HeapStore() {
}
// virtual
void* HeapStore::Alloc(uint64 size) {
nallocs_++;
size_ += size;
return new char[size];
}
HeapStore* const kHeapStore = new HeapStore();
// -----------------------------------------------------------------------------
StaticStore::StaticStore(uint64 size)
: size_(size),
free_(size),
base_(new char[size]),
next_(base_) {
CHECK_NOTNULL(base_);
}
StaticStore::~StaticStore() {
}
// virtual
void* StaticStore::Alloc(uint64 size) {
VLOG(3) << __PRETTY_FUNCTION__
<< " size=" << size
<< " free=" << free_;
// TODO: Ensure 8 bytes alignment
if (size > free_) return NULL;
void* const new_alloc = next_;
free_ -= size;
next_ += size;
return new_alloc;
}
void StaticStore::AddRoot(HeapValue* root) {
roots_.insert(root);
}
void StaticStore::RemoveRoot(HeapValue* root) {
roots_.erase(root);
}
// static
void StaticStore::Move(StaticStore* from, Store* to) {
for (auto it = from->roots_.begin(); it != from->roots_.end(); ++it) {
(*it)->Move(to);
}
}
} // namespace store
|
7d0ef8586711905b925316ba46e02ad08b03daba | a239184157a518bf68c7f4c99ce835bbafafe77d | /MediaPlayer/RingBuffer.cpp | 1df1884cf58890304bb612e19a643e9903bb1631 | [] | no_license | xc724655471/MediaPlayer | 6f320ee0112b0a98f3b4fabdfe77667f05dd01db | 13f0f518fd4e9e0ecb763ca1b23bf12bbd1ab249 | refs/heads/master | 2020-03-25T16:57:20.800532 | 2018-08-31T09:41:26 | 2018-08-31T09:41:26 | 143,955,994 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,812 | cpp | RingBuffer.cpp | #include "stdafx.h"
#include "RingBuffer.h"
#define MAX_RING_BUFFER_SIZE (2*1024*1000)
#define MIN_RING_BUFFER_SIZE (128*1000)
#define DEFAULT_RING_BUFFER_SIZE (512*1000)
RingBuffer::RingBuffer()
{
m_iWidx = 0;
m_iRIdx = 0;
m_uBufferSize = DEFAULT_RING_BUFFER_SIZE;
m_pBuffer = new char[m_uBufferSize];
m_bOutsideBuf = false;
m_iWorkStatus = RINGBUFFER_NORMAL;
//InitializeCriticalSectionAndSpinCount(&m_csBufMutex, 4000);
}
RingBuffer::RingBuffer(unsigned bufferSize, char* pBuffer)
{
m_iWidx = 0;
m_iRIdx = 0;
// if (bufferSize < MIN_RING_BUFFER_SIZE)
// {
// bufferSize = MIN_RING_BUFFER_SIZE;
// }
// if (bufferSize > MAX_RING_BUFFER_SIZE)
// {
// bufferSize = MAX_RING_BUFFER_SIZE;
// }
//outside buf do not check size
m_uBufferSize = bufferSize;
m_pBuffer = pBuffer;
m_bOutsideBuf = true;
m_iWorkStatus = RINGBUFFER_NORMAL;
}
RingBuffer::RingBuffer(unsigned bufferSize)
{
m_iWidx = 0;
m_iRIdx = 0;
if (bufferSize < MIN_RING_BUFFER_SIZE)
{
bufferSize = MIN_RING_BUFFER_SIZE;
}
if (bufferSize > MAX_RING_BUFFER_SIZE)
{
bufferSize = MAX_RING_BUFFER_SIZE;
}
m_uBufferSize = bufferSize;
m_pBuffer = new char[m_uBufferSize];
m_bOutsideBuf = false;
m_iWorkStatus = RINGBUFFER_NORMAL;
}
RingBuffer::~RingBuffer()
{
if (!m_bOutsideBuf && m_pBuffer)
{
delete[]m_pBuffer;
m_pBuffer = NULL;
}
// DeleteCriticalSection(&m_csBufMutex);
}
//left 1Byte for guard
int RingBuffer::GetFreeBufferBytes(int iRidx, int iWidx)
{
if (iRidx == iWidx)
{
return m_uBufferSize-1;
}
else if (iWidx > iRidx)
{
return (iRidx - iWidx + m_uBufferSize - 1);
}
else
{
return (iRidx - iWidx - 1);
}
}
//this func can write to the addr = ridx-1 (at most)
int RingBuffer::Write(const unsigned char* pBuf, unsigned writeLen)
{
//m_pBuffer may alloc memory failed
if (!m_pBuffer)
{
return -1;
}
int iRidx = m_iRIdx;
int iWidx = m_iWidx;
if (!pBuf || 0 == writeLen || GetFreeBufferBytes(iRidx, iWidx) < writeLen)
{
return -1;
}
int len1 = 0;
if (m_iWidx < iRidx)
{
memcpy(&m_pBuffer[m_iWidx], pBuf, writeLen);
m_iWidx += writeLen;
}
else
{
len1 = m_uBufferSize - m_iWidx;
if (writeLen <= len1)
{
memcpy(&m_pBuffer[m_iWidx], pBuf, writeLen);
m_iWidx += writeLen;
}
else
{
memcpy(&m_pBuffer[m_iWidx], pBuf, len1);
memcpy(m_pBuffer, pBuf + len1, writeLen - len1);
m_iWidx = writeLen - len1;
}
}
return writeLen;
}
void RingBuffer::Init(){}
//
int RingBuffer::Read(unsigned char* pBuf, unsigned readLen)
{
//m_pBuffer may alloc memory failed
if (!m_pBuffer)
{
return -1;
}
if (!pBuf)
{
return -1;
}
int iWidx = m_iWidx;
int iRidx = m_iRIdx;
int bufferDataLen = m_uBufferSize - GetFreeBufferBytes(iRidx, iWidx) - 1;
if (bufferDataLen <= readLen)
{
//can not use readall here, because GetFreeBufferBytes func and readall func may use the different
//ridx and widx
return ReadToWidx(pBuf, iWidx);
}
else
{
if (m_iRIdx < iWidx)
{
memcpy(pBuf, &m_pBuffer[m_iRIdx], readLen);
m_iRIdx += readLen;
}
else
{
int len1 = m_uBufferSize - m_iRIdx;
if (len1 >= readLen)
{
memcpy(pBuf, &m_pBuffer[m_iRIdx], readLen);
m_iRIdx += readLen;
}
else
{
memcpy(pBuf, &m_pBuffer[m_iRIdx], len1);
memcpy(pBuf + len1, m_pBuffer, readLen - len1);
m_iRIdx = readLen - len1;
}
} //end m_iRIdx >= m_iWidx
return readLen;
}//end bufferDataLen > readLen
}
// read to widx
int RingBuffer::ReadToWidx(unsigned char* pBuf, int iWidx)
{
//m_pBuffer may alloc memory failed
if (!m_pBuffer)
{
return -1;
}
if (!pBuf || m_iWidx == m_iRIdx)
{
return -1;
}
int curWidx = m_iWidx;
if (m_iRIdx < curWidx)
{
if (iWidx < m_iRIdx || iWidx > curWidx)
{
return -1;
}
}
else
{
if (iWidx > curWidx && iWidx < m_iRIdx)
{
return -1;
}
}
//must use temp varible here
//int iWidx = m_iWidx;
int readLen = 0;
if (m_iRIdx > iWidx)
{
memcpy(pBuf, &m_pBuffer[m_iRIdx], m_uBufferSize - m_iRIdx);
memcpy(pBuf + m_uBufferSize - m_iRIdx, m_pBuffer, iWidx);
readLen = m_uBufferSize - m_iRIdx + iWidx;
}
else
{
memcpy(pBuf, &m_pBuffer[m_iRIdx], iWidx - m_iRIdx);
readLen = iWidx - m_iRIdx;
}
//###can not set m_iRIdx = m_iWidx!!!!!
m_iRIdx = iWidx;
return readLen;
}
int RingBuffer::ReadAll(unsigned char* pBuf)
{
//m_pBuffer may alloc memory failed
if (!m_pBuffer)
{
return -1;
}
if (!pBuf || m_iWidx == m_iRIdx)
{
return -1;
}
return ReadToWidx(pBuf, m_iWidx);
}
char* RingBuffer::GetBufferAddr()
{
return m_pBuffer;
}
int RingBuffer::GetBufferSize()
{
return m_uBufferSize;
}
#if 0
//read to widx
int RingBuffer::ReadAll(unsigned char* pBuf)
{
if (!pBuf || m_iWidx == m_iRIdx)
{
return -1;
}
//must use temp varible here
int iWidx = m_iWidx;
int readLen = 0;
if (m_iRIdx > iWidx)
{
memcpy(pBuf, &m_pBuffer[m_iRIdx], m_uBufferSize - m_iRIdx);
memcpy(pBuf + m_uBufferSize - m_iRIdx, m_pBuffer, iWidx);
readLen = m_uBufferSize - m_iRIdx + iWidx;
}
else
{
memcpy(pBuf, &m_pBuffer[m_iRIdx], iWidx - m_iRIdx);
readLen = iWidx - m_iRIdx;
}
//###can not set m_iRIdx = m_iWidx!!!!!
m_iRIdx = iWidx;
return readLen;
}
#endif
RINGBUFFER_WORK_STATUS RingBuffer::GetStatus()
{
return m_iWorkStatus;
}
int RingBuffer::SetStatus(RINGBUFFER_WORK_STATUS status)
{
if (status < RINGBUFFER_NORMAL || status >= RINGBUFFER_END)
{
return -1;
}
m_iWorkStatus = status;
return 0;
}
int RingBuffer::Analyze()
{
return 0;
}
void RingBuffer::Lock()
{
// EnterCriticalSection(&m_csBufMutex);
}
void RingBuffer::UnLock()
{
// LeaveCriticalSection(&m_csBufMutex);
}
void RingBuffer::Stop()
{
SetStatus(RINGBUFFER_STOP);
}
int RingBuffer::GetFreeBufferBytes()
{
return GetFreeBufferBytes(m_iRIdx, m_iWidx);
}
int RingBuffer::GetDataBytes()
{
return m_uBufferSize - GetFreeBufferBytes();
} |
eea0d8cbefe18296965e3dabfc5399f0da3126e7 | 71c53955083e9cc22e2c46a18f15aae33acf79ae | /5_taskcode/mainwindow.h | b0f0308b32b9e3c93a21db93ea42c0cd8b2f5cf9 | [] | no_license | vlad23345/5-task | ce7b3628c41cca6b948fa1efcbcbd7944bfbdb67 | 0d383dfa7a23be43f62c1e9736b308a2881d8000 | refs/heads/master | 2022-08-30T07:25:49.279637 | 2020-06-01T08:36:30 | 2020-06-01T08:36:30 | 268,464,159 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 611 | h | mainwindow.h | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QThread>
#include <QVector>
#include <QTableWidget>
#include <QProgressBar>
#include <QHeaderView>
#include "longprocess.h"
namespace Ui {
class MainWindow;
}
typedef QPair<QThread *,LongProcess *> TPair;
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void on_pushButton_clicked();
void update(int n,int i);
void deleteLater(int n);
private:
QVector<TPair*> processes;
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
|
88ff47c595f7f384d6de4bbac413f480d081e68a | 0c87a04068a61a5f68e9139a31ff9250e4f68fb2 | /Timer.h | 487b13a94e458aaa3d94303d578952ecf9fc31e0 | [] | no_license | Iqbal-1013/lib | 88151dfd2e5937ac3d56ddb58875cc314b6496fb | a48d43753a2fb5c595ccd971e4efc0f80048cb28 | refs/heads/master | 2020-03-11T19:27:33.243586 | 2018-04-19T11:53:23 | 2018-04-19T11:53:23 | 130,208,148 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 350 | h | Timer.h | #ifndef Timer_h
#define Timer_h
namespace Timer
{
unsigned long start = 0;
void Start()
{
start = millis();
}
void Start(unsigned long &start)
{
start = millis();
}
unsigned long Duration()
{
return millis() - start;
}
unsigned long Duration(unsigned long &start)
{
return millis() - start;
}
}
#endif // !Timer_h
|
6fdbccf66f4b6e17c509e850da6ba2ae2555702d | d043fed5f640de4057aecf9dfeeed0ec34e69582 | /include/node.h | e7bf38fdc9aed3e308f4919087afb6366f1b1973 | [] | no_license | cristina-gcm/binary-search-tree | 08df388127f6d901bea86cd9202b38f0f1d09691 | 3d0caf749449b9af3da598642632cb73c625b47b | refs/heads/master | 2021-04-24T06:40:34.182206 | 2020-03-25T21:31:18 | 2020-03-25T21:31:18 | 250,094,825 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 155 | h | node.h | #ifndef NODE_H
#define NODE_H
class node
{
int info;
node *st, *dr;
public
node();
node(int info);
~node();
};
#endif // NODE_H
|
375a2e02bd045dbc99149a7a3066937c6f260eda | aa0917a80f2164d4b8a13a73e3a9926fe05ecb5b | /include/poisson2d.hpp | b066c9e6ead30f1788fdc9d3482919afab40591c | [
"BSD-3-Clause"
] | permissive | jasondegraw/skyline | 5ba43405708664e5b529825d61f533f1c8756a3e | e706c86550929b2aab6e6f758682b72f9a476ce4 | refs/heads/master | 2020-06-16T01:12:16.622530 | 2019-08-26T00:16:22 | 2019-08-26T00:16:22 | 195,441,326 | 0 | 0 | BSD-3-Clause | 2019-07-05T16:46:00 | 2019-07-05T16:46:00 | null | UTF-8 | C++ | false | false | 19,477 | hpp | poisson2d.hpp | // Copyright (c) 2019, Alliance for Sustainable Energy, LLC
// Copyright (c) 2019, Jason W. DeGraw
// 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.
#ifndef POISSON2D_HPP
#define POISSON2D_HPP
#include <optional>
#include <iostream>
namespace poisson {
enum class BoundaryCondition { Dirichlet, Adiabatic, Periodic};
enum class Type { DDDD=1, DDDA, DDAA, DAAA, DADA, AAAA, DPDP, APAP, DPAP, PPPP};
enum class Rotation { CCW0 = 0, CCW90 = 90, CCW180 = 180, CCW270 = 270 };
template<typename I, typename R, template <typename ...> typename V> struct GaussSiedelIterator
{
GaussSiedelIterator(I ni, I nj, V<R> &f, BoundaryCondition N = BoundaryCondition::Dirichlet,
BoundaryCondition E = BoundaryCondition::Dirichlet, BoundaryCondition S = BoundaryCondition::Dirichlet,
BoundaryCondition W = BoundaryCondition::Dirichlet) : ni(ni), nj(nj), north_boundary_condition(N), east_boundary_condition(E),
south_boundary_condition(S), west_boundary_condition(W), f(f)
{
u.resize(f.size());
for (I i = 0; i < f.size(); ++i) {
u[i] = 0;
}
}
R iterate()
{
R delta = 0.0;
I ij = 0;
// First row
if (west_boundary_condition == BoundaryCondition::Adiabatic) {
u[0] = u[1];
delta = std::max(delta, std::abs(u[0] - u[1]));
ij = 1;
} else if (west_boundary_condition == BoundaryCondition::Dirichlet
&& south_boundary_condition == BoundaryCondition::Dirichlet) {
R last = u[0];
u[0] = 0.25*(f[0] + u[1] + u[ni]);
delta = std::abs(last - u[0]);
ij = 1;
}
if (south_boundary_condition == BoundaryCondition::Adiabatic) {
for (; ij < ni-1; ++ij) {
delta = std::max(delta, std::abs(u[ij] - u[ij + ni]));
u[ij] = u[ij + ni];
}
} else if (south_boundary_condition == BoundaryCondition::Dirichlet) {
for (; ij < ni - 1; ++ij) {
R last = u[ij];
u[ij] = 0.25*(f[ij] + u[ij + 1] + u[ij - 1] + u[ij + ni]);
delta = std::max(delta, std::abs(last - u[ij]));
}
}
if (east_boundary_condition == BoundaryCondition::Adiabatic) {
u[ij] = u[ij-1];
delta = std::max(delta, std::abs(u[ij] - u[ij-1]));
++ij;
} else if (east_boundary_condition == BoundaryCondition::Dirichlet
&& south_boundary_condition == BoundaryCondition::Dirichlet) {
R last = u[ij];
u[ij] = 0.25*(f[ij] + u[ij-1] + u[ij+ni]);
delta = std::abs(last - u[ij]);
++ij;
}
// Main body
for (I j = 1; j < nj-1; ++j) {
// First
if (west_boundary_condition == BoundaryCondition::Adiabatic) {
} else {
R last = u[ij];
u[ij] = 0.25*(f[ij] + u[ij + 1] + u[ij + ni] + u[ij - ni]);
delta = std::max(delta, std::abs(last - u[ij]));
}
++ij;
for (I i = 1; i < ni-1; ++i) {
R last = u[ij];
u[ij] = 0.25*(f[ij] + u[ij - 1] + u[ij + 1] + u[ij + ni] + u[ij - ni]);
delta = std::max(delta, std::abs(last - u[ij]));
++ij;
}
// Last
if (east_boundary_condition == BoundaryCondition::Adiabatic) {
} else {
R last = u[ij];
u[ij] = 0.25*(f[ij] + u[ij - 1] + u[ij + ni] + u[ij - ni]);
delta = std::max(delta, std::abs(last - u[ij]));
}
++ij;
}
// Last row
if (west_boundary_condition == BoundaryCondition::Adiabatic) {
delta = std::max(delta, std::abs(u[ij] - u[ij + 1]));
u[ij] = u[ij+1];
} else if (west_boundary_condition == BoundaryCondition::Dirichlet
&& south_boundary_condition == BoundaryCondition::Dirichlet) {
R last = u[ij];
u[ij] = 0.25*(f[0] + u[ij+1] + u[ij-ni]);
delta = std::max(delta, std::abs(last - u[ij]));
}
++ij;
if (south_boundary_condition == BoundaryCondition::Adiabatic) {
for (; ij < ni - 1; ++ij) {
delta = std::max(delta, std::abs(u[ij] - u[ij - ni]));
u[ij] = u[ij - ni];
}
} else if (south_boundary_condition == BoundaryCondition::Dirichlet) {
for (; ij < ni - 1; ++ij) {
R last = u[ij];
u[ij] = 0.25*(f[ij] + u[ij + 1] + u[ij - 1] + u[ij + ni]);
delta = std::max(delta, std::abs(last - u[ij]));
}
}
if (east_boundary_condition == BoundaryCondition::Adiabatic) {
u[ij] = u[ij - 1];
delta = std::max(delta, std::abs(u[ij] - u[ij - 1]));
} else if (east_boundary_condition == BoundaryCondition::Dirichlet
&& north_boundary_condition == BoundaryCondition::Dirichlet) {
R last = u[ij];
u[ij] = 0.25*(f[ij] + u[ij - 1] + u[ij - ni]);
delta = std::abs(last - u[ij]);
}
return delta;
}
I ni, nj;
BoundaryCondition north_boundary_condition = BoundaryCondition::Dirichlet;
BoundaryCondition east_boundary_condition = BoundaryCondition::Dirichlet;
BoundaryCondition south_boundary_condition = BoundaryCondition::Dirichlet;
BoundaryCondition west_boundary_condition = BoundaryCondition::Dirichlet;
V<R> u, f;
};
template <typename I> struct Case2D
{
Case2D(Type type, Rotation rotation, I ni, I nj, I mi, I mj, I start, I stride) : type(type), rotation(rotation), ni(ni), nj(nj), mi(mi), mj(mj),
start(start), stride(stride)
{}
static std::optional<Case2D> diagnose(I ni, I nj, BoundaryCondition N, BoundaryCondition E, BoundaryCondition S, BoundaryCondition W)
{
int nD{ 0 };
int nP{ 0 };
if (N == BoundaryCondition::Dirichlet) {
++nD;
} else if(N == BoundaryCondition::Periodic) {
++nP;
}
if (E == BoundaryCondition::Dirichlet) {
++nD;
} else if(E == BoundaryCondition::Periodic) {
++nP;
}
if (S == BoundaryCondition::Dirichlet) {
++nD;
} else if(S == BoundaryCondition::Periodic) {
++nP;
}
if (W == BoundaryCondition::Dirichlet) {
++nD;
} else if(W == BoundaryCondition::Periodic) {
++nP;
}
if (nP > 0) {
// To do at some point
} else {
// Non-periodic cases
if (nD == 4) {
// DDDD
return Case2D(Type::DDDD, Rotation::CCW0, ni, nj, ni - 2, nj - 2, ni + 1, 2);
} else if(nD == 3) {
// DDDA
Rotation rotation{ Rotation::CCW0 };
I mi{ ni - 1 };
I mj{ nj - 2 };
I start{ ni };
I stride{ 1 };
if (N == BoundaryCondition::Adiabatic) {
rotation = Rotation::CCW90;
mi = ni - 2;
mj = nj - 1;
start = 1;
stride = 2;
} else if(E == BoundaryCondition::Adiabatic) {
rotation = Rotation::CCW180;
mi = ni - 1;
mj = nj - 2;
start = ni + 1;
stride = 1;
} else if(S == BoundaryCondition::Adiabatic) {
rotation = Rotation::CCW270;
mi = ni - 2;
mj = nj - 1;
start = ni + 1;
stride = 2;
}
return Case2D(Type::DDDA, rotation, ni, nj, mi, mj, start, stride);
} else if (nD == 1) {
// DAAA
Rotation rotation{ Rotation::CCW0 };
I mi{ ni };
I mj{ nj - 1 };
I start{ 0 };
I stride{ 0 };
if (W == BoundaryCondition::Dirichlet) {
rotation = Rotation::CCW90;
mi = ni - 1;
mj = nj;
start = 1;
stride = 1;
} else if (S == BoundaryCondition::Dirichlet) {
rotation = Rotation::CCW180;
mi = ni;
mj = nj - 1;
start = ni;
stride = 1;
} else if (E == BoundaryCondition::Dirichlet) {
rotation = Rotation::CCW270;
mi = ni - 1;
mj = nj;
start = 0;
stride = 1;
}
return Case2D(Type::DAAA, rotation, ni, nj, mi, mj, start, stride);
} else if (nD == 0) {
// AAAA, To do at some point
} else {
// DDAA or DADA
if (N == BoundaryCondition::Dirichlet) {
// DDAA(0), DAAD(90), DADA(0)
if (S == BoundaryCondition::Dirichlet) {
// DADA
return Case2D(Type::DADA, Rotation::CCW0, ni, nj, ni, nj-2, ni, 0);
} else if (W == BoundaryCondition::Dirichlet) {
// DAAD
return Case2D(Type::DDAA, Rotation::CCW90, ni, nj, ni-1, nj-1, 1, 1);
}
// DDAA
return Case2D(Type::DDAA, Rotation::CCW0, ni, nj, ni - 1, nj - 1, 0, 1);
} else {
// AADD(180), ADDA(270), ADAD(90)
if (E == BoundaryCondition::Adiabatic) {
// AADD
return Case2D(Type::DDAA, Rotation::CCW180, ni, nj, ni - 1, nj - 1, ni + 1, 1);
} else if (S == BoundaryCondition::Dirichlet) {
// ADDA
return Case2D(Type::DDAA, Rotation::CCW270, ni, nj, ni - 1, nj - 1, ni, 1);
}
// ADAD
return Case2D(Type::DADA, Rotation::CCW90, ni, nj, ni - 2, nj, 1, 2);
}
}
}
return {};
}
Type type{ Type::DDDD };
Rotation rotation{ Rotation::CCW0 };
I ni{ 0 }, nj{ 0 }, mi{ 0 }, mj{ 0 };
I start{ 0 }, stride{ 0 };
};
template <typename I, typename R, template <typename ...> typename V> struct Poisson2D
{
Poisson2D(I ni, I nj) : ni(std::max(ni, (I)3)), nj(std::max(nj, (I)3))
{
I N2 = ni * nj;
x.resize(N2);
y.resize(N2);
u.resize(N2);
f.resize(N2);
for (I i = 0; i < N2; ++i) {
u[i] = 0.0;
f[i] = 0.0;
}
R deltax = 1.0 / (R)(ni - 1);
R deltay = 1.0 / (R)(nj - 1);
I ij = 0;
for (I j = 0; j < nj; ++j) {
R yy = deltay * j;
for (I i = 0; i < ni; ++i) {
y[ij] = yy;
x[ij] = deltax * i;
++ij;
}
}
}
Poisson2D(I n) : Poisson2D(n,n)
{}
R operator()(I i, I j)
{
return u[i + j * ni];
}
void set_west(std::function<R(R)> fcn)
{
I ij = 0;
for (I j = 0; j < nj; ++j) {
u[ij] = fcn(y[ij]);
ij += ni;
}
}
void set_east(std::function<R(R)> fcn)
{
I ij = ni-1;
for (I j = 0; j < nj; ++j) {
u[ij] = fcn(y[ij]);
ij += ni;
}
}
void set_south(std::function<R(R)> fcn)
{
I ij = 0;
for (I j = 0; j < nj; ++j) {
u[ij] = fcn(x[ij]);
++ij;
}
}
void set_north(std::function<R(R)> fcn)
{
I ij = nj*(ni - 1);
for (I j = 0; j < nj; ++j) {
u[ij] = fcn(x[ij]);
++ij;
}
}
void set_rhs(std::function<R(R,R)> fcn)
{
I ij = nj * (ni - 1);
for (I j = 0; j < nj; ++j) {
f[ij] = fcn(x[ij],y[ij]);
++ij;
}
}
const I ni, nj;
V<R> x, y, u, f;
BoundaryCondition north_boundary_condition = BoundaryCondition::Dirichlet;
BoundaryCondition east_boundary_condition = BoundaryCondition::Dirichlet;
BoundaryCondition south_boundary_condition = BoundaryCondition::Dirichlet;
BoundaryCondition west_boundary_condition = BoundaryCondition::Dirichlet;
std::optional<GaussSiedelIterator<I,R,V>> gauss_siedel_iterator(V<I> &x_map, std::ostream *out = nullptr)
{
auto twod = Case2D<I>::diagnose(ni, nj, north_boundary_condition,
east_boundary_condition, south_boundary_condition, west_boundary_condition);
if (!twod) {
return {};
}
if (out != nullptr) {
*out << " Type: " << (int)(twod->type) << std::endl;
*out << " Rot: " << (int)(twod->rotation) << std::endl;
*out << " ni: " << twod->ni << std::endl;
*out << " nj: " << twod->nj << std::endl;
*out << " mi: " << twod->mi << std::endl;
*out << " mj: " << twod->mj << std::endl;
*out << "Start: " << twod->start << std::endl;
*out << "Shift: " << twod->stride << std::endl;
}
I N = twod->mi*twod->mj;
V<R> newf(N);
x_map.resize(N);
I ij = twod->start;
I mij = 0;
for (I j = 0; j < twod->mj; ++j) {
for (I i = 0; i < twod->mi; ++i) {
x_map[mij] = ij;
newf[mij] = f[ij];
++mij;
++ij;
}
ij += twod->stride;
}
// Modify for boundary conditions
// Handle W border
ij = twod->start;
mij = 0;
if (west_boundary_condition == BoundaryCondition::Dirichlet) {
for (I j = 0; j < twod->mj; ++j) {
newf[mij] += u[ij - 1];
mij += twod->mi;
ij += ni;
}
} else {
mij += twod->mj*twod->mi;
ij += twod->mj*ni;
}
// Handle N border
mij = (twod->mj - 1)*twod->mi;
ij = x_map[mij];
if (north_boundary_condition == BoundaryCondition::Dirichlet) {
for (I i = 0; i < twod->mi; ++i) {
newf[mij] += u[ij + ni];
++mij;
++ij;
}
}
// Handle S border
ij = twod->start;
mij = 0;
if (south_boundary_condition == BoundaryCondition::Dirichlet) {
for (I i = 0; i < twod->mi; ++i) {
newf[mij] += u[ij - ni];
++mij;
++ij;
}
}
// Handle E border
mij = twod->mi-1;
ij = x_map[mij];
if (east_boundary_condition == BoundaryCondition::Dirichlet) {
for (I j = 0; j < twod->mj; ++j) {
newf[mij] += u[ij + 1];
mij += twod->mi;
ij += ni;
}
}
return GaussSiedelIterator<I, R, V>(twod->mi, twod->mj, newf, north_boundary_condition, east_boundary_condition,
south_boundary_condition, west_boundary_condition);
}
I matrix_system(V<V<R>> &M, V<I> &x_map, V<R> &b, std::ostream *out = nullptr)
{
auto twod = Case2D<I>::diagnose(ni, nj, north_boundary_condition,
east_boundary_condition, south_boundary_condition, west_boundary_condition);
if (!twod) {
return 0;
}
if (out != nullptr) {
*out << " Type: " << (int)(twod->type) << std::endl;
*out << " Rot: " << (int)(twod->rotation) << std::endl;
*out << " ni: " << twod->ni << std::endl;
*out << " nj: " << twod->nj << std::endl;
*out << " mi: " << twod->mi << std::endl;
*out << " mj: " << twod->mj << std::endl;
*out << "Start: " << twod->start << std::endl;
*out << "Shift: " << twod->stride << std::endl;
}
I N = twod->mi*twod->mj;
x_map.resize(N);
I ij = twod->start;
I mij = 0;
for (I j = 0; j < twod->mj; ++j) {
for (I i = 0; i < twod->mi; ++i) {
x_map[mij] = ij;
++mij;
++ij;
}
ij += twod->stride;
}
// Initialize the matrix equations
b.resize(twod->mi*twod->mj);
M.resize(twod->mi*twod->mj);
for (I i = 0; i < N; ++i) {
M[i].resize(twod->mi*twod->mj);
b[i] = f[x_map[i]];
for (I j = 0; j < N; ++j) {
M[i][j] = 0.0;
}
}
// Set up the equations
ij = twod->start;
mij = 0;
// j = 0
// Handle SW corner
if (west_boundary_condition == BoundaryCondition::Dirichlet &&
south_boundary_condition == BoundaryCondition::Dirichlet) {
b[mij] += u[ij - 1] + u[ij - ni];
M[mij][mij] = 4.0;
M[mij][mij + twod->mi] = -1.0;
M[mij][mij + 1] = -1.0;
++ij;
++mij;
}
// Now the rest
if (south_boundary_condition == BoundaryCondition::Adiabatic) {
for (I i = 0; i < twod->mi; ++i) {
M[mij][mij] = 1.0;
M[mij][mij + twod->mi] = -1.0;
++ij;
++mij;
}
} else if (south_boundary_condition == BoundaryCondition::Dirichlet) {
for (I i = 1; i < twod->mi-1; ++i) {
b[mij] += u[ij - ni];
M[mij][mij] = 4.0;
M[mij][mij + twod->mi] = -1.0;
M[mij][mij - 1] = -1.0;
M[mij][mij + 1] = -1.0;
++ij;
++mij;
}
}
// Handle the SE corner
if (east_boundary_condition == BoundaryCondition::Dirichlet &&
south_boundary_condition == BoundaryCondition::Dirichlet) {
b[mij] += u[ij + 1] + u[ij - ni];
M[mij][mij] = 4.0;
M[mij][mij + twod->mi] = -1.0;
M[mij][mij - 1] = -1.0;
++ij;
++mij;
}
ij += twod->stride;
// 1 <= j < mj-1
for (I j = 1; j < twod->mj-1; ++j) {
// i = 0
if (west_boundary_condition == BoundaryCondition::Dirichlet) {
b[mij] += u[ij - 1];
M[mij][mij] = 4.0;
M[mij][mij - twod->mi] = -1.0;
M[mij][mij + twod->mi] = -1.0;
M[mij][mij + 1] = -1.0;
} else {
// others go here
}
++ij;
++mij;
for (I i = 1; i < twod->mi-1; ++i) {
M[mij][mij] = 4.0;
M[mij][mij - twod->mi] = -1.0;
M[mij][mij + twod->mi] = -1.0;
M[mij][mij - 1] = -1.0;
M[mij][mij + 1] = -1.0;
++mij;
++ij;
}
// i = mi-1
if (west_boundary_condition == BoundaryCondition::Dirichlet) {
b[mij] += u[ij + 1];
M[mij][mij] = 4.0;
M[mij][mij - twod->mi] = -1.0;
M[mij][mij + twod->mi] = -1.0;
M[mij][mij - 1] = -1.0;
} else {
// others go here
}
++mij;
++ij;
ij += twod->stride;
}
// j = mj-1
// Handle the NW corner
if (west_boundary_condition == BoundaryCondition::Dirichlet &&
north_boundary_condition == BoundaryCondition::Dirichlet) {
b[mij] += u[ij - 1] + u[ij + ni];
M[mij][mij] = 4.0;
M[mij][mij - twod->mi] = -1.0;
M[mij][mij + 1] = -1.0;
++ij;
++mij;
}
// Now the rest
if (north_boundary_condition == BoundaryCondition::Adiabatic) {
for (I i = 0; i < twod->mi; ++i) {
M[mij][mij] = 1.0;
M[mij][mij - twod->mi] = -1.0;
++ij;
++mij;
}
} else if (north_boundary_condition == BoundaryCondition::Dirichlet) {
for (I i = 1; i < twod->mi - 1; ++i) {
b[mij] += u[ij + ni];
M[mij][mij] = 4.0;
M[mij][mij - twod->mi] = -1.0;
M[mij][mij - 1] = -1.0;
M[mij][mij + 1] = -1.0;
++ij;
++mij;
}
}
// Handle the NE corner
if (east_boundary_condition == BoundaryCondition::Dirichlet &&
north_boundary_condition == BoundaryCondition::Dirichlet) {
b[mij] += u[ij + 1] + u[ij + ni];
M[mij][mij] = 4.0;
M[mij][mij - twod->mi] = -1.0;
M[mij][mij - 1] = -1.0;
++ij;
++mij;
}
return N;
}
};
}
#endif
|
20721ccec6c0d618cfabe06b4d2e191f5403e073 | e89c3fdb417976fc813da96510bba8da42235c71 | /editor/paintItems/shapes/triangleitem.cpp | c011656d61bf4a4ea3ebd7b052673483cff462f0 | [] | no_license | sm-jalali-f/jetprint | ec02f796d9445b497b424f01af739438146005eb | fb8c5fc669ae3ab5b6b787207ebcdf2a7567a7f4 | refs/heads/master | 2021-01-09T05:28:54.478245 | 2017-03-18T08:11:51 | 2017-03-18T08:11:51 | 80,773,364 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,489 | cpp | triangleitem.cpp | #include "triangleitem.h"
TriangleItem::TriangleItem(QWidget *parent, QPointF position1, QPointF position2, QPointF position3)
:DrawItem()
{
this->parent = parent;
this->position1 =position1;
this->position2 =position2;
this->position3 =position3;
this->itemType = SHAPE_TRIANGLE;
}
QPoint TriangleItem::getPosition()
{
return getLeftTopPoint();
}
int TriangleItem::getWidth() const
{
return (getRightBottomPoint().x()-getLeftTopPoint().x());
}
int TriangleItem::getHeight() const
{
return (getRightBottomPoint().y()-getLeftTopPoint().y());
}
QPixmap TriangleItem::toPixmap()
{
if (!scene()) {
qWarning() << "[ControlItem::toPixmap] scene is null.";
return QPixmap();
}
QRectF r = boundingRect();
QPixmap pixmap(r.width(), r.height());
pixmap.fill(Qt::transparent);
QPainter painter(&pixmap);
painter.drawRect(r);
scene()->render(&painter, QRectF(), sceneBoundingRect());
painter.end();
return pixmap;
}
void TriangleItem::setPosition(int x, int y)
{
QPoint leftTop;
leftTop = getLeftTopPoint();
int diffX = x- leftTop.x();
int diffY = y - leftTop.y();
qDebug()<<"pos1:"<<position1;
qDebug()<<"pos2:"<<position2;
qDebug()<<"pos3:"<<position3;
position1.setX(position1.x()+diffX);
position2.setX(position2.x()+diffX);
position3.setX(position3.x()+diffX);
position1.setY(position1.y()+diffY);
position2.setY(position2.y()+diffY);
position3.setY(position3.y()+diffY);
}
void TriangleItem::hideItem()
{
this->hide();
}
void TriangleItem::showItem()
{
this->show();
}
bool TriangleItem::isInside(QPoint point)
{
if( point.x()< this->getPosition().x()+this->getWidth()
&& point.x() > this->getPosition().x()
&& point.y() > this->getPosition().y()
&& point.y() < this->getPosition().y()+this->getHeight()){
return true;
}
return false;
}
void TriangleItem::changeFontSize(int fontSize)
{
}
void TriangleItem::itemDropEvent(QDropEvent *event)
{
if(!isDragingItem())
return;
if (event->mimeData()->hasFormat("application/x-dnditemdata")) {
// isDraging = false;
// isPressed = false;
QByteArray itemData = event->mimeData()->data("application/x-dnditemdata");
QDataStream dataStream(&itemData, QIODevice::ReadOnly);
QPixmap pixmap;
QPoint offset;
dataStream >> pixmap >> offset;
this->setPosition(event->pos().x()-insideX,event->pos().y()-insideY);
if (event->source() == parent) {
event->setDropAction(Qt::MoveAction);
event->accept();
} else {
event->acceptProposedAction();
}
} else {
event->ignore();
}
}
void TriangleItem::itemDragEnterEvent(QDragEnterEvent *event)
{
if (event->mimeData()->hasFormat("application/x-dnditemdata")) {
if (event->source() == parent) {
event->setDropAction(Qt::MoveAction);
event->accept();
} else {
event->acceptProposedAction();
}
} else {
event->ignore();
}
}
void TriangleItem::itemDragMoveEvent(QDragMoveEvent *event)
{
if (event->mimeData()->hasFormat("application/x-dnditemdata")) {
if (event->source() == parent) {
event->setDropAction(Qt::MoveAction);
event->accept();
} else {
event->acceptProposedAction();
}
} else {
event->ignore();
}
}
void TriangleItem::keyboardPressed(QKeyEvent *event)
{
}
MouseMoveResult TriangleItem::onMouseMove(QMouseEvent *event)
{
if(!isPressedItem()){
return whereIsPoint(QPoint(event->x(),event->y()));
}
// isDraging =true;
QByteArray itemData;
QDataStream dataStream(&itemData, QIODevice::WriteOnly);
QPoint circleCenter(this->getPosition().x(),this->getPosition().y());
dataStream << this->toPixmap() << QPoint(event->pos() - circleCenter);
QMimeData *mimeData = new QMimeData;
mimeData->setData("application/x-dnditemdata", itemData);
QDrag *drag = new QDrag(parent);
drag->setMimeData(mimeData);
drag->setPixmap(this->toPixmap());
drag->setHotSpot(event->pos() - circleCenter);
drag->exec(Qt::CopyAction | Qt::MoveAction, Qt::CopyAction);
return IN_DRAGING_MODE;
}
void TriangleItem::onMouseReleased(QMouseEvent *event)
{
// if(!isDraging && isPressed){
// this->isSelect =true;
// this->isPressed= false;
// }
}
bool TriangleItem::onMousePressed(QMouseEvent *event)
{
if(isInside(QPoint(event->pos().x(),event->pos().y()))){
insideX = event->pos().x()-this->getPosition().x();
insideY = event->pos().y()-this->getPosition().y();
// isPressed = true;
return true;
}
// this->isSelect =false;
return false;
}
QRectF TriangleItem::boundingRect() const
{
QPointF leftTop = getLeftTopPoint();
return QRectF(leftTop.x(),leftTop.y(),getWidth(),getHeight());
}
void TriangleItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
if(isRemoved())
return;
scene()->setBackgroundBrush(shapeBgBrush);
painter->setOpacity(Qt::transparent);
if(!isDragingItem())
painter->setPen(shapePen);
else
painter->setPen(dragPen);
painter->drawLine(QLine(position1.x(),position1.y(),position2.x(),position2.y()));
painter->drawLine(QLine(position1.x(),position1.y(),position3.x(),position3.y()));
painter->drawLine(QLine(position3.x(),position3.y(),position2.x(),position2.y()));
updateCornerPoint();
if(isDrawBorder()){
this->paintSelectBorder(painter,leftTop,rightTop,leftBottom,rightBottom);
}
}
QPoint TriangleItem::getLeftTopPoint() const
{
int minX,minY;
if(position1.x()<position2.x()){
if(position1.x()<position3.x())
minX = position1.x();
else
minX = position3.x();
}else{
if(position2.x()<position3.x())
minX = position2.x();
else
minX = position3.x();
}
if(position1.y()<position2.y()){
if(position1.y()<position3.y())
minY = position1.y();
else
minY = position3.y();
}else{
if(position2.y()<position3.y())
minY = position2.y();
else
minY = position3.y();
}
return QPoint(minX,minY);
}
QPoint TriangleItem::getRightBottomPoint() const
{
int maxX,maxY;
if(position1.x()>position2.x()){
if(position1.x()>position3.x())
maxX = position1.x();
else
maxX = position3.x();
}else{
if(position2.x()>position3.x())
maxX = position2.x();
else
maxX = position3.x();
}
if(position1.y()>position2.y()){
if(position1.y()>position3.y())
maxY = position1.y();
else
maxY = position3.y();
}else{
if(position2.y()>position3.y())
maxY = position2.y();
else
maxY = position3.y();
}
return QPoint(maxX,maxY);
}
|
b6c45a3b5611519627612085a9c014836a123e0c | e6b96681b393ae335f2f7aa8db84acc65a3e6c8d | /atcoder.jp/agc010/agc010_c/Main.cpp | f04dadfa0f1717a24cd08d96ffdd89222de0551a | [] | no_license | okuraofvegetable/AtCoder | a2e92f5126d5593d01c2c4d471b1a2c08b5d3a0d | dd535c3c1139ce311503e69938611f1d7311046d | refs/heads/master | 2022-02-21T15:19:26.172528 | 2021-03-27T04:04:55 | 2021-03-27T04:04:55 | 249,614,943 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,793 | cpp | Main.cpp | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef pair<int,int> P;
#define pb push_back
#define mp make_pair
#define eps 1e-9
#define INF 2000000000
#define LLINF 1000000000000000ll
#define sz(x) ((int)(x).size())
#define fi first
#define sec second
#define all(x) (x).begin(),(x).end()
#define sq(x) ((x)*(x))
#define rep(i,n) for(int (i)=0;(i)<(int)(n);(i)++)
#define repn(i,a,n) for(int (i)=(a);(i)<(int)(n);(i)++)
#define EQ(a,b) (abs((a)-(b))<eps)
template<class T> void chmin(T& a,const T& b){if(a>b)a=b;}
template<class T> void chmax(T& a,const T& b){if(a<b)a=b;}
int N;
ll A[100100];
vector<int> g[100100];
int par[100100];
int deg[100100];
ll c[100100];
ll csum[100100];
void dfs(int v,int p){
par[v]=p;
int cnt = 0;
for(int i=0;i<g[v].size();i++){
int u = g[v][i];
if(u==p)continue;
cnt++;
dfs(u,v);
csum[v]+=c[u];
}
if(cnt>0)c[v]=2ll*A[v]-csum[v];
else c[v]=A[v];
}
void fail(int x=-1){
//cout << "fail: " << x << endl;
cout << "NO" << endl;
exit(0);
}
int main(){
cin >> N;
for(int i=0;i<N;i++)cin >> A[i];
for(int i=0;i<N-1;i++){
int a,b;
cin >> a >> b;
a--;b--;
deg[a]++;
deg[b]++;
g[a].pb(b);
g[b].pb(a);
}
dfs(0,-1);
for(int i=0;i<N;i++){
//cout << i << ' ' << c[i] << ' ' << csum[i] << endl;
if(i>0&&c[i]<0ll)fail();
}
if(deg[0]==1){
if(c[g[0][0]]!=A[0])fail(0);
}else{
if(c[0]!=0)fail();
for(int i=0;i<g[0].size();i++){
int u = g[0][i];
if(c[u]>A[0])fail();
}
}
for(int i=1;i<N;i++){
if(deg[i]>1&&c[i]>csum[i])fail(1);
ll rem = 0ll;
ll h = (csum[i]-c[i])/2ll;
for(int j=0;j<g[i].size();j++){
int u = g[i][j];
if(par[i]==u)continue;
rem += max(0ll,c[u]-h);
}
if(rem>c[i])fail(2);
}
cout << "YES" << endl;
return 0;
} |
e931a85ce5b1869ecd3ac43092a21af11f2a861c | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/os/ossrv/stdlibs/apps/libc/testoffsetof/inc/toffsetof.h | 98979b280ed6a4e443701b94ab69535b57e757b0 | [] | no_license | SymbianSource/oss.FCL.sftools.ana.compatanamdw | a6a8abf9ef7ad71021d43b7f2b2076b504d4445e | 1169475bbf82ebb763de36686d144336fcf9d93b | refs/heads/master | 2020-12-24T12:29:44.646072 | 2010-11-11T14:03:20 | 2010-11-11T14:03:20 | 72,994,432 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 940 | h | toffsetof.h | /*
* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description:
*
*/
#ifndef __TESTOFFSETOF_H__
#define __TESTOFFSETOF_H__
// INCLUDES
#include <test/TestExecuteStepBase.h>
#include <stdio.h>
#include <stddef.h>
_LIT(Koffsetof, "offsetof_test");
class CTestOffsetof : public CTestStep
{
public:
~CTestOffsetof();
CTestOffsetof(const TDesC& aStepName);
TVerdict doTestStepL();
TVerdict doTestStepPreambleL();
TVerdict doTestStepPostambleL();
protected:
TInt offsetof_test();
};
#endif //__TESTOFFSETOF_H__
|
9505f5358a743f877f86af168b5ffb6bc351c63b | 9f5dd76fe21a66f90700f83840f2491dd34b17f9 | /third_party/mlir/test/lib/Transforms/TestCallGraph.cpp | debf5e77645555b5e328b204fec2ba156b1ba77f | [
"Apache-2.0"
] | permissive | thuanvh/tensorflow | b328964da68744bbd77799b13729835dcf4dbf79 | a599e0e2fc5a0e7964ad25c2f5c7e6ed5b679dc6 | refs/heads/master | 2021-07-20T13:55:40.451003 | 2019-12-03T06:34:09 | 2019-12-03T06:34:09 | 119,012,773 | 3 | 1 | Apache-2.0 | 2019-12-03T06:42:38 | 2018-01-26T06:05:36 | C++ | UTF-8 | C++ | false | false | 1,422 | cpp | TestCallGraph.cpp | //===- TestCallGraph.cpp - Test callgraph construction and iteration ------===//
//
// Copyright 2019 The MLIR 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.
// =============================================================================
//
// This file contains test passes for constructing and iterating over a
// callgraph.
//
//===----------------------------------------------------------------------===//
#include "mlir/Analysis/CallGraph.h"
#include "mlir/Pass/Pass.h"
using namespace mlir;
namespace {
struct TestCallGraphPass : public ModulePass<TestCallGraphPass> {
void runOnModule() {
llvm::errs() << "Testing : " << getModule().getAttr("test.name") << "\n";
getAnalysis<CallGraph>().print(llvm::errs());
}
};
} // end anonymous namespace
static PassRegistration<TestCallGraphPass>
pass("test-print-callgraph",
"Print the contents of a constructed callgraph.");
|
2782527c7634908bc690e696fef6b9a79b9200b7 | 1487d7451af7de570b3b1d2c4b56040fc11e8ba3 | /app/src/main/cpp/player/CPlayer.h | 1ea098ff36dc60dfdeb3568373a5aa9acf5d5d8f | [] | no_license | BlueLucky/NdkPlayer | d39c5dcea06a9d3c878b137a2580a113bc671dac | cf83d75ea7f5a4a7ca8c3c8d8408356354126d30 | refs/heads/master | 2023-05-04T12:07:41.101809 | 2021-05-31T10:21:00 | 2021-05-31T10:21:00 | 368,521,415 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,155 | h | CPlayer.h | #ifndef NDKPLAYER_CPLAYER_H
#define NDKPLAYER_CPLAYER_H
#include <cstring>
#include <pthread.h>
#include "../channel/AudioChannel.h"
#include "../channel/VideoChannel.h"
#include "../callback/JNICallbackHelper.h"
#include <android/log.h>
#define TAG "Lucky_log"
// ... 我都不知道传入什么 借助JNI里面的宏来自动帮我填充
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,TAG,__VA_ARGS__)
extern "C"{
#include <libavformat/avformat.h>
#include <libavutil/time.h>
};
typedef void(*RenderCallBack)(uint8_t *,int,int,int) ;
class CPlayer {
private:
char *dataSource=0;
AVFormatContext *formatContext=0;
pthread_t pid_prepare = 0;
pthread_t pid_start = 0;
AudioChannel *audio_channel=0;
VideoChannel *video_channel=0;
JNICallbackHelper *helper =0;
void onError(int,int,char *);
RenderCallBack renderCallBack;
public:
CPlayer(const char *dataSource, JNICallbackHelper *pHelper);
~CPlayer();
void prepare();
void prepare_();
void start();
void start_();
bool isPlaying;
void setRendCallBack(RenderCallBack renderCallBack);
};
#endif //NDKPLAYER_CPLAYER_H
|
3bd0fe14738a120120c7a9f359d29bfb178ff84d | 227c9efed80c3279526696ddaeaaee552de6a691 | /src/accumulate_cpu.cpp | 52ac14af65ff50a638dd66149b33650eba1708c5 | [] | no_license | ajis01/vvision-kernels | 7090b3b882bef5b638790fdff6dfa611e18db31d | e9e43ebc8ac4911b98fc856f49a6c81c4049b6ea | refs/heads/main | 2023-04-01T02:06:21.605303 | 2021-04-12T08:30:37 | 2021-04-12T08:30:37 | 339,648,972 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 785 | cpp | accumulate_cpu.cpp | #include "cpu_kernels.h"
namespace cpu {
//accumalate src into dest with mask
int accumulate(float const* src, int srcRows, int srcCols, int srcStep, int srcChannels,
float* dest, int destRows, int destCols, int destStep, int destChannels){
assert(srcRows == destRows && srcCols == destCols && srcStep == destStep && srcChannels==destChannels);
for(int jj=0; jj<srcCols; jj+=BLOCK_SIZE){
for(int i=0; i<srcRows; ++i){
for(int j=jj; j<std::min(jj+BLOCK_SIZE,srcCols); ++j){
for(int k=0; k<srcChannels; ++k)
dest[i*destStep + j*srcChannels + k] += src[i*srcStep + j*srcChannels + k];
}
}
}
return KERNEL_SUCCESS;
}
} |
b027ffcf3bafb1d894931601906266ed682dc8ee | 1786f51414ac5919b4a80c7858e11f7eb12cb1a9 | /USST/2019夏集训/day3/I.cpp | c956ea7cf45838e418ba56a1c506863816ea86d0 | [] | no_license | SetsunaChyan/OI_source_code | 206c4d7a0d2587a4d09beeeb185765bca0948f27 | bb484131e02467cdccd6456ea1ecb17a72f6e3f6 | refs/heads/master | 2020-04-06T21:42:44.429553 | 2019-12-02T09:18:54 | 2019-12-02T09:18:54 | 157,811,588 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,143 | cpp | I.cpp | #include <bits/stdc++.h>
using namespace std;
int par[10005],val[10005][20],lg[10005],dep[10005],fa[10005][20],m,n,q,tot=0,vis[10005];
struct edge
{
int x,y,z;
}e1[50005];
vector<int> e[10005],v[10005];
int _find(int x){return x==par[x]?x:par[x]=_find(par[x]);}
bool cmp(edge a,edge b){return a.z>b.z;}
void dfs(int now,int u,int col)
{
dep[now]=dep[u]+1;
fa[now][0]=u;
vis[now]=col;
for(int i=1;(1<<i)<=dep[now];i++)
fa[now][i]=fa[fa[now][i-1]][i-1],val[now][i]=min(val[fa[now][i-1]][i-1],val[now][i-1]);
for(int i=0;i<e[now].size();i++)
if(!vis[e[now][i]])
{
val[e[now][i]][0]=v[now][i];
dfs(e[now][i],now,col);
}
}
int lca(int x,int y)
{
int ret=0x3f3f3f3f;
if(dep[x]<dep[y]) swap(x,y);
while(dep[x]>dep[y])
ret=min(ret,val[x][lg[dep[x]-dep[y]]-1]),x=fa[x][lg[dep[x]-dep[y]]-1];
if(x==y) return ret;
for(int i=lg[dep[x]]-1;i>=0;i--)
if(fa[x][i]!=fa[y][i])
{
ret=min(ret,val[x][i]);
ret=min(ret,val[y][i]);
x=fa[x][i],y=fa[y][i];
}
ret=min(ret,val[x][0]);
ret=min(ret,val[y][0]);
return ret;
}
int main()
{
memset(vis,0,sizeof(vis));
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++) par[i]=i;
lg[0]=0;
for(int i=1;i<=n;i++)
lg[i]=lg[i-1]+(1<<lg[i-1]==i);
for(int i=0;i<m;i++)
scanf("%d%d%d",&e1[i].x,&e1[i].y,&e1[i].z);
sort(e1,e1+m,cmp);
for(int i=0;i<m;i++)
{
int x=_find(e1[i].x),y=_find(e1[i].y);
if(x==y) continue;
par[x]=y;
e[e1[i].x].push_back(e1[i].y),v[e1[i].x].push_back(e1[i].z);
e[e1[i].y].push_back(e1[i].x),v[e1[i].y].push_back(e1[i].z);
}
for(int i=1;i<=n;i++)
if(!vis[i])
{
tot++;
dep[i]=0,val[i][0]=0x3f3f3f3f;
dfs(i,i,tot);
}
scanf("%d",&q);
while(q--)
{
int x,y;
scanf("%d%d",&x,&y);
if(vis[x]!=vis[y])
printf("-1\n");
else
printf("%d\n",lca(x,y));
}
return 0;
}
/*
4 3
1 2 4
2 3 3
3 1 1
3
1 3
1 4
1 3
*/
|
d59187b48e2925df9be5332daf8f5a151bf6330d | a3d6556180e74af7b555f8d47d3fea55b94bcbda | /media/formats/dts/dts_stream_parser.cc | 108de4dc5fad3d45eb56f68af4689f3d9b62277d | [
"BSD-3-Clause"
] | permissive | chromium/chromium | aaa9eda10115b50b0616d2f1aed5ef35d1d779d6 | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | refs/heads/main | 2023-08-24T00:35:12.585945 | 2023-08-23T22:01:11 | 2023-08-23T22:01:11 | 120,360,765 | 17,408 | 7,102 | BSD-3-Clause | 2023-09-10T23:44:27 | 2018-02-05T20:55:32 | null | UTF-8 | C++ | false | false | 2,927 | cc | dts_stream_parser.cc | // Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "media/formats/dts/dts_stream_parser.h"
#include <stddef.h>
#include "build/build_config.h"
#include "media/base/media_log.h"
namespace media {
DTSStreamParser::DTSStreamParser()
: MPEGAudioStreamParserBase(kDTSCoreSyncWord, AudioCodec::kDTS, 0) {}
DTSStreamParser::~DTSStreamParser() = default;
int DTSStreamParser::ParseFrameHeader(const uint8_t* data,
int size,
int* frame_size,
int* sample_rate,
ChannelLayout* channel_layout,
int* sample_count,
bool* metadata_frame,
std::vector<uint8_t>* extra_data) {
if (data == nullptr || size < kDTSCoreHeaderSizeInBytes)
return 0;
BitReader reader(data, size);
// Read and validate Sync word.
uint32_t sync_word = 0;
reader.ReadBits(32, &sync_word);
if (sync_word != kDTSCoreSyncWord)
return 0;
int fsize = 0, ext_audio = 0, ext_audio_id = 0, nblks = 0, sfreq = 0;
// Skip ftype(1-bit) + DeficitSample Count(5-bits) + CRC Present Flag(1-bit)
reader.SkipBits(7);
reader.ReadBits(7, &nblks);
reader.ReadBits(14, &fsize);
reader.SkipBits(6); // Skip AMODE
reader.ReadBits(4, &sfreq);
reader.SkipBits(10); // Skip: RATE, FixedBit, DNYF, TIMEF, AUSX, HDCD
reader.ReadBits(3, &ext_audio_id);
reader.ReadBits(1, &ext_audio);
constexpr int kSampleRateCore[16] = {0, 8000, 16000, 32000, 0, 0,
11025, 22050, 44100, 0, 0, 12000,
24000, 48000, 0, 0};
if (fsize < 95) // Invalid values of FSIZE is 0-94.
return 0;
if (nblks < 5 || nblks > 127) // Valid values of nblks is 5-127.
return 0;
if (kSampleRateCore[sfreq] == 0) // Table value of 0 indicates invalid
return 0;
// extended audio may modify sample count and rate
bool is_core_x96 = ext_audio && ext_audio_id == 2;
if (channel_layout)
*channel_layout = media::CHANNEL_LAYOUT_5_1;
if (extra_data)
extra_data->clear();
if (frame_size)
*frame_size = fsize + 1; // Framesize is FSIZE + 1.
if (metadata_frame)
*metadata_frame = false;
// Use nblks to compute frame duration, a.k.a number of PCM samples per
// channel in the current DTS frames in the buffer.
if (sample_count) {
*sample_count = (nblks + 1) * 32; // Num of PCM samples in current frame
if (is_core_x96)
*sample_count <<= 1;
}
if (sample_rate) {
*sample_rate = kSampleRateCore[sfreq]; // sfreq is table lookup
if (is_core_x96)
*sample_rate <<= 1;
}
return reader.bits_read() / 8;
}
} // namespace media
|
f8768f2d2c402867379e2f80096167891a3e7086 | 55405bda5a9063b53f643d46bf520433e1d647d8 | /AddressBook/TableViewCustom.hpp | a916fd9ccbe02921d13959419af2053891282318 | [] | no_license | InvictusInnovations/keyhotee | c6f41e8c7856e54feeb3ba6b3b950174813a8d0e | cb4d1402559e645fb843affd221079f979c807d6 | refs/heads/master | 2021-01-23T03:44:20.215606 | 2014-09-05T08:44:12 | 2014-09-05T08:44:12 | 13,315,798 | 8 | 6 | null | 2014-03-13T16:33:17 | 2013-10-04T03:41:43 | C | UTF-8 | C++ | false | false | 461 | hpp | TableViewCustom.hpp | #pragma once
#include <QTableView>
class IModificationsChecker;
class TableViewCustom : public QTableView
{
Q_OBJECT
public:
explicit TableViewCustom(QWidget *parent = nullptr);
virtual ~TableViewCustom();
void setModificationsChecker (IModificationsChecker*);
protected:
virtual bool viewportEvent(QEvent *event) override;
virtual void keyPressEvent(QKeyEvent *event) override;
private:
IModificationsChecker* _modificationsChecker;
}; |
1a2aae74e9a5d1a3e8d69fd702bc72d9108dbb3c | 96583bbe1987f76286d781ed612e641451e08741 | /Delta_Firmware/WifiSettings.h | 0dcf2d84a629dc812d09c73347aae9b332126aee | [] | no_license | VanThanBK/deltax_opensource_old | b3ceac05f65dfb0b003e03e0c3cf7f0798127c56 | 48fdcb0104b27dae6c92fbb993732fa8efce9a5f | refs/heads/master | 2023-03-27T15:50:28.124724 | 2021-02-26T04:33:22 | 2021-02-26T04:33:22 | 342,460,476 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 451 | h | WifiSettings.h | // WifiSettings.h
#ifndef _WIFISETTINGS_h
#define _WIFISETTINGS_h
#if defined(ARDUINO) && ARDUINO >= 100
#include "arduino.h"
#else
#include "WProgram.h"
#endif
#include <EEPROM.h>
#include "config.h"
class WifiSettingsClass
{
protected:
public:
void init();
void Save();
void SaveIP();
void IP();
void GetSsid();
void GetPswd();
String SSIDWifi;
String PSWDWifi;
String IPWifi;
};
extern WifiSettingsClass WifiSettings;
#endif
|
de453ae7170a50c02ba30877e7e38ef4c6db0c1e | 0da0d68390d4c82632259e1775d5ff70d00bbd0e | /modules/le_tessellator/le_tessellator.h | 86930feaaecd554f4f1d9f2413243e78bace3736 | [
"MIT"
] | permissive | tgfrerer/island | 1974c1c574d3037fe3364e6a10633f97395a0b9b | a2f91d050b49a3f2a0ae5ce4c8cdc21e6f8d8fd3 | refs/heads/wip | 2023-08-29T22:26:24.367135 | 2023-08-09T15:37:36 | 2023-08-09T15:37:36 | 150,248,562 | 844 | 35 | MIT | 2023-08-01T19:28:37 | 2018-09-25T10:36:37 | C++ | UTF-8 | C++ | false | false | 2,948 | h | le_tessellator.h | #ifndef GUARD_le_tessellator_H
#define GUARD_le_tessellator_H
#include "le_core.h"
#ifdef __cplusplus
# include <glm/fwd.hpp>
#endif
struct le_tessellator_o;
// clang-format off
struct le_tessellator_api {
typedef uint16_t IndexType;
struct le_tessellator_interface_t {
static constexpr auto OptionsWindingsOffset = 3;
enum Options : uint64_t {
// Flip one or more bits for options.
bitUseEarcutTessellator = 1 << 0, // use earcut over libtess, libtess being default
bitConstrainedDelaunayTriangulation = 1 << 1, /* ignored if tessellator not libtess */
bitReverseContours = 1 << 2, /* ignored if tessellator not libtess */
// Pick *one* of the following winding modes;
// For a description of winding modes, see: <http://www.glprogramming.com/red/chapter11.html>
eWindingOdd = 0 << OptionsWindingsOffset, /* ignored if tessellator not libtess */
eWindingNonzero = 1 << OptionsWindingsOffset, /* ignored if tessellator not libtess */
eWindingPositive = 3 << OptionsWindingsOffset, /* ignored if tessellator not libtess */
eWindingNegative = 4 << OptionsWindingsOffset, /* ignored if tessellator not libtess */
eWindingAbsGeqTwo = 5 << OptionsWindingsOffset, /* ignored if tessellator not libtess */
};
le_tessellator_o * ( * create ) ( );
void ( * destroy ) ( le_tessellator_o* self );
void ( * set_options ) ( le_tessellator_o* self, uint64_t options);
void ( * add_polyline ) ( le_tessellator_o* self, glm::vec2 const * const pPoints, size_t const& pointCount );
void ( * get_indices ) ( le_tessellator_o* self, IndexType const ** pIndices, size_t * indexCount );
void ( * get_vertices ) ( le_tessellator_o* self, glm::vec2 const ** pVertices, size_t * vertexCount );
bool ( * tessellate ) ( le_tessellator_o* self );
void ( * reset ) ( le_tessellator_o* self );
};
le_tessellator_interface_t le_tessellator_i;
};
// clang-format on
LE_MODULE( le_tessellator );
LE_MODULE_LOAD_DEFAULT( le_tessellator );
#ifdef __cplusplus
namespace le_tessellator {
static const auto& api = le_tessellator_api_i;
static const auto& le_tessellator_i = api -> le_tessellator_i;
using Options = le_tessellator_api::le_tessellator_interface_t::Options;
} // namespace le_tessellator
class LeTessellator : NoCopy, NoMove {
le_tessellator_o* self;
public:
LeTessellator()
: self( le_tessellator::le_tessellator_i.create() ) {
}
~LeTessellator() {
le_tessellator::le_tessellator_i.destroy( self );
}
operator auto() {
return self;
}
};
#endif // __cplusplus
#endif
|
57fa97c13bb21d451e8548ec1f59b8509545b62d | e2181e9439866cbf1455fdff66e4e27879eb034e | /src_my/utils/log.hpp | dd346deed579c804ca37b4f3857a76bf0da75843 | [] | no_license | lineCode/game_server-1 | 3fb841d3a4973d47e9c2692bbf9b1e440c499e5d | d9178ee8a0a504e5873bee3616d323056c9c9764 | refs/heads/master | 2020-05-19T08:01:02.835874 | 2019-05-03T11:10:57 | 2019-05-03T11:10:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,573 | hpp | log.hpp | #pragma once
#define BOOST_LOG_DYN_LINK 1
#include "proto/config_options.pb.h"
#include <boost/log/core.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/sinks/text_file_backend.hpp>
#include <boost/log/utility/setup/file.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
#include <boost/log/sources/severity_logger.hpp>
#include <boost/log/sources/record_ostream.hpp>
#include <string>
#include <iomanip>
namespace pc = proto::config;
namespace logging = boost::log;
namespace src = boost::log::sources;
namespace sinks = boost::log::sinks;
namespace expr = boost::log::expressions;
namespace keywords = boost::log::keywords;
using namespace std;
extern src::severity_logger<logging::trivial::severity_level> g_log;
#define __TLOG BOOST_LOG_SEV(g_log, logging::trivial::trace) << "[TRACE] "
#define __DLOG BOOST_LOG_SEV(g_log, logging::trivial::debug) << "[DEBUG] "
#define __ILOG BOOST_LOG_SEV(g_log, logging::trivial::info) << " [INFO] "
#define __ELOG BOOST_LOG_SEV(g_log, logging::trivial::error) << "[ERROR] "
#define __BILOG BOOST_LOG_SEV(g_log, logging::trivial::fatal)
#define TLOG __TLOG << setw(20) << " [NONE] "
#define DLOG __DLOG << setw(20) << " [NONE] "
#define ILOG __ILOG << setw(20) << " [NONE] "
#define ELOG __ELOG << setw(20) << " [NONE] "
namespace nora {
void init_log(const string& prefix, pc::options::log_level level);
void init_log_for_log_server(const string& prefix, pc::options::log_level level);
void change_log_level(pc::options::log_level level);
}
|
1c0e9fcb61af199a472c00a724948fb8e9b6a01a | e1de41ce287bbd0181b92f4746290233c4bb7755 | /client/Classes/View/GalleryLayer.cpp | e90a4da8d57b4f857df3679e253fcf5880e66deb | [] | no_license | yf0994/game-DarkWar | c7572cb80eced4356a0faadbd1a4b97d1b90f2ce | ba39e4b57c381e9a4e969b2ed58990bc1cfd94a9 | refs/heads/master | 2021-05-29T15:47:01.214082 | 2015-08-29T03:28:06 | 2015-08-29T03:28:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,728 | cpp | GalleryLayer.cpp | #include "GalleryLayer.h"
using namespace cocos2d;
using namespace cocos2d::extension;
CCPoint distance = ccp(10,0);
GalleryLayer::GalleryLayer()
{
mCallBack = NULL;
mDataSet = NULL;
itemArray = CCArray::createWithCapacity(5);
itemArray->retain();
mCurrentPageIndex = 0;
mPageNum = 0;
pageWidth = 0;
touchEffective = false;
}
GalleryLayer* GalleryLayer::create(CCSize size/*, CCNode* container*/)
{
CCLayer* container = CCLayer::create();
GalleryLayer* lay = new GalleryLayer();
lay->initWithViewSize(size,container);
lay->container = container;
lay->autorelease();
lay->setDirection(kCCScrollViewDirectionHorizontal);
lay->pageWidth = size.width + distance.x;
container->setContentSize(size);
container->setPosition(0,size.height/2);
return lay;
}
void GalleryLayer::setDataSetAndCallBack(GalleryDataSet* dataSet, GalleryCallBack* callBack)
{
mCallBack = callBack;
mDataSet = dataSet;
}
void GalleryLayer::reloadData()
{
CCPoint offset = ccp(0,0);
if (mDataSet)
{
mPageNum = mDataSet->getItemNum();
for (int i=0;i<mPageNum;i++)
{
CCNode* item = mDataSet->createItem(i);
container->addChild(item);
itemArray->addObject(item);
offset.x += item->getContentSize().width/2;
//offset.y += item->getContentSize().height/2;
item->setPosition(offset);
offset.x += item->getContentSize().width/2;
//offset.y += item->getContentSize().height/2;
offset.x += distance.x;
offset.y += distance.y;
}
}
}
bool GalleryLayer::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent)
{
touchEffective = CCScrollView::ccTouchBegan(pTouch,pEvent);
m_touchPoint = CCDirector::sharedDirector()->convertToGL(pTouch->getLocationInView());
return true;
}
void GalleryLayer::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent)
{
CCScrollView::ccTouchMoved(pTouch,pEvent);
}
void GalleryLayer::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent)
{
CCScrollView::ccTouchEnded(pTouch,pEvent);
// 不让他自己滑动
unscheduleAllSelectors();
if (touchEffective)
tryAutoScroll(m_touchPoint,pTouch->getLocation());
return;
}
void GalleryLayer::ccTouchCancelled(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent)
{
CCScrollView::ccTouchCancelled(pTouch,pEvent);
// 不让他自己滑动
unscheduleAllSelectors();
if (touchEffective)
tryAutoScroll(m_touchPoint,pTouch->getLocation());
return;
}
void GalleryLayer::scrollToPage(int pageIndex,bool animation /* = true */)
{
if (pageIndex < mPageNum && pageIndex >= 0)
{
mCurrentPageIndex = pageIndex;
scrollToCurrentPage(animation);
}
}
void GalleryLayer::scrollToCurrentPage(bool animation /* = true */)
{
CCPoint offset = ccp( -mCurrentPageIndex*pageWidth,container->getPositionY());
if (animation)
{
CCAction* action = CCSequence::create(
CCMoveTo::create(0.2f,offset),
CCCallFuncN::create(this,SEL_CallFuncN(&GalleryLayer::scrollEnd)),
NULL
);
container->stopAllActions();
container->runAction(action);
}else
{
container->setPosition(offset);
scrollEnd(NULL);
}
}
void GalleryLayer::scrollEnd(CCNode* container)
{
if (mCallBack)
{
mCallBack->onGallerySelected(mCurrentPageIndex,(CCNode*)itemArray->objectAtIndex(mCurrentPageIndex));
}
}
void GalleryLayer::tryAutoScroll(CCPoint startPoint,CCPoint endPoint)
{
float dis = ccpDistance(startPoint,endPoint);
bool goToRight = endPoint.x - startPoint.x < 0;
CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
if (dis > visibleSize.width/3)
{
if (goToRight && mCurrentPageIndex + 1 < mPageNum)
{
mCurrentPageIndex++;
}
else if(!goToRight && mCurrentPageIndex - 1 >= 0)
{
mCurrentPageIndex--;
}
}
scrollToCurrentPage();
}
GalleryLayer::~GalleryLayer()
{
itemArray->release();
} |
547c4feb700c57d4ad8de8cbe6d3dbc4d8f14387 | 17c5982b29c3a7c8294d5a25ddf9bb179f570d08 | /Classes/AGalacticThingyUI.h | e77fd24b48981542a7dec138618443771a00df84 | [] | no_license | fozolo/galactica-anno-dominari-3 | 89e1881c9312b8c5d51fb9ba05f13838eaf2fdd6 | c17049494120e8a2ad68309c4dda7ca37fd89e43 | refs/heads/master | 2020-09-11T20:09:28.562762 | 2016-01-12T19:06:04 | 2016-01-12T19:06:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,937 | h | AGalacticThingyUI.h | // AGalacticThingyUI.h
// ===========================================================================
// Copyright (c) 1996-2002, Sacred Tree Software
// All rights reserved
// ===========================================================================
// 3/9/96 ERZ, 4/18/96
// 3/14/02 ERZ, separated from AGalacticThingy
#ifndef AGALACTIC_THINGY_UI_H_INCLUDED
#define AGALACTIC_THINGY_UI_H_INCLUDED
#define kSelectionFrame false
#define kEntireFrame true
#include "AGalacticThingy.h"
#ifndef GALACTICA_SERVER
#include <LPane.h>
#include "GalacticaUtilsUI.h"
class GalacticaClient;
class AGalacticThingyUI : public AGalacticThingy, public LPane {
public:
static AGalacticThingyUI* MakeUIThingyFromSubClassType(LView* inSuper, GalacticaShared* inGame, long inThingyType);
enum { class_ID = 'thgy' };
AGalacticThingyUI(LView *inSuperView, GalacticaShared* inGame, long inThingyType);
AGalacticThingyUI(LView *inSuperView, GalacticaShared* inGame, LStream *inStream, long inThingyType);
virtual ~AGalacticThingyUI();
void InitThingyUI();
// ---- identity methods ----
virtual void SetID(SInt32 inID) { mPaneID = inID; AGalacticThingy::SetID(inID); }
virtual AGalacticThingyUI* AsThingyUI() { return this; }
// ---- persistence/streaming methods ----
virtual void FinishInitSelf(); // do anything that was waiting til pane id was assigned
virtual void ReadStream(LStream *inStream, UInt32 streamVersion = version_SavedTurnFile);
// ---- mouse handling methods ----
virtual void Click(SMouseDownEvent &inMouseDown);
virtual void ClickSelf(const SMouseDownEvent& inMouseDown);
virtual void DoubleClickSelf();
virtual Boolean DragSelf(SMouseDownEvent &inMouseDown); // called by click, return false if no dragging occurred.
virtual void AdjustMouseSelf(Point inPortPt, const EventRecord& inMacEvent, RgnHandle outMouseRgn);
virtual Boolean Contains(SInt32 inHorizPort, SInt32 inVertPort) const;
virtual Boolean IsHitBy(SInt32 inHorizPort, SInt32 inVertPort);
Rect GetHotSpotRect() const; // returns info based on ThingyClassInfo::GetHotSpotSize()
void CalcPortHotSpotRect(Rect &outRect) const;
// ---- selection methods ----
virtual void Select();
bool IsSelected() const;
// ---- drawing methods ----
void DrawHilite(bool inHilite);
inline bool Hiliting() const {return sChangingHilite;}
bool IsHilited() const {return sHilitedThingy == this;}
static AGalacticThingyUI* GetHilitedThingy() {return sHilitedThingy;}
virtual bool ShouldDraw() const;
virtual float GetBrightness(short inDisplayMode);
virtual Point GetDrawOffsetFromCenter() const {Point p = {0,0}; return p;}
virtual Rect GetCenterRelativeFrame(bool full = false) const; // override to return frame relative to center pt
virtual float GetScaleFactorForZoom() const;
void UpdateSelectionMarker(UInt32 inTick); // does everything needed to draw the selection marker
void DrawSelectionMarker();
void EraseSelectionMarker();
virtual bool DrawSphereOfInfluence(int level = -1);
virtual void DrawSelf();
virtual void Refresh();
Point GetDrawingPosition() const {return mDrawOffset;}
// ---- object info methods ----
Waypoint GetPosition() const {return mCurrPos;}
virtual ResIDT GetViewLayrResIDOffset();
virtual void Changed();
// ---- miscellaneous methods ----
virtual void ThingMoved(bool inRefresh);
void CalcPosition(bool inRefresh);
virtual void RemoveSelfFromGame(); // take something that has already been marked as dead completely out of the game
protected:
Point mDrawOffset; // center of thingy relative to the topleft of frame
static AGalacticThingyUI* sHilitedThingy; // last thingy to receive a hilite command
static SInt32 sOldHilitedPos; // order in list of last thingy that was hilited
static Cursor sTargetCursor;
static bool sCursorLoaded;
static bool sDragging; // item is being dragged
static bool sAutoscrolling; // autoscrolling during a drag
private:
bool mSelectionMarkerShown; // private: use DrawSelectionMarker()
int mSelectionMarkerPos;
static UInt32 sSelectionMarkerChangeTick;
static bool sChangingHilite; // true = Drawing should change state of hiliting; Private: use DrawHilite(), Hiliting() and IsHilited()
};
/*#ifdef DEBUG
ostream& operator << (ostream& cout, AGalacticThingyUI *outThingy);
#endif
*/
#else
// for a Galactica Server, we just declare AGalacticaThingyUI to be the same as a
// non-UI thingy
class AGalacticThingyUI : public AGalacticThingy {
public:
AGalacticThingyUI(LView*, GalacticaShared* inGame, long inThingyType)
: AGalacticThingy(inGame, inThingyType) {}
// AGalacticThingyUI(LView*, GalacticaShared* inGame, LStream *inStream, long inThingyType)
// : AGalacticThingy(inGame, inStream, inThingyType) {}
};
#endif // GALACTICA_SERVER
typedef std::vector<AGalacticThingyUI*> StdThingyUIList;
#endif // AGALACTIC_THINGY_UI_H_INCLUDED
|
067e31740ed132440c4361b6e1fd718946b7bb49 | b18c7355c25b98cbe5ba699a2ff5961f85594bf5 | /src/InfiniTAM/studio/app/src/main/jni/tangoMain.h | 7f35c886226e28fed51e9a1d46ad8a46497b40aa | [] | no_license | KastnerRG/infinitam_fpga | 963656807303ac6cf859337a3e8da32edf96928a | 771202a2db0da71c06f1d50b0e9cc4e9063d9313 | refs/heads/master | 2020-05-26T05:01:54.483419 | 2019-07-11T23:52:37 | 2019-07-11T23:52:37 | 188,115,310 | 24 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,408 | h | tangoMain.h |
#ifndef TANGO_MAIN_H_
#define TANGO_MAIN_H_
#include <jni.h>
#include "logging.h"
//#include "ImageDataBuffer.h"
//#include "DataBuffer.h"
//#include "DataWriter.h"
//#include "TangoImages.h"
typedef void* TangoConfig;
class TangoMain
{
public:
TangoMain();
~TangoMain();
// Check that the installed version of the Tango API is up to date.
//
// @return returns true if the application version is compatible with the
// Tango Core version.
bool CheckTangoVersion(JNIEnv* env, jobject caller_activity,
int min_tango_version);
// Called when Tango Service is connected successfully.
bool OnTangoServiceConnected(JNIEnv* env, jobject binder);
// Setup the configuration file for the Tango Service.
int TangoSetupConfig();
// Connect the onPoseAvailable callback.
int TangoConnectCallbacks();
// Connect to Tango Service.
// This function will start the Tango Service pipeline, in this case, it will
// start Motion Tracking and Depth Sensing callbacks.
bool TangoConnect();
// Disconnect from Tango Service, release all the resources that the app is
// holding from the Tango Service.
void TangoDisconnect();
void setConfigBool(const char* key, bool value);
bool getConfigBool(const char* key);
private:
TangoConfig tango_config_;
};
#endif // TANGO_MAIN_H_
|
9eeeaabb5e15dc7a55c555778f798959352faeb5 | 5220ec44bd018f12c32da698cacf8a4ee5108ecf | /Data Structures/Programs/Program2/service.h | bbf365b30b9271b5ebfa704dc3db92f4096b29fc | [] | no_license | ace0625/school-work | bf994f96a0821aaf6aa73194189a98c8feb96b07 | bf41322ec812924e1d60a26d9378afd28555298d | refs/heads/master | 2021-01-01T03:34:55.865381 | 2016-05-25T21:23:14 | 2016-05-25T21:23:14 | 59,698,576 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,124 | h | service.h | //CS163
//Assignment #2
//4/29/2015
//Hyunchan Kim
//service.h
//This class is the base class implements creating an order, copying order, getting current time,
//displaying service, total remaining time, and average time. The data go to the queue and stacks
//classes to manage different data structures.
#ifndef _SERVICE_H
#define _SERVICE_H
#include <iostream>
#include <cctype>
#include <cstring>
#include <ctime>
using namespace std;
//service class
class service
{
public:
service(); //constructor
~service(); //destructor
int createOrder(char * name, char * order, char * arrival_time, int length_of_time); //create an order
int copy_order(const service & copyfrom); //copy order
char getCurrentTime(); // get currentTime
void display(); //display a service
int total_remaining_time();
int average_time();
private:
char * name; //customer's name
char * order; //order name
char * arrival_time; //arrival time
int length_of_time; // the length of time
int total_time; // total time
};
//ask user whether to start again
bool again();
#endif
|
02c151abf072abf876874d94a62907a5e3413873 | 8194c153de598eaca637559443f71d13b729d4d2 | /ogsr_engine/xrGame/ai/monsters/ai_monster_squad_manager.cpp | 6446fc2ba8e535b202d312cd4ceeeb18ce1db097 | [
"Apache-2.0"
] | permissive | NikitaNikson/X-Ray_Renewal_Engine | 8bb464b3e15eeabdae53ba69bd3c4c37b814e33e | 38cfb4a047de85bb0ea6097439287c29718202d2 | refs/heads/dev | 2023-07-01T13:43:36.317546 | 2021-08-01T15:03:31 | 2021-08-01T15:03:31 | 391,685,134 | 4 | 4 | Apache-2.0 | 2021-08-01T16:52:09 | 2021-08-01T16:52:09 | null | UTF-8 | C++ | false | false | 3,379 | cpp | ai_monster_squad_manager.cpp | #include "stdafx.h"
#include "ai_monster_squad_manager.h"
#include "ai_monster_squad.h"
#include "../../entity.h"
//////////////////////////////////////////////////////////////////////////
// SQUAD MANAGER Implementation
//////////////////////////////////////////////////////////////////////////
CMonsterSquadManager *g_monster_squad = 0;
CMonsterSquadManager::CMonsterSquadManager()
{
}
CMonsterSquadManager::~CMonsterSquadManager()
{
for (u32 team_id=0; team_id<team.size();team_id++) {
for (u32 squad_id=0; squad_id<team[team_id].size(); squad_id++) {
for (u32 group_id=0; group_id<team[team_id][squad_id].size(); group_id++) {
xr_delete(team[team_id][squad_id][group_id]);
}
}
}
}
void CMonsterSquadManager::register_member(u8 team_id, u8 squad_id, u8 group_id, CEntity *e)
{
CMonsterSquad *pSquad;
// нет team - создать team, squad и group
if (team_id >= team.size()) {
team.resize (team_id + 1);
team[team_id].resize (squad_id + 1);
team[team_id][squad_id].resize (group_id + 1);
for (u32 i=0; i<group_id; i++)
team[team_id][squad_id][i] = 0;
pSquad = xr_new<CMonsterSquad>();
team[team_id][squad_id][group_id] = pSquad;
// есть team, нет squad - создать squad
} else if (squad_id >= team[team_id].size()) {
team[team_id].resize (squad_id + 1);
team[team_id][squad_id].resize (group_id + 1);
for (u32 i=0; i<group_id; i++)
team[team_id][squad_id][i] = 0;
pSquad = xr_new<CMonsterSquad>();
team[team_id][squad_id][group_id] = pSquad;
// есть team, squad, нет group
} else if (group_id >= team[team_id][squad_id].size()) {
u32 prev_size = (u32)team[team_id][squad_id].size();
team[team_id][squad_id].resize (group_id + 1);
for (u32 i = prev_size; i < group_id; i++)
team[team_id][squad_id][i] = 0;
pSquad = xr_new<CMonsterSquad>();
team[team_id][squad_id][group_id] = pSquad;
} else {
if (team[team_id][squad_id][group_id] == 0) {
pSquad = xr_new<CMonsterSquad>();
team[team_id][squad_id][group_id] = pSquad;
} else {
// TODO: Verify IT!
pSquad = team[team_id][squad_id][group_id];
}
}
pSquad->RegisterMember(e);
}
void CMonsterSquadManager::remove_member(u8 team_id, u8 squad_id, u8 group_id, CEntity *e)
{
get_squad(team_id, squad_id, group_id)->RemoveMember(e);
}
CMonsterSquad *CMonsterSquadManager::get_squad(u8 team_id, u8 squad_id, u8 group_id)
{
VERIFY((team_id < team.size()) && (squad_id < team[team_id].size()) && (group_id < team[team_id][squad_id].size()));
return team[team_id][squad_id][group_id];
}
CMonsterSquad *CMonsterSquadManager::get_squad(const CEntity *entity)
{
return get_squad((u8)entity->g_Team(),(u8)entity->g_Squad(),(u8)entity->g_Group());
}
void CMonsterSquadManager::update(CEntity *entity)
{
CMonsterSquad *squad = monster_squad().get_squad(entity);
if (squad && squad->SquadActive() && (squad->GetLeader() == entity)) {
squad->UpdateSquadCommands();
}
}
void CMonsterSquadManager::remove_links(CObject *O)
{
for (u32 team_id=0; team_id<team.size();team_id++) {
for (u32 squad_id=0; squad_id<team[team_id].size(); squad_id++) {
for (u32 group_id=0; group_id<team[team_id][squad_id].size(); group_id++) {
CMonsterSquad *squad = team[team_id][squad_id][group_id];
if (squad) squad->remove_links(O);
}
}
}
}
|
79f97de934b6f5f2060c2f846478ef3fa6953c0f | b2e0629201d0390bb78a651cc9cc070ec41d7703 | /9.2/main.cpp | b45cddc61626ee03eb29dd9704515b04068535c8 | [] | no_license | joook/DesignPatternProjects | b702e63531f0a08f09046dfe3b7406315f16178a | 1e881a0b397f91350f562e026f14bd20bf396239 | refs/heads/master | 2023-02-10T09:38:15.282012 | 2021-01-10T13:32:36 | 2021-01-10T13:32:36 | 262,780,839 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 606 | cpp | main.cpp | #include "component.h"
#include <iostream>
using namespace std;
int main()
{
Box OuterBox(1.00);
Box AccessoryBox;
Product iPhone("iPhone 4s", 5000.00);
Product Charger("iPhone Charger", 50.00);
Product EarPhones("iPhone EarPhones", 100.00);
OuterBox.add(&iPhone);
OuterBox.add(&Charger);
OuterBox.remove(&Charger);
OuterBox.add(&AccessoryBox);
AccessoryBox.add(&Charger);
AccessoryBox.add(&EarPhones);
cout << "Product list: " << OuterBox.getComponentList() << endl;
cout << "Total price is: " << OuterBox.getTotalPrice() << endl;
return 0;
}
|
8d41bbe5c5359632f113ec5477f75c23c3a43396 | 6b18884327584cd84e677b53a5c1c121cbed7aaf | /2D Physics Engine ERawlings/GhostParticlePhysics.h | 2608cdb40aedd7a9799411a556b3d84056877fa4 | [
"MIT"
] | permissive | EmmaRawlings/2D-Physics-Engine-ERawlings | dfa9ef64d71ac71aed0c57cfa88ade5e9859a85d | 63e1c330321bb7f826049ca12dfa95c4ddb346e8 | refs/heads/master | 2021-11-27T00:32:03.064186 | 2017-02-07T20:21:42 | 2017-02-07T20:21:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 282 | h | GhostParticlePhysics.h | #pragma once
#include "PointObject.h"
class GhostParticlePhysics :
public PointObject
{
public:
GhostParticlePhysics();
GhostParticlePhysics(const Vector2 &position, const Vector2 &momentum, const double &mass);
void update(const double &seconds);
~GhostParticlePhysics();
};
|
fcaf443a0c190f68c3c9df49b1a609b0674ad7ba | 15d64c874329eac5ac609983205ccaf53ffc1f62 | /src/msg/MsgManager.cc | 4bcc23e9099123a71ca8e2b71ca28ed49df24084 | [] | no_license | Gancc123/flame | 75fb0f1b91a8f3117a4faf02df16a367d6b2d8b2 | b680dee8bf6a263dd65024e37fb3d8f1017e3b09 | refs/heads/master | 2022-11-30T03:36:54.335864 | 2020-05-09T13:03:37 | 2020-05-09T13:03:37 | 285,832,839 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,743 | cc | MsgManager.cc | #include "MsgManager.h"
#include "msg_common.h"
#include "msg_data.h"
#include "msg_types.h"
#include "Stack.h"
#include "socket/TcpStack.h"
#ifdef HAVE_RDMA
#include "rdma/RdmaStack.h"
#endif
#ifdef HAVE_SPDK
#include "spdk/SpdkMsgWorker.h"
#endif
namespace flame{
namespace msg{
MsgManager::MsgManager(MsgContext *c, int worker_num)
: mct(c), is_running(false), m_mutex(MUTEX_TYPE_DEFAULT){
workers.reserve(worker_num);
for(int i = 0;i < worker_num; ++i){
MsgWorker *msg_worker = nullptr;
if(mct->config->msg_worker_type == msg_worker_type_t::THREAD){
msg_worker = new ThrMsgWorker(mct, i);
#ifdef HAVE_SPDK
}else if(mct->config->msg_worker_type == msg_worker_type_t::SPDK){
msg_worker = new SpdkMsgWorker(mct, i);
#endif //HAVE_SPDK
}else{ //use ThrMsgWorker as default.
msg_worker = new ThrMsgWorker(mct, i);
}
workers.push_back(msg_worker);
if(!mct->config->msg_worker_cpu_map.empty()){
int cpu_id = mct->config->msg_worker_cpu_map[i];
workers[i]->set_affinity(cpu_id);
ML(mct, info, "bind thr{} to cpu{}", i, cpu_id);
}
}
}
MsgManager::~MsgManager(){
MutexLocker l(m_mutex);
if(is_running){
clear_before_stop();
is_running = false;
}
for(auto worker : workers){
if(worker->running()){
worker->stop();
}
delete worker;
}
if(declare_msg){
declare_msg->put();
declare_msg = nullptr;
}
m_msger_cb = nullptr;
}
MsgWorker* MsgManager::get_lightest_load_worker(){
if(workers.size() <= 0) return nullptr;
int load = workers[0]->get_job_num(), index = 0;
for(int i = 1;i < workers.size(); ++i){
if(load > workers[i]->get_job_num()){
load = workers[i]->get_job_num();
index = i;
}
}
return workers[index];
}
void MsgManager::add_lp(ListenPort *lp){
for(auto &worker : workers){
worker->add_event(lp);
}
}
void MsgManager::del_lp(ListenPort *lp){
for(auto &worker : workers){
worker->del_event(lp->fd);
}
}
void MsgManager::add_conn(Connection *conn){
auto worker = get_lightest_load_worker();
if(!worker)
return;
if(!conn->is_owner_fixed()){
conn->set_owner(worker);
}
if(conn->has_fd()){
worker->add_event(conn);
}else{
worker->update_job_num(1);
}
}
void MsgManager::del_conn(Connection *conn){
MsgWorker *worker = conn->get_owner();
if(worker){
if(conn->has_fd()){
worker->del_event(conn->fd);
}else{
worker->update_job_num(-1);
}
}
}
ListenPort* MsgManager::add_listen_port(NodeAddr *addr, msg_ttype_t ttype){
ML(mct, trace, "{} {}", addr->to_string(), msg_ttype_to_str(ttype));
MutexLocker l(m_mutex);
if(!addr) return nullptr;
auto lp_iter = listen_map.find(addr);
if(lp_iter != listen_map.end()){
return lp_iter->second;
}
ListenPort *lp = nullptr;
switch(ttype){
case msg_ttype_t::TCP:
lp = Stack::get_tcp_stack()->create_listen_port(addr);
if(!lp) return nullptr;
lp->set_listener(this);
this->add_lp(lp);
addr->get();
listen_map[addr] = lp;
break;
#ifdef HAVE_RDMA
case msg_ttype_t::RDMA:
{
auto rdma_stack = Stack::get_rdma_stack();
if(!rdma_stack) return nullptr;
lp = rdma_stack->create_listen_port(addr);
}
if(!lp) return nullptr;
lp->set_listener(this);
this->add_lp(lp);
addr->get();
listen_map[addr] = lp;
break;
#endif
default:
return nullptr;
};
return lp;
}
int MsgManager::del_listen_port(NodeAddr *addr){
ML(mct, trace, "{}", addr->to_string());
MutexLocker l(m_mutex);
if(!addr) return -1;
auto lp_iter = listen_map.find(addr);
if(lp_iter != listen_map.end()){
auto lp_addr = lp_iter->first;
auto lp = lp_iter->second;
listen_map.erase(lp_iter);
lp_addr->put();
this->del_lp(lp);
return 1;
}
return 0;
}
Msg *MsgManager::get_declare_msg(){
MutexLocker l(m_mutex);
if(declare_msg){
return declare_msg;
}
Msg *msg = Msg::alloc_msg(mct);
msg->type = FLAME_MSG_TYPE_DECLARE_ID;
msg_declare_id_d data;
data.msger_id = mct->config->msger_id;
NodeAddr *tcp_lp_addr = nullptr;
NodeAddr *rdma_lp_addr = nullptr;
for(auto &pair : listen_map){
switch(pair.second->get_ttype()){
case msg_ttype_t::TCP:
if(!tcp_lp_addr){
tcp_lp_addr = pair.first;
}
break;
case msg_ttype_t::RDMA:
if(!rdma_lp_addr){
rdma_lp_addr = pair.first;
}
break;
}
}
if(tcp_lp_addr){
data.has_tcp_lp = true;
tcp_lp_addr->encode(&data.tcp_listen_addr,
sizeof(data.tcp_listen_addr));
}
if(rdma_lp_addr){
data.has_rdma_lp = true;
rdma_lp_addr->encode(&data.rdma_listen_addr,
sizeof(data.rdma_listen_addr));
}
msg->append_data(data);
declare_msg = msg;
return declare_msg;
}
Connection* MsgManager::add_connection(NodeAddr *addr, msg_ttype_t ttype){
if(!addr) return nullptr;
ML(mct, trace, "{} {}", addr->to_string(), msg_ttype_to_str(ttype));
Connection *conn = nullptr;
switch(ttype){
case msg_ttype_t::TCP:
conn = Stack::get_tcp_stack()->connect(addr);
if(!conn) return nullptr;
conn->set_listener(this);
this->add_conn(conn);
break;
#ifdef HAVE_RDMA
case msg_ttype_t::RDMA:
{
auto rdma_stack = Stack::get_rdma_stack();
if(!rdma_stack) return nullptr;
conn = rdma_stack->connect(addr);
}
if(!conn) return nullptr;
conn->set_listener(this);
this->add_conn(conn);
break;
#endif
default:
return nullptr;
};
Msg *msg = get_declare_msg();
conn->send_msg(msg);
//conn->put(); //return conn with its ownership
return conn;
}
int MsgManager::del_connection(Connection *conn){
if(!conn) return -1;
ML(mct, trace, "{}", conn->to_string());
{
MutexLocker l(m_mutex);
if(session_unknown_conns.erase(conn) > 0){
conn->put();
}
this->del_conn(conn);
}
if(conn->get_session()){
conn->get_session()->del_conn(conn);
}
return 0;
}
Session *MsgManager::get_session(msger_id_t msger_id){
ML(mct, trace, "{}", msger_id_to_str(msger_id));
MutexLocker l(m_mutex);
auto it = session_map.find(msger_id);
if(it != session_map.end()){
return it->second;
}
Session *s = new Session(mct, msger_id);
session_map[msger_id] = s;
return s;
}
int MsgManager::del_session(msger_id_t msger_id){
ML(mct, trace, "{}", msger_id_to_str(msger_id));
MutexLocker l(m_mutex);
auto it = session_map.find(msger_id);
if(it != session_map.end()){
return -1;
}
it->second->put();
session_map.erase(it);
return 0;
}
int MsgManager::start(){
ML(mct, trace, "");
clear_done = false;
MutexLocker l(m_mutex);
if(is_running) return 0;
is_running = true;
for(auto &worker : workers){
worker->start();
}
return 0;
}
int MsgManager::clear_before_stop(){
ML(mct, trace, "");
MutexLocker l(m_mutex);
for(auto& pair : listen_map){
del_lp(pair.second);
pair.first->put();
pair.second->put();
}
listen_map.clear();
for(auto conn : session_unknown_conns){
del_conn(conn);
conn->put();
}
session_unknown_conns.clear();
for(auto& pair : session_map){
pair.second->put();
}
session_map.clear();
clear_done = true;
return 0;
}
int MsgManager::stop(){
ML(mct, trace, "");
MutexLocker l(m_mutex);
if(!is_running) return 0;
is_running = false;
for(auto &worker : workers){
worker->stop();
}
return 0;
}
void MsgManager::on_listen_accept(ListenPort *lp, Connection *conn){
conn->get();
ML(mct, trace, "{} {}", lp->to_string(), conn->to_string());
{
MutexLocker l(m_mutex);
session_unknown_conns.insert(conn);
conn->set_listener(this);
this->add_conn(conn);
}
if(m_msger_cb){
m_msger_cb->on_listen_accept(lp, conn);
}
}
void MsgManager::on_listen_error(NodeAddr *listen_addr){
listen_addr->get();
ML(mct, trace, "{}", listen_addr->to_string());
del_listen_port(listen_addr);
if(m_msger_cb){
m_msger_cb->on_listen_error(listen_addr);
}
listen_addr->put();
}
void MsgManager::on_conn_recv(Connection *conn, Msg *msg){
ML(mct, trace, "{} {}", conn->to_string(), msg->to_string());
if(msg->type == FLAME_MSG_TYPE_DECLARE_ID){
msg_declare_id_d data;
auto it = msg->data_buffer_list().begin();
data.decode(it);
Session* s = get_session(data.msger_id);
assert(s);
if(data.has_tcp_lp){
auto tcp_listen_addr = new NodeAddr(mct, data.tcp_listen_addr);
s->set_listen_addr(tcp_listen_addr, msg_ttype_t::TCP);
tcp_listen_addr->put();
}
if(data.has_rdma_lp){
auto rdma_listen_addr = new NodeAddr(mct, data.rdma_listen_addr);
s->set_listen_addr(rdma_listen_addr, msg_ttype_t::RDMA);
rdma_listen_addr->put();
}
//Alway success though the conn may has the same type and same sl.
//Here may has duplicate conns.
int r = s->add_conn(conn);
{
MutexLocker l(m_mutex);
if(session_unknown_conns.erase(conn) > 0){
conn->put();
}
}
//When the two sides connect to each other at the same time.
//Here may drop both.
//So, we just reserve both here(r == 0). There may be better solutions.
if(r){ //add failed.(maybe duplicate)
ML(mct, info, "Drop {} due to duplicae", conn->to_string());
conn->close();
}else if(m_msger_cb){
m_msger_cb->on_conn_declared(conn, s);
}
return;
}
if(m_msger_cb){
m_msger_cb->on_conn_recv(conn, msg);
}
}
void MsgManager::on_conn_error(Connection *conn){
ML(mct, trace, "{}", conn->to_string());
if(m_msger_cb){
m_msger_cb->on_conn_error(conn);
}
this->del_connection(conn);
}
} //namespace msg
} //namespace flame |
17b2c52bb8d1bf2b74b4244253597617923a2fc4 | 50c1c675fef2c560dd904df9ab80791847f83f2c | /include/NearestNeighborGenerator.hxx | 57247d38749486eba6421c5cc4540ad7693ca6f5 | [] | no_license | xlou/BOT | 3bf9089c91b86f22ec2d2da01ffac00bd009c12f | 1046b11ffd038468693055422f5b00c50ba96a9b | refs/heads/master | 2016-09-06T01:56:02.951423 | 2013-02-01T16:34:59 | 2013-02-01T16:34:59 | 2,142,202 | 5 | 3 | null | null | null | null | IBM852 | C++ | false | false | 7,270 | hxx | NearestNeighborGenerator.hxx | /*!
* @author Xinghua Lou <xinghua.lou@iwr.uni-heidelberg.de>
*
* @section LICENSE
*
* BOT. Copyright (c) 2010 by Xinghua Lou.
*
* This software was developed by Xinghua Lou.
* Enquiries shall be directed to: xinghua.lou@iwr.uni-heidelberg.de.
*
* All advertising materials mentioning features or use of this software must
* display the following acknowledgement: ``This product includes the BOT
* library developed by Xinghua Lou. Please direct enquiries concerning BOT to
* xinghua.lou@iwr.uni-heidelberg.de.
*
* 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.
* - All advertising materials mentioning features or use of this software must
* display the following acknowledgement: ``This product includes the BOT
* library developed by Xinghua Lou. Please direct enquiries concerning BOT to
* xinghua.lou@iwr.uni-heidelberg.de.
* - The names of the authors must not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``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 AUTHORS 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 __NEAREST_NEIGHBOR_GENERATOR_HXX__
#define __NEAREST_NEIGHBOR_GENERATOR_HXX__
#include <algorithm>
#include <stdexcept>
#include "TypeDefinition.hxx"
#include "VigraSTLInterface.hxx"
#include "InputOutput.hxx"
using namespace vigra::linalg;
namespace bot
{
/*! The class computes nearest neighbors
*
*/
class NearestNeighborGenerator
{
public:
/*! Default constructor, initialize default values
*
*/
NearestNeighborGenerator()
{
k_ = 3;
d_max_ = LARGEST_DISTANCE;
symmetrical_ = false;
};
/*! Constructor with k, distance threshold and the symmetry property specified
* @param k The neighborhood number
* @param d_max The distance threshold
* @param symmetrical Whether the neighborhood is symmetrical
*/
NearestNeighborGenerator(
const int32 k,
const MatrixElem d_max,
const bool symmetrical)
{
k_ = k;
d_max_ = d_max;
symmetrical_ = symmetrical;
};
/*! Return the neighborhood number
* @return An int32 value as the neighborhood number
*/
const int32 k() const
{
return k_;
};
/*! Return the maximally allowed spatial distance
* @return A MatrixElem value as the maximally allowed spatial distance
*/
const MatrixElem d_max() const
{
return d_max_;
};
/*! Return the symmetry property
* @return A bool value that is true when the symmetry property is turned on
*/
const bool symmetrical() const
{
return symmetrical_;
};
/*! Return the kth smallest value in a vector
*
* If k is greater than the vector size, the overall smallest value is returned.
* @param vec The input vector
* @return The value of the kth smallest value in a vector
*/
template<class t_elem >
t_elem kth_smallest_value(const std::vector<t_elem >& vec)
{
size_t myk;
size_t vec_size = vec.size();
if( vec_size < 1 ) {
throw std::runtime_error("NearestNeighborGenerator::kth_smallest_value(): vector has to contain at leas one element");
}
int n_neighbors = vec.size() - (int) std::count(vec.begin(), vec.end(), LARGEST_DISTANCE);
int k_min = std::min(k(), n_neighbors);
std::vector<t_elem > vec_ = vec;
std::nth_element(vec_.begin(), vec_.begin() + k_min, vec_.end());
return vec_[k_min];
};
/*! Return a list of paired indices that satisfies the neighborhood constraints
* @param pts1 A list of points as the source
* @param pts2 A list of points as the target
* @return A list of paired indices that satisfies the neighborhood constraints
*/
std::vector<IDPair > operator() (const Matrix2D& pts1, const Matrix2D& pts2)
{
std::vector<IDPair > id_pairs;
if (pts1.elementCount() == 0 || pts2.elementCount() == 0)
return id_pairs;
// compute the distance matrix: think binomial ĘC (a-b)^2=a^2-2ab+b^2
Matrix2D::difference_type shape1(pts1.shape(0), 1);
Matrix2D::difference_type shape2(pts2.shape(0), 1);
Matrix2D
mean1(shape1, 0.0), std1(shape1, 0.0), norm1(shape1, 0.0),
mean2(shape2, 0.0), std2(shape2, 0.0), norm2(shape2, 0.0);
rowStatistics(pts1, mean1, std1, norm1);
rowStatistics(pts2, mean2, std2, norm2);
Matrix2D d_mat = sqrt(
sq(repeatMatrix(norm1, 1, norm2.shape(0)))
+ sq(repeatMatrix(transpose(norm2), norm1.shape(0), 1))
- (mmul(pts1, transpose(pts2)) *= 2));
// only keep the upper right part (if necessary), change the rest to maximum value
if (symmetrical()) {
for (int32 x = 0; x < d_mat.shape(0); x ++)
for (int32 y = 0; y <= x; y ++)
d_mat(x, y) = LARGEST_DISTANCE;
}
// determine the k nearest neighbors with d_max distance thresholding
for (int32 row = 0; row < d_mat.shape(0); row ++) {
// if having less than k neighbors, no need to compute, add them all
// if (d_mat.shape(1) - row - 1 <= k())
// continue;
Matrix2D::view_type view = rowVector(d_mat, row);
std::vector<MatrixElem > vec = VigraSTLInterface::view_to_vector<MatrixElem >(view);
MatrixElem d_max_k = std::min(d_max(), kth_smallest_value(vec));
std::replace_if(vec.begin(), vec.end(),
std::bind2nd(std::greater_equal<MatrixElem >(), d_max_k), LARGEST_DISTANCE);
VigraSTLInterface::fill_vector_to_view(vec, view);
}
// find the index of the neighboring pairs
for (int32 p = 0; p < d_mat.size(); p ++) {
if (d_mat[p] >= LARGEST_DISTANCE)
continue ;
Matrix2D::difference_type coord = d_mat.scanOrderIndexToCoordinate (p);
id_pairs.push_back(std::make_pair<int32, int32 >(coord[0], coord[1]));
};
return id_pairs;
};
protected:
int32 k_;
MatrixElem d_max_;
bool symmetrical_;
};
}
#endif /* __NEAREST_NEIGHBOR_GENERATOR_HXX__ */
|
e9066fdcd2d424c42adb6011deb6ca8e6011e73f | b64d126327d55b6030c917a7754c2d9eb5af4e60 | /GameTemplate/Game/IItemObject.cpp | 1899979e227e1c2008271c246afb9f4169654efe | [] | no_license | TakuyaI/FPSGame | c0a880c7e2f6e9816cc626e98fcd7c3e92b958f1 | e2856ccde8a7f7058ec89e77b7b8f6027b7229d5 | refs/heads/master | 2022-12-27T12:51:55.154331 | 2020-10-05T05:21:15 | 2020-10-05T05:21:15 | 225,989,396 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 112 | cpp | IItemObject.cpp | #include "stdafx.h"
#include "IItemObject.h"
IItemObject::IItemObject()
{
}
IItemObject::~IItemObject()
{
}
|
be88a082599ffdbf35286e5e91ffa60fca82bace | 437beb6be23b9263493d633a638a6dc2e2eb891a | /3. Medium/3. 661 - Blowing Fuses.cpp | 96d3f316e0f0d03f3128baa5c5fa10a5fb8ccfcc | [
"MIT"
] | permissive | Preetam2114/Competitive-Programming-3 | f16e045741a8df7e78bdfc9a44c3be5dae182083 | 1dd2eb3ec6371a645041eb9874ea2404ab636ba3 | refs/heads/main | 2023-01-18T23:44:41.458840 | 2020-11-19T18:24:29 | 2020-11-19T18:24:29 | 305,607,762 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,668 | cpp | 3. 661 - Blowing Fuses.cpp | /*
* Chef : preetam rane
* Chef-Id : pvr2114
* Dish : 3. 661 - Blowing Fuses
* Created on : Sunday, 1st November 2020 9:22:07 am
*/
#include <bits/stdc++.h>
using namespace std;
#ifndef preetam
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#pragma GCC target ("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native")
#endif
#define F first
#define S second
#define pb push_back
#define mp make_pair
#define rep(i,a,b) for(int i = a; i <= b; i++)
#define inputarr(arr,n) for(int i = 0; i < n; i++) cin>>arr[i];
#define inputmat(arr,a,b) for(int i=0; i < a; i++)for(int j=0; j < b; j++)cin>>arr[i][j];
#define print(arr) for(auto a:arr) cout<<a<<" "; cout<<"\n";
#define all(ar) ar.begin(), ar.end()
#define foreach(it, ar) for (auto it = ar.begin(); it != ar.end(); it++)
#define fil(ar, val) memset(ar, val, sizeof(ar))
#define endl '\n'
#ifndef preetam
template<typename KeyType, typename ValueType>
std::pair<KeyType,ValueType> get_max( const std::map<KeyType,ValueType>& x ) {
using pairtype=std::pair<KeyType,ValueType>;
return *std::max_element(x.begin(), x.end(), [] (const pairtype & p1, const pairtype & p2) {
return p1.second < p2.second;
});
}
template <class Container>
void split(const std::string& str, Container& cont){
std::istringstream iss(str);
std::copy(std::istream_iterator<std::string>(iss),
std::istream_iterator<std::string>(),
std::back_inserter(cont));
}
constexpr unsigned int shash(const char *s, int off = 0){
return !s[off] ? 5381 : (shash(s, off+1)*33) ^ s[off];
}
typedef long long ll;
typedef long double ld;
typedef long double f80;
typedef pair<int, int> pii;
const ll mod = 1e9;
#endif
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
ll t=1;
int n,m,c;
while(cin>>n>>m>>c){
if(c==0 && m==0 && n==0)
break;
int maxpow = 0,total =0;
bool blown = false;
vector<int> val(n);
vector<int> stat(n);
rep(i,0,n-1){
cin>>val[i];
stat[i]=0;
}
rep(i,0,m-1){
cin>>n;
if (!stat[n - 1]) {
total += val[n - 1];
stat[n - 1] = !stat[n - 1];
}
else {
total -= val[n - 1];
stat[n - 1] = !stat[n - 1];
}
if (total > c) blown = true;
else {
if (total > maxpow) maxpow = total;
}
}
if (blown) {
cout << "Sequence " << t << endl << "Fuse was blown." << endl;
}
else {
cout << "Sequence " << t << endl << "Fuse was not blown."<<endl<< "Maximal power consumption was " << maxpow << " amperes." << endl;
}
cout<<endl;
t++;
}
return 0;
} |
756d6a468ca2b2c52de5852e52ea1a8c5e7bf7c4 | 32dad2f438a7b4313ee81b73815a32243bb3830f | /Program 6.cpp | b0a499cc0eac1425140810e44fffdcfa88f4cfad | [] | no_license | furkanmidik/programlama | cb56f0d7f404cd96fafe2144da1512db23a9f029 | 2b82bd83642c39f9bdfd727e04d36d0f9356aa60 | refs/heads/master | 2021-08-15T22:40:45.994576 | 2017-11-18T13:22:39 | 2017-11-18T13:22:39 | 111,206,570 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 193 | cpp | Program 6.cpp | #include <stdio.h>
#include <conio.h>
main()
{
char kelime[20];
printf("Bir kelime giriniz : ");
scanf("%s",kelime);
printf("Girilen kelime : %s",kelime);
getch();
}
|
494a7ce8bb72a545d8648acef5d6a0528f8c522a | cf9146c1a3dd4d0ae6b5f490de33a65dac418c15 | /sprint00/t04/referenceOrPointer.cpp | e09c97e98cef79ca8faf54e2ed109ed8fd844e05 | [] | no_license | dmushynska/marathon_c_plus_plus | 5fe63e71dffcf783ddbfeaecfb1d42f62c7c27e0 | 69782b3dc8cede716fe0e4528df0f77e3e00facb | refs/heads/master | 2022-12-15T04:54:11.176178 | 2020-09-17T10:04:45 | 2020-09-17T10:04:45 | 290,715,426 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 373 | cpp | referenceOrPointer.cpp | #include "referenceOrPointer.h"
void multiplyByPointer(int* ptr, int mult) {
*ptr *= mult;
}
void multiplyByReference(int& ref, int mult) {
ref *= mult;
}
// int main() {
// int a = 3;
// int &b = a;
// multiplyByPointer(&a, a);
// std::cout << a << std::endl; // 9
// multiplyByReference(b, a);
// std::cout << b << std::endl; // 81
// } |
1944826ade89920b7e8e13a958a5246075b52949 | 903dac660b0db25b05ac375a5916f023ef199fc0 | /src/SSEEncrypter.cpp | d0fd0fb7445545f5e85348eec2f33bb0efb4d5e1 | [] | no_license | TANGO-Project/cryptsdc | d6af5dd9e4252462cabf383fd52b9814d0dc0a29 | 4428fc289c97818d58a8010593636c64bde56e82 | refs/heads/master | 2020-03-28T05:57:34.072152 | 2018-10-23T13:29:24 | 2018-10-23T13:29:24 | 147,806,026 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,570 | cpp | SSEEncrypter.cpp | /*
* Copyright 2018 James Dyer
*
* 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.
*
* This is being developed for the TANGO Project: http://tango-project.eu
*/
#include <iostream>
#include <iterator>
#include <cryptopp/osrng.h>
#include <cryptopp/hex.h>
#include <jsoncpp/json/json.h>
#include "SSEEncrypter.h"
SSEEncrypter::SSEEncrypter() {
CryptoPP::AutoSeededRandomPool rng;
key.CleanNew(CryptoPP::AES::MAX_KEYLENGTH);
rng.GenerateBlock(key, key.size());
keyGenKey.CleanNew(CryptoPP::AES::MAX_KEYLENGTH);
rng.GenerateBlock(keyGenKey, keyGenKey.size());
keyGenIV.CleanNew(CryptoPP::AES::BLOCKSIZE);
}
SSEEncrypter::SSEEncrypter(std::string& secrets){
Json::Value root;
Json::Reader reader;
key.CleanNew(CryptoPP::AES::MAX_KEYLENGTH);
keyGenKey.CleanNew(CryptoPP::AES::MAX_KEYLENGTH);
keyGenIV.CleanNew(CryptoPP::AES::BLOCKSIZE);
if(reader.parse(secrets, root)){
std::string hexEncodedKey = root["key"].asString();
decodeHexString(hexEncodedKey, key);
std::string hexEncodedKeyGenKey = root["keygenkey"].asString();
decodeHexString(hexEncodedKeyGenKey, keyGenKey);
}
}
SSEEncrypter::~SSEEncrypter() {
}
CryptoPP::SecByteBlock SSEEncrypter::createSearchKey(std::string& word){
int outputBlocks = word.size()/CryptoPP::AES::BLOCKSIZE;
if (word.size() % CryptoPP::AES::BLOCKSIZE) outputBlocks++;
int outputSize = outputBlocks*CryptoPP::AES::BLOCKSIZE;
CryptoPP::SecByteBlock cipher(nullptr,outputSize);
keygen.SetKeyWithIV(keyGenKey, keyGenKey.size(), keyGenIV, keyGenIV.size());
CryptoPP::StringSource(word, true,
new CryptoPP::StreamTransformationFilter(keygen,
new CryptoPP::ArraySink(cipher,cipher.size())));
if (outputSize>CryptoPP::AES::MAX_KEYLENGTH){
//get last 32 bytes of ciphertext: ensures that word <= MAX_KEYLENGTH bytes does not generate
//same key as word > MAX_KEYLENGTH bytes
CryptoPP::SecByteBlock lastbytes(nullptr,CryptoPP::AES::MAX_KEYLENGTH);
std::copy(cipher.begin()+(cipher.size()-CryptoPP::AES::MAX_KEYLENGTH),cipher.end(),lastbytes.begin());
return lastbytes;
}
else return cipher;
}
std::string SSEEncrypter::createHexEncodedSearchKey(std::string& word){
std::string hexString;
CryptoPP::SecByteBlock searchKey = createSearchKey(word);
CryptoPP::ArraySource ss(searchKey.data(), searchKey.size(), true,
new CryptoPP::HexEncoder(
new CryptoPP::StringSink(hexString)
) // HexEncoder
); // ArraySource
return hexString;
}
void SSEEncrypter::decodeHexString(std::string& hexString, CryptoPP::SecByteBlock& bytes){
CryptoPP::StringSource ss(hexString, true,
new CryptoPP::HexDecoder(
new CryptoPP::ArraySink(bytes,bytes.size())
) // HexDecoder
); // StringSource
}
std::string SSEEncrypter::encrypt(std::string& plaintext){
Json::Value root;
//Generate random IV
CryptoPP::AutoSeededRandomPool rng;
CryptoPP::SecByteBlock iv(nullptr,CryptoPP::AES::BLOCKSIZE);
rng.GenerateBlock(iv, iv.size());
//Hex encode IV and add to JSON
std::string hexEncodedIV;
CryptoPP::ArraySource as(iv, iv.size(), true,
new CryptoPP::HexEncoder(
new CryptoPP::StringSink(hexEncodedIV)
) // HexEncoder
); // StringSource
root["iv"]=hexEncodedIV;
//Encrypt plaintext using key and IV, hex encode, and add to JSON
e.SetKeyWithIV(key, key.size(), iv, iv.size());
std::string payload;
CryptoPP::StringSource ss(plaintext, true,
new CryptoPP::StreamTransformationFilter(e,
new CryptoPP::StringSink(payload)
)
);
std::string hexEncodedPayload;
CryptoPP::StringSource ss2(payload, true,
new CryptoPP::HexEncoder(
new CryptoPP::StringSink(hexEncodedPayload)
) // HexEncoder
); // StringSource
root["payload"]=hexEncodedPayload;
//Create searchKey
CryptoPP::SecByteBlock searchKey = createSearchKey(plaintext);
//Create CMAC tag using searchKey and add to JSON
std::string tag;
mac.SetKey(searchKey.data(), searchKey.size());
CryptoPP::StringSource(payload, true,
new CryptoPP::HashFilter(mac,
new CryptoPP::HexEncoder(
new CryptoPP::StringSink(tag))));
root["tag"]=tag;
//Write JSON object to string
Json::FastWriter writer;
std::string json = writer.write(root);
return json;
}
CryptoPP::SecByteBlock SSEEncrypter::getKey(){
return key;
}
CryptoPP::SecByteBlock SSEEncrypter::getKeyGenKey(){
return keyGenKey;
}
std::string SSEEncrypter::getHexEncodedKey(){
std::string hexEncodedKey;
CryptoPP::ArraySource as(key, key.size(), true,
new CryptoPP::HexEncoder(
new CryptoPP::StringSink(hexEncodedKey)
) // HexEncoder
); // StringSource
return hexEncodedKey;
}
std::string SSEEncrypter::getHexEncodedKeyGenKey(){
std::string hexEncodedKey;
CryptoPP::ArraySource as(keyGenKey, keyGenKey.size(), true,
new CryptoPP::HexEncoder(
new CryptoPP::StringSink(hexEncodedKey)
) // HexEncoder
); // StringSource
return hexEncodedKey;
}
std::string SSEEncrypter::writeSecretsToJSON(){
Json::Value root;
root["key"]=getHexEncodedKey();
root["keygenkey"]=getHexEncodedKeyGenKey();
Json::FastWriter writer;
std::string json = writer.write(root);
return json;
}
|
6b2c3d6f2fde2d1f8df76895913be1fc6c193141 | 2814b4ed8ebe8bbeb2e4210ed083326dd6ce7252 | /Easy/160. Intersection of Two Linked Lists/getIntersectionNode.cpp | 751d04966242858b6a58e36fd0197bd5c34ca9fe | [] | no_license | teddy8997/LeetCode | 31970b5efe1945204bf2f8fc4e5d6924f05636db | 399edc5300fb1cb2cb0fe51b42ce3a913c830d25 | refs/heads/master | 2023-04-10T21:14:28.684276 | 2021-04-19T06:12:34 | 2021-04-19T06:12:34 | 303,752,589 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,175 | cpp | getIntersectionNode.cpp | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/*
先計算出listA跟listB的長度lengthA跟lengthB
再計算兩個長度大小的差值,較長list的先走差值步
兩個list再一步一步互相比較,如果沒有相交點代表會走到null
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
int lengthA = getLength(headA);
int lengthB = getLength(headB);
if(lengthA < lengthB){
for(int i = 0; i < lengthB - lengthA; i++){
headB = headB->next;
}
}else{
for(int i = 0; i < lengthA - lengthB; i++){
headA = headA->next;
}
}
while(headA && headB && headA != headB){
headA = headA->next;
headB = headB->next;
}
return (headA && headB)? headA : NULL;
}
private:
int getLength(ListNode* n){
int count = 0;
while(n){
n = n->next;
count++;
}
return count;
}
}; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.